blob: 29ec2d4b81cd23d0c05e344b2df04655ec287c0e [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
John McCall475999d2010-08-22 00:05:51 +000046protected:
Mark Seabornedf0d382013-07-24 16:25:13 +000047 bool UseARMMethodPtrABI;
48 bool UseARMGuardVarABI;
John McCalld23b27e2016-09-16 02:40:45 +000049 bool Use32BitVTableOffsetABI;
John McCall7a9aac22010-08-23 01:21:21 +000050
Timur Iskhodzhanov67455222013-10-03 06:26:13 +000051 ItaniumMangleContext &getMangleContext() {
52 return cast<ItaniumMangleContext>(CodeGen::CGCXXABI::getMangleContext());
53 }
54
Charles Davis4e786dd2010-05-25 19:52:27 +000055public:
Mark Seabornedf0d382013-07-24 16:25:13 +000056 ItaniumCXXABI(CodeGen::CodeGenModule &CGM,
57 bool UseARMMethodPtrABI = false,
58 bool UseARMGuardVarABI = false) :
59 CGCXXABI(CGM), UseARMMethodPtrABI(UseARMMethodPtrABI),
John McCalld23b27e2016-09-16 02:40:45 +000060 UseARMGuardVarABI(UseARMGuardVarABI),
Richard Smithb17d6fa2016-12-01 03:04:07 +000061 Use32BitVTableOffsetABI(false) { }
John McCall475999d2010-08-22 00:05:51 +000062
Reid Kleckner40ca9132014-05-13 22:05:45 +000063 bool classifyReturnType(CGFunctionInfo &FI) const override;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000064
Craig Topper4f12f102014-03-12 06:41:41 +000065 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override {
Richard Smith96cd6712017-08-16 01:49:53 +000066 // If C++ prohibits us from making a copy, pass by address.
Reid Kleckneradb41982019-04-30 22:23:20 +000067 if (!RD->canPassInRegisters())
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000068 return RAA_Indirect;
69 return RAA_Default;
70 }
71
John McCall7f416cc2015-09-08 08:05:57 +000072 bool isThisCompleteObject(GlobalDecl GD) const override {
73 // The Itanium ABI has separate complete-object vs. base-object
74 // variants of both constructors and destructors.
75 if (isa<CXXDestructorDecl>(GD.getDecl())) {
76 switch (GD.getDtorType()) {
77 case Dtor_Complete:
78 case Dtor_Deleting:
79 return true;
80
81 case Dtor_Base:
82 return false;
83
84 case Dtor_Comdat:
85 llvm_unreachable("emitting dtor comdat as function?");
86 }
87 llvm_unreachable("bad dtor kind");
88 }
89 if (isa<CXXConstructorDecl>(GD.getDecl())) {
90 switch (GD.getCtorType()) {
91 case Ctor_Complete:
92 return true;
93
94 case Ctor_Base:
95 return false;
96
97 case Ctor_CopyingClosure:
98 case Ctor_DefaultClosure:
99 llvm_unreachable("closure ctors in Itanium ABI?");
100
101 case Ctor_Comdat:
102 llvm_unreachable("emitting ctor comdat as function?");
103 }
104 llvm_unreachable("bad dtor kind");
105 }
106
107 // No other kinds.
108 return false;
109 }
110
Craig Topper4f12f102014-03-12 06:41:41 +0000111 bool isZeroInitializable(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +0000112
Craig Topper4f12f102014-03-12 06:41:41 +0000113 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
John McCall7a9aac22010-08-23 01:21:21 +0000114
John McCallb92ab1a2016-10-26 23:46:34 +0000115 CGCallee
Craig Topper4f12f102014-03-12 06:41:41 +0000116 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
117 const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000118 Address This,
119 llvm::Value *&ThisPtrForCall,
Craig Topper4f12f102014-03-12 06:41:41 +0000120 llvm::Value *MemFnPtr,
121 const MemberPointerType *MPT) override;
John McCalla8bbb822010-08-22 03:04:22 +0000122
Craig Topper4f12f102014-03-12 06:41:41 +0000123 llvm::Value *
124 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000125 Address Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000126 llvm::Value *MemPtr,
127 const MemberPointerType *MPT) override;
John McCallc134eb52010-08-31 21:07:20 +0000128
John McCall7a9aac22010-08-23 01:21:21 +0000129 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
130 const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +0000131 llvm::Value *Src) override;
John McCallc62bb392012-02-15 01:22:51 +0000132 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +0000133 llvm::Constant *Src) override;
John McCall84fa5102010-08-22 04:16:24 +0000134
Craig Topper4f12f102014-03-12 06:41:41 +0000135 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +0000136
David Majnemere2be95b2015-06-23 07:31:01 +0000137 llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD) override;
John McCallf3a88602011-02-03 08:15:49 +0000138 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +0000139 CharUnits offset) override;
140 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
Richard Smithdafff942012-01-14 04:30:29 +0000141 llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
142 CharUnits ThisAdjustment);
John McCall1c456c82010-08-22 06:43:33 +0000143
John McCall7a9aac22010-08-23 01:21:21 +0000144 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000145 llvm::Value *L, llvm::Value *R,
John McCall7a9aac22010-08-23 01:21:21 +0000146 const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +0000147 bool Inequality) override;
John McCall131d97d2010-08-22 08:30:07 +0000148
John McCall7a9aac22010-08-23 01:21:21 +0000149 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000150 llvm::Value *Addr,
151 const MemberPointerType *MPT) override;
John McCall5d865c322010-08-31 07:33:07 +0000152
David Majnemer08681372014-11-01 07:37:17 +0000153 void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,
John McCall7f416cc2015-09-08 08:05:57 +0000154 Address Ptr, QualType ElementType,
David Majnemer0c0b6d92014-10-31 20:09:12 +0000155 const CXXDestructorDecl *Dtor) override;
John McCall82fb8922012-09-25 10:10:39 +0000156
David Majnemer442d0a22014-11-25 07:20:20 +0000157 void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
David Majnemer7c237072015-03-05 00:46:22 +0000158 void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override;
David Majnemer442d0a22014-11-25 07:20:20 +0000159
Reid Klecknerfff8e7f2015-03-03 19:21:04 +0000160 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
161
162 llvm::CallInst *
163 emitTerminateForUnexpectedException(CodeGenFunction &CGF,
164 llvm::Value *Exn) override;
165
Thomas Andersonb6d87cf2018-07-24 00:43:47 +0000166 void EmitFundamentalRTTIDescriptors(const CXXRecordDecl *RD);
David Majnemer443250f2015-03-17 20:35:00 +0000167 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
Reid Kleckner10aa7702015-09-16 20:15:55 +0000168 CatchTypeInfo
David Majnemer37b417f2015-03-29 21:55:10 +0000169 getAddrOfCXXCatchHandlerType(QualType Ty,
170 QualType CatchHandlerType) override {
Reid Kleckner10aa7702015-09-16 20:15:55 +0000171 return CatchTypeInfo{getAddrOfRTTIDescriptor(Ty), 0};
David Majnemer443250f2015-03-17 20:35:00 +0000172 }
David Majnemere2cb8d12014-07-07 06:20:47 +0000173
David Majnemer1162d252014-06-22 19:05:33 +0000174 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
175 void EmitBadTypeidCall(CodeGenFunction &CGF) override;
176 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
John McCall7f416cc2015-09-08 08:05:57 +0000177 Address ThisPtr,
David Majnemer1162d252014-06-22 19:05:33 +0000178 llvm::Type *StdTypeInfoPtrTy) override;
179
180 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
181 QualType SrcRecordTy) override;
182
John McCall7f416cc2015-09-08 08:05:57 +0000183 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, Address Value,
David Majnemer1162d252014-06-22 19:05:33 +0000184 QualType SrcRecordTy, QualType DestTy,
185 QualType DestRecordTy,
186 llvm::BasicBlock *CastEnd) override;
187
John McCall7f416cc2015-09-08 08:05:57 +0000188 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
David Majnemer1162d252014-06-22 19:05:33 +0000189 QualType SrcRecordTy,
190 QualType DestTy) override;
191
192 bool EmitBadCastCall(CodeGenFunction &CGF) override;
193
Craig Topper4f12f102014-03-12 06:41:41 +0000194 llvm::Value *
John McCall7f416cc2015-09-08 08:05:57 +0000195 GetVirtualBaseClassOffset(CodeGenFunction &CGF, Address This,
Craig Topper4f12f102014-03-12 06:41:41 +0000196 const CXXRecordDecl *ClassDecl,
197 const CXXRecordDecl *BaseClassDecl) override;
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000198
Craig Topper4f12f102014-03-12 06:41:41 +0000199 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000200
George Burgess IVf203dbf2017-02-22 20:28:02 +0000201 AddedStructorArgs
Peter Collingbourned1c5b282019-03-22 23:05:10 +0000202 buildStructorSignature(GlobalDecl GD,
George Burgess IVf203dbf2017-02-22 20:28:02 +0000203 SmallVectorImpl<CanQualType> &ArgTys) override;
John McCall5d865c322010-08-31 07:33:07 +0000204
Reid Klecknere7de47e2013-07-22 13:51:44 +0000205 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
Craig Topper4f12f102014-03-12 06:41:41 +0000206 CXXDtorType DT) const override {
Reid Klecknere7de47e2013-07-22 13:51:44 +0000207 // Itanium does not emit any destructor variant as an inline thunk.
208 // Delegating may occur as an optimization, but all variants are either
209 // emitted with external linkage or as linkonce if they are inline and used.
210 return false;
211 }
212
Craig Topper4f12f102014-03-12 06:41:41 +0000213 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
Reid Klecknere7de47e2013-07-22 13:51:44 +0000214
Reid Kleckner89077a12013-12-17 19:46:40 +0000215 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
Craig Topper4f12f102014-03-12 06:41:41 +0000216 FunctionArgList &Params) override;
John McCall5d865c322010-08-31 07:33:07 +0000217
Craig Topper4f12f102014-03-12 06:41:41 +0000218 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
John McCall8ed55a52010-09-02 09:58:18 +0000219
George Burgess IVf203dbf2017-02-22 20:28:02 +0000220 AddedStructorArgs
221 addImplicitConstructorArgs(CodeGenFunction &CGF, const CXXConstructorDecl *D,
222 CXXCtorType Type, bool ForVirtualBase,
223 bool Delegating, CallArgList &Args) override;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000224
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000225 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
226 CXXDtorType Type, bool ForVirtualBase,
Marco Antognini88559632019-07-22 09:39:13 +0000227 bool Delegating, Address This,
228 QualType ThisTy) override;
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000229
Craig Topper4f12f102014-03-12 06:41:41 +0000230 void emitVTableDefinitions(CodeGenVTables &CGVT,
231 const CXXRecordDecl *RD) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000232
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000233 bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,
234 CodeGenFunction::VPtr Vptr) override;
235
236 bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override {
237 return true;
238 }
239
240 llvm::Constant *
241 getVTableAddressPoint(BaseSubobject Base,
242 const CXXRecordDecl *VTableClass) override;
243
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000244 llvm::Value *getVTableAddressPointInStructor(
245 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000246 BaseSubobject Base, const CXXRecordDecl *NearestVBase) override;
247
248 llvm::Value *getVTableAddressPointInStructorWithVTT(
249 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
250 BaseSubobject Base, const CXXRecordDecl *NearestVBase);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000251
252 llvm::Constant *
253 getVTableAddressPointForConstExpr(BaseSubobject Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000254 const CXXRecordDecl *VTableClass) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000255
256 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
Craig Topper4f12f102014-03-12 06:41:41 +0000257 CharUnits VPtrOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000258
John McCall9831b842018-02-06 18:52:44 +0000259 CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
260 Address This, llvm::Type *Ty,
261 SourceLocation Loc) override;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000262
David Majnemer0c0b6d92014-10-31 20:09:12 +0000263 llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
264 const CXXDestructorDecl *Dtor,
Marco Antognini88559632019-07-22 09:39:13 +0000265 CXXDtorType DtorType, Address This,
266 DeleteOrMemberCallExpr E) override;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000267
Craig Topper4f12f102014-03-12 06:41:41 +0000268 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
Reid Kleckner7810af02013-06-19 15:20:38 +0000269
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000270 bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const override;
Richard Smithc195c252018-11-27 19:33:49 +0000271 bool canSpeculativelyEmitVTableAsBaseClass(const CXXRecordDecl *RD) const;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000272
Hans Wennborgc94391d2014-06-06 20:04:01 +0000273 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
274 bool ReturnAdjustment) override {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000275 // Allow inlining of thunks by emitting them with available_externally
276 // linkage together with vtables when needed.
Peter Collingbourne8fabc1b2015-07-01 02:10:26 +0000277 if (ForVTable && !Thunk->hasLocalLinkage())
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000278 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
Rafael Espindolab7350042018-03-01 00:35:47 +0000279 CGM.setGVProperties(Thunk, GD);
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000280 }
281
Rafael Espindolab7350042018-03-01 00:35:47 +0000282 bool exportThunk() override { return true; }
283
John McCall7f416cc2015-09-08 08:05:57 +0000284 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This,
Craig Topper4f12f102014-03-12 06:41:41 +0000285 const ThisAdjustment &TA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000286
John McCall7f416cc2015-09-08 08:05:57 +0000287 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
Craig Topper4f12f102014-03-12 06:41:41 +0000288 const ReturnAdjustment &RA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000289
David Majnemer196ac332014-09-11 23:05:02 +0000290 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
291 FunctionArgList &Args) const override {
292 assert(!Args.empty() && "expected the arglist to not be empty!");
293 return Args.size() - 1;
294 }
295
Craig Topper4f12f102014-03-12 06:41:41 +0000296 StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
297 StringRef GetDeletedVirtualCallName() override
298 { return "__cxa_deleted_virtual"; }
Joao Matos2ce88ef2012-07-17 17:10:11 +0000299
Craig Topper4f12f102014-03-12 06:41:41 +0000300 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall7f416cc2015-09-08 08:05:57 +0000301 Address InitializeArrayCookie(CodeGenFunction &CGF,
302 Address NewPtr,
303 llvm::Value *NumElements,
304 const CXXNewExpr *expr,
305 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000306 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000307 Address allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000308 CharUnits cookieSize) override;
John McCall68ff0372010-09-08 01:44:27 +0000309
John McCallcdf7ef52010-11-06 09:44:32 +0000310 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000311 llvm::GlobalVariable *DeclPtr,
312 bool PerformInit) override;
Richard Smithdbf74ba2013-04-14 23:01:42 +0000313 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
James Y Knightf7321542019-02-07 01:14:17 +0000314 llvm::FunctionCallee dtor,
315 llvm::Constant *addr) override;
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000316
317 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +0000318 llvm::Value *Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000319 void EmitThreadLocalInitFuncs(
David Majnemerb3341ea2014-10-05 05:05:40 +0000320 CodeGenModule &CGM,
Richard Smith5a99c492015-12-01 01:10:48 +0000321 ArrayRef<const VarDecl *> CXXThreadLocals,
David Majnemerb3341ea2014-10-05 05:05:40 +0000322 ArrayRef<llvm::Function *> CXXThreadLocalInits,
Richard Smith5a99c492015-12-01 01:10:48 +0000323 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) override;
David Majnemerb3341ea2014-10-05 05:05:40 +0000324
325 bool usesThreadWrapperFunction() const override { return true; }
Richard Smith0f383742014-03-26 22:48:22 +0000326 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
327 QualType LValType) override;
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000328
Craig Topper4f12f102014-03-12 06:41:41 +0000329 bool NeedsVTTParameter(GlobalDecl GD) override;
David Majnemere2cb8d12014-07-07 06:20:47 +0000330
331 /**************************** RTTI Uniqueness ******************************/
332
333protected:
334 /// Returns true if the ABI requires RTTI type_info objects to be unique
335 /// across a program.
336 virtual bool shouldRTTIBeUnique() const { return true; }
337
338public:
339 /// What sort of unique-RTTI behavior should we use?
340 enum RTTIUniquenessKind {
341 /// We are guaranteeing, or need to guarantee, that the RTTI string
342 /// is unique.
343 RUK_Unique,
344
345 /// We are not guaranteeing uniqueness for the RTTI string, so we
346 /// can demote to hidden visibility but must use string comparisons.
347 RUK_NonUniqueHidden,
348
349 /// We are not guaranteeing uniqueness for the RTTI string, so we
350 /// have to use string comparisons, but we also have to emit it with
351 /// non-hidden visibility.
352 RUK_NonUniqueVisible
353 };
354
355 /// Return the required visibility status for the given type and linkage in
356 /// the current ABI.
357 RTTIUniquenessKind
358 classifyRTTIUniqueness(QualType CanTy,
359 llvm::GlobalValue::LinkageTypes Linkage) const;
360 friend class ItaniumRTTIBuilder;
Rafael Espindola91f68b42014-09-15 19:20:10 +0000361
Peter Collingbourned1c5b282019-03-22 23:05:10 +0000362 void emitCXXStructor(GlobalDecl GD) override;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000363
Peter Collingbourne60108802017-12-13 21:53:04 +0000364 std::pair<llvm::Value *, const CXXRecordDecl *>
365 LoadVTablePtr(CodeGenFunction &CGF, Address This,
366 const CXXRecordDecl *RD) override;
367
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000368 private:
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000369 bool hasAnyUnusedVirtualInlineFunction(const CXXRecordDecl *RD) const {
370 const auto &VtableLayout =
371 CGM.getItaniumVTableContext().getVTableLayout(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000372
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000373 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
374 // Skip empty slot.
375 if (!VtableComponent.isUsedFunctionPointerKind())
376 continue;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000377
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000378 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
379 if (!Method->getCanonicalDecl()->isInlined())
380 continue;
381
382 StringRef Name = CGM.getMangledName(VtableComponent.getGlobalDecl());
383 auto *Entry = CGM.GetGlobalValue(Name);
384 // This checks if virtual inline function has already been emitted.
385 // Note that it is possible that this inline function would be emitted
386 // after trying to emit vtable speculatively. Because of this we do
387 // an extra pass after emitting all deferred vtables to find and emit
388 // these vtables opportunistically.
389 if (!Entry || Entry->isDeclaration())
390 return true;
391 }
392 return false;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000393 }
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000394
395 bool isVTableHidden(const CXXRecordDecl *RD) const {
396 const auto &VtableLayout =
397 CGM.getItaniumVTableContext().getVTableLayout(RD);
398
399 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
400 if (VtableComponent.isRTTIKind()) {
401 const CXXRecordDecl *RTTIDecl = VtableComponent.getRTTIDecl();
402 if (RTTIDecl->getVisibility() == Visibility::HiddenVisibility)
403 return true;
404 } else if (VtableComponent.isUsedFunctionPointerKind()) {
405 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
406 if (Method->getVisibility() == Visibility::HiddenVisibility &&
407 !Method->isDefined())
408 return true;
409 }
410 }
411 return false;
412 }
Charles Davis4e786dd2010-05-25 19:52:27 +0000413};
John McCall86353412010-08-21 22:46:04 +0000414
415class ARMCXXABI : public ItaniumCXXABI {
416public:
Mark Seabornedf0d382013-07-24 16:25:13 +0000417 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
Sam Clegga5ee6392019-07-19 00:30:23 +0000418 ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
419 /*UseARMGuardVarABI=*/true) {}
John McCall5d865c322010-08-31 07:33:07 +0000420
Craig Topper4f12f102014-03-12 06:41:41 +0000421 bool HasThisReturn(GlobalDecl GD) const override {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000422 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
423 isa<CXXDestructorDecl>(GD.getDecl()) &&
424 GD.getDtorType() != Dtor_Deleting));
425 }
John McCall5d865c322010-08-31 07:33:07 +0000426
Craig Topper4f12f102014-03-12 06:41:41 +0000427 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
428 QualType ResTy) override;
John McCall5d865c322010-08-31 07:33:07 +0000429
Craig Topper4f12f102014-03-12 06:41:41 +0000430 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall7f416cc2015-09-08 08:05:57 +0000431 Address InitializeArrayCookie(CodeGenFunction &CGF,
432 Address NewPtr,
433 llvm::Value *NumElements,
434 const CXXNewExpr *expr,
435 QualType ElementType) override;
436 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, Address allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000437 CharUnits cookieSize) override;
John McCall86353412010-08-21 22:46:04 +0000438};
Tim Northovera2ee4332014-03-29 15:09:45 +0000439
440class iOS64CXXABI : public ARMCXXABI {
441public:
John McCalld23b27e2016-09-16 02:40:45 +0000442 iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {
443 Use32BitVTableOffsetABI = true;
444 }
Tim Northover65f582f2014-03-30 17:32:48 +0000445
446 // ARM64 libraries are prepared for non-unique RTTI.
David Majnemere2cb8d12014-07-07 06:20:47 +0000447 bool shouldRTTIBeUnique() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +0000448};
Dan Gohmanc2853072015-09-03 22:51:53 +0000449
450class WebAssemblyCXXABI final : public ItaniumCXXABI {
451public:
452 explicit WebAssemblyCXXABI(CodeGen::CodeGenModule &CGM)
453 : ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
454 /*UseARMGuardVarABI=*/true) {}
Heejin Ahnc6479192018-05-31 22:18:13 +0000455 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
Dan Gohmanc2853072015-09-03 22:51:53 +0000456
457private:
458 bool HasThisReturn(GlobalDecl GD) const override {
459 return isa<CXXConstructorDecl>(GD.getDecl()) ||
460 (isa<CXXDestructorDecl>(GD.getDecl()) &&
461 GD.getDtorType() != Dtor_Deleting);
462 }
Derek Schuff8179be42016-05-10 17:44:55 +0000463 bool canCallMismatchedFunctionType() const override { return false; }
Dan Gohmanc2853072015-09-03 22:51:53 +0000464};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000465}
Charles Davis4e786dd2010-05-25 19:52:27 +0000466
Charles Davis53c59df2010-08-16 03:33:14 +0000467CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000468 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000469 // For IR-generation purposes, there's no significant difference
470 // between the ARM and iOS ABIs.
471 case TargetCXXABI::GenericARM:
472 case TargetCXXABI::iOS:
Tim Northover756447a2015-10-30 16:30:36 +0000473 case TargetCXXABI::WatchOS:
John McCall57625922013-01-25 23:36:14 +0000474 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000475
Tim Northovera2ee4332014-03-29 15:09:45 +0000476 case TargetCXXABI::iOS64:
477 return new iOS64CXXABI(CGM);
478
Tim Northover9bb857a2013-01-31 12:13:10 +0000479 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
480 // include the other 32-bit ARM oddities: constructor/destructor return values
481 // and array cookies.
482 case TargetCXXABI::GenericAArch64:
Sam Clegga5ee6392019-07-19 00:30:23 +0000483 return new ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
484 /*UseARMGuardVarABI=*/true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000485
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000486 case TargetCXXABI::GenericMIPS:
Sam Clegga5ee6392019-07-19 00:30:23 +0000487 return new ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true);
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000488
Dan Gohmanc2853072015-09-03 22:51:53 +0000489 case TargetCXXABI::WebAssembly:
490 return new WebAssemblyCXXABI(CGM);
491
John McCall57625922013-01-25 23:36:14 +0000492 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000493 if (CGM.getContext().getTargetInfo().getTriple().getArch()
494 == llvm::Triple::le32) {
495 // For PNaCl, use ARM-style method pointers so that PNaCl code
496 // does not assume anything about the alignment of function
497 // pointers.
Sam Clegga5ee6392019-07-19 00:30:23 +0000498 return new ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true);
Mark Seabornedf0d382013-07-24 16:25:13 +0000499 }
John McCall57625922013-01-25 23:36:14 +0000500 return new ItaniumCXXABI(CGM);
501
502 case TargetCXXABI::Microsoft:
503 llvm_unreachable("Microsoft ABI is not Itanium-based");
504 }
505 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000506}
507
Chris Lattnera5f58b02011-07-09 17:41:47 +0000508llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000509ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
510 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000511 return CGM.PtrDiffTy;
Serge Guelton1d993272017-05-09 19:31:30 +0000512 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy);
John McCall1c456c82010-08-22 06:43:33 +0000513}
514
John McCalld9c6c0b2010-08-22 00:59:17 +0000515/// In the Itanium and ARM ABIs, method pointers have the form:
516/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
517///
518/// In the Itanium ABI:
519/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
520/// - the this-adjustment is (memptr.adj)
521/// - the virtual offset is (memptr.ptr - 1)
522///
523/// In the ARM ABI:
524/// - method pointers are virtual if (memptr.adj & 1) is nonzero
525/// - the this-adjustment is (memptr.adj >> 1)
526/// - the virtual offset is (memptr.ptr)
527/// ARM uses 'adj' for the virtual flag because Thumb functions
528/// may be only single-byte aligned.
529///
530/// If the member is virtual, the adjusted 'this' pointer points
531/// to a vtable pointer from which the virtual offset is applied.
532///
533/// If the member is non-virtual, memptr.ptr is the address of
534/// the function to call.
John McCallb92ab1a2016-10-26 23:46:34 +0000535CGCallee ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
John McCall7f416cc2015-09-08 08:05:57 +0000536 CodeGenFunction &CGF, const Expr *E, Address ThisAddr,
537 llvm::Value *&ThisPtrForCall,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000538 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
John McCall475999d2010-08-22 00:05:51 +0000539 CGBuilderTy &Builder = CGF.Builder;
540
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000541 const FunctionProtoType *FPT =
John McCall475999d2010-08-22 00:05:51 +0000542 MPT->getPointeeType()->getAs<FunctionProtoType>();
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000543 const CXXRecordDecl *RD =
John McCall475999d2010-08-22 00:05:51 +0000544 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
545
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000546 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(
547 CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr));
John McCall475999d2010-08-22 00:05:51 +0000548
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000549 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000550
John McCalld9c6c0b2010-08-22 00:59:17 +0000551 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
552 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
553 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
554
John McCalla1dee5302010-08-22 10:59:02 +0000555 // Extract memptr.adj, which is in the second field.
556 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000557
558 // Compute the true adjustment.
559 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000560 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000561 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000562
563 // Apply the adjustment and cast back to the original struct type
564 // for consistency.
John McCall7f416cc2015-09-08 08:05:57 +0000565 llvm::Value *This = ThisAddr.getPointer();
John McCalld9c6c0b2010-08-22 00:59:17 +0000566 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
567 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
568 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall7f416cc2015-09-08 08:05:57 +0000569 ThisPtrForCall = This;
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000570
John McCall475999d2010-08-22 00:05:51 +0000571 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000572 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000573
John McCall475999d2010-08-22 00:05:51 +0000574 // If the LSB in the function pointer is 1, the function pointer points to
575 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000576 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000577 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000578 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
579 else
580 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
581 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000582 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
583
584 // In the virtual path, the adjustment left 'This' pointing to the
585 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000586 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000587 CGF.EmitBlock(FnVirtual);
588
589 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000590 llvm::Type *VTableTy = Builder.getInt8PtrTy();
John McCall7f416cc2015-09-08 08:05:57 +0000591 CharUnits VTablePtrAlign =
592 CGF.CGM.getDynamicOffsetAlignment(ThisAddr.getAlignment(), RD,
593 CGF.getPointerAlign());
594 llvm::Value *VTable =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000595 CGF.GetVTablePtr(Address(This, VTablePtrAlign), VTableTy, RD);
John McCall475999d2010-08-22 00:05:51 +0000596
597 // Apply the offset.
John McCalld23b27e2016-09-16 02:40:45 +0000598 // On ARM64, to reserve extra space in virtual member function pointers,
599 // we only pay attention to the low 32 bits of the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000600 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000601 if (!UseARMMethodPtrABI)
602 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld23b27e2016-09-16 02:40:45 +0000603 if (Use32BitVTableOffsetABI) {
604 VTableOffset = Builder.CreateTrunc(VTableOffset, CGF.Int32Ty);
605 VTableOffset = Builder.CreateZExt(VTableOffset, CGM.PtrDiffTy);
606 }
Peter Collingbournee44acad2018-06-26 02:15:47 +0000607 // Compute the address of the virtual function pointer.
608 llvm::Value *VFPAddr = Builder.CreateGEP(VTable, VTableOffset);
609
610 // Check the address of the function pointer if CFI on member function
611 // pointers is enabled.
612 llvm::Constant *CheckSourceLocation;
613 llvm::Constant *CheckTypeDesc;
614 bool ShouldEmitCFICheck = CGF.SanOpts.has(SanitizerKind::CFIMFCall) &&
615 CGM.HasHiddenLTOVisibility(RD);
616 if (ShouldEmitCFICheck) {
617 CodeGenFunction::SanitizerScope SanScope(&CGF);
618
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000619 CheckSourceLocation = CGF.EmitCheckSourceLocation(E->getBeginLoc());
Peter Collingbournee44acad2018-06-26 02:15:47 +0000620 CheckTypeDesc = CGF.EmitCheckTypeDescriptor(QualType(MPT, 0));
621 llvm::Constant *StaticData[] = {
622 llvm::ConstantInt::get(CGF.Int8Ty, CodeGenFunction::CFITCK_VMFCall),
623 CheckSourceLocation,
624 CheckTypeDesc,
625 };
626
627 llvm::Metadata *MD =
628 CGM.CreateMetadataIdentifierForVirtualMemPtrType(QualType(MPT, 0));
629 llvm::Value *TypeId = llvm::MetadataAsValue::get(CGF.getLLVMContext(), MD);
630
631 llvm::Value *TypeTest = Builder.CreateCall(
632 CGM.getIntrinsic(llvm::Intrinsic::type_test), {VFPAddr, TypeId});
633
634 if (CGM.getCodeGenOpts().SanitizeTrap.has(SanitizerKind::CFIMFCall)) {
635 CGF.EmitTrapCheck(TypeTest);
636 } else {
637 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
638 CGM.getLLVMContext(),
639 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
640 llvm::Value *ValidVtable = Builder.CreateCall(
641 CGM.getIntrinsic(llvm::Intrinsic::type_test), {VTable, AllVtables});
642 CGF.EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIMFCall),
643 SanitizerHandler::CFICheckFail, StaticData,
644 {VTable, ValidVtable});
645 }
646
647 FnVirtual = Builder.GetInsertBlock();
648 }
John McCall475999d2010-08-22 00:05:51 +0000649
650 // Load the virtual function to call.
Peter Collingbournee44acad2018-06-26 02:15:47 +0000651 VFPAddr = Builder.CreateBitCast(VFPAddr, FTy->getPointerTo()->getPointerTo());
652 llvm::Value *VirtualFn = Builder.CreateAlignedLoad(
653 VFPAddr, CGF.getPointerAlign(), "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000654 CGF.EmitBranch(FnEnd);
655
656 // In the non-virtual path, the function pointer is actually a
657 // function pointer.
658 CGF.EmitBlock(FnNonVirtual);
659 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000660 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000661
Peter Collingbournee44acad2018-06-26 02:15:47 +0000662 // Check the function pointer if CFI on member function pointers is enabled.
663 if (ShouldEmitCFICheck) {
664 CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
665 if (RD->hasDefinition()) {
666 CodeGenFunction::SanitizerScope SanScope(&CGF);
667
668 llvm::Constant *StaticData[] = {
669 llvm::ConstantInt::get(CGF.Int8Ty, CodeGenFunction::CFITCK_NVMFCall),
670 CheckSourceLocation,
671 CheckTypeDesc,
672 };
673
674 llvm::Value *Bit = Builder.getFalse();
675 llvm::Value *CastedNonVirtualFn =
676 Builder.CreateBitCast(NonVirtualFn, CGF.Int8PtrTy);
677 for (const CXXRecordDecl *Base : CGM.getMostBaseClasses(RD)) {
678 llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(
679 getContext().getMemberPointerType(
680 MPT->getPointeeType(),
681 getContext().getRecordType(Base).getTypePtr()));
682 llvm::Value *TypeId =
683 llvm::MetadataAsValue::get(CGF.getLLVMContext(), MD);
684
685 llvm::Value *TypeTest =
686 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
687 {CastedNonVirtualFn, TypeId});
688 Bit = Builder.CreateOr(Bit, TypeTest);
689 }
690
691 CGF.EmitCheck(std::make_pair(Bit, SanitizerKind::CFIMFCall),
692 SanitizerHandler::CFICheckFail, StaticData,
693 {CastedNonVirtualFn, llvm::UndefValue::get(CGF.IntPtrTy)});
694
695 FnNonVirtual = Builder.GetInsertBlock();
696 }
697 }
698
John McCall475999d2010-08-22 00:05:51 +0000699 // We're done.
700 CGF.EmitBlock(FnEnd);
John McCallb92ab1a2016-10-26 23:46:34 +0000701 llvm::PHINode *CalleePtr = Builder.CreatePHI(FTy->getPointerTo(), 2);
702 CalleePtr->addIncoming(VirtualFn, FnVirtual);
703 CalleePtr->addIncoming(NonVirtualFn, FnNonVirtual);
704
705 CGCallee Callee(FPT, CalleePtr);
John McCall475999d2010-08-22 00:05:51 +0000706 return Callee;
707}
John McCalla8bbb822010-08-22 03:04:22 +0000708
John McCallc134eb52010-08-31 21:07:20 +0000709/// Compute an l-value by applying the given pointer-to-member to a
710/// base object.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000711llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
John McCall7f416cc2015-09-08 08:05:57 +0000712 CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000713 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000714 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000715
716 CGBuilderTy &Builder = CGF.Builder;
717
John McCallc134eb52010-08-31 21:07:20 +0000718 // Cast to char*.
John McCall7f416cc2015-09-08 08:05:57 +0000719 Base = Builder.CreateElementBitCast(Base, CGF.Int8Ty);
John McCallc134eb52010-08-31 21:07:20 +0000720
721 // Apply the offset, which we assume is non-null.
John McCall7f416cc2015-09-08 08:05:57 +0000722 llvm::Value *Addr =
723 Builder.CreateInBoundsGEP(Base.getPointer(), MemPtr, "memptr.offset");
John McCallc134eb52010-08-31 21:07:20 +0000724
725 // Cast the address to the appropriate pointer type, adopting the
726 // address space of the base pointer.
John McCall7f416cc2015-09-08 08:05:57 +0000727 llvm::Type *PType = CGF.ConvertTypeForMem(MPT->getPointeeType())
728 ->getPointerTo(Base.getAddressSpace());
John McCallc134eb52010-08-31 21:07:20 +0000729 return Builder.CreateBitCast(Addr, PType);
730}
731
John McCallc62bb392012-02-15 01:22:51 +0000732/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
733/// conversion.
734///
735/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000736///
737/// Obligatory offset/adjustment diagram:
738/// <-- offset --> <-- adjustment -->
739/// |--------------------------|----------------------|--------------------|
740/// ^Derived address point ^Base address point ^Member address point
741///
742/// So when converting a base member pointer to a derived member pointer,
743/// we add the offset to the adjustment because the address point has
744/// decreased; and conversely, when converting a derived MP to a base MP
745/// we subtract the offset from the adjustment because the address point
746/// has increased.
747///
748/// The standard forbids (at compile time) conversion to and from
749/// virtual bases, which is why we don't have to consider them here.
750///
751/// The standard forbids (at run time) casting a derived MP to a base
752/// MP when the derived MP does not point to a member of the base.
753/// This is why -1 is a reasonable choice for null data member
754/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000755llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000756ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
757 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000758 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000759 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000760 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
761 E->getCastKind() == CK_ReinterpretMemberPointer);
762
763 // Under Itanium, reinterprets don't require any additional processing.
764 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
765
766 // Use constant emission if we can.
767 if (isa<llvm::Constant>(src))
768 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
769
770 llvm::Constant *adj = getMemberPointerAdjustment(E);
771 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000772
773 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000774 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000775
John McCallc62bb392012-02-15 01:22:51 +0000776 const MemberPointerType *destTy =
777 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000778
John McCall7a9aac22010-08-23 01:21:21 +0000779 // For member data pointers, this is just a matter of adding the
780 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000781 if (destTy->isMemberDataPointer()) {
782 llvm::Value *dst;
783 if (isDerivedToBase)
784 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000785 else
John McCallc62bb392012-02-15 01:22:51 +0000786 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000787
788 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000789 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
790 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
791 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000792 }
793
John McCalla1dee5302010-08-22 10:59:02 +0000794 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000795 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000796 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
797 offset <<= 1;
798 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000799 }
800
John McCallc62bb392012-02-15 01:22:51 +0000801 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
802 llvm::Value *dstAdj;
803 if (isDerivedToBase)
804 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000805 else
John McCallc62bb392012-02-15 01:22:51 +0000806 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000807
John McCallc62bb392012-02-15 01:22:51 +0000808 return Builder.CreateInsertValue(src, dstAdj, 1);
809}
810
811llvm::Constant *
812ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
813 llvm::Constant *src) {
814 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
815 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
816 E->getCastKind() == CK_ReinterpretMemberPointer);
817
818 // Under Itanium, reinterprets don't require any additional processing.
819 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
820
821 // If the adjustment is trivial, we don't need to do anything.
822 llvm::Constant *adj = getMemberPointerAdjustment(E);
823 if (!adj) return src;
824
825 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
826
827 const MemberPointerType *destTy =
828 E->getType()->castAs<MemberPointerType>();
829
830 // For member data pointers, this is just a matter of adding the
831 // offset if the source is non-null.
832 if (destTy->isMemberDataPointer()) {
833 // null maps to null.
834 if (src->isAllOnesValue()) return src;
835
836 if (isDerivedToBase)
837 return llvm::ConstantExpr::getNSWSub(src, adj);
838 else
839 return llvm::ConstantExpr::getNSWAdd(src, adj);
840 }
841
842 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000843 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000844 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
845 offset <<= 1;
846 adj = llvm::ConstantInt::get(adj->getType(), offset);
847 }
848
849 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
850 llvm::Constant *dstAdj;
851 if (isDerivedToBase)
852 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
853 else
854 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
855
856 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000857}
John McCall84fa5102010-08-22 04:16:24 +0000858
859llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000860ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000861 // Itanium C++ ABI 2.3:
862 // A NULL pointer is represented as -1.
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000863 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000864 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000865
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000866 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000867 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000868 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000869}
870
John McCallf3a88602011-02-03 08:15:49 +0000871llvm::Constant *
872ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
873 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000874 // Itanium C++ ABI 2.3:
875 // A pointer to data member is an offset from the base address of
876 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000877 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000878}
879
David Majnemere2be95b2015-06-23 07:31:01 +0000880llvm::Constant *
881ItaniumCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000882 return BuildMemberPointer(MD, CharUnits::Zero());
883}
884
885llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
886 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000887 assert(MD->isInstance() && "Member function must not be static!");
John McCalla1dee5302010-08-22 10:59:02 +0000888
889 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000890
891 // Get the function pointer (or index if this is a virtual function).
892 llvm::Constant *MemPtr[2];
893 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000894 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000895
Ken Dyckdf016282011-04-09 01:30:02 +0000896 const ASTContext &Context = getContext();
897 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000898 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000899 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000900
Mark Seabornedf0d382013-07-24 16:25:13 +0000901 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000902 // ARM C++ ABI 3.2.1:
903 // This ABI specifies that adj contains twice the this
904 // adjustment, plus 1 if the member function is virtual. The
905 // least significant bit of adj then makes exactly the same
906 // discrimination as the least significant bit of ptr does for
907 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000908 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
909 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000910 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000911 } else {
912 // Itanium C++ ABI 2.3:
913 // For a virtual function, [the pointer field] is 1 plus the
914 // virtual table offset (in bytes) of the function,
915 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000916 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
917 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000918 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000919 }
920 } else {
John McCall2979fe02011-04-12 00:42:48 +0000921 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000922 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000923 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000924 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000925 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000926 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000927 } else {
John McCall2979fe02011-04-12 00:42:48 +0000928 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
929 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000930 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000931 }
John McCall2979fe02011-04-12 00:42:48 +0000932 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000933
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000934 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000935 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
936 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000937 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000938 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000939
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000940 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000941}
942
Richard Smithdafff942012-01-14 04:30:29 +0000943llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
944 QualType MPType) {
945 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
946 const ValueDecl *MPD = MP.getMemberPointerDecl();
947 if (!MPD)
948 return EmitNullMemberPointer(MPT);
949
Reid Kleckner452abac2013-05-09 21:01:17 +0000950 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000951
952 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
953 return BuildMemberPointer(MD, ThisAdjustment);
954
955 CharUnits FieldOffset =
956 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
957 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
958}
959
John McCall131d97d2010-08-22 08:30:07 +0000960/// The comparison algorithm is pretty easy: the member pointers are
961/// the same if they're either bitwise identical *or* both null.
962///
963/// ARM is different here only because null-ness is more complicated.
964llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000965ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
966 llvm::Value *L,
967 llvm::Value *R,
968 const MemberPointerType *MPT,
969 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000970 CGBuilderTy &Builder = CGF.Builder;
971
John McCall131d97d2010-08-22 08:30:07 +0000972 llvm::ICmpInst::Predicate Eq;
973 llvm::Instruction::BinaryOps And, Or;
974 if (Inequality) {
975 Eq = llvm::ICmpInst::ICMP_NE;
976 And = llvm::Instruction::Or;
977 Or = llvm::Instruction::And;
978 } else {
979 Eq = llvm::ICmpInst::ICMP_EQ;
980 And = llvm::Instruction::And;
981 Or = llvm::Instruction::Or;
982 }
983
John McCall7a9aac22010-08-23 01:21:21 +0000984 // Member data pointers are easy because there's a unique null
985 // value, so it just comes down to bitwise equality.
986 if (MPT->isMemberDataPointer())
987 return Builder.CreateICmp(Eq, L, R);
988
989 // For member function pointers, the tautologies are more complex.
990 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000991 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000992 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000993 // (L == R) <==> (L.ptr == R.ptr &&
994 // (L.adj == R.adj ||
995 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000996 // The inequality tautologies have exactly the same structure, except
997 // applying De Morgan's laws.
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000998
John McCall7a9aac22010-08-23 01:21:21 +0000999 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
1000 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
1001
John McCall131d97d2010-08-22 08:30:07 +00001002 // This condition tests whether L.ptr == R.ptr. This must always be
1003 // true for equality to hold.
1004 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
1005
1006 // This condition, together with the assumption that L.ptr == R.ptr,
1007 // tests whether the pointers are both null. ARM imposes an extra
1008 // condition.
1009 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
1010 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
1011
1012 // This condition tests whether L.adj == R.adj. If this isn't
1013 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +00001014 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
1015 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +00001016 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
1017
1018 // Null member function pointers on ARM clear the low bit of Adj,
1019 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +00001020 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +00001021 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
1022
1023 // Compute (l.adj | r.adj) & 1 and test it against zero.
1024 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
1025 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
1026 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
1027 "cmp.or.adj");
1028 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
1029 }
1030
1031 // Tie together all our conditions.
1032 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
1033 Result = Builder.CreateBinOp(And, PtrEq, Result,
1034 Inequality ? "memptr.ne" : "memptr.eq");
1035 return Result;
1036}
1037
1038llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +00001039ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
1040 llvm::Value *MemPtr,
1041 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +00001042 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +00001043
1044 /// For member data pointers, this is just a check against -1.
1045 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +00001046 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +00001047 llvm::Value *NegativeOne =
1048 llvm::Constant::getAllOnesValue(MemPtr->getType());
1049 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
1050 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00001051
Daniel Dunbar914bc412011-04-19 23:10:47 +00001052 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +00001053 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +00001054
1055 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
1056 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
1057
Daniel Dunbar914bc412011-04-19 23:10:47 +00001058 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
1059 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +00001060 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +00001061 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +00001062 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +00001063 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +00001064 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
1065 "memptr.isvirtual");
1066 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +00001067 }
1068
1069 return Result;
1070}
John McCall1c456c82010-08-22 06:43:33 +00001071
Reid Kleckner40ca9132014-05-13 22:05:45 +00001072bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
1073 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
1074 if (!RD)
1075 return false;
1076
Richard Smith96cd6712017-08-16 01:49:53 +00001077 // If C++ prohibits us from making a copy, return by address.
Reid Kleckneradb41982019-04-30 22:23:20 +00001078 if (!RD->canPassInRegisters()) {
John McCall7f416cc2015-09-08 08:05:57 +00001079 auto Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
1080 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
Reid Kleckner40ca9132014-05-13 22:05:45 +00001081 return true;
1082 }
Reid Kleckner40ca9132014-05-13 22:05:45 +00001083 return false;
1084}
1085
John McCall614dbdc2010-08-22 21:01:12 +00001086/// The Itanium ABI requires non-zero initialization only for data
1087/// member pointers, for which '0' is a valid offset.
1088bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
David Majnemer5fd33e02015-04-24 01:25:08 +00001089 return MPT->isMemberFunctionPointer();
John McCall84fa5102010-08-22 04:16:24 +00001090}
John McCall5d865c322010-08-31 07:33:07 +00001091
John McCall82fb8922012-09-25 10:10:39 +00001092/// The Itanium ABI always places an offset to the complete object
1093/// at entry -2 in the vtable.
David Majnemer08681372014-11-01 07:37:17 +00001094void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
1095 const CXXDeleteExpr *DE,
John McCall7f416cc2015-09-08 08:05:57 +00001096 Address Ptr,
David Majnemer08681372014-11-01 07:37:17 +00001097 QualType ElementType,
1098 const CXXDestructorDecl *Dtor) {
1099 bool UseGlobalDelete = DE->isGlobalDelete();
David Majnemer0c0b6d92014-10-31 20:09:12 +00001100 if (UseGlobalDelete) {
1101 // Derive the complete-object pointer, which is what we need
1102 // to pass to the deallocation function.
John McCall82fb8922012-09-25 10:10:39 +00001103
David Majnemer0c0b6d92014-10-31 20:09:12 +00001104 // Grab the vtable pointer as an intptr_t*.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001105 auto *ClassDecl =
1106 cast<CXXRecordDecl>(ElementType->getAs<RecordType>()->getDecl());
1107 llvm::Value *VTable =
1108 CGF.GetVTablePtr(Ptr, CGF.IntPtrTy->getPointerTo(), ClassDecl);
John McCall82fb8922012-09-25 10:10:39 +00001109
David Majnemer0c0b6d92014-10-31 20:09:12 +00001110 // Track back to entry -2 and pull out the offset there.
1111 llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
1112 VTable, -2, "complete-offset.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001113 llvm::Value *Offset =
1114 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
David Majnemer0c0b6d92014-10-31 20:09:12 +00001115
1116 // Apply the offset.
John McCall7f416cc2015-09-08 08:05:57 +00001117 llvm::Value *CompletePtr =
1118 CGF.Builder.CreateBitCast(Ptr.getPointer(), CGF.Int8PtrTy);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001119 CompletePtr = CGF.Builder.CreateInBoundsGEP(CompletePtr, Offset);
1120
1121 // If we're supposed to call the global delete, make sure we do so
1122 // even if the destructor throws.
David Majnemer08681372014-11-01 07:37:17 +00001123 CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr,
1124 ElementType);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001125 }
1126
1127 // FIXME: Provide a source location here even though there's no
1128 // CXXMemberCallExpr for dtor call.
1129 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
Marco Antognini88559632019-07-22 09:39:13 +00001130 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, DE);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001131
1132 if (UseGlobalDelete)
1133 CGF.PopCleanupBlock();
John McCall82fb8922012-09-25 10:10:39 +00001134}
1135
David Majnemer442d0a22014-11-25 07:20:20 +00001136void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
1137 // void __cxa_rethrow();
1138
1139 llvm::FunctionType *FTy =
Rui Ueyama49a3ad22019-07-16 04:46:31 +00001140 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
David Majnemer442d0a22014-11-25 07:20:20 +00001141
James Y Knight9871db02019-02-05 16:42:33 +00001142 llvm::FunctionCallee Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
David Majnemer442d0a22014-11-25 07:20:20 +00001143
1144 if (isNoReturn)
1145 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, None);
1146 else
1147 CGF.EmitRuntimeCallOrInvoke(Fn);
1148}
1149
James Y Knight9871db02019-02-05 16:42:33 +00001150static llvm::FunctionCallee getAllocateExceptionFn(CodeGenModule &CGM) {
David Majnemer7c237072015-03-05 00:46:22 +00001151 // void *__cxa_allocate_exception(size_t thrown_size);
1152
1153 llvm::FunctionType *FTy =
Rui Ueyama49a3ad22019-07-16 04:46:31 +00001154 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*isVarArg=*/false);
David Majnemer7c237072015-03-05 00:46:22 +00001155
1156 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
1157}
1158
James Y Knight9871db02019-02-05 16:42:33 +00001159static llvm::FunctionCallee getThrowFn(CodeGenModule &CGM) {
David Majnemer7c237072015-03-05 00:46:22 +00001160 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
1161 // void (*dest) (void *));
1162
1163 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
1164 llvm::FunctionType *FTy =
Rui Ueyama49a3ad22019-07-16 04:46:31 +00001165 llvm::FunctionType::get(CGM.VoidTy, Args, /*isVarArg=*/false);
David Majnemer7c237072015-03-05 00:46:22 +00001166
1167 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
1168}
1169
1170void ItaniumCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
1171 QualType ThrowType = E->getSubExpr()->getType();
1172 // Now allocate the exception object.
1173 llvm::Type *SizeTy = CGF.ConvertType(getContext().getSizeType());
1174 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
1175
James Y Knight9871db02019-02-05 16:42:33 +00001176 llvm::FunctionCallee AllocExceptionFn = getAllocateExceptionFn(CGM);
David Majnemer7c237072015-03-05 00:46:22 +00001177 llvm::CallInst *ExceptionPtr = CGF.EmitNounwindRuntimeCall(
1178 AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception");
1179
Akira Hatanakac39a2432019-05-10 02:16:37 +00001180 CharUnits ExnAlign = CGF.getContext().getExnObjectAlignment();
John McCall7f416cc2015-09-08 08:05:57 +00001181 CGF.EmitAnyExprToExn(E->getSubExpr(), Address(ExceptionPtr, ExnAlign));
David Majnemer7c237072015-03-05 00:46:22 +00001182
1183 // Now throw the exception.
1184 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
1185 /*ForEH=*/true);
1186
1187 // The address of the destructor. If the exception type has a
1188 // trivial destructor (or isn't a record), we just pass null.
1189 llvm::Constant *Dtor = nullptr;
1190 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
1191 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
1192 if (!Record->hasTrivialDestructor()) {
1193 CXXDestructorDecl *DtorD = Record->getDestructor();
Peter Collingbourned1c5b282019-03-22 23:05:10 +00001194 Dtor = CGM.getAddrOfCXXStructor(GlobalDecl(DtorD, Dtor_Complete));
David Majnemer7c237072015-03-05 00:46:22 +00001195 Dtor = llvm::ConstantExpr::getBitCast(Dtor, CGM.Int8PtrTy);
1196 }
1197 }
1198 if (!Dtor) Dtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
1199
1200 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
1201 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
1202}
1203
James Y Knight9871db02019-02-05 16:42:33 +00001204static llvm::FunctionCallee getItaniumDynamicCastFn(CodeGenFunction &CGF) {
David Majnemer1162d252014-06-22 19:05:33 +00001205 // void *__dynamic_cast(const void *sub,
1206 // const abi::__class_type_info *src,
1207 // const abi::__class_type_info *dst,
1208 // std::ptrdiff_t src2dst_offset);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00001209
David Majnemer1162d252014-06-22 19:05:33 +00001210 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
Jake Ehrlichc451cf22017-11-11 01:15:41 +00001211 llvm::Type *PtrDiffTy =
David Majnemer1162d252014-06-22 19:05:33 +00001212 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1213
1214 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
1215
1216 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
1217
1218 // Mark the function as nounwind readonly.
1219 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
1220 llvm::Attribute::ReadOnly };
Reid Klecknerde864822017-03-21 16:57:30 +00001221 llvm::AttributeList Attrs = llvm::AttributeList::get(
1222 CGF.getLLVMContext(), llvm::AttributeList::FunctionIndex, FuncAttrs);
David Majnemer1162d252014-06-22 19:05:33 +00001223
1224 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
1225}
1226
James Y Knight9871db02019-02-05 16:42:33 +00001227static llvm::FunctionCallee getBadCastFn(CodeGenFunction &CGF) {
David Majnemer1162d252014-06-22 19:05:33 +00001228 // void __cxa_bad_cast();
1229 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1230 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1231}
1232
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001233/// Compute the src2dst_offset hint as described in the
David Majnemer1162d252014-06-22 19:05:33 +00001234/// Itanium C++ ABI [2.9.7]
1235static CharUnits computeOffsetHint(ASTContext &Context,
1236 const CXXRecordDecl *Src,
1237 const CXXRecordDecl *Dst) {
1238 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1239 /*DetectVirtual=*/false);
1240
1241 // If Dst is not derived from Src we can skip the whole computation below and
1242 // return that Src is not a public base of Dst. Record all inheritance paths.
1243 if (!Dst->isDerivedFrom(Src, Paths))
1244 return CharUnits::fromQuantity(-2ULL);
1245
1246 unsigned NumPublicPaths = 0;
1247 CharUnits Offset;
1248
1249 // Now walk all possible inheritance paths.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001250 for (const CXXBasePath &Path : Paths) {
1251 if (Path.Access != AS_public) // Ignore non-public inheritance.
David Majnemer1162d252014-06-22 19:05:33 +00001252 continue;
1253
1254 ++NumPublicPaths;
1255
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001256 for (const CXXBasePathElement &PathElement : Path) {
David Majnemer1162d252014-06-22 19:05:33 +00001257 // If the path contains a virtual base class we can't give any hint.
1258 // -1: no hint.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001259 if (PathElement.Base->isVirtual())
David Majnemer1162d252014-06-22 19:05:33 +00001260 return CharUnits::fromQuantity(-1ULL);
1261
1262 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
1263 continue;
1264
1265 // Accumulate the base class offsets.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001266 const ASTRecordLayout &L = Context.getASTRecordLayout(PathElement.Class);
1267 Offset += L.getBaseClassOffset(
1268 PathElement.Base->getType()->getAsCXXRecordDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001269 }
1270 }
1271
1272 // -2: Src is not a public base of Dst.
1273 if (NumPublicPaths == 0)
1274 return CharUnits::fromQuantity(-2ULL);
1275
1276 // -3: Src is a multiple public base type but never a virtual base type.
1277 if (NumPublicPaths > 1)
1278 return CharUnits::fromQuantity(-3ULL);
1279
1280 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
1281 // Return the offset of Src from the origin of Dst.
1282 return Offset;
1283}
1284
James Y Knight9871db02019-02-05 16:42:33 +00001285static llvm::FunctionCallee getBadTypeidFn(CodeGenFunction &CGF) {
David Majnemer1162d252014-06-22 19:05:33 +00001286 // void __cxa_bad_typeid();
1287 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1288
1289 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1290}
1291
1292bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
1293 QualType SrcRecordTy) {
1294 return IsDeref;
1295}
1296
1297void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
James Y Knight9871db02019-02-05 16:42:33 +00001298 llvm::FunctionCallee Fn = getBadTypeidFn(CGF);
James Y Knight3933add2019-01-30 02:54:28 +00001299 llvm::CallBase *Call = CGF.EmitRuntimeCallOrInvoke(Fn);
1300 Call->setDoesNotReturn();
David Majnemer1162d252014-06-22 19:05:33 +00001301 CGF.Builder.CreateUnreachable();
1302}
1303
1304llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
1305 QualType SrcRecordTy,
John McCall7f416cc2015-09-08 08:05:57 +00001306 Address ThisPtr,
David Majnemer1162d252014-06-22 19:05:33 +00001307 llvm::Type *StdTypeInfoPtrTy) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001308 auto *ClassDecl =
1309 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001310 llvm::Value *Value =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001311 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo(), ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001312
1313 // Load the type info.
1314 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001315 return CGF.Builder.CreateAlignedLoad(Value, CGF.getPointerAlign());
David Majnemer1162d252014-06-22 19:05:33 +00001316}
1317
1318bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1319 QualType SrcRecordTy) {
1320 return SrcIsPtr;
1321}
1322
1323llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
John McCall7f416cc2015-09-08 08:05:57 +00001324 CodeGenFunction &CGF, Address ThisAddr, QualType SrcRecordTy,
David Majnemer1162d252014-06-22 19:05:33 +00001325 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1326 llvm::Type *PtrDiffLTy =
1327 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1328 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1329
1330 llvm::Value *SrcRTTI =
1331 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1332 llvm::Value *DestRTTI =
1333 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1334
1335 // Compute the offset hint.
1336 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1337 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1338 llvm::Value *OffsetHint = llvm::ConstantInt::get(
1339 PtrDiffLTy,
1340 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
1341
1342 // Emit the call to __dynamic_cast.
John McCall7f416cc2015-09-08 08:05:57 +00001343 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001344 Value = CGF.EmitCastToVoidPtr(Value);
1345
1346 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
1347 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
1348 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1349
1350 /// C++ [expr.dynamic.cast]p9:
1351 /// A failed cast to reference type throws std::bad_cast
1352 if (DestTy->isReferenceType()) {
1353 llvm::BasicBlock *BadCastBlock =
1354 CGF.createBasicBlock("dynamic_cast.bad_cast");
1355
1356 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1357 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1358
1359 CGF.EmitBlock(BadCastBlock);
1360 EmitBadCastCall(CGF);
1361 }
1362
1363 return Value;
1364}
1365
1366llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001367 Address ThisAddr,
David Majnemer1162d252014-06-22 19:05:33 +00001368 QualType SrcRecordTy,
1369 QualType DestTy) {
1370 llvm::Type *PtrDiffLTy =
1371 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1372 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1373
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001374 auto *ClassDecl =
1375 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001376 // Get the vtable pointer.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001377 llvm::Value *VTable = CGF.GetVTablePtr(ThisAddr, PtrDiffLTy->getPointerTo(),
1378 ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001379
1380 // Get the offset-to-top from the vtable.
1381 llvm::Value *OffsetToTop =
1382 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001383 OffsetToTop =
1384 CGF.Builder.CreateAlignedLoad(OffsetToTop, CGF.getPointerAlign(),
1385 "offset.to.top");
David Majnemer1162d252014-06-22 19:05:33 +00001386
1387 // Finally, add the offset to the pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001388 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001389 Value = CGF.EmitCastToVoidPtr(Value);
1390 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1391
1392 return CGF.Builder.CreateBitCast(Value, DestLTy);
1393}
1394
1395bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
James Y Knight9871db02019-02-05 16:42:33 +00001396 llvm::FunctionCallee Fn = getBadCastFn(CGF);
James Y Knight3933add2019-01-30 02:54:28 +00001397 llvm::CallBase *Call = CGF.EmitRuntimeCallOrInvoke(Fn);
1398 Call->setDoesNotReturn();
David Majnemer1162d252014-06-22 19:05:33 +00001399 CGF.Builder.CreateUnreachable();
1400 return true;
1401}
1402
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001403llvm::Value *
1404ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001405 Address This,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001406 const CXXRecordDecl *ClassDecl,
1407 const CXXRecordDecl *BaseClassDecl) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001408 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy, ClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001409 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001410 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1411 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001412
1413 llvm::Value *VBaseOffsetPtr =
1414 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1415 "vbase.offset.ptr");
1416 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1417 CGM.PtrDiffTy->getPointerTo());
1418
1419 llvm::Value *VBaseOffset =
John McCall7f416cc2015-09-08 08:05:57 +00001420 CGF.Builder.CreateAlignedLoad(VBaseOffsetPtr, CGF.getPointerAlign(),
1421 "vbase.offset");
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001422
1423 return VBaseOffset;
1424}
1425
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001426void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1427 // Just make sure we're in sync with TargetCXXABI.
1428 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1429
Rafael Espindolac3cde362013-12-09 14:51:17 +00001430 // The constructor used for constructing this as a base class;
1431 // ignores virtual bases.
1432 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1433
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001434 // The constructor used for constructing this as a complete class;
Nico Weber4c2ffb22015-01-07 05:25:05 +00001435 // constructs the virtual bases, then calls the base constructor.
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001436 if (!D->getParent()->isAbstract()) {
1437 // We don't need to emit the complete ctor if the class is abstract.
1438 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1439 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001440}
1441
George Burgess IVf203dbf2017-02-22 20:28:02 +00001442CGCXXABI::AddedStructorArgs
Peter Collingbourned1c5b282019-03-22 23:05:10 +00001443ItaniumCXXABI::buildStructorSignature(GlobalDecl GD,
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001444 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +00001445 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001446
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001447 // All parameters are already in place except VTT, which goes after 'this'.
1448 // These are Clang types, so we don't need to worry about sret yet.
John McCall5d865c322010-08-31 07:33:07 +00001449
1450 // Check if we need to add a VTT parameter (which has type void **).
Peter Collingbourned1c5b282019-03-22 23:05:10 +00001451 if ((isa<CXXConstructorDecl>(GD.getDecl()) ? GD.getCtorType() == Ctor_Base
1452 : GD.getDtorType() == Dtor_Base) &&
1453 cast<CXXMethodDecl>(GD.getDecl())->getParent()->getNumVBases() != 0) {
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001454 ArgTys.insert(ArgTys.begin() + 1,
1455 Context.getPointerType(Context.VoidPtrTy));
George Burgess IVf203dbf2017-02-22 20:28:02 +00001456 return AddedStructorArgs::prefix(1);
1457 }
1458 return AddedStructorArgs{};
John McCall5d865c322010-08-31 07:33:07 +00001459}
1460
Reid Klecknere7de47e2013-07-22 13:51:44 +00001461void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
Rafael Espindolac3cde362013-12-09 14:51:17 +00001462 // The destructor used for destructing this as a base class; ignores
1463 // virtual bases.
1464 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001465
1466 // The destructor used for destructing this as a most-derived class;
1467 // call the base destructor and then destructs any virtual bases.
1468 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1469
Rafael Espindolac3cde362013-12-09 14:51:17 +00001470 // The destructor in a virtual table is always a 'deleting'
1471 // destructor, which calls the complete destructor and then uses the
1472 // appropriate operator delete.
1473 if (D->isVirtual())
1474 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001475}
1476
Reid Kleckner89077a12013-12-17 19:46:40 +00001477void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1478 QualType &ResTy,
1479 FunctionArgList &Params) {
John McCall5d865c322010-08-31 07:33:07 +00001480 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +00001481 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
John McCall5d865c322010-08-31 07:33:07 +00001482
1483 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001484 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +00001485 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001486
1487 // FIXME: avoid the fake decl
1488 QualType T = Context.getPointerType(Context.VoidPtrTy);
Alexey Bataev56223232017-06-09 13:40:18 +00001489 auto *VTTDecl = ImplicitParamDecl::Create(
1490 Context, /*DC=*/nullptr, MD->getLocation(), &Context.Idents.get("vtt"),
1491 T, ImplicitParamDecl::CXXVTT);
Reid Kleckner89077a12013-12-17 19:46:40 +00001492 Params.insert(Params.begin() + 1, VTTDecl);
Reid Kleckner2af6d732013-12-13 00:09:59 +00001493 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +00001494 }
1495}
1496
John McCall5d865c322010-08-31 07:33:07 +00001497void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
Justin Lebared4f1722016-07-27 22:04:24 +00001498 // Naked functions have no prolog.
1499 if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>())
1500 return;
1501
Reid Kleckner06239e42017-11-16 19:09:36 +00001502 /// Initialize the 'this' slot. In the Itanium C++ ABI, no prologue
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001503 /// adjustments are required, because they are all handled by thunks.
Reid Kleckner06239e42017-11-16 19:09:36 +00001504 setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));
John McCall5d865c322010-08-31 07:33:07 +00001505
1506 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +00001507 if (getStructorImplicitParamDecl(CGF)) {
1508 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1509 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +00001510 }
John McCall5d865c322010-08-31 07:33:07 +00001511
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001512 /// If this is a function that the ABI specifies returns 'this', initialize
1513 /// the return slot to 'this' at the start of the function.
1514 ///
1515 /// Unlike the setting of return types, this is done within the ABI
1516 /// implementation instead of by clients of CGCXXABI because:
1517 /// 1) getThisValue is currently protected
1518 /// 2) in theory, an ABI could implement 'this' returns some other way;
1519 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +00001520 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +00001521 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +00001522}
1523
George Burgess IVf203dbf2017-02-22 20:28:02 +00001524CGCXXABI::AddedStructorArgs ItaniumCXXABI::addImplicitConstructorArgs(
Reid Kleckner89077a12013-12-17 19:46:40 +00001525 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1526 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1527 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
George Burgess IVf203dbf2017-02-22 20:28:02 +00001528 return AddedStructorArgs{};
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001529
Reid Kleckner89077a12013-12-17 19:46:40 +00001530 // Insert the implicit 'vtt' argument as the second argument.
1531 llvm::Value *VTT =
1532 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1533 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
Yaxun Liu5b330e82018-03-15 15:25:19 +00001534 Args.insert(Args.begin() + 1, CallArg(RValue::get(VTT), VTTTy));
George Burgess IVf203dbf2017-02-22 20:28:02 +00001535 return AddedStructorArgs::prefix(1); // Added one arg.
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001536}
1537
1538void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1539 const CXXDestructorDecl *DD,
1540 CXXDtorType Type, bool ForVirtualBase,
Marco Antognini88559632019-07-22 09:39:13 +00001541 bool Delegating, Address This,
1542 QualType ThisTy) {
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001543 GlobalDecl GD(DD, Type);
1544 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1545 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1546
John McCallb92ab1a2016-10-26 23:46:34 +00001547 CGCallee Callee;
1548 if (getContext().getLangOpts().AppleKext &&
1549 Type != Dtor_Base && DD->isVirtual())
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001550 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
John McCallb92ab1a2016-10-26 23:46:34 +00001551 else
Peter Collingbourned1c5b282019-03-22 23:05:10 +00001552 Callee = CGCallee::forDirect(CGM.getAddrOfCXXStructor(GD), GD);
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001553
Marco Antognini88559632019-07-22 09:39:13 +00001554 CGF.EmitCXXDestructorCall(GD, Callee, This.getPointer(), ThisTy, VTT, VTTTy,
1555 nullptr);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001556}
1557
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001558void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1559 const CXXRecordDecl *RD) {
1560 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1561 if (VTable->hasInitializer())
1562 return;
1563
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001564 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001565 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1566 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
David Majnemerd905da42014-07-01 20:30:31 +00001567 llvm::Constant *RTTI =
1568 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001569
1570 // Create and set the initializer.
John McCall9c6cb762016-11-28 22:18:33 +00001571 ConstantInitBuilder Builder(CGM);
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001572 auto Components = Builder.beginStruct();
John McCall9c6cb762016-11-28 22:18:33 +00001573 CGVT.createVTableInitializer(Components, VTLayout, RTTI);
1574 Components.finishAndSetAsInitializer(VTable);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001575
1576 // Set the correct linkage.
1577 VTable->setLinkage(Linkage);
1578
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001579 if (CGM.supportsCOMDAT() && VTable->isWeakForLinker())
1580 VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName()));
Rafael Espindolacb92c192015-01-15 23:18:01 +00001581
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001582 // Set the right visibility.
Rafael Espindola699f5d62018-02-07 22:15:33 +00001583 CGM.setGVProperties(VTable, RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001584
1585 // If this is the magic class __cxxabiv1::__fundamental_type_info,
1586 // we will emit the typeinfo for the fundamental types. This is the
1587 // same behaviour as GCC.
1588 const DeclContext *DC = RD->getDeclContext();
1589 if (RD->getIdentifier() &&
1590 RD->getIdentifier()->isStr("__fundamental_type_info") &&
1591 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1592 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1593 DC->getParent()->isTranslationUnit())
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00001594 EmitFundamentalRTTIDescriptors(RD);
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001595
Evgeniy Stepanov93987df2016-01-23 01:20:18 +00001596 if (!VTable->isDeclarationForLinker())
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001597 CGM.EmitVTableTypeMetadata(VTable, VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001598}
1599
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001600bool ItaniumCXXABI::isVirtualOffsetNeededForVTableField(
1601 CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
1602 if (Vptr.NearestVBase == nullptr)
1603 return false;
1604 return NeedsVTTParameter(CGF.CurGD);
Piotr Padlewski255652e2015-09-09 22:20:28 +00001605}
1606
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001607llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1608 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1609 const CXXRecordDecl *NearestVBase) {
1610
1611 if ((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1612 NeedsVTTParameter(CGF.CurGD)) {
1613 return getVTableAddressPointInStructorWithVTT(CGF, VTableClass, Base,
1614 NearestVBase);
1615 }
1616 return getVTableAddressPoint(Base, VTableClass);
1617}
1618
1619llvm::Constant *
1620ItaniumCXXABI::getVTableAddressPoint(BaseSubobject Base,
1621 const CXXRecordDecl *VTableClass) {
1622 llvm::GlobalValue *VTable = getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001623
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001624 // Find the appropriate vtable within the vtable group, and the address point
1625 // within that vtable.
1626 VTableLayout::AddressPointLocation AddressPoint =
1627 CGM.getItaniumVTableContext()
1628 .getVTableLayout(VTableClass)
1629 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001630 llvm::Value *Indices[] = {
Peter Collingbourne4e6a5402016-03-14 19:07:10 +00001631 llvm::ConstantInt::get(CGM.Int32Ty, 0),
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001632 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.VTableIndex),
1633 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.AddressPointIndex),
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001634 };
1635
Peter Collingbourne25a2b702016-12-13 20:50:44 +00001636 return llvm::ConstantExpr::getGetElementPtr(VTable->getValueType(), VTable,
1637 Indices, /*InBounds=*/true,
1638 /*InRangeIndex=*/1);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001639}
1640
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001641llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructorWithVTT(
1642 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1643 const CXXRecordDecl *NearestVBase) {
1644 assert((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1645 NeedsVTTParameter(CGF.CurGD) && "This class doesn't have VTT");
1646
1647 // Get the secondary vpointer index.
1648 uint64_t VirtualPointerIndex =
1649 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1650
1651 /// Load the VTT.
1652 llvm::Value *VTT = CGF.LoadCXXVTT();
1653 if (VirtualPointerIndex)
1654 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1655
1656 // And load the address point from the VTT.
1657 return CGF.Builder.CreateAlignedLoad(VTT, CGF.getPointerAlign());
1658}
1659
1660llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1661 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1662 return getVTableAddressPoint(Base, VTableClass);
1663}
1664
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001665llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1666 CharUnits VPtrOffset) {
1667 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1668
1669 llvm::GlobalVariable *&VTable = VTables[RD];
1670 if (VTable)
1671 return VTable;
1672
Eric Christopherd160c502016-01-29 01:35:53 +00001673 // Queue up this vtable for possible deferred emission.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001674 CGM.addDeferredVTable(RD);
1675
Yaron Kerene46f7ed2015-07-29 14:21:47 +00001676 SmallString<256> Name;
1677 llvm::raw_svector_ostream Out(Name);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001678 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001679
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001680 const VTableLayout &VTLayout =
1681 CGM.getItaniumVTableContext().getVTableLayout(RD);
1682 llvm::Type *VTableType = CGM.getVTables().getVTableType(VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001683
David Greenbe0c5b62018-09-12 14:09:06 +00001684 // Use pointer alignment for the vtable. Otherwise we would align them based
1685 // on the size of the initializer which doesn't make sense as only single
1686 // values are read.
1687 unsigned PAlign = CGM.getTarget().getPointerAlign(0);
1688
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001689 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
David Greenbe0c5b62018-09-12 14:09:06 +00001690 Name, VTableType, llvm::GlobalValue::ExternalLinkage,
1691 getContext().toCharUnitsFromBits(PAlign).getQuantity());
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001692 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Hans Wennborgda24e9c2014-06-02 23:13:03 +00001693
Rafael Espindola922f2aa2018-02-23 19:30:48 +00001694 CGM.setGVProperties(VTable, RD);
1695
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001696 return VTable;
1697}
1698
John McCall9831b842018-02-06 18:52:44 +00001699CGCallee ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1700 GlobalDecl GD,
1701 Address This,
1702 llvm::Type *Ty,
1703 SourceLocation Loc) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001704 Ty = Ty->getPointerTo()->getPointerTo();
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001705 auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
1706 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty, MethodDecl->getParent());
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001707
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001708 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
John McCall9831b842018-02-06 18:52:44 +00001709 llvm::Value *VFunc;
1710 if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) {
1711 VFunc = CGF.EmitVTableTypeCheckedLoad(
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001712 MethodDecl->getParent(), VTable,
1713 VTableIndex * CGM.getContext().getTargetInfo().getPointerWidth(0) / 8);
John McCall9831b842018-02-06 18:52:44 +00001714 } else {
1715 CGF.EmitTypeMetadataCodeForVCall(MethodDecl->getParent(), VTable, Loc);
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001716
John McCall9831b842018-02-06 18:52:44 +00001717 llvm::Value *VFuncPtr =
1718 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1719 auto *VFuncLoad =
1720 CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign());
Piotr Padlewski77cc9622016-10-29 15:28:30 +00001721
John McCall9831b842018-02-06 18:52:44 +00001722 // Add !invariant.load md to virtual function load to indicate that
1723 // function didn't change inside vtable.
1724 // It's safe to add it without -fstrict-vtable-pointers, but it would not
1725 // help in devirtualization because it will only matter if we will have 2
1726 // the same virtual function loads from the same vtable load, which won't
1727 // happen without enabled devirtualization with -fstrict-vtable-pointers.
1728 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1729 CGM.getCodeGenOpts().StrictVTablePointers)
1730 VFuncLoad->setMetadata(
1731 llvm::LLVMContext::MD_invariant_load,
1732 llvm::MDNode::get(CGM.getLLVMContext(),
1733 llvm::ArrayRef<llvm::Metadata *>()));
1734 VFunc = VFuncLoad;
1735 }
John McCallb92ab1a2016-10-26 23:46:34 +00001736
Erich Keanede6480a32018-11-13 15:48:08 +00001737 CGCallee Callee(GD, VFunc);
John McCall9831b842018-02-06 18:52:44 +00001738 return Callee;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001739}
1740
David Majnemer0c0b6d92014-10-31 20:09:12 +00001741llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
1742 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
Marco Antognini88559632019-07-22 09:39:13 +00001743 Address This, DeleteOrMemberCallExpr E) {
1744 auto *CE = E.dyn_cast<const CXXMemberCallExpr *>();
1745 auto *D = E.dyn_cast<const CXXDeleteExpr *>();
1746 assert((CE != nullptr) ^ (D != nullptr));
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001747 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001748 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1749
Peter Collingbourned1c5b282019-03-22 23:05:10 +00001750 GlobalDecl GD(Dtor, DtorType);
1751 const CGFunctionInfo *FInfo =
1752 &CGM.getTypes().arrangeCXXStructorDeclaration(GD);
George Burgess IV00f70bd2018-03-01 05:43:23 +00001753 llvm::FunctionType *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Peter Collingbourned1c5b282019-03-22 23:05:10 +00001754 CGCallee Callee = CGCallee::forVirtual(CE, GD, This, Ty);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001755
Marco Antognini88559632019-07-22 09:39:13 +00001756 QualType ThisTy;
1757 if (CE) {
1758 ThisTy = CE->getObjectType();
1759 } else {
1760 ThisTy = D->getDestroyedType();
1761 }
1762
1763 CGF.EmitCXXDestructorCall(GD, Callee, This.getPointer(), ThisTy, nullptr,
1764 QualType(), nullptr);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001765 return nullptr;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001766}
1767
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001768void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001769 CodeGenVTables &VTables = CGM.getVTables();
1770 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001771 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001772}
1773
Richard Smithc195c252018-11-27 19:33:49 +00001774bool ItaniumCXXABI::canSpeculativelyEmitVTableAsBaseClass(
1775 const CXXRecordDecl *RD) const {
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001776 // We don't emit available_externally vtables if we are in -fapple-kext mode
1777 // because kext mode does not permit devirtualization.
1778 if (CGM.getLangOpts().AppleKext)
1779 return false;
1780
Piotr Padlewskie368de32018-06-13 13:55:42 +00001781 // If the vtable is hidden then it is not safe to emit an available_externally
1782 // copy of vtable.
1783 if (isVTableHidden(RD))
1784 return false;
1785
1786 if (CGM.getCodeGenOpts().ForceEmitVTables)
1787 return true;
1788
1789 // If we don't have any not emitted inline virtual function then we are safe
1790 // to emit an available_externally copy of vtable.
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001791 // FIXME we can still emit a copy of the vtable if we
1792 // can emit definition of the inline functions.
Richard Smithc195c252018-11-27 19:33:49 +00001793 if (hasAnyUnusedVirtualInlineFunction(RD))
1794 return false;
1795
1796 // For a class with virtual bases, we must also be able to speculatively
1797 // emit the VTT, because CodeGen doesn't have separate notions of "can emit
1798 // the vtable" and "can emit the VTT". For a base subobject, this means we
1799 // need to be able to emit non-virtual base vtables.
1800 if (RD->getNumVBases()) {
1801 for (const auto &B : RD->bases()) {
1802 auto *BRD = B.getType()->getAsCXXRecordDecl();
1803 assert(BRD && "no class for base specifier");
1804 if (B.isVirtual() || !BRD->isDynamicClass())
1805 continue;
1806 if (!canSpeculativelyEmitVTableAsBaseClass(BRD))
1807 return false;
1808 }
1809 }
1810
1811 return true;
1812}
1813
1814bool ItaniumCXXABI::canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const {
1815 if (!canSpeculativelyEmitVTableAsBaseClass(RD))
1816 return false;
1817
1818 // For a complete-object vtable (or more specifically, for the VTT), we need
1819 // to be able to speculatively emit the vtables of all dynamic virtual bases.
1820 for (const auto &B : RD->vbases()) {
1821 auto *BRD = B.getType()->getAsCXXRecordDecl();
1822 assert(BRD && "no class for base specifier");
1823 if (!BRD->isDynamicClass())
1824 continue;
1825 if (!canSpeculativelyEmitVTableAsBaseClass(BRD))
1826 return false;
1827 }
1828
1829 return true;
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001830}
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001831static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001832 Address InitialPtr,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001833 int64_t NonVirtualAdjustment,
1834 int64_t VirtualAdjustment,
1835 bool IsReturnAdjustment) {
1836 if (!NonVirtualAdjustment && !VirtualAdjustment)
John McCall7f416cc2015-09-08 08:05:57 +00001837 return InitialPtr.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001838
John McCall7f416cc2015-09-08 08:05:57 +00001839 Address V = CGF.Builder.CreateElementBitCast(InitialPtr, CGF.Int8Ty);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001840
John McCall7f416cc2015-09-08 08:05:57 +00001841 // In a base-to-derived cast, the non-virtual adjustment is applied first.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001842 if (NonVirtualAdjustment && !IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001843 V = CGF.Builder.CreateConstInBoundsByteGEP(V,
1844 CharUnits::fromQuantity(NonVirtualAdjustment));
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001845 }
1846
John McCall7f416cc2015-09-08 08:05:57 +00001847 // Perform the virtual adjustment if we have one.
1848 llvm::Value *ResultPtr;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001849 if (VirtualAdjustment) {
1850 llvm::Type *PtrDiffTy =
1851 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1852
John McCall7f416cc2015-09-08 08:05:57 +00001853 Address VTablePtrPtr = CGF.Builder.CreateElementBitCast(V, CGF.Int8PtrTy);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001854 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1855
1856 llvm::Value *OffsetPtr =
1857 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1858
1859 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1860
1861 // Load the adjustment offset from the vtable.
John McCall7f416cc2015-09-08 08:05:57 +00001862 llvm::Value *Offset =
1863 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001864
1865 // Adjust our pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001866 ResultPtr = CGF.Builder.CreateInBoundsGEP(V.getPointer(), Offset);
1867 } else {
1868 ResultPtr = V.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001869 }
1870
John McCall7f416cc2015-09-08 08:05:57 +00001871 // In a derived-to-base conversion, the non-virtual adjustment is
1872 // applied second.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001873 if (NonVirtualAdjustment && IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001874 ResultPtr = CGF.Builder.CreateConstInBoundsGEP1_64(ResultPtr,
1875 NonVirtualAdjustment);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001876 }
1877
1878 // Cast back to the original type.
John McCall7f416cc2015-09-08 08:05:57 +00001879 return CGF.Builder.CreateBitCast(ResultPtr, InitialPtr.getType());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001880}
1881
1882llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001883 Address This,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001884 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001885 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1886 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001887 /*IsReturnAdjustment=*/false);
1888}
1889
1890llvm::Value *
John McCall7f416cc2015-09-08 08:05:57 +00001891ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001892 const ReturnAdjustment &RA) {
1893 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1894 RA.Virtual.Itanium.VBaseOffsetOffset,
1895 /*IsReturnAdjustment=*/true);
1896}
1897
John McCall5d865c322010-08-31 07:33:07 +00001898void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1899 RValue RV, QualType ResultType) {
1900 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1901 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1902
1903 // Destructor thunks in the ARM ABI have indeterminate results.
John McCall7f416cc2015-09-08 08:05:57 +00001904 llvm::Type *T = CGF.ReturnValue.getElementType();
John McCall5d865c322010-08-31 07:33:07 +00001905 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1906 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1907}
John McCall8ed55a52010-09-02 09:58:18 +00001908
1909/************************** Array allocation cookies **************************/
1910
John McCallb91cd662012-05-01 05:23:51 +00001911CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1912 // The array cookie is a size_t; pad that up to the element alignment.
1913 // The cookie is actually right-justified in that space.
1914 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1915 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001916}
1917
John McCall7f416cc2015-09-08 08:05:57 +00001918Address ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1919 Address NewPtr,
1920 llvm::Value *NumElements,
1921 const CXXNewExpr *expr,
1922 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001923 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001924
John McCall7f416cc2015-09-08 08:05:57 +00001925 unsigned AS = NewPtr.getAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001926
John McCall9bca9232010-09-02 10:25:57 +00001927 ASTContext &Ctx = getContext();
John McCall7f416cc2015-09-08 08:05:57 +00001928 CharUnits SizeSize = CGF.getSizeSize();
John McCall8ed55a52010-09-02 09:58:18 +00001929
1930 // The size of the cookie.
1931 CharUnits CookieSize =
1932 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001933 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001934
1935 // Compute an offset to the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001936 Address CookiePtr = NewPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001937 CharUnits CookieOffset = CookieSize - SizeSize;
1938 if (!CookieOffset.isZero())
John McCall7f416cc2015-09-08 08:05:57 +00001939 CookiePtr = CGF.Builder.CreateConstInBoundsByteGEP(CookiePtr, CookieOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001940
1941 // Write the number of elements into the appropriate slot.
John McCall7f416cc2015-09-08 08:05:57 +00001942 Address NumElementsPtr =
1943 CGF.Builder.CreateElementBitCast(CookiePtr, CGF.SizeTy);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001944 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
John McCall7f416cc2015-09-08 08:05:57 +00001945
1946 // Handle the array cookie specially in ASan.
Filipe Cabecinhas6f83fa92018-01-02 13:46:12 +00001947 if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 &&
Filipe Cabecinhas4ba58172018-02-12 11:49:02 +00001948 (expr->getOperatorNew()->isReplaceableGlobalAllocationFunction() ||
Filipe Cabecinhas0eb50082018-11-02 17:29:04 +00001949 CGM.getCodeGenOpts().SanitizeAddressPoisonCustomArrayCookie)) {
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001950 // The store to the CookiePtr does not need to be instrumented.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001951 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
1952 llvm::FunctionType *FTy =
John McCall7f416cc2015-09-08 08:05:57 +00001953 llvm::FunctionType::get(CGM.VoidTy, NumElementsPtr.getType(), false);
James Y Knight9871db02019-02-05 16:42:33 +00001954 llvm::FunctionCallee F =
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001955 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001956 CGF.Builder.CreateCall(F, NumElementsPtr.getPointer());
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001957 }
John McCall8ed55a52010-09-02 09:58:18 +00001958
1959 // Finally, compute a pointer to the actual data buffer by skipping
1960 // over the cookie completely.
John McCall7f416cc2015-09-08 08:05:57 +00001961 return CGF.Builder.CreateConstInBoundsByteGEP(NewPtr, CookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001962}
1963
John McCallb91cd662012-05-01 05:23:51 +00001964llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001965 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00001966 CharUnits cookieSize) {
1967 // The element size is right-justified in the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001968 Address numElementsPtr = allocPtr;
1969 CharUnits numElementsOffset = cookieSize - CGF.getSizeSize();
John McCallb91cd662012-05-01 05:23:51 +00001970 if (!numElementsOffset.isZero())
1971 numElementsPtr =
John McCall7f416cc2015-09-08 08:05:57 +00001972 CGF.Builder.CreateConstInBoundsByteGEP(numElementsPtr, numElementsOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001973
John McCall7f416cc2015-09-08 08:05:57 +00001974 unsigned AS = allocPtr.getAddressSpace();
1975 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001976 if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0)
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001977 return CGF.Builder.CreateLoad(numElementsPtr);
1978 // In asan mode emit a function call instead of a regular load and let the
1979 // run-time deal with it: if the shadow is properly poisoned return the
1980 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
1981 // We can't simply ignore this load using nosanitize metadata because
1982 // the metadata may be lost.
1983 llvm::FunctionType *FTy =
1984 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
James Y Knight9871db02019-02-05 16:42:33 +00001985 llvm::FunctionCallee F =
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001986 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001987 return CGF.Builder.CreateCall(F, numElementsPtr.getPointer());
John McCall8ed55a52010-09-02 09:58:18 +00001988}
1989
John McCallb91cd662012-05-01 05:23:51 +00001990CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001991 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001992 // struct array_cookie {
1993 // std::size_t element_size; // element_size != 0
1994 // std::size_t element_count;
1995 // };
John McCallc19c7062013-01-25 23:36:19 +00001996 // But the base ABI doesn't give anything an alignment greater than
1997 // 8, so we can dismiss this as typical ABI-author blindness to
1998 // actual language complexity and round up to the element alignment.
1999 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
2000 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00002001}
2002
John McCall7f416cc2015-09-08 08:05:57 +00002003Address ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
2004 Address newPtr,
2005 llvm::Value *numElements,
2006 const CXXNewExpr *expr,
2007 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00002008 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00002009
John McCall8ed55a52010-09-02 09:58:18 +00002010 // The cookie is always at the start of the buffer.
John McCall7f416cc2015-09-08 08:05:57 +00002011 Address cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00002012
2013 // The first element is the element size.
John McCall7f416cc2015-09-08 08:05:57 +00002014 cookie = CGF.Builder.CreateElementBitCast(cookie, CGF.SizeTy);
John McCallc19c7062013-01-25 23:36:19 +00002015 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
2016 getContext().getTypeSizeInChars(elementType).getQuantity());
2017 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00002018
2019 // The second element is the element count.
James Y Knight751fe282019-02-09 22:22:28 +00002020 cookie = CGF.Builder.CreateConstInBoundsGEP(cookie, 1);
John McCallc19c7062013-01-25 23:36:19 +00002021 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00002022
2023 // Finally, compute a pointer to the actual data buffer by skipping
2024 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00002025 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
John McCall7f416cc2015-09-08 08:05:57 +00002026 return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00002027}
2028
John McCallb91cd662012-05-01 05:23:51 +00002029llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002030 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00002031 CharUnits cookieSize) {
2032 // The number of elements is at offset sizeof(size_t) relative to
2033 // the allocated pointer.
John McCall7f416cc2015-09-08 08:05:57 +00002034 Address numElementsPtr
2035 = CGF.Builder.CreateConstInBoundsByteGEP(allocPtr, CGF.getSizeSize());
John McCall8ed55a52010-09-02 09:58:18 +00002036
John McCall7f416cc2015-09-08 08:05:57 +00002037 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
John McCallb91cd662012-05-01 05:23:51 +00002038 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00002039}
2040
John McCall68ff0372010-09-08 01:44:27 +00002041/*********************** Static local initialization **************************/
2042
James Y Knight9871db02019-02-05 16:42:33 +00002043static llvm::FunctionCallee getGuardAcquireFn(CodeGenModule &CGM,
2044 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00002045 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00002046 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00002047 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00002048 GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00002049 return CGM.CreateRuntimeFunction(
2050 FTy, "__cxa_guard_acquire",
2051 llvm::AttributeList::get(CGM.getLLVMContext(),
2052 llvm::AttributeList::FunctionIndex,
2053 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00002054}
2055
James Y Knight9871db02019-02-05 16:42:33 +00002056static llvm::FunctionCallee getGuardReleaseFn(CodeGenModule &CGM,
2057 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00002058 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00002059 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00002060 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00002061 return CGM.CreateRuntimeFunction(
2062 FTy, "__cxa_guard_release",
2063 llvm::AttributeList::get(CGM.getLLVMContext(),
2064 llvm::AttributeList::FunctionIndex,
2065 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00002066}
2067
James Y Knight9871db02019-02-05 16:42:33 +00002068static llvm::FunctionCallee getGuardAbortFn(CodeGenModule &CGM,
2069 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00002070 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00002071 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00002072 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00002073 return CGM.CreateRuntimeFunction(
2074 FTy, "__cxa_guard_abort",
2075 llvm::AttributeList::get(CGM.getLLVMContext(),
2076 llvm::AttributeList::FunctionIndex,
2077 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00002078}
2079
2080namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002081 struct CallGuardAbort final : EHScopeStack::Cleanup {
John McCall68ff0372010-09-08 01:44:27 +00002082 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00002083 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00002084
Craig Topper4f12f102014-03-12 06:41:41 +00002085 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00002086 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
2087 Guard);
John McCall68ff0372010-09-08 01:44:27 +00002088 }
2089 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002090}
John McCall68ff0372010-09-08 01:44:27 +00002091
2092/// The ARM code here follows the Itanium code closely enough that we
2093/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00002094void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
2095 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00002096 llvm::GlobalVariable *var,
2097 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00002098 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00002099
Richard Smith62f19e72016-06-25 00:15:56 +00002100 // Inline variables that weren't instantiated from variable templates have
2101 // partially-ordered initialization within their translation unit.
2102 bool NonTemplateInline =
2103 D.isInline() &&
2104 !isTemplateInstantiation(D.getTemplateSpecializationKind());
2105
2106 // We only need to use thread-safe statics for local non-TLS variables and
2107 // inline variables; other global initialization is always single-threaded
2108 // or (through lazy dynamic loading in multiple threads) unsequenced.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002109 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
Richard Smith62f19e72016-06-25 00:15:56 +00002110 (D.isLocalVarDecl() || NonTemplateInline) &&
2111 !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00002112
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00002113 // If we have a global variable with internal linkage and thread-safe statics
2114 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00002115 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
2116
2117 llvm::IntegerType *guardTy;
John McCall7f416cc2015-09-08 08:05:57 +00002118 CharUnits guardAlignment;
John McCall5aa52592011-06-17 07:33:57 +00002119 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00002120 guardTy = CGF.Int8Ty;
John McCall7f416cc2015-09-08 08:05:57 +00002121 guardAlignment = CharUnits::One();
John McCall5aa52592011-06-17 07:33:57 +00002122 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00002123 // Guard variables are 64 bits in the generic ABI and size width on ARM
2124 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
John McCall7f416cc2015-09-08 08:05:57 +00002125 if (UseARMGuardVarABI) {
2126 guardTy = CGF.SizeTy;
2127 guardAlignment = CGF.getSizeAlign();
2128 } else {
2129 guardTy = CGF.Int64Ty;
2130 guardAlignment = CharUnits::fromQuantity(
2131 CGM.getDataLayout().getABITypeAlignment(guardTy));
2132 }
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00002133 }
John McCallb88a5662012-03-30 21:00:39 +00002134 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00002135
John McCallb88a5662012-03-30 21:00:39 +00002136 // Create the guard variable if we don't already have it (as we
2137 // might if we're double-emitting this function body).
2138 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
2139 if (!guard) {
2140 // Mangle the name for the guard.
2141 SmallString<256> guardName;
2142 {
2143 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00002144 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00002145 }
John McCall8e7cb6d2010-11-02 21:04:24 +00002146
John McCallb88a5662012-03-30 21:00:39 +00002147 // Create the guard variable with a zero-initializer.
2148 // Just absorb linkage and visibility from the guarded variable.
2149 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
2150 false, var->getLinkage(),
2151 llvm::ConstantInt::get(guardTy, 0),
2152 guardName.str());
Rafael Espindola699f5d62018-02-07 22:15:33 +00002153 guard->setDSOLocal(var->isDSOLocal());
John McCallb88a5662012-03-30 21:00:39 +00002154 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00002155 // If the variable is thread-local, so is its guard variable.
2156 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCall7f416cc2015-09-08 08:05:57 +00002157 guard->setAlignment(guardAlignment.getQuantity());
John McCallb88a5662012-03-30 21:00:39 +00002158
Yaron Keren5bfa1082015-09-03 20:33:29 +00002159 // The ABI says: "It is suggested that it be emitted in the same COMDAT
2160 // group as the associated data object." In practice, this doesn't work for
Dan Gohman839f2152017-01-17 21:46:38 +00002161 // non-ELF and non-Wasm object formats, so only do it for ELF and Wasm.
Rafael Espindola0d4fb982015-01-12 22:13:53 +00002162 llvm::Comdat *C = var->getComdat();
Yaron Keren5bfa1082015-09-03 20:33:29 +00002163 if (!D.isLocalVarDecl() && C &&
Dan Gohman839f2152017-01-17 21:46:38 +00002164 (CGM.getTarget().getTriple().isOSBinFormatELF() ||
2165 CGM.getTarget().getTriple().isOSBinFormatWasm())) {
Rafael Espindola2ae4b632014-09-19 19:43:18 +00002166 guard->setComdat(C);
Richard Smith62f19e72016-06-25 00:15:56 +00002167 // An inline variable's guard function is run from the per-TU
2168 // initialization function, not via a dedicated global ctor function, so
2169 // we can't put it in a comdat.
2170 if (!NonTemplateInline)
2171 CGF.CurFn->setComdat(C);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00002172 } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) {
2173 guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName()));
Rafael Espindola2ae4b632014-09-19 19:43:18 +00002174 }
2175
John McCallb88a5662012-03-30 21:00:39 +00002176 CGM.setStaticLocalDeclGuardAddress(&D, guard);
2177 }
John McCall87590e62012-03-30 07:09:50 +00002178
John McCall7f416cc2015-09-08 08:05:57 +00002179 Address guardAddr = Address(guard, guardAlignment);
2180
John McCall68ff0372010-09-08 01:44:27 +00002181 // Test whether the variable has completed initialization.
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002182 //
John McCall68ff0372010-09-08 01:44:27 +00002183 // Itanium C++ ABI 3.3.2:
2184 // The following is pseudo-code showing how these functions can be used:
2185 // if (obj_guard.first_byte == 0) {
2186 // if ( __cxa_guard_acquire (&obj_guard) ) {
2187 // try {
2188 // ... initialize the object ...;
2189 // } catch (...) {
2190 // __cxa_guard_abort (&obj_guard);
2191 // throw;
2192 // }
2193 // ... queue object destructor with __cxa_atexit() ...;
2194 // __cxa_guard_release (&obj_guard);
2195 // }
2196 // }
Tim Northovera2ee4332014-03-29 15:09:45 +00002197
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002198 // Load the first byte of the guard variable.
2199 llvm::LoadInst *LI =
John McCall7f416cc2015-09-08 08:05:57 +00002200 Builder.CreateLoad(Builder.CreateElementBitCast(guardAddr, CGM.Int8Ty));
John McCall68ff0372010-09-08 01:44:27 +00002201
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002202 // Itanium ABI:
2203 // An implementation supporting thread-safety on multiprocessor
2204 // systems must also guarantee that references to the initialized
2205 // object do not occur before the load of the initialization flag.
2206 //
2207 // In LLVM, we do this by marking the load Acquire.
2208 if (threadsafe)
JF Bastien92f4ef12016-04-06 17:26:42 +00002209 LI->setAtomic(llvm::AtomicOrdering::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00002210
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002211 // For ARM, we should only check the first bit, rather than the entire byte:
2212 //
2213 // ARM C++ ABI 3.2.3.1:
2214 // To support the potential use of initialization guard variables
2215 // as semaphores that are the target of ARM SWP and LDREX/STREX
2216 // synchronizing instructions we define a static initialization
2217 // guard variable to be a 4-byte aligned, 4-byte word with the
2218 // following inline access protocol.
2219 // #define INITIALIZED 1
2220 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
2221 // if (__cxa_guard_acquire(&obj_guard))
2222 // ...
2223 // }
2224 //
2225 // and similarly for ARM64:
2226 //
2227 // ARM64 C++ ABI 3.2.2:
2228 // This ABI instead only specifies the value bit 0 of the static guard
2229 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
2230 // variable is not initialized and 1 when it is.
2231 llvm::Value *V =
2232 (UseARMGuardVarABI && !useInt8GuardVariable)
2233 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
2234 : LI;
Richard Smithae8d62c2017-07-26 22:01:09 +00002235 llvm::Value *NeedsInit = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00002236
2237 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
2238 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2239
2240 // Check if the first byte of the guard variable is zero.
Richard Smithae8d62c2017-07-26 22:01:09 +00002241 CGF.EmitCXXGuardedInitBranch(NeedsInit, InitCheckBlock, EndBlock,
2242 CodeGenFunction::GuardKind::VariableGuard, &D);
John McCall68ff0372010-09-08 01:44:27 +00002243
2244 CGF.EmitBlock(InitCheckBlock);
2245
2246 // Variables used when coping with thread-safe statics and exceptions.
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002247 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002248 // Call __cxa_guard_acquire.
2249 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00002250 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002251
John McCall68ff0372010-09-08 01:44:27 +00002252 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002253
John McCall68ff0372010-09-08 01:44:27 +00002254 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
2255 InitBlock, EndBlock);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002256
John McCall68ff0372010-09-08 01:44:27 +00002257 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00002258 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002259
John McCall68ff0372010-09-08 01:44:27 +00002260 CGF.EmitBlock(InitBlock);
2261 }
2262
2263 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00002264 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00002265
John McCall5aa52592011-06-17 07:33:57 +00002266 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002267 // Pop the guard-abort cleanup if we pushed one.
2268 CGF.PopCleanupBlock();
2269
2270 // Call __cxa_guard_release. This cannot throw.
John McCall7f416cc2015-09-08 08:05:57 +00002271 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy),
2272 guardAddr.getPointer());
John McCall68ff0372010-09-08 01:44:27 +00002273 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002274 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guardAddr);
John McCall68ff0372010-09-08 01:44:27 +00002275 }
2276
2277 CGF.EmitBlock(EndBlock);
2278}
John McCallc84ed6a2012-05-01 06:13:13 +00002279
2280/// Register a global destructor using __cxa_atexit.
2281static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
James Y Knightf7321542019-02-07 01:14:17 +00002282 llvm::FunctionCallee dtor,
2283 llvm::Constant *addr, bool TLS) {
Erich Keane34ec6922019-06-13 18:20:19 +00002284 assert((TLS || CGF.getTypes().getCodeGenOpts().CXAAtExit) &&
2285 "__cxa_atexit is disabled");
Bill Wendling95cae882013-05-02 19:18:03 +00002286 const char *Name = "__cxa_atexit";
2287 if (TLS) {
2288 const llvm::Triple &T = CGF.getTarget().getTriple();
Manman Renf93fff22015-11-11 23:08:18 +00002289 Name = T.isOSDarwin() ? "_tlv_atexit" : "__cxa_thread_atexit";
Bill Wendling95cae882013-05-02 19:18:03 +00002290 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00002291
John McCallc84ed6a2012-05-01 06:13:13 +00002292 // We're assuming that the destructor function is something we can
2293 // reasonably call with the default CC. Go ahead and cast it to the
2294 // right prototype.
2295 llvm::Type *dtorTy =
2296 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
2297
Anastasia Stulova960ff082019-07-15 11:58:10 +00002298 // Preserve address space of addr.
2299 auto AddrAS = addr ? addr->getType()->getPointerAddressSpace() : 0;
2300 auto AddrInt8PtrTy =
2301 AddrAS ? CGF.Int8Ty->getPointerTo(AddrAS) : CGF.Int8PtrTy;
2302
2303 // Create a variable that binds the atexit to this shared object.
2304 llvm::Constant *handle =
2305 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
2306 auto *GV = cast<llvm::GlobalValue>(handle->stripPointerCasts());
2307 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
2308
John McCallc84ed6a2012-05-01 06:13:13 +00002309 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
Anastasia Stulova960ff082019-07-15 11:58:10 +00002310 llvm::Type *paramTys[] = {dtorTy, AddrInt8PtrTy, handle->getType()};
John McCallc84ed6a2012-05-01 06:13:13 +00002311 llvm::FunctionType *atexitTy =
2312 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
2313
2314 // Fetch the actual function.
James Y Knight9871db02019-02-05 16:42:33 +00002315 llvm::FunctionCallee atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
2316 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit.getCallee()))
John McCallc84ed6a2012-05-01 06:13:13 +00002317 fn->setDoesNotThrow();
2318
Akira Hatanaka617e2612018-04-17 18:41:52 +00002319 if (!addr)
2320 // addr is null when we are trying to register a dtor annotated with
2321 // __attribute__((destructor)) in a constructor function. Using null here is
2322 // okay because this argument is just passed back to the destructor
2323 // function.
2324 addr = llvm::Constant::getNullValue(CGF.Int8PtrTy);
2325
James Y Knightf7321542019-02-07 01:14:17 +00002326 llvm::Value *args[] = {llvm::ConstantExpr::getBitCast(
2327 cast<llvm::Constant>(dtor.getCallee()), dtorTy),
Anastasia Stulova960ff082019-07-15 11:58:10 +00002328 llvm::ConstantExpr::getBitCast(addr, AddrInt8PtrTy),
James Y Knightf7321542019-02-07 01:14:17 +00002329 handle};
John McCall882987f2013-02-28 19:01:20 +00002330 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00002331}
2332
Akira Hatanaka617e2612018-04-17 18:41:52 +00002333void CodeGenModule::registerGlobalDtorsWithAtExit() {
2334 for (const auto I : DtorsUsingAtExit) {
2335 int Priority = I.first;
2336 const llvm::TinyPtrVector<llvm::Function *> &Dtors = I.second;
2337
2338 // Create a function that registers destructors that have the same priority.
2339 //
2340 // Since constructor functions are run in non-descending order of their
2341 // priorities, destructors are registered in non-descending order of their
2342 // priorities, and since destructor functions are run in the reverse order
2343 // of their registration, destructor functions are run in non-ascending
2344 // order of their priorities.
2345 CodeGenFunction CGF(*this);
2346 std::string GlobalInitFnName =
2347 std::string("__GLOBAL_init_") + llvm::to_string(Priority);
2348 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
2349 llvm::Function *GlobalInitFn = CreateGlobalInitOrDestructFunction(
2350 FTy, GlobalInitFnName, getTypes().arrangeNullaryFunction(),
2351 SourceLocation());
2352 ASTContext &Ctx = getContext();
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002353 QualType ReturnTy = Ctx.VoidTy;
2354 QualType FunctionTy = Ctx.getFunctionType(ReturnTy, llvm::None, {});
Akira Hatanaka617e2612018-04-17 18:41:52 +00002355 FunctionDecl *FD = FunctionDecl::Create(
2356 Ctx, Ctx.getTranslationUnitDecl(), SourceLocation(), SourceLocation(),
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002357 &Ctx.Idents.get(GlobalInitFnName), FunctionTy, nullptr, SC_Static,
Akira Hatanaka617e2612018-04-17 18:41:52 +00002358 false, false);
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002359 CGF.StartFunction(GlobalDecl(FD), ReturnTy, GlobalInitFn,
Akira Hatanaka617e2612018-04-17 18:41:52 +00002360 getTypes().arrangeNullaryFunction(), FunctionArgList(),
2361 SourceLocation(), SourceLocation());
2362
2363 for (auto *Dtor : Dtors) {
2364 // Register the destructor function calling __cxa_atexit if it is
2365 // available. Otherwise fall back on calling atexit.
2366 if (getCodeGenOpts().CXAAtExit)
2367 emitGlobalDtorWithCXAAtExit(CGF, Dtor, nullptr, false);
2368 else
2369 CGF.registerGlobalDtorWithAtExit(Dtor);
2370 }
2371
2372 CGF.FinishFunction();
2373 AddGlobalCtor(GlobalInitFn, Priority, nullptr);
2374 }
2375}
2376
John McCallc84ed6a2012-05-01 06:13:13 +00002377/// Register a global destructor as best as we know how.
James Y Knightf7321542019-02-07 01:14:17 +00002378void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
2379 llvm::FunctionCallee dtor,
John McCallc84ed6a2012-05-01 06:13:13 +00002380 llvm::Constant *addr) {
Erik Pilkington5a559e62018-08-21 17:24:06 +00002381 if (D.isNoDestroy(CGM.getContext()))
2382 return;
2383
Erich Keane34ec6922019-06-13 18:20:19 +00002384 // emitGlobalDtorWithCXAAtExit will emit a call to either __cxa_thread_atexit
2385 // or __cxa_atexit depending on whether this VarDecl is a thread-local storage
2386 // or not. CXAAtExit controls only __cxa_atexit, so use it if it is enabled.
2387 // We can always use __cxa_thread_atexit.
2388 if (CGM.getCodeGenOpts().CXAAtExit || D.getTLSKind())
Richard Smithdbf74ba2013-04-14 23:01:42 +00002389 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
2390
John McCallc84ed6a2012-05-01 06:13:13 +00002391 // In Apple kexts, we want to add a global destructor entry.
2392 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00002393 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00002394 // Generate a global destructor entry.
2395 return CGM.AddCXXDtorEntry(dtor, addr);
2396 }
2397
David Blaikieebe87e12013-08-27 23:57:18 +00002398 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00002399}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002400
David Majnemer9b21c332014-07-11 20:28:10 +00002401static bool isThreadWrapperReplaceable(const VarDecl *VD,
2402 CodeGen::CodeGenModule &CGM) {
2403 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
Manman Renf93fff22015-11-11 23:08:18 +00002404 // Darwin prefers to have references to thread local variables to go through
David Majnemer9b21c332014-07-11 20:28:10 +00002405 // the thread wrapper instead of directly referencing the backing variable.
2406 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
Manman Renf93fff22015-11-11 23:08:18 +00002407 CGM.getTarget().getTriple().isOSDarwin();
David Majnemer9b21c332014-07-11 20:28:10 +00002408}
2409
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002410/// Get the appropriate linkage for the wrapper function. This is essentially
David Majnemer4632e1e2014-06-27 16:56:27 +00002411/// the weak form of the variable's linkage; every translation unit which needs
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002412/// the wrapper emits a copy, and we want the linker to merge them.
David Majnemer35ab3282014-06-11 04:08:55 +00002413static llvm::GlobalValue::LinkageTypes
2414getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
2415 llvm::GlobalValue::LinkageTypes VarLinkage =
Rui Ueyama49a3ad22019-07-16 04:46:31 +00002416 CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false);
David Majnemer35ab3282014-06-11 04:08:55 +00002417
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002418 // For internal linkage variables, we don't need an external or weak wrapper.
2419 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
2420 return VarLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00002421
David Majnemer9b21c332014-07-11 20:28:10 +00002422 // If the thread wrapper is replaceable, give it appropriate linkage.
Manman Ren68150262015-11-11 22:42:31 +00002423 if (isThreadWrapperReplaceable(VD, CGM))
2424 if (!llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) &&
2425 !llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
2426 return VarLinkage;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002427 return llvm::GlobalValue::WeakODRLinkage;
2428}
2429
2430llvm::Function *
2431ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +00002432 llvm::Value *Val) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002433 // Mangle the name for the thread_local wrapper function.
2434 SmallString<256> WrapperName;
2435 {
2436 llvm::raw_svector_ostream Out(WrapperName);
2437 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002438 }
2439
Akira Hatanaka26907f92016-01-15 03:34:06 +00002440 // FIXME: If VD is a definition, we should regenerate the function attributes
2441 // before returning.
Alexander Musmanf94c3182014-09-26 06:28:25 +00002442 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002443 return cast<llvm::Function>(V);
2444
Akira Hatanaka26907f92016-01-15 03:34:06 +00002445 QualType RetQT = VD->getType();
2446 if (RetQT->isReferenceType())
2447 RetQT = RetQT.getNonReferenceType();
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002448
John McCallc56a8b32016-03-11 04:30:31 +00002449 const CGFunctionInfo &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2450 getContext().getPointerType(RetQT), FunctionArgList());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002451
2452 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FI);
David Majnemer35ab3282014-06-11 04:08:55 +00002453 llvm::Function *Wrapper =
2454 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
2455 WrapperName.str(), &CGM.getModule());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002456
Erich Keanede6480a32018-11-13 15:48:08 +00002457 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, Wrapper);
Akira Hatanaka26907f92016-01-15 03:34:06 +00002458
2459 if (VD->hasDefinition())
2460 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Wrapper);
2461
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002462 // Always resolve references to the wrapper at link time.
Vlad Tsyrklevichc93390b2019-01-17 17:53:45 +00002463 if (!Wrapper->hasLocalLinkage())
2464 if (!isThreadWrapperReplaceable(VD, CGM) ||
2465 llvm::GlobalVariable::isLinkOnceLinkage(Wrapper->getLinkage()) ||
2466 llvm::GlobalVariable::isWeakODRLinkage(Wrapper->getLinkage()) ||
2467 VD->getVisibility() == HiddenVisibility)
2468 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
Manman Renb0b3af72015-12-17 00:42:36 +00002469
2470 if (isThreadWrapperReplaceable(VD, CGM)) {
2471 Wrapper->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2472 Wrapper->addFnAttr(llvm::Attribute::NoUnwind);
2473 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002474 return Wrapper;
2475}
2476
2477void ItaniumCXXABI::EmitThreadLocalInitFuncs(
Richard Smith5a99c492015-12-01 01:10:48 +00002478 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
2479 ArrayRef<llvm::Function *> CXXThreadLocalInits,
2480 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
David Majnemerb3341ea2014-10-05 05:05:40 +00002481 llvm::Function *InitFunc = nullptr;
Richard Smithfbe23692017-01-13 00:43:31 +00002482
2483 // Separate initializers into those with ordered (or partially-ordered)
2484 // initialization and those with unordered initialization.
2485 llvm::SmallVector<llvm::Function *, 8> OrderedInits;
2486 llvm::SmallDenseMap<const VarDecl *, llvm::Function *> UnorderedInits;
2487 for (unsigned I = 0; I != CXXThreadLocalInits.size(); ++I) {
2488 if (isTemplateInstantiation(
2489 CXXThreadLocalInitVars[I]->getTemplateSpecializationKind()))
2490 UnorderedInits[CXXThreadLocalInitVars[I]->getCanonicalDecl()] =
2491 CXXThreadLocalInits[I];
2492 else
2493 OrderedInits.push_back(CXXThreadLocalInits[I]);
2494 }
2495
2496 if (!OrderedInits.empty()) {
David Majnemerb3341ea2014-10-05 05:05:40 +00002497 // Generate a guarded initialization function.
2498 llvm::FunctionType *FTy =
2499 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002500 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2501 InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init", FI,
Alexey Samsonov1444bb92014-10-17 00:20:19 +00002502 SourceLocation(),
David Majnemerb3341ea2014-10-05 05:05:40 +00002503 /*TLS=*/true);
2504 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
2505 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
2506 llvm::GlobalVariable::InternalLinkage,
2507 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
2508 Guard->setThreadLocal(true);
John McCall7f416cc2015-09-08 08:05:57 +00002509
2510 CharUnits GuardAlign = CharUnits::One();
2511 Guard->setAlignment(GuardAlign.getQuantity());
2512
Richard Smith3ad06362018-10-31 20:39:26 +00002513 CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(
2514 InitFunc, OrderedInits, ConstantAddress(Guard, GuardAlign));
Manman Ren5e5d0462016-03-18 23:35:21 +00002515 // On Darwin platforms, use CXX_FAST_TLS calling convention.
2516 if (CGM.getTarget().getTriple().isOSDarwin()) {
2517 InitFunc->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2518 InitFunc->addFnAttr(llvm::Attribute::NoUnwind);
2519 }
David Majnemerb3341ea2014-10-05 05:05:40 +00002520 }
Richard Smithfbe23692017-01-13 00:43:31 +00002521
2522 // Emit thread wrappers.
Richard Smith5a99c492015-12-01 01:10:48 +00002523 for (const VarDecl *VD : CXXThreadLocals) {
2524 llvm::GlobalVariable *Var =
2525 cast<llvm::GlobalVariable>(CGM.GetGlobalValue(CGM.getMangledName(VD)));
Richard Smithfbe23692017-01-13 00:43:31 +00002526 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002527
David Majnemer9b21c332014-07-11 20:28:10 +00002528 // Some targets require that all access to thread local variables go through
2529 // the thread wrapper. This means that we cannot attempt to create a thread
2530 // wrapper or a thread helper.
Richard Smithfbe23692017-01-13 00:43:31 +00002531 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition()) {
2532 Wrapper->setLinkage(llvm::Function::ExternalLinkage);
David Majnemer9b21c332014-07-11 20:28:10 +00002533 continue;
Richard Smithfbe23692017-01-13 00:43:31 +00002534 }
David Majnemer9b21c332014-07-11 20:28:10 +00002535
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002536 // Mangle the name for the thread_local initialization function.
2537 SmallString<256> InitFnName;
2538 {
2539 llvm::raw_svector_ostream Out(InitFnName);
2540 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002541 }
2542
James Y Knightf7321542019-02-07 01:14:17 +00002543 llvm::FunctionType *InitFnTy = llvm::FunctionType::get(CGM.VoidTy, false);
2544
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002545 // If we have a definition for the variable, emit the initialization
2546 // function as an alias to the global Init function (if any). Otherwise,
2547 // produce a declaration of the initialization function.
Craig Topper8a13c412014-05-21 05:09:00 +00002548 llvm::GlobalValue *Init = nullptr;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002549 bool InitIsInitFunc = false;
2550 if (VD->hasDefinition()) {
2551 InitIsInitFunc = true;
Richard Smithfbe23692017-01-13 00:43:31 +00002552 llvm::Function *InitFuncToUse = InitFunc;
2553 if (isTemplateInstantiation(VD->getTemplateSpecializationKind()))
2554 InitFuncToUse = UnorderedInits.lookup(VD->getCanonicalDecl());
2555 if (InitFuncToUse)
Rafael Espindola234405b2014-05-17 21:30:14 +00002556 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
Richard Smithfbe23692017-01-13 00:43:31 +00002557 InitFuncToUse);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002558 } else {
2559 // Emit a weak global function referring to the initialization function.
2560 // This function will not exist if the TU defining the thread_local
2561 // variable in question does not need any dynamic initialization for
2562 // its thread_local variables.
James Y Knightf7321542019-02-07 01:14:17 +00002563 Init = llvm::Function::Create(InitFnTy,
Richard Smithfbe23692017-01-13 00:43:31 +00002564 llvm::GlobalVariable::ExternalWeakLinkage,
2565 InitFnName.str(), &CGM.getModule());
John McCallc56a8b32016-03-11 04:30:31 +00002566 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
Erich Keanede6480a32018-11-13 15:48:08 +00002567 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI,
2568 cast<llvm::Function>(Init));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002569 }
2570
Rafael Espindolaabdb3222018-03-07 23:18:06 +00002571 if (Init) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002572 Init->setVisibility(Var->getVisibility());
Rafael Espindolaabdb3222018-03-07 23:18:06 +00002573 Init->setDSOLocal(Var->isDSOLocal());
2574 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002575
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002576 llvm::LLVMContext &Context = CGM.getModule().getContext();
2577 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
John McCall7f416cc2015-09-08 08:05:57 +00002578 CGBuilderTy Builder(CGM, Entry);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002579 if (InitIsInitFunc) {
Manman Ren5e5d0462016-03-18 23:35:21 +00002580 if (Init) {
James Y Knightf7321542019-02-07 01:14:17 +00002581 llvm::CallInst *CallVal = Builder.CreateCall(InitFnTy, Init);
Akira Hatanaka1da9dbb2018-05-29 18:28:49 +00002582 if (isThreadWrapperReplaceable(VD, CGM)) {
Manman Ren5e5d0462016-03-18 23:35:21 +00002583 CallVal->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
Akira Hatanaka1da9dbb2018-05-29 18:28:49 +00002584 llvm::Function *Fn =
2585 cast<llvm::Function>(cast<llvm::GlobalAlias>(Init)->getAliasee());
2586 Fn->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2587 }
Manman Ren5e5d0462016-03-18 23:35:21 +00002588 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002589 } else {
2590 // Don't know whether we have an init function. Call it if it exists.
2591 llvm::Value *Have = Builder.CreateIsNotNull(Init);
2592 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2593 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2594 Builder.CreateCondBr(Have, InitBB, ExitBB);
2595
2596 Builder.SetInsertPoint(InitBB);
James Y Knightf7321542019-02-07 01:14:17 +00002597 Builder.CreateCall(InitFnTy, Init);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002598 Builder.CreateBr(ExitBB);
2599
2600 Builder.SetInsertPoint(ExitBB);
2601 }
2602
2603 // For a reference, the result of the wrapper function is a pointer to
2604 // the referenced object.
2605 llvm::Value *Val = Var;
2606 if (VD->getType()->isReferenceType()) {
John McCall7f416cc2015-09-08 08:05:57 +00002607 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2608 Val = Builder.CreateAlignedLoad(Val, Align);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002609 }
Alexander Musmanf94c3182014-09-26 06:28:25 +00002610 if (Val->getType() != Wrapper->getReturnType())
2611 Val = Builder.CreatePointerBitCastOrAddrSpaceCast(
2612 Val, Wrapper->getReturnType(), "");
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002613 Builder.CreateRet(Val);
2614 }
2615}
2616
Richard Smith0f383742014-03-26 22:48:22 +00002617LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2618 const VarDecl *VD,
2619 QualType LValType) {
Richard Smith5a99c492015-12-01 01:10:48 +00002620 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD);
Alexander Musmanf94c3182014-09-26 06:28:25 +00002621 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002622
Manman Renb0b3af72015-12-17 00:42:36 +00002623 llvm::CallInst *CallVal = CGF.Builder.CreateCall(Wrapper);
Saleem Abdulrasool4a7130a2016-08-01 21:31:24 +00002624 CallVal->setCallingConv(Wrapper->getCallingConv());
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002625
2626 LValue LV;
2627 if (VD->getType()->isReferenceType())
Manman Renb0b3af72015-12-17 00:42:36 +00002628 LV = CGF.MakeNaturalAlignAddrLValue(CallVal, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002629 else
Manman Renb0b3af72015-12-17 00:42:36 +00002630 LV = CGF.MakeAddrLValue(CallVal, LValType,
2631 CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002632 // FIXME: need setObjCGCLValueClass?
2633 return LV;
2634}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002635
2636/// Return whether the given global decl needs a VTT parameter, which it does
2637/// if it's a base constructor or destructor with virtual bases.
2638bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
2639 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002640
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002641 // We don't have any virtual bases, just return early.
2642 if (!MD->getParent()->getNumVBases())
2643 return false;
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002644
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002645 // Check if we have a base constructor.
2646 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
2647 return true;
2648
2649 // Check if we have a base destructor.
2650 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2651 return true;
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002652
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002653 return false;
2654}
David Majnemere2cb8d12014-07-07 06:20:47 +00002655
2656namespace {
2657class ItaniumRTTIBuilder {
2658 CodeGenModule &CGM; // Per-module state.
2659 llvm::LLVMContext &VMContext;
2660 const ItaniumCXXABI &CXXABI; // Per-module state.
2661
2662 /// Fields - The fields of the RTTI descriptor currently being built.
2663 SmallVector<llvm::Constant *, 16> Fields;
2664
2665 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2666 llvm::GlobalVariable *
2667 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2668
2669 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2670 /// descriptor of the given type.
2671 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2672
2673 /// BuildVTablePointer - Build the vtable pointer for the given type.
2674 void BuildVTablePointer(const Type *Ty);
2675
2676 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2677 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2678 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2679
2680 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2681 /// classes with bases that do not satisfy the abi::__si_class_type_info
2682 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2683 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2684
2685 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2686 /// for pointer types.
2687 void BuildPointerTypeInfo(QualType PointeeTy);
2688
2689 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2690 /// type_info for an object type.
2691 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2692
2693 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2694 /// struct, used for member pointer types.
2695 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2696
2697public:
2698 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2699 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2700
2701 // Pointer type info flags.
2702 enum {
2703 /// PTI_Const - Type has const qualifier.
2704 PTI_Const = 0x1,
2705
2706 /// PTI_Volatile - Type has volatile qualifier.
2707 PTI_Volatile = 0x2,
2708
2709 /// PTI_Restrict - Type has restrict qualifier.
2710 PTI_Restrict = 0x4,
2711
2712 /// PTI_Incomplete - Type is incomplete.
2713 PTI_Incomplete = 0x8,
2714
2715 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2716 /// (in pointer to member).
Richard Smitha7d93782016-12-01 03:32:42 +00002717 PTI_ContainingClassIncomplete = 0x10,
2718
2719 /// PTI_TransactionSafe - Pointee is transaction_safe function (C++ TM TS).
2720 //PTI_TransactionSafe = 0x20,
2721
2722 /// PTI_Noexcept - Pointee is noexcept function (C++1z).
2723 PTI_Noexcept = 0x40,
David Majnemere2cb8d12014-07-07 06:20:47 +00002724 };
2725
2726 // VMI type info flags.
2727 enum {
2728 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2729 VMI_NonDiamondRepeat = 0x1,
2730
2731 /// VMI_DiamondShaped - Class is diamond shaped.
2732 VMI_DiamondShaped = 0x2
2733 };
2734
2735 // Base class type info flags.
2736 enum {
2737 /// BCTI_Virtual - Base class is virtual.
2738 BCTI_Virtual = 0x1,
2739
2740 /// BCTI_Public - Base class is public.
2741 BCTI_Public = 0x2
2742 };
2743
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00002744 /// BuildTypeInfo - Build the RTTI type info struct for the given type, or
2745 /// link to an existing RTTI descriptor if one already exists.
2746 llvm::Constant *BuildTypeInfo(QualType Ty);
2747
David Majnemere2cb8d12014-07-07 06:20:47 +00002748 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00002749 llvm::Constant *BuildTypeInfo(
2750 QualType Ty,
2751 llvm::GlobalVariable::LinkageTypes Linkage,
2752 llvm::GlobalValue::VisibilityTypes Visibility,
2753 llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass);
David Majnemere2cb8d12014-07-07 06:20:47 +00002754};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002755}
David Majnemere2cb8d12014-07-07 06:20:47 +00002756
2757llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2758 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002759 SmallString<256> Name;
2760 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002761 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002762
2763 // We know that the mangled name of the type starts at index 4 of the
2764 // mangled name of the typename, so we can just index into it in order to
2765 // get the mangled name of the type.
2766 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2767 Name.substr(4));
David Greenbe0c5b62018-09-12 14:09:06 +00002768 auto Align = CGM.getContext().getTypeAlignInChars(CGM.getContext().CharTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00002769
David Greenbe0c5b62018-09-12 14:09:06 +00002770 llvm::GlobalVariable *GV = CGM.CreateOrReplaceCXXRuntimeVariable(
2771 Name, Init->getType(), Linkage, Align.getQuantity());
David Majnemere2cb8d12014-07-07 06:20:47 +00002772
2773 GV->setInitializer(Init);
2774
2775 return GV;
2776}
2777
2778llvm::Constant *
2779ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2780 // Mangle the RTTI name.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002781 SmallString<256> Name;
2782 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002783 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002784
2785 // Look for an existing global.
2786 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2787
2788 if (!GV) {
2789 // Create a new global variable.
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00002790 // Note for the future: If we would ever like to do deferred emission of
2791 // RTTI, check if emitting vtables opportunistically need any adjustment.
2792
David Majnemere2cb8d12014-07-07 06:20:47 +00002793 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00002794 /*isConstant=*/true,
David Majnemere2cb8d12014-07-07 06:20:47 +00002795 llvm::GlobalValue::ExternalLinkage, nullptr,
2796 Name);
Rafael Espindola3f727a82018-03-14 18:14:46 +00002797 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
2798 CGM.setGVProperties(GV, RD);
David Majnemere2cb8d12014-07-07 06:20:47 +00002799 }
2800
2801 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2802}
2803
2804/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2805/// info for that type is defined in the standard library.
2806static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2807 // Itanium C++ ABI 2.9.2:
2808 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
2809 // the run-time support library. Specifically, the run-time support
2810 // library should contain type_info objects for the types X, X* and
2811 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2812 // unsigned char, signed char, short, unsigned short, int, unsigned int,
2813 // long, unsigned long, long long, unsigned long long, float, double,
2814 // long double, char16_t, char32_t, and the IEEE 754r decimal and
2815 // half-precision floating point types.
Richard Smith4a382012016-02-03 01:32:42 +00002816 //
2817 // GCC also emits RTTI for __int128.
2818 // FIXME: We do not emit RTTI information for decimal types here.
2819
2820 // Types added here must also be added to EmitFundamentalRTTIDescriptors.
David Majnemere2cb8d12014-07-07 06:20:47 +00002821 switch (Ty->getKind()) {
2822 case BuiltinType::Void:
2823 case BuiltinType::NullPtr:
2824 case BuiltinType::Bool:
2825 case BuiltinType::WChar_S:
2826 case BuiltinType::WChar_U:
2827 case BuiltinType::Char_U:
2828 case BuiltinType::Char_S:
2829 case BuiltinType::UChar:
2830 case BuiltinType::SChar:
2831 case BuiltinType::Short:
2832 case BuiltinType::UShort:
2833 case BuiltinType::Int:
2834 case BuiltinType::UInt:
2835 case BuiltinType::Long:
2836 case BuiltinType::ULong:
2837 case BuiltinType::LongLong:
2838 case BuiltinType::ULongLong:
2839 case BuiltinType::Half:
2840 case BuiltinType::Float:
2841 case BuiltinType::Double:
2842 case BuiltinType::LongDouble:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00002843 case BuiltinType::Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002844 case BuiltinType::Float128:
Richard Smith3a8244d2018-05-01 05:02:45 +00002845 case BuiltinType::Char8:
David Majnemere2cb8d12014-07-07 06:20:47 +00002846 case BuiltinType::Char16:
2847 case BuiltinType::Char32:
2848 case BuiltinType::Int128:
2849 case BuiltinType::UInt128:
Richard Smith4a382012016-02-03 01:32:42 +00002850 return true;
2851
Alexey Bader954ba212016-04-08 13:40:33 +00002852#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2853 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00002854#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00002855#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2856 case BuiltinType::Id:
2857#include "clang/Basic/OpenCLExtensionTypes.def"
David Majnemere2cb8d12014-07-07 06:20:47 +00002858 case BuiltinType::OCLSampler:
2859 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002860 case BuiltinType::OCLClkEvent:
2861 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002862 case BuiltinType::OCLReserveID:
Richard Sandifordeb485fb2019-08-09 08:52:54 +00002863#define SVE_TYPE(Name, Id, SingletonId) \
2864 case BuiltinType::Id:
2865#include "clang/Basic/AArch64SVEACLETypes.def"
Leonard Chanf921d852018-06-04 16:07:52 +00002866 case BuiltinType::ShortAccum:
2867 case BuiltinType::Accum:
2868 case BuiltinType::LongAccum:
2869 case BuiltinType::UShortAccum:
2870 case BuiltinType::UAccum:
2871 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00002872 case BuiltinType::ShortFract:
2873 case BuiltinType::Fract:
2874 case BuiltinType::LongFract:
2875 case BuiltinType::UShortFract:
2876 case BuiltinType::UFract:
2877 case BuiltinType::ULongFract:
2878 case BuiltinType::SatShortAccum:
2879 case BuiltinType::SatAccum:
2880 case BuiltinType::SatLongAccum:
2881 case BuiltinType::SatUShortAccum:
2882 case BuiltinType::SatUAccum:
2883 case BuiltinType::SatULongAccum:
2884 case BuiltinType::SatShortFract:
2885 case BuiltinType::SatFract:
2886 case BuiltinType::SatLongFract:
2887 case BuiltinType::SatUShortFract:
2888 case BuiltinType::SatUFract:
2889 case BuiltinType::SatULongFract:
Richard Smith4a382012016-02-03 01:32:42 +00002890 return false;
David Majnemere2cb8d12014-07-07 06:20:47 +00002891
2892 case BuiltinType::Dependent:
2893#define BUILTIN_TYPE(Id, SingletonId)
2894#define PLACEHOLDER_TYPE(Id, SingletonId) \
2895 case BuiltinType::Id:
2896#include "clang/AST/BuiltinTypes.def"
2897 llvm_unreachable("asking for RRTI for a placeholder type!");
2898
2899 case BuiltinType::ObjCId:
2900 case BuiltinType::ObjCClass:
2901 case BuiltinType::ObjCSel:
2902 llvm_unreachable("FIXME: Objective-C types are unsupported!");
2903 }
2904
2905 llvm_unreachable("Invalid BuiltinType Kind!");
2906}
2907
2908static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2909 QualType PointeeTy = PointerTy->getPointeeType();
2910 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2911 if (!BuiltinTy)
2912 return false;
2913
2914 // Check the qualifiers.
2915 Qualifiers Quals = PointeeTy.getQualifiers();
2916 Quals.removeConst();
2917
2918 if (!Quals.empty())
2919 return false;
2920
2921 return TypeInfoIsInStandardLibrary(BuiltinTy);
2922}
2923
2924/// IsStandardLibraryRTTIDescriptor - Returns whether the type
2925/// information for the given type exists in the standard library.
2926static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2927 // Type info for builtin types is defined in the standard library.
2928 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2929 return TypeInfoIsInStandardLibrary(BuiltinTy);
2930
2931 // Type info for some pointer types to builtin types is defined in the
2932 // standard library.
2933 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2934 return TypeInfoIsInStandardLibrary(PointerTy);
2935
2936 return false;
2937}
2938
2939/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
2940/// the given type exists somewhere else, and that we should not emit the type
2941/// information in this translation unit. Assumes that it is not a
2942/// standard-library type.
2943static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
2944 QualType Ty) {
2945 ASTContext &Context = CGM.getContext();
2946
2947 // If RTTI is disabled, assume it might be disabled in the
2948 // translation unit that defines any potential key function, too.
2949 if (!Context.getLangOpts().RTTI) return false;
2950
2951 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2952 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2953 if (!RD->hasDefinition())
2954 return false;
2955
2956 if (!RD->isDynamicClass())
2957 return false;
2958
2959 // FIXME: this may need to be reconsidered if the key function
2960 // changes.
David Majnemerbe9022c2015-08-06 20:56:55 +00002961 // N.B. We must always emit the RTTI data ourselves if there exists a key
2962 // function.
2963 bool IsDLLImport = RD->hasAttr<DLLImportAttr>();
Martin Storsjo3b528942018-02-02 06:22:35 +00002964
2965 // Don't import the RTTI but emit it locally.
Martin Storsjo228ccd62019-04-26 19:31:51 +00002966 if (CGM.getTriple().isWindowsGNUEnvironment())
Martin Storsjo3b528942018-02-02 06:22:35 +00002967 return false;
2968
David Majnemer1fb1a042014-11-07 07:26:38 +00002969 if (CGM.getVTables().isVTableExternal(RD))
Shoaib Meenai61118e72017-07-04 01:02:19 +00002970 return IsDLLImport && !CGM.getTriple().isWindowsItaniumEnvironment()
2971 ? false
2972 : true;
David Majnemer1fb1a042014-11-07 07:26:38 +00002973
David Majnemerbe9022c2015-08-06 20:56:55 +00002974 if (IsDLLImport)
David Majnemer1fb1a042014-11-07 07:26:38 +00002975 return true;
David Majnemere2cb8d12014-07-07 06:20:47 +00002976 }
2977
2978 return false;
2979}
2980
2981/// IsIncompleteClassType - Returns whether the given record type is incomplete.
2982static bool IsIncompleteClassType(const RecordType *RecordTy) {
2983 return !RecordTy->getDecl()->isCompleteDefinition();
2984}
2985
2986/// ContainsIncompleteClassType - Returns whether the given type contains an
2987/// incomplete class type. This is true if
2988///
2989/// * The given type is an incomplete class type.
2990/// * The given type is a pointer type whose pointee type contains an
2991/// incomplete class type.
2992/// * The given type is a member pointer type whose class is an incomplete
2993/// class type.
2994/// * The given type is a member pointer type whoise pointee type contains an
2995/// incomplete class type.
2996/// is an indirect or direct pointer to an incomplete class type.
2997static bool ContainsIncompleteClassType(QualType Ty) {
2998 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2999 if (IsIncompleteClassType(RecordTy))
3000 return true;
3001 }
3002
3003 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
3004 return ContainsIncompleteClassType(PointerTy->getPointeeType());
3005
3006 if (const MemberPointerType *MemberPointerTy =
3007 dyn_cast<MemberPointerType>(Ty)) {
3008 // Check if the class type is incomplete.
3009 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
3010 if (IsIncompleteClassType(ClassType))
3011 return true;
3012
3013 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
3014 }
3015
3016 return false;
3017}
3018
3019// CanUseSingleInheritance - Return whether the given record decl has a "single,
3020// public, non-virtual base at offset zero (i.e. the derived class is dynamic
3021// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
3022static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
3023 // Check the number of bases.
3024 if (RD->getNumBases() != 1)
3025 return false;
3026
3027 // Get the base.
3028 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
3029
3030 // Check that the base is not virtual.
3031 if (Base->isVirtual())
3032 return false;
3033
3034 // Check that the base is public.
3035 if (Base->getAccessSpecifier() != AS_public)
3036 return false;
3037
3038 // Check that the class is dynamic iff the base is.
3039 const CXXRecordDecl *BaseDecl =
3040 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
3041 if (!BaseDecl->isEmpty() &&
3042 BaseDecl->isDynamicClass() != RD->isDynamicClass())
3043 return false;
3044
3045 return true;
3046}
3047
3048void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
3049 // abi::__class_type_info.
3050 static const char * const ClassTypeInfo =
3051 "_ZTVN10__cxxabiv117__class_type_infoE";
3052 // abi::__si_class_type_info.
3053 static const char * const SIClassTypeInfo =
3054 "_ZTVN10__cxxabiv120__si_class_type_infoE";
3055 // abi::__vmi_class_type_info.
3056 static const char * const VMIClassTypeInfo =
3057 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
3058
3059 const char *VTableName = nullptr;
3060
3061 switch (Ty->getTypeClass()) {
3062#define TYPE(Class, Base)
3063#define ABSTRACT_TYPE(Class, Base)
3064#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3065#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3066#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3067#include "clang/AST/TypeNodes.def"
3068 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
3069
3070 case Type::LValueReference:
3071 case Type::RValueReference:
3072 llvm_unreachable("References shouldn't get here");
3073
3074 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00003075 case Type::DeducedTemplateSpecialization:
3076 llvm_unreachable("Undeduced type shouldn't get here");
David Majnemere2cb8d12014-07-07 06:20:47 +00003077
Xiuli Pan9c14e282016-01-09 12:53:17 +00003078 case Type::Pipe:
3079 llvm_unreachable("Pipe types shouldn't get here");
3080
David Majnemere2cb8d12014-07-07 06:20:47 +00003081 case Type::Builtin:
3082 // GCC treats vector and complex types as fundamental types.
3083 case Type::Vector:
3084 case Type::ExtVector:
3085 case Type::Complex:
3086 case Type::Atomic:
3087 // FIXME: GCC treats block pointers as fundamental types?!
3088 case Type::BlockPointer:
3089 // abi::__fundamental_type_info.
3090 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
3091 break;
3092
3093 case Type::ConstantArray:
3094 case Type::IncompleteArray:
3095 case Type::VariableArray:
3096 // abi::__array_type_info.
3097 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
3098 break;
3099
3100 case Type::FunctionNoProto:
3101 case Type::FunctionProto:
Richard Smithb17d6fa2016-12-01 03:04:07 +00003102 // abi::__function_type_info.
3103 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
David Majnemere2cb8d12014-07-07 06:20:47 +00003104 break;
3105
3106 case Type::Enum:
3107 // abi::__enum_type_info.
3108 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
3109 break;
3110
3111 case Type::Record: {
Rafael Espindolaf6688122018-03-22 21:14:16 +00003112 const CXXRecordDecl *RD =
3113 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
David Majnemere2cb8d12014-07-07 06:20:47 +00003114
3115 if (!RD->hasDefinition() || !RD->getNumBases()) {
3116 VTableName = ClassTypeInfo;
3117 } else if (CanUseSingleInheritance(RD)) {
3118 VTableName = SIClassTypeInfo;
3119 } else {
3120 VTableName = VMIClassTypeInfo;
3121 }
3122
3123 break;
3124 }
3125
3126 case Type::ObjCObject:
3127 // Ignore protocol qualifiers.
3128 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
3129
3130 // Handle id and Class.
3131 if (isa<BuiltinType>(Ty)) {
3132 VTableName = ClassTypeInfo;
3133 break;
3134 }
3135
3136 assert(isa<ObjCInterfaceType>(Ty));
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +00003137 LLVM_FALLTHROUGH;
David Majnemere2cb8d12014-07-07 06:20:47 +00003138
3139 case Type::ObjCInterface:
3140 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
3141 VTableName = SIClassTypeInfo;
3142 } else {
3143 VTableName = ClassTypeInfo;
3144 }
3145 break;
3146
3147 case Type::ObjCObjectPointer:
3148 case Type::Pointer:
3149 // abi::__pointer_type_info.
3150 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
3151 break;
3152
3153 case Type::MemberPointer:
3154 // abi::__pointer_to_member_type_info.
3155 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
3156 break;
3157 }
3158
3159 llvm::Constant *VTable =
3160 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
Rafael Espindolafe9a55a2018-03-23 01:36:23 +00003161 CGM.setDSOLocal(cast<llvm::GlobalValue>(VTable->stripPointerCasts()));
David Majnemere2cb8d12014-07-07 06:20:47 +00003162
3163 llvm::Type *PtrDiffTy =
3164 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
3165
3166 // The vtable address point is 2.
3167 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00003168 VTable =
3169 llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.Int8PtrTy, VTable, Two);
David Majnemere2cb8d12014-07-07 06:20:47 +00003170 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
3171
3172 Fields.push_back(VTable);
3173}
3174
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003175/// Return the linkage that the type info and type info name constants
David Majnemere2cb8d12014-07-07 06:20:47 +00003176/// should have for the given type.
Richard Smithbbb26552018-05-21 20:10:54 +00003177static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
3178 QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003179 // Itanium C++ ABI 2.9.5p7:
3180 // In addition, it and all of the intermediate abi::__pointer_type_info
3181 // structs in the chain down to the abi::__class_type_info for the
3182 // incomplete class type must be prevented from resolving to the
3183 // corresponding type_info structs for the complete class type, possibly
3184 // by making them local static objects. Finally, a dummy class RTTI is
3185 // generated for the incomplete type that will not resolve to the final
3186 // complete class RTTI (because the latter need not exist), possibly by
3187 // making it a local static object.
3188 if (ContainsIncompleteClassType(Ty))
Richard Smithbbb26552018-05-21 20:10:54 +00003189 return llvm::GlobalValue::InternalLinkage;
3190
3191 switch (Ty->getLinkage()) {
3192 case NoLinkage:
3193 case InternalLinkage:
3194 case UniqueExternalLinkage:
3195 return llvm::GlobalValue::InternalLinkage;
3196
3197 case VisibleNoLinkage:
3198 case ModuleInternalLinkage:
3199 case ModuleLinkage:
3200 case ExternalLinkage:
3201 // RTTI is not enabled, which means that this type info struct is going
3202 // to be used for exception handling. Give it linkonce_odr linkage.
3203 if (!CGM.getLangOpts().RTTI)
3204 return llvm::GlobalValue::LinkOnceODRLinkage;
3205
3206 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
3207 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
3208 if (RD->hasAttr<WeakAttr>())
3209 return llvm::GlobalValue::WeakODRLinkage;
3210 if (CGM.getTriple().isWindowsItaniumEnvironment())
3211 if (RD->hasAttr<DLLImportAttr>() &&
3212 ShouldUseExternalRTTIDescriptor(CGM, Ty))
3213 return llvm::GlobalValue::ExternalLinkage;
3214 // MinGW always uses LinkOnceODRLinkage for type info.
3215 if (RD->isDynamicClass() &&
3216 !CGM.getContext()
3217 .getTargetInfo()
3218 .getTriple()
3219 .isWindowsGNUEnvironment())
3220 return CGM.getVTableLinkage(RD);
3221 }
3222
3223 return llvm::GlobalValue::LinkOnceODRLinkage;
3224 }
3225
3226 llvm_unreachable("Invalid linkage!");
David Majnemere2cb8d12014-07-07 06:20:47 +00003227}
3228
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003229llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003230 // We want to operate on the canonical type.
Yaron Kerenebd14262016-03-16 12:14:43 +00003231 Ty = Ty.getCanonicalType();
David Majnemere2cb8d12014-07-07 06:20:47 +00003232
3233 // Check if we've already emitted an RTTI descriptor for this type.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00003234 SmallString<256> Name;
3235 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00003236 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00003237
3238 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
3239 if (OldGV && !OldGV->isDeclaration()) {
3240 assert(!OldGV->hasAvailableExternallyLinkage() &&
3241 "available_externally typeinfos not yet implemented");
3242
3243 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
3244 }
3245
3246 // Check if there is already an external RTTI descriptor for this type.
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003247 if (IsStandardLibraryRTTIDescriptor(Ty) ||
3248 ShouldUseExternalRTTIDescriptor(CGM, Ty))
David Majnemere2cb8d12014-07-07 06:20:47 +00003249 return GetAddrOfExternalRTTIDescriptor(Ty);
3250
3251 // Emit the standard library with external linkage.
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003252 llvm::GlobalVariable::LinkageTypes Linkage = getTypeInfoLinkage(CGM, Ty);
Richard Smithbbb26552018-05-21 20:10:54 +00003253
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003254 // Give the type_info object and name the formal visibility of the
3255 // type itself.
3256 llvm::GlobalValue::VisibilityTypes llvmVisibility;
3257 if (llvm::GlobalValue::isLocalLinkage(Linkage))
3258 // If the linkage is local, only default visibility makes sense.
3259 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
3260 else if (CXXABI.classifyRTTIUniqueness(Ty, Linkage) ==
3261 ItaniumCXXABI::RUK_NonUniqueHidden)
3262 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
3263 else
3264 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
3265
3266 llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass =
3267 llvm::GlobalValue::DefaultStorageClass;
3268 if (CGM.getTriple().isWindowsItaniumEnvironment()) {
3269 auto RD = Ty->getAsCXXRecordDecl();
3270 if (RD && RD->hasAttr<DLLExportAttr>())
3271 DLLStorageClass = llvm::GlobalValue::DLLExportStorageClass;
3272 }
3273
3274 return BuildTypeInfo(Ty, Linkage, llvmVisibility, DLLStorageClass);
3275}
3276
3277llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(
3278 QualType Ty,
3279 llvm::GlobalVariable::LinkageTypes Linkage,
3280 llvm::GlobalValue::VisibilityTypes Visibility,
3281 llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003282 // Add the vtable pointer.
3283 BuildVTablePointer(cast<Type>(Ty));
3284
3285 // And the name.
Richard Smithbbb26552018-05-21 20:10:54 +00003286 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
David Majnemere2cb8d12014-07-07 06:20:47 +00003287 llvm::Constant *TypeNameField;
3288
3289 // If we're supposed to demote the visibility, be sure to set a flag
3290 // to use a string comparison for type_info comparisons.
3291 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
Richard Smithbbb26552018-05-21 20:10:54 +00003292 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
David Majnemere2cb8d12014-07-07 06:20:47 +00003293 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
3294 // The flag is the sign bit, which on ARM64 is defined to be clear
3295 // for global pointers. This is very ARM64-specific.
3296 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
3297 llvm::Constant *flag =
3298 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
3299 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
3300 TypeNameField =
3301 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
3302 } else {
3303 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
3304 }
3305 Fields.push_back(TypeNameField);
3306
3307 switch (Ty->getTypeClass()) {
3308#define TYPE(Class, Base)
3309#define ABSTRACT_TYPE(Class, Base)
3310#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3311#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3312#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3313#include "clang/AST/TypeNodes.def"
3314 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
3315
3316 // GCC treats vector types as fundamental types.
3317 case Type::Builtin:
3318 case Type::Vector:
3319 case Type::ExtVector:
3320 case Type::Complex:
3321 case Type::BlockPointer:
3322 // Itanium C++ ABI 2.9.5p4:
3323 // abi::__fundamental_type_info adds no data members to std::type_info.
3324 break;
3325
3326 case Type::LValueReference:
3327 case Type::RValueReference:
3328 llvm_unreachable("References shouldn't get here");
3329
3330 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00003331 case Type::DeducedTemplateSpecialization:
3332 llvm_unreachable("Undeduced type shouldn't get here");
David Majnemere2cb8d12014-07-07 06:20:47 +00003333
Xiuli Pan9c14e282016-01-09 12:53:17 +00003334 case Type::Pipe:
3335 llvm_unreachable("Pipe type shouldn't get here");
3336
David Majnemere2cb8d12014-07-07 06:20:47 +00003337 case Type::ConstantArray:
3338 case Type::IncompleteArray:
3339 case Type::VariableArray:
3340 // Itanium C++ ABI 2.9.5p5:
3341 // abi::__array_type_info adds no data members to std::type_info.
3342 break;
3343
3344 case Type::FunctionNoProto:
Richard Smithb17d6fa2016-12-01 03:04:07 +00003345 case Type::FunctionProto:
David Majnemere2cb8d12014-07-07 06:20:47 +00003346 // Itanium C++ ABI 2.9.5p5:
3347 // abi::__function_type_info adds no data members to std::type_info.
3348 break;
3349
3350 case Type::Enum:
3351 // Itanium C++ ABI 2.9.5p5:
3352 // abi::__enum_type_info adds no data members to std::type_info.
3353 break;
3354
3355 case Type::Record: {
3356 const CXXRecordDecl *RD =
3357 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
3358 if (!RD->hasDefinition() || !RD->getNumBases()) {
3359 // We don't need to emit any fields.
3360 break;
3361 }
3362
3363 if (CanUseSingleInheritance(RD))
3364 BuildSIClassTypeInfo(RD);
3365 else
3366 BuildVMIClassTypeInfo(RD);
3367
3368 break;
3369 }
3370
3371 case Type::ObjCObject:
3372 case Type::ObjCInterface:
3373 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
3374 break;
3375
3376 case Type::ObjCObjectPointer:
3377 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
3378 break;
3379
3380 case Type::Pointer:
3381 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
3382 break;
3383
3384 case Type::MemberPointer:
3385 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
3386 break;
3387
3388 case Type::Atomic:
3389 // No fields, at least for the moment.
3390 break;
3391 }
3392
3393 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
3394
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003395 SmallString<256> Name;
3396 llvm::raw_svector_ostream Out(Name);
3397 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
Rafael Espindolacb92c192015-01-15 23:18:01 +00003398 llvm::Module &M = CGM.getModule();
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003399 llvm::GlobalVariable *OldGV = M.getNamedGlobal(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00003400 llvm::GlobalVariable *GV =
Rafael Espindolacb92c192015-01-15 23:18:01 +00003401 new llvm::GlobalVariable(M, Init->getType(),
Rui Ueyama49a3ad22019-07-16 04:46:31 +00003402 /*isConstant=*/true, Linkage, Init, Name);
Rafael Espindolacb92c192015-01-15 23:18:01 +00003403
David Majnemere2cb8d12014-07-07 06:20:47 +00003404 // If there's already an old global variable, replace it with the new one.
3405 if (OldGV) {
3406 GV->takeName(OldGV);
3407 llvm::Constant *NewPtr =
3408 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3409 OldGV->replaceAllUsesWith(NewPtr);
3410 OldGV->eraseFromParent();
3411 }
3412
Yaron Keren04da2382015-07-29 15:42:28 +00003413 if (CGM.supportsCOMDAT() && GV->isWeakForLinker())
3414 GV->setComdat(M.getOrInsertComdat(GV->getName()));
3415
David Greenbe0c5b62018-09-12 14:09:06 +00003416 CharUnits Align =
3417 CGM.getContext().toCharUnitsFromBits(CGM.getTarget().getPointerAlign(0));
3418 GV->setAlignment(Align.getQuantity());
3419
David Majnemere2cb8d12014-07-07 06:20:47 +00003420 // The Itanium ABI specifies that type_info objects must be globally
3421 // unique, with one exception: if the type is an incomplete class
3422 // type or a (possibly indirect) pointer to one. That exception
3423 // affects the general case of comparing type_info objects produced
3424 // by the typeid operator, which is why the comparison operators on
3425 // std::type_info generally use the type_info name pointers instead
3426 // of the object addresses. However, the language's built-in uses
3427 // of RTTI generally require class types to be complete, even when
3428 // manipulating pointers to those class types. This allows the
3429 // implementation of dynamic_cast to rely on address equality tests,
3430 // which is much faster.
3431
3432 // All of this is to say that it's important that both the type_info
3433 // object and the type_info name be uniqued when weakly emitted.
3434
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003435 TypeName->setVisibility(Visibility);
Rafael Espindola3dd49812018-02-23 00:22:15 +00003436 CGM.setDSOLocal(TypeName);
Rafael Espindola699f5d62018-02-07 22:15:33 +00003437
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003438 GV->setVisibility(Visibility);
Rafael Espindola3dd49812018-02-23 00:22:15 +00003439 CGM.setDSOLocal(GV);
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003440
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003441 TypeName->setDLLStorageClass(DLLStorageClass);
3442 GV->setDLLStorageClass(DLLStorageClass);
David Majnemere2cb8d12014-07-07 06:20:47 +00003443
Peter Collingbournee08e68d2019-06-07 19:10:08 +00003444 TypeName->setPartition(CGM.getCodeGenOpts().SymbolPartition);
3445 GV->setPartition(CGM.getCodeGenOpts().SymbolPartition);
3446
David Majnemere2cb8d12014-07-07 06:20:47 +00003447 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
3448}
3449
David Majnemere2cb8d12014-07-07 06:20:47 +00003450/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
3451/// for the given Objective-C object type.
3452void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
3453 // Drop qualifiers.
3454 const Type *T = OT->getBaseType().getTypePtr();
3455 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
3456
3457 // The builtin types are abi::__class_type_infos and don't require
3458 // extra fields.
3459 if (isa<BuiltinType>(T)) return;
3460
3461 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
3462 ObjCInterfaceDecl *Super = Class->getSuperClass();
3463
3464 // Root classes are also __class_type_info.
3465 if (!Super) return;
3466
3467 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
3468
3469 // Everything else is single inheritance.
3470 llvm::Constant *BaseTypeInfo =
3471 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
3472 Fields.push_back(BaseTypeInfo);
3473}
3474
3475/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
3476/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
3477void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
3478 // Itanium C++ ABI 2.9.5p6b:
3479 // It adds to abi::__class_type_info a single member pointing to the
3480 // type_info structure for the base type,
3481 llvm::Constant *BaseTypeInfo =
3482 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
3483 Fields.push_back(BaseTypeInfo);
3484}
3485
3486namespace {
3487 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
3488 /// a class hierarchy.
3489 struct SeenBases {
3490 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
3491 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
3492 };
3493}
3494
3495/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
3496/// abi::__vmi_class_type_info.
3497///
3498static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
3499 SeenBases &Bases) {
3500
3501 unsigned Flags = 0;
3502
3503 const CXXRecordDecl *BaseDecl =
3504 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
3505
3506 if (Base->isVirtual()) {
3507 // Mark the virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003508 if (!Bases.VirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003509 // If this virtual base has been seen before, then the class is diamond
3510 // shaped.
3511 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
3512 } else {
3513 if (Bases.NonVirtualBases.count(BaseDecl))
3514 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3515 }
3516 } else {
3517 // Mark the non-virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003518 if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003519 // If this non-virtual base has been seen before, then the class has non-
3520 // diamond shaped repeated inheritance.
3521 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3522 } else {
3523 if (Bases.VirtualBases.count(BaseDecl))
3524 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3525 }
3526 }
3527
3528 // Walk all bases.
3529 for (const auto &I : BaseDecl->bases())
3530 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3531
3532 return Flags;
3533}
3534
3535static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
3536 unsigned Flags = 0;
3537 SeenBases Bases;
3538
3539 // Walk all bases.
3540 for (const auto &I : RD->bases())
3541 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3542
3543 return Flags;
3544}
3545
3546/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
3547/// classes with bases that do not satisfy the abi::__si_class_type_info
3548/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
3549void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
3550 llvm::Type *UnsignedIntLTy =
3551 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3552
3553 // Itanium C++ ABI 2.9.5p6c:
3554 // __flags is a word with flags describing details about the class
3555 // structure, which may be referenced by using the __flags_masks
3556 // enumeration. These flags refer to both direct and indirect bases.
3557 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
3558 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3559
3560 // Itanium C++ ABI 2.9.5p6c:
3561 // __base_count is a word with the number of direct proper base class
3562 // descriptions that follow.
3563 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
3564
3565 if (!RD->getNumBases())
3566 return;
3567
David Majnemere2cb8d12014-07-07 06:20:47 +00003568 // Now add the base class descriptions.
3569
3570 // Itanium C++ ABI 2.9.5p6c:
3571 // __base_info[] is an array of base class descriptions -- one for every
3572 // direct proper base. Each description is of the type:
3573 //
3574 // struct abi::__base_class_type_info {
3575 // public:
3576 // const __class_type_info *__base_type;
3577 // long __offset_flags;
3578 //
3579 // enum __offset_flags_masks {
3580 // __virtual_mask = 0x1,
3581 // __public_mask = 0x2,
3582 // __offset_shift = 8
3583 // };
3584 // };
Reid Klecknerd8b04662016-08-25 22:16:30 +00003585
3586 // If we're in mingw and 'long' isn't wide enough for a pointer, use 'long
3587 // long' instead of 'long' for __offset_flags. libstdc++abi uses long long on
3588 // LLP64 platforms.
3589 // FIXME: Consider updating libc++abi to match, and extend this logic to all
3590 // LLP64 platforms.
3591 QualType OffsetFlagsTy = CGM.getContext().LongTy;
3592 const TargetInfo &TI = CGM.getContext().getTargetInfo();
3593 if (TI.getTriple().isOSCygMing() && TI.getPointerWidth(0) > TI.getLongWidth())
3594 OffsetFlagsTy = CGM.getContext().LongLongTy;
3595 llvm::Type *OffsetFlagsLTy =
3596 CGM.getTypes().ConvertType(OffsetFlagsTy);
3597
David Majnemere2cb8d12014-07-07 06:20:47 +00003598 for (const auto &Base : RD->bases()) {
3599 // The __base_type member points to the RTTI for the base type.
3600 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
3601
3602 const CXXRecordDecl *BaseDecl =
3603 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
3604
3605 int64_t OffsetFlags = 0;
3606
3607 // All but the lower 8 bits of __offset_flags are a signed offset.
3608 // For a non-virtual base, this is the offset in the object of the base
3609 // subobject. For a virtual base, this is the offset in the virtual table of
3610 // the virtual base offset for the virtual base referenced (negative).
3611 CharUnits Offset;
3612 if (Base.isVirtual())
3613 Offset =
3614 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
3615 else {
3616 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
3617 Offset = Layout.getBaseClassOffset(BaseDecl);
3618 };
3619
3620 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
3621
3622 // The low-order byte of __offset_flags contains flags, as given by the
3623 // masks from the enumeration __offset_flags_masks.
3624 if (Base.isVirtual())
3625 OffsetFlags |= BCTI_Virtual;
3626 if (Base.getAccessSpecifier() == AS_public)
3627 OffsetFlags |= BCTI_Public;
3628
Reid Klecknerd8b04662016-08-25 22:16:30 +00003629 Fields.push_back(llvm::ConstantInt::get(OffsetFlagsLTy, OffsetFlags));
David Majnemere2cb8d12014-07-07 06:20:47 +00003630 }
3631}
3632
Richard Smitha7d93782016-12-01 03:32:42 +00003633/// Compute the flags for a __pbase_type_info, and remove the corresponding
3634/// pieces from \p Type.
3635static unsigned extractPBaseFlags(ASTContext &Ctx, QualType &Type) {
3636 unsigned Flags = 0;
David Majnemere2cb8d12014-07-07 06:20:47 +00003637
Richard Smitha7d93782016-12-01 03:32:42 +00003638 if (Type.isConstQualified())
3639 Flags |= ItaniumRTTIBuilder::PTI_Const;
3640 if (Type.isVolatileQualified())
3641 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
3642 if (Type.isRestrictQualified())
3643 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
3644 Type = Type.getUnqualifiedType();
David Majnemere2cb8d12014-07-07 06:20:47 +00003645
3646 // Itanium C++ ABI 2.9.5p7:
3647 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3648 // incomplete class type, the incomplete target type flag is set.
Richard Smitha7d93782016-12-01 03:32:42 +00003649 if (ContainsIncompleteClassType(Type))
3650 Flags |= ItaniumRTTIBuilder::PTI_Incomplete;
3651
3652 if (auto *Proto = Type->getAs<FunctionProtoType>()) {
Richard Smitheaf11ad2018-05-03 03:58:32 +00003653 if (Proto->isNothrow()) {
Richard Smitha7d93782016-12-01 03:32:42 +00003654 Flags |= ItaniumRTTIBuilder::PTI_Noexcept;
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00003655 Type = Ctx.getFunctionTypeWithExceptionSpec(Type, EST_None);
Richard Smitha7d93782016-12-01 03:32:42 +00003656 }
3657 }
3658
3659 return Flags;
3660}
3661
3662/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
3663/// used for pointer types.
3664void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
3665 // Itanium C++ ABI 2.9.5p7:
3666 // __flags is a flag word describing the cv-qualification and other
3667 // attributes of the type pointed to
3668 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003669
3670 llvm::Type *UnsignedIntLTy =
3671 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3672 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3673
3674 // Itanium C++ ABI 2.9.5p7:
3675 // __pointee is a pointer to the std::type_info derivation for the
3676 // unqualified type being pointed to.
3677 llvm::Constant *PointeeTypeInfo =
Richard Smitha7d93782016-12-01 03:32:42 +00003678 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003679 Fields.push_back(PointeeTypeInfo);
3680}
3681
3682/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
3683/// struct, used for member pointer types.
3684void
3685ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
3686 QualType PointeeTy = Ty->getPointeeType();
3687
David Majnemere2cb8d12014-07-07 06:20:47 +00003688 // Itanium C++ ABI 2.9.5p7:
3689 // __flags is a flag word describing the cv-qualification and other
3690 // attributes of the type pointed to.
Richard Smitha7d93782016-12-01 03:32:42 +00003691 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003692
3693 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
David Majnemere2cb8d12014-07-07 06:20:47 +00003694 if (IsIncompleteClassType(ClassType))
3695 Flags |= PTI_ContainingClassIncomplete;
3696
3697 llvm::Type *UnsignedIntLTy =
3698 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3699 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3700
3701 // Itanium C++ ABI 2.9.5p7:
3702 // __pointee is a pointer to the std::type_info derivation for the
3703 // unqualified type being pointed to.
3704 llvm::Constant *PointeeTypeInfo =
Richard Smitha7d93782016-12-01 03:32:42 +00003705 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003706 Fields.push_back(PointeeTypeInfo);
3707
3708 // Itanium C++ ABI 2.9.5p9:
3709 // __context is a pointer to an abi::__class_type_info corresponding to the
3710 // class type containing the member pointed to
3711 // (e.g., the "A" in "int A::*").
3712 Fields.push_back(
3713 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
3714}
3715
David Majnemer443250f2015-03-17 20:35:00 +00003716llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003717 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
3718}
3719
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003720void ItaniumCXXABI::EmitFundamentalRTTIDescriptors(const CXXRecordDecl *RD) {
Richard Smith4a382012016-02-03 01:32:42 +00003721 // Types added here must also be added to TypeInfoIsInStandardLibrary.
David Majnemere2cb8d12014-07-07 06:20:47 +00003722 QualType FundamentalTypes[] = {
3723 getContext().VoidTy, getContext().NullPtrTy,
3724 getContext().BoolTy, getContext().WCharTy,
3725 getContext().CharTy, getContext().UnsignedCharTy,
3726 getContext().SignedCharTy, getContext().ShortTy,
3727 getContext().UnsignedShortTy, getContext().IntTy,
3728 getContext().UnsignedIntTy, getContext().LongTy,
3729 getContext().UnsignedLongTy, getContext().LongLongTy,
Richard Smith4a382012016-02-03 01:32:42 +00003730 getContext().UnsignedLongLongTy, getContext().Int128Ty,
3731 getContext().UnsignedInt128Ty, getContext().HalfTy,
David Majnemere2cb8d12014-07-07 06:20:47 +00003732 getContext().FloatTy, getContext().DoubleTy,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00003733 getContext().LongDoubleTy, getContext().Float128Ty,
Richard Smith3a8244d2018-05-01 05:02:45 +00003734 getContext().Char8Ty, getContext().Char16Ty,
3735 getContext().Char32Ty
David Majnemere2cb8d12014-07-07 06:20:47 +00003736 };
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003737 llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass =
3738 RD->hasAttr<DLLExportAttr>()
3739 ? llvm::GlobalValue::DLLExportStorageClass
3740 : llvm::GlobalValue::DefaultStorageClass;
3741 llvm::GlobalValue::VisibilityTypes Visibility =
3742 CodeGenModule::GetLLVMVisibility(RD->getVisibility());
3743 for (const QualType &FundamentalType : FundamentalTypes) {
3744 QualType PointerType = getContext().getPointerType(FundamentalType);
3745 QualType PointerTypeConst = getContext().getPointerType(
3746 FundamentalType.withConst());
3747 for (QualType Type : {FundamentalType, PointerType, PointerTypeConst})
3748 ItaniumRTTIBuilder(*this).BuildTypeInfo(
3749 Type, llvm::GlobalValue::ExternalLinkage,
3750 Visibility, DLLStorageClass);
3751 }
David Majnemere2cb8d12014-07-07 06:20:47 +00003752}
3753
3754/// What sort of uniqueness rules should we use for the RTTI for the
3755/// given type?
3756ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
3757 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
3758 if (shouldRTTIBeUnique())
3759 return RUK_Unique;
3760
3761 // It's only necessary for linkonce_odr or weak_odr linkage.
3762 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
3763 Linkage != llvm::GlobalValue::WeakODRLinkage)
3764 return RUK_Unique;
3765
3766 // It's only necessary with default visibility.
3767 if (CanTy->getVisibility() != DefaultVisibility)
3768 return RUK_Unique;
3769
3770 // If we're not required to publish this symbol, hide it.
3771 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3772 return RUK_NonUniqueHidden;
3773
3774 // If we're required to publish this symbol, as we might be under an
3775 // explicit instantiation, leave it with default visibility but
3776 // enable string-comparisons.
3777 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
3778 return RUK_NonUniqueVisible;
3779}
Rafael Espindola91f68b42014-09-15 19:20:10 +00003780
Rafael Espindola1e4df922014-09-16 15:18:21 +00003781// Find out how to codegen the complete destructor and constructor
3782namespace {
3783enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
3784}
3785static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
3786 const CXXMethodDecl *MD) {
3787 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
3788 return StructorCodegen::Emit;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003789
Rafael Espindola1e4df922014-09-16 15:18:21 +00003790 // The complete and base structors are not equivalent if there are any virtual
3791 // bases, so emit separate functions.
3792 if (MD->getParent()->getNumVBases())
3793 return StructorCodegen::Emit;
3794
3795 GlobalDecl AliasDecl;
3796 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3797 AliasDecl = GlobalDecl(DD, Dtor_Complete);
3798 } else {
3799 const auto *CD = cast<CXXConstructorDecl>(MD);
3800 AliasDecl = GlobalDecl(CD, Ctor_Complete);
3801 }
3802 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3803
Chandler Carruth1f82d9b2018-07-29 03:05:07 +00003804 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
3805 return StructorCodegen::RAUW;
Rafael Espindola1e4df922014-09-16 15:18:21 +00003806
Pavel Labathc370f262018-05-14 11:35:44 +00003807 // FIXME: Should we allow available_externally aliases?
Chandler Carruth1f82d9b2018-07-29 03:05:07 +00003808 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
3809 return StructorCodegen::RAUW;
Rafael Espindola1e4df922014-09-16 15:18:21 +00003810
Rafael Espindola0806f982014-09-16 20:19:43 +00003811 if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
Dan Gohman839f2152017-01-17 21:46:38 +00003812 // Only ELF and wasm support COMDATs with arbitrary names (C5/D5).
3813 if (CGM.getTarget().getTriple().isOSBinFormatELF() ||
3814 CGM.getTarget().getTriple().isOSBinFormatWasm())
Rafael Espindola0806f982014-09-16 20:19:43 +00003815 return StructorCodegen::COMDAT;
3816 return StructorCodegen::Emit;
3817 }
Rafael Espindola1e4df922014-09-16 15:18:21 +00003818
3819 return StructorCodegen::Alias;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003820}
3821
Rafael Espindola1e4df922014-09-16 15:18:21 +00003822static void emitConstructorDestructorAlias(CodeGenModule &CGM,
3823 GlobalDecl AliasDecl,
3824 GlobalDecl TargetDecl) {
3825 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3826
3827 StringRef MangledName = CGM.getMangledName(AliasDecl);
3828 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
3829 if (Entry && !Entry->isDeclaration())
3830 return;
3831
3832 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
Rafael Espindola1e4df922014-09-16 15:18:21 +00003833
3834 // Create the alias with no name.
David Blaikie2a791d72015-09-14 18:38:22 +00003835 auto *Alias = llvm::GlobalAlias::create(Linkage, "", Aliasee);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003836
Peter Collingbourned914fd22018-06-18 20:58:54 +00003837 // Constructors and destructors are always unnamed_addr.
3838 Alias->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3839
Rafael Espindola1e4df922014-09-16 15:18:21 +00003840 // Switch any previous uses to the alias.
3841 if (Entry) {
NAKAMURA Takumie9621042015-09-15 01:39:27 +00003842 assert(Entry->getType() == Aliasee->getType() &&
Rafael Espindola1e4df922014-09-16 15:18:21 +00003843 "declaration exists with different type");
3844 Alias->takeName(Entry);
3845 Entry->replaceAllUsesWith(Alias);
3846 Entry->eraseFromParent();
3847 } else {
3848 Alias->setName(MangledName);
3849 }
3850
3851 // Finally, set up the alias with its proper name and attributes.
Rafael Espindolab7350042018-03-01 00:35:47 +00003852 CGM.SetCommonAttributes(AliasDecl, Alias);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003853}
3854
Peter Collingbourned1c5b282019-03-22 23:05:10 +00003855void ItaniumCXXABI::emitCXXStructor(GlobalDecl GD) {
3856 auto *MD = cast<CXXMethodDecl>(GD.getDecl());
Rafael Espindola1e4df922014-09-16 15:18:21 +00003857 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
3858 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
3859
3860 StructorCodegen CGType = getCodegenToUse(CGM, MD);
3861
Peter Collingbourned1c5b282019-03-22 23:05:10 +00003862 if (CD ? GD.getCtorType() == Ctor_Complete
3863 : GD.getDtorType() == Dtor_Complete) {
Rafael Espindola1e4df922014-09-16 15:18:21 +00003864 GlobalDecl BaseDecl;
Peter Collingbourned1c5b282019-03-22 23:05:10 +00003865 if (CD)
3866 BaseDecl = GD.getWithCtorType(Ctor_Base);
3867 else
3868 BaseDecl = GD.getWithDtorType(Dtor_Base);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003869
3870 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
Peter Collingbourned1c5b282019-03-22 23:05:10 +00003871 emitConstructorDestructorAlias(CGM, GD, BaseDecl);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003872 return;
3873 }
3874
3875 if (CGType == StructorCodegen::RAUW) {
Peter Collingbourned1c5b282019-03-22 23:05:10 +00003876 StringRef MangledName = CGM.getMangledName(GD);
Andrey Bokhankocab58582015-08-31 13:20:44 +00003877 auto *Aliasee = CGM.GetAddrOfGlobal(BaseDecl);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003878 CGM.addReplacement(MangledName, Aliasee);
3879 return;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003880 }
3881 }
3882
3883 // The base destructor is equivalent to the base destructor of its
3884 // base class if there is exactly one non-virtual base class with a
3885 // non-trivial destructor, there are no fields with a non-trivial
3886 // destructor, and the body of the destructor is trivial.
Peter Collingbourned1c5b282019-03-22 23:05:10 +00003887 if (DD && GD.getDtorType() == Dtor_Base &&
3888 CGType != StructorCodegen::COMDAT &&
Rafael Espindola1e4df922014-09-16 15:18:21 +00003889 !CGM.TryEmitBaseDestructorAsAlias(DD))
Rafael Espindola91f68b42014-09-15 19:20:10 +00003890 return;
3891
Richard Smith5b349582017-10-13 01:55:36 +00003892 // FIXME: The deleting destructor is equivalent to the selected operator
3893 // delete if:
3894 // * either the delete is a destroying operator delete or the destructor
3895 // would be trivial if it weren't virtual,
3896 // * the conversion from the 'this' parameter to the first parameter of the
3897 // destructor is equivalent to a bitcast,
3898 // * the destructor does not have an implicit "this" return, and
3899 // * the operator delete has the same calling convention and IR function type
3900 // as the destructor.
3901 // In such cases we should try to emit the deleting dtor as an alias to the
3902 // selected 'operator delete'.
3903
Peter Collingbourned1c5b282019-03-22 23:05:10 +00003904 llvm::Function *Fn = CGM.codegenCXXStructor(GD);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003905
Rafael Espindola1e4df922014-09-16 15:18:21 +00003906 if (CGType == StructorCodegen::COMDAT) {
3907 SmallString<256> Buffer;
3908 llvm::raw_svector_ostream Out(Buffer);
3909 if (DD)
3910 getMangleContext().mangleCXXDtorComdat(DD, Out);
3911 else
3912 getMangleContext().mangleCXXCtorComdat(CD, Out);
3913 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
3914 Fn->setComdat(C);
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003915 } else {
3916 CGM.maybeSetTrivialComdat(*MD, *Fn);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003917 }
Rafael Espindola91f68b42014-09-15 19:20:10 +00003918}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003919
James Y Knight9871db02019-02-05 16:42:33 +00003920static llvm::FunctionCallee getBeginCatchFn(CodeGenModule &CGM) {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003921 // void *__cxa_begin_catch(void*);
3922 llvm::FunctionType *FTy = llvm::FunctionType::get(
Rui Ueyama49a3ad22019-07-16 04:46:31 +00003923 CGM.Int8PtrTy, CGM.Int8PtrTy, /*isVarArg=*/false);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003924
3925 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
3926}
3927
James Y Knight9871db02019-02-05 16:42:33 +00003928static llvm::FunctionCallee getEndCatchFn(CodeGenModule &CGM) {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003929 // void __cxa_end_catch();
3930 llvm::FunctionType *FTy =
Rui Ueyama49a3ad22019-07-16 04:46:31 +00003931 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003932
3933 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
3934}
3935
James Y Knight9871db02019-02-05 16:42:33 +00003936static llvm::FunctionCallee getGetExceptionPtrFn(CodeGenModule &CGM) {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003937 // void *__cxa_get_exception_ptr(void*);
3938 llvm::FunctionType *FTy = llvm::FunctionType::get(
Rui Ueyama49a3ad22019-07-16 04:46:31 +00003939 CGM.Int8PtrTy, CGM.Int8PtrTy, /*isVarArg=*/false);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003940
3941 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
3942}
3943
3944namespace {
3945 /// A cleanup to call __cxa_end_catch. In many cases, the caught
3946 /// exception type lets us state definitively that the thrown exception
3947 /// type does not have a destructor. In particular:
3948 /// - Catch-alls tell us nothing, so we have to conservatively
3949 /// assume that the thrown exception might have a destructor.
3950 /// - Catches by reference behave according to their base types.
3951 /// - Catches of non-record types will only trigger for exceptions
3952 /// of non-record types, which never have destructors.
3953 /// - Catches of record types can trigger for arbitrary subclasses
3954 /// of the caught type, so we have to assume the actual thrown
3955 /// exception type might have a throwing destructor, even if the
3956 /// caught type's destructor is trivial or nothrow.
David Blaikie7e70d682015-08-18 22:40:54 +00003957 struct CallEndCatch final : EHScopeStack::Cleanup {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003958 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
3959 bool MightThrow;
3960
3961 void Emit(CodeGenFunction &CGF, Flags flags) override {
3962 if (!MightThrow) {
3963 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
3964 return;
3965 }
3966
3967 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
3968 }
3969 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003970}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003971
3972/// Emits a call to __cxa_begin_catch and enters a cleanup to call
3973/// __cxa_end_catch.
3974///
3975/// \param EndMightThrow - true if __cxa_end_catch might throw
3976static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
3977 llvm::Value *Exn,
3978 bool EndMightThrow) {
3979 llvm::CallInst *call =
3980 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
3981
3982 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
3983
3984 return call;
3985}
3986
3987/// A "special initializer" callback for initializing a catch
3988/// parameter during catch initialization.
3989static void InitCatchParam(CodeGenFunction &CGF,
3990 const VarDecl &CatchParam,
John McCall7f416cc2015-09-08 08:05:57 +00003991 Address ParamAddr,
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003992 SourceLocation Loc) {
3993 // Load the exception from where the landing pad saved it.
3994 llvm::Value *Exn = CGF.getExceptionFromSlot();
3995
3996 CanQualType CatchType =
3997 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
3998 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
3999
4000 // If we're catching by reference, we can just cast the object
4001 // pointer to the appropriate pointer.
4002 if (isa<ReferenceType>(CatchType)) {
4003 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
4004 bool EndCatchMightThrow = CaughtType->isRecordType();
4005
4006 // __cxa_begin_catch returns the adjusted object pointer.
4007 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
4008
4009 // We have no way to tell the personality function that we're
4010 // catching by reference, so if we're catching a pointer,
4011 // __cxa_begin_catch will actually return that pointer by value.
4012 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
4013 QualType PointeeType = PT->getPointeeType();
4014
4015 // When catching by reference, generally we should just ignore
4016 // this by-value pointer and use the exception object instead.
4017 if (!PointeeType->isRecordType()) {
4018
4019 // Exn points to the struct _Unwind_Exception header, which
4020 // we have to skip past in order to reach the exception data.
4021 unsigned HeaderSize =
4022 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
4023 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
4024
4025 // However, if we're catching a pointer-to-record type that won't
4026 // work, because the personality function might have adjusted
4027 // the pointer. There's actually no way for us to fully satisfy
4028 // the language/ABI contract here: we can't use Exn because it
4029 // might have the wrong adjustment, but we can't use the by-value
4030 // pointer because it's off by a level of abstraction.
4031 //
4032 // The current solution is to dump the adjusted pointer into an
4033 // alloca, which breaks language semantics (because changing the
4034 // pointer doesn't change the exception) but at least works.
4035 // The better solution would be to filter out non-exact matches
4036 // and rethrow them, but this is tricky because the rethrow
4037 // really needs to be catchable by other sites at this landing
4038 // pad. The best solution is to fix the personality function.
4039 } else {
4040 // Pull the pointer for the reference type off.
4041 llvm::Type *PtrTy =
4042 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
4043
4044 // Create the temporary and write the adjusted pointer into it.
John McCall7f416cc2015-09-08 08:05:57 +00004045 Address ExnPtrTmp =
4046 CGF.CreateTempAlloca(PtrTy, CGF.getPointerAlign(), "exn.byref.tmp");
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004047 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
4048 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
4049
4050 // Bind the reference to the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00004051 AdjustedExn = ExnPtrTmp.getPointer();
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004052 }
4053 }
4054
4055 llvm::Value *ExnCast =
4056 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
4057 CGF.Builder.CreateStore(ExnCast, ParamAddr);
4058 return;
4059 }
4060
4061 // Scalars and complexes.
4062 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
4063 if (TEK != TEK_Aggregate) {
4064 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
4065
4066 // If the catch type is a pointer type, __cxa_begin_catch returns
4067 // the pointer by value.
4068 if (CatchType->hasPointerRepresentation()) {
4069 llvm::Value *CastExn =
4070 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
4071
4072 switch (CatchType.getQualifiers().getObjCLifetime()) {
4073 case Qualifiers::OCL_Strong:
4074 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +00004075 LLVM_FALLTHROUGH;
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004076
4077 case Qualifiers::OCL_None:
4078 case Qualifiers::OCL_ExplicitNone:
4079 case Qualifiers::OCL_Autoreleasing:
4080 CGF.Builder.CreateStore(CastExn, ParamAddr);
4081 return;
4082
4083 case Qualifiers::OCL_Weak:
4084 CGF.EmitARCInitWeak(ParamAddr, CastExn);
4085 return;
4086 }
4087 llvm_unreachable("bad ownership qualifier!");
4088 }
4089
4090 // Otherwise, it returns a pointer into the exception object.
4091
4092 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
4093 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
4094
4095 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
John McCall7f416cc2015-09-08 08:05:57 +00004096 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004097 switch (TEK) {
4098 case TEK_Complex:
4099 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
4100 /*init*/ true);
4101 return;
4102 case TEK_Scalar: {
4103 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
4104 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
4105 return;
4106 }
4107 case TEK_Aggregate:
4108 llvm_unreachable("evaluation kind filtered out!");
4109 }
4110 llvm_unreachable("bad evaluation kind");
4111 }
4112
4113 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
John McCall7f416cc2015-09-08 08:05:57 +00004114 auto catchRD = CatchType->getAsCXXRecordDecl();
4115 CharUnits caughtExnAlignment = CGF.CGM.getClassPointerAlignment(catchRD);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004116
4117 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
4118
4119 // Check for a copy expression. If we don't have a copy expression,
4120 // that means a trivial copy is okay.
4121 const Expr *copyExpr = CatchParam.getInit();
4122 if (!copyExpr) {
4123 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
John McCall7f416cc2015-09-08 08:05:57 +00004124 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
4125 caughtExnAlignment);
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00004126 LValue Dest = CGF.MakeAddrLValue(ParamAddr, CatchType);
4127 LValue Src = CGF.MakeAddrLValue(adjustedExn, CatchType);
Richard Smithe78fac52018-04-05 20:52:58 +00004128 CGF.EmitAggregateCopy(Dest, Src, CatchType, AggValueSlot::DoesNotOverlap);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004129 return;
4130 }
4131
4132 // We have to call __cxa_get_exception_ptr to get the adjusted
4133 // pointer before copying.
4134 llvm::CallInst *rawAdjustedExn =
4135 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
4136
4137 // Cast that to the appropriate type.
John McCall7f416cc2015-09-08 08:05:57 +00004138 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
4139 caughtExnAlignment);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004140
4141 // The copy expression is defined in terms of an OpaqueValueExpr.
4142 // Find it and map it to the adjusted expression.
4143 CodeGenFunction::OpaqueValueMapping
4144 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
4145 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
4146
4147 // Call the copy ctor in a terminate scope.
4148 CGF.EHStack.pushTerminate();
4149
4150 // Perform the copy construction.
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004151 CGF.EmitAggExpr(copyExpr,
John McCall7f416cc2015-09-08 08:05:57 +00004152 AggValueSlot::forAddr(ParamAddr, Qualifiers(),
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004153 AggValueSlot::IsNotDestructed,
4154 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00004155 AggValueSlot::IsNotAliased,
4156 AggValueSlot::DoesNotOverlap));
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004157
4158 // Leave the terminate scope.
4159 CGF.EHStack.popTerminate();
4160
4161 // Undo the opaque value mapping.
4162 opaque.pop();
4163
4164 // Finally we can call __cxa_begin_catch.
4165 CallBeginCatch(CGF, Exn, true);
4166}
4167
4168/// Begins a catch statement by initializing the catch variable and
4169/// calling __cxa_begin_catch.
4170void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF,
4171 const CXXCatchStmt *S) {
4172 // We have to be very careful with the ordering of cleanups here:
4173 // C++ [except.throw]p4:
4174 // The destruction [of the exception temporary] occurs
4175 // immediately after the destruction of the object declared in
4176 // the exception-declaration in the handler.
4177 //
4178 // So the precise ordering is:
4179 // 1. Construct catch variable.
4180 // 2. __cxa_begin_catch
4181 // 3. Enter __cxa_end_catch cleanup
4182 // 4. Enter dtor cleanup
4183 //
4184 // We do this by using a slightly abnormal initialization process.
4185 // Delegation sequence:
4186 // - ExitCXXTryStmt opens a RunCleanupsScope
4187 // - EmitAutoVarAlloca creates the variable and debug info
4188 // - InitCatchParam initializes the variable from the exception
4189 // - CallBeginCatch calls __cxa_begin_catch
4190 // - CallBeginCatch enters the __cxa_end_catch cleanup
4191 // - EmitAutoVarCleanups enters the variable destructor cleanup
4192 // - EmitCXXTryStmt emits the code for the catch body
4193 // - EmitCXXTryStmt close the RunCleanupsScope
4194
4195 VarDecl *CatchParam = S->getExceptionDecl();
4196 if (!CatchParam) {
4197 llvm::Value *Exn = CGF.getExceptionFromSlot();
4198 CallBeginCatch(CGF, Exn, true);
4199 return;
4200 }
4201
4202 // Emit the local.
4203 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004204 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getBeginLoc());
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004205 CGF.EmitAutoVarCleanups(var);
4206}
4207
4208/// Get or define the following function:
4209/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
4210/// This code is used only in C++.
James Y Knight9871db02019-02-05 16:42:33 +00004211static llvm::FunctionCallee getClangCallTerminateFn(CodeGenModule &CGM) {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004212 llvm::FunctionType *fnTy =
Rui Ueyama49a3ad22019-07-16 04:46:31 +00004213 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*isVarArg=*/false);
James Y Knight9871db02019-02-05 16:42:33 +00004214 llvm::FunctionCallee fnRef = CGM.CreateRuntimeFunction(
Rui Ueyama49a3ad22019-07-16 04:46:31 +00004215 fnTy, "__clang_call_terminate", llvm::AttributeList(), /*Local=*/true);
James Y Knight9871db02019-02-05 16:42:33 +00004216 llvm::Function *fn =
4217 cast<llvm::Function>(fnRef.getCallee()->stripPointerCasts());
4218 if (fn->empty()) {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004219 fn->setDoesNotThrow();
4220 fn->setDoesNotReturn();
4221
4222 // What we really want is to massively penalize inlining without
4223 // forbidding it completely. The difference between that and
4224 // 'noinline' is negligible.
4225 fn->addFnAttr(llvm::Attribute::NoInline);
4226
4227 // Allow this function to be shared across translation units, but
4228 // we don't want it to turn into an exported symbol.
4229 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
4230 fn->setVisibility(llvm::Function::HiddenVisibility);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00004231 if (CGM.supportsCOMDAT())
4232 fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004233
4234 // Set up the function.
4235 llvm::BasicBlock *entry =
James Y Knight9871db02019-02-05 16:42:33 +00004236 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
John McCall7f416cc2015-09-08 08:05:57 +00004237 CGBuilderTy builder(CGM, entry);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004238
4239 // Pull the exception pointer out of the parameter list.
4240 llvm::Value *exn = &*fn->arg_begin();
4241
4242 // Call __cxa_begin_catch(exn).
4243 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
4244 catchCall->setDoesNotThrow();
4245 catchCall->setCallingConv(CGM.getRuntimeCC());
4246
4247 // Call std::terminate().
David Blaikie4ba525b2015-07-14 17:27:39 +00004248 llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn());
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004249 termCall->setDoesNotThrow();
4250 termCall->setDoesNotReturn();
4251 termCall->setCallingConv(CGM.getRuntimeCC());
4252
4253 // std::terminate cannot return.
4254 builder.CreateUnreachable();
4255 }
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004256 return fnRef;
4257}
4258
4259llvm::CallInst *
4260ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
4261 llvm::Value *Exn) {
4262 // In C++, we want to call __cxa_begin_catch() before terminating.
4263 if (Exn) {
4264 assert(CGF.CGM.getLangOpts().CPlusPlus);
4265 return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn);
4266 }
4267 return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
4268}
Peter Collingbourne60108802017-12-13 21:53:04 +00004269
4270std::pair<llvm::Value *, const CXXRecordDecl *>
4271ItaniumCXXABI::LoadVTablePtr(CodeGenFunction &CGF, Address This,
4272 const CXXRecordDecl *RD) {
4273 return {CGF.GetVTablePtr(This, CGM.Int8PtrTy, RD), RD};
4274}
Heejin Ahnc6479192018-05-31 22:18:13 +00004275
4276void WebAssemblyCXXABI::emitBeginCatch(CodeGenFunction &CGF,
4277 const CXXCatchStmt *C) {
Heejin Ahn1eb074d2018-06-01 01:01:37 +00004278 if (CGF.getTarget().hasFeature("exception-handling"))
4279 CGF.EHStack.pushCleanup<CatchRetScope>(
4280 NormalCleanup, cast<llvm::CatchPadInst>(CGF.CurrentFuncletPad));
Heejin Ahnc6479192018-05-31 22:18:13 +00004281 ItaniumCXXABI::emitBeginCatch(CGF, C);
4282}