blob: b79e51f3ae1f8585fabe2f5da2701a25a34b451c [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"
Akira Hatanaka617e2612018-04-17 18:41:52 +000037#include "llvm/Support/ScopedPrinter.h"
Charles Davis4e786dd2010-05-25 19:52:27 +000038
39using namespace clang;
John McCall475999d2010-08-22 00:05:51 +000040using namespace CodeGen;
Charles Davis4e786dd2010-05-25 19:52:27 +000041
42namespace {
Charles Davis53c59df2010-08-16 03:33:14 +000043class ItaniumCXXABI : public CodeGen::CGCXXABI {
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +000044 /// VTables - All the vtables which have been defined.
45 llvm::DenseMap<const CXXRecordDecl *, llvm::GlobalVariable *> VTables;
46
John McCall475999d2010-08-22 00:05:51 +000047protected:
Mark Seabornedf0d382013-07-24 16:25:13 +000048 bool UseARMMethodPtrABI;
49 bool UseARMGuardVarABI;
John McCalld23b27e2016-09-16 02:40:45 +000050 bool Use32BitVTableOffsetABI;
John McCall7a9aac22010-08-23 01:21:21 +000051
Timur Iskhodzhanov67455222013-10-03 06:26:13 +000052 ItaniumMangleContext &getMangleContext() {
53 return cast<ItaniumMangleContext>(CodeGen::CGCXXABI::getMangleContext());
54 }
55
Charles Davis4e786dd2010-05-25 19:52:27 +000056public:
Mark Seabornedf0d382013-07-24 16:25:13 +000057 ItaniumCXXABI(CodeGen::CodeGenModule &CGM,
58 bool UseARMMethodPtrABI = false,
59 bool UseARMGuardVarABI = false) :
60 CGCXXABI(CGM), UseARMMethodPtrABI(UseARMMethodPtrABI),
John McCalld23b27e2016-09-16 02:40:45 +000061 UseARMGuardVarABI(UseARMGuardVarABI),
Richard Smithb17d6fa2016-12-01 03:04:07 +000062 Use32BitVTableOffsetABI(false) { }
John McCall475999d2010-08-22 00:05:51 +000063
Reid Kleckner40ca9132014-05-13 22:05:45 +000064 bool classifyReturnType(CGFunctionInfo &FI) const override;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000065
Richard Smithf667ad52017-08-26 01:04:35 +000066 bool passClassIndirect(const CXXRecordDecl *RD) const {
Richard Smithf667ad52017-08-26 01:04:35 +000067 return !canCopyArgument(RD);
68 }
69
Craig Topper4f12f102014-03-12 06:41:41 +000070 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override {
Richard Smith96cd6712017-08-16 01:49:53 +000071 // If C++ prohibits us from making a copy, pass by address.
Richard Smithf667ad52017-08-26 01:04:35 +000072 if (passClassIndirect(RD))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000073 return RAA_Indirect;
74 return RAA_Default;
75 }
76
John McCall7f416cc2015-09-08 08:05:57 +000077 bool isThisCompleteObject(GlobalDecl GD) const override {
78 // The Itanium ABI has separate complete-object vs. base-object
79 // variants of both constructors and destructors.
80 if (isa<CXXDestructorDecl>(GD.getDecl())) {
81 switch (GD.getDtorType()) {
82 case Dtor_Complete:
83 case Dtor_Deleting:
84 return true;
85
86 case Dtor_Base:
87 return false;
88
89 case Dtor_Comdat:
90 llvm_unreachable("emitting dtor comdat as function?");
91 }
92 llvm_unreachable("bad dtor kind");
93 }
94 if (isa<CXXConstructorDecl>(GD.getDecl())) {
95 switch (GD.getCtorType()) {
96 case Ctor_Complete:
97 return true;
98
99 case Ctor_Base:
100 return false;
101
102 case Ctor_CopyingClosure:
103 case Ctor_DefaultClosure:
104 llvm_unreachable("closure ctors in Itanium ABI?");
105
106 case Ctor_Comdat:
107 llvm_unreachable("emitting ctor comdat as function?");
108 }
109 llvm_unreachable("bad dtor kind");
110 }
111
112 // No other kinds.
113 return false;
114 }
115
Craig Topper4f12f102014-03-12 06:41:41 +0000116 bool isZeroInitializable(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +0000117
Craig Topper4f12f102014-03-12 06:41:41 +0000118 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
John McCall7a9aac22010-08-23 01:21:21 +0000119
John McCallb92ab1a2016-10-26 23:46:34 +0000120 CGCallee
Craig Topper4f12f102014-03-12 06:41:41 +0000121 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
122 const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000123 Address This,
124 llvm::Value *&ThisPtrForCall,
Craig Topper4f12f102014-03-12 06:41:41 +0000125 llvm::Value *MemFnPtr,
126 const MemberPointerType *MPT) override;
John McCalla8bbb822010-08-22 03:04:22 +0000127
Craig Topper4f12f102014-03-12 06:41:41 +0000128 llvm::Value *
129 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000130 Address Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000131 llvm::Value *MemPtr,
132 const MemberPointerType *MPT) override;
John McCallc134eb52010-08-31 21:07:20 +0000133
John McCall7a9aac22010-08-23 01:21:21 +0000134 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
135 const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +0000136 llvm::Value *Src) override;
John McCallc62bb392012-02-15 01:22:51 +0000137 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +0000138 llvm::Constant *Src) override;
John McCall84fa5102010-08-22 04:16:24 +0000139
Craig Topper4f12f102014-03-12 06:41:41 +0000140 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +0000141
David Majnemere2be95b2015-06-23 07:31:01 +0000142 llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD) override;
John McCallf3a88602011-02-03 08:15:49 +0000143 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +0000144 CharUnits offset) override;
145 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
Richard Smithdafff942012-01-14 04:30:29 +0000146 llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
147 CharUnits ThisAdjustment);
John McCall1c456c82010-08-22 06:43:33 +0000148
John McCall7a9aac22010-08-23 01:21:21 +0000149 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000150 llvm::Value *L, llvm::Value *R,
John McCall7a9aac22010-08-23 01:21:21 +0000151 const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +0000152 bool Inequality) override;
John McCall131d97d2010-08-22 08:30:07 +0000153
John McCall7a9aac22010-08-23 01:21:21 +0000154 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000155 llvm::Value *Addr,
156 const MemberPointerType *MPT) override;
John McCall5d865c322010-08-31 07:33:07 +0000157
David Majnemer08681372014-11-01 07:37:17 +0000158 void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,
John McCall7f416cc2015-09-08 08:05:57 +0000159 Address Ptr, QualType ElementType,
David Majnemer0c0b6d92014-10-31 20:09:12 +0000160 const CXXDestructorDecl *Dtor) override;
John McCall82fb8922012-09-25 10:10:39 +0000161
Akira Hatanakac47fcf02017-07-27 18:52:44 +0000162 /// Itanium says that an _Unwind_Exception has to be "double-word"
163 /// aligned (and thus the end of it is also so-aligned), meaning 16
164 /// bytes. Of course, that was written for the actual Itanium,
165 /// which is a 64-bit platform. Classically, the ABI doesn't really
166 /// specify the alignment on other platforms, but in practice
167 /// libUnwind declares the struct with __attribute__((aligned)), so
168 /// we assume that alignment here. (It's generally 16 bytes, but
169 /// some targets overwrite it.)
John McCall7f416cc2015-09-08 08:05:57 +0000170 CharUnits getAlignmentOfExnObject() {
Akira Hatanakac47fcf02017-07-27 18:52:44 +0000171 auto align = CGM.getContext().getTargetDefaultAlignForAttributeAligned();
172 return CGM.getContext().toCharUnitsFromBits(align);
John McCall7f416cc2015-09-08 08:05:57 +0000173 }
174
David Majnemer442d0a22014-11-25 07:20:20 +0000175 void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
David Majnemer7c237072015-03-05 00:46:22 +0000176 void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override;
David Majnemer442d0a22014-11-25 07:20:20 +0000177
Reid Klecknerfff8e7f2015-03-03 19:21:04 +0000178 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
179
180 llvm::CallInst *
181 emitTerminateForUnexpectedException(CodeGenFunction &CGF,
182 llvm::Value *Exn) override;
183
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +0000184 void EmitFundamentalRTTIDescriptor(QualType Type, bool DLLExport);
185 void EmitFundamentalRTTIDescriptors(bool DLLExport);
David Majnemer443250f2015-03-17 20:35:00 +0000186 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
Reid Kleckner10aa7702015-09-16 20:15:55 +0000187 CatchTypeInfo
David Majnemer37b417f2015-03-29 21:55:10 +0000188 getAddrOfCXXCatchHandlerType(QualType Ty,
189 QualType CatchHandlerType) override {
Reid Kleckner10aa7702015-09-16 20:15:55 +0000190 return CatchTypeInfo{getAddrOfRTTIDescriptor(Ty), 0};
David Majnemer443250f2015-03-17 20:35:00 +0000191 }
David Majnemere2cb8d12014-07-07 06:20:47 +0000192
David Majnemer1162d252014-06-22 19:05:33 +0000193 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
194 void EmitBadTypeidCall(CodeGenFunction &CGF) override;
195 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
John McCall7f416cc2015-09-08 08:05:57 +0000196 Address ThisPtr,
David Majnemer1162d252014-06-22 19:05:33 +0000197 llvm::Type *StdTypeInfoPtrTy) override;
198
199 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
200 QualType SrcRecordTy) override;
201
John McCall7f416cc2015-09-08 08:05:57 +0000202 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, Address Value,
David Majnemer1162d252014-06-22 19:05:33 +0000203 QualType SrcRecordTy, QualType DestTy,
204 QualType DestRecordTy,
205 llvm::BasicBlock *CastEnd) override;
206
John McCall7f416cc2015-09-08 08:05:57 +0000207 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
David Majnemer1162d252014-06-22 19:05:33 +0000208 QualType SrcRecordTy,
209 QualType DestTy) override;
210
211 bool EmitBadCastCall(CodeGenFunction &CGF) override;
212
Craig Topper4f12f102014-03-12 06:41:41 +0000213 llvm::Value *
John McCall7f416cc2015-09-08 08:05:57 +0000214 GetVirtualBaseClassOffset(CodeGenFunction &CGF, Address This,
Craig Topper4f12f102014-03-12 06:41:41 +0000215 const CXXRecordDecl *ClassDecl,
216 const CXXRecordDecl *BaseClassDecl) override;
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000217
Craig Topper4f12f102014-03-12 06:41:41 +0000218 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000219
George Burgess IVf203dbf2017-02-22 20:28:02 +0000220 AddedStructorArgs
221 buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
222 SmallVectorImpl<CanQualType> &ArgTys) override;
John McCall5d865c322010-08-31 07:33:07 +0000223
Reid Klecknere7de47e2013-07-22 13:51:44 +0000224 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
Craig Topper4f12f102014-03-12 06:41:41 +0000225 CXXDtorType DT) const override {
Reid Klecknere7de47e2013-07-22 13:51:44 +0000226 // Itanium does not emit any destructor variant as an inline thunk.
227 // Delegating may occur as an optimization, but all variants are either
228 // emitted with external linkage or as linkonce if they are inline and used.
229 return false;
230 }
231
Craig Topper4f12f102014-03-12 06:41:41 +0000232 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
Reid Klecknere7de47e2013-07-22 13:51:44 +0000233
Reid Kleckner89077a12013-12-17 19:46:40 +0000234 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
Craig Topper4f12f102014-03-12 06:41:41 +0000235 FunctionArgList &Params) override;
John McCall5d865c322010-08-31 07:33:07 +0000236
Craig Topper4f12f102014-03-12 06:41:41 +0000237 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
John McCall8ed55a52010-09-02 09:58:18 +0000238
George Burgess IVf203dbf2017-02-22 20:28:02 +0000239 AddedStructorArgs
240 addImplicitConstructorArgs(CodeGenFunction &CGF, const CXXConstructorDecl *D,
241 CXXCtorType Type, bool ForVirtualBase,
242 bool Delegating, CallArgList &Args) override;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000243
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000244 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
245 CXXDtorType Type, bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +0000246 bool Delegating, Address This) override;
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000247
Craig Topper4f12f102014-03-12 06:41:41 +0000248 void emitVTableDefinitions(CodeGenVTables &CGVT,
249 const CXXRecordDecl *RD) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000250
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000251 bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,
252 CodeGenFunction::VPtr Vptr) override;
253
254 bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override {
255 return true;
256 }
257
258 llvm::Constant *
259 getVTableAddressPoint(BaseSubobject Base,
260 const CXXRecordDecl *VTableClass) override;
261
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000262 llvm::Value *getVTableAddressPointInStructor(
263 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000264 BaseSubobject Base, const CXXRecordDecl *NearestVBase) override;
265
266 llvm::Value *getVTableAddressPointInStructorWithVTT(
267 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
268 BaseSubobject Base, const CXXRecordDecl *NearestVBase);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000269
270 llvm::Constant *
271 getVTableAddressPointForConstExpr(BaseSubobject Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000272 const CXXRecordDecl *VTableClass) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000273
274 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
Craig Topper4f12f102014-03-12 06:41:41 +0000275 CharUnits VPtrOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000276
John McCall9831b842018-02-06 18:52:44 +0000277 CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
278 Address This, llvm::Type *Ty,
279 SourceLocation Loc) override;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000280
David Majnemer0c0b6d92014-10-31 20:09:12 +0000281 llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
282 const CXXDestructorDecl *Dtor,
283 CXXDtorType DtorType,
John McCall7f416cc2015-09-08 08:05:57 +0000284 Address This,
David Majnemer0c0b6d92014-10-31 20:09:12 +0000285 const CXXMemberCallExpr *CE) override;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000286
Craig Topper4f12f102014-03-12 06:41:41 +0000287 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
Reid Kleckner7810af02013-06-19 15:20:38 +0000288
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000289 bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const override;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000290
Hans Wennborgc94391d2014-06-06 20:04:01 +0000291 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
292 bool ReturnAdjustment) override {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000293 // Allow inlining of thunks by emitting them with available_externally
294 // linkage together with vtables when needed.
Peter Collingbourne8fabc1b2015-07-01 02:10:26 +0000295 if (ForVTable && !Thunk->hasLocalLinkage())
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000296 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
Rafael Espindolab7350042018-03-01 00:35:47 +0000297 CGM.setGVProperties(Thunk, GD);
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000298 }
299
Rafael Espindolab7350042018-03-01 00:35:47 +0000300 bool exportThunk() override { return true; }
301
John McCall7f416cc2015-09-08 08:05:57 +0000302 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This,
Craig Topper4f12f102014-03-12 06:41:41 +0000303 const ThisAdjustment &TA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000304
John McCall7f416cc2015-09-08 08:05:57 +0000305 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
Craig Topper4f12f102014-03-12 06:41:41 +0000306 const ReturnAdjustment &RA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000307
David Majnemer196ac332014-09-11 23:05:02 +0000308 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
309 FunctionArgList &Args) const override {
310 assert(!Args.empty() && "expected the arglist to not be empty!");
311 return Args.size() - 1;
312 }
313
Craig Topper4f12f102014-03-12 06:41:41 +0000314 StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
315 StringRef GetDeletedVirtualCallName() override
316 { return "__cxa_deleted_virtual"; }
Joao Matos2ce88ef2012-07-17 17:10:11 +0000317
Craig Topper4f12f102014-03-12 06:41:41 +0000318 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall7f416cc2015-09-08 08:05:57 +0000319 Address InitializeArrayCookie(CodeGenFunction &CGF,
320 Address NewPtr,
321 llvm::Value *NumElements,
322 const CXXNewExpr *expr,
323 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000324 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000325 Address allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000326 CharUnits cookieSize) override;
John McCall68ff0372010-09-08 01:44:27 +0000327
John McCallcdf7ef52010-11-06 09:44:32 +0000328 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000329 llvm::GlobalVariable *DeclPtr,
330 bool PerformInit) override;
Richard Smithdbf74ba2013-04-14 23:01:42 +0000331 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000332 llvm::Constant *dtor, llvm::Constant *addr) override;
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000333
334 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +0000335 llvm::Value *Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000336 void EmitThreadLocalInitFuncs(
David Majnemerb3341ea2014-10-05 05:05:40 +0000337 CodeGenModule &CGM,
Richard Smith5a99c492015-12-01 01:10:48 +0000338 ArrayRef<const VarDecl *> CXXThreadLocals,
David Majnemerb3341ea2014-10-05 05:05:40 +0000339 ArrayRef<llvm::Function *> CXXThreadLocalInits,
Richard Smith5a99c492015-12-01 01:10:48 +0000340 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) override;
David Majnemerb3341ea2014-10-05 05:05:40 +0000341
342 bool usesThreadWrapperFunction() const override { return true; }
Richard Smith0f383742014-03-26 22:48:22 +0000343 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
344 QualType LValType) override;
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000345
Craig Topper4f12f102014-03-12 06:41:41 +0000346 bool NeedsVTTParameter(GlobalDecl GD) override;
David Majnemere2cb8d12014-07-07 06:20:47 +0000347
348 /**************************** RTTI Uniqueness ******************************/
349
350protected:
351 /// Returns true if the ABI requires RTTI type_info objects to be unique
352 /// across a program.
353 virtual bool shouldRTTIBeUnique() const { return true; }
354
355public:
356 /// What sort of unique-RTTI behavior should we use?
357 enum RTTIUniquenessKind {
358 /// We are guaranteeing, or need to guarantee, that the RTTI string
359 /// is unique.
360 RUK_Unique,
361
362 /// We are not guaranteeing uniqueness for the RTTI string, so we
363 /// can demote to hidden visibility but must use string comparisons.
364 RUK_NonUniqueHidden,
365
366 /// We are not guaranteeing uniqueness for the RTTI string, so we
367 /// have to use string comparisons, but we also have to emit it with
368 /// non-hidden visibility.
369 RUK_NonUniqueVisible
370 };
371
372 /// Return the required visibility status for the given type and linkage in
373 /// the current ABI.
374 RTTIUniquenessKind
375 classifyRTTIUniqueness(QualType CanTy,
376 llvm::GlobalValue::LinkageTypes Linkage) const;
377 friend class ItaniumRTTIBuilder;
Rafael Espindola91f68b42014-09-15 19:20:10 +0000378
379 void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000380
Peter Collingbourne60108802017-12-13 21:53:04 +0000381 std::pair<llvm::Value *, const CXXRecordDecl *>
382 LoadVTablePtr(CodeGenFunction &CGF, Address This,
383 const CXXRecordDecl *RD) override;
384
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000385 private:
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000386 bool hasAnyUnusedVirtualInlineFunction(const CXXRecordDecl *RD) const {
387 const auto &VtableLayout =
388 CGM.getItaniumVTableContext().getVTableLayout(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000389
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000390 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
391 // Skip empty slot.
392 if (!VtableComponent.isUsedFunctionPointerKind())
393 continue;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000394
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000395 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
396 if (!Method->getCanonicalDecl()->isInlined())
397 continue;
398
399 StringRef Name = CGM.getMangledName(VtableComponent.getGlobalDecl());
400 auto *Entry = CGM.GetGlobalValue(Name);
401 // This checks if virtual inline function has already been emitted.
402 // Note that it is possible that this inline function would be emitted
403 // after trying to emit vtable speculatively. Because of this we do
404 // an extra pass after emitting all deferred vtables to find and emit
405 // these vtables opportunistically.
406 if (!Entry || Entry->isDeclaration())
407 return true;
408 }
409 return false;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000410 }
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000411
412 bool isVTableHidden(const CXXRecordDecl *RD) const {
413 const auto &VtableLayout =
414 CGM.getItaniumVTableContext().getVTableLayout(RD);
415
416 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
417 if (VtableComponent.isRTTIKind()) {
418 const CXXRecordDecl *RTTIDecl = VtableComponent.getRTTIDecl();
419 if (RTTIDecl->getVisibility() == Visibility::HiddenVisibility)
420 return true;
421 } else if (VtableComponent.isUsedFunctionPointerKind()) {
422 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
423 if (Method->getVisibility() == Visibility::HiddenVisibility &&
424 !Method->isDefined())
425 return true;
426 }
427 }
428 return false;
429 }
Charles Davis4e786dd2010-05-25 19:52:27 +0000430};
John McCall86353412010-08-21 22:46:04 +0000431
432class ARMCXXABI : public ItaniumCXXABI {
433public:
Mark Seabornedf0d382013-07-24 16:25:13 +0000434 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
435 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
436 /* UseARMGuardVarABI = */ true) {}
John McCall5d865c322010-08-31 07:33:07 +0000437
Craig Topper4f12f102014-03-12 06:41:41 +0000438 bool HasThisReturn(GlobalDecl GD) const override {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000439 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
440 isa<CXXDestructorDecl>(GD.getDecl()) &&
441 GD.getDtorType() != Dtor_Deleting));
442 }
John McCall5d865c322010-08-31 07:33:07 +0000443
Craig Topper4f12f102014-03-12 06:41:41 +0000444 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
445 QualType ResTy) override;
John McCall5d865c322010-08-31 07:33:07 +0000446
Craig Topper4f12f102014-03-12 06:41:41 +0000447 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall7f416cc2015-09-08 08:05:57 +0000448 Address InitializeArrayCookie(CodeGenFunction &CGF,
449 Address NewPtr,
450 llvm::Value *NumElements,
451 const CXXNewExpr *expr,
452 QualType ElementType) override;
453 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, Address allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000454 CharUnits cookieSize) override;
John McCall86353412010-08-21 22:46:04 +0000455};
Tim Northovera2ee4332014-03-29 15:09:45 +0000456
457class iOS64CXXABI : public ARMCXXABI {
458public:
John McCalld23b27e2016-09-16 02:40:45 +0000459 iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {
460 Use32BitVTableOffsetABI = true;
461 }
Tim Northover65f582f2014-03-30 17:32:48 +0000462
463 // ARM64 libraries are prepared for non-unique RTTI.
David Majnemere2cb8d12014-07-07 06:20:47 +0000464 bool shouldRTTIBeUnique() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +0000465};
Dan Gohmanc2853072015-09-03 22:51:53 +0000466
467class WebAssemblyCXXABI final : public ItaniumCXXABI {
468public:
469 explicit WebAssemblyCXXABI(CodeGen::CodeGenModule &CGM)
470 : ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
471 /*UseARMGuardVarABI=*/true) {}
Heejin Ahnc6479192018-05-31 22:18:13 +0000472 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
Dan Gohmanc2853072015-09-03 22:51:53 +0000473
474private:
475 bool HasThisReturn(GlobalDecl GD) const override {
476 return isa<CXXConstructorDecl>(GD.getDecl()) ||
477 (isa<CXXDestructorDecl>(GD.getDecl()) &&
478 GD.getDtorType() != Dtor_Deleting);
479 }
Derek Schuff8179be42016-05-10 17:44:55 +0000480 bool canCallMismatchedFunctionType() const override { return false; }
Dan Gohmanc2853072015-09-03 22:51:53 +0000481};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000482}
Charles Davis4e786dd2010-05-25 19:52:27 +0000483
Charles Davis53c59df2010-08-16 03:33:14 +0000484CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000485 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000486 // For IR-generation purposes, there's no significant difference
487 // between the ARM and iOS ABIs.
488 case TargetCXXABI::GenericARM:
489 case TargetCXXABI::iOS:
Tim Northover756447a2015-10-30 16:30:36 +0000490 case TargetCXXABI::WatchOS:
John McCall57625922013-01-25 23:36:14 +0000491 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000492
Tim Northovera2ee4332014-03-29 15:09:45 +0000493 case TargetCXXABI::iOS64:
494 return new iOS64CXXABI(CGM);
495
Tim Northover9bb857a2013-01-31 12:13:10 +0000496 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
497 // include the other 32-bit ARM oddities: constructor/destructor return values
498 // and array cookies.
499 case TargetCXXABI::GenericAArch64:
Mark Seabornedf0d382013-07-24 16:25:13 +0000500 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
501 /* UseARMGuardVarABI = */ true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000502
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000503 case TargetCXXABI::GenericMIPS:
504 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true);
505
Dan Gohmanc2853072015-09-03 22:51:53 +0000506 case TargetCXXABI::WebAssembly:
507 return new WebAssemblyCXXABI(CGM);
508
John McCall57625922013-01-25 23:36:14 +0000509 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000510 if (CGM.getContext().getTargetInfo().getTriple().getArch()
511 == llvm::Triple::le32) {
512 // For PNaCl, use ARM-style method pointers so that PNaCl code
513 // does not assume anything about the alignment of function
514 // pointers.
515 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
516 /* UseARMGuardVarABI = */ false);
517 }
John McCall57625922013-01-25 23:36:14 +0000518 return new ItaniumCXXABI(CGM);
519
520 case TargetCXXABI::Microsoft:
521 llvm_unreachable("Microsoft ABI is not Itanium-based");
522 }
523 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000524}
525
Chris Lattnera5f58b02011-07-09 17:41:47 +0000526llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000527ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
528 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000529 return CGM.PtrDiffTy;
Serge Guelton1d993272017-05-09 19:31:30 +0000530 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy);
John McCall1c456c82010-08-22 06:43:33 +0000531}
532
John McCalld9c6c0b2010-08-22 00:59:17 +0000533/// In the Itanium and ARM ABIs, method pointers have the form:
534/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
535///
536/// In the Itanium ABI:
537/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
538/// - the this-adjustment is (memptr.adj)
539/// - the virtual offset is (memptr.ptr - 1)
540///
541/// In the ARM ABI:
542/// - method pointers are virtual if (memptr.adj & 1) is nonzero
543/// - the this-adjustment is (memptr.adj >> 1)
544/// - the virtual offset is (memptr.ptr)
545/// ARM uses 'adj' for the virtual flag because Thumb functions
546/// may be only single-byte aligned.
547///
548/// If the member is virtual, the adjusted 'this' pointer points
549/// to a vtable pointer from which the virtual offset is applied.
550///
551/// If the member is non-virtual, memptr.ptr is the address of
552/// the function to call.
John McCallb92ab1a2016-10-26 23:46:34 +0000553CGCallee ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
John McCall7f416cc2015-09-08 08:05:57 +0000554 CodeGenFunction &CGF, const Expr *E, Address ThisAddr,
555 llvm::Value *&ThisPtrForCall,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000556 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
John McCall475999d2010-08-22 00:05:51 +0000557 CGBuilderTy &Builder = CGF.Builder;
558
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000559 const FunctionProtoType *FPT =
John McCall475999d2010-08-22 00:05:51 +0000560 MPT->getPointeeType()->getAs<FunctionProtoType>();
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000561 const CXXRecordDecl *RD =
John McCall475999d2010-08-22 00:05:51 +0000562 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
563
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000564 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(
565 CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr));
John McCall475999d2010-08-22 00:05:51 +0000566
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000567 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000568
John McCalld9c6c0b2010-08-22 00:59:17 +0000569 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
570 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
571 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
572
John McCalla1dee5302010-08-22 10:59:02 +0000573 // Extract memptr.adj, which is in the second field.
574 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000575
576 // Compute the true adjustment.
577 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000578 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000579 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000580
581 // Apply the adjustment and cast back to the original struct type
582 // for consistency.
John McCall7f416cc2015-09-08 08:05:57 +0000583 llvm::Value *This = ThisAddr.getPointer();
John McCalld9c6c0b2010-08-22 00:59:17 +0000584 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
585 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
586 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall7f416cc2015-09-08 08:05:57 +0000587 ThisPtrForCall = This;
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000588
John McCall475999d2010-08-22 00:05:51 +0000589 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000590 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000591
John McCall475999d2010-08-22 00:05:51 +0000592 // If the LSB in the function pointer is 1, the function pointer points to
593 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000594 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000595 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000596 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
597 else
598 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
599 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000600 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
601
602 // In the virtual path, the adjustment left 'This' pointing to the
603 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000604 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000605 CGF.EmitBlock(FnVirtual);
606
607 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000608 llvm::Type *VTableTy = Builder.getInt8PtrTy();
John McCall7f416cc2015-09-08 08:05:57 +0000609 CharUnits VTablePtrAlign =
610 CGF.CGM.getDynamicOffsetAlignment(ThisAddr.getAlignment(), RD,
611 CGF.getPointerAlign());
612 llvm::Value *VTable =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000613 CGF.GetVTablePtr(Address(This, VTablePtrAlign), VTableTy, RD);
John McCall475999d2010-08-22 00:05:51 +0000614
615 // Apply the offset.
John McCalld23b27e2016-09-16 02:40:45 +0000616 // On ARM64, to reserve extra space in virtual member function pointers,
617 // we only pay attention to the low 32 bits of the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000618 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000619 if (!UseARMMethodPtrABI)
620 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld23b27e2016-09-16 02:40:45 +0000621 if (Use32BitVTableOffsetABI) {
622 VTableOffset = Builder.CreateTrunc(VTableOffset, CGF.Int32Ty);
623 VTableOffset = Builder.CreateZExt(VTableOffset, CGM.PtrDiffTy);
624 }
John McCalld9c6c0b2010-08-22 00:59:17 +0000625 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall475999d2010-08-22 00:05:51 +0000626
627 // Load the virtual function to call.
628 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCall7f416cc2015-09-08 08:05:57 +0000629 llvm::Value *VirtualFn =
630 Builder.CreateAlignedLoad(VTable, CGF.getPointerAlign(),
631 "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000632 CGF.EmitBranch(FnEnd);
633
634 // In the non-virtual path, the function pointer is actually a
635 // function pointer.
636 CGF.EmitBlock(FnNonVirtual);
637 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000638 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000639
John McCall475999d2010-08-22 00:05:51 +0000640 // We're done.
641 CGF.EmitBlock(FnEnd);
John McCallb92ab1a2016-10-26 23:46:34 +0000642 llvm::PHINode *CalleePtr = Builder.CreatePHI(FTy->getPointerTo(), 2);
643 CalleePtr->addIncoming(VirtualFn, FnVirtual);
644 CalleePtr->addIncoming(NonVirtualFn, FnNonVirtual);
645
646 CGCallee Callee(FPT, CalleePtr);
John McCall475999d2010-08-22 00:05:51 +0000647 return Callee;
648}
John McCalla8bbb822010-08-22 03:04:22 +0000649
John McCallc134eb52010-08-31 21:07:20 +0000650/// Compute an l-value by applying the given pointer-to-member to a
651/// base object.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000652llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
John McCall7f416cc2015-09-08 08:05:57 +0000653 CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000654 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000655 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000656
657 CGBuilderTy &Builder = CGF.Builder;
658
John McCallc134eb52010-08-31 21:07:20 +0000659 // Cast to char*.
John McCall7f416cc2015-09-08 08:05:57 +0000660 Base = Builder.CreateElementBitCast(Base, CGF.Int8Ty);
John McCallc134eb52010-08-31 21:07:20 +0000661
662 // Apply the offset, which we assume is non-null.
John McCall7f416cc2015-09-08 08:05:57 +0000663 llvm::Value *Addr =
664 Builder.CreateInBoundsGEP(Base.getPointer(), MemPtr, "memptr.offset");
John McCallc134eb52010-08-31 21:07:20 +0000665
666 // Cast the address to the appropriate pointer type, adopting the
667 // address space of the base pointer.
John McCall7f416cc2015-09-08 08:05:57 +0000668 llvm::Type *PType = CGF.ConvertTypeForMem(MPT->getPointeeType())
669 ->getPointerTo(Base.getAddressSpace());
John McCallc134eb52010-08-31 21:07:20 +0000670 return Builder.CreateBitCast(Addr, PType);
671}
672
John McCallc62bb392012-02-15 01:22:51 +0000673/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
674/// conversion.
675///
676/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000677///
678/// Obligatory offset/adjustment diagram:
679/// <-- offset --> <-- adjustment -->
680/// |--------------------------|----------------------|--------------------|
681/// ^Derived address point ^Base address point ^Member address point
682///
683/// So when converting a base member pointer to a derived member pointer,
684/// we add the offset to the adjustment because the address point has
685/// decreased; and conversely, when converting a derived MP to a base MP
686/// we subtract the offset from the adjustment because the address point
687/// has increased.
688///
689/// The standard forbids (at compile time) conversion to and from
690/// virtual bases, which is why we don't have to consider them here.
691///
692/// The standard forbids (at run time) casting a derived MP to a base
693/// MP when the derived MP does not point to a member of the base.
694/// This is why -1 is a reasonable choice for null data member
695/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000696llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000697ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
698 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000699 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000700 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000701 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
702 E->getCastKind() == CK_ReinterpretMemberPointer);
703
704 // Under Itanium, reinterprets don't require any additional processing.
705 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
706
707 // Use constant emission if we can.
708 if (isa<llvm::Constant>(src))
709 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
710
711 llvm::Constant *adj = getMemberPointerAdjustment(E);
712 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000713
714 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000715 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000716
John McCallc62bb392012-02-15 01:22:51 +0000717 const MemberPointerType *destTy =
718 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000719
John McCall7a9aac22010-08-23 01:21:21 +0000720 // For member data pointers, this is just a matter of adding the
721 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000722 if (destTy->isMemberDataPointer()) {
723 llvm::Value *dst;
724 if (isDerivedToBase)
725 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000726 else
John McCallc62bb392012-02-15 01:22:51 +0000727 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000728
729 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000730 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
731 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
732 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000733 }
734
John McCalla1dee5302010-08-22 10:59:02 +0000735 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000736 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000737 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
738 offset <<= 1;
739 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000740 }
741
John McCallc62bb392012-02-15 01:22:51 +0000742 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
743 llvm::Value *dstAdj;
744 if (isDerivedToBase)
745 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000746 else
John McCallc62bb392012-02-15 01:22:51 +0000747 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000748
John McCallc62bb392012-02-15 01:22:51 +0000749 return Builder.CreateInsertValue(src, dstAdj, 1);
750}
751
752llvm::Constant *
753ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
754 llvm::Constant *src) {
755 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
756 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
757 E->getCastKind() == CK_ReinterpretMemberPointer);
758
759 // Under Itanium, reinterprets don't require any additional processing.
760 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
761
762 // If the adjustment is trivial, we don't need to do anything.
763 llvm::Constant *adj = getMemberPointerAdjustment(E);
764 if (!adj) return src;
765
766 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
767
768 const MemberPointerType *destTy =
769 E->getType()->castAs<MemberPointerType>();
770
771 // For member data pointers, this is just a matter of adding the
772 // offset if the source is non-null.
773 if (destTy->isMemberDataPointer()) {
774 // null maps to null.
775 if (src->isAllOnesValue()) return src;
776
777 if (isDerivedToBase)
778 return llvm::ConstantExpr::getNSWSub(src, adj);
779 else
780 return llvm::ConstantExpr::getNSWAdd(src, adj);
781 }
782
783 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000784 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000785 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
786 offset <<= 1;
787 adj = llvm::ConstantInt::get(adj->getType(), offset);
788 }
789
790 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
791 llvm::Constant *dstAdj;
792 if (isDerivedToBase)
793 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
794 else
795 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
796
797 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000798}
John McCall84fa5102010-08-22 04:16:24 +0000799
800llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000801ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000802 // Itanium C++ ABI 2.3:
803 // A NULL pointer is represented as -1.
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000804 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000805 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000806
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000807 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000808 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000809 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000810}
811
John McCallf3a88602011-02-03 08:15:49 +0000812llvm::Constant *
813ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
814 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000815 // Itanium C++ ABI 2.3:
816 // A pointer to data member is an offset from the base address of
817 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000818 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000819}
820
David Majnemere2be95b2015-06-23 07:31:01 +0000821llvm::Constant *
822ItaniumCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000823 return BuildMemberPointer(MD, CharUnits::Zero());
824}
825
826llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
827 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000828 assert(MD->isInstance() && "Member function must not be static!");
John McCalla1dee5302010-08-22 10:59:02 +0000829
830 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000831
832 // Get the function pointer (or index if this is a virtual function).
833 llvm::Constant *MemPtr[2];
834 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000835 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000836
Ken Dyckdf016282011-04-09 01:30:02 +0000837 const ASTContext &Context = getContext();
838 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000839 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000840 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000841
Mark Seabornedf0d382013-07-24 16:25:13 +0000842 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000843 // ARM C++ ABI 3.2.1:
844 // This ABI specifies that adj contains twice the this
845 // adjustment, plus 1 if the member function is virtual. The
846 // least significant bit of adj then makes exactly the same
847 // discrimination as the least significant bit of ptr does for
848 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000849 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
850 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000851 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000852 } else {
853 // Itanium C++ ABI 2.3:
854 // For a virtual function, [the pointer field] is 1 plus the
855 // virtual table offset (in bytes) of the function,
856 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000857 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
858 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000859 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000860 }
861 } else {
John McCall2979fe02011-04-12 00:42:48 +0000862 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000863 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000864 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000865 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000866 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000867 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000868 } else {
John McCall2979fe02011-04-12 00:42:48 +0000869 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
870 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000871 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000872 }
John McCall2979fe02011-04-12 00:42:48 +0000873 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000874
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000875 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000876 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
877 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000878 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000879 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000880
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000881 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000882}
883
Richard Smithdafff942012-01-14 04:30:29 +0000884llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
885 QualType MPType) {
886 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
887 const ValueDecl *MPD = MP.getMemberPointerDecl();
888 if (!MPD)
889 return EmitNullMemberPointer(MPT);
890
Reid Kleckner452abac2013-05-09 21:01:17 +0000891 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000892
893 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
894 return BuildMemberPointer(MD, ThisAdjustment);
895
896 CharUnits FieldOffset =
897 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
898 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
899}
900
John McCall131d97d2010-08-22 08:30:07 +0000901/// The comparison algorithm is pretty easy: the member pointers are
902/// the same if they're either bitwise identical *or* both null.
903///
904/// ARM is different here only because null-ness is more complicated.
905llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000906ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
907 llvm::Value *L,
908 llvm::Value *R,
909 const MemberPointerType *MPT,
910 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000911 CGBuilderTy &Builder = CGF.Builder;
912
John McCall131d97d2010-08-22 08:30:07 +0000913 llvm::ICmpInst::Predicate Eq;
914 llvm::Instruction::BinaryOps And, Or;
915 if (Inequality) {
916 Eq = llvm::ICmpInst::ICMP_NE;
917 And = llvm::Instruction::Or;
918 Or = llvm::Instruction::And;
919 } else {
920 Eq = llvm::ICmpInst::ICMP_EQ;
921 And = llvm::Instruction::And;
922 Or = llvm::Instruction::Or;
923 }
924
John McCall7a9aac22010-08-23 01:21:21 +0000925 // Member data pointers are easy because there's a unique null
926 // value, so it just comes down to bitwise equality.
927 if (MPT->isMemberDataPointer())
928 return Builder.CreateICmp(Eq, L, R);
929
930 // For member function pointers, the tautologies are more complex.
931 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000932 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000933 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000934 // (L == R) <==> (L.ptr == R.ptr &&
935 // (L.adj == R.adj ||
936 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000937 // The inequality tautologies have exactly the same structure, except
938 // applying De Morgan's laws.
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000939
John McCall7a9aac22010-08-23 01:21:21 +0000940 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
941 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
942
John McCall131d97d2010-08-22 08:30:07 +0000943 // This condition tests whether L.ptr == R.ptr. This must always be
944 // true for equality to hold.
945 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
946
947 // This condition, together with the assumption that L.ptr == R.ptr,
948 // tests whether the pointers are both null. ARM imposes an extra
949 // condition.
950 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
951 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
952
953 // This condition tests whether L.adj == R.adj. If this isn't
954 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +0000955 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
956 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000957 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
958
959 // Null member function pointers on ARM clear the low bit of Adj,
960 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000961 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000962 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
963
964 // Compute (l.adj | r.adj) & 1 and test it against zero.
965 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
966 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
967 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
968 "cmp.or.adj");
969 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
970 }
971
972 // Tie together all our conditions.
973 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
974 Result = Builder.CreateBinOp(And, PtrEq, Result,
975 Inequality ? "memptr.ne" : "memptr.eq");
976 return Result;
977}
978
979llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000980ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
981 llvm::Value *MemPtr,
982 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +0000983 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +0000984
985 /// For member data pointers, this is just a check against -1.
986 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000987 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +0000988 llvm::Value *NegativeOne =
989 llvm::Constant::getAllOnesValue(MemPtr->getType());
990 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
991 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000992
Daniel Dunbar914bc412011-04-19 23:10:47 +0000993 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +0000994 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +0000995
996 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
997 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
998
Daniel Dunbar914bc412011-04-19 23:10:47 +0000999 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
1000 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +00001001 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +00001002 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +00001003 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +00001004 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +00001005 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
1006 "memptr.isvirtual");
1007 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +00001008 }
1009
1010 return Result;
1011}
John McCall1c456c82010-08-22 06:43:33 +00001012
Reid Kleckner40ca9132014-05-13 22:05:45 +00001013bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
1014 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
1015 if (!RD)
1016 return false;
1017
Richard Smith96cd6712017-08-16 01:49:53 +00001018 // If C++ prohibits us from making a copy, return by address.
Richard Smithf667ad52017-08-26 01:04:35 +00001019 if (passClassIndirect(RD)) {
John McCall7f416cc2015-09-08 08:05:57 +00001020 auto Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
1021 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
Reid Kleckner40ca9132014-05-13 22:05:45 +00001022 return true;
1023 }
Reid Kleckner40ca9132014-05-13 22:05:45 +00001024 return false;
1025}
1026
John McCall614dbdc2010-08-22 21:01:12 +00001027/// The Itanium ABI requires non-zero initialization only for data
1028/// member pointers, for which '0' is a valid offset.
1029bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
David Majnemer5fd33e02015-04-24 01:25:08 +00001030 return MPT->isMemberFunctionPointer();
John McCall84fa5102010-08-22 04:16:24 +00001031}
John McCall5d865c322010-08-31 07:33:07 +00001032
John McCall82fb8922012-09-25 10:10:39 +00001033/// The Itanium ABI always places an offset to the complete object
1034/// at entry -2 in the vtable.
David Majnemer08681372014-11-01 07:37:17 +00001035void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
1036 const CXXDeleteExpr *DE,
John McCall7f416cc2015-09-08 08:05:57 +00001037 Address Ptr,
David Majnemer08681372014-11-01 07:37:17 +00001038 QualType ElementType,
1039 const CXXDestructorDecl *Dtor) {
1040 bool UseGlobalDelete = DE->isGlobalDelete();
David Majnemer0c0b6d92014-10-31 20:09:12 +00001041 if (UseGlobalDelete) {
1042 // Derive the complete-object pointer, which is what we need
1043 // to pass to the deallocation function.
John McCall82fb8922012-09-25 10:10:39 +00001044
David Majnemer0c0b6d92014-10-31 20:09:12 +00001045 // Grab the vtable pointer as an intptr_t*.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001046 auto *ClassDecl =
1047 cast<CXXRecordDecl>(ElementType->getAs<RecordType>()->getDecl());
1048 llvm::Value *VTable =
1049 CGF.GetVTablePtr(Ptr, CGF.IntPtrTy->getPointerTo(), ClassDecl);
John McCall82fb8922012-09-25 10:10:39 +00001050
David Majnemer0c0b6d92014-10-31 20:09:12 +00001051 // Track back to entry -2 and pull out the offset there.
1052 llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
1053 VTable, -2, "complete-offset.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001054 llvm::Value *Offset =
1055 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
David Majnemer0c0b6d92014-10-31 20:09:12 +00001056
1057 // Apply the offset.
John McCall7f416cc2015-09-08 08:05:57 +00001058 llvm::Value *CompletePtr =
1059 CGF.Builder.CreateBitCast(Ptr.getPointer(), CGF.Int8PtrTy);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001060 CompletePtr = CGF.Builder.CreateInBoundsGEP(CompletePtr, Offset);
1061
1062 // If we're supposed to call the global delete, make sure we do so
1063 // even if the destructor throws.
David Majnemer08681372014-11-01 07:37:17 +00001064 CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr,
1065 ElementType);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001066 }
1067
1068 // FIXME: Provide a source location here even though there's no
1069 // CXXMemberCallExpr for dtor call.
1070 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
1071 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr);
1072
1073 if (UseGlobalDelete)
1074 CGF.PopCleanupBlock();
John McCall82fb8922012-09-25 10:10:39 +00001075}
1076
David Majnemer442d0a22014-11-25 07:20:20 +00001077void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
1078 // void __cxa_rethrow();
1079
1080 llvm::FunctionType *FTy =
1081 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
1082
1083 llvm::Constant *Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
1084
1085 if (isNoReturn)
1086 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, None);
1087 else
1088 CGF.EmitRuntimeCallOrInvoke(Fn);
1089}
1090
David Majnemer7c237072015-03-05 00:46:22 +00001091static llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) {
1092 // void *__cxa_allocate_exception(size_t thrown_size);
1093
1094 llvm::FunctionType *FTy =
1095 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false);
1096
1097 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
1098}
1099
1100static llvm::Constant *getThrowFn(CodeGenModule &CGM) {
1101 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
1102 // void (*dest) (void *));
1103
1104 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
1105 llvm::FunctionType *FTy =
1106 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
1107
1108 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
1109}
1110
1111void ItaniumCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
1112 QualType ThrowType = E->getSubExpr()->getType();
1113 // Now allocate the exception object.
1114 llvm::Type *SizeTy = CGF.ConvertType(getContext().getSizeType());
1115 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
1116
1117 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM);
1118 llvm::CallInst *ExceptionPtr = CGF.EmitNounwindRuntimeCall(
1119 AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception");
1120
John McCall7f416cc2015-09-08 08:05:57 +00001121 CharUnits ExnAlign = getAlignmentOfExnObject();
1122 CGF.EmitAnyExprToExn(E->getSubExpr(), Address(ExceptionPtr, ExnAlign));
David Majnemer7c237072015-03-05 00:46:22 +00001123
1124 // Now throw the exception.
1125 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
1126 /*ForEH=*/true);
1127
1128 // The address of the destructor. If the exception type has a
1129 // trivial destructor (or isn't a record), we just pass null.
1130 llvm::Constant *Dtor = nullptr;
1131 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
1132 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
1133 if (!Record->hasTrivialDestructor()) {
1134 CXXDestructorDecl *DtorD = Record->getDestructor();
1135 Dtor = CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete);
1136 Dtor = llvm::ConstantExpr::getBitCast(Dtor, CGM.Int8PtrTy);
1137 }
1138 }
1139 if (!Dtor) Dtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
1140
1141 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
1142 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
1143}
1144
David Majnemer1162d252014-06-22 19:05:33 +00001145static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) {
1146 // void *__dynamic_cast(const void *sub,
1147 // const abi::__class_type_info *src,
1148 // const abi::__class_type_info *dst,
1149 // std::ptrdiff_t src2dst_offset);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00001150
David Majnemer1162d252014-06-22 19:05:33 +00001151 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
Jake Ehrlichc451cf22017-11-11 01:15:41 +00001152 llvm::Type *PtrDiffTy =
David Majnemer1162d252014-06-22 19:05:33 +00001153 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1154
1155 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
1156
1157 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
1158
1159 // Mark the function as nounwind readonly.
1160 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
1161 llvm::Attribute::ReadOnly };
Reid Klecknerde864822017-03-21 16:57:30 +00001162 llvm::AttributeList Attrs = llvm::AttributeList::get(
1163 CGF.getLLVMContext(), llvm::AttributeList::FunctionIndex, FuncAttrs);
David Majnemer1162d252014-06-22 19:05:33 +00001164
1165 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
1166}
1167
1168static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1169 // void __cxa_bad_cast();
1170 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1171 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1172}
1173
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001174/// Compute the src2dst_offset hint as described in the
David Majnemer1162d252014-06-22 19:05:33 +00001175/// Itanium C++ ABI [2.9.7]
1176static CharUnits computeOffsetHint(ASTContext &Context,
1177 const CXXRecordDecl *Src,
1178 const CXXRecordDecl *Dst) {
1179 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1180 /*DetectVirtual=*/false);
1181
1182 // If Dst is not derived from Src we can skip the whole computation below and
1183 // return that Src is not a public base of Dst. Record all inheritance paths.
1184 if (!Dst->isDerivedFrom(Src, Paths))
1185 return CharUnits::fromQuantity(-2ULL);
1186
1187 unsigned NumPublicPaths = 0;
1188 CharUnits Offset;
1189
1190 // Now walk all possible inheritance paths.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001191 for (const CXXBasePath &Path : Paths) {
1192 if (Path.Access != AS_public) // Ignore non-public inheritance.
David Majnemer1162d252014-06-22 19:05:33 +00001193 continue;
1194
1195 ++NumPublicPaths;
1196
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001197 for (const CXXBasePathElement &PathElement : Path) {
David Majnemer1162d252014-06-22 19:05:33 +00001198 // If the path contains a virtual base class we can't give any hint.
1199 // -1: no hint.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001200 if (PathElement.Base->isVirtual())
David Majnemer1162d252014-06-22 19:05:33 +00001201 return CharUnits::fromQuantity(-1ULL);
1202
1203 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
1204 continue;
1205
1206 // Accumulate the base class offsets.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001207 const ASTRecordLayout &L = Context.getASTRecordLayout(PathElement.Class);
1208 Offset += L.getBaseClassOffset(
1209 PathElement.Base->getType()->getAsCXXRecordDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001210 }
1211 }
1212
1213 // -2: Src is not a public base of Dst.
1214 if (NumPublicPaths == 0)
1215 return CharUnits::fromQuantity(-2ULL);
1216
1217 // -3: Src is a multiple public base type but never a virtual base type.
1218 if (NumPublicPaths > 1)
1219 return CharUnits::fromQuantity(-3ULL);
1220
1221 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
1222 // Return the offset of Src from the origin of Dst.
1223 return Offset;
1224}
1225
1226static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1227 // void __cxa_bad_typeid();
1228 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1229
1230 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1231}
1232
1233bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
1234 QualType SrcRecordTy) {
1235 return IsDeref;
1236}
1237
1238void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
1239 llvm::Value *Fn = getBadTypeidFn(CGF);
1240 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1241 CGF.Builder.CreateUnreachable();
1242}
1243
1244llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
1245 QualType SrcRecordTy,
John McCall7f416cc2015-09-08 08:05:57 +00001246 Address ThisPtr,
David Majnemer1162d252014-06-22 19:05:33 +00001247 llvm::Type *StdTypeInfoPtrTy) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001248 auto *ClassDecl =
1249 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001250 llvm::Value *Value =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001251 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo(), ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001252
1253 // Load the type info.
1254 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001255 return CGF.Builder.CreateAlignedLoad(Value, CGF.getPointerAlign());
David Majnemer1162d252014-06-22 19:05:33 +00001256}
1257
1258bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1259 QualType SrcRecordTy) {
1260 return SrcIsPtr;
1261}
1262
1263llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
John McCall7f416cc2015-09-08 08:05:57 +00001264 CodeGenFunction &CGF, Address ThisAddr, QualType SrcRecordTy,
David Majnemer1162d252014-06-22 19:05:33 +00001265 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1266 llvm::Type *PtrDiffLTy =
1267 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1268 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1269
1270 llvm::Value *SrcRTTI =
1271 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1272 llvm::Value *DestRTTI =
1273 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1274
1275 // Compute the offset hint.
1276 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1277 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1278 llvm::Value *OffsetHint = llvm::ConstantInt::get(
1279 PtrDiffLTy,
1280 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
1281
1282 // Emit the call to __dynamic_cast.
John McCall7f416cc2015-09-08 08:05:57 +00001283 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001284 Value = CGF.EmitCastToVoidPtr(Value);
1285
1286 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
1287 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
1288 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1289
1290 /// C++ [expr.dynamic.cast]p9:
1291 /// A failed cast to reference type throws std::bad_cast
1292 if (DestTy->isReferenceType()) {
1293 llvm::BasicBlock *BadCastBlock =
1294 CGF.createBasicBlock("dynamic_cast.bad_cast");
1295
1296 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1297 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1298
1299 CGF.EmitBlock(BadCastBlock);
1300 EmitBadCastCall(CGF);
1301 }
1302
1303 return Value;
1304}
1305
1306llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001307 Address ThisAddr,
David Majnemer1162d252014-06-22 19:05:33 +00001308 QualType SrcRecordTy,
1309 QualType DestTy) {
1310 llvm::Type *PtrDiffLTy =
1311 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1312 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1313
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001314 auto *ClassDecl =
1315 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001316 // Get the vtable pointer.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001317 llvm::Value *VTable = CGF.GetVTablePtr(ThisAddr, PtrDiffLTy->getPointerTo(),
1318 ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001319
1320 // Get the offset-to-top from the vtable.
1321 llvm::Value *OffsetToTop =
1322 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001323 OffsetToTop =
1324 CGF.Builder.CreateAlignedLoad(OffsetToTop, CGF.getPointerAlign(),
1325 "offset.to.top");
David Majnemer1162d252014-06-22 19:05:33 +00001326
1327 // Finally, add the offset to the pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001328 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001329 Value = CGF.EmitCastToVoidPtr(Value);
1330 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1331
1332 return CGF.Builder.CreateBitCast(Value, DestLTy);
1333}
1334
1335bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1336 llvm::Value *Fn = getBadCastFn(CGF);
1337 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1338 CGF.Builder.CreateUnreachable();
1339 return true;
1340}
1341
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001342llvm::Value *
1343ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001344 Address This,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001345 const CXXRecordDecl *ClassDecl,
1346 const CXXRecordDecl *BaseClassDecl) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001347 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy, ClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001348 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001349 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1350 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001351
1352 llvm::Value *VBaseOffsetPtr =
1353 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1354 "vbase.offset.ptr");
1355 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1356 CGM.PtrDiffTy->getPointerTo());
1357
1358 llvm::Value *VBaseOffset =
John McCall7f416cc2015-09-08 08:05:57 +00001359 CGF.Builder.CreateAlignedLoad(VBaseOffsetPtr, CGF.getPointerAlign(),
1360 "vbase.offset");
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001361
1362 return VBaseOffset;
1363}
1364
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001365void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1366 // Just make sure we're in sync with TargetCXXABI.
1367 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1368
Rafael Espindolac3cde362013-12-09 14:51:17 +00001369 // The constructor used for constructing this as a base class;
1370 // ignores virtual bases.
1371 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1372
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001373 // The constructor used for constructing this as a complete class;
Nico Weber4c2ffb22015-01-07 05:25:05 +00001374 // constructs the virtual bases, then calls the base constructor.
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001375 if (!D->getParent()->isAbstract()) {
1376 // We don't need to emit the complete ctor if the class is abstract.
1377 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1378 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001379}
1380
George Burgess IVf203dbf2017-02-22 20:28:02 +00001381CGCXXABI::AddedStructorArgs
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001382ItaniumCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
1383 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +00001384 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001385
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001386 // All parameters are already in place except VTT, which goes after 'this'.
1387 // These are Clang types, so we don't need to worry about sret yet.
John McCall5d865c322010-08-31 07:33:07 +00001388
1389 // Check if we need to add a VTT parameter (which has type void **).
George Burgess IVf203dbf2017-02-22 20:28:02 +00001390 if (T == StructorType::Base && MD->getParent()->getNumVBases() != 0) {
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001391 ArgTys.insert(ArgTys.begin() + 1,
1392 Context.getPointerType(Context.VoidPtrTy));
George Burgess IVf203dbf2017-02-22 20:28:02 +00001393 return AddedStructorArgs::prefix(1);
1394 }
1395 return AddedStructorArgs{};
John McCall5d865c322010-08-31 07:33:07 +00001396}
1397
Reid Klecknere7de47e2013-07-22 13:51:44 +00001398void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
Rafael Espindolac3cde362013-12-09 14:51:17 +00001399 // The destructor used for destructing this as a base class; ignores
1400 // virtual bases.
1401 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001402
1403 // The destructor used for destructing this as a most-derived class;
1404 // call the base destructor and then destructs any virtual bases.
1405 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1406
Rafael Espindolac3cde362013-12-09 14:51:17 +00001407 // The destructor in a virtual table is always a 'deleting'
1408 // destructor, which calls the complete destructor and then uses the
1409 // appropriate operator delete.
1410 if (D->isVirtual())
1411 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001412}
1413
Reid Kleckner89077a12013-12-17 19:46:40 +00001414void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1415 QualType &ResTy,
1416 FunctionArgList &Params) {
John McCall5d865c322010-08-31 07:33:07 +00001417 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +00001418 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
John McCall5d865c322010-08-31 07:33:07 +00001419
1420 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001421 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +00001422 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001423
1424 // FIXME: avoid the fake decl
1425 QualType T = Context.getPointerType(Context.VoidPtrTy);
Alexey Bataev56223232017-06-09 13:40:18 +00001426 auto *VTTDecl = ImplicitParamDecl::Create(
1427 Context, /*DC=*/nullptr, MD->getLocation(), &Context.Idents.get("vtt"),
1428 T, ImplicitParamDecl::CXXVTT);
Reid Kleckner89077a12013-12-17 19:46:40 +00001429 Params.insert(Params.begin() + 1, VTTDecl);
Reid Kleckner2af6d732013-12-13 00:09:59 +00001430 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +00001431 }
1432}
1433
John McCall5d865c322010-08-31 07:33:07 +00001434void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
Justin Lebared4f1722016-07-27 22:04:24 +00001435 // Naked functions have no prolog.
1436 if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>())
1437 return;
1438
Reid Kleckner06239e42017-11-16 19:09:36 +00001439 /// Initialize the 'this' slot. In the Itanium C++ ABI, no prologue
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001440 /// adjustments are required, because they are all handled by thunks.
Reid Kleckner06239e42017-11-16 19:09:36 +00001441 setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));
John McCall5d865c322010-08-31 07:33:07 +00001442
1443 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +00001444 if (getStructorImplicitParamDecl(CGF)) {
1445 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1446 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +00001447 }
John McCall5d865c322010-08-31 07:33:07 +00001448
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001449 /// If this is a function that the ABI specifies returns 'this', initialize
1450 /// the return slot to 'this' at the start of the function.
1451 ///
1452 /// Unlike the setting of return types, this is done within the ABI
1453 /// implementation instead of by clients of CGCXXABI because:
1454 /// 1) getThisValue is currently protected
1455 /// 2) in theory, an ABI could implement 'this' returns some other way;
1456 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +00001457 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +00001458 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +00001459}
1460
George Burgess IVf203dbf2017-02-22 20:28:02 +00001461CGCXXABI::AddedStructorArgs ItaniumCXXABI::addImplicitConstructorArgs(
Reid Kleckner89077a12013-12-17 19:46:40 +00001462 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1463 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1464 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
George Burgess IVf203dbf2017-02-22 20:28:02 +00001465 return AddedStructorArgs{};
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001466
Reid Kleckner89077a12013-12-17 19:46:40 +00001467 // Insert the implicit 'vtt' argument as the second argument.
1468 llvm::Value *VTT =
1469 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1470 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
Yaxun Liu5b330e82018-03-15 15:25:19 +00001471 Args.insert(Args.begin() + 1, CallArg(RValue::get(VTT), VTTTy));
George Burgess IVf203dbf2017-02-22 20:28:02 +00001472 return AddedStructorArgs::prefix(1); // Added one arg.
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001473}
1474
1475void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1476 const CXXDestructorDecl *DD,
1477 CXXDtorType Type, bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +00001478 bool Delegating, Address This) {
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001479 GlobalDecl GD(DD, Type);
1480 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1481 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1482
John McCallb92ab1a2016-10-26 23:46:34 +00001483 CGCallee Callee;
1484 if (getContext().getLangOpts().AppleKext &&
1485 Type != Dtor_Base && DD->isVirtual())
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001486 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
John McCallb92ab1a2016-10-26 23:46:34 +00001487 else
1488 Callee =
1489 CGCallee::forDirect(CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type)),
1490 DD);
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001491
John McCall7f416cc2015-09-08 08:05:57 +00001492 CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(),
Richard Smith762672a2016-09-28 19:09:10 +00001493 This.getPointer(), VTT, VTTTy,
1494 nullptr, nullptr);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001495}
1496
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001497void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1498 const CXXRecordDecl *RD) {
1499 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1500 if (VTable->hasInitializer())
1501 return;
1502
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001503 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001504 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1505 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
David Majnemerd905da42014-07-01 20:30:31 +00001506 llvm::Constant *RTTI =
1507 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001508
1509 // Create and set the initializer.
John McCall9c6cb762016-11-28 22:18:33 +00001510 ConstantInitBuilder Builder(CGM);
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001511 auto Components = Builder.beginStruct();
John McCall9c6cb762016-11-28 22:18:33 +00001512 CGVT.createVTableInitializer(Components, VTLayout, RTTI);
1513 Components.finishAndSetAsInitializer(VTable);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001514
1515 // Set the correct linkage.
1516 VTable->setLinkage(Linkage);
1517
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001518 if (CGM.supportsCOMDAT() && VTable->isWeakForLinker())
1519 VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName()));
Rafael Espindolacb92c192015-01-15 23:18:01 +00001520
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001521 // Set the right visibility.
Rafael Espindola699f5d62018-02-07 22:15:33 +00001522 CGM.setGVProperties(VTable, RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001523
Benjamin Kramer5d34a2b2014-09-10 12:50:59 +00001524 // Use pointer alignment for the vtable. Otherwise we would align them based
1525 // on the size of the initializer which doesn't make sense as only single
1526 // values are read.
1527 unsigned PAlign = CGM.getTarget().getPointerAlign(0);
1528 VTable->setAlignment(getContext().toCharUnitsFromBits(PAlign).getQuantity());
1529
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001530 // If this is the magic class __cxxabiv1::__fundamental_type_info,
1531 // we will emit the typeinfo for the fundamental types. This is the
1532 // same behaviour as GCC.
1533 const DeclContext *DC = RD->getDeclContext();
1534 if (RD->getIdentifier() &&
1535 RD->getIdentifier()->isStr("__fundamental_type_info") &&
1536 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1537 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1538 DC->getParent()->isTranslationUnit())
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00001539 EmitFundamentalRTTIDescriptors(RD->hasAttr<DLLExportAttr>());
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001540
Evgeniy Stepanov93987df2016-01-23 01:20:18 +00001541 if (!VTable->isDeclarationForLinker())
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001542 CGM.EmitVTableTypeMetadata(VTable, VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001543}
1544
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001545bool ItaniumCXXABI::isVirtualOffsetNeededForVTableField(
1546 CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
1547 if (Vptr.NearestVBase == nullptr)
1548 return false;
1549 return NeedsVTTParameter(CGF.CurGD);
Piotr Padlewski255652e2015-09-09 22:20:28 +00001550}
1551
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001552llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1553 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1554 const CXXRecordDecl *NearestVBase) {
1555
1556 if ((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1557 NeedsVTTParameter(CGF.CurGD)) {
1558 return getVTableAddressPointInStructorWithVTT(CGF, VTableClass, Base,
1559 NearestVBase);
1560 }
1561 return getVTableAddressPoint(Base, VTableClass);
1562}
1563
1564llvm::Constant *
1565ItaniumCXXABI::getVTableAddressPoint(BaseSubobject Base,
1566 const CXXRecordDecl *VTableClass) {
1567 llvm::GlobalValue *VTable = getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001568
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001569 // Find the appropriate vtable within the vtable group, and the address point
1570 // within that vtable.
1571 VTableLayout::AddressPointLocation AddressPoint =
1572 CGM.getItaniumVTableContext()
1573 .getVTableLayout(VTableClass)
1574 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001575 llvm::Value *Indices[] = {
Peter Collingbourne4e6a5402016-03-14 19:07:10 +00001576 llvm::ConstantInt::get(CGM.Int32Ty, 0),
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001577 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.VTableIndex),
1578 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.AddressPointIndex),
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001579 };
1580
Peter Collingbourne25a2b702016-12-13 20:50:44 +00001581 return llvm::ConstantExpr::getGetElementPtr(VTable->getValueType(), VTable,
1582 Indices, /*InBounds=*/true,
1583 /*InRangeIndex=*/1);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001584}
1585
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001586llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructorWithVTT(
1587 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1588 const CXXRecordDecl *NearestVBase) {
1589 assert((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1590 NeedsVTTParameter(CGF.CurGD) && "This class doesn't have VTT");
1591
1592 // Get the secondary vpointer index.
1593 uint64_t VirtualPointerIndex =
1594 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1595
1596 /// Load the VTT.
1597 llvm::Value *VTT = CGF.LoadCXXVTT();
1598 if (VirtualPointerIndex)
1599 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1600
1601 // And load the address point from the VTT.
1602 return CGF.Builder.CreateAlignedLoad(VTT, CGF.getPointerAlign());
1603}
1604
1605llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1606 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1607 return getVTableAddressPoint(Base, VTableClass);
1608}
1609
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001610llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1611 CharUnits VPtrOffset) {
1612 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1613
1614 llvm::GlobalVariable *&VTable = VTables[RD];
1615 if (VTable)
1616 return VTable;
1617
Eric Christopherd160c502016-01-29 01:35:53 +00001618 // Queue up this vtable for possible deferred emission.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001619 CGM.addDeferredVTable(RD);
1620
Yaron Kerene46f7ed2015-07-29 14:21:47 +00001621 SmallString<256> Name;
1622 llvm::raw_svector_ostream Out(Name);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001623 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001624
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001625 const VTableLayout &VTLayout =
1626 CGM.getItaniumVTableContext().getVTableLayout(RD);
1627 llvm::Type *VTableType = CGM.getVTables().getVTableType(VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001628
1629 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001630 Name, VTableType, llvm::GlobalValue::ExternalLinkage);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001631 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Hans Wennborgda24e9c2014-06-02 23:13:03 +00001632
Rafael Espindola922f2aa2018-02-23 19:30:48 +00001633 CGM.setGVProperties(VTable, RD);
1634
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001635 return VTable;
1636}
1637
John McCall9831b842018-02-06 18:52:44 +00001638CGCallee ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1639 GlobalDecl GD,
1640 Address This,
1641 llvm::Type *Ty,
1642 SourceLocation Loc) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001643 Ty = Ty->getPointerTo()->getPointerTo();
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001644 auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
1645 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty, MethodDecl->getParent());
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001646
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001647 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
John McCall9831b842018-02-06 18:52:44 +00001648 llvm::Value *VFunc;
1649 if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) {
1650 VFunc = CGF.EmitVTableTypeCheckedLoad(
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001651 MethodDecl->getParent(), VTable,
1652 VTableIndex * CGM.getContext().getTargetInfo().getPointerWidth(0) / 8);
John McCall9831b842018-02-06 18:52:44 +00001653 } else {
1654 CGF.EmitTypeMetadataCodeForVCall(MethodDecl->getParent(), VTable, Loc);
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001655
John McCall9831b842018-02-06 18:52:44 +00001656 llvm::Value *VFuncPtr =
1657 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1658 auto *VFuncLoad =
1659 CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign());
Piotr Padlewski77cc9622016-10-29 15:28:30 +00001660
John McCall9831b842018-02-06 18:52:44 +00001661 // Add !invariant.load md to virtual function load to indicate that
1662 // function didn't change inside vtable.
1663 // It's safe to add it without -fstrict-vtable-pointers, but it would not
1664 // help in devirtualization because it will only matter if we will have 2
1665 // the same virtual function loads from the same vtable load, which won't
1666 // happen without enabled devirtualization with -fstrict-vtable-pointers.
1667 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1668 CGM.getCodeGenOpts().StrictVTablePointers)
1669 VFuncLoad->setMetadata(
1670 llvm::LLVMContext::MD_invariant_load,
1671 llvm::MDNode::get(CGM.getLLVMContext(),
1672 llvm::ArrayRef<llvm::Metadata *>()));
1673 VFunc = VFuncLoad;
1674 }
John McCallb92ab1a2016-10-26 23:46:34 +00001675
Reid Kleckner138ab492018-05-17 18:12:18 +00001676 CGCallee Callee(MethodDecl->getCanonicalDecl(), VFunc);
John McCall9831b842018-02-06 18:52:44 +00001677 return Callee;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001678}
1679
David Majnemer0c0b6d92014-10-31 20:09:12 +00001680llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
1681 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
John McCall7f416cc2015-09-08 08:05:57 +00001682 Address This, const CXXMemberCallExpr *CE) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001683 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001684 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1685
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001686 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1687 Dtor, getFromDtorType(DtorType));
George Burgess IV00f70bd2018-03-01 05:43:23 +00001688 llvm::FunctionType *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
John McCallb92ab1a2016-10-26 23:46:34 +00001689 CGCallee Callee =
Peter Collingbourneea211002018-02-05 23:09:13 +00001690 CGCallee::forVirtual(CE, GlobalDecl(Dtor, DtorType), This, Ty);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001691
John McCall7f416cc2015-09-08 08:05:57 +00001692 CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(),
1693 This.getPointer(), /*ImplicitParam=*/nullptr,
Richard Smith762672a2016-09-28 19:09:10 +00001694 QualType(), CE, nullptr);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001695 return nullptr;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001696}
1697
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001698void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001699 CodeGenVTables &VTables = CGM.getVTables();
1700 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001701 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001702}
1703
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001704bool ItaniumCXXABI::canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const {
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001705 // We don't emit available_externally vtables if we are in -fapple-kext mode
1706 // because kext mode does not permit devirtualization.
1707 if (CGM.getLangOpts().AppleKext)
1708 return false;
1709
Piotr Padlewskie368de32018-06-13 13:55:42 +00001710 // If the vtable is hidden then it is not safe to emit an available_externally
1711 // copy of vtable.
1712 if (isVTableHidden(RD))
1713 return false;
1714
1715 if (CGM.getCodeGenOpts().ForceEmitVTables)
1716 return true;
1717
1718 // If we don't have any not emitted inline virtual function then we are safe
1719 // to emit an available_externally copy of vtable.
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001720 // FIXME we can still emit a copy of the vtable if we
1721 // can emit definition of the inline functions.
Piotr Padlewskie368de32018-06-13 13:55:42 +00001722 return !hasAnyUnusedVirtualInlineFunction(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001723}
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001724static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001725 Address InitialPtr,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001726 int64_t NonVirtualAdjustment,
1727 int64_t VirtualAdjustment,
1728 bool IsReturnAdjustment) {
1729 if (!NonVirtualAdjustment && !VirtualAdjustment)
John McCall7f416cc2015-09-08 08:05:57 +00001730 return InitialPtr.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001731
John McCall7f416cc2015-09-08 08:05:57 +00001732 Address V = CGF.Builder.CreateElementBitCast(InitialPtr, CGF.Int8Ty);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001733
John McCall7f416cc2015-09-08 08:05:57 +00001734 // In a base-to-derived cast, the non-virtual adjustment is applied first.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001735 if (NonVirtualAdjustment && !IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001736 V = CGF.Builder.CreateConstInBoundsByteGEP(V,
1737 CharUnits::fromQuantity(NonVirtualAdjustment));
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001738 }
1739
John McCall7f416cc2015-09-08 08:05:57 +00001740 // Perform the virtual adjustment if we have one.
1741 llvm::Value *ResultPtr;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001742 if (VirtualAdjustment) {
1743 llvm::Type *PtrDiffTy =
1744 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1745
John McCall7f416cc2015-09-08 08:05:57 +00001746 Address VTablePtrPtr = CGF.Builder.CreateElementBitCast(V, CGF.Int8PtrTy);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001747 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1748
1749 llvm::Value *OffsetPtr =
1750 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1751
1752 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1753
1754 // Load the adjustment offset from the vtable.
John McCall7f416cc2015-09-08 08:05:57 +00001755 llvm::Value *Offset =
1756 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001757
1758 // Adjust our pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001759 ResultPtr = CGF.Builder.CreateInBoundsGEP(V.getPointer(), Offset);
1760 } else {
1761 ResultPtr = V.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001762 }
1763
John McCall7f416cc2015-09-08 08:05:57 +00001764 // In a derived-to-base conversion, the non-virtual adjustment is
1765 // applied second.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001766 if (NonVirtualAdjustment && IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001767 ResultPtr = CGF.Builder.CreateConstInBoundsGEP1_64(ResultPtr,
1768 NonVirtualAdjustment);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001769 }
1770
1771 // Cast back to the original type.
John McCall7f416cc2015-09-08 08:05:57 +00001772 return CGF.Builder.CreateBitCast(ResultPtr, InitialPtr.getType());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001773}
1774
1775llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001776 Address This,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001777 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001778 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1779 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001780 /*IsReturnAdjustment=*/false);
1781}
1782
1783llvm::Value *
John McCall7f416cc2015-09-08 08:05:57 +00001784ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001785 const ReturnAdjustment &RA) {
1786 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1787 RA.Virtual.Itanium.VBaseOffsetOffset,
1788 /*IsReturnAdjustment=*/true);
1789}
1790
John McCall5d865c322010-08-31 07:33:07 +00001791void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1792 RValue RV, QualType ResultType) {
1793 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1794 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1795
1796 // Destructor thunks in the ARM ABI have indeterminate results.
John McCall7f416cc2015-09-08 08:05:57 +00001797 llvm::Type *T = CGF.ReturnValue.getElementType();
John McCall5d865c322010-08-31 07:33:07 +00001798 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1799 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1800}
John McCall8ed55a52010-09-02 09:58:18 +00001801
1802/************************** Array allocation cookies **************************/
1803
John McCallb91cd662012-05-01 05:23:51 +00001804CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1805 // The array cookie is a size_t; pad that up to the element alignment.
1806 // The cookie is actually right-justified in that space.
1807 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1808 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001809}
1810
John McCall7f416cc2015-09-08 08:05:57 +00001811Address ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1812 Address NewPtr,
1813 llvm::Value *NumElements,
1814 const CXXNewExpr *expr,
1815 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001816 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001817
John McCall7f416cc2015-09-08 08:05:57 +00001818 unsigned AS = NewPtr.getAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001819
John McCall9bca9232010-09-02 10:25:57 +00001820 ASTContext &Ctx = getContext();
John McCall7f416cc2015-09-08 08:05:57 +00001821 CharUnits SizeSize = CGF.getSizeSize();
John McCall8ed55a52010-09-02 09:58:18 +00001822
1823 // The size of the cookie.
1824 CharUnits CookieSize =
1825 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001826 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001827
1828 // Compute an offset to the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001829 Address CookiePtr = NewPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001830 CharUnits CookieOffset = CookieSize - SizeSize;
1831 if (!CookieOffset.isZero())
John McCall7f416cc2015-09-08 08:05:57 +00001832 CookiePtr = CGF.Builder.CreateConstInBoundsByteGEP(CookiePtr, CookieOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001833
1834 // Write the number of elements into the appropriate slot.
John McCall7f416cc2015-09-08 08:05:57 +00001835 Address NumElementsPtr =
1836 CGF.Builder.CreateElementBitCast(CookiePtr, CGF.SizeTy);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001837 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
John McCall7f416cc2015-09-08 08:05:57 +00001838
1839 // Handle the array cookie specially in ASan.
Filipe Cabecinhas6f83fa92018-01-02 13:46:12 +00001840 if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 &&
Filipe Cabecinhas4ba58172018-02-12 11:49:02 +00001841 (expr->getOperatorNew()->isReplaceableGlobalAllocationFunction() ||
1842 CGM.getCodeGenOpts().SanitizeAddressPoisonClassMemberArrayNewCookie)) {
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001843 // The store to the CookiePtr does not need to be instrumented.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001844 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
1845 llvm::FunctionType *FTy =
John McCall7f416cc2015-09-08 08:05:57 +00001846 llvm::FunctionType::get(CGM.VoidTy, NumElementsPtr.getType(), false);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001847 llvm::Constant *F =
1848 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001849 CGF.Builder.CreateCall(F, NumElementsPtr.getPointer());
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001850 }
John McCall8ed55a52010-09-02 09:58:18 +00001851
1852 // Finally, compute a pointer to the actual data buffer by skipping
1853 // over the cookie completely.
John McCall7f416cc2015-09-08 08:05:57 +00001854 return CGF.Builder.CreateConstInBoundsByteGEP(NewPtr, CookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001855}
1856
John McCallb91cd662012-05-01 05:23:51 +00001857llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001858 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00001859 CharUnits cookieSize) {
1860 // The element size is right-justified in the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001861 Address numElementsPtr = allocPtr;
1862 CharUnits numElementsOffset = cookieSize - CGF.getSizeSize();
John McCallb91cd662012-05-01 05:23:51 +00001863 if (!numElementsOffset.isZero())
1864 numElementsPtr =
John McCall7f416cc2015-09-08 08:05:57 +00001865 CGF.Builder.CreateConstInBoundsByteGEP(numElementsPtr, numElementsOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001866
John McCall7f416cc2015-09-08 08:05:57 +00001867 unsigned AS = allocPtr.getAddressSpace();
1868 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001869 if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0)
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001870 return CGF.Builder.CreateLoad(numElementsPtr);
1871 // In asan mode emit a function call instead of a regular load and let the
1872 // run-time deal with it: if the shadow is properly poisoned return the
1873 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
1874 // We can't simply ignore this load using nosanitize metadata because
1875 // the metadata may be lost.
1876 llvm::FunctionType *FTy =
1877 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
1878 llvm::Constant *F =
1879 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001880 return CGF.Builder.CreateCall(F, numElementsPtr.getPointer());
John McCall8ed55a52010-09-02 09:58:18 +00001881}
1882
John McCallb91cd662012-05-01 05:23:51 +00001883CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001884 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001885 // struct array_cookie {
1886 // std::size_t element_size; // element_size != 0
1887 // std::size_t element_count;
1888 // };
John McCallc19c7062013-01-25 23:36:19 +00001889 // But the base ABI doesn't give anything an alignment greater than
1890 // 8, so we can dismiss this as typical ABI-author blindness to
1891 // actual language complexity and round up to the element alignment.
1892 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1893 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001894}
1895
John McCall7f416cc2015-09-08 08:05:57 +00001896Address ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1897 Address newPtr,
1898 llvm::Value *numElements,
1899 const CXXNewExpr *expr,
1900 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001901 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001902
John McCall8ed55a52010-09-02 09:58:18 +00001903 // The cookie is always at the start of the buffer.
John McCall7f416cc2015-09-08 08:05:57 +00001904 Address cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001905
1906 // The first element is the element size.
John McCall7f416cc2015-09-08 08:05:57 +00001907 cookie = CGF.Builder.CreateElementBitCast(cookie, CGF.SizeTy);
John McCallc19c7062013-01-25 23:36:19 +00001908 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1909 getContext().getTypeSizeInChars(elementType).getQuantity());
1910 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001911
1912 // The second element is the element count.
John McCall7f416cc2015-09-08 08:05:57 +00001913 cookie = CGF.Builder.CreateConstInBoundsGEP(cookie, 1, CGF.getSizeSize());
John McCallc19c7062013-01-25 23:36:19 +00001914 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001915
1916 // Finally, compute a pointer to the actual data buffer by skipping
1917 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001918 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
John McCall7f416cc2015-09-08 08:05:57 +00001919 return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001920}
1921
John McCallb91cd662012-05-01 05:23:51 +00001922llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001923 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00001924 CharUnits cookieSize) {
1925 // The number of elements is at offset sizeof(size_t) relative to
1926 // the allocated pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001927 Address numElementsPtr
1928 = CGF.Builder.CreateConstInBoundsByteGEP(allocPtr, CGF.getSizeSize());
John McCall8ed55a52010-09-02 09:58:18 +00001929
John McCall7f416cc2015-09-08 08:05:57 +00001930 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
John McCallb91cd662012-05-01 05:23:51 +00001931 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001932}
1933
John McCall68ff0372010-09-08 01:44:27 +00001934/*********************** Static local initialization **************************/
1935
1936static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001937 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001938 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001939 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001940 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001941 GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00001942 return CGM.CreateRuntimeFunction(
1943 FTy, "__cxa_guard_acquire",
1944 llvm::AttributeList::get(CGM.getLLVMContext(),
1945 llvm::AttributeList::FunctionIndex,
1946 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001947}
1948
1949static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001950 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001951 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001952 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001953 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00001954 return CGM.CreateRuntimeFunction(
1955 FTy, "__cxa_guard_release",
1956 llvm::AttributeList::get(CGM.getLLVMContext(),
1957 llvm::AttributeList::FunctionIndex,
1958 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001959}
1960
1961static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001962 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001963 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001964 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001965 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00001966 return CGM.CreateRuntimeFunction(
1967 FTy, "__cxa_guard_abort",
1968 llvm::AttributeList::get(CGM.getLLVMContext(),
1969 llvm::AttributeList::FunctionIndex,
1970 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001971}
1972
1973namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001974 struct CallGuardAbort final : EHScopeStack::Cleanup {
John McCall68ff0372010-09-08 01:44:27 +00001975 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001976 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001977
Craig Topper4f12f102014-03-12 06:41:41 +00001978 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00001979 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1980 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001981 }
1982 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001983}
John McCall68ff0372010-09-08 01:44:27 +00001984
1985/// The ARM code here follows the Itanium code closely enough that we
1986/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001987void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1988 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001989 llvm::GlobalVariable *var,
1990 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00001991 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00001992
Richard Smith62f19e72016-06-25 00:15:56 +00001993 // Inline variables that weren't instantiated from variable templates have
1994 // partially-ordered initialization within their translation unit.
1995 bool NonTemplateInline =
1996 D.isInline() &&
1997 !isTemplateInstantiation(D.getTemplateSpecializationKind());
1998
1999 // We only need to use thread-safe statics for local non-TLS variables and
2000 // inline variables; other global initialization is always single-threaded
2001 // or (through lazy dynamic loading in multiple threads) unsequenced.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002002 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
Richard Smith62f19e72016-06-25 00:15:56 +00002003 (D.isLocalVarDecl() || NonTemplateInline) &&
2004 !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00002005
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00002006 // If we have a global variable with internal linkage and thread-safe statics
2007 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00002008 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
2009
2010 llvm::IntegerType *guardTy;
John McCall7f416cc2015-09-08 08:05:57 +00002011 CharUnits guardAlignment;
John McCall5aa52592011-06-17 07:33:57 +00002012 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00002013 guardTy = CGF.Int8Ty;
John McCall7f416cc2015-09-08 08:05:57 +00002014 guardAlignment = CharUnits::One();
John McCall5aa52592011-06-17 07:33:57 +00002015 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00002016 // Guard variables are 64 bits in the generic ABI and size width on ARM
2017 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
John McCall7f416cc2015-09-08 08:05:57 +00002018 if (UseARMGuardVarABI) {
2019 guardTy = CGF.SizeTy;
2020 guardAlignment = CGF.getSizeAlign();
2021 } else {
2022 guardTy = CGF.Int64Ty;
2023 guardAlignment = CharUnits::fromQuantity(
2024 CGM.getDataLayout().getABITypeAlignment(guardTy));
2025 }
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00002026 }
John McCallb88a5662012-03-30 21:00:39 +00002027 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00002028
John McCallb88a5662012-03-30 21:00:39 +00002029 // Create the guard variable if we don't already have it (as we
2030 // might if we're double-emitting this function body).
2031 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
2032 if (!guard) {
2033 // Mangle the name for the guard.
2034 SmallString<256> guardName;
2035 {
2036 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00002037 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00002038 }
John McCall8e7cb6d2010-11-02 21:04:24 +00002039
John McCallb88a5662012-03-30 21:00:39 +00002040 // Create the guard variable with a zero-initializer.
2041 // Just absorb linkage and visibility from the guarded variable.
2042 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
2043 false, var->getLinkage(),
2044 llvm::ConstantInt::get(guardTy, 0),
2045 guardName.str());
Rafael Espindola699f5d62018-02-07 22:15:33 +00002046 guard->setDSOLocal(var->isDSOLocal());
John McCallb88a5662012-03-30 21:00:39 +00002047 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00002048 // If the variable is thread-local, so is its guard variable.
2049 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCall7f416cc2015-09-08 08:05:57 +00002050 guard->setAlignment(guardAlignment.getQuantity());
John McCallb88a5662012-03-30 21:00:39 +00002051
Yaron Keren5bfa1082015-09-03 20:33:29 +00002052 // The ABI says: "It is suggested that it be emitted in the same COMDAT
2053 // group as the associated data object." In practice, this doesn't work for
Dan Gohman839f2152017-01-17 21:46:38 +00002054 // non-ELF and non-Wasm object formats, so only do it for ELF and Wasm.
Rafael Espindola0d4fb982015-01-12 22:13:53 +00002055 llvm::Comdat *C = var->getComdat();
Yaron Keren5bfa1082015-09-03 20:33:29 +00002056 if (!D.isLocalVarDecl() && C &&
Dan Gohman839f2152017-01-17 21:46:38 +00002057 (CGM.getTarget().getTriple().isOSBinFormatELF() ||
2058 CGM.getTarget().getTriple().isOSBinFormatWasm())) {
Rafael Espindola2ae4b632014-09-19 19:43:18 +00002059 guard->setComdat(C);
Richard Smith62f19e72016-06-25 00:15:56 +00002060 // An inline variable's guard function is run from the per-TU
2061 // initialization function, not via a dedicated global ctor function, so
2062 // we can't put it in a comdat.
2063 if (!NonTemplateInline)
2064 CGF.CurFn->setComdat(C);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00002065 } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) {
2066 guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName()));
Rafael Espindola2ae4b632014-09-19 19:43:18 +00002067 }
2068
John McCallb88a5662012-03-30 21:00:39 +00002069 CGM.setStaticLocalDeclGuardAddress(&D, guard);
2070 }
John McCall87590e62012-03-30 07:09:50 +00002071
John McCall7f416cc2015-09-08 08:05:57 +00002072 Address guardAddr = Address(guard, guardAlignment);
2073
John McCall68ff0372010-09-08 01:44:27 +00002074 // Test whether the variable has completed initialization.
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002075 //
John McCall68ff0372010-09-08 01:44:27 +00002076 // Itanium C++ ABI 3.3.2:
2077 // The following is pseudo-code showing how these functions can be used:
2078 // if (obj_guard.first_byte == 0) {
2079 // if ( __cxa_guard_acquire (&obj_guard) ) {
2080 // try {
2081 // ... initialize the object ...;
2082 // } catch (...) {
2083 // __cxa_guard_abort (&obj_guard);
2084 // throw;
2085 // }
2086 // ... queue object destructor with __cxa_atexit() ...;
2087 // __cxa_guard_release (&obj_guard);
2088 // }
2089 // }
Tim Northovera2ee4332014-03-29 15:09:45 +00002090
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002091 // Load the first byte of the guard variable.
2092 llvm::LoadInst *LI =
John McCall7f416cc2015-09-08 08:05:57 +00002093 Builder.CreateLoad(Builder.CreateElementBitCast(guardAddr, CGM.Int8Ty));
John McCall68ff0372010-09-08 01:44:27 +00002094
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002095 // Itanium ABI:
2096 // An implementation supporting thread-safety on multiprocessor
2097 // systems must also guarantee that references to the initialized
2098 // object do not occur before the load of the initialization flag.
2099 //
2100 // In LLVM, we do this by marking the load Acquire.
2101 if (threadsafe)
JF Bastien92f4ef12016-04-06 17:26:42 +00002102 LI->setAtomic(llvm::AtomicOrdering::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00002103
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002104 // For ARM, we should only check the first bit, rather than the entire byte:
2105 //
2106 // ARM C++ ABI 3.2.3.1:
2107 // To support the potential use of initialization guard variables
2108 // as semaphores that are the target of ARM SWP and LDREX/STREX
2109 // synchronizing instructions we define a static initialization
2110 // guard variable to be a 4-byte aligned, 4-byte word with the
2111 // following inline access protocol.
2112 // #define INITIALIZED 1
2113 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
2114 // if (__cxa_guard_acquire(&obj_guard))
2115 // ...
2116 // }
2117 //
2118 // and similarly for ARM64:
2119 //
2120 // ARM64 C++ ABI 3.2.2:
2121 // This ABI instead only specifies the value bit 0 of the static guard
2122 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
2123 // variable is not initialized and 1 when it is.
2124 llvm::Value *V =
2125 (UseARMGuardVarABI && !useInt8GuardVariable)
2126 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
2127 : LI;
Richard Smithae8d62c2017-07-26 22:01:09 +00002128 llvm::Value *NeedsInit = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00002129
2130 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
2131 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2132
2133 // Check if the first byte of the guard variable is zero.
Richard Smithae8d62c2017-07-26 22:01:09 +00002134 CGF.EmitCXXGuardedInitBranch(NeedsInit, InitCheckBlock, EndBlock,
2135 CodeGenFunction::GuardKind::VariableGuard, &D);
John McCall68ff0372010-09-08 01:44:27 +00002136
2137 CGF.EmitBlock(InitCheckBlock);
2138
2139 // Variables used when coping with thread-safe statics and exceptions.
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002140 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002141 // Call __cxa_guard_acquire.
2142 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00002143 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002144
John McCall68ff0372010-09-08 01:44:27 +00002145 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002146
John McCall68ff0372010-09-08 01:44:27 +00002147 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
2148 InitBlock, EndBlock);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002149
John McCall68ff0372010-09-08 01:44:27 +00002150 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00002151 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002152
John McCall68ff0372010-09-08 01:44:27 +00002153 CGF.EmitBlock(InitBlock);
2154 }
2155
2156 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00002157 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00002158
John McCall5aa52592011-06-17 07:33:57 +00002159 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002160 // Pop the guard-abort cleanup if we pushed one.
2161 CGF.PopCleanupBlock();
2162
2163 // Call __cxa_guard_release. This cannot throw.
John McCall7f416cc2015-09-08 08:05:57 +00002164 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy),
2165 guardAddr.getPointer());
John McCall68ff0372010-09-08 01:44:27 +00002166 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002167 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guardAddr);
John McCall68ff0372010-09-08 01:44:27 +00002168 }
2169
2170 CGF.EmitBlock(EndBlock);
2171}
John McCallc84ed6a2012-05-01 06:13:13 +00002172
2173/// Register a global destructor using __cxa_atexit.
2174static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
2175 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00002176 llvm::Constant *addr,
2177 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00002178 const char *Name = "__cxa_atexit";
2179 if (TLS) {
2180 const llvm::Triple &T = CGF.getTarget().getTriple();
Manman Renf93fff22015-11-11 23:08:18 +00002181 Name = T.isOSDarwin() ? "_tlv_atexit" : "__cxa_thread_atexit";
Bill Wendling95cae882013-05-02 19:18:03 +00002182 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00002183
John McCallc84ed6a2012-05-01 06:13:13 +00002184 // We're assuming that the destructor function is something we can
2185 // reasonably call with the default CC. Go ahead and cast it to the
2186 // right prototype.
2187 llvm::Type *dtorTy =
2188 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
2189
2190 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
2191 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
2192 llvm::FunctionType *atexitTy =
2193 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
2194
2195 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002196 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00002197 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
2198 fn->setDoesNotThrow();
2199
2200 // Create a variable that binds the atexit to this shared object.
2201 llvm::Constant *handle =
Reid Kleckner9de92142017-02-13 18:49:21 +00002202 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
2203 auto *GV = cast<llvm::GlobalValue>(handle->stripPointerCasts());
2204 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
John McCallc84ed6a2012-05-01 06:13:13 +00002205
Akira Hatanaka617e2612018-04-17 18:41:52 +00002206 if (!addr)
2207 // addr is null when we are trying to register a dtor annotated with
2208 // __attribute__((destructor)) in a constructor function. Using null here is
2209 // okay because this argument is just passed back to the destructor
2210 // function.
2211 addr = llvm::Constant::getNullValue(CGF.Int8PtrTy);
2212
John McCallc84ed6a2012-05-01 06:13:13 +00002213 llvm::Value *args[] = {
2214 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
2215 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
2216 handle
2217 };
John McCall882987f2013-02-28 19:01:20 +00002218 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00002219}
2220
Akira Hatanaka617e2612018-04-17 18:41:52 +00002221void CodeGenModule::registerGlobalDtorsWithAtExit() {
2222 for (const auto I : DtorsUsingAtExit) {
2223 int Priority = I.first;
2224 const llvm::TinyPtrVector<llvm::Function *> &Dtors = I.second;
2225
2226 // Create a function that registers destructors that have the same priority.
2227 //
2228 // Since constructor functions are run in non-descending order of their
2229 // priorities, destructors are registered in non-descending order of their
2230 // priorities, and since destructor functions are run in the reverse order
2231 // of their registration, destructor functions are run in non-ascending
2232 // order of their priorities.
2233 CodeGenFunction CGF(*this);
2234 std::string GlobalInitFnName =
2235 std::string("__GLOBAL_init_") + llvm::to_string(Priority);
2236 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
2237 llvm::Function *GlobalInitFn = CreateGlobalInitOrDestructFunction(
2238 FTy, GlobalInitFnName, getTypes().arrangeNullaryFunction(),
2239 SourceLocation());
2240 ASTContext &Ctx = getContext();
2241 FunctionDecl *FD = FunctionDecl::Create(
2242 Ctx, Ctx.getTranslationUnitDecl(), SourceLocation(), SourceLocation(),
2243 &Ctx.Idents.get(GlobalInitFnName), Ctx.VoidTy, nullptr, SC_Static,
2244 false, false);
2245 CGF.StartFunction(GlobalDecl(FD), getContext().VoidTy, GlobalInitFn,
2246 getTypes().arrangeNullaryFunction(), FunctionArgList(),
2247 SourceLocation(), SourceLocation());
2248
2249 for (auto *Dtor : Dtors) {
2250 // Register the destructor function calling __cxa_atexit if it is
2251 // available. Otherwise fall back on calling atexit.
2252 if (getCodeGenOpts().CXAAtExit)
2253 emitGlobalDtorWithCXAAtExit(CGF, Dtor, nullptr, false);
2254 else
2255 CGF.registerGlobalDtorWithAtExit(Dtor);
2256 }
2257
2258 CGF.FinishFunction();
2259 AddGlobalCtor(GlobalInitFn, Priority, nullptr);
2260 }
2261}
2262
John McCallc84ed6a2012-05-01 06:13:13 +00002263/// Register a global destructor as best as we know how.
2264void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00002265 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00002266 llvm::Constant *dtor,
2267 llvm::Constant *addr) {
2268 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002269 if (CGM.getCodeGenOpts().CXAAtExit)
2270 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
2271
2272 if (D.getTLSKind())
2273 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00002274
2275 // In Apple kexts, we want to add a global destructor entry.
2276 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00002277 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00002278 // Generate a global destructor entry.
2279 return CGM.AddCXXDtorEntry(dtor, addr);
2280 }
2281
David Blaikieebe87e12013-08-27 23:57:18 +00002282 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00002283}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002284
David Majnemer9b21c332014-07-11 20:28:10 +00002285static bool isThreadWrapperReplaceable(const VarDecl *VD,
2286 CodeGen::CodeGenModule &CGM) {
2287 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
Manman Renf93fff22015-11-11 23:08:18 +00002288 // Darwin prefers to have references to thread local variables to go through
David Majnemer9b21c332014-07-11 20:28:10 +00002289 // the thread wrapper instead of directly referencing the backing variable.
2290 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
Manman Renf93fff22015-11-11 23:08:18 +00002291 CGM.getTarget().getTriple().isOSDarwin();
David Majnemer9b21c332014-07-11 20:28:10 +00002292}
2293
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002294/// Get the appropriate linkage for the wrapper function. This is essentially
David Majnemer4632e1e2014-06-27 16:56:27 +00002295/// the weak form of the variable's linkage; every translation unit which needs
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002296/// the wrapper emits a copy, and we want the linker to merge them.
David Majnemer35ab3282014-06-11 04:08:55 +00002297static llvm::GlobalValue::LinkageTypes
2298getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
2299 llvm::GlobalValue::LinkageTypes VarLinkage =
2300 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
2301
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002302 // For internal linkage variables, we don't need an external or weak wrapper.
2303 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
2304 return VarLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00002305
David Majnemer9b21c332014-07-11 20:28:10 +00002306 // If the thread wrapper is replaceable, give it appropriate linkage.
Manman Ren68150262015-11-11 22:42:31 +00002307 if (isThreadWrapperReplaceable(VD, CGM))
2308 if (!llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) &&
2309 !llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
2310 return VarLinkage;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002311 return llvm::GlobalValue::WeakODRLinkage;
2312}
2313
2314llvm::Function *
2315ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +00002316 llvm::Value *Val) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002317 // Mangle the name for the thread_local wrapper function.
2318 SmallString<256> WrapperName;
2319 {
2320 llvm::raw_svector_ostream Out(WrapperName);
2321 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002322 }
2323
Akira Hatanaka26907f92016-01-15 03:34:06 +00002324 // FIXME: If VD is a definition, we should regenerate the function attributes
2325 // before returning.
Alexander Musmanf94c3182014-09-26 06:28:25 +00002326 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002327 return cast<llvm::Function>(V);
2328
Akira Hatanaka26907f92016-01-15 03:34:06 +00002329 QualType RetQT = VD->getType();
2330 if (RetQT->isReferenceType())
2331 RetQT = RetQT.getNonReferenceType();
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002332
John McCallc56a8b32016-03-11 04:30:31 +00002333 const CGFunctionInfo &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2334 getContext().getPointerType(RetQT), FunctionArgList());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002335
2336 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FI);
David Majnemer35ab3282014-06-11 04:08:55 +00002337 llvm::Function *Wrapper =
2338 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
2339 WrapperName.str(), &CGM.getModule());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002340
2341 CGM.SetLLVMFunctionAttributes(nullptr, FI, Wrapper);
2342
2343 if (VD->hasDefinition())
2344 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Wrapper);
2345
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002346 // Always resolve references to the wrapper at link time.
Manman Ren68150262015-11-11 22:42:31 +00002347 if (!Wrapper->hasLocalLinkage() && !(isThreadWrapperReplaceable(VD, CGM) &&
2348 !llvm::GlobalVariable::isLinkOnceLinkage(Wrapper->getLinkage()) &&
2349 !llvm::GlobalVariable::isWeakODRLinkage(Wrapper->getLinkage())))
Duncan P. N. Exon Smith4434d362014-05-07 22:36:11 +00002350 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
Manman Renb0b3af72015-12-17 00:42:36 +00002351
2352 if (isThreadWrapperReplaceable(VD, CGM)) {
2353 Wrapper->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2354 Wrapper->addFnAttr(llvm::Attribute::NoUnwind);
2355 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002356 return Wrapper;
2357}
2358
2359void ItaniumCXXABI::EmitThreadLocalInitFuncs(
Richard Smith5a99c492015-12-01 01:10:48 +00002360 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
2361 ArrayRef<llvm::Function *> CXXThreadLocalInits,
2362 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
David Majnemerb3341ea2014-10-05 05:05:40 +00002363 llvm::Function *InitFunc = nullptr;
Richard Smithfbe23692017-01-13 00:43:31 +00002364
2365 // Separate initializers into those with ordered (or partially-ordered)
2366 // initialization and those with unordered initialization.
2367 llvm::SmallVector<llvm::Function *, 8> OrderedInits;
2368 llvm::SmallDenseMap<const VarDecl *, llvm::Function *> UnorderedInits;
2369 for (unsigned I = 0; I != CXXThreadLocalInits.size(); ++I) {
2370 if (isTemplateInstantiation(
2371 CXXThreadLocalInitVars[I]->getTemplateSpecializationKind()))
2372 UnorderedInits[CXXThreadLocalInitVars[I]->getCanonicalDecl()] =
2373 CXXThreadLocalInits[I];
2374 else
2375 OrderedInits.push_back(CXXThreadLocalInits[I]);
2376 }
2377
2378 if (!OrderedInits.empty()) {
David Majnemerb3341ea2014-10-05 05:05:40 +00002379 // Generate a guarded initialization function.
2380 llvm::FunctionType *FTy =
2381 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002382 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2383 InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init", FI,
Alexey Samsonov1444bb92014-10-17 00:20:19 +00002384 SourceLocation(),
David Majnemerb3341ea2014-10-05 05:05:40 +00002385 /*TLS=*/true);
2386 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
2387 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
2388 llvm::GlobalVariable::InternalLinkage,
2389 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
2390 Guard->setThreadLocal(true);
John McCall7f416cc2015-09-08 08:05:57 +00002391
2392 CharUnits GuardAlign = CharUnits::One();
2393 Guard->setAlignment(GuardAlign.getQuantity());
2394
Richard Smithfbe23692017-01-13 00:43:31 +00002395 CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(InitFunc, OrderedInits,
2396 Address(Guard, GuardAlign));
Manman Ren5e5d0462016-03-18 23:35:21 +00002397 // On Darwin platforms, use CXX_FAST_TLS calling convention.
2398 if (CGM.getTarget().getTriple().isOSDarwin()) {
2399 InitFunc->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2400 InitFunc->addFnAttr(llvm::Attribute::NoUnwind);
2401 }
David Majnemerb3341ea2014-10-05 05:05:40 +00002402 }
Richard Smithfbe23692017-01-13 00:43:31 +00002403
2404 // Emit thread wrappers.
Richard Smith5a99c492015-12-01 01:10:48 +00002405 for (const VarDecl *VD : CXXThreadLocals) {
2406 llvm::GlobalVariable *Var =
2407 cast<llvm::GlobalVariable>(CGM.GetGlobalValue(CGM.getMangledName(VD)));
Richard Smithfbe23692017-01-13 00:43:31 +00002408 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002409
David Majnemer9b21c332014-07-11 20:28:10 +00002410 // Some targets require that all access to thread local variables go through
2411 // the thread wrapper. This means that we cannot attempt to create a thread
2412 // wrapper or a thread helper.
Richard Smithfbe23692017-01-13 00:43:31 +00002413 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition()) {
2414 Wrapper->setLinkage(llvm::Function::ExternalLinkage);
David Majnemer9b21c332014-07-11 20:28:10 +00002415 continue;
Richard Smithfbe23692017-01-13 00:43:31 +00002416 }
David Majnemer9b21c332014-07-11 20:28:10 +00002417
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002418 // Mangle the name for the thread_local initialization function.
2419 SmallString<256> InitFnName;
2420 {
2421 llvm::raw_svector_ostream Out(InitFnName);
2422 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002423 }
2424
2425 // If we have a definition for the variable, emit the initialization
2426 // function as an alias to the global Init function (if any). Otherwise,
2427 // produce a declaration of the initialization function.
Craig Topper8a13c412014-05-21 05:09:00 +00002428 llvm::GlobalValue *Init = nullptr;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002429 bool InitIsInitFunc = false;
2430 if (VD->hasDefinition()) {
2431 InitIsInitFunc = true;
Richard Smithfbe23692017-01-13 00:43:31 +00002432 llvm::Function *InitFuncToUse = InitFunc;
2433 if (isTemplateInstantiation(VD->getTemplateSpecializationKind()))
2434 InitFuncToUse = UnorderedInits.lookup(VD->getCanonicalDecl());
2435 if (InitFuncToUse)
Rafael Espindola234405b2014-05-17 21:30:14 +00002436 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
Richard Smithfbe23692017-01-13 00:43:31 +00002437 InitFuncToUse);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002438 } else {
2439 // Emit a weak global function referring to the initialization function.
2440 // This function will not exist if the TU defining the thread_local
2441 // variable in question does not need any dynamic initialization for
2442 // its thread_local variables.
2443 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
Richard Smithfbe23692017-01-13 00:43:31 +00002444 Init = llvm::Function::Create(FnTy,
2445 llvm::GlobalVariable::ExternalWeakLinkage,
2446 InitFnName.str(), &CGM.getModule());
John McCallc56a8b32016-03-11 04:30:31 +00002447 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
Akira Hatanaka26907f92016-01-15 03:34:06 +00002448 CGM.SetLLVMFunctionAttributes(nullptr, FI, cast<llvm::Function>(Init));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002449 }
2450
Rafael Espindolaabdb3222018-03-07 23:18:06 +00002451 if (Init) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002452 Init->setVisibility(Var->getVisibility());
Rafael Espindolaabdb3222018-03-07 23:18:06 +00002453 Init->setDSOLocal(Var->isDSOLocal());
2454 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002455
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002456 llvm::LLVMContext &Context = CGM.getModule().getContext();
2457 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
John McCall7f416cc2015-09-08 08:05:57 +00002458 CGBuilderTy Builder(CGM, Entry);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002459 if (InitIsInitFunc) {
Manman Ren5e5d0462016-03-18 23:35:21 +00002460 if (Init) {
2461 llvm::CallInst *CallVal = Builder.CreateCall(Init);
Akira Hatanaka1da9dbb2018-05-29 18:28:49 +00002462 if (isThreadWrapperReplaceable(VD, CGM)) {
Manman Ren5e5d0462016-03-18 23:35:21 +00002463 CallVal->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
Akira Hatanaka1da9dbb2018-05-29 18:28:49 +00002464 llvm::Function *Fn =
2465 cast<llvm::Function>(cast<llvm::GlobalAlias>(Init)->getAliasee());
2466 Fn->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2467 }
Manman Ren5e5d0462016-03-18 23:35:21 +00002468 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002469 } else {
2470 // Don't know whether we have an init function. Call it if it exists.
2471 llvm::Value *Have = Builder.CreateIsNotNull(Init);
2472 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2473 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2474 Builder.CreateCondBr(Have, InitBB, ExitBB);
2475
2476 Builder.SetInsertPoint(InitBB);
David Blaikie4ba525b2015-07-14 17:27:39 +00002477 Builder.CreateCall(Init);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002478 Builder.CreateBr(ExitBB);
2479
2480 Builder.SetInsertPoint(ExitBB);
2481 }
2482
2483 // For a reference, the result of the wrapper function is a pointer to
2484 // the referenced object.
2485 llvm::Value *Val = Var;
2486 if (VD->getType()->isReferenceType()) {
John McCall7f416cc2015-09-08 08:05:57 +00002487 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2488 Val = Builder.CreateAlignedLoad(Val, Align);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002489 }
Alexander Musmanf94c3182014-09-26 06:28:25 +00002490 if (Val->getType() != Wrapper->getReturnType())
2491 Val = Builder.CreatePointerBitCastOrAddrSpaceCast(
2492 Val, Wrapper->getReturnType(), "");
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002493 Builder.CreateRet(Val);
2494 }
2495}
2496
Richard Smith0f383742014-03-26 22:48:22 +00002497LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2498 const VarDecl *VD,
2499 QualType LValType) {
Richard Smith5a99c492015-12-01 01:10:48 +00002500 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD);
Alexander Musmanf94c3182014-09-26 06:28:25 +00002501 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002502
Manman Renb0b3af72015-12-17 00:42:36 +00002503 llvm::CallInst *CallVal = CGF.Builder.CreateCall(Wrapper);
Saleem Abdulrasool4a7130a2016-08-01 21:31:24 +00002504 CallVal->setCallingConv(Wrapper->getCallingConv());
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002505
2506 LValue LV;
2507 if (VD->getType()->isReferenceType())
Manman Renb0b3af72015-12-17 00:42:36 +00002508 LV = CGF.MakeNaturalAlignAddrLValue(CallVal, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002509 else
Manman Renb0b3af72015-12-17 00:42:36 +00002510 LV = CGF.MakeAddrLValue(CallVal, LValType,
2511 CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002512 // FIXME: need setObjCGCLValueClass?
2513 return LV;
2514}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002515
2516/// Return whether the given global decl needs a VTT parameter, which it does
2517/// if it's a base constructor or destructor with virtual bases.
2518bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
2519 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002520
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002521 // We don't have any virtual bases, just return early.
2522 if (!MD->getParent()->getNumVBases())
2523 return false;
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002524
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002525 // Check if we have a base constructor.
2526 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
2527 return true;
2528
2529 // Check if we have a base destructor.
2530 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2531 return true;
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002532
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002533 return false;
2534}
David Majnemere2cb8d12014-07-07 06:20:47 +00002535
2536namespace {
2537class ItaniumRTTIBuilder {
2538 CodeGenModule &CGM; // Per-module state.
2539 llvm::LLVMContext &VMContext;
2540 const ItaniumCXXABI &CXXABI; // Per-module state.
2541
2542 /// Fields - The fields of the RTTI descriptor currently being built.
2543 SmallVector<llvm::Constant *, 16> Fields;
2544
2545 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2546 llvm::GlobalVariable *
2547 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2548
2549 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2550 /// descriptor of the given type.
2551 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2552
2553 /// BuildVTablePointer - Build the vtable pointer for the given type.
2554 void BuildVTablePointer(const Type *Ty);
2555
2556 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2557 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2558 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2559
2560 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2561 /// classes with bases that do not satisfy the abi::__si_class_type_info
2562 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2563 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2564
2565 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2566 /// for pointer types.
2567 void BuildPointerTypeInfo(QualType PointeeTy);
2568
2569 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2570 /// type_info for an object type.
2571 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2572
2573 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2574 /// struct, used for member pointer types.
2575 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2576
2577public:
2578 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2579 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2580
2581 // Pointer type info flags.
2582 enum {
2583 /// PTI_Const - Type has const qualifier.
2584 PTI_Const = 0x1,
2585
2586 /// PTI_Volatile - Type has volatile qualifier.
2587 PTI_Volatile = 0x2,
2588
2589 /// PTI_Restrict - Type has restrict qualifier.
2590 PTI_Restrict = 0x4,
2591
2592 /// PTI_Incomplete - Type is incomplete.
2593 PTI_Incomplete = 0x8,
2594
2595 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2596 /// (in pointer to member).
Richard Smitha7d93782016-12-01 03:32:42 +00002597 PTI_ContainingClassIncomplete = 0x10,
2598
2599 /// PTI_TransactionSafe - Pointee is transaction_safe function (C++ TM TS).
2600 //PTI_TransactionSafe = 0x20,
2601
2602 /// PTI_Noexcept - Pointee is noexcept function (C++1z).
2603 PTI_Noexcept = 0x40,
David Majnemere2cb8d12014-07-07 06:20:47 +00002604 };
2605
2606 // VMI type info flags.
2607 enum {
2608 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2609 VMI_NonDiamondRepeat = 0x1,
2610
2611 /// VMI_DiamondShaped - Class is diamond shaped.
2612 VMI_DiamondShaped = 0x2
2613 };
2614
2615 // Base class type info flags.
2616 enum {
2617 /// BCTI_Virtual - Base class is virtual.
2618 BCTI_Virtual = 0x1,
2619
2620 /// BCTI_Public - Base class is public.
2621 BCTI_Public = 0x2
2622 };
2623
2624 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
2625 ///
2626 /// \param Force - true to force the creation of this RTTI value
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00002627 /// \param DLLExport - true to mark the RTTI value as DLLExport
2628 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false,
2629 bool DLLExport = false);
David Majnemere2cb8d12014-07-07 06:20:47 +00002630};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002631}
David Majnemere2cb8d12014-07-07 06:20:47 +00002632
2633llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2634 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002635 SmallString<256> Name;
2636 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002637 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002638
2639 // We know that the mangled name of the type starts at index 4 of the
2640 // mangled name of the typename, so we can just index into it in order to
2641 // get the mangled name of the type.
2642 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2643 Name.substr(4));
2644
2645 llvm::GlobalVariable *GV =
2646 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
2647
2648 GV->setInitializer(Init);
2649
2650 return GV;
2651}
2652
2653llvm::Constant *
2654ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2655 // Mangle the RTTI name.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002656 SmallString<256> Name;
2657 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002658 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002659
2660 // Look for an existing global.
2661 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2662
2663 if (!GV) {
2664 // Create a new global variable.
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00002665 // Note for the future: If we would ever like to do deferred emission of
2666 // RTTI, check if emitting vtables opportunistically need any adjustment.
2667
David Majnemere2cb8d12014-07-07 06:20:47 +00002668 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2669 /*Constant=*/true,
2670 llvm::GlobalValue::ExternalLinkage, nullptr,
2671 Name);
Rafael Espindola3f727a82018-03-14 18:14:46 +00002672 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
2673 CGM.setGVProperties(GV, RD);
David Majnemere2cb8d12014-07-07 06:20:47 +00002674 }
2675
2676 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2677}
2678
2679/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2680/// info for that type is defined in the standard library.
2681static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2682 // Itanium C++ ABI 2.9.2:
2683 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
2684 // the run-time support library. Specifically, the run-time support
2685 // library should contain type_info objects for the types X, X* and
2686 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2687 // unsigned char, signed char, short, unsigned short, int, unsigned int,
2688 // long, unsigned long, long long, unsigned long long, float, double,
2689 // long double, char16_t, char32_t, and the IEEE 754r decimal and
2690 // half-precision floating point types.
Richard Smith4a382012016-02-03 01:32:42 +00002691 //
2692 // GCC also emits RTTI for __int128.
2693 // FIXME: We do not emit RTTI information for decimal types here.
2694
2695 // Types added here must also be added to EmitFundamentalRTTIDescriptors.
David Majnemere2cb8d12014-07-07 06:20:47 +00002696 switch (Ty->getKind()) {
2697 case BuiltinType::Void:
2698 case BuiltinType::NullPtr:
2699 case BuiltinType::Bool:
2700 case BuiltinType::WChar_S:
2701 case BuiltinType::WChar_U:
2702 case BuiltinType::Char_U:
2703 case BuiltinType::Char_S:
2704 case BuiltinType::UChar:
2705 case BuiltinType::SChar:
2706 case BuiltinType::Short:
2707 case BuiltinType::UShort:
2708 case BuiltinType::Int:
2709 case BuiltinType::UInt:
2710 case BuiltinType::Long:
2711 case BuiltinType::ULong:
2712 case BuiltinType::LongLong:
2713 case BuiltinType::ULongLong:
2714 case BuiltinType::Half:
2715 case BuiltinType::Float:
2716 case BuiltinType::Double:
2717 case BuiltinType::LongDouble:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00002718 case BuiltinType::Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002719 case BuiltinType::Float128:
Richard Smith3a8244d2018-05-01 05:02:45 +00002720 case BuiltinType::Char8:
David Majnemere2cb8d12014-07-07 06:20:47 +00002721 case BuiltinType::Char16:
2722 case BuiltinType::Char32:
2723 case BuiltinType::Int128:
2724 case BuiltinType::UInt128:
Richard Smith4a382012016-02-03 01:32:42 +00002725 return true;
2726
Alexey Bader954ba212016-04-08 13:40:33 +00002727#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2728 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00002729#include "clang/Basic/OpenCLImageTypes.def"
David Majnemere2cb8d12014-07-07 06:20:47 +00002730 case BuiltinType::OCLSampler:
2731 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002732 case BuiltinType::OCLClkEvent:
2733 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002734 case BuiltinType::OCLReserveID:
Leonard Chanf921d852018-06-04 16:07:52 +00002735 case BuiltinType::ShortAccum:
2736 case BuiltinType::Accum:
2737 case BuiltinType::LongAccum:
2738 case BuiltinType::UShortAccum:
2739 case BuiltinType::UAccum:
2740 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00002741 case BuiltinType::ShortFract:
2742 case BuiltinType::Fract:
2743 case BuiltinType::LongFract:
2744 case BuiltinType::UShortFract:
2745 case BuiltinType::UFract:
2746 case BuiltinType::ULongFract:
2747 case BuiltinType::SatShortAccum:
2748 case BuiltinType::SatAccum:
2749 case BuiltinType::SatLongAccum:
2750 case BuiltinType::SatUShortAccum:
2751 case BuiltinType::SatUAccum:
2752 case BuiltinType::SatULongAccum:
2753 case BuiltinType::SatShortFract:
2754 case BuiltinType::SatFract:
2755 case BuiltinType::SatLongFract:
2756 case BuiltinType::SatUShortFract:
2757 case BuiltinType::SatUFract:
2758 case BuiltinType::SatULongFract:
Richard Smith4a382012016-02-03 01:32:42 +00002759 return false;
David Majnemere2cb8d12014-07-07 06:20:47 +00002760
2761 case BuiltinType::Dependent:
2762#define BUILTIN_TYPE(Id, SingletonId)
2763#define PLACEHOLDER_TYPE(Id, SingletonId) \
2764 case BuiltinType::Id:
2765#include "clang/AST/BuiltinTypes.def"
2766 llvm_unreachable("asking for RRTI for a placeholder type!");
2767
2768 case BuiltinType::ObjCId:
2769 case BuiltinType::ObjCClass:
2770 case BuiltinType::ObjCSel:
2771 llvm_unreachable("FIXME: Objective-C types are unsupported!");
2772 }
2773
2774 llvm_unreachable("Invalid BuiltinType Kind!");
2775}
2776
2777static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2778 QualType PointeeTy = PointerTy->getPointeeType();
2779 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2780 if (!BuiltinTy)
2781 return false;
2782
2783 // Check the qualifiers.
2784 Qualifiers Quals = PointeeTy.getQualifiers();
2785 Quals.removeConst();
2786
2787 if (!Quals.empty())
2788 return false;
2789
2790 return TypeInfoIsInStandardLibrary(BuiltinTy);
2791}
2792
2793/// IsStandardLibraryRTTIDescriptor - Returns whether the type
2794/// information for the given type exists in the standard library.
2795static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2796 // Type info for builtin types is defined in the standard library.
2797 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2798 return TypeInfoIsInStandardLibrary(BuiltinTy);
2799
2800 // Type info for some pointer types to builtin types is defined in the
2801 // standard library.
2802 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2803 return TypeInfoIsInStandardLibrary(PointerTy);
2804
2805 return false;
2806}
2807
2808/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
2809/// the given type exists somewhere else, and that we should not emit the type
2810/// information in this translation unit. Assumes that it is not a
2811/// standard-library type.
2812static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
2813 QualType Ty) {
2814 ASTContext &Context = CGM.getContext();
2815
2816 // If RTTI is disabled, assume it might be disabled in the
2817 // translation unit that defines any potential key function, too.
2818 if (!Context.getLangOpts().RTTI) return false;
2819
2820 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2821 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2822 if (!RD->hasDefinition())
2823 return false;
2824
2825 if (!RD->isDynamicClass())
2826 return false;
2827
2828 // FIXME: this may need to be reconsidered if the key function
2829 // changes.
David Majnemerbe9022c2015-08-06 20:56:55 +00002830 // N.B. We must always emit the RTTI data ourselves if there exists a key
2831 // function.
2832 bool IsDLLImport = RD->hasAttr<DLLImportAttr>();
Martin Storsjo3b528942018-02-02 06:22:35 +00002833
2834 // Don't import the RTTI but emit it locally.
2835 if (CGM.getTriple().isWindowsGNUEnvironment() && IsDLLImport)
2836 return false;
2837
David Majnemer1fb1a042014-11-07 07:26:38 +00002838 if (CGM.getVTables().isVTableExternal(RD))
Shoaib Meenai61118e72017-07-04 01:02:19 +00002839 return IsDLLImport && !CGM.getTriple().isWindowsItaniumEnvironment()
2840 ? false
2841 : true;
David Majnemer1fb1a042014-11-07 07:26:38 +00002842
David Majnemerbe9022c2015-08-06 20:56:55 +00002843 if (IsDLLImport)
David Majnemer1fb1a042014-11-07 07:26:38 +00002844 return true;
David Majnemere2cb8d12014-07-07 06:20:47 +00002845 }
2846
2847 return false;
2848}
2849
2850/// IsIncompleteClassType - Returns whether the given record type is incomplete.
2851static bool IsIncompleteClassType(const RecordType *RecordTy) {
2852 return !RecordTy->getDecl()->isCompleteDefinition();
2853}
2854
2855/// ContainsIncompleteClassType - Returns whether the given type contains an
2856/// incomplete class type. This is true if
2857///
2858/// * The given type is an incomplete class type.
2859/// * The given type is a pointer type whose pointee type contains an
2860/// incomplete class type.
2861/// * The given type is a member pointer type whose class is an incomplete
2862/// class type.
2863/// * The given type is a member pointer type whoise pointee type contains an
2864/// incomplete class type.
2865/// is an indirect or direct pointer to an incomplete class type.
2866static bool ContainsIncompleteClassType(QualType Ty) {
2867 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2868 if (IsIncompleteClassType(RecordTy))
2869 return true;
2870 }
2871
2872 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2873 return ContainsIncompleteClassType(PointerTy->getPointeeType());
2874
2875 if (const MemberPointerType *MemberPointerTy =
2876 dyn_cast<MemberPointerType>(Ty)) {
2877 // Check if the class type is incomplete.
2878 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
2879 if (IsIncompleteClassType(ClassType))
2880 return true;
2881
2882 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
2883 }
2884
2885 return false;
2886}
2887
2888// CanUseSingleInheritance - Return whether the given record decl has a "single,
2889// public, non-virtual base at offset zero (i.e. the derived class is dynamic
2890// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
2891static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
2892 // Check the number of bases.
2893 if (RD->getNumBases() != 1)
2894 return false;
2895
2896 // Get the base.
2897 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
2898
2899 // Check that the base is not virtual.
2900 if (Base->isVirtual())
2901 return false;
2902
2903 // Check that the base is public.
2904 if (Base->getAccessSpecifier() != AS_public)
2905 return false;
2906
2907 // Check that the class is dynamic iff the base is.
2908 const CXXRecordDecl *BaseDecl =
2909 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2910 if (!BaseDecl->isEmpty() &&
2911 BaseDecl->isDynamicClass() != RD->isDynamicClass())
2912 return false;
2913
2914 return true;
2915}
2916
2917void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
2918 // abi::__class_type_info.
2919 static const char * const ClassTypeInfo =
2920 "_ZTVN10__cxxabiv117__class_type_infoE";
2921 // abi::__si_class_type_info.
2922 static const char * const SIClassTypeInfo =
2923 "_ZTVN10__cxxabiv120__si_class_type_infoE";
2924 // abi::__vmi_class_type_info.
2925 static const char * const VMIClassTypeInfo =
2926 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
2927
2928 const char *VTableName = nullptr;
2929
2930 switch (Ty->getTypeClass()) {
2931#define TYPE(Class, Base)
2932#define ABSTRACT_TYPE(Class, Base)
2933#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2934#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2935#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2936#include "clang/AST/TypeNodes.def"
2937 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2938
2939 case Type::LValueReference:
2940 case Type::RValueReference:
2941 llvm_unreachable("References shouldn't get here");
2942
2943 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00002944 case Type::DeducedTemplateSpecialization:
2945 llvm_unreachable("Undeduced type shouldn't get here");
David Majnemere2cb8d12014-07-07 06:20:47 +00002946
Xiuli Pan9c14e282016-01-09 12:53:17 +00002947 case Type::Pipe:
2948 llvm_unreachable("Pipe types shouldn't get here");
2949
David Majnemere2cb8d12014-07-07 06:20:47 +00002950 case Type::Builtin:
2951 // GCC treats vector and complex types as fundamental types.
2952 case Type::Vector:
2953 case Type::ExtVector:
2954 case Type::Complex:
2955 case Type::Atomic:
2956 // FIXME: GCC treats block pointers as fundamental types?!
2957 case Type::BlockPointer:
2958 // abi::__fundamental_type_info.
2959 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
2960 break;
2961
2962 case Type::ConstantArray:
2963 case Type::IncompleteArray:
2964 case Type::VariableArray:
2965 // abi::__array_type_info.
2966 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
2967 break;
2968
2969 case Type::FunctionNoProto:
2970 case Type::FunctionProto:
Richard Smithb17d6fa2016-12-01 03:04:07 +00002971 // abi::__function_type_info.
2972 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
David Majnemere2cb8d12014-07-07 06:20:47 +00002973 break;
2974
2975 case Type::Enum:
2976 // abi::__enum_type_info.
2977 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
2978 break;
2979
2980 case Type::Record: {
Rafael Espindolaf6688122018-03-22 21:14:16 +00002981 const CXXRecordDecl *RD =
2982 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
David Majnemere2cb8d12014-07-07 06:20:47 +00002983
2984 if (!RD->hasDefinition() || !RD->getNumBases()) {
2985 VTableName = ClassTypeInfo;
2986 } else if (CanUseSingleInheritance(RD)) {
2987 VTableName = SIClassTypeInfo;
2988 } else {
2989 VTableName = VMIClassTypeInfo;
2990 }
2991
2992 break;
2993 }
2994
2995 case Type::ObjCObject:
2996 // Ignore protocol qualifiers.
2997 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
2998
2999 // Handle id and Class.
3000 if (isa<BuiltinType>(Ty)) {
3001 VTableName = ClassTypeInfo;
3002 break;
3003 }
3004
3005 assert(isa<ObjCInterfaceType>(Ty));
3006 // Fall through.
3007
3008 case Type::ObjCInterface:
3009 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
3010 VTableName = SIClassTypeInfo;
3011 } else {
3012 VTableName = ClassTypeInfo;
3013 }
3014 break;
3015
3016 case Type::ObjCObjectPointer:
3017 case Type::Pointer:
3018 // abi::__pointer_type_info.
3019 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
3020 break;
3021
3022 case Type::MemberPointer:
3023 // abi::__pointer_to_member_type_info.
3024 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
3025 break;
3026 }
3027
3028 llvm::Constant *VTable =
3029 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
Rafael Espindolafe9a55a2018-03-23 01:36:23 +00003030 CGM.setDSOLocal(cast<llvm::GlobalValue>(VTable->stripPointerCasts()));
David Majnemere2cb8d12014-07-07 06:20:47 +00003031
3032 llvm::Type *PtrDiffTy =
3033 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
3034
3035 // The vtable address point is 2.
3036 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00003037 VTable =
3038 llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.Int8PtrTy, VTable, Two);
David Majnemere2cb8d12014-07-07 06:20:47 +00003039 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
3040
3041 Fields.push_back(VTable);
3042}
3043
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003044/// Return the linkage that the type info and type info name constants
David Majnemere2cb8d12014-07-07 06:20:47 +00003045/// should have for the given type.
Richard Smithbbb26552018-05-21 20:10:54 +00003046static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
3047 QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003048 // Itanium C++ ABI 2.9.5p7:
3049 // In addition, it and all of the intermediate abi::__pointer_type_info
3050 // structs in the chain down to the abi::__class_type_info for the
3051 // incomplete class type must be prevented from resolving to the
3052 // corresponding type_info structs for the complete class type, possibly
3053 // by making them local static objects. Finally, a dummy class RTTI is
3054 // generated for the incomplete type that will not resolve to the final
3055 // complete class RTTI (because the latter need not exist), possibly by
3056 // making it a local static object.
3057 if (ContainsIncompleteClassType(Ty))
Richard Smithbbb26552018-05-21 20:10:54 +00003058 return llvm::GlobalValue::InternalLinkage;
3059
3060 switch (Ty->getLinkage()) {
3061 case NoLinkage:
3062 case InternalLinkage:
3063 case UniqueExternalLinkage:
3064 return llvm::GlobalValue::InternalLinkage;
3065
3066 case VisibleNoLinkage:
3067 case ModuleInternalLinkage:
3068 case ModuleLinkage:
3069 case ExternalLinkage:
3070 // RTTI is not enabled, which means that this type info struct is going
3071 // to be used for exception handling. Give it linkonce_odr linkage.
3072 if (!CGM.getLangOpts().RTTI)
3073 return llvm::GlobalValue::LinkOnceODRLinkage;
3074
3075 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
3076 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
3077 if (RD->hasAttr<WeakAttr>())
3078 return llvm::GlobalValue::WeakODRLinkage;
3079 if (CGM.getTriple().isWindowsItaniumEnvironment())
3080 if (RD->hasAttr<DLLImportAttr>() &&
3081 ShouldUseExternalRTTIDescriptor(CGM, Ty))
3082 return llvm::GlobalValue::ExternalLinkage;
3083 // MinGW always uses LinkOnceODRLinkage for type info.
3084 if (RD->isDynamicClass() &&
3085 !CGM.getContext()
3086 .getTargetInfo()
3087 .getTriple()
3088 .isWindowsGNUEnvironment())
3089 return CGM.getVTableLinkage(RD);
3090 }
3091
3092 return llvm::GlobalValue::LinkOnceODRLinkage;
3093 }
3094
3095 llvm_unreachable("Invalid linkage!");
David Majnemere2cb8d12014-07-07 06:20:47 +00003096}
3097
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003098llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force,
3099 bool DLLExport) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003100 // We want to operate on the canonical type.
Yaron Kerenebd14262016-03-16 12:14:43 +00003101 Ty = Ty.getCanonicalType();
David Majnemere2cb8d12014-07-07 06:20:47 +00003102
3103 // Check if we've already emitted an RTTI descriptor for this type.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00003104 SmallString<256> Name;
3105 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00003106 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00003107
3108 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
3109 if (OldGV && !OldGV->isDeclaration()) {
3110 assert(!OldGV->hasAvailableExternallyLinkage() &&
3111 "available_externally typeinfos not yet implemented");
3112
3113 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
3114 }
3115
3116 // Check if there is already an external RTTI descriptor for this type.
3117 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
3118 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
3119 return GetAddrOfExternalRTTIDescriptor(Ty);
3120
3121 // Emit the standard library with external linkage.
Richard Smithbbb26552018-05-21 20:10:54 +00003122 llvm::GlobalVariable::LinkageTypes Linkage;
David Majnemere2cb8d12014-07-07 06:20:47 +00003123 if (IsStdLib)
Richard Smithbbb26552018-05-21 20:10:54 +00003124 Linkage = llvm::GlobalValue::ExternalLinkage;
3125 else
3126 Linkage = getTypeInfoLinkage(CGM, Ty);
3127
David Majnemere2cb8d12014-07-07 06:20:47 +00003128 // Add the vtable pointer.
3129 BuildVTablePointer(cast<Type>(Ty));
3130
3131 // And the name.
Richard Smithbbb26552018-05-21 20:10:54 +00003132 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
David Majnemere2cb8d12014-07-07 06:20:47 +00003133 llvm::Constant *TypeNameField;
3134
3135 // If we're supposed to demote the visibility, be sure to set a flag
3136 // to use a string comparison for type_info comparisons.
3137 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
Richard Smithbbb26552018-05-21 20:10:54 +00003138 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
David Majnemere2cb8d12014-07-07 06:20:47 +00003139 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
3140 // The flag is the sign bit, which on ARM64 is defined to be clear
3141 // for global pointers. This is very ARM64-specific.
3142 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
3143 llvm::Constant *flag =
3144 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
3145 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
3146 TypeNameField =
3147 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
3148 } else {
3149 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
3150 }
3151 Fields.push_back(TypeNameField);
3152
3153 switch (Ty->getTypeClass()) {
3154#define TYPE(Class, Base)
3155#define ABSTRACT_TYPE(Class, Base)
3156#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3157#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3158#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3159#include "clang/AST/TypeNodes.def"
3160 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
3161
3162 // GCC treats vector types as fundamental types.
3163 case Type::Builtin:
3164 case Type::Vector:
3165 case Type::ExtVector:
3166 case Type::Complex:
3167 case Type::BlockPointer:
3168 // Itanium C++ ABI 2.9.5p4:
3169 // abi::__fundamental_type_info adds no data members to std::type_info.
3170 break;
3171
3172 case Type::LValueReference:
3173 case Type::RValueReference:
3174 llvm_unreachable("References shouldn't get here");
3175
3176 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00003177 case Type::DeducedTemplateSpecialization:
3178 llvm_unreachable("Undeduced type shouldn't get here");
David Majnemere2cb8d12014-07-07 06:20:47 +00003179
Xiuli Pan9c14e282016-01-09 12:53:17 +00003180 case Type::Pipe:
3181 llvm_unreachable("Pipe type shouldn't get here");
3182
David Majnemere2cb8d12014-07-07 06:20:47 +00003183 case Type::ConstantArray:
3184 case Type::IncompleteArray:
3185 case Type::VariableArray:
3186 // Itanium C++ ABI 2.9.5p5:
3187 // abi::__array_type_info adds no data members to std::type_info.
3188 break;
3189
3190 case Type::FunctionNoProto:
Richard Smithb17d6fa2016-12-01 03:04:07 +00003191 case Type::FunctionProto:
David Majnemere2cb8d12014-07-07 06:20:47 +00003192 // Itanium C++ ABI 2.9.5p5:
3193 // abi::__function_type_info adds no data members to std::type_info.
3194 break;
3195
3196 case Type::Enum:
3197 // Itanium C++ ABI 2.9.5p5:
3198 // abi::__enum_type_info adds no data members to std::type_info.
3199 break;
3200
3201 case Type::Record: {
3202 const CXXRecordDecl *RD =
3203 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
3204 if (!RD->hasDefinition() || !RD->getNumBases()) {
3205 // We don't need to emit any fields.
3206 break;
3207 }
3208
3209 if (CanUseSingleInheritance(RD))
3210 BuildSIClassTypeInfo(RD);
3211 else
3212 BuildVMIClassTypeInfo(RD);
3213
3214 break;
3215 }
3216
3217 case Type::ObjCObject:
3218 case Type::ObjCInterface:
3219 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
3220 break;
3221
3222 case Type::ObjCObjectPointer:
3223 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
3224 break;
3225
3226 case Type::Pointer:
3227 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
3228 break;
3229
3230 case Type::MemberPointer:
3231 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
3232 break;
3233
3234 case Type::Atomic:
3235 // No fields, at least for the moment.
3236 break;
3237 }
3238
3239 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
3240
Rafael Espindolacb92c192015-01-15 23:18:01 +00003241 llvm::Module &M = CGM.getModule();
David Majnemere2cb8d12014-07-07 06:20:47 +00003242 llvm::GlobalVariable *GV =
Rafael Espindolacb92c192015-01-15 23:18:01 +00003243 new llvm::GlobalVariable(M, Init->getType(),
Richard Smithbbb26552018-05-21 20:10:54 +00003244 /*Constant=*/true, Linkage, Init, Name);
Rafael Espindolacb92c192015-01-15 23:18:01 +00003245
David Majnemere2cb8d12014-07-07 06:20:47 +00003246 // If there's already an old global variable, replace it with the new one.
3247 if (OldGV) {
3248 GV->takeName(OldGV);
3249 llvm::Constant *NewPtr =
3250 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3251 OldGV->replaceAllUsesWith(NewPtr);
3252 OldGV->eraseFromParent();
3253 }
3254
Yaron Keren04da2382015-07-29 15:42:28 +00003255 if (CGM.supportsCOMDAT() && GV->isWeakForLinker())
3256 GV->setComdat(M.getOrInsertComdat(GV->getName()));
3257
David Majnemere2cb8d12014-07-07 06:20:47 +00003258 // The Itanium ABI specifies that type_info objects must be globally
3259 // unique, with one exception: if the type is an incomplete class
3260 // type or a (possibly indirect) pointer to one. That exception
3261 // affects the general case of comparing type_info objects produced
3262 // by the typeid operator, which is why the comparison operators on
3263 // std::type_info generally use the type_info name pointers instead
3264 // of the object addresses. However, the language's built-in uses
3265 // of RTTI generally require class types to be complete, even when
3266 // manipulating pointers to those class types. This allows the
3267 // implementation of dynamic_cast to rely on address equality tests,
3268 // which is much faster.
3269
3270 // All of this is to say that it's important that both the type_info
3271 // object and the type_info name be uniqued when weakly emitted.
3272
3273 // Give the type_info object and name the formal visibility of the
3274 // type itself.
Richard Smithbbb26552018-05-21 20:10:54 +00003275 llvm::GlobalValue::VisibilityTypes llvmVisibility;
3276 if (llvm::GlobalValue::isLocalLinkage(Linkage))
3277 // If the linkage is local, only default visibility makes sense.
3278 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
3279 else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden)
3280 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
3281 else
3282 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003283
Richard Smithbbb26552018-05-21 20:10:54 +00003284 TypeName->setVisibility(llvmVisibility);
Rafael Espindola3dd49812018-02-23 00:22:15 +00003285 CGM.setDSOLocal(TypeName);
Rafael Espindola699f5d62018-02-07 22:15:33 +00003286
Richard Smithbbb26552018-05-21 20:10:54 +00003287 GV->setVisibility(llvmVisibility);
Rafael Espindola3dd49812018-02-23 00:22:15 +00003288 CGM.setDSOLocal(GV);
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003289
3290 if (CGM.getTriple().isWindowsItaniumEnvironment()) {
3291 auto RD = Ty->getAsCXXRecordDecl();
3292 if (DLLExport || (RD && RD->hasAttr<DLLExportAttr>())) {
3293 TypeName->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
3294 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
Shoaib Meenai61118e72017-07-04 01:02:19 +00003295 } else if (RD && RD->hasAttr<DLLImportAttr>() &&
3296 ShouldUseExternalRTTIDescriptor(CGM, Ty)) {
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003297 TypeName->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3298 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3299
3300 // Because the typename and the typeinfo are DLL import, convert them to
3301 // declarations rather than definitions. The initializers still need to
3302 // be constructed to calculate the type for the declarations.
3303 TypeName->setInitializer(nullptr);
3304 GV->setInitializer(nullptr);
3305 }
3306 }
David Majnemere2cb8d12014-07-07 06:20:47 +00003307
3308 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
3309}
3310
David Majnemere2cb8d12014-07-07 06:20:47 +00003311/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
3312/// for the given Objective-C object type.
3313void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
3314 // Drop qualifiers.
3315 const Type *T = OT->getBaseType().getTypePtr();
3316 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
3317
3318 // The builtin types are abi::__class_type_infos and don't require
3319 // extra fields.
3320 if (isa<BuiltinType>(T)) return;
3321
3322 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
3323 ObjCInterfaceDecl *Super = Class->getSuperClass();
3324
3325 // Root classes are also __class_type_info.
3326 if (!Super) return;
3327
3328 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
3329
3330 // Everything else is single inheritance.
3331 llvm::Constant *BaseTypeInfo =
3332 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
3333 Fields.push_back(BaseTypeInfo);
3334}
3335
3336/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
3337/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
3338void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
3339 // Itanium C++ ABI 2.9.5p6b:
3340 // It adds to abi::__class_type_info a single member pointing to the
3341 // type_info structure for the base type,
3342 llvm::Constant *BaseTypeInfo =
3343 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
3344 Fields.push_back(BaseTypeInfo);
3345}
3346
3347namespace {
3348 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
3349 /// a class hierarchy.
3350 struct SeenBases {
3351 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
3352 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
3353 };
3354}
3355
3356/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
3357/// abi::__vmi_class_type_info.
3358///
3359static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
3360 SeenBases &Bases) {
3361
3362 unsigned Flags = 0;
3363
3364 const CXXRecordDecl *BaseDecl =
3365 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
3366
3367 if (Base->isVirtual()) {
3368 // Mark the virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003369 if (!Bases.VirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003370 // If this virtual base has been seen before, then the class is diamond
3371 // shaped.
3372 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
3373 } else {
3374 if (Bases.NonVirtualBases.count(BaseDecl))
3375 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3376 }
3377 } else {
3378 // Mark the non-virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003379 if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003380 // If this non-virtual base has been seen before, then the class has non-
3381 // diamond shaped repeated inheritance.
3382 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3383 } else {
3384 if (Bases.VirtualBases.count(BaseDecl))
3385 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3386 }
3387 }
3388
3389 // Walk all bases.
3390 for (const auto &I : BaseDecl->bases())
3391 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3392
3393 return Flags;
3394}
3395
3396static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
3397 unsigned Flags = 0;
3398 SeenBases Bases;
3399
3400 // Walk all bases.
3401 for (const auto &I : RD->bases())
3402 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3403
3404 return Flags;
3405}
3406
3407/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
3408/// classes with bases that do not satisfy the abi::__si_class_type_info
3409/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
3410void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
3411 llvm::Type *UnsignedIntLTy =
3412 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3413
3414 // Itanium C++ ABI 2.9.5p6c:
3415 // __flags is a word with flags describing details about the class
3416 // structure, which may be referenced by using the __flags_masks
3417 // enumeration. These flags refer to both direct and indirect bases.
3418 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
3419 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3420
3421 // Itanium C++ ABI 2.9.5p6c:
3422 // __base_count is a word with the number of direct proper base class
3423 // descriptions that follow.
3424 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
3425
3426 if (!RD->getNumBases())
3427 return;
3428
David Majnemere2cb8d12014-07-07 06:20:47 +00003429 // Now add the base class descriptions.
3430
3431 // Itanium C++ ABI 2.9.5p6c:
3432 // __base_info[] is an array of base class descriptions -- one for every
3433 // direct proper base. Each description is of the type:
3434 //
3435 // struct abi::__base_class_type_info {
3436 // public:
3437 // const __class_type_info *__base_type;
3438 // long __offset_flags;
3439 //
3440 // enum __offset_flags_masks {
3441 // __virtual_mask = 0x1,
3442 // __public_mask = 0x2,
3443 // __offset_shift = 8
3444 // };
3445 // };
Reid Klecknerd8b04662016-08-25 22:16:30 +00003446
3447 // If we're in mingw and 'long' isn't wide enough for a pointer, use 'long
3448 // long' instead of 'long' for __offset_flags. libstdc++abi uses long long on
3449 // LLP64 platforms.
3450 // FIXME: Consider updating libc++abi to match, and extend this logic to all
3451 // LLP64 platforms.
3452 QualType OffsetFlagsTy = CGM.getContext().LongTy;
3453 const TargetInfo &TI = CGM.getContext().getTargetInfo();
3454 if (TI.getTriple().isOSCygMing() && TI.getPointerWidth(0) > TI.getLongWidth())
3455 OffsetFlagsTy = CGM.getContext().LongLongTy;
3456 llvm::Type *OffsetFlagsLTy =
3457 CGM.getTypes().ConvertType(OffsetFlagsTy);
3458
David Majnemere2cb8d12014-07-07 06:20:47 +00003459 for (const auto &Base : RD->bases()) {
3460 // The __base_type member points to the RTTI for the base type.
3461 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
3462
3463 const CXXRecordDecl *BaseDecl =
3464 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
3465
3466 int64_t OffsetFlags = 0;
3467
3468 // All but the lower 8 bits of __offset_flags are a signed offset.
3469 // For a non-virtual base, this is the offset in the object of the base
3470 // subobject. For a virtual base, this is the offset in the virtual table of
3471 // the virtual base offset for the virtual base referenced (negative).
3472 CharUnits Offset;
3473 if (Base.isVirtual())
3474 Offset =
3475 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
3476 else {
3477 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
3478 Offset = Layout.getBaseClassOffset(BaseDecl);
3479 };
3480
3481 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
3482
3483 // The low-order byte of __offset_flags contains flags, as given by the
3484 // masks from the enumeration __offset_flags_masks.
3485 if (Base.isVirtual())
3486 OffsetFlags |= BCTI_Virtual;
3487 if (Base.getAccessSpecifier() == AS_public)
3488 OffsetFlags |= BCTI_Public;
3489
Reid Klecknerd8b04662016-08-25 22:16:30 +00003490 Fields.push_back(llvm::ConstantInt::get(OffsetFlagsLTy, OffsetFlags));
David Majnemere2cb8d12014-07-07 06:20:47 +00003491 }
3492}
3493
Richard Smitha7d93782016-12-01 03:32:42 +00003494/// Compute the flags for a __pbase_type_info, and remove the corresponding
3495/// pieces from \p Type.
3496static unsigned extractPBaseFlags(ASTContext &Ctx, QualType &Type) {
3497 unsigned Flags = 0;
David Majnemere2cb8d12014-07-07 06:20:47 +00003498
Richard Smitha7d93782016-12-01 03:32:42 +00003499 if (Type.isConstQualified())
3500 Flags |= ItaniumRTTIBuilder::PTI_Const;
3501 if (Type.isVolatileQualified())
3502 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
3503 if (Type.isRestrictQualified())
3504 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
3505 Type = Type.getUnqualifiedType();
David Majnemere2cb8d12014-07-07 06:20:47 +00003506
3507 // Itanium C++ ABI 2.9.5p7:
3508 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3509 // incomplete class type, the incomplete target type flag is set.
Richard Smitha7d93782016-12-01 03:32:42 +00003510 if (ContainsIncompleteClassType(Type))
3511 Flags |= ItaniumRTTIBuilder::PTI_Incomplete;
3512
3513 if (auto *Proto = Type->getAs<FunctionProtoType>()) {
Richard Smitheaf11ad2018-05-03 03:58:32 +00003514 if (Proto->isNothrow()) {
Richard Smitha7d93782016-12-01 03:32:42 +00003515 Flags |= ItaniumRTTIBuilder::PTI_Noexcept;
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00003516 Type = Ctx.getFunctionTypeWithExceptionSpec(Type, EST_None);
Richard Smitha7d93782016-12-01 03:32:42 +00003517 }
3518 }
3519
3520 return Flags;
3521}
3522
3523/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
3524/// used for pointer types.
3525void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
3526 // Itanium C++ ABI 2.9.5p7:
3527 // __flags is a flag word describing the cv-qualification and other
3528 // attributes of the type pointed to
3529 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003530
3531 llvm::Type *UnsignedIntLTy =
3532 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3533 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3534
3535 // Itanium C++ ABI 2.9.5p7:
3536 // __pointee is a pointer to the std::type_info derivation for the
3537 // unqualified type being pointed to.
3538 llvm::Constant *PointeeTypeInfo =
Richard Smitha7d93782016-12-01 03:32:42 +00003539 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003540 Fields.push_back(PointeeTypeInfo);
3541}
3542
3543/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
3544/// struct, used for member pointer types.
3545void
3546ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
3547 QualType PointeeTy = Ty->getPointeeType();
3548
David Majnemere2cb8d12014-07-07 06:20:47 +00003549 // Itanium C++ ABI 2.9.5p7:
3550 // __flags is a flag word describing the cv-qualification and other
3551 // attributes of the type pointed to.
Richard Smitha7d93782016-12-01 03:32:42 +00003552 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003553
3554 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
David Majnemere2cb8d12014-07-07 06:20:47 +00003555 if (IsIncompleteClassType(ClassType))
3556 Flags |= PTI_ContainingClassIncomplete;
3557
3558 llvm::Type *UnsignedIntLTy =
3559 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3560 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3561
3562 // Itanium C++ ABI 2.9.5p7:
3563 // __pointee is a pointer to the std::type_info derivation for the
3564 // unqualified type being pointed to.
3565 llvm::Constant *PointeeTypeInfo =
Richard Smitha7d93782016-12-01 03:32:42 +00003566 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003567 Fields.push_back(PointeeTypeInfo);
3568
3569 // Itanium C++ ABI 2.9.5p9:
3570 // __context is a pointer to an abi::__class_type_info corresponding to the
3571 // class type containing the member pointed to
3572 // (e.g., the "A" in "int A::*").
3573 Fields.push_back(
3574 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
3575}
3576
David Majnemer443250f2015-03-17 20:35:00 +00003577llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003578 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
3579}
3580
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003581void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type,
3582 bool DLLExport) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003583 QualType PointerType = getContext().getPointerType(Type);
3584 QualType PointerTypeConst = getContext().getPointerType(Type.withConst());
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003585 ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, /*Force=*/true, DLLExport);
3586 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, /*Force=*/true,
3587 DLLExport);
3588 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, /*Force=*/true,
3589 DLLExport);
David Majnemere2cb8d12014-07-07 06:20:47 +00003590}
3591
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003592void ItaniumCXXABI::EmitFundamentalRTTIDescriptors(bool DLLExport) {
Richard Smith4a382012016-02-03 01:32:42 +00003593 // Types added here must also be added to TypeInfoIsInStandardLibrary.
David Majnemere2cb8d12014-07-07 06:20:47 +00003594 QualType FundamentalTypes[] = {
3595 getContext().VoidTy, getContext().NullPtrTy,
3596 getContext().BoolTy, getContext().WCharTy,
3597 getContext().CharTy, getContext().UnsignedCharTy,
3598 getContext().SignedCharTy, getContext().ShortTy,
3599 getContext().UnsignedShortTy, getContext().IntTy,
3600 getContext().UnsignedIntTy, getContext().LongTy,
3601 getContext().UnsignedLongTy, getContext().LongLongTy,
Richard Smith4a382012016-02-03 01:32:42 +00003602 getContext().UnsignedLongLongTy, getContext().Int128Ty,
3603 getContext().UnsignedInt128Ty, getContext().HalfTy,
David Majnemere2cb8d12014-07-07 06:20:47 +00003604 getContext().FloatTy, getContext().DoubleTy,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00003605 getContext().LongDoubleTy, getContext().Float128Ty,
Richard Smith3a8244d2018-05-01 05:02:45 +00003606 getContext().Char8Ty, getContext().Char16Ty,
3607 getContext().Char32Ty
David Majnemere2cb8d12014-07-07 06:20:47 +00003608 };
3609 for (const QualType &FundamentalType : FundamentalTypes)
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003610 EmitFundamentalRTTIDescriptor(FundamentalType, DLLExport);
David Majnemere2cb8d12014-07-07 06:20:47 +00003611}
3612
3613/// What sort of uniqueness rules should we use for the RTTI for the
3614/// given type?
3615ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
3616 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
3617 if (shouldRTTIBeUnique())
3618 return RUK_Unique;
3619
3620 // It's only necessary for linkonce_odr or weak_odr linkage.
3621 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
3622 Linkage != llvm::GlobalValue::WeakODRLinkage)
3623 return RUK_Unique;
3624
3625 // It's only necessary with default visibility.
3626 if (CanTy->getVisibility() != DefaultVisibility)
3627 return RUK_Unique;
3628
3629 // If we're not required to publish this symbol, hide it.
3630 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3631 return RUK_NonUniqueHidden;
3632
3633 // If we're required to publish this symbol, as we might be under an
3634 // explicit instantiation, leave it with default visibility but
3635 // enable string-comparisons.
3636 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
3637 return RUK_NonUniqueVisible;
3638}
Rafael Espindola91f68b42014-09-15 19:20:10 +00003639
Rafael Espindola1e4df922014-09-16 15:18:21 +00003640// Find out how to codegen the complete destructor and constructor
3641namespace {
3642enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
3643}
3644static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
3645 const CXXMethodDecl *MD) {
3646 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
3647 return StructorCodegen::Emit;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003648
Rafael Espindola1e4df922014-09-16 15:18:21 +00003649 // The complete and base structors are not equivalent if there are any virtual
3650 // bases, so emit separate functions.
3651 if (MD->getParent()->getNumVBases())
3652 return StructorCodegen::Emit;
3653
3654 GlobalDecl AliasDecl;
3655 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3656 AliasDecl = GlobalDecl(DD, Dtor_Complete);
3657 } else {
3658 const auto *CD = cast<CXXConstructorDecl>(MD);
3659 AliasDecl = GlobalDecl(CD, Ctor_Complete);
3660 }
3661 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3662
Richard Smith6ca999b2018-05-30 00:45:10 +00003663 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
3664 return StructorCodegen::RAUW;
Rafael Espindola1e4df922014-09-16 15:18:21 +00003665
Pavel Labathc370f262018-05-14 11:35:44 +00003666 // FIXME: Should we allow available_externally aliases?
Richard Smith6ca999b2018-05-30 00:45:10 +00003667 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
3668 return StructorCodegen::RAUW;
Rafael Espindola1e4df922014-09-16 15:18:21 +00003669
Rafael Espindola0806f982014-09-16 20:19:43 +00003670 if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
Dan Gohman839f2152017-01-17 21:46:38 +00003671 // Only ELF and wasm support COMDATs with arbitrary names (C5/D5).
3672 if (CGM.getTarget().getTriple().isOSBinFormatELF() ||
3673 CGM.getTarget().getTriple().isOSBinFormatWasm())
Rafael Espindola0806f982014-09-16 20:19:43 +00003674 return StructorCodegen::COMDAT;
3675 return StructorCodegen::Emit;
3676 }
Rafael Espindola1e4df922014-09-16 15:18:21 +00003677
3678 return StructorCodegen::Alias;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003679}
3680
Rafael Espindola1e4df922014-09-16 15:18:21 +00003681static void emitConstructorDestructorAlias(CodeGenModule &CGM,
3682 GlobalDecl AliasDecl,
3683 GlobalDecl TargetDecl) {
3684 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3685
3686 StringRef MangledName = CGM.getMangledName(AliasDecl);
3687 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
3688 if (Entry && !Entry->isDeclaration())
3689 return;
3690
3691 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
Rafael Espindola1e4df922014-09-16 15:18:21 +00003692
3693 // Create the alias with no name.
David Blaikie2a791d72015-09-14 18:38:22 +00003694 auto *Alias = llvm::GlobalAlias::create(Linkage, "", Aliasee);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003695
3696 // Switch any previous uses to the alias.
3697 if (Entry) {
NAKAMURA Takumie9621042015-09-15 01:39:27 +00003698 assert(Entry->getType() == Aliasee->getType() &&
Rafael Espindola1e4df922014-09-16 15:18:21 +00003699 "declaration exists with different type");
3700 Alias->takeName(Entry);
3701 Entry->replaceAllUsesWith(Alias);
3702 Entry->eraseFromParent();
3703 } else {
3704 Alias->setName(MangledName);
3705 }
3706
3707 // Finally, set up the alias with its proper name and attributes.
Rafael Espindolab7350042018-03-01 00:35:47 +00003708 CGM.SetCommonAttributes(AliasDecl, Alias);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003709}
3710
3711void ItaniumCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
3712 StructorType Type) {
3713 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
3714 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
3715
3716 StructorCodegen CGType = getCodegenToUse(CGM, MD);
3717
3718 if (Type == StructorType::Complete) {
3719 GlobalDecl CompleteDecl;
3720 GlobalDecl BaseDecl;
3721 if (CD) {
3722 CompleteDecl = GlobalDecl(CD, Ctor_Complete);
3723 BaseDecl = GlobalDecl(CD, Ctor_Base);
3724 } else {
3725 CompleteDecl = GlobalDecl(DD, Dtor_Complete);
3726 BaseDecl = GlobalDecl(DD, Dtor_Base);
3727 }
3728
3729 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
3730 emitConstructorDestructorAlias(CGM, CompleteDecl, BaseDecl);
3731 return;
3732 }
3733
3734 if (CGType == StructorCodegen::RAUW) {
3735 StringRef MangledName = CGM.getMangledName(CompleteDecl);
Andrey Bokhankocab58582015-08-31 13:20:44 +00003736 auto *Aliasee = CGM.GetAddrOfGlobal(BaseDecl);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003737 CGM.addReplacement(MangledName, Aliasee);
3738 return;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003739 }
3740 }
3741
3742 // The base destructor is equivalent to the base destructor of its
3743 // base class if there is exactly one non-virtual base class with a
3744 // non-trivial destructor, there are no fields with a non-trivial
3745 // destructor, and the body of the destructor is trivial.
Rafael Espindola1e4df922014-09-16 15:18:21 +00003746 if (DD && Type == StructorType::Base && CGType != StructorCodegen::COMDAT &&
3747 !CGM.TryEmitBaseDestructorAsAlias(DD))
Rafael Espindola91f68b42014-09-15 19:20:10 +00003748 return;
3749
Richard Smith5b349582017-10-13 01:55:36 +00003750 // FIXME: The deleting destructor is equivalent to the selected operator
3751 // delete if:
3752 // * either the delete is a destroying operator delete or the destructor
3753 // would be trivial if it weren't virtual,
3754 // * the conversion from the 'this' parameter to the first parameter of the
3755 // destructor is equivalent to a bitcast,
3756 // * the destructor does not have an implicit "this" return, and
3757 // * the operator delete has the same calling convention and IR function type
3758 // as the destructor.
3759 // In such cases we should try to emit the deleting dtor as an alias to the
3760 // selected 'operator delete'.
3761
Rafael Espindola1e4df922014-09-16 15:18:21 +00003762 llvm::Function *Fn = CGM.codegenCXXStructor(MD, Type);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003763
Rafael Espindola1e4df922014-09-16 15:18:21 +00003764 if (CGType == StructorCodegen::COMDAT) {
3765 SmallString<256> Buffer;
3766 llvm::raw_svector_ostream Out(Buffer);
3767 if (DD)
3768 getMangleContext().mangleCXXDtorComdat(DD, Out);
3769 else
3770 getMangleContext().mangleCXXCtorComdat(CD, Out);
3771 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
3772 Fn->setComdat(C);
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003773 } else {
3774 CGM.maybeSetTrivialComdat(*MD, *Fn);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003775 }
Rafael Espindola91f68b42014-09-15 19:20:10 +00003776}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003777
3778static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) {
3779 // void *__cxa_begin_catch(void*);
3780 llvm::FunctionType *FTy = llvm::FunctionType::get(
3781 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3782
3783 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
3784}
3785
3786static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) {
3787 // void __cxa_end_catch();
3788 llvm::FunctionType *FTy =
3789 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
3790
3791 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
3792}
3793
3794static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) {
3795 // void *__cxa_get_exception_ptr(void*);
3796 llvm::FunctionType *FTy = llvm::FunctionType::get(
3797 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3798
3799 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
3800}
3801
3802namespace {
3803 /// A cleanup to call __cxa_end_catch. In many cases, the caught
3804 /// exception type lets us state definitively that the thrown exception
3805 /// type does not have a destructor. In particular:
3806 /// - Catch-alls tell us nothing, so we have to conservatively
3807 /// assume that the thrown exception might have a destructor.
3808 /// - Catches by reference behave according to their base types.
3809 /// - Catches of non-record types will only trigger for exceptions
3810 /// of non-record types, which never have destructors.
3811 /// - Catches of record types can trigger for arbitrary subclasses
3812 /// of the caught type, so we have to assume the actual thrown
3813 /// exception type might have a throwing destructor, even if the
3814 /// caught type's destructor is trivial or nothrow.
David Blaikie7e70d682015-08-18 22:40:54 +00003815 struct CallEndCatch final : EHScopeStack::Cleanup {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003816 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
3817 bool MightThrow;
3818
3819 void Emit(CodeGenFunction &CGF, Flags flags) override {
3820 if (!MightThrow) {
3821 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
3822 return;
3823 }
3824
3825 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
3826 }
3827 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003828}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003829
3830/// Emits a call to __cxa_begin_catch and enters a cleanup to call
3831/// __cxa_end_catch.
3832///
3833/// \param EndMightThrow - true if __cxa_end_catch might throw
3834static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
3835 llvm::Value *Exn,
3836 bool EndMightThrow) {
3837 llvm::CallInst *call =
3838 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
3839
3840 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
3841
3842 return call;
3843}
3844
3845/// A "special initializer" callback for initializing a catch
3846/// parameter during catch initialization.
3847static void InitCatchParam(CodeGenFunction &CGF,
3848 const VarDecl &CatchParam,
John McCall7f416cc2015-09-08 08:05:57 +00003849 Address ParamAddr,
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003850 SourceLocation Loc) {
3851 // Load the exception from where the landing pad saved it.
3852 llvm::Value *Exn = CGF.getExceptionFromSlot();
3853
3854 CanQualType CatchType =
3855 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
3856 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
3857
3858 // If we're catching by reference, we can just cast the object
3859 // pointer to the appropriate pointer.
3860 if (isa<ReferenceType>(CatchType)) {
3861 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
3862 bool EndCatchMightThrow = CaughtType->isRecordType();
3863
3864 // __cxa_begin_catch returns the adjusted object pointer.
3865 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
3866
3867 // We have no way to tell the personality function that we're
3868 // catching by reference, so if we're catching a pointer,
3869 // __cxa_begin_catch will actually return that pointer by value.
3870 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
3871 QualType PointeeType = PT->getPointeeType();
3872
3873 // When catching by reference, generally we should just ignore
3874 // this by-value pointer and use the exception object instead.
3875 if (!PointeeType->isRecordType()) {
3876
3877 // Exn points to the struct _Unwind_Exception header, which
3878 // we have to skip past in order to reach the exception data.
3879 unsigned HeaderSize =
3880 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
3881 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
3882
3883 // However, if we're catching a pointer-to-record type that won't
3884 // work, because the personality function might have adjusted
3885 // the pointer. There's actually no way for us to fully satisfy
3886 // the language/ABI contract here: we can't use Exn because it
3887 // might have the wrong adjustment, but we can't use the by-value
3888 // pointer because it's off by a level of abstraction.
3889 //
3890 // The current solution is to dump the adjusted pointer into an
3891 // alloca, which breaks language semantics (because changing the
3892 // pointer doesn't change the exception) but at least works.
3893 // The better solution would be to filter out non-exact matches
3894 // and rethrow them, but this is tricky because the rethrow
3895 // really needs to be catchable by other sites at this landing
3896 // pad. The best solution is to fix the personality function.
3897 } else {
3898 // Pull the pointer for the reference type off.
3899 llvm::Type *PtrTy =
3900 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
3901
3902 // Create the temporary and write the adjusted pointer into it.
John McCall7f416cc2015-09-08 08:05:57 +00003903 Address ExnPtrTmp =
3904 CGF.CreateTempAlloca(PtrTy, CGF.getPointerAlign(), "exn.byref.tmp");
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003905 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3906 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
3907
3908 // Bind the reference to the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00003909 AdjustedExn = ExnPtrTmp.getPointer();
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003910 }
3911 }
3912
3913 llvm::Value *ExnCast =
3914 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
3915 CGF.Builder.CreateStore(ExnCast, ParamAddr);
3916 return;
3917 }
3918
3919 // Scalars and complexes.
3920 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
3921 if (TEK != TEK_Aggregate) {
3922 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
3923
3924 // If the catch type is a pointer type, __cxa_begin_catch returns
3925 // the pointer by value.
3926 if (CatchType->hasPointerRepresentation()) {
3927 llvm::Value *CastExn =
3928 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
3929
3930 switch (CatchType.getQualifiers().getObjCLifetime()) {
3931 case Qualifiers::OCL_Strong:
3932 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
3933 // fallthrough
3934
3935 case Qualifiers::OCL_None:
3936 case Qualifiers::OCL_ExplicitNone:
3937 case Qualifiers::OCL_Autoreleasing:
3938 CGF.Builder.CreateStore(CastExn, ParamAddr);
3939 return;
3940
3941 case Qualifiers::OCL_Weak:
3942 CGF.EmitARCInitWeak(ParamAddr, CastExn);
3943 return;
3944 }
3945 llvm_unreachable("bad ownership qualifier!");
3946 }
3947
3948 // Otherwise, it returns a pointer into the exception object.
3949
3950 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3951 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3952
3953 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
John McCall7f416cc2015-09-08 08:05:57 +00003954 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003955 switch (TEK) {
3956 case TEK_Complex:
3957 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
3958 /*init*/ true);
3959 return;
3960 case TEK_Scalar: {
3961 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
3962 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
3963 return;
3964 }
3965 case TEK_Aggregate:
3966 llvm_unreachable("evaluation kind filtered out!");
3967 }
3968 llvm_unreachable("bad evaluation kind");
3969 }
3970
3971 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
John McCall7f416cc2015-09-08 08:05:57 +00003972 auto catchRD = CatchType->getAsCXXRecordDecl();
3973 CharUnits caughtExnAlignment = CGF.CGM.getClassPointerAlignment(catchRD);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003974
3975 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3976
3977 // Check for a copy expression. If we don't have a copy expression,
3978 // that means a trivial copy is okay.
3979 const Expr *copyExpr = CatchParam.getInit();
3980 if (!copyExpr) {
3981 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
John McCall7f416cc2015-09-08 08:05:57 +00003982 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3983 caughtExnAlignment);
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00003984 LValue Dest = CGF.MakeAddrLValue(ParamAddr, CatchType);
3985 LValue Src = CGF.MakeAddrLValue(adjustedExn, CatchType);
Richard Smithe78fac52018-04-05 20:52:58 +00003986 CGF.EmitAggregateCopy(Dest, Src, CatchType, AggValueSlot::DoesNotOverlap);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003987 return;
3988 }
3989
3990 // We have to call __cxa_get_exception_ptr to get the adjusted
3991 // pointer before copying.
3992 llvm::CallInst *rawAdjustedExn =
3993 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
3994
3995 // Cast that to the appropriate type.
John McCall7f416cc2015-09-08 08:05:57 +00003996 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3997 caughtExnAlignment);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003998
3999 // The copy expression is defined in terms of an OpaqueValueExpr.
4000 // Find it and map it to the adjusted expression.
4001 CodeGenFunction::OpaqueValueMapping
4002 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
4003 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
4004
4005 // Call the copy ctor in a terminate scope.
4006 CGF.EHStack.pushTerminate();
4007
4008 // Perform the copy construction.
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004009 CGF.EmitAggExpr(copyExpr,
John McCall7f416cc2015-09-08 08:05:57 +00004010 AggValueSlot::forAddr(ParamAddr, Qualifiers(),
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004011 AggValueSlot::IsNotDestructed,
4012 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00004013 AggValueSlot::IsNotAliased,
4014 AggValueSlot::DoesNotOverlap));
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004015
4016 // Leave the terminate scope.
4017 CGF.EHStack.popTerminate();
4018
4019 // Undo the opaque value mapping.
4020 opaque.pop();
4021
4022 // Finally we can call __cxa_begin_catch.
4023 CallBeginCatch(CGF, Exn, true);
4024}
4025
4026/// Begins a catch statement by initializing the catch variable and
4027/// calling __cxa_begin_catch.
4028void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF,
4029 const CXXCatchStmt *S) {
4030 // We have to be very careful with the ordering of cleanups here:
4031 // C++ [except.throw]p4:
4032 // The destruction [of the exception temporary] occurs
4033 // immediately after the destruction of the object declared in
4034 // the exception-declaration in the handler.
4035 //
4036 // So the precise ordering is:
4037 // 1. Construct catch variable.
4038 // 2. __cxa_begin_catch
4039 // 3. Enter __cxa_end_catch cleanup
4040 // 4. Enter dtor cleanup
4041 //
4042 // We do this by using a slightly abnormal initialization process.
4043 // Delegation sequence:
4044 // - ExitCXXTryStmt opens a RunCleanupsScope
4045 // - EmitAutoVarAlloca creates the variable and debug info
4046 // - InitCatchParam initializes the variable from the exception
4047 // - CallBeginCatch calls __cxa_begin_catch
4048 // - CallBeginCatch enters the __cxa_end_catch cleanup
4049 // - EmitAutoVarCleanups enters the variable destructor cleanup
4050 // - EmitCXXTryStmt emits the code for the catch body
4051 // - EmitCXXTryStmt close the RunCleanupsScope
4052
4053 VarDecl *CatchParam = S->getExceptionDecl();
4054 if (!CatchParam) {
4055 llvm::Value *Exn = CGF.getExceptionFromSlot();
4056 CallBeginCatch(CGF, Exn, true);
4057 return;
4058 }
4059
4060 // Emit the local.
4061 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
4062 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
4063 CGF.EmitAutoVarCleanups(var);
4064}
4065
4066/// Get or define the following function:
4067/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
4068/// This code is used only in C++.
4069static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
4070 llvm::FunctionType *fnTy =
4071 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00004072 llvm::Constant *fnRef = CGM.CreateRuntimeFunction(
4073 fnTy, "__clang_call_terminate", llvm::AttributeList(), /*Local=*/true);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004074
4075 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
4076 if (fn && fn->empty()) {
4077 fn->setDoesNotThrow();
4078 fn->setDoesNotReturn();
4079
4080 // What we really want is to massively penalize inlining without
4081 // forbidding it completely. The difference between that and
4082 // 'noinline' is negligible.
4083 fn->addFnAttr(llvm::Attribute::NoInline);
4084
4085 // Allow this function to be shared across translation units, but
4086 // we don't want it to turn into an exported symbol.
4087 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
4088 fn->setVisibility(llvm::Function::HiddenVisibility);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00004089 if (CGM.supportsCOMDAT())
4090 fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004091
4092 // Set up the function.
4093 llvm::BasicBlock *entry =
4094 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
John McCall7f416cc2015-09-08 08:05:57 +00004095 CGBuilderTy builder(CGM, entry);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004096
4097 // Pull the exception pointer out of the parameter list.
4098 llvm::Value *exn = &*fn->arg_begin();
4099
4100 // Call __cxa_begin_catch(exn).
4101 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
4102 catchCall->setDoesNotThrow();
4103 catchCall->setCallingConv(CGM.getRuntimeCC());
4104
4105 // Call std::terminate().
David Blaikie4ba525b2015-07-14 17:27:39 +00004106 llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn());
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004107 termCall->setDoesNotThrow();
4108 termCall->setDoesNotReturn();
4109 termCall->setCallingConv(CGM.getRuntimeCC());
4110
4111 // std::terminate cannot return.
4112 builder.CreateUnreachable();
4113 }
4114
4115 return fnRef;
4116}
4117
4118llvm::CallInst *
4119ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
4120 llvm::Value *Exn) {
4121 // In C++, we want to call __cxa_begin_catch() before terminating.
4122 if (Exn) {
4123 assert(CGF.CGM.getLangOpts().CPlusPlus);
4124 return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn);
4125 }
4126 return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
4127}
Peter Collingbourne60108802017-12-13 21:53:04 +00004128
4129std::pair<llvm::Value *, const CXXRecordDecl *>
4130ItaniumCXXABI::LoadVTablePtr(CodeGenFunction &CGF, Address This,
4131 const CXXRecordDecl *RD) {
4132 return {CGF.GetVTablePtr(This, CGM.Int8PtrTy, RD), RD};
4133}
Heejin Ahnc6479192018-05-31 22:18:13 +00004134
4135void WebAssemblyCXXABI::emitBeginCatch(CodeGenFunction &CGF,
4136 const CXXCatchStmt *C) {
Heejin Ahn1eb074d2018-06-01 01:01:37 +00004137 if (CGF.getTarget().hasFeature("exception-handling"))
4138 CGF.EHStack.pushCleanup<CatchRetScope>(
4139 NormalCleanup, cast<llvm::CatchPadInst>(CGF.CurrentFuncletPad));
Heejin Ahnc6479192018-05-31 22:18:13 +00004140 ItaniumCXXABI::emitBeginCatch(CGF, C);
4141}