blob: 20021808f759bf2df57c726eb75aac9374e54ea4 [file] [log] [blame]
Charles Davis4e786dd2010-05-25 19:52:27 +00001//===------- ItaniumCXXABI.cpp - Emit LLVM Code from ASTs for a Module ----===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattner57540c52011-04-15 05:22:18 +000010// This provides C++ code generation targeting the Itanium C++ ABI. The class
Charles Davis4e786dd2010-05-25 19:52:27 +000011// in this file generates structures that follow the Itanium C++ ABI, which is
12// documented at:
13// http://www.codesourcery.com/public/cxx-abi/abi.html
14// http://www.codesourcery.com/public/cxx-abi/abi-eh.html
John McCall86353412010-08-21 22:46:04 +000015//
16// It also supports the closely-related ARM ABI, documented at:
17// http://infocenter.arm.com/help/topic/com.arm.doc.ihi0041c/IHI0041C_cppabi.pdf
18//
Charles Davis4e786dd2010-05-25 19:52:27 +000019//===----------------------------------------------------------------------===//
20
21#include "CGCXXABI.h"
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000022#include "CGCleanup.h"
John McCall7a9aac22010-08-23 01:21:21 +000023#include "CGRecordLayout.h"
Charles Davisa325a6e2012-06-23 23:44:00 +000024#include "CGVTables.h"
John McCall475999d2010-08-22 00:05:51 +000025#include "CodeGenFunction.h"
Charles Davis4e786dd2010-05-25 19:52:27 +000026#include "CodeGenModule.h"
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000027#include "TargetInfo.h"
John McCall5ad74072017-03-02 20:04:19 +000028#include "clang/CodeGen/ConstantInitBuilder.h"
Craig Topperc9ee1d02012-09-15 18:47:51 +000029#include "clang/AST/Mangle.h"
30#include "clang/AST/Type.h"
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000031#include "clang/AST/StmtCXX.h"
David Majnemer1162d252014-06-22 19:05:33 +000032#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000033#include "llvm/IR/DataLayout.h"
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000034#include "llvm/IR/Instructions.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000035#include "llvm/IR/Intrinsics.h"
36#include "llvm/IR/Value.h"
Charles Davis4e786dd2010-05-25 19:52:27 +000037
38using namespace clang;
John McCall475999d2010-08-22 00:05:51 +000039using namespace CodeGen;
Charles Davis4e786dd2010-05-25 19:52:27 +000040
41namespace {
Charles Davis53c59df2010-08-16 03:33:14 +000042class ItaniumCXXABI : public CodeGen::CGCXXABI {
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +000043 /// VTables - All the vtables which have been defined.
44 llvm::DenseMap<const CXXRecordDecl *, llvm::GlobalVariable *> VTables;
45
John McCall475999d2010-08-22 00:05:51 +000046protected:
Mark Seabornedf0d382013-07-24 16:25:13 +000047 bool UseARMMethodPtrABI;
48 bool UseARMGuardVarABI;
John McCalld23b27e2016-09-16 02:40:45 +000049 bool Use32BitVTableOffsetABI;
John McCall7a9aac22010-08-23 01:21:21 +000050
Timur Iskhodzhanov67455222013-10-03 06:26:13 +000051 ItaniumMangleContext &getMangleContext() {
52 return cast<ItaniumMangleContext>(CodeGen::CGCXXABI::getMangleContext());
53 }
54
Charles Davis4e786dd2010-05-25 19:52:27 +000055public:
Mark Seabornedf0d382013-07-24 16:25:13 +000056 ItaniumCXXABI(CodeGen::CodeGenModule &CGM,
57 bool UseARMMethodPtrABI = false,
58 bool UseARMGuardVarABI = false) :
59 CGCXXABI(CGM), UseARMMethodPtrABI(UseARMMethodPtrABI),
John McCalld23b27e2016-09-16 02:40:45 +000060 UseARMGuardVarABI(UseARMGuardVarABI),
Richard Smithb17d6fa2016-12-01 03:04:07 +000061 Use32BitVTableOffsetABI(false) { }
John McCall475999d2010-08-22 00:05:51 +000062
Reid Kleckner40ca9132014-05-13 22:05:45 +000063 bool classifyReturnType(CGFunctionInfo &FI) const override;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000064
Richard Smithf667ad52017-08-26 01:04:35 +000065 bool passClassIndirect(const CXXRecordDecl *RD) const {
66 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
67 // The PS4 platform ABI follows the behavior of Clang 3.2.
68 if (CGM.getCodeGenOpts().getClangABICompat() <=
69 CodeGenOptions::ClangABI::Ver4 ||
70 CGM.getTriple().getOS() == llvm::Triple::PS4)
Akira Hatanaka02914dc2018-02-05 20:23:22 +000071 return RD->hasNonTrivialDestructorForCall() ||
72 RD->hasNonTrivialCopyConstructorForCall();
Richard Smithf667ad52017-08-26 01:04:35 +000073 return !canCopyArgument(RD);
74 }
75
Craig Topper4f12f102014-03-12 06:41:41 +000076 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override {
Richard Smith96cd6712017-08-16 01:49:53 +000077 // If C++ prohibits us from making a copy, pass by address.
Richard Smithf667ad52017-08-26 01:04:35 +000078 if (passClassIndirect(RD))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000079 return RAA_Indirect;
80 return RAA_Default;
81 }
82
John McCall7f416cc2015-09-08 08:05:57 +000083 bool isThisCompleteObject(GlobalDecl GD) const override {
84 // The Itanium ABI has separate complete-object vs. base-object
85 // variants of both constructors and destructors.
86 if (isa<CXXDestructorDecl>(GD.getDecl())) {
87 switch (GD.getDtorType()) {
88 case Dtor_Complete:
89 case Dtor_Deleting:
90 return true;
91
92 case Dtor_Base:
93 return false;
94
95 case Dtor_Comdat:
96 llvm_unreachable("emitting dtor comdat as function?");
97 }
98 llvm_unreachable("bad dtor kind");
99 }
100 if (isa<CXXConstructorDecl>(GD.getDecl())) {
101 switch (GD.getCtorType()) {
102 case Ctor_Complete:
103 return true;
104
105 case Ctor_Base:
106 return false;
107
108 case Ctor_CopyingClosure:
109 case Ctor_DefaultClosure:
110 llvm_unreachable("closure ctors in Itanium ABI?");
111
112 case Ctor_Comdat:
113 llvm_unreachable("emitting ctor comdat as function?");
114 }
115 llvm_unreachable("bad dtor kind");
116 }
117
118 // No other kinds.
119 return false;
120 }
121
Craig Topper4f12f102014-03-12 06:41:41 +0000122 bool isZeroInitializable(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +0000123
Craig Topper4f12f102014-03-12 06:41:41 +0000124 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
John McCall7a9aac22010-08-23 01:21:21 +0000125
John McCallb92ab1a2016-10-26 23:46:34 +0000126 CGCallee
Craig Topper4f12f102014-03-12 06:41:41 +0000127 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
128 const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000129 Address This,
130 llvm::Value *&ThisPtrForCall,
Craig Topper4f12f102014-03-12 06:41:41 +0000131 llvm::Value *MemFnPtr,
132 const MemberPointerType *MPT) override;
John McCalla8bbb822010-08-22 03:04:22 +0000133
Craig Topper4f12f102014-03-12 06:41:41 +0000134 llvm::Value *
135 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000136 Address Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000137 llvm::Value *MemPtr,
138 const MemberPointerType *MPT) override;
John McCallc134eb52010-08-31 21:07:20 +0000139
John McCall7a9aac22010-08-23 01:21:21 +0000140 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
141 const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +0000142 llvm::Value *Src) override;
John McCallc62bb392012-02-15 01:22:51 +0000143 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +0000144 llvm::Constant *Src) override;
John McCall84fa5102010-08-22 04:16:24 +0000145
Craig Topper4f12f102014-03-12 06:41:41 +0000146 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +0000147
David Majnemere2be95b2015-06-23 07:31:01 +0000148 llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD) override;
John McCallf3a88602011-02-03 08:15:49 +0000149 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +0000150 CharUnits offset) override;
151 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
Richard Smithdafff942012-01-14 04:30:29 +0000152 llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
153 CharUnits ThisAdjustment);
John McCall1c456c82010-08-22 06:43:33 +0000154
John McCall7a9aac22010-08-23 01:21:21 +0000155 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000156 llvm::Value *L, llvm::Value *R,
John McCall7a9aac22010-08-23 01:21:21 +0000157 const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +0000158 bool Inequality) override;
John McCall131d97d2010-08-22 08:30:07 +0000159
John McCall7a9aac22010-08-23 01:21:21 +0000160 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000161 llvm::Value *Addr,
162 const MemberPointerType *MPT) override;
John McCall5d865c322010-08-31 07:33:07 +0000163
David Majnemer08681372014-11-01 07:37:17 +0000164 void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,
John McCall7f416cc2015-09-08 08:05:57 +0000165 Address Ptr, QualType ElementType,
David Majnemer0c0b6d92014-10-31 20:09:12 +0000166 const CXXDestructorDecl *Dtor) override;
John McCall82fb8922012-09-25 10:10:39 +0000167
Akira Hatanakac47fcf02017-07-27 18:52:44 +0000168 /// Itanium says that an _Unwind_Exception has to be "double-word"
169 /// aligned (and thus the end of it is also so-aligned), meaning 16
170 /// bytes. Of course, that was written for the actual Itanium,
171 /// which is a 64-bit platform. Classically, the ABI doesn't really
172 /// specify the alignment on other platforms, but in practice
173 /// libUnwind declares the struct with __attribute__((aligned)), so
174 /// we assume that alignment here. (It's generally 16 bytes, but
175 /// some targets overwrite it.)
John McCall7f416cc2015-09-08 08:05:57 +0000176 CharUnits getAlignmentOfExnObject() {
Akira Hatanakac47fcf02017-07-27 18:52:44 +0000177 auto align = CGM.getContext().getTargetDefaultAlignForAttributeAligned();
178 return CGM.getContext().toCharUnitsFromBits(align);
John McCall7f416cc2015-09-08 08:05:57 +0000179 }
180
David Majnemer442d0a22014-11-25 07:20:20 +0000181 void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
David Majnemer7c237072015-03-05 00:46:22 +0000182 void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override;
David Majnemer442d0a22014-11-25 07:20:20 +0000183
Reid Klecknerfff8e7f2015-03-03 19:21:04 +0000184 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
185
186 llvm::CallInst *
187 emitTerminateForUnexpectedException(CodeGenFunction &CGF,
188 llvm::Value *Exn) override;
189
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +0000190 void EmitFundamentalRTTIDescriptor(QualType Type, bool DLLExport);
191 void EmitFundamentalRTTIDescriptors(bool DLLExport);
David Majnemer443250f2015-03-17 20:35:00 +0000192 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
Reid Kleckner10aa7702015-09-16 20:15:55 +0000193 CatchTypeInfo
David Majnemer37b417f2015-03-29 21:55:10 +0000194 getAddrOfCXXCatchHandlerType(QualType Ty,
195 QualType CatchHandlerType) override {
Reid Kleckner10aa7702015-09-16 20:15:55 +0000196 return CatchTypeInfo{getAddrOfRTTIDescriptor(Ty), 0};
David Majnemer443250f2015-03-17 20:35:00 +0000197 }
David Majnemere2cb8d12014-07-07 06:20:47 +0000198
David Majnemer1162d252014-06-22 19:05:33 +0000199 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
200 void EmitBadTypeidCall(CodeGenFunction &CGF) override;
201 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
John McCall7f416cc2015-09-08 08:05:57 +0000202 Address ThisPtr,
David Majnemer1162d252014-06-22 19:05:33 +0000203 llvm::Type *StdTypeInfoPtrTy) override;
204
205 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
206 QualType SrcRecordTy) override;
207
John McCall7f416cc2015-09-08 08:05:57 +0000208 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, Address Value,
David Majnemer1162d252014-06-22 19:05:33 +0000209 QualType SrcRecordTy, QualType DestTy,
210 QualType DestRecordTy,
211 llvm::BasicBlock *CastEnd) override;
212
John McCall7f416cc2015-09-08 08:05:57 +0000213 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
David Majnemer1162d252014-06-22 19:05:33 +0000214 QualType SrcRecordTy,
215 QualType DestTy) override;
216
217 bool EmitBadCastCall(CodeGenFunction &CGF) override;
218
Craig Topper4f12f102014-03-12 06:41:41 +0000219 llvm::Value *
John McCall7f416cc2015-09-08 08:05:57 +0000220 GetVirtualBaseClassOffset(CodeGenFunction &CGF, Address This,
Craig Topper4f12f102014-03-12 06:41:41 +0000221 const CXXRecordDecl *ClassDecl,
222 const CXXRecordDecl *BaseClassDecl) override;
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000223
Craig Topper4f12f102014-03-12 06:41:41 +0000224 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000225
George Burgess IVf203dbf2017-02-22 20:28:02 +0000226 AddedStructorArgs
227 buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
228 SmallVectorImpl<CanQualType> &ArgTys) override;
John McCall5d865c322010-08-31 07:33:07 +0000229
Reid Klecknere7de47e2013-07-22 13:51:44 +0000230 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
Craig Topper4f12f102014-03-12 06:41:41 +0000231 CXXDtorType DT) const override {
Reid Klecknere7de47e2013-07-22 13:51:44 +0000232 // Itanium does not emit any destructor variant as an inline thunk.
233 // Delegating may occur as an optimization, but all variants are either
234 // emitted with external linkage or as linkonce if they are inline and used.
235 return false;
236 }
237
Craig Topper4f12f102014-03-12 06:41:41 +0000238 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
Reid Klecknere7de47e2013-07-22 13:51:44 +0000239
Reid Kleckner89077a12013-12-17 19:46:40 +0000240 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
Craig Topper4f12f102014-03-12 06:41:41 +0000241 FunctionArgList &Params) override;
John McCall5d865c322010-08-31 07:33:07 +0000242
Craig Topper4f12f102014-03-12 06:41:41 +0000243 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
John McCall8ed55a52010-09-02 09:58:18 +0000244
George Burgess IVf203dbf2017-02-22 20:28:02 +0000245 AddedStructorArgs
246 addImplicitConstructorArgs(CodeGenFunction &CGF, const CXXConstructorDecl *D,
247 CXXCtorType Type, bool ForVirtualBase,
248 bool Delegating, CallArgList &Args) override;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000249
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000250 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
251 CXXDtorType Type, bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +0000252 bool Delegating, Address This) override;
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000253
Craig Topper4f12f102014-03-12 06:41:41 +0000254 void emitVTableDefinitions(CodeGenVTables &CGVT,
255 const CXXRecordDecl *RD) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000256
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000257 bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,
258 CodeGenFunction::VPtr Vptr) override;
259
260 bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override {
261 return true;
262 }
263
264 llvm::Constant *
265 getVTableAddressPoint(BaseSubobject Base,
266 const CXXRecordDecl *VTableClass) override;
267
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000268 llvm::Value *getVTableAddressPointInStructor(
269 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000270 BaseSubobject Base, const CXXRecordDecl *NearestVBase) override;
271
272 llvm::Value *getVTableAddressPointInStructorWithVTT(
273 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
274 BaseSubobject Base, const CXXRecordDecl *NearestVBase);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000275
276 llvm::Constant *
277 getVTableAddressPointForConstExpr(BaseSubobject Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000278 const CXXRecordDecl *VTableClass) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000279
280 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
Craig Topper4f12f102014-03-12 06:41:41 +0000281 CharUnits VPtrOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000282
John McCall9831b842018-02-06 18:52:44 +0000283 CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
284 Address This, llvm::Type *Ty,
285 SourceLocation Loc) override;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000286
David Majnemer0c0b6d92014-10-31 20:09:12 +0000287 llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
288 const CXXDestructorDecl *Dtor,
289 CXXDtorType DtorType,
John McCall7f416cc2015-09-08 08:05:57 +0000290 Address This,
David Majnemer0c0b6d92014-10-31 20:09:12 +0000291 const CXXMemberCallExpr *CE) override;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000292
Craig Topper4f12f102014-03-12 06:41:41 +0000293 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
Reid Kleckner7810af02013-06-19 15:20:38 +0000294
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000295 bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const override;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000296
Hans Wennborgc94391d2014-06-06 20:04:01 +0000297 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
298 bool ReturnAdjustment) override {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000299 // Allow inlining of thunks by emitting them with available_externally
300 // linkage together with vtables when needed.
Peter Collingbourne8fabc1b2015-07-01 02:10:26 +0000301 if (ForVTable && !Thunk->hasLocalLinkage())
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000302 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
Rafael Espindolab7350042018-03-01 00:35:47 +0000303 CGM.setGVProperties(Thunk, GD);
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000304 }
305
Rafael Espindolab7350042018-03-01 00:35:47 +0000306 bool exportThunk() override { return true; }
307
John McCall7f416cc2015-09-08 08:05:57 +0000308 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This,
Craig Topper4f12f102014-03-12 06:41:41 +0000309 const ThisAdjustment &TA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000310
John McCall7f416cc2015-09-08 08:05:57 +0000311 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
Craig Topper4f12f102014-03-12 06:41:41 +0000312 const ReturnAdjustment &RA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000313
David Majnemer196ac332014-09-11 23:05:02 +0000314 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
315 FunctionArgList &Args) const override {
316 assert(!Args.empty() && "expected the arglist to not be empty!");
317 return Args.size() - 1;
318 }
319
Craig Topper4f12f102014-03-12 06:41:41 +0000320 StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
321 StringRef GetDeletedVirtualCallName() override
322 { return "__cxa_deleted_virtual"; }
Joao Matos2ce88ef2012-07-17 17:10:11 +0000323
Craig Topper4f12f102014-03-12 06:41:41 +0000324 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall7f416cc2015-09-08 08:05:57 +0000325 Address InitializeArrayCookie(CodeGenFunction &CGF,
326 Address NewPtr,
327 llvm::Value *NumElements,
328 const CXXNewExpr *expr,
329 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000330 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000331 Address allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000332 CharUnits cookieSize) override;
John McCall68ff0372010-09-08 01:44:27 +0000333
John McCallcdf7ef52010-11-06 09:44:32 +0000334 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000335 llvm::GlobalVariable *DeclPtr,
336 bool PerformInit) override;
Richard Smithdbf74ba2013-04-14 23:01:42 +0000337 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000338 llvm::Constant *dtor, llvm::Constant *addr) override;
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000339
340 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +0000341 llvm::Value *Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000342 void EmitThreadLocalInitFuncs(
David Majnemerb3341ea2014-10-05 05:05:40 +0000343 CodeGenModule &CGM,
Richard Smith5a99c492015-12-01 01:10:48 +0000344 ArrayRef<const VarDecl *> CXXThreadLocals,
David Majnemerb3341ea2014-10-05 05:05:40 +0000345 ArrayRef<llvm::Function *> CXXThreadLocalInits,
Richard Smith5a99c492015-12-01 01:10:48 +0000346 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) override;
David Majnemerb3341ea2014-10-05 05:05:40 +0000347
348 bool usesThreadWrapperFunction() const override { return true; }
Richard Smith0f383742014-03-26 22:48:22 +0000349 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
350 QualType LValType) override;
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000351
Craig Topper4f12f102014-03-12 06:41:41 +0000352 bool NeedsVTTParameter(GlobalDecl GD) override;
David Majnemere2cb8d12014-07-07 06:20:47 +0000353
354 /**************************** RTTI Uniqueness ******************************/
355
356protected:
357 /// Returns true if the ABI requires RTTI type_info objects to be unique
358 /// across a program.
359 virtual bool shouldRTTIBeUnique() const { return true; }
360
361public:
362 /// What sort of unique-RTTI behavior should we use?
363 enum RTTIUniquenessKind {
364 /// We are guaranteeing, or need to guarantee, that the RTTI string
365 /// is unique.
366 RUK_Unique,
367
368 /// We are not guaranteeing uniqueness for the RTTI string, so we
369 /// can demote to hidden visibility but must use string comparisons.
370 RUK_NonUniqueHidden,
371
372 /// We are not guaranteeing uniqueness for the RTTI string, so we
373 /// have to use string comparisons, but we also have to emit it with
374 /// non-hidden visibility.
375 RUK_NonUniqueVisible
376 };
377
378 /// Return the required visibility status for the given type and linkage in
379 /// the current ABI.
380 RTTIUniquenessKind
381 classifyRTTIUniqueness(QualType CanTy,
382 llvm::GlobalValue::LinkageTypes Linkage) const;
383 friend class ItaniumRTTIBuilder;
Rafael Espindola91f68b42014-09-15 19:20:10 +0000384
385 void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000386
Peter Collingbourne60108802017-12-13 21:53:04 +0000387 std::pair<llvm::Value *, const CXXRecordDecl *>
388 LoadVTablePtr(CodeGenFunction &CGF, Address This,
389 const CXXRecordDecl *RD) override;
390
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000391 private:
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000392 bool hasAnyUnusedVirtualInlineFunction(const CXXRecordDecl *RD) const {
393 const auto &VtableLayout =
394 CGM.getItaniumVTableContext().getVTableLayout(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000395
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000396 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
397 // Skip empty slot.
398 if (!VtableComponent.isUsedFunctionPointerKind())
399 continue;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000400
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000401 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
402 if (!Method->getCanonicalDecl()->isInlined())
403 continue;
404
405 StringRef Name = CGM.getMangledName(VtableComponent.getGlobalDecl());
406 auto *Entry = CGM.GetGlobalValue(Name);
407 // This checks if virtual inline function has already been emitted.
408 // Note that it is possible that this inline function would be emitted
409 // after trying to emit vtable speculatively. Because of this we do
410 // an extra pass after emitting all deferred vtables to find and emit
411 // these vtables opportunistically.
412 if (!Entry || Entry->isDeclaration())
413 return true;
414 }
415 return false;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000416 }
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000417
418 bool isVTableHidden(const CXXRecordDecl *RD) const {
419 const auto &VtableLayout =
420 CGM.getItaniumVTableContext().getVTableLayout(RD);
421
422 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
423 if (VtableComponent.isRTTIKind()) {
424 const CXXRecordDecl *RTTIDecl = VtableComponent.getRTTIDecl();
425 if (RTTIDecl->getVisibility() == Visibility::HiddenVisibility)
426 return true;
427 } else if (VtableComponent.isUsedFunctionPointerKind()) {
428 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
429 if (Method->getVisibility() == Visibility::HiddenVisibility &&
430 !Method->isDefined())
431 return true;
432 }
433 }
434 return false;
435 }
Charles Davis4e786dd2010-05-25 19:52:27 +0000436};
John McCall86353412010-08-21 22:46:04 +0000437
438class ARMCXXABI : public ItaniumCXXABI {
439public:
Mark Seabornedf0d382013-07-24 16:25:13 +0000440 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
441 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
442 /* UseARMGuardVarABI = */ true) {}
John McCall5d865c322010-08-31 07:33:07 +0000443
Craig Topper4f12f102014-03-12 06:41:41 +0000444 bool HasThisReturn(GlobalDecl GD) const override {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000445 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
446 isa<CXXDestructorDecl>(GD.getDecl()) &&
447 GD.getDtorType() != Dtor_Deleting));
448 }
John McCall5d865c322010-08-31 07:33:07 +0000449
Craig Topper4f12f102014-03-12 06:41:41 +0000450 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
451 QualType ResTy) override;
John McCall5d865c322010-08-31 07:33:07 +0000452
Craig Topper4f12f102014-03-12 06:41:41 +0000453 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall7f416cc2015-09-08 08:05:57 +0000454 Address InitializeArrayCookie(CodeGenFunction &CGF,
455 Address NewPtr,
456 llvm::Value *NumElements,
457 const CXXNewExpr *expr,
458 QualType ElementType) override;
459 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, Address allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000460 CharUnits cookieSize) override;
John McCall86353412010-08-21 22:46:04 +0000461};
Tim Northovera2ee4332014-03-29 15:09:45 +0000462
463class iOS64CXXABI : public ARMCXXABI {
464public:
John McCalld23b27e2016-09-16 02:40:45 +0000465 iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {
466 Use32BitVTableOffsetABI = true;
467 }
Tim Northover65f582f2014-03-30 17:32:48 +0000468
469 // ARM64 libraries are prepared for non-unique RTTI.
David Majnemere2cb8d12014-07-07 06:20:47 +0000470 bool shouldRTTIBeUnique() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +0000471};
Dan Gohmanc2853072015-09-03 22:51:53 +0000472
473class WebAssemblyCXXABI final : public ItaniumCXXABI {
474public:
475 explicit WebAssemblyCXXABI(CodeGen::CodeGenModule &CGM)
476 : ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
477 /*UseARMGuardVarABI=*/true) {}
478
479private:
480 bool HasThisReturn(GlobalDecl GD) const override {
481 return isa<CXXConstructorDecl>(GD.getDecl()) ||
482 (isa<CXXDestructorDecl>(GD.getDecl()) &&
483 GD.getDtorType() != Dtor_Deleting);
484 }
Derek Schuff8179be42016-05-10 17:44:55 +0000485 bool canCallMismatchedFunctionType() const override { return false; }
Dan Gohmanc2853072015-09-03 22:51:53 +0000486};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000487}
Charles Davis4e786dd2010-05-25 19:52:27 +0000488
Charles Davis53c59df2010-08-16 03:33:14 +0000489CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000490 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000491 // For IR-generation purposes, there's no significant difference
492 // between the ARM and iOS ABIs.
493 case TargetCXXABI::GenericARM:
494 case TargetCXXABI::iOS:
Tim Northover756447a2015-10-30 16:30:36 +0000495 case TargetCXXABI::WatchOS:
John McCall57625922013-01-25 23:36:14 +0000496 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000497
Tim Northovera2ee4332014-03-29 15:09:45 +0000498 case TargetCXXABI::iOS64:
499 return new iOS64CXXABI(CGM);
500
Tim Northover9bb857a2013-01-31 12:13:10 +0000501 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
502 // include the other 32-bit ARM oddities: constructor/destructor return values
503 // and array cookies.
504 case TargetCXXABI::GenericAArch64:
Mark Seabornedf0d382013-07-24 16:25:13 +0000505 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
506 /* UseARMGuardVarABI = */ true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000507
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000508 case TargetCXXABI::GenericMIPS:
509 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true);
510
Dan Gohmanc2853072015-09-03 22:51:53 +0000511 case TargetCXXABI::WebAssembly:
512 return new WebAssemblyCXXABI(CGM);
513
John McCall57625922013-01-25 23:36:14 +0000514 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000515 if (CGM.getContext().getTargetInfo().getTriple().getArch()
516 == llvm::Triple::le32) {
517 // For PNaCl, use ARM-style method pointers so that PNaCl code
518 // does not assume anything about the alignment of function
519 // pointers.
520 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
521 /* UseARMGuardVarABI = */ false);
522 }
John McCall57625922013-01-25 23:36:14 +0000523 return new ItaniumCXXABI(CGM);
524
525 case TargetCXXABI::Microsoft:
526 llvm_unreachable("Microsoft ABI is not Itanium-based");
527 }
528 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000529}
530
Chris Lattnera5f58b02011-07-09 17:41:47 +0000531llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000532ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
533 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000534 return CGM.PtrDiffTy;
Serge Guelton1d993272017-05-09 19:31:30 +0000535 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy);
John McCall1c456c82010-08-22 06:43:33 +0000536}
537
John McCalld9c6c0b2010-08-22 00:59:17 +0000538/// In the Itanium and ARM ABIs, method pointers have the form:
539/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
540///
541/// In the Itanium ABI:
542/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
543/// - the this-adjustment is (memptr.adj)
544/// - the virtual offset is (memptr.ptr - 1)
545///
546/// In the ARM ABI:
547/// - method pointers are virtual if (memptr.adj & 1) is nonzero
548/// - the this-adjustment is (memptr.adj >> 1)
549/// - the virtual offset is (memptr.ptr)
550/// ARM uses 'adj' for the virtual flag because Thumb functions
551/// may be only single-byte aligned.
552///
553/// If the member is virtual, the adjusted 'this' pointer points
554/// to a vtable pointer from which the virtual offset is applied.
555///
556/// If the member is non-virtual, memptr.ptr is the address of
557/// the function to call.
John McCallb92ab1a2016-10-26 23:46:34 +0000558CGCallee ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
John McCall7f416cc2015-09-08 08:05:57 +0000559 CodeGenFunction &CGF, const Expr *E, Address ThisAddr,
560 llvm::Value *&ThisPtrForCall,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000561 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
John McCall475999d2010-08-22 00:05:51 +0000562 CGBuilderTy &Builder = CGF.Builder;
563
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000564 const FunctionProtoType *FPT =
John McCall475999d2010-08-22 00:05:51 +0000565 MPT->getPointeeType()->getAs<FunctionProtoType>();
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000566 const CXXRecordDecl *RD =
John McCall475999d2010-08-22 00:05:51 +0000567 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
568
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000569 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(
570 CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr));
John McCall475999d2010-08-22 00:05:51 +0000571
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000572 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000573
John McCalld9c6c0b2010-08-22 00:59:17 +0000574 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
575 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
576 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
577
John McCalla1dee5302010-08-22 10:59:02 +0000578 // Extract memptr.adj, which is in the second field.
579 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000580
581 // Compute the true adjustment.
582 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000583 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000584 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000585
586 // Apply the adjustment and cast back to the original struct type
587 // for consistency.
John McCall7f416cc2015-09-08 08:05:57 +0000588 llvm::Value *This = ThisAddr.getPointer();
John McCalld9c6c0b2010-08-22 00:59:17 +0000589 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
590 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
591 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall7f416cc2015-09-08 08:05:57 +0000592 ThisPtrForCall = This;
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000593
John McCall475999d2010-08-22 00:05:51 +0000594 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000595 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000596
John McCall475999d2010-08-22 00:05:51 +0000597 // If the LSB in the function pointer is 1, the function pointer points to
598 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000599 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000600 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000601 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
602 else
603 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
604 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000605 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
606
607 // In the virtual path, the adjustment left 'This' pointing to the
608 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000609 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000610 CGF.EmitBlock(FnVirtual);
611
612 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000613 llvm::Type *VTableTy = Builder.getInt8PtrTy();
John McCall7f416cc2015-09-08 08:05:57 +0000614 CharUnits VTablePtrAlign =
615 CGF.CGM.getDynamicOffsetAlignment(ThisAddr.getAlignment(), RD,
616 CGF.getPointerAlign());
617 llvm::Value *VTable =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000618 CGF.GetVTablePtr(Address(This, VTablePtrAlign), VTableTy, RD);
John McCall475999d2010-08-22 00:05:51 +0000619
620 // Apply the offset.
John McCalld23b27e2016-09-16 02:40:45 +0000621 // On ARM64, to reserve extra space in virtual member function pointers,
622 // we only pay attention to the low 32 bits of the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000623 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000624 if (!UseARMMethodPtrABI)
625 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld23b27e2016-09-16 02:40:45 +0000626 if (Use32BitVTableOffsetABI) {
627 VTableOffset = Builder.CreateTrunc(VTableOffset, CGF.Int32Ty);
628 VTableOffset = Builder.CreateZExt(VTableOffset, CGM.PtrDiffTy);
629 }
John McCalld9c6c0b2010-08-22 00:59:17 +0000630 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall475999d2010-08-22 00:05:51 +0000631
632 // Load the virtual function to call.
633 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCall7f416cc2015-09-08 08:05:57 +0000634 llvm::Value *VirtualFn =
635 Builder.CreateAlignedLoad(VTable, CGF.getPointerAlign(),
636 "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000637 CGF.EmitBranch(FnEnd);
638
639 // In the non-virtual path, the function pointer is actually a
640 // function pointer.
641 CGF.EmitBlock(FnNonVirtual);
642 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000643 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000644
John McCall475999d2010-08-22 00:05:51 +0000645 // We're done.
646 CGF.EmitBlock(FnEnd);
John McCallb92ab1a2016-10-26 23:46:34 +0000647 llvm::PHINode *CalleePtr = Builder.CreatePHI(FTy->getPointerTo(), 2);
648 CalleePtr->addIncoming(VirtualFn, FnVirtual);
649 CalleePtr->addIncoming(NonVirtualFn, FnNonVirtual);
650
651 CGCallee Callee(FPT, CalleePtr);
John McCall475999d2010-08-22 00:05:51 +0000652 return Callee;
653}
John McCalla8bbb822010-08-22 03:04:22 +0000654
John McCallc134eb52010-08-31 21:07:20 +0000655/// Compute an l-value by applying the given pointer-to-member to a
656/// base object.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000657llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
John McCall7f416cc2015-09-08 08:05:57 +0000658 CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000659 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000660 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000661
662 CGBuilderTy &Builder = CGF.Builder;
663
John McCallc134eb52010-08-31 21:07:20 +0000664 // Cast to char*.
John McCall7f416cc2015-09-08 08:05:57 +0000665 Base = Builder.CreateElementBitCast(Base, CGF.Int8Ty);
John McCallc134eb52010-08-31 21:07:20 +0000666
667 // Apply the offset, which we assume is non-null.
John McCall7f416cc2015-09-08 08:05:57 +0000668 llvm::Value *Addr =
669 Builder.CreateInBoundsGEP(Base.getPointer(), MemPtr, "memptr.offset");
John McCallc134eb52010-08-31 21:07:20 +0000670
671 // Cast the address to the appropriate pointer type, adopting the
672 // address space of the base pointer.
John McCall7f416cc2015-09-08 08:05:57 +0000673 llvm::Type *PType = CGF.ConvertTypeForMem(MPT->getPointeeType())
674 ->getPointerTo(Base.getAddressSpace());
John McCallc134eb52010-08-31 21:07:20 +0000675 return Builder.CreateBitCast(Addr, PType);
676}
677
John McCallc62bb392012-02-15 01:22:51 +0000678/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
679/// conversion.
680///
681/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000682///
683/// Obligatory offset/adjustment diagram:
684/// <-- offset --> <-- adjustment -->
685/// |--------------------------|----------------------|--------------------|
686/// ^Derived address point ^Base address point ^Member address point
687///
688/// So when converting a base member pointer to a derived member pointer,
689/// we add the offset to the adjustment because the address point has
690/// decreased; and conversely, when converting a derived MP to a base MP
691/// we subtract the offset from the adjustment because the address point
692/// has increased.
693///
694/// The standard forbids (at compile time) conversion to and from
695/// virtual bases, which is why we don't have to consider them here.
696///
697/// The standard forbids (at run time) casting a derived MP to a base
698/// MP when the derived MP does not point to a member of the base.
699/// This is why -1 is a reasonable choice for null data member
700/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000701llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000702ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
703 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000704 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000705 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000706 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
707 E->getCastKind() == CK_ReinterpretMemberPointer);
708
709 // Under Itanium, reinterprets don't require any additional processing.
710 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
711
712 // Use constant emission if we can.
713 if (isa<llvm::Constant>(src))
714 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
715
716 llvm::Constant *adj = getMemberPointerAdjustment(E);
717 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000718
719 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000720 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000721
John McCallc62bb392012-02-15 01:22:51 +0000722 const MemberPointerType *destTy =
723 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000724
John McCall7a9aac22010-08-23 01:21:21 +0000725 // For member data pointers, this is just a matter of adding the
726 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000727 if (destTy->isMemberDataPointer()) {
728 llvm::Value *dst;
729 if (isDerivedToBase)
730 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000731 else
John McCallc62bb392012-02-15 01:22:51 +0000732 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000733
734 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000735 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
736 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
737 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000738 }
739
John McCalla1dee5302010-08-22 10:59:02 +0000740 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000741 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000742 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
743 offset <<= 1;
744 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000745 }
746
John McCallc62bb392012-02-15 01:22:51 +0000747 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
748 llvm::Value *dstAdj;
749 if (isDerivedToBase)
750 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000751 else
John McCallc62bb392012-02-15 01:22:51 +0000752 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000753
John McCallc62bb392012-02-15 01:22:51 +0000754 return Builder.CreateInsertValue(src, dstAdj, 1);
755}
756
757llvm::Constant *
758ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
759 llvm::Constant *src) {
760 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
761 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
762 E->getCastKind() == CK_ReinterpretMemberPointer);
763
764 // Under Itanium, reinterprets don't require any additional processing.
765 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
766
767 // If the adjustment is trivial, we don't need to do anything.
768 llvm::Constant *adj = getMemberPointerAdjustment(E);
769 if (!adj) return src;
770
771 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
772
773 const MemberPointerType *destTy =
774 E->getType()->castAs<MemberPointerType>();
775
776 // For member data pointers, this is just a matter of adding the
777 // offset if the source is non-null.
778 if (destTy->isMemberDataPointer()) {
779 // null maps to null.
780 if (src->isAllOnesValue()) return src;
781
782 if (isDerivedToBase)
783 return llvm::ConstantExpr::getNSWSub(src, adj);
784 else
785 return llvm::ConstantExpr::getNSWAdd(src, adj);
786 }
787
788 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000789 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000790 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
791 offset <<= 1;
792 adj = llvm::ConstantInt::get(adj->getType(), offset);
793 }
794
795 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
796 llvm::Constant *dstAdj;
797 if (isDerivedToBase)
798 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
799 else
800 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
801
802 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000803}
John McCall84fa5102010-08-22 04:16:24 +0000804
805llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000806ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000807 // Itanium C++ ABI 2.3:
808 // A NULL pointer is represented as -1.
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000809 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000810 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000811
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000812 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000813 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000814 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000815}
816
John McCallf3a88602011-02-03 08:15:49 +0000817llvm::Constant *
818ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
819 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000820 // Itanium C++ ABI 2.3:
821 // A pointer to data member is an offset from the base address of
822 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000823 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000824}
825
David Majnemere2be95b2015-06-23 07:31:01 +0000826llvm::Constant *
827ItaniumCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000828 return BuildMemberPointer(MD, CharUnits::Zero());
829}
830
831llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
832 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000833 assert(MD->isInstance() && "Member function must not be static!");
834 MD = MD->getCanonicalDecl();
835
836 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000837
838 // Get the function pointer (or index if this is a virtual function).
839 llvm::Constant *MemPtr[2];
840 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000841 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000842
Ken Dyckdf016282011-04-09 01:30:02 +0000843 const ASTContext &Context = getContext();
844 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000845 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000846 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000847
Mark Seabornedf0d382013-07-24 16:25:13 +0000848 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000849 // ARM C++ ABI 3.2.1:
850 // This ABI specifies that adj contains twice the this
851 // adjustment, plus 1 if the member function is virtual. The
852 // least significant bit of adj then makes exactly the same
853 // discrimination as the least significant bit of ptr does for
854 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000855 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
856 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000857 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000858 } else {
859 // Itanium C++ ABI 2.3:
860 // For a virtual function, [the pointer field] is 1 plus the
861 // virtual table offset (in bytes) of the function,
862 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000863 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
864 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000865 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000866 }
867 } else {
John McCall2979fe02011-04-12 00:42:48 +0000868 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000869 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000870 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000871 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000872 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000873 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000874 } else {
John McCall2979fe02011-04-12 00:42:48 +0000875 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
876 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000877 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000878 }
John McCall2979fe02011-04-12 00:42:48 +0000879 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000880
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000881 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000882 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
883 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000884 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000885 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000886
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000887 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000888}
889
Richard Smithdafff942012-01-14 04:30:29 +0000890llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
891 QualType MPType) {
892 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
893 const ValueDecl *MPD = MP.getMemberPointerDecl();
894 if (!MPD)
895 return EmitNullMemberPointer(MPT);
896
Reid Kleckner452abac2013-05-09 21:01:17 +0000897 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000898
899 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
900 return BuildMemberPointer(MD, ThisAdjustment);
901
902 CharUnits FieldOffset =
903 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
904 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
905}
906
John McCall131d97d2010-08-22 08:30:07 +0000907/// The comparison algorithm is pretty easy: the member pointers are
908/// the same if they're either bitwise identical *or* both null.
909///
910/// ARM is different here only because null-ness is more complicated.
911llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000912ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
913 llvm::Value *L,
914 llvm::Value *R,
915 const MemberPointerType *MPT,
916 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000917 CGBuilderTy &Builder = CGF.Builder;
918
John McCall131d97d2010-08-22 08:30:07 +0000919 llvm::ICmpInst::Predicate Eq;
920 llvm::Instruction::BinaryOps And, Or;
921 if (Inequality) {
922 Eq = llvm::ICmpInst::ICMP_NE;
923 And = llvm::Instruction::Or;
924 Or = llvm::Instruction::And;
925 } else {
926 Eq = llvm::ICmpInst::ICMP_EQ;
927 And = llvm::Instruction::And;
928 Or = llvm::Instruction::Or;
929 }
930
John McCall7a9aac22010-08-23 01:21:21 +0000931 // Member data pointers are easy because there's a unique null
932 // value, so it just comes down to bitwise equality.
933 if (MPT->isMemberDataPointer())
934 return Builder.CreateICmp(Eq, L, R);
935
936 // For member function pointers, the tautologies are more complex.
937 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000938 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000939 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000940 // (L == R) <==> (L.ptr == R.ptr &&
941 // (L.adj == R.adj ||
942 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000943 // The inequality tautologies have exactly the same structure, except
944 // applying De Morgan's laws.
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000945
John McCall7a9aac22010-08-23 01:21:21 +0000946 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
947 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
948
John McCall131d97d2010-08-22 08:30:07 +0000949 // This condition tests whether L.ptr == R.ptr. This must always be
950 // true for equality to hold.
951 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
952
953 // This condition, together with the assumption that L.ptr == R.ptr,
954 // tests whether the pointers are both null. ARM imposes an extra
955 // condition.
956 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
957 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
958
959 // This condition tests whether L.adj == R.adj. If this isn't
960 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +0000961 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
962 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000963 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
964
965 // Null member function pointers on ARM clear the low bit of Adj,
966 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000967 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000968 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
969
970 // Compute (l.adj | r.adj) & 1 and test it against zero.
971 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
972 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
973 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
974 "cmp.or.adj");
975 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
976 }
977
978 // Tie together all our conditions.
979 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
980 Result = Builder.CreateBinOp(And, PtrEq, Result,
981 Inequality ? "memptr.ne" : "memptr.eq");
982 return Result;
983}
984
985llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000986ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
987 llvm::Value *MemPtr,
988 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +0000989 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +0000990
991 /// For member data pointers, this is just a check against -1.
992 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000993 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +0000994 llvm::Value *NegativeOne =
995 llvm::Constant::getAllOnesValue(MemPtr->getType());
996 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
997 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000998
Daniel Dunbar914bc412011-04-19 23:10:47 +0000999 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +00001000 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +00001001
1002 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
1003 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
1004
Daniel Dunbar914bc412011-04-19 23:10:47 +00001005 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
1006 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +00001007 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +00001008 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +00001009 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +00001010 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +00001011 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
1012 "memptr.isvirtual");
1013 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +00001014 }
1015
1016 return Result;
1017}
John McCall1c456c82010-08-22 06:43:33 +00001018
Reid Kleckner40ca9132014-05-13 22:05:45 +00001019bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
1020 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
1021 if (!RD)
1022 return false;
1023
Richard Smith96cd6712017-08-16 01:49:53 +00001024 // If C++ prohibits us from making a copy, return by address.
Richard Smithf667ad52017-08-26 01:04:35 +00001025 if (passClassIndirect(RD)) {
John McCall7f416cc2015-09-08 08:05:57 +00001026 auto Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
1027 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
Reid Kleckner40ca9132014-05-13 22:05:45 +00001028 return true;
1029 }
Reid Kleckner40ca9132014-05-13 22:05:45 +00001030 return false;
1031}
1032
John McCall614dbdc2010-08-22 21:01:12 +00001033/// The Itanium ABI requires non-zero initialization only for data
1034/// member pointers, for which '0' is a valid offset.
1035bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
David Majnemer5fd33e02015-04-24 01:25:08 +00001036 return MPT->isMemberFunctionPointer();
John McCall84fa5102010-08-22 04:16:24 +00001037}
John McCall5d865c322010-08-31 07:33:07 +00001038
John McCall82fb8922012-09-25 10:10:39 +00001039/// The Itanium ABI always places an offset to the complete object
1040/// at entry -2 in the vtable.
David Majnemer08681372014-11-01 07:37:17 +00001041void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
1042 const CXXDeleteExpr *DE,
John McCall7f416cc2015-09-08 08:05:57 +00001043 Address Ptr,
David Majnemer08681372014-11-01 07:37:17 +00001044 QualType ElementType,
1045 const CXXDestructorDecl *Dtor) {
1046 bool UseGlobalDelete = DE->isGlobalDelete();
David Majnemer0c0b6d92014-10-31 20:09:12 +00001047 if (UseGlobalDelete) {
1048 // Derive the complete-object pointer, which is what we need
1049 // to pass to the deallocation function.
John McCall82fb8922012-09-25 10:10:39 +00001050
David Majnemer0c0b6d92014-10-31 20:09:12 +00001051 // Grab the vtable pointer as an intptr_t*.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001052 auto *ClassDecl =
1053 cast<CXXRecordDecl>(ElementType->getAs<RecordType>()->getDecl());
1054 llvm::Value *VTable =
1055 CGF.GetVTablePtr(Ptr, CGF.IntPtrTy->getPointerTo(), ClassDecl);
John McCall82fb8922012-09-25 10:10:39 +00001056
David Majnemer0c0b6d92014-10-31 20:09:12 +00001057 // Track back to entry -2 and pull out the offset there.
1058 llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
1059 VTable, -2, "complete-offset.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001060 llvm::Value *Offset =
1061 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
David Majnemer0c0b6d92014-10-31 20:09:12 +00001062
1063 // Apply the offset.
John McCall7f416cc2015-09-08 08:05:57 +00001064 llvm::Value *CompletePtr =
1065 CGF.Builder.CreateBitCast(Ptr.getPointer(), CGF.Int8PtrTy);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001066 CompletePtr = CGF.Builder.CreateInBoundsGEP(CompletePtr, Offset);
1067
1068 // If we're supposed to call the global delete, make sure we do so
1069 // even if the destructor throws.
David Majnemer08681372014-11-01 07:37:17 +00001070 CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr,
1071 ElementType);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001072 }
1073
1074 // FIXME: Provide a source location here even though there's no
1075 // CXXMemberCallExpr for dtor call.
1076 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
1077 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr);
1078
1079 if (UseGlobalDelete)
1080 CGF.PopCleanupBlock();
John McCall82fb8922012-09-25 10:10:39 +00001081}
1082
David Majnemer442d0a22014-11-25 07:20:20 +00001083void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
1084 // void __cxa_rethrow();
1085
1086 llvm::FunctionType *FTy =
1087 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
1088
1089 llvm::Constant *Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
1090
1091 if (isNoReturn)
1092 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, None);
1093 else
1094 CGF.EmitRuntimeCallOrInvoke(Fn);
1095}
1096
David Majnemer7c237072015-03-05 00:46:22 +00001097static llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) {
1098 // void *__cxa_allocate_exception(size_t thrown_size);
1099
1100 llvm::FunctionType *FTy =
1101 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false);
1102
1103 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
1104}
1105
1106static llvm::Constant *getThrowFn(CodeGenModule &CGM) {
1107 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
1108 // void (*dest) (void *));
1109
1110 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
1111 llvm::FunctionType *FTy =
1112 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
1113
1114 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
1115}
1116
1117void ItaniumCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
1118 QualType ThrowType = E->getSubExpr()->getType();
1119 // Now allocate the exception object.
1120 llvm::Type *SizeTy = CGF.ConvertType(getContext().getSizeType());
1121 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
1122
1123 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM);
1124 llvm::CallInst *ExceptionPtr = CGF.EmitNounwindRuntimeCall(
1125 AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception");
1126
John McCall7f416cc2015-09-08 08:05:57 +00001127 CharUnits ExnAlign = getAlignmentOfExnObject();
1128 CGF.EmitAnyExprToExn(E->getSubExpr(), Address(ExceptionPtr, ExnAlign));
David Majnemer7c237072015-03-05 00:46:22 +00001129
1130 // Now throw the exception.
1131 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
1132 /*ForEH=*/true);
1133
1134 // The address of the destructor. If the exception type has a
1135 // trivial destructor (or isn't a record), we just pass null.
1136 llvm::Constant *Dtor = nullptr;
1137 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
1138 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
1139 if (!Record->hasTrivialDestructor()) {
1140 CXXDestructorDecl *DtorD = Record->getDestructor();
1141 Dtor = CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete);
1142 Dtor = llvm::ConstantExpr::getBitCast(Dtor, CGM.Int8PtrTy);
1143 }
1144 }
1145 if (!Dtor) Dtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
1146
1147 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
1148 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
1149}
1150
David Majnemer1162d252014-06-22 19:05:33 +00001151static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) {
1152 // void *__dynamic_cast(const void *sub,
1153 // const abi::__class_type_info *src,
1154 // const abi::__class_type_info *dst,
1155 // std::ptrdiff_t src2dst_offset);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00001156
David Majnemer1162d252014-06-22 19:05:33 +00001157 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
Jake Ehrlichc451cf22017-11-11 01:15:41 +00001158 llvm::Type *PtrDiffTy =
David Majnemer1162d252014-06-22 19:05:33 +00001159 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1160
1161 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
1162
1163 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
1164
1165 // Mark the function as nounwind readonly.
1166 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
1167 llvm::Attribute::ReadOnly };
Reid Klecknerde864822017-03-21 16:57:30 +00001168 llvm::AttributeList Attrs = llvm::AttributeList::get(
1169 CGF.getLLVMContext(), llvm::AttributeList::FunctionIndex, FuncAttrs);
David Majnemer1162d252014-06-22 19:05:33 +00001170
1171 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
1172}
1173
1174static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1175 // void __cxa_bad_cast();
1176 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1177 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1178}
1179
1180/// \brief Compute the src2dst_offset hint as described in the
1181/// Itanium C++ ABI [2.9.7]
1182static CharUnits computeOffsetHint(ASTContext &Context,
1183 const CXXRecordDecl *Src,
1184 const CXXRecordDecl *Dst) {
1185 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1186 /*DetectVirtual=*/false);
1187
1188 // If Dst is not derived from Src we can skip the whole computation below and
1189 // return that Src is not a public base of Dst. Record all inheritance paths.
1190 if (!Dst->isDerivedFrom(Src, Paths))
1191 return CharUnits::fromQuantity(-2ULL);
1192
1193 unsigned NumPublicPaths = 0;
1194 CharUnits Offset;
1195
1196 // Now walk all possible inheritance paths.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001197 for (const CXXBasePath &Path : Paths) {
1198 if (Path.Access != AS_public) // Ignore non-public inheritance.
David Majnemer1162d252014-06-22 19:05:33 +00001199 continue;
1200
1201 ++NumPublicPaths;
1202
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001203 for (const CXXBasePathElement &PathElement : Path) {
David Majnemer1162d252014-06-22 19:05:33 +00001204 // If the path contains a virtual base class we can't give any hint.
1205 // -1: no hint.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001206 if (PathElement.Base->isVirtual())
David Majnemer1162d252014-06-22 19:05:33 +00001207 return CharUnits::fromQuantity(-1ULL);
1208
1209 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
1210 continue;
1211
1212 // Accumulate the base class offsets.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001213 const ASTRecordLayout &L = Context.getASTRecordLayout(PathElement.Class);
1214 Offset += L.getBaseClassOffset(
1215 PathElement.Base->getType()->getAsCXXRecordDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001216 }
1217 }
1218
1219 // -2: Src is not a public base of Dst.
1220 if (NumPublicPaths == 0)
1221 return CharUnits::fromQuantity(-2ULL);
1222
1223 // -3: Src is a multiple public base type but never a virtual base type.
1224 if (NumPublicPaths > 1)
1225 return CharUnits::fromQuantity(-3ULL);
1226
1227 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
1228 // Return the offset of Src from the origin of Dst.
1229 return Offset;
1230}
1231
1232static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1233 // void __cxa_bad_typeid();
1234 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1235
1236 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1237}
1238
1239bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
1240 QualType SrcRecordTy) {
1241 return IsDeref;
1242}
1243
1244void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
1245 llvm::Value *Fn = getBadTypeidFn(CGF);
1246 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1247 CGF.Builder.CreateUnreachable();
1248}
1249
1250llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
1251 QualType SrcRecordTy,
John McCall7f416cc2015-09-08 08:05:57 +00001252 Address ThisPtr,
David Majnemer1162d252014-06-22 19:05:33 +00001253 llvm::Type *StdTypeInfoPtrTy) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001254 auto *ClassDecl =
1255 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001256 llvm::Value *Value =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001257 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo(), ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001258
1259 // Load the type info.
1260 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001261 return CGF.Builder.CreateAlignedLoad(Value, CGF.getPointerAlign());
David Majnemer1162d252014-06-22 19:05:33 +00001262}
1263
1264bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1265 QualType SrcRecordTy) {
1266 return SrcIsPtr;
1267}
1268
1269llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
John McCall7f416cc2015-09-08 08:05:57 +00001270 CodeGenFunction &CGF, Address ThisAddr, QualType SrcRecordTy,
David Majnemer1162d252014-06-22 19:05:33 +00001271 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1272 llvm::Type *PtrDiffLTy =
1273 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1274 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1275
1276 llvm::Value *SrcRTTI =
1277 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1278 llvm::Value *DestRTTI =
1279 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1280
1281 // Compute the offset hint.
1282 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1283 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1284 llvm::Value *OffsetHint = llvm::ConstantInt::get(
1285 PtrDiffLTy,
1286 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
1287
1288 // Emit the call to __dynamic_cast.
John McCall7f416cc2015-09-08 08:05:57 +00001289 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001290 Value = CGF.EmitCastToVoidPtr(Value);
1291
1292 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
1293 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
1294 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1295
1296 /// C++ [expr.dynamic.cast]p9:
1297 /// A failed cast to reference type throws std::bad_cast
1298 if (DestTy->isReferenceType()) {
1299 llvm::BasicBlock *BadCastBlock =
1300 CGF.createBasicBlock("dynamic_cast.bad_cast");
1301
1302 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1303 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1304
1305 CGF.EmitBlock(BadCastBlock);
1306 EmitBadCastCall(CGF);
1307 }
1308
1309 return Value;
1310}
1311
1312llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001313 Address ThisAddr,
David Majnemer1162d252014-06-22 19:05:33 +00001314 QualType SrcRecordTy,
1315 QualType DestTy) {
1316 llvm::Type *PtrDiffLTy =
1317 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1318 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1319
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001320 auto *ClassDecl =
1321 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001322 // Get the vtable pointer.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001323 llvm::Value *VTable = CGF.GetVTablePtr(ThisAddr, PtrDiffLTy->getPointerTo(),
1324 ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001325
1326 // Get the offset-to-top from the vtable.
1327 llvm::Value *OffsetToTop =
1328 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001329 OffsetToTop =
1330 CGF.Builder.CreateAlignedLoad(OffsetToTop, CGF.getPointerAlign(),
1331 "offset.to.top");
David Majnemer1162d252014-06-22 19:05:33 +00001332
1333 // Finally, add the offset to the pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001334 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001335 Value = CGF.EmitCastToVoidPtr(Value);
1336 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1337
1338 return CGF.Builder.CreateBitCast(Value, DestLTy);
1339}
1340
1341bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1342 llvm::Value *Fn = getBadCastFn(CGF);
1343 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1344 CGF.Builder.CreateUnreachable();
1345 return true;
1346}
1347
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001348llvm::Value *
1349ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001350 Address This,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001351 const CXXRecordDecl *ClassDecl,
1352 const CXXRecordDecl *BaseClassDecl) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001353 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy, ClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001354 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001355 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1356 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001357
1358 llvm::Value *VBaseOffsetPtr =
1359 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1360 "vbase.offset.ptr");
1361 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1362 CGM.PtrDiffTy->getPointerTo());
1363
1364 llvm::Value *VBaseOffset =
John McCall7f416cc2015-09-08 08:05:57 +00001365 CGF.Builder.CreateAlignedLoad(VBaseOffsetPtr, CGF.getPointerAlign(),
1366 "vbase.offset");
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001367
1368 return VBaseOffset;
1369}
1370
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001371void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1372 // Just make sure we're in sync with TargetCXXABI.
1373 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1374
Rafael Espindolac3cde362013-12-09 14:51:17 +00001375 // The constructor used for constructing this as a base class;
1376 // ignores virtual bases.
1377 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1378
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001379 // The constructor used for constructing this as a complete class;
Nico Weber4c2ffb22015-01-07 05:25:05 +00001380 // constructs the virtual bases, then calls the base constructor.
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001381 if (!D->getParent()->isAbstract()) {
1382 // We don't need to emit the complete ctor if the class is abstract.
1383 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1384 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001385}
1386
George Burgess IVf203dbf2017-02-22 20:28:02 +00001387CGCXXABI::AddedStructorArgs
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001388ItaniumCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
1389 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +00001390 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001391
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001392 // All parameters are already in place except VTT, which goes after 'this'.
1393 // These are Clang types, so we don't need to worry about sret yet.
John McCall5d865c322010-08-31 07:33:07 +00001394
1395 // Check if we need to add a VTT parameter (which has type void **).
George Burgess IVf203dbf2017-02-22 20:28:02 +00001396 if (T == StructorType::Base && MD->getParent()->getNumVBases() != 0) {
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001397 ArgTys.insert(ArgTys.begin() + 1,
1398 Context.getPointerType(Context.VoidPtrTy));
George Burgess IVf203dbf2017-02-22 20:28:02 +00001399 return AddedStructorArgs::prefix(1);
1400 }
1401 return AddedStructorArgs{};
John McCall5d865c322010-08-31 07:33:07 +00001402}
1403
Reid Klecknere7de47e2013-07-22 13:51:44 +00001404void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
Rafael Espindolac3cde362013-12-09 14:51:17 +00001405 // The destructor used for destructing this as a base class; ignores
1406 // virtual bases.
1407 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001408
1409 // The destructor used for destructing this as a most-derived class;
1410 // call the base destructor and then destructs any virtual bases.
1411 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1412
Rafael Espindolac3cde362013-12-09 14:51:17 +00001413 // The destructor in a virtual table is always a 'deleting'
1414 // destructor, which calls the complete destructor and then uses the
1415 // appropriate operator delete.
1416 if (D->isVirtual())
1417 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001418}
1419
Reid Kleckner89077a12013-12-17 19:46:40 +00001420void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1421 QualType &ResTy,
1422 FunctionArgList &Params) {
John McCall5d865c322010-08-31 07:33:07 +00001423 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +00001424 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
John McCall5d865c322010-08-31 07:33:07 +00001425
1426 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001427 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +00001428 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001429
1430 // FIXME: avoid the fake decl
1431 QualType T = Context.getPointerType(Context.VoidPtrTy);
Alexey Bataev56223232017-06-09 13:40:18 +00001432 auto *VTTDecl = ImplicitParamDecl::Create(
1433 Context, /*DC=*/nullptr, MD->getLocation(), &Context.Idents.get("vtt"),
1434 T, ImplicitParamDecl::CXXVTT);
Reid Kleckner89077a12013-12-17 19:46:40 +00001435 Params.insert(Params.begin() + 1, VTTDecl);
Reid Kleckner2af6d732013-12-13 00:09:59 +00001436 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +00001437 }
1438}
1439
John McCall5d865c322010-08-31 07:33:07 +00001440void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
Justin Lebared4f1722016-07-27 22:04:24 +00001441 // Naked functions have no prolog.
1442 if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>())
1443 return;
1444
Reid Kleckner06239e42017-11-16 19:09:36 +00001445 /// Initialize the 'this' slot. In the Itanium C++ ABI, no prologue
1446 /// adjustments are required, becuase they are all handled by thunks.
1447 setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));
John McCall5d865c322010-08-31 07:33:07 +00001448
1449 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +00001450 if (getStructorImplicitParamDecl(CGF)) {
1451 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1452 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +00001453 }
John McCall5d865c322010-08-31 07:33:07 +00001454
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001455 /// If this is a function that the ABI specifies returns 'this', initialize
1456 /// the return slot to 'this' at the start of the function.
1457 ///
1458 /// Unlike the setting of return types, this is done within the ABI
1459 /// implementation instead of by clients of CGCXXABI because:
1460 /// 1) getThisValue is currently protected
1461 /// 2) in theory, an ABI could implement 'this' returns some other way;
1462 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +00001463 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +00001464 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +00001465}
1466
George Burgess IVf203dbf2017-02-22 20:28:02 +00001467CGCXXABI::AddedStructorArgs ItaniumCXXABI::addImplicitConstructorArgs(
Reid Kleckner89077a12013-12-17 19:46:40 +00001468 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1469 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1470 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
George Burgess IVf203dbf2017-02-22 20:28:02 +00001471 return AddedStructorArgs{};
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001472
Reid Kleckner89077a12013-12-17 19:46:40 +00001473 // Insert the implicit 'vtt' argument as the second argument.
1474 llvm::Value *VTT =
1475 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1476 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
Yaxun Liu5b330e82018-03-15 15:25:19 +00001477 Args.insert(Args.begin() + 1, CallArg(RValue::get(VTT), VTTTy));
George Burgess IVf203dbf2017-02-22 20:28:02 +00001478 return AddedStructorArgs::prefix(1); // Added one arg.
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001479}
1480
1481void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1482 const CXXDestructorDecl *DD,
1483 CXXDtorType Type, bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +00001484 bool Delegating, Address This) {
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001485 GlobalDecl GD(DD, Type);
1486 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1487 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1488
John McCallb92ab1a2016-10-26 23:46:34 +00001489 CGCallee Callee;
1490 if (getContext().getLangOpts().AppleKext &&
1491 Type != Dtor_Base && DD->isVirtual())
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001492 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
John McCallb92ab1a2016-10-26 23:46:34 +00001493 else
1494 Callee =
1495 CGCallee::forDirect(CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type)),
1496 DD);
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001497
John McCall7f416cc2015-09-08 08:05:57 +00001498 CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(),
Richard Smith762672a2016-09-28 19:09:10 +00001499 This.getPointer(), VTT, VTTTy,
1500 nullptr, nullptr);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001501}
1502
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001503void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1504 const CXXRecordDecl *RD) {
1505 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1506 if (VTable->hasInitializer())
1507 return;
1508
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001509 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001510 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1511 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
David Majnemerd905da42014-07-01 20:30:31 +00001512 llvm::Constant *RTTI =
1513 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001514
1515 // Create and set the initializer.
John McCall9c6cb762016-11-28 22:18:33 +00001516 ConstantInitBuilder Builder(CGM);
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001517 auto Components = Builder.beginStruct();
John McCall9c6cb762016-11-28 22:18:33 +00001518 CGVT.createVTableInitializer(Components, VTLayout, RTTI);
1519 Components.finishAndSetAsInitializer(VTable);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001520
1521 // Set the correct linkage.
1522 VTable->setLinkage(Linkage);
1523
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001524 if (CGM.supportsCOMDAT() && VTable->isWeakForLinker())
1525 VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName()));
Rafael Espindolacb92c192015-01-15 23:18:01 +00001526
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001527 // Set the right visibility.
Rafael Espindola699f5d62018-02-07 22:15:33 +00001528 CGM.setGVProperties(VTable, RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001529
Benjamin Kramer5d34a2b2014-09-10 12:50:59 +00001530 // Use pointer alignment for the vtable. Otherwise we would align them based
1531 // on the size of the initializer which doesn't make sense as only single
1532 // values are read.
1533 unsigned PAlign = CGM.getTarget().getPointerAlign(0);
1534 VTable->setAlignment(getContext().toCharUnitsFromBits(PAlign).getQuantity());
1535
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001536 // If this is the magic class __cxxabiv1::__fundamental_type_info,
1537 // we will emit the typeinfo for the fundamental types. This is the
1538 // same behaviour as GCC.
1539 const DeclContext *DC = RD->getDeclContext();
1540 if (RD->getIdentifier() &&
1541 RD->getIdentifier()->isStr("__fundamental_type_info") &&
1542 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1543 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1544 DC->getParent()->isTranslationUnit())
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00001545 EmitFundamentalRTTIDescriptors(RD->hasAttr<DLLExportAttr>());
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001546
Evgeniy Stepanov93987df2016-01-23 01:20:18 +00001547 if (!VTable->isDeclarationForLinker())
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001548 CGM.EmitVTableTypeMetadata(VTable, VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001549}
1550
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001551bool ItaniumCXXABI::isVirtualOffsetNeededForVTableField(
1552 CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
1553 if (Vptr.NearestVBase == nullptr)
1554 return false;
1555 return NeedsVTTParameter(CGF.CurGD);
Piotr Padlewski255652e2015-09-09 22:20:28 +00001556}
1557
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001558llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1559 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1560 const CXXRecordDecl *NearestVBase) {
1561
1562 if ((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1563 NeedsVTTParameter(CGF.CurGD)) {
1564 return getVTableAddressPointInStructorWithVTT(CGF, VTableClass, Base,
1565 NearestVBase);
1566 }
1567 return getVTableAddressPoint(Base, VTableClass);
1568}
1569
1570llvm::Constant *
1571ItaniumCXXABI::getVTableAddressPoint(BaseSubobject Base,
1572 const CXXRecordDecl *VTableClass) {
1573 llvm::GlobalValue *VTable = getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001574
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001575 // Find the appropriate vtable within the vtable group, and the address point
1576 // within that vtable.
1577 VTableLayout::AddressPointLocation AddressPoint =
1578 CGM.getItaniumVTableContext()
1579 .getVTableLayout(VTableClass)
1580 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001581 llvm::Value *Indices[] = {
Peter Collingbourne4e6a5402016-03-14 19:07:10 +00001582 llvm::ConstantInt::get(CGM.Int32Ty, 0),
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001583 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.VTableIndex),
1584 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.AddressPointIndex),
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001585 };
1586
Peter Collingbourne25a2b702016-12-13 20:50:44 +00001587 return llvm::ConstantExpr::getGetElementPtr(VTable->getValueType(), VTable,
1588 Indices, /*InBounds=*/true,
1589 /*InRangeIndex=*/1);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001590}
1591
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001592llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructorWithVTT(
1593 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1594 const CXXRecordDecl *NearestVBase) {
1595 assert((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1596 NeedsVTTParameter(CGF.CurGD) && "This class doesn't have VTT");
1597
1598 // Get the secondary vpointer index.
1599 uint64_t VirtualPointerIndex =
1600 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1601
1602 /// Load the VTT.
1603 llvm::Value *VTT = CGF.LoadCXXVTT();
1604 if (VirtualPointerIndex)
1605 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1606
1607 // And load the address point from the VTT.
1608 return CGF.Builder.CreateAlignedLoad(VTT, CGF.getPointerAlign());
1609}
1610
1611llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1612 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1613 return getVTableAddressPoint(Base, VTableClass);
1614}
1615
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001616llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1617 CharUnits VPtrOffset) {
1618 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1619
1620 llvm::GlobalVariable *&VTable = VTables[RD];
1621 if (VTable)
1622 return VTable;
1623
Eric Christopherd160c502016-01-29 01:35:53 +00001624 // Queue up this vtable for possible deferred emission.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001625 CGM.addDeferredVTable(RD);
1626
Yaron Kerene46f7ed2015-07-29 14:21:47 +00001627 SmallString<256> Name;
1628 llvm::raw_svector_ostream Out(Name);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001629 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001630
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001631 const VTableLayout &VTLayout =
1632 CGM.getItaniumVTableContext().getVTableLayout(RD);
1633 llvm::Type *VTableType = CGM.getVTables().getVTableType(VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001634
1635 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001636 Name, VTableType, llvm::GlobalValue::ExternalLinkage);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001637 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Hans Wennborgda24e9c2014-06-02 23:13:03 +00001638
Rafael Espindola922f2aa2018-02-23 19:30:48 +00001639 CGM.setGVProperties(VTable, RD);
1640
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001641 return VTable;
1642}
1643
John McCall9831b842018-02-06 18:52:44 +00001644CGCallee ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1645 GlobalDecl GD,
1646 Address This,
1647 llvm::Type *Ty,
1648 SourceLocation Loc) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001649 GD = GD.getCanonicalDecl();
1650 Ty = Ty->getPointerTo()->getPointerTo();
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001651 auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
1652 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty, MethodDecl->getParent());
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001653
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001654 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
John McCall9831b842018-02-06 18:52:44 +00001655 llvm::Value *VFunc;
1656 if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) {
1657 VFunc = CGF.EmitVTableTypeCheckedLoad(
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001658 MethodDecl->getParent(), VTable,
1659 VTableIndex * CGM.getContext().getTargetInfo().getPointerWidth(0) / 8);
John McCall9831b842018-02-06 18:52:44 +00001660 } else {
1661 CGF.EmitTypeMetadataCodeForVCall(MethodDecl->getParent(), VTable, Loc);
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001662
John McCall9831b842018-02-06 18:52:44 +00001663 llvm::Value *VFuncPtr =
1664 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1665 auto *VFuncLoad =
1666 CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign());
Piotr Padlewski77cc9622016-10-29 15:28:30 +00001667
John McCall9831b842018-02-06 18:52:44 +00001668 // Add !invariant.load md to virtual function load to indicate that
1669 // function didn't change inside vtable.
1670 // It's safe to add it without -fstrict-vtable-pointers, but it would not
1671 // help in devirtualization because it will only matter if we will have 2
1672 // the same virtual function loads from the same vtable load, which won't
1673 // happen without enabled devirtualization with -fstrict-vtable-pointers.
1674 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1675 CGM.getCodeGenOpts().StrictVTablePointers)
1676 VFuncLoad->setMetadata(
1677 llvm::LLVMContext::MD_invariant_load,
1678 llvm::MDNode::get(CGM.getLLVMContext(),
1679 llvm::ArrayRef<llvm::Metadata *>()));
1680 VFunc = VFuncLoad;
1681 }
John McCallb92ab1a2016-10-26 23:46:34 +00001682
John McCall9831b842018-02-06 18:52:44 +00001683 CGCallee Callee(MethodDecl, VFunc);
1684 return Callee;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001685}
1686
David Majnemer0c0b6d92014-10-31 20:09:12 +00001687llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
1688 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
John McCall7f416cc2015-09-08 08:05:57 +00001689 Address This, const CXXMemberCallExpr *CE) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001690 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001691 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1692
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001693 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1694 Dtor, getFromDtorType(DtorType));
George Burgess IV00f70bd2018-03-01 05:43:23 +00001695 llvm::FunctionType *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
John McCallb92ab1a2016-10-26 23:46:34 +00001696 CGCallee Callee =
Peter Collingbourneea211002018-02-05 23:09:13 +00001697 CGCallee::forVirtual(CE, GlobalDecl(Dtor, DtorType), This, Ty);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001698
John McCall7f416cc2015-09-08 08:05:57 +00001699 CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(),
1700 This.getPointer(), /*ImplicitParam=*/nullptr,
Richard Smith762672a2016-09-28 19:09:10 +00001701 QualType(), CE, nullptr);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001702 return nullptr;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001703}
1704
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001705void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001706 CodeGenVTables &VTables = CGM.getVTables();
1707 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001708 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001709}
1710
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001711bool ItaniumCXXABI::canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const {
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001712 // We don't emit available_externally vtables if we are in -fapple-kext mode
1713 // because kext mode does not permit devirtualization.
1714 if (CGM.getLangOpts().AppleKext)
1715 return false;
1716
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00001717 // If we don't have any not emitted inline virtual function, and if vtable is
1718 // not hidden, then we are safe to emit available_externally copy of vtable.
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001719 // FIXME we can still emit a copy of the vtable if we
1720 // can emit definition of the inline functions.
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00001721 return !hasAnyUnusedVirtualInlineFunction(RD) && !isVTableHidden(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001722}
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001723static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001724 Address InitialPtr,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001725 int64_t NonVirtualAdjustment,
1726 int64_t VirtualAdjustment,
1727 bool IsReturnAdjustment) {
1728 if (!NonVirtualAdjustment && !VirtualAdjustment)
John McCall7f416cc2015-09-08 08:05:57 +00001729 return InitialPtr.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001730
John McCall7f416cc2015-09-08 08:05:57 +00001731 Address V = CGF.Builder.CreateElementBitCast(InitialPtr, CGF.Int8Ty);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001732
John McCall7f416cc2015-09-08 08:05:57 +00001733 // In a base-to-derived cast, the non-virtual adjustment is applied first.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001734 if (NonVirtualAdjustment && !IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001735 V = CGF.Builder.CreateConstInBoundsByteGEP(V,
1736 CharUnits::fromQuantity(NonVirtualAdjustment));
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001737 }
1738
John McCall7f416cc2015-09-08 08:05:57 +00001739 // Perform the virtual adjustment if we have one.
1740 llvm::Value *ResultPtr;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001741 if (VirtualAdjustment) {
1742 llvm::Type *PtrDiffTy =
1743 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1744
John McCall7f416cc2015-09-08 08:05:57 +00001745 Address VTablePtrPtr = CGF.Builder.CreateElementBitCast(V, CGF.Int8PtrTy);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001746 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1747
1748 llvm::Value *OffsetPtr =
1749 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1750
1751 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1752
1753 // Load the adjustment offset from the vtable.
John McCall7f416cc2015-09-08 08:05:57 +00001754 llvm::Value *Offset =
1755 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001756
1757 // Adjust our pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001758 ResultPtr = CGF.Builder.CreateInBoundsGEP(V.getPointer(), Offset);
1759 } else {
1760 ResultPtr = V.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001761 }
1762
John McCall7f416cc2015-09-08 08:05:57 +00001763 // In a derived-to-base conversion, the non-virtual adjustment is
1764 // applied second.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001765 if (NonVirtualAdjustment && IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001766 ResultPtr = CGF.Builder.CreateConstInBoundsGEP1_64(ResultPtr,
1767 NonVirtualAdjustment);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001768 }
1769
1770 // Cast back to the original type.
John McCall7f416cc2015-09-08 08:05:57 +00001771 return CGF.Builder.CreateBitCast(ResultPtr, InitialPtr.getType());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001772}
1773
1774llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001775 Address This,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001776 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001777 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1778 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001779 /*IsReturnAdjustment=*/false);
1780}
1781
1782llvm::Value *
John McCall7f416cc2015-09-08 08:05:57 +00001783ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001784 const ReturnAdjustment &RA) {
1785 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1786 RA.Virtual.Itanium.VBaseOffsetOffset,
1787 /*IsReturnAdjustment=*/true);
1788}
1789
John McCall5d865c322010-08-31 07:33:07 +00001790void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1791 RValue RV, QualType ResultType) {
1792 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1793 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1794
1795 // Destructor thunks in the ARM ABI have indeterminate results.
John McCall7f416cc2015-09-08 08:05:57 +00001796 llvm::Type *T = CGF.ReturnValue.getElementType();
John McCall5d865c322010-08-31 07:33:07 +00001797 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1798 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1799}
John McCall8ed55a52010-09-02 09:58:18 +00001800
1801/************************** Array allocation cookies **************************/
1802
John McCallb91cd662012-05-01 05:23:51 +00001803CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1804 // The array cookie is a size_t; pad that up to the element alignment.
1805 // The cookie is actually right-justified in that space.
1806 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1807 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001808}
1809
John McCall7f416cc2015-09-08 08:05:57 +00001810Address ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1811 Address NewPtr,
1812 llvm::Value *NumElements,
1813 const CXXNewExpr *expr,
1814 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001815 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001816
John McCall7f416cc2015-09-08 08:05:57 +00001817 unsigned AS = NewPtr.getAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001818
John McCall9bca9232010-09-02 10:25:57 +00001819 ASTContext &Ctx = getContext();
John McCall7f416cc2015-09-08 08:05:57 +00001820 CharUnits SizeSize = CGF.getSizeSize();
John McCall8ed55a52010-09-02 09:58:18 +00001821
1822 // The size of the cookie.
1823 CharUnits CookieSize =
1824 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001825 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001826
1827 // Compute an offset to the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001828 Address CookiePtr = NewPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001829 CharUnits CookieOffset = CookieSize - SizeSize;
1830 if (!CookieOffset.isZero())
John McCall7f416cc2015-09-08 08:05:57 +00001831 CookiePtr = CGF.Builder.CreateConstInBoundsByteGEP(CookiePtr, CookieOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001832
1833 // Write the number of elements into the appropriate slot.
John McCall7f416cc2015-09-08 08:05:57 +00001834 Address NumElementsPtr =
1835 CGF.Builder.CreateElementBitCast(CookiePtr, CGF.SizeTy);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001836 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
John McCall7f416cc2015-09-08 08:05:57 +00001837
1838 // Handle the array cookie specially in ASan.
Filipe Cabecinhas6f83fa92018-01-02 13:46:12 +00001839 if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 &&
Filipe Cabecinhas4ba58172018-02-12 11:49:02 +00001840 (expr->getOperatorNew()->isReplaceableGlobalAllocationFunction() ||
1841 CGM.getCodeGenOpts().SanitizeAddressPoisonClassMemberArrayNewCookie)) {
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001842 // The store to the CookiePtr does not need to be instrumented.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001843 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
1844 llvm::FunctionType *FTy =
John McCall7f416cc2015-09-08 08:05:57 +00001845 llvm::FunctionType::get(CGM.VoidTy, NumElementsPtr.getType(), false);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001846 llvm::Constant *F =
1847 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001848 CGF.Builder.CreateCall(F, NumElementsPtr.getPointer());
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001849 }
John McCall8ed55a52010-09-02 09:58:18 +00001850
1851 // Finally, compute a pointer to the actual data buffer by skipping
1852 // over the cookie completely.
John McCall7f416cc2015-09-08 08:05:57 +00001853 return CGF.Builder.CreateConstInBoundsByteGEP(NewPtr, CookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001854}
1855
John McCallb91cd662012-05-01 05:23:51 +00001856llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001857 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00001858 CharUnits cookieSize) {
1859 // The element size is right-justified in the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001860 Address numElementsPtr = allocPtr;
1861 CharUnits numElementsOffset = cookieSize - CGF.getSizeSize();
John McCallb91cd662012-05-01 05:23:51 +00001862 if (!numElementsOffset.isZero())
1863 numElementsPtr =
John McCall7f416cc2015-09-08 08:05:57 +00001864 CGF.Builder.CreateConstInBoundsByteGEP(numElementsPtr, numElementsOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001865
John McCall7f416cc2015-09-08 08:05:57 +00001866 unsigned AS = allocPtr.getAddressSpace();
1867 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001868 if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0)
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001869 return CGF.Builder.CreateLoad(numElementsPtr);
1870 // In asan mode emit a function call instead of a regular load and let the
1871 // run-time deal with it: if the shadow is properly poisoned return the
1872 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
1873 // We can't simply ignore this load using nosanitize metadata because
1874 // the metadata may be lost.
1875 llvm::FunctionType *FTy =
1876 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
1877 llvm::Constant *F =
1878 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001879 return CGF.Builder.CreateCall(F, numElementsPtr.getPointer());
John McCall8ed55a52010-09-02 09:58:18 +00001880}
1881
John McCallb91cd662012-05-01 05:23:51 +00001882CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001883 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001884 // struct array_cookie {
1885 // std::size_t element_size; // element_size != 0
1886 // std::size_t element_count;
1887 // };
John McCallc19c7062013-01-25 23:36:19 +00001888 // But the base ABI doesn't give anything an alignment greater than
1889 // 8, so we can dismiss this as typical ABI-author blindness to
1890 // actual language complexity and round up to the element alignment.
1891 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1892 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001893}
1894
John McCall7f416cc2015-09-08 08:05:57 +00001895Address ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1896 Address newPtr,
1897 llvm::Value *numElements,
1898 const CXXNewExpr *expr,
1899 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001900 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001901
John McCall8ed55a52010-09-02 09:58:18 +00001902 // The cookie is always at the start of the buffer.
John McCall7f416cc2015-09-08 08:05:57 +00001903 Address cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001904
1905 // The first element is the element size.
John McCall7f416cc2015-09-08 08:05:57 +00001906 cookie = CGF.Builder.CreateElementBitCast(cookie, CGF.SizeTy);
John McCallc19c7062013-01-25 23:36:19 +00001907 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1908 getContext().getTypeSizeInChars(elementType).getQuantity());
1909 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001910
1911 // The second element is the element count.
John McCall7f416cc2015-09-08 08:05:57 +00001912 cookie = CGF.Builder.CreateConstInBoundsGEP(cookie, 1, CGF.getSizeSize());
John McCallc19c7062013-01-25 23:36:19 +00001913 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001914
1915 // Finally, compute a pointer to the actual data buffer by skipping
1916 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001917 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
John McCall7f416cc2015-09-08 08:05:57 +00001918 return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001919}
1920
John McCallb91cd662012-05-01 05:23:51 +00001921llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001922 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00001923 CharUnits cookieSize) {
1924 // The number of elements is at offset sizeof(size_t) relative to
1925 // the allocated pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001926 Address numElementsPtr
1927 = CGF.Builder.CreateConstInBoundsByteGEP(allocPtr, CGF.getSizeSize());
John McCall8ed55a52010-09-02 09:58:18 +00001928
John McCall7f416cc2015-09-08 08:05:57 +00001929 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
John McCallb91cd662012-05-01 05:23:51 +00001930 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001931}
1932
John McCall68ff0372010-09-08 01:44:27 +00001933/*********************** Static local initialization **************************/
1934
1935static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001936 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001937 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001938 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001939 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001940 GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00001941 return CGM.CreateRuntimeFunction(
1942 FTy, "__cxa_guard_acquire",
1943 llvm::AttributeList::get(CGM.getLLVMContext(),
1944 llvm::AttributeList::FunctionIndex,
1945 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001946}
1947
1948static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001949 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001950 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001951 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001952 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00001953 return CGM.CreateRuntimeFunction(
1954 FTy, "__cxa_guard_release",
1955 llvm::AttributeList::get(CGM.getLLVMContext(),
1956 llvm::AttributeList::FunctionIndex,
1957 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001958}
1959
1960static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001961 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001962 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001963 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001964 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00001965 return CGM.CreateRuntimeFunction(
1966 FTy, "__cxa_guard_abort",
1967 llvm::AttributeList::get(CGM.getLLVMContext(),
1968 llvm::AttributeList::FunctionIndex,
1969 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001970}
1971
1972namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001973 struct CallGuardAbort final : EHScopeStack::Cleanup {
John McCall68ff0372010-09-08 01:44:27 +00001974 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001975 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001976
Craig Topper4f12f102014-03-12 06:41:41 +00001977 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00001978 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1979 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001980 }
1981 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001982}
John McCall68ff0372010-09-08 01:44:27 +00001983
1984/// The ARM code here follows the Itanium code closely enough that we
1985/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001986void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1987 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001988 llvm::GlobalVariable *var,
1989 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00001990 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00001991
Richard Smith62f19e72016-06-25 00:15:56 +00001992 // Inline variables that weren't instantiated from variable templates have
1993 // partially-ordered initialization within their translation unit.
1994 bool NonTemplateInline =
1995 D.isInline() &&
1996 !isTemplateInstantiation(D.getTemplateSpecializationKind());
1997
1998 // We only need to use thread-safe statics for local non-TLS variables and
1999 // inline variables; other global initialization is always single-threaded
2000 // or (through lazy dynamic loading in multiple threads) unsequenced.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002001 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
Richard Smith62f19e72016-06-25 00:15:56 +00002002 (D.isLocalVarDecl() || NonTemplateInline) &&
2003 !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00002004
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00002005 // If we have a global variable with internal linkage and thread-safe statics
2006 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00002007 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
2008
2009 llvm::IntegerType *guardTy;
John McCall7f416cc2015-09-08 08:05:57 +00002010 CharUnits guardAlignment;
John McCall5aa52592011-06-17 07:33:57 +00002011 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00002012 guardTy = CGF.Int8Ty;
John McCall7f416cc2015-09-08 08:05:57 +00002013 guardAlignment = CharUnits::One();
John McCall5aa52592011-06-17 07:33:57 +00002014 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00002015 // Guard variables are 64 bits in the generic ABI and size width on ARM
2016 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
John McCall7f416cc2015-09-08 08:05:57 +00002017 if (UseARMGuardVarABI) {
2018 guardTy = CGF.SizeTy;
2019 guardAlignment = CGF.getSizeAlign();
2020 } else {
2021 guardTy = CGF.Int64Ty;
2022 guardAlignment = CharUnits::fromQuantity(
2023 CGM.getDataLayout().getABITypeAlignment(guardTy));
2024 }
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00002025 }
John McCallb88a5662012-03-30 21:00:39 +00002026 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00002027
John McCallb88a5662012-03-30 21:00:39 +00002028 // Create the guard variable if we don't already have it (as we
2029 // might if we're double-emitting this function body).
2030 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
2031 if (!guard) {
2032 // Mangle the name for the guard.
2033 SmallString<256> guardName;
2034 {
2035 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00002036 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00002037 }
John McCall8e7cb6d2010-11-02 21:04:24 +00002038
John McCallb88a5662012-03-30 21:00:39 +00002039 // Create the guard variable with a zero-initializer.
2040 // Just absorb linkage and visibility from the guarded variable.
2041 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
2042 false, var->getLinkage(),
2043 llvm::ConstantInt::get(guardTy, 0),
2044 guardName.str());
Rafael Espindola699f5d62018-02-07 22:15:33 +00002045 guard->setDSOLocal(var->isDSOLocal());
John McCallb88a5662012-03-30 21:00:39 +00002046 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00002047 // If the variable is thread-local, so is its guard variable.
2048 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCall7f416cc2015-09-08 08:05:57 +00002049 guard->setAlignment(guardAlignment.getQuantity());
John McCallb88a5662012-03-30 21:00:39 +00002050
Yaron Keren5bfa1082015-09-03 20:33:29 +00002051 // The ABI says: "It is suggested that it be emitted in the same COMDAT
2052 // group as the associated data object." In practice, this doesn't work for
Dan Gohman839f2152017-01-17 21:46:38 +00002053 // non-ELF and non-Wasm object formats, so only do it for ELF and Wasm.
Rafael Espindola0d4fb982015-01-12 22:13:53 +00002054 llvm::Comdat *C = var->getComdat();
Yaron Keren5bfa1082015-09-03 20:33:29 +00002055 if (!D.isLocalVarDecl() && C &&
Dan Gohman839f2152017-01-17 21:46:38 +00002056 (CGM.getTarget().getTriple().isOSBinFormatELF() ||
2057 CGM.getTarget().getTriple().isOSBinFormatWasm())) {
Rafael Espindola2ae4b632014-09-19 19:43:18 +00002058 guard->setComdat(C);
Richard Smith62f19e72016-06-25 00:15:56 +00002059 // An inline variable's guard function is run from the per-TU
2060 // initialization function, not via a dedicated global ctor function, so
2061 // we can't put it in a comdat.
2062 if (!NonTemplateInline)
2063 CGF.CurFn->setComdat(C);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00002064 } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) {
2065 guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName()));
Rafael Espindola2ae4b632014-09-19 19:43:18 +00002066 }
2067
John McCallb88a5662012-03-30 21:00:39 +00002068 CGM.setStaticLocalDeclGuardAddress(&D, guard);
2069 }
John McCall87590e62012-03-30 07:09:50 +00002070
John McCall7f416cc2015-09-08 08:05:57 +00002071 Address guardAddr = Address(guard, guardAlignment);
2072
John McCall68ff0372010-09-08 01:44:27 +00002073 // Test whether the variable has completed initialization.
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002074 //
John McCall68ff0372010-09-08 01:44:27 +00002075 // Itanium C++ ABI 3.3.2:
2076 // The following is pseudo-code showing how these functions can be used:
2077 // if (obj_guard.first_byte == 0) {
2078 // if ( __cxa_guard_acquire (&obj_guard) ) {
2079 // try {
2080 // ... initialize the object ...;
2081 // } catch (...) {
2082 // __cxa_guard_abort (&obj_guard);
2083 // throw;
2084 // }
2085 // ... queue object destructor with __cxa_atexit() ...;
2086 // __cxa_guard_release (&obj_guard);
2087 // }
2088 // }
Tim Northovera2ee4332014-03-29 15:09:45 +00002089
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002090 // Load the first byte of the guard variable.
2091 llvm::LoadInst *LI =
John McCall7f416cc2015-09-08 08:05:57 +00002092 Builder.CreateLoad(Builder.CreateElementBitCast(guardAddr, CGM.Int8Ty));
John McCall68ff0372010-09-08 01:44:27 +00002093
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002094 // Itanium ABI:
2095 // An implementation supporting thread-safety on multiprocessor
2096 // systems must also guarantee that references to the initialized
2097 // object do not occur before the load of the initialization flag.
2098 //
2099 // In LLVM, we do this by marking the load Acquire.
2100 if (threadsafe)
JF Bastien92f4ef12016-04-06 17:26:42 +00002101 LI->setAtomic(llvm::AtomicOrdering::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00002102
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002103 // For ARM, we should only check the first bit, rather than the entire byte:
2104 //
2105 // ARM C++ ABI 3.2.3.1:
2106 // To support the potential use of initialization guard variables
2107 // as semaphores that are the target of ARM SWP and LDREX/STREX
2108 // synchronizing instructions we define a static initialization
2109 // guard variable to be a 4-byte aligned, 4-byte word with the
2110 // following inline access protocol.
2111 // #define INITIALIZED 1
2112 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
2113 // if (__cxa_guard_acquire(&obj_guard))
2114 // ...
2115 // }
2116 //
2117 // and similarly for ARM64:
2118 //
2119 // ARM64 C++ ABI 3.2.2:
2120 // This ABI instead only specifies the value bit 0 of the static guard
2121 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
2122 // variable is not initialized and 1 when it is.
2123 llvm::Value *V =
2124 (UseARMGuardVarABI && !useInt8GuardVariable)
2125 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
2126 : LI;
Richard Smithae8d62c2017-07-26 22:01:09 +00002127 llvm::Value *NeedsInit = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00002128
2129 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
2130 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2131
2132 // Check if the first byte of the guard variable is zero.
Richard Smithae8d62c2017-07-26 22:01:09 +00002133 CGF.EmitCXXGuardedInitBranch(NeedsInit, InitCheckBlock, EndBlock,
2134 CodeGenFunction::GuardKind::VariableGuard, &D);
John McCall68ff0372010-09-08 01:44:27 +00002135
2136 CGF.EmitBlock(InitCheckBlock);
2137
2138 // Variables used when coping with thread-safe statics and exceptions.
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002139 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002140 // Call __cxa_guard_acquire.
2141 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00002142 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002143
John McCall68ff0372010-09-08 01:44:27 +00002144 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002145
John McCall68ff0372010-09-08 01:44:27 +00002146 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
2147 InitBlock, EndBlock);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002148
John McCall68ff0372010-09-08 01:44:27 +00002149 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00002150 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002151
John McCall68ff0372010-09-08 01:44:27 +00002152 CGF.EmitBlock(InitBlock);
2153 }
2154
2155 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00002156 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00002157
John McCall5aa52592011-06-17 07:33:57 +00002158 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002159 // Pop the guard-abort cleanup if we pushed one.
2160 CGF.PopCleanupBlock();
2161
2162 // Call __cxa_guard_release. This cannot throw.
John McCall7f416cc2015-09-08 08:05:57 +00002163 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy),
2164 guardAddr.getPointer());
John McCall68ff0372010-09-08 01:44:27 +00002165 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002166 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guardAddr);
John McCall68ff0372010-09-08 01:44:27 +00002167 }
2168
2169 CGF.EmitBlock(EndBlock);
2170}
John McCallc84ed6a2012-05-01 06:13:13 +00002171
2172/// Register a global destructor using __cxa_atexit.
2173static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
2174 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00002175 llvm::Constant *addr,
2176 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00002177 const char *Name = "__cxa_atexit";
2178 if (TLS) {
2179 const llvm::Triple &T = CGF.getTarget().getTriple();
Manman Renf93fff22015-11-11 23:08:18 +00002180 Name = T.isOSDarwin() ? "_tlv_atexit" : "__cxa_thread_atexit";
Bill Wendling95cae882013-05-02 19:18:03 +00002181 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00002182
John McCallc84ed6a2012-05-01 06:13:13 +00002183 // We're assuming that the destructor function is something we can
2184 // reasonably call with the default CC. Go ahead and cast it to the
2185 // right prototype.
2186 llvm::Type *dtorTy =
2187 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
2188
2189 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
2190 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
2191 llvm::FunctionType *atexitTy =
2192 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
2193
2194 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002195 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00002196 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
2197 fn->setDoesNotThrow();
2198
2199 // Create a variable that binds the atexit to this shared object.
2200 llvm::Constant *handle =
Reid Kleckner9de92142017-02-13 18:49:21 +00002201 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
2202 auto *GV = cast<llvm::GlobalValue>(handle->stripPointerCasts());
2203 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
John McCallc84ed6a2012-05-01 06:13:13 +00002204
2205 llvm::Value *args[] = {
2206 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
2207 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
2208 handle
2209 };
John McCall882987f2013-02-28 19:01:20 +00002210 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00002211}
2212
2213/// Register a global destructor as best as we know how.
2214void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00002215 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00002216 llvm::Constant *dtor,
2217 llvm::Constant *addr) {
2218 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002219 if (CGM.getCodeGenOpts().CXAAtExit)
2220 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
2221
2222 if (D.getTLSKind())
2223 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00002224
2225 // In Apple kexts, we want to add a global destructor entry.
2226 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00002227 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00002228 // Generate a global destructor entry.
2229 return CGM.AddCXXDtorEntry(dtor, addr);
2230 }
2231
David Blaikieebe87e12013-08-27 23:57:18 +00002232 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00002233}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002234
David Majnemer9b21c332014-07-11 20:28:10 +00002235static bool isThreadWrapperReplaceable(const VarDecl *VD,
2236 CodeGen::CodeGenModule &CGM) {
2237 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
Manman Renf93fff22015-11-11 23:08:18 +00002238 // Darwin prefers to have references to thread local variables to go through
David Majnemer9b21c332014-07-11 20:28:10 +00002239 // the thread wrapper instead of directly referencing the backing variable.
2240 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
Manman Renf93fff22015-11-11 23:08:18 +00002241 CGM.getTarget().getTriple().isOSDarwin();
David Majnemer9b21c332014-07-11 20:28:10 +00002242}
2243
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002244/// Get the appropriate linkage for the wrapper function. This is essentially
David Majnemer4632e1e2014-06-27 16:56:27 +00002245/// the weak form of the variable's linkage; every translation unit which needs
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002246/// the wrapper emits a copy, and we want the linker to merge them.
David Majnemer35ab3282014-06-11 04:08:55 +00002247static llvm::GlobalValue::LinkageTypes
2248getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
2249 llvm::GlobalValue::LinkageTypes VarLinkage =
2250 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
2251
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002252 // For internal linkage variables, we don't need an external or weak wrapper.
2253 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
2254 return VarLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00002255
David Majnemer9b21c332014-07-11 20:28:10 +00002256 // If the thread wrapper is replaceable, give it appropriate linkage.
Manman Ren68150262015-11-11 22:42:31 +00002257 if (isThreadWrapperReplaceable(VD, CGM))
2258 if (!llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) &&
2259 !llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
2260 return VarLinkage;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002261 return llvm::GlobalValue::WeakODRLinkage;
2262}
2263
2264llvm::Function *
2265ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +00002266 llvm::Value *Val) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002267 // Mangle the name for the thread_local wrapper function.
2268 SmallString<256> WrapperName;
2269 {
2270 llvm::raw_svector_ostream Out(WrapperName);
2271 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002272 }
2273
Akira Hatanaka26907f92016-01-15 03:34:06 +00002274 // FIXME: If VD is a definition, we should regenerate the function attributes
2275 // before returning.
Alexander Musmanf94c3182014-09-26 06:28:25 +00002276 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002277 return cast<llvm::Function>(V);
2278
Akira Hatanaka26907f92016-01-15 03:34:06 +00002279 QualType RetQT = VD->getType();
2280 if (RetQT->isReferenceType())
2281 RetQT = RetQT.getNonReferenceType();
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002282
John McCallc56a8b32016-03-11 04:30:31 +00002283 const CGFunctionInfo &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2284 getContext().getPointerType(RetQT), FunctionArgList());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002285
2286 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FI);
David Majnemer35ab3282014-06-11 04:08:55 +00002287 llvm::Function *Wrapper =
2288 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
2289 WrapperName.str(), &CGM.getModule());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002290
2291 CGM.SetLLVMFunctionAttributes(nullptr, FI, Wrapper);
2292
2293 if (VD->hasDefinition())
2294 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Wrapper);
2295
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002296 // Always resolve references to the wrapper at link time.
Manman Ren68150262015-11-11 22:42:31 +00002297 if (!Wrapper->hasLocalLinkage() && !(isThreadWrapperReplaceable(VD, CGM) &&
2298 !llvm::GlobalVariable::isLinkOnceLinkage(Wrapper->getLinkage()) &&
2299 !llvm::GlobalVariable::isWeakODRLinkage(Wrapper->getLinkage())))
Duncan P. N. Exon Smith4434d362014-05-07 22:36:11 +00002300 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
Manman Renb0b3af72015-12-17 00:42:36 +00002301
2302 if (isThreadWrapperReplaceable(VD, CGM)) {
2303 Wrapper->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2304 Wrapper->addFnAttr(llvm::Attribute::NoUnwind);
2305 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002306 return Wrapper;
2307}
2308
2309void ItaniumCXXABI::EmitThreadLocalInitFuncs(
Richard Smith5a99c492015-12-01 01:10:48 +00002310 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
2311 ArrayRef<llvm::Function *> CXXThreadLocalInits,
2312 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
David Majnemerb3341ea2014-10-05 05:05:40 +00002313 llvm::Function *InitFunc = nullptr;
Richard Smithfbe23692017-01-13 00:43:31 +00002314
2315 // Separate initializers into those with ordered (or partially-ordered)
2316 // initialization and those with unordered initialization.
2317 llvm::SmallVector<llvm::Function *, 8> OrderedInits;
2318 llvm::SmallDenseMap<const VarDecl *, llvm::Function *> UnorderedInits;
2319 for (unsigned I = 0; I != CXXThreadLocalInits.size(); ++I) {
2320 if (isTemplateInstantiation(
2321 CXXThreadLocalInitVars[I]->getTemplateSpecializationKind()))
2322 UnorderedInits[CXXThreadLocalInitVars[I]->getCanonicalDecl()] =
2323 CXXThreadLocalInits[I];
2324 else
2325 OrderedInits.push_back(CXXThreadLocalInits[I]);
2326 }
2327
2328 if (!OrderedInits.empty()) {
David Majnemerb3341ea2014-10-05 05:05:40 +00002329 // Generate a guarded initialization function.
2330 llvm::FunctionType *FTy =
2331 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002332 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2333 InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init", FI,
Alexey Samsonov1444bb92014-10-17 00:20:19 +00002334 SourceLocation(),
David Majnemerb3341ea2014-10-05 05:05:40 +00002335 /*TLS=*/true);
2336 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
2337 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
2338 llvm::GlobalVariable::InternalLinkage,
2339 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
2340 Guard->setThreadLocal(true);
John McCall7f416cc2015-09-08 08:05:57 +00002341
2342 CharUnits GuardAlign = CharUnits::One();
2343 Guard->setAlignment(GuardAlign.getQuantity());
2344
Richard Smithfbe23692017-01-13 00:43:31 +00002345 CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(InitFunc, OrderedInits,
2346 Address(Guard, GuardAlign));
Manman Ren5e5d0462016-03-18 23:35:21 +00002347 // On Darwin platforms, use CXX_FAST_TLS calling convention.
2348 if (CGM.getTarget().getTriple().isOSDarwin()) {
2349 InitFunc->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2350 InitFunc->addFnAttr(llvm::Attribute::NoUnwind);
2351 }
David Majnemerb3341ea2014-10-05 05:05:40 +00002352 }
Richard Smithfbe23692017-01-13 00:43:31 +00002353
2354 // Emit thread wrappers.
Richard Smith5a99c492015-12-01 01:10:48 +00002355 for (const VarDecl *VD : CXXThreadLocals) {
2356 llvm::GlobalVariable *Var =
2357 cast<llvm::GlobalVariable>(CGM.GetGlobalValue(CGM.getMangledName(VD)));
Richard Smithfbe23692017-01-13 00:43:31 +00002358 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002359
David Majnemer9b21c332014-07-11 20:28:10 +00002360 // Some targets require that all access to thread local variables go through
2361 // the thread wrapper. This means that we cannot attempt to create a thread
2362 // wrapper or a thread helper.
Richard Smithfbe23692017-01-13 00:43:31 +00002363 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition()) {
2364 Wrapper->setLinkage(llvm::Function::ExternalLinkage);
David Majnemer9b21c332014-07-11 20:28:10 +00002365 continue;
Richard Smithfbe23692017-01-13 00:43:31 +00002366 }
David Majnemer9b21c332014-07-11 20:28:10 +00002367
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002368 // Mangle the name for the thread_local initialization function.
2369 SmallString<256> InitFnName;
2370 {
2371 llvm::raw_svector_ostream Out(InitFnName);
2372 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002373 }
2374
2375 // If we have a definition for the variable, emit the initialization
2376 // function as an alias to the global Init function (if any). Otherwise,
2377 // produce a declaration of the initialization function.
Craig Topper8a13c412014-05-21 05:09:00 +00002378 llvm::GlobalValue *Init = nullptr;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002379 bool InitIsInitFunc = false;
2380 if (VD->hasDefinition()) {
2381 InitIsInitFunc = true;
Richard Smithfbe23692017-01-13 00:43:31 +00002382 llvm::Function *InitFuncToUse = InitFunc;
2383 if (isTemplateInstantiation(VD->getTemplateSpecializationKind()))
2384 InitFuncToUse = UnorderedInits.lookup(VD->getCanonicalDecl());
2385 if (InitFuncToUse)
Rafael Espindola234405b2014-05-17 21:30:14 +00002386 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
Richard Smithfbe23692017-01-13 00:43:31 +00002387 InitFuncToUse);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002388 } else {
2389 // Emit a weak global function referring to the initialization function.
2390 // This function will not exist if the TU defining the thread_local
2391 // variable in question does not need any dynamic initialization for
2392 // its thread_local variables.
2393 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
Richard Smithfbe23692017-01-13 00:43:31 +00002394 Init = llvm::Function::Create(FnTy,
2395 llvm::GlobalVariable::ExternalWeakLinkage,
2396 InitFnName.str(), &CGM.getModule());
John McCallc56a8b32016-03-11 04:30:31 +00002397 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
Akira Hatanaka26907f92016-01-15 03:34:06 +00002398 CGM.SetLLVMFunctionAttributes(nullptr, FI, cast<llvm::Function>(Init));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002399 }
2400
Rafael Espindolaabdb3222018-03-07 23:18:06 +00002401 if (Init) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002402 Init->setVisibility(Var->getVisibility());
Rafael Espindolaabdb3222018-03-07 23:18:06 +00002403 Init->setDSOLocal(Var->isDSOLocal());
2404 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002405
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002406 llvm::LLVMContext &Context = CGM.getModule().getContext();
2407 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
John McCall7f416cc2015-09-08 08:05:57 +00002408 CGBuilderTy Builder(CGM, Entry);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002409 if (InitIsInitFunc) {
Manman Ren5e5d0462016-03-18 23:35:21 +00002410 if (Init) {
2411 llvm::CallInst *CallVal = Builder.CreateCall(Init);
2412 if (isThreadWrapperReplaceable(VD, CGM))
2413 CallVal->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2414 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002415 } else {
2416 // Don't know whether we have an init function. Call it if it exists.
2417 llvm::Value *Have = Builder.CreateIsNotNull(Init);
2418 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2419 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2420 Builder.CreateCondBr(Have, InitBB, ExitBB);
2421
2422 Builder.SetInsertPoint(InitBB);
David Blaikie4ba525b2015-07-14 17:27:39 +00002423 Builder.CreateCall(Init);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002424 Builder.CreateBr(ExitBB);
2425
2426 Builder.SetInsertPoint(ExitBB);
2427 }
2428
2429 // For a reference, the result of the wrapper function is a pointer to
2430 // the referenced object.
2431 llvm::Value *Val = Var;
2432 if (VD->getType()->isReferenceType()) {
John McCall7f416cc2015-09-08 08:05:57 +00002433 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2434 Val = Builder.CreateAlignedLoad(Val, Align);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002435 }
Alexander Musmanf94c3182014-09-26 06:28:25 +00002436 if (Val->getType() != Wrapper->getReturnType())
2437 Val = Builder.CreatePointerBitCastOrAddrSpaceCast(
2438 Val, Wrapper->getReturnType(), "");
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002439 Builder.CreateRet(Val);
2440 }
2441}
2442
Richard Smith0f383742014-03-26 22:48:22 +00002443LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2444 const VarDecl *VD,
2445 QualType LValType) {
Richard Smith5a99c492015-12-01 01:10:48 +00002446 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD);
Alexander Musmanf94c3182014-09-26 06:28:25 +00002447 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002448
Manman Renb0b3af72015-12-17 00:42:36 +00002449 llvm::CallInst *CallVal = CGF.Builder.CreateCall(Wrapper);
Saleem Abdulrasool4a7130a2016-08-01 21:31:24 +00002450 CallVal->setCallingConv(Wrapper->getCallingConv());
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002451
2452 LValue LV;
2453 if (VD->getType()->isReferenceType())
Manman Renb0b3af72015-12-17 00:42:36 +00002454 LV = CGF.MakeNaturalAlignAddrLValue(CallVal, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002455 else
Manman Renb0b3af72015-12-17 00:42:36 +00002456 LV = CGF.MakeAddrLValue(CallVal, LValType,
2457 CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002458 // FIXME: need setObjCGCLValueClass?
2459 return LV;
2460}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002461
2462/// Return whether the given global decl needs a VTT parameter, which it does
2463/// if it's a base constructor or destructor with virtual bases.
2464bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
2465 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002466
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002467 // We don't have any virtual bases, just return early.
2468 if (!MD->getParent()->getNumVBases())
2469 return false;
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002470
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002471 // Check if we have a base constructor.
2472 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
2473 return true;
2474
2475 // Check if we have a base destructor.
2476 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2477 return true;
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002478
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002479 return false;
2480}
David Majnemere2cb8d12014-07-07 06:20:47 +00002481
2482namespace {
2483class ItaniumRTTIBuilder {
2484 CodeGenModule &CGM; // Per-module state.
2485 llvm::LLVMContext &VMContext;
2486 const ItaniumCXXABI &CXXABI; // Per-module state.
2487
2488 /// Fields - The fields of the RTTI descriptor currently being built.
2489 SmallVector<llvm::Constant *, 16> Fields;
2490
2491 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2492 llvm::GlobalVariable *
2493 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2494
2495 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2496 /// descriptor of the given type.
2497 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2498
2499 /// BuildVTablePointer - Build the vtable pointer for the given type.
2500 void BuildVTablePointer(const Type *Ty);
2501
2502 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2503 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2504 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2505
2506 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2507 /// classes with bases that do not satisfy the abi::__si_class_type_info
2508 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2509 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2510
2511 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2512 /// for pointer types.
2513 void BuildPointerTypeInfo(QualType PointeeTy);
2514
2515 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2516 /// type_info for an object type.
2517 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2518
2519 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2520 /// struct, used for member pointer types.
2521 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2522
2523public:
2524 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2525 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2526
2527 // Pointer type info flags.
2528 enum {
2529 /// PTI_Const - Type has const qualifier.
2530 PTI_Const = 0x1,
2531
2532 /// PTI_Volatile - Type has volatile qualifier.
2533 PTI_Volatile = 0x2,
2534
2535 /// PTI_Restrict - Type has restrict qualifier.
2536 PTI_Restrict = 0x4,
2537
2538 /// PTI_Incomplete - Type is incomplete.
2539 PTI_Incomplete = 0x8,
2540
2541 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2542 /// (in pointer to member).
Richard Smitha7d93782016-12-01 03:32:42 +00002543 PTI_ContainingClassIncomplete = 0x10,
2544
2545 /// PTI_TransactionSafe - Pointee is transaction_safe function (C++ TM TS).
2546 //PTI_TransactionSafe = 0x20,
2547
2548 /// PTI_Noexcept - Pointee is noexcept function (C++1z).
2549 PTI_Noexcept = 0x40,
David Majnemere2cb8d12014-07-07 06:20:47 +00002550 };
2551
2552 // VMI type info flags.
2553 enum {
2554 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2555 VMI_NonDiamondRepeat = 0x1,
2556
2557 /// VMI_DiamondShaped - Class is diamond shaped.
2558 VMI_DiamondShaped = 0x2
2559 };
2560
2561 // Base class type info flags.
2562 enum {
2563 /// BCTI_Virtual - Base class is virtual.
2564 BCTI_Virtual = 0x1,
2565
2566 /// BCTI_Public - Base class is public.
2567 BCTI_Public = 0x2
2568 };
2569
2570 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
2571 ///
2572 /// \param Force - true to force the creation of this RTTI value
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00002573 /// \param DLLExport - true to mark the RTTI value as DLLExport
2574 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false,
2575 bool DLLExport = false);
David Majnemere2cb8d12014-07-07 06:20:47 +00002576};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002577}
David Majnemere2cb8d12014-07-07 06:20:47 +00002578
2579llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2580 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002581 SmallString<256> Name;
2582 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002583 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002584
2585 // We know that the mangled name of the type starts at index 4 of the
2586 // mangled name of the typename, so we can just index into it in order to
2587 // get the mangled name of the type.
2588 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2589 Name.substr(4));
2590
2591 llvm::GlobalVariable *GV =
2592 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
2593
2594 GV->setInitializer(Init);
2595
2596 return GV;
2597}
2598
2599llvm::Constant *
2600ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2601 // Mangle the RTTI name.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002602 SmallString<256> Name;
2603 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002604 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002605
2606 // Look for an existing global.
2607 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2608
2609 if (!GV) {
2610 // Create a new global variable.
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00002611 // Note for the future: If we would ever like to do deferred emission of
2612 // RTTI, check if emitting vtables opportunistically need any adjustment.
2613
David Majnemere2cb8d12014-07-07 06:20:47 +00002614 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2615 /*Constant=*/true,
2616 llvm::GlobalValue::ExternalLinkage, nullptr,
2617 Name);
Rafael Espindola3f727a82018-03-14 18:14:46 +00002618 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
2619 CGM.setGVProperties(GV, RD);
David Majnemere2cb8d12014-07-07 06:20:47 +00002620 }
2621
2622 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2623}
2624
2625/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2626/// info for that type is defined in the standard library.
2627static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2628 // Itanium C++ ABI 2.9.2:
2629 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
2630 // the run-time support library. Specifically, the run-time support
2631 // library should contain type_info objects for the types X, X* and
2632 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2633 // unsigned char, signed char, short, unsigned short, int, unsigned int,
2634 // long, unsigned long, long long, unsigned long long, float, double,
2635 // long double, char16_t, char32_t, and the IEEE 754r decimal and
2636 // half-precision floating point types.
Richard Smith4a382012016-02-03 01:32:42 +00002637 //
2638 // GCC also emits RTTI for __int128.
2639 // FIXME: We do not emit RTTI information for decimal types here.
2640
2641 // Types added here must also be added to EmitFundamentalRTTIDescriptors.
David Majnemere2cb8d12014-07-07 06:20:47 +00002642 switch (Ty->getKind()) {
2643 case BuiltinType::Void:
2644 case BuiltinType::NullPtr:
2645 case BuiltinType::Bool:
2646 case BuiltinType::WChar_S:
2647 case BuiltinType::WChar_U:
2648 case BuiltinType::Char_U:
2649 case BuiltinType::Char_S:
2650 case BuiltinType::UChar:
2651 case BuiltinType::SChar:
2652 case BuiltinType::Short:
2653 case BuiltinType::UShort:
2654 case BuiltinType::Int:
2655 case BuiltinType::UInt:
2656 case BuiltinType::Long:
2657 case BuiltinType::ULong:
2658 case BuiltinType::LongLong:
2659 case BuiltinType::ULongLong:
2660 case BuiltinType::Half:
2661 case BuiltinType::Float:
2662 case BuiltinType::Double:
2663 case BuiltinType::LongDouble:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00002664 case BuiltinType::Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002665 case BuiltinType::Float128:
David Majnemere2cb8d12014-07-07 06:20:47 +00002666 case BuiltinType::Char16:
2667 case BuiltinType::Char32:
2668 case BuiltinType::Int128:
2669 case BuiltinType::UInt128:
Richard Smith4a382012016-02-03 01:32:42 +00002670 return true;
2671
Alexey Bader954ba212016-04-08 13:40:33 +00002672#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2673 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00002674#include "clang/Basic/OpenCLImageTypes.def"
David Majnemere2cb8d12014-07-07 06:20:47 +00002675 case BuiltinType::OCLSampler:
2676 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002677 case BuiltinType::OCLClkEvent:
2678 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002679 case BuiltinType::OCLReserveID:
Richard Smith4a382012016-02-03 01:32:42 +00002680 return false;
David Majnemere2cb8d12014-07-07 06:20:47 +00002681
2682 case BuiltinType::Dependent:
2683#define BUILTIN_TYPE(Id, SingletonId)
2684#define PLACEHOLDER_TYPE(Id, SingletonId) \
2685 case BuiltinType::Id:
2686#include "clang/AST/BuiltinTypes.def"
2687 llvm_unreachable("asking for RRTI for a placeholder type!");
2688
2689 case BuiltinType::ObjCId:
2690 case BuiltinType::ObjCClass:
2691 case BuiltinType::ObjCSel:
2692 llvm_unreachable("FIXME: Objective-C types are unsupported!");
2693 }
2694
2695 llvm_unreachable("Invalid BuiltinType Kind!");
2696}
2697
2698static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2699 QualType PointeeTy = PointerTy->getPointeeType();
2700 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2701 if (!BuiltinTy)
2702 return false;
2703
2704 // Check the qualifiers.
2705 Qualifiers Quals = PointeeTy.getQualifiers();
2706 Quals.removeConst();
2707
2708 if (!Quals.empty())
2709 return false;
2710
2711 return TypeInfoIsInStandardLibrary(BuiltinTy);
2712}
2713
2714/// IsStandardLibraryRTTIDescriptor - Returns whether the type
2715/// information for the given type exists in the standard library.
2716static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2717 // Type info for builtin types is defined in the standard library.
2718 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2719 return TypeInfoIsInStandardLibrary(BuiltinTy);
2720
2721 // Type info for some pointer types to builtin types is defined in the
2722 // standard library.
2723 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2724 return TypeInfoIsInStandardLibrary(PointerTy);
2725
2726 return false;
2727}
2728
2729/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
2730/// the given type exists somewhere else, and that we should not emit the type
2731/// information in this translation unit. Assumes that it is not a
2732/// standard-library type.
2733static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
2734 QualType Ty) {
2735 ASTContext &Context = CGM.getContext();
2736
2737 // If RTTI is disabled, assume it might be disabled in the
2738 // translation unit that defines any potential key function, too.
2739 if (!Context.getLangOpts().RTTI) return false;
2740
2741 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2742 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2743 if (!RD->hasDefinition())
2744 return false;
2745
2746 if (!RD->isDynamicClass())
2747 return false;
2748
2749 // FIXME: this may need to be reconsidered if the key function
2750 // changes.
David Majnemerbe9022c2015-08-06 20:56:55 +00002751 // N.B. We must always emit the RTTI data ourselves if there exists a key
2752 // function.
2753 bool IsDLLImport = RD->hasAttr<DLLImportAttr>();
Martin Storsjo3b528942018-02-02 06:22:35 +00002754
2755 // Don't import the RTTI but emit it locally.
2756 if (CGM.getTriple().isWindowsGNUEnvironment() && IsDLLImport)
2757 return false;
2758
David Majnemer1fb1a042014-11-07 07:26:38 +00002759 if (CGM.getVTables().isVTableExternal(RD))
Shoaib Meenai61118e72017-07-04 01:02:19 +00002760 return IsDLLImport && !CGM.getTriple().isWindowsItaniumEnvironment()
2761 ? false
2762 : true;
David Majnemer1fb1a042014-11-07 07:26:38 +00002763
David Majnemerbe9022c2015-08-06 20:56:55 +00002764 if (IsDLLImport)
David Majnemer1fb1a042014-11-07 07:26:38 +00002765 return true;
David Majnemere2cb8d12014-07-07 06:20:47 +00002766 }
2767
2768 return false;
2769}
2770
2771/// IsIncompleteClassType - Returns whether the given record type is incomplete.
2772static bool IsIncompleteClassType(const RecordType *RecordTy) {
2773 return !RecordTy->getDecl()->isCompleteDefinition();
2774}
2775
2776/// ContainsIncompleteClassType - Returns whether the given type contains an
2777/// incomplete class type. This is true if
2778///
2779/// * The given type is an incomplete class type.
2780/// * The given type is a pointer type whose pointee type contains an
2781/// incomplete class type.
2782/// * The given type is a member pointer type whose class is an incomplete
2783/// class type.
2784/// * The given type is a member pointer type whoise pointee type contains an
2785/// incomplete class type.
2786/// is an indirect or direct pointer to an incomplete class type.
2787static bool ContainsIncompleteClassType(QualType Ty) {
2788 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2789 if (IsIncompleteClassType(RecordTy))
2790 return true;
2791 }
2792
2793 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2794 return ContainsIncompleteClassType(PointerTy->getPointeeType());
2795
2796 if (const MemberPointerType *MemberPointerTy =
2797 dyn_cast<MemberPointerType>(Ty)) {
2798 // Check if the class type is incomplete.
2799 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
2800 if (IsIncompleteClassType(ClassType))
2801 return true;
2802
2803 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
2804 }
2805
2806 return false;
2807}
2808
2809// CanUseSingleInheritance - Return whether the given record decl has a "single,
2810// public, non-virtual base at offset zero (i.e. the derived class is dynamic
2811// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
2812static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
2813 // Check the number of bases.
2814 if (RD->getNumBases() != 1)
2815 return false;
2816
2817 // Get the base.
2818 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
2819
2820 // Check that the base is not virtual.
2821 if (Base->isVirtual())
2822 return false;
2823
2824 // Check that the base is public.
2825 if (Base->getAccessSpecifier() != AS_public)
2826 return false;
2827
2828 // Check that the class is dynamic iff the base is.
2829 const CXXRecordDecl *BaseDecl =
2830 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2831 if (!BaseDecl->isEmpty() &&
2832 BaseDecl->isDynamicClass() != RD->isDynamicClass())
2833 return false;
2834
2835 return true;
2836}
2837
2838void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
2839 // abi::__class_type_info.
2840 static const char * const ClassTypeInfo =
2841 "_ZTVN10__cxxabiv117__class_type_infoE";
2842 // abi::__si_class_type_info.
2843 static const char * const SIClassTypeInfo =
2844 "_ZTVN10__cxxabiv120__si_class_type_infoE";
2845 // abi::__vmi_class_type_info.
2846 static const char * const VMIClassTypeInfo =
2847 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
2848
2849 const char *VTableName = nullptr;
2850
2851 switch (Ty->getTypeClass()) {
2852#define TYPE(Class, Base)
2853#define ABSTRACT_TYPE(Class, Base)
2854#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2855#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2856#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2857#include "clang/AST/TypeNodes.def"
2858 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2859
2860 case Type::LValueReference:
2861 case Type::RValueReference:
2862 llvm_unreachable("References shouldn't get here");
2863
2864 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00002865 case Type::DeducedTemplateSpecialization:
2866 llvm_unreachable("Undeduced type shouldn't get here");
David Majnemere2cb8d12014-07-07 06:20:47 +00002867
Xiuli Pan9c14e282016-01-09 12:53:17 +00002868 case Type::Pipe:
2869 llvm_unreachable("Pipe types shouldn't get here");
2870
David Majnemere2cb8d12014-07-07 06:20:47 +00002871 case Type::Builtin:
2872 // GCC treats vector and complex types as fundamental types.
2873 case Type::Vector:
2874 case Type::ExtVector:
2875 case Type::Complex:
2876 case Type::Atomic:
2877 // FIXME: GCC treats block pointers as fundamental types?!
2878 case Type::BlockPointer:
2879 // abi::__fundamental_type_info.
2880 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
2881 break;
2882
2883 case Type::ConstantArray:
2884 case Type::IncompleteArray:
2885 case Type::VariableArray:
2886 // abi::__array_type_info.
2887 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
2888 break;
2889
2890 case Type::FunctionNoProto:
2891 case Type::FunctionProto:
Richard Smithb17d6fa2016-12-01 03:04:07 +00002892 // abi::__function_type_info.
2893 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
David Majnemere2cb8d12014-07-07 06:20:47 +00002894 break;
2895
2896 case Type::Enum:
2897 // abi::__enum_type_info.
2898 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
2899 break;
2900
2901 case Type::Record: {
Rafael Espindolaf6688122018-03-22 21:14:16 +00002902 const CXXRecordDecl *RD =
2903 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
David Majnemere2cb8d12014-07-07 06:20:47 +00002904
2905 if (!RD->hasDefinition() || !RD->getNumBases()) {
2906 VTableName = ClassTypeInfo;
2907 } else if (CanUseSingleInheritance(RD)) {
2908 VTableName = SIClassTypeInfo;
2909 } else {
2910 VTableName = VMIClassTypeInfo;
2911 }
2912
2913 break;
2914 }
2915
2916 case Type::ObjCObject:
2917 // Ignore protocol qualifiers.
2918 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
2919
2920 // Handle id and Class.
2921 if (isa<BuiltinType>(Ty)) {
2922 VTableName = ClassTypeInfo;
2923 break;
2924 }
2925
2926 assert(isa<ObjCInterfaceType>(Ty));
2927 // Fall through.
2928
2929 case Type::ObjCInterface:
2930 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
2931 VTableName = SIClassTypeInfo;
2932 } else {
2933 VTableName = ClassTypeInfo;
2934 }
2935 break;
2936
2937 case Type::ObjCObjectPointer:
2938 case Type::Pointer:
2939 // abi::__pointer_type_info.
2940 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
2941 break;
2942
2943 case Type::MemberPointer:
2944 // abi::__pointer_to_member_type_info.
2945 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
2946 break;
2947 }
2948
2949 llvm::Constant *VTable =
2950 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
Rafael Espindolafe9a55a2018-03-23 01:36:23 +00002951 CGM.setDSOLocal(cast<llvm::GlobalValue>(VTable->stripPointerCasts()));
David Majnemere2cb8d12014-07-07 06:20:47 +00002952
2953 llvm::Type *PtrDiffTy =
2954 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
2955
2956 // The vtable address point is 2.
2957 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00002958 VTable =
2959 llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.Int8PtrTy, VTable, Two);
David Majnemere2cb8d12014-07-07 06:20:47 +00002960 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
2961
2962 Fields.push_back(VTable);
2963}
2964
2965/// \brief Return the linkage that the type info and type info name constants
2966/// should have for the given type.
2967static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
2968 QualType Ty) {
2969 // Itanium C++ ABI 2.9.5p7:
2970 // In addition, it and all of the intermediate abi::__pointer_type_info
2971 // structs in the chain down to the abi::__class_type_info for the
2972 // incomplete class type must be prevented from resolving to the
2973 // corresponding type_info structs for the complete class type, possibly
2974 // by making them local static objects. Finally, a dummy class RTTI is
2975 // generated for the incomplete type that will not resolve to the final
2976 // complete class RTTI (because the latter need not exist), possibly by
2977 // making it a local static object.
2978 if (ContainsIncompleteClassType(Ty))
2979 return llvm::GlobalValue::InternalLinkage;
2980
2981 switch (Ty->getLinkage()) {
2982 case NoLinkage:
2983 case InternalLinkage:
2984 case UniqueExternalLinkage:
2985 return llvm::GlobalValue::InternalLinkage;
2986
2987 case VisibleNoLinkage:
Richard Smith1283e982017-07-07 20:04:28 +00002988 case ModuleInternalLinkage:
2989 case ModuleLinkage:
David Majnemere2cb8d12014-07-07 06:20:47 +00002990 case ExternalLinkage:
Saleem Abdulrasool18820022016-12-02 22:46:18 +00002991 // RTTI is not enabled, which means that this type info struct is going
2992 // to be used for exception handling. Give it linkonce_odr linkage.
2993 if (!CGM.getLangOpts().RTTI)
David Majnemere2cb8d12014-07-07 06:20:47 +00002994 return llvm::GlobalValue::LinkOnceODRLinkage;
David Majnemere2cb8d12014-07-07 06:20:47 +00002995
2996 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
2997 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2998 if (RD->hasAttr<WeakAttr>())
2999 return llvm::GlobalValue::WeakODRLinkage;
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003000 if (CGM.getTriple().isWindowsItaniumEnvironment())
Shoaib Meenai61118e72017-07-04 01:02:19 +00003001 if (RD->hasAttr<DLLImportAttr>() &&
3002 ShouldUseExternalRTTIDescriptor(CGM, Ty))
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003003 return llvm::GlobalValue::ExternalLinkage;
Martin Storsjoc6c5af72017-09-01 06:41:55 +00003004 // MinGW always uses LinkOnceODRLinkage for type info.
3005 if (RD->isDynamicClass() &&
3006 !CGM.getContext()
3007 .getTargetInfo()
3008 .getTriple()
3009 .isWindowsGNUEnvironment())
3010 return CGM.getVTableLinkage(RD);
David Majnemere2cb8d12014-07-07 06:20:47 +00003011 }
3012
3013 return llvm::GlobalValue::LinkOnceODRLinkage;
3014 }
3015
3016 llvm_unreachable("Invalid linkage!");
3017}
3018
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003019llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force,
3020 bool DLLExport) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003021 // We want to operate on the canonical type.
Yaron Kerenebd14262016-03-16 12:14:43 +00003022 Ty = Ty.getCanonicalType();
David Majnemere2cb8d12014-07-07 06:20:47 +00003023
3024 // Check if we've already emitted an RTTI descriptor for this type.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00003025 SmallString<256> Name;
3026 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00003027 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00003028
3029 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
3030 if (OldGV && !OldGV->isDeclaration()) {
3031 assert(!OldGV->hasAvailableExternallyLinkage() &&
3032 "available_externally typeinfos not yet implemented");
3033
3034 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
3035 }
3036
3037 // Check if there is already an external RTTI descriptor for this type.
3038 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
3039 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
3040 return GetAddrOfExternalRTTIDescriptor(Ty);
3041
3042 // Emit the standard library with external linkage.
3043 llvm::GlobalVariable::LinkageTypes Linkage;
3044 if (IsStdLib)
3045 Linkage = llvm::GlobalValue::ExternalLinkage;
3046 else
3047 Linkage = getTypeInfoLinkage(CGM, Ty);
3048
3049 // Add the vtable pointer.
3050 BuildVTablePointer(cast<Type>(Ty));
3051
3052 // And the name.
3053 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
3054 llvm::Constant *TypeNameField;
3055
3056 // If we're supposed to demote the visibility, be sure to set a flag
3057 // to use a string comparison for type_info comparisons.
3058 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
3059 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
3060 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
3061 // The flag is the sign bit, which on ARM64 is defined to be clear
3062 // for global pointers. This is very ARM64-specific.
3063 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
3064 llvm::Constant *flag =
3065 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
3066 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
3067 TypeNameField =
3068 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
3069 } else {
3070 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
3071 }
3072 Fields.push_back(TypeNameField);
3073
3074 switch (Ty->getTypeClass()) {
3075#define TYPE(Class, Base)
3076#define ABSTRACT_TYPE(Class, Base)
3077#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3078#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3079#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3080#include "clang/AST/TypeNodes.def"
3081 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
3082
3083 // GCC treats vector types as fundamental types.
3084 case Type::Builtin:
3085 case Type::Vector:
3086 case Type::ExtVector:
3087 case Type::Complex:
3088 case Type::BlockPointer:
3089 // Itanium C++ ABI 2.9.5p4:
3090 // abi::__fundamental_type_info adds no data members to std::type_info.
3091 break;
3092
3093 case Type::LValueReference:
3094 case Type::RValueReference:
3095 llvm_unreachable("References shouldn't get here");
3096
3097 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00003098 case Type::DeducedTemplateSpecialization:
3099 llvm_unreachable("Undeduced type shouldn't get here");
David Majnemere2cb8d12014-07-07 06:20:47 +00003100
Xiuli Pan9c14e282016-01-09 12:53:17 +00003101 case Type::Pipe:
3102 llvm_unreachable("Pipe type shouldn't get here");
3103
David Majnemere2cb8d12014-07-07 06:20:47 +00003104 case Type::ConstantArray:
3105 case Type::IncompleteArray:
3106 case Type::VariableArray:
3107 // Itanium C++ ABI 2.9.5p5:
3108 // abi::__array_type_info adds no data members to std::type_info.
3109 break;
3110
3111 case Type::FunctionNoProto:
Richard Smithb17d6fa2016-12-01 03:04:07 +00003112 case Type::FunctionProto:
David Majnemere2cb8d12014-07-07 06:20:47 +00003113 // Itanium C++ ABI 2.9.5p5:
3114 // abi::__function_type_info adds no data members to std::type_info.
3115 break;
3116
3117 case Type::Enum:
3118 // Itanium C++ ABI 2.9.5p5:
3119 // abi::__enum_type_info adds no data members to std::type_info.
3120 break;
3121
3122 case Type::Record: {
3123 const CXXRecordDecl *RD =
3124 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
3125 if (!RD->hasDefinition() || !RD->getNumBases()) {
3126 // We don't need to emit any fields.
3127 break;
3128 }
3129
3130 if (CanUseSingleInheritance(RD))
3131 BuildSIClassTypeInfo(RD);
3132 else
3133 BuildVMIClassTypeInfo(RD);
3134
3135 break;
3136 }
3137
3138 case Type::ObjCObject:
3139 case Type::ObjCInterface:
3140 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
3141 break;
3142
3143 case Type::ObjCObjectPointer:
3144 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
3145 break;
3146
3147 case Type::Pointer:
3148 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
3149 break;
3150
3151 case Type::MemberPointer:
3152 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
3153 break;
3154
3155 case Type::Atomic:
3156 // No fields, at least for the moment.
3157 break;
3158 }
3159
3160 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
3161
Rafael Espindolacb92c192015-01-15 23:18:01 +00003162 llvm::Module &M = CGM.getModule();
David Majnemere2cb8d12014-07-07 06:20:47 +00003163 llvm::GlobalVariable *GV =
Rafael Espindolacb92c192015-01-15 23:18:01 +00003164 new llvm::GlobalVariable(M, Init->getType(),
3165 /*Constant=*/true, Linkage, Init, Name);
3166
David Majnemere2cb8d12014-07-07 06:20:47 +00003167 // If there's already an old global variable, replace it with the new one.
3168 if (OldGV) {
3169 GV->takeName(OldGV);
3170 llvm::Constant *NewPtr =
3171 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3172 OldGV->replaceAllUsesWith(NewPtr);
3173 OldGV->eraseFromParent();
3174 }
3175
Yaron Keren04da2382015-07-29 15:42:28 +00003176 if (CGM.supportsCOMDAT() && GV->isWeakForLinker())
3177 GV->setComdat(M.getOrInsertComdat(GV->getName()));
3178
David Majnemere2cb8d12014-07-07 06:20:47 +00003179 // The Itanium ABI specifies that type_info objects must be globally
3180 // unique, with one exception: if the type is an incomplete class
3181 // type or a (possibly indirect) pointer to one. That exception
3182 // affects the general case of comparing type_info objects produced
3183 // by the typeid operator, which is why the comparison operators on
3184 // std::type_info generally use the type_info name pointers instead
3185 // of the object addresses. However, the language's built-in uses
3186 // of RTTI generally require class types to be complete, even when
3187 // manipulating pointers to those class types. This allows the
3188 // implementation of dynamic_cast to rely on address equality tests,
3189 // which is much faster.
3190
3191 // All of this is to say that it's important that both the type_info
3192 // object and the type_info name be uniqued when weakly emitted.
3193
3194 // Give the type_info object and name the formal visibility of the
3195 // type itself.
3196 llvm::GlobalValue::VisibilityTypes llvmVisibility;
3197 if (llvm::GlobalValue::isLocalLinkage(Linkage))
3198 // If the linkage is local, only default visibility makes sense.
3199 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
3200 else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden)
3201 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
3202 else
3203 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003204
David Majnemere2cb8d12014-07-07 06:20:47 +00003205 TypeName->setVisibility(llvmVisibility);
Rafael Espindola3dd49812018-02-23 00:22:15 +00003206 CGM.setDSOLocal(TypeName);
Rafael Espindola699f5d62018-02-07 22:15:33 +00003207
David Majnemere2cb8d12014-07-07 06:20:47 +00003208 GV->setVisibility(llvmVisibility);
Rafael Espindola3dd49812018-02-23 00:22:15 +00003209 CGM.setDSOLocal(GV);
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003210
3211 if (CGM.getTriple().isWindowsItaniumEnvironment()) {
3212 auto RD = Ty->getAsCXXRecordDecl();
3213 if (DLLExport || (RD && RD->hasAttr<DLLExportAttr>())) {
3214 TypeName->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
3215 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
Shoaib Meenai61118e72017-07-04 01:02:19 +00003216 } else if (RD && RD->hasAttr<DLLImportAttr>() &&
3217 ShouldUseExternalRTTIDescriptor(CGM, Ty)) {
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003218 TypeName->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3219 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3220
3221 // Because the typename and the typeinfo are DLL import, convert them to
3222 // declarations rather than definitions. The initializers still need to
3223 // be constructed to calculate the type for the declarations.
3224 TypeName->setInitializer(nullptr);
3225 GV->setInitializer(nullptr);
3226 }
3227 }
David Majnemere2cb8d12014-07-07 06:20:47 +00003228
3229 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
3230}
3231
David Majnemere2cb8d12014-07-07 06:20:47 +00003232/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
3233/// for the given Objective-C object type.
3234void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
3235 // Drop qualifiers.
3236 const Type *T = OT->getBaseType().getTypePtr();
3237 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
3238
3239 // The builtin types are abi::__class_type_infos and don't require
3240 // extra fields.
3241 if (isa<BuiltinType>(T)) return;
3242
3243 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
3244 ObjCInterfaceDecl *Super = Class->getSuperClass();
3245
3246 // Root classes are also __class_type_info.
3247 if (!Super) return;
3248
3249 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
3250
3251 // Everything else is single inheritance.
3252 llvm::Constant *BaseTypeInfo =
3253 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
3254 Fields.push_back(BaseTypeInfo);
3255}
3256
3257/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
3258/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
3259void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
3260 // Itanium C++ ABI 2.9.5p6b:
3261 // It adds to abi::__class_type_info a single member pointing to the
3262 // type_info structure for the base type,
3263 llvm::Constant *BaseTypeInfo =
3264 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
3265 Fields.push_back(BaseTypeInfo);
3266}
3267
3268namespace {
3269 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
3270 /// a class hierarchy.
3271 struct SeenBases {
3272 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
3273 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
3274 };
3275}
3276
3277/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
3278/// abi::__vmi_class_type_info.
3279///
3280static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
3281 SeenBases &Bases) {
3282
3283 unsigned Flags = 0;
3284
3285 const CXXRecordDecl *BaseDecl =
3286 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
3287
3288 if (Base->isVirtual()) {
3289 // Mark the virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003290 if (!Bases.VirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003291 // If this virtual base has been seen before, then the class is diamond
3292 // shaped.
3293 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
3294 } else {
3295 if (Bases.NonVirtualBases.count(BaseDecl))
3296 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3297 }
3298 } else {
3299 // Mark the non-virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003300 if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003301 // If this non-virtual base has been seen before, then the class has non-
3302 // diamond shaped repeated inheritance.
3303 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3304 } else {
3305 if (Bases.VirtualBases.count(BaseDecl))
3306 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3307 }
3308 }
3309
3310 // Walk all bases.
3311 for (const auto &I : BaseDecl->bases())
3312 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3313
3314 return Flags;
3315}
3316
3317static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
3318 unsigned Flags = 0;
3319 SeenBases Bases;
3320
3321 // Walk all bases.
3322 for (const auto &I : RD->bases())
3323 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3324
3325 return Flags;
3326}
3327
3328/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
3329/// classes with bases that do not satisfy the abi::__si_class_type_info
3330/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
3331void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
3332 llvm::Type *UnsignedIntLTy =
3333 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3334
3335 // Itanium C++ ABI 2.9.5p6c:
3336 // __flags is a word with flags describing details about the class
3337 // structure, which may be referenced by using the __flags_masks
3338 // enumeration. These flags refer to both direct and indirect bases.
3339 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
3340 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3341
3342 // Itanium C++ ABI 2.9.5p6c:
3343 // __base_count is a word with the number of direct proper base class
3344 // descriptions that follow.
3345 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
3346
3347 if (!RD->getNumBases())
3348 return;
3349
David Majnemere2cb8d12014-07-07 06:20:47 +00003350 // Now add the base class descriptions.
3351
3352 // Itanium C++ ABI 2.9.5p6c:
3353 // __base_info[] is an array of base class descriptions -- one for every
3354 // direct proper base. Each description is of the type:
3355 //
3356 // struct abi::__base_class_type_info {
3357 // public:
3358 // const __class_type_info *__base_type;
3359 // long __offset_flags;
3360 //
3361 // enum __offset_flags_masks {
3362 // __virtual_mask = 0x1,
3363 // __public_mask = 0x2,
3364 // __offset_shift = 8
3365 // };
3366 // };
Reid Klecknerd8b04662016-08-25 22:16:30 +00003367
3368 // If we're in mingw and 'long' isn't wide enough for a pointer, use 'long
3369 // long' instead of 'long' for __offset_flags. libstdc++abi uses long long on
3370 // LLP64 platforms.
3371 // FIXME: Consider updating libc++abi to match, and extend this logic to all
3372 // LLP64 platforms.
3373 QualType OffsetFlagsTy = CGM.getContext().LongTy;
3374 const TargetInfo &TI = CGM.getContext().getTargetInfo();
3375 if (TI.getTriple().isOSCygMing() && TI.getPointerWidth(0) > TI.getLongWidth())
3376 OffsetFlagsTy = CGM.getContext().LongLongTy;
3377 llvm::Type *OffsetFlagsLTy =
3378 CGM.getTypes().ConvertType(OffsetFlagsTy);
3379
David Majnemere2cb8d12014-07-07 06:20:47 +00003380 for (const auto &Base : RD->bases()) {
3381 // The __base_type member points to the RTTI for the base type.
3382 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
3383
3384 const CXXRecordDecl *BaseDecl =
3385 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
3386
3387 int64_t OffsetFlags = 0;
3388
3389 // All but the lower 8 bits of __offset_flags are a signed offset.
3390 // For a non-virtual base, this is the offset in the object of the base
3391 // subobject. For a virtual base, this is the offset in the virtual table of
3392 // the virtual base offset for the virtual base referenced (negative).
3393 CharUnits Offset;
3394 if (Base.isVirtual())
3395 Offset =
3396 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
3397 else {
3398 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
3399 Offset = Layout.getBaseClassOffset(BaseDecl);
3400 };
3401
3402 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
3403
3404 // The low-order byte of __offset_flags contains flags, as given by the
3405 // masks from the enumeration __offset_flags_masks.
3406 if (Base.isVirtual())
3407 OffsetFlags |= BCTI_Virtual;
3408 if (Base.getAccessSpecifier() == AS_public)
3409 OffsetFlags |= BCTI_Public;
3410
Reid Klecknerd8b04662016-08-25 22:16:30 +00003411 Fields.push_back(llvm::ConstantInt::get(OffsetFlagsLTy, OffsetFlags));
David Majnemere2cb8d12014-07-07 06:20:47 +00003412 }
3413}
3414
Richard Smitha7d93782016-12-01 03:32:42 +00003415/// Compute the flags for a __pbase_type_info, and remove the corresponding
3416/// pieces from \p Type.
3417static unsigned extractPBaseFlags(ASTContext &Ctx, QualType &Type) {
3418 unsigned Flags = 0;
David Majnemere2cb8d12014-07-07 06:20:47 +00003419
Richard Smitha7d93782016-12-01 03:32:42 +00003420 if (Type.isConstQualified())
3421 Flags |= ItaniumRTTIBuilder::PTI_Const;
3422 if (Type.isVolatileQualified())
3423 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
3424 if (Type.isRestrictQualified())
3425 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
3426 Type = Type.getUnqualifiedType();
David Majnemere2cb8d12014-07-07 06:20:47 +00003427
3428 // Itanium C++ ABI 2.9.5p7:
3429 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3430 // incomplete class type, the incomplete target type flag is set.
Richard Smitha7d93782016-12-01 03:32:42 +00003431 if (ContainsIncompleteClassType(Type))
3432 Flags |= ItaniumRTTIBuilder::PTI_Incomplete;
3433
3434 if (auto *Proto = Type->getAs<FunctionProtoType>()) {
3435 if (Proto->isNothrow(Ctx)) {
3436 Flags |= ItaniumRTTIBuilder::PTI_Noexcept;
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00003437 Type = Ctx.getFunctionTypeWithExceptionSpec(Type, EST_None);
Richard Smitha7d93782016-12-01 03:32:42 +00003438 }
3439 }
3440
3441 return Flags;
3442}
3443
3444/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
3445/// used for pointer types.
3446void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
3447 // Itanium C++ ABI 2.9.5p7:
3448 // __flags is a flag word describing the cv-qualification and other
3449 // attributes of the type pointed to
3450 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003451
3452 llvm::Type *UnsignedIntLTy =
3453 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3454 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3455
3456 // Itanium C++ ABI 2.9.5p7:
3457 // __pointee is a pointer to the std::type_info derivation for the
3458 // unqualified type being pointed to.
3459 llvm::Constant *PointeeTypeInfo =
Richard Smitha7d93782016-12-01 03:32:42 +00003460 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003461 Fields.push_back(PointeeTypeInfo);
3462}
3463
3464/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
3465/// struct, used for member pointer types.
3466void
3467ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
3468 QualType PointeeTy = Ty->getPointeeType();
3469
David Majnemere2cb8d12014-07-07 06:20:47 +00003470 // Itanium C++ ABI 2.9.5p7:
3471 // __flags is a flag word describing the cv-qualification and other
3472 // attributes of the type pointed to.
Richard Smitha7d93782016-12-01 03:32:42 +00003473 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003474
3475 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
David Majnemere2cb8d12014-07-07 06:20:47 +00003476 if (IsIncompleteClassType(ClassType))
3477 Flags |= PTI_ContainingClassIncomplete;
3478
3479 llvm::Type *UnsignedIntLTy =
3480 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3481 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3482
3483 // Itanium C++ ABI 2.9.5p7:
3484 // __pointee is a pointer to the std::type_info derivation for the
3485 // unqualified type being pointed to.
3486 llvm::Constant *PointeeTypeInfo =
Richard Smitha7d93782016-12-01 03:32:42 +00003487 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003488 Fields.push_back(PointeeTypeInfo);
3489
3490 // Itanium C++ ABI 2.9.5p9:
3491 // __context is a pointer to an abi::__class_type_info corresponding to the
3492 // class type containing the member pointed to
3493 // (e.g., the "A" in "int A::*").
3494 Fields.push_back(
3495 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
3496}
3497
David Majnemer443250f2015-03-17 20:35:00 +00003498llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003499 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
3500}
3501
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003502void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type,
3503 bool DLLExport) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003504 QualType PointerType = getContext().getPointerType(Type);
3505 QualType PointerTypeConst = getContext().getPointerType(Type.withConst());
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003506 ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, /*Force=*/true, DLLExport);
3507 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, /*Force=*/true,
3508 DLLExport);
3509 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, /*Force=*/true,
3510 DLLExport);
David Majnemere2cb8d12014-07-07 06:20:47 +00003511}
3512
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003513void ItaniumCXXABI::EmitFundamentalRTTIDescriptors(bool DLLExport) {
Richard Smith4a382012016-02-03 01:32:42 +00003514 // Types added here must also be added to TypeInfoIsInStandardLibrary.
David Majnemere2cb8d12014-07-07 06:20:47 +00003515 QualType FundamentalTypes[] = {
3516 getContext().VoidTy, getContext().NullPtrTy,
3517 getContext().BoolTy, getContext().WCharTy,
3518 getContext().CharTy, getContext().UnsignedCharTy,
3519 getContext().SignedCharTy, getContext().ShortTy,
3520 getContext().UnsignedShortTy, getContext().IntTy,
3521 getContext().UnsignedIntTy, getContext().LongTy,
3522 getContext().UnsignedLongTy, getContext().LongLongTy,
Richard Smith4a382012016-02-03 01:32:42 +00003523 getContext().UnsignedLongLongTy, getContext().Int128Ty,
3524 getContext().UnsignedInt128Ty, getContext().HalfTy,
David Majnemere2cb8d12014-07-07 06:20:47 +00003525 getContext().FloatTy, getContext().DoubleTy,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00003526 getContext().LongDoubleTy, getContext().Float128Ty,
3527 getContext().Char16Ty, getContext().Char32Ty
David Majnemere2cb8d12014-07-07 06:20:47 +00003528 };
3529 for (const QualType &FundamentalType : FundamentalTypes)
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003530 EmitFundamentalRTTIDescriptor(FundamentalType, DLLExport);
David Majnemere2cb8d12014-07-07 06:20:47 +00003531}
3532
3533/// What sort of uniqueness rules should we use for the RTTI for the
3534/// given type?
3535ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
3536 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
3537 if (shouldRTTIBeUnique())
3538 return RUK_Unique;
3539
3540 // It's only necessary for linkonce_odr or weak_odr linkage.
3541 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
3542 Linkage != llvm::GlobalValue::WeakODRLinkage)
3543 return RUK_Unique;
3544
3545 // It's only necessary with default visibility.
3546 if (CanTy->getVisibility() != DefaultVisibility)
3547 return RUK_Unique;
3548
3549 // If we're not required to publish this symbol, hide it.
3550 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3551 return RUK_NonUniqueHidden;
3552
3553 // If we're required to publish this symbol, as we might be under an
3554 // explicit instantiation, leave it with default visibility but
3555 // enable string-comparisons.
3556 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
3557 return RUK_NonUniqueVisible;
3558}
Rafael Espindola91f68b42014-09-15 19:20:10 +00003559
Rafael Espindola1e4df922014-09-16 15:18:21 +00003560// Find out how to codegen the complete destructor and constructor
3561namespace {
3562enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
3563}
3564static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
3565 const CXXMethodDecl *MD) {
3566 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
3567 return StructorCodegen::Emit;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003568
Rafael Espindola1e4df922014-09-16 15:18:21 +00003569 // The complete and base structors are not equivalent if there are any virtual
3570 // bases, so emit separate functions.
3571 if (MD->getParent()->getNumVBases())
3572 return StructorCodegen::Emit;
3573
3574 GlobalDecl AliasDecl;
3575 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3576 AliasDecl = GlobalDecl(DD, Dtor_Complete);
3577 } else {
3578 const auto *CD = cast<CXXConstructorDecl>(MD);
3579 AliasDecl = GlobalDecl(CD, Ctor_Complete);
3580 }
3581 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3582
3583 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
3584 return StructorCodegen::RAUW;
3585
3586 // FIXME: Should we allow available_externally aliases?
3587 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
3588 return StructorCodegen::RAUW;
3589
Rafael Espindola0806f982014-09-16 20:19:43 +00003590 if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
Dan Gohman839f2152017-01-17 21:46:38 +00003591 // Only ELF and wasm support COMDATs with arbitrary names (C5/D5).
3592 if (CGM.getTarget().getTriple().isOSBinFormatELF() ||
3593 CGM.getTarget().getTriple().isOSBinFormatWasm())
Rafael Espindola0806f982014-09-16 20:19:43 +00003594 return StructorCodegen::COMDAT;
3595 return StructorCodegen::Emit;
3596 }
Rafael Espindola1e4df922014-09-16 15:18:21 +00003597
3598 return StructorCodegen::Alias;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003599}
3600
Rafael Espindola1e4df922014-09-16 15:18:21 +00003601static void emitConstructorDestructorAlias(CodeGenModule &CGM,
3602 GlobalDecl AliasDecl,
3603 GlobalDecl TargetDecl) {
3604 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3605
3606 StringRef MangledName = CGM.getMangledName(AliasDecl);
3607 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
3608 if (Entry && !Entry->isDeclaration())
3609 return;
3610
3611 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
Rafael Espindola1e4df922014-09-16 15:18:21 +00003612
3613 // Create the alias with no name.
David Blaikie2a791d72015-09-14 18:38:22 +00003614 auto *Alias = llvm::GlobalAlias::create(Linkage, "", Aliasee);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003615
3616 // Switch any previous uses to the alias.
3617 if (Entry) {
NAKAMURA Takumie9621042015-09-15 01:39:27 +00003618 assert(Entry->getType() == Aliasee->getType() &&
Rafael Espindola1e4df922014-09-16 15:18:21 +00003619 "declaration exists with different type");
3620 Alias->takeName(Entry);
3621 Entry->replaceAllUsesWith(Alias);
3622 Entry->eraseFromParent();
3623 } else {
3624 Alias->setName(MangledName);
3625 }
3626
3627 // Finally, set up the alias with its proper name and attributes.
Rafael Espindolab7350042018-03-01 00:35:47 +00003628 CGM.SetCommonAttributes(AliasDecl, Alias);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003629}
3630
3631void ItaniumCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
3632 StructorType Type) {
3633 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
3634 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
3635
3636 StructorCodegen CGType = getCodegenToUse(CGM, MD);
3637
3638 if (Type == StructorType::Complete) {
3639 GlobalDecl CompleteDecl;
3640 GlobalDecl BaseDecl;
3641 if (CD) {
3642 CompleteDecl = GlobalDecl(CD, Ctor_Complete);
3643 BaseDecl = GlobalDecl(CD, Ctor_Base);
3644 } else {
3645 CompleteDecl = GlobalDecl(DD, Dtor_Complete);
3646 BaseDecl = GlobalDecl(DD, Dtor_Base);
3647 }
3648
3649 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
3650 emitConstructorDestructorAlias(CGM, CompleteDecl, BaseDecl);
3651 return;
3652 }
3653
3654 if (CGType == StructorCodegen::RAUW) {
3655 StringRef MangledName = CGM.getMangledName(CompleteDecl);
Andrey Bokhankocab58582015-08-31 13:20:44 +00003656 auto *Aliasee = CGM.GetAddrOfGlobal(BaseDecl);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003657 CGM.addReplacement(MangledName, Aliasee);
3658 return;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003659 }
3660 }
3661
3662 // The base destructor is equivalent to the base destructor of its
3663 // base class if there is exactly one non-virtual base class with a
3664 // non-trivial destructor, there are no fields with a non-trivial
3665 // destructor, and the body of the destructor is trivial.
Rafael Espindola1e4df922014-09-16 15:18:21 +00003666 if (DD && Type == StructorType::Base && CGType != StructorCodegen::COMDAT &&
3667 !CGM.TryEmitBaseDestructorAsAlias(DD))
Rafael Espindola91f68b42014-09-15 19:20:10 +00003668 return;
3669
Richard Smith5b349582017-10-13 01:55:36 +00003670 // FIXME: The deleting destructor is equivalent to the selected operator
3671 // delete if:
3672 // * either the delete is a destroying operator delete or the destructor
3673 // would be trivial if it weren't virtual,
3674 // * the conversion from the 'this' parameter to the first parameter of the
3675 // destructor is equivalent to a bitcast,
3676 // * the destructor does not have an implicit "this" return, and
3677 // * the operator delete has the same calling convention and IR function type
3678 // as the destructor.
3679 // In such cases we should try to emit the deleting dtor as an alias to the
3680 // selected 'operator delete'.
3681
Rafael Espindola1e4df922014-09-16 15:18:21 +00003682 llvm::Function *Fn = CGM.codegenCXXStructor(MD, Type);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003683
Rafael Espindola1e4df922014-09-16 15:18:21 +00003684 if (CGType == StructorCodegen::COMDAT) {
3685 SmallString<256> Buffer;
3686 llvm::raw_svector_ostream Out(Buffer);
3687 if (DD)
3688 getMangleContext().mangleCXXDtorComdat(DD, Out);
3689 else
3690 getMangleContext().mangleCXXCtorComdat(CD, Out);
3691 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
3692 Fn->setComdat(C);
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003693 } else {
3694 CGM.maybeSetTrivialComdat(*MD, *Fn);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003695 }
Rafael Espindola91f68b42014-09-15 19:20:10 +00003696}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003697
3698static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) {
3699 // void *__cxa_begin_catch(void*);
3700 llvm::FunctionType *FTy = llvm::FunctionType::get(
3701 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3702
3703 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
3704}
3705
3706static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) {
3707 // void __cxa_end_catch();
3708 llvm::FunctionType *FTy =
3709 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
3710
3711 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
3712}
3713
3714static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) {
3715 // void *__cxa_get_exception_ptr(void*);
3716 llvm::FunctionType *FTy = llvm::FunctionType::get(
3717 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3718
3719 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
3720}
3721
3722namespace {
3723 /// A cleanup to call __cxa_end_catch. In many cases, the caught
3724 /// exception type lets us state definitively that the thrown exception
3725 /// type does not have a destructor. In particular:
3726 /// - Catch-alls tell us nothing, so we have to conservatively
3727 /// assume that the thrown exception might have a destructor.
3728 /// - Catches by reference behave according to their base types.
3729 /// - Catches of non-record types will only trigger for exceptions
3730 /// of non-record types, which never have destructors.
3731 /// - Catches of record types can trigger for arbitrary subclasses
3732 /// of the caught type, so we have to assume the actual thrown
3733 /// exception type might have a throwing destructor, even if the
3734 /// caught type's destructor is trivial or nothrow.
David Blaikie7e70d682015-08-18 22:40:54 +00003735 struct CallEndCatch final : EHScopeStack::Cleanup {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003736 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
3737 bool MightThrow;
3738
3739 void Emit(CodeGenFunction &CGF, Flags flags) override {
3740 if (!MightThrow) {
3741 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
3742 return;
3743 }
3744
3745 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
3746 }
3747 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003748}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003749
3750/// Emits a call to __cxa_begin_catch and enters a cleanup to call
3751/// __cxa_end_catch.
3752///
3753/// \param EndMightThrow - true if __cxa_end_catch might throw
3754static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
3755 llvm::Value *Exn,
3756 bool EndMightThrow) {
3757 llvm::CallInst *call =
3758 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
3759
3760 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
3761
3762 return call;
3763}
3764
3765/// A "special initializer" callback for initializing a catch
3766/// parameter during catch initialization.
3767static void InitCatchParam(CodeGenFunction &CGF,
3768 const VarDecl &CatchParam,
John McCall7f416cc2015-09-08 08:05:57 +00003769 Address ParamAddr,
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003770 SourceLocation Loc) {
3771 // Load the exception from where the landing pad saved it.
3772 llvm::Value *Exn = CGF.getExceptionFromSlot();
3773
3774 CanQualType CatchType =
3775 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
3776 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
3777
3778 // If we're catching by reference, we can just cast the object
3779 // pointer to the appropriate pointer.
3780 if (isa<ReferenceType>(CatchType)) {
3781 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
3782 bool EndCatchMightThrow = CaughtType->isRecordType();
3783
3784 // __cxa_begin_catch returns the adjusted object pointer.
3785 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
3786
3787 // We have no way to tell the personality function that we're
3788 // catching by reference, so if we're catching a pointer,
3789 // __cxa_begin_catch will actually return that pointer by value.
3790 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
3791 QualType PointeeType = PT->getPointeeType();
3792
3793 // When catching by reference, generally we should just ignore
3794 // this by-value pointer and use the exception object instead.
3795 if (!PointeeType->isRecordType()) {
3796
3797 // Exn points to the struct _Unwind_Exception header, which
3798 // we have to skip past in order to reach the exception data.
3799 unsigned HeaderSize =
3800 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
3801 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
3802
3803 // However, if we're catching a pointer-to-record type that won't
3804 // work, because the personality function might have adjusted
3805 // the pointer. There's actually no way for us to fully satisfy
3806 // the language/ABI contract here: we can't use Exn because it
3807 // might have the wrong adjustment, but we can't use the by-value
3808 // pointer because it's off by a level of abstraction.
3809 //
3810 // The current solution is to dump the adjusted pointer into an
3811 // alloca, which breaks language semantics (because changing the
3812 // pointer doesn't change the exception) but at least works.
3813 // The better solution would be to filter out non-exact matches
3814 // and rethrow them, but this is tricky because the rethrow
3815 // really needs to be catchable by other sites at this landing
3816 // pad. The best solution is to fix the personality function.
3817 } else {
3818 // Pull the pointer for the reference type off.
3819 llvm::Type *PtrTy =
3820 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
3821
3822 // Create the temporary and write the adjusted pointer into it.
John McCall7f416cc2015-09-08 08:05:57 +00003823 Address ExnPtrTmp =
3824 CGF.CreateTempAlloca(PtrTy, CGF.getPointerAlign(), "exn.byref.tmp");
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003825 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3826 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
3827
3828 // Bind the reference to the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00003829 AdjustedExn = ExnPtrTmp.getPointer();
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003830 }
3831 }
3832
3833 llvm::Value *ExnCast =
3834 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
3835 CGF.Builder.CreateStore(ExnCast, ParamAddr);
3836 return;
3837 }
3838
3839 // Scalars and complexes.
3840 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
3841 if (TEK != TEK_Aggregate) {
3842 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
3843
3844 // If the catch type is a pointer type, __cxa_begin_catch returns
3845 // the pointer by value.
3846 if (CatchType->hasPointerRepresentation()) {
3847 llvm::Value *CastExn =
3848 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
3849
3850 switch (CatchType.getQualifiers().getObjCLifetime()) {
3851 case Qualifiers::OCL_Strong:
3852 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
3853 // fallthrough
3854
3855 case Qualifiers::OCL_None:
3856 case Qualifiers::OCL_ExplicitNone:
3857 case Qualifiers::OCL_Autoreleasing:
3858 CGF.Builder.CreateStore(CastExn, ParamAddr);
3859 return;
3860
3861 case Qualifiers::OCL_Weak:
3862 CGF.EmitARCInitWeak(ParamAddr, CastExn);
3863 return;
3864 }
3865 llvm_unreachable("bad ownership qualifier!");
3866 }
3867
3868 // Otherwise, it returns a pointer into the exception object.
3869
3870 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3871 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3872
3873 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
John McCall7f416cc2015-09-08 08:05:57 +00003874 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003875 switch (TEK) {
3876 case TEK_Complex:
3877 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
3878 /*init*/ true);
3879 return;
3880 case TEK_Scalar: {
3881 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
3882 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
3883 return;
3884 }
3885 case TEK_Aggregate:
3886 llvm_unreachable("evaluation kind filtered out!");
3887 }
3888 llvm_unreachable("bad evaluation kind");
3889 }
3890
3891 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
John McCall7f416cc2015-09-08 08:05:57 +00003892 auto catchRD = CatchType->getAsCXXRecordDecl();
3893 CharUnits caughtExnAlignment = CGF.CGM.getClassPointerAlignment(catchRD);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003894
3895 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3896
3897 // Check for a copy expression. If we don't have a copy expression,
3898 // that means a trivial copy is okay.
3899 const Expr *copyExpr = CatchParam.getInit();
3900 if (!copyExpr) {
3901 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
John McCall7f416cc2015-09-08 08:05:57 +00003902 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3903 caughtExnAlignment);
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00003904 LValue Dest = CGF.MakeAddrLValue(ParamAddr, CatchType);
3905 LValue Src = CGF.MakeAddrLValue(adjustedExn, CatchType);
3906 CGF.EmitAggregateCopy(Dest, Src, CatchType);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003907 return;
3908 }
3909
3910 // We have to call __cxa_get_exception_ptr to get the adjusted
3911 // pointer before copying.
3912 llvm::CallInst *rawAdjustedExn =
3913 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
3914
3915 // Cast that to the appropriate type.
John McCall7f416cc2015-09-08 08:05:57 +00003916 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3917 caughtExnAlignment);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003918
3919 // The copy expression is defined in terms of an OpaqueValueExpr.
3920 // Find it and map it to the adjusted expression.
3921 CodeGenFunction::OpaqueValueMapping
3922 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
3923 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
3924
3925 // Call the copy ctor in a terminate scope.
3926 CGF.EHStack.pushTerminate();
3927
3928 // Perform the copy construction.
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003929 CGF.EmitAggExpr(copyExpr,
John McCall7f416cc2015-09-08 08:05:57 +00003930 AggValueSlot::forAddr(ParamAddr, Qualifiers(),
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003931 AggValueSlot::IsNotDestructed,
3932 AggValueSlot::DoesNotNeedGCBarriers,
3933 AggValueSlot::IsNotAliased));
3934
3935 // Leave the terminate scope.
3936 CGF.EHStack.popTerminate();
3937
3938 // Undo the opaque value mapping.
3939 opaque.pop();
3940
3941 // Finally we can call __cxa_begin_catch.
3942 CallBeginCatch(CGF, Exn, true);
3943}
3944
3945/// Begins a catch statement by initializing the catch variable and
3946/// calling __cxa_begin_catch.
3947void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF,
3948 const CXXCatchStmt *S) {
3949 // We have to be very careful with the ordering of cleanups here:
3950 // C++ [except.throw]p4:
3951 // The destruction [of the exception temporary] occurs
3952 // immediately after the destruction of the object declared in
3953 // the exception-declaration in the handler.
3954 //
3955 // So the precise ordering is:
3956 // 1. Construct catch variable.
3957 // 2. __cxa_begin_catch
3958 // 3. Enter __cxa_end_catch cleanup
3959 // 4. Enter dtor cleanup
3960 //
3961 // We do this by using a slightly abnormal initialization process.
3962 // Delegation sequence:
3963 // - ExitCXXTryStmt opens a RunCleanupsScope
3964 // - EmitAutoVarAlloca creates the variable and debug info
3965 // - InitCatchParam initializes the variable from the exception
3966 // - CallBeginCatch calls __cxa_begin_catch
3967 // - CallBeginCatch enters the __cxa_end_catch cleanup
3968 // - EmitAutoVarCleanups enters the variable destructor cleanup
3969 // - EmitCXXTryStmt emits the code for the catch body
3970 // - EmitCXXTryStmt close the RunCleanupsScope
3971
3972 VarDecl *CatchParam = S->getExceptionDecl();
3973 if (!CatchParam) {
3974 llvm::Value *Exn = CGF.getExceptionFromSlot();
3975 CallBeginCatch(CGF, Exn, true);
3976 return;
3977 }
3978
3979 // Emit the local.
3980 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
3981 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
3982 CGF.EmitAutoVarCleanups(var);
3983}
3984
3985/// Get or define the following function:
3986/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
3987/// This code is used only in C++.
3988static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
3989 llvm::FunctionType *fnTy =
3990 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00003991 llvm::Constant *fnRef = CGM.CreateRuntimeFunction(
3992 fnTy, "__clang_call_terminate", llvm::AttributeList(), /*Local=*/true);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003993
3994 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
3995 if (fn && fn->empty()) {
3996 fn->setDoesNotThrow();
3997 fn->setDoesNotReturn();
3998
3999 // What we really want is to massively penalize inlining without
4000 // forbidding it completely. The difference between that and
4001 // 'noinline' is negligible.
4002 fn->addFnAttr(llvm::Attribute::NoInline);
4003
4004 // Allow this function to be shared across translation units, but
4005 // we don't want it to turn into an exported symbol.
4006 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
4007 fn->setVisibility(llvm::Function::HiddenVisibility);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00004008 if (CGM.supportsCOMDAT())
4009 fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004010
4011 // Set up the function.
4012 llvm::BasicBlock *entry =
4013 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
John McCall7f416cc2015-09-08 08:05:57 +00004014 CGBuilderTy builder(CGM, entry);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004015
4016 // Pull the exception pointer out of the parameter list.
4017 llvm::Value *exn = &*fn->arg_begin();
4018
4019 // Call __cxa_begin_catch(exn).
4020 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
4021 catchCall->setDoesNotThrow();
4022 catchCall->setCallingConv(CGM.getRuntimeCC());
4023
4024 // Call std::terminate().
David Blaikie4ba525b2015-07-14 17:27:39 +00004025 llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn());
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004026 termCall->setDoesNotThrow();
4027 termCall->setDoesNotReturn();
4028 termCall->setCallingConv(CGM.getRuntimeCC());
4029
4030 // std::terminate cannot return.
4031 builder.CreateUnreachable();
4032 }
4033
4034 return fnRef;
4035}
4036
4037llvm::CallInst *
4038ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
4039 llvm::Value *Exn) {
4040 // In C++, we want to call __cxa_begin_catch() before terminating.
4041 if (Exn) {
4042 assert(CGF.CGM.getLangOpts().CPlusPlus);
4043 return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn);
4044 }
4045 return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
4046}
Peter Collingbourne60108802017-12-13 21:53:04 +00004047
4048std::pair<llvm::Value *, const CXXRecordDecl *>
4049ItaniumCXXABI::LoadVTablePtr(CodeGenFunction &CGF, Address This,
4050 const CXXRecordDecl *RD) {
4051 return {CGF.GetVTablePtr(This, CGM.Int8PtrTy, RD), RD};
4052}