blob: 35e707243ea0f0bdc0b3a69481690643930fdc58 [file] [log] [blame]
Charles Davis4e786dd2010-05-25 19:52:27 +00001//===------- ItaniumCXXABI.cpp - Emit LLVM Code from ASTs for a Module ----===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Charles Davis4e786dd2010-05-25 19:52:27 +00006//
7//===----------------------------------------------------------------------===//
8//
Chris Lattner57540c52011-04-15 05:22:18 +00009// This provides C++ code generation targeting the Itanium C++ ABI. The class
Charles Davis4e786dd2010-05-25 19:52:27 +000010// in this file generates structures that follow the Itanium C++ ABI, which is
11// documented at:
12// http://www.codesourcery.com/public/cxx-abi/abi.html
13// http://www.codesourcery.com/public/cxx-abi/abi-eh.html
John McCall86353412010-08-21 22:46:04 +000014//
15// It also supports the closely-related ARM ABI, documented at:
16// http://infocenter.arm.com/help/topic/com.arm.doc.ihi0041c/IHI0041C_cppabi.pdf
17//
Charles Davis4e786dd2010-05-25 19:52:27 +000018//===----------------------------------------------------------------------===//
19
20#include "CGCXXABI.h"
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000021#include "CGCleanup.h"
John McCall7a9aac22010-08-23 01:21:21 +000022#include "CGRecordLayout.h"
Charles Davisa325a6e2012-06-23 23:44:00 +000023#include "CGVTables.h"
John McCall475999d2010-08-22 00:05:51 +000024#include "CodeGenFunction.h"
Charles Davis4e786dd2010-05-25 19:52:27 +000025#include "CodeGenModule.h"
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000026#include "TargetInfo.h"
John McCall5ad74072017-03-02 20:04:19 +000027#include "clang/CodeGen/ConstantInitBuilder.h"
Craig Topperc9ee1d02012-09-15 18:47:51 +000028#include "clang/AST/Mangle.h"
29#include "clang/AST/Type.h"
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000030#include "clang/AST/StmtCXX.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000031#include "llvm/IR/DataLayout.h"
Thomas Andersonb6d87cf2018-07-24 00:43:47 +000032#include "llvm/IR/GlobalValue.h"
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000033#include "llvm/IR/Instructions.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000034#include "llvm/IR/Intrinsics.h"
35#include "llvm/IR/Value.h"
Akira Hatanaka617e2612018-04-17 18:41:52 +000036#include "llvm/Support/ScopedPrinter.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
Richard Smith00223822019-09-12 20:00:24 +000046 /// All the thread wrapper functions that have been used.
47 llvm::SmallVector<std::pair<const VarDecl *, llvm::Function *>, 8>
48 ThreadWrappers;
49
John McCall475999d2010-08-22 00:05:51 +000050protected:
Mark Seabornedf0d382013-07-24 16:25:13 +000051 bool UseARMMethodPtrABI;
52 bool UseARMGuardVarABI;
John McCalld23b27e2016-09-16 02:40:45 +000053 bool Use32BitVTableOffsetABI;
John McCall7a9aac22010-08-23 01:21:21 +000054
Timur Iskhodzhanov67455222013-10-03 06:26:13 +000055 ItaniumMangleContext &getMangleContext() {
56 return cast<ItaniumMangleContext>(CodeGen::CGCXXABI::getMangleContext());
57 }
58
Charles Davis4e786dd2010-05-25 19:52:27 +000059public:
Mark Seabornedf0d382013-07-24 16:25:13 +000060 ItaniumCXXABI(CodeGen::CodeGenModule &CGM,
61 bool UseARMMethodPtrABI = false,
62 bool UseARMGuardVarABI = false) :
63 CGCXXABI(CGM), UseARMMethodPtrABI(UseARMMethodPtrABI),
John McCalld23b27e2016-09-16 02:40:45 +000064 UseARMGuardVarABI(UseARMGuardVarABI),
Richard Smithb17d6fa2016-12-01 03:04:07 +000065 Use32BitVTableOffsetABI(false) { }
John McCall475999d2010-08-22 00:05:51 +000066
Reid Kleckner40ca9132014-05-13 22:05:45 +000067 bool classifyReturnType(CGFunctionInfo &FI) const override;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000068
Craig Topper4f12f102014-03-12 06:41:41 +000069 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override {
Richard Smith96cd6712017-08-16 01:49:53 +000070 // If C++ prohibits us from making a copy, pass by address.
Reid Kleckneradb41982019-04-30 22:23:20 +000071 if (!RD->canPassInRegisters())
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000072 return RAA_Indirect;
73 return RAA_Default;
74 }
75
John McCall7f416cc2015-09-08 08:05:57 +000076 bool isThisCompleteObject(GlobalDecl GD) const override {
77 // The Itanium ABI has separate complete-object vs. base-object
78 // variants of both constructors and destructors.
79 if (isa<CXXDestructorDecl>(GD.getDecl())) {
80 switch (GD.getDtorType()) {
81 case Dtor_Complete:
82 case Dtor_Deleting:
83 return true;
84
85 case Dtor_Base:
86 return false;
87
88 case Dtor_Comdat:
89 llvm_unreachable("emitting dtor comdat as function?");
90 }
91 llvm_unreachable("bad dtor kind");
92 }
93 if (isa<CXXConstructorDecl>(GD.getDecl())) {
94 switch (GD.getCtorType()) {
95 case Ctor_Complete:
96 return true;
97
98 case Ctor_Base:
99 return false;
100
101 case Ctor_CopyingClosure:
102 case Ctor_DefaultClosure:
103 llvm_unreachable("closure ctors in Itanium ABI?");
104
105 case Ctor_Comdat:
106 llvm_unreachable("emitting ctor comdat as function?");
107 }
108 llvm_unreachable("bad dtor kind");
109 }
110
111 // No other kinds.
112 return false;
113 }
114
Craig Topper4f12f102014-03-12 06:41:41 +0000115 bool isZeroInitializable(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +0000116
Craig Topper4f12f102014-03-12 06:41:41 +0000117 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
John McCall7a9aac22010-08-23 01:21:21 +0000118
John McCallb92ab1a2016-10-26 23:46:34 +0000119 CGCallee
Craig Topper4f12f102014-03-12 06:41:41 +0000120 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
121 const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000122 Address This,
123 llvm::Value *&ThisPtrForCall,
Craig Topper4f12f102014-03-12 06:41:41 +0000124 llvm::Value *MemFnPtr,
125 const MemberPointerType *MPT) override;
John McCalla8bbb822010-08-22 03:04:22 +0000126
Craig Topper4f12f102014-03-12 06:41:41 +0000127 llvm::Value *
128 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000129 Address Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000130 llvm::Value *MemPtr,
131 const MemberPointerType *MPT) override;
John McCallc134eb52010-08-31 21:07:20 +0000132
John McCall7a9aac22010-08-23 01:21:21 +0000133 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
134 const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +0000135 llvm::Value *Src) override;
John McCallc62bb392012-02-15 01:22:51 +0000136 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +0000137 llvm::Constant *Src) override;
John McCall84fa5102010-08-22 04:16:24 +0000138
Craig Topper4f12f102014-03-12 06:41:41 +0000139 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +0000140
David Majnemere2be95b2015-06-23 07:31:01 +0000141 llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD) override;
John McCallf3a88602011-02-03 08:15:49 +0000142 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +0000143 CharUnits offset) override;
144 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
Richard Smithdafff942012-01-14 04:30:29 +0000145 llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
146 CharUnits ThisAdjustment);
John McCall1c456c82010-08-22 06:43:33 +0000147
John McCall7a9aac22010-08-23 01:21:21 +0000148 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000149 llvm::Value *L, llvm::Value *R,
John McCall7a9aac22010-08-23 01:21:21 +0000150 const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +0000151 bool Inequality) override;
John McCall131d97d2010-08-22 08:30:07 +0000152
John McCall7a9aac22010-08-23 01:21:21 +0000153 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000154 llvm::Value *Addr,
155 const MemberPointerType *MPT) override;
John McCall5d865c322010-08-31 07:33:07 +0000156
David Majnemer08681372014-11-01 07:37:17 +0000157 void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,
John McCall7f416cc2015-09-08 08:05:57 +0000158 Address Ptr, QualType ElementType,
David Majnemer0c0b6d92014-10-31 20:09:12 +0000159 const CXXDestructorDecl *Dtor) override;
John McCall82fb8922012-09-25 10:10:39 +0000160
David Majnemer442d0a22014-11-25 07:20:20 +0000161 void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
David Majnemer7c237072015-03-05 00:46:22 +0000162 void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override;
David Majnemer442d0a22014-11-25 07:20:20 +0000163
Reid Klecknerfff8e7f2015-03-03 19:21:04 +0000164 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
165
166 llvm::CallInst *
167 emitTerminateForUnexpectedException(CodeGenFunction &CGF,
168 llvm::Value *Exn) override;
169
Thomas Andersonb6d87cf2018-07-24 00:43:47 +0000170 void EmitFundamentalRTTIDescriptors(const CXXRecordDecl *RD);
David Majnemer443250f2015-03-17 20:35:00 +0000171 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
Reid Kleckner10aa7702015-09-16 20:15:55 +0000172 CatchTypeInfo
David Majnemer37b417f2015-03-29 21:55:10 +0000173 getAddrOfCXXCatchHandlerType(QualType Ty,
174 QualType CatchHandlerType) override {
Reid Kleckner10aa7702015-09-16 20:15:55 +0000175 return CatchTypeInfo{getAddrOfRTTIDescriptor(Ty), 0};
David Majnemer443250f2015-03-17 20:35:00 +0000176 }
David Majnemere2cb8d12014-07-07 06:20:47 +0000177
David Majnemer1162d252014-06-22 19:05:33 +0000178 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
179 void EmitBadTypeidCall(CodeGenFunction &CGF) override;
180 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
John McCall7f416cc2015-09-08 08:05:57 +0000181 Address ThisPtr,
David Majnemer1162d252014-06-22 19:05:33 +0000182 llvm::Type *StdTypeInfoPtrTy) override;
183
184 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
185 QualType SrcRecordTy) override;
186
John McCall7f416cc2015-09-08 08:05:57 +0000187 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, Address Value,
David Majnemer1162d252014-06-22 19:05:33 +0000188 QualType SrcRecordTy, QualType DestTy,
189 QualType DestRecordTy,
190 llvm::BasicBlock *CastEnd) override;
191
John McCall7f416cc2015-09-08 08:05:57 +0000192 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
David Majnemer1162d252014-06-22 19:05:33 +0000193 QualType SrcRecordTy,
194 QualType DestTy) override;
195
196 bool EmitBadCastCall(CodeGenFunction &CGF) override;
197
Craig Topper4f12f102014-03-12 06:41:41 +0000198 llvm::Value *
John McCall7f416cc2015-09-08 08:05:57 +0000199 GetVirtualBaseClassOffset(CodeGenFunction &CGF, Address This,
Craig Topper4f12f102014-03-12 06:41:41 +0000200 const CXXRecordDecl *ClassDecl,
201 const CXXRecordDecl *BaseClassDecl) override;
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000202
Craig Topper4f12f102014-03-12 06:41:41 +0000203 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000204
George Burgess IVf203dbf2017-02-22 20:28:02 +0000205 AddedStructorArgs
Peter Collingbourned1c5b282019-03-22 23:05:10 +0000206 buildStructorSignature(GlobalDecl GD,
George Burgess IVf203dbf2017-02-22 20:28:02 +0000207 SmallVectorImpl<CanQualType> &ArgTys) override;
John McCall5d865c322010-08-31 07:33:07 +0000208
Reid Klecknere7de47e2013-07-22 13:51:44 +0000209 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
Craig Topper4f12f102014-03-12 06:41:41 +0000210 CXXDtorType DT) const override {
Reid Klecknere7de47e2013-07-22 13:51:44 +0000211 // Itanium does not emit any destructor variant as an inline thunk.
212 // Delegating may occur as an optimization, but all variants are either
213 // emitted with external linkage or as linkonce if they are inline and used.
214 return false;
215 }
216
Craig Topper4f12f102014-03-12 06:41:41 +0000217 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
Reid Klecknere7de47e2013-07-22 13:51:44 +0000218
Reid Kleckner89077a12013-12-17 19:46:40 +0000219 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
Craig Topper4f12f102014-03-12 06:41:41 +0000220 FunctionArgList &Params) override;
John McCall5d865c322010-08-31 07:33:07 +0000221
Craig Topper4f12f102014-03-12 06:41:41 +0000222 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
John McCall8ed55a52010-09-02 09:58:18 +0000223
George Burgess IVf203dbf2017-02-22 20:28:02 +0000224 AddedStructorArgs
225 addImplicitConstructorArgs(CodeGenFunction &CGF, const CXXConstructorDecl *D,
226 CXXCtorType Type, bool ForVirtualBase,
227 bool Delegating, CallArgList &Args) override;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000228
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000229 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
230 CXXDtorType Type, bool ForVirtualBase,
Marco Antognini88559632019-07-22 09:39:13 +0000231 bool Delegating, Address This,
232 QualType ThisTy) override;
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000233
Craig Topper4f12f102014-03-12 06:41:41 +0000234 void emitVTableDefinitions(CodeGenVTables &CGVT,
235 const CXXRecordDecl *RD) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000236
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000237 bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,
238 CodeGenFunction::VPtr Vptr) override;
239
240 bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override {
241 return true;
242 }
243
244 llvm::Constant *
245 getVTableAddressPoint(BaseSubobject Base,
246 const CXXRecordDecl *VTableClass) override;
247
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000248 llvm::Value *getVTableAddressPointInStructor(
249 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000250 BaseSubobject Base, const CXXRecordDecl *NearestVBase) override;
251
252 llvm::Value *getVTableAddressPointInStructorWithVTT(
253 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
254 BaseSubobject Base, const CXXRecordDecl *NearestVBase);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000255
256 llvm::Constant *
257 getVTableAddressPointForConstExpr(BaseSubobject Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000258 const CXXRecordDecl *VTableClass) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000259
260 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
Craig Topper4f12f102014-03-12 06:41:41 +0000261 CharUnits VPtrOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000262
John McCall9831b842018-02-06 18:52:44 +0000263 CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
264 Address This, llvm::Type *Ty,
265 SourceLocation Loc) override;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000266
David Majnemer0c0b6d92014-10-31 20:09:12 +0000267 llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
268 const CXXDestructorDecl *Dtor,
Marco Antognini88559632019-07-22 09:39:13 +0000269 CXXDtorType DtorType, Address This,
270 DeleteOrMemberCallExpr E) override;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000271
Craig Topper4f12f102014-03-12 06:41:41 +0000272 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
Reid Kleckner7810af02013-06-19 15:20:38 +0000273
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000274 bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const override;
Richard Smithc195c252018-11-27 19:33:49 +0000275 bool canSpeculativelyEmitVTableAsBaseClass(const CXXRecordDecl *RD) const;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000276
Hans Wennborgc94391d2014-06-06 20:04:01 +0000277 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
278 bool ReturnAdjustment) override {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000279 // Allow inlining of thunks by emitting them with available_externally
280 // linkage together with vtables when needed.
Peter Collingbourne8fabc1b2015-07-01 02:10:26 +0000281 if (ForVTable && !Thunk->hasLocalLinkage())
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000282 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
Rafael Espindolab7350042018-03-01 00:35:47 +0000283 CGM.setGVProperties(Thunk, GD);
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000284 }
285
Rafael Espindolab7350042018-03-01 00:35:47 +0000286 bool exportThunk() override { return true; }
287
John McCall7f416cc2015-09-08 08:05:57 +0000288 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This,
Craig Topper4f12f102014-03-12 06:41:41 +0000289 const ThisAdjustment &TA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000290
John McCall7f416cc2015-09-08 08:05:57 +0000291 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
Craig Topper4f12f102014-03-12 06:41:41 +0000292 const ReturnAdjustment &RA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000293
David Majnemer196ac332014-09-11 23:05:02 +0000294 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
295 FunctionArgList &Args) const override {
296 assert(!Args.empty() && "expected the arglist to not be empty!");
297 return Args.size() - 1;
298 }
299
Craig Topper4f12f102014-03-12 06:41:41 +0000300 StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
301 StringRef GetDeletedVirtualCallName() override
302 { return "__cxa_deleted_virtual"; }
Joao Matos2ce88ef2012-07-17 17:10:11 +0000303
Craig Topper4f12f102014-03-12 06:41:41 +0000304 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall7f416cc2015-09-08 08:05:57 +0000305 Address InitializeArrayCookie(CodeGenFunction &CGF,
306 Address NewPtr,
307 llvm::Value *NumElements,
308 const CXXNewExpr *expr,
309 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000310 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000311 Address allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000312 CharUnits cookieSize) override;
John McCall68ff0372010-09-08 01:44:27 +0000313
John McCallcdf7ef52010-11-06 09:44:32 +0000314 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000315 llvm::GlobalVariable *DeclPtr,
316 bool PerformInit) override;
Richard Smithdbf74ba2013-04-14 23:01:42 +0000317 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
James Y Knightf7321542019-02-07 01:14:17 +0000318 llvm::FunctionCallee dtor,
319 llvm::Constant *addr) override;
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000320
321 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +0000322 llvm::Value *Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000323 void EmitThreadLocalInitFuncs(
David Majnemerb3341ea2014-10-05 05:05:40 +0000324 CodeGenModule &CGM,
Richard Smith5a99c492015-12-01 01:10:48 +0000325 ArrayRef<const VarDecl *> CXXThreadLocals,
David Majnemerb3341ea2014-10-05 05:05:40 +0000326 ArrayRef<llvm::Function *> CXXThreadLocalInits,
Richard Smith5a99c492015-12-01 01:10:48 +0000327 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) override;
David Majnemerb3341ea2014-10-05 05:05:40 +0000328
Richard Smith00223822019-09-12 20:00:24 +0000329 /// Determine whether we will definitely emit this variable with a constant
330 /// initializer, either because the language semantics demand it or because
331 /// we know that the initializer is a constant.
332 bool isEmittedWithConstantInitializer(const VarDecl *VD) const {
333 VD = VD->getMostRecentDecl();
334 if (VD->hasAttr<ConstInitAttr>())
335 return true;
336
337 // All later checks examine the initializer specified on the variable. If
338 // the variable is weak, such examination would not be correct.
339 if (VD->isWeak() || VD->hasAttr<SelectAnyAttr>())
340 return false;
341
342 const VarDecl *InitDecl = VD->getInitializingDeclaration();
343 if (!InitDecl)
344 return false;
345
346 // If there's no initializer to run, this is constant initialization.
347 if (!InitDecl->hasInit())
348 return true;
349
350 // If we have the only definition, we don't need a thread wrapper if we
351 // will emit the value as a constant.
352 if (isUniqueGVALinkage(getContext().GetGVALinkageForVariable(VD)))
Richard Smith2b4fa532019-09-29 05:08:46 +0000353 return !VD->needsDestruction(getContext()) && InitDecl->evaluateValue();
Richard Smith00223822019-09-12 20:00:24 +0000354
355 // Otherwise, we need a thread wrapper unless we know that every
356 // translation unit will emit the value as a constant. We rely on
357 // ICE-ness not varying between translation units, which isn't actually
358 // guaranteed by the standard but is necessary for sanity.
359 return InitDecl->isInitKnownICE() && InitDecl->isInitICE();
360 }
361
362 bool usesThreadWrapperFunction(const VarDecl *VD) const override {
363 return !isEmittedWithConstantInitializer(VD);
364 }
Richard Smith0f383742014-03-26 22:48:22 +0000365 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
366 QualType LValType) override;
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000367
Craig Topper4f12f102014-03-12 06:41:41 +0000368 bool NeedsVTTParameter(GlobalDecl GD) override;
David Majnemere2cb8d12014-07-07 06:20:47 +0000369
370 /**************************** RTTI Uniqueness ******************************/
371
372protected:
373 /// Returns true if the ABI requires RTTI type_info objects to be unique
374 /// across a program.
375 virtual bool shouldRTTIBeUnique() const { return true; }
376
377public:
378 /// What sort of unique-RTTI behavior should we use?
379 enum RTTIUniquenessKind {
380 /// We are guaranteeing, or need to guarantee, that the RTTI string
381 /// is unique.
382 RUK_Unique,
383
384 /// We are not guaranteeing uniqueness for the RTTI string, so we
385 /// can demote to hidden visibility but must use string comparisons.
386 RUK_NonUniqueHidden,
387
388 /// We are not guaranteeing uniqueness for the RTTI string, so we
389 /// have to use string comparisons, but we also have to emit it with
390 /// non-hidden visibility.
391 RUK_NonUniqueVisible
392 };
393
394 /// Return the required visibility status for the given type and linkage in
395 /// the current ABI.
396 RTTIUniquenessKind
397 classifyRTTIUniqueness(QualType CanTy,
398 llvm::GlobalValue::LinkageTypes Linkage) const;
399 friend class ItaniumRTTIBuilder;
Rafael Espindola91f68b42014-09-15 19:20:10 +0000400
Peter Collingbourned1c5b282019-03-22 23:05:10 +0000401 void emitCXXStructor(GlobalDecl GD) override;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000402
Peter Collingbourne60108802017-12-13 21:53:04 +0000403 std::pair<llvm::Value *, const CXXRecordDecl *>
404 LoadVTablePtr(CodeGenFunction &CGF, Address This,
405 const CXXRecordDecl *RD) override;
406
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000407 private:
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000408 bool hasAnyUnusedVirtualInlineFunction(const CXXRecordDecl *RD) const {
409 const auto &VtableLayout =
410 CGM.getItaniumVTableContext().getVTableLayout(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000411
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000412 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
413 // Skip empty slot.
414 if (!VtableComponent.isUsedFunctionPointerKind())
415 continue;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000416
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000417 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
418 if (!Method->getCanonicalDecl()->isInlined())
419 continue;
420
421 StringRef Name = CGM.getMangledName(VtableComponent.getGlobalDecl());
422 auto *Entry = CGM.GetGlobalValue(Name);
423 // This checks if virtual inline function has already been emitted.
424 // Note that it is possible that this inline function would be emitted
425 // after trying to emit vtable speculatively. Because of this we do
426 // an extra pass after emitting all deferred vtables to find and emit
427 // these vtables opportunistically.
428 if (!Entry || Entry->isDeclaration())
429 return true;
430 }
431 return false;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000432 }
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000433
434 bool isVTableHidden(const CXXRecordDecl *RD) const {
435 const auto &VtableLayout =
436 CGM.getItaniumVTableContext().getVTableLayout(RD);
437
438 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
439 if (VtableComponent.isRTTIKind()) {
440 const CXXRecordDecl *RTTIDecl = VtableComponent.getRTTIDecl();
441 if (RTTIDecl->getVisibility() == Visibility::HiddenVisibility)
442 return true;
443 } else if (VtableComponent.isUsedFunctionPointerKind()) {
444 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
445 if (Method->getVisibility() == Visibility::HiddenVisibility &&
446 !Method->isDefined())
447 return true;
448 }
449 }
450 return false;
451 }
Charles Davis4e786dd2010-05-25 19:52:27 +0000452};
John McCall86353412010-08-21 22:46:04 +0000453
454class ARMCXXABI : public ItaniumCXXABI {
455public:
Mark Seabornedf0d382013-07-24 16:25:13 +0000456 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
Sam Clegga5ee6392019-07-19 00:30:23 +0000457 ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
458 /*UseARMGuardVarABI=*/true) {}
John McCall5d865c322010-08-31 07:33:07 +0000459
Craig Topper4f12f102014-03-12 06:41:41 +0000460 bool HasThisReturn(GlobalDecl GD) const override {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000461 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
462 isa<CXXDestructorDecl>(GD.getDecl()) &&
463 GD.getDtorType() != Dtor_Deleting));
464 }
John McCall5d865c322010-08-31 07:33:07 +0000465
Craig Topper4f12f102014-03-12 06:41:41 +0000466 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
467 QualType ResTy) override;
John McCall5d865c322010-08-31 07:33:07 +0000468
Craig Topper4f12f102014-03-12 06:41:41 +0000469 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall7f416cc2015-09-08 08:05:57 +0000470 Address InitializeArrayCookie(CodeGenFunction &CGF,
471 Address NewPtr,
472 llvm::Value *NumElements,
473 const CXXNewExpr *expr,
474 QualType ElementType) override;
475 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, Address allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000476 CharUnits cookieSize) override;
John McCall86353412010-08-21 22:46:04 +0000477};
Tim Northovera2ee4332014-03-29 15:09:45 +0000478
479class iOS64CXXABI : public ARMCXXABI {
480public:
John McCalld23b27e2016-09-16 02:40:45 +0000481 iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {
482 Use32BitVTableOffsetABI = true;
483 }
Tim Northover65f582f2014-03-30 17:32:48 +0000484
485 // ARM64 libraries are prepared for non-unique RTTI.
David Majnemere2cb8d12014-07-07 06:20:47 +0000486 bool shouldRTTIBeUnique() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +0000487};
Dan Gohmanc2853072015-09-03 22:51:53 +0000488
489class WebAssemblyCXXABI final : public ItaniumCXXABI {
490public:
491 explicit WebAssemblyCXXABI(CodeGen::CodeGenModule &CGM)
492 : ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
493 /*UseARMGuardVarABI=*/true) {}
Heejin Ahnc6479192018-05-31 22:18:13 +0000494 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
Dan Gohmanc2853072015-09-03 22:51:53 +0000495
496private:
497 bool HasThisReturn(GlobalDecl GD) const override {
498 return isa<CXXConstructorDecl>(GD.getDecl()) ||
499 (isa<CXXDestructorDecl>(GD.getDecl()) &&
500 GD.getDtorType() != Dtor_Deleting);
501 }
Derek Schuff8179be42016-05-10 17:44:55 +0000502 bool canCallMismatchedFunctionType() const override { return false; }
Dan Gohmanc2853072015-09-03 22:51:53 +0000503};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000504}
Charles Davis4e786dd2010-05-25 19:52:27 +0000505
Charles Davis53c59df2010-08-16 03:33:14 +0000506CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000507 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000508 // For IR-generation purposes, there's no significant difference
509 // between the ARM and iOS ABIs.
510 case TargetCXXABI::GenericARM:
511 case TargetCXXABI::iOS:
Tim Northover756447a2015-10-30 16:30:36 +0000512 case TargetCXXABI::WatchOS:
John McCall57625922013-01-25 23:36:14 +0000513 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000514
Tim Northovera2ee4332014-03-29 15:09:45 +0000515 case TargetCXXABI::iOS64:
516 return new iOS64CXXABI(CGM);
517
Tim Northover9bb857a2013-01-31 12:13:10 +0000518 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
519 // include the other 32-bit ARM oddities: constructor/destructor return values
520 // and array cookies.
521 case TargetCXXABI::GenericAArch64:
Sam Clegga5ee6392019-07-19 00:30:23 +0000522 return new ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
523 /*UseARMGuardVarABI=*/true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000524
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000525 case TargetCXXABI::GenericMIPS:
Sam Clegga5ee6392019-07-19 00:30:23 +0000526 return new ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true);
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000527
Dan Gohmanc2853072015-09-03 22:51:53 +0000528 case TargetCXXABI::WebAssembly:
529 return new WebAssemblyCXXABI(CGM);
530
John McCall57625922013-01-25 23:36:14 +0000531 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000532 if (CGM.getContext().getTargetInfo().getTriple().getArch()
533 == llvm::Triple::le32) {
534 // For PNaCl, use ARM-style method pointers so that PNaCl code
535 // does not assume anything about the alignment of function
536 // pointers.
Sam Clegga5ee6392019-07-19 00:30:23 +0000537 return new ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true);
Mark Seabornedf0d382013-07-24 16:25:13 +0000538 }
John McCall57625922013-01-25 23:36:14 +0000539 return new ItaniumCXXABI(CGM);
540
541 case TargetCXXABI::Microsoft:
542 llvm_unreachable("Microsoft ABI is not Itanium-based");
543 }
544 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000545}
546
Chris Lattnera5f58b02011-07-09 17:41:47 +0000547llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000548ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
549 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000550 return CGM.PtrDiffTy;
Serge Guelton1d993272017-05-09 19:31:30 +0000551 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy);
John McCall1c456c82010-08-22 06:43:33 +0000552}
553
John McCalld9c6c0b2010-08-22 00:59:17 +0000554/// In the Itanium and ARM ABIs, method pointers have the form:
555/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
556///
557/// In the Itanium ABI:
558/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
559/// - the this-adjustment is (memptr.adj)
560/// - the virtual offset is (memptr.ptr - 1)
561///
562/// In the ARM ABI:
563/// - method pointers are virtual if (memptr.adj & 1) is nonzero
564/// - the this-adjustment is (memptr.adj >> 1)
565/// - the virtual offset is (memptr.ptr)
566/// ARM uses 'adj' for the virtual flag because Thumb functions
567/// may be only single-byte aligned.
568///
569/// If the member is virtual, the adjusted 'this' pointer points
570/// to a vtable pointer from which the virtual offset is applied.
571///
572/// If the member is non-virtual, memptr.ptr is the address of
573/// the function to call.
John McCallb92ab1a2016-10-26 23:46:34 +0000574CGCallee ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
John McCall7f416cc2015-09-08 08:05:57 +0000575 CodeGenFunction &CGF, const Expr *E, Address ThisAddr,
576 llvm::Value *&ThisPtrForCall,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000577 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
John McCall475999d2010-08-22 00:05:51 +0000578 CGBuilderTy &Builder = CGF.Builder;
579
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000580 const FunctionProtoType *FPT =
John McCall475999d2010-08-22 00:05:51 +0000581 MPT->getPointeeType()->getAs<FunctionProtoType>();
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000582 const CXXRecordDecl *RD =
John McCall475999d2010-08-22 00:05:51 +0000583 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
584
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000585 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(
586 CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr));
John McCall475999d2010-08-22 00:05:51 +0000587
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000588 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000589
John McCalld9c6c0b2010-08-22 00:59:17 +0000590 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
591 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
592 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
593
John McCalla1dee5302010-08-22 10:59:02 +0000594 // Extract memptr.adj, which is in the second field.
595 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000596
597 // Compute the true adjustment.
598 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000599 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000600 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000601
602 // Apply the adjustment and cast back to the original struct type
603 // for consistency.
John McCall7f416cc2015-09-08 08:05:57 +0000604 llvm::Value *This = ThisAddr.getPointer();
John McCalld9c6c0b2010-08-22 00:59:17 +0000605 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
606 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
607 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall7f416cc2015-09-08 08:05:57 +0000608 ThisPtrForCall = This;
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000609
John McCall475999d2010-08-22 00:05:51 +0000610 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000611 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000612
John McCall475999d2010-08-22 00:05:51 +0000613 // If the LSB in the function pointer is 1, the function pointer points to
614 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000615 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000616 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000617 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
618 else
619 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
620 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000621 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
622
623 // In the virtual path, the adjustment left 'This' pointing to the
624 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000625 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000626 CGF.EmitBlock(FnVirtual);
627
628 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000629 llvm::Type *VTableTy = Builder.getInt8PtrTy();
John McCall7f416cc2015-09-08 08:05:57 +0000630 CharUnits VTablePtrAlign =
631 CGF.CGM.getDynamicOffsetAlignment(ThisAddr.getAlignment(), RD,
632 CGF.getPointerAlign());
633 llvm::Value *VTable =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000634 CGF.GetVTablePtr(Address(This, VTablePtrAlign), VTableTy, RD);
John McCall475999d2010-08-22 00:05:51 +0000635
636 // Apply the offset.
John McCalld23b27e2016-09-16 02:40:45 +0000637 // On ARM64, to reserve extra space in virtual member function pointers,
638 // we only pay attention to the low 32 bits of the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000639 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000640 if (!UseARMMethodPtrABI)
641 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld23b27e2016-09-16 02:40:45 +0000642 if (Use32BitVTableOffsetABI) {
643 VTableOffset = Builder.CreateTrunc(VTableOffset, CGF.Int32Ty);
644 VTableOffset = Builder.CreateZExt(VTableOffset, CGM.PtrDiffTy);
645 }
Peter Collingbournee44acad2018-06-26 02:15:47 +0000646 // Compute the address of the virtual function pointer.
647 llvm::Value *VFPAddr = Builder.CreateGEP(VTable, VTableOffset);
648
649 // Check the address of the function pointer if CFI on member function
650 // pointers is enabled.
651 llvm::Constant *CheckSourceLocation;
652 llvm::Constant *CheckTypeDesc;
653 bool ShouldEmitCFICheck = CGF.SanOpts.has(SanitizerKind::CFIMFCall) &&
654 CGM.HasHiddenLTOVisibility(RD);
655 if (ShouldEmitCFICheck) {
656 CodeGenFunction::SanitizerScope SanScope(&CGF);
657
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000658 CheckSourceLocation = CGF.EmitCheckSourceLocation(E->getBeginLoc());
Peter Collingbournee44acad2018-06-26 02:15:47 +0000659 CheckTypeDesc = CGF.EmitCheckTypeDescriptor(QualType(MPT, 0));
660 llvm::Constant *StaticData[] = {
661 llvm::ConstantInt::get(CGF.Int8Ty, CodeGenFunction::CFITCK_VMFCall),
662 CheckSourceLocation,
663 CheckTypeDesc,
664 };
665
666 llvm::Metadata *MD =
667 CGM.CreateMetadataIdentifierForVirtualMemPtrType(QualType(MPT, 0));
668 llvm::Value *TypeId = llvm::MetadataAsValue::get(CGF.getLLVMContext(), MD);
669
670 llvm::Value *TypeTest = Builder.CreateCall(
671 CGM.getIntrinsic(llvm::Intrinsic::type_test), {VFPAddr, TypeId});
672
673 if (CGM.getCodeGenOpts().SanitizeTrap.has(SanitizerKind::CFIMFCall)) {
674 CGF.EmitTrapCheck(TypeTest);
675 } else {
676 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
677 CGM.getLLVMContext(),
678 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
679 llvm::Value *ValidVtable = Builder.CreateCall(
680 CGM.getIntrinsic(llvm::Intrinsic::type_test), {VTable, AllVtables});
681 CGF.EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIMFCall),
682 SanitizerHandler::CFICheckFail, StaticData,
683 {VTable, ValidVtable});
684 }
685
686 FnVirtual = Builder.GetInsertBlock();
687 }
John McCall475999d2010-08-22 00:05:51 +0000688
689 // Load the virtual function to call.
Peter Collingbournee44acad2018-06-26 02:15:47 +0000690 VFPAddr = Builder.CreateBitCast(VFPAddr, FTy->getPointerTo()->getPointerTo());
691 llvm::Value *VirtualFn = Builder.CreateAlignedLoad(
692 VFPAddr, CGF.getPointerAlign(), "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000693 CGF.EmitBranch(FnEnd);
694
695 // In the non-virtual path, the function pointer is actually a
696 // function pointer.
697 CGF.EmitBlock(FnNonVirtual);
698 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000699 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000700
Peter Collingbournee44acad2018-06-26 02:15:47 +0000701 // Check the function pointer if CFI on member function pointers is enabled.
702 if (ShouldEmitCFICheck) {
703 CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
704 if (RD->hasDefinition()) {
705 CodeGenFunction::SanitizerScope SanScope(&CGF);
706
707 llvm::Constant *StaticData[] = {
708 llvm::ConstantInt::get(CGF.Int8Ty, CodeGenFunction::CFITCK_NVMFCall),
709 CheckSourceLocation,
710 CheckTypeDesc,
711 };
712
713 llvm::Value *Bit = Builder.getFalse();
714 llvm::Value *CastedNonVirtualFn =
715 Builder.CreateBitCast(NonVirtualFn, CGF.Int8PtrTy);
716 for (const CXXRecordDecl *Base : CGM.getMostBaseClasses(RD)) {
717 llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(
718 getContext().getMemberPointerType(
719 MPT->getPointeeType(),
720 getContext().getRecordType(Base).getTypePtr()));
721 llvm::Value *TypeId =
722 llvm::MetadataAsValue::get(CGF.getLLVMContext(), MD);
723
724 llvm::Value *TypeTest =
725 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
726 {CastedNonVirtualFn, TypeId});
727 Bit = Builder.CreateOr(Bit, TypeTest);
728 }
729
730 CGF.EmitCheck(std::make_pair(Bit, SanitizerKind::CFIMFCall),
731 SanitizerHandler::CFICheckFail, StaticData,
732 {CastedNonVirtualFn, llvm::UndefValue::get(CGF.IntPtrTy)});
733
734 FnNonVirtual = Builder.GetInsertBlock();
735 }
736 }
737
John McCall475999d2010-08-22 00:05:51 +0000738 // We're done.
739 CGF.EmitBlock(FnEnd);
John McCallb92ab1a2016-10-26 23:46:34 +0000740 llvm::PHINode *CalleePtr = Builder.CreatePHI(FTy->getPointerTo(), 2);
741 CalleePtr->addIncoming(VirtualFn, FnVirtual);
742 CalleePtr->addIncoming(NonVirtualFn, FnNonVirtual);
743
744 CGCallee Callee(FPT, CalleePtr);
John McCall475999d2010-08-22 00:05:51 +0000745 return Callee;
746}
John McCalla8bbb822010-08-22 03:04:22 +0000747
John McCallc134eb52010-08-31 21:07:20 +0000748/// Compute an l-value by applying the given pointer-to-member to a
749/// base object.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000750llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
John McCall7f416cc2015-09-08 08:05:57 +0000751 CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000752 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000753 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000754
755 CGBuilderTy &Builder = CGF.Builder;
756
John McCallc134eb52010-08-31 21:07:20 +0000757 // Cast to char*.
John McCall7f416cc2015-09-08 08:05:57 +0000758 Base = Builder.CreateElementBitCast(Base, CGF.Int8Ty);
John McCallc134eb52010-08-31 21:07:20 +0000759
760 // Apply the offset, which we assume is non-null.
John McCall7f416cc2015-09-08 08:05:57 +0000761 llvm::Value *Addr =
762 Builder.CreateInBoundsGEP(Base.getPointer(), MemPtr, "memptr.offset");
John McCallc134eb52010-08-31 21:07:20 +0000763
764 // Cast the address to the appropriate pointer type, adopting the
765 // address space of the base pointer.
John McCall7f416cc2015-09-08 08:05:57 +0000766 llvm::Type *PType = CGF.ConvertTypeForMem(MPT->getPointeeType())
767 ->getPointerTo(Base.getAddressSpace());
John McCallc134eb52010-08-31 21:07:20 +0000768 return Builder.CreateBitCast(Addr, PType);
769}
770
John McCallc62bb392012-02-15 01:22:51 +0000771/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
772/// conversion.
773///
774/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000775///
776/// Obligatory offset/adjustment diagram:
777/// <-- offset --> <-- adjustment -->
778/// |--------------------------|----------------------|--------------------|
779/// ^Derived address point ^Base address point ^Member address point
780///
781/// So when converting a base member pointer to a derived member pointer,
782/// we add the offset to the adjustment because the address point has
783/// decreased; and conversely, when converting a derived MP to a base MP
784/// we subtract the offset from the adjustment because the address point
785/// has increased.
786///
787/// The standard forbids (at compile time) conversion to and from
788/// virtual bases, which is why we don't have to consider them here.
789///
790/// The standard forbids (at run time) casting a derived MP to a base
791/// MP when the derived MP does not point to a member of the base.
792/// This is why -1 is a reasonable choice for null data member
793/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000794llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000795ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
796 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000797 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000798 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000799 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
800 E->getCastKind() == CK_ReinterpretMemberPointer);
801
802 // Under Itanium, reinterprets don't require any additional processing.
803 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
804
805 // Use constant emission if we can.
806 if (isa<llvm::Constant>(src))
807 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
808
809 llvm::Constant *adj = getMemberPointerAdjustment(E);
810 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000811
812 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000813 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000814
John McCallc62bb392012-02-15 01:22:51 +0000815 const MemberPointerType *destTy =
816 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000817
John McCall7a9aac22010-08-23 01:21:21 +0000818 // For member data pointers, this is just a matter of adding the
819 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000820 if (destTy->isMemberDataPointer()) {
821 llvm::Value *dst;
822 if (isDerivedToBase)
823 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000824 else
John McCallc62bb392012-02-15 01:22:51 +0000825 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000826
827 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000828 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
829 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
830 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000831 }
832
John McCalla1dee5302010-08-22 10:59:02 +0000833 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000834 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000835 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
836 offset <<= 1;
837 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000838 }
839
John McCallc62bb392012-02-15 01:22:51 +0000840 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
841 llvm::Value *dstAdj;
842 if (isDerivedToBase)
843 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000844 else
John McCallc62bb392012-02-15 01:22:51 +0000845 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000846
John McCallc62bb392012-02-15 01:22:51 +0000847 return Builder.CreateInsertValue(src, dstAdj, 1);
848}
849
850llvm::Constant *
851ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
852 llvm::Constant *src) {
853 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
854 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
855 E->getCastKind() == CK_ReinterpretMemberPointer);
856
857 // Under Itanium, reinterprets don't require any additional processing.
858 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
859
860 // If the adjustment is trivial, we don't need to do anything.
861 llvm::Constant *adj = getMemberPointerAdjustment(E);
862 if (!adj) return src;
863
864 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
865
866 const MemberPointerType *destTy =
867 E->getType()->castAs<MemberPointerType>();
868
869 // For member data pointers, this is just a matter of adding the
870 // offset if the source is non-null.
871 if (destTy->isMemberDataPointer()) {
872 // null maps to null.
873 if (src->isAllOnesValue()) return src;
874
875 if (isDerivedToBase)
876 return llvm::ConstantExpr::getNSWSub(src, adj);
877 else
878 return llvm::ConstantExpr::getNSWAdd(src, adj);
879 }
880
881 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000882 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000883 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
884 offset <<= 1;
885 adj = llvm::ConstantInt::get(adj->getType(), offset);
886 }
887
888 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
889 llvm::Constant *dstAdj;
890 if (isDerivedToBase)
891 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
892 else
893 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
894
895 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000896}
John McCall84fa5102010-08-22 04:16:24 +0000897
898llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000899ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000900 // Itanium C++ ABI 2.3:
901 // A NULL pointer is represented as -1.
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000902 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000903 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000904
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000905 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000906 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000907 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000908}
909
John McCallf3a88602011-02-03 08:15:49 +0000910llvm::Constant *
911ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
912 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000913 // Itanium C++ ABI 2.3:
914 // A pointer to data member is an offset from the base address of
915 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000916 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000917}
918
David Majnemere2be95b2015-06-23 07:31:01 +0000919llvm::Constant *
920ItaniumCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000921 return BuildMemberPointer(MD, CharUnits::Zero());
922}
923
924llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
925 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000926 assert(MD->isInstance() && "Member function must not be static!");
John McCalla1dee5302010-08-22 10:59:02 +0000927
928 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000929
930 // Get the function pointer (or index if this is a virtual function).
931 llvm::Constant *MemPtr[2];
932 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000933 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000934
Ken Dyckdf016282011-04-09 01:30:02 +0000935 const ASTContext &Context = getContext();
936 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000937 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000938 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000939
Mark Seabornedf0d382013-07-24 16:25:13 +0000940 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000941 // ARM C++ ABI 3.2.1:
942 // This ABI specifies that adj contains twice the this
943 // adjustment, plus 1 if the member function is virtual. The
944 // least significant bit of adj then makes exactly the same
945 // discrimination as the least significant bit of ptr does for
946 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000947 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
948 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000949 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000950 } else {
951 // Itanium C++ ABI 2.3:
952 // For a virtual function, [the pointer field] is 1 plus the
953 // virtual table offset (in bytes) of the function,
954 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000955 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
956 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000957 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000958 }
959 } else {
John McCall2979fe02011-04-12 00:42:48 +0000960 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000961 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000962 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000963 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000964 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000965 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000966 } else {
John McCall2979fe02011-04-12 00:42:48 +0000967 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
968 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000969 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000970 }
John McCall2979fe02011-04-12 00:42:48 +0000971 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000972
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000973 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000974 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
975 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000976 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000977 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000978
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000979 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000980}
981
Richard Smithdafff942012-01-14 04:30:29 +0000982llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
983 QualType MPType) {
984 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
985 const ValueDecl *MPD = MP.getMemberPointerDecl();
986 if (!MPD)
987 return EmitNullMemberPointer(MPT);
988
Reid Kleckner452abac2013-05-09 21:01:17 +0000989 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000990
991 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
992 return BuildMemberPointer(MD, ThisAdjustment);
993
994 CharUnits FieldOffset =
995 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
996 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
997}
998
John McCall131d97d2010-08-22 08:30:07 +0000999/// The comparison algorithm is pretty easy: the member pointers are
1000/// the same if they're either bitwise identical *or* both null.
1001///
1002/// ARM is different here only because null-ness is more complicated.
1003llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +00001004ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
1005 llvm::Value *L,
1006 llvm::Value *R,
1007 const MemberPointerType *MPT,
1008 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +00001009 CGBuilderTy &Builder = CGF.Builder;
1010
John McCall131d97d2010-08-22 08:30:07 +00001011 llvm::ICmpInst::Predicate Eq;
1012 llvm::Instruction::BinaryOps And, Or;
1013 if (Inequality) {
1014 Eq = llvm::ICmpInst::ICMP_NE;
1015 And = llvm::Instruction::Or;
1016 Or = llvm::Instruction::And;
1017 } else {
1018 Eq = llvm::ICmpInst::ICMP_EQ;
1019 And = llvm::Instruction::And;
1020 Or = llvm::Instruction::Or;
1021 }
1022
John McCall7a9aac22010-08-23 01:21:21 +00001023 // Member data pointers are easy because there's a unique null
1024 // value, so it just comes down to bitwise equality.
1025 if (MPT->isMemberDataPointer())
1026 return Builder.CreateICmp(Eq, L, R);
1027
1028 // For member function pointers, the tautologies are more complex.
1029 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +00001030 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +00001031 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +00001032 // (L == R) <==> (L.ptr == R.ptr &&
1033 // (L.adj == R.adj ||
1034 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +00001035 // The inequality tautologies have exactly the same structure, except
1036 // applying De Morgan's laws.
Jake Ehrlichc451cf22017-11-11 01:15:41 +00001037
John McCall7a9aac22010-08-23 01:21:21 +00001038 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
1039 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
1040
John McCall131d97d2010-08-22 08:30:07 +00001041 // This condition tests whether L.ptr == R.ptr. This must always be
1042 // true for equality to hold.
1043 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
1044
1045 // This condition, together with the assumption that L.ptr == R.ptr,
1046 // tests whether the pointers are both null. ARM imposes an extra
1047 // condition.
1048 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
1049 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
1050
1051 // This condition tests whether L.adj == R.adj. If this isn't
1052 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +00001053 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
1054 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +00001055 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
1056
1057 // Null member function pointers on ARM clear the low bit of Adj,
1058 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +00001059 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +00001060 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
1061
1062 // Compute (l.adj | r.adj) & 1 and test it against zero.
1063 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
1064 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
1065 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
1066 "cmp.or.adj");
1067 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
1068 }
1069
1070 // Tie together all our conditions.
1071 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
1072 Result = Builder.CreateBinOp(And, PtrEq, Result,
1073 Inequality ? "memptr.ne" : "memptr.eq");
1074 return Result;
1075}
1076
1077llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +00001078ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
1079 llvm::Value *MemPtr,
1080 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +00001081 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +00001082
1083 /// For member data pointers, this is just a check against -1.
1084 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +00001085 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +00001086 llvm::Value *NegativeOne =
1087 llvm::Constant::getAllOnesValue(MemPtr->getType());
1088 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
1089 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00001090
Daniel Dunbar914bc412011-04-19 23:10:47 +00001091 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +00001092 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +00001093
1094 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
1095 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
1096
Daniel Dunbar914bc412011-04-19 23:10:47 +00001097 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
1098 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +00001099 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +00001100 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +00001101 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +00001102 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +00001103 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
1104 "memptr.isvirtual");
1105 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +00001106 }
1107
1108 return Result;
1109}
John McCall1c456c82010-08-22 06:43:33 +00001110
Reid Kleckner40ca9132014-05-13 22:05:45 +00001111bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
1112 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
1113 if (!RD)
1114 return false;
1115
Richard Smith96cd6712017-08-16 01:49:53 +00001116 // If C++ prohibits us from making a copy, return by address.
Reid Kleckneradb41982019-04-30 22:23:20 +00001117 if (!RD->canPassInRegisters()) {
John McCall7f416cc2015-09-08 08:05:57 +00001118 auto Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
1119 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
Reid Kleckner40ca9132014-05-13 22:05:45 +00001120 return true;
1121 }
Reid Kleckner40ca9132014-05-13 22:05:45 +00001122 return false;
1123}
1124
John McCall614dbdc2010-08-22 21:01:12 +00001125/// The Itanium ABI requires non-zero initialization only for data
1126/// member pointers, for which '0' is a valid offset.
1127bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
David Majnemer5fd33e02015-04-24 01:25:08 +00001128 return MPT->isMemberFunctionPointer();
John McCall84fa5102010-08-22 04:16:24 +00001129}
John McCall5d865c322010-08-31 07:33:07 +00001130
John McCall82fb8922012-09-25 10:10:39 +00001131/// The Itanium ABI always places an offset to the complete object
1132/// at entry -2 in the vtable.
David Majnemer08681372014-11-01 07:37:17 +00001133void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
1134 const CXXDeleteExpr *DE,
John McCall7f416cc2015-09-08 08:05:57 +00001135 Address Ptr,
David Majnemer08681372014-11-01 07:37:17 +00001136 QualType ElementType,
1137 const CXXDestructorDecl *Dtor) {
1138 bool UseGlobalDelete = DE->isGlobalDelete();
David Majnemer0c0b6d92014-10-31 20:09:12 +00001139 if (UseGlobalDelete) {
1140 // Derive the complete-object pointer, which is what we need
1141 // to pass to the deallocation function.
John McCall82fb8922012-09-25 10:10:39 +00001142
David Majnemer0c0b6d92014-10-31 20:09:12 +00001143 // Grab the vtable pointer as an intptr_t*.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001144 auto *ClassDecl =
1145 cast<CXXRecordDecl>(ElementType->getAs<RecordType>()->getDecl());
1146 llvm::Value *VTable =
1147 CGF.GetVTablePtr(Ptr, CGF.IntPtrTy->getPointerTo(), ClassDecl);
John McCall82fb8922012-09-25 10:10:39 +00001148
David Majnemer0c0b6d92014-10-31 20:09:12 +00001149 // Track back to entry -2 and pull out the offset there.
1150 llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
1151 VTable, -2, "complete-offset.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001152 llvm::Value *Offset =
1153 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
David Majnemer0c0b6d92014-10-31 20:09:12 +00001154
1155 // Apply the offset.
John McCall7f416cc2015-09-08 08:05:57 +00001156 llvm::Value *CompletePtr =
1157 CGF.Builder.CreateBitCast(Ptr.getPointer(), CGF.Int8PtrTy);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001158 CompletePtr = CGF.Builder.CreateInBoundsGEP(CompletePtr, Offset);
1159
1160 // If we're supposed to call the global delete, make sure we do so
1161 // even if the destructor throws.
David Majnemer08681372014-11-01 07:37:17 +00001162 CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr,
1163 ElementType);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001164 }
1165
1166 // FIXME: Provide a source location here even though there's no
1167 // CXXMemberCallExpr for dtor call.
1168 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
Marco Antognini88559632019-07-22 09:39:13 +00001169 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, DE);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001170
1171 if (UseGlobalDelete)
1172 CGF.PopCleanupBlock();
John McCall82fb8922012-09-25 10:10:39 +00001173}
1174
David Majnemer442d0a22014-11-25 07:20:20 +00001175void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
1176 // void __cxa_rethrow();
1177
1178 llvm::FunctionType *FTy =
Rui Ueyama49a3ad22019-07-16 04:46:31 +00001179 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
David Majnemer442d0a22014-11-25 07:20:20 +00001180
James Y Knight9871db02019-02-05 16:42:33 +00001181 llvm::FunctionCallee Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
David Majnemer442d0a22014-11-25 07:20:20 +00001182
1183 if (isNoReturn)
1184 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, None);
1185 else
1186 CGF.EmitRuntimeCallOrInvoke(Fn);
1187}
1188
James Y Knight9871db02019-02-05 16:42:33 +00001189static llvm::FunctionCallee getAllocateExceptionFn(CodeGenModule &CGM) {
David Majnemer7c237072015-03-05 00:46:22 +00001190 // void *__cxa_allocate_exception(size_t thrown_size);
1191
1192 llvm::FunctionType *FTy =
Rui Ueyama49a3ad22019-07-16 04:46:31 +00001193 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*isVarArg=*/false);
David Majnemer7c237072015-03-05 00:46:22 +00001194
1195 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
1196}
1197
James Y Knight9871db02019-02-05 16:42:33 +00001198static llvm::FunctionCallee getThrowFn(CodeGenModule &CGM) {
David Majnemer7c237072015-03-05 00:46:22 +00001199 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
1200 // void (*dest) (void *));
1201
1202 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
1203 llvm::FunctionType *FTy =
Rui Ueyama49a3ad22019-07-16 04:46:31 +00001204 llvm::FunctionType::get(CGM.VoidTy, Args, /*isVarArg=*/false);
David Majnemer7c237072015-03-05 00:46:22 +00001205
1206 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
1207}
1208
1209void ItaniumCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
1210 QualType ThrowType = E->getSubExpr()->getType();
1211 // Now allocate the exception object.
1212 llvm::Type *SizeTy = CGF.ConvertType(getContext().getSizeType());
1213 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
1214
James Y Knight9871db02019-02-05 16:42:33 +00001215 llvm::FunctionCallee AllocExceptionFn = getAllocateExceptionFn(CGM);
David Majnemer7c237072015-03-05 00:46:22 +00001216 llvm::CallInst *ExceptionPtr = CGF.EmitNounwindRuntimeCall(
1217 AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception");
1218
Akira Hatanakac39a2432019-05-10 02:16:37 +00001219 CharUnits ExnAlign = CGF.getContext().getExnObjectAlignment();
John McCall7f416cc2015-09-08 08:05:57 +00001220 CGF.EmitAnyExprToExn(E->getSubExpr(), Address(ExceptionPtr, ExnAlign));
David Majnemer7c237072015-03-05 00:46:22 +00001221
1222 // Now throw the exception.
1223 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
1224 /*ForEH=*/true);
1225
1226 // The address of the destructor. If the exception type has a
1227 // trivial destructor (or isn't a record), we just pass null.
1228 llvm::Constant *Dtor = nullptr;
1229 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
1230 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
1231 if (!Record->hasTrivialDestructor()) {
1232 CXXDestructorDecl *DtorD = Record->getDestructor();
Peter Collingbourned1c5b282019-03-22 23:05:10 +00001233 Dtor = CGM.getAddrOfCXXStructor(GlobalDecl(DtorD, Dtor_Complete));
David Majnemer7c237072015-03-05 00:46:22 +00001234 Dtor = llvm::ConstantExpr::getBitCast(Dtor, CGM.Int8PtrTy);
1235 }
1236 }
1237 if (!Dtor) Dtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
1238
1239 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
1240 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
1241}
1242
James Y Knight9871db02019-02-05 16:42:33 +00001243static llvm::FunctionCallee getItaniumDynamicCastFn(CodeGenFunction &CGF) {
David Majnemer1162d252014-06-22 19:05:33 +00001244 // void *__dynamic_cast(const void *sub,
1245 // const abi::__class_type_info *src,
1246 // const abi::__class_type_info *dst,
1247 // std::ptrdiff_t src2dst_offset);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00001248
David Majnemer1162d252014-06-22 19:05:33 +00001249 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
Jake Ehrlichc451cf22017-11-11 01:15:41 +00001250 llvm::Type *PtrDiffTy =
David Majnemer1162d252014-06-22 19:05:33 +00001251 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1252
1253 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
1254
1255 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
1256
1257 // Mark the function as nounwind readonly.
1258 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
1259 llvm::Attribute::ReadOnly };
Reid Klecknerde864822017-03-21 16:57:30 +00001260 llvm::AttributeList Attrs = llvm::AttributeList::get(
1261 CGF.getLLVMContext(), llvm::AttributeList::FunctionIndex, FuncAttrs);
David Majnemer1162d252014-06-22 19:05:33 +00001262
1263 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
1264}
1265
James Y Knight9871db02019-02-05 16:42:33 +00001266static llvm::FunctionCallee getBadCastFn(CodeGenFunction &CGF) {
David Majnemer1162d252014-06-22 19:05:33 +00001267 // void __cxa_bad_cast();
1268 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1269 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1270}
1271
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001272/// Compute the src2dst_offset hint as described in the
David Majnemer1162d252014-06-22 19:05:33 +00001273/// Itanium C++ ABI [2.9.7]
1274static CharUnits computeOffsetHint(ASTContext &Context,
1275 const CXXRecordDecl *Src,
1276 const CXXRecordDecl *Dst) {
1277 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1278 /*DetectVirtual=*/false);
1279
1280 // If Dst is not derived from Src we can skip the whole computation below and
1281 // return that Src is not a public base of Dst. Record all inheritance paths.
1282 if (!Dst->isDerivedFrom(Src, Paths))
1283 return CharUnits::fromQuantity(-2ULL);
1284
1285 unsigned NumPublicPaths = 0;
1286 CharUnits Offset;
1287
1288 // Now walk all possible inheritance paths.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001289 for (const CXXBasePath &Path : Paths) {
1290 if (Path.Access != AS_public) // Ignore non-public inheritance.
David Majnemer1162d252014-06-22 19:05:33 +00001291 continue;
1292
1293 ++NumPublicPaths;
1294
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001295 for (const CXXBasePathElement &PathElement : Path) {
David Majnemer1162d252014-06-22 19:05:33 +00001296 // If the path contains a virtual base class we can't give any hint.
1297 // -1: no hint.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001298 if (PathElement.Base->isVirtual())
David Majnemer1162d252014-06-22 19:05:33 +00001299 return CharUnits::fromQuantity(-1ULL);
1300
1301 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
1302 continue;
1303
1304 // Accumulate the base class offsets.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001305 const ASTRecordLayout &L = Context.getASTRecordLayout(PathElement.Class);
1306 Offset += L.getBaseClassOffset(
1307 PathElement.Base->getType()->getAsCXXRecordDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001308 }
1309 }
1310
1311 // -2: Src is not a public base of Dst.
1312 if (NumPublicPaths == 0)
1313 return CharUnits::fromQuantity(-2ULL);
1314
1315 // -3: Src is a multiple public base type but never a virtual base type.
1316 if (NumPublicPaths > 1)
1317 return CharUnits::fromQuantity(-3ULL);
1318
1319 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
1320 // Return the offset of Src from the origin of Dst.
1321 return Offset;
1322}
1323
James Y Knight9871db02019-02-05 16:42:33 +00001324static llvm::FunctionCallee getBadTypeidFn(CodeGenFunction &CGF) {
David Majnemer1162d252014-06-22 19:05:33 +00001325 // void __cxa_bad_typeid();
1326 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1327
1328 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1329}
1330
1331bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
1332 QualType SrcRecordTy) {
1333 return IsDeref;
1334}
1335
1336void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
James Y Knight9871db02019-02-05 16:42:33 +00001337 llvm::FunctionCallee Fn = getBadTypeidFn(CGF);
James Y Knight3933add2019-01-30 02:54:28 +00001338 llvm::CallBase *Call = CGF.EmitRuntimeCallOrInvoke(Fn);
1339 Call->setDoesNotReturn();
David Majnemer1162d252014-06-22 19:05:33 +00001340 CGF.Builder.CreateUnreachable();
1341}
1342
1343llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
1344 QualType SrcRecordTy,
John McCall7f416cc2015-09-08 08:05:57 +00001345 Address ThisPtr,
David Majnemer1162d252014-06-22 19:05:33 +00001346 llvm::Type *StdTypeInfoPtrTy) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001347 auto *ClassDecl =
1348 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001349 llvm::Value *Value =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001350 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo(), ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001351
1352 // Load the type info.
1353 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001354 return CGF.Builder.CreateAlignedLoad(Value, CGF.getPointerAlign());
David Majnemer1162d252014-06-22 19:05:33 +00001355}
1356
1357bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1358 QualType SrcRecordTy) {
1359 return SrcIsPtr;
1360}
1361
1362llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
John McCall7f416cc2015-09-08 08:05:57 +00001363 CodeGenFunction &CGF, Address ThisAddr, QualType SrcRecordTy,
David Majnemer1162d252014-06-22 19:05:33 +00001364 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1365 llvm::Type *PtrDiffLTy =
1366 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1367 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1368
1369 llvm::Value *SrcRTTI =
1370 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1371 llvm::Value *DestRTTI =
1372 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1373
1374 // Compute the offset hint.
1375 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1376 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1377 llvm::Value *OffsetHint = llvm::ConstantInt::get(
1378 PtrDiffLTy,
1379 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
1380
1381 // Emit the call to __dynamic_cast.
John McCall7f416cc2015-09-08 08:05:57 +00001382 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001383 Value = CGF.EmitCastToVoidPtr(Value);
1384
1385 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
1386 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
1387 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1388
1389 /// C++ [expr.dynamic.cast]p9:
1390 /// A failed cast to reference type throws std::bad_cast
1391 if (DestTy->isReferenceType()) {
1392 llvm::BasicBlock *BadCastBlock =
1393 CGF.createBasicBlock("dynamic_cast.bad_cast");
1394
1395 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1396 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1397
1398 CGF.EmitBlock(BadCastBlock);
1399 EmitBadCastCall(CGF);
1400 }
1401
1402 return Value;
1403}
1404
1405llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001406 Address ThisAddr,
David Majnemer1162d252014-06-22 19:05:33 +00001407 QualType SrcRecordTy,
1408 QualType DestTy) {
1409 llvm::Type *PtrDiffLTy =
1410 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1411 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1412
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001413 auto *ClassDecl =
1414 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001415 // Get the vtable pointer.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001416 llvm::Value *VTable = CGF.GetVTablePtr(ThisAddr, PtrDiffLTy->getPointerTo(),
1417 ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001418
1419 // Get the offset-to-top from the vtable.
1420 llvm::Value *OffsetToTop =
1421 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001422 OffsetToTop =
1423 CGF.Builder.CreateAlignedLoad(OffsetToTop, CGF.getPointerAlign(),
1424 "offset.to.top");
David Majnemer1162d252014-06-22 19:05:33 +00001425
1426 // Finally, add the offset to the pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001427 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001428 Value = CGF.EmitCastToVoidPtr(Value);
1429 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1430
1431 return CGF.Builder.CreateBitCast(Value, DestLTy);
1432}
1433
1434bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
James Y Knight9871db02019-02-05 16:42:33 +00001435 llvm::FunctionCallee Fn = getBadCastFn(CGF);
James Y Knight3933add2019-01-30 02:54:28 +00001436 llvm::CallBase *Call = CGF.EmitRuntimeCallOrInvoke(Fn);
1437 Call->setDoesNotReturn();
David Majnemer1162d252014-06-22 19:05:33 +00001438 CGF.Builder.CreateUnreachable();
1439 return true;
1440}
1441
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001442llvm::Value *
1443ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001444 Address This,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001445 const CXXRecordDecl *ClassDecl,
1446 const CXXRecordDecl *BaseClassDecl) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001447 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy, ClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001448 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001449 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1450 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001451
1452 llvm::Value *VBaseOffsetPtr =
1453 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1454 "vbase.offset.ptr");
1455 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1456 CGM.PtrDiffTy->getPointerTo());
1457
1458 llvm::Value *VBaseOffset =
John McCall7f416cc2015-09-08 08:05:57 +00001459 CGF.Builder.CreateAlignedLoad(VBaseOffsetPtr, CGF.getPointerAlign(),
1460 "vbase.offset");
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001461
1462 return VBaseOffset;
1463}
1464
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001465void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1466 // Just make sure we're in sync with TargetCXXABI.
1467 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1468
Rafael Espindolac3cde362013-12-09 14:51:17 +00001469 // The constructor used for constructing this as a base class;
1470 // ignores virtual bases.
1471 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1472
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001473 // The constructor used for constructing this as a complete class;
Nico Weber4c2ffb22015-01-07 05:25:05 +00001474 // constructs the virtual bases, then calls the base constructor.
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001475 if (!D->getParent()->isAbstract()) {
1476 // We don't need to emit the complete ctor if the class is abstract.
1477 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1478 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001479}
1480
George Burgess IVf203dbf2017-02-22 20:28:02 +00001481CGCXXABI::AddedStructorArgs
Peter Collingbourned1c5b282019-03-22 23:05:10 +00001482ItaniumCXXABI::buildStructorSignature(GlobalDecl GD,
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001483 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +00001484 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001485
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001486 // All parameters are already in place except VTT, which goes after 'this'.
1487 // These are Clang types, so we don't need to worry about sret yet.
John McCall5d865c322010-08-31 07:33:07 +00001488
1489 // Check if we need to add a VTT parameter (which has type void **).
Peter Collingbourned1c5b282019-03-22 23:05:10 +00001490 if ((isa<CXXConstructorDecl>(GD.getDecl()) ? GD.getCtorType() == Ctor_Base
1491 : GD.getDtorType() == Dtor_Base) &&
1492 cast<CXXMethodDecl>(GD.getDecl())->getParent()->getNumVBases() != 0) {
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001493 ArgTys.insert(ArgTys.begin() + 1,
1494 Context.getPointerType(Context.VoidPtrTy));
George Burgess IVf203dbf2017-02-22 20:28:02 +00001495 return AddedStructorArgs::prefix(1);
1496 }
1497 return AddedStructorArgs{};
John McCall5d865c322010-08-31 07:33:07 +00001498}
1499
Reid Klecknere7de47e2013-07-22 13:51:44 +00001500void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
Rafael Espindolac3cde362013-12-09 14:51:17 +00001501 // The destructor used for destructing this as a base class; ignores
1502 // virtual bases.
1503 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001504
1505 // The destructor used for destructing this as a most-derived class;
1506 // call the base destructor and then destructs any virtual bases.
1507 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1508
Rafael Espindolac3cde362013-12-09 14:51:17 +00001509 // The destructor in a virtual table is always a 'deleting'
1510 // destructor, which calls the complete destructor and then uses the
1511 // appropriate operator delete.
1512 if (D->isVirtual())
1513 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001514}
1515
Reid Kleckner89077a12013-12-17 19:46:40 +00001516void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1517 QualType &ResTy,
1518 FunctionArgList &Params) {
John McCall5d865c322010-08-31 07:33:07 +00001519 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +00001520 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
John McCall5d865c322010-08-31 07:33:07 +00001521
1522 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001523 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +00001524 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001525
1526 // FIXME: avoid the fake decl
1527 QualType T = Context.getPointerType(Context.VoidPtrTy);
Alexey Bataev56223232017-06-09 13:40:18 +00001528 auto *VTTDecl = ImplicitParamDecl::Create(
1529 Context, /*DC=*/nullptr, MD->getLocation(), &Context.Idents.get("vtt"),
1530 T, ImplicitParamDecl::CXXVTT);
Reid Kleckner89077a12013-12-17 19:46:40 +00001531 Params.insert(Params.begin() + 1, VTTDecl);
Reid Kleckner2af6d732013-12-13 00:09:59 +00001532 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +00001533 }
1534}
1535
John McCall5d865c322010-08-31 07:33:07 +00001536void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
Justin Lebared4f1722016-07-27 22:04:24 +00001537 // Naked functions have no prolog.
1538 if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>())
1539 return;
1540
Reid Kleckner06239e42017-11-16 19:09:36 +00001541 /// Initialize the 'this' slot. In the Itanium C++ ABI, no prologue
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001542 /// adjustments are required, because they are all handled by thunks.
Reid Kleckner06239e42017-11-16 19:09:36 +00001543 setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));
John McCall5d865c322010-08-31 07:33:07 +00001544
1545 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +00001546 if (getStructorImplicitParamDecl(CGF)) {
1547 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1548 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +00001549 }
John McCall5d865c322010-08-31 07:33:07 +00001550
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001551 /// If this is a function that the ABI specifies returns 'this', initialize
1552 /// the return slot to 'this' at the start of the function.
1553 ///
1554 /// Unlike the setting of return types, this is done within the ABI
1555 /// implementation instead of by clients of CGCXXABI because:
1556 /// 1) getThisValue is currently protected
1557 /// 2) in theory, an ABI could implement 'this' returns some other way;
1558 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +00001559 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +00001560 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +00001561}
1562
George Burgess IVf203dbf2017-02-22 20:28:02 +00001563CGCXXABI::AddedStructorArgs ItaniumCXXABI::addImplicitConstructorArgs(
Reid Kleckner89077a12013-12-17 19:46:40 +00001564 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1565 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1566 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
George Burgess IVf203dbf2017-02-22 20:28:02 +00001567 return AddedStructorArgs{};
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001568
Reid Kleckner89077a12013-12-17 19:46:40 +00001569 // Insert the implicit 'vtt' argument as the second argument.
1570 llvm::Value *VTT =
1571 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1572 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
Yaxun Liu5b330e82018-03-15 15:25:19 +00001573 Args.insert(Args.begin() + 1, CallArg(RValue::get(VTT), VTTTy));
George Burgess IVf203dbf2017-02-22 20:28:02 +00001574 return AddedStructorArgs::prefix(1); // Added one arg.
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001575}
1576
1577void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1578 const CXXDestructorDecl *DD,
1579 CXXDtorType Type, bool ForVirtualBase,
Marco Antognini88559632019-07-22 09:39:13 +00001580 bool Delegating, Address This,
1581 QualType ThisTy) {
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001582 GlobalDecl GD(DD, Type);
1583 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1584 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1585
John McCallb92ab1a2016-10-26 23:46:34 +00001586 CGCallee Callee;
1587 if (getContext().getLangOpts().AppleKext &&
1588 Type != Dtor_Base && DD->isVirtual())
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001589 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
John McCallb92ab1a2016-10-26 23:46:34 +00001590 else
Peter Collingbourned1c5b282019-03-22 23:05:10 +00001591 Callee = CGCallee::forDirect(CGM.getAddrOfCXXStructor(GD), GD);
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001592
Marco Antognini88559632019-07-22 09:39:13 +00001593 CGF.EmitCXXDestructorCall(GD, Callee, This.getPointer(), ThisTy, VTT, VTTTy,
1594 nullptr);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001595}
1596
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001597void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1598 const CXXRecordDecl *RD) {
1599 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1600 if (VTable->hasInitializer())
1601 return;
1602
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001603 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001604 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1605 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
David Majnemerd905da42014-07-01 20:30:31 +00001606 llvm::Constant *RTTI =
1607 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001608
1609 // Create and set the initializer.
John McCall9c6cb762016-11-28 22:18:33 +00001610 ConstantInitBuilder Builder(CGM);
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001611 auto Components = Builder.beginStruct();
John McCall9c6cb762016-11-28 22:18:33 +00001612 CGVT.createVTableInitializer(Components, VTLayout, RTTI);
1613 Components.finishAndSetAsInitializer(VTable);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001614
1615 // Set the correct linkage.
1616 VTable->setLinkage(Linkage);
1617
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001618 if (CGM.supportsCOMDAT() && VTable->isWeakForLinker())
1619 VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName()));
Rafael Espindolacb92c192015-01-15 23:18:01 +00001620
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001621 // Set the right visibility.
Rafael Espindola699f5d62018-02-07 22:15:33 +00001622 CGM.setGVProperties(VTable, RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001623
1624 // If this is the magic class __cxxabiv1::__fundamental_type_info,
1625 // we will emit the typeinfo for the fundamental types. This is the
1626 // same behaviour as GCC.
1627 const DeclContext *DC = RD->getDeclContext();
1628 if (RD->getIdentifier() &&
1629 RD->getIdentifier()->isStr("__fundamental_type_info") &&
1630 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1631 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1632 DC->getParent()->isTranslationUnit())
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00001633 EmitFundamentalRTTIDescriptors(RD);
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001634
Evgeniy Stepanov93987df2016-01-23 01:20:18 +00001635 if (!VTable->isDeclarationForLinker())
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001636 CGM.EmitVTableTypeMetadata(VTable, VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001637}
1638
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001639bool ItaniumCXXABI::isVirtualOffsetNeededForVTableField(
1640 CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
1641 if (Vptr.NearestVBase == nullptr)
1642 return false;
1643 return NeedsVTTParameter(CGF.CurGD);
Piotr Padlewski255652e2015-09-09 22:20:28 +00001644}
1645
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001646llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1647 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1648 const CXXRecordDecl *NearestVBase) {
1649
1650 if ((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1651 NeedsVTTParameter(CGF.CurGD)) {
1652 return getVTableAddressPointInStructorWithVTT(CGF, VTableClass, Base,
1653 NearestVBase);
1654 }
1655 return getVTableAddressPoint(Base, VTableClass);
1656}
1657
1658llvm::Constant *
1659ItaniumCXXABI::getVTableAddressPoint(BaseSubobject Base,
1660 const CXXRecordDecl *VTableClass) {
1661 llvm::GlobalValue *VTable = getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001662
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001663 // Find the appropriate vtable within the vtable group, and the address point
1664 // within that vtable.
1665 VTableLayout::AddressPointLocation AddressPoint =
1666 CGM.getItaniumVTableContext()
1667 .getVTableLayout(VTableClass)
1668 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001669 llvm::Value *Indices[] = {
Peter Collingbourne4e6a5402016-03-14 19:07:10 +00001670 llvm::ConstantInt::get(CGM.Int32Ty, 0),
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001671 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.VTableIndex),
1672 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.AddressPointIndex),
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001673 };
1674
Peter Collingbourne25a2b702016-12-13 20:50:44 +00001675 return llvm::ConstantExpr::getGetElementPtr(VTable->getValueType(), VTable,
1676 Indices, /*InBounds=*/true,
1677 /*InRangeIndex=*/1);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001678}
1679
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001680llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructorWithVTT(
1681 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1682 const CXXRecordDecl *NearestVBase) {
1683 assert((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1684 NeedsVTTParameter(CGF.CurGD) && "This class doesn't have VTT");
1685
1686 // Get the secondary vpointer index.
1687 uint64_t VirtualPointerIndex =
1688 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1689
1690 /// Load the VTT.
1691 llvm::Value *VTT = CGF.LoadCXXVTT();
1692 if (VirtualPointerIndex)
1693 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1694
1695 // And load the address point from the VTT.
1696 return CGF.Builder.CreateAlignedLoad(VTT, CGF.getPointerAlign());
1697}
1698
1699llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1700 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1701 return getVTableAddressPoint(Base, VTableClass);
1702}
1703
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001704llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1705 CharUnits VPtrOffset) {
1706 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1707
1708 llvm::GlobalVariable *&VTable = VTables[RD];
1709 if (VTable)
1710 return VTable;
1711
Eric Christopherd160c502016-01-29 01:35:53 +00001712 // Queue up this vtable for possible deferred emission.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001713 CGM.addDeferredVTable(RD);
1714
Yaron Kerene46f7ed2015-07-29 14:21:47 +00001715 SmallString<256> Name;
1716 llvm::raw_svector_ostream Out(Name);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001717 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001718
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001719 const VTableLayout &VTLayout =
1720 CGM.getItaniumVTableContext().getVTableLayout(RD);
1721 llvm::Type *VTableType = CGM.getVTables().getVTableType(VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001722
David Greenbe0c5b62018-09-12 14:09:06 +00001723 // Use pointer alignment for the vtable. Otherwise we would align them based
1724 // on the size of the initializer which doesn't make sense as only single
1725 // values are read.
1726 unsigned PAlign = CGM.getTarget().getPointerAlign(0);
1727
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001728 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
David Greenbe0c5b62018-09-12 14:09:06 +00001729 Name, VTableType, llvm::GlobalValue::ExternalLinkage,
1730 getContext().toCharUnitsFromBits(PAlign).getQuantity());
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001731 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Hans Wennborgda24e9c2014-06-02 23:13:03 +00001732
Rafael Espindola922f2aa2018-02-23 19:30:48 +00001733 CGM.setGVProperties(VTable, RD);
1734
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001735 return VTable;
1736}
1737
John McCall9831b842018-02-06 18:52:44 +00001738CGCallee ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1739 GlobalDecl GD,
1740 Address This,
1741 llvm::Type *Ty,
1742 SourceLocation Loc) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001743 Ty = Ty->getPointerTo()->getPointerTo();
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001744 auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
1745 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty, MethodDecl->getParent());
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001746
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001747 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
John McCall9831b842018-02-06 18:52:44 +00001748 llvm::Value *VFunc;
1749 if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) {
1750 VFunc = CGF.EmitVTableTypeCheckedLoad(
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001751 MethodDecl->getParent(), VTable,
1752 VTableIndex * CGM.getContext().getTargetInfo().getPointerWidth(0) / 8);
John McCall9831b842018-02-06 18:52:44 +00001753 } else {
1754 CGF.EmitTypeMetadataCodeForVCall(MethodDecl->getParent(), VTable, Loc);
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001755
John McCall9831b842018-02-06 18:52:44 +00001756 llvm::Value *VFuncPtr =
1757 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1758 auto *VFuncLoad =
1759 CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign());
Piotr Padlewski77cc9622016-10-29 15:28:30 +00001760
John McCall9831b842018-02-06 18:52:44 +00001761 // Add !invariant.load md to virtual function load to indicate that
1762 // function didn't change inside vtable.
1763 // It's safe to add it without -fstrict-vtable-pointers, but it would not
1764 // help in devirtualization because it will only matter if we will have 2
1765 // the same virtual function loads from the same vtable load, which won't
1766 // happen without enabled devirtualization with -fstrict-vtable-pointers.
1767 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1768 CGM.getCodeGenOpts().StrictVTablePointers)
1769 VFuncLoad->setMetadata(
1770 llvm::LLVMContext::MD_invariant_load,
1771 llvm::MDNode::get(CGM.getLLVMContext(),
1772 llvm::ArrayRef<llvm::Metadata *>()));
1773 VFunc = VFuncLoad;
1774 }
John McCallb92ab1a2016-10-26 23:46:34 +00001775
Erich Keanede6480a32018-11-13 15:48:08 +00001776 CGCallee Callee(GD, VFunc);
John McCall9831b842018-02-06 18:52:44 +00001777 return Callee;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001778}
1779
David Majnemer0c0b6d92014-10-31 20:09:12 +00001780llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
1781 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
Marco Antognini88559632019-07-22 09:39:13 +00001782 Address This, DeleteOrMemberCallExpr E) {
1783 auto *CE = E.dyn_cast<const CXXMemberCallExpr *>();
1784 auto *D = E.dyn_cast<const CXXDeleteExpr *>();
1785 assert((CE != nullptr) ^ (D != nullptr));
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001786 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001787 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1788
Peter Collingbourned1c5b282019-03-22 23:05:10 +00001789 GlobalDecl GD(Dtor, DtorType);
1790 const CGFunctionInfo *FInfo =
1791 &CGM.getTypes().arrangeCXXStructorDeclaration(GD);
George Burgess IV00f70bd2018-03-01 05:43:23 +00001792 llvm::FunctionType *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Peter Collingbourned1c5b282019-03-22 23:05:10 +00001793 CGCallee Callee = CGCallee::forVirtual(CE, GD, This, Ty);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001794
Marco Antognini88559632019-07-22 09:39:13 +00001795 QualType ThisTy;
1796 if (CE) {
1797 ThisTy = CE->getObjectType();
1798 } else {
1799 ThisTy = D->getDestroyedType();
1800 }
1801
1802 CGF.EmitCXXDestructorCall(GD, Callee, This.getPointer(), ThisTy, nullptr,
1803 QualType(), nullptr);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001804 return nullptr;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001805}
1806
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001807void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001808 CodeGenVTables &VTables = CGM.getVTables();
1809 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001810 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001811}
1812
Richard Smithc195c252018-11-27 19:33:49 +00001813bool ItaniumCXXABI::canSpeculativelyEmitVTableAsBaseClass(
1814 const CXXRecordDecl *RD) const {
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001815 // We don't emit available_externally vtables if we are in -fapple-kext mode
1816 // because kext mode does not permit devirtualization.
1817 if (CGM.getLangOpts().AppleKext)
1818 return false;
1819
Piotr Padlewskie368de32018-06-13 13:55:42 +00001820 // If the vtable is hidden then it is not safe to emit an available_externally
1821 // copy of vtable.
1822 if (isVTableHidden(RD))
1823 return false;
1824
1825 if (CGM.getCodeGenOpts().ForceEmitVTables)
1826 return true;
1827
1828 // If we don't have any not emitted inline virtual function then we are safe
1829 // to emit an available_externally copy of vtable.
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001830 // FIXME we can still emit a copy of the vtable if we
1831 // can emit definition of the inline functions.
Richard Smithc195c252018-11-27 19:33:49 +00001832 if (hasAnyUnusedVirtualInlineFunction(RD))
1833 return false;
1834
1835 // For a class with virtual bases, we must also be able to speculatively
1836 // emit the VTT, because CodeGen doesn't have separate notions of "can emit
1837 // the vtable" and "can emit the VTT". For a base subobject, this means we
1838 // need to be able to emit non-virtual base vtables.
1839 if (RD->getNumVBases()) {
1840 for (const auto &B : RD->bases()) {
1841 auto *BRD = B.getType()->getAsCXXRecordDecl();
1842 assert(BRD && "no class for base specifier");
1843 if (B.isVirtual() || !BRD->isDynamicClass())
1844 continue;
1845 if (!canSpeculativelyEmitVTableAsBaseClass(BRD))
1846 return false;
1847 }
1848 }
1849
1850 return true;
1851}
1852
1853bool ItaniumCXXABI::canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const {
1854 if (!canSpeculativelyEmitVTableAsBaseClass(RD))
1855 return false;
1856
1857 // For a complete-object vtable (or more specifically, for the VTT), we need
1858 // to be able to speculatively emit the vtables of all dynamic virtual bases.
1859 for (const auto &B : RD->vbases()) {
1860 auto *BRD = B.getType()->getAsCXXRecordDecl();
1861 assert(BRD && "no class for base specifier");
1862 if (!BRD->isDynamicClass())
1863 continue;
1864 if (!canSpeculativelyEmitVTableAsBaseClass(BRD))
1865 return false;
1866 }
1867
1868 return true;
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001869}
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001870static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001871 Address InitialPtr,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001872 int64_t NonVirtualAdjustment,
1873 int64_t VirtualAdjustment,
1874 bool IsReturnAdjustment) {
1875 if (!NonVirtualAdjustment && !VirtualAdjustment)
John McCall7f416cc2015-09-08 08:05:57 +00001876 return InitialPtr.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001877
John McCall7f416cc2015-09-08 08:05:57 +00001878 Address V = CGF.Builder.CreateElementBitCast(InitialPtr, CGF.Int8Ty);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001879
John McCall7f416cc2015-09-08 08:05:57 +00001880 // In a base-to-derived cast, the non-virtual adjustment is applied first.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001881 if (NonVirtualAdjustment && !IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001882 V = CGF.Builder.CreateConstInBoundsByteGEP(V,
1883 CharUnits::fromQuantity(NonVirtualAdjustment));
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001884 }
1885
John McCall7f416cc2015-09-08 08:05:57 +00001886 // Perform the virtual adjustment if we have one.
1887 llvm::Value *ResultPtr;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001888 if (VirtualAdjustment) {
1889 llvm::Type *PtrDiffTy =
1890 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1891
John McCall7f416cc2015-09-08 08:05:57 +00001892 Address VTablePtrPtr = CGF.Builder.CreateElementBitCast(V, CGF.Int8PtrTy);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001893 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1894
1895 llvm::Value *OffsetPtr =
1896 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1897
1898 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1899
1900 // Load the adjustment offset from the vtable.
John McCall7f416cc2015-09-08 08:05:57 +00001901 llvm::Value *Offset =
1902 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001903
1904 // Adjust our pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001905 ResultPtr = CGF.Builder.CreateInBoundsGEP(V.getPointer(), Offset);
1906 } else {
1907 ResultPtr = V.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001908 }
1909
John McCall7f416cc2015-09-08 08:05:57 +00001910 // In a derived-to-base conversion, the non-virtual adjustment is
1911 // applied second.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001912 if (NonVirtualAdjustment && IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001913 ResultPtr = CGF.Builder.CreateConstInBoundsGEP1_64(ResultPtr,
1914 NonVirtualAdjustment);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001915 }
1916
1917 // Cast back to the original type.
John McCall7f416cc2015-09-08 08:05:57 +00001918 return CGF.Builder.CreateBitCast(ResultPtr, InitialPtr.getType());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001919}
1920
1921llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001922 Address This,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001923 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001924 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1925 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001926 /*IsReturnAdjustment=*/false);
1927}
1928
1929llvm::Value *
John McCall7f416cc2015-09-08 08:05:57 +00001930ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001931 const ReturnAdjustment &RA) {
1932 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1933 RA.Virtual.Itanium.VBaseOffsetOffset,
1934 /*IsReturnAdjustment=*/true);
1935}
1936
John McCall5d865c322010-08-31 07:33:07 +00001937void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1938 RValue RV, QualType ResultType) {
1939 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1940 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1941
1942 // Destructor thunks in the ARM ABI have indeterminate results.
John McCall7f416cc2015-09-08 08:05:57 +00001943 llvm::Type *T = CGF.ReturnValue.getElementType();
John McCall5d865c322010-08-31 07:33:07 +00001944 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1945 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1946}
John McCall8ed55a52010-09-02 09:58:18 +00001947
1948/************************** Array allocation cookies **************************/
1949
John McCallb91cd662012-05-01 05:23:51 +00001950CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1951 // The array cookie is a size_t; pad that up to the element alignment.
1952 // The cookie is actually right-justified in that space.
1953 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1954 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001955}
1956
John McCall7f416cc2015-09-08 08:05:57 +00001957Address ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1958 Address NewPtr,
1959 llvm::Value *NumElements,
1960 const CXXNewExpr *expr,
1961 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001962 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001963
John McCall7f416cc2015-09-08 08:05:57 +00001964 unsigned AS = NewPtr.getAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001965
John McCall9bca9232010-09-02 10:25:57 +00001966 ASTContext &Ctx = getContext();
John McCall7f416cc2015-09-08 08:05:57 +00001967 CharUnits SizeSize = CGF.getSizeSize();
John McCall8ed55a52010-09-02 09:58:18 +00001968
1969 // The size of the cookie.
1970 CharUnits CookieSize =
1971 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001972 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001973
1974 // Compute an offset to the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001975 Address CookiePtr = NewPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001976 CharUnits CookieOffset = CookieSize - SizeSize;
1977 if (!CookieOffset.isZero())
John McCall7f416cc2015-09-08 08:05:57 +00001978 CookiePtr = CGF.Builder.CreateConstInBoundsByteGEP(CookiePtr, CookieOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001979
1980 // Write the number of elements into the appropriate slot.
John McCall7f416cc2015-09-08 08:05:57 +00001981 Address NumElementsPtr =
1982 CGF.Builder.CreateElementBitCast(CookiePtr, CGF.SizeTy);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001983 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
John McCall7f416cc2015-09-08 08:05:57 +00001984
1985 // Handle the array cookie specially in ASan.
Filipe Cabecinhas6f83fa92018-01-02 13:46:12 +00001986 if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 &&
Filipe Cabecinhas4ba58172018-02-12 11:49:02 +00001987 (expr->getOperatorNew()->isReplaceableGlobalAllocationFunction() ||
Filipe Cabecinhas0eb50082018-11-02 17:29:04 +00001988 CGM.getCodeGenOpts().SanitizeAddressPoisonCustomArrayCookie)) {
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001989 // The store to the CookiePtr does not need to be instrumented.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001990 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
1991 llvm::FunctionType *FTy =
John McCall7f416cc2015-09-08 08:05:57 +00001992 llvm::FunctionType::get(CGM.VoidTy, NumElementsPtr.getType(), false);
James Y Knight9871db02019-02-05 16:42:33 +00001993 llvm::FunctionCallee F =
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001994 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001995 CGF.Builder.CreateCall(F, NumElementsPtr.getPointer());
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001996 }
John McCall8ed55a52010-09-02 09:58:18 +00001997
1998 // Finally, compute a pointer to the actual data buffer by skipping
1999 // over the cookie completely.
John McCall7f416cc2015-09-08 08:05:57 +00002000 return CGF.Builder.CreateConstInBoundsByteGEP(NewPtr, CookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00002001}
2002
John McCallb91cd662012-05-01 05:23:51 +00002003llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002004 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00002005 CharUnits cookieSize) {
2006 // The element size is right-justified in the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00002007 Address numElementsPtr = allocPtr;
2008 CharUnits numElementsOffset = cookieSize - CGF.getSizeSize();
John McCallb91cd662012-05-01 05:23:51 +00002009 if (!numElementsOffset.isZero())
2010 numElementsPtr =
John McCall7f416cc2015-09-08 08:05:57 +00002011 CGF.Builder.CreateConstInBoundsByteGEP(numElementsPtr, numElementsOffset);
John McCall8ed55a52010-09-02 09:58:18 +00002012
John McCall7f416cc2015-09-08 08:05:57 +00002013 unsigned AS = allocPtr.getAddressSpace();
2014 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002015 if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0)
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00002016 return CGF.Builder.CreateLoad(numElementsPtr);
2017 // In asan mode emit a function call instead of a regular load and let the
2018 // run-time deal with it: if the shadow is properly poisoned return the
2019 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
2020 // We can't simply ignore this load using nosanitize metadata because
2021 // the metadata may be lost.
2022 llvm::FunctionType *FTy =
2023 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
James Y Knight9871db02019-02-05 16:42:33 +00002024 llvm::FunctionCallee F =
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00002025 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00002026 return CGF.Builder.CreateCall(F, numElementsPtr.getPointer());
John McCall8ed55a52010-09-02 09:58:18 +00002027}
2028
John McCallb91cd662012-05-01 05:23:51 +00002029CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00002030 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00002031 // struct array_cookie {
2032 // std::size_t element_size; // element_size != 0
2033 // std::size_t element_count;
2034 // };
John McCallc19c7062013-01-25 23:36:19 +00002035 // But the base ABI doesn't give anything an alignment greater than
2036 // 8, so we can dismiss this as typical ABI-author blindness to
2037 // actual language complexity and round up to the element alignment.
2038 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
2039 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00002040}
2041
John McCall7f416cc2015-09-08 08:05:57 +00002042Address ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
2043 Address newPtr,
2044 llvm::Value *numElements,
2045 const CXXNewExpr *expr,
2046 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00002047 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00002048
John McCall8ed55a52010-09-02 09:58:18 +00002049 // The cookie is always at the start of the buffer.
John McCall7f416cc2015-09-08 08:05:57 +00002050 Address cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00002051
2052 // The first element is the element size.
John McCall7f416cc2015-09-08 08:05:57 +00002053 cookie = CGF.Builder.CreateElementBitCast(cookie, CGF.SizeTy);
John McCallc19c7062013-01-25 23:36:19 +00002054 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
2055 getContext().getTypeSizeInChars(elementType).getQuantity());
2056 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00002057
2058 // The second element is the element count.
James Y Knight751fe282019-02-09 22:22:28 +00002059 cookie = CGF.Builder.CreateConstInBoundsGEP(cookie, 1);
John McCallc19c7062013-01-25 23:36:19 +00002060 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00002061
2062 // Finally, compute a pointer to the actual data buffer by skipping
2063 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00002064 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
John McCall7f416cc2015-09-08 08:05:57 +00002065 return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00002066}
2067
John McCallb91cd662012-05-01 05:23:51 +00002068llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002069 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00002070 CharUnits cookieSize) {
2071 // The number of elements is at offset sizeof(size_t) relative to
2072 // the allocated pointer.
John McCall7f416cc2015-09-08 08:05:57 +00002073 Address numElementsPtr
2074 = CGF.Builder.CreateConstInBoundsByteGEP(allocPtr, CGF.getSizeSize());
John McCall8ed55a52010-09-02 09:58:18 +00002075
John McCall7f416cc2015-09-08 08:05:57 +00002076 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
John McCallb91cd662012-05-01 05:23:51 +00002077 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00002078}
2079
John McCall68ff0372010-09-08 01:44:27 +00002080/*********************** Static local initialization **************************/
2081
James Y Knight9871db02019-02-05 16:42:33 +00002082static llvm::FunctionCallee getGuardAcquireFn(CodeGenModule &CGM,
2083 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00002084 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00002085 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00002086 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00002087 GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00002088 return CGM.CreateRuntimeFunction(
2089 FTy, "__cxa_guard_acquire",
2090 llvm::AttributeList::get(CGM.getLLVMContext(),
2091 llvm::AttributeList::FunctionIndex,
2092 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00002093}
2094
James Y Knight9871db02019-02-05 16:42:33 +00002095static llvm::FunctionCallee getGuardReleaseFn(CodeGenModule &CGM,
2096 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00002097 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00002098 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00002099 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00002100 return CGM.CreateRuntimeFunction(
2101 FTy, "__cxa_guard_release",
2102 llvm::AttributeList::get(CGM.getLLVMContext(),
2103 llvm::AttributeList::FunctionIndex,
2104 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00002105}
2106
James Y Knight9871db02019-02-05 16:42:33 +00002107static llvm::FunctionCallee getGuardAbortFn(CodeGenModule &CGM,
2108 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00002109 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00002110 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00002111 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00002112 return CGM.CreateRuntimeFunction(
2113 FTy, "__cxa_guard_abort",
2114 llvm::AttributeList::get(CGM.getLLVMContext(),
2115 llvm::AttributeList::FunctionIndex,
2116 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00002117}
2118
2119namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002120 struct CallGuardAbort final : EHScopeStack::Cleanup {
John McCall68ff0372010-09-08 01:44:27 +00002121 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00002122 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00002123
Craig Topper4f12f102014-03-12 06:41:41 +00002124 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00002125 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
2126 Guard);
John McCall68ff0372010-09-08 01:44:27 +00002127 }
2128 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002129}
John McCall68ff0372010-09-08 01:44:27 +00002130
2131/// The ARM code here follows the Itanium code closely enough that we
2132/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00002133void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
2134 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00002135 llvm::GlobalVariable *var,
2136 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00002137 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00002138
Richard Smith62f19e72016-06-25 00:15:56 +00002139 // Inline variables that weren't instantiated from variable templates have
2140 // partially-ordered initialization within their translation unit.
2141 bool NonTemplateInline =
2142 D.isInline() &&
2143 !isTemplateInstantiation(D.getTemplateSpecializationKind());
2144
2145 // We only need to use thread-safe statics for local non-TLS variables and
2146 // inline variables; other global initialization is always single-threaded
2147 // or (through lazy dynamic loading in multiple threads) unsequenced.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002148 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
Richard Smith62f19e72016-06-25 00:15:56 +00002149 (D.isLocalVarDecl() || NonTemplateInline) &&
2150 !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00002151
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00002152 // If we have a global variable with internal linkage and thread-safe statics
2153 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00002154 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
2155
2156 llvm::IntegerType *guardTy;
John McCall7f416cc2015-09-08 08:05:57 +00002157 CharUnits guardAlignment;
John McCall5aa52592011-06-17 07:33:57 +00002158 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00002159 guardTy = CGF.Int8Ty;
John McCall7f416cc2015-09-08 08:05:57 +00002160 guardAlignment = CharUnits::One();
John McCall5aa52592011-06-17 07:33:57 +00002161 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00002162 // Guard variables are 64 bits in the generic ABI and size width on ARM
2163 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
John McCall7f416cc2015-09-08 08:05:57 +00002164 if (UseARMGuardVarABI) {
2165 guardTy = CGF.SizeTy;
2166 guardAlignment = CGF.getSizeAlign();
2167 } else {
2168 guardTy = CGF.Int64Ty;
2169 guardAlignment = CharUnits::fromQuantity(
2170 CGM.getDataLayout().getABITypeAlignment(guardTy));
2171 }
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00002172 }
John McCallb88a5662012-03-30 21:00:39 +00002173 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00002174
John McCallb88a5662012-03-30 21:00:39 +00002175 // Create the guard variable if we don't already have it (as we
2176 // might if we're double-emitting this function body).
2177 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
2178 if (!guard) {
2179 // Mangle the name for the guard.
2180 SmallString<256> guardName;
2181 {
2182 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00002183 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00002184 }
John McCall8e7cb6d2010-11-02 21:04:24 +00002185
John McCallb88a5662012-03-30 21:00:39 +00002186 // Create the guard variable with a zero-initializer.
2187 // Just absorb linkage and visibility from the guarded variable.
2188 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
2189 false, var->getLinkage(),
2190 llvm::ConstantInt::get(guardTy, 0),
2191 guardName.str());
Rafael Espindola699f5d62018-02-07 22:15:33 +00002192 guard->setDSOLocal(var->isDSOLocal());
John McCallb88a5662012-03-30 21:00:39 +00002193 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00002194 // If the variable is thread-local, so is its guard variable.
2195 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCall7f416cc2015-09-08 08:05:57 +00002196 guard->setAlignment(guardAlignment.getQuantity());
John McCallb88a5662012-03-30 21:00:39 +00002197
Yaron Keren5bfa1082015-09-03 20:33:29 +00002198 // The ABI says: "It is suggested that it be emitted in the same COMDAT
2199 // group as the associated data object." In practice, this doesn't work for
Dan Gohman839f2152017-01-17 21:46:38 +00002200 // non-ELF and non-Wasm object formats, so only do it for ELF and Wasm.
Rafael Espindola0d4fb982015-01-12 22:13:53 +00002201 llvm::Comdat *C = var->getComdat();
Yaron Keren5bfa1082015-09-03 20:33:29 +00002202 if (!D.isLocalVarDecl() && C &&
Dan Gohman839f2152017-01-17 21:46:38 +00002203 (CGM.getTarget().getTriple().isOSBinFormatELF() ||
2204 CGM.getTarget().getTriple().isOSBinFormatWasm())) {
Rafael Espindola2ae4b632014-09-19 19:43:18 +00002205 guard->setComdat(C);
Richard Smith62f19e72016-06-25 00:15:56 +00002206 // An inline variable's guard function is run from the per-TU
2207 // initialization function, not via a dedicated global ctor function, so
2208 // we can't put it in a comdat.
2209 if (!NonTemplateInline)
2210 CGF.CurFn->setComdat(C);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00002211 } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) {
2212 guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName()));
Rafael Espindola2ae4b632014-09-19 19:43:18 +00002213 }
2214
John McCallb88a5662012-03-30 21:00:39 +00002215 CGM.setStaticLocalDeclGuardAddress(&D, guard);
2216 }
John McCall87590e62012-03-30 07:09:50 +00002217
John McCall7f416cc2015-09-08 08:05:57 +00002218 Address guardAddr = Address(guard, guardAlignment);
2219
John McCall68ff0372010-09-08 01:44:27 +00002220 // Test whether the variable has completed initialization.
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002221 //
John McCall68ff0372010-09-08 01:44:27 +00002222 // Itanium C++ ABI 3.3.2:
2223 // The following is pseudo-code showing how these functions can be used:
2224 // if (obj_guard.first_byte == 0) {
2225 // if ( __cxa_guard_acquire (&obj_guard) ) {
2226 // try {
2227 // ... initialize the object ...;
2228 // } catch (...) {
2229 // __cxa_guard_abort (&obj_guard);
2230 // throw;
2231 // }
2232 // ... queue object destructor with __cxa_atexit() ...;
2233 // __cxa_guard_release (&obj_guard);
2234 // }
2235 // }
Tim Northovera2ee4332014-03-29 15:09:45 +00002236
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002237 // Load the first byte of the guard variable.
2238 llvm::LoadInst *LI =
John McCall7f416cc2015-09-08 08:05:57 +00002239 Builder.CreateLoad(Builder.CreateElementBitCast(guardAddr, CGM.Int8Ty));
John McCall68ff0372010-09-08 01:44:27 +00002240
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002241 // Itanium ABI:
2242 // An implementation supporting thread-safety on multiprocessor
2243 // systems must also guarantee that references to the initialized
2244 // object do not occur before the load of the initialization flag.
2245 //
2246 // In LLVM, we do this by marking the load Acquire.
2247 if (threadsafe)
JF Bastien92f4ef12016-04-06 17:26:42 +00002248 LI->setAtomic(llvm::AtomicOrdering::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00002249
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002250 // For ARM, we should only check the first bit, rather than the entire byte:
2251 //
2252 // ARM C++ ABI 3.2.3.1:
2253 // To support the potential use of initialization guard variables
2254 // as semaphores that are the target of ARM SWP and LDREX/STREX
2255 // synchronizing instructions we define a static initialization
2256 // guard variable to be a 4-byte aligned, 4-byte word with the
2257 // following inline access protocol.
2258 // #define INITIALIZED 1
2259 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
2260 // if (__cxa_guard_acquire(&obj_guard))
2261 // ...
2262 // }
2263 //
2264 // and similarly for ARM64:
2265 //
2266 // ARM64 C++ ABI 3.2.2:
2267 // This ABI instead only specifies the value bit 0 of the static guard
2268 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
2269 // variable is not initialized and 1 when it is.
2270 llvm::Value *V =
2271 (UseARMGuardVarABI && !useInt8GuardVariable)
2272 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
2273 : LI;
Richard Smithae8d62c2017-07-26 22:01:09 +00002274 llvm::Value *NeedsInit = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00002275
2276 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
2277 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2278
2279 // Check if the first byte of the guard variable is zero.
Richard Smithae8d62c2017-07-26 22:01:09 +00002280 CGF.EmitCXXGuardedInitBranch(NeedsInit, InitCheckBlock, EndBlock,
2281 CodeGenFunction::GuardKind::VariableGuard, &D);
John McCall68ff0372010-09-08 01:44:27 +00002282
2283 CGF.EmitBlock(InitCheckBlock);
2284
2285 // Variables used when coping with thread-safe statics and exceptions.
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002286 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002287 // Call __cxa_guard_acquire.
2288 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00002289 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002290
John McCall68ff0372010-09-08 01:44:27 +00002291 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002292
John McCall68ff0372010-09-08 01:44:27 +00002293 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
2294 InitBlock, EndBlock);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002295
John McCall68ff0372010-09-08 01:44:27 +00002296 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00002297 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002298
John McCall68ff0372010-09-08 01:44:27 +00002299 CGF.EmitBlock(InitBlock);
2300 }
2301
2302 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00002303 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00002304
John McCall5aa52592011-06-17 07:33:57 +00002305 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002306 // Pop the guard-abort cleanup if we pushed one.
2307 CGF.PopCleanupBlock();
2308
2309 // Call __cxa_guard_release. This cannot throw.
John McCall7f416cc2015-09-08 08:05:57 +00002310 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy),
2311 guardAddr.getPointer());
John McCall68ff0372010-09-08 01:44:27 +00002312 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002313 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guardAddr);
John McCall68ff0372010-09-08 01:44:27 +00002314 }
2315
2316 CGF.EmitBlock(EndBlock);
2317}
John McCallc84ed6a2012-05-01 06:13:13 +00002318
2319/// Register a global destructor using __cxa_atexit.
2320static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
James Y Knightf7321542019-02-07 01:14:17 +00002321 llvm::FunctionCallee dtor,
2322 llvm::Constant *addr, bool TLS) {
Erich Keane34ec6922019-06-13 18:20:19 +00002323 assert((TLS || CGF.getTypes().getCodeGenOpts().CXAAtExit) &&
2324 "__cxa_atexit is disabled");
Bill Wendling95cae882013-05-02 19:18:03 +00002325 const char *Name = "__cxa_atexit";
2326 if (TLS) {
2327 const llvm::Triple &T = CGF.getTarget().getTriple();
Manman Renf93fff22015-11-11 23:08:18 +00002328 Name = T.isOSDarwin() ? "_tlv_atexit" : "__cxa_thread_atexit";
Bill Wendling95cae882013-05-02 19:18:03 +00002329 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00002330
John McCallc84ed6a2012-05-01 06:13:13 +00002331 // We're assuming that the destructor function is something we can
2332 // reasonably call with the default CC. Go ahead and cast it to the
2333 // right prototype.
2334 llvm::Type *dtorTy =
2335 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
2336
Anastasia Stulova960ff082019-07-15 11:58:10 +00002337 // Preserve address space of addr.
2338 auto AddrAS = addr ? addr->getType()->getPointerAddressSpace() : 0;
2339 auto AddrInt8PtrTy =
2340 AddrAS ? CGF.Int8Ty->getPointerTo(AddrAS) : CGF.Int8PtrTy;
2341
2342 // Create a variable that binds the atexit to this shared object.
2343 llvm::Constant *handle =
2344 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
2345 auto *GV = cast<llvm::GlobalValue>(handle->stripPointerCasts());
2346 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
2347
John McCallc84ed6a2012-05-01 06:13:13 +00002348 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
Anastasia Stulova960ff082019-07-15 11:58:10 +00002349 llvm::Type *paramTys[] = {dtorTy, AddrInt8PtrTy, handle->getType()};
John McCallc84ed6a2012-05-01 06:13:13 +00002350 llvm::FunctionType *atexitTy =
2351 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
2352
2353 // Fetch the actual function.
James Y Knight9871db02019-02-05 16:42:33 +00002354 llvm::FunctionCallee atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
2355 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit.getCallee()))
John McCallc84ed6a2012-05-01 06:13:13 +00002356 fn->setDoesNotThrow();
2357
Akira Hatanaka617e2612018-04-17 18:41:52 +00002358 if (!addr)
2359 // addr is null when we are trying to register a dtor annotated with
2360 // __attribute__((destructor)) in a constructor function. Using null here is
2361 // okay because this argument is just passed back to the destructor
2362 // function.
2363 addr = llvm::Constant::getNullValue(CGF.Int8PtrTy);
2364
James Y Knightf7321542019-02-07 01:14:17 +00002365 llvm::Value *args[] = {llvm::ConstantExpr::getBitCast(
2366 cast<llvm::Constant>(dtor.getCallee()), dtorTy),
Anastasia Stulova960ff082019-07-15 11:58:10 +00002367 llvm::ConstantExpr::getBitCast(addr, AddrInt8PtrTy),
James Y Knightf7321542019-02-07 01:14:17 +00002368 handle};
John McCall882987f2013-02-28 19:01:20 +00002369 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00002370}
2371
Akira Hatanaka617e2612018-04-17 18:41:52 +00002372void CodeGenModule::registerGlobalDtorsWithAtExit() {
2373 for (const auto I : DtorsUsingAtExit) {
2374 int Priority = I.first;
2375 const llvm::TinyPtrVector<llvm::Function *> &Dtors = I.second;
2376
2377 // Create a function that registers destructors that have the same priority.
2378 //
2379 // Since constructor functions are run in non-descending order of their
2380 // priorities, destructors are registered in non-descending order of their
2381 // priorities, and since destructor functions are run in the reverse order
2382 // of their registration, destructor functions are run in non-ascending
2383 // order of their priorities.
2384 CodeGenFunction CGF(*this);
2385 std::string GlobalInitFnName =
2386 std::string("__GLOBAL_init_") + llvm::to_string(Priority);
2387 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
2388 llvm::Function *GlobalInitFn = CreateGlobalInitOrDestructFunction(
2389 FTy, GlobalInitFnName, getTypes().arrangeNullaryFunction(),
2390 SourceLocation());
2391 ASTContext &Ctx = getContext();
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002392 QualType ReturnTy = Ctx.VoidTy;
2393 QualType FunctionTy = Ctx.getFunctionType(ReturnTy, llvm::None, {});
Akira Hatanaka617e2612018-04-17 18:41:52 +00002394 FunctionDecl *FD = FunctionDecl::Create(
2395 Ctx, Ctx.getTranslationUnitDecl(), SourceLocation(), SourceLocation(),
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002396 &Ctx.Idents.get(GlobalInitFnName), FunctionTy, nullptr, SC_Static,
Akira Hatanaka617e2612018-04-17 18:41:52 +00002397 false, false);
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002398 CGF.StartFunction(GlobalDecl(FD), ReturnTy, GlobalInitFn,
Akira Hatanaka617e2612018-04-17 18:41:52 +00002399 getTypes().arrangeNullaryFunction(), FunctionArgList(),
2400 SourceLocation(), SourceLocation());
2401
2402 for (auto *Dtor : Dtors) {
2403 // Register the destructor function calling __cxa_atexit if it is
2404 // available. Otherwise fall back on calling atexit.
2405 if (getCodeGenOpts().CXAAtExit)
2406 emitGlobalDtorWithCXAAtExit(CGF, Dtor, nullptr, false);
2407 else
2408 CGF.registerGlobalDtorWithAtExit(Dtor);
2409 }
2410
2411 CGF.FinishFunction();
2412 AddGlobalCtor(GlobalInitFn, Priority, nullptr);
2413 }
2414}
2415
John McCallc84ed6a2012-05-01 06:13:13 +00002416/// Register a global destructor as best as we know how.
James Y Knightf7321542019-02-07 01:14:17 +00002417void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
2418 llvm::FunctionCallee dtor,
John McCallc84ed6a2012-05-01 06:13:13 +00002419 llvm::Constant *addr) {
Erik Pilkington5a559e62018-08-21 17:24:06 +00002420 if (D.isNoDestroy(CGM.getContext()))
2421 return;
2422
Erich Keane34ec6922019-06-13 18:20:19 +00002423 // emitGlobalDtorWithCXAAtExit will emit a call to either __cxa_thread_atexit
2424 // or __cxa_atexit depending on whether this VarDecl is a thread-local storage
2425 // or not. CXAAtExit controls only __cxa_atexit, so use it if it is enabled.
2426 // We can always use __cxa_thread_atexit.
2427 if (CGM.getCodeGenOpts().CXAAtExit || D.getTLSKind())
Richard Smithdbf74ba2013-04-14 23:01:42 +00002428 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
2429
John McCallc84ed6a2012-05-01 06:13:13 +00002430 // In Apple kexts, we want to add a global destructor entry.
2431 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00002432 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00002433 // Generate a global destructor entry.
2434 return CGM.AddCXXDtorEntry(dtor, addr);
2435 }
2436
David Blaikieebe87e12013-08-27 23:57:18 +00002437 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00002438}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002439
David Majnemer9b21c332014-07-11 20:28:10 +00002440static bool isThreadWrapperReplaceable(const VarDecl *VD,
2441 CodeGen::CodeGenModule &CGM) {
2442 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
Manman Renf93fff22015-11-11 23:08:18 +00002443 // Darwin prefers to have references to thread local variables to go through
David Majnemer9b21c332014-07-11 20:28:10 +00002444 // the thread wrapper instead of directly referencing the backing variable.
2445 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
Manman Renf93fff22015-11-11 23:08:18 +00002446 CGM.getTarget().getTriple().isOSDarwin();
David Majnemer9b21c332014-07-11 20:28:10 +00002447}
2448
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002449/// Get the appropriate linkage for the wrapper function. This is essentially
David Majnemer4632e1e2014-06-27 16:56:27 +00002450/// the weak form of the variable's linkage; every translation unit which needs
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002451/// the wrapper emits a copy, and we want the linker to merge them.
David Majnemer35ab3282014-06-11 04:08:55 +00002452static llvm::GlobalValue::LinkageTypes
2453getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
2454 llvm::GlobalValue::LinkageTypes VarLinkage =
Rui Ueyama49a3ad22019-07-16 04:46:31 +00002455 CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false);
David Majnemer35ab3282014-06-11 04:08:55 +00002456
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002457 // For internal linkage variables, we don't need an external or weak wrapper.
2458 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
2459 return VarLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00002460
David Majnemer9b21c332014-07-11 20:28:10 +00002461 // If the thread wrapper is replaceable, give it appropriate linkage.
Manman Ren68150262015-11-11 22:42:31 +00002462 if (isThreadWrapperReplaceable(VD, CGM))
2463 if (!llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) &&
2464 !llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
2465 return VarLinkage;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002466 return llvm::GlobalValue::WeakODRLinkage;
2467}
2468
2469llvm::Function *
2470ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +00002471 llvm::Value *Val) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002472 // Mangle the name for the thread_local wrapper function.
2473 SmallString<256> WrapperName;
2474 {
2475 llvm::raw_svector_ostream Out(WrapperName);
2476 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002477 }
2478
Akira Hatanaka26907f92016-01-15 03:34:06 +00002479 // FIXME: If VD is a definition, we should regenerate the function attributes
2480 // before returning.
Alexander Musmanf94c3182014-09-26 06:28:25 +00002481 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002482 return cast<llvm::Function>(V);
2483
Akira Hatanaka26907f92016-01-15 03:34:06 +00002484 QualType RetQT = VD->getType();
2485 if (RetQT->isReferenceType())
2486 RetQT = RetQT.getNonReferenceType();
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002487
John McCallc56a8b32016-03-11 04:30:31 +00002488 const CGFunctionInfo &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2489 getContext().getPointerType(RetQT), FunctionArgList());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002490
2491 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FI);
David Majnemer35ab3282014-06-11 04:08:55 +00002492 llvm::Function *Wrapper =
2493 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
2494 WrapperName.str(), &CGM.getModule());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002495
Erich Keanede6480a32018-11-13 15:48:08 +00002496 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, Wrapper);
Akira Hatanaka26907f92016-01-15 03:34:06 +00002497
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002498 // Always resolve references to the wrapper at link time.
Vlad Tsyrklevichc93390b2019-01-17 17:53:45 +00002499 if (!Wrapper->hasLocalLinkage())
2500 if (!isThreadWrapperReplaceable(VD, CGM) ||
2501 llvm::GlobalVariable::isLinkOnceLinkage(Wrapper->getLinkage()) ||
2502 llvm::GlobalVariable::isWeakODRLinkage(Wrapper->getLinkage()) ||
2503 VD->getVisibility() == HiddenVisibility)
2504 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
Manman Renb0b3af72015-12-17 00:42:36 +00002505
2506 if (isThreadWrapperReplaceable(VD, CGM)) {
2507 Wrapper->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2508 Wrapper->addFnAttr(llvm::Attribute::NoUnwind);
2509 }
Richard Smith00223822019-09-12 20:00:24 +00002510
2511 ThreadWrappers.push_back({VD, Wrapper});
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002512 return Wrapper;
2513}
2514
2515void ItaniumCXXABI::EmitThreadLocalInitFuncs(
Richard Smith5a99c492015-12-01 01:10:48 +00002516 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
2517 ArrayRef<llvm::Function *> CXXThreadLocalInits,
2518 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
David Majnemerb3341ea2014-10-05 05:05:40 +00002519 llvm::Function *InitFunc = nullptr;
Richard Smithfbe23692017-01-13 00:43:31 +00002520
2521 // Separate initializers into those with ordered (or partially-ordered)
2522 // initialization and those with unordered initialization.
2523 llvm::SmallVector<llvm::Function *, 8> OrderedInits;
2524 llvm::SmallDenseMap<const VarDecl *, llvm::Function *> UnorderedInits;
2525 for (unsigned I = 0; I != CXXThreadLocalInits.size(); ++I) {
2526 if (isTemplateInstantiation(
2527 CXXThreadLocalInitVars[I]->getTemplateSpecializationKind()))
2528 UnorderedInits[CXXThreadLocalInitVars[I]->getCanonicalDecl()] =
2529 CXXThreadLocalInits[I];
2530 else
2531 OrderedInits.push_back(CXXThreadLocalInits[I]);
2532 }
2533
2534 if (!OrderedInits.empty()) {
David Majnemerb3341ea2014-10-05 05:05:40 +00002535 // Generate a guarded initialization function.
2536 llvm::FunctionType *FTy =
2537 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002538 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2539 InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init", FI,
Alexey Samsonov1444bb92014-10-17 00:20:19 +00002540 SourceLocation(),
David Majnemerb3341ea2014-10-05 05:05:40 +00002541 /*TLS=*/true);
2542 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
2543 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
2544 llvm::GlobalVariable::InternalLinkage,
2545 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
2546 Guard->setThreadLocal(true);
John McCall7f416cc2015-09-08 08:05:57 +00002547
2548 CharUnits GuardAlign = CharUnits::One();
2549 Guard->setAlignment(GuardAlign.getQuantity());
2550
Richard Smith3ad06362018-10-31 20:39:26 +00002551 CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(
2552 InitFunc, OrderedInits, ConstantAddress(Guard, GuardAlign));
Manman Ren5e5d0462016-03-18 23:35:21 +00002553 // On Darwin platforms, use CXX_FAST_TLS calling convention.
2554 if (CGM.getTarget().getTriple().isOSDarwin()) {
2555 InitFunc->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2556 InitFunc->addFnAttr(llvm::Attribute::NoUnwind);
2557 }
David Majnemerb3341ea2014-10-05 05:05:40 +00002558 }
Richard Smithfbe23692017-01-13 00:43:31 +00002559
Richard Smith00223822019-09-12 20:00:24 +00002560 // Create declarations for thread wrappers for all thread-local variables
2561 // with non-discardable definitions in this translation unit.
Richard Smith5a99c492015-12-01 01:10:48 +00002562 for (const VarDecl *VD : CXXThreadLocals) {
Richard Smith00223822019-09-12 20:00:24 +00002563 if (VD->hasDefinition() &&
2564 !isDiscardableGVALinkage(getContext().GetGVALinkageForVariable(VD))) {
2565 llvm::GlobalValue *GV = CGM.GetGlobalValue(CGM.getMangledName(VD));
2566 getOrCreateThreadLocalWrapper(VD, GV);
2567 }
2568 }
2569
2570 // Emit all referenced thread wrappers.
2571 for (auto VDAndWrapper : ThreadWrappers) {
2572 const VarDecl *VD = VDAndWrapper.first;
Richard Smith5a99c492015-12-01 01:10:48 +00002573 llvm::GlobalVariable *Var =
2574 cast<llvm::GlobalVariable>(CGM.GetGlobalValue(CGM.getMangledName(VD)));
Richard Smith00223822019-09-12 20:00:24 +00002575 llvm::Function *Wrapper = VDAndWrapper.second;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002576
David Majnemer9b21c332014-07-11 20:28:10 +00002577 // Some targets require that all access to thread local variables go through
2578 // the thread wrapper. This means that we cannot attempt to create a thread
2579 // wrapper or a thread helper.
Richard Smith00223822019-09-12 20:00:24 +00002580 if (!VD->hasDefinition()) {
2581 if (isThreadWrapperReplaceable(VD, CGM)) {
2582 Wrapper->setLinkage(llvm::Function::ExternalLinkage);
2583 continue;
2584 }
2585
2586 // If this isn't a TU in which this variable is defined, the thread
2587 // wrapper is discardable.
2588 if (Wrapper->getLinkage() == llvm::Function::WeakODRLinkage)
2589 Wrapper->setLinkage(llvm::Function::LinkOnceODRLinkage);
Richard Smithfbe23692017-01-13 00:43:31 +00002590 }
David Majnemer9b21c332014-07-11 20:28:10 +00002591
Richard Smith00223822019-09-12 20:00:24 +00002592 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Wrapper);
2593
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002594 // Mangle the name for the thread_local initialization function.
2595 SmallString<256> InitFnName;
2596 {
2597 llvm::raw_svector_ostream Out(InitFnName);
2598 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002599 }
2600
James Y Knightf7321542019-02-07 01:14:17 +00002601 llvm::FunctionType *InitFnTy = llvm::FunctionType::get(CGM.VoidTy, false);
2602
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002603 // If we have a definition for the variable, emit the initialization
2604 // function as an alias to the global Init function (if any). Otherwise,
2605 // produce a declaration of the initialization function.
Craig Topper8a13c412014-05-21 05:09:00 +00002606 llvm::GlobalValue *Init = nullptr;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002607 bool InitIsInitFunc = false;
Richard Smith00223822019-09-12 20:00:24 +00002608 bool HasConstantInitialization = false;
2609 if (isEmittedWithConstantInitializer(VD)) {
2610 HasConstantInitialization = true;
2611 } else if (VD->hasDefinition()) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002612 InitIsInitFunc = true;
Richard Smithfbe23692017-01-13 00:43:31 +00002613 llvm::Function *InitFuncToUse = InitFunc;
2614 if (isTemplateInstantiation(VD->getTemplateSpecializationKind()))
2615 InitFuncToUse = UnorderedInits.lookup(VD->getCanonicalDecl());
2616 if (InitFuncToUse)
Rafael Espindola234405b2014-05-17 21:30:14 +00002617 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
Richard Smithfbe23692017-01-13 00:43:31 +00002618 InitFuncToUse);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002619 } else {
2620 // Emit a weak global function referring to the initialization function.
2621 // This function will not exist if the TU defining the thread_local
2622 // variable in question does not need any dynamic initialization for
2623 // its thread_local variables.
James Y Knightf7321542019-02-07 01:14:17 +00002624 Init = llvm::Function::Create(InitFnTy,
Richard Smithfbe23692017-01-13 00:43:31 +00002625 llvm::GlobalVariable::ExternalWeakLinkage,
2626 InitFnName.str(), &CGM.getModule());
John McCallc56a8b32016-03-11 04:30:31 +00002627 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
Erich Keanede6480a32018-11-13 15:48:08 +00002628 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI,
2629 cast<llvm::Function>(Init));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002630 }
2631
Rafael Espindolaabdb3222018-03-07 23:18:06 +00002632 if (Init) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002633 Init->setVisibility(Var->getVisibility());
Rafael Espindolaabdb3222018-03-07 23:18:06 +00002634 Init->setDSOLocal(Var->isDSOLocal());
2635 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002636
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002637 llvm::LLVMContext &Context = CGM.getModule().getContext();
2638 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
John McCall7f416cc2015-09-08 08:05:57 +00002639 CGBuilderTy Builder(CGM, Entry);
Richard Smith00223822019-09-12 20:00:24 +00002640 if (HasConstantInitialization) {
2641 // No dynamic initialization to invoke.
2642 } else if (InitIsInitFunc) {
Manman Ren5e5d0462016-03-18 23:35:21 +00002643 if (Init) {
James Y Knightf7321542019-02-07 01:14:17 +00002644 llvm::CallInst *CallVal = Builder.CreateCall(InitFnTy, Init);
Akira Hatanaka1da9dbb2018-05-29 18:28:49 +00002645 if (isThreadWrapperReplaceable(VD, CGM)) {
Manman Ren5e5d0462016-03-18 23:35:21 +00002646 CallVal->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
Akira Hatanaka1da9dbb2018-05-29 18:28:49 +00002647 llvm::Function *Fn =
2648 cast<llvm::Function>(cast<llvm::GlobalAlias>(Init)->getAliasee());
2649 Fn->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2650 }
Manman Ren5e5d0462016-03-18 23:35:21 +00002651 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002652 } else {
2653 // Don't know whether we have an init function. Call it if it exists.
2654 llvm::Value *Have = Builder.CreateIsNotNull(Init);
2655 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2656 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2657 Builder.CreateCondBr(Have, InitBB, ExitBB);
2658
2659 Builder.SetInsertPoint(InitBB);
James Y Knightf7321542019-02-07 01:14:17 +00002660 Builder.CreateCall(InitFnTy, Init);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002661 Builder.CreateBr(ExitBB);
2662
2663 Builder.SetInsertPoint(ExitBB);
2664 }
2665
2666 // For a reference, the result of the wrapper function is a pointer to
2667 // the referenced object.
2668 llvm::Value *Val = Var;
2669 if (VD->getType()->isReferenceType()) {
John McCall7f416cc2015-09-08 08:05:57 +00002670 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2671 Val = Builder.CreateAlignedLoad(Val, Align);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002672 }
Alexander Musmanf94c3182014-09-26 06:28:25 +00002673 if (Val->getType() != Wrapper->getReturnType())
2674 Val = Builder.CreatePointerBitCastOrAddrSpaceCast(
2675 Val, Wrapper->getReturnType(), "");
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002676 Builder.CreateRet(Val);
2677 }
2678}
2679
Richard Smith0f383742014-03-26 22:48:22 +00002680LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2681 const VarDecl *VD,
2682 QualType LValType) {
Richard Smith5a99c492015-12-01 01:10:48 +00002683 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD);
Alexander Musmanf94c3182014-09-26 06:28:25 +00002684 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002685
Manman Renb0b3af72015-12-17 00:42:36 +00002686 llvm::CallInst *CallVal = CGF.Builder.CreateCall(Wrapper);
Saleem Abdulrasool4a7130a2016-08-01 21:31:24 +00002687 CallVal->setCallingConv(Wrapper->getCallingConv());
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002688
2689 LValue LV;
2690 if (VD->getType()->isReferenceType())
Manman Renb0b3af72015-12-17 00:42:36 +00002691 LV = CGF.MakeNaturalAlignAddrLValue(CallVal, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002692 else
Manman Renb0b3af72015-12-17 00:42:36 +00002693 LV = CGF.MakeAddrLValue(CallVal, LValType,
2694 CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002695 // FIXME: need setObjCGCLValueClass?
2696 return LV;
2697}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002698
2699/// Return whether the given global decl needs a VTT parameter, which it does
2700/// if it's a base constructor or destructor with virtual bases.
2701bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
2702 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002703
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002704 // We don't have any virtual bases, just return early.
2705 if (!MD->getParent()->getNumVBases())
2706 return false;
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002707
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002708 // Check if we have a base constructor.
2709 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
2710 return true;
2711
2712 // Check if we have a base destructor.
2713 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2714 return true;
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002715
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002716 return false;
2717}
David Majnemere2cb8d12014-07-07 06:20:47 +00002718
2719namespace {
2720class ItaniumRTTIBuilder {
2721 CodeGenModule &CGM; // Per-module state.
2722 llvm::LLVMContext &VMContext;
2723 const ItaniumCXXABI &CXXABI; // Per-module state.
2724
2725 /// Fields - The fields of the RTTI descriptor currently being built.
2726 SmallVector<llvm::Constant *, 16> Fields;
2727
2728 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2729 llvm::GlobalVariable *
2730 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2731
2732 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2733 /// descriptor of the given type.
2734 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2735
2736 /// BuildVTablePointer - Build the vtable pointer for the given type.
2737 void BuildVTablePointer(const Type *Ty);
2738
2739 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2740 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2741 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2742
2743 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2744 /// classes with bases that do not satisfy the abi::__si_class_type_info
2745 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2746 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2747
2748 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2749 /// for pointer types.
2750 void BuildPointerTypeInfo(QualType PointeeTy);
2751
2752 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2753 /// type_info for an object type.
2754 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2755
2756 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2757 /// struct, used for member pointer types.
2758 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2759
2760public:
2761 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2762 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2763
2764 // Pointer type info flags.
2765 enum {
2766 /// PTI_Const - Type has const qualifier.
2767 PTI_Const = 0x1,
2768
2769 /// PTI_Volatile - Type has volatile qualifier.
2770 PTI_Volatile = 0x2,
2771
2772 /// PTI_Restrict - Type has restrict qualifier.
2773 PTI_Restrict = 0x4,
2774
2775 /// PTI_Incomplete - Type is incomplete.
2776 PTI_Incomplete = 0x8,
2777
2778 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2779 /// (in pointer to member).
Richard Smitha7d93782016-12-01 03:32:42 +00002780 PTI_ContainingClassIncomplete = 0x10,
2781
2782 /// PTI_TransactionSafe - Pointee is transaction_safe function (C++ TM TS).
2783 //PTI_TransactionSafe = 0x20,
2784
2785 /// PTI_Noexcept - Pointee is noexcept function (C++1z).
2786 PTI_Noexcept = 0x40,
David Majnemere2cb8d12014-07-07 06:20:47 +00002787 };
2788
2789 // VMI type info flags.
2790 enum {
2791 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2792 VMI_NonDiamondRepeat = 0x1,
2793
2794 /// VMI_DiamondShaped - Class is diamond shaped.
2795 VMI_DiamondShaped = 0x2
2796 };
2797
2798 // Base class type info flags.
2799 enum {
2800 /// BCTI_Virtual - Base class is virtual.
2801 BCTI_Virtual = 0x1,
2802
2803 /// BCTI_Public - Base class is public.
2804 BCTI_Public = 0x2
2805 };
2806
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00002807 /// BuildTypeInfo - Build the RTTI type info struct for the given type, or
2808 /// link to an existing RTTI descriptor if one already exists.
2809 llvm::Constant *BuildTypeInfo(QualType Ty);
2810
David Majnemere2cb8d12014-07-07 06:20:47 +00002811 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00002812 llvm::Constant *BuildTypeInfo(
2813 QualType Ty,
2814 llvm::GlobalVariable::LinkageTypes Linkage,
2815 llvm::GlobalValue::VisibilityTypes Visibility,
2816 llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass);
David Majnemere2cb8d12014-07-07 06:20:47 +00002817};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002818}
David Majnemere2cb8d12014-07-07 06:20:47 +00002819
2820llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2821 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002822 SmallString<256> Name;
2823 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002824 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002825
2826 // We know that the mangled name of the type starts at index 4 of the
2827 // mangled name of the typename, so we can just index into it in order to
2828 // get the mangled name of the type.
2829 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2830 Name.substr(4));
David Greenbe0c5b62018-09-12 14:09:06 +00002831 auto Align = CGM.getContext().getTypeAlignInChars(CGM.getContext().CharTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00002832
David Greenbe0c5b62018-09-12 14:09:06 +00002833 llvm::GlobalVariable *GV = CGM.CreateOrReplaceCXXRuntimeVariable(
2834 Name, Init->getType(), Linkage, Align.getQuantity());
David Majnemere2cb8d12014-07-07 06:20:47 +00002835
2836 GV->setInitializer(Init);
2837
2838 return GV;
2839}
2840
2841llvm::Constant *
2842ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2843 // Mangle the RTTI name.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002844 SmallString<256> Name;
2845 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002846 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002847
2848 // Look for an existing global.
2849 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2850
2851 if (!GV) {
2852 // Create a new global variable.
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00002853 // Note for the future: If we would ever like to do deferred emission of
2854 // RTTI, check if emitting vtables opportunistically need any adjustment.
2855
David Majnemere2cb8d12014-07-07 06:20:47 +00002856 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00002857 /*isConstant=*/true,
David Majnemere2cb8d12014-07-07 06:20:47 +00002858 llvm::GlobalValue::ExternalLinkage, nullptr,
2859 Name);
Rafael Espindola3f727a82018-03-14 18:14:46 +00002860 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
2861 CGM.setGVProperties(GV, RD);
David Majnemere2cb8d12014-07-07 06:20:47 +00002862 }
2863
2864 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2865}
2866
2867/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2868/// info for that type is defined in the standard library.
2869static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2870 // Itanium C++ ABI 2.9.2:
2871 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
2872 // the run-time support library. Specifically, the run-time support
2873 // library should contain type_info objects for the types X, X* and
2874 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2875 // unsigned char, signed char, short, unsigned short, int, unsigned int,
2876 // long, unsigned long, long long, unsigned long long, float, double,
2877 // long double, char16_t, char32_t, and the IEEE 754r decimal and
2878 // half-precision floating point types.
Richard Smith4a382012016-02-03 01:32:42 +00002879 //
2880 // GCC also emits RTTI for __int128.
2881 // FIXME: We do not emit RTTI information for decimal types here.
2882
2883 // Types added here must also be added to EmitFundamentalRTTIDescriptors.
David Majnemere2cb8d12014-07-07 06:20:47 +00002884 switch (Ty->getKind()) {
2885 case BuiltinType::Void:
2886 case BuiltinType::NullPtr:
2887 case BuiltinType::Bool:
2888 case BuiltinType::WChar_S:
2889 case BuiltinType::WChar_U:
2890 case BuiltinType::Char_U:
2891 case BuiltinType::Char_S:
2892 case BuiltinType::UChar:
2893 case BuiltinType::SChar:
2894 case BuiltinType::Short:
2895 case BuiltinType::UShort:
2896 case BuiltinType::Int:
2897 case BuiltinType::UInt:
2898 case BuiltinType::Long:
2899 case BuiltinType::ULong:
2900 case BuiltinType::LongLong:
2901 case BuiltinType::ULongLong:
2902 case BuiltinType::Half:
2903 case BuiltinType::Float:
2904 case BuiltinType::Double:
2905 case BuiltinType::LongDouble:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00002906 case BuiltinType::Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002907 case BuiltinType::Float128:
Richard Smith3a8244d2018-05-01 05:02:45 +00002908 case BuiltinType::Char8:
David Majnemere2cb8d12014-07-07 06:20:47 +00002909 case BuiltinType::Char16:
2910 case BuiltinType::Char32:
2911 case BuiltinType::Int128:
2912 case BuiltinType::UInt128:
Richard Smith4a382012016-02-03 01:32:42 +00002913 return true;
2914
Alexey Bader954ba212016-04-08 13:40:33 +00002915#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2916 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00002917#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00002918#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2919 case BuiltinType::Id:
2920#include "clang/Basic/OpenCLExtensionTypes.def"
David Majnemere2cb8d12014-07-07 06:20:47 +00002921 case BuiltinType::OCLSampler:
2922 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002923 case BuiltinType::OCLClkEvent:
2924 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002925 case BuiltinType::OCLReserveID:
Richard Sandifordeb485fb2019-08-09 08:52:54 +00002926#define SVE_TYPE(Name, Id, SingletonId) \
2927 case BuiltinType::Id:
2928#include "clang/Basic/AArch64SVEACLETypes.def"
Leonard Chanf921d852018-06-04 16:07:52 +00002929 case BuiltinType::ShortAccum:
2930 case BuiltinType::Accum:
2931 case BuiltinType::LongAccum:
2932 case BuiltinType::UShortAccum:
2933 case BuiltinType::UAccum:
2934 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00002935 case BuiltinType::ShortFract:
2936 case BuiltinType::Fract:
2937 case BuiltinType::LongFract:
2938 case BuiltinType::UShortFract:
2939 case BuiltinType::UFract:
2940 case BuiltinType::ULongFract:
2941 case BuiltinType::SatShortAccum:
2942 case BuiltinType::SatAccum:
2943 case BuiltinType::SatLongAccum:
2944 case BuiltinType::SatUShortAccum:
2945 case BuiltinType::SatUAccum:
2946 case BuiltinType::SatULongAccum:
2947 case BuiltinType::SatShortFract:
2948 case BuiltinType::SatFract:
2949 case BuiltinType::SatLongFract:
2950 case BuiltinType::SatUShortFract:
2951 case BuiltinType::SatUFract:
2952 case BuiltinType::SatULongFract:
Richard Smith4a382012016-02-03 01:32:42 +00002953 return false;
David Majnemere2cb8d12014-07-07 06:20:47 +00002954
2955 case BuiltinType::Dependent:
2956#define BUILTIN_TYPE(Id, SingletonId)
2957#define PLACEHOLDER_TYPE(Id, SingletonId) \
2958 case BuiltinType::Id:
2959#include "clang/AST/BuiltinTypes.def"
2960 llvm_unreachable("asking for RRTI for a placeholder type!");
2961
2962 case BuiltinType::ObjCId:
2963 case BuiltinType::ObjCClass:
2964 case BuiltinType::ObjCSel:
2965 llvm_unreachable("FIXME: Objective-C types are unsupported!");
2966 }
2967
2968 llvm_unreachable("Invalid BuiltinType Kind!");
2969}
2970
2971static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2972 QualType PointeeTy = PointerTy->getPointeeType();
2973 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2974 if (!BuiltinTy)
2975 return false;
2976
2977 // Check the qualifiers.
2978 Qualifiers Quals = PointeeTy.getQualifiers();
2979 Quals.removeConst();
2980
2981 if (!Quals.empty())
2982 return false;
2983
2984 return TypeInfoIsInStandardLibrary(BuiltinTy);
2985}
2986
2987/// IsStandardLibraryRTTIDescriptor - Returns whether the type
2988/// information for the given type exists in the standard library.
2989static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2990 // Type info for builtin types is defined in the standard library.
2991 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2992 return TypeInfoIsInStandardLibrary(BuiltinTy);
2993
2994 // Type info for some pointer types to builtin types is defined in the
2995 // standard library.
2996 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2997 return TypeInfoIsInStandardLibrary(PointerTy);
2998
2999 return false;
3000}
3001
3002/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
3003/// the given type exists somewhere else, and that we should not emit the type
3004/// information in this translation unit. Assumes that it is not a
3005/// standard-library type.
3006static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
3007 QualType Ty) {
3008 ASTContext &Context = CGM.getContext();
3009
3010 // If RTTI is disabled, assume it might be disabled in the
3011 // translation unit that defines any potential key function, too.
3012 if (!Context.getLangOpts().RTTI) return false;
3013
3014 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
3015 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
3016 if (!RD->hasDefinition())
3017 return false;
3018
3019 if (!RD->isDynamicClass())
3020 return false;
3021
3022 // FIXME: this may need to be reconsidered if the key function
3023 // changes.
David Majnemerbe9022c2015-08-06 20:56:55 +00003024 // N.B. We must always emit the RTTI data ourselves if there exists a key
3025 // function.
3026 bool IsDLLImport = RD->hasAttr<DLLImportAttr>();
Martin Storsjo3b528942018-02-02 06:22:35 +00003027
3028 // Don't import the RTTI but emit it locally.
Martin Storsjo228ccd62019-04-26 19:31:51 +00003029 if (CGM.getTriple().isWindowsGNUEnvironment())
Martin Storsjo3b528942018-02-02 06:22:35 +00003030 return false;
3031
David Majnemer1fb1a042014-11-07 07:26:38 +00003032 if (CGM.getVTables().isVTableExternal(RD))
Shoaib Meenai61118e72017-07-04 01:02:19 +00003033 return IsDLLImport && !CGM.getTriple().isWindowsItaniumEnvironment()
3034 ? false
3035 : true;
David Majnemer1fb1a042014-11-07 07:26:38 +00003036
David Majnemerbe9022c2015-08-06 20:56:55 +00003037 if (IsDLLImport)
David Majnemer1fb1a042014-11-07 07:26:38 +00003038 return true;
David Majnemere2cb8d12014-07-07 06:20:47 +00003039 }
3040
3041 return false;
3042}
3043
3044/// IsIncompleteClassType - Returns whether the given record type is incomplete.
3045static bool IsIncompleteClassType(const RecordType *RecordTy) {
3046 return !RecordTy->getDecl()->isCompleteDefinition();
3047}
3048
3049/// ContainsIncompleteClassType - Returns whether the given type contains an
3050/// incomplete class type. This is true if
3051///
3052/// * The given type is an incomplete class type.
3053/// * The given type is a pointer type whose pointee type contains an
3054/// incomplete class type.
3055/// * The given type is a member pointer type whose class is an incomplete
3056/// class type.
3057/// * The given type is a member pointer type whoise pointee type contains an
3058/// incomplete class type.
3059/// is an indirect or direct pointer to an incomplete class type.
3060static bool ContainsIncompleteClassType(QualType Ty) {
3061 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
3062 if (IsIncompleteClassType(RecordTy))
3063 return true;
3064 }
3065
3066 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
3067 return ContainsIncompleteClassType(PointerTy->getPointeeType());
3068
3069 if (const MemberPointerType *MemberPointerTy =
3070 dyn_cast<MemberPointerType>(Ty)) {
3071 // Check if the class type is incomplete.
3072 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
3073 if (IsIncompleteClassType(ClassType))
3074 return true;
3075
3076 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
3077 }
3078
3079 return false;
3080}
3081
3082// CanUseSingleInheritance - Return whether the given record decl has a "single,
3083// public, non-virtual base at offset zero (i.e. the derived class is dynamic
3084// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
3085static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
3086 // Check the number of bases.
3087 if (RD->getNumBases() != 1)
3088 return false;
3089
3090 // Get the base.
3091 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
3092
3093 // Check that the base is not virtual.
3094 if (Base->isVirtual())
3095 return false;
3096
3097 // Check that the base is public.
3098 if (Base->getAccessSpecifier() != AS_public)
3099 return false;
3100
3101 // Check that the class is dynamic iff the base is.
3102 const CXXRecordDecl *BaseDecl =
3103 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
3104 if (!BaseDecl->isEmpty() &&
3105 BaseDecl->isDynamicClass() != RD->isDynamicClass())
3106 return false;
3107
3108 return true;
3109}
3110
3111void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
3112 // abi::__class_type_info.
3113 static const char * const ClassTypeInfo =
3114 "_ZTVN10__cxxabiv117__class_type_infoE";
3115 // abi::__si_class_type_info.
3116 static const char * const SIClassTypeInfo =
3117 "_ZTVN10__cxxabiv120__si_class_type_infoE";
3118 // abi::__vmi_class_type_info.
3119 static const char * const VMIClassTypeInfo =
3120 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
3121
3122 const char *VTableName = nullptr;
3123
3124 switch (Ty->getTypeClass()) {
3125#define TYPE(Class, Base)
3126#define ABSTRACT_TYPE(Class, Base)
3127#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3128#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3129#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3130#include "clang/AST/TypeNodes.def"
3131 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
3132
3133 case Type::LValueReference:
3134 case Type::RValueReference:
3135 llvm_unreachable("References shouldn't get here");
3136
3137 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00003138 case Type::DeducedTemplateSpecialization:
3139 llvm_unreachable("Undeduced type shouldn't get here");
David Majnemere2cb8d12014-07-07 06:20:47 +00003140
Xiuli Pan9c14e282016-01-09 12:53:17 +00003141 case Type::Pipe:
3142 llvm_unreachable("Pipe types shouldn't get here");
3143
David Majnemere2cb8d12014-07-07 06:20:47 +00003144 case Type::Builtin:
3145 // GCC treats vector and complex types as fundamental types.
3146 case Type::Vector:
3147 case Type::ExtVector:
3148 case Type::Complex:
3149 case Type::Atomic:
3150 // FIXME: GCC treats block pointers as fundamental types?!
3151 case Type::BlockPointer:
3152 // abi::__fundamental_type_info.
3153 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
3154 break;
3155
3156 case Type::ConstantArray:
3157 case Type::IncompleteArray:
3158 case Type::VariableArray:
3159 // abi::__array_type_info.
3160 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
3161 break;
3162
3163 case Type::FunctionNoProto:
3164 case Type::FunctionProto:
Richard Smithb17d6fa2016-12-01 03:04:07 +00003165 // abi::__function_type_info.
3166 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
David Majnemere2cb8d12014-07-07 06:20:47 +00003167 break;
3168
3169 case Type::Enum:
3170 // abi::__enum_type_info.
3171 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
3172 break;
3173
3174 case Type::Record: {
Rafael Espindolaf6688122018-03-22 21:14:16 +00003175 const CXXRecordDecl *RD =
3176 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
David Majnemere2cb8d12014-07-07 06:20:47 +00003177
3178 if (!RD->hasDefinition() || !RD->getNumBases()) {
3179 VTableName = ClassTypeInfo;
3180 } else if (CanUseSingleInheritance(RD)) {
3181 VTableName = SIClassTypeInfo;
3182 } else {
3183 VTableName = VMIClassTypeInfo;
3184 }
3185
3186 break;
3187 }
3188
3189 case Type::ObjCObject:
3190 // Ignore protocol qualifiers.
3191 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
3192
3193 // Handle id and Class.
3194 if (isa<BuiltinType>(Ty)) {
3195 VTableName = ClassTypeInfo;
3196 break;
3197 }
3198
3199 assert(isa<ObjCInterfaceType>(Ty));
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +00003200 LLVM_FALLTHROUGH;
David Majnemere2cb8d12014-07-07 06:20:47 +00003201
3202 case Type::ObjCInterface:
3203 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
3204 VTableName = SIClassTypeInfo;
3205 } else {
3206 VTableName = ClassTypeInfo;
3207 }
3208 break;
3209
3210 case Type::ObjCObjectPointer:
3211 case Type::Pointer:
3212 // abi::__pointer_type_info.
3213 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
3214 break;
3215
3216 case Type::MemberPointer:
3217 // abi::__pointer_to_member_type_info.
3218 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
3219 break;
3220 }
3221
3222 llvm::Constant *VTable =
3223 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
Rafael Espindolafe9a55a2018-03-23 01:36:23 +00003224 CGM.setDSOLocal(cast<llvm::GlobalValue>(VTable->stripPointerCasts()));
David Majnemere2cb8d12014-07-07 06:20:47 +00003225
3226 llvm::Type *PtrDiffTy =
3227 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
3228
3229 // The vtable address point is 2.
3230 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00003231 VTable =
3232 llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.Int8PtrTy, VTable, Two);
David Majnemere2cb8d12014-07-07 06:20:47 +00003233 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
3234
3235 Fields.push_back(VTable);
3236}
3237
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003238/// Return the linkage that the type info and type info name constants
David Majnemere2cb8d12014-07-07 06:20:47 +00003239/// should have for the given type.
Richard Smithbbb26552018-05-21 20:10:54 +00003240static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
3241 QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003242 // Itanium C++ ABI 2.9.5p7:
3243 // In addition, it and all of the intermediate abi::__pointer_type_info
3244 // structs in the chain down to the abi::__class_type_info for the
3245 // incomplete class type must be prevented from resolving to the
3246 // corresponding type_info structs for the complete class type, possibly
3247 // by making them local static objects. Finally, a dummy class RTTI is
3248 // generated for the incomplete type that will not resolve to the final
3249 // complete class RTTI (because the latter need not exist), possibly by
3250 // making it a local static object.
3251 if (ContainsIncompleteClassType(Ty))
Richard Smithbbb26552018-05-21 20:10:54 +00003252 return llvm::GlobalValue::InternalLinkage;
3253
3254 switch (Ty->getLinkage()) {
3255 case NoLinkage:
3256 case InternalLinkage:
3257 case UniqueExternalLinkage:
3258 return llvm::GlobalValue::InternalLinkage;
3259
3260 case VisibleNoLinkage:
3261 case ModuleInternalLinkage:
3262 case ModuleLinkage:
3263 case ExternalLinkage:
3264 // RTTI is not enabled, which means that this type info struct is going
3265 // to be used for exception handling. Give it linkonce_odr linkage.
3266 if (!CGM.getLangOpts().RTTI)
3267 return llvm::GlobalValue::LinkOnceODRLinkage;
3268
3269 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
3270 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
3271 if (RD->hasAttr<WeakAttr>())
3272 return llvm::GlobalValue::WeakODRLinkage;
3273 if (CGM.getTriple().isWindowsItaniumEnvironment())
3274 if (RD->hasAttr<DLLImportAttr>() &&
3275 ShouldUseExternalRTTIDescriptor(CGM, Ty))
3276 return llvm::GlobalValue::ExternalLinkage;
3277 // MinGW always uses LinkOnceODRLinkage for type info.
3278 if (RD->isDynamicClass() &&
3279 !CGM.getContext()
3280 .getTargetInfo()
3281 .getTriple()
3282 .isWindowsGNUEnvironment())
3283 return CGM.getVTableLinkage(RD);
3284 }
3285
3286 return llvm::GlobalValue::LinkOnceODRLinkage;
3287 }
3288
3289 llvm_unreachable("Invalid linkage!");
David Majnemere2cb8d12014-07-07 06:20:47 +00003290}
3291
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003292llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003293 // We want to operate on the canonical type.
Yaron Kerenebd14262016-03-16 12:14:43 +00003294 Ty = Ty.getCanonicalType();
David Majnemere2cb8d12014-07-07 06:20:47 +00003295
3296 // Check if we've already emitted an RTTI descriptor for this type.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00003297 SmallString<256> Name;
3298 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00003299 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00003300
3301 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
3302 if (OldGV && !OldGV->isDeclaration()) {
3303 assert(!OldGV->hasAvailableExternallyLinkage() &&
3304 "available_externally typeinfos not yet implemented");
3305
3306 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
3307 }
3308
3309 // Check if there is already an external RTTI descriptor for this type.
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003310 if (IsStandardLibraryRTTIDescriptor(Ty) ||
3311 ShouldUseExternalRTTIDescriptor(CGM, Ty))
David Majnemere2cb8d12014-07-07 06:20:47 +00003312 return GetAddrOfExternalRTTIDescriptor(Ty);
3313
3314 // Emit the standard library with external linkage.
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003315 llvm::GlobalVariable::LinkageTypes Linkage = getTypeInfoLinkage(CGM, Ty);
Richard Smithbbb26552018-05-21 20:10:54 +00003316
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003317 // Give the type_info object and name the formal visibility of the
3318 // type itself.
3319 llvm::GlobalValue::VisibilityTypes llvmVisibility;
3320 if (llvm::GlobalValue::isLocalLinkage(Linkage))
3321 // If the linkage is local, only default visibility makes sense.
3322 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
3323 else if (CXXABI.classifyRTTIUniqueness(Ty, Linkage) ==
3324 ItaniumCXXABI::RUK_NonUniqueHidden)
3325 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
3326 else
3327 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
3328
3329 llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass =
3330 llvm::GlobalValue::DefaultStorageClass;
3331 if (CGM.getTriple().isWindowsItaniumEnvironment()) {
3332 auto RD = Ty->getAsCXXRecordDecl();
3333 if (RD && RD->hasAttr<DLLExportAttr>())
3334 DLLStorageClass = llvm::GlobalValue::DLLExportStorageClass;
3335 }
3336
3337 return BuildTypeInfo(Ty, Linkage, llvmVisibility, DLLStorageClass);
3338}
3339
3340llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(
3341 QualType Ty,
3342 llvm::GlobalVariable::LinkageTypes Linkage,
3343 llvm::GlobalValue::VisibilityTypes Visibility,
3344 llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003345 // Add the vtable pointer.
3346 BuildVTablePointer(cast<Type>(Ty));
3347
3348 // And the name.
Richard Smithbbb26552018-05-21 20:10:54 +00003349 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
David Majnemere2cb8d12014-07-07 06:20:47 +00003350 llvm::Constant *TypeNameField;
3351
3352 // If we're supposed to demote the visibility, be sure to set a flag
3353 // to use a string comparison for type_info comparisons.
3354 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
Richard Smithbbb26552018-05-21 20:10:54 +00003355 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
David Majnemere2cb8d12014-07-07 06:20:47 +00003356 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
3357 // The flag is the sign bit, which on ARM64 is defined to be clear
3358 // for global pointers. This is very ARM64-specific.
3359 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
3360 llvm::Constant *flag =
3361 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
3362 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
3363 TypeNameField =
3364 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
3365 } else {
3366 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
3367 }
3368 Fields.push_back(TypeNameField);
3369
3370 switch (Ty->getTypeClass()) {
3371#define TYPE(Class, Base)
3372#define ABSTRACT_TYPE(Class, Base)
3373#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3374#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3375#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3376#include "clang/AST/TypeNodes.def"
3377 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
3378
3379 // GCC treats vector types as fundamental types.
3380 case Type::Builtin:
3381 case Type::Vector:
3382 case Type::ExtVector:
3383 case Type::Complex:
3384 case Type::BlockPointer:
3385 // Itanium C++ ABI 2.9.5p4:
3386 // abi::__fundamental_type_info adds no data members to std::type_info.
3387 break;
3388
3389 case Type::LValueReference:
3390 case Type::RValueReference:
3391 llvm_unreachable("References shouldn't get here");
3392
3393 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00003394 case Type::DeducedTemplateSpecialization:
3395 llvm_unreachable("Undeduced type shouldn't get here");
David Majnemere2cb8d12014-07-07 06:20:47 +00003396
Xiuli Pan9c14e282016-01-09 12:53:17 +00003397 case Type::Pipe:
3398 llvm_unreachable("Pipe type shouldn't get here");
3399
David Majnemere2cb8d12014-07-07 06:20:47 +00003400 case Type::ConstantArray:
3401 case Type::IncompleteArray:
3402 case Type::VariableArray:
3403 // Itanium C++ ABI 2.9.5p5:
3404 // abi::__array_type_info adds no data members to std::type_info.
3405 break;
3406
3407 case Type::FunctionNoProto:
Richard Smithb17d6fa2016-12-01 03:04:07 +00003408 case Type::FunctionProto:
David Majnemere2cb8d12014-07-07 06:20:47 +00003409 // Itanium C++ ABI 2.9.5p5:
3410 // abi::__function_type_info adds no data members to std::type_info.
3411 break;
3412
3413 case Type::Enum:
3414 // Itanium C++ ABI 2.9.5p5:
3415 // abi::__enum_type_info adds no data members to std::type_info.
3416 break;
3417
3418 case Type::Record: {
3419 const CXXRecordDecl *RD =
3420 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
3421 if (!RD->hasDefinition() || !RD->getNumBases()) {
3422 // We don't need to emit any fields.
3423 break;
3424 }
3425
3426 if (CanUseSingleInheritance(RD))
3427 BuildSIClassTypeInfo(RD);
3428 else
3429 BuildVMIClassTypeInfo(RD);
3430
3431 break;
3432 }
3433
3434 case Type::ObjCObject:
3435 case Type::ObjCInterface:
3436 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
3437 break;
3438
3439 case Type::ObjCObjectPointer:
3440 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
3441 break;
3442
3443 case Type::Pointer:
3444 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
3445 break;
3446
3447 case Type::MemberPointer:
3448 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
3449 break;
3450
3451 case Type::Atomic:
3452 // No fields, at least for the moment.
3453 break;
3454 }
3455
3456 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
3457
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003458 SmallString<256> Name;
3459 llvm::raw_svector_ostream Out(Name);
3460 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
Rafael Espindolacb92c192015-01-15 23:18:01 +00003461 llvm::Module &M = CGM.getModule();
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003462 llvm::GlobalVariable *OldGV = M.getNamedGlobal(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00003463 llvm::GlobalVariable *GV =
Rafael Espindolacb92c192015-01-15 23:18:01 +00003464 new llvm::GlobalVariable(M, Init->getType(),
Rui Ueyama49a3ad22019-07-16 04:46:31 +00003465 /*isConstant=*/true, Linkage, Init, Name);
Rafael Espindolacb92c192015-01-15 23:18:01 +00003466
David Majnemere2cb8d12014-07-07 06:20:47 +00003467 // If there's already an old global variable, replace it with the new one.
3468 if (OldGV) {
3469 GV->takeName(OldGV);
3470 llvm::Constant *NewPtr =
3471 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3472 OldGV->replaceAllUsesWith(NewPtr);
3473 OldGV->eraseFromParent();
3474 }
3475
Yaron Keren04da2382015-07-29 15:42:28 +00003476 if (CGM.supportsCOMDAT() && GV->isWeakForLinker())
3477 GV->setComdat(M.getOrInsertComdat(GV->getName()));
3478
David Greenbe0c5b62018-09-12 14:09:06 +00003479 CharUnits Align =
3480 CGM.getContext().toCharUnitsFromBits(CGM.getTarget().getPointerAlign(0));
3481 GV->setAlignment(Align.getQuantity());
3482
David Majnemere2cb8d12014-07-07 06:20:47 +00003483 // The Itanium ABI specifies that type_info objects must be globally
3484 // unique, with one exception: if the type is an incomplete class
3485 // type or a (possibly indirect) pointer to one. That exception
3486 // affects the general case of comparing type_info objects produced
3487 // by the typeid operator, which is why the comparison operators on
3488 // std::type_info generally use the type_info name pointers instead
3489 // of the object addresses. However, the language's built-in uses
3490 // of RTTI generally require class types to be complete, even when
3491 // manipulating pointers to those class types. This allows the
3492 // implementation of dynamic_cast to rely on address equality tests,
3493 // which is much faster.
3494
3495 // All of this is to say that it's important that both the type_info
3496 // object and the type_info name be uniqued when weakly emitted.
3497
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003498 TypeName->setVisibility(Visibility);
Rafael Espindola3dd49812018-02-23 00:22:15 +00003499 CGM.setDSOLocal(TypeName);
Rafael Espindola699f5d62018-02-07 22:15:33 +00003500
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003501 GV->setVisibility(Visibility);
Rafael Espindola3dd49812018-02-23 00:22:15 +00003502 CGM.setDSOLocal(GV);
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003503
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003504 TypeName->setDLLStorageClass(DLLStorageClass);
3505 GV->setDLLStorageClass(DLLStorageClass);
David Majnemere2cb8d12014-07-07 06:20:47 +00003506
Peter Collingbournee08e68d2019-06-07 19:10:08 +00003507 TypeName->setPartition(CGM.getCodeGenOpts().SymbolPartition);
3508 GV->setPartition(CGM.getCodeGenOpts().SymbolPartition);
3509
David Majnemere2cb8d12014-07-07 06:20:47 +00003510 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
3511}
3512
David Majnemere2cb8d12014-07-07 06:20:47 +00003513/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
3514/// for the given Objective-C object type.
3515void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
3516 // Drop qualifiers.
3517 const Type *T = OT->getBaseType().getTypePtr();
3518 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
3519
3520 // The builtin types are abi::__class_type_infos and don't require
3521 // extra fields.
3522 if (isa<BuiltinType>(T)) return;
3523
3524 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
3525 ObjCInterfaceDecl *Super = Class->getSuperClass();
3526
3527 // Root classes are also __class_type_info.
3528 if (!Super) return;
3529
3530 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
3531
3532 // Everything else is single inheritance.
3533 llvm::Constant *BaseTypeInfo =
3534 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
3535 Fields.push_back(BaseTypeInfo);
3536}
3537
3538/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
3539/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
3540void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
3541 // Itanium C++ ABI 2.9.5p6b:
3542 // It adds to abi::__class_type_info a single member pointing to the
3543 // type_info structure for the base type,
3544 llvm::Constant *BaseTypeInfo =
3545 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
3546 Fields.push_back(BaseTypeInfo);
3547}
3548
3549namespace {
3550 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
3551 /// a class hierarchy.
3552 struct SeenBases {
3553 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
3554 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
3555 };
3556}
3557
3558/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
3559/// abi::__vmi_class_type_info.
3560///
3561static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
3562 SeenBases &Bases) {
3563
3564 unsigned Flags = 0;
3565
3566 const CXXRecordDecl *BaseDecl =
3567 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
3568
3569 if (Base->isVirtual()) {
3570 // Mark the virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003571 if (!Bases.VirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003572 // If this virtual base has been seen before, then the class is diamond
3573 // shaped.
3574 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
3575 } else {
3576 if (Bases.NonVirtualBases.count(BaseDecl))
3577 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3578 }
3579 } else {
3580 // Mark the non-virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003581 if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003582 // If this non-virtual base has been seen before, then the class has non-
3583 // diamond shaped repeated inheritance.
3584 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3585 } else {
3586 if (Bases.VirtualBases.count(BaseDecl))
3587 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3588 }
3589 }
3590
3591 // Walk all bases.
3592 for (const auto &I : BaseDecl->bases())
3593 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3594
3595 return Flags;
3596}
3597
3598static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
3599 unsigned Flags = 0;
3600 SeenBases Bases;
3601
3602 // Walk all bases.
3603 for (const auto &I : RD->bases())
3604 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3605
3606 return Flags;
3607}
3608
3609/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
3610/// classes with bases that do not satisfy the abi::__si_class_type_info
3611/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
3612void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
3613 llvm::Type *UnsignedIntLTy =
3614 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3615
3616 // Itanium C++ ABI 2.9.5p6c:
3617 // __flags is a word with flags describing details about the class
3618 // structure, which may be referenced by using the __flags_masks
3619 // enumeration. These flags refer to both direct and indirect bases.
3620 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
3621 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3622
3623 // Itanium C++ ABI 2.9.5p6c:
3624 // __base_count is a word with the number of direct proper base class
3625 // descriptions that follow.
3626 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
3627
3628 if (!RD->getNumBases())
3629 return;
3630
David Majnemere2cb8d12014-07-07 06:20:47 +00003631 // Now add the base class descriptions.
3632
3633 // Itanium C++ ABI 2.9.5p6c:
3634 // __base_info[] is an array of base class descriptions -- one for every
3635 // direct proper base. Each description is of the type:
3636 //
3637 // struct abi::__base_class_type_info {
3638 // public:
3639 // const __class_type_info *__base_type;
3640 // long __offset_flags;
3641 //
3642 // enum __offset_flags_masks {
3643 // __virtual_mask = 0x1,
3644 // __public_mask = 0x2,
3645 // __offset_shift = 8
3646 // };
3647 // };
Reid Klecknerd8b04662016-08-25 22:16:30 +00003648
3649 // If we're in mingw and 'long' isn't wide enough for a pointer, use 'long
3650 // long' instead of 'long' for __offset_flags. libstdc++abi uses long long on
3651 // LLP64 platforms.
3652 // FIXME: Consider updating libc++abi to match, and extend this logic to all
3653 // LLP64 platforms.
3654 QualType OffsetFlagsTy = CGM.getContext().LongTy;
3655 const TargetInfo &TI = CGM.getContext().getTargetInfo();
3656 if (TI.getTriple().isOSCygMing() && TI.getPointerWidth(0) > TI.getLongWidth())
3657 OffsetFlagsTy = CGM.getContext().LongLongTy;
3658 llvm::Type *OffsetFlagsLTy =
3659 CGM.getTypes().ConvertType(OffsetFlagsTy);
3660
David Majnemere2cb8d12014-07-07 06:20:47 +00003661 for (const auto &Base : RD->bases()) {
3662 // The __base_type member points to the RTTI for the base type.
3663 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
3664
3665 const CXXRecordDecl *BaseDecl =
3666 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
3667
3668 int64_t OffsetFlags = 0;
3669
3670 // All but the lower 8 bits of __offset_flags are a signed offset.
3671 // For a non-virtual base, this is the offset in the object of the base
3672 // subobject. For a virtual base, this is the offset in the virtual table of
3673 // the virtual base offset for the virtual base referenced (negative).
3674 CharUnits Offset;
3675 if (Base.isVirtual())
3676 Offset =
3677 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
3678 else {
3679 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
3680 Offset = Layout.getBaseClassOffset(BaseDecl);
3681 };
3682
3683 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
3684
3685 // The low-order byte of __offset_flags contains flags, as given by the
3686 // masks from the enumeration __offset_flags_masks.
3687 if (Base.isVirtual())
3688 OffsetFlags |= BCTI_Virtual;
3689 if (Base.getAccessSpecifier() == AS_public)
3690 OffsetFlags |= BCTI_Public;
3691
Reid Klecknerd8b04662016-08-25 22:16:30 +00003692 Fields.push_back(llvm::ConstantInt::get(OffsetFlagsLTy, OffsetFlags));
David Majnemere2cb8d12014-07-07 06:20:47 +00003693 }
3694}
3695
Richard Smitha7d93782016-12-01 03:32:42 +00003696/// Compute the flags for a __pbase_type_info, and remove the corresponding
3697/// pieces from \p Type.
3698static unsigned extractPBaseFlags(ASTContext &Ctx, QualType &Type) {
3699 unsigned Flags = 0;
David Majnemere2cb8d12014-07-07 06:20:47 +00003700
Richard Smitha7d93782016-12-01 03:32:42 +00003701 if (Type.isConstQualified())
3702 Flags |= ItaniumRTTIBuilder::PTI_Const;
3703 if (Type.isVolatileQualified())
3704 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
3705 if (Type.isRestrictQualified())
3706 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
3707 Type = Type.getUnqualifiedType();
David Majnemere2cb8d12014-07-07 06:20:47 +00003708
3709 // Itanium C++ ABI 2.9.5p7:
3710 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3711 // incomplete class type, the incomplete target type flag is set.
Richard Smitha7d93782016-12-01 03:32:42 +00003712 if (ContainsIncompleteClassType(Type))
3713 Flags |= ItaniumRTTIBuilder::PTI_Incomplete;
3714
3715 if (auto *Proto = Type->getAs<FunctionProtoType>()) {
Richard Smitheaf11ad2018-05-03 03:58:32 +00003716 if (Proto->isNothrow()) {
Richard Smitha7d93782016-12-01 03:32:42 +00003717 Flags |= ItaniumRTTIBuilder::PTI_Noexcept;
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00003718 Type = Ctx.getFunctionTypeWithExceptionSpec(Type, EST_None);
Richard Smitha7d93782016-12-01 03:32:42 +00003719 }
3720 }
3721
3722 return Flags;
3723}
3724
3725/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
3726/// used for pointer types.
3727void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
3728 // Itanium C++ ABI 2.9.5p7:
3729 // __flags is a flag word describing the cv-qualification and other
3730 // attributes of the type pointed to
3731 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003732
3733 llvm::Type *UnsignedIntLTy =
3734 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3735 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3736
3737 // Itanium C++ ABI 2.9.5p7:
3738 // __pointee is a pointer to the std::type_info derivation for the
3739 // unqualified type being pointed to.
3740 llvm::Constant *PointeeTypeInfo =
Richard Smitha7d93782016-12-01 03:32:42 +00003741 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003742 Fields.push_back(PointeeTypeInfo);
3743}
3744
3745/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
3746/// struct, used for member pointer types.
3747void
3748ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
3749 QualType PointeeTy = Ty->getPointeeType();
3750
David Majnemere2cb8d12014-07-07 06:20:47 +00003751 // Itanium C++ ABI 2.9.5p7:
3752 // __flags is a flag word describing the cv-qualification and other
3753 // attributes of the type pointed to.
Richard Smitha7d93782016-12-01 03:32:42 +00003754 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003755
3756 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
David Majnemere2cb8d12014-07-07 06:20:47 +00003757 if (IsIncompleteClassType(ClassType))
3758 Flags |= PTI_ContainingClassIncomplete;
3759
3760 llvm::Type *UnsignedIntLTy =
3761 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3762 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3763
3764 // Itanium C++ ABI 2.9.5p7:
3765 // __pointee is a pointer to the std::type_info derivation for the
3766 // unqualified type being pointed to.
3767 llvm::Constant *PointeeTypeInfo =
Richard Smitha7d93782016-12-01 03:32:42 +00003768 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003769 Fields.push_back(PointeeTypeInfo);
3770
3771 // Itanium C++ ABI 2.9.5p9:
3772 // __context is a pointer to an abi::__class_type_info corresponding to the
3773 // class type containing the member pointed to
3774 // (e.g., the "A" in "int A::*").
3775 Fields.push_back(
3776 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
3777}
3778
David Majnemer443250f2015-03-17 20:35:00 +00003779llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003780 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
3781}
3782
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003783void ItaniumCXXABI::EmitFundamentalRTTIDescriptors(const CXXRecordDecl *RD) {
Richard Smith4a382012016-02-03 01:32:42 +00003784 // Types added here must also be added to TypeInfoIsInStandardLibrary.
David Majnemere2cb8d12014-07-07 06:20:47 +00003785 QualType FundamentalTypes[] = {
3786 getContext().VoidTy, getContext().NullPtrTy,
3787 getContext().BoolTy, getContext().WCharTy,
3788 getContext().CharTy, getContext().UnsignedCharTy,
3789 getContext().SignedCharTy, getContext().ShortTy,
3790 getContext().UnsignedShortTy, getContext().IntTy,
3791 getContext().UnsignedIntTy, getContext().LongTy,
3792 getContext().UnsignedLongTy, getContext().LongLongTy,
Richard Smith4a382012016-02-03 01:32:42 +00003793 getContext().UnsignedLongLongTy, getContext().Int128Ty,
3794 getContext().UnsignedInt128Ty, getContext().HalfTy,
David Majnemere2cb8d12014-07-07 06:20:47 +00003795 getContext().FloatTy, getContext().DoubleTy,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00003796 getContext().LongDoubleTy, getContext().Float128Ty,
Richard Smith3a8244d2018-05-01 05:02:45 +00003797 getContext().Char8Ty, getContext().Char16Ty,
3798 getContext().Char32Ty
David Majnemere2cb8d12014-07-07 06:20:47 +00003799 };
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003800 llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass =
3801 RD->hasAttr<DLLExportAttr>()
3802 ? llvm::GlobalValue::DLLExportStorageClass
3803 : llvm::GlobalValue::DefaultStorageClass;
3804 llvm::GlobalValue::VisibilityTypes Visibility =
3805 CodeGenModule::GetLLVMVisibility(RD->getVisibility());
3806 for (const QualType &FundamentalType : FundamentalTypes) {
3807 QualType PointerType = getContext().getPointerType(FundamentalType);
3808 QualType PointerTypeConst = getContext().getPointerType(
3809 FundamentalType.withConst());
3810 for (QualType Type : {FundamentalType, PointerType, PointerTypeConst})
3811 ItaniumRTTIBuilder(*this).BuildTypeInfo(
3812 Type, llvm::GlobalValue::ExternalLinkage,
3813 Visibility, DLLStorageClass);
3814 }
David Majnemere2cb8d12014-07-07 06:20:47 +00003815}
3816
3817/// What sort of uniqueness rules should we use for the RTTI for the
3818/// given type?
3819ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
3820 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
3821 if (shouldRTTIBeUnique())
3822 return RUK_Unique;
3823
3824 // It's only necessary for linkonce_odr or weak_odr linkage.
3825 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
3826 Linkage != llvm::GlobalValue::WeakODRLinkage)
3827 return RUK_Unique;
3828
3829 // It's only necessary with default visibility.
3830 if (CanTy->getVisibility() != DefaultVisibility)
3831 return RUK_Unique;
3832
3833 // If we're not required to publish this symbol, hide it.
3834 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3835 return RUK_NonUniqueHidden;
3836
3837 // If we're required to publish this symbol, as we might be under an
3838 // explicit instantiation, leave it with default visibility but
3839 // enable string-comparisons.
3840 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
3841 return RUK_NonUniqueVisible;
3842}
Rafael Espindola91f68b42014-09-15 19:20:10 +00003843
Rafael Espindola1e4df922014-09-16 15:18:21 +00003844// Find out how to codegen the complete destructor and constructor
3845namespace {
3846enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
3847}
3848static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
3849 const CXXMethodDecl *MD) {
3850 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
3851 return StructorCodegen::Emit;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003852
Rafael Espindola1e4df922014-09-16 15:18:21 +00003853 // The complete and base structors are not equivalent if there are any virtual
3854 // bases, so emit separate functions.
3855 if (MD->getParent()->getNumVBases())
3856 return StructorCodegen::Emit;
3857
3858 GlobalDecl AliasDecl;
3859 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3860 AliasDecl = GlobalDecl(DD, Dtor_Complete);
3861 } else {
3862 const auto *CD = cast<CXXConstructorDecl>(MD);
3863 AliasDecl = GlobalDecl(CD, Ctor_Complete);
3864 }
3865 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3866
Chandler Carruth1f82d9b2018-07-29 03:05:07 +00003867 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
3868 return StructorCodegen::RAUW;
Rafael Espindola1e4df922014-09-16 15:18:21 +00003869
Pavel Labathc370f262018-05-14 11:35:44 +00003870 // FIXME: Should we allow available_externally aliases?
Chandler Carruth1f82d9b2018-07-29 03:05:07 +00003871 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
3872 return StructorCodegen::RAUW;
Rafael Espindola1e4df922014-09-16 15:18:21 +00003873
Rafael Espindola0806f982014-09-16 20:19:43 +00003874 if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
Dan Gohman839f2152017-01-17 21:46:38 +00003875 // Only ELF and wasm support COMDATs with arbitrary names (C5/D5).
3876 if (CGM.getTarget().getTriple().isOSBinFormatELF() ||
3877 CGM.getTarget().getTriple().isOSBinFormatWasm())
Rafael Espindola0806f982014-09-16 20:19:43 +00003878 return StructorCodegen::COMDAT;
3879 return StructorCodegen::Emit;
3880 }
Rafael Espindola1e4df922014-09-16 15:18:21 +00003881
3882 return StructorCodegen::Alias;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003883}
3884
Rafael Espindola1e4df922014-09-16 15:18:21 +00003885static void emitConstructorDestructorAlias(CodeGenModule &CGM,
3886 GlobalDecl AliasDecl,
3887 GlobalDecl TargetDecl) {
3888 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3889
3890 StringRef MangledName = CGM.getMangledName(AliasDecl);
3891 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
3892 if (Entry && !Entry->isDeclaration())
3893 return;
3894
3895 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
Rafael Espindola1e4df922014-09-16 15:18:21 +00003896
3897 // Create the alias with no name.
David Blaikie2a791d72015-09-14 18:38:22 +00003898 auto *Alias = llvm::GlobalAlias::create(Linkage, "", Aliasee);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003899
Peter Collingbourned914fd22018-06-18 20:58:54 +00003900 // Constructors and destructors are always unnamed_addr.
3901 Alias->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3902
Rafael Espindola1e4df922014-09-16 15:18:21 +00003903 // Switch any previous uses to the alias.
3904 if (Entry) {
NAKAMURA Takumie9621042015-09-15 01:39:27 +00003905 assert(Entry->getType() == Aliasee->getType() &&
Rafael Espindola1e4df922014-09-16 15:18:21 +00003906 "declaration exists with different type");
3907 Alias->takeName(Entry);
3908 Entry->replaceAllUsesWith(Alias);
3909 Entry->eraseFromParent();
3910 } else {
3911 Alias->setName(MangledName);
3912 }
3913
3914 // Finally, set up the alias with its proper name and attributes.
Rafael Espindolab7350042018-03-01 00:35:47 +00003915 CGM.SetCommonAttributes(AliasDecl, Alias);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003916}
3917
Peter Collingbourned1c5b282019-03-22 23:05:10 +00003918void ItaniumCXXABI::emitCXXStructor(GlobalDecl GD) {
3919 auto *MD = cast<CXXMethodDecl>(GD.getDecl());
Rafael Espindola1e4df922014-09-16 15:18:21 +00003920 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
3921 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
3922
3923 StructorCodegen CGType = getCodegenToUse(CGM, MD);
3924
Peter Collingbourned1c5b282019-03-22 23:05:10 +00003925 if (CD ? GD.getCtorType() == Ctor_Complete
3926 : GD.getDtorType() == Dtor_Complete) {
Rafael Espindola1e4df922014-09-16 15:18:21 +00003927 GlobalDecl BaseDecl;
Peter Collingbourned1c5b282019-03-22 23:05:10 +00003928 if (CD)
3929 BaseDecl = GD.getWithCtorType(Ctor_Base);
3930 else
3931 BaseDecl = GD.getWithDtorType(Dtor_Base);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003932
3933 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
Peter Collingbourned1c5b282019-03-22 23:05:10 +00003934 emitConstructorDestructorAlias(CGM, GD, BaseDecl);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003935 return;
3936 }
3937
3938 if (CGType == StructorCodegen::RAUW) {
Peter Collingbourned1c5b282019-03-22 23:05:10 +00003939 StringRef MangledName = CGM.getMangledName(GD);
Andrey Bokhankocab58582015-08-31 13:20:44 +00003940 auto *Aliasee = CGM.GetAddrOfGlobal(BaseDecl);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003941 CGM.addReplacement(MangledName, Aliasee);
3942 return;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003943 }
3944 }
3945
3946 // The base destructor is equivalent to the base destructor of its
3947 // base class if there is exactly one non-virtual base class with a
3948 // non-trivial destructor, there are no fields with a non-trivial
3949 // destructor, and the body of the destructor is trivial.
Peter Collingbourned1c5b282019-03-22 23:05:10 +00003950 if (DD && GD.getDtorType() == Dtor_Base &&
3951 CGType != StructorCodegen::COMDAT &&
Rafael Espindola1e4df922014-09-16 15:18:21 +00003952 !CGM.TryEmitBaseDestructorAsAlias(DD))
Rafael Espindola91f68b42014-09-15 19:20:10 +00003953 return;
3954
Richard Smith5b349582017-10-13 01:55:36 +00003955 // FIXME: The deleting destructor is equivalent to the selected operator
3956 // delete if:
3957 // * either the delete is a destroying operator delete or the destructor
3958 // would be trivial if it weren't virtual,
3959 // * the conversion from the 'this' parameter to the first parameter of the
3960 // destructor is equivalent to a bitcast,
3961 // * the destructor does not have an implicit "this" return, and
3962 // * the operator delete has the same calling convention and IR function type
3963 // as the destructor.
3964 // In such cases we should try to emit the deleting dtor as an alias to the
3965 // selected 'operator delete'.
3966
Peter Collingbourned1c5b282019-03-22 23:05:10 +00003967 llvm::Function *Fn = CGM.codegenCXXStructor(GD);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003968
Rafael Espindola1e4df922014-09-16 15:18:21 +00003969 if (CGType == StructorCodegen::COMDAT) {
3970 SmallString<256> Buffer;
3971 llvm::raw_svector_ostream Out(Buffer);
3972 if (DD)
3973 getMangleContext().mangleCXXDtorComdat(DD, Out);
3974 else
3975 getMangleContext().mangleCXXCtorComdat(CD, Out);
3976 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
3977 Fn->setComdat(C);
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003978 } else {
3979 CGM.maybeSetTrivialComdat(*MD, *Fn);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003980 }
Rafael Espindola91f68b42014-09-15 19:20:10 +00003981}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003982
James Y Knight9871db02019-02-05 16:42:33 +00003983static llvm::FunctionCallee getBeginCatchFn(CodeGenModule &CGM) {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003984 // void *__cxa_begin_catch(void*);
3985 llvm::FunctionType *FTy = llvm::FunctionType::get(
Rui Ueyama49a3ad22019-07-16 04:46:31 +00003986 CGM.Int8PtrTy, CGM.Int8PtrTy, /*isVarArg=*/false);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003987
3988 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
3989}
3990
James Y Knight9871db02019-02-05 16:42:33 +00003991static llvm::FunctionCallee getEndCatchFn(CodeGenModule &CGM) {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003992 // void __cxa_end_catch();
3993 llvm::FunctionType *FTy =
Rui Ueyama49a3ad22019-07-16 04:46:31 +00003994 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003995
3996 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
3997}
3998
James Y Knight9871db02019-02-05 16:42:33 +00003999static llvm::FunctionCallee getGetExceptionPtrFn(CodeGenModule &CGM) {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004000 // void *__cxa_get_exception_ptr(void*);
4001 llvm::FunctionType *FTy = llvm::FunctionType::get(
Rui Ueyama49a3ad22019-07-16 04:46:31 +00004002 CGM.Int8PtrTy, CGM.Int8PtrTy, /*isVarArg=*/false);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004003
4004 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
4005}
4006
4007namespace {
4008 /// A cleanup to call __cxa_end_catch. In many cases, the caught
4009 /// exception type lets us state definitively that the thrown exception
4010 /// type does not have a destructor. In particular:
4011 /// - Catch-alls tell us nothing, so we have to conservatively
4012 /// assume that the thrown exception might have a destructor.
4013 /// - Catches by reference behave according to their base types.
4014 /// - Catches of non-record types will only trigger for exceptions
4015 /// of non-record types, which never have destructors.
4016 /// - Catches of record types can trigger for arbitrary subclasses
4017 /// of the caught type, so we have to assume the actual thrown
4018 /// exception type might have a throwing destructor, even if the
4019 /// caught type's destructor is trivial or nothrow.
David Blaikie7e70d682015-08-18 22:40:54 +00004020 struct CallEndCatch final : EHScopeStack::Cleanup {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004021 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
4022 bool MightThrow;
4023
4024 void Emit(CodeGenFunction &CGF, Flags flags) override {
4025 if (!MightThrow) {
4026 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
4027 return;
4028 }
4029
4030 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
4031 }
4032 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004033}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004034
4035/// Emits a call to __cxa_begin_catch and enters a cleanup to call
4036/// __cxa_end_catch.
4037///
4038/// \param EndMightThrow - true if __cxa_end_catch might throw
4039static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
4040 llvm::Value *Exn,
4041 bool EndMightThrow) {
4042 llvm::CallInst *call =
4043 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
4044
4045 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
4046
4047 return call;
4048}
4049
4050/// A "special initializer" callback for initializing a catch
4051/// parameter during catch initialization.
4052static void InitCatchParam(CodeGenFunction &CGF,
4053 const VarDecl &CatchParam,
John McCall7f416cc2015-09-08 08:05:57 +00004054 Address ParamAddr,
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004055 SourceLocation Loc) {
4056 // Load the exception from where the landing pad saved it.
4057 llvm::Value *Exn = CGF.getExceptionFromSlot();
4058
4059 CanQualType CatchType =
4060 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
4061 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
4062
4063 // If we're catching by reference, we can just cast the object
4064 // pointer to the appropriate pointer.
4065 if (isa<ReferenceType>(CatchType)) {
4066 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
4067 bool EndCatchMightThrow = CaughtType->isRecordType();
4068
4069 // __cxa_begin_catch returns the adjusted object pointer.
4070 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
4071
4072 // We have no way to tell the personality function that we're
4073 // catching by reference, so if we're catching a pointer,
4074 // __cxa_begin_catch will actually return that pointer by value.
4075 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
4076 QualType PointeeType = PT->getPointeeType();
4077
4078 // When catching by reference, generally we should just ignore
4079 // this by-value pointer and use the exception object instead.
4080 if (!PointeeType->isRecordType()) {
4081
4082 // Exn points to the struct _Unwind_Exception header, which
4083 // we have to skip past in order to reach the exception data.
4084 unsigned HeaderSize =
4085 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
4086 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
4087
4088 // However, if we're catching a pointer-to-record type that won't
4089 // work, because the personality function might have adjusted
4090 // the pointer. There's actually no way for us to fully satisfy
4091 // the language/ABI contract here: we can't use Exn because it
4092 // might have the wrong adjustment, but we can't use the by-value
4093 // pointer because it's off by a level of abstraction.
4094 //
4095 // The current solution is to dump the adjusted pointer into an
4096 // alloca, which breaks language semantics (because changing the
4097 // pointer doesn't change the exception) but at least works.
4098 // The better solution would be to filter out non-exact matches
4099 // and rethrow them, but this is tricky because the rethrow
4100 // really needs to be catchable by other sites at this landing
4101 // pad. The best solution is to fix the personality function.
4102 } else {
4103 // Pull the pointer for the reference type off.
4104 llvm::Type *PtrTy =
4105 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
4106
4107 // Create the temporary and write the adjusted pointer into it.
John McCall7f416cc2015-09-08 08:05:57 +00004108 Address ExnPtrTmp =
4109 CGF.CreateTempAlloca(PtrTy, CGF.getPointerAlign(), "exn.byref.tmp");
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004110 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
4111 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
4112
4113 // Bind the reference to the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00004114 AdjustedExn = ExnPtrTmp.getPointer();
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004115 }
4116 }
4117
4118 llvm::Value *ExnCast =
4119 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
4120 CGF.Builder.CreateStore(ExnCast, ParamAddr);
4121 return;
4122 }
4123
4124 // Scalars and complexes.
4125 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
4126 if (TEK != TEK_Aggregate) {
4127 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
4128
4129 // If the catch type is a pointer type, __cxa_begin_catch returns
4130 // the pointer by value.
4131 if (CatchType->hasPointerRepresentation()) {
4132 llvm::Value *CastExn =
4133 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
4134
4135 switch (CatchType.getQualifiers().getObjCLifetime()) {
4136 case Qualifiers::OCL_Strong:
4137 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +00004138 LLVM_FALLTHROUGH;
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004139
4140 case Qualifiers::OCL_None:
4141 case Qualifiers::OCL_ExplicitNone:
4142 case Qualifiers::OCL_Autoreleasing:
4143 CGF.Builder.CreateStore(CastExn, ParamAddr);
4144 return;
4145
4146 case Qualifiers::OCL_Weak:
4147 CGF.EmitARCInitWeak(ParamAddr, CastExn);
4148 return;
4149 }
4150 llvm_unreachable("bad ownership qualifier!");
4151 }
4152
4153 // Otherwise, it returns a pointer into the exception object.
4154
4155 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
4156 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
4157
4158 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
John McCall7f416cc2015-09-08 08:05:57 +00004159 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004160 switch (TEK) {
4161 case TEK_Complex:
4162 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
4163 /*init*/ true);
4164 return;
4165 case TEK_Scalar: {
4166 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
4167 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
4168 return;
4169 }
4170 case TEK_Aggregate:
4171 llvm_unreachable("evaluation kind filtered out!");
4172 }
4173 llvm_unreachable("bad evaluation kind");
4174 }
4175
4176 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
John McCall7f416cc2015-09-08 08:05:57 +00004177 auto catchRD = CatchType->getAsCXXRecordDecl();
4178 CharUnits caughtExnAlignment = CGF.CGM.getClassPointerAlignment(catchRD);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004179
4180 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
4181
4182 // Check for a copy expression. If we don't have a copy expression,
4183 // that means a trivial copy is okay.
4184 const Expr *copyExpr = CatchParam.getInit();
4185 if (!copyExpr) {
4186 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
John McCall7f416cc2015-09-08 08:05:57 +00004187 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
4188 caughtExnAlignment);
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00004189 LValue Dest = CGF.MakeAddrLValue(ParamAddr, CatchType);
4190 LValue Src = CGF.MakeAddrLValue(adjustedExn, CatchType);
Richard Smithe78fac52018-04-05 20:52:58 +00004191 CGF.EmitAggregateCopy(Dest, Src, CatchType, AggValueSlot::DoesNotOverlap);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004192 return;
4193 }
4194
4195 // We have to call __cxa_get_exception_ptr to get the adjusted
4196 // pointer before copying.
4197 llvm::CallInst *rawAdjustedExn =
4198 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
4199
4200 // Cast that to the appropriate type.
John McCall7f416cc2015-09-08 08:05:57 +00004201 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
4202 caughtExnAlignment);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004203
4204 // The copy expression is defined in terms of an OpaqueValueExpr.
4205 // Find it and map it to the adjusted expression.
4206 CodeGenFunction::OpaqueValueMapping
4207 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
4208 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
4209
4210 // Call the copy ctor in a terminate scope.
4211 CGF.EHStack.pushTerminate();
4212
4213 // Perform the copy construction.
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004214 CGF.EmitAggExpr(copyExpr,
John McCall7f416cc2015-09-08 08:05:57 +00004215 AggValueSlot::forAddr(ParamAddr, Qualifiers(),
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004216 AggValueSlot::IsNotDestructed,
4217 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00004218 AggValueSlot::IsNotAliased,
4219 AggValueSlot::DoesNotOverlap));
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004220
4221 // Leave the terminate scope.
4222 CGF.EHStack.popTerminate();
4223
4224 // Undo the opaque value mapping.
4225 opaque.pop();
4226
4227 // Finally we can call __cxa_begin_catch.
4228 CallBeginCatch(CGF, Exn, true);
4229}
4230
4231/// Begins a catch statement by initializing the catch variable and
4232/// calling __cxa_begin_catch.
4233void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF,
4234 const CXXCatchStmt *S) {
4235 // We have to be very careful with the ordering of cleanups here:
4236 // C++ [except.throw]p4:
4237 // The destruction [of the exception temporary] occurs
4238 // immediately after the destruction of the object declared in
4239 // the exception-declaration in the handler.
4240 //
4241 // So the precise ordering is:
4242 // 1. Construct catch variable.
4243 // 2. __cxa_begin_catch
4244 // 3. Enter __cxa_end_catch cleanup
4245 // 4. Enter dtor cleanup
4246 //
4247 // We do this by using a slightly abnormal initialization process.
4248 // Delegation sequence:
4249 // - ExitCXXTryStmt opens a RunCleanupsScope
4250 // - EmitAutoVarAlloca creates the variable and debug info
4251 // - InitCatchParam initializes the variable from the exception
4252 // - CallBeginCatch calls __cxa_begin_catch
4253 // - CallBeginCatch enters the __cxa_end_catch cleanup
4254 // - EmitAutoVarCleanups enters the variable destructor cleanup
4255 // - EmitCXXTryStmt emits the code for the catch body
4256 // - EmitCXXTryStmt close the RunCleanupsScope
4257
4258 VarDecl *CatchParam = S->getExceptionDecl();
4259 if (!CatchParam) {
4260 llvm::Value *Exn = CGF.getExceptionFromSlot();
4261 CallBeginCatch(CGF, Exn, true);
4262 return;
4263 }
4264
4265 // Emit the local.
4266 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004267 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getBeginLoc());
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004268 CGF.EmitAutoVarCleanups(var);
4269}
4270
4271/// Get or define the following function:
4272/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
4273/// This code is used only in C++.
James Y Knight9871db02019-02-05 16:42:33 +00004274static llvm::FunctionCallee getClangCallTerminateFn(CodeGenModule &CGM) {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004275 llvm::FunctionType *fnTy =
Rui Ueyama49a3ad22019-07-16 04:46:31 +00004276 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*isVarArg=*/false);
James Y Knight9871db02019-02-05 16:42:33 +00004277 llvm::FunctionCallee fnRef = CGM.CreateRuntimeFunction(
Rui Ueyama49a3ad22019-07-16 04:46:31 +00004278 fnTy, "__clang_call_terminate", llvm::AttributeList(), /*Local=*/true);
James Y Knight9871db02019-02-05 16:42:33 +00004279 llvm::Function *fn =
4280 cast<llvm::Function>(fnRef.getCallee()->stripPointerCasts());
4281 if (fn->empty()) {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004282 fn->setDoesNotThrow();
4283 fn->setDoesNotReturn();
4284
4285 // What we really want is to massively penalize inlining without
4286 // forbidding it completely. The difference between that and
4287 // 'noinline' is negligible.
4288 fn->addFnAttr(llvm::Attribute::NoInline);
4289
4290 // Allow this function to be shared across translation units, but
4291 // we don't want it to turn into an exported symbol.
4292 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
4293 fn->setVisibility(llvm::Function::HiddenVisibility);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00004294 if (CGM.supportsCOMDAT())
4295 fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004296
4297 // Set up the function.
4298 llvm::BasicBlock *entry =
James Y Knight9871db02019-02-05 16:42:33 +00004299 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
John McCall7f416cc2015-09-08 08:05:57 +00004300 CGBuilderTy builder(CGM, entry);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004301
4302 // Pull the exception pointer out of the parameter list.
4303 llvm::Value *exn = &*fn->arg_begin();
4304
4305 // Call __cxa_begin_catch(exn).
4306 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
4307 catchCall->setDoesNotThrow();
4308 catchCall->setCallingConv(CGM.getRuntimeCC());
4309
4310 // Call std::terminate().
David Blaikie4ba525b2015-07-14 17:27:39 +00004311 llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn());
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004312 termCall->setDoesNotThrow();
4313 termCall->setDoesNotReturn();
4314 termCall->setCallingConv(CGM.getRuntimeCC());
4315
4316 // std::terminate cannot return.
4317 builder.CreateUnreachable();
4318 }
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004319 return fnRef;
4320}
4321
4322llvm::CallInst *
4323ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
4324 llvm::Value *Exn) {
4325 // In C++, we want to call __cxa_begin_catch() before terminating.
4326 if (Exn) {
4327 assert(CGF.CGM.getLangOpts().CPlusPlus);
4328 return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn);
4329 }
4330 return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
4331}
Peter Collingbourne60108802017-12-13 21:53:04 +00004332
4333std::pair<llvm::Value *, const CXXRecordDecl *>
4334ItaniumCXXABI::LoadVTablePtr(CodeGenFunction &CGF, Address This,
4335 const CXXRecordDecl *RD) {
4336 return {CGF.GetVTablePtr(This, CGM.Int8PtrTy, RD), RD};
4337}
Heejin Ahnc6479192018-05-31 22:18:13 +00004338
4339void WebAssemblyCXXABI::emitBeginCatch(CodeGenFunction &CGF,
4340 const CXXCatchStmt *C) {
Heejin Ahn1eb074d2018-06-01 01:01:37 +00004341 if (CGF.getTarget().hasFeature("exception-handling"))
4342 CGF.EHStack.pushCleanup<CatchRetScope>(
4343 NormalCleanup, cast<llvm::CatchPadInst>(CGF.CurrentFuncletPad));
Heejin Ahnc6479192018-05-31 22:18:13 +00004344 ItaniumCXXABI::emitBeginCatch(CGF, C);
4345}