blob: bbb323e4f29d31f7258705149f0634e9904bf477 [file] [log] [blame]
Charles Davis4e786dd2010-05-25 19:52:27 +00001//===------- ItaniumCXXABI.cpp - Emit LLVM Code from ASTs for a Module ----===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattner57540c52011-04-15 05:22:18 +000010// This provides C++ code generation targeting the Itanium C++ ABI. The class
Charles Davis4e786dd2010-05-25 19:52:27 +000011// in this file generates structures that follow the Itanium C++ ABI, which is
12// documented at:
13// http://www.codesourcery.com/public/cxx-abi/abi.html
14// http://www.codesourcery.com/public/cxx-abi/abi-eh.html
John McCall86353412010-08-21 22:46:04 +000015//
16// It also supports the closely-related ARM ABI, documented at:
17// http://infocenter.arm.com/help/topic/com.arm.doc.ihi0041c/IHI0041C_cppabi.pdf
18//
Charles Davis4e786dd2010-05-25 19:52:27 +000019//===----------------------------------------------------------------------===//
20
21#include "CGCXXABI.h"
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000022#include "CGCleanup.h"
John McCall7a9aac22010-08-23 01:21:21 +000023#include "CGRecordLayout.h"
Charles Davisa325a6e2012-06-23 23:44:00 +000024#include "CGVTables.h"
John McCall475999d2010-08-22 00:05:51 +000025#include "CodeGenFunction.h"
Charles Davis4e786dd2010-05-25 19:52:27 +000026#include "CodeGenModule.h"
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000027#include "TargetInfo.h"
John McCall5ad74072017-03-02 20:04:19 +000028#include "clang/CodeGen/ConstantInitBuilder.h"
Craig Topperc9ee1d02012-09-15 18:47:51 +000029#include "clang/AST/Mangle.h"
30#include "clang/AST/Type.h"
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000031#include "clang/AST/StmtCXX.h"
David Majnemer1162d252014-06-22 19:05:33 +000032#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000033#include "llvm/IR/DataLayout.h"
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000034#include "llvm/IR/Instructions.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000035#include "llvm/IR/Intrinsics.h"
36#include "llvm/IR/Value.h"
Charles Davis4e786dd2010-05-25 19:52:27 +000037
38using namespace clang;
John McCall475999d2010-08-22 00:05:51 +000039using namespace CodeGen;
Charles Davis4e786dd2010-05-25 19:52:27 +000040
41namespace {
Charles Davis53c59df2010-08-16 03:33:14 +000042class ItaniumCXXABI : public CodeGen::CGCXXABI {
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +000043 /// VTables - All the vtables which have been defined.
44 llvm::DenseMap<const CXXRecordDecl *, llvm::GlobalVariable *> VTables;
45
John McCall475999d2010-08-22 00:05:51 +000046protected:
Mark Seabornedf0d382013-07-24 16:25:13 +000047 bool UseARMMethodPtrABI;
48 bool UseARMGuardVarABI;
John McCalld23b27e2016-09-16 02:40:45 +000049 bool Use32BitVTableOffsetABI;
John McCall7a9aac22010-08-23 01:21:21 +000050
Timur Iskhodzhanov67455222013-10-03 06:26:13 +000051 ItaniumMangleContext &getMangleContext() {
52 return cast<ItaniumMangleContext>(CodeGen::CGCXXABI::getMangleContext());
53 }
54
Charles Davis4e786dd2010-05-25 19:52:27 +000055public:
Mark Seabornedf0d382013-07-24 16:25:13 +000056 ItaniumCXXABI(CodeGen::CodeGenModule &CGM,
57 bool UseARMMethodPtrABI = false,
58 bool UseARMGuardVarABI = false) :
59 CGCXXABI(CGM), UseARMMethodPtrABI(UseARMMethodPtrABI),
John McCalld23b27e2016-09-16 02:40:45 +000060 UseARMGuardVarABI(UseARMGuardVarABI),
Richard Smithb17d6fa2016-12-01 03:04:07 +000061 Use32BitVTableOffsetABI(false) { }
John McCall475999d2010-08-22 00:05:51 +000062
Reid Kleckner40ca9132014-05-13 22:05:45 +000063 bool classifyReturnType(CGFunctionInfo &FI) const override;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000064
Richard Smithf667ad52017-08-26 01:04:35 +000065 bool passClassIndirect(const CXXRecordDecl *RD) const {
66 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
67 // The PS4 platform ABI follows the behavior of Clang 3.2.
68 if (CGM.getCodeGenOpts().getClangABICompat() <=
69 CodeGenOptions::ClangABI::Ver4 ||
70 CGM.getTriple().getOS() == llvm::Triple::PS4)
Akira Hatanaka02914dc2018-02-05 20:23:22 +000071 return RD->hasNonTrivialDestructorForCall() ||
72 RD->hasNonTrivialCopyConstructorForCall();
Richard Smithf667ad52017-08-26 01:04:35 +000073 return !canCopyArgument(RD);
74 }
75
Craig Topper4f12f102014-03-12 06:41:41 +000076 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override {
Richard Smith96cd6712017-08-16 01:49:53 +000077 // If C++ prohibits us from making a copy, pass by address.
Richard Smithf667ad52017-08-26 01:04:35 +000078 if (passClassIndirect(RD))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000079 return RAA_Indirect;
80 return RAA_Default;
81 }
82
John McCall7f416cc2015-09-08 08:05:57 +000083 bool isThisCompleteObject(GlobalDecl GD) const override {
84 // The Itanium ABI has separate complete-object vs. base-object
85 // variants of both constructors and destructors.
86 if (isa<CXXDestructorDecl>(GD.getDecl())) {
87 switch (GD.getDtorType()) {
88 case Dtor_Complete:
89 case Dtor_Deleting:
90 return true;
91
92 case Dtor_Base:
93 return false;
94
95 case Dtor_Comdat:
96 llvm_unreachable("emitting dtor comdat as function?");
97 }
98 llvm_unreachable("bad dtor kind");
99 }
100 if (isa<CXXConstructorDecl>(GD.getDecl())) {
101 switch (GD.getCtorType()) {
102 case Ctor_Complete:
103 return true;
104
105 case Ctor_Base:
106 return false;
107
108 case Ctor_CopyingClosure:
109 case Ctor_DefaultClosure:
110 llvm_unreachable("closure ctors in Itanium ABI?");
111
112 case Ctor_Comdat:
113 llvm_unreachable("emitting ctor comdat as function?");
114 }
115 llvm_unreachable("bad dtor kind");
116 }
117
118 // No other kinds.
119 return false;
120 }
121
Craig Topper4f12f102014-03-12 06:41:41 +0000122 bool isZeroInitializable(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +0000123
Craig Topper4f12f102014-03-12 06:41:41 +0000124 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
John McCall7a9aac22010-08-23 01:21:21 +0000125
John McCallb92ab1a2016-10-26 23:46:34 +0000126 CGCallee
Craig Topper4f12f102014-03-12 06:41:41 +0000127 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
128 const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000129 Address This,
130 llvm::Value *&ThisPtrForCall,
Craig Topper4f12f102014-03-12 06:41:41 +0000131 llvm::Value *MemFnPtr,
132 const MemberPointerType *MPT) override;
John McCalla8bbb822010-08-22 03:04:22 +0000133
Craig Topper4f12f102014-03-12 06:41:41 +0000134 llvm::Value *
135 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000136 Address Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000137 llvm::Value *MemPtr,
138 const MemberPointerType *MPT) override;
John McCallc134eb52010-08-31 21:07:20 +0000139
John McCall7a9aac22010-08-23 01:21:21 +0000140 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
141 const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +0000142 llvm::Value *Src) override;
John McCallc62bb392012-02-15 01:22:51 +0000143 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +0000144 llvm::Constant *Src) override;
John McCall84fa5102010-08-22 04:16:24 +0000145
Craig Topper4f12f102014-03-12 06:41:41 +0000146 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +0000147
David Majnemere2be95b2015-06-23 07:31:01 +0000148 llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD) override;
John McCallf3a88602011-02-03 08:15:49 +0000149 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +0000150 CharUnits offset) override;
151 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
Richard Smithdafff942012-01-14 04:30:29 +0000152 llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
153 CharUnits ThisAdjustment);
John McCall1c456c82010-08-22 06:43:33 +0000154
John McCall7a9aac22010-08-23 01:21:21 +0000155 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000156 llvm::Value *L, llvm::Value *R,
John McCall7a9aac22010-08-23 01:21:21 +0000157 const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +0000158 bool Inequality) override;
John McCall131d97d2010-08-22 08:30:07 +0000159
John McCall7a9aac22010-08-23 01:21:21 +0000160 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000161 llvm::Value *Addr,
162 const MemberPointerType *MPT) override;
John McCall5d865c322010-08-31 07:33:07 +0000163
David Majnemer08681372014-11-01 07:37:17 +0000164 void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,
John McCall7f416cc2015-09-08 08:05:57 +0000165 Address Ptr, QualType ElementType,
David Majnemer0c0b6d92014-10-31 20:09:12 +0000166 const CXXDestructorDecl *Dtor) override;
John McCall82fb8922012-09-25 10:10:39 +0000167
Akira Hatanakac47fcf02017-07-27 18:52:44 +0000168 /// Itanium says that an _Unwind_Exception has to be "double-word"
169 /// aligned (and thus the end of it is also so-aligned), meaning 16
170 /// bytes. Of course, that was written for the actual Itanium,
171 /// which is a 64-bit platform. Classically, the ABI doesn't really
172 /// specify the alignment on other platforms, but in practice
173 /// libUnwind declares the struct with __attribute__((aligned)), so
174 /// we assume that alignment here. (It's generally 16 bytes, but
175 /// some targets overwrite it.)
John McCall7f416cc2015-09-08 08:05:57 +0000176 CharUnits getAlignmentOfExnObject() {
Akira Hatanakac47fcf02017-07-27 18:52:44 +0000177 auto align = CGM.getContext().getTargetDefaultAlignForAttributeAligned();
178 return CGM.getContext().toCharUnitsFromBits(align);
John McCall7f416cc2015-09-08 08:05:57 +0000179 }
180
David Majnemer442d0a22014-11-25 07:20:20 +0000181 void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
David Majnemer7c237072015-03-05 00:46:22 +0000182 void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override;
David Majnemer442d0a22014-11-25 07:20:20 +0000183
Reid Klecknerfff8e7f2015-03-03 19:21:04 +0000184 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
185
186 llvm::CallInst *
187 emitTerminateForUnexpectedException(CodeGenFunction &CGF,
188 llvm::Value *Exn) override;
189
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +0000190 void EmitFundamentalRTTIDescriptor(QualType Type, bool DLLExport);
191 void EmitFundamentalRTTIDescriptors(bool DLLExport);
David Majnemer443250f2015-03-17 20:35:00 +0000192 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
Reid Kleckner10aa7702015-09-16 20:15:55 +0000193 CatchTypeInfo
David Majnemer37b417f2015-03-29 21:55:10 +0000194 getAddrOfCXXCatchHandlerType(QualType Ty,
195 QualType CatchHandlerType) override {
Reid Kleckner10aa7702015-09-16 20:15:55 +0000196 return CatchTypeInfo{getAddrOfRTTIDescriptor(Ty), 0};
David Majnemer443250f2015-03-17 20:35:00 +0000197 }
David Majnemere2cb8d12014-07-07 06:20:47 +0000198
David Majnemer1162d252014-06-22 19:05:33 +0000199 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
200 void EmitBadTypeidCall(CodeGenFunction &CGF) override;
201 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
John McCall7f416cc2015-09-08 08:05:57 +0000202 Address ThisPtr,
David Majnemer1162d252014-06-22 19:05:33 +0000203 llvm::Type *StdTypeInfoPtrTy) override;
204
205 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
206 QualType SrcRecordTy) override;
207
John McCall7f416cc2015-09-08 08:05:57 +0000208 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, Address Value,
David Majnemer1162d252014-06-22 19:05:33 +0000209 QualType SrcRecordTy, QualType DestTy,
210 QualType DestRecordTy,
211 llvm::BasicBlock *CastEnd) override;
212
John McCall7f416cc2015-09-08 08:05:57 +0000213 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
David Majnemer1162d252014-06-22 19:05:33 +0000214 QualType SrcRecordTy,
215 QualType DestTy) override;
216
217 bool EmitBadCastCall(CodeGenFunction &CGF) override;
218
Craig Topper4f12f102014-03-12 06:41:41 +0000219 llvm::Value *
John McCall7f416cc2015-09-08 08:05:57 +0000220 GetVirtualBaseClassOffset(CodeGenFunction &CGF, Address This,
Craig Topper4f12f102014-03-12 06:41:41 +0000221 const CXXRecordDecl *ClassDecl,
222 const CXXRecordDecl *BaseClassDecl) override;
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000223
Craig Topper4f12f102014-03-12 06:41:41 +0000224 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000225
George Burgess IVf203dbf2017-02-22 20:28:02 +0000226 AddedStructorArgs
227 buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
228 SmallVectorImpl<CanQualType> &ArgTys) override;
John McCall5d865c322010-08-31 07:33:07 +0000229
Reid Klecknere7de47e2013-07-22 13:51:44 +0000230 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
Craig Topper4f12f102014-03-12 06:41:41 +0000231 CXXDtorType DT) const override {
Reid Klecknere7de47e2013-07-22 13:51:44 +0000232 // Itanium does not emit any destructor variant as an inline thunk.
233 // Delegating may occur as an optimization, but all variants are either
234 // emitted with external linkage or as linkonce if they are inline and used.
235 return false;
236 }
237
Craig Topper4f12f102014-03-12 06:41:41 +0000238 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
Reid Klecknere7de47e2013-07-22 13:51:44 +0000239
Reid Kleckner89077a12013-12-17 19:46:40 +0000240 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
Craig Topper4f12f102014-03-12 06:41:41 +0000241 FunctionArgList &Params) override;
John McCall5d865c322010-08-31 07:33:07 +0000242
Craig Topper4f12f102014-03-12 06:41:41 +0000243 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
John McCall8ed55a52010-09-02 09:58:18 +0000244
George Burgess IVf203dbf2017-02-22 20:28:02 +0000245 AddedStructorArgs
246 addImplicitConstructorArgs(CodeGenFunction &CGF, const CXXConstructorDecl *D,
247 CXXCtorType Type, bool ForVirtualBase,
248 bool Delegating, CallArgList &Args) override;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000249
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000250 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
251 CXXDtorType Type, bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +0000252 bool Delegating, Address This) override;
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000253
Craig Topper4f12f102014-03-12 06:41:41 +0000254 void emitVTableDefinitions(CodeGenVTables &CGVT,
255 const CXXRecordDecl *RD) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000256
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000257 bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,
258 CodeGenFunction::VPtr Vptr) override;
259
260 bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override {
261 return true;
262 }
263
264 llvm::Constant *
265 getVTableAddressPoint(BaseSubobject Base,
266 const CXXRecordDecl *VTableClass) override;
267
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000268 llvm::Value *getVTableAddressPointInStructor(
269 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000270 BaseSubobject Base, const CXXRecordDecl *NearestVBase) override;
271
272 llvm::Value *getVTableAddressPointInStructorWithVTT(
273 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
274 BaseSubobject Base, const CXXRecordDecl *NearestVBase);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000275
276 llvm::Constant *
277 getVTableAddressPointForConstExpr(BaseSubobject Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000278 const CXXRecordDecl *VTableClass) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000279
280 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
Craig Topper4f12f102014-03-12 06:41:41 +0000281 CharUnits VPtrOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000282
John McCall9831b842018-02-06 18:52:44 +0000283 CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
284 Address This, llvm::Type *Ty,
285 SourceLocation Loc) override;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000286
David Majnemer0c0b6d92014-10-31 20:09:12 +0000287 llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
288 const CXXDestructorDecl *Dtor,
289 CXXDtorType DtorType,
John McCall7f416cc2015-09-08 08:05:57 +0000290 Address This,
David Majnemer0c0b6d92014-10-31 20:09:12 +0000291 const CXXMemberCallExpr *CE) override;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000292
Craig Topper4f12f102014-03-12 06:41:41 +0000293 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
Reid Kleckner7810af02013-06-19 15:20:38 +0000294
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000295 bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const override;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000296
Hans Wennborgc94391d2014-06-06 20:04:01 +0000297 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
298 bool ReturnAdjustment) override {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000299 // Allow inlining of thunks by emitting them with available_externally
300 // linkage together with vtables when needed.
Peter Collingbourne8fabc1b2015-07-01 02:10:26 +0000301 if (ForVTable && !Thunk->hasLocalLinkage())
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000302 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
Shoaib Meenaicef66e52017-07-24 17:16:27 +0000303
304 // Propagate dllexport storage, to enable the linker to generate import
305 // thunks as necessary (e.g. when a parent class has a key function and a
306 // child class doesn't, and the construction vtable for the parent in the
307 // child needs to reference the parent's thunks).
308 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
309 if (MD->hasAttr<DLLExportAttr>())
310 Thunk->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000311 }
312
John McCall7f416cc2015-09-08 08:05:57 +0000313 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This,
Craig Topper4f12f102014-03-12 06:41:41 +0000314 const ThisAdjustment &TA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000315
John McCall7f416cc2015-09-08 08:05:57 +0000316 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
Craig Topper4f12f102014-03-12 06:41:41 +0000317 const ReturnAdjustment &RA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000318
David Majnemer196ac332014-09-11 23:05:02 +0000319 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
320 FunctionArgList &Args) const override {
321 assert(!Args.empty() && "expected the arglist to not be empty!");
322 return Args.size() - 1;
323 }
324
Craig Topper4f12f102014-03-12 06:41:41 +0000325 StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
326 StringRef GetDeletedVirtualCallName() override
327 { return "__cxa_deleted_virtual"; }
Joao Matos2ce88ef2012-07-17 17:10:11 +0000328
Craig Topper4f12f102014-03-12 06:41:41 +0000329 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall7f416cc2015-09-08 08:05:57 +0000330 Address InitializeArrayCookie(CodeGenFunction &CGF,
331 Address NewPtr,
332 llvm::Value *NumElements,
333 const CXXNewExpr *expr,
334 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000335 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000336 Address allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000337 CharUnits cookieSize) override;
John McCall68ff0372010-09-08 01:44:27 +0000338
John McCallcdf7ef52010-11-06 09:44:32 +0000339 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000340 llvm::GlobalVariable *DeclPtr,
341 bool PerformInit) override;
Richard Smithdbf74ba2013-04-14 23:01:42 +0000342 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000343 llvm::Constant *dtor, llvm::Constant *addr) override;
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000344
345 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +0000346 llvm::Value *Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000347 void EmitThreadLocalInitFuncs(
David Majnemerb3341ea2014-10-05 05:05:40 +0000348 CodeGenModule &CGM,
Richard Smith5a99c492015-12-01 01:10:48 +0000349 ArrayRef<const VarDecl *> CXXThreadLocals,
David Majnemerb3341ea2014-10-05 05:05:40 +0000350 ArrayRef<llvm::Function *> CXXThreadLocalInits,
Richard Smith5a99c492015-12-01 01:10:48 +0000351 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) override;
David Majnemerb3341ea2014-10-05 05:05:40 +0000352
353 bool usesThreadWrapperFunction() const override { return true; }
Richard Smith0f383742014-03-26 22:48:22 +0000354 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
355 QualType LValType) override;
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000356
Craig Topper4f12f102014-03-12 06:41:41 +0000357 bool NeedsVTTParameter(GlobalDecl GD) override;
David Majnemere2cb8d12014-07-07 06:20:47 +0000358
359 /**************************** RTTI Uniqueness ******************************/
360
361protected:
362 /// Returns true if the ABI requires RTTI type_info objects to be unique
363 /// across a program.
364 virtual bool shouldRTTIBeUnique() const { return true; }
365
366public:
367 /// What sort of unique-RTTI behavior should we use?
368 enum RTTIUniquenessKind {
369 /// We are guaranteeing, or need to guarantee, that the RTTI string
370 /// is unique.
371 RUK_Unique,
372
373 /// We are not guaranteeing uniqueness for the RTTI string, so we
374 /// can demote to hidden visibility but must use string comparisons.
375 RUK_NonUniqueHidden,
376
377 /// We are not guaranteeing uniqueness for the RTTI string, so we
378 /// have to use string comparisons, but we also have to emit it with
379 /// non-hidden visibility.
380 RUK_NonUniqueVisible
381 };
382
383 /// Return the required visibility status for the given type and linkage in
384 /// the current ABI.
385 RTTIUniquenessKind
386 classifyRTTIUniqueness(QualType CanTy,
387 llvm::GlobalValue::LinkageTypes Linkage) const;
388 friend class ItaniumRTTIBuilder;
Rafael Espindola91f68b42014-09-15 19:20:10 +0000389
390 void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000391
Peter Collingbourne60108802017-12-13 21:53:04 +0000392 std::pair<llvm::Value *, const CXXRecordDecl *>
393 LoadVTablePtr(CodeGenFunction &CGF, Address This,
394 const CXXRecordDecl *RD) override;
395
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000396 private:
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000397 bool hasAnyUnusedVirtualInlineFunction(const CXXRecordDecl *RD) const {
398 const auto &VtableLayout =
399 CGM.getItaniumVTableContext().getVTableLayout(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000400
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000401 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
402 // Skip empty slot.
403 if (!VtableComponent.isUsedFunctionPointerKind())
404 continue;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000405
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000406 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
407 if (!Method->getCanonicalDecl()->isInlined())
408 continue;
409
410 StringRef Name = CGM.getMangledName(VtableComponent.getGlobalDecl());
411 auto *Entry = CGM.GetGlobalValue(Name);
412 // This checks if virtual inline function has already been emitted.
413 // Note that it is possible that this inline function would be emitted
414 // after trying to emit vtable speculatively. Because of this we do
415 // an extra pass after emitting all deferred vtables to find and emit
416 // these vtables opportunistically.
417 if (!Entry || Entry->isDeclaration())
418 return true;
419 }
420 return false;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000421 }
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000422
423 bool isVTableHidden(const CXXRecordDecl *RD) const {
424 const auto &VtableLayout =
425 CGM.getItaniumVTableContext().getVTableLayout(RD);
426
427 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
428 if (VtableComponent.isRTTIKind()) {
429 const CXXRecordDecl *RTTIDecl = VtableComponent.getRTTIDecl();
430 if (RTTIDecl->getVisibility() == Visibility::HiddenVisibility)
431 return true;
432 } else if (VtableComponent.isUsedFunctionPointerKind()) {
433 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
434 if (Method->getVisibility() == Visibility::HiddenVisibility &&
435 !Method->isDefined())
436 return true;
437 }
438 }
439 return false;
440 }
Charles Davis4e786dd2010-05-25 19:52:27 +0000441};
John McCall86353412010-08-21 22:46:04 +0000442
443class ARMCXXABI : public ItaniumCXXABI {
444public:
Mark Seabornedf0d382013-07-24 16:25:13 +0000445 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
446 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
447 /* UseARMGuardVarABI = */ true) {}
John McCall5d865c322010-08-31 07:33:07 +0000448
Craig Topper4f12f102014-03-12 06:41:41 +0000449 bool HasThisReturn(GlobalDecl GD) const override {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000450 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
451 isa<CXXDestructorDecl>(GD.getDecl()) &&
452 GD.getDtorType() != Dtor_Deleting));
453 }
John McCall5d865c322010-08-31 07:33:07 +0000454
Craig Topper4f12f102014-03-12 06:41:41 +0000455 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
456 QualType ResTy) override;
John McCall5d865c322010-08-31 07:33:07 +0000457
Craig Topper4f12f102014-03-12 06:41:41 +0000458 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall7f416cc2015-09-08 08:05:57 +0000459 Address InitializeArrayCookie(CodeGenFunction &CGF,
460 Address NewPtr,
461 llvm::Value *NumElements,
462 const CXXNewExpr *expr,
463 QualType ElementType) override;
464 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, Address allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000465 CharUnits cookieSize) override;
John McCall86353412010-08-21 22:46:04 +0000466};
Tim Northovera2ee4332014-03-29 15:09:45 +0000467
468class iOS64CXXABI : public ARMCXXABI {
469public:
John McCalld23b27e2016-09-16 02:40:45 +0000470 iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {
471 Use32BitVTableOffsetABI = true;
472 }
Tim Northover65f582f2014-03-30 17:32:48 +0000473
474 // ARM64 libraries are prepared for non-unique RTTI.
David Majnemere2cb8d12014-07-07 06:20:47 +0000475 bool shouldRTTIBeUnique() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +0000476};
Dan Gohmanc2853072015-09-03 22:51:53 +0000477
478class WebAssemblyCXXABI final : public ItaniumCXXABI {
479public:
480 explicit WebAssemblyCXXABI(CodeGen::CodeGenModule &CGM)
481 : ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
482 /*UseARMGuardVarABI=*/true) {}
483
484private:
485 bool HasThisReturn(GlobalDecl GD) const override {
486 return isa<CXXConstructorDecl>(GD.getDecl()) ||
487 (isa<CXXDestructorDecl>(GD.getDecl()) &&
488 GD.getDtorType() != Dtor_Deleting);
489 }
Derek Schuff8179be42016-05-10 17:44:55 +0000490 bool canCallMismatchedFunctionType() const override { return false; }
Dan Gohmanc2853072015-09-03 22:51:53 +0000491};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000492}
Charles Davis4e786dd2010-05-25 19:52:27 +0000493
Charles Davis53c59df2010-08-16 03:33:14 +0000494CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000495 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000496 // For IR-generation purposes, there's no significant difference
497 // between the ARM and iOS ABIs.
498 case TargetCXXABI::GenericARM:
499 case TargetCXXABI::iOS:
Tim Northover756447a2015-10-30 16:30:36 +0000500 case TargetCXXABI::WatchOS:
John McCall57625922013-01-25 23:36:14 +0000501 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000502
Tim Northovera2ee4332014-03-29 15:09:45 +0000503 case TargetCXXABI::iOS64:
504 return new iOS64CXXABI(CGM);
505
Tim Northover9bb857a2013-01-31 12:13:10 +0000506 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
507 // include the other 32-bit ARM oddities: constructor/destructor return values
508 // and array cookies.
509 case TargetCXXABI::GenericAArch64:
Mark Seabornedf0d382013-07-24 16:25:13 +0000510 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
511 /* UseARMGuardVarABI = */ true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000512
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000513 case TargetCXXABI::GenericMIPS:
514 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true);
515
Dan Gohmanc2853072015-09-03 22:51:53 +0000516 case TargetCXXABI::WebAssembly:
517 return new WebAssemblyCXXABI(CGM);
518
John McCall57625922013-01-25 23:36:14 +0000519 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000520 if (CGM.getContext().getTargetInfo().getTriple().getArch()
521 == llvm::Triple::le32) {
522 // For PNaCl, use ARM-style method pointers so that PNaCl code
523 // does not assume anything about the alignment of function
524 // pointers.
525 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
526 /* UseARMGuardVarABI = */ false);
527 }
John McCall57625922013-01-25 23:36:14 +0000528 return new ItaniumCXXABI(CGM);
529
530 case TargetCXXABI::Microsoft:
531 llvm_unreachable("Microsoft ABI is not Itanium-based");
532 }
533 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000534}
535
Chris Lattnera5f58b02011-07-09 17:41:47 +0000536llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000537ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
538 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000539 return CGM.PtrDiffTy;
Serge Guelton1d993272017-05-09 19:31:30 +0000540 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy);
John McCall1c456c82010-08-22 06:43:33 +0000541}
542
John McCalld9c6c0b2010-08-22 00:59:17 +0000543/// In the Itanium and ARM ABIs, method pointers have the form:
544/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
545///
546/// In the Itanium ABI:
547/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
548/// - the this-adjustment is (memptr.adj)
549/// - the virtual offset is (memptr.ptr - 1)
550///
551/// In the ARM ABI:
552/// - method pointers are virtual if (memptr.adj & 1) is nonzero
553/// - the this-adjustment is (memptr.adj >> 1)
554/// - the virtual offset is (memptr.ptr)
555/// ARM uses 'adj' for the virtual flag because Thumb functions
556/// may be only single-byte aligned.
557///
558/// If the member is virtual, the adjusted 'this' pointer points
559/// to a vtable pointer from which the virtual offset is applied.
560///
561/// If the member is non-virtual, memptr.ptr is the address of
562/// the function to call.
John McCallb92ab1a2016-10-26 23:46:34 +0000563CGCallee ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
John McCall7f416cc2015-09-08 08:05:57 +0000564 CodeGenFunction &CGF, const Expr *E, Address ThisAddr,
565 llvm::Value *&ThisPtrForCall,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000566 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
John McCall475999d2010-08-22 00:05:51 +0000567 CGBuilderTy &Builder = CGF.Builder;
568
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000569 const FunctionProtoType *FPT =
John McCall475999d2010-08-22 00:05:51 +0000570 MPT->getPointeeType()->getAs<FunctionProtoType>();
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000571 const CXXRecordDecl *RD =
John McCall475999d2010-08-22 00:05:51 +0000572 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
573
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000574 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(
575 CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr));
John McCall475999d2010-08-22 00:05:51 +0000576
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000577 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000578
John McCalld9c6c0b2010-08-22 00:59:17 +0000579 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
580 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
581 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
582
John McCalla1dee5302010-08-22 10:59:02 +0000583 // Extract memptr.adj, which is in the second field.
584 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000585
586 // Compute the true adjustment.
587 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000588 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000589 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000590
591 // Apply the adjustment and cast back to the original struct type
592 // for consistency.
John McCall7f416cc2015-09-08 08:05:57 +0000593 llvm::Value *This = ThisAddr.getPointer();
John McCalld9c6c0b2010-08-22 00:59:17 +0000594 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
595 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
596 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall7f416cc2015-09-08 08:05:57 +0000597 ThisPtrForCall = This;
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000598
John McCall475999d2010-08-22 00:05:51 +0000599 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000600 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000601
John McCall475999d2010-08-22 00:05:51 +0000602 // If the LSB in the function pointer is 1, the function pointer points to
603 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000604 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000605 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000606 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
607 else
608 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
609 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000610 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
611
612 // In the virtual path, the adjustment left 'This' pointing to the
613 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000614 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000615 CGF.EmitBlock(FnVirtual);
616
617 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000618 llvm::Type *VTableTy = Builder.getInt8PtrTy();
John McCall7f416cc2015-09-08 08:05:57 +0000619 CharUnits VTablePtrAlign =
620 CGF.CGM.getDynamicOffsetAlignment(ThisAddr.getAlignment(), RD,
621 CGF.getPointerAlign());
622 llvm::Value *VTable =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000623 CGF.GetVTablePtr(Address(This, VTablePtrAlign), VTableTy, RD);
John McCall475999d2010-08-22 00:05:51 +0000624
625 // Apply the offset.
John McCalld23b27e2016-09-16 02:40:45 +0000626 // On ARM64, to reserve extra space in virtual member function pointers,
627 // we only pay attention to the low 32 bits of the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000628 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000629 if (!UseARMMethodPtrABI)
630 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld23b27e2016-09-16 02:40:45 +0000631 if (Use32BitVTableOffsetABI) {
632 VTableOffset = Builder.CreateTrunc(VTableOffset, CGF.Int32Ty);
633 VTableOffset = Builder.CreateZExt(VTableOffset, CGM.PtrDiffTy);
634 }
John McCalld9c6c0b2010-08-22 00:59:17 +0000635 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall475999d2010-08-22 00:05:51 +0000636
637 // Load the virtual function to call.
638 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCall7f416cc2015-09-08 08:05:57 +0000639 llvm::Value *VirtualFn =
640 Builder.CreateAlignedLoad(VTable, CGF.getPointerAlign(),
641 "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000642 CGF.EmitBranch(FnEnd);
643
644 // In the non-virtual path, the function pointer is actually a
645 // function pointer.
646 CGF.EmitBlock(FnNonVirtual);
647 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000648 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000649
John McCall475999d2010-08-22 00:05:51 +0000650 // We're done.
651 CGF.EmitBlock(FnEnd);
John McCallb92ab1a2016-10-26 23:46:34 +0000652 llvm::PHINode *CalleePtr = Builder.CreatePHI(FTy->getPointerTo(), 2);
653 CalleePtr->addIncoming(VirtualFn, FnVirtual);
654 CalleePtr->addIncoming(NonVirtualFn, FnNonVirtual);
655
656 CGCallee Callee(FPT, CalleePtr);
John McCall475999d2010-08-22 00:05:51 +0000657 return Callee;
658}
John McCalla8bbb822010-08-22 03:04:22 +0000659
John McCallc134eb52010-08-31 21:07:20 +0000660/// Compute an l-value by applying the given pointer-to-member to a
661/// base object.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000662llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
John McCall7f416cc2015-09-08 08:05:57 +0000663 CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000664 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000665 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000666
667 CGBuilderTy &Builder = CGF.Builder;
668
John McCallc134eb52010-08-31 21:07:20 +0000669 // Cast to char*.
John McCall7f416cc2015-09-08 08:05:57 +0000670 Base = Builder.CreateElementBitCast(Base, CGF.Int8Ty);
John McCallc134eb52010-08-31 21:07:20 +0000671
672 // Apply the offset, which we assume is non-null.
John McCall7f416cc2015-09-08 08:05:57 +0000673 llvm::Value *Addr =
674 Builder.CreateInBoundsGEP(Base.getPointer(), MemPtr, "memptr.offset");
John McCallc134eb52010-08-31 21:07:20 +0000675
676 // Cast the address to the appropriate pointer type, adopting the
677 // address space of the base pointer.
John McCall7f416cc2015-09-08 08:05:57 +0000678 llvm::Type *PType = CGF.ConvertTypeForMem(MPT->getPointeeType())
679 ->getPointerTo(Base.getAddressSpace());
John McCallc134eb52010-08-31 21:07:20 +0000680 return Builder.CreateBitCast(Addr, PType);
681}
682
John McCallc62bb392012-02-15 01:22:51 +0000683/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
684/// conversion.
685///
686/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000687///
688/// Obligatory offset/adjustment diagram:
689/// <-- offset --> <-- adjustment -->
690/// |--------------------------|----------------------|--------------------|
691/// ^Derived address point ^Base address point ^Member address point
692///
693/// So when converting a base member pointer to a derived member pointer,
694/// we add the offset to the adjustment because the address point has
695/// decreased; and conversely, when converting a derived MP to a base MP
696/// we subtract the offset from the adjustment because the address point
697/// has increased.
698///
699/// The standard forbids (at compile time) conversion to and from
700/// virtual bases, which is why we don't have to consider them here.
701///
702/// The standard forbids (at run time) casting a derived MP to a base
703/// MP when the derived MP does not point to a member of the base.
704/// This is why -1 is a reasonable choice for null data member
705/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000706llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000707ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
708 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000709 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000710 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000711 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
712 E->getCastKind() == CK_ReinterpretMemberPointer);
713
714 // Under Itanium, reinterprets don't require any additional processing.
715 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
716
717 // Use constant emission if we can.
718 if (isa<llvm::Constant>(src))
719 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
720
721 llvm::Constant *adj = getMemberPointerAdjustment(E);
722 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000723
724 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000725 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000726
John McCallc62bb392012-02-15 01:22:51 +0000727 const MemberPointerType *destTy =
728 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000729
John McCall7a9aac22010-08-23 01:21:21 +0000730 // For member data pointers, this is just a matter of adding the
731 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000732 if (destTy->isMemberDataPointer()) {
733 llvm::Value *dst;
734 if (isDerivedToBase)
735 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000736 else
John McCallc62bb392012-02-15 01:22:51 +0000737 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000738
739 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000740 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
741 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
742 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000743 }
744
John McCalla1dee5302010-08-22 10:59:02 +0000745 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000746 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000747 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
748 offset <<= 1;
749 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000750 }
751
John McCallc62bb392012-02-15 01:22:51 +0000752 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
753 llvm::Value *dstAdj;
754 if (isDerivedToBase)
755 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000756 else
John McCallc62bb392012-02-15 01:22:51 +0000757 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000758
John McCallc62bb392012-02-15 01:22:51 +0000759 return Builder.CreateInsertValue(src, dstAdj, 1);
760}
761
762llvm::Constant *
763ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
764 llvm::Constant *src) {
765 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
766 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
767 E->getCastKind() == CK_ReinterpretMemberPointer);
768
769 // Under Itanium, reinterprets don't require any additional processing.
770 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
771
772 // If the adjustment is trivial, we don't need to do anything.
773 llvm::Constant *adj = getMemberPointerAdjustment(E);
774 if (!adj) return src;
775
776 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
777
778 const MemberPointerType *destTy =
779 E->getType()->castAs<MemberPointerType>();
780
781 // For member data pointers, this is just a matter of adding the
782 // offset if the source is non-null.
783 if (destTy->isMemberDataPointer()) {
784 // null maps to null.
785 if (src->isAllOnesValue()) return src;
786
787 if (isDerivedToBase)
788 return llvm::ConstantExpr::getNSWSub(src, adj);
789 else
790 return llvm::ConstantExpr::getNSWAdd(src, adj);
791 }
792
793 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000794 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000795 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
796 offset <<= 1;
797 adj = llvm::ConstantInt::get(adj->getType(), offset);
798 }
799
800 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
801 llvm::Constant *dstAdj;
802 if (isDerivedToBase)
803 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
804 else
805 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
806
807 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000808}
John McCall84fa5102010-08-22 04:16:24 +0000809
810llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000811ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000812 // Itanium C++ ABI 2.3:
813 // A NULL pointer is represented as -1.
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000814 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000815 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000816
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000817 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000818 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000819 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000820}
821
John McCallf3a88602011-02-03 08:15:49 +0000822llvm::Constant *
823ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
824 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000825 // Itanium C++ ABI 2.3:
826 // A pointer to data member is an offset from the base address of
827 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000828 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000829}
830
David Majnemere2be95b2015-06-23 07:31:01 +0000831llvm::Constant *
832ItaniumCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000833 return BuildMemberPointer(MD, CharUnits::Zero());
834}
835
836llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
837 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000838 assert(MD->isInstance() && "Member function must not be static!");
839 MD = MD->getCanonicalDecl();
840
841 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000842
843 // Get the function pointer (or index if this is a virtual function).
844 llvm::Constant *MemPtr[2];
845 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000846 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000847
Ken Dyckdf016282011-04-09 01:30:02 +0000848 const ASTContext &Context = getContext();
849 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000850 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000851 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000852
Mark Seabornedf0d382013-07-24 16:25:13 +0000853 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000854 // ARM C++ ABI 3.2.1:
855 // This ABI specifies that adj contains twice the this
856 // adjustment, plus 1 if the member function is virtual. The
857 // least significant bit of adj then makes exactly the same
858 // discrimination as the least significant bit of ptr does for
859 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000860 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
861 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000862 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000863 } else {
864 // Itanium C++ ABI 2.3:
865 // For a virtual function, [the pointer field] is 1 plus the
866 // virtual table offset (in bytes) of the function,
867 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000868 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
869 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000870 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000871 }
872 } else {
John McCall2979fe02011-04-12 00:42:48 +0000873 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000874 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000875 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000876 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000877 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000878 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000879 } else {
John McCall2979fe02011-04-12 00:42:48 +0000880 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
881 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000882 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000883 }
John McCall2979fe02011-04-12 00:42:48 +0000884 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000885
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000886 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000887 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
888 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000889 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000890 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000891
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000892 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000893}
894
Richard Smithdafff942012-01-14 04:30:29 +0000895llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
896 QualType MPType) {
897 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
898 const ValueDecl *MPD = MP.getMemberPointerDecl();
899 if (!MPD)
900 return EmitNullMemberPointer(MPT);
901
Reid Kleckner452abac2013-05-09 21:01:17 +0000902 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000903
904 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
905 return BuildMemberPointer(MD, ThisAdjustment);
906
907 CharUnits FieldOffset =
908 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
909 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
910}
911
John McCall131d97d2010-08-22 08:30:07 +0000912/// The comparison algorithm is pretty easy: the member pointers are
913/// the same if they're either bitwise identical *or* both null.
914///
915/// ARM is different here only because null-ness is more complicated.
916llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000917ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
918 llvm::Value *L,
919 llvm::Value *R,
920 const MemberPointerType *MPT,
921 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000922 CGBuilderTy &Builder = CGF.Builder;
923
John McCall131d97d2010-08-22 08:30:07 +0000924 llvm::ICmpInst::Predicate Eq;
925 llvm::Instruction::BinaryOps And, Or;
926 if (Inequality) {
927 Eq = llvm::ICmpInst::ICMP_NE;
928 And = llvm::Instruction::Or;
929 Or = llvm::Instruction::And;
930 } else {
931 Eq = llvm::ICmpInst::ICMP_EQ;
932 And = llvm::Instruction::And;
933 Or = llvm::Instruction::Or;
934 }
935
John McCall7a9aac22010-08-23 01:21:21 +0000936 // Member data pointers are easy because there's a unique null
937 // value, so it just comes down to bitwise equality.
938 if (MPT->isMemberDataPointer())
939 return Builder.CreateICmp(Eq, L, R);
940
941 // For member function pointers, the tautologies are more complex.
942 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000943 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000944 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000945 // (L == R) <==> (L.ptr == R.ptr &&
946 // (L.adj == R.adj ||
947 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000948 // The inequality tautologies have exactly the same structure, except
949 // applying De Morgan's laws.
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000950
John McCall7a9aac22010-08-23 01:21:21 +0000951 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
952 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
953
John McCall131d97d2010-08-22 08:30:07 +0000954 // This condition tests whether L.ptr == R.ptr. This must always be
955 // true for equality to hold.
956 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
957
958 // This condition, together with the assumption that L.ptr == R.ptr,
959 // tests whether the pointers are both null. ARM imposes an extra
960 // condition.
961 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
962 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
963
964 // This condition tests whether L.adj == R.adj. If this isn't
965 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +0000966 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
967 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000968 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
969
970 // Null member function pointers on ARM clear the low bit of Adj,
971 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000972 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000973 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
974
975 // Compute (l.adj | r.adj) & 1 and test it against zero.
976 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
977 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
978 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
979 "cmp.or.adj");
980 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
981 }
982
983 // Tie together all our conditions.
984 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
985 Result = Builder.CreateBinOp(And, PtrEq, Result,
986 Inequality ? "memptr.ne" : "memptr.eq");
987 return Result;
988}
989
990llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000991ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
992 llvm::Value *MemPtr,
993 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +0000994 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +0000995
996 /// For member data pointers, this is just a check against -1.
997 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000998 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +0000999 llvm::Value *NegativeOne =
1000 llvm::Constant::getAllOnesValue(MemPtr->getType());
1001 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
1002 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00001003
Daniel Dunbar914bc412011-04-19 23:10:47 +00001004 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +00001005 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +00001006
1007 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
1008 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
1009
Daniel Dunbar914bc412011-04-19 23:10:47 +00001010 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
1011 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +00001012 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +00001013 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +00001014 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +00001015 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +00001016 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
1017 "memptr.isvirtual");
1018 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +00001019 }
1020
1021 return Result;
1022}
John McCall1c456c82010-08-22 06:43:33 +00001023
Reid Kleckner40ca9132014-05-13 22:05:45 +00001024bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
1025 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
1026 if (!RD)
1027 return false;
1028
Richard Smith96cd6712017-08-16 01:49:53 +00001029 // If C++ prohibits us from making a copy, return by address.
Richard Smithf667ad52017-08-26 01:04:35 +00001030 if (passClassIndirect(RD)) {
John McCall7f416cc2015-09-08 08:05:57 +00001031 auto Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
1032 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
Reid Kleckner40ca9132014-05-13 22:05:45 +00001033 return true;
1034 }
Reid Kleckner40ca9132014-05-13 22:05:45 +00001035 return false;
1036}
1037
John McCall614dbdc2010-08-22 21:01:12 +00001038/// The Itanium ABI requires non-zero initialization only for data
1039/// member pointers, for which '0' is a valid offset.
1040bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
David Majnemer5fd33e02015-04-24 01:25:08 +00001041 return MPT->isMemberFunctionPointer();
John McCall84fa5102010-08-22 04:16:24 +00001042}
John McCall5d865c322010-08-31 07:33:07 +00001043
John McCall82fb8922012-09-25 10:10:39 +00001044/// The Itanium ABI always places an offset to the complete object
1045/// at entry -2 in the vtable.
David Majnemer08681372014-11-01 07:37:17 +00001046void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
1047 const CXXDeleteExpr *DE,
John McCall7f416cc2015-09-08 08:05:57 +00001048 Address Ptr,
David Majnemer08681372014-11-01 07:37:17 +00001049 QualType ElementType,
1050 const CXXDestructorDecl *Dtor) {
1051 bool UseGlobalDelete = DE->isGlobalDelete();
David Majnemer0c0b6d92014-10-31 20:09:12 +00001052 if (UseGlobalDelete) {
1053 // Derive the complete-object pointer, which is what we need
1054 // to pass to the deallocation function.
John McCall82fb8922012-09-25 10:10:39 +00001055
David Majnemer0c0b6d92014-10-31 20:09:12 +00001056 // Grab the vtable pointer as an intptr_t*.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001057 auto *ClassDecl =
1058 cast<CXXRecordDecl>(ElementType->getAs<RecordType>()->getDecl());
1059 llvm::Value *VTable =
1060 CGF.GetVTablePtr(Ptr, CGF.IntPtrTy->getPointerTo(), ClassDecl);
John McCall82fb8922012-09-25 10:10:39 +00001061
David Majnemer0c0b6d92014-10-31 20:09:12 +00001062 // Track back to entry -2 and pull out the offset there.
1063 llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
1064 VTable, -2, "complete-offset.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001065 llvm::Value *Offset =
1066 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
David Majnemer0c0b6d92014-10-31 20:09:12 +00001067
1068 // Apply the offset.
John McCall7f416cc2015-09-08 08:05:57 +00001069 llvm::Value *CompletePtr =
1070 CGF.Builder.CreateBitCast(Ptr.getPointer(), CGF.Int8PtrTy);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001071 CompletePtr = CGF.Builder.CreateInBoundsGEP(CompletePtr, Offset);
1072
1073 // If we're supposed to call the global delete, make sure we do so
1074 // even if the destructor throws.
David Majnemer08681372014-11-01 07:37:17 +00001075 CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr,
1076 ElementType);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001077 }
1078
1079 // FIXME: Provide a source location here even though there's no
1080 // CXXMemberCallExpr for dtor call.
1081 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
1082 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr);
1083
1084 if (UseGlobalDelete)
1085 CGF.PopCleanupBlock();
John McCall82fb8922012-09-25 10:10:39 +00001086}
1087
David Majnemer442d0a22014-11-25 07:20:20 +00001088void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
1089 // void __cxa_rethrow();
1090
1091 llvm::FunctionType *FTy =
1092 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
1093
1094 llvm::Constant *Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
1095
1096 if (isNoReturn)
1097 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, None);
1098 else
1099 CGF.EmitRuntimeCallOrInvoke(Fn);
1100}
1101
David Majnemer7c237072015-03-05 00:46:22 +00001102static llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) {
1103 // void *__cxa_allocate_exception(size_t thrown_size);
1104
1105 llvm::FunctionType *FTy =
1106 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false);
1107
1108 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
1109}
1110
1111static llvm::Constant *getThrowFn(CodeGenModule &CGM) {
1112 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
1113 // void (*dest) (void *));
1114
1115 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
1116 llvm::FunctionType *FTy =
1117 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
1118
1119 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
1120}
1121
1122void ItaniumCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
1123 QualType ThrowType = E->getSubExpr()->getType();
1124 // Now allocate the exception object.
1125 llvm::Type *SizeTy = CGF.ConvertType(getContext().getSizeType());
1126 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
1127
1128 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM);
1129 llvm::CallInst *ExceptionPtr = CGF.EmitNounwindRuntimeCall(
1130 AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception");
1131
John McCall7f416cc2015-09-08 08:05:57 +00001132 CharUnits ExnAlign = getAlignmentOfExnObject();
1133 CGF.EmitAnyExprToExn(E->getSubExpr(), Address(ExceptionPtr, ExnAlign));
David Majnemer7c237072015-03-05 00:46:22 +00001134
1135 // Now throw the exception.
1136 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
1137 /*ForEH=*/true);
1138
1139 // The address of the destructor. If the exception type has a
1140 // trivial destructor (or isn't a record), we just pass null.
1141 llvm::Constant *Dtor = nullptr;
1142 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
1143 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
1144 if (!Record->hasTrivialDestructor()) {
1145 CXXDestructorDecl *DtorD = Record->getDestructor();
1146 Dtor = CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete);
1147 Dtor = llvm::ConstantExpr::getBitCast(Dtor, CGM.Int8PtrTy);
1148 }
1149 }
1150 if (!Dtor) Dtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
1151
1152 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
1153 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
1154}
1155
David Majnemer1162d252014-06-22 19:05:33 +00001156static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) {
1157 // void *__dynamic_cast(const void *sub,
1158 // const abi::__class_type_info *src,
1159 // const abi::__class_type_info *dst,
1160 // std::ptrdiff_t src2dst_offset);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00001161
David Majnemer1162d252014-06-22 19:05:33 +00001162 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
Jake Ehrlichc451cf22017-11-11 01:15:41 +00001163 llvm::Type *PtrDiffTy =
David Majnemer1162d252014-06-22 19:05:33 +00001164 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1165
1166 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
1167
1168 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
1169
1170 // Mark the function as nounwind readonly.
1171 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
1172 llvm::Attribute::ReadOnly };
Reid Klecknerde864822017-03-21 16:57:30 +00001173 llvm::AttributeList Attrs = llvm::AttributeList::get(
1174 CGF.getLLVMContext(), llvm::AttributeList::FunctionIndex, FuncAttrs);
David Majnemer1162d252014-06-22 19:05:33 +00001175
1176 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
1177}
1178
1179static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1180 // void __cxa_bad_cast();
1181 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1182 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1183}
1184
1185/// \brief Compute the src2dst_offset hint as described in the
1186/// Itanium C++ ABI [2.9.7]
1187static CharUnits computeOffsetHint(ASTContext &Context,
1188 const CXXRecordDecl *Src,
1189 const CXXRecordDecl *Dst) {
1190 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1191 /*DetectVirtual=*/false);
1192
1193 // If Dst is not derived from Src we can skip the whole computation below and
1194 // return that Src is not a public base of Dst. Record all inheritance paths.
1195 if (!Dst->isDerivedFrom(Src, Paths))
1196 return CharUnits::fromQuantity(-2ULL);
1197
1198 unsigned NumPublicPaths = 0;
1199 CharUnits Offset;
1200
1201 // Now walk all possible inheritance paths.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001202 for (const CXXBasePath &Path : Paths) {
1203 if (Path.Access != AS_public) // Ignore non-public inheritance.
David Majnemer1162d252014-06-22 19:05:33 +00001204 continue;
1205
1206 ++NumPublicPaths;
1207
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001208 for (const CXXBasePathElement &PathElement : Path) {
David Majnemer1162d252014-06-22 19:05:33 +00001209 // If the path contains a virtual base class we can't give any hint.
1210 // -1: no hint.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001211 if (PathElement.Base->isVirtual())
David Majnemer1162d252014-06-22 19:05:33 +00001212 return CharUnits::fromQuantity(-1ULL);
1213
1214 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
1215 continue;
1216
1217 // Accumulate the base class offsets.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001218 const ASTRecordLayout &L = Context.getASTRecordLayout(PathElement.Class);
1219 Offset += L.getBaseClassOffset(
1220 PathElement.Base->getType()->getAsCXXRecordDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001221 }
1222 }
1223
1224 // -2: Src is not a public base of Dst.
1225 if (NumPublicPaths == 0)
1226 return CharUnits::fromQuantity(-2ULL);
1227
1228 // -3: Src is a multiple public base type but never a virtual base type.
1229 if (NumPublicPaths > 1)
1230 return CharUnits::fromQuantity(-3ULL);
1231
1232 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
1233 // Return the offset of Src from the origin of Dst.
1234 return Offset;
1235}
1236
1237static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1238 // void __cxa_bad_typeid();
1239 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1240
1241 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1242}
1243
1244bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
1245 QualType SrcRecordTy) {
1246 return IsDeref;
1247}
1248
1249void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
1250 llvm::Value *Fn = getBadTypeidFn(CGF);
1251 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1252 CGF.Builder.CreateUnreachable();
1253}
1254
1255llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
1256 QualType SrcRecordTy,
John McCall7f416cc2015-09-08 08:05:57 +00001257 Address ThisPtr,
David Majnemer1162d252014-06-22 19:05:33 +00001258 llvm::Type *StdTypeInfoPtrTy) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001259 auto *ClassDecl =
1260 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001261 llvm::Value *Value =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001262 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo(), ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001263
1264 // Load the type info.
1265 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001266 return CGF.Builder.CreateAlignedLoad(Value, CGF.getPointerAlign());
David Majnemer1162d252014-06-22 19:05:33 +00001267}
1268
1269bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1270 QualType SrcRecordTy) {
1271 return SrcIsPtr;
1272}
1273
1274llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
John McCall7f416cc2015-09-08 08:05:57 +00001275 CodeGenFunction &CGF, Address ThisAddr, QualType SrcRecordTy,
David Majnemer1162d252014-06-22 19:05:33 +00001276 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1277 llvm::Type *PtrDiffLTy =
1278 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1279 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1280
1281 llvm::Value *SrcRTTI =
1282 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1283 llvm::Value *DestRTTI =
1284 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1285
1286 // Compute the offset hint.
1287 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1288 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1289 llvm::Value *OffsetHint = llvm::ConstantInt::get(
1290 PtrDiffLTy,
1291 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
1292
1293 // Emit the call to __dynamic_cast.
John McCall7f416cc2015-09-08 08:05:57 +00001294 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001295 Value = CGF.EmitCastToVoidPtr(Value);
1296
1297 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
1298 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
1299 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1300
1301 /// C++ [expr.dynamic.cast]p9:
1302 /// A failed cast to reference type throws std::bad_cast
1303 if (DestTy->isReferenceType()) {
1304 llvm::BasicBlock *BadCastBlock =
1305 CGF.createBasicBlock("dynamic_cast.bad_cast");
1306
1307 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1308 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1309
1310 CGF.EmitBlock(BadCastBlock);
1311 EmitBadCastCall(CGF);
1312 }
1313
1314 return Value;
1315}
1316
1317llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001318 Address ThisAddr,
David Majnemer1162d252014-06-22 19:05:33 +00001319 QualType SrcRecordTy,
1320 QualType DestTy) {
1321 llvm::Type *PtrDiffLTy =
1322 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1323 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1324
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001325 auto *ClassDecl =
1326 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001327 // Get the vtable pointer.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001328 llvm::Value *VTable = CGF.GetVTablePtr(ThisAddr, PtrDiffLTy->getPointerTo(),
1329 ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001330
1331 // Get the offset-to-top from the vtable.
1332 llvm::Value *OffsetToTop =
1333 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001334 OffsetToTop =
1335 CGF.Builder.CreateAlignedLoad(OffsetToTop, CGF.getPointerAlign(),
1336 "offset.to.top");
David Majnemer1162d252014-06-22 19:05:33 +00001337
1338 // Finally, add the offset to the pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001339 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001340 Value = CGF.EmitCastToVoidPtr(Value);
1341 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1342
1343 return CGF.Builder.CreateBitCast(Value, DestLTy);
1344}
1345
1346bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1347 llvm::Value *Fn = getBadCastFn(CGF);
1348 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1349 CGF.Builder.CreateUnreachable();
1350 return true;
1351}
1352
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001353llvm::Value *
1354ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001355 Address This,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001356 const CXXRecordDecl *ClassDecl,
1357 const CXXRecordDecl *BaseClassDecl) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001358 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy, ClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001359 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001360 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1361 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001362
1363 llvm::Value *VBaseOffsetPtr =
1364 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1365 "vbase.offset.ptr");
1366 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1367 CGM.PtrDiffTy->getPointerTo());
1368
1369 llvm::Value *VBaseOffset =
John McCall7f416cc2015-09-08 08:05:57 +00001370 CGF.Builder.CreateAlignedLoad(VBaseOffsetPtr, CGF.getPointerAlign(),
1371 "vbase.offset");
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001372
1373 return VBaseOffset;
1374}
1375
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001376void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1377 // Just make sure we're in sync with TargetCXXABI.
1378 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1379
Rafael Espindolac3cde362013-12-09 14:51:17 +00001380 // The constructor used for constructing this as a base class;
1381 // ignores virtual bases.
1382 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1383
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001384 // The constructor used for constructing this as a complete class;
Nico Weber4c2ffb22015-01-07 05:25:05 +00001385 // constructs the virtual bases, then calls the base constructor.
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001386 if (!D->getParent()->isAbstract()) {
1387 // We don't need to emit the complete ctor if the class is abstract.
1388 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1389 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001390}
1391
George Burgess IVf203dbf2017-02-22 20:28:02 +00001392CGCXXABI::AddedStructorArgs
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001393ItaniumCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
1394 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +00001395 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001396
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001397 // All parameters are already in place except VTT, which goes after 'this'.
1398 // These are Clang types, so we don't need to worry about sret yet.
John McCall5d865c322010-08-31 07:33:07 +00001399
1400 // Check if we need to add a VTT parameter (which has type void **).
George Burgess IVf203dbf2017-02-22 20:28:02 +00001401 if (T == StructorType::Base && MD->getParent()->getNumVBases() != 0) {
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001402 ArgTys.insert(ArgTys.begin() + 1,
1403 Context.getPointerType(Context.VoidPtrTy));
George Burgess IVf203dbf2017-02-22 20:28:02 +00001404 return AddedStructorArgs::prefix(1);
1405 }
1406 return AddedStructorArgs{};
John McCall5d865c322010-08-31 07:33:07 +00001407}
1408
Reid Klecknere7de47e2013-07-22 13:51:44 +00001409void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
Rafael Espindolac3cde362013-12-09 14:51:17 +00001410 // The destructor used for destructing this as a base class; ignores
1411 // virtual bases.
1412 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001413
1414 // The destructor used for destructing this as a most-derived class;
1415 // call the base destructor and then destructs any virtual bases.
1416 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1417
Rafael Espindolac3cde362013-12-09 14:51:17 +00001418 // The destructor in a virtual table is always a 'deleting'
1419 // destructor, which calls the complete destructor and then uses the
1420 // appropriate operator delete.
1421 if (D->isVirtual())
1422 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001423}
1424
Reid Kleckner89077a12013-12-17 19:46:40 +00001425void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1426 QualType &ResTy,
1427 FunctionArgList &Params) {
John McCall5d865c322010-08-31 07:33:07 +00001428 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +00001429 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
John McCall5d865c322010-08-31 07:33:07 +00001430
1431 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001432 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +00001433 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001434
1435 // FIXME: avoid the fake decl
1436 QualType T = Context.getPointerType(Context.VoidPtrTy);
Alexey Bataev56223232017-06-09 13:40:18 +00001437 auto *VTTDecl = ImplicitParamDecl::Create(
1438 Context, /*DC=*/nullptr, MD->getLocation(), &Context.Idents.get("vtt"),
1439 T, ImplicitParamDecl::CXXVTT);
Reid Kleckner89077a12013-12-17 19:46:40 +00001440 Params.insert(Params.begin() + 1, VTTDecl);
Reid Kleckner2af6d732013-12-13 00:09:59 +00001441 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +00001442 }
1443}
1444
John McCall5d865c322010-08-31 07:33:07 +00001445void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
Justin Lebared4f1722016-07-27 22:04:24 +00001446 // Naked functions have no prolog.
1447 if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>())
1448 return;
1449
Reid Kleckner06239e42017-11-16 19:09:36 +00001450 /// Initialize the 'this' slot. In the Itanium C++ ABI, no prologue
1451 /// adjustments are required, becuase they are all handled by thunks.
1452 setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));
John McCall5d865c322010-08-31 07:33:07 +00001453
1454 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +00001455 if (getStructorImplicitParamDecl(CGF)) {
1456 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1457 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +00001458 }
John McCall5d865c322010-08-31 07:33:07 +00001459
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001460 /// If this is a function that the ABI specifies returns 'this', initialize
1461 /// the return slot to 'this' at the start of the function.
1462 ///
1463 /// Unlike the setting of return types, this is done within the ABI
1464 /// implementation instead of by clients of CGCXXABI because:
1465 /// 1) getThisValue is currently protected
1466 /// 2) in theory, an ABI could implement 'this' returns some other way;
1467 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +00001468 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +00001469 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +00001470}
1471
George Burgess IVf203dbf2017-02-22 20:28:02 +00001472CGCXXABI::AddedStructorArgs ItaniumCXXABI::addImplicitConstructorArgs(
Reid Kleckner89077a12013-12-17 19:46:40 +00001473 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1474 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1475 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
George Burgess IVf203dbf2017-02-22 20:28:02 +00001476 return AddedStructorArgs{};
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001477
Reid Kleckner89077a12013-12-17 19:46:40 +00001478 // Insert the implicit 'vtt' argument as the second argument.
1479 llvm::Value *VTT =
1480 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1481 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1482 Args.insert(Args.begin() + 1,
1483 CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false));
George Burgess IVf203dbf2017-02-22 20:28:02 +00001484 return AddedStructorArgs::prefix(1); // Added one arg.
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001485}
1486
1487void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1488 const CXXDestructorDecl *DD,
1489 CXXDtorType Type, bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +00001490 bool Delegating, Address This) {
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001491 GlobalDecl GD(DD, Type);
1492 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1493 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1494
John McCallb92ab1a2016-10-26 23:46:34 +00001495 CGCallee Callee;
1496 if (getContext().getLangOpts().AppleKext &&
1497 Type != Dtor_Base && DD->isVirtual())
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001498 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
John McCallb92ab1a2016-10-26 23:46:34 +00001499 else
1500 Callee =
1501 CGCallee::forDirect(CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type)),
1502 DD);
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001503
John McCall7f416cc2015-09-08 08:05:57 +00001504 CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(),
Richard Smith762672a2016-09-28 19:09:10 +00001505 This.getPointer(), VTT, VTTTy,
1506 nullptr, nullptr);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001507}
1508
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001509void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1510 const CXXRecordDecl *RD) {
1511 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1512 if (VTable->hasInitializer())
1513 return;
1514
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001515 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001516 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1517 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
David Majnemerd905da42014-07-01 20:30:31 +00001518 llvm::Constant *RTTI =
1519 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001520
1521 // Create and set the initializer.
John McCall9c6cb762016-11-28 22:18:33 +00001522 ConstantInitBuilder Builder(CGM);
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001523 auto Components = Builder.beginStruct();
John McCall9c6cb762016-11-28 22:18:33 +00001524 CGVT.createVTableInitializer(Components, VTLayout, RTTI);
1525 Components.finishAndSetAsInitializer(VTable);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001526
1527 // Set the correct linkage.
1528 VTable->setLinkage(Linkage);
1529
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001530 if (CGM.supportsCOMDAT() && VTable->isWeakForLinker())
1531 VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName()));
Rafael Espindolacb92c192015-01-15 23:18:01 +00001532
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001533 // Set the right visibility.
Rafael Espindola699f5d62018-02-07 22:15:33 +00001534 CGM.setGVProperties(VTable, RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001535
Benjamin Kramer5d34a2b2014-09-10 12:50:59 +00001536 // Use pointer alignment for the vtable. Otherwise we would align them based
1537 // on the size of the initializer which doesn't make sense as only single
1538 // values are read.
1539 unsigned PAlign = CGM.getTarget().getPointerAlign(0);
1540 VTable->setAlignment(getContext().toCharUnitsFromBits(PAlign).getQuantity());
1541
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001542 // If this is the magic class __cxxabiv1::__fundamental_type_info,
1543 // we will emit the typeinfo for the fundamental types. This is the
1544 // same behaviour as GCC.
1545 const DeclContext *DC = RD->getDeclContext();
1546 if (RD->getIdentifier() &&
1547 RD->getIdentifier()->isStr("__fundamental_type_info") &&
1548 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1549 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1550 DC->getParent()->isTranslationUnit())
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00001551 EmitFundamentalRTTIDescriptors(RD->hasAttr<DLLExportAttr>());
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001552
Evgeniy Stepanov93987df2016-01-23 01:20:18 +00001553 if (!VTable->isDeclarationForLinker())
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001554 CGM.EmitVTableTypeMetadata(VTable, VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001555}
1556
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001557bool ItaniumCXXABI::isVirtualOffsetNeededForVTableField(
1558 CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
1559 if (Vptr.NearestVBase == nullptr)
1560 return false;
1561 return NeedsVTTParameter(CGF.CurGD);
Piotr Padlewski255652e2015-09-09 22:20:28 +00001562}
1563
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001564llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1565 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1566 const CXXRecordDecl *NearestVBase) {
1567
1568 if ((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1569 NeedsVTTParameter(CGF.CurGD)) {
1570 return getVTableAddressPointInStructorWithVTT(CGF, VTableClass, Base,
1571 NearestVBase);
1572 }
1573 return getVTableAddressPoint(Base, VTableClass);
1574}
1575
1576llvm::Constant *
1577ItaniumCXXABI::getVTableAddressPoint(BaseSubobject Base,
1578 const CXXRecordDecl *VTableClass) {
1579 llvm::GlobalValue *VTable = getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001580
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001581 // Find the appropriate vtable within the vtable group, and the address point
1582 // within that vtable.
1583 VTableLayout::AddressPointLocation AddressPoint =
1584 CGM.getItaniumVTableContext()
1585 .getVTableLayout(VTableClass)
1586 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001587 llvm::Value *Indices[] = {
Peter Collingbourne4e6a5402016-03-14 19:07:10 +00001588 llvm::ConstantInt::get(CGM.Int32Ty, 0),
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001589 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.VTableIndex),
1590 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.AddressPointIndex),
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001591 };
1592
Peter Collingbourne25a2b702016-12-13 20:50:44 +00001593 return llvm::ConstantExpr::getGetElementPtr(VTable->getValueType(), VTable,
1594 Indices, /*InBounds=*/true,
1595 /*InRangeIndex=*/1);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001596}
1597
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001598llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructorWithVTT(
1599 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1600 const CXXRecordDecl *NearestVBase) {
1601 assert((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1602 NeedsVTTParameter(CGF.CurGD) && "This class doesn't have VTT");
1603
1604 // Get the secondary vpointer index.
1605 uint64_t VirtualPointerIndex =
1606 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1607
1608 /// Load the VTT.
1609 llvm::Value *VTT = CGF.LoadCXXVTT();
1610 if (VirtualPointerIndex)
1611 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1612
1613 // And load the address point from the VTT.
1614 return CGF.Builder.CreateAlignedLoad(VTT, CGF.getPointerAlign());
1615}
1616
1617llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1618 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1619 return getVTableAddressPoint(Base, VTableClass);
1620}
1621
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001622llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1623 CharUnits VPtrOffset) {
1624 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1625
1626 llvm::GlobalVariable *&VTable = VTables[RD];
1627 if (VTable)
1628 return VTable;
1629
Eric Christopherd160c502016-01-29 01:35:53 +00001630 // Queue up this vtable for possible deferred emission.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001631 CGM.addDeferredVTable(RD);
1632
Yaron Kerene46f7ed2015-07-29 14:21:47 +00001633 SmallString<256> Name;
1634 llvm::raw_svector_ostream Out(Name);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001635 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001636
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001637 const VTableLayout &VTLayout =
1638 CGM.getItaniumVTableContext().getVTableLayout(RD);
1639 llvm::Type *VTableType = CGM.getVTables().getVTableType(VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001640
1641 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001642 Name, VTableType, llvm::GlobalValue::ExternalLinkage);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001643 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Rafael Espindola699f5d62018-02-07 22:15:33 +00001644 CGM.setGVProperties(VTable, RD);
Hans Wennborgda24e9c2014-06-02 23:13:03 +00001645
1646 if (RD->hasAttr<DLLImportAttr>())
1647 VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1648 else if (RD->hasAttr<DLLExportAttr>())
1649 VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1650
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001651 return VTable;
1652}
1653
John McCall9831b842018-02-06 18:52:44 +00001654CGCallee ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1655 GlobalDecl GD,
1656 Address This,
1657 llvm::Type *Ty,
1658 SourceLocation Loc) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001659 GD = GD.getCanonicalDecl();
1660 Ty = Ty->getPointerTo()->getPointerTo();
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001661 auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
1662 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty, MethodDecl->getParent());
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001663
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001664 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
John McCall9831b842018-02-06 18:52:44 +00001665 llvm::Value *VFunc;
1666 if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) {
1667 VFunc = CGF.EmitVTableTypeCheckedLoad(
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001668 MethodDecl->getParent(), VTable,
1669 VTableIndex * CGM.getContext().getTargetInfo().getPointerWidth(0) / 8);
John McCall9831b842018-02-06 18:52:44 +00001670 } else {
1671 CGF.EmitTypeMetadataCodeForVCall(MethodDecl->getParent(), VTable, Loc);
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001672
John McCall9831b842018-02-06 18:52:44 +00001673 llvm::Value *VFuncPtr =
1674 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1675 auto *VFuncLoad =
1676 CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign());
Piotr Padlewski77cc9622016-10-29 15:28:30 +00001677
John McCall9831b842018-02-06 18:52:44 +00001678 // Add !invariant.load md to virtual function load to indicate that
1679 // function didn't change inside vtable.
1680 // It's safe to add it without -fstrict-vtable-pointers, but it would not
1681 // help in devirtualization because it will only matter if we will have 2
1682 // the same virtual function loads from the same vtable load, which won't
1683 // happen without enabled devirtualization with -fstrict-vtable-pointers.
1684 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1685 CGM.getCodeGenOpts().StrictVTablePointers)
1686 VFuncLoad->setMetadata(
1687 llvm::LLVMContext::MD_invariant_load,
1688 llvm::MDNode::get(CGM.getLLVMContext(),
1689 llvm::ArrayRef<llvm::Metadata *>()));
1690 VFunc = VFuncLoad;
1691 }
John McCallb92ab1a2016-10-26 23:46:34 +00001692
John McCall9831b842018-02-06 18:52:44 +00001693 CGCallee Callee(MethodDecl, VFunc);
1694 return Callee;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001695}
1696
David Majnemer0c0b6d92014-10-31 20:09:12 +00001697llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
1698 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
John McCall7f416cc2015-09-08 08:05:57 +00001699 Address This, const CXXMemberCallExpr *CE) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001700 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001701 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1702
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001703 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1704 Dtor, getFromDtorType(DtorType));
Peter Collingbourneea211002018-02-05 23:09:13 +00001705 auto *Ty =
1706 cast<llvm::FunctionType>(CGF.CGM.getTypes().GetFunctionType(*FInfo));
John McCallb92ab1a2016-10-26 23:46:34 +00001707 CGCallee Callee =
Peter Collingbourneea211002018-02-05 23:09:13 +00001708 CGCallee::forVirtual(CE, GlobalDecl(Dtor, DtorType), This, Ty);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001709
John McCall7f416cc2015-09-08 08:05:57 +00001710 CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(),
1711 This.getPointer(), /*ImplicitParam=*/nullptr,
Richard Smith762672a2016-09-28 19:09:10 +00001712 QualType(), CE, nullptr);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001713 return nullptr;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001714}
1715
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001716void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001717 CodeGenVTables &VTables = CGM.getVTables();
1718 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001719 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001720}
1721
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001722bool ItaniumCXXABI::canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const {
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001723 // We don't emit available_externally vtables if we are in -fapple-kext mode
1724 // because kext mode does not permit devirtualization.
1725 if (CGM.getLangOpts().AppleKext)
1726 return false;
1727
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00001728 // If we don't have any not emitted inline virtual function, and if vtable is
1729 // not hidden, then we are safe to emit available_externally copy of vtable.
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001730 // FIXME we can still emit a copy of the vtable if we
1731 // can emit definition of the inline functions.
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00001732 return !hasAnyUnusedVirtualInlineFunction(RD) && !isVTableHidden(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001733}
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001734static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001735 Address InitialPtr,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001736 int64_t NonVirtualAdjustment,
1737 int64_t VirtualAdjustment,
1738 bool IsReturnAdjustment) {
1739 if (!NonVirtualAdjustment && !VirtualAdjustment)
John McCall7f416cc2015-09-08 08:05:57 +00001740 return InitialPtr.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001741
John McCall7f416cc2015-09-08 08:05:57 +00001742 Address V = CGF.Builder.CreateElementBitCast(InitialPtr, CGF.Int8Ty);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001743
John McCall7f416cc2015-09-08 08:05:57 +00001744 // In a base-to-derived cast, the non-virtual adjustment is applied first.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001745 if (NonVirtualAdjustment && !IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001746 V = CGF.Builder.CreateConstInBoundsByteGEP(V,
1747 CharUnits::fromQuantity(NonVirtualAdjustment));
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001748 }
1749
John McCall7f416cc2015-09-08 08:05:57 +00001750 // Perform the virtual adjustment if we have one.
1751 llvm::Value *ResultPtr;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001752 if (VirtualAdjustment) {
1753 llvm::Type *PtrDiffTy =
1754 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1755
John McCall7f416cc2015-09-08 08:05:57 +00001756 Address VTablePtrPtr = CGF.Builder.CreateElementBitCast(V, CGF.Int8PtrTy);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001757 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1758
1759 llvm::Value *OffsetPtr =
1760 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1761
1762 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1763
1764 // Load the adjustment offset from the vtable.
John McCall7f416cc2015-09-08 08:05:57 +00001765 llvm::Value *Offset =
1766 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001767
1768 // Adjust our pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001769 ResultPtr = CGF.Builder.CreateInBoundsGEP(V.getPointer(), Offset);
1770 } else {
1771 ResultPtr = V.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001772 }
1773
John McCall7f416cc2015-09-08 08:05:57 +00001774 // In a derived-to-base conversion, the non-virtual adjustment is
1775 // applied second.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001776 if (NonVirtualAdjustment && IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001777 ResultPtr = CGF.Builder.CreateConstInBoundsGEP1_64(ResultPtr,
1778 NonVirtualAdjustment);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001779 }
1780
1781 // Cast back to the original type.
John McCall7f416cc2015-09-08 08:05:57 +00001782 return CGF.Builder.CreateBitCast(ResultPtr, InitialPtr.getType());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001783}
1784
1785llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001786 Address This,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001787 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001788 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1789 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001790 /*IsReturnAdjustment=*/false);
1791}
1792
1793llvm::Value *
John McCall7f416cc2015-09-08 08:05:57 +00001794ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001795 const ReturnAdjustment &RA) {
1796 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1797 RA.Virtual.Itanium.VBaseOffsetOffset,
1798 /*IsReturnAdjustment=*/true);
1799}
1800
John McCall5d865c322010-08-31 07:33:07 +00001801void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1802 RValue RV, QualType ResultType) {
1803 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1804 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1805
1806 // Destructor thunks in the ARM ABI have indeterminate results.
John McCall7f416cc2015-09-08 08:05:57 +00001807 llvm::Type *T = CGF.ReturnValue.getElementType();
John McCall5d865c322010-08-31 07:33:07 +00001808 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1809 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1810}
John McCall8ed55a52010-09-02 09:58:18 +00001811
1812/************************** Array allocation cookies **************************/
1813
John McCallb91cd662012-05-01 05:23:51 +00001814CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1815 // The array cookie is a size_t; pad that up to the element alignment.
1816 // The cookie is actually right-justified in that space.
1817 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1818 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001819}
1820
John McCall7f416cc2015-09-08 08:05:57 +00001821Address ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1822 Address NewPtr,
1823 llvm::Value *NumElements,
1824 const CXXNewExpr *expr,
1825 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001826 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001827
John McCall7f416cc2015-09-08 08:05:57 +00001828 unsigned AS = NewPtr.getAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001829
John McCall9bca9232010-09-02 10:25:57 +00001830 ASTContext &Ctx = getContext();
John McCall7f416cc2015-09-08 08:05:57 +00001831 CharUnits SizeSize = CGF.getSizeSize();
John McCall8ed55a52010-09-02 09:58:18 +00001832
1833 // The size of the cookie.
1834 CharUnits CookieSize =
1835 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001836 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001837
1838 // Compute an offset to the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001839 Address CookiePtr = NewPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001840 CharUnits CookieOffset = CookieSize - SizeSize;
1841 if (!CookieOffset.isZero())
John McCall7f416cc2015-09-08 08:05:57 +00001842 CookiePtr = CGF.Builder.CreateConstInBoundsByteGEP(CookiePtr, CookieOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001843
1844 // Write the number of elements into the appropriate slot.
John McCall7f416cc2015-09-08 08:05:57 +00001845 Address NumElementsPtr =
1846 CGF.Builder.CreateElementBitCast(CookiePtr, CGF.SizeTy);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001847 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
John McCall7f416cc2015-09-08 08:05:57 +00001848
1849 // Handle the array cookie specially in ASan.
Filipe Cabecinhas6f83fa92018-01-02 13:46:12 +00001850 if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 &&
1851 expr->getOperatorNew()->isReplaceableGlobalAllocationFunction()) {
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001852 // The store to the CookiePtr does not need to be instrumented.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001853 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
1854 llvm::FunctionType *FTy =
John McCall7f416cc2015-09-08 08:05:57 +00001855 llvm::FunctionType::get(CGM.VoidTy, NumElementsPtr.getType(), false);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001856 llvm::Constant *F =
1857 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001858 CGF.Builder.CreateCall(F, NumElementsPtr.getPointer());
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001859 }
John McCall8ed55a52010-09-02 09:58:18 +00001860
1861 // Finally, compute a pointer to the actual data buffer by skipping
1862 // over the cookie completely.
John McCall7f416cc2015-09-08 08:05:57 +00001863 return CGF.Builder.CreateConstInBoundsByteGEP(NewPtr, CookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001864}
1865
John McCallb91cd662012-05-01 05:23:51 +00001866llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001867 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00001868 CharUnits cookieSize) {
1869 // The element size is right-justified in the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001870 Address numElementsPtr = allocPtr;
1871 CharUnits numElementsOffset = cookieSize - CGF.getSizeSize();
John McCallb91cd662012-05-01 05:23:51 +00001872 if (!numElementsOffset.isZero())
1873 numElementsPtr =
John McCall7f416cc2015-09-08 08:05:57 +00001874 CGF.Builder.CreateConstInBoundsByteGEP(numElementsPtr, numElementsOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001875
John McCall7f416cc2015-09-08 08:05:57 +00001876 unsigned AS = allocPtr.getAddressSpace();
1877 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001878 if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0)
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001879 return CGF.Builder.CreateLoad(numElementsPtr);
1880 // In asan mode emit a function call instead of a regular load and let the
1881 // run-time deal with it: if the shadow is properly poisoned return the
1882 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
1883 // We can't simply ignore this load using nosanitize metadata because
1884 // the metadata may be lost.
1885 llvm::FunctionType *FTy =
1886 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
1887 llvm::Constant *F =
1888 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001889 return CGF.Builder.CreateCall(F, numElementsPtr.getPointer());
John McCall8ed55a52010-09-02 09:58:18 +00001890}
1891
John McCallb91cd662012-05-01 05:23:51 +00001892CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001893 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001894 // struct array_cookie {
1895 // std::size_t element_size; // element_size != 0
1896 // std::size_t element_count;
1897 // };
John McCallc19c7062013-01-25 23:36:19 +00001898 // But the base ABI doesn't give anything an alignment greater than
1899 // 8, so we can dismiss this as typical ABI-author blindness to
1900 // actual language complexity and round up to the element alignment.
1901 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1902 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001903}
1904
John McCall7f416cc2015-09-08 08:05:57 +00001905Address ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1906 Address newPtr,
1907 llvm::Value *numElements,
1908 const CXXNewExpr *expr,
1909 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001910 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001911
John McCall8ed55a52010-09-02 09:58:18 +00001912 // The cookie is always at the start of the buffer.
John McCall7f416cc2015-09-08 08:05:57 +00001913 Address cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001914
1915 // The first element is the element size.
John McCall7f416cc2015-09-08 08:05:57 +00001916 cookie = CGF.Builder.CreateElementBitCast(cookie, CGF.SizeTy);
John McCallc19c7062013-01-25 23:36:19 +00001917 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1918 getContext().getTypeSizeInChars(elementType).getQuantity());
1919 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001920
1921 // The second element is the element count.
John McCall7f416cc2015-09-08 08:05:57 +00001922 cookie = CGF.Builder.CreateConstInBoundsGEP(cookie, 1, CGF.getSizeSize());
John McCallc19c7062013-01-25 23:36:19 +00001923 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001924
1925 // Finally, compute a pointer to the actual data buffer by skipping
1926 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001927 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
John McCall7f416cc2015-09-08 08:05:57 +00001928 return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001929}
1930
John McCallb91cd662012-05-01 05:23:51 +00001931llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001932 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00001933 CharUnits cookieSize) {
1934 // The number of elements is at offset sizeof(size_t) relative to
1935 // the allocated pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001936 Address numElementsPtr
1937 = CGF.Builder.CreateConstInBoundsByteGEP(allocPtr, CGF.getSizeSize());
John McCall8ed55a52010-09-02 09:58:18 +00001938
John McCall7f416cc2015-09-08 08:05:57 +00001939 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
John McCallb91cd662012-05-01 05:23:51 +00001940 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001941}
1942
John McCall68ff0372010-09-08 01:44:27 +00001943/*********************** Static local initialization **************************/
1944
1945static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001946 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001947 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001948 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001949 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001950 GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00001951 return CGM.CreateRuntimeFunction(
1952 FTy, "__cxa_guard_acquire",
1953 llvm::AttributeList::get(CGM.getLLVMContext(),
1954 llvm::AttributeList::FunctionIndex,
1955 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001956}
1957
1958static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001959 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001960 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001961 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001962 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00001963 return CGM.CreateRuntimeFunction(
1964 FTy, "__cxa_guard_release",
1965 llvm::AttributeList::get(CGM.getLLVMContext(),
1966 llvm::AttributeList::FunctionIndex,
1967 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001968}
1969
1970static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001971 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001972 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001973 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001974 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00001975 return CGM.CreateRuntimeFunction(
1976 FTy, "__cxa_guard_abort",
1977 llvm::AttributeList::get(CGM.getLLVMContext(),
1978 llvm::AttributeList::FunctionIndex,
1979 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001980}
1981
1982namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001983 struct CallGuardAbort final : EHScopeStack::Cleanup {
John McCall68ff0372010-09-08 01:44:27 +00001984 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001985 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001986
Craig Topper4f12f102014-03-12 06:41:41 +00001987 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00001988 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1989 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001990 }
1991 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001992}
John McCall68ff0372010-09-08 01:44:27 +00001993
1994/// The ARM code here follows the Itanium code closely enough that we
1995/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001996void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1997 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001998 llvm::GlobalVariable *var,
1999 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00002000 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00002001
Richard Smith62f19e72016-06-25 00:15:56 +00002002 // Inline variables that weren't instantiated from variable templates have
2003 // partially-ordered initialization within their translation unit.
2004 bool NonTemplateInline =
2005 D.isInline() &&
2006 !isTemplateInstantiation(D.getTemplateSpecializationKind());
2007
2008 // We only need to use thread-safe statics for local non-TLS variables and
2009 // inline variables; other global initialization is always single-threaded
2010 // or (through lazy dynamic loading in multiple threads) unsequenced.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002011 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
Richard Smith62f19e72016-06-25 00:15:56 +00002012 (D.isLocalVarDecl() || NonTemplateInline) &&
2013 !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00002014
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00002015 // If we have a global variable with internal linkage and thread-safe statics
2016 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00002017 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
2018
2019 llvm::IntegerType *guardTy;
John McCall7f416cc2015-09-08 08:05:57 +00002020 CharUnits guardAlignment;
John McCall5aa52592011-06-17 07:33:57 +00002021 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00002022 guardTy = CGF.Int8Ty;
John McCall7f416cc2015-09-08 08:05:57 +00002023 guardAlignment = CharUnits::One();
John McCall5aa52592011-06-17 07:33:57 +00002024 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00002025 // Guard variables are 64 bits in the generic ABI and size width on ARM
2026 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
John McCall7f416cc2015-09-08 08:05:57 +00002027 if (UseARMGuardVarABI) {
2028 guardTy = CGF.SizeTy;
2029 guardAlignment = CGF.getSizeAlign();
2030 } else {
2031 guardTy = CGF.Int64Ty;
2032 guardAlignment = CharUnits::fromQuantity(
2033 CGM.getDataLayout().getABITypeAlignment(guardTy));
2034 }
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00002035 }
John McCallb88a5662012-03-30 21:00:39 +00002036 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00002037
John McCallb88a5662012-03-30 21:00:39 +00002038 // Create the guard variable if we don't already have it (as we
2039 // might if we're double-emitting this function body).
2040 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
2041 if (!guard) {
2042 // Mangle the name for the guard.
2043 SmallString<256> guardName;
2044 {
2045 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00002046 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00002047 }
John McCall8e7cb6d2010-11-02 21:04:24 +00002048
John McCallb88a5662012-03-30 21:00:39 +00002049 // Create the guard variable with a zero-initializer.
2050 // Just absorb linkage and visibility from the guarded variable.
2051 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
2052 false, var->getLinkage(),
2053 llvm::ConstantInt::get(guardTy, 0),
2054 guardName.str());
Rafael Espindola699f5d62018-02-07 22:15:33 +00002055 guard->setDSOLocal(var->isDSOLocal());
John McCallb88a5662012-03-30 21:00:39 +00002056 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00002057 // If the variable is thread-local, so is its guard variable.
2058 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCall7f416cc2015-09-08 08:05:57 +00002059 guard->setAlignment(guardAlignment.getQuantity());
John McCallb88a5662012-03-30 21:00:39 +00002060
Yaron Keren5bfa1082015-09-03 20:33:29 +00002061 // The ABI says: "It is suggested that it be emitted in the same COMDAT
2062 // group as the associated data object." In practice, this doesn't work for
Dan Gohman839f2152017-01-17 21:46:38 +00002063 // non-ELF and non-Wasm object formats, so only do it for ELF and Wasm.
Rafael Espindola0d4fb982015-01-12 22:13:53 +00002064 llvm::Comdat *C = var->getComdat();
Yaron Keren5bfa1082015-09-03 20:33:29 +00002065 if (!D.isLocalVarDecl() && C &&
Dan Gohman839f2152017-01-17 21:46:38 +00002066 (CGM.getTarget().getTriple().isOSBinFormatELF() ||
2067 CGM.getTarget().getTriple().isOSBinFormatWasm())) {
Rafael Espindola2ae4b632014-09-19 19:43:18 +00002068 guard->setComdat(C);
Richard Smith62f19e72016-06-25 00:15:56 +00002069 // An inline variable's guard function is run from the per-TU
2070 // initialization function, not via a dedicated global ctor function, so
2071 // we can't put it in a comdat.
2072 if (!NonTemplateInline)
2073 CGF.CurFn->setComdat(C);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00002074 } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) {
2075 guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName()));
Rafael Espindola2ae4b632014-09-19 19:43:18 +00002076 }
2077
John McCallb88a5662012-03-30 21:00:39 +00002078 CGM.setStaticLocalDeclGuardAddress(&D, guard);
2079 }
John McCall87590e62012-03-30 07:09:50 +00002080
John McCall7f416cc2015-09-08 08:05:57 +00002081 Address guardAddr = Address(guard, guardAlignment);
2082
John McCall68ff0372010-09-08 01:44:27 +00002083 // Test whether the variable has completed initialization.
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002084 //
John McCall68ff0372010-09-08 01:44:27 +00002085 // Itanium C++ ABI 3.3.2:
2086 // The following is pseudo-code showing how these functions can be used:
2087 // if (obj_guard.first_byte == 0) {
2088 // if ( __cxa_guard_acquire (&obj_guard) ) {
2089 // try {
2090 // ... initialize the object ...;
2091 // } catch (...) {
2092 // __cxa_guard_abort (&obj_guard);
2093 // throw;
2094 // }
2095 // ... queue object destructor with __cxa_atexit() ...;
2096 // __cxa_guard_release (&obj_guard);
2097 // }
2098 // }
Tim Northovera2ee4332014-03-29 15:09:45 +00002099
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002100 // Load the first byte of the guard variable.
2101 llvm::LoadInst *LI =
John McCall7f416cc2015-09-08 08:05:57 +00002102 Builder.CreateLoad(Builder.CreateElementBitCast(guardAddr, CGM.Int8Ty));
John McCall68ff0372010-09-08 01:44:27 +00002103
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002104 // Itanium ABI:
2105 // An implementation supporting thread-safety on multiprocessor
2106 // systems must also guarantee that references to the initialized
2107 // object do not occur before the load of the initialization flag.
2108 //
2109 // In LLVM, we do this by marking the load Acquire.
2110 if (threadsafe)
JF Bastien92f4ef12016-04-06 17:26:42 +00002111 LI->setAtomic(llvm::AtomicOrdering::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00002112
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002113 // For ARM, we should only check the first bit, rather than the entire byte:
2114 //
2115 // ARM C++ ABI 3.2.3.1:
2116 // To support the potential use of initialization guard variables
2117 // as semaphores that are the target of ARM SWP and LDREX/STREX
2118 // synchronizing instructions we define a static initialization
2119 // guard variable to be a 4-byte aligned, 4-byte word with the
2120 // following inline access protocol.
2121 // #define INITIALIZED 1
2122 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
2123 // if (__cxa_guard_acquire(&obj_guard))
2124 // ...
2125 // }
2126 //
2127 // and similarly for ARM64:
2128 //
2129 // ARM64 C++ ABI 3.2.2:
2130 // This ABI instead only specifies the value bit 0 of the static guard
2131 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
2132 // variable is not initialized and 1 when it is.
2133 llvm::Value *V =
2134 (UseARMGuardVarABI && !useInt8GuardVariable)
2135 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
2136 : LI;
Richard Smithae8d62c2017-07-26 22:01:09 +00002137 llvm::Value *NeedsInit = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00002138
2139 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
2140 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2141
2142 // Check if the first byte of the guard variable is zero.
Richard Smithae8d62c2017-07-26 22:01:09 +00002143 CGF.EmitCXXGuardedInitBranch(NeedsInit, InitCheckBlock, EndBlock,
2144 CodeGenFunction::GuardKind::VariableGuard, &D);
John McCall68ff0372010-09-08 01:44:27 +00002145
2146 CGF.EmitBlock(InitCheckBlock);
2147
2148 // Variables used when coping with thread-safe statics and exceptions.
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002149 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002150 // Call __cxa_guard_acquire.
2151 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00002152 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002153
John McCall68ff0372010-09-08 01:44:27 +00002154 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002155
John McCall68ff0372010-09-08 01:44:27 +00002156 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
2157 InitBlock, EndBlock);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002158
John McCall68ff0372010-09-08 01:44:27 +00002159 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00002160 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002161
John McCall68ff0372010-09-08 01:44:27 +00002162 CGF.EmitBlock(InitBlock);
2163 }
2164
2165 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00002166 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00002167
John McCall5aa52592011-06-17 07:33:57 +00002168 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002169 // Pop the guard-abort cleanup if we pushed one.
2170 CGF.PopCleanupBlock();
2171
2172 // Call __cxa_guard_release. This cannot throw.
John McCall7f416cc2015-09-08 08:05:57 +00002173 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy),
2174 guardAddr.getPointer());
John McCall68ff0372010-09-08 01:44:27 +00002175 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002176 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guardAddr);
John McCall68ff0372010-09-08 01:44:27 +00002177 }
2178
2179 CGF.EmitBlock(EndBlock);
2180}
John McCallc84ed6a2012-05-01 06:13:13 +00002181
2182/// Register a global destructor using __cxa_atexit.
2183static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
2184 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00002185 llvm::Constant *addr,
2186 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00002187 const char *Name = "__cxa_atexit";
2188 if (TLS) {
2189 const llvm::Triple &T = CGF.getTarget().getTriple();
Manman Renf93fff22015-11-11 23:08:18 +00002190 Name = T.isOSDarwin() ? "_tlv_atexit" : "__cxa_thread_atexit";
Bill Wendling95cae882013-05-02 19:18:03 +00002191 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00002192
John McCallc84ed6a2012-05-01 06:13:13 +00002193 // We're assuming that the destructor function is something we can
2194 // reasonably call with the default CC. Go ahead and cast it to the
2195 // right prototype.
2196 llvm::Type *dtorTy =
2197 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
2198
2199 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
2200 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
2201 llvm::FunctionType *atexitTy =
2202 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
2203
2204 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002205 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00002206 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
2207 fn->setDoesNotThrow();
2208
2209 // Create a variable that binds the atexit to this shared object.
2210 llvm::Constant *handle =
Reid Kleckner9de92142017-02-13 18:49:21 +00002211 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
2212 auto *GV = cast<llvm::GlobalValue>(handle->stripPointerCasts());
2213 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
John McCallc84ed6a2012-05-01 06:13:13 +00002214
2215 llvm::Value *args[] = {
2216 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
2217 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
2218 handle
2219 };
John McCall882987f2013-02-28 19:01:20 +00002220 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00002221}
2222
2223/// Register a global destructor as best as we know how.
2224void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00002225 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00002226 llvm::Constant *dtor,
2227 llvm::Constant *addr) {
2228 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002229 if (CGM.getCodeGenOpts().CXAAtExit)
2230 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
2231
2232 if (D.getTLSKind())
2233 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00002234
2235 // In Apple kexts, we want to add a global destructor entry.
2236 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00002237 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00002238 // Generate a global destructor entry.
2239 return CGM.AddCXXDtorEntry(dtor, addr);
2240 }
2241
David Blaikieebe87e12013-08-27 23:57:18 +00002242 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00002243}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002244
David Majnemer9b21c332014-07-11 20:28:10 +00002245static bool isThreadWrapperReplaceable(const VarDecl *VD,
2246 CodeGen::CodeGenModule &CGM) {
2247 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
Manman Renf93fff22015-11-11 23:08:18 +00002248 // Darwin prefers to have references to thread local variables to go through
David Majnemer9b21c332014-07-11 20:28:10 +00002249 // the thread wrapper instead of directly referencing the backing variable.
2250 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
Manman Renf93fff22015-11-11 23:08:18 +00002251 CGM.getTarget().getTriple().isOSDarwin();
David Majnemer9b21c332014-07-11 20:28:10 +00002252}
2253
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002254/// Get the appropriate linkage for the wrapper function. This is essentially
David Majnemer4632e1e2014-06-27 16:56:27 +00002255/// the weak form of the variable's linkage; every translation unit which needs
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002256/// the wrapper emits a copy, and we want the linker to merge them.
David Majnemer35ab3282014-06-11 04:08:55 +00002257static llvm::GlobalValue::LinkageTypes
2258getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
2259 llvm::GlobalValue::LinkageTypes VarLinkage =
2260 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
2261
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002262 // For internal linkage variables, we don't need an external or weak wrapper.
2263 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
2264 return VarLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00002265
David Majnemer9b21c332014-07-11 20:28:10 +00002266 // If the thread wrapper is replaceable, give it appropriate linkage.
Manman Ren68150262015-11-11 22:42:31 +00002267 if (isThreadWrapperReplaceable(VD, CGM))
2268 if (!llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) &&
2269 !llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
2270 return VarLinkage;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002271 return llvm::GlobalValue::WeakODRLinkage;
2272}
2273
2274llvm::Function *
2275ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +00002276 llvm::Value *Val) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002277 // Mangle the name for the thread_local wrapper function.
2278 SmallString<256> WrapperName;
2279 {
2280 llvm::raw_svector_ostream Out(WrapperName);
2281 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002282 }
2283
Akira Hatanaka26907f92016-01-15 03:34:06 +00002284 // FIXME: If VD is a definition, we should regenerate the function attributes
2285 // before returning.
Alexander Musmanf94c3182014-09-26 06:28:25 +00002286 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002287 return cast<llvm::Function>(V);
2288
Akira Hatanaka26907f92016-01-15 03:34:06 +00002289 QualType RetQT = VD->getType();
2290 if (RetQT->isReferenceType())
2291 RetQT = RetQT.getNonReferenceType();
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002292
John McCallc56a8b32016-03-11 04:30:31 +00002293 const CGFunctionInfo &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2294 getContext().getPointerType(RetQT), FunctionArgList());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002295
2296 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FI);
David Majnemer35ab3282014-06-11 04:08:55 +00002297 llvm::Function *Wrapper =
2298 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
2299 WrapperName.str(), &CGM.getModule());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002300
2301 CGM.SetLLVMFunctionAttributes(nullptr, FI, Wrapper);
2302
2303 if (VD->hasDefinition())
2304 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Wrapper);
2305
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002306 // Always resolve references to the wrapper at link time.
Manman Ren68150262015-11-11 22:42:31 +00002307 if (!Wrapper->hasLocalLinkage() && !(isThreadWrapperReplaceable(VD, CGM) &&
2308 !llvm::GlobalVariable::isLinkOnceLinkage(Wrapper->getLinkage()) &&
2309 !llvm::GlobalVariable::isWeakODRLinkage(Wrapper->getLinkage())))
Duncan P. N. Exon Smith4434d362014-05-07 22:36:11 +00002310 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
Manman Renb0b3af72015-12-17 00:42:36 +00002311
2312 if (isThreadWrapperReplaceable(VD, CGM)) {
2313 Wrapper->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2314 Wrapper->addFnAttr(llvm::Attribute::NoUnwind);
2315 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002316 return Wrapper;
2317}
2318
2319void ItaniumCXXABI::EmitThreadLocalInitFuncs(
Richard Smith5a99c492015-12-01 01:10:48 +00002320 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
2321 ArrayRef<llvm::Function *> CXXThreadLocalInits,
2322 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
David Majnemerb3341ea2014-10-05 05:05:40 +00002323 llvm::Function *InitFunc = nullptr;
Richard Smithfbe23692017-01-13 00:43:31 +00002324
2325 // Separate initializers into those with ordered (or partially-ordered)
2326 // initialization and those with unordered initialization.
2327 llvm::SmallVector<llvm::Function *, 8> OrderedInits;
2328 llvm::SmallDenseMap<const VarDecl *, llvm::Function *> UnorderedInits;
2329 for (unsigned I = 0; I != CXXThreadLocalInits.size(); ++I) {
2330 if (isTemplateInstantiation(
2331 CXXThreadLocalInitVars[I]->getTemplateSpecializationKind()))
2332 UnorderedInits[CXXThreadLocalInitVars[I]->getCanonicalDecl()] =
2333 CXXThreadLocalInits[I];
2334 else
2335 OrderedInits.push_back(CXXThreadLocalInits[I]);
2336 }
2337
2338 if (!OrderedInits.empty()) {
David Majnemerb3341ea2014-10-05 05:05:40 +00002339 // Generate a guarded initialization function.
2340 llvm::FunctionType *FTy =
2341 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002342 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2343 InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init", FI,
Alexey Samsonov1444bb92014-10-17 00:20:19 +00002344 SourceLocation(),
David Majnemerb3341ea2014-10-05 05:05:40 +00002345 /*TLS=*/true);
2346 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
2347 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
2348 llvm::GlobalVariable::InternalLinkage,
2349 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
2350 Guard->setThreadLocal(true);
John McCall7f416cc2015-09-08 08:05:57 +00002351
2352 CharUnits GuardAlign = CharUnits::One();
2353 Guard->setAlignment(GuardAlign.getQuantity());
2354
Richard Smithfbe23692017-01-13 00:43:31 +00002355 CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(InitFunc, OrderedInits,
2356 Address(Guard, GuardAlign));
Manman Ren5e5d0462016-03-18 23:35:21 +00002357 // On Darwin platforms, use CXX_FAST_TLS calling convention.
2358 if (CGM.getTarget().getTriple().isOSDarwin()) {
2359 InitFunc->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2360 InitFunc->addFnAttr(llvm::Attribute::NoUnwind);
2361 }
David Majnemerb3341ea2014-10-05 05:05:40 +00002362 }
Richard Smithfbe23692017-01-13 00:43:31 +00002363
2364 // Emit thread wrappers.
Richard Smith5a99c492015-12-01 01:10:48 +00002365 for (const VarDecl *VD : CXXThreadLocals) {
2366 llvm::GlobalVariable *Var =
2367 cast<llvm::GlobalVariable>(CGM.GetGlobalValue(CGM.getMangledName(VD)));
Richard Smithfbe23692017-01-13 00:43:31 +00002368 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002369
David Majnemer9b21c332014-07-11 20:28:10 +00002370 // Some targets require that all access to thread local variables go through
2371 // the thread wrapper. This means that we cannot attempt to create a thread
2372 // wrapper or a thread helper.
Richard Smithfbe23692017-01-13 00:43:31 +00002373 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition()) {
2374 Wrapper->setLinkage(llvm::Function::ExternalLinkage);
David Majnemer9b21c332014-07-11 20:28:10 +00002375 continue;
Richard Smithfbe23692017-01-13 00:43:31 +00002376 }
David Majnemer9b21c332014-07-11 20:28:10 +00002377
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002378 // Mangle the name for the thread_local initialization function.
2379 SmallString<256> InitFnName;
2380 {
2381 llvm::raw_svector_ostream Out(InitFnName);
2382 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002383 }
2384
2385 // If we have a definition for the variable, emit the initialization
2386 // function as an alias to the global Init function (if any). Otherwise,
2387 // produce a declaration of the initialization function.
Craig Topper8a13c412014-05-21 05:09:00 +00002388 llvm::GlobalValue *Init = nullptr;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002389 bool InitIsInitFunc = false;
2390 if (VD->hasDefinition()) {
2391 InitIsInitFunc = true;
Richard Smithfbe23692017-01-13 00:43:31 +00002392 llvm::Function *InitFuncToUse = InitFunc;
2393 if (isTemplateInstantiation(VD->getTemplateSpecializationKind()))
2394 InitFuncToUse = UnorderedInits.lookup(VD->getCanonicalDecl());
2395 if (InitFuncToUse)
Rafael Espindola234405b2014-05-17 21:30:14 +00002396 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
Richard Smithfbe23692017-01-13 00:43:31 +00002397 InitFuncToUse);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002398 } else {
2399 // Emit a weak global function referring to the initialization function.
2400 // This function will not exist if the TU defining the thread_local
2401 // variable in question does not need any dynamic initialization for
2402 // its thread_local variables.
2403 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
Richard Smithfbe23692017-01-13 00:43:31 +00002404 Init = llvm::Function::Create(FnTy,
2405 llvm::GlobalVariable::ExternalWeakLinkage,
2406 InitFnName.str(), &CGM.getModule());
John McCallc56a8b32016-03-11 04:30:31 +00002407 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
Akira Hatanaka26907f92016-01-15 03:34:06 +00002408 CGM.SetLLVMFunctionAttributes(nullptr, FI, cast<llvm::Function>(Init));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002409 }
2410
2411 if (Init)
2412 Init->setVisibility(Var->getVisibility());
2413
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002414 llvm::LLVMContext &Context = CGM.getModule().getContext();
2415 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
John McCall7f416cc2015-09-08 08:05:57 +00002416 CGBuilderTy Builder(CGM, Entry);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002417 if (InitIsInitFunc) {
Manman Ren5e5d0462016-03-18 23:35:21 +00002418 if (Init) {
2419 llvm::CallInst *CallVal = Builder.CreateCall(Init);
2420 if (isThreadWrapperReplaceable(VD, CGM))
2421 CallVal->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2422 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002423 } else {
2424 // Don't know whether we have an init function. Call it if it exists.
2425 llvm::Value *Have = Builder.CreateIsNotNull(Init);
2426 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2427 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2428 Builder.CreateCondBr(Have, InitBB, ExitBB);
2429
2430 Builder.SetInsertPoint(InitBB);
David Blaikie4ba525b2015-07-14 17:27:39 +00002431 Builder.CreateCall(Init);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002432 Builder.CreateBr(ExitBB);
2433
2434 Builder.SetInsertPoint(ExitBB);
2435 }
2436
2437 // For a reference, the result of the wrapper function is a pointer to
2438 // the referenced object.
2439 llvm::Value *Val = Var;
2440 if (VD->getType()->isReferenceType()) {
John McCall7f416cc2015-09-08 08:05:57 +00002441 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2442 Val = Builder.CreateAlignedLoad(Val, Align);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002443 }
Alexander Musmanf94c3182014-09-26 06:28:25 +00002444 if (Val->getType() != Wrapper->getReturnType())
2445 Val = Builder.CreatePointerBitCastOrAddrSpaceCast(
2446 Val, Wrapper->getReturnType(), "");
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002447 Builder.CreateRet(Val);
2448 }
2449}
2450
Richard Smith0f383742014-03-26 22:48:22 +00002451LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2452 const VarDecl *VD,
2453 QualType LValType) {
Richard Smith5a99c492015-12-01 01:10:48 +00002454 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD);
Alexander Musmanf94c3182014-09-26 06:28:25 +00002455 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002456
Manman Renb0b3af72015-12-17 00:42:36 +00002457 llvm::CallInst *CallVal = CGF.Builder.CreateCall(Wrapper);
Saleem Abdulrasool4a7130a2016-08-01 21:31:24 +00002458 CallVal->setCallingConv(Wrapper->getCallingConv());
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002459
2460 LValue LV;
2461 if (VD->getType()->isReferenceType())
Manman Renb0b3af72015-12-17 00:42:36 +00002462 LV = CGF.MakeNaturalAlignAddrLValue(CallVal, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002463 else
Manman Renb0b3af72015-12-17 00:42:36 +00002464 LV = CGF.MakeAddrLValue(CallVal, LValType,
2465 CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002466 // FIXME: need setObjCGCLValueClass?
2467 return LV;
2468}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002469
2470/// Return whether the given global decl needs a VTT parameter, which it does
2471/// if it's a base constructor or destructor with virtual bases.
2472bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
2473 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002474
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002475 // We don't have any virtual bases, just return early.
2476 if (!MD->getParent()->getNumVBases())
2477 return false;
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002478
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002479 // Check if we have a base constructor.
2480 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
2481 return true;
2482
2483 // Check if we have a base destructor.
2484 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2485 return true;
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002486
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002487 return false;
2488}
David Majnemere2cb8d12014-07-07 06:20:47 +00002489
2490namespace {
2491class ItaniumRTTIBuilder {
2492 CodeGenModule &CGM; // Per-module state.
2493 llvm::LLVMContext &VMContext;
2494 const ItaniumCXXABI &CXXABI; // Per-module state.
2495
2496 /// Fields - The fields of the RTTI descriptor currently being built.
2497 SmallVector<llvm::Constant *, 16> Fields;
2498
2499 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2500 llvm::GlobalVariable *
2501 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2502
2503 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2504 /// descriptor of the given type.
2505 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2506
2507 /// BuildVTablePointer - Build the vtable pointer for the given type.
2508 void BuildVTablePointer(const Type *Ty);
2509
2510 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2511 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2512 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2513
2514 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2515 /// classes with bases that do not satisfy the abi::__si_class_type_info
2516 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2517 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2518
2519 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2520 /// for pointer types.
2521 void BuildPointerTypeInfo(QualType PointeeTy);
2522
2523 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2524 /// type_info for an object type.
2525 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2526
2527 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2528 /// struct, used for member pointer types.
2529 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2530
2531public:
2532 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2533 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2534
2535 // Pointer type info flags.
2536 enum {
2537 /// PTI_Const - Type has const qualifier.
2538 PTI_Const = 0x1,
2539
2540 /// PTI_Volatile - Type has volatile qualifier.
2541 PTI_Volatile = 0x2,
2542
2543 /// PTI_Restrict - Type has restrict qualifier.
2544 PTI_Restrict = 0x4,
2545
2546 /// PTI_Incomplete - Type is incomplete.
2547 PTI_Incomplete = 0x8,
2548
2549 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2550 /// (in pointer to member).
Richard Smitha7d93782016-12-01 03:32:42 +00002551 PTI_ContainingClassIncomplete = 0x10,
2552
2553 /// PTI_TransactionSafe - Pointee is transaction_safe function (C++ TM TS).
2554 //PTI_TransactionSafe = 0x20,
2555
2556 /// PTI_Noexcept - Pointee is noexcept function (C++1z).
2557 PTI_Noexcept = 0x40,
David Majnemere2cb8d12014-07-07 06:20:47 +00002558 };
2559
2560 // VMI type info flags.
2561 enum {
2562 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2563 VMI_NonDiamondRepeat = 0x1,
2564
2565 /// VMI_DiamondShaped - Class is diamond shaped.
2566 VMI_DiamondShaped = 0x2
2567 };
2568
2569 // Base class type info flags.
2570 enum {
2571 /// BCTI_Virtual - Base class is virtual.
2572 BCTI_Virtual = 0x1,
2573
2574 /// BCTI_Public - Base class is public.
2575 BCTI_Public = 0x2
2576 };
2577
2578 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
2579 ///
2580 /// \param Force - true to force the creation of this RTTI value
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00002581 /// \param DLLExport - true to mark the RTTI value as DLLExport
2582 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false,
2583 bool DLLExport = false);
David Majnemere2cb8d12014-07-07 06:20:47 +00002584};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002585}
David Majnemere2cb8d12014-07-07 06:20:47 +00002586
2587llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2588 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002589 SmallString<256> Name;
2590 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002591 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002592
2593 // We know that the mangled name of the type starts at index 4 of the
2594 // mangled name of the typename, so we can just index into it in order to
2595 // get the mangled name of the type.
2596 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2597 Name.substr(4));
2598
2599 llvm::GlobalVariable *GV =
2600 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
2601
2602 GV->setInitializer(Init);
2603
2604 return GV;
2605}
2606
2607llvm::Constant *
2608ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2609 // Mangle the RTTI name.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002610 SmallString<256> Name;
2611 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002612 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002613
2614 // Look for an existing global.
2615 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2616
2617 if (!GV) {
2618 // Create a new global variable.
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00002619 // Note for the future: If we would ever like to do deferred emission of
2620 // RTTI, check if emitting vtables opportunistically need any adjustment.
2621
David Majnemere2cb8d12014-07-07 06:20:47 +00002622 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2623 /*Constant=*/true,
2624 llvm::GlobalValue::ExternalLinkage, nullptr,
2625 Name);
David Majnemer1fb1a042014-11-07 07:26:38 +00002626 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2627 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2628 if (RD->hasAttr<DLLImportAttr>())
2629 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2630 }
David Majnemere2cb8d12014-07-07 06:20:47 +00002631 }
2632
2633 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2634}
2635
2636/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2637/// info for that type is defined in the standard library.
2638static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2639 // Itanium C++ ABI 2.9.2:
2640 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
2641 // the run-time support library. Specifically, the run-time support
2642 // library should contain type_info objects for the types X, X* and
2643 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2644 // unsigned char, signed char, short, unsigned short, int, unsigned int,
2645 // long, unsigned long, long long, unsigned long long, float, double,
2646 // long double, char16_t, char32_t, and the IEEE 754r decimal and
2647 // half-precision floating point types.
Richard Smith4a382012016-02-03 01:32:42 +00002648 //
2649 // GCC also emits RTTI for __int128.
2650 // FIXME: We do not emit RTTI information for decimal types here.
2651
2652 // Types added here must also be added to EmitFundamentalRTTIDescriptors.
David Majnemere2cb8d12014-07-07 06:20:47 +00002653 switch (Ty->getKind()) {
2654 case BuiltinType::Void:
2655 case BuiltinType::NullPtr:
2656 case BuiltinType::Bool:
2657 case BuiltinType::WChar_S:
2658 case BuiltinType::WChar_U:
2659 case BuiltinType::Char_U:
2660 case BuiltinType::Char_S:
2661 case BuiltinType::UChar:
2662 case BuiltinType::SChar:
2663 case BuiltinType::Short:
2664 case BuiltinType::UShort:
2665 case BuiltinType::Int:
2666 case BuiltinType::UInt:
2667 case BuiltinType::Long:
2668 case BuiltinType::ULong:
2669 case BuiltinType::LongLong:
2670 case BuiltinType::ULongLong:
2671 case BuiltinType::Half:
2672 case BuiltinType::Float:
2673 case BuiltinType::Double:
2674 case BuiltinType::LongDouble:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00002675 case BuiltinType::Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002676 case BuiltinType::Float128:
David Majnemere2cb8d12014-07-07 06:20:47 +00002677 case BuiltinType::Char16:
2678 case BuiltinType::Char32:
2679 case BuiltinType::Int128:
2680 case BuiltinType::UInt128:
Richard Smith4a382012016-02-03 01:32:42 +00002681 return true;
2682
Alexey Bader954ba212016-04-08 13:40:33 +00002683#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2684 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00002685#include "clang/Basic/OpenCLImageTypes.def"
David Majnemere2cb8d12014-07-07 06:20:47 +00002686 case BuiltinType::OCLSampler:
2687 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002688 case BuiltinType::OCLClkEvent:
2689 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002690 case BuiltinType::OCLReserveID:
Richard Smith4a382012016-02-03 01:32:42 +00002691 return false;
David Majnemere2cb8d12014-07-07 06:20:47 +00002692
2693 case BuiltinType::Dependent:
2694#define BUILTIN_TYPE(Id, SingletonId)
2695#define PLACEHOLDER_TYPE(Id, SingletonId) \
2696 case BuiltinType::Id:
2697#include "clang/AST/BuiltinTypes.def"
2698 llvm_unreachable("asking for RRTI for a placeholder type!");
2699
2700 case BuiltinType::ObjCId:
2701 case BuiltinType::ObjCClass:
2702 case BuiltinType::ObjCSel:
2703 llvm_unreachable("FIXME: Objective-C types are unsupported!");
2704 }
2705
2706 llvm_unreachable("Invalid BuiltinType Kind!");
2707}
2708
2709static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2710 QualType PointeeTy = PointerTy->getPointeeType();
2711 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2712 if (!BuiltinTy)
2713 return false;
2714
2715 // Check the qualifiers.
2716 Qualifiers Quals = PointeeTy.getQualifiers();
2717 Quals.removeConst();
2718
2719 if (!Quals.empty())
2720 return false;
2721
2722 return TypeInfoIsInStandardLibrary(BuiltinTy);
2723}
2724
2725/// IsStandardLibraryRTTIDescriptor - Returns whether the type
2726/// information for the given type exists in the standard library.
2727static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2728 // Type info for builtin types is defined in the standard library.
2729 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2730 return TypeInfoIsInStandardLibrary(BuiltinTy);
2731
2732 // Type info for some pointer types to builtin types is defined in the
2733 // standard library.
2734 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2735 return TypeInfoIsInStandardLibrary(PointerTy);
2736
2737 return false;
2738}
2739
2740/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
2741/// the given type exists somewhere else, and that we should not emit the type
2742/// information in this translation unit. Assumes that it is not a
2743/// standard-library type.
2744static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
2745 QualType Ty) {
2746 ASTContext &Context = CGM.getContext();
2747
2748 // If RTTI is disabled, assume it might be disabled in the
2749 // translation unit that defines any potential key function, too.
2750 if (!Context.getLangOpts().RTTI) return false;
2751
2752 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2753 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2754 if (!RD->hasDefinition())
2755 return false;
2756
2757 if (!RD->isDynamicClass())
2758 return false;
2759
2760 // FIXME: this may need to be reconsidered if the key function
2761 // changes.
David Majnemerbe9022c2015-08-06 20:56:55 +00002762 // N.B. We must always emit the RTTI data ourselves if there exists a key
2763 // function.
2764 bool IsDLLImport = RD->hasAttr<DLLImportAttr>();
Martin Storsjo3b528942018-02-02 06:22:35 +00002765
2766 // Don't import the RTTI but emit it locally.
2767 if (CGM.getTriple().isWindowsGNUEnvironment() && IsDLLImport)
2768 return false;
2769
David Majnemer1fb1a042014-11-07 07:26:38 +00002770 if (CGM.getVTables().isVTableExternal(RD))
Shoaib Meenai61118e72017-07-04 01:02:19 +00002771 return IsDLLImport && !CGM.getTriple().isWindowsItaniumEnvironment()
2772 ? false
2773 : true;
David Majnemer1fb1a042014-11-07 07:26:38 +00002774
David Majnemerbe9022c2015-08-06 20:56:55 +00002775 if (IsDLLImport)
David Majnemer1fb1a042014-11-07 07:26:38 +00002776 return true;
David Majnemere2cb8d12014-07-07 06:20:47 +00002777 }
2778
2779 return false;
2780}
2781
2782/// IsIncompleteClassType - Returns whether the given record type is incomplete.
2783static bool IsIncompleteClassType(const RecordType *RecordTy) {
2784 return !RecordTy->getDecl()->isCompleteDefinition();
2785}
2786
2787/// ContainsIncompleteClassType - Returns whether the given type contains an
2788/// incomplete class type. This is true if
2789///
2790/// * The given type is an incomplete class type.
2791/// * The given type is a pointer type whose pointee type contains an
2792/// incomplete class type.
2793/// * The given type is a member pointer type whose class is an incomplete
2794/// class type.
2795/// * The given type is a member pointer type whoise pointee type contains an
2796/// incomplete class type.
2797/// is an indirect or direct pointer to an incomplete class type.
2798static bool ContainsIncompleteClassType(QualType Ty) {
2799 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2800 if (IsIncompleteClassType(RecordTy))
2801 return true;
2802 }
2803
2804 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2805 return ContainsIncompleteClassType(PointerTy->getPointeeType());
2806
2807 if (const MemberPointerType *MemberPointerTy =
2808 dyn_cast<MemberPointerType>(Ty)) {
2809 // Check if the class type is incomplete.
2810 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
2811 if (IsIncompleteClassType(ClassType))
2812 return true;
2813
2814 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
2815 }
2816
2817 return false;
2818}
2819
2820// CanUseSingleInheritance - Return whether the given record decl has a "single,
2821// public, non-virtual base at offset zero (i.e. the derived class is dynamic
2822// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
2823static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
2824 // Check the number of bases.
2825 if (RD->getNumBases() != 1)
2826 return false;
2827
2828 // Get the base.
2829 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
2830
2831 // Check that the base is not virtual.
2832 if (Base->isVirtual())
2833 return false;
2834
2835 // Check that the base is public.
2836 if (Base->getAccessSpecifier() != AS_public)
2837 return false;
2838
2839 // Check that the class is dynamic iff the base is.
2840 const CXXRecordDecl *BaseDecl =
2841 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2842 if (!BaseDecl->isEmpty() &&
2843 BaseDecl->isDynamicClass() != RD->isDynamicClass())
2844 return false;
2845
2846 return true;
2847}
2848
2849void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
2850 // abi::__class_type_info.
2851 static const char * const ClassTypeInfo =
2852 "_ZTVN10__cxxabiv117__class_type_infoE";
2853 // abi::__si_class_type_info.
2854 static const char * const SIClassTypeInfo =
2855 "_ZTVN10__cxxabiv120__si_class_type_infoE";
2856 // abi::__vmi_class_type_info.
2857 static const char * const VMIClassTypeInfo =
2858 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
2859
2860 const char *VTableName = nullptr;
2861
2862 switch (Ty->getTypeClass()) {
2863#define TYPE(Class, Base)
2864#define ABSTRACT_TYPE(Class, Base)
2865#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2866#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2867#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2868#include "clang/AST/TypeNodes.def"
2869 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2870
2871 case Type::LValueReference:
2872 case Type::RValueReference:
2873 llvm_unreachable("References shouldn't get here");
2874
2875 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00002876 case Type::DeducedTemplateSpecialization:
2877 llvm_unreachable("Undeduced type shouldn't get here");
David Majnemere2cb8d12014-07-07 06:20:47 +00002878
Xiuli Pan9c14e282016-01-09 12:53:17 +00002879 case Type::Pipe:
2880 llvm_unreachable("Pipe types shouldn't get here");
2881
David Majnemere2cb8d12014-07-07 06:20:47 +00002882 case Type::Builtin:
2883 // GCC treats vector and complex types as fundamental types.
2884 case Type::Vector:
2885 case Type::ExtVector:
2886 case Type::Complex:
2887 case Type::Atomic:
2888 // FIXME: GCC treats block pointers as fundamental types?!
2889 case Type::BlockPointer:
2890 // abi::__fundamental_type_info.
2891 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
2892 break;
2893
2894 case Type::ConstantArray:
2895 case Type::IncompleteArray:
2896 case Type::VariableArray:
2897 // abi::__array_type_info.
2898 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
2899 break;
2900
2901 case Type::FunctionNoProto:
2902 case Type::FunctionProto:
Richard Smithb17d6fa2016-12-01 03:04:07 +00002903 // abi::__function_type_info.
2904 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
David Majnemere2cb8d12014-07-07 06:20:47 +00002905 break;
2906
2907 case Type::Enum:
2908 // abi::__enum_type_info.
2909 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
2910 break;
2911
2912 case Type::Record: {
2913 const CXXRecordDecl *RD =
2914 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2915
2916 if (!RD->hasDefinition() || !RD->getNumBases()) {
2917 VTableName = ClassTypeInfo;
2918 } else if (CanUseSingleInheritance(RD)) {
2919 VTableName = SIClassTypeInfo;
2920 } else {
2921 VTableName = VMIClassTypeInfo;
2922 }
2923
2924 break;
2925 }
2926
2927 case Type::ObjCObject:
2928 // Ignore protocol qualifiers.
2929 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
2930
2931 // Handle id and Class.
2932 if (isa<BuiltinType>(Ty)) {
2933 VTableName = ClassTypeInfo;
2934 break;
2935 }
2936
2937 assert(isa<ObjCInterfaceType>(Ty));
2938 // Fall through.
2939
2940 case Type::ObjCInterface:
2941 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
2942 VTableName = SIClassTypeInfo;
2943 } else {
2944 VTableName = ClassTypeInfo;
2945 }
2946 break;
2947
2948 case Type::ObjCObjectPointer:
2949 case Type::Pointer:
2950 // abi::__pointer_type_info.
2951 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
2952 break;
2953
2954 case Type::MemberPointer:
2955 // abi::__pointer_to_member_type_info.
2956 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
2957 break;
2958 }
2959
2960 llvm::Constant *VTable =
2961 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
2962
2963 llvm::Type *PtrDiffTy =
2964 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
2965
2966 // The vtable address point is 2.
2967 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00002968 VTable =
2969 llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.Int8PtrTy, VTable, Two);
David Majnemere2cb8d12014-07-07 06:20:47 +00002970 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
2971
2972 Fields.push_back(VTable);
2973}
2974
2975/// \brief Return the linkage that the type info and type info name constants
2976/// should have for the given type.
2977static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
2978 QualType Ty) {
2979 // Itanium C++ ABI 2.9.5p7:
2980 // In addition, it and all of the intermediate abi::__pointer_type_info
2981 // structs in the chain down to the abi::__class_type_info for the
2982 // incomplete class type must be prevented from resolving to the
2983 // corresponding type_info structs for the complete class type, possibly
2984 // by making them local static objects. Finally, a dummy class RTTI is
2985 // generated for the incomplete type that will not resolve to the final
2986 // complete class RTTI (because the latter need not exist), possibly by
2987 // making it a local static object.
2988 if (ContainsIncompleteClassType(Ty))
2989 return llvm::GlobalValue::InternalLinkage;
2990
2991 switch (Ty->getLinkage()) {
2992 case NoLinkage:
2993 case InternalLinkage:
2994 case UniqueExternalLinkage:
2995 return llvm::GlobalValue::InternalLinkage;
2996
2997 case VisibleNoLinkage:
Richard Smith1283e982017-07-07 20:04:28 +00002998 case ModuleInternalLinkage:
2999 case ModuleLinkage:
David Majnemere2cb8d12014-07-07 06:20:47 +00003000 case ExternalLinkage:
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003001 // RTTI is not enabled, which means that this type info struct is going
3002 // to be used for exception handling. Give it linkonce_odr linkage.
3003 if (!CGM.getLangOpts().RTTI)
David Majnemere2cb8d12014-07-07 06:20:47 +00003004 return llvm::GlobalValue::LinkOnceODRLinkage;
David Majnemere2cb8d12014-07-07 06:20:47 +00003005
3006 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
3007 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
3008 if (RD->hasAttr<WeakAttr>())
3009 return llvm::GlobalValue::WeakODRLinkage;
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003010 if (CGM.getTriple().isWindowsItaniumEnvironment())
Shoaib Meenai61118e72017-07-04 01:02:19 +00003011 if (RD->hasAttr<DLLImportAttr>() &&
3012 ShouldUseExternalRTTIDescriptor(CGM, Ty))
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003013 return llvm::GlobalValue::ExternalLinkage;
Martin Storsjoc6c5af72017-09-01 06:41:55 +00003014 // MinGW always uses LinkOnceODRLinkage for type info.
3015 if (RD->isDynamicClass() &&
3016 !CGM.getContext()
3017 .getTargetInfo()
3018 .getTriple()
3019 .isWindowsGNUEnvironment())
3020 return CGM.getVTableLinkage(RD);
David Majnemere2cb8d12014-07-07 06:20:47 +00003021 }
3022
3023 return llvm::GlobalValue::LinkOnceODRLinkage;
3024 }
3025
3026 llvm_unreachable("Invalid linkage!");
3027}
3028
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003029llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force,
3030 bool DLLExport) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003031 // We want to operate on the canonical type.
Yaron Kerenebd14262016-03-16 12:14:43 +00003032 Ty = Ty.getCanonicalType();
David Majnemere2cb8d12014-07-07 06:20:47 +00003033
3034 // Check if we've already emitted an RTTI descriptor for this type.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00003035 SmallString<256> Name;
3036 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00003037 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00003038
3039 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
3040 if (OldGV && !OldGV->isDeclaration()) {
3041 assert(!OldGV->hasAvailableExternallyLinkage() &&
3042 "available_externally typeinfos not yet implemented");
3043
3044 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
3045 }
3046
3047 // Check if there is already an external RTTI descriptor for this type.
3048 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
3049 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
3050 return GetAddrOfExternalRTTIDescriptor(Ty);
3051
3052 // Emit the standard library with external linkage.
3053 llvm::GlobalVariable::LinkageTypes Linkage;
3054 if (IsStdLib)
3055 Linkage = llvm::GlobalValue::ExternalLinkage;
3056 else
3057 Linkage = getTypeInfoLinkage(CGM, Ty);
3058
3059 // Add the vtable pointer.
3060 BuildVTablePointer(cast<Type>(Ty));
3061
3062 // And the name.
3063 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
3064 llvm::Constant *TypeNameField;
3065
3066 // If we're supposed to demote the visibility, be sure to set a flag
3067 // to use a string comparison for type_info comparisons.
3068 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
3069 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
3070 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
3071 // The flag is the sign bit, which on ARM64 is defined to be clear
3072 // for global pointers. This is very ARM64-specific.
3073 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
3074 llvm::Constant *flag =
3075 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
3076 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
3077 TypeNameField =
3078 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
3079 } else {
3080 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
3081 }
3082 Fields.push_back(TypeNameField);
3083
3084 switch (Ty->getTypeClass()) {
3085#define TYPE(Class, Base)
3086#define ABSTRACT_TYPE(Class, Base)
3087#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3088#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3089#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3090#include "clang/AST/TypeNodes.def"
3091 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
3092
3093 // GCC treats vector types as fundamental types.
3094 case Type::Builtin:
3095 case Type::Vector:
3096 case Type::ExtVector:
3097 case Type::Complex:
3098 case Type::BlockPointer:
3099 // Itanium C++ ABI 2.9.5p4:
3100 // abi::__fundamental_type_info adds no data members to std::type_info.
3101 break;
3102
3103 case Type::LValueReference:
3104 case Type::RValueReference:
3105 llvm_unreachable("References shouldn't get here");
3106
3107 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00003108 case Type::DeducedTemplateSpecialization:
3109 llvm_unreachable("Undeduced type shouldn't get here");
David Majnemere2cb8d12014-07-07 06:20:47 +00003110
Xiuli Pan9c14e282016-01-09 12:53:17 +00003111 case Type::Pipe:
3112 llvm_unreachable("Pipe type shouldn't get here");
3113
David Majnemere2cb8d12014-07-07 06:20:47 +00003114 case Type::ConstantArray:
3115 case Type::IncompleteArray:
3116 case Type::VariableArray:
3117 // Itanium C++ ABI 2.9.5p5:
3118 // abi::__array_type_info adds no data members to std::type_info.
3119 break;
3120
3121 case Type::FunctionNoProto:
Richard Smithb17d6fa2016-12-01 03:04:07 +00003122 case Type::FunctionProto:
David Majnemere2cb8d12014-07-07 06:20:47 +00003123 // Itanium C++ ABI 2.9.5p5:
3124 // abi::__function_type_info adds no data members to std::type_info.
3125 break;
3126
3127 case Type::Enum:
3128 // Itanium C++ ABI 2.9.5p5:
3129 // abi::__enum_type_info adds no data members to std::type_info.
3130 break;
3131
3132 case Type::Record: {
3133 const CXXRecordDecl *RD =
3134 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
3135 if (!RD->hasDefinition() || !RD->getNumBases()) {
3136 // We don't need to emit any fields.
3137 break;
3138 }
3139
3140 if (CanUseSingleInheritance(RD))
3141 BuildSIClassTypeInfo(RD);
3142 else
3143 BuildVMIClassTypeInfo(RD);
3144
3145 break;
3146 }
3147
3148 case Type::ObjCObject:
3149 case Type::ObjCInterface:
3150 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
3151 break;
3152
3153 case Type::ObjCObjectPointer:
3154 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
3155 break;
3156
3157 case Type::Pointer:
3158 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
3159 break;
3160
3161 case Type::MemberPointer:
3162 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
3163 break;
3164
3165 case Type::Atomic:
3166 // No fields, at least for the moment.
3167 break;
3168 }
3169
3170 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
3171
Rafael Espindolacb92c192015-01-15 23:18:01 +00003172 llvm::Module &M = CGM.getModule();
David Majnemere2cb8d12014-07-07 06:20:47 +00003173 llvm::GlobalVariable *GV =
Rafael Espindolacb92c192015-01-15 23:18:01 +00003174 new llvm::GlobalVariable(M, Init->getType(),
3175 /*Constant=*/true, Linkage, Init, Name);
3176
David Majnemere2cb8d12014-07-07 06:20:47 +00003177 // If there's already an old global variable, replace it with the new one.
3178 if (OldGV) {
3179 GV->takeName(OldGV);
3180 llvm::Constant *NewPtr =
3181 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3182 OldGV->replaceAllUsesWith(NewPtr);
3183 OldGV->eraseFromParent();
3184 }
3185
Yaron Keren04da2382015-07-29 15:42:28 +00003186 if (CGM.supportsCOMDAT() && GV->isWeakForLinker())
3187 GV->setComdat(M.getOrInsertComdat(GV->getName()));
3188
David Majnemere2cb8d12014-07-07 06:20:47 +00003189 // The Itanium ABI specifies that type_info objects must be globally
3190 // unique, with one exception: if the type is an incomplete class
3191 // type or a (possibly indirect) pointer to one. That exception
3192 // affects the general case of comparing type_info objects produced
3193 // by the typeid operator, which is why the comparison operators on
3194 // std::type_info generally use the type_info name pointers instead
3195 // of the object addresses. However, the language's built-in uses
3196 // of RTTI generally require class types to be complete, even when
3197 // manipulating pointers to those class types. This allows the
3198 // implementation of dynamic_cast to rely on address equality tests,
3199 // which is much faster.
3200
3201 // All of this is to say that it's important that both the type_info
3202 // object and the type_info name be uniqued when weakly emitted.
3203
3204 // Give the type_info object and name the formal visibility of the
3205 // type itself.
3206 llvm::GlobalValue::VisibilityTypes llvmVisibility;
3207 if (llvm::GlobalValue::isLocalLinkage(Linkage))
3208 // If the linkage is local, only default visibility makes sense.
3209 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
3210 else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden)
3211 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
3212 else
3213 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003214
David Majnemere2cb8d12014-07-07 06:20:47 +00003215 TypeName->setVisibility(llvmVisibility);
Rafael Espindola699f5d62018-02-07 22:15:33 +00003216 CGM.setDSOLocal(TypeName, Ty->getAsCXXRecordDecl());
3217
David Majnemere2cb8d12014-07-07 06:20:47 +00003218 GV->setVisibility(llvmVisibility);
Rafael Espindola699f5d62018-02-07 22:15:33 +00003219 CGM.setDSOLocal(GV, Ty->getAsCXXRecordDecl());
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003220
3221 if (CGM.getTriple().isWindowsItaniumEnvironment()) {
3222 auto RD = Ty->getAsCXXRecordDecl();
3223 if (DLLExport || (RD && RD->hasAttr<DLLExportAttr>())) {
3224 TypeName->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
3225 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
Shoaib Meenai61118e72017-07-04 01:02:19 +00003226 } else if (RD && RD->hasAttr<DLLImportAttr>() &&
3227 ShouldUseExternalRTTIDescriptor(CGM, Ty)) {
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003228 TypeName->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3229 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3230
3231 // Because the typename and the typeinfo are DLL import, convert them to
3232 // declarations rather than definitions. The initializers still need to
3233 // be constructed to calculate the type for the declarations.
3234 TypeName->setInitializer(nullptr);
3235 GV->setInitializer(nullptr);
3236 }
3237 }
David Majnemere2cb8d12014-07-07 06:20:47 +00003238
3239 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
3240}
3241
David Majnemere2cb8d12014-07-07 06:20:47 +00003242/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
3243/// for the given Objective-C object type.
3244void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
3245 // Drop qualifiers.
3246 const Type *T = OT->getBaseType().getTypePtr();
3247 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
3248
3249 // The builtin types are abi::__class_type_infos and don't require
3250 // extra fields.
3251 if (isa<BuiltinType>(T)) return;
3252
3253 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
3254 ObjCInterfaceDecl *Super = Class->getSuperClass();
3255
3256 // Root classes are also __class_type_info.
3257 if (!Super) return;
3258
3259 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
3260
3261 // Everything else is single inheritance.
3262 llvm::Constant *BaseTypeInfo =
3263 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
3264 Fields.push_back(BaseTypeInfo);
3265}
3266
3267/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
3268/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
3269void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
3270 // Itanium C++ ABI 2.9.5p6b:
3271 // It adds to abi::__class_type_info a single member pointing to the
3272 // type_info structure for the base type,
3273 llvm::Constant *BaseTypeInfo =
3274 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
3275 Fields.push_back(BaseTypeInfo);
3276}
3277
3278namespace {
3279 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
3280 /// a class hierarchy.
3281 struct SeenBases {
3282 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
3283 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
3284 };
3285}
3286
3287/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
3288/// abi::__vmi_class_type_info.
3289///
3290static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
3291 SeenBases &Bases) {
3292
3293 unsigned Flags = 0;
3294
3295 const CXXRecordDecl *BaseDecl =
3296 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
3297
3298 if (Base->isVirtual()) {
3299 // Mark the virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003300 if (!Bases.VirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003301 // If this virtual base has been seen before, then the class is diamond
3302 // shaped.
3303 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
3304 } else {
3305 if (Bases.NonVirtualBases.count(BaseDecl))
3306 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3307 }
3308 } else {
3309 // Mark the non-virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003310 if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003311 // If this non-virtual base has been seen before, then the class has non-
3312 // diamond shaped repeated inheritance.
3313 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3314 } else {
3315 if (Bases.VirtualBases.count(BaseDecl))
3316 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3317 }
3318 }
3319
3320 // Walk all bases.
3321 for (const auto &I : BaseDecl->bases())
3322 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3323
3324 return Flags;
3325}
3326
3327static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
3328 unsigned Flags = 0;
3329 SeenBases Bases;
3330
3331 // Walk all bases.
3332 for (const auto &I : RD->bases())
3333 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3334
3335 return Flags;
3336}
3337
3338/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
3339/// classes with bases that do not satisfy the abi::__si_class_type_info
3340/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
3341void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
3342 llvm::Type *UnsignedIntLTy =
3343 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3344
3345 // Itanium C++ ABI 2.9.5p6c:
3346 // __flags is a word with flags describing details about the class
3347 // structure, which may be referenced by using the __flags_masks
3348 // enumeration. These flags refer to both direct and indirect bases.
3349 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
3350 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3351
3352 // Itanium C++ ABI 2.9.5p6c:
3353 // __base_count is a word with the number of direct proper base class
3354 // descriptions that follow.
3355 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
3356
3357 if (!RD->getNumBases())
3358 return;
3359
David Majnemere2cb8d12014-07-07 06:20:47 +00003360 // Now add the base class descriptions.
3361
3362 // Itanium C++ ABI 2.9.5p6c:
3363 // __base_info[] is an array of base class descriptions -- one for every
3364 // direct proper base. Each description is of the type:
3365 //
3366 // struct abi::__base_class_type_info {
3367 // public:
3368 // const __class_type_info *__base_type;
3369 // long __offset_flags;
3370 //
3371 // enum __offset_flags_masks {
3372 // __virtual_mask = 0x1,
3373 // __public_mask = 0x2,
3374 // __offset_shift = 8
3375 // };
3376 // };
Reid Klecknerd8b04662016-08-25 22:16:30 +00003377
3378 // If we're in mingw and 'long' isn't wide enough for a pointer, use 'long
3379 // long' instead of 'long' for __offset_flags. libstdc++abi uses long long on
3380 // LLP64 platforms.
3381 // FIXME: Consider updating libc++abi to match, and extend this logic to all
3382 // LLP64 platforms.
3383 QualType OffsetFlagsTy = CGM.getContext().LongTy;
3384 const TargetInfo &TI = CGM.getContext().getTargetInfo();
3385 if (TI.getTriple().isOSCygMing() && TI.getPointerWidth(0) > TI.getLongWidth())
3386 OffsetFlagsTy = CGM.getContext().LongLongTy;
3387 llvm::Type *OffsetFlagsLTy =
3388 CGM.getTypes().ConvertType(OffsetFlagsTy);
3389
David Majnemere2cb8d12014-07-07 06:20:47 +00003390 for (const auto &Base : RD->bases()) {
3391 // The __base_type member points to the RTTI for the base type.
3392 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
3393
3394 const CXXRecordDecl *BaseDecl =
3395 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
3396
3397 int64_t OffsetFlags = 0;
3398
3399 // All but the lower 8 bits of __offset_flags are a signed offset.
3400 // For a non-virtual base, this is the offset in the object of the base
3401 // subobject. For a virtual base, this is the offset in the virtual table of
3402 // the virtual base offset for the virtual base referenced (negative).
3403 CharUnits Offset;
3404 if (Base.isVirtual())
3405 Offset =
3406 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
3407 else {
3408 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
3409 Offset = Layout.getBaseClassOffset(BaseDecl);
3410 };
3411
3412 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
3413
3414 // The low-order byte of __offset_flags contains flags, as given by the
3415 // masks from the enumeration __offset_flags_masks.
3416 if (Base.isVirtual())
3417 OffsetFlags |= BCTI_Virtual;
3418 if (Base.getAccessSpecifier() == AS_public)
3419 OffsetFlags |= BCTI_Public;
3420
Reid Klecknerd8b04662016-08-25 22:16:30 +00003421 Fields.push_back(llvm::ConstantInt::get(OffsetFlagsLTy, OffsetFlags));
David Majnemere2cb8d12014-07-07 06:20:47 +00003422 }
3423}
3424
Richard Smitha7d93782016-12-01 03:32:42 +00003425/// Compute the flags for a __pbase_type_info, and remove the corresponding
3426/// pieces from \p Type.
3427static unsigned extractPBaseFlags(ASTContext &Ctx, QualType &Type) {
3428 unsigned Flags = 0;
David Majnemere2cb8d12014-07-07 06:20:47 +00003429
Richard Smitha7d93782016-12-01 03:32:42 +00003430 if (Type.isConstQualified())
3431 Flags |= ItaniumRTTIBuilder::PTI_Const;
3432 if (Type.isVolatileQualified())
3433 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
3434 if (Type.isRestrictQualified())
3435 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
3436 Type = Type.getUnqualifiedType();
David Majnemere2cb8d12014-07-07 06:20:47 +00003437
3438 // Itanium C++ ABI 2.9.5p7:
3439 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3440 // incomplete class type, the incomplete target type flag is set.
Richard Smitha7d93782016-12-01 03:32:42 +00003441 if (ContainsIncompleteClassType(Type))
3442 Flags |= ItaniumRTTIBuilder::PTI_Incomplete;
3443
3444 if (auto *Proto = Type->getAs<FunctionProtoType>()) {
3445 if (Proto->isNothrow(Ctx)) {
3446 Flags |= ItaniumRTTIBuilder::PTI_Noexcept;
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00003447 Type = Ctx.getFunctionTypeWithExceptionSpec(Type, EST_None);
Richard Smitha7d93782016-12-01 03:32:42 +00003448 }
3449 }
3450
3451 return Flags;
3452}
3453
3454/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
3455/// used for pointer types.
3456void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
3457 // Itanium C++ ABI 2.9.5p7:
3458 // __flags is a flag word describing the cv-qualification and other
3459 // attributes of the type pointed to
3460 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003461
3462 llvm::Type *UnsignedIntLTy =
3463 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3464 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3465
3466 // Itanium C++ ABI 2.9.5p7:
3467 // __pointee is a pointer to the std::type_info derivation for the
3468 // unqualified type being pointed to.
3469 llvm::Constant *PointeeTypeInfo =
Richard Smitha7d93782016-12-01 03:32:42 +00003470 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003471 Fields.push_back(PointeeTypeInfo);
3472}
3473
3474/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
3475/// struct, used for member pointer types.
3476void
3477ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
3478 QualType PointeeTy = Ty->getPointeeType();
3479
David Majnemere2cb8d12014-07-07 06:20:47 +00003480 // Itanium C++ ABI 2.9.5p7:
3481 // __flags is a flag word describing the cv-qualification and other
3482 // attributes of the type pointed to.
Richard Smitha7d93782016-12-01 03:32:42 +00003483 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003484
3485 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
David Majnemere2cb8d12014-07-07 06:20:47 +00003486 if (IsIncompleteClassType(ClassType))
3487 Flags |= PTI_ContainingClassIncomplete;
3488
3489 llvm::Type *UnsignedIntLTy =
3490 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3491 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3492
3493 // Itanium C++ ABI 2.9.5p7:
3494 // __pointee is a pointer to the std::type_info derivation for the
3495 // unqualified type being pointed to.
3496 llvm::Constant *PointeeTypeInfo =
Richard Smitha7d93782016-12-01 03:32:42 +00003497 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003498 Fields.push_back(PointeeTypeInfo);
3499
3500 // Itanium C++ ABI 2.9.5p9:
3501 // __context is a pointer to an abi::__class_type_info corresponding to the
3502 // class type containing the member pointed to
3503 // (e.g., the "A" in "int A::*").
3504 Fields.push_back(
3505 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
3506}
3507
David Majnemer443250f2015-03-17 20:35:00 +00003508llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003509 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
3510}
3511
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003512void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type,
3513 bool DLLExport) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003514 QualType PointerType = getContext().getPointerType(Type);
3515 QualType PointerTypeConst = getContext().getPointerType(Type.withConst());
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003516 ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, /*Force=*/true, DLLExport);
3517 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, /*Force=*/true,
3518 DLLExport);
3519 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, /*Force=*/true,
3520 DLLExport);
David Majnemere2cb8d12014-07-07 06:20:47 +00003521}
3522
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003523void ItaniumCXXABI::EmitFundamentalRTTIDescriptors(bool DLLExport) {
Richard Smith4a382012016-02-03 01:32:42 +00003524 // Types added here must also be added to TypeInfoIsInStandardLibrary.
David Majnemere2cb8d12014-07-07 06:20:47 +00003525 QualType FundamentalTypes[] = {
3526 getContext().VoidTy, getContext().NullPtrTy,
3527 getContext().BoolTy, getContext().WCharTy,
3528 getContext().CharTy, getContext().UnsignedCharTy,
3529 getContext().SignedCharTy, getContext().ShortTy,
3530 getContext().UnsignedShortTy, getContext().IntTy,
3531 getContext().UnsignedIntTy, getContext().LongTy,
3532 getContext().UnsignedLongTy, getContext().LongLongTy,
Richard Smith4a382012016-02-03 01:32:42 +00003533 getContext().UnsignedLongLongTy, getContext().Int128Ty,
3534 getContext().UnsignedInt128Ty, getContext().HalfTy,
David Majnemere2cb8d12014-07-07 06:20:47 +00003535 getContext().FloatTy, getContext().DoubleTy,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00003536 getContext().LongDoubleTy, getContext().Float128Ty,
3537 getContext().Char16Ty, getContext().Char32Ty
David Majnemere2cb8d12014-07-07 06:20:47 +00003538 };
3539 for (const QualType &FundamentalType : FundamentalTypes)
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003540 EmitFundamentalRTTIDescriptor(FundamentalType, DLLExport);
David Majnemere2cb8d12014-07-07 06:20:47 +00003541}
3542
3543/// What sort of uniqueness rules should we use for the RTTI for the
3544/// given type?
3545ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
3546 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
3547 if (shouldRTTIBeUnique())
3548 return RUK_Unique;
3549
3550 // It's only necessary for linkonce_odr or weak_odr linkage.
3551 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
3552 Linkage != llvm::GlobalValue::WeakODRLinkage)
3553 return RUK_Unique;
3554
3555 // It's only necessary with default visibility.
3556 if (CanTy->getVisibility() != DefaultVisibility)
3557 return RUK_Unique;
3558
3559 // If we're not required to publish this symbol, hide it.
3560 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3561 return RUK_NonUniqueHidden;
3562
3563 // If we're required to publish this symbol, as we might be under an
3564 // explicit instantiation, leave it with default visibility but
3565 // enable string-comparisons.
3566 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
3567 return RUK_NonUniqueVisible;
3568}
Rafael Espindola91f68b42014-09-15 19:20:10 +00003569
Rafael Espindola1e4df922014-09-16 15:18:21 +00003570// Find out how to codegen the complete destructor and constructor
3571namespace {
3572enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
3573}
3574static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
3575 const CXXMethodDecl *MD) {
3576 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
3577 return StructorCodegen::Emit;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003578
Rafael Espindola1e4df922014-09-16 15:18:21 +00003579 // The complete and base structors are not equivalent if there are any virtual
3580 // bases, so emit separate functions.
3581 if (MD->getParent()->getNumVBases())
3582 return StructorCodegen::Emit;
3583
3584 GlobalDecl AliasDecl;
3585 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3586 AliasDecl = GlobalDecl(DD, Dtor_Complete);
3587 } else {
3588 const auto *CD = cast<CXXConstructorDecl>(MD);
3589 AliasDecl = GlobalDecl(CD, Ctor_Complete);
3590 }
3591 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3592
3593 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
3594 return StructorCodegen::RAUW;
3595
3596 // FIXME: Should we allow available_externally aliases?
3597 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
3598 return StructorCodegen::RAUW;
3599
Rafael Espindola0806f982014-09-16 20:19:43 +00003600 if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
Dan Gohman839f2152017-01-17 21:46:38 +00003601 // Only ELF and wasm support COMDATs with arbitrary names (C5/D5).
3602 if (CGM.getTarget().getTriple().isOSBinFormatELF() ||
3603 CGM.getTarget().getTriple().isOSBinFormatWasm())
Rafael Espindola0806f982014-09-16 20:19:43 +00003604 return StructorCodegen::COMDAT;
3605 return StructorCodegen::Emit;
3606 }
Rafael Espindola1e4df922014-09-16 15:18:21 +00003607
3608 return StructorCodegen::Alias;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003609}
3610
Rafael Espindola1e4df922014-09-16 15:18:21 +00003611static void emitConstructorDestructorAlias(CodeGenModule &CGM,
3612 GlobalDecl AliasDecl,
3613 GlobalDecl TargetDecl) {
3614 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3615
3616 StringRef MangledName = CGM.getMangledName(AliasDecl);
3617 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
3618 if (Entry && !Entry->isDeclaration())
3619 return;
3620
3621 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
Rafael Espindola1e4df922014-09-16 15:18:21 +00003622
3623 // Create the alias with no name.
David Blaikie2a791d72015-09-14 18:38:22 +00003624 auto *Alias = llvm::GlobalAlias::create(Linkage, "", Aliasee);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003625
3626 // Switch any previous uses to the alias.
3627 if (Entry) {
NAKAMURA Takumie9621042015-09-15 01:39:27 +00003628 assert(Entry->getType() == Aliasee->getType() &&
Rafael Espindola1e4df922014-09-16 15:18:21 +00003629 "declaration exists with different type");
3630 Alias->takeName(Entry);
3631 Entry->replaceAllUsesWith(Alias);
3632 Entry->eraseFromParent();
3633 } else {
3634 Alias->setName(MangledName);
3635 }
3636
3637 // Finally, set up the alias with its proper name and attributes.
Dario Domiziolic4fb8ca72014-09-19 22:06:24 +00003638 CGM.setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003639}
3640
3641void ItaniumCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
3642 StructorType Type) {
3643 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
3644 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
3645
3646 StructorCodegen CGType = getCodegenToUse(CGM, MD);
3647
3648 if (Type == StructorType::Complete) {
3649 GlobalDecl CompleteDecl;
3650 GlobalDecl BaseDecl;
3651 if (CD) {
3652 CompleteDecl = GlobalDecl(CD, Ctor_Complete);
3653 BaseDecl = GlobalDecl(CD, Ctor_Base);
3654 } else {
3655 CompleteDecl = GlobalDecl(DD, Dtor_Complete);
3656 BaseDecl = GlobalDecl(DD, Dtor_Base);
3657 }
3658
3659 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
3660 emitConstructorDestructorAlias(CGM, CompleteDecl, BaseDecl);
3661 return;
3662 }
3663
3664 if (CGType == StructorCodegen::RAUW) {
3665 StringRef MangledName = CGM.getMangledName(CompleteDecl);
Andrey Bokhankocab58582015-08-31 13:20:44 +00003666 auto *Aliasee = CGM.GetAddrOfGlobal(BaseDecl);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003667 CGM.addReplacement(MangledName, Aliasee);
3668 return;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003669 }
3670 }
3671
3672 // The base destructor is equivalent to the base destructor of its
3673 // base class if there is exactly one non-virtual base class with a
3674 // non-trivial destructor, there are no fields with a non-trivial
3675 // destructor, and the body of the destructor is trivial.
Rafael Espindola1e4df922014-09-16 15:18:21 +00003676 if (DD && Type == StructorType::Base && CGType != StructorCodegen::COMDAT &&
3677 !CGM.TryEmitBaseDestructorAsAlias(DD))
Rafael Espindola91f68b42014-09-15 19:20:10 +00003678 return;
3679
Richard Smith5b349582017-10-13 01:55:36 +00003680 // FIXME: The deleting destructor is equivalent to the selected operator
3681 // delete if:
3682 // * either the delete is a destroying operator delete or the destructor
3683 // would be trivial if it weren't virtual,
3684 // * the conversion from the 'this' parameter to the first parameter of the
3685 // destructor is equivalent to a bitcast,
3686 // * the destructor does not have an implicit "this" return, and
3687 // * the operator delete has the same calling convention and IR function type
3688 // as the destructor.
3689 // In such cases we should try to emit the deleting dtor as an alias to the
3690 // selected 'operator delete'.
3691
Rafael Espindola1e4df922014-09-16 15:18:21 +00003692 llvm::Function *Fn = CGM.codegenCXXStructor(MD, Type);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003693
Rafael Espindola1e4df922014-09-16 15:18:21 +00003694 if (CGType == StructorCodegen::COMDAT) {
3695 SmallString<256> Buffer;
3696 llvm::raw_svector_ostream Out(Buffer);
3697 if (DD)
3698 getMangleContext().mangleCXXDtorComdat(DD, Out);
3699 else
3700 getMangleContext().mangleCXXCtorComdat(CD, Out);
3701 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
3702 Fn->setComdat(C);
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003703 } else {
3704 CGM.maybeSetTrivialComdat(*MD, *Fn);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003705 }
Rafael Espindola91f68b42014-09-15 19:20:10 +00003706}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003707
3708static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) {
3709 // void *__cxa_begin_catch(void*);
3710 llvm::FunctionType *FTy = llvm::FunctionType::get(
3711 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3712
3713 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
3714}
3715
3716static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) {
3717 // void __cxa_end_catch();
3718 llvm::FunctionType *FTy =
3719 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
3720
3721 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
3722}
3723
3724static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) {
3725 // void *__cxa_get_exception_ptr(void*);
3726 llvm::FunctionType *FTy = llvm::FunctionType::get(
3727 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3728
3729 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
3730}
3731
3732namespace {
3733 /// A cleanup to call __cxa_end_catch. In many cases, the caught
3734 /// exception type lets us state definitively that the thrown exception
3735 /// type does not have a destructor. In particular:
3736 /// - Catch-alls tell us nothing, so we have to conservatively
3737 /// assume that the thrown exception might have a destructor.
3738 /// - Catches by reference behave according to their base types.
3739 /// - Catches of non-record types will only trigger for exceptions
3740 /// of non-record types, which never have destructors.
3741 /// - Catches of record types can trigger for arbitrary subclasses
3742 /// of the caught type, so we have to assume the actual thrown
3743 /// exception type might have a throwing destructor, even if the
3744 /// caught type's destructor is trivial or nothrow.
David Blaikie7e70d682015-08-18 22:40:54 +00003745 struct CallEndCatch final : EHScopeStack::Cleanup {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003746 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
3747 bool MightThrow;
3748
3749 void Emit(CodeGenFunction &CGF, Flags flags) override {
3750 if (!MightThrow) {
3751 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
3752 return;
3753 }
3754
3755 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
3756 }
3757 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003758}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003759
3760/// Emits a call to __cxa_begin_catch and enters a cleanup to call
3761/// __cxa_end_catch.
3762///
3763/// \param EndMightThrow - true if __cxa_end_catch might throw
3764static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
3765 llvm::Value *Exn,
3766 bool EndMightThrow) {
3767 llvm::CallInst *call =
3768 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
3769
3770 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
3771
3772 return call;
3773}
3774
3775/// A "special initializer" callback for initializing a catch
3776/// parameter during catch initialization.
3777static void InitCatchParam(CodeGenFunction &CGF,
3778 const VarDecl &CatchParam,
John McCall7f416cc2015-09-08 08:05:57 +00003779 Address ParamAddr,
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003780 SourceLocation Loc) {
3781 // Load the exception from where the landing pad saved it.
3782 llvm::Value *Exn = CGF.getExceptionFromSlot();
3783
3784 CanQualType CatchType =
3785 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
3786 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
3787
3788 // If we're catching by reference, we can just cast the object
3789 // pointer to the appropriate pointer.
3790 if (isa<ReferenceType>(CatchType)) {
3791 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
3792 bool EndCatchMightThrow = CaughtType->isRecordType();
3793
3794 // __cxa_begin_catch returns the adjusted object pointer.
3795 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
3796
3797 // We have no way to tell the personality function that we're
3798 // catching by reference, so if we're catching a pointer,
3799 // __cxa_begin_catch will actually return that pointer by value.
3800 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
3801 QualType PointeeType = PT->getPointeeType();
3802
3803 // When catching by reference, generally we should just ignore
3804 // this by-value pointer and use the exception object instead.
3805 if (!PointeeType->isRecordType()) {
3806
3807 // Exn points to the struct _Unwind_Exception header, which
3808 // we have to skip past in order to reach the exception data.
3809 unsigned HeaderSize =
3810 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
3811 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
3812
3813 // However, if we're catching a pointer-to-record type that won't
3814 // work, because the personality function might have adjusted
3815 // the pointer. There's actually no way for us to fully satisfy
3816 // the language/ABI contract here: we can't use Exn because it
3817 // might have the wrong adjustment, but we can't use the by-value
3818 // pointer because it's off by a level of abstraction.
3819 //
3820 // The current solution is to dump the adjusted pointer into an
3821 // alloca, which breaks language semantics (because changing the
3822 // pointer doesn't change the exception) but at least works.
3823 // The better solution would be to filter out non-exact matches
3824 // and rethrow them, but this is tricky because the rethrow
3825 // really needs to be catchable by other sites at this landing
3826 // pad. The best solution is to fix the personality function.
3827 } else {
3828 // Pull the pointer for the reference type off.
3829 llvm::Type *PtrTy =
3830 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
3831
3832 // Create the temporary and write the adjusted pointer into it.
John McCall7f416cc2015-09-08 08:05:57 +00003833 Address ExnPtrTmp =
3834 CGF.CreateTempAlloca(PtrTy, CGF.getPointerAlign(), "exn.byref.tmp");
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003835 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3836 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
3837
3838 // Bind the reference to the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00003839 AdjustedExn = ExnPtrTmp.getPointer();
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003840 }
3841 }
3842
3843 llvm::Value *ExnCast =
3844 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
3845 CGF.Builder.CreateStore(ExnCast, ParamAddr);
3846 return;
3847 }
3848
3849 // Scalars and complexes.
3850 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
3851 if (TEK != TEK_Aggregate) {
3852 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
3853
3854 // If the catch type is a pointer type, __cxa_begin_catch returns
3855 // the pointer by value.
3856 if (CatchType->hasPointerRepresentation()) {
3857 llvm::Value *CastExn =
3858 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
3859
3860 switch (CatchType.getQualifiers().getObjCLifetime()) {
3861 case Qualifiers::OCL_Strong:
3862 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
3863 // fallthrough
3864
3865 case Qualifiers::OCL_None:
3866 case Qualifiers::OCL_ExplicitNone:
3867 case Qualifiers::OCL_Autoreleasing:
3868 CGF.Builder.CreateStore(CastExn, ParamAddr);
3869 return;
3870
3871 case Qualifiers::OCL_Weak:
3872 CGF.EmitARCInitWeak(ParamAddr, CastExn);
3873 return;
3874 }
3875 llvm_unreachable("bad ownership qualifier!");
3876 }
3877
3878 // Otherwise, it returns a pointer into the exception object.
3879
3880 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3881 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3882
3883 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
John McCall7f416cc2015-09-08 08:05:57 +00003884 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003885 switch (TEK) {
3886 case TEK_Complex:
3887 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
3888 /*init*/ true);
3889 return;
3890 case TEK_Scalar: {
3891 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
3892 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
3893 return;
3894 }
3895 case TEK_Aggregate:
3896 llvm_unreachable("evaluation kind filtered out!");
3897 }
3898 llvm_unreachable("bad evaluation kind");
3899 }
3900
3901 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
John McCall7f416cc2015-09-08 08:05:57 +00003902 auto catchRD = CatchType->getAsCXXRecordDecl();
3903 CharUnits caughtExnAlignment = CGF.CGM.getClassPointerAlignment(catchRD);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003904
3905 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3906
3907 // Check for a copy expression. If we don't have a copy expression,
3908 // that means a trivial copy is okay.
3909 const Expr *copyExpr = CatchParam.getInit();
3910 if (!copyExpr) {
3911 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
John McCall7f416cc2015-09-08 08:05:57 +00003912 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3913 caughtExnAlignment);
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00003914 LValue Dest = CGF.MakeAddrLValue(ParamAddr, CatchType);
3915 LValue Src = CGF.MakeAddrLValue(adjustedExn, CatchType);
3916 CGF.EmitAggregateCopy(Dest, Src, CatchType);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003917 return;
3918 }
3919
3920 // We have to call __cxa_get_exception_ptr to get the adjusted
3921 // pointer before copying.
3922 llvm::CallInst *rawAdjustedExn =
3923 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
3924
3925 // Cast that to the appropriate type.
John McCall7f416cc2015-09-08 08:05:57 +00003926 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3927 caughtExnAlignment);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003928
3929 // The copy expression is defined in terms of an OpaqueValueExpr.
3930 // Find it and map it to the adjusted expression.
3931 CodeGenFunction::OpaqueValueMapping
3932 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
3933 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
3934
3935 // Call the copy ctor in a terminate scope.
3936 CGF.EHStack.pushTerminate();
3937
3938 // Perform the copy construction.
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003939 CGF.EmitAggExpr(copyExpr,
John McCall7f416cc2015-09-08 08:05:57 +00003940 AggValueSlot::forAddr(ParamAddr, Qualifiers(),
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003941 AggValueSlot::IsNotDestructed,
3942 AggValueSlot::DoesNotNeedGCBarriers,
3943 AggValueSlot::IsNotAliased));
3944
3945 // Leave the terminate scope.
3946 CGF.EHStack.popTerminate();
3947
3948 // Undo the opaque value mapping.
3949 opaque.pop();
3950
3951 // Finally we can call __cxa_begin_catch.
3952 CallBeginCatch(CGF, Exn, true);
3953}
3954
3955/// Begins a catch statement by initializing the catch variable and
3956/// calling __cxa_begin_catch.
3957void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF,
3958 const CXXCatchStmt *S) {
3959 // We have to be very careful with the ordering of cleanups here:
3960 // C++ [except.throw]p4:
3961 // The destruction [of the exception temporary] occurs
3962 // immediately after the destruction of the object declared in
3963 // the exception-declaration in the handler.
3964 //
3965 // So the precise ordering is:
3966 // 1. Construct catch variable.
3967 // 2. __cxa_begin_catch
3968 // 3. Enter __cxa_end_catch cleanup
3969 // 4. Enter dtor cleanup
3970 //
3971 // We do this by using a slightly abnormal initialization process.
3972 // Delegation sequence:
3973 // - ExitCXXTryStmt opens a RunCleanupsScope
3974 // - EmitAutoVarAlloca creates the variable and debug info
3975 // - InitCatchParam initializes the variable from the exception
3976 // - CallBeginCatch calls __cxa_begin_catch
3977 // - CallBeginCatch enters the __cxa_end_catch cleanup
3978 // - EmitAutoVarCleanups enters the variable destructor cleanup
3979 // - EmitCXXTryStmt emits the code for the catch body
3980 // - EmitCXXTryStmt close the RunCleanupsScope
3981
3982 VarDecl *CatchParam = S->getExceptionDecl();
3983 if (!CatchParam) {
3984 llvm::Value *Exn = CGF.getExceptionFromSlot();
3985 CallBeginCatch(CGF, Exn, true);
3986 return;
3987 }
3988
3989 // Emit the local.
3990 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
3991 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
3992 CGF.EmitAutoVarCleanups(var);
3993}
3994
3995/// Get or define the following function:
3996/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
3997/// This code is used only in C++.
3998static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
3999 llvm::FunctionType *fnTy =
4000 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00004001 llvm::Constant *fnRef = CGM.CreateRuntimeFunction(
4002 fnTy, "__clang_call_terminate", llvm::AttributeList(), /*Local=*/true);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004003
4004 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
4005 if (fn && fn->empty()) {
4006 fn->setDoesNotThrow();
4007 fn->setDoesNotReturn();
4008
4009 // What we really want is to massively penalize inlining without
4010 // forbidding it completely. The difference between that and
4011 // 'noinline' is negligible.
4012 fn->addFnAttr(llvm::Attribute::NoInline);
4013
4014 // Allow this function to be shared across translation units, but
4015 // we don't want it to turn into an exported symbol.
4016 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
4017 fn->setVisibility(llvm::Function::HiddenVisibility);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00004018 if (CGM.supportsCOMDAT())
4019 fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004020
4021 // Set up the function.
4022 llvm::BasicBlock *entry =
4023 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
John McCall7f416cc2015-09-08 08:05:57 +00004024 CGBuilderTy builder(CGM, entry);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004025
4026 // Pull the exception pointer out of the parameter list.
4027 llvm::Value *exn = &*fn->arg_begin();
4028
4029 // Call __cxa_begin_catch(exn).
4030 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
4031 catchCall->setDoesNotThrow();
4032 catchCall->setCallingConv(CGM.getRuntimeCC());
4033
4034 // Call std::terminate().
David Blaikie4ba525b2015-07-14 17:27:39 +00004035 llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn());
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004036 termCall->setDoesNotThrow();
4037 termCall->setDoesNotReturn();
4038 termCall->setCallingConv(CGM.getRuntimeCC());
4039
4040 // std::terminate cannot return.
4041 builder.CreateUnreachable();
4042 }
4043
4044 return fnRef;
4045}
4046
4047llvm::CallInst *
4048ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
4049 llvm::Value *Exn) {
4050 // In C++, we want to call __cxa_begin_catch() before terminating.
4051 if (Exn) {
4052 assert(CGF.CGM.getLangOpts().CPlusPlus);
4053 return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn);
4054 }
4055 return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
4056}
Peter Collingbourne60108802017-12-13 21:53:04 +00004057
4058std::pair<llvm::Value *, const CXXRecordDecl *>
4059ItaniumCXXABI::LoadVTablePtr(CodeGenFunction &CGF, Address This,
4060 const CXXRecordDecl *RD) {
4061 return {CGF.GetVTablePtr(This, CGM.Int8PtrTy, RD), RD};
4062}