blob: 0374e4cf9acaa42a5c30834117d3caa5a26f8af0 [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) {}
472
473private:
474 bool HasThisReturn(GlobalDecl GD) const override {
475 return isa<CXXConstructorDecl>(GD.getDecl()) ||
476 (isa<CXXDestructorDecl>(GD.getDecl()) &&
477 GD.getDtorType() != Dtor_Deleting);
478 }
Derek Schuff8179be42016-05-10 17:44:55 +0000479 bool canCallMismatchedFunctionType() const override { return false; }
Dan Gohmanc2853072015-09-03 22:51:53 +0000480};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000481}
Charles Davis4e786dd2010-05-25 19:52:27 +0000482
Charles Davis53c59df2010-08-16 03:33:14 +0000483CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000484 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000485 // For IR-generation purposes, there's no significant difference
486 // between the ARM and iOS ABIs.
487 case TargetCXXABI::GenericARM:
488 case TargetCXXABI::iOS:
Tim Northover756447a2015-10-30 16:30:36 +0000489 case TargetCXXABI::WatchOS:
John McCall57625922013-01-25 23:36:14 +0000490 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000491
Tim Northovera2ee4332014-03-29 15:09:45 +0000492 case TargetCXXABI::iOS64:
493 return new iOS64CXXABI(CGM);
494
Tim Northover9bb857a2013-01-31 12:13:10 +0000495 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
496 // include the other 32-bit ARM oddities: constructor/destructor return values
497 // and array cookies.
498 case TargetCXXABI::GenericAArch64:
Mark Seabornedf0d382013-07-24 16:25:13 +0000499 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
500 /* UseARMGuardVarABI = */ true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000501
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000502 case TargetCXXABI::GenericMIPS:
503 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true);
504
Dan Gohmanc2853072015-09-03 22:51:53 +0000505 case TargetCXXABI::WebAssembly:
506 return new WebAssemblyCXXABI(CGM);
507
John McCall57625922013-01-25 23:36:14 +0000508 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000509 if (CGM.getContext().getTargetInfo().getTriple().getArch()
510 == llvm::Triple::le32) {
511 // For PNaCl, use ARM-style method pointers so that PNaCl code
512 // does not assume anything about the alignment of function
513 // pointers.
514 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
515 /* UseARMGuardVarABI = */ false);
516 }
John McCall57625922013-01-25 23:36:14 +0000517 return new ItaniumCXXABI(CGM);
518
519 case TargetCXXABI::Microsoft:
520 llvm_unreachable("Microsoft ABI is not Itanium-based");
521 }
522 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000523}
524
Chris Lattnera5f58b02011-07-09 17:41:47 +0000525llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000526ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
527 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000528 return CGM.PtrDiffTy;
Serge Guelton1d993272017-05-09 19:31:30 +0000529 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy);
John McCall1c456c82010-08-22 06:43:33 +0000530}
531
John McCalld9c6c0b2010-08-22 00:59:17 +0000532/// In the Itanium and ARM ABIs, method pointers have the form:
533/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
534///
535/// In the Itanium ABI:
536/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
537/// - the this-adjustment is (memptr.adj)
538/// - the virtual offset is (memptr.ptr - 1)
539///
540/// In the ARM ABI:
541/// - method pointers are virtual if (memptr.adj & 1) is nonzero
542/// - the this-adjustment is (memptr.adj >> 1)
543/// - the virtual offset is (memptr.ptr)
544/// ARM uses 'adj' for the virtual flag because Thumb functions
545/// may be only single-byte aligned.
546///
547/// If the member is virtual, the adjusted 'this' pointer points
548/// to a vtable pointer from which the virtual offset is applied.
549///
550/// If the member is non-virtual, memptr.ptr is the address of
551/// the function to call.
John McCallb92ab1a2016-10-26 23:46:34 +0000552CGCallee ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
John McCall7f416cc2015-09-08 08:05:57 +0000553 CodeGenFunction &CGF, const Expr *E, Address ThisAddr,
554 llvm::Value *&ThisPtrForCall,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000555 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
John McCall475999d2010-08-22 00:05:51 +0000556 CGBuilderTy &Builder = CGF.Builder;
557
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000558 const FunctionProtoType *FPT =
John McCall475999d2010-08-22 00:05:51 +0000559 MPT->getPointeeType()->getAs<FunctionProtoType>();
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000560 const CXXRecordDecl *RD =
John McCall475999d2010-08-22 00:05:51 +0000561 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
562
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000563 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(
564 CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr));
John McCall475999d2010-08-22 00:05:51 +0000565
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000566 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000567
John McCalld9c6c0b2010-08-22 00:59:17 +0000568 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
569 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
570 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
571
John McCalla1dee5302010-08-22 10:59:02 +0000572 // Extract memptr.adj, which is in the second field.
573 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000574
575 // Compute the true adjustment.
576 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000577 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000578 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000579
580 // Apply the adjustment and cast back to the original struct type
581 // for consistency.
John McCall7f416cc2015-09-08 08:05:57 +0000582 llvm::Value *This = ThisAddr.getPointer();
John McCalld9c6c0b2010-08-22 00:59:17 +0000583 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
584 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
585 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall7f416cc2015-09-08 08:05:57 +0000586 ThisPtrForCall = This;
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000587
John McCall475999d2010-08-22 00:05:51 +0000588 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000589 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000590
John McCall475999d2010-08-22 00:05:51 +0000591 // If the LSB in the function pointer is 1, the function pointer points to
592 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000593 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000594 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000595 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
596 else
597 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
598 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000599 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
600
601 // In the virtual path, the adjustment left 'This' pointing to the
602 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000603 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000604 CGF.EmitBlock(FnVirtual);
605
606 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000607 llvm::Type *VTableTy = Builder.getInt8PtrTy();
John McCall7f416cc2015-09-08 08:05:57 +0000608 CharUnits VTablePtrAlign =
609 CGF.CGM.getDynamicOffsetAlignment(ThisAddr.getAlignment(), RD,
610 CGF.getPointerAlign());
611 llvm::Value *VTable =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000612 CGF.GetVTablePtr(Address(This, VTablePtrAlign), VTableTy, RD);
John McCall475999d2010-08-22 00:05:51 +0000613
614 // Apply the offset.
John McCalld23b27e2016-09-16 02:40:45 +0000615 // On ARM64, to reserve extra space in virtual member function pointers,
616 // we only pay attention to the low 32 bits of the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000617 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000618 if (!UseARMMethodPtrABI)
619 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld23b27e2016-09-16 02:40:45 +0000620 if (Use32BitVTableOffsetABI) {
621 VTableOffset = Builder.CreateTrunc(VTableOffset, CGF.Int32Ty);
622 VTableOffset = Builder.CreateZExt(VTableOffset, CGM.PtrDiffTy);
623 }
John McCalld9c6c0b2010-08-22 00:59:17 +0000624 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall475999d2010-08-22 00:05:51 +0000625
626 // Load the virtual function to call.
627 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCall7f416cc2015-09-08 08:05:57 +0000628 llvm::Value *VirtualFn =
629 Builder.CreateAlignedLoad(VTable, CGF.getPointerAlign(),
630 "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000631 CGF.EmitBranch(FnEnd);
632
633 // In the non-virtual path, the function pointer is actually a
634 // function pointer.
635 CGF.EmitBlock(FnNonVirtual);
636 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000637 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000638
John McCall475999d2010-08-22 00:05:51 +0000639 // We're done.
640 CGF.EmitBlock(FnEnd);
John McCallb92ab1a2016-10-26 23:46:34 +0000641 llvm::PHINode *CalleePtr = Builder.CreatePHI(FTy->getPointerTo(), 2);
642 CalleePtr->addIncoming(VirtualFn, FnVirtual);
643 CalleePtr->addIncoming(NonVirtualFn, FnNonVirtual);
644
645 CGCallee Callee(FPT, CalleePtr);
John McCall475999d2010-08-22 00:05:51 +0000646 return Callee;
647}
John McCalla8bbb822010-08-22 03:04:22 +0000648
John McCallc134eb52010-08-31 21:07:20 +0000649/// Compute an l-value by applying the given pointer-to-member to a
650/// base object.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000651llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
John McCall7f416cc2015-09-08 08:05:57 +0000652 CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000653 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000654 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000655
656 CGBuilderTy &Builder = CGF.Builder;
657
John McCallc134eb52010-08-31 21:07:20 +0000658 // Cast to char*.
John McCall7f416cc2015-09-08 08:05:57 +0000659 Base = Builder.CreateElementBitCast(Base, CGF.Int8Ty);
John McCallc134eb52010-08-31 21:07:20 +0000660
661 // Apply the offset, which we assume is non-null.
John McCall7f416cc2015-09-08 08:05:57 +0000662 llvm::Value *Addr =
663 Builder.CreateInBoundsGEP(Base.getPointer(), MemPtr, "memptr.offset");
John McCallc134eb52010-08-31 21:07:20 +0000664
665 // Cast the address to the appropriate pointer type, adopting the
666 // address space of the base pointer.
John McCall7f416cc2015-09-08 08:05:57 +0000667 llvm::Type *PType = CGF.ConvertTypeForMem(MPT->getPointeeType())
668 ->getPointerTo(Base.getAddressSpace());
John McCallc134eb52010-08-31 21:07:20 +0000669 return Builder.CreateBitCast(Addr, PType);
670}
671
John McCallc62bb392012-02-15 01:22:51 +0000672/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
673/// conversion.
674///
675/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000676///
677/// Obligatory offset/adjustment diagram:
678/// <-- offset --> <-- adjustment -->
679/// |--------------------------|----------------------|--------------------|
680/// ^Derived address point ^Base address point ^Member address point
681///
682/// So when converting a base member pointer to a derived member pointer,
683/// we add the offset to the adjustment because the address point has
684/// decreased; and conversely, when converting a derived MP to a base MP
685/// we subtract the offset from the adjustment because the address point
686/// has increased.
687///
688/// The standard forbids (at compile time) conversion to and from
689/// virtual bases, which is why we don't have to consider them here.
690///
691/// The standard forbids (at run time) casting a derived MP to a base
692/// MP when the derived MP does not point to a member of the base.
693/// This is why -1 is a reasonable choice for null data member
694/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000695llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000696ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
697 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000698 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000699 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000700 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
701 E->getCastKind() == CK_ReinterpretMemberPointer);
702
703 // Under Itanium, reinterprets don't require any additional processing.
704 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
705
706 // Use constant emission if we can.
707 if (isa<llvm::Constant>(src))
708 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
709
710 llvm::Constant *adj = getMemberPointerAdjustment(E);
711 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000712
713 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000714 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000715
John McCallc62bb392012-02-15 01:22:51 +0000716 const MemberPointerType *destTy =
717 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000718
John McCall7a9aac22010-08-23 01:21:21 +0000719 // For member data pointers, this is just a matter of adding the
720 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000721 if (destTy->isMemberDataPointer()) {
722 llvm::Value *dst;
723 if (isDerivedToBase)
724 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000725 else
John McCallc62bb392012-02-15 01:22:51 +0000726 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000727
728 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000729 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
730 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
731 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000732 }
733
John McCalla1dee5302010-08-22 10:59:02 +0000734 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000735 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000736 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
737 offset <<= 1;
738 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000739 }
740
John McCallc62bb392012-02-15 01:22:51 +0000741 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
742 llvm::Value *dstAdj;
743 if (isDerivedToBase)
744 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000745 else
John McCallc62bb392012-02-15 01:22:51 +0000746 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000747
John McCallc62bb392012-02-15 01:22:51 +0000748 return Builder.CreateInsertValue(src, dstAdj, 1);
749}
750
751llvm::Constant *
752ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
753 llvm::Constant *src) {
754 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
755 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
756 E->getCastKind() == CK_ReinterpretMemberPointer);
757
758 // Under Itanium, reinterprets don't require any additional processing.
759 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
760
761 // If the adjustment is trivial, we don't need to do anything.
762 llvm::Constant *adj = getMemberPointerAdjustment(E);
763 if (!adj) return src;
764
765 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
766
767 const MemberPointerType *destTy =
768 E->getType()->castAs<MemberPointerType>();
769
770 // For member data pointers, this is just a matter of adding the
771 // offset if the source is non-null.
772 if (destTy->isMemberDataPointer()) {
773 // null maps to null.
774 if (src->isAllOnesValue()) return src;
775
776 if (isDerivedToBase)
777 return llvm::ConstantExpr::getNSWSub(src, adj);
778 else
779 return llvm::ConstantExpr::getNSWAdd(src, adj);
780 }
781
782 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000783 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000784 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
785 offset <<= 1;
786 adj = llvm::ConstantInt::get(adj->getType(), offset);
787 }
788
789 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
790 llvm::Constant *dstAdj;
791 if (isDerivedToBase)
792 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
793 else
794 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
795
796 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000797}
John McCall84fa5102010-08-22 04:16:24 +0000798
799llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000800ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000801 // Itanium C++ ABI 2.3:
802 // A NULL pointer is represented as -1.
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000803 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000804 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000805
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000806 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000807 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000808 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000809}
810
John McCallf3a88602011-02-03 08:15:49 +0000811llvm::Constant *
812ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
813 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000814 // Itanium C++ ABI 2.3:
815 // A pointer to data member is an offset from the base address of
816 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000817 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000818}
819
David Majnemere2be95b2015-06-23 07:31:01 +0000820llvm::Constant *
821ItaniumCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000822 return BuildMemberPointer(MD, CharUnits::Zero());
823}
824
825llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
826 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000827 assert(MD->isInstance() && "Member function must not be static!");
John McCalla1dee5302010-08-22 10:59:02 +0000828
829 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000830
831 // Get the function pointer (or index if this is a virtual function).
832 llvm::Constant *MemPtr[2];
833 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000834 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000835
Ken Dyckdf016282011-04-09 01:30:02 +0000836 const ASTContext &Context = getContext();
837 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000838 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000839 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000840
Mark Seabornedf0d382013-07-24 16:25:13 +0000841 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000842 // ARM C++ ABI 3.2.1:
843 // This ABI specifies that adj contains twice the this
844 // adjustment, plus 1 if the member function is virtual. The
845 // least significant bit of adj then makes exactly the same
846 // discrimination as the least significant bit of ptr does for
847 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000848 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
849 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000850 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000851 } else {
852 // Itanium C++ ABI 2.3:
853 // For a virtual function, [the pointer field] is 1 plus the
854 // virtual table offset (in bytes) of the function,
855 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000856 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
857 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000858 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000859 }
860 } else {
John McCall2979fe02011-04-12 00:42:48 +0000861 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000862 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000863 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000864 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000865 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000866 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000867 } else {
John McCall2979fe02011-04-12 00:42:48 +0000868 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
869 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000870 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000871 }
John McCall2979fe02011-04-12 00:42:48 +0000872 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000873
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000874 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000875 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
876 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000877 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000878 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000879
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000880 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000881}
882
Richard Smithdafff942012-01-14 04:30:29 +0000883llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
884 QualType MPType) {
885 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
886 const ValueDecl *MPD = MP.getMemberPointerDecl();
887 if (!MPD)
888 return EmitNullMemberPointer(MPT);
889
Reid Kleckner452abac2013-05-09 21:01:17 +0000890 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000891
892 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
893 return BuildMemberPointer(MD, ThisAdjustment);
894
895 CharUnits FieldOffset =
896 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
897 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
898}
899
John McCall131d97d2010-08-22 08:30:07 +0000900/// The comparison algorithm is pretty easy: the member pointers are
901/// the same if they're either bitwise identical *or* both null.
902///
903/// ARM is different here only because null-ness is more complicated.
904llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000905ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
906 llvm::Value *L,
907 llvm::Value *R,
908 const MemberPointerType *MPT,
909 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000910 CGBuilderTy &Builder = CGF.Builder;
911
John McCall131d97d2010-08-22 08:30:07 +0000912 llvm::ICmpInst::Predicate Eq;
913 llvm::Instruction::BinaryOps And, Or;
914 if (Inequality) {
915 Eq = llvm::ICmpInst::ICMP_NE;
916 And = llvm::Instruction::Or;
917 Or = llvm::Instruction::And;
918 } else {
919 Eq = llvm::ICmpInst::ICMP_EQ;
920 And = llvm::Instruction::And;
921 Or = llvm::Instruction::Or;
922 }
923
John McCall7a9aac22010-08-23 01:21:21 +0000924 // Member data pointers are easy because there's a unique null
925 // value, so it just comes down to bitwise equality.
926 if (MPT->isMemberDataPointer())
927 return Builder.CreateICmp(Eq, L, R);
928
929 // For member function pointers, the tautologies are more complex.
930 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000931 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000932 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000933 // (L == R) <==> (L.ptr == R.ptr &&
934 // (L.adj == R.adj ||
935 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000936 // The inequality tautologies have exactly the same structure, except
937 // applying De Morgan's laws.
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000938
John McCall7a9aac22010-08-23 01:21:21 +0000939 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
940 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
941
John McCall131d97d2010-08-22 08:30:07 +0000942 // This condition tests whether L.ptr == R.ptr. This must always be
943 // true for equality to hold.
944 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
945
946 // This condition, together with the assumption that L.ptr == R.ptr,
947 // tests whether the pointers are both null. ARM imposes an extra
948 // condition.
949 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
950 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
951
952 // This condition tests whether L.adj == R.adj. If this isn't
953 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +0000954 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
955 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000956 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
957
958 // Null member function pointers on ARM clear the low bit of Adj,
959 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000960 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000961 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
962
963 // Compute (l.adj | r.adj) & 1 and test it against zero.
964 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
965 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
966 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
967 "cmp.or.adj");
968 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
969 }
970
971 // Tie together all our conditions.
972 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
973 Result = Builder.CreateBinOp(And, PtrEq, Result,
974 Inequality ? "memptr.ne" : "memptr.eq");
975 return Result;
976}
977
978llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000979ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
980 llvm::Value *MemPtr,
981 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +0000982 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +0000983
984 /// For member data pointers, this is just a check against -1.
985 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000986 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +0000987 llvm::Value *NegativeOne =
988 llvm::Constant::getAllOnesValue(MemPtr->getType());
989 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
990 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000991
Daniel Dunbar914bc412011-04-19 23:10:47 +0000992 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +0000993 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +0000994
995 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
996 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
997
Daniel Dunbar914bc412011-04-19 23:10:47 +0000998 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
999 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +00001000 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +00001001 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +00001002 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +00001003 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +00001004 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
1005 "memptr.isvirtual");
1006 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +00001007 }
1008
1009 return Result;
1010}
John McCall1c456c82010-08-22 06:43:33 +00001011
Reid Kleckner40ca9132014-05-13 22:05:45 +00001012bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
1013 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
1014 if (!RD)
1015 return false;
1016
Richard Smith96cd6712017-08-16 01:49:53 +00001017 // If C++ prohibits us from making a copy, return by address.
Richard Smithf667ad52017-08-26 01:04:35 +00001018 if (passClassIndirect(RD)) {
John McCall7f416cc2015-09-08 08:05:57 +00001019 auto Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
1020 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
Reid Kleckner40ca9132014-05-13 22:05:45 +00001021 return true;
1022 }
Reid Kleckner40ca9132014-05-13 22:05:45 +00001023 return false;
1024}
1025
John McCall614dbdc2010-08-22 21:01:12 +00001026/// The Itanium ABI requires non-zero initialization only for data
1027/// member pointers, for which '0' is a valid offset.
1028bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
David Majnemer5fd33e02015-04-24 01:25:08 +00001029 return MPT->isMemberFunctionPointer();
John McCall84fa5102010-08-22 04:16:24 +00001030}
John McCall5d865c322010-08-31 07:33:07 +00001031
John McCall82fb8922012-09-25 10:10:39 +00001032/// The Itanium ABI always places an offset to the complete object
1033/// at entry -2 in the vtable.
David Majnemer08681372014-11-01 07:37:17 +00001034void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
1035 const CXXDeleteExpr *DE,
John McCall7f416cc2015-09-08 08:05:57 +00001036 Address Ptr,
David Majnemer08681372014-11-01 07:37:17 +00001037 QualType ElementType,
1038 const CXXDestructorDecl *Dtor) {
1039 bool UseGlobalDelete = DE->isGlobalDelete();
David Majnemer0c0b6d92014-10-31 20:09:12 +00001040 if (UseGlobalDelete) {
1041 // Derive the complete-object pointer, which is what we need
1042 // to pass to the deallocation function.
John McCall82fb8922012-09-25 10:10:39 +00001043
David Majnemer0c0b6d92014-10-31 20:09:12 +00001044 // Grab the vtable pointer as an intptr_t*.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001045 auto *ClassDecl =
1046 cast<CXXRecordDecl>(ElementType->getAs<RecordType>()->getDecl());
1047 llvm::Value *VTable =
1048 CGF.GetVTablePtr(Ptr, CGF.IntPtrTy->getPointerTo(), ClassDecl);
John McCall82fb8922012-09-25 10:10:39 +00001049
David Majnemer0c0b6d92014-10-31 20:09:12 +00001050 // Track back to entry -2 and pull out the offset there.
1051 llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
1052 VTable, -2, "complete-offset.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001053 llvm::Value *Offset =
1054 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
David Majnemer0c0b6d92014-10-31 20:09:12 +00001055
1056 // Apply the offset.
John McCall7f416cc2015-09-08 08:05:57 +00001057 llvm::Value *CompletePtr =
1058 CGF.Builder.CreateBitCast(Ptr.getPointer(), CGF.Int8PtrTy);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001059 CompletePtr = CGF.Builder.CreateInBoundsGEP(CompletePtr, Offset);
1060
1061 // If we're supposed to call the global delete, make sure we do so
1062 // even if the destructor throws.
David Majnemer08681372014-11-01 07:37:17 +00001063 CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr,
1064 ElementType);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001065 }
1066
1067 // FIXME: Provide a source location here even though there's no
1068 // CXXMemberCallExpr for dtor call.
1069 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
1070 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr);
1071
1072 if (UseGlobalDelete)
1073 CGF.PopCleanupBlock();
John McCall82fb8922012-09-25 10:10:39 +00001074}
1075
David Majnemer442d0a22014-11-25 07:20:20 +00001076void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
1077 // void __cxa_rethrow();
1078
1079 llvm::FunctionType *FTy =
1080 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
1081
1082 llvm::Constant *Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
1083
1084 if (isNoReturn)
1085 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, None);
1086 else
1087 CGF.EmitRuntimeCallOrInvoke(Fn);
1088}
1089
David Majnemer7c237072015-03-05 00:46:22 +00001090static llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) {
1091 // void *__cxa_allocate_exception(size_t thrown_size);
1092
1093 llvm::FunctionType *FTy =
1094 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false);
1095
1096 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
1097}
1098
1099static llvm::Constant *getThrowFn(CodeGenModule &CGM) {
1100 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
1101 // void (*dest) (void *));
1102
1103 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
1104 llvm::FunctionType *FTy =
1105 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
1106
1107 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
1108}
1109
1110void ItaniumCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
1111 QualType ThrowType = E->getSubExpr()->getType();
1112 // Now allocate the exception object.
1113 llvm::Type *SizeTy = CGF.ConvertType(getContext().getSizeType());
1114 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
1115
1116 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM);
1117 llvm::CallInst *ExceptionPtr = CGF.EmitNounwindRuntimeCall(
1118 AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception");
1119
John McCall7f416cc2015-09-08 08:05:57 +00001120 CharUnits ExnAlign = getAlignmentOfExnObject();
1121 CGF.EmitAnyExprToExn(E->getSubExpr(), Address(ExceptionPtr, ExnAlign));
David Majnemer7c237072015-03-05 00:46:22 +00001122
1123 // Now throw the exception.
1124 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
1125 /*ForEH=*/true);
1126
1127 // The address of the destructor. If the exception type has a
1128 // trivial destructor (or isn't a record), we just pass null.
1129 llvm::Constant *Dtor = nullptr;
1130 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
1131 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
1132 if (!Record->hasTrivialDestructor()) {
1133 CXXDestructorDecl *DtorD = Record->getDestructor();
1134 Dtor = CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete);
1135 Dtor = llvm::ConstantExpr::getBitCast(Dtor, CGM.Int8PtrTy);
1136 }
1137 }
1138 if (!Dtor) Dtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
1139
1140 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
1141 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
1142}
1143
David Majnemer1162d252014-06-22 19:05:33 +00001144static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) {
1145 // void *__dynamic_cast(const void *sub,
1146 // const abi::__class_type_info *src,
1147 // const abi::__class_type_info *dst,
1148 // std::ptrdiff_t src2dst_offset);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00001149
David Majnemer1162d252014-06-22 19:05:33 +00001150 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
Jake Ehrlichc451cf22017-11-11 01:15:41 +00001151 llvm::Type *PtrDiffTy =
David Majnemer1162d252014-06-22 19:05:33 +00001152 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1153
1154 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
1155
1156 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
1157
1158 // Mark the function as nounwind readonly.
1159 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
1160 llvm::Attribute::ReadOnly };
Reid Klecknerde864822017-03-21 16:57:30 +00001161 llvm::AttributeList Attrs = llvm::AttributeList::get(
1162 CGF.getLLVMContext(), llvm::AttributeList::FunctionIndex, FuncAttrs);
David Majnemer1162d252014-06-22 19:05:33 +00001163
1164 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
1165}
1166
1167static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1168 // void __cxa_bad_cast();
1169 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1170 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1171}
1172
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001173/// Compute the src2dst_offset hint as described in the
David Majnemer1162d252014-06-22 19:05:33 +00001174/// Itanium C++ ABI [2.9.7]
1175static CharUnits computeOffsetHint(ASTContext &Context,
1176 const CXXRecordDecl *Src,
1177 const CXXRecordDecl *Dst) {
1178 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1179 /*DetectVirtual=*/false);
1180
1181 // If Dst is not derived from Src we can skip the whole computation below and
1182 // return that Src is not a public base of Dst. Record all inheritance paths.
1183 if (!Dst->isDerivedFrom(Src, Paths))
1184 return CharUnits::fromQuantity(-2ULL);
1185
1186 unsigned NumPublicPaths = 0;
1187 CharUnits Offset;
1188
1189 // Now walk all possible inheritance paths.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001190 for (const CXXBasePath &Path : Paths) {
1191 if (Path.Access != AS_public) // Ignore non-public inheritance.
David Majnemer1162d252014-06-22 19:05:33 +00001192 continue;
1193
1194 ++NumPublicPaths;
1195
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001196 for (const CXXBasePathElement &PathElement : Path) {
David Majnemer1162d252014-06-22 19:05:33 +00001197 // If the path contains a virtual base class we can't give any hint.
1198 // -1: no hint.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001199 if (PathElement.Base->isVirtual())
David Majnemer1162d252014-06-22 19:05:33 +00001200 return CharUnits::fromQuantity(-1ULL);
1201
1202 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
1203 continue;
1204
1205 // Accumulate the base class offsets.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001206 const ASTRecordLayout &L = Context.getASTRecordLayout(PathElement.Class);
1207 Offset += L.getBaseClassOffset(
1208 PathElement.Base->getType()->getAsCXXRecordDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001209 }
1210 }
1211
1212 // -2: Src is not a public base of Dst.
1213 if (NumPublicPaths == 0)
1214 return CharUnits::fromQuantity(-2ULL);
1215
1216 // -3: Src is a multiple public base type but never a virtual base type.
1217 if (NumPublicPaths > 1)
1218 return CharUnits::fromQuantity(-3ULL);
1219
1220 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
1221 // Return the offset of Src from the origin of Dst.
1222 return Offset;
1223}
1224
1225static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1226 // void __cxa_bad_typeid();
1227 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1228
1229 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1230}
1231
1232bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
1233 QualType SrcRecordTy) {
1234 return IsDeref;
1235}
1236
1237void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
1238 llvm::Value *Fn = getBadTypeidFn(CGF);
1239 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1240 CGF.Builder.CreateUnreachable();
1241}
1242
1243llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
1244 QualType SrcRecordTy,
John McCall7f416cc2015-09-08 08:05:57 +00001245 Address ThisPtr,
David Majnemer1162d252014-06-22 19:05:33 +00001246 llvm::Type *StdTypeInfoPtrTy) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001247 auto *ClassDecl =
1248 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001249 llvm::Value *Value =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001250 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo(), ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001251
1252 // Load the type info.
1253 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001254 return CGF.Builder.CreateAlignedLoad(Value, CGF.getPointerAlign());
David Majnemer1162d252014-06-22 19:05:33 +00001255}
1256
1257bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1258 QualType SrcRecordTy) {
1259 return SrcIsPtr;
1260}
1261
1262llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
John McCall7f416cc2015-09-08 08:05:57 +00001263 CodeGenFunction &CGF, Address ThisAddr, QualType SrcRecordTy,
David Majnemer1162d252014-06-22 19:05:33 +00001264 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1265 llvm::Type *PtrDiffLTy =
1266 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1267 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1268
1269 llvm::Value *SrcRTTI =
1270 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1271 llvm::Value *DestRTTI =
1272 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1273
1274 // Compute the offset hint.
1275 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1276 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1277 llvm::Value *OffsetHint = llvm::ConstantInt::get(
1278 PtrDiffLTy,
1279 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
1280
1281 // Emit the call to __dynamic_cast.
John McCall7f416cc2015-09-08 08:05:57 +00001282 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001283 Value = CGF.EmitCastToVoidPtr(Value);
1284
1285 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
1286 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
1287 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1288
1289 /// C++ [expr.dynamic.cast]p9:
1290 /// A failed cast to reference type throws std::bad_cast
1291 if (DestTy->isReferenceType()) {
1292 llvm::BasicBlock *BadCastBlock =
1293 CGF.createBasicBlock("dynamic_cast.bad_cast");
1294
1295 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1296 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1297
1298 CGF.EmitBlock(BadCastBlock);
1299 EmitBadCastCall(CGF);
1300 }
1301
1302 return Value;
1303}
1304
1305llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001306 Address ThisAddr,
David Majnemer1162d252014-06-22 19:05:33 +00001307 QualType SrcRecordTy,
1308 QualType DestTy) {
1309 llvm::Type *PtrDiffLTy =
1310 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1311 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1312
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001313 auto *ClassDecl =
1314 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001315 // Get the vtable pointer.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001316 llvm::Value *VTable = CGF.GetVTablePtr(ThisAddr, PtrDiffLTy->getPointerTo(),
1317 ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001318
1319 // Get the offset-to-top from the vtable.
1320 llvm::Value *OffsetToTop =
1321 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001322 OffsetToTop =
1323 CGF.Builder.CreateAlignedLoad(OffsetToTop, CGF.getPointerAlign(),
1324 "offset.to.top");
David Majnemer1162d252014-06-22 19:05:33 +00001325
1326 // Finally, add the offset to the pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001327 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001328 Value = CGF.EmitCastToVoidPtr(Value);
1329 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1330
1331 return CGF.Builder.CreateBitCast(Value, DestLTy);
1332}
1333
1334bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1335 llvm::Value *Fn = getBadCastFn(CGF);
1336 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1337 CGF.Builder.CreateUnreachable();
1338 return true;
1339}
1340
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001341llvm::Value *
1342ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001343 Address This,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001344 const CXXRecordDecl *ClassDecl,
1345 const CXXRecordDecl *BaseClassDecl) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001346 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy, ClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001347 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001348 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1349 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001350
1351 llvm::Value *VBaseOffsetPtr =
1352 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1353 "vbase.offset.ptr");
1354 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1355 CGM.PtrDiffTy->getPointerTo());
1356
1357 llvm::Value *VBaseOffset =
John McCall7f416cc2015-09-08 08:05:57 +00001358 CGF.Builder.CreateAlignedLoad(VBaseOffsetPtr, CGF.getPointerAlign(),
1359 "vbase.offset");
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001360
1361 return VBaseOffset;
1362}
1363
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001364void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1365 // Just make sure we're in sync with TargetCXXABI.
1366 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1367
Rafael Espindolac3cde362013-12-09 14:51:17 +00001368 // The constructor used for constructing this as a base class;
1369 // ignores virtual bases.
1370 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1371
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001372 // The constructor used for constructing this as a complete class;
Nico Weber4c2ffb22015-01-07 05:25:05 +00001373 // constructs the virtual bases, then calls the base constructor.
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001374 if (!D->getParent()->isAbstract()) {
1375 // We don't need to emit the complete ctor if the class is abstract.
1376 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1377 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001378}
1379
George Burgess IVf203dbf2017-02-22 20:28:02 +00001380CGCXXABI::AddedStructorArgs
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001381ItaniumCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
1382 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +00001383 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001384
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001385 // All parameters are already in place except VTT, which goes after 'this'.
1386 // These are Clang types, so we don't need to worry about sret yet.
John McCall5d865c322010-08-31 07:33:07 +00001387
1388 // Check if we need to add a VTT parameter (which has type void **).
George Burgess IVf203dbf2017-02-22 20:28:02 +00001389 if (T == StructorType::Base && MD->getParent()->getNumVBases() != 0) {
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001390 ArgTys.insert(ArgTys.begin() + 1,
1391 Context.getPointerType(Context.VoidPtrTy));
George Burgess IVf203dbf2017-02-22 20:28:02 +00001392 return AddedStructorArgs::prefix(1);
1393 }
1394 return AddedStructorArgs{};
John McCall5d865c322010-08-31 07:33:07 +00001395}
1396
Reid Klecknere7de47e2013-07-22 13:51:44 +00001397void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
Rafael Espindolac3cde362013-12-09 14:51:17 +00001398 // The destructor used for destructing this as a base class; ignores
1399 // virtual bases.
1400 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001401
1402 // The destructor used for destructing this as a most-derived class;
1403 // call the base destructor and then destructs any virtual bases.
1404 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1405
Rafael Espindolac3cde362013-12-09 14:51:17 +00001406 // The destructor in a virtual table is always a 'deleting'
1407 // destructor, which calls the complete destructor and then uses the
1408 // appropriate operator delete.
1409 if (D->isVirtual())
1410 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001411}
1412
Reid Kleckner89077a12013-12-17 19:46:40 +00001413void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1414 QualType &ResTy,
1415 FunctionArgList &Params) {
John McCall5d865c322010-08-31 07:33:07 +00001416 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +00001417 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
John McCall5d865c322010-08-31 07:33:07 +00001418
1419 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001420 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +00001421 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001422
1423 // FIXME: avoid the fake decl
1424 QualType T = Context.getPointerType(Context.VoidPtrTy);
Alexey Bataev56223232017-06-09 13:40:18 +00001425 auto *VTTDecl = ImplicitParamDecl::Create(
1426 Context, /*DC=*/nullptr, MD->getLocation(), &Context.Idents.get("vtt"),
1427 T, ImplicitParamDecl::CXXVTT);
Reid Kleckner89077a12013-12-17 19:46:40 +00001428 Params.insert(Params.begin() + 1, VTTDecl);
Reid Kleckner2af6d732013-12-13 00:09:59 +00001429 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +00001430 }
1431}
1432
John McCall5d865c322010-08-31 07:33:07 +00001433void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
Justin Lebared4f1722016-07-27 22:04:24 +00001434 // Naked functions have no prolog.
1435 if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>())
1436 return;
1437
Reid Kleckner06239e42017-11-16 19:09:36 +00001438 /// Initialize the 'this' slot. In the Itanium C++ ABI, no prologue
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001439 /// adjustments are required, because they are all handled by thunks.
Reid Kleckner06239e42017-11-16 19:09:36 +00001440 setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));
John McCall5d865c322010-08-31 07:33:07 +00001441
1442 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +00001443 if (getStructorImplicitParamDecl(CGF)) {
1444 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1445 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +00001446 }
John McCall5d865c322010-08-31 07:33:07 +00001447
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001448 /// If this is a function that the ABI specifies returns 'this', initialize
1449 /// the return slot to 'this' at the start of the function.
1450 ///
1451 /// Unlike the setting of return types, this is done within the ABI
1452 /// implementation instead of by clients of CGCXXABI because:
1453 /// 1) getThisValue is currently protected
1454 /// 2) in theory, an ABI could implement 'this' returns some other way;
1455 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +00001456 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +00001457 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +00001458}
1459
George Burgess IVf203dbf2017-02-22 20:28:02 +00001460CGCXXABI::AddedStructorArgs ItaniumCXXABI::addImplicitConstructorArgs(
Reid Kleckner89077a12013-12-17 19:46:40 +00001461 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1462 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1463 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
George Burgess IVf203dbf2017-02-22 20:28:02 +00001464 return AddedStructorArgs{};
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001465
Reid Kleckner89077a12013-12-17 19:46:40 +00001466 // Insert the implicit 'vtt' argument as the second argument.
1467 llvm::Value *VTT =
1468 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1469 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
Yaxun Liu5b330e82018-03-15 15:25:19 +00001470 Args.insert(Args.begin() + 1, CallArg(RValue::get(VTT), VTTTy));
George Burgess IVf203dbf2017-02-22 20:28:02 +00001471 return AddedStructorArgs::prefix(1); // Added one arg.
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001472}
1473
1474void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1475 const CXXDestructorDecl *DD,
1476 CXXDtorType Type, bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +00001477 bool Delegating, Address This) {
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001478 GlobalDecl GD(DD, Type);
1479 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1480 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1481
John McCallb92ab1a2016-10-26 23:46:34 +00001482 CGCallee Callee;
1483 if (getContext().getLangOpts().AppleKext &&
1484 Type != Dtor_Base && DD->isVirtual())
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001485 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
John McCallb92ab1a2016-10-26 23:46:34 +00001486 else
1487 Callee =
1488 CGCallee::forDirect(CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type)),
1489 DD);
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001490
John McCall7f416cc2015-09-08 08:05:57 +00001491 CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(),
Richard Smith762672a2016-09-28 19:09:10 +00001492 This.getPointer(), VTT, VTTTy,
1493 nullptr, nullptr);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001494}
1495
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001496void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1497 const CXXRecordDecl *RD) {
1498 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1499 if (VTable->hasInitializer())
1500 return;
1501
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001502 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001503 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1504 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
David Majnemerd905da42014-07-01 20:30:31 +00001505 llvm::Constant *RTTI =
1506 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001507
1508 // Create and set the initializer.
John McCall9c6cb762016-11-28 22:18:33 +00001509 ConstantInitBuilder Builder(CGM);
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001510 auto Components = Builder.beginStruct();
John McCall9c6cb762016-11-28 22:18:33 +00001511 CGVT.createVTableInitializer(Components, VTLayout, RTTI);
1512 Components.finishAndSetAsInitializer(VTable);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001513
1514 // Set the correct linkage.
1515 VTable->setLinkage(Linkage);
1516
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001517 if (CGM.supportsCOMDAT() && VTable->isWeakForLinker())
1518 VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName()));
Rafael Espindolacb92c192015-01-15 23:18:01 +00001519
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001520 // Set the right visibility.
Rafael Espindola699f5d62018-02-07 22:15:33 +00001521 CGM.setGVProperties(VTable, RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001522
Benjamin Kramer5d34a2b2014-09-10 12:50:59 +00001523 // Use pointer alignment for the vtable. Otherwise we would align them based
1524 // on the size of the initializer which doesn't make sense as only single
1525 // values are read.
1526 unsigned PAlign = CGM.getTarget().getPointerAlign(0);
1527 VTable->setAlignment(getContext().toCharUnitsFromBits(PAlign).getQuantity());
1528
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001529 // If this is the magic class __cxxabiv1::__fundamental_type_info,
1530 // we will emit the typeinfo for the fundamental types. This is the
1531 // same behaviour as GCC.
1532 const DeclContext *DC = RD->getDeclContext();
1533 if (RD->getIdentifier() &&
1534 RD->getIdentifier()->isStr("__fundamental_type_info") &&
1535 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1536 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1537 DC->getParent()->isTranslationUnit())
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00001538 EmitFundamentalRTTIDescriptors(RD->hasAttr<DLLExportAttr>());
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001539
Evgeniy Stepanov93987df2016-01-23 01:20:18 +00001540 if (!VTable->isDeclarationForLinker())
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001541 CGM.EmitVTableTypeMetadata(VTable, VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001542}
1543
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001544bool ItaniumCXXABI::isVirtualOffsetNeededForVTableField(
1545 CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
1546 if (Vptr.NearestVBase == nullptr)
1547 return false;
1548 return NeedsVTTParameter(CGF.CurGD);
Piotr Padlewski255652e2015-09-09 22:20:28 +00001549}
1550
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001551llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1552 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1553 const CXXRecordDecl *NearestVBase) {
1554
1555 if ((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1556 NeedsVTTParameter(CGF.CurGD)) {
1557 return getVTableAddressPointInStructorWithVTT(CGF, VTableClass, Base,
1558 NearestVBase);
1559 }
1560 return getVTableAddressPoint(Base, VTableClass);
1561}
1562
1563llvm::Constant *
1564ItaniumCXXABI::getVTableAddressPoint(BaseSubobject Base,
1565 const CXXRecordDecl *VTableClass) {
1566 llvm::GlobalValue *VTable = getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001567
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001568 // Find the appropriate vtable within the vtable group, and the address point
1569 // within that vtable.
1570 VTableLayout::AddressPointLocation AddressPoint =
1571 CGM.getItaniumVTableContext()
1572 .getVTableLayout(VTableClass)
1573 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001574 llvm::Value *Indices[] = {
Peter Collingbourne4e6a5402016-03-14 19:07:10 +00001575 llvm::ConstantInt::get(CGM.Int32Ty, 0),
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001576 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.VTableIndex),
1577 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.AddressPointIndex),
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001578 };
1579
Peter Collingbourne25a2b702016-12-13 20:50:44 +00001580 return llvm::ConstantExpr::getGetElementPtr(VTable->getValueType(), VTable,
1581 Indices, /*InBounds=*/true,
1582 /*InRangeIndex=*/1);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001583}
1584
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001585llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructorWithVTT(
1586 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1587 const CXXRecordDecl *NearestVBase) {
1588 assert((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1589 NeedsVTTParameter(CGF.CurGD) && "This class doesn't have VTT");
1590
1591 // Get the secondary vpointer index.
1592 uint64_t VirtualPointerIndex =
1593 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1594
1595 /// Load the VTT.
1596 llvm::Value *VTT = CGF.LoadCXXVTT();
1597 if (VirtualPointerIndex)
1598 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1599
1600 // And load the address point from the VTT.
1601 return CGF.Builder.CreateAlignedLoad(VTT, CGF.getPointerAlign());
1602}
1603
1604llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1605 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1606 return getVTableAddressPoint(Base, VTableClass);
1607}
1608
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001609llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1610 CharUnits VPtrOffset) {
1611 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1612
1613 llvm::GlobalVariable *&VTable = VTables[RD];
1614 if (VTable)
1615 return VTable;
1616
Eric Christopherd160c502016-01-29 01:35:53 +00001617 // Queue up this vtable for possible deferred emission.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001618 CGM.addDeferredVTable(RD);
1619
Yaron Kerene46f7ed2015-07-29 14:21:47 +00001620 SmallString<256> Name;
1621 llvm::raw_svector_ostream Out(Name);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001622 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001623
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001624 const VTableLayout &VTLayout =
1625 CGM.getItaniumVTableContext().getVTableLayout(RD);
1626 llvm::Type *VTableType = CGM.getVTables().getVTableType(VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001627
1628 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001629 Name, VTableType, llvm::GlobalValue::ExternalLinkage);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001630 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Hans Wennborgda24e9c2014-06-02 23:13:03 +00001631
Rafael Espindola922f2aa2018-02-23 19:30:48 +00001632 CGM.setGVProperties(VTable, RD);
1633
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001634 return VTable;
1635}
1636
John McCall9831b842018-02-06 18:52:44 +00001637CGCallee ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1638 GlobalDecl GD,
1639 Address This,
1640 llvm::Type *Ty,
1641 SourceLocation Loc) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001642 Ty = Ty->getPointerTo()->getPointerTo();
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001643 auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
1644 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty, MethodDecl->getParent());
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001645
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001646 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
John McCall9831b842018-02-06 18:52:44 +00001647 llvm::Value *VFunc;
1648 if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) {
1649 VFunc = CGF.EmitVTableTypeCheckedLoad(
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001650 MethodDecl->getParent(), VTable,
1651 VTableIndex * CGM.getContext().getTargetInfo().getPointerWidth(0) / 8);
John McCall9831b842018-02-06 18:52:44 +00001652 } else {
1653 CGF.EmitTypeMetadataCodeForVCall(MethodDecl->getParent(), VTable, Loc);
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001654
John McCall9831b842018-02-06 18:52:44 +00001655 llvm::Value *VFuncPtr =
1656 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1657 auto *VFuncLoad =
1658 CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign());
Piotr Padlewski77cc9622016-10-29 15:28:30 +00001659
John McCall9831b842018-02-06 18:52:44 +00001660 // Add !invariant.load md to virtual function load to indicate that
1661 // function didn't change inside vtable.
1662 // It's safe to add it without -fstrict-vtable-pointers, but it would not
1663 // help in devirtualization because it will only matter if we will have 2
1664 // the same virtual function loads from the same vtable load, which won't
1665 // happen without enabled devirtualization with -fstrict-vtable-pointers.
1666 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1667 CGM.getCodeGenOpts().StrictVTablePointers)
1668 VFuncLoad->setMetadata(
1669 llvm::LLVMContext::MD_invariant_load,
1670 llvm::MDNode::get(CGM.getLLVMContext(),
1671 llvm::ArrayRef<llvm::Metadata *>()));
1672 VFunc = VFuncLoad;
1673 }
John McCallb92ab1a2016-10-26 23:46:34 +00001674
Reid Kleckner138ab492018-05-17 18:12:18 +00001675 CGCallee Callee(MethodDecl->getCanonicalDecl(), VFunc);
John McCall9831b842018-02-06 18:52:44 +00001676 return Callee;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001677}
1678
David Majnemer0c0b6d92014-10-31 20:09:12 +00001679llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
1680 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
John McCall7f416cc2015-09-08 08:05:57 +00001681 Address This, const CXXMemberCallExpr *CE) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001682 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001683 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1684
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001685 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1686 Dtor, getFromDtorType(DtorType));
George Burgess IV00f70bd2018-03-01 05:43:23 +00001687 llvm::FunctionType *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
John McCallb92ab1a2016-10-26 23:46:34 +00001688 CGCallee Callee =
Peter Collingbourneea211002018-02-05 23:09:13 +00001689 CGCallee::forVirtual(CE, GlobalDecl(Dtor, DtorType), This, Ty);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001690
John McCall7f416cc2015-09-08 08:05:57 +00001691 CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(),
1692 This.getPointer(), /*ImplicitParam=*/nullptr,
Richard Smith762672a2016-09-28 19:09:10 +00001693 QualType(), CE, nullptr);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001694 return nullptr;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001695}
1696
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001697void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001698 CodeGenVTables &VTables = CGM.getVTables();
1699 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001700 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001701}
1702
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001703bool ItaniumCXXABI::canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const {
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001704 // We don't emit available_externally vtables if we are in -fapple-kext mode
1705 // because kext mode does not permit devirtualization.
1706 if (CGM.getLangOpts().AppleKext)
1707 return false;
1708
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00001709 // If we don't have any not emitted inline virtual function, and if vtable is
1710 // not hidden, then we are safe to emit available_externally copy of vtable.
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001711 // FIXME we can still emit a copy of the vtable if we
1712 // can emit definition of the inline functions.
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00001713 return !hasAnyUnusedVirtualInlineFunction(RD) && !isVTableHidden(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001714}
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001715static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001716 Address InitialPtr,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001717 int64_t NonVirtualAdjustment,
1718 int64_t VirtualAdjustment,
1719 bool IsReturnAdjustment) {
1720 if (!NonVirtualAdjustment && !VirtualAdjustment)
John McCall7f416cc2015-09-08 08:05:57 +00001721 return InitialPtr.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001722
John McCall7f416cc2015-09-08 08:05:57 +00001723 Address V = CGF.Builder.CreateElementBitCast(InitialPtr, CGF.Int8Ty);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001724
John McCall7f416cc2015-09-08 08:05:57 +00001725 // In a base-to-derived cast, the non-virtual adjustment is applied first.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001726 if (NonVirtualAdjustment && !IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001727 V = CGF.Builder.CreateConstInBoundsByteGEP(V,
1728 CharUnits::fromQuantity(NonVirtualAdjustment));
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001729 }
1730
John McCall7f416cc2015-09-08 08:05:57 +00001731 // Perform the virtual adjustment if we have one.
1732 llvm::Value *ResultPtr;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001733 if (VirtualAdjustment) {
1734 llvm::Type *PtrDiffTy =
1735 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1736
John McCall7f416cc2015-09-08 08:05:57 +00001737 Address VTablePtrPtr = CGF.Builder.CreateElementBitCast(V, CGF.Int8PtrTy);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001738 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1739
1740 llvm::Value *OffsetPtr =
1741 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1742
1743 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1744
1745 // Load the adjustment offset from the vtable.
John McCall7f416cc2015-09-08 08:05:57 +00001746 llvm::Value *Offset =
1747 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001748
1749 // Adjust our pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001750 ResultPtr = CGF.Builder.CreateInBoundsGEP(V.getPointer(), Offset);
1751 } else {
1752 ResultPtr = V.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001753 }
1754
John McCall7f416cc2015-09-08 08:05:57 +00001755 // In a derived-to-base conversion, the non-virtual adjustment is
1756 // applied second.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001757 if (NonVirtualAdjustment && IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001758 ResultPtr = CGF.Builder.CreateConstInBoundsGEP1_64(ResultPtr,
1759 NonVirtualAdjustment);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001760 }
1761
1762 // Cast back to the original type.
John McCall7f416cc2015-09-08 08:05:57 +00001763 return CGF.Builder.CreateBitCast(ResultPtr, InitialPtr.getType());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001764}
1765
1766llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001767 Address This,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001768 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001769 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1770 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001771 /*IsReturnAdjustment=*/false);
1772}
1773
1774llvm::Value *
John McCall7f416cc2015-09-08 08:05:57 +00001775ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001776 const ReturnAdjustment &RA) {
1777 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1778 RA.Virtual.Itanium.VBaseOffsetOffset,
1779 /*IsReturnAdjustment=*/true);
1780}
1781
John McCall5d865c322010-08-31 07:33:07 +00001782void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1783 RValue RV, QualType ResultType) {
1784 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1785 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1786
1787 // Destructor thunks in the ARM ABI have indeterminate results.
John McCall7f416cc2015-09-08 08:05:57 +00001788 llvm::Type *T = CGF.ReturnValue.getElementType();
John McCall5d865c322010-08-31 07:33:07 +00001789 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1790 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1791}
John McCall8ed55a52010-09-02 09:58:18 +00001792
1793/************************** Array allocation cookies **************************/
1794
John McCallb91cd662012-05-01 05:23:51 +00001795CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1796 // The array cookie is a size_t; pad that up to the element alignment.
1797 // The cookie is actually right-justified in that space.
1798 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1799 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001800}
1801
John McCall7f416cc2015-09-08 08:05:57 +00001802Address ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1803 Address NewPtr,
1804 llvm::Value *NumElements,
1805 const CXXNewExpr *expr,
1806 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001807 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001808
John McCall7f416cc2015-09-08 08:05:57 +00001809 unsigned AS = NewPtr.getAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001810
John McCall9bca9232010-09-02 10:25:57 +00001811 ASTContext &Ctx = getContext();
John McCall7f416cc2015-09-08 08:05:57 +00001812 CharUnits SizeSize = CGF.getSizeSize();
John McCall8ed55a52010-09-02 09:58:18 +00001813
1814 // The size of the cookie.
1815 CharUnits CookieSize =
1816 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001817 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001818
1819 // Compute an offset to the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001820 Address CookiePtr = NewPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001821 CharUnits CookieOffset = CookieSize - SizeSize;
1822 if (!CookieOffset.isZero())
John McCall7f416cc2015-09-08 08:05:57 +00001823 CookiePtr = CGF.Builder.CreateConstInBoundsByteGEP(CookiePtr, CookieOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001824
1825 // Write the number of elements into the appropriate slot.
John McCall7f416cc2015-09-08 08:05:57 +00001826 Address NumElementsPtr =
1827 CGF.Builder.CreateElementBitCast(CookiePtr, CGF.SizeTy);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001828 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
John McCall7f416cc2015-09-08 08:05:57 +00001829
1830 // Handle the array cookie specially in ASan.
Filipe Cabecinhas6f83fa92018-01-02 13:46:12 +00001831 if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 &&
Filipe Cabecinhas4ba58172018-02-12 11:49:02 +00001832 (expr->getOperatorNew()->isReplaceableGlobalAllocationFunction() ||
1833 CGM.getCodeGenOpts().SanitizeAddressPoisonClassMemberArrayNewCookie)) {
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001834 // The store to the CookiePtr does not need to be instrumented.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001835 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
1836 llvm::FunctionType *FTy =
John McCall7f416cc2015-09-08 08:05:57 +00001837 llvm::FunctionType::get(CGM.VoidTy, NumElementsPtr.getType(), false);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001838 llvm::Constant *F =
1839 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001840 CGF.Builder.CreateCall(F, NumElementsPtr.getPointer());
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001841 }
John McCall8ed55a52010-09-02 09:58:18 +00001842
1843 // Finally, compute a pointer to the actual data buffer by skipping
1844 // over the cookie completely.
John McCall7f416cc2015-09-08 08:05:57 +00001845 return CGF.Builder.CreateConstInBoundsByteGEP(NewPtr, CookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001846}
1847
John McCallb91cd662012-05-01 05:23:51 +00001848llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001849 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00001850 CharUnits cookieSize) {
1851 // The element size is right-justified in the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001852 Address numElementsPtr = allocPtr;
1853 CharUnits numElementsOffset = cookieSize - CGF.getSizeSize();
John McCallb91cd662012-05-01 05:23:51 +00001854 if (!numElementsOffset.isZero())
1855 numElementsPtr =
John McCall7f416cc2015-09-08 08:05:57 +00001856 CGF.Builder.CreateConstInBoundsByteGEP(numElementsPtr, numElementsOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001857
John McCall7f416cc2015-09-08 08:05:57 +00001858 unsigned AS = allocPtr.getAddressSpace();
1859 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001860 if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0)
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001861 return CGF.Builder.CreateLoad(numElementsPtr);
1862 // In asan mode emit a function call instead of a regular load and let the
1863 // run-time deal with it: if the shadow is properly poisoned return the
1864 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
1865 // We can't simply ignore this load using nosanitize metadata because
1866 // the metadata may be lost.
1867 llvm::FunctionType *FTy =
1868 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
1869 llvm::Constant *F =
1870 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001871 return CGF.Builder.CreateCall(F, numElementsPtr.getPointer());
John McCall8ed55a52010-09-02 09:58:18 +00001872}
1873
John McCallb91cd662012-05-01 05:23:51 +00001874CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001875 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001876 // struct array_cookie {
1877 // std::size_t element_size; // element_size != 0
1878 // std::size_t element_count;
1879 // };
John McCallc19c7062013-01-25 23:36:19 +00001880 // But the base ABI doesn't give anything an alignment greater than
1881 // 8, so we can dismiss this as typical ABI-author blindness to
1882 // actual language complexity and round up to the element alignment.
1883 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1884 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001885}
1886
John McCall7f416cc2015-09-08 08:05:57 +00001887Address ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1888 Address newPtr,
1889 llvm::Value *numElements,
1890 const CXXNewExpr *expr,
1891 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001892 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001893
John McCall8ed55a52010-09-02 09:58:18 +00001894 // The cookie is always at the start of the buffer.
John McCall7f416cc2015-09-08 08:05:57 +00001895 Address cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001896
1897 // The first element is the element size.
John McCall7f416cc2015-09-08 08:05:57 +00001898 cookie = CGF.Builder.CreateElementBitCast(cookie, CGF.SizeTy);
John McCallc19c7062013-01-25 23:36:19 +00001899 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1900 getContext().getTypeSizeInChars(elementType).getQuantity());
1901 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001902
1903 // The second element is the element count.
John McCall7f416cc2015-09-08 08:05:57 +00001904 cookie = CGF.Builder.CreateConstInBoundsGEP(cookie, 1, CGF.getSizeSize());
John McCallc19c7062013-01-25 23:36:19 +00001905 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001906
1907 // Finally, compute a pointer to the actual data buffer by skipping
1908 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001909 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
John McCall7f416cc2015-09-08 08:05:57 +00001910 return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001911}
1912
John McCallb91cd662012-05-01 05:23:51 +00001913llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001914 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00001915 CharUnits cookieSize) {
1916 // The number of elements is at offset sizeof(size_t) relative to
1917 // the allocated pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001918 Address numElementsPtr
1919 = CGF.Builder.CreateConstInBoundsByteGEP(allocPtr, CGF.getSizeSize());
John McCall8ed55a52010-09-02 09:58:18 +00001920
John McCall7f416cc2015-09-08 08:05:57 +00001921 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
John McCallb91cd662012-05-01 05:23:51 +00001922 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001923}
1924
John McCall68ff0372010-09-08 01:44:27 +00001925/*********************** Static local initialization **************************/
1926
1927static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001928 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001929 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001930 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001931 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001932 GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00001933 return CGM.CreateRuntimeFunction(
1934 FTy, "__cxa_guard_acquire",
1935 llvm::AttributeList::get(CGM.getLLVMContext(),
1936 llvm::AttributeList::FunctionIndex,
1937 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001938}
1939
1940static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001941 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001942 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001943 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001944 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00001945 return CGM.CreateRuntimeFunction(
1946 FTy, "__cxa_guard_release",
1947 llvm::AttributeList::get(CGM.getLLVMContext(),
1948 llvm::AttributeList::FunctionIndex,
1949 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001950}
1951
1952static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001953 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001954 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001955 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001956 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00001957 return CGM.CreateRuntimeFunction(
1958 FTy, "__cxa_guard_abort",
1959 llvm::AttributeList::get(CGM.getLLVMContext(),
1960 llvm::AttributeList::FunctionIndex,
1961 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001962}
1963
1964namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001965 struct CallGuardAbort final : EHScopeStack::Cleanup {
John McCall68ff0372010-09-08 01:44:27 +00001966 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001967 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001968
Craig Topper4f12f102014-03-12 06:41:41 +00001969 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00001970 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1971 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001972 }
1973 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001974}
John McCall68ff0372010-09-08 01:44:27 +00001975
1976/// The ARM code here follows the Itanium code closely enough that we
1977/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001978void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1979 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001980 llvm::GlobalVariable *var,
1981 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00001982 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00001983
Richard Smith62f19e72016-06-25 00:15:56 +00001984 // Inline variables that weren't instantiated from variable templates have
1985 // partially-ordered initialization within their translation unit.
1986 bool NonTemplateInline =
1987 D.isInline() &&
1988 !isTemplateInstantiation(D.getTemplateSpecializationKind());
1989
1990 // We only need to use thread-safe statics for local non-TLS variables and
1991 // inline variables; other global initialization is always single-threaded
1992 // or (through lazy dynamic loading in multiple threads) unsequenced.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001993 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
Richard Smith62f19e72016-06-25 00:15:56 +00001994 (D.isLocalVarDecl() || NonTemplateInline) &&
1995 !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001996
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001997 // If we have a global variable with internal linkage and thread-safe statics
1998 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00001999 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
2000
2001 llvm::IntegerType *guardTy;
John McCall7f416cc2015-09-08 08:05:57 +00002002 CharUnits guardAlignment;
John McCall5aa52592011-06-17 07:33:57 +00002003 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00002004 guardTy = CGF.Int8Ty;
John McCall7f416cc2015-09-08 08:05:57 +00002005 guardAlignment = CharUnits::One();
John McCall5aa52592011-06-17 07:33:57 +00002006 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00002007 // Guard variables are 64 bits in the generic ABI and size width on ARM
2008 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
John McCall7f416cc2015-09-08 08:05:57 +00002009 if (UseARMGuardVarABI) {
2010 guardTy = CGF.SizeTy;
2011 guardAlignment = CGF.getSizeAlign();
2012 } else {
2013 guardTy = CGF.Int64Ty;
2014 guardAlignment = CharUnits::fromQuantity(
2015 CGM.getDataLayout().getABITypeAlignment(guardTy));
2016 }
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00002017 }
John McCallb88a5662012-03-30 21:00:39 +00002018 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00002019
John McCallb88a5662012-03-30 21:00:39 +00002020 // Create the guard variable if we don't already have it (as we
2021 // might if we're double-emitting this function body).
2022 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
2023 if (!guard) {
2024 // Mangle the name for the guard.
2025 SmallString<256> guardName;
2026 {
2027 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00002028 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00002029 }
John McCall8e7cb6d2010-11-02 21:04:24 +00002030
John McCallb88a5662012-03-30 21:00:39 +00002031 // Create the guard variable with a zero-initializer.
2032 // Just absorb linkage and visibility from the guarded variable.
2033 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
2034 false, var->getLinkage(),
2035 llvm::ConstantInt::get(guardTy, 0),
2036 guardName.str());
Rafael Espindola699f5d62018-02-07 22:15:33 +00002037 guard->setDSOLocal(var->isDSOLocal());
John McCallb88a5662012-03-30 21:00:39 +00002038 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00002039 // If the variable is thread-local, so is its guard variable.
2040 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCall7f416cc2015-09-08 08:05:57 +00002041 guard->setAlignment(guardAlignment.getQuantity());
John McCallb88a5662012-03-30 21:00:39 +00002042
Yaron Keren5bfa1082015-09-03 20:33:29 +00002043 // The ABI says: "It is suggested that it be emitted in the same COMDAT
2044 // group as the associated data object." In practice, this doesn't work for
Dan Gohman839f2152017-01-17 21:46:38 +00002045 // non-ELF and non-Wasm object formats, so only do it for ELF and Wasm.
Rafael Espindola0d4fb982015-01-12 22:13:53 +00002046 llvm::Comdat *C = var->getComdat();
Yaron Keren5bfa1082015-09-03 20:33:29 +00002047 if (!D.isLocalVarDecl() && C &&
Dan Gohman839f2152017-01-17 21:46:38 +00002048 (CGM.getTarget().getTriple().isOSBinFormatELF() ||
2049 CGM.getTarget().getTriple().isOSBinFormatWasm())) {
Rafael Espindola2ae4b632014-09-19 19:43:18 +00002050 guard->setComdat(C);
Richard Smith62f19e72016-06-25 00:15:56 +00002051 // An inline variable's guard function is run from the per-TU
2052 // initialization function, not via a dedicated global ctor function, so
2053 // we can't put it in a comdat.
2054 if (!NonTemplateInline)
2055 CGF.CurFn->setComdat(C);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00002056 } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) {
2057 guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName()));
Rafael Espindola2ae4b632014-09-19 19:43:18 +00002058 }
2059
John McCallb88a5662012-03-30 21:00:39 +00002060 CGM.setStaticLocalDeclGuardAddress(&D, guard);
2061 }
John McCall87590e62012-03-30 07:09:50 +00002062
John McCall7f416cc2015-09-08 08:05:57 +00002063 Address guardAddr = Address(guard, guardAlignment);
2064
John McCall68ff0372010-09-08 01:44:27 +00002065 // Test whether the variable has completed initialization.
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002066 //
John McCall68ff0372010-09-08 01:44:27 +00002067 // Itanium C++ ABI 3.3.2:
2068 // The following is pseudo-code showing how these functions can be used:
2069 // if (obj_guard.first_byte == 0) {
2070 // if ( __cxa_guard_acquire (&obj_guard) ) {
2071 // try {
2072 // ... initialize the object ...;
2073 // } catch (...) {
2074 // __cxa_guard_abort (&obj_guard);
2075 // throw;
2076 // }
2077 // ... queue object destructor with __cxa_atexit() ...;
2078 // __cxa_guard_release (&obj_guard);
2079 // }
2080 // }
Tim Northovera2ee4332014-03-29 15:09:45 +00002081
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002082 // Load the first byte of the guard variable.
2083 llvm::LoadInst *LI =
John McCall7f416cc2015-09-08 08:05:57 +00002084 Builder.CreateLoad(Builder.CreateElementBitCast(guardAddr, CGM.Int8Ty));
John McCall68ff0372010-09-08 01:44:27 +00002085
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002086 // Itanium ABI:
2087 // An implementation supporting thread-safety on multiprocessor
2088 // systems must also guarantee that references to the initialized
2089 // object do not occur before the load of the initialization flag.
2090 //
2091 // In LLVM, we do this by marking the load Acquire.
2092 if (threadsafe)
JF Bastien92f4ef12016-04-06 17:26:42 +00002093 LI->setAtomic(llvm::AtomicOrdering::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00002094
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002095 // For ARM, we should only check the first bit, rather than the entire byte:
2096 //
2097 // ARM C++ ABI 3.2.3.1:
2098 // To support the potential use of initialization guard variables
2099 // as semaphores that are the target of ARM SWP and LDREX/STREX
2100 // synchronizing instructions we define a static initialization
2101 // guard variable to be a 4-byte aligned, 4-byte word with the
2102 // following inline access protocol.
2103 // #define INITIALIZED 1
2104 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
2105 // if (__cxa_guard_acquire(&obj_guard))
2106 // ...
2107 // }
2108 //
2109 // and similarly for ARM64:
2110 //
2111 // ARM64 C++ ABI 3.2.2:
2112 // This ABI instead only specifies the value bit 0 of the static guard
2113 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
2114 // variable is not initialized and 1 when it is.
2115 llvm::Value *V =
2116 (UseARMGuardVarABI && !useInt8GuardVariable)
2117 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
2118 : LI;
Richard Smithae8d62c2017-07-26 22:01:09 +00002119 llvm::Value *NeedsInit = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00002120
2121 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
2122 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2123
2124 // Check if the first byte of the guard variable is zero.
Richard Smithae8d62c2017-07-26 22:01:09 +00002125 CGF.EmitCXXGuardedInitBranch(NeedsInit, InitCheckBlock, EndBlock,
2126 CodeGenFunction::GuardKind::VariableGuard, &D);
John McCall68ff0372010-09-08 01:44:27 +00002127
2128 CGF.EmitBlock(InitCheckBlock);
2129
2130 // Variables used when coping with thread-safe statics and exceptions.
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002131 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002132 // Call __cxa_guard_acquire.
2133 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00002134 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002135
John McCall68ff0372010-09-08 01:44:27 +00002136 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002137
John McCall68ff0372010-09-08 01:44:27 +00002138 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
2139 InitBlock, EndBlock);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002140
John McCall68ff0372010-09-08 01:44:27 +00002141 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00002142 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002143
John McCall68ff0372010-09-08 01:44:27 +00002144 CGF.EmitBlock(InitBlock);
2145 }
2146
2147 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00002148 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00002149
John McCall5aa52592011-06-17 07:33:57 +00002150 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002151 // Pop the guard-abort cleanup if we pushed one.
2152 CGF.PopCleanupBlock();
2153
2154 // Call __cxa_guard_release. This cannot throw.
John McCall7f416cc2015-09-08 08:05:57 +00002155 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy),
2156 guardAddr.getPointer());
John McCall68ff0372010-09-08 01:44:27 +00002157 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002158 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guardAddr);
John McCall68ff0372010-09-08 01:44:27 +00002159 }
2160
2161 CGF.EmitBlock(EndBlock);
2162}
John McCallc84ed6a2012-05-01 06:13:13 +00002163
2164/// Register a global destructor using __cxa_atexit.
2165static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
2166 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00002167 llvm::Constant *addr,
2168 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00002169 const char *Name = "__cxa_atexit";
2170 if (TLS) {
2171 const llvm::Triple &T = CGF.getTarget().getTriple();
Manman Renf93fff22015-11-11 23:08:18 +00002172 Name = T.isOSDarwin() ? "_tlv_atexit" : "__cxa_thread_atexit";
Bill Wendling95cae882013-05-02 19:18:03 +00002173 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00002174
John McCallc84ed6a2012-05-01 06:13:13 +00002175 // We're assuming that the destructor function is something we can
2176 // reasonably call with the default CC. Go ahead and cast it to the
2177 // right prototype.
2178 llvm::Type *dtorTy =
2179 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
2180
2181 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
2182 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
2183 llvm::FunctionType *atexitTy =
2184 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
2185
2186 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002187 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00002188 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
2189 fn->setDoesNotThrow();
2190
2191 // Create a variable that binds the atexit to this shared object.
2192 llvm::Constant *handle =
Reid Kleckner9de92142017-02-13 18:49:21 +00002193 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
2194 auto *GV = cast<llvm::GlobalValue>(handle->stripPointerCasts());
2195 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
John McCallc84ed6a2012-05-01 06:13:13 +00002196
Akira Hatanaka617e2612018-04-17 18:41:52 +00002197 if (!addr)
2198 // addr is null when we are trying to register a dtor annotated with
2199 // __attribute__((destructor)) in a constructor function. Using null here is
2200 // okay because this argument is just passed back to the destructor
2201 // function.
2202 addr = llvm::Constant::getNullValue(CGF.Int8PtrTy);
2203
John McCallc84ed6a2012-05-01 06:13:13 +00002204 llvm::Value *args[] = {
2205 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
2206 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
2207 handle
2208 };
John McCall882987f2013-02-28 19:01:20 +00002209 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00002210}
2211
Akira Hatanaka617e2612018-04-17 18:41:52 +00002212void CodeGenModule::registerGlobalDtorsWithAtExit() {
2213 for (const auto I : DtorsUsingAtExit) {
2214 int Priority = I.first;
2215 const llvm::TinyPtrVector<llvm::Function *> &Dtors = I.second;
2216
2217 // Create a function that registers destructors that have the same priority.
2218 //
2219 // Since constructor functions are run in non-descending order of their
2220 // priorities, destructors are registered in non-descending order of their
2221 // priorities, and since destructor functions are run in the reverse order
2222 // of their registration, destructor functions are run in non-ascending
2223 // order of their priorities.
2224 CodeGenFunction CGF(*this);
2225 std::string GlobalInitFnName =
2226 std::string("__GLOBAL_init_") + llvm::to_string(Priority);
2227 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
2228 llvm::Function *GlobalInitFn = CreateGlobalInitOrDestructFunction(
2229 FTy, GlobalInitFnName, getTypes().arrangeNullaryFunction(),
2230 SourceLocation());
2231 ASTContext &Ctx = getContext();
2232 FunctionDecl *FD = FunctionDecl::Create(
2233 Ctx, Ctx.getTranslationUnitDecl(), SourceLocation(), SourceLocation(),
2234 &Ctx.Idents.get(GlobalInitFnName), Ctx.VoidTy, nullptr, SC_Static,
2235 false, false);
2236 CGF.StartFunction(GlobalDecl(FD), getContext().VoidTy, GlobalInitFn,
2237 getTypes().arrangeNullaryFunction(), FunctionArgList(),
2238 SourceLocation(), SourceLocation());
2239
2240 for (auto *Dtor : Dtors) {
2241 // Register the destructor function calling __cxa_atexit if it is
2242 // available. Otherwise fall back on calling atexit.
2243 if (getCodeGenOpts().CXAAtExit)
2244 emitGlobalDtorWithCXAAtExit(CGF, Dtor, nullptr, false);
2245 else
2246 CGF.registerGlobalDtorWithAtExit(Dtor);
2247 }
2248
2249 CGF.FinishFunction();
2250 AddGlobalCtor(GlobalInitFn, Priority, nullptr);
2251 }
2252}
2253
John McCallc84ed6a2012-05-01 06:13:13 +00002254/// Register a global destructor as best as we know how.
2255void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00002256 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00002257 llvm::Constant *dtor,
2258 llvm::Constant *addr) {
2259 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002260 if (CGM.getCodeGenOpts().CXAAtExit)
2261 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
2262
2263 if (D.getTLSKind())
2264 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00002265
2266 // In Apple kexts, we want to add a global destructor entry.
2267 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00002268 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00002269 // Generate a global destructor entry.
2270 return CGM.AddCXXDtorEntry(dtor, addr);
2271 }
2272
David Blaikieebe87e12013-08-27 23:57:18 +00002273 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00002274}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002275
David Majnemer9b21c332014-07-11 20:28:10 +00002276static bool isThreadWrapperReplaceable(const VarDecl *VD,
2277 CodeGen::CodeGenModule &CGM) {
2278 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
Manman Renf93fff22015-11-11 23:08:18 +00002279 // Darwin prefers to have references to thread local variables to go through
David Majnemer9b21c332014-07-11 20:28:10 +00002280 // the thread wrapper instead of directly referencing the backing variable.
2281 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
Manman Renf93fff22015-11-11 23:08:18 +00002282 CGM.getTarget().getTriple().isOSDarwin();
David Majnemer9b21c332014-07-11 20:28:10 +00002283}
2284
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002285/// Get the appropriate linkage for the wrapper function. This is essentially
David Majnemer4632e1e2014-06-27 16:56:27 +00002286/// the weak form of the variable's linkage; every translation unit which needs
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002287/// the wrapper emits a copy, and we want the linker to merge them.
David Majnemer35ab3282014-06-11 04:08:55 +00002288static llvm::GlobalValue::LinkageTypes
2289getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
2290 llvm::GlobalValue::LinkageTypes VarLinkage =
2291 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
2292
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002293 // For internal linkage variables, we don't need an external or weak wrapper.
2294 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
2295 return VarLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00002296
David Majnemer9b21c332014-07-11 20:28:10 +00002297 // If the thread wrapper is replaceable, give it appropriate linkage.
Manman Ren68150262015-11-11 22:42:31 +00002298 if (isThreadWrapperReplaceable(VD, CGM))
2299 if (!llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) &&
2300 !llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
2301 return VarLinkage;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002302 return llvm::GlobalValue::WeakODRLinkage;
2303}
2304
2305llvm::Function *
2306ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +00002307 llvm::Value *Val) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002308 // Mangle the name for the thread_local wrapper function.
2309 SmallString<256> WrapperName;
2310 {
2311 llvm::raw_svector_ostream Out(WrapperName);
2312 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002313 }
2314
Akira Hatanaka26907f92016-01-15 03:34:06 +00002315 // FIXME: If VD is a definition, we should regenerate the function attributes
2316 // before returning.
Alexander Musmanf94c3182014-09-26 06:28:25 +00002317 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002318 return cast<llvm::Function>(V);
2319
Akira Hatanaka26907f92016-01-15 03:34:06 +00002320 QualType RetQT = VD->getType();
2321 if (RetQT->isReferenceType())
2322 RetQT = RetQT.getNonReferenceType();
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002323
John McCallc56a8b32016-03-11 04:30:31 +00002324 const CGFunctionInfo &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2325 getContext().getPointerType(RetQT), FunctionArgList());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002326
2327 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FI);
David Majnemer35ab3282014-06-11 04:08:55 +00002328 llvm::Function *Wrapper =
2329 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
2330 WrapperName.str(), &CGM.getModule());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002331
2332 CGM.SetLLVMFunctionAttributes(nullptr, FI, Wrapper);
2333
2334 if (VD->hasDefinition())
2335 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Wrapper);
2336
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002337 // Always resolve references to the wrapper at link time.
Manman Ren68150262015-11-11 22:42:31 +00002338 if (!Wrapper->hasLocalLinkage() && !(isThreadWrapperReplaceable(VD, CGM) &&
2339 !llvm::GlobalVariable::isLinkOnceLinkage(Wrapper->getLinkage()) &&
2340 !llvm::GlobalVariable::isWeakODRLinkage(Wrapper->getLinkage())))
Duncan P. N. Exon Smith4434d362014-05-07 22:36:11 +00002341 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
Manman Renb0b3af72015-12-17 00:42:36 +00002342
2343 if (isThreadWrapperReplaceable(VD, CGM)) {
2344 Wrapper->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2345 Wrapper->addFnAttr(llvm::Attribute::NoUnwind);
2346 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002347 return Wrapper;
2348}
2349
2350void ItaniumCXXABI::EmitThreadLocalInitFuncs(
Richard Smith5a99c492015-12-01 01:10:48 +00002351 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
2352 ArrayRef<llvm::Function *> CXXThreadLocalInits,
2353 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
David Majnemerb3341ea2014-10-05 05:05:40 +00002354 llvm::Function *InitFunc = nullptr;
Richard Smithfbe23692017-01-13 00:43:31 +00002355
2356 // Separate initializers into those with ordered (or partially-ordered)
2357 // initialization and those with unordered initialization.
2358 llvm::SmallVector<llvm::Function *, 8> OrderedInits;
2359 llvm::SmallDenseMap<const VarDecl *, llvm::Function *> UnorderedInits;
2360 for (unsigned I = 0; I != CXXThreadLocalInits.size(); ++I) {
2361 if (isTemplateInstantiation(
2362 CXXThreadLocalInitVars[I]->getTemplateSpecializationKind()))
2363 UnorderedInits[CXXThreadLocalInitVars[I]->getCanonicalDecl()] =
2364 CXXThreadLocalInits[I];
2365 else
2366 OrderedInits.push_back(CXXThreadLocalInits[I]);
2367 }
2368
2369 if (!OrderedInits.empty()) {
David Majnemerb3341ea2014-10-05 05:05:40 +00002370 // Generate a guarded initialization function.
2371 llvm::FunctionType *FTy =
2372 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002373 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2374 InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init", FI,
Alexey Samsonov1444bb92014-10-17 00:20:19 +00002375 SourceLocation(),
David Majnemerb3341ea2014-10-05 05:05:40 +00002376 /*TLS=*/true);
2377 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
2378 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
2379 llvm::GlobalVariable::InternalLinkage,
2380 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
2381 Guard->setThreadLocal(true);
John McCall7f416cc2015-09-08 08:05:57 +00002382
2383 CharUnits GuardAlign = CharUnits::One();
2384 Guard->setAlignment(GuardAlign.getQuantity());
2385
Richard Smithfbe23692017-01-13 00:43:31 +00002386 CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(InitFunc, OrderedInits,
2387 Address(Guard, GuardAlign));
Manman Ren5e5d0462016-03-18 23:35:21 +00002388 // On Darwin platforms, use CXX_FAST_TLS calling convention.
2389 if (CGM.getTarget().getTriple().isOSDarwin()) {
2390 InitFunc->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2391 InitFunc->addFnAttr(llvm::Attribute::NoUnwind);
2392 }
David Majnemerb3341ea2014-10-05 05:05:40 +00002393 }
Richard Smithfbe23692017-01-13 00:43:31 +00002394
2395 // Emit thread wrappers.
Richard Smith5a99c492015-12-01 01:10:48 +00002396 for (const VarDecl *VD : CXXThreadLocals) {
2397 llvm::GlobalVariable *Var =
2398 cast<llvm::GlobalVariable>(CGM.GetGlobalValue(CGM.getMangledName(VD)));
Richard Smithfbe23692017-01-13 00:43:31 +00002399 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002400
David Majnemer9b21c332014-07-11 20:28:10 +00002401 // Some targets require that all access to thread local variables go through
2402 // the thread wrapper. This means that we cannot attempt to create a thread
2403 // wrapper or a thread helper.
Richard Smithfbe23692017-01-13 00:43:31 +00002404 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition()) {
2405 Wrapper->setLinkage(llvm::Function::ExternalLinkage);
David Majnemer9b21c332014-07-11 20:28:10 +00002406 continue;
Richard Smithfbe23692017-01-13 00:43:31 +00002407 }
David Majnemer9b21c332014-07-11 20:28:10 +00002408
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002409 // Mangle the name for the thread_local initialization function.
2410 SmallString<256> InitFnName;
2411 {
2412 llvm::raw_svector_ostream Out(InitFnName);
2413 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002414 }
2415
2416 // If we have a definition for the variable, emit the initialization
2417 // function as an alias to the global Init function (if any). Otherwise,
2418 // produce a declaration of the initialization function.
Craig Topper8a13c412014-05-21 05:09:00 +00002419 llvm::GlobalValue *Init = nullptr;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002420 bool InitIsInitFunc = false;
2421 if (VD->hasDefinition()) {
2422 InitIsInitFunc = true;
Richard Smithfbe23692017-01-13 00:43:31 +00002423 llvm::Function *InitFuncToUse = InitFunc;
2424 if (isTemplateInstantiation(VD->getTemplateSpecializationKind()))
2425 InitFuncToUse = UnorderedInits.lookup(VD->getCanonicalDecl());
2426 if (InitFuncToUse)
Rafael Espindola234405b2014-05-17 21:30:14 +00002427 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
Richard Smithfbe23692017-01-13 00:43:31 +00002428 InitFuncToUse);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002429 } else {
2430 // Emit a weak global function referring to the initialization function.
2431 // This function will not exist if the TU defining the thread_local
2432 // variable in question does not need any dynamic initialization for
2433 // its thread_local variables.
2434 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
Richard Smithfbe23692017-01-13 00:43:31 +00002435 Init = llvm::Function::Create(FnTy,
2436 llvm::GlobalVariable::ExternalWeakLinkage,
2437 InitFnName.str(), &CGM.getModule());
John McCallc56a8b32016-03-11 04:30:31 +00002438 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
Akira Hatanaka26907f92016-01-15 03:34:06 +00002439 CGM.SetLLVMFunctionAttributes(nullptr, FI, cast<llvm::Function>(Init));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002440 }
2441
Rafael Espindolaabdb3222018-03-07 23:18:06 +00002442 if (Init) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002443 Init->setVisibility(Var->getVisibility());
Rafael Espindolaabdb3222018-03-07 23:18:06 +00002444 Init->setDSOLocal(Var->isDSOLocal());
2445 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002446
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002447 llvm::LLVMContext &Context = CGM.getModule().getContext();
2448 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
John McCall7f416cc2015-09-08 08:05:57 +00002449 CGBuilderTy Builder(CGM, Entry);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002450 if (InitIsInitFunc) {
Manman Ren5e5d0462016-03-18 23:35:21 +00002451 if (Init) {
2452 llvm::CallInst *CallVal = Builder.CreateCall(Init);
2453 if (isThreadWrapperReplaceable(VD, CGM))
2454 CallVal->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2455 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002456 } else {
2457 // Don't know whether we have an init function. Call it if it exists.
2458 llvm::Value *Have = Builder.CreateIsNotNull(Init);
2459 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2460 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2461 Builder.CreateCondBr(Have, InitBB, ExitBB);
2462
2463 Builder.SetInsertPoint(InitBB);
David Blaikie4ba525b2015-07-14 17:27:39 +00002464 Builder.CreateCall(Init);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002465 Builder.CreateBr(ExitBB);
2466
2467 Builder.SetInsertPoint(ExitBB);
2468 }
2469
2470 // For a reference, the result of the wrapper function is a pointer to
2471 // the referenced object.
2472 llvm::Value *Val = Var;
2473 if (VD->getType()->isReferenceType()) {
John McCall7f416cc2015-09-08 08:05:57 +00002474 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2475 Val = Builder.CreateAlignedLoad(Val, Align);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002476 }
Alexander Musmanf94c3182014-09-26 06:28:25 +00002477 if (Val->getType() != Wrapper->getReturnType())
2478 Val = Builder.CreatePointerBitCastOrAddrSpaceCast(
2479 Val, Wrapper->getReturnType(), "");
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002480 Builder.CreateRet(Val);
2481 }
2482}
2483
Richard Smith0f383742014-03-26 22:48:22 +00002484LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2485 const VarDecl *VD,
2486 QualType LValType) {
Richard Smith5a99c492015-12-01 01:10:48 +00002487 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD);
Alexander Musmanf94c3182014-09-26 06:28:25 +00002488 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002489
Manman Renb0b3af72015-12-17 00:42:36 +00002490 llvm::CallInst *CallVal = CGF.Builder.CreateCall(Wrapper);
Saleem Abdulrasool4a7130a2016-08-01 21:31:24 +00002491 CallVal->setCallingConv(Wrapper->getCallingConv());
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002492
2493 LValue LV;
2494 if (VD->getType()->isReferenceType())
Manman Renb0b3af72015-12-17 00:42:36 +00002495 LV = CGF.MakeNaturalAlignAddrLValue(CallVal, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002496 else
Manman Renb0b3af72015-12-17 00:42:36 +00002497 LV = CGF.MakeAddrLValue(CallVal, LValType,
2498 CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002499 // FIXME: need setObjCGCLValueClass?
2500 return LV;
2501}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002502
2503/// Return whether the given global decl needs a VTT parameter, which it does
2504/// if it's a base constructor or destructor with virtual bases.
2505bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
2506 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002507
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002508 // We don't have any virtual bases, just return early.
2509 if (!MD->getParent()->getNumVBases())
2510 return false;
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002511
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002512 // Check if we have a base constructor.
2513 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
2514 return true;
2515
2516 // Check if we have a base destructor.
2517 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2518 return true;
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002519
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002520 return false;
2521}
David Majnemere2cb8d12014-07-07 06:20:47 +00002522
2523namespace {
2524class ItaniumRTTIBuilder {
2525 CodeGenModule &CGM; // Per-module state.
2526 llvm::LLVMContext &VMContext;
2527 const ItaniumCXXABI &CXXABI; // Per-module state.
2528
2529 /// Fields - The fields of the RTTI descriptor currently being built.
2530 SmallVector<llvm::Constant *, 16> Fields;
2531
2532 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2533 llvm::GlobalVariable *
2534 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2535
2536 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2537 /// descriptor of the given type.
2538 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2539
2540 /// BuildVTablePointer - Build the vtable pointer for the given type.
2541 void BuildVTablePointer(const Type *Ty);
2542
2543 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2544 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2545 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2546
2547 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2548 /// classes with bases that do not satisfy the abi::__si_class_type_info
2549 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2550 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2551
2552 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2553 /// for pointer types.
2554 void BuildPointerTypeInfo(QualType PointeeTy);
2555
2556 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2557 /// type_info for an object type.
2558 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2559
2560 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2561 /// struct, used for member pointer types.
2562 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2563
2564public:
2565 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2566 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2567
2568 // Pointer type info flags.
2569 enum {
2570 /// PTI_Const - Type has const qualifier.
2571 PTI_Const = 0x1,
2572
2573 /// PTI_Volatile - Type has volatile qualifier.
2574 PTI_Volatile = 0x2,
2575
2576 /// PTI_Restrict - Type has restrict qualifier.
2577 PTI_Restrict = 0x4,
2578
2579 /// PTI_Incomplete - Type is incomplete.
2580 PTI_Incomplete = 0x8,
2581
2582 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2583 /// (in pointer to member).
Richard Smitha7d93782016-12-01 03:32:42 +00002584 PTI_ContainingClassIncomplete = 0x10,
2585
2586 /// PTI_TransactionSafe - Pointee is transaction_safe function (C++ TM TS).
2587 //PTI_TransactionSafe = 0x20,
2588
2589 /// PTI_Noexcept - Pointee is noexcept function (C++1z).
2590 PTI_Noexcept = 0x40,
David Majnemere2cb8d12014-07-07 06:20:47 +00002591 };
2592
2593 // VMI type info flags.
2594 enum {
2595 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2596 VMI_NonDiamondRepeat = 0x1,
2597
2598 /// VMI_DiamondShaped - Class is diamond shaped.
2599 VMI_DiamondShaped = 0x2
2600 };
2601
2602 // Base class type info flags.
2603 enum {
2604 /// BCTI_Virtual - Base class is virtual.
2605 BCTI_Virtual = 0x1,
2606
2607 /// BCTI_Public - Base class is public.
2608 BCTI_Public = 0x2
2609 };
2610
2611 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
2612 ///
2613 /// \param Force - true to force the creation of this RTTI value
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00002614 /// \param DLLExport - true to mark the RTTI value as DLLExport
2615 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false,
2616 bool DLLExport = false);
David Majnemere2cb8d12014-07-07 06:20:47 +00002617};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002618}
David Majnemere2cb8d12014-07-07 06:20:47 +00002619
2620llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2621 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002622 SmallString<256> Name;
2623 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002624 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002625
2626 // We know that the mangled name of the type starts at index 4 of the
2627 // mangled name of the typename, so we can just index into it in order to
2628 // get the mangled name of the type.
2629 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2630 Name.substr(4));
2631
2632 llvm::GlobalVariable *GV =
2633 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
2634
2635 GV->setInitializer(Init);
2636
2637 return GV;
2638}
2639
2640llvm::Constant *
2641ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2642 // Mangle the RTTI name.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002643 SmallString<256> Name;
2644 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002645 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002646
2647 // Look for an existing global.
2648 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2649
2650 if (!GV) {
2651 // Create a new global variable.
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00002652 // Note for the future: If we would ever like to do deferred emission of
2653 // RTTI, check if emitting vtables opportunistically need any adjustment.
2654
David Majnemere2cb8d12014-07-07 06:20:47 +00002655 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2656 /*Constant=*/true,
2657 llvm::GlobalValue::ExternalLinkage, nullptr,
2658 Name);
Rafael Espindola3f727a82018-03-14 18:14:46 +00002659 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
2660 CGM.setGVProperties(GV, RD);
David Majnemere2cb8d12014-07-07 06:20:47 +00002661 }
2662
2663 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2664}
2665
2666/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2667/// info for that type is defined in the standard library.
2668static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2669 // Itanium C++ ABI 2.9.2:
2670 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
2671 // the run-time support library. Specifically, the run-time support
2672 // library should contain type_info objects for the types X, X* and
2673 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2674 // unsigned char, signed char, short, unsigned short, int, unsigned int,
2675 // long, unsigned long, long long, unsigned long long, float, double,
2676 // long double, char16_t, char32_t, and the IEEE 754r decimal and
2677 // half-precision floating point types.
Richard Smith4a382012016-02-03 01:32:42 +00002678 //
2679 // GCC also emits RTTI for __int128.
2680 // FIXME: We do not emit RTTI information for decimal types here.
2681
2682 // Types added here must also be added to EmitFundamentalRTTIDescriptors.
David Majnemere2cb8d12014-07-07 06:20:47 +00002683 switch (Ty->getKind()) {
2684 case BuiltinType::Void:
2685 case BuiltinType::NullPtr:
2686 case BuiltinType::Bool:
2687 case BuiltinType::WChar_S:
2688 case BuiltinType::WChar_U:
2689 case BuiltinType::Char_U:
2690 case BuiltinType::Char_S:
2691 case BuiltinType::UChar:
2692 case BuiltinType::SChar:
2693 case BuiltinType::Short:
2694 case BuiltinType::UShort:
2695 case BuiltinType::Int:
2696 case BuiltinType::UInt:
2697 case BuiltinType::Long:
2698 case BuiltinType::ULong:
2699 case BuiltinType::LongLong:
2700 case BuiltinType::ULongLong:
2701 case BuiltinType::Half:
2702 case BuiltinType::Float:
2703 case BuiltinType::Double:
2704 case BuiltinType::LongDouble:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00002705 case BuiltinType::Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002706 case BuiltinType::Float128:
Richard Smith3a8244d2018-05-01 05:02:45 +00002707 case BuiltinType::Char8:
David Majnemere2cb8d12014-07-07 06:20:47 +00002708 case BuiltinType::Char16:
2709 case BuiltinType::Char32:
2710 case BuiltinType::Int128:
2711 case BuiltinType::UInt128:
Richard Smith4a382012016-02-03 01:32:42 +00002712 return true;
2713
Alexey Bader954ba212016-04-08 13:40:33 +00002714#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2715 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00002716#include "clang/Basic/OpenCLImageTypes.def"
David Majnemere2cb8d12014-07-07 06:20:47 +00002717 case BuiltinType::OCLSampler:
2718 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002719 case BuiltinType::OCLClkEvent:
2720 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002721 case BuiltinType::OCLReserveID:
Richard Smith4a382012016-02-03 01:32:42 +00002722 return false;
David Majnemere2cb8d12014-07-07 06:20:47 +00002723
2724 case BuiltinType::Dependent:
2725#define BUILTIN_TYPE(Id, SingletonId)
2726#define PLACEHOLDER_TYPE(Id, SingletonId) \
2727 case BuiltinType::Id:
2728#include "clang/AST/BuiltinTypes.def"
2729 llvm_unreachable("asking for RRTI for a placeholder type!");
2730
2731 case BuiltinType::ObjCId:
2732 case BuiltinType::ObjCClass:
2733 case BuiltinType::ObjCSel:
2734 llvm_unreachable("FIXME: Objective-C types are unsupported!");
2735 }
2736
2737 llvm_unreachable("Invalid BuiltinType Kind!");
2738}
2739
2740static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2741 QualType PointeeTy = PointerTy->getPointeeType();
2742 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2743 if (!BuiltinTy)
2744 return false;
2745
2746 // Check the qualifiers.
2747 Qualifiers Quals = PointeeTy.getQualifiers();
2748 Quals.removeConst();
2749
2750 if (!Quals.empty())
2751 return false;
2752
2753 return TypeInfoIsInStandardLibrary(BuiltinTy);
2754}
2755
2756/// IsStandardLibraryRTTIDescriptor - Returns whether the type
2757/// information for the given type exists in the standard library.
2758static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2759 // Type info for builtin types is defined in the standard library.
2760 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2761 return TypeInfoIsInStandardLibrary(BuiltinTy);
2762
2763 // Type info for some pointer types to builtin types is defined in the
2764 // standard library.
2765 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2766 return TypeInfoIsInStandardLibrary(PointerTy);
2767
2768 return false;
2769}
2770
2771/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
2772/// the given type exists somewhere else, and that we should not emit the type
2773/// information in this translation unit. Assumes that it is not a
2774/// standard-library type.
2775static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
2776 QualType Ty) {
2777 ASTContext &Context = CGM.getContext();
2778
2779 // If RTTI is disabled, assume it might be disabled in the
2780 // translation unit that defines any potential key function, too.
2781 if (!Context.getLangOpts().RTTI) return false;
2782
2783 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2784 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2785 if (!RD->hasDefinition())
2786 return false;
2787
2788 if (!RD->isDynamicClass())
2789 return false;
2790
2791 // FIXME: this may need to be reconsidered if the key function
2792 // changes.
David Majnemerbe9022c2015-08-06 20:56:55 +00002793 // N.B. We must always emit the RTTI data ourselves if there exists a key
2794 // function.
2795 bool IsDLLImport = RD->hasAttr<DLLImportAttr>();
Martin Storsjo3b528942018-02-02 06:22:35 +00002796
2797 // Don't import the RTTI but emit it locally.
2798 if (CGM.getTriple().isWindowsGNUEnvironment() && IsDLLImport)
2799 return false;
2800
David Majnemer1fb1a042014-11-07 07:26:38 +00002801 if (CGM.getVTables().isVTableExternal(RD))
Shoaib Meenai61118e72017-07-04 01:02:19 +00002802 return IsDLLImport && !CGM.getTriple().isWindowsItaniumEnvironment()
2803 ? false
2804 : true;
David Majnemer1fb1a042014-11-07 07:26:38 +00002805
David Majnemerbe9022c2015-08-06 20:56:55 +00002806 if (IsDLLImport)
David Majnemer1fb1a042014-11-07 07:26:38 +00002807 return true;
David Majnemere2cb8d12014-07-07 06:20:47 +00002808 }
2809
2810 return false;
2811}
2812
2813/// IsIncompleteClassType - Returns whether the given record type is incomplete.
2814static bool IsIncompleteClassType(const RecordType *RecordTy) {
2815 return !RecordTy->getDecl()->isCompleteDefinition();
2816}
2817
2818/// ContainsIncompleteClassType - Returns whether the given type contains an
2819/// incomplete class type. This is true if
2820///
2821/// * The given type is an incomplete class type.
2822/// * The given type is a pointer type whose pointee type contains an
2823/// incomplete class type.
2824/// * The given type is a member pointer type whose class is an incomplete
2825/// class type.
2826/// * The given type is a member pointer type whoise pointee type contains an
2827/// incomplete class type.
2828/// is an indirect or direct pointer to an incomplete class type.
2829static bool ContainsIncompleteClassType(QualType Ty) {
2830 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2831 if (IsIncompleteClassType(RecordTy))
2832 return true;
2833 }
2834
2835 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2836 return ContainsIncompleteClassType(PointerTy->getPointeeType());
2837
2838 if (const MemberPointerType *MemberPointerTy =
2839 dyn_cast<MemberPointerType>(Ty)) {
2840 // Check if the class type is incomplete.
2841 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
2842 if (IsIncompleteClassType(ClassType))
2843 return true;
2844
2845 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
2846 }
2847
2848 return false;
2849}
2850
2851// CanUseSingleInheritance - Return whether the given record decl has a "single,
2852// public, non-virtual base at offset zero (i.e. the derived class is dynamic
2853// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
2854static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
2855 // Check the number of bases.
2856 if (RD->getNumBases() != 1)
2857 return false;
2858
2859 // Get the base.
2860 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
2861
2862 // Check that the base is not virtual.
2863 if (Base->isVirtual())
2864 return false;
2865
2866 // Check that the base is public.
2867 if (Base->getAccessSpecifier() != AS_public)
2868 return false;
2869
2870 // Check that the class is dynamic iff the base is.
2871 const CXXRecordDecl *BaseDecl =
2872 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2873 if (!BaseDecl->isEmpty() &&
2874 BaseDecl->isDynamicClass() != RD->isDynamicClass())
2875 return false;
2876
2877 return true;
2878}
2879
2880void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
2881 // abi::__class_type_info.
2882 static const char * const ClassTypeInfo =
2883 "_ZTVN10__cxxabiv117__class_type_infoE";
2884 // abi::__si_class_type_info.
2885 static const char * const SIClassTypeInfo =
2886 "_ZTVN10__cxxabiv120__si_class_type_infoE";
2887 // abi::__vmi_class_type_info.
2888 static const char * const VMIClassTypeInfo =
2889 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
2890
2891 const char *VTableName = nullptr;
2892
2893 switch (Ty->getTypeClass()) {
2894#define TYPE(Class, Base)
2895#define ABSTRACT_TYPE(Class, Base)
2896#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2897#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2898#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2899#include "clang/AST/TypeNodes.def"
2900 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2901
2902 case Type::LValueReference:
2903 case Type::RValueReference:
2904 llvm_unreachable("References shouldn't get here");
2905
2906 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00002907 case Type::DeducedTemplateSpecialization:
2908 llvm_unreachable("Undeduced type shouldn't get here");
David Majnemere2cb8d12014-07-07 06:20:47 +00002909
Xiuli Pan9c14e282016-01-09 12:53:17 +00002910 case Type::Pipe:
2911 llvm_unreachable("Pipe types shouldn't get here");
2912
David Majnemere2cb8d12014-07-07 06:20:47 +00002913 case Type::Builtin:
2914 // GCC treats vector and complex types as fundamental types.
2915 case Type::Vector:
2916 case Type::ExtVector:
2917 case Type::Complex:
2918 case Type::Atomic:
2919 // FIXME: GCC treats block pointers as fundamental types?!
2920 case Type::BlockPointer:
2921 // abi::__fundamental_type_info.
2922 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
2923 break;
2924
2925 case Type::ConstantArray:
2926 case Type::IncompleteArray:
2927 case Type::VariableArray:
2928 // abi::__array_type_info.
2929 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
2930 break;
2931
2932 case Type::FunctionNoProto:
2933 case Type::FunctionProto:
Richard Smithb17d6fa2016-12-01 03:04:07 +00002934 // abi::__function_type_info.
2935 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
David Majnemere2cb8d12014-07-07 06:20:47 +00002936 break;
2937
2938 case Type::Enum:
2939 // abi::__enum_type_info.
2940 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
2941 break;
2942
2943 case Type::Record: {
Rafael Espindolaf6688122018-03-22 21:14:16 +00002944 const CXXRecordDecl *RD =
2945 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
David Majnemere2cb8d12014-07-07 06:20:47 +00002946
2947 if (!RD->hasDefinition() || !RD->getNumBases()) {
2948 VTableName = ClassTypeInfo;
2949 } else if (CanUseSingleInheritance(RD)) {
2950 VTableName = SIClassTypeInfo;
2951 } else {
2952 VTableName = VMIClassTypeInfo;
2953 }
2954
2955 break;
2956 }
2957
2958 case Type::ObjCObject:
2959 // Ignore protocol qualifiers.
2960 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
2961
2962 // Handle id and Class.
2963 if (isa<BuiltinType>(Ty)) {
2964 VTableName = ClassTypeInfo;
2965 break;
2966 }
2967
2968 assert(isa<ObjCInterfaceType>(Ty));
2969 // Fall through.
2970
2971 case Type::ObjCInterface:
2972 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
2973 VTableName = SIClassTypeInfo;
2974 } else {
2975 VTableName = ClassTypeInfo;
2976 }
2977 break;
2978
2979 case Type::ObjCObjectPointer:
2980 case Type::Pointer:
2981 // abi::__pointer_type_info.
2982 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
2983 break;
2984
2985 case Type::MemberPointer:
2986 // abi::__pointer_to_member_type_info.
2987 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
2988 break;
2989 }
2990
2991 llvm::Constant *VTable =
2992 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
Rafael Espindolafe9a55a2018-03-23 01:36:23 +00002993 CGM.setDSOLocal(cast<llvm::GlobalValue>(VTable->stripPointerCasts()));
David Majnemere2cb8d12014-07-07 06:20:47 +00002994
2995 llvm::Type *PtrDiffTy =
2996 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
2997
2998 // The vtable address point is 2.
2999 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00003000 VTable =
3001 llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.Int8PtrTy, VTable, Two);
David Majnemere2cb8d12014-07-07 06:20:47 +00003002 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
3003
3004 Fields.push_back(VTable);
3005}
3006
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003007/// Return the linkage that the type info and type info name constants
David Majnemere2cb8d12014-07-07 06:20:47 +00003008/// should have for the given type.
Eric Fiselier85ba3322018-05-10 19:51:56 +00003009static std::pair<llvm::GlobalVariable::LinkageTypes,
3010 llvm::GlobalVariable::LinkageTypes>
3011getTypeInfoLinkage(CodeGenModule &CGM, QualType Ty) {
3012 llvm::GlobalValue::LinkageTypes TypeLinkage = [&]() {
3013 switch (Ty->getLinkage()) {
3014 case NoLinkage:
3015 case InternalLinkage:
3016 case UniqueExternalLinkage:
3017 return llvm::GlobalValue::InternalLinkage;
3018
3019 case VisibleNoLinkage:
3020 case ModuleInternalLinkage:
3021 case ModuleLinkage:
3022 case ExternalLinkage:
3023 // RTTI is not enabled, which means that this type info struct is going
3024 // to be used for exception handling. Give it linkonce_odr linkage.
3025 if (!CGM.getLangOpts().RTTI)
3026 return llvm::GlobalValue::LinkOnceODRLinkage;
3027
3028 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
3029 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
3030 if (RD->hasAttr<WeakAttr>())
3031 return llvm::GlobalValue::WeakODRLinkage;
3032 if (CGM.getTriple().isWindowsItaniumEnvironment())
3033 if (RD->hasAttr<DLLImportAttr>() &&
3034 ShouldUseExternalRTTIDescriptor(CGM, Ty))
3035 return llvm::GlobalValue::ExternalLinkage;
3036 // MinGW always uses LinkOnceODRLinkage for type info.
3037 if (RD->isCompleteDefinition() && RD->isDynamicClass() &&
3038 !CGM.getContext()
3039 .getTargetInfo()
3040 .getTriple()
3041 .isWindowsGNUEnvironment())
3042 return CGM.getVTableLinkage(RD);
3043 }
3044
3045 return llvm::GlobalValue::LinkOnceODRLinkage;
3046 }
3047 llvm_unreachable("Invalid linkage!");
3048 }();
David Majnemere2cb8d12014-07-07 06:20:47 +00003049 // Itanium C++ ABI 2.9.5p7:
3050 // In addition, it and all of the intermediate abi::__pointer_type_info
3051 // structs in the chain down to the abi::__class_type_info for the
3052 // incomplete class type must be prevented from resolving to the
3053 // corresponding type_info structs for the complete class type, possibly
3054 // by making them local static objects. Finally, a dummy class RTTI is
3055 // generated for the incomplete type that will not resolve to the final
3056 // complete class RTTI (because the latter need not exist), possibly by
3057 // making it a local static object.
3058 if (ContainsIncompleteClassType(Ty))
Eric Fiselier85ba3322018-05-10 19:51:56 +00003059 return {llvm::GlobalValue::InternalLinkage, TypeLinkage};
3060 return {TypeLinkage, TypeLinkage};
David Majnemere2cb8d12014-07-07 06:20:47 +00003061}
3062
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003063llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force,
3064 bool DLLExport) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003065 // We want to operate on the canonical type.
Yaron Kerenebd14262016-03-16 12:14:43 +00003066 Ty = Ty.getCanonicalType();
David Majnemere2cb8d12014-07-07 06:20:47 +00003067
3068 // Check if we've already emitted an RTTI descriptor for this type.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00003069 SmallString<256> Name;
3070 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00003071 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00003072
3073 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
3074 if (OldGV && !OldGV->isDeclaration()) {
3075 assert(!OldGV->hasAvailableExternallyLinkage() &&
3076 "available_externally typeinfos not yet implemented");
3077
3078 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
3079 }
3080
3081 // Check if there is already an external RTTI descriptor for this type.
3082 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
3083 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
3084 return GetAddrOfExternalRTTIDescriptor(Ty);
3085
3086 // Emit the standard library with external linkage.
Eric Fiselier85ba3322018-05-10 19:51:56 +00003087 llvm::GlobalVariable::LinkageTypes InfoLinkage, NameLinkage;
David Majnemere2cb8d12014-07-07 06:20:47 +00003088 if (IsStdLib)
Eric Fiselier85ba3322018-05-10 19:51:56 +00003089 InfoLinkage = NameLinkage = llvm::GlobalValue::ExternalLinkage;
3090 else {
3091 auto LinkagePair = getTypeInfoLinkage(CGM, Ty);
3092 InfoLinkage = LinkagePair.first;
3093 NameLinkage = LinkagePair.second;
3094 }
David Majnemere2cb8d12014-07-07 06:20:47 +00003095 // Add the vtable pointer.
3096 BuildVTablePointer(cast<Type>(Ty));
3097
3098 // And the name.
Eric Fiselier85ba3322018-05-10 19:51:56 +00003099 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, NameLinkage);
David Majnemere2cb8d12014-07-07 06:20:47 +00003100 llvm::Constant *TypeNameField;
3101
3102 // If we're supposed to demote the visibility, be sure to set a flag
3103 // to use a string comparison for type_info comparisons.
3104 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
Eric Fiselier85ba3322018-05-10 19:51:56 +00003105 CXXABI.classifyRTTIUniqueness(Ty, NameLinkage);
David Majnemere2cb8d12014-07-07 06:20:47 +00003106 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
3107 // The flag is the sign bit, which on ARM64 is defined to be clear
3108 // for global pointers. This is very ARM64-specific.
3109 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
3110 llvm::Constant *flag =
3111 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
3112 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
3113 TypeNameField =
3114 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
3115 } else {
3116 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
3117 }
3118 Fields.push_back(TypeNameField);
3119
3120 switch (Ty->getTypeClass()) {
3121#define TYPE(Class, Base)
3122#define ABSTRACT_TYPE(Class, Base)
3123#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3124#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3125#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3126#include "clang/AST/TypeNodes.def"
3127 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
3128
3129 // GCC treats vector types as fundamental types.
3130 case Type::Builtin:
3131 case Type::Vector:
3132 case Type::ExtVector:
3133 case Type::Complex:
3134 case Type::BlockPointer:
3135 // Itanium C++ ABI 2.9.5p4:
3136 // abi::__fundamental_type_info adds no data members to std::type_info.
3137 break;
3138
3139 case Type::LValueReference:
3140 case Type::RValueReference:
3141 llvm_unreachable("References shouldn't get here");
3142
3143 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00003144 case Type::DeducedTemplateSpecialization:
3145 llvm_unreachable("Undeduced type shouldn't get here");
David Majnemere2cb8d12014-07-07 06:20:47 +00003146
Xiuli Pan9c14e282016-01-09 12:53:17 +00003147 case Type::Pipe:
3148 llvm_unreachable("Pipe type shouldn't get here");
3149
David Majnemere2cb8d12014-07-07 06:20:47 +00003150 case Type::ConstantArray:
3151 case Type::IncompleteArray:
3152 case Type::VariableArray:
3153 // Itanium C++ ABI 2.9.5p5:
3154 // abi::__array_type_info adds no data members to std::type_info.
3155 break;
3156
3157 case Type::FunctionNoProto:
Richard Smithb17d6fa2016-12-01 03:04:07 +00003158 case Type::FunctionProto:
David Majnemere2cb8d12014-07-07 06:20:47 +00003159 // Itanium C++ ABI 2.9.5p5:
3160 // abi::__function_type_info adds no data members to std::type_info.
3161 break;
3162
3163 case Type::Enum:
3164 // Itanium C++ ABI 2.9.5p5:
3165 // abi::__enum_type_info adds no data members to std::type_info.
3166 break;
3167
3168 case Type::Record: {
3169 const CXXRecordDecl *RD =
3170 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
3171 if (!RD->hasDefinition() || !RD->getNumBases()) {
3172 // We don't need to emit any fields.
3173 break;
3174 }
3175
3176 if (CanUseSingleInheritance(RD))
3177 BuildSIClassTypeInfo(RD);
3178 else
3179 BuildVMIClassTypeInfo(RD);
3180
3181 break;
3182 }
3183
3184 case Type::ObjCObject:
3185 case Type::ObjCInterface:
3186 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
3187 break;
3188
3189 case Type::ObjCObjectPointer:
3190 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
3191 break;
3192
3193 case Type::Pointer:
3194 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
3195 break;
3196
3197 case Type::MemberPointer:
3198 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
3199 break;
3200
3201 case Type::Atomic:
3202 // No fields, at least for the moment.
3203 break;
3204 }
3205
3206 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
3207
Rafael Espindolacb92c192015-01-15 23:18:01 +00003208 llvm::Module &M = CGM.getModule();
David Majnemere2cb8d12014-07-07 06:20:47 +00003209 llvm::GlobalVariable *GV =
Rafael Espindolacb92c192015-01-15 23:18:01 +00003210 new llvm::GlobalVariable(M, Init->getType(),
Eric Fiselier85ba3322018-05-10 19:51:56 +00003211 /*Constant=*/true, InfoLinkage, Init, Name);
Rafael Espindolacb92c192015-01-15 23:18:01 +00003212
David Majnemere2cb8d12014-07-07 06:20:47 +00003213 // If there's already an old global variable, replace it with the new one.
3214 if (OldGV) {
3215 GV->takeName(OldGV);
3216 llvm::Constant *NewPtr =
3217 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3218 OldGV->replaceAllUsesWith(NewPtr);
3219 OldGV->eraseFromParent();
3220 }
3221
Yaron Keren04da2382015-07-29 15:42:28 +00003222 if (CGM.supportsCOMDAT() && GV->isWeakForLinker())
3223 GV->setComdat(M.getOrInsertComdat(GV->getName()));
3224
David Majnemere2cb8d12014-07-07 06:20:47 +00003225 // The Itanium ABI specifies that type_info objects must be globally
3226 // unique, with one exception: if the type is an incomplete class
3227 // type or a (possibly indirect) pointer to one. That exception
3228 // affects the general case of comparing type_info objects produced
3229 // by the typeid operator, which is why the comparison operators on
3230 // std::type_info generally use the type_info name pointers instead
3231 // of the object addresses. However, the language's built-in uses
3232 // of RTTI generally require class types to be complete, even when
3233 // manipulating pointers to those class types. This allows the
3234 // implementation of dynamic_cast to rely on address equality tests,
3235 // which is much faster.
3236
3237 // All of this is to say that it's important that both the type_info
3238 // object and the type_info name be uniqued when weakly emitted.
3239
3240 // Give the type_info object and name the formal visibility of the
3241 // type itself.
Eric Fiselier85ba3322018-05-10 19:51:56 +00003242 auto computeVisibility = [&](llvm::GlobalValue::LinkageTypes Linkage) {
3243 if (llvm::GlobalValue::isLocalLinkage(Linkage))
3244 // If the linkage is local, only default visibility makes sense.
3245 return llvm::GlobalValue::DefaultVisibility;
3246 else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden)
3247 return llvm::GlobalValue::HiddenVisibility;
3248 else
3249 return CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
3250 };
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003251
Eric Fiselier85ba3322018-05-10 19:51:56 +00003252 TypeName->setVisibility(computeVisibility(NameLinkage));
Rafael Espindola3dd49812018-02-23 00:22:15 +00003253 CGM.setDSOLocal(TypeName);
Rafael Espindola699f5d62018-02-07 22:15:33 +00003254
Eric Fiselier85ba3322018-05-10 19:51:56 +00003255 GV->setVisibility(computeVisibility(InfoLinkage));
Rafael Espindola3dd49812018-02-23 00:22:15 +00003256 CGM.setDSOLocal(GV);
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003257
3258 if (CGM.getTriple().isWindowsItaniumEnvironment()) {
3259 auto RD = Ty->getAsCXXRecordDecl();
3260 if (DLLExport || (RD && RD->hasAttr<DLLExportAttr>())) {
3261 TypeName->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
3262 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
Shoaib Meenai61118e72017-07-04 01:02:19 +00003263 } else if (RD && RD->hasAttr<DLLImportAttr>() &&
3264 ShouldUseExternalRTTIDescriptor(CGM, Ty)) {
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003265 TypeName->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3266 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3267
3268 // Because the typename and the typeinfo are DLL import, convert them to
3269 // declarations rather than definitions. The initializers still need to
3270 // be constructed to calculate the type for the declarations.
3271 TypeName->setInitializer(nullptr);
3272 GV->setInitializer(nullptr);
3273 }
3274 }
David Majnemere2cb8d12014-07-07 06:20:47 +00003275
3276 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
3277}
3278
David Majnemere2cb8d12014-07-07 06:20:47 +00003279/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
3280/// for the given Objective-C object type.
3281void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
3282 // Drop qualifiers.
3283 const Type *T = OT->getBaseType().getTypePtr();
3284 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
3285
3286 // The builtin types are abi::__class_type_infos and don't require
3287 // extra fields.
3288 if (isa<BuiltinType>(T)) return;
3289
3290 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
3291 ObjCInterfaceDecl *Super = Class->getSuperClass();
3292
3293 // Root classes are also __class_type_info.
3294 if (!Super) return;
3295
3296 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
3297
3298 // Everything else is single inheritance.
3299 llvm::Constant *BaseTypeInfo =
3300 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
3301 Fields.push_back(BaseTypeInfo);
3302}
3303
3304/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
3305/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
3306void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
3307 // Itanium C++ ABI 2.9.5p6b:
3308 // It adds to abi::__class_type_info a single member pointing to the
3309 // type_info structure for the base type,
3310 llvm::Constant *BaseTypeInfo =
3311 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
3312 Fields.push_back(BaseTypeInfo);
3313}
3314
3315namespace {
3316 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
3317 /// a class hierarchy.
3318 struct SeenBases {
3319 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
3320 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
3321 };
3322}
3323
3324/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
3325/// abi::__vmi_class_type_info.
3326///
3327static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
3328 SeenBases &Bases) {
3329
3330 unsigned Flags = 0;
3331
3332 const CXXRecordDecl *BaseDecl =
3333 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
3334
3335 if (Base->isVirtual()) {
3336 // Mark the virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003337 if (!Bases.VirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003338 // If this virtual base has been seen before, then the class is diamond
3339 // shaped.
3340 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
3341 } else {
3342 if (Bases.NonVirtualBases.count(BaseDecl))
3343 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3344 }
3345 } else {
3346 // Mark the non-virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003347 if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003348 // If this non-virtual base has been seen before, then the class has non-
3349 // diamond shaped repeated inheritance.
3350 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3351 } else {
3352 if (Bases.VirtualBases.count(BaseDecl))
3353 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3354 }
3355 }
3356
3357 // Walk all bases.
3358 for (const auto &I : BaseDecl->bases())
3359 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3360
3361 return Flags;
3362}
3363
3364static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
3365 unsigned Flags = 0;
3366 SeenBases Bases;
3367
3368 // Walk all bases.
3369 for (const auto &I : RD->bases())
3370 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3371
3372 return Flags;
3373}
3374
3375/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
3376/// classes with bases that do not satisfy the abi::__si_class_type_info
3377/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
3378void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
3379 llvm::Type *UnsignedIntLTy =
3380 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3381
3382 // Itanium C++ ABI 2.9.5p6c:
3383 // __flags is a word with flags describing details about the class
3384 // structure, which may be referenced by using the __flags_masks
3385 // enumeration. These flags refer to both direct and indirect bases.
3386 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
3387 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3388
3389 // Itanium C++ ABI 2.9.5p6c:
3390 // __base_count is a word with the number of direct proper base class
3391 // descriptions that follow.
3392 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
3393
3394 if (!RD->getNumBases())
3395 return;
3396
David Majnemere2cb8d12014-07-07 06:20:47 +00003397 // Now add the base class descriptions.
3398
3399 // Itanium C++ ABI 2.9.5p6c:
3400 // __base_info[] is an array of base class descriptions -- one for every
3401 // direct proper base. Each description is of the type:
3402 //
3403 // struct abi::__base_class_type_info {
3404 // public:
3405 // const __class_type_info *__base_type;
3406 // long __offset_flags;
3407 //
3408 // enum __offset_flags_masks {
3409 // __virtual_mask = 0x1,
3410 // __public_mask = 0x2,
3411 // __offset_shift = 8
3412 // };
3413 // };
Reid Klecknerd8b04662016-08-25 22:16:30 +00003414
3415 // If we're in mingw and 'long' isn't wide enough for a pointer, use 'long
3416 // long' instead of 'long' for __offset_flags. libstdc++abi uses long long on
3417 // LLP64 platforms.
3418 // FIXME: Consider updating libc++abi to match, and extend this logic to all
3419 // LLP64 platforms.
3420 QualType OffsetFlagsTy = CGM.getContext().LongTy;
3421 const TargetInfo &TI = CGM.getContext().getTargetInfo();
3422 if (TI.getTriple().isOSCygMing() && TI.getPointerWidth(0) > TI.getLongWidth())
3423 OffsetFlagsTy = CGM.getContext().LongLongTy;
3424 llvm::Type *OffsetFlagsLTy =
3425 CGM.getTypes().ConvertType(OffsetFlagsTy);
3426
David Majnemere2cb8d12014-07-07 06:20:47 +00003427 for (const auto &Base : RD->bases()) {
3428 // The __base_type member points to the RTTI for the base type.
3429 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
3430
3431 const CXXRecordDecl *BaseDecl =
3432 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
3433
3434 int64_t OffsetFlags = 0;
3435
3436 // All but the lower 8 bits of __offset_flags are a signed offset.
3437 // For a non-virtual base, this is the offset in the object of the base
3438 // subobject. For a virtual base, this is the offset in the virtual table of
3439 // the virtual base offset for the virtual base referenced (negative).
3440 CharUnits Offset;
3441 if (Base.isVirtual())
3442 Offset =
3443 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
3444 else {
3445 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
3446 Offset = Layout.getBaseClassOffset(BaseDecl);
3447 };
3448
3449 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
3450
3451 // The low-order byte of __offset_flags contains flags, as given by the
3452 // masks from the enumeration __offset_flags_masks.
3453 if (Base.isVirtual())
3454 OffsetFlags |= BCTI_Virtual;
3455 if (Base.getAccessSpecifier() == AS_public)
3456 OffsetFlags |= BCTI_Public;
3457
Reid Klecknerd8b04662016-08-25 22:16:30 +00003458 Fields.push_back(llvm::ConstantInt::get(OffsetFlagsLTy, OffsetFlags));
David Majnemere2cb8d12014-07-07 06:20:47 +00003459 }
3460}
3461
Richard Smitha7d93782016-12-01 03:32:42 +00003462/// Compute the flags for a __pbase_type_info, and remove the corresponding
3463/// pieces from \p Type.
3464static unsigned extractPBaseFlags(ASTContext &Ctx, QualType &Type) {
3465 unsigned Flags = 0;
David Majnemere2cb8d12014-07-07 06:20:47 +00003466
Richard Smitha7d93782016-12-01 03:32:42 +00003467 if (Type.isConstQualified())
3468 Flags |= ItaniumRTTIBuilder::PTI_Const;
3469 if (Type.isVolatileQualified())
3470 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
3471 if (Type.isRestrictQualified())
3472 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
3473 Type = Type.getUnqualifiedType();
David Majnemere2cb8d12014-07-07 06:20:47 +00003474
3475 // Itanium C++ ABI 2.9.5p7:
3476 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3477 // incomplete class type, the incomplete target type flag is set.
Richard Smitha7d93782016-12-01 03:32:42 +00003478 if (ContainsIncompleteClassType(Type))
3479 Flags |= ItaniumRTTIBuilder::PTI_Incomplete;
3480
3481 if (auto *Proto = Type->getAs<FunctionProtoType>()) {
Richard Smitheaf11ad2018-05-03 03:58:32 +00003482 if (Proto->isNothrow()) {
Richard Smitha7d93782016-12-01 03:32:42 +00003483 Flags |= ItaniumRTTIBuilder::PTI_Noexcept;
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00003484 Type = Ctx.getFunctionTypeWithExceptionSpec(Type, EST_None);
Richard Smitha7d93782016-12-01 03:32:42 +00003485 }
3486 }
3487
3488 return Flags;
3489}
3490
3491/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
3492/// used for pointer types.
3493void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
3494 // Itanium C++ ABI 2.9.5p7:
3495 // __flags is a flag word describing the cv-qualification and other
3496 // attributes of the type pointed to
3497 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003498
3499 llvm::Type *UnsignedIntLTy =
3500 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3501 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3502
3503 // Itanium C++ ABI 2.9.5p7:
3504 // __pointee is a pointer to the std::type_info derivation for the
3505 // unqualified type being pointed to.
3506 llvm::Constant *PointeeTypeInfo =
Richard Smitha7d93782016-12-01 03:32:42 +00003507 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003508 Fields.push_back(PointeeTypeInfo);
3509}
3510
3511/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
3512/// struct, used for member pointer types.
3513void
3514ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
3515 QualType PointeeTy = Ty->getPointeeType();
3516
David Majnemere2cb8d12014-07-07 06:20:47 +00003517 // Itanium C++ ABI 2.9.5p7:
3518 // __flags is a flag word describing the cv-qualification and other
3519 // attributes of the type pointed to.
Richard Smitha7d93782016-12-01 03:32:42 +00003520 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003521
3522 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
David Majnemere2cb8d12014-07-07 06:20:47 +00003523 if (IsIncompleteClassType(ClassType))
3524 Flags |= PTI_ContainingClassIncomplete;
3525
3526 llvm::Type *UnsignedIntLTy =
3527 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3528 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3529
3530 // Itanium C++ ABI 2.9.5p7:
3531 // __pointee is a pointer to the std::type_info derivation for the
3532 // unqualified type being pointed to.
3533 llvm::Constant *PointeeTypeInfo =
Richard Smitha7d93782016-12-01 03:32:42 +00003534 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003535 Fields.push_back(PointeeTypeInfo);
3536
3537 // Itanium C++ ABI 2.9.5p9:
3538 // __context is a pointer to an abi::__class_type_info corresponding to the
3539 // class type containing the member pointed to
3540 // (e.g., the "A" in "int A::*").
3541 Fields.push_back(
3542 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
3543}
3544
David Majnemer443250f2015-03-17 20:35:00 +00003545llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003546 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
3547}
3548
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003549void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type,
3550 bool DLLExport) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003551 QualType PointerType = getContext().getPointerType(Type);
3552 QualType PointerTypeConst = getContext().getPointerType(Type.withConst());
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003553 ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, /*Force=*/true, DLLExport);
3554 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, /*Force=*/true,
3555 DLLExport);
3556 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, /*Force=*/true,
3557 DLLExport);
David Majnemere2cb8d12014-07-07 06:20:47 +00003558}
3559
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003560void ItaniumCXXABI::EmitFundamentalRTTIDescriptors(bool DLLExport) {
Richard Smith4a382012016-02-03 01:32:42 +00003561 // Types added here must also be added to TypeInfoIsInStandardLibrary.
David Majnemere2cb8d12014-07-07 06:20:47 +00003562 QualType FundamentalTypes[] = {
3563 getContext().VoidTy, getContext().NullPtrTy,
3564 getContext().BoolTy, getContext().WCharTy,
3565 getContext().CharTy, getContext().UnsignedCharTy,
3566 getContext().SignedCharTy, getContext().ShortTy,
3567 getContext().UnsignedShortTy, getContext().IntTy,
3568 getContext().UnsignedIntTy, getContext().LongTy,
3569 getContext().UnsignedLongTy, getContext().LongLongTy,
Richard Smith4a382012016-02-03 01:32:42 +00003570 getContext().UnsignedLongLongTy, getContext().Int128Ty,
3571 getContext().UnsignedInt128Ty, getContext().HalfTy,
David Majnemere2cb8d12014-07-07 06:20:47 +00003572 getContext().FloatTy, getContext().DoubleTy,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00003573 getContext().LongDoubleTy, getContext().Float128Ty,
Richard Smith3a8244d2018-05-01 05:02:45 +00003574 getContext().Char8Ty, getContext().Char16Ty,
3575 getContext().Char32Ty
David Majnemere2cb8d12014-07-07 06:20:47 +00003576 };
3577 for (const QualType &FundamentalType : FundamentalTypes)
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003578 EmitFundamentalRTTIDescriptor(FundamentalType, DLLExport);
David Majnemere2cb8d12014-07-07 06:20:47 +00003579}
3580
3581/// What sort of uniqueness rules should we use for the RTTI for the
3582/// given type?
3583ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
3584 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
3585 if (shouldRTTIBeUnique())
3586 return RUK_Unique;
3587
3588 // It's only necessary for linkonce_odr or weak_odr linkage.
3589 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
3590 Linkage != llvm::GlobalValue::WeakODRLinkage)
3591 return RUK_Unique;
3592
3593 // It's only necessary with default visibility.
3594 if (CanTy->getVisibility() != DefaultVisibility)
3595 return RUK_Unique;
3596
3597 // If we're not required to publish this symbol, hide it.
3598 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3599 return RUK_NonUniqueHidden;
3600
3601 // If we're required to publish this symbol, as we might be under an
3602 // explicit instantiation, leave it with default visibility but
3603 // enable string-comparisons.
3604 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
3605 return RUK_NonUniqueVisible;
3606}
Rafael Espindola91f68b42014-09-15 19:20:10 +00003607
Rafael Espindola1e4df922014-09-16 15:18:21 +00003608// Find out how to codegen the complete destructor and constructor
3609namespace {
3610enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
3611}
3612static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
3613 const CXXMethodDecl *MD) {
3614 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
3615 return StructorCodegen::Emit;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003616
Rafael Espindola1e4df922014-09-16 15:18:21 +00003617 // The complete and base structors are not equivalent if there are any virtual
3618 // bases, so emit separate functions.
3619 if (MD->getParent()->getNumVBases())
3620 return StructorCodegen::Emit;
3621
3622 GlobalDecl AliasDecl;
3623 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3624 AliasDecl = GlobalDecl(DD, Dtor_Complete);
3625 } else {
3626 const auto *CD = cast<CXXConstructorDecl>(MD);
3627 AliasDecl = GlobalDecl(CD, Ctor_Complete);
3628 }
3629 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3630
Pavel Labathb3b02552018-05-21 11:47:45 +00003631 // All discardable structors can be RAUWed, but we don't want to do that in
3632 // unoptimized code, as that makes complete structor symbol disappear
3633 // completely, which degrades debugging experience.
3634 // Symbols with private linkage can be safely aliased, so we special case them
3635 // here.
3636 if (llvm::GlobalValue::isLocalLinkage(Linkage))
3637 return CGM.getCodeGenOpts().OptimizationLevel > 0 ? StructorCodegen::RAUW
3638 : StructorCodegen::Alias;
Rafael Espindola1e4df922014-09-16 15:18:21 +00003639
Pavel Labathb3b02552018-05-21 11:47:45 +00003640 // Linkonce structors cannot be aliased nor placed in a comdat, so these need
3641 // to be emitted separately.
Pavel Labathc370f262018-05-14 11:35:44 +00003642 // FIXME: Should we allow available_externally aliases?
Pavel Labathb3b02552018-05-21 11:47:45 +00003643 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage) ||
3644 !llvm::GlobalAlias::isValidLinkage(Linkage))
3645 return CGM.getCodeGenOpts().OptimizationLevel > 0 ? StructorCodegen::RAUW
3646 : StructorCodegen::Emit;
Rafael Espindola1e4df922014-09-16 15:18:21 +00003647
Rafael Espindola0806f982014-09-16 20:19:43 +00003648 if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
Dan Gohman839f2152017-01-17 21:46:38 +00003649 // Only ELF and wasm support COMDATs with arbitrary names (C5/D5).
3650 if (CGM.getTarget().getTriple().isOSBinFormatELF() ||
3651 CGM.getTarget().getTriple().isOSBinFormatWasm())
Rafael Espindola0806f982014-09-16 20:19:43 +00003652 return StructorCodegen::COMDAT;
3653 return StructorCodegen::Emit;
3654 }
Rafael Espindola1e4df922014-09-16 15:18:21 +00003655
3656 return StructorCodegen::Alias;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003657}
3658
Rafael Espindola1e4df922014-09-16 15:18:21 +00003659static void emitConstructorDestructorAlias(CodeGenModule &CGM,
3660 GlobalDecl AliasDecl,
3661 GlobalDecl TargetDecl) {
3662 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3663
3664 StringRef MangledName = CGM.getMangledName(AliasDecl);
3665 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
3666 if (Entry && !Entry->isDeclaration())
3667 return;
3668
3669 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
Rafael Espindola1e4df922014-09-16 15:18:21 +00003670
3671 // Create the alias with no name.
David Blaikie2a791d72015-09-14 18:38:22 +00003672 auto *Alias = llvm::GlobalAlias::create(Linkage, "", Aliasee);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003673
3674 // Switch any previous uses to the alias.
3675 if (Entry) {
NAKAMURA Takumie9621042015-09-15 01:39:27 +00003676 assert(Entry->getType() == Aliasee->getType() &&
Rafael Espindola1e4df922014-09-16 15:18:21 +00003677 "declaration exists with different type");
3678 Alias->takeName(Entry);
3679 Entry->replaceAllUsesWith(Alias);
3680 Entry->eraseFromParent();
3681 } else {
3682 Alias->setName(MangledName);
3683 }
3684
3685 // Finally, set up the alias with its proper name and attributes.
Rafael Espindolab7350042018-03-01 00:35:47 +00003686 CGM.SetCommonAttributes(AliasDecl, Alias);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003687}
3688
3689void ItaniumCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
3690 StructorType Type) {
3691 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
3692 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
3693
3694 StructorCodegen CGType = getCodegenToUse(CGM, MD);
3695
3696 if (Type == StructorType::Complete) {
3697 GlobalDecl CompleteDecl;
3698 GlobalDecl BaseDecl;
3699 if (CD) {
3700 CompleteDecl = GlobalDecl(CD, Ctor_Complete);
3701 BaseDecl = GlobalDecl(CD, Ctor_Base);
3702 } else {
3703 CompleteDecl = GlobalDecl(DD, Dtor_Complete);
3704 BaseDecl = GlobalDecl(DD, Dtor_Base);
3705 }
3706
3707 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
3708 emitConstructorDestructorAlias(CGM, CompleteDecl, BaseDecl);
3709 return;
3710 }
3711
3712 if (CGType == StructorCodegen::RAUW) {
3713 StringRef MangledName = CGM.getMangledName(CompleteDecl);
Andrey Bokhankocab58582015-08-31 13:20:44 +00003714 auto *Aliasee = CGM.GetAddrOfGlobal(BaseDecl);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003715 CGM.addReplacement(MangledName, Aliasee);
3716 return;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003717 }
3718 }
3719
3720 // The base destructor is equivalent to the base destructor of its
3721 // base class if there is exactly one non-virtual base class with a
3722 // non-trivial destructor, there are no fields with a non-trivial
3723 // destructor, and the body of the destructor is trivial.
Rafael Espindola1e4df922014-09-16 15:18:21 +00003724 if (DD && Type == StructorType::Base && CGType != StructorCodegen::COMDAT &&
3725 !CGM.TryEmitBaseDestructorAsAlias(DD))
Rafael Espindola91f68b42014-09-15 19:20:10 +00003726 return;
3727
Richard Smith5b349582017-10-13 01:55:36 +00003728 // FIXME: The deleting destructor is equivalent to the selected operator
3729 // delete if:
3730 // * either the delete is a destroying operator delete or the destructor
3731 // would be trivial if it weren't virtual,
3732 // * the conversion from the 'this' parameter to the first parameter of the
3733 // destructor is equivalent to a bitcast,
3734 // * the destructor does not have an implicit "this" return, and
3735 // * the operator delete has the same calling convention and IR function type
3736 // as the destructor.
3737 // In such cases we should try to emit the deleting dtor as an alias to the
3738 // selected 'operator delete'.
3739
Rafael Espindola1e4df922014-09-16 15:18:21 +00003740 llvm::Function *Fn = CGM.codegenCXXStructor(MD, Type);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003741
Rafael Espindola1e4df922014-09-16 15:18:21 +00003742 if (CGType == StructorCodegen::COMDAT) {
3743 SmallString<256> Buffer;
3744 llvm::raw_svector_ostream Out(Buffer);
3745 if (DD)
3746 getMangleContext().mangleCXXDtorComdat(DD, Out);
3747 else
3748 getMangleContext().mangleCXXCtorComdat(CD, Out);
3749 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
3750 Fn->setComdat(C);
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003751 } else {
3752 CGM.maybeSetTrivialComdat(*MD, *Fn);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003753 }
Rafael Espindola91f68b42014-09-15 19:20:10 +00003754}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003755
3756static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) {
3757 // void *__cxa_begin_catch(void*);
3758 llvm::FunctionType *FTy = llvm::FunctionType::get(
3759 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3760
3761 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
3762}
3763
3764static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) {
3765 // void __cxa_end_catch();
3766 llvm::FunctionType *FTy =
3767 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
3768
3769 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
3770}
3771
3772static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) {
3773 // void *__cxa_get_exception_ptr(void*);
3774 llvm::FunctionType *FTy = llvm::FunctionType::get(
3775 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3776
3777 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
3778}
3779
3780namespace {
3781 /// A cleanup to call __cxa_end_catch. In many cases, the caught
3782 /// exception type lets us state definitively that the thrown exception
3783 /// type does not have a destructor. In particular:
3784 /// - Catch-alls tell us nothing, so we have to conservatively
3785 /// assume that the thrown exception might have a destructor.
3786 /// - Catches by reference behave according to their base types.
3787 /// - Catches of non-record types will only trigger for exceptions
3788 /// of non-record types, which never have destructors.
3789 /// - Catches of record types can trigger for arbitrary subclasses
3790 /// of the caught type, so we have to assume the actual thrown
3791 /// exception type might have a throwing destructor, even if the
3792 /// caught type's destructor is trivial or nothrow.
David Blaikie7e70d682015-08-18 22:40:54 +00003793 struct CallEndCatch final : EHScopeStack::Cleanup {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003794 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
3795 bool MightThrow;
3796
3797 void Emit(CodeGenFunction &CGF, Flags flags) override {
3798 if (!MightThrow) {
3799 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
3800 return;
3801 }
3802
3803 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
3804 }
3805 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003806}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003807
3808/// Emits a call to __cxa_begin_catch and enters a cleanup to call
3809/// __cxa_end_catch.
3810///
3811/// \param EndMightThrow - true if __cxa_end_catch might throw
3812static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
3813 llvm::Value *Exn,
3814 bool EndMightThrow) {
3815 llvm::CallInst *call =
3816 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
3817
3818 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
3819
3820 return call;
3821}
3822
3823/// A "special initializer" callback for initializing a catch
3824/// parameter during catch initialization.
3825static void InitCatchParam(CodeGenFunction &CGF,
3826 const VarDecl &CatchParam,
John McCall7f416cc2015-09-08 08:05:57 +00003827 Address ParamAddr,
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003828 SourceLocation Loc) {
3829 // Load the exception from where the landing pad saved it.
3830 llvm::Value *Exn = CGF.getExceptionFromSlot();
3831
3832 CanQualType CatchType =
3833 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
3834 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
3835
3836 // If we're catching by reference, we can just cast the object
3837 // pointer to the appropriate pointer.
3838 if (isa<ReferenceType>(CatchType)) {
3839 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
3840 bool EndCatchMightThrow = CaughtType->isRecordType();
3841
3842 // __cxa_begin_catch returns the adjusted object pointer.
3843 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
3844
3845 // We have no way to tell the personality function that we're
3846 // catching by reference, so if we're catching a pointer,
3847 // __cxa_begin_catch will actually return that pointer by value.
3848 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
3849 QualType PointeeType = PT->getPointeeType();
3850
3851 // When catching by reference, generally we should just ignore
3852 // this by-value pointer and use the exception object instead.
3853 if (!PointeeType->isRecordType()) {
3854
3855 // Exn points to the struct _Unwind_Exception header, which
3856 // we have to skip past in order to reach the exception data.
3857 unsigned HeaderSize =
3858 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
3859 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
3860
3861 // However, if we're catching a pointer-to-record type that won't
3862 // work, because the personality function might have adjusted
3863 // the pointer. There's actually no way for us to fully satisfy
3864 // the language/ABI contract here: we can't use Exn because it
3865 // might have the wrong adjustment, but we can't use the by-value
3866 // pointer because it's off by a level of abstraction.
3867 //
3868 // The current solution is to dump the adjusted pointer into an
3869 // alloca, which breaks language semantics (because changing the
3870 // pointer doesn't change the exception) but at least works.
3871 // The better solution would be to filter out non-exact matches
3872 // and rethrow them, but this is tricky because the rethrow
3873 // really needs to be catchable by other sites at this landing
3874 // pad. The best solution is to fix the personality function.
3875 } else {
3876 // Pull the pointer for the reference type off.
3877 llvm::Type *PtrTy =
3878 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
3879
3880 // Create the temporary and write the adjusted pointer into it.
John McCall7f416cc2015-09-08 08:05:57 +00003881 Address ExnPtrTmp =
3882 CGF.CreateTempAlloca(PtrTy, CGF.getPointerAlign(), "exn.byref.tmp");
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003883 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3884 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
3885
3886 // Bind the reference to the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00003887 AdjustedExn = ExnPtrTmp.getPointer();
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003888 }
3889 }
3890
3891 llvm::Value *ExnCast =
3892 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
3893 CGF.Builder.CreateStore(ExnCast, ParamAddr);
3894 return;
3895 }
3896
3897 // Scalars and complexes.
3898 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
3899 if (TEK != TEK_Aggregate) {
3900 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
3901
3902 // If the catch type is a pointer type, __cxa_begin_catch returns
3903 // the pointer by value.
3904 if (CatchType->hasPointerRepresentation()) {
3905 llvm::Value *CastExn =
3906 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
3907
3908 switch (CatchType.getQualifiers().getObjCLifetime()) {
3909 case Qualifiers::OCL_Strong:
3910 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
3911 // fallthrough
3912
3913 case Qualifiers::OCL_None:
3914 case Qualifiers::OCL_ExplicitNone:
3915 case Qualifiers::OCL_Autoreleasing:
3916 CGF.Builder.CreateStore(CastExn, ParamAddr);
3917 return;
3918
3919 case Qualifiers::OCL_Weak:
3920 CGF.EmitARCInitWeak(ParamAddr, CastExn);
3921 return;
3922 }
3923 llvm_unreachable("bad ownership qualifier!");
3924 }
3925
3926 // Otherwise, it returns a pointer into the exception object.
3927
3928 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3929 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3930
3931 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
John McCall7f416cc2015-09-08 08:05:57 +00003932 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003933 switch (TEK) {
3934 case TEK_Complex:
3935 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
3936 /*init*/ true);
3937 return;
3938 case TEK_Scalar: {
3939 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
3940 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
3941 return;
3942 }
3943 case TEK_Aggregate:
3944 llvm_unreachable("evaluation kind filtered out!");
3945 }
3946 llvm_unreachable("bad evaluation kind");
3947 }
3948
3949 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
John McCall7f416cc2015-09-08 08:05:57 +00003950 auto catchRD = CatchType->getAsCXXRecordDecl();
3951 CharUnits caughtExnAlignment = CGF.CGM.getClassPointerAlignment(catchRD);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003952
3953 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3954
3955 // Check for a copy expression. If we don't have a copy expression,
3956 // that means a trivial copy is okay.
3957 const Expr *copyExpr = CatchParam.getInit();
3958 if (!copyExpr) {
3959 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
John McCall7f416cc2015-09-08 08:05:57 +00003960 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3961 caughtExnAlignment);
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00003962 LValue Dest = CGF.MakeAddrLValue(ParamAddr, CatchType);
3963 LValue Src = CGF.MakeAddrLValue(adjustedExn, CatchType);
Richard Smithe78fac52018-04-05 20:52:58 +00003964 CGF.EmitAggregateCopy(Dest, Src, CatchType, AggValueSlot::DoesNotOverlap);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003965 return;
3966 }
3967
3968 // We have to call __cxa_get_exception_ptr to get the adjusted
3969 // pointer before copying.
3970 llvm::CallInst *rawAdjustedExn =
3971 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
3972
3973 // Cast that to the appropriate type.
John McCall7f416cc2015-09-08 08:05:57 +00003974 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3975 caughtExnAlignment);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003976
3977 // The copy expression is defined in terms of an OpaqueValueExpr.
3978 // Find it and map it to the adjusted expression.
3979 CodeGenFunction::OpaqueValueMapping
3980 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
3981 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
3982
3983 // Call the copy ctor in a terminate scope.
3984 CGF.EHStack.pushTerminate();
3985
3986 // Perform the copy construction.
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003987 CGF.EmitAggExpr(copyExpr,
John McCall7f416cc2015-09-08 08:05:57 +00003988 AggValueSlot::forAddr(ParamAddr, Qualifiers(),
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003989 AggValueSlot::IsNotDestructed,
3990 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00003991 AggValueSlot::IsNotAliased,
3992 AggValueSlot::DoesNotOverlap));
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003993
3994 // Leave the terminate scope.
3995 CGF.EHStack.popTerminate();
3996
3997 // Undo the opaque value mapping.
3998 opaque.pop();
3999
4000 // Finally we can call __cxa_begin_catch.
4001 CallBeginCatch(CGF, Exn, true);
4002}
4003
4004/// Begins a catch statement by initializing the catch variable and
4005/// calling __cxa_begin_catch.
4006void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF,
4007 const CXXCatchStmt *S) {
4008 // We have to be very careful with the ordering of cleanups here:
4009 // C++ [except.throw]p4:
4010 // The destruction [of the exception temporary] occurs
4011 // immediately after the destruction of the object declared in
4012 // the exception-declaration in the handler.
4013 //
4014 // So the precise ordering is:
4015 // 1. Construct catch variable.
4016 // 2. __cxa_begin_catch
4017 // 3. Enter __cxa_end_catch cleanup
4018 // 4. Enter dtor cleanup
4019 //
4020 // We do this by using a slightly abnormal initialization process.
4021 // Delegation sequence:
4022 // - ExitCXXTryStmt opens a RunCleanupsScope
4023 // - EmitAutoVarAlloca creates the variable and debug info
4024 // - InitCatchParam initializes the variable from the exception
4025 // - CallBeginCatch calls __cxa_begin_catch
4026 // - CallBeginCatch enters the __cxa_end_catch cleanup
4027 // - EmitAutoVarCleanups enters the variable destructor cleanup
4028 // - EmitCXXTryStmt emits the code for the catch body
4029 // - EmitCXXTryStmt close the RunCleanupsScope
4030
4031 VarDecl *CatchParam = S->getExceptionDecl();
4032 if (!CatchParam) {
4033 llvm::Value *Exn = CGF.getExceptionFromSlot();
4034 CallBeginCatch(CGF, Exn, true);
4035 return;
4036 }
4037
4038 // Emit the local.
4039 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
4040 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
4041 CGF.EmitAutoVarCleanups(var);
4042}
4043
4044/// Get or define the following function:
4045/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
4046/// This code is used only in C++.
4047static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
4048 llvm::FunctionType *fnTy =
4049 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00004050 llvm::Constant *fnRef = CGM.CreateRuntimeFunction(
4051 fnTy, "__clang_call_terminate", llvm::AttributeList(), /*Local=*/true);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004052
4053 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
4054 if (fn && fn->empty()) {
4055 fn->setDoesNotThrow();
4056 fn->setDoesNotReturn();
4057
4058 // What we really want is to massively penalize inlining without
4059 // forbidding it completely. The difference between that and
4060 // 'noinline' is negligible.
4061 fn->addFnAttr(llvm::Attribute::NoInline);
4062
4063 // Allow this function to be shared across translation units, but
4064 // we don't want it to turn into an exported symbol.
4065 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
4066 fn->setVisibility(llvm::Function::HiddenVisibility);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00004067 if (CGM.supportsCOMDAT())
4068 fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004069
4070 // Set up the function.
4071 llvm::BasicBlock *entry =
4072 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
John McCall7f416cc2015-09-08 08:05:57 +00004073 CGBuilderTy builder(CGM, entry);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004074
4075 // Pull the exception pointer out of the parameter list.
4076 llvm::Value *exn = &*fn->arg_begin();
4077
4078 // Call __cxa_begin_catch(exn).
4079 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
4080 catchCall->setDoesNotThrow();
4081 catchCall->setCallingConv(CGM.getRuntimeCC());
4082
4083 // Call std::terminate().
David Blaikie4ba525b2015-07-14 17:27:39 +00004084 llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn());
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004085 termCall->setDoesNotThrow();
4086 termCall->setDoesNotReturn();
4087 termCall->setCallingConv(CGM.getRuntimeCC());
4088
4089 // std::terminate cannot return.
4090 builder.CreateUnreachable();
4091 }
4092
4093 return fnRef;
4094}
4095
4096llvm::CallInst *
4097ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
4098 llvm::Value *Exn) {
4099 // In C++, we want to call __cxa_begin_catch() before terminating.
4100 if (Exn) {
4101 assert(CGF.CGM.getLangOpts().CPlusPlus);
4102 return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn);
4103 }
4104 return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
4105}
Peter Collingbourne60108802017-12-13 21:53:04 +00004106
4107std::pair<llvm::Value *, const CXXRecordDecl *>
4108ItaniumCXXABI::LoadVTablePtr(CodeGenFunction &CGF, Address This,
4109 const CXXRecordDecl *RD) {
4110 return {CGF.GetVTablePtr(This, CGM.Int8PtrTy, RD), RD};
4111}