blob: bd9e882dac4092d87f4ea7cebe4dac7f87dbc88a [file] [log] [blame]
Charles Davis4e786dd2010-05-25 19:52:27 +00001//===------- ItaniumCXXABI.cpp - Emit LLVM Code from ASTs for a Module ----===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattner57540c52011-04-15 05:22:18 +000010// This provides C++ code generation targeting the Itanium C++ ABI. The class
Charles Davis4e786dd2010-05-25 19:52:27 +000011// in this file generates structures that follow the Itanium C++ ABI, which is
12// documented at:
13// http://www.codesourcery.com/public/cxx-abi/abi.html
14// http://www.codesourcery.com/public/cxx-abi/abi-eh.html
John McCall86353412010-08-21 22:46:04 +000015//
16// It also supports the closely-related ARM ABI, documented at:
17// http://infocenter.arm.com/help/topic/com.arm.doc.ihi0041c/IHI0041C_cppabi.pdf
18//
Charles Davis4e786dd2010-05-25 19:52:27 +000019//===----------------------------------------------------------------------===//
20
21#include "CGCXXABI.h"
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000022#include "CGCleanup.h"
John McCall7a9aac22010-08-23 01:21:21 +000023#include "CGRecordLayout.h"
Charles Davisa325a6e2012-06-23 23:44:00 +000024#include "CGVTables.h"
John McCall475999d2010-08-22 00:05:51 +000025#include "CodeGenFunction.h"
Charles Davis4e786dd2010-05-25 19:52:27 +000026#include "CodeGenModule.h"
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000027#include "TargetInfo.h"
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"
David Majnemer1162d252014-06-22 19:05:33 +000031#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000032#include "llvm/IR/DataLayout.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"
Charles Davis4e786dd2010-05-25 19:52:27 +000036
37using namespace clang;
John McCall475999d2010-08-22 00:05:51 +000038using namespace CodeGen;
Charles Davis4e786dd2010-05-25 19:52:27 +000039
40namespace {
Charles Davis53c59df2010-08-16 03:33:14 +000041class ItaniumCXXABI : public CodeGen::CGCXXABI {
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +000042 /// VTables - All the vtables which have been defined.
43 llvm::DenseMap<const CXXRecordDecl *, llvm::GlobalVariable *> VTables;
44
John McCall475999d2010-08-22 00:05:51 +000045protected:
Mark Seabornedf0d382013-07-24 16:25:13 +000046 bool UseARMMethodPtrABI;
47 bool UseARMGuardVarABI;
John McCall7a9aac22010-08-23 01:21:21 +000048
Timur Iskhodzhanov67455222013-10-03 06:26:13 +000049 ItaniumMangleContext &getMangleContext() {
50 return cast<ItaniumMangleContext>(CodeGen::CGCXXABI::getMangleContext());
51 }
52
Charles Davis4e786dd2010-05-25 19:52:27 +000053public:
Mark Seabornedf0d382013-07-24 16:25:13 +000054 ItaniumCXXABI(CodeGen::CodeGenModule &CGM,
55 bool UseARMMethodPtrABI = false,
56 bool UseARMGuardVarABI = false) :
57 CGCXXABI(CGM), UseARMMethodPtrABI(UseARMMethodPtrABI),
58 UseARMGuardVarABI(UseARMGuardVarABI) { }
John McCall475999d2010-08-22 00:05:51 +000059
Reid Kleckner40ca9132014-05-13 22:05:45 +000060 bool classifyReturnType(CGFunctionInfo &FI) const override;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000061
Craig Topper4f12f102014-03-12 06:41:41 +000062 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override {
Reid Klecknerd355ca72014-05-15 01:26:32 +000063 // Structures with either a non-trivial destructor or a non-trivial
64 // copy constructor are always indirect.
65 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
66 // special members.
67 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor())
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
Craig Topper4f12f102014-03-12 06:41:41 +0000115 llvm::Value *
116 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
John McCall7f416cc2015-09-08 08:05:57 +0000157 CharUnits getAlignmentOfExnObject() {
Akira Hatanaka68ab7fe2016-03-31 06:36:07 +0000158 unsigned Align = CGM.getContext().getTargetInfo().getExnObjectAlignment();
159 return CGM.getContext().toCharUnitsFromBits(Align);
John McCall7f416cc2015-09-08 08:05:57 +0000160 }
161
David Majnemer442d0a22014-11-25 07:20:20 +0000162 void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
David Majnemer7c237072015-03-05 00:46:22 +0000163 void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override;
David Majnemer442d0a22014-11-25 07:20:20 +0000164
Reid Klecknerfff8e7f2015-03-03 19:21:04 +0000165 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
166
167 llvm::CallInst *
168 emitTerminateForUnexpectedException(CodeGenFunction &CGF,
169 llvm::Value *Exn) override;
170
David Majnemere2cb8d12014-07-07 06:20:47 +0000171 void EmitFundamentalRTTIDescriptor(QualType Type);
172 void EmitFundamentalRTTIDescriptors();
David Majnemer443250f2015-03-17 20:35:00 +0000173 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
Reid Kleckner10aa7702015-09-16 20:15:55 +0000174 CatchTypeInfo
David Majnemer37b417f2015-03-29 21:55:10 +0000175 getAddrOfCXXCatchHandlerType(QualType Ty,
176 QualType CatchHandlerType) override {
Reid Kleckner10aa7702015-09-16 20:15:55 +0000177 return CatchTypeInfo{getAddrOfRTTIDescriptor(Ty), 0};
David Majnemer443250f2015-03-17 20:35:00 +0000178 }
David Majnemere2cb8d12014-07-07 06:20:47 +0000179
David Majnemer1162d252014-06-22 19:05:33 +0000180 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
181 void EmitBadTypeidCall(CodeGenFunction &CGF) override;
182 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
John McCall7f416cc2015-09-08 08:05:57 +0000183 Address ThisPtr,
David Majnemer1162d252014-06-22 19:05:33 +0000184 llvm::Type *StdTypeInfoPtrTy) override;
185
186 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
187 QualType SrcRecordTy) override;
188
John McCall7f416cc2015-09-08 08:05:57 +0000189 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, Address Value,
David Majnemer1162d252014-06-22 19:05:33 +0000190 QualType SrcRecordTy, QualType DestTy,
191 QualType DestRecordTy,
192 llvm::BasicBlock *CastEnd) override;
193
John McCall7f416cc2015-09-08 08:05:57 +0000194 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
David Majnemer1162d252014-06-22 19:05:33 +0000195 QualType SrcRecordTy,
196 QualType DestTy) override;
197
198 bool EmitBadCastCall(CodeGenFunction &CGF) override;
199
Craig Topper4f12f102014-03-12 06:41:41 +0000200 llvm::Value *
John McCall7f416cc2015-09-08 08:05:57 +0000201 GetVirtualBaseClassOffset(CodeGenFunction &CGF, Address This,
Craig Topper4f12f102014-03-12 06:41:41 +0000202 const CXXRecordDecl *ClassDecl,
203 const CXXRecordDecl *BaseClassDecl) override;
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000204
Craig Topper4f12f102014-03-12 06:41:41 +0000205 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000206
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000207 void buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
208 SmallVectorImpl<CanQualType> &ArgTys) override;
John McCall5d865c322010-08-31 07:33:07 +0000209
Reid Klecknere7de47e2013-07-22 13:51:44 +0000210 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
Craig Topper4f12f102014-03-12 06:41:41 +0000211 CXXDtorType DT) const override {
Reid Klecknere7de47e2013-07-22 13:51:44 +0000212 // Itanium does not emit any destructor variant as an inline thunk.
213 // Delegating may occur as an optimization, but all variants are either
214 // emitted with external linkage or as linkonce if they are inline and used.
215 return false;
216 }
217
Craig Topper4f12f102014-03-12 06:41:41 +0000218 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
Reid Klecknere7de47e2013-07-22 13:51:44 +0000219
Reid Kleckner89077a12013-12-17 19:46:40 +0000220 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
Craig Topper4f12f102014-03-12 06:41:41 +0000221 FunctionArgList &Params) override;
John McCall5d865c322010-08-31 07:33:07 +0000222
Craig Topper4f12f102014-03-12 06:41:41 +0000223 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
John McCall8ed55a52010-09-02 09:58:18 +0000224
Reid Kleckner89077a12013-12-17 19:46:40 +0000225 unsigned addImplicitConstructorArgs(CodeGenFunction &CGF,
226 const CXXConstructorDecl *D,
227 CXXCtorType Type, bool ForVirtualBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000228 bool Delegating,
229 CallArgList &Args) override;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000230
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000231 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
232 CXXDtorType Type, bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +0000233 bool Delegating, Address This) override;
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000234
Craig Topper4f12f102014-03-12 06:41:41 +0000235 void emitVTableDefinitions(CodeGenVTables &CGVT,
236 const CXXRecordDecl *RD) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000237
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000238 bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,
239 CodeGenFunction::VPtr Vptr) override;
240
241 bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override {
242 return true;
243 }
244
245 llvm::Constant *
246 getVTableAddressPoint(BaseSubobject Base,
247 const CXXRecordDecl *VTableClass) override;
248
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000249 llvm::Value *getVTableAddressPointInStructor(
250 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000251 BaseSubobject Base, const CXXRecordDecl *NearestVBase) override;
252
253 llvm::Value *getVTableAddressPointInStructorWithVTT(
254 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
255 BaseSubobject Base, const CXXRecordDecl *NearestVBase);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000256
257 llvm::Constant *
258 getVTableAddressPointForConstExpr(BaseSubobject Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000259 const CXXRecordDecl *VTableClass) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000260
261 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
Craig Topper4f12f102014-03-12 06:41:41 +0000262 CharUnits VPtrOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000263
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000264 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
John McCall7f416cc2015-09-08 08:05:57 +0000265 Address This, llvm::Type *Ty,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +0000266 SourceLocation Loc) override;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000267
David Majnemer0c0b6d92014-10-31 20:09:12 +0000268 llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
269 const CXXDestructorDecl *Dtor,
270 CXXDtorType DtorType,
John McCall7f416cc2015-09-08 08:05:57 +0000271 Address This,
David Majnemer0c0b6d92014-10-31 20:09:12 +0000272 const CXXMemberCallExpr *CE) override;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000273
Craig Topper4f12f102014-03-12 06:41:41 +0000274 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
Reid Kleckner7810af02013-06-19 15:20:38 +0000275
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000276 bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const override;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000277
Hans Wennborgc94391d2014-06-06 20:04:01 +0000278 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
279 bool ReturnAdjustment) override {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000280 // Allow inlining of thunks by emitting them with available_externally
281 // linkage together with vtables when needed.
Peter Collingbourne8fabc1b2015-07-01 02:10:26 +0000282 if (ForVTable && !Thunk->hasLocalLinkage())
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000283 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
284 }
285
John McCall7f416cc2015-09-08 08:05:57 +0000286 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This,
Craig Topper4f12f102014-03-12 06:41:41 +0000287 const ThisAdjustment &TA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000288
John McCall7f416cc2015-09-08 08:05:57 +0000289 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
Craig Topper4f12f102014-03-12 06:41:41 +0000290 const ReturnAdjustment &RA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000291
David Majnemer196ac332014-09-11 23:05:02 +0000292 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
293 FunctionArgList &Args) const override {
294 assert(!Args.empty() && "expected the arglist to not be empty!");
295 return Args.size() - 1;
296 }
297
Craig Topper4f12f102014-03-12 06:41:41 +0000298 StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
299 StringRef GetDeletedVirtualCallName() override
300 { return "__cxa_deleted_virtual"; }
Joao Matos2ce88ef2012-07-17 17:10:11 +0000301
Craig Topper4f12f102014-03-12 06:41:41 +0000302 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall7f416cc2015-09-08 08:05:57 +0000303 Address InitializeArrayCookie(CodeGenFunction &CGF,
304 Address NewPtr,
305 llvm::Value *NumElements,
306 const CXXNewExpr *expr,
307 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000308 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000309 Address allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000310 CharUnits cookieSize) override;
John McCall68ff0372010-09-08 01:44:27 +0000311
John McCallcdf7ef52010-11-06 09:44:32 +0000312 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000313 llvm::GlobalVariable *DeclPtr,
314 bool PerformInit) override;
Richard Smithdbf74ba2013-04-14 23:01:42 +0000315 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000316 llvm::Constant *dtor, llvm::Constant *addr) override;
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000317
318 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +0000319 llvm::Value *Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000320 void EmitThreadLocalInitFuncs(
David Majnemerb3341ea2014-10-05 05:05:40 +0000321 CodeGenModule &CGM,
Richard Smith5a99c492015-12-01 01:10:48 +0000322 ArrayRef<const VarDecl *> CXXThreadLocals,
David Majnemerb3341ea2014-10-05 05:05:40 +0000323 ArrayRef<llvm::Function *> CXXThreadLocalInits,
Richard Smith5a99c492015-12-01 01:10:48 +0000324 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) override;
David Majnemerb3341ea2014-10-05 05:05:40 +0000325
326 bool usesThreadWrapperFunction() const override { return true; }
Richard Smith0f383742014-03-26 22:48:22 +0000327 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
328 QualType LValType) override;
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000329
Craig Topper4f12f102014-03-12 06:41:41 +0000330 bool NeedsVTTParameter(GlobalDecl GD) override;
David Majnemere2cb8d12014-07-07 06:20:47 +0000331
332 /**************************** RTTI Uniqueness ******************************/
333
334protected:
335 /// Returns true if the ABI requires RTTI type_info objects to be unique
336 /// across a program.
337 virtual bool shouldRTTIBeUnique() const { return true; }
338
339public:
340 /// What sort of unique-RTTI behavior should we use?
341 enum RTTIUniquenessKind {
342 /// We are guaranteeing, or need to guarantee, that the RTTI string
343 /// is unique.
344 RUK_Unique,
345
346 /// We are not guaranteeing uniqueness for the RTTI string, so we
347 /// can demote to hidden visibility but must use string comparisons.
348 RUK_NonUniqueHidden,
349
350 /// We are not guaranteeing uniqueness for the RTTI string, so we
351 /// have to use string comparisons, but we also have to emit it with
352 /// non-hidden visibility.
353 RUK_NonUniqueVisible
354 };
355
356 /// Return the required visibility status for the given type and linkage in
357 /// the current ABI.
358 RTTIUniquenessKind
359 classifyRTTIUniqueness(QualType CanTy,
360 llvm::GlobalValue::LinkageTypes Linkage) const;
361 friend class ItaniumRTTIBuilder;
Rafael Espindola91f68b42014-09-15 19:20:10 +0000362
363 void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000364
365 private:
Piotr Padlewski1d02f682015-08-19 20:09:09 +0000366 bool hasAnyUsedVirtualInlineFunction(const CXXRecordDecl *RD) const {
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000367 const auto &VtableLayout =
368 CGM.getItaniumVTableContext().getVTableLayout(RD);
369
370 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
Piotr Padlewski1d02f682015-08-19 20:09:09 +0000371 if (!VtableComponent.isUsedFunctionPointerKind())
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000372 continue;
373
Piotr Padlewski1d02f682015-08-19 20:09:09 +0000374 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000375 if (Method->getCanonicalDecl()->isInlined())
376 return true;
377 }
378 return false;
379 }
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000380
381 bool isVTableHidden(const CXXRecordDecl *RD) const {
382 const auto &VtableLayout =
383 CGM.getItaniumVTableContext().getVTableLayout(RD);
384
385 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
386 if (VtableComponent.isRTTIKind()) {
387 const CXXRecordDecl *RTTIDecl = VtableComponent.getRTTIDecl();
388 if (RTTIDecl->getVisibility() == Visibility::HiddenVisibility)
389 return true;
390 } else if (VtableComponent.isUsedFunctionPointerKind()) {
391 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
392 if (Method->getVisibility() == Visibility::HiddenVisibility &&
393 !Method->isDefined())
394 return true;
395 }
396 }
397 return false;
398 }
Charles Davis4e786dd2010-05-25 19:52:27 +0000399};
John McCall86353412010-08-21 22:46:04 +0000400
401class ARMCXXABI : public ItaniumCXXABI {
402public:
Mark Seabornedf0d382013-07-24 16:25:13 +0000403 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
404 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
405 /* UseARMGuardVarABI = */ true) {}
John McCall5d865c322010-08-31 07:33:07 +0000406
Craig Topper4f12f102014-03-12 06:41:41 +0000407 bool HasThisReturn(GlobalDecl GD) const override {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000408 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
409 isa<CXXDestructorDecl>(GD.getDecl()) &&
410 GD.getDtorType() != Dtor_Deleting));
411 }
John McCall5d865c322010-08-31 07:33:07 +0000412
Craig Topper4f12f102014-03-12 06:41:41 +0000413 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
414 QualType ResTy) override;
John McCall5d865c322010-08-31 07:33:07 +0000415
Craig Topper4f12f102014-03-12 06:41:41 +0000416 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall7f416cc2015-09-08 08:05:57 +0000417 Address InitializeArrayCookie(CodeGenFunction &CGF,
418 Address NewPtr,
419 llvm::Value *NumElements,
420 const CXXNewExpr *expr,
421 QualType ElementType) override;
422 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, Address allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000423 CharUnits cookieSize) override;
John McCall86353412010-08-21 22:46:04 +0000424};
Tim Northovera2ee4332014-03-29 15:09:45 +0000425
426class iOS64CXXABI : public ARMCXXABI {
427public:
428 iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {}
Tim Northover65f582f2014-03-30 17:32:48 +0000429
430 // ARM64 libraries are prepared for non-unique RTTI.
David Majnemere2cb8d12014-07-07 06:20:47 +0000431 bool shouldRTTIBeUnique() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +0000432};
Dan Gohmanc2853072015-09-03 22:51:53 +0000433
434class WebAssemblyCXXABI final : public ItaniumCXXABI {
435public:
436 explicit WebAssemblyCXXABI(CodeGen::CodeGenModule &CGM)
437 : ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
438 /*UseARMGuardVarABI=*/true) {}
439
440private:
441 bool HasThisReturn(GlobalDecl GD) const override {
442 return isa<CXXConstructorDecl>(GD.getDecl()) ||
443 (isa<CXXDestructorDecl>(GD.getDecl()) &&
444 GD.getDtorType() != Dtor_Deleting);
445 }
Derek Schuff8179be42016-05-10 17:44:55 +0000446 bool canCallMismatchedFunctionType() const override { return false; }
Dan Gohmanc2853072015-09-03 22:51:53 +0000447};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000448}
Charles Davis4e786dd2010-05-25 19:52:27 +0000449
Charles Davis53c59df2010-08-16 03:33:14 +0000450CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000451 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000452 // For IR-generation purposes, there's no significant difference
453 // between the ARM and iOS ABIs.
454 case TargetCXXABI::GenericARM:
455 case TargetCXXABI::iOS:
Tim Northover756447a2015-10-30 16:30:36 +0000456 case TargetCXXABI::WatchOS:
John McCall57625922013-01-25 23:36:14 +0000457 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000458
Tim Northovera2ee4332014-03-29 15:09:45 +0000459 case TargetCXXABI::iOS64:
460 return new iOS64CXXABI(CGM);
461
Tim Northover9bb857a2013-01-31 12:13:10 +0000462 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
463 // include the other 32-bit ARM oddities: constructor/destructor return values
464 // and array cookies.
465 case TargetCXXABI::GenericAArch64:
Mark Seabornedf0d382013-07-24 16:25:13 +0000466 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
467 /* UseARMGuardVarABI = */ true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000468
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000469 case TargetCXXABI::GenericMIPS:
470 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true);
471
Dan Gohmanc2853072015-09-03 22:51:53 +0000472 case TargetCXXABI::WebAssembly:
473 return new WebAssemblyCXXABI(CGM);
474
John McCall57625922013-01-25 23:36:14 +0000475 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000476 if (CGM.getContext().getTargetInfo().getTriple().getArch()
477 == llvm::Triple::le32) {
478 // For PNaCl, use ARM-style method pointers so that PNaCl code
479 // does not assume anything about the alignment of function
480 // pointers.
481 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
482 /* UseARMGuardVarABI = */ false);
483 }
John McCall57625922013-01-25 23:36:14 +0000484 return new ItaniumCXXABI(CGM);
485
486 case TargetCXXABI::Microsoft:
487 llvm_unreachable("Microsoft ABI is not Itanium-based");
488 }
489 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000490}
491
Chris Lattnera5f58b02011-07-09 17:41:47 +0000492llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000493ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
494 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000495 return CGM.PtrDiffTy;
Reid Kleckneree7cf842014-12-01 22:02:27 +0000496 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, nullptr);
John McCall1c456c82010-08-22 06:43:33 +0000497}
498
John McCalld9c6c0b2010-08-22 00:59:17 +0000499/// In the Itanium and ARM ABIs, method pointers have the form:
500/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
501///
502/// In the Itanium ABI:
503/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
504/// - the this-adjustment is (memptr.adj)
505/// - the virtual offset is (memptr.ptr - 1)
506///
507/// In the ARM ABI:
508/// - method pointers are virtual if (memptr.adj & 1) is nonzero
509/// - the this-adjustment is (memptr.adj >> 1)
510/// - the virtual offset is (memptr.ptr)
511/// ARM uses 'adj' for the virtual flag because Thumb functions
512/// may be only single-byte aligned.
513///
514/// If the member is virtual, the adjusted 'this' pointer points
515/// to a vtable pointer from which the virtual offset is applied.
516///
517/// If the member is non-virtual, memptr.ptr is the address of
518/// the function to call.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000519llvm::Value *ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
John McCall7f416cc2015-09-08 08:05:57 +0000520 CodeGenFunction &CGF, const Expr *E, Address ThisAddr,
521 llvm::Value *&ThisPtrForCall,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000522 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
John McCall475999d2010-08-22 00:05:51 +0000523 CGBuilderTy &Builder = CGF.Builder;
524
525 const FunctionProtoType *FPT =
526 MPT->getPointeeType()->getAs<FunctionProtoType>();
527 const CXXRecordDecl *RD =
528 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
529
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000530 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(
531 CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr));
John McCall475999d2010-08-22 00:05:51 +0000532
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000533 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000534
John McCalld9c6c0b2010-08-22 00:59:17 +0000535 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
536 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
537 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
538
John McCalla1dee5302010-08-22 10:59:02 +0000539 // Extract memptr.adj, which is in the second field.
540 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000541
542 // Compute the true adjustment.
543 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000544 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000545 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000546
547 // Apply the adjustment and cast back to the original struct type
548 // for consistency.
John McCall7f416cc2015-09-08 08:05:57 +0000549 llvm::Value *This = ThisAddr.getPointer();
John McCalld9c6c0b2010-08-22 00:59:17 +0000550 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
551 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
552 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall7f416cc2015-09-08 08:05:57 +0000553 ThisPtrForCall = This;
John McCall475999d2010-08-22 00:05:51 +0000554
555 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000556 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall475999d2010-08-22 00:05:51 +0000557
558 // If the LSB in the function pointer is 1, the function pointer points to
559 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000560 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000561 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000562 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
563 else
564 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
565 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000566 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
567
568 // In the virtual path, the adjustment left 'This' pointing to the
569 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000570 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000571 CGF.EmitBlock(FnVirtual);
572
573 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000574 llvm::Type *VTableTy = Builder.getInt8PtrTy();
John McCall7f416cc2015-09-08 08:05:57 +0000575 CharUnits VTablePtrAlign =
576 CGF.CGM.getDynamicOffsetAlignment(ThisAddr.getAlignment(), RD,
577 CGF.getPointerAlign());
578 llvm::Value *VTable =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000579 CGF.GetVTablePtr(Address(This, VTablePtrAlign), VTableTy, RD);
John McCall475999d2010-08-22 00:05:51 +0000580
581 // Apply the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000582 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000583 if (!UseARMMethodPtrABI)
584 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld9c6c0b2010-08-22 00:59:17 +0000585 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall475999d2010-08-22 00:05:51 +0000586
587 // Load the virtual function to call.
588 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCall7f416cc2015-09-08 08:05:57 +0000589 llvm::Value *VirtualFn =
590 Builder.CreateAlignedLoad(VTable, CGF.getPointerAlign(),
591 "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000592 CGF.EmitBranch(FnEnd);
593
594 // In the non-virtual path, the function pointer is actually a
595 // function pointer.
596 CGF.EmitBlock(FnNonVirtual);
597 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000598 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall475999d2010-08-22 00:05:51 +0000599
600 // We're done.
601 CGF.EmitBlock(FnEnd);
Jay Foad20c0f022011-03-30 11:28:58 +0000602 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
John McCall475999d2010-08-22 00:05:51 +0000603 Callee->addIncoming(VirtualFn, FnVirtual);
604 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
605 return Callee;
606}
John McCalla8bbb822010-08-22 03:04:22 +0000607
John McCallc134eb52010-08-31 21:07:20 +0000608/// Compute an l-value by applying the given pointer-to-member to a
609/// base object.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000610llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
John McCall7f416cc2015-09-08 08:05:57 +0000611 CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000612 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000613 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000614
615 CGBuilderTy &Builder = CGF.Builder;
616
John McCallc134eb52010-08-31 21:07:20 +0000617 // Cast to char*.
John McCall7f416cc2015-09-08 08:05:57 +0000618 Base = Builder.CreateElementBitCast(Base, CGF.Int8Ty);
John McCallc134eb52010-08-31 21:07:20 +0000619
620 // Apply the offset, which we assume is non-null.
John McCall7f416cc2015-09-08 08:05:57 +0000621 llvm::Value *Addr =
622 Builder.CreateInBoundsGEP(Base.getPointer(), MemPtr, "memptr.offset");
John McCallc134eb52010-08-31 21:07:20 +0000623
624 // Cast the address to the appropriate pointer type, adopting the
625 // address space of the base pointer.
John McCall7f416cc2015-09-08 08:05:57 +0000626 llvm::Type *PType = CGF.ConvertTypeForMem(MPT->getPointeeType())
627 ->getPointerTo(Base.getAddressSpace());
John McCallc134eb52010-08-31 21:07:20 +0000628 return Builder.CreateBitCast(Addr, PType);
629}
630
John McCallc62bb392012-02-15 01:22:51 +0000631/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
632/// conversion.
633///
634/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000635///
636/// Obligatory offset/adjustment diagram:
637/// <-- offset --> <-- adjustment -->
638/// |--------------------------|----------------------|--------------------|
639/// ^Derived address point ^Base address point ^Member address point
640///
641/// So when converting a base member pointer to a derived member pointer,
642/// we add the offset to the adjustment because the address point has
643/// decreased; and conversely, when converting a derived MP to a base MP
644/// we subtract the offset from the adjustment because the address point
645/// has increased.
646///
647/// The standard forbids (at compile time) conversion to and from
648/// virtual bases, which is why we don't have to consider them here.
649///
650/// The standard forbids (at run time) casting a derived MP to a base
651/// MP when the derived MP does not point to a member of the base.
652/// This is why -1 is a reasonable choice for null data member
653/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000654llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000655ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
656 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000657 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000658 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000659 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
660 E->getCastKind() == CK_ReinterpretMemberPointer);
661
662 // Under Itanium, reinterprets don't require any additional processing.
663 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
664
665 // Use constant emission if we can.
666 if (isa<llvm::Constant>(src))
667 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
668
669 llvm::Constant *adj = getMemberPointerAdjustment(E);
670 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000671
672 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000673 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000674
John McCallc62bb392012-02-15 01:22:51 +0000675 const MemberPointerType *destTy =
676 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000677
John McCall7a9aac22010-08-23 01:21:21 +0000678 // For member data pointers, this is just a matter of adding the
679 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000680 if (destTy->isMemberDataPointer()) {
681 llvm::Value *dst;
682 if (isDerivedToBase)
683 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000684 else
John McCallc62bb392012-02-15 01:22:51 +0000685 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000686
687 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000688 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
689 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
690 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000691 }
692
John McCalla1dee5302010-08-22 10:59:02 +0000693 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000694 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000695 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
696 offset <<= 1;
697 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000698 }
699
John McCallc62bb392012-02-15 01:22:51 +0000700 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
701 llvm::Value *dstAdj;
702 if (isDerivedToBase)
703 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000704 else
John McCallc62bb392012-02-15 01:22:51 +0000705 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000706
John McCallc62bb392012-02-15 01:22:51 +0000707 return Builder.CreateInsertValue(src, dstAdj, 1);
708}
709
710llvm::Constant *
711ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
712 llvm::Constant *src) {
713 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
714 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
715 E->getCastKind() == CK_ReinterpretMemberPointer);
716
717 // Under Itanium, reinterprets don't require any additional processing.
718 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
719
720 // If the adjustment is trivial, we don't need to do anything.
721 llvm::Constant *adj = getMemberPointerAdjustment(E);
722 if (!adj) return src;
723
724 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
725
726 const MemberPointerType *destTy =
727 E->getType()->castAs<MemberPointerType>();
728
729 // For member data pointers, this is just a matter of adding the
730 // offset if the source is non-null.
731 if (destTy->isMemberDataPointer()) {
732 // null maps to null.
733 if (src->isAllOnesValue()) return src;
734
735 if (isDerivedToBase)
736 return llvm::ConstantExpr::getNSWSub(src, adj);
737 else
738 return llvm::ConstantExpr::getNSWAdd(src, adj);
739 }
740
741 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000742 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000743 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
744 offset <<= 1;
745 adj = llvm::ConstantInt::get(adj->getType(), offset);
746 }
747
748 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
749 llvm::Constant *dstAdj;
750 if (isDerivedToBase)
751 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
752 else
753 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
754
755 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000756}
John McCall84fa5102010-08-22 04:16:24 +0000757
758llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000759ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000760 // Itanium C++ ABI 2.3:
761 // A NULL pointer is represented as -1.
762 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000763 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000764
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000765 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000766 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000767 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000768}
769
John McCallf3a88602011-02-03 08:15:49 +0000770llvm::Constant *
771ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
772 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000773 // Itanium C++ ABI 2.3:
774 // A pointer to data member is an offset from the base address of
775 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000776 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000777}
778
David Majnemere2be95b2015-06-23 07:31:01 +0000779llvm::Constant *
780ItaniumCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000781 return BuildMemberPointer(MD, CharUnits::Zero());
782}
783
784llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
785 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000786 assert(MD->isInstance() && "Member function must not be static!");
787 MD = MD->getCanonicalDecl();
788
789 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000790
791 // Get the function pointer (or index if this is a virtual function).
792 llvm::Constant *MemPtr[2];
793 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000794 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000795
Ken Dyckdf016282011-04-09 01:30:02 +0000796 const ASTContext &Context = getContext();
797 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000798 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000799 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000800
Mark Seabornedf0d382013-07-24 16:25:13 +0000801 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000802 // ARM C++ ABI 3.2.1:
803 // This ABI specifies that adj contains twice the this
804 // adjustment, plus 1 if the member function is virtual. The
805 // least significant bit of adj then makes exactly the same
806 // discrimination as the least significant bit of ptr does for
807 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000808 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
809 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000810 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000811 } else {
812 // Itanium C++ ABI 2.3:
813 // For a virtual function, [the pointer field] is 1 plus the
814 // virtual table offset (in bytes) of the function,
815 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000816 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
817 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000818 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000819 }
820 } else {
John McCall2979fe02011-04-12 00:42:48 +0000821 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000822 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000823 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000824 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000825 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000826 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000827 } else {
John McCall2979fe02011-04-12 00:42:48 +0000828 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
829 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000830 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000831 }
John McCall2979fe02011-04-12 00:42:48 +0000832 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000833
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000834 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000835 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
836 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000837 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000838 }
John McCall1c456c82010-08-22 06:43:33 +0000839
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000840 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000841}
842
Richard Smithdafff942012-01-14 04:30:29 +0000843llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
844 QualType MPType) {
845 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
846 const ValueDecl *MPD = MP.getMemberPointerDecl();
847 if (!MPD)
848 return EmitNullMemberPointer(MPT);
849
Reid Kleckner452abac2013-05-09 21:01:17 +0000850 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000851
852 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
853 return BuildMemberPointer(MD, ThisAdjustment);
854
855 CharUnits FieldOffset =
856 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
857 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
858}
859
John McCall131d97d2010-08-22 08:30:07 +0000860/// The comparison algorithm is pretty easy: the member pointers are
861/// the same if they're either bitwise identical *or* both null.
862///
863/// ARM is different here only because null-ness is more complicated.
864llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000865ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
866 llvm::Value *L,
867 llvm::Value *R,
868 const MemberPointerType *MPT,
869 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000870 CGBuilderTy &Builder = CGF.Builder;
871
John McCall131d97d2010-08-22 08:30:07 +0000872 llvm::ICmpInst::Predicate Eq;
873 llvm::Instruction::BinaryOps And, Or;
874 if (Inequality) {
875 Eq = llvm::ICmpInst::ICMP_NE;
876 And = llvm::Instruction::Or;
877 Or = llvm::Instruction::And;
878 } else {
879 Eq = llvm::ICmpInst::ICMP_EQ;
880 And = llvm::Instruction::And;
881 Or = llvm::Instruction::Or;
882 }
883
John McCall7a9aac22010-08-23 01:21:21 +0000884 // Member data pointers are easy because there's a unique null
885 // value, so it just comes down to bitwise equality.
886 if (MPT->isMemberDataPointer())
887 return Builder.CreateICmp(Eq, L, R);
888
889 // For member function pointers, the tautologies are more complex.
890 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000891 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000892 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000893 // (L == R) <==> (L.ptr == R.ptr &&
894 // (L.adj == R.adj ||
895 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000896 // The inequality tautologies have exactly the same structure, except
897 // applying De Morgan's laws.
898
899 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
900 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
901
John McCall131d97d2010-08-22 08:30:07 +0000902 // This condition tests whether L.ptr == R.ptr. This must always be
903 // true for equality to hold.
904 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
905
906 // This condition, together with the assumption that L.ptr == R.ptr,
907 // tests whether the pointers are both null. ARM imposes an extra
908 // condition.
909 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
910 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
911
912 // This condition tests whether L.adj == R.adj. If this isn't
913 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +0000914 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
915 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000916 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
917
918 // Null member function pointers on ARM clear the low bit of Adj,
919 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000920 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000921 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
922
923 // Compute (l.adj | r.adj) & 1 and test it against zero.
924 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
925 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
926 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
927 "cmp.or.adj");
928 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
929 }
930
931 // Tie together all our conditions.
932 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
933 Result = Builder.CreateBinOp(And, PtrEq, Result,
934 Inequality ? "memptr.ne" : "memptr.eq");
935 return Result;
936}
937
938llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000939ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
940 llvm::Value *MemPtr,
941 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +0000942 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +0000943
944 /// For member data pointers, this is just a check against -1.
945 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000946 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +0000947 llvm::Value *NegativeOne =
948 llvm::Constant::getAllOnesValue(MemPtr->getType());
949 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
950 }
John McCall131d97d2010-08-22 08:30:07 +0000951
Daniel Dunbar914bc412011-04-19 23:10:47 +0000952 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +0000953 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +0000954
955 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
956 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
957
Daniel Dunbar914bc412011-04-19 23:10:47 +0000958 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
959 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000960 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000961 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +0000962 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000963 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +0000964 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
965 "memptr.isvirtual");
966 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +0000967 }
968
969 return Result;
970}
John McCall1c456c82010-08-22 06:43:33 +0000971
Reid Kleckner40ca9132014-05-13 22:05:45 +0000972bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
973 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
974 if (!RD)
975 return false;
976
Reid Klecknerd355ca72014-05-15 01:26:32 +0000977 // Return indirectly if we have a non-trivial copy ctor or non-trivial dtor.
978 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
979 // special members.
980 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor()) {
John McCall7f416cc2015-09-08 08:05:57 +0000981 auto Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
982 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
Reid Kleckner40ca9132014-05-13 22:05:45 +0000983 return true;
984 }
Reid Kleckner40ca9132014-05-13 22:05:45 +0000985 return false;
986}
987
John McCall614dbdc2010-08-22 21:01:12 +0000988/// The Itanium ABI requires non-zero initialization only for data
989/// member pointers, for which '0' is a valid offset.
990bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
David Majnemer5fd33e02015-04-24 01:25:08 +0000991 return MPT->isMemberFunctionPointer();
John McCall84fa5102010-08-22 04:16:24 +0000992}
John McCall5d865c322010-08-31 07:33:07 +0000993
John McCall82fb8922012-09-25 10:10:39 +0000994/// The Itanium ABI always places an offset to the complete object
995/// at entry -2 in the vtable.
David Majnemer08681372014-11-01 07:37:17 +0000996void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
997 const CXXDeleteExpr *DE,
John McCall7f416cc2015-09-08 08:05:57 +0000998 Address Ptr,
David Majnemer08681372014-11-01 07:37:17 +0000999 QualType ElementType,
1000 const CXXDestructorDecl *Dtor) {
1001 bool UseGlobalDelete = DE->isGlobalDelete();
David Majnemer0c0b6d92014-10-31 20:09:12 +00001002 if (UseGlobalDelete) {
1003 // Derive the complete-object pointer, which is what we need
1004 // to pass to the deallocation function.
John McCall82fb8922012-09-25 10:10:39 +00001005
David Majnemer0c0b6d92014-10-31 20:09:12 +00001006 // Grab the vtable pointer as an intptr_t*.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001007 auto *ClassDecl =
1008 cast<CXXRecordDecl>(ElementType->getAs<RecordType>()->getDecl());
1009 llvm::Value *VTable =
1010 CGF.GetVTablePtr(Ptr, CGF.IntPtrTy->getPointerTo(), ClassDecl);
John McCall82fb8922012-09-25 10:10:39 +00001011
David Majnemer0c0b6d92014-10-31 20:09:12 +00001012 // Track back to entry -2 and pull out the offset there.
1013 llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
1014 VTable, -2, "complete-offset.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001015 llvm::Value *Offset =
1016 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
David Majnemer0c0b6d92014-10-31 20:09:12 +00001017
1018 // Apply the offset.
John McCall7f416cc2015-09-08 08:05:57 +00001019 llvm::Value *CompletePtr =
1020 CGF.Builder.CreateBitCast(Ptr.getPointer(), CGF.Int8PtrTy);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001021 CompletePtr = CGF.Builder.CreateInBoundsGEP(CompletePtr, Offset);
1022
1023 // If we're supposed to call the global delete, make sure we do so
1024 // even if the destructor throws.
David Majnemer08681372014-11-01 07:37:17 +00001025 CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr,
1026 ElementType);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001027 }
1028
1029 // FIXME: Provide a source location here even though there's no
1030 // CXXMemberCallExpr for dtor call.
1031 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
1032 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr);
1033
1034 if (UseGlobalDelete)
1035 CGF.PopCleanupBlock();
John McCall82fb8922012-09-25 10:10:39 +00001036}
1037
David Majnemer442d0a22014-11-25 07:20:20 +00001038void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
1039 // void __cxa_rethrow();
1040
1041 llvm::FunctionType *FTy =
1042 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
1043
1044 llvm::Constant *Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
1045
1046 if (isNoReturn)
1047 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, None);
1048 else
1049 CGF.EmitRuntimeCallOrInvoke(Fn);
1050}
1051
David Majnemer7c237072015-03-05 00:46:22 +00001052static llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) {
1053 // void *__cxa_allocate_exception(size_t thrown_size);
1054
1055 llvm::FunctionType *FTy =
1056 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false);
1057
1058 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
1059}
1060
1061static llvm::Constant *getThrowFn(CodeGenModule &CGM) {
1062 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
1063 // void (*dest) (void *));
1064
1065 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
1066 llvm::FunctionType *FTy =
1067 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
1068
1069 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
1070}
1071
1072void ItaniumCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
1073 QualType ThrowType = E->getSubExpr()->getType();
1074 // Now allocate the exception object.
1075 llvm::Type *SizeTy = CGF.ConvertType(getContext().getSizeType());
1076 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
1077
1078 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM);
1079 llvm::CallInst *ExceptionPtr = CGF.EmitNounwindRuntimeCall(
1080 AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception");
1081
John McCall7f416cc2015-09-08 08:05:57 +00001082 CharUnits ExnAlign = getAlignmentOfExnObject();
1083 CGF.EmitAnyExprToExn(E->getSubExpr(), Address(ExceptionPtr, ExnAlign));
David Majnemer7c237072015-03-05 00:46:22 +00001084
1085 // Now throw the exception.
1086 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
1087 /*ForEH=*/true);
1088
1089 // The address of the destructor. If the exception type has a
1090 // trivial destructor (or isn't a record), we just pass null.
1091 llvm::Constant *Dtor = nullptr;
1092 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
1093 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
1094 if (!Record->hasTrivialDestructor()) {
1095 CXXDestructorDecl *DtorD = Record->getDestructor();
1096 Dtor = CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete);
1097 Dtor = llvm::ConstantExpr::getBitCast(Dtor, CGM.Int8PtrTy);
1098 }
1099 }
1100 if (!Dtor) Dtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
1101
1102 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
1103 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
1104}
1105
David Majnemer1162d252014-06-22 19:05:33 +00001106static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) {
1107 // void *__dynamic_cast(const void *sub,
1108 // const abi::__class_type_info *src,
1109 // const abi::__class_type_info *dst,
1110 // std::ptrdiff_t src2dst_offset);
1111
1112 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1113 llvm::Type *PtrDiffTy =
1114 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1115
1116 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
1117
1118 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
1119
1120 // Mark the function as nounwind readonly.
1121 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
1122 llvm::Attribute::ReadOnly };
1123 llvm::AttributeSet Attrs = llvm::AttributeSet::get(
1124 CGF.getLLVMContext(), llvm::AttributeSet::FunctionIndex, FuncAttrs);
1125
1126 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
1127}
1128
1129static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1130 // void __cxa_bad_cast();
1131 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1132 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1133}
1134
1135/// \brief Compute the src2dst_offset hint as described in the
1136/// Itanium C++ ABI [2.9.7]
1137static CharUnits computeOffsetHint(ASTContext &Context,
1138 const CXXRecordDecl *Src,
1139 const CXXRecordDecl *Dst) {
1140 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1141 /*DetectVirtual=*/false);
1142
1143 // If Dst is not derived from Src we can skip the whole computation below and
1144 // return that Src is not a public base of Dst. Record all inheritance paths.
1145 if (!Dst->isDerivedFrom(Src, Paths))
1146 return CharUnits::fromQuantity(-2ULL);
1147
1148 unsigned NumPublicPaths = 0;
1149 CharUnits Offset;
1150
1151 // Now walk all possible inheritance paths.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001152 for (const CXXBasePath &Path : Paths) {
1153 if (Path.Access != AS_public) // Ignore non-public inheritance.
David Majnemer1162d252014-06-22 19:05:33 +00001154 continue;
1155
1156 ++NumPublicPaths;
1157
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001158 for (const CXXBasePathElement &PathElement : Path) {
David Majnemer1162d252014-06-22 19:05:33 +00001159 // If the path contains a virtual base class we can't give any hint.
1160 // -1: no hint.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001161 if (PathElement.Base->isVirtual())
David Majnemer1162d252014-06-22 19:05:33 +00001162 return CharUnits::fromQuantity(-1ULL);
1163
1164 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
1165 continue;
1166
1167 // Accumulate the base class offsets.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001168 const ASTRecordLayout &L = Context.getASTRecordLayout(PathElement.Class);
1169 Offset += L.getBaseClassOffset(
1170 PathElement.Base->getType()->getAsCXXRecordDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001171 }
1172 }
1173
1174 // -2: Src is not a public base of Dst.
1175 if (NumPublicPaths == 0)
1176 return CharUnits::fromQuantity(-2ULL);
1177
1178 // -3: Src is a multiple public base type but never a virtual base type.
1179 if (NumPublicPaths > 1)
1180 return CharUnits::fromQuantity(-3ULL);
1181
1182 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
1183 // Return the offset of Src from the origin of Dst.
1184 return Offset;
1185}
1186
1187static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1188 // void __cxa_bad_typeid();
1189 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1190
1191 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1192}
1193
1194bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
1195 QualType SrcRecordTy) {
1196 return IsDeref;
1197}
1198
1199void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
1200 llvm::Value *Fn = getBadTypeidFn(CGF);
1201 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1202 CGF.Builder.CreateUnreachable();
1203}
1204
1205llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
1206 QualType SrcRecordTy,
John McCall7f416cc2015-09-08 08:05:57 +00001207 Address ThisPtr,
David Majnemer1162d252014-06-22 19:05:33 +00001208 llvm::Type *StdTypeInfoPtrTy) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001209 auto *ClassDecl =
1210 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001211 llvm::Value *Value =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001212 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo(), ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001213
1214 // Load the type info.
1215 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001216 return CGF.Builder.CreateAlignedLoad(Value, CGF.getPointerAlign());
David Majnemer1162d252014-06-22 19:05:33 +00001217}
1218
1219bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1220 QualType SrcRecordTy) {
1221 return SrcIsPtr;
1222}
1223
1224llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
John McCall7f416cc2015-09-08 08:05:57 +00001225 CodeGenFunction &CGF, Address ThisAddr, QualType SrcRecordTy,
David Majnemer1162d252014-06-22 19:05:33 +00001226 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1227 llvm::Type *PtrDiffLTy =
1228 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1229 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1230
1231 llvm::Value *SrcRTTI =
1232 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1233 llvm::Value *DestRTTI =
1234 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1235
1236 // Compute the offset hint.
1237 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1238 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1239 llvm::Value *OffsetHint = llvm::ConstantInt::get(
1240 PtrDiffLTy,
1241 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
1242
1243 // Emit the call to __dynamic_cast.
John McCall7f416cc2015-09-08 08:05:57 +00001244 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001245 Value = CGF.EmitCastToVoidPtr(Value);
1246
1247 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
1248 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
1249 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1250
1251 /// C++ [expr.dynamic.cast]p9:
1252 /// A failed cast to reference type throws std::bad_cast
1253 if (DestTy->isReferenceType()) {
1254 llvm::BasicBlock *BadCastBlock =
1255 CGF.createBasicBlock("dynamic_cast.bad_cast");
1256
1257 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1258 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1259
1260 CGF.EmitBlock(BadCastBlock);
1261 EmitBadCastCall(CGF);
1262 }
1263
1264 return Value;
1265}
1266
1267llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001268 Address ThisAddr,
David Majnemer1162d252014-06-22 19:05:33 +00001269 QualType SrcRecordTy,
1270 QualType DestTy) {
1271 llvm::Type *PtrDiffLTy =
1272 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1273 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1274
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001275 auto *ClassDecl =
1276 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001277 // Get the vtable pointer.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001278 llvm::Value *VTable = CGF.GetVTablePtr(ThisAddr, PtrDiffLTy->getPointerTo(),
1279 ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001280
1281 // Get the offset-to-top from the vtable.
1282 llvm::Value *OffsetToTop =
1283 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001284 OffsetToTop =
1285 CGF.Builder.CreateAlignedLoad(OffsetToTop, CGF.getPointerAlign(),
1286 "offset.to.top");
David Majnemer1162d252014-06-22 19:05:33 +00001287
1288 // Finally, add the offset to the pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001289 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001290 Value = CGF.EmitCastToVoidPtr(Value);
1291 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1292
1293 return CGF.Builder.CreateBitCast(Value, DestLTy);
1294}
1295
1296bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1297 llvm::Value *Fn = getBadCastFn(CGF);
1298 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1299 CGF.Builder.CreateUnreachable();
1300 return true;
1301}
1302
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001303llvm::Value *
1304ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001305 Address This,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001306 const CXXRecordDecl *ClassDecl,
1307 const CXXRecordDecl *BaseClassDecl) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001308 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy, ClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001309 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001310 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1311 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001312
1313 llvm::Value *VBaseOffsetPtr =
1314 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1315 "vbase.offset.ptr");
1316 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1317 CGM.PtrDiffTy->getPointerTo());
1318
1319 llvm::Value *VBaseOffset =
John McCall7f416cc2015-09-08 08:05:57 +00001320 CGF.Builder.CreateAlignedLoad(VBaseOffsetPtr, CGF.getPointerAlign(),
1321 "vbase.offset");
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001322
1323 return VBaseOffset;
1324}
1325
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001326void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1327 // Just make sure we're in sync with TargetCXXABI.
1328 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1329
Rafael Espindolac3cde362013-12-09 14:51:17 +00001330 // The constructor used for constructing this as a base class;
1331 // ignores virtual bases.
1332 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1333
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001334 // The constructor used for constructing this as a complete class;
Nico Weber4c2ffb22015-01-07 05:25:05 +00001335 // constructs the virtual bases, then calls the base constructor.
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001336 if (!D->getParent()->isAbstract()) {
1337 // We don't need to emit the complete ctor if the class is abstract.
1338 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1339 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001340}
1341
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001342void
1343ItaniumCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
1344 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +00001345 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001346
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001347 // All parameters are already in place except VTT, which goes after 'this'.
1348 // These are Clang types, so we don't need to worry about sret yet.
John McCall5d865c322010-08-31 07:33:07 +00001349
1350 // Check if we need to add a VTT parameter (which has type void **).
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001351 if (T == StructorType::Base && MD->getParent()->getNumVBases() != 0)
1352 ArgTys.insert(ArgTys.begin() + 1,
1353 Context.getPointerType(Context.VoidPtrTy));
John McCall5d865c322010-08-31 07:33:07 +00001354}
1355
Reid Klecknere7de47e2013-07-22 13:51:44 +00001356void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
Rafael Espindolac3cde362013-12-09 14:51:17 +00001357 // The destructor used for destructing this as a base class; ignores
1358 // virtual bases.
1359 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001360
1361 // The destructor used for destructing this as a most-derived class;
1362 // call the base destructor and then destructs any virtual bases.
1363 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1364
Rafael Espindolac3cde362013-12-09 14:51:17 +00001365 // The destructor in a virtual table is always a 'deleting'
1366 // destructor, which calls the complete destructor and then uses the
1367 // appropriate operator delete.
1368 if (D->isVirtual())
1369 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001370}
1371
Reid Kleckner89077a12013-12-17 19:46:40 +00001372void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1373 QualType &ResTy,
1374 FunctionArgList &Params) {
John McCall5d865c322010-08-31 07:33:07 +00001375 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +00001376 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
John McCall5d865c322010-08-31 07:33:07 +00001377
1378 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001379 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +00001380 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001381
1382 // FIXME: avoid the fake decl
1383 QualType T = Context.getPointerType(Context.VoidPtrTy);
1384 ImplicitParamDecl *VTTDecl
Craig Topper8a13c412014-05-21 05:09:00 +00001385 = ImplicitParamDecl::Create(Context, nullptr, MD->getLocation(),
John McCall5d865c322010-08-31 07:33:07 +00001386 &Context.Idents.get("vtt"), T);
Reid Kleckner89077a12013-12-17 19:46:40 +00001387 Params.insert(Params.begin() + 1, VTTDecl);
Reid Kleckner2af6d732013-12-13 00:09:59 +00001388 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +00001389 }
1390}
1391
John McCall5d865c322010-08-31 07:33:07 +00001392void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
Justin Lebared4f1722016-07-27 22:04:24 +00001393 // Naked functions have no prolog.
1394 if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>())
1395 return;
1396
John McCall5d865c322010-08-31 07:33:07 +00001397 /// Initialize the 'this' slot.
1398 EmitThisParam(CGF);
1399
1400 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +00001401 if (getStructorImplicitParamDecl(CGF)) {
1402 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1403 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +00001404 }
John McCall5d865c322010-08-31 07:33:07 +00001405
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001406 /// If this is a function that the ABI specifies returns 'this', initialize
1407 /// the return slot to 'this' at the start of the function.
1408 ///
1409 /// Unlike the setting of return types, this is done within the ABI
1410 /// implementation instead of by clients of CGCXXABI because:
1411 /// 1) getThisValue is currently protected
1412 /// 2) in theory, an ABI could implement 'this' returns some other way;
1413 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +00001414 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +00001415 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +00001416}
1417
Reid Kleckner89077a12013-12-17 19:46:40 +00001418unsigned ItaniumCXXABI::addImplicitConstructorArgs(
1419 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1420 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1421 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
1422 return 0;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001423
Reid Kleckner89077a12013-12-17 19:46:40 +00001424 // Insert the implicit 'vtt' argument as the second argument.
1425 llvm::Value *VTT =
1426 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1427 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1428 Args.insert(Args.begin() + 1,
1429 CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false));
1430 return 1; // Added one arg.
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001431}
1432
1433void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1434 const CXXDestructorDecl *DD,
1435 CXXDtorType Type, bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +00001436 bool Delegating, Address This) {
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001437 GlobalDecl GD(DD, Type);
1438 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1439 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1440
Craig Topper8a13c412014-05-21 05:09:00 +00001441 llvm::Value *Callee = nullptr;
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001442 if (getContext().getLangOpts().AppleKext)
1443 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
1444
1445 if (!Callee)
Rafael Espindola1ac0ec82014-09-11 15:42:06 +00001446 Callee = CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type));
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001447
John McCall7f416cc2015-09-08 08:05:57 +00001448 CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(),
1449 This.getPointer(), VTT, VTTTy, nullptr);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001450}
1451
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001452void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1453 const CXXRecordDecl *RD) {
1454 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1455 if (VTable->hasInitializer())
1456 return;
1457
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001458 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001459 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1460 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
David Majnemerd905da42014-07-01 20:30:31 +00001461 llvm::Constant *RTTI =
1462 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001463
1464 // Create and set the initializer.
Peter Collingbournee53683f2016-09-08 01:14:39 +00001465 llvm::Constant *Init = CGVT.CreateVTableInitializer(VTLayout, RTTI);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001466 VTable->setInitializer(Init);
1467
1468 // Set the correct linkage.
1469 VTable->setLinkage(Linkage);
1470
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001471 if (CGM.supportsCOMDAT() && VTable->isWeakForLinker())
1472 VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName()));
Rafael Espindolacb92c192015-01-15 23:18:01 +00001473
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001474 // Set the right visibility.
John McCall8f80a612014-02-08 00:41:16 +00001475 CGM.setGlobalVisibility(VTable, RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001476
Benjamin Kramer5d34a2b2014-09-10 12:50:59 +00001477 // Use pointer alignment for the vtable. Otherwise we would align them based
1478 // on the size of the initializer which doesn't make sense as only single
1479 // values are read.
1480 unsigned PAlign = CGM.getTarget().getPointerAlign(0);
1481 VTable->setAlignment(getContext().toCharUnitsFromBits(PAlign).getQuantity());
1482
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001483 // If this is the magic class __cxxabiv1::__fundamental_type_info,
1484 // we will emit the typeinfo for the fundamental types. This is the
1485 // same behaviour as GCC.
1486 const DeclContext *DC = RD->getDeclContext();
1487 if (RD->getIdentifier() &&
1488 RD->getIdentifier()->isStr("__fundamental_type_info") &&
1489 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1490 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1491 DC->getParent()->isTranslationUnit())
David Majnemere2cb8d12014-07-07 06:20:47 +00001492 EmitFundamentalRTTIDescriptors();
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001493
Evgeniy Stepanov93987df2016-01-23 01:20:18 +00001494 if (!VTable->isDeclarationForLinker())
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001495 CGM.EmitVTableTypeMetadata(VTable, VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001496}
1497
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001498bool ItaniumCXXABI::isVirtualOffsetNeededForVTableField(
1499 CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
1500 if (Vptr.NearestVBase == nullptr)
1501 return false;
1502 return NeedsVTTParameter(CGF.CurGD);
Piotr Padlewski255652e2015-09-09 22:20:28 +00001503}
1504
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001505llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1506 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1507 const CXXRecordDecl *NearestVBase) {
1508
1509 if ((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1510 NeedsVTTParameter(CGF.CurGD)) {
1511 return getVTableAddressPointInStructorWithVTT(CGF, VTableClass, Base,
1512 NearestVBase);
1513 }
1514 return getVTableAddressPoint(Base, VTableClass);
1515}
1516
1517llvm::Constant *
1518ItaniumCXXABI::getVTableAddressPoint(BaseSubobject Base,
1519 const CXXRecordDecl *VTableClass) {
1520 llvm::GlobalValue *VTable = getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001521
1522 // Find the appropriate vtable within the vtable group.
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001523 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1524 .getVTableLayout(VTableClass)
1525 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001526 llvm::Value *Indices[] = {
Peter Collingbourne4e6a5402016-03-14 19:07:10 +00001527 llvm::ConstantInt::get(CGM.Int32Ty, 0),
1528 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint)
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001529 };
1530
David Blaikiee3b172a2015-04-02 18:55:21 +00001531 return llvm::ConstantExpr::getInBoundsGetElementPtr(VTable->getValueType(),
1532 VTable, Indices);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001533}
1534
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001535llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructorWithVTT(
1536 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1537 const CXXRecordDecl *NearestVBase) {
1538 assert((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1539 NeedsVTTParameter(CGF.CurGD) && "This class doesn't have VTT");
1540
1541 // Get the secondary vpointer index.
1542 uint64_t VirtualPointerIndex =
1543 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1544
1545 /// Load the VTT.
1546 llvm::Value *VTT = CGF.LoadCXXVTT();
1547 if (VirtualPointerIndex)
1548 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1549
1550 // And load the address point from the VTT.
1551 return CGF.Builder.CreateAlignedLoad(VTT, CGF.getPointerAlign());
1552}
1553
1554llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1555 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1556 return getVTableAddressPoint(Base, VTableClass);
1557}
1558
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001559llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1560 CharUnits VPtrOffset) {
1561 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1562
1563 llvm::GlobalVariable *&VTable = VTables[RD];
1564 if (VTable)
1565 return VTable;
1566
Eric Christopherd160c502016-01-29 01:35:53 +00001567 // Queue up this vtable for possible deferred emission.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001568 CGM.addDeferredVTable(RD);
1569
Yaron Kerene46f7ed2015-07-29 14:21:47 +00001570 SmallString<256> Name;
1571 llvm::raw_svector_ostream Out(Name);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001572 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001573
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001574 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001575 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
Peter Collingbournee53683f2016-09-08 01:14:39 +00001576 CGM.Int8PtrTy, VTContext.getVTableLayout(RD).vtable_components().size());
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001577
1578 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
1579 Name, ArrayType, llvm::GlobalValue::ExternalLinkage);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001580 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Hans Wennborgda24e9c2014-06-02 23:13:03 +00001581
1582 if (RD->hasAttr<DLLImportAttr>())
1583 VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1584 else if (RD->hasAttr<DLLExportAttr>())
1585 VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1586
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001587 return VTable;
1588}
1589
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001590llvm::Value *ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1591 GlobalDecl GD,
John McCall7f416cc2015-09-08 08:05:57 +00001592 Address This,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001593 llvm::Type *Ty,
1594 SourceLocation Loc) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001595 GD = GD.getCanonicalDecl();
1596 Ty = Ty->getPointerTo()->getPointerTo();
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001597 auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
1598 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty, MethodDecl->getParent());
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001599
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001600 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001601 if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) {
1602 return CGF.EmitVTableTypeCheckedLoad(
1603 MethodDecl->getParent(), VTable,
1604 VTableIndex * CGM.getContext().getTargetInfo().getPointerWidth(0) / 8);
1605 } else {
1606 CGF.EmitTypeMetadataCodeForVCall(MethodDecl->getParent(), VTable, Loc);
1607
1608 llvm::Value *VFuncPtr =
1609 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1610 return CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign());
1611 }
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001612}
1613
David Majnemer0c0b6d92014-10-31 20:09:12 +00001614llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
1615 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
John McCall7f416cc2015-09-08 08:05:57 +00001616 Address This, const CXXMemberCallExpr *CE) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001617 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001618 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1619
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001620 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1621 Dtor, getFromDtorType(DtorType));
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001622 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001623 llvm::Value *Callee =
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001624 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty,
1625 CE ? CE->getLocStart() : SourceLocation());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001626
John McCall7f416cc2015-09-08 08:05:57 +00001627 CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(),
1628 This.getPointer(), /*ImplicitParam=*/nullptr,
1629 QualType(), CE);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001630 return nullptr;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001631}
1632
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001633void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001634 CodeGenVTables &VTables = CGM.getVTables();
1635 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001636 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001637}
1638
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001639bool ItaniumCXXABI::canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const {
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001640 // We don't emit available_externally vtables if we are in -fapple-kext mode
1641 // because kext mode does not permit devirtualization.
1642 if (CGM.getLangOpts().AppleKext)
1643 return false;
1644
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001645 // If we don't have any inline virtual functions, and if vtable is not hidden,
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001646 // then we are safe to emit available_externally copy of vtable.
1647 // FIXME we can still emit a copy of the vtable if we
1648 // can emit definition of the inline functions.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001649 return !hasAnyUsedVirtualInlineFunction(RD) && !isVTableHidden(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001650}
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001651static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001652 Address InitialPtr,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001653 int64_t NonVirtualAdjustment,
1654 int64_t VirtualAdjustment,
1655 bool IsReturnAdjustment) {
1656 if (!NonVirtualAdjustment && !VirtualAdjustment)
John McCall7f416cc2015-09-08 08:05:57 +00001657 return InitialPtr.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001658
John McCall7f416cc2015-09-08 08:05:57 +00001659 Address V = CGF.Builder.CreateElementBitCast(InitialPtr, CGF.Int8Ty);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001660
John McCall7f416cc2015-09-08 08:05:57 +00001661 // In a base-to-derived cast, the non-virtual adjustment is applied first.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001662 if (NonVirtualAdjustment && !IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001663 V = CGF.Builder.CreateConstInBoundsByteGEP(V,
1664 CharUnits::fromQuantity(NonVirtualAdjustment));
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001665 }
1666
John McCall7f416cc2015-09-08 08:05:57 +00001667 // Perform the virtual adjustment if we have one.
1668 llvm::Value *ResultPtr;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001669 if (VirtualAdjustment) {
1670 llvm::Type *PtrDiffTy =
1671 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1672
John McCall7f416cc2015-09-08 08:05:57 +00001673 Address VTablePtrPtr = CGF.Builder.CreateElementBitCast(V, CGF.Int8PtrTy);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001674 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1675
1676 llvm::Value *OffsetPtr =
1677 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1678
1679 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1680
1681 // Load the adjustment offset from the vtable.
John McCall7f416cc2015-09-08 08:05:57 +00001682 llvm::Value *Offset =
1683 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001684
1685 // Adjust our pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001686 ResultPtr = CGF.Builder.CreateInBoundsGEP(V.getPointer(), Offset);
1687 } else {
1688 ResultPtr = V.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001689 }
1690
John McCall7f416cc2015-09-08 08:05:57 +00001691 // In a derived-to-base conversion, the non-virtual adjustment is
1692 // applied second.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001693 if (NonVirtualAdjustment && IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001694 ResultPtr = CGF.Builder.CreateConstInBoundsGEP1_64(ResultPtr,
1695 NonVirtualAdjustment);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001696 }
1697
1698 // Cast back to the original type.
John McCall7f416cc2015-09-08 08:05:57 +00001699 return CGF.Builder.CreateBitCast(ResultPtr, InitialPtr.getType());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001700}
1701
1702llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001703 Address This,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001704 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001705 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1706 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001707 /*IsReturnAdjustment=*/false);
1708}
1709
1710llvm::Value *
John McCall7f416cc2015-09-08 08:05:57 +00001711ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001712 const ReturnAdjustment &RA) {
1713 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1714 RA.Virtual.Itanium.VBaseOffsetOffset,
1715 /*IsReturnAdjustment=*/true);
1716}
1717
John McCall5d865c322010-08-31 07:33:07 +00001718void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1719 RValue RV, QualType ResultType) {
1720 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1721 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1722
1723 // Destructor thunks in the ARM ABI have indeterminate results.
John McCall7f416cc2015-09-08 08:05:57 +00001724 llvm::Type *T = CGF.ReturnValue.getElementType();
John McCall5d865c322010-08-31 07:33:07 +00001725 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1726 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1727}
John McCall8ed55a52010-09-02 09:58:18 +00001728
1729/************************** Array allocation cookies **************************/
1730
John McCallb91cd662012-05-01 05:23:51 +00001731CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1732 // The array cookie is a size_t; pad that up to the element alignment.
1733 // The cookie is actually right-justified in that space.
1734 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1735 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001736}
1737
John McCall7f416cc2015-09-08 08:05:57 +00001738Address ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1739 Address NewPtr,
1740 llvm::Value *NumElements,
1741 const CXXNewExpr *expr,
1742 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001743 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001744
John McCall7f416cc2015-09-08 08:05:57 +00001745 unsigned AS = NewPtr.getAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001746
John McCall9bca9232010-09-02 10:25:57 +00001747 ASTContext &Ctx = getContext();
John McCall7f416cc2015-09-08 08:05:57 +00001748 CharUnits SizeSize = CGF.getSizeSize();
John McCall8ed55a52010-09-02 09:58:18 +00001749
1750 // The size of the cookie.
1751 CharUnits CookieSize =
1752 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001753 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001754
1755 // Compute an offset to the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001756 Address CookiePtr = NewPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001757 CharUnits CookieOffset = CookieSize - SizeSize;
1758 if (!CookieOffset.isZero())
John McCall7f416cc2015-09-08 08:05:57 +00001759 CookiePtr = CGF.Builder.CreateConstInBoundsByteGEP(CookiePtr, CookieOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001760
1761 // Write the number of elements into the appropriate slot.
John McCall7f416cc2015-09-08 08:05:57 +00001762 Address NumElementsPtr =
1763 CGF.Builder.CreateElementBitCast(CookiePtr, CGF.SizeTy);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001764 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
John McCall7f416cc2015-09-08 08:05:57 +00001765
1766 // Handle the array cookie specially in ASan.
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001767 if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 &&
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001768 expr->getOperatorNew()->isReplaceableGlobalAllocationFunction()) {
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001769 // The store to the CookiePtr does not need to be instrumented.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001770 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
1771 llvm::FunctionType *FTy =
John McCall7f416cc2015-09-08 08:05:57 +00001772 llvm::FunctionType::get(CGM.VoidTy, NumElementsPtr.getType(), false);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001773 llvm::Constant *F =
1774 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001775 CGF.Builder.CreateCall(F, NumElementsPtr.getPointer());
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001776 }
John McCall8ed55a52010-09-02 09:58:18 +00001777
1778 // Finally, compute a pointer to the actual data buffer by skipping
1779 // over the cookie completely.
John McCall7f416cc2015-09-08 08:05:57 +00001780 return CGF.Builder.CreateConstInBoundsByteGEP(NewPtr, CookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001781}
1782
John McCallb91cd662012-05-01 05:23:51 +00001783llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001784 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00001785 CharUnits cookieSize) {
1786 // The element size is right-justified in the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001787 Address numElementsPtr = allocPtr;
1788 CharUnits numElementsOffset = cookieSize - CGF.getSizeSize();
John McCallb91cd662012-05-01 05:23:51 +00001789 if (!numElementsOffset.isZero())
1790 numElementsPtr =
John McCall7f416cc2015-09-08 08:05:57 +00001791 CGF.Builder.CreateConstInBoundsByteGEP(numElementsPtr, numElementsOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001792
John McCall7f416cc2015-09-08 08:05:57 +00001793 unsigned AS = allocPtr.getAddressSpace();
1794 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001795 if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0)
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001796 return CGF.Builder.CreateLoad(numElementsPtr);
1797 // In asan mode emit a function call instead of a regular load and let the
1798 // run-time deal with it: if the shadow is properly poisoned return the
1799 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
1800 // We can't simply ignore this load using nosanitize metadata because
1801 // the metadata may be lost.
1802 llvm::FunctionType *FTy =
1803 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
1804 llvm::Constant *F =
1805 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001806 return CGF.Builder.CreateCall(F, numElementsPtr.getPointer());
John McCall8ed55a52010-09-02 09:58:18 +00001807}
1808
John McCallb91cd662012-05-01 05:23:51 +00001809CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001810 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001811 // struct array_cookie {
1812 // std::size_t element_size; // element_size != 0
1813 // std::size_t element_count;
1814 // };
John McCallc19c7062013-01-25 23:36:19 +00001815 // But the base ABI doesn't give anything an alignment greater than
1816 // 8, so we can dismiss this as typical ABI-author blindness to
1817 // actual language complexity and round up to the element alignment.
1818 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1819 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001820}
1821
John McCall7f416cc2015-09-08 08:05:57 +00001822Address ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1823 Address newPtr,
1824 llvm::Value *numElements,
1825 const CXXNewExpr *expr,
1826 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001827 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001828
John McCall8ed55a52010-09-02 09:58:18 +00001829 // The cookie is always at the start of the buffer.
John McCall7f416cc2015-09-08 08:05:57 +00001830 Address cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001831
1832 // The first element is the element size.
John McCall7f416cc2015-09-08 08:05:57 +00001833 cookie = CGF.Builder.CreateElementBitCast(cookie, CGF.SizeTy);
John McCallc19c7062013-01-25 23:36:19 +00001834 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1835 getContext().getTypeSizeInChars(elementType).getQuantity());
1836 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001837
1838 // The second element is the element count.
John McCall7f416cc2015-09-08 08:05:57 +00001839 cookie = CGF.Builder.CreateConstInBoundsGEP(cookie, 1, CGF.getSizeSize());
John McCallc19c7062013-01-25 23:36:19 +00001840 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001841
1842 // Finally, compute a pointer to the actual data buffer by skipping
1843 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001844 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
John McCall7f416cc2015-09-08 08:05:57 +00001845 return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001846}
1847
John McCallb91cd662012-05-01 05:23:51 +00001848llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001849 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00001850 CharUnits cookieSize) {
1851 // The number of elements is at offset sizeof(size_t) relative to
1852 // the allocated pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001853 Address numElementsPtr
1854 = CGF.Builder.CreateConstInBoundsByteGEP(allocPtr, CGF.getSizeSize());
John McCall8ed55a52010-09-02 09:58:18 +00001855
John McCall7f416cc2015-09-08 08:05:57 +00001856 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
John McCallb91cd662012-05-01 05:23:51 +00001857 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001858}
1859
John McCall68ff0372010-09-08 01:44:27 +00001860/*********************** Static local initialization **************************/
1861
1862static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001863 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001864 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001865 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001866 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001867 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001868 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001869 llvm::AttributeSet::get(CGM.getLLVMContext(),
1870 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001871 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001872}
1873
1874static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001875 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001876 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001877 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001878 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001879 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001880 llvm::AttributeSet::get(CGM.getLLVMContext(),
1881 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001882 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001883}
1884
1885static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001886 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001887 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001888 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001889 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001890 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001891 llvm::AttributeSet::get(CGM.getLLVMContext(),
1892 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001893 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001894}
1895
1896namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001897 struct CallGuardAbort final : EHScopeStack::Cleanup {
John McCall68ff0372010-09-08 01:44:27 +00001898 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001899 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001900
Craig Topper4f12f102014-03-12 06:41:41 +00001901 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00001902 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1903 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001904 }
1905 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001906}
John McCall68ff0372010-09-08 01:44:27 +00001907
1908/// The ARM code here follows the Itanium code closely enough that we
1909/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001910void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1911 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001912 llvm::GlobalVariable *var,
1913 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00001914 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00001915
Richard Smith62f19e72016-06-25 00:15:56 +00001916 // Inline variables that weren't instantiated from variable templates have
1917 // partially-ordered initialization within their translation unit.
1918 bool NonTemplateInline =
1919 D.isInline() &&
1920 !isTemplateInstantiation(D.getTemplateSpecializationKind());
1921
1922 // We only need to use thread-safe statics for local non-TLS variables and
1923 // inline variables; other global initialization is always single-threaded
1924 // or (through lazy dynamic loading in multiple threads) unsequenced.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001925 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
Richard Smith62f19e72016-06-25 00:15:56 +00001926 (D.isLocalVarDecl() || NonTemplateInline) &&
1927 !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001928
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001929 // If we have a global variable with internal linkage and thread-safe statics
1930 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00001931 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1932
1933 llvm::IntegerType *guardTy;
John McCall7f416cc2015-09-08 08:05:57 +00001934 CharUnits guardAlignment;
John McCall5aa52592011-06-17 07:33:57 +00001935 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00001936 guardTy = CGF.Int8Ty;
John McCall7f416cc2015-09-08 08:05:57 +00001937 guardAlignment = CharUnits::One();
John McCall5aa52592011-06-17 07:33:57 +00001938 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00001939 // Guard variables are 64 bits in the generic ABI and size width on ARM
1940 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
John McCall7f416cc2015-09-08 08:05:57 +00001941 if (UseARMGuardVarABI) {
1942 guardTy = CGF.SizeTy;
1943 guardAlignment = CGF.getSizeAlign();
1944 } else {
1945 guardTy = CGF.Int64Ty;
1946 guardAlignment = CharUnits::fromQuantity(
1947 CGM.getDataLayout().getABITypeAlignment(guardTy));
1948 }
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001949 }
John McCallb88a5662012-03-30 21:00:39 +00001950 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00001951
John McCallb88a5662012-03-30 21:00:39 +00001952 // Create the guard variable if we don't already have it (as we
1953 // might if we're double-emitting this function body).
1954 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1955 if (!guard) {
1956 // Mangle the name for the guard.
1957 SmallString<256> guardName;
1958 {
1959 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00001960 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00001961 }
John McCall8e7cb6d2010-11-02 21:04:24 +00001962
John McCallb88a5662012-03-30 21:00:39 +00001963 // Create the guard variable with a zero-initializer.
1964 // Just absorb linkage and visibility from the guarded variable.
1965 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1966 false, var->getLinkage(),
1967 llvm::ConstantInt::get(guardTy, 0),
1968 guardName.str());
1969 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00001970 // If the variable is thread-local, so is its guard variable.
1971 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCall7f416cc2015-09-08 08:05:57 +00001972 guard->setAlignment(guardAlignment.getQuantity());
John McCallb88a5662012-03-30 21:00:39 +00001973
Yaron Keren5bfa1082015-09-03 20:33:29 +00001974 // The ABI says: "It is suggested that it be emitted in the same COMDAT
1975 // group as the associated data object." In practice, this doesn't work for
1976 // non-ELF object formats, so only do it for ELF.
Rafael Espindola0d4fb982015-01-12 22:13:53 +00001977 llvm::Comdat *C = var->getComdat();
Yaron Keren5bfa1082015-09-03 20:33:29 +00001978 if (!D.isLocalVarDecl() && C &&
1979 CGM.getTarget().getTriple().isOSBinFormatELF()) {
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001980 guard->setComdat(C);
Richard Smith62f19e72016-06-25 00:15:56 +00001981 // An inline variable's guard function is run from the per-TU
1982 // initialization function, not via a dedicated global ctor function, so
1983 // we can't put it in a comdat.
1984 if (!NonTemplateInline)
1985 CGF.CurFn->setComdat(C);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001986 } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) {
1987 guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName()));
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001988 }
1989
John McCallb88a5662012-03-30 21:00:39 +00001990 CGM.setStaticLocalDeclGuardAddress(&D, guard);
1991 }
John McCall87590e62012-03-30 07:09:50 +00001992
John McCall7f416cc2015-09-08 08:05:57 +00001993 Address guardAddr = Address(guard, guardAlignment);
1994
John McCall68ff0372010-09-08 01:44:27 +00001995 // Test whether the variable has completed initialization.
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001996 //
John McCall68ff0372010-09-08 01:44:27 +00001997 // Itanium C++ ABI 3.3.2:
1998 // The following is pseudo-code showing how these functions can be used:
1999 // if (obj_guard.first_byte == 0) {
2000 // if ( __cxa_guard_acquire (&obj_guard) ) {
2001 // try {
2002 // ... initialize the object ...;
2003 // } catch (...) {
2004 // __cxa_guard_abort (&obj_guard);
2005 // throw;
2006 // }
2007 // ... queue object destructor with __cxa_atexit() ...;
2008 // __cxa_guard_release (&obj_guard);
2009 // }
2010 // }
Tim Northovera2ee4332014-03-29 15:09:45 +00002011
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002012 // Load the first byte of the guard variable.
2013 llvm::LoadInst *LI =
John McCall7f416cc2015-09-08 08:05:57 +00002014 Builder.CreateLoad(Builder.CreateElementBitCast(guardAddr, CGM.Int8Ty));
John McCall68ff0372010-09-08 01:44:27 +00002015
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002016 // Itanium ABI:
2017 // An implementation supporting thread-safety on multiprocessor
2018 // systems must also guarantee that references to the initialized
2019 // object do not occur before the load of the initialization flag.
2020 //
2021 // In LLVM, we do this by marking the load Acquire.
2022 if (threadsafe)
JF Bastien92f4ef12016-04-06 17:26:42 +00002023 LI->setAtomic(llvm::AtomicOrdering::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00002024
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002025 // For ARM, we should only check the first bit, rather than the entire byte:
2026 //
2027 // ARM C++ ABI 3.2.3.1:
2028 // To support the potential use of initialization guard variables
2029 // as semaphores that are the target of ARM SWP and LDREX/STREX
2030 // synchronizing instructions we define a static initialization
2031 // guard variable to be a 4-byte aligned, 4-byte word with the
2032 // following inline access protocol.
2033 // #define INITIALIZED 1
2034 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
2035 // if (__cxa_guard_acquire(&obj_guard))
2036 // ...
2037 // }
2038 //
2039 // and similarly for ARM64:
2040 //
2041 // ARM64 C++ ABI 3.2.2:
2042 // This ABI instead only specifies the value bit 0 of the static guard
2043 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
2044 // variable is not initialized and 1 when it is.
2045 llvm::Value *V =
2046 (UseARMGuardVarABI && !useInt8GuardVariable)
2047 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
2048 : LI;
2049 llvm::Value *isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00002050
2051 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
2052 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2053
2054 // Check if the first byte of the guard variable is zero.
John McCallb88a5662012-03-30 21:00:39 +00002055 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall68ff0372010-09-08 01:44:27 +00002056
2057 CGF.EmitBlock(InitCheckBlock);
2058
2059 // Variables used when coping with thread-safe statics and exceptions.
John McCall5aa52592011-06-17 07:33:57 +00002060 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002061 // Call __cxa_guard_acquire.
2062 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00002063 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00002064
2065 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2066
2067 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
2068 InitBlock, EndBlock);
2069
2070 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00002071 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall68ff0372010-09-08 01:44:27 +00002072
2073 CGF.EmitBlock(InitBlock);
2074 }
2075
2076 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00002077 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00002078
John McCall5aa52592011-06-17 07:33:57 +00002079 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002080 // Pop the guard-abort cleanup if we pushed one.
2081 CGF.PopCleanupBlock();
2082
2083 // Call __cxa_guard_release. This cannot throw.
John McCall7f416cc2015-09-08 08:05:57 +00002084 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy),
2085 guardAddr.getPointer());
John McCall68ff0372010-09-08 01:44:27 +00002086 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002087 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guardAddr);
John McCall68ff0372010-09-08 01:44:27 +00002088 }
2089
2090 CGF.EmitBlock(EndBlock);
2091}
John McCallc84ed6a2012-05-01 06:13:13 +00002092
2093/// Register a global destructor using __cxa_atexit.
2094static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
2095 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00002096 llvm::Constant *addr,
2097 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00002098 const char *Name = "__cxa_atexit";
2099 if (TLS) {
2100 const llvm::Triple &T = CGF.getTarget().getTriple();
Manman Renf93fff22015-11-11 23:08:18 +00002101 Name = T.isOSDarwin() ? "_tlv_atexit" : "__cxa_thread_atexit";
Bill Wendling95cae882013-05-02 19:18:03 +00002102 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00002103
John McCallc84ed6a2012-05-01 06:13:13 +00002104 // We're assuming that the destructor function is something we can
2105 // reasonably call with the default CC. Go ahead and cast it to the
2106 // right prototype.
2107 llvm::Type *dtorTy =
2108 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
2109
2110 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
2111 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
2112 llvm::FunctionType *atexitTy =
2113 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
2114
2115 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002116 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00002117 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
2118 fn->setDoesNotThrow();
2119
2120 // Create a variable that binds the atexit to this shared object.
2121 llvm::Constant *handle =
2122 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
2123
2124 llvm::Value *args[] = {
2125 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
2126 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
2127 handle
2128 };
John McCall882987f2013-02-28 19:01:20 +00002129 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00002130}
2131
2132/// Register a global destructor as best as we know how.
2133void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00002134 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00002135 llvm::Constant *dtor,
2136 llvm::Constant *addr) {
2137 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002138 if (CGM.getCodeGenOpts().CXAAtExit)
2139 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
2140
2141 if (D.getTLSKind())
2142 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00002143
2144 // In Apple kexts, we want to add a global destructor entry.
2145 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00002146 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00002147 // Generate a global destructor entry.
2148 return CGM.AddCXXDtorEntry(dtor, addr);
2149 }
2150
David Blaikieebe87e12013-08-27 23:57:18 +00002151 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00002152}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002153
David Majnemer9b21c332014-07-11 20:28:10 +00002154static bool isThreadWrapperReplaceable(const VarDecl *VD,
2155 CodeGen::CodeGenModule &CGM) {
2156 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
Manman Renf93fff22015-11-11 23:08:18 +00002157 // Darwin prefers to have references to thread local variables to go through
David Majnemer9b21c332014-07-11 20:28:10 +00002158 // the thread wrapper instead of directly referencing the backing variable.
2159 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
Manman Renf93fff22015-11-11 23:08:18 +00002160 CGM.getTarget().getTriple().isOSDarwin();
David Majnemer9b21c332014-07-11 20:28:10 +00002161}
2162
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002163/// Get the appropriate linkage for the wrapper function. This is essentially
David Majnemer4632e1e2014-06-27 16:56:27 +00002164/// the weak form of the variable's linkage; every translation unit which needs
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002165/// the wrapper emits a copy, and we want the linker to merge them.
David Majnemer35ab3282014-06-11 04:08:55 +00002166static llvm::GlobalValue::LinkageTypes
2167getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
2168 llvm::GlobalValue::LinkageTypes VarLinkage =
2169 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
2170
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002171 // For internal linkage variables, we don't need an external or weak wrapper.
2172 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
2173 return VarLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00002174
David Majnemer9b21c332014-07-11 20:28:10 +00002175 // If the thread wrapper is replaceable, give it appropriate linkage.
Manman Ren68150262015-11-11 22:42:31 +00002176 if (isThreadWrapperReplaceable(VD, CGM))
2177 if (!llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) &&
2178 !llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
2179 return VarLinkage;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002180 return llvm::GlobalValue::WeakODRLinkage;
2181}
2182
2183llvm::Function *
2184ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +00002185 llvm::Value *Val) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002186 // Mangle the name for the thread_local wrapper function.
2187 SmallString<256> WrapperName;
2188 {
2189 llvm::raw_svector_ostream Out(WrapperName);
2190 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002191 }
2192
Akira Hatanaka26907f92016-01-15 03:34:06 +00002193 // FIXME: If VD is a definition, we should regenerate the function attributes
2194 // before returning.
Alexander Musmanf94c3182014-09-26 06:28:25 +00002195 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002196 return cast<llvm::Function>(V);
2197
Akira Hatanaka26907f92016-01-15 03:34:06 +00002198 QualType RetQT = VD->getType();
2199 if (RetQT->isReferenceType())
2200 RetQT = RetQT.getNonReferenceType();
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002201
John McCallc56a8b32016-03-11 04:30:31 +00002202 const CGFunctionInfo &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2203 getContext().getPointerType(RetQT), FunctionArgList());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002204
2205 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FI);
David Majnemer35ab3282014-06-11 04:08:55 +00002206 llvm::Function *Wrapper =
2207 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
2208 WrapperName.str(), &CGM.getModule());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002209
2210 CGM.SetLLVMFunctionAttributes(nullptr, FI, Wrapper);
2211
2212 if (VD->hasDefinition())
2213 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Wrapper);
2214
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002215 // Always resolve references to the wrapper at link time.
Manman Ren68150262015-11-11 22:42:31 +00002216 if (!Wrapper->hasLocalLinkage() && !(isThreadWrapperReplaceable(VD, CGM) &&
2217 !llvm::GlobalVariable::isLinkOnceLinkage(Wrapper->getLinkage()) &&
2218 !llvm::GlobalVariable::isWeakODRLinkage(Wrapper->getLinkage())))
Duncan P. N. Exon Smith4434d362014-05-07 22:36:11 +00002219 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
Manman Renb0b3af72015-12-17 00:42:36 +00002220
2221 if (isThreadWrapperReplaceable(VD, CGM)) {
2222 Wrapper->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2223 Wrapper->addFnAttr(llvm::Attribute::NoUnwind);
2224 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002225 return Wrapper;
2226}
2227
2228void ItaniumCXXABI::EmitThreadLocalInitFuncs(
Richard Smith5a99c492015-12-01 01:10:48 +00002229 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
2230 ArrayRef<llvm::Function *> CXXThreadLocalInits,
2231 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
David Majnemerb3341ea2014-10-05 05:05:40 +00002232 llvm::Function *InitFunc = nullptr;
2233 if (!CXXThreadLocalInits.empty()) {
2234 // Generate a guarded initialization function.
2235 llvm::FunctionType *FTy =
2236 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002237 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2238 InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init", FI,
Alexey Samsonov1444bb92014-10-17 00:20:19 +00002239 SourceLocation(),
David Majnemerb3341ea2014-10-05 05:05:40 +00002240 /*TLS=*/true);
2241 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
2242 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
2243 llvm::GlobalVariable::InternalLinkage,
2244 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
2245 Guard->setThreadLocal(true);
John McCall7f416cc2015-09-08 08:05:57 +00002246
2247 CharUnits GuardAlign = CharUnits::One();
2248 Guard->setAlignment(GuardAlign.getQuantity());
2249
David Majnemerb3341ea2014-10-05 05:05:40 +00002250 CodeGenFunction(CGM)
John McCall7f416cc2015-09-08 08:05:57 +00002251 .GenerateCXXGlobalInitFunc(InitFunc, CXXThreadLocalInits,
2252 Address(Guard, GuardAlign));
Manman Ren5e5d0462016-03-18 23:35:21 +00002253 // On Darwin platforms, use CXX_FAST_TLS calling convention.
2254 if (CGM.getTarget().getTriple().isOSDarwin()) {
2255 InitFunc->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2256 InitFunc->addFnAttr(llvm::Attribute::NoUnwind);
2257 }
David Majnemerb3341ea2014-10-05 05:05:40 +00002258 }
Richard Smith5a99c492015-12-01 01:10:48 +00002259 for (const VarDecl *VD : CXXThreadLocals) {
2260 llvm::GlobalVariable *Var =
2261 cast<llvm::GlobalVariable>(CGM.GetGlobalValue(CGM.getMangledName(VD)));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002262
David Majnemer9b21c332014-07-11 20:28:10 +00002263 // Some targets require that all access to thread local variables go through
2264 // the thread wrapper. This means that we cannot attempt to create a thread
2265 // wrapper or a thread helper.
2266 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition())
2267 continue;
2268
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002269 // Mangle the name for the thread_local initialization function.
2270 SmallString<256> InitFnName;
2271 {
2272 llvm::raw_svector_ostream Out(InitFnName);
2273 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002274 }
2275
2276 // If we have a definition for the variable, emit the initialization
2277 // function as an alias to the global Init function (if any). Otherwise,
2278 // produce a declaration of the initialization function.
Craig Topper8a13c412014-05-21 05:09:00 +00002279 llvm::GlobalValue *Init = nullptr;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002280 bool InitIsInitFunc = false;
2281 if (VD->hasDefinition()) {
2282 InitIsInitFunc = true;
2283 if (InitFunc)
Rafael Espindola234405b2014-05-17 21:30:14 +00002284 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
2285 InitFunc);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002286 } else {
2287 // Emit a weak global function referring to the initialization function.
2288 // This function will not exist if the TU defining the thread_local
2289 // variable in question does not need any dynamic initialization for
2290 // its thread_local variables.
2291 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
2292 Init = llvm::Function::Create(
2293 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
2294 &CGM.getModule());
John McCallc56a8b32016-03-11 04:30:31 +00002295 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
Akira Hatanaka26907f92016-01-15 03:34:06 +00002296 CGM.SetLLVMFunctionAttributes(nullptr, FI, cast<llvm::Function>(Init));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002297 }
2298
2299 if (Init)
2300 Init->setVisibility(Var->getVisibility());
2301
2302 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
2303 llvm::LLVMContext &Context = CGM.getModule().getContext();
2304 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
John McCall7f416cc2015-09-08 08:05:57 +00002305 CGBuilderTy Builder(CGM, Entry);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002306 if (InitIsInitFunc) {
Manman Ren5e5d0462016-03-18 23:35:21 +00002307 if (Init) {
2308 llvm::CallInst *CallVal = Builder.CreateCall(Init);
2309 if (isThreadWrapperReplaceable(VD, CGM))
2310 CallVal->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2311 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002312 } else {
2313 // Don't know whether we have an init function. Call it if it exists.
2314 llvm::Value *Have = Builder.CreateIsNotNull(Init);
2315 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2316 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2317 Builder.CreateCondBr(Have, InitBB, ExitBB);
2318
2319 Builder.SetInsertPoint(InitBB);
David Blaikie4ba525b2015-07-14 17:27:39 +00002320 Builder.CreateCall(Init);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002321 Builder.CreateBr(ExitBB);
2322
2323 Builder.SetInsertPoint(ExitBB);
2324 }
2325
2326 // For a reference, the result of the wrapper function is a pointer to
2327 // the referenced object.
2328 llvm::Value *Val = Var;
2329 if (VD->getType()->isReferenceType()) {
John McCall7f416cc2015-09-08 08:05:57 +00002330 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2331 Val = Builder.CreateAlignedLoad(Val, Align);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002332 }
Alexander Musmanf94c3182014-09-26 06:28:25 +00002333 if (Val->getType() != Wrapper->getReturnType())
2334 Val = Builder.CreatePointerBitCastOrAddrSpaceCast(
2335 Val, Wrapper->getReturnType(), "");
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002336 Builder.CreateRet(Val);
2337 }
2338}
2339
Richard Smith0f383742014-03-26 22:48:22 +00002340LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2341 const VarDecl *VD,
2342 QualType LValType) {
Richard Smith5a99c492015-12-01 01:10:48 +00002343 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD);
Alexander Musmanf94c3182014-09-26 06:28:25 +00002344 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002345
Manman Renb0b3af72015-12-17 00:42:36 +00002346 llvm::CallInst *CallVal = CGF.Builder.CreateCall(Wrapper);
Saleem Abdulrasool4a7130a2016-08-01 21:31:24 +00002347 CallVal->setCallingConv(Wrapper->getCallingConv());
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002348
2349 LValue LV;
2350 if (VD->getType()->isReferenceType())
Manman Renb0b3af72015-12-17 00:42:36 +00002351 LV = CGF.MakeNaturalAlignAddrLValue(CallVal, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002352 else
Manman Renb0b3af72015-12-17 00:42:36 +00002353 LV = CGF.MakeAddrLValue(CallVal, LValType,
2354 CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002355 // FIXME: need setObjCGCLValueClass?
2356 return LV;
2357}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002358
2359/// Return whether the given global decl needs a VTT parameter, which it does
2360/// if it's a base constructor or destructor with virtual bases.
2361bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
2362 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
2363
2364 // We don't have any virtual bases, just return early.
2365 if (!MD->getParent()->getNumVBases())
2366 return false;
2367
2368 // Check if we have a base constructor.
2369 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
2370 return true;
2371
2372 // Check if we have a base destructor.
2373 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2374 return true;
2375
2376 return false;
2377}
David Majnemere2cb8d12014-07-07 06:20:47 +00002378
2379namespace {
2380class ItaniumRTTIBuilder {
2381 CodeGenModule &CGM; // Per-module state.
2382 llvm::LLVMContext &VMContext;
2383 const ItaniumCXXABI &CXXABI; // Per-module state.
2384
2385 /// Fields - The fields of the RTTI descriptor currently being built.
2386 SmallVector<llvm::Constant *, 16> Fields;
2387
2388 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2389 llvm::GlobalVariable *
2390 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2391
2392 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2393 /// descriptor of the given type.
2394 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2395
2396 /// BuildVTablePointer - Build the vtable pointer for the given type.
2397 void BuildVTablePointer(const Type *Ty);
2398
2399 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2400 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2401 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2402
2403 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2404 /// classes with bases that do not satisfy the abi::__si_class_type_info
2405 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2406 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2407
2408 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2409 /// for pointer types.
2410 void BuildPointerTypeInfo(QualType PointeeTy);
2411
2412 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2413 /// type_info for an object type.
2414 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2415
2416 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2417 /// struct, used for member pointer types.
2418 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2419
2420public:
2421 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2422 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2423
2424 // Pointer type info flags.
2425 enum {
2426 /// PTI_Const - Type has const qualifier.
2427 PTI_Const = 0x1,
2428
2429 /// PTI_Volatile - Type has volatile qualifier.
2430 PTI_Volatile = 0x2,
2431
2432 /// PTI_Restrict - Type has restrict qualifier.
2433 PTI_Restrict = 0x4,
2434
2435 /// PTI_Incomplete - Type is incomplete.
2436 PTI_Incomplete = 0x8,
2437
2438 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2439 /// (in pointer to member).
2440 PTI_ContainingClassIncomplete = 0x10
2441 };
2442
2443 // VMI type info flags.
2444 enum {
2445 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2446 VMI_NonDiamondRepeat = 0x1,
2447
2448 /// VMI_DiamondShaped - Class is diamond shaped.
2449 VMI_DiamondShaped = 0x2
2450 };
2451
2452 // Base class type info flags.
2453 enum {
2454 /// BCTI_Virtual - Base class is virtual.
2455 BCTI_Virtual = 0x1,
2456
2457 /// BCTI_Public - Base class is public.
2458 BCTI_Public = 0x2
2459 };
2460
2461 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
2462 ///
2463 /// \param Force - true to force the creation of this RTTI value
2464 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false);
2465};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002466}
David Majnemere2cb8d12014-07-07 06:20:47 +00002467
2468llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2469 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002470 SmallString<256> Name;
2471 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002472 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002473
2474 // We know that the mangled name of the type starts at index 4 of the
2475 // mangled name of the typename, so we can just index into it in order to
2476 // get the mangled name of the type.
2477 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2478 Name.substr(4));
2479
2480 llvm::GlobalVariable *GV =
2481 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
2482
2483 GV->setInitializer(Init);
2484
2485 return GV;
2486}
2487
2488llvm::Constant *
2489ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2490 // Mangle the RTTI name.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002491 SmallString<256> Name;
2492 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002493 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002494
2495 // Look for an existing global.
2496 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2497
2498 if (!GV) {
2499 // Create a new global variable.
2500 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2501 /*Constant=*/true,
2502 llvm::GlobalValue::ExternalLinkage, nullptr,
2503 Name);
David Majnemer1fb1a042014-11-07 07:26:38 +00002504 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2505 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2506 if (RD->hasAttr<DLLImportAttr>())
2507 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2508 }
David Majnemere2cb8d12014-07-07 06:20:47 +00002509 }
2510
2511 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2512}
2513
2514/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2515/// info for that type is defined in the standard library.
2516static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2517 // Itanium C++ ABI 2.9.2:
2518 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
2519 // the run-time support library. Specifically, the run-time support
2520 // library should contain type_info objects for the types X, X* and
2521 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2522 // unsigned char, signed char, short, unsigned short, int, unsigned int,
2523 // long, unsigned long, long long, unsigned long long, float, double,
2524 // long double, char16_t, char32_t, and the IEEE 754r decimal and
2525 // half-precision floating point types.
Richard Smith4a382012016-02-03 01:32:42 +00002526 //
2527 // GCC also emits RTTI for __int128.
2528 // FIXME: We do not emit RTTI information for decimal types here.
2529
2530 // Types added here must also be added to EmitFundamentalRTTIDescriptors.
David Majnemere2cb8d12014-07-07 06:20:47 +00002531 switch (Ty->getKind()) {
2532 case BuiltinType::Void:
2533 case BuiltinType::NullPtr:
2534 case BuiltinType::Bool:
2535 case BuiltinType::WChar_S:
2536 case BuiltinType::WChar_U:
2537 case BuiltinType::Char_U:
2538 case BuiltinType::Char_S:
2539 case BuiltinType::UChar:
2540 case BuiltinType::SChar:
2541 case BuiltinType::Short:
2542 case BuiltinType::UShort:
2543 case BuiltinType::Int:
2544 case BuiltinType::UInt:
2545 case BuiltinType::Long:
2546 case BuiltinType::ULong:
2547 case BuiltinType::LongLong:
2548 case BuiltinType::ULongLong:
2549 case BuiltinType::Half:
2550 case BuiltinType::Float:
2551 case BuiltinType::Double:
2552 case BuiltinType::LongDouble:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002553 case BuiltinType::Float128:
David Majnemere2cb8d12014-07-07 06:20:47 +00002554 case BuiltinType::Char16:
2555 case BuiltinType::Char32:
2556 case BuiltinType::Int128:
2557 case BuiltinType::UInt128:
Richard Smith4a382012016-02-03 01:32:42 +00002558 return true;
2559
Alexey Bader954ba212016-04-08 13:40:33 +00002560#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2561 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00002562#include "clang/Basic/OpenCLImageTypes.def"
David Majnemere2cb8d12014-07-07 06:20:47 +00002563 case BuiltinType::OCLSampler:
2564 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002565 case BuiltinType::OCLClkEvent:
2566 case BuiltinType::OCLQueue:
2567 case BuiltinType::OCLNDRange:
2568 case BuiltinType::OCLReserveID:
Richard Smith4a382012016-02-03 01:32:42 +00002569 return false;
David Majnemere2cb8d12014-07-07 06:20:47 +00002570
2571 case BuiltinType::Dependent:
2572#define BUILTIN_TYPE(Id, SingletonId)
2573#define PLACEHOLDER_TYPE(Id, SingletonId) \
2574 case BuiltinType::Id:
2575#include "clang/AST/BuiltinTypes.def"
2576 llvm_unreachable("asking for RRTI for a placeholder type!");
2577
2578 case BuiltinType::ObjCId:
2579 case BuiltinType::ObjCClass:
2580 case BuiltinType::ObjCSel:
2581 llvm_unreachable("FIXME: Objective-C types are unsupported!");
2582 }
2583
2584 llvm_unreachable("Invalid BuiltinType Kind!");
2585}
2586
2587static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2588 QualType PointeeTy = PointerTy->getPointeeType();
2589 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2590 if (!BuiltinTy)
2591 return false;
2592
2593 // Check the qualifiers.
2594 Qualifiers Quals = PointeeTy.getQualifiers();
2595 Quals.removeConst();
2596
2597 if (!Quals.empty())
2598 return false;
2599
2600 return TypeInfoIsInStandardLibrary(BuiltinTy);
2601}
2602
2603/// IsStandardLibraryRTTIDescriptor - Returns whether the type
2604/// information for the given type exists in the standard library.
2605static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2606 // Type info for builtin types is defined in the standard library.
2607 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2608 return TypeInfoIsInStandardLibrary(BuiltinTy);
2609
2610 // Type info for some pointer types to builtin types is defined in the
2611 // standard library.
2612 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2613 return TypeInfoIsInStandardLibrary(PointerTy);
2614
2615 return false;
2616}
2617
2618/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
2619/// the given type exists somewhere else, and that we should not emit the type
2620/// information in this translation unit. Assumes that it is not a
2621/// standard-library type.
2622static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
2623 QualType Ty) {
2624 ASTContext &Context = CGM.getContext();
2625
2626 // If RTTI is disabled, assume it might be disabled in the
2627 // translation unit that defines any potential key function, too.
2628 if (!Context.getLangOpts().RTTI) return false;
2629
2630 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2631 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2632 if (!RD->hasDefinition())
2633 return false;
2634
2635 if (!RD->isDynamicClass())
2636 return false;
2637
2638 // FIXME: this may need to be reconsidered if the key function
2639 // changes.
David Majnemerbe9022c2015-08-06 20:56:55 +00002640 // N.B. We must always emit the RTTI data ourselves if there exists a key
2641 // function.
2642 bool IsDLLImport = RD->hasAttr<DLLImportAttr>();
David Majnemer1fb1a042014-11-07 07:26:38 +00002643 if (CGM.getVTables().isVTableExternal(RD))
David Majnemerbe9022c2015-08-06 20:56:55 +00002644 return IsDLLImport ? false : true;
David Majnemer1fb1a042014-11-07 07:26:38 +00002645
David Majnemerbe9022c2015-08-06 20:56:55 +00002646 if (IsDLLImport)
David Majnemer1fb1a042014-11-07 07:26:38 +00002647 return true;
David Majnemere2cb8d12014-07-07 06:20:47 +00002648 }
2649
2650 return false;
2651}
2652
2653/// IsIncompleteClassType - Returns whether the given record type is incomplete.
2654static bool IsIncompleteClassType(const RecordType *RecordTy) {
2655 return !RecordTy->getDecl()->isCompleteDefinition();
2656}
2657
2658/// ContainsIncompleteClassType - Returns whether the given type contains an
2659/// incomplete class type. This is true if
2660///
2661/// * The given type is an incomplete class type.
2662/// * The given type is a pointer type whose pointee type contains an
2663/// incomplete class type.
2664/// * The given type is a member pointer type whose class is an incomplete
2665/// class type.
2666/// * The given type is a member pointer type whoise pointee type contains an
2667/// incomplete class type.
2668/// is an indirect or direct pointer to an incomplete class type.
2669static bool ContainsIncompleteClassType(QualType Ty) {
2670 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2671 if (IsIncompleteClassType(RecordTy))
2672 return true;
2673 }
2674
2675 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2676 return ContainsIncompleteClassType(PointerTy->getPointeeType());
2677
2678 if (const MemberPointerType *MemberPointerTy =
2679 dyn_cast<MemberPointerType>(Ty)) {
2680 // Check if the class type is incomplete.
2681 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
2682 if (IsIncompleteClassType(ClassType))
2683 return true;
2684
2685 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
2686 }
2687
2688 return false;
2689}
2690
2691// CanUseSingleInheritance - Return whether the given record decl has a "single,
2692// public, non-virtual base at offset zero (i.e. the derived class is dynamic
2693// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
2694static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
2695 // Check the number of bases.
2696 if (RD->getNumBases() != 1)
2697 return false;
2698
2699 // Get the base.
2700 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
2701
2702 // Check that the base is not virtual.
2703 if (Base->isVirtual())
2704 return false;
2705
2706 // Check that the base is public.
2707 if (Base->getAccessSpecifier() != AS_public)
2708 return false;
2709
2710 // Check that the class is dynamic iff the base is.
2711 const CXXRecordDecl *BaseDecl =
2712 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2713 if (!BaseDecl->isEmpty() &&
2714 BaseDecl->isDynamicClass() != RD->isDynamicClass())
2715 return false;
2716
2717 return true;
2718}
2719
2720void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
2721 // abi::__class_type_info.
2722 static const char * const ClassTypeInfo =
2723 "_ZTVN10__cxxabiv117__class_type_infoE";
2724 // abi::__si_class_type_info.
2725 static const char * const SIClassTypeInfo =
2726 "_ZTVN10__cxxabiv120__si_class_type_infoE";
2727 // abi::__vmi_class_type_info.
2728 static const char * const VMIClassTypeInfo =
2729 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
2730
2731 const char *VTableName = nullptr;
2732
2733 switch (Ty->getTypeClass()) {
2734#define TYPE(Class, Base)
2735#define ABSTRACT_TYPE(Class, Base)
2736#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2737#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2738#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2739#include "clang/AST/TypeNodes.def"
2740 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2741
2742 case Type::LValueReference:
2743 case Type::RValueReference:
2744 llvm_unreachable("References shouldn't get here");
2745
2746 case Type::Auto:
2747 llvm_unreachable("Undeduced auto type shouldn't get here");
2748
Xiuli Pan9c14e282016-01-09 12:53:17 +00002749 case Type::Pipe:
2750 llvm_unreachable("Pipe types shouldn't get here");
2751
David Majnemere2cb8d12014-07-07 06:20:47 +00002752 case Type::Builtin:
2753 // GCC treats vector and complex types as fundamental types.
2754 case Type::Vector:
2755 case Type::ExtVector:
2756 case Type::Complex:
2757 case Type::Atomic:
2758 // FIXME: GCC treats block pointers as fundamental types?!
2759 case Type::BlockPointer:
2760 // abi::__fundamental_type_info.
2761 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
2762 break;
2763
2764 case Type::ConstantArray:
2765 case Type::IncompleteArray:
2766 case Type::VariableArray:
2767 // abi::__array_type_info.
2768 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
2769 break;
2770
2771 case Type::FunctionNoProto:
2772 case Type::FunctionProto:
2773 // abi::__function_type_info.
2774 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
2775 break;
2776
2777 case Type::Enum:
2778 // abi::__enum_type_info.
2779 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
2780 break;
2781
2782 case Type::Record: {
2783 const CXXRecordDecl *RD =
2784 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2785
2786 if (!RD->hasDefinition() || !RD->getNumBases()) {
2787 VTableName = ClassTypeInfo;
2788 } else if (CanUseSingleInheritance(RD)) {
2789 VTableName = SIClassTypeInfo;
2790 } else {
2791 VTableName = VMIClassTypeInfo;
2792 }
2793
2794 break;
2795 }
2796
2797 case Type::ObjCObject:
2798 // Ignore protocol qualifiers.
2799 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
2800
2801 // Handle id and Class.
2802 if (isa<BuiltinType>(Ty)) {
2803 VTableName = ClassTypeInfo;
2804 break;
2805 }
2806
2807 assert(isa<ObjCInterfaceType>(Ty));
2808 // Fall through.
2809
2810 case Type::ObjCInterface:
2811 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
2812 VTableName = SIClassTypeInfo;
2813 } else {
2814 VTableName = ClassTypeInfo;
2815 }
2816 break;
2817
2818 case Type::ObjCObjectPointer:
2819 case Type::Pointer:
2820 // abi::__pointer_type_info.
2821 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
2822 break;
2823
2824 case Type::MemberPointer:
2825 // abi::__pointer_to_member_type_info.
2826 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
2827 break;
2828 }
2829
2830 llvm::Constant *VTable =
2831 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
2832
2833 llvm::Type *PtrDiffTy =
2834 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
2835
2836 // The vtable address point is 2.
2837 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00002838 VTable =
2839 llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.Int8PtrTy, VTable, Two);
David Majnemere2cb8d12014-07-07 06:20:47 +00002840 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
2841
2842 Fields.push_back(VTable);
2843}
2844
2845/// \brief Return the linkage that the type info and type info name constants
2846/// should have for the given type.
2847static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
2848 QualType Ty) {
2849 // Itanium C++ ABI 2.9.5p7:
2850 // In addition, it and all of the intermediate abi::__pointer_type_info
2851 // structs in the chain down to the abi::__class_type_info for the
2852 // incomplete class type must be prevented from resolving to the
2853 // corresponding type_info structs for the complete class type, possibly
2854 // by making them local static objects. Finally, a dummy class RTTI is
2855 // generated for the incomplete type that will not resolve to the final
2856 // complete class RTTI (because the latter need not exist), possibly by
2857 // making it a local static object.
2858 if (ContainsIncompleteClassType(Ty))
2859 return llvm::GlobalValue::InternalLinkage;
2860
2861 switch (Ty->getLinkage()) {
2862 case NoLinkage:
2863 case InternalLinkage:
2864 case UniqueExternalLinkage:
2865 return llvm::GlobalValue::InternalLinkage;
2866
2867 case VisibleNoLinkage:
2868 case ExternalLinkage:
2869 if (!CGM.getLangOpts().RTTI) {
2870 // RTTI is not enabled, which means that this type info struct is going
2871 // to be used for exception handling. Give it linkonce_odr linkage.
2872 return llvm::GlobalValue::LinkOnceODRLinkage;
2873 }
2874
2875 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
2876 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2877 if (RD->hasAttr<WeakAttr>())
2878 return llvm::GlobalValue::WeakODRLinkage;
David Majnemerbe9022c2015-08-06 20:56:55 +00002879 if (RD->isDynamicClass()) {
2880 llvm::GlobalValue::LinkageTypes LT = CGM.getVTableLinkage(RD);
2881 // MinGW won't export the RTTI information when there is a key function.
2882 // Make sure we emit our own copy instead of attempting to dllimport it.
2883 if (RD->hasAttr<DLLImportAttr>() &&
2884 llvm::GlobalValue::isAvailableExternallyLinkage(LT))
2885 LT = llvm::GlobalValue::LinkOnceODRLinkage;
2886 return LT;
2887 }
David Majnemere2cb8d12014-07-07 06:20:47 +00002888 }
2889
2890 return llvm::GlobalValue::LinkOnceODRLinkage;
2891 }
2892
2893 llvm_unreachable("Invalid linkage!");
2894}
2895
2896llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force) {
2897 // We want to operate on the canonical type.
Yaron Kerenebd14262016-03-16 12:14:43 +00002898 Ty = Ty.getCanonicalType();
David Majnemere2cb8d12014-07-07 06:20:47 +00002899
2900 // Check if we've already emitted an RTTI descriptor for this type.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002901 SmallString<256> Name;
2902 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002903 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002904
2905 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
2906 if (OldGV && !OldGV->isDeclaration()) {
2907 assert(!OldGV->hasAvailableExternallyLinkage() &&
2908 "available_externally typeinfos not yet implemented");
2909
2910 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
2911 }
2912
2913 // Check if there is already an external RTTI descriptor for this type.
2914 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
2915 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
2916 return GetAddrOfExternalRTTIDescriptor(Ty);
2917
2918 // Emit the standard library with external linkage.
2919 llvm::GlobalVariable::LinkageTypes Linkage;
2920 if (IsStdLib)
2921 Linkage = llvm::GlobalValue::ExternalLinkage;
2922 else
2923 Linkage = getTypeInfoLinkage(CGM, Ty);
2924
2925 // Add the vtable pointer.
2926 BuildVTablePointer(cast<Type>(Ty));
2927
2928 // And the name.
2929 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
2930 llvm::Constant *TypeNameField;
2931
2932 // If we're supposed to demote the visibility, be sure to set a flag
2933 // to use a string comparison for type_info comparisons.
2934 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
2935 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
2936 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
2937 // The flag is the sign bit, which on ARM64 is defined to be clear
2938 // for global pointers. This is very ARM64-specific.
2939 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
2940 llvm::Constant *flag =
2941 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
2942 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
2943 TypeNameField =
2944 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
2945 } else {
2946 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
2947 }
2948 Fields.push_back(TypeNameField);
2949
2950 switch (Ty->getTypeClass()) {
2951#define TYPE(Class, Base)
2952#define ABSTRACT_TYPE(Class, Base)
2953#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2954#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2955#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2956#include "clang/AST/TypeNodes.def"
2957 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2958
2959 // GCC treats vector types as fundamental types.
2960 case Type::Builtin:
2961 case Type::Vector:
2962 case Type::ExtVector:
2963 case Type::Complex:
2964 case Type::BlockPointer:
2965 // Itanium C++ ABI 2.9.5p4:
2966 // abi::__fundamental_type_info adds no data members to std::type_info.
2967 break;
2968
2969 case Type::LValueReference:
2970 case Type::RValueReference:
2971 llvm_unreachable("References shouldn't get here");
2972
2973 case Type::Auto:
2974 llvm_unreachable("Undeduced auto type shouldn't get here");
2975
Xiuli Pan9c14e282016-01-09 12:53:17 +00002976 case Type::Pipe:
2977 llvm_unreachable("Pipe type shouldn't get here");
2978
David Majnemere2cb8d12014-07-07 06:20:47 +00002979 case Type::ConstantArray:
2980 case Type::IncompleteArray:
2981 case Type::VariableArray:
2982 // Itanium C++ ABI 2.9.5p5:
2983 // abi::__array_type_info adds no data members to std::type_info.
2984 break;
2985
2986 case Type::FunctionNoProto:
2987 case Type::FunctionProto:
2988 // Itanium C++ ABI 2.9.5p5:
2989 // abi::__function_type_info adds no data members to std::type_info.
2990 break;
2991
2992 case Type::Enum:
2993 // Itanium C++ ABI 2.9.5p5:
2994 // abi::__enum_type_info adds no data members to std::type_info.
2995 break;
2996
2997 case Type::Record: {
2998 const CXXRecordDecl *RD =
2999 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
3000 if (!RD->hasDefinition() || !RD->getNumBases()) {
3001 // We don't need to emit any fields.
3002 break;
3003 }
3004
3005 if (CanUseSingleInheritance(RD))
3006 BuildSIClassTypeInfo(RD);
3007 else
3008 BuildVMIClassTypeInfo(RD);
3009
3010 break;
3011 }
3012
3013 case Type::ObjCObject:
3014 case Type::ObjCInterface:
3015 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
3016 break;
3017
3018 case Type::ObjCObjectPointer:
3019 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
3020 break;
3021
3022 case Type::Pointer:
3023 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
3024 break;
3025
3026 case Type::MemberPointer:
3027 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
3028 break;
3029
3030 case Type::Atomic:
3031 // No fields, at least for the moment.
3032 break;
3033 }
3034
3035 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
3036
Rafael Espindolacb92c192015-01-15 23:18:01 +00003037 llvm::Module &M = CGM.getModule();
David Majnemere2cb8d12014-07-07 06:20:47 +00003038 llvm::GlobalVariable *GV =
Rafael Espindolacb92c192015-01-15 23:18:01 +00003039 new llvm::GlobalVariable(M, Init->getType(),
3040 /*Constant=*/true, Linkage, Init, Name);
3041
David Majnemere2cb8d12014-07-07 06:20:47 +00003042 // If there's already an old global variable, replace it with the new one.
3043 if (OldGV) {
3044 GV->takeName(OldGV);
3045 llvm::Constant *NewPtr =
3046 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3047 OldGV->replaceAllUsesWith(NewPtr);
3048 OldGV->eraseFromParent();
3049 }
3050
Yaron Keren04da2382015-07-29 15:42:28 +00003051 if (CGM.supportsCOMDAT() && GV->isWeakForLinker())
3052 GV->setComdat(M.getOrInsertComdat(GV->getName()));
3053
David Majnemere2cb8d12014-07-07 06:20:47 +00003054 // The Itanium ABI specifies that type_info objects must be globally
3055 // unique, with one exception: if the type is an incomplete class
3056 // type or a (possibly indirect) pointer to one. That exception
3057 // affects the general case of comparing type_info objects produced
3058 // by the typeid operator, which is why the comparison operators on
3059 // std::type_info generally use the type_info name pointers instead
3060 // of the object addresses. However, the language's built-in uses
3061 // of RTTI generally require class types to be complete, even when
3062 // manipulating pointers to those class types. This allows the
3063 // implementation of dynamic_cast to rely on address equality tests,
3064 // which is much faster.
3065
3066 // All of this is to say that it's important that both the type_info
3067 // object and the type_info name be uniqued when weakly emitted.
3068
3069 // Give the type_info object and name the formal visibility of the
3070 // type itself.
3071 llvm::GlobalValue::VisibilityTypes llvmVisibility;
3072 if (llvm::GlobalValue::isLocalLinkage(Linkage))
3073 // If the linkage is local, only default visibility makes sense.
3074 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
3075 else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden)
3076 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
3077 else
3078 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
3079 TypeName->setVisibility(llvmVisibility);
3080 GV->setVisibility(llvmVisibility);
3081
3082 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
3083}
3084
3085/// ComputeQualifierFlags - Compute the pointer type info flags from the
3086/// given qualifier.
3087static unsigned ComputeQualifierFlags(Qualifiers Quals) {
3088 unsigned Flags = 0;
3089
3090 if (Quals.hasConst())
3091 Flags |= ItaniumRTTIBuilder::PTI_Const;
3092 if (Quals.hasVolatile())
3093 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
3094 if (Quals.hasRestrict())
3095 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
3096
3097 return Flags;
3098}
3099
3100/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
3101/// for the given Objective-C object type.
3102void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
3103 // Drop qualifiers.
3104 const Type *T = OT->getBaseType().getTypePtr();
3105 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
3106
3107 // The builtin types are abi::__class_type_infos and don't require
3108 // extra fields.
3109 if (isa<BuiltinType>(T)) return;
3110
3111 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
3112 ObjCInterfaceDecl *Super = Class->getSuperClass();
3113
3114 // Root classes are also __class_type_info.
3115 if (!Super) return;
3116
3117 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
3118
3119 // Everything else is single inheritance.
3120 llvm::Constant *BaseTypeInfo =
3121 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
3122 Fields.push_back(BaseTypeInfo);
3123}
3124
3125/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
3126/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
3127void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
3128 // Itanium C++ ABI 2.9.5p6b:
3129 // It adds to abi::__class_type_info a single member pointing to the
3130 // type_info structure for the base type,
3131 llvm::Constant *BaseTypeInfo =
3132 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
3133 Fields.push_back(BaseTypeInfo);
3134}
3135
3136namespace {
3137 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
3138 /// a class hierarchy.
3139 struct SeenBases {
3140 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
3141 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
3142 };
3143}
3144
3145/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
3146/// abi::__vmi_class_type_info.
3147///
3148static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
3149 SeenBases &Bases) {
3150
3151 unsigned Flags = 0;
3152
3153 const CXXRecordDecl *BaseDecl =
3154 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
3155
3156 if (Base->isVirtual()) {
3157 // Mark the virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003158 if (!Bases.VirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003159 // If this virtual base has been seen before, then the class is diamond
3160 // shaped.
3161 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
3162 } else {
3163 if (Bases.NonVirtualBases.count(BaseDecl))
3164 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3165 }
3166 } else {
3167 // Mark the non-virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003168 if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003169 // If this non-virtual base has been seen before, then the class has non-
3170 // diamond shaped repeated inheritance.
3171 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3172 } else {
3173 if (Bases.VirtualBases.count(BaseDecl))
3174 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3175 }
3176 }
3177
3178 // Walk all bases.
3179 for (const auto &I : BaseDecl->bases())
3180 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3181
3182 return Flags;
3183}
3184
3185static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
3186 unsigned Flags = 0;
3187 SeenBases Bases;
3188
3189 // Walk all bases.
3190 for (const auto &I : RD->bases())
3191 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3192
3193 return Flags;
3194}
3195
3196/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
3197/// classes with bases that do not satisfy the abi::__si_class_type_info
3198/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
3199void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
3200 llvm::Type *UnsignedIntLTy =
3201 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3202
3203 // Itanium C++ ABI 2.9.5p6c:
3204 // __flags is a word with flags describing details about the class
3205 // structure, which may be referenced by using the __flags_masks
3206 // enumeration. These flags refer to both direct and indirect bases.
3207 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
3208 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3209
3210 // Itanium C++ ABI 2.9.5p6c:
3211 // __base_count is a word with the number of direct proper base class
3212 // descriptions that follow.
3213 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
3214
3215 if (!RD->getNumBases())
3216 return;
3217
David Majnemere2cb8d12014-07-07 06:20:47 +00003218 // Now add the base class descriptions.
3219
3220 // Itanium C++ ABI 2.9.5p6c:
3221 // __base_info[] is an array of base class descriptions -- one for every
3222 // direct proper base. Each description is of the type:
3223 //
3224 // struct abi::__base_class_type_info {
3225 // public:
3226 // const __class_type_info *__base_type;
3227 // long __offset_flags;
3228 //
3229 // enum __offset_flags_masks {
3230 // __virtual_mask = 0x1,
3231 // __public_mask = 0x2,
3232 // __offset_shift = 8
3233 // };
3234 // };
Reid Klecknerd8b04662016-08-25 22:16:30 +00003235
3236 // If we're in mingw and 'long' isn't wide enough for a pointer, use 'long
3237 // long' instead of 'long' for __offset_flags. libstdc++abi uses long long on
3238 // LLP64 platforms.
3239 // FIXME: Consider updating libc++abi to match, and extend this logic to all
3240 // LLP64 platforms.
3241 QualType OffsetFlagsTy = CGM.getContext().LongTy;
3242 const TargetInfo &TI = CGM.getContext().getTargetInfo();
3243 if (TI.getTriple().isOSCygMing() && TI.getPointerWidth(0) > TI.getLongWidth())
3244 OffsetFlagsTy = CGM.getContext().LongLongTy;
3245 llvm::Type *OffsetFlagsLTy =
3246 CGM.getTypes().ConvertType(OffsetFlagsTy);
3247
David Majnemere2cb8d12014-07-07 06:20:47 +00003248 for (const auto &Base : RD->bases()) {
3249 // The __base_type member points to the RTTI for the base type.
3250 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
3251
3252 const CXXRecordDecl *BaseDecl =
3253 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
3254
3255 int64_t OffsetFlags = 0;
3256
3257 // All but the lower 8 bits of __offset_flags are a signed offset.
3258 // For a non-virtual base, this is the offset in the object of the base
3259 // subobject. For a virtual base, this is the offset in the virtual table of
3260 // the virtual base offset for the virtual base referenced (negative).
3261 CharUnits Offset;
3262 if (Base.isVirtual())
3263 Offset =
3264 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
3265 else {
3266 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
3267 Offset = Layout.getBaseClassOffset(BaseDecl);
3268 };
3269
3270 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
3271
3272 // The low-order byte of __offset_flags contains flags, as given by the
3273 // masks from the enumeration __offset_flags_masks.
3274 if (Base.isVirtual())
3275 OffsetFlags |= BCTI_Virtual;
3276 if (Base.getAccessSpecifier() == AS_public)
3277 OffsetFlags |= BCTI_Public;
3278
Reid Klecknerd8b04662016-08-25 22:16:30 +00003279 Fields.push_back(llvm::ConstantInt::get(OffsetFlagsLTy, OffsetFlags));
David Majnemere2cb8d12014-07-07 06:20:47 +00003280 }
3281}
3282
3283/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
3284/// used for pointer types.
3285void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
3286 Qualifiers Quals;
3287 QualType UnqualifiedPointeeTy =
3288 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
3289
3290 // Itanium C++ ABI 2.9.5p7:
3291 // __flags is a flag word describing the cv-qualification and other
3292 // attributes of the type pointed to
3293 unsigned Flags = ComputeQualifierFlags(Quals);
3294
3295 // Itanium C++ ABI 2.9.5p7:
3296 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3297 // incomplete class type, the incomplete target type flag is set.
3298 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
3299 Flags |= PTI_Incomplete;
3300
3301 llvm::Type *UnsignedIntLTy =
3302 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3303 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3304
3305 // Itanium C++ ABI 2.9.5p7:
3306 // __pointee is a pointer to the std::type_info derivation for the
3307 // unqualified type being pointed to.
3308 llvm::Constant *PointeeTypeInfo =
3309 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
3310 Fields.push_back(PointeeTypeInfo);
3311}
3312
3313/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
3314/// struct, used for member pointer types.
3315void
3316ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
3317 QualType PointeeTy = Ty->getPointeeType();
3318
3319 Qualifiers Quals;
3320 QualType UnqualifiedPointeeTy =
3321 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
3322
3323 // Itanium C++ ABI 2.9.5p7:
3324 // __flags is a flag word describing the cv-qualification and other
3325 // attributes of the type pointed to.
3326 unsigned Flags = ComputeQualifierFlags(Quals);
3327
3328 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
3329
3330 // Itanium C++ ABI 2.9.5p7:
3331 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3332 // incomplete class type, the incomplete target type flag is set.
3333 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
3334 Flags |= PTI_Incomplete;
3335
3336 if (IsIncompleteClassType(ClassType))
3337 Flags |= PTI_ContainingClassIncomplete;
3338
3339 llvm::Type *UnsignedIntLTy =
3340 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3341 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3342
3343 // Itanium C++ ABI 2.9.5p7:
3344 // __pointee is a pointer to the std::type_info derivation for the
3345 // unqualified type being pointed to.
3346 llvm::Constant *PointeeTypeInfo =
3347 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
3348 Fields.push_back(PointeeTypeInfo);
3349
3350 // Itanium C++ ABI 2.9.5p9:
3351 // __context is a pointer to an abi::__class_type_info corresponding to the
3352 // class type containing the member pointed to
3353 // (e.g., the "A" in "int A::*").
3354 Fields.push_back(
3355 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
3356}
3357
David Majnemer443250f2015-03-17 20:35:00 +00003358llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003359 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
3360}
3361
3362void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type) {
3363 QualType PointerType = getContext().getPointerType(Type);
3364 QualType PointerTypeConst = getContext().getPointerType(Type.withConst());
3365 ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, true);
3366 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, true);
3367 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, true);
3368}
3369
3370void ItaniumCXXABI::EmitFundamentalRTTIDescriptors() {
Richard Smith4a382012016-02-03 01:32:42 +00003371 // Types added here must also be added to TypeInfoIsInStandardLibrary.
David Majnemere2cb8d12014-07-07 06:20:47 +00003372 QualType FundamentalTypes[] = {
3373 getContext().VoidTy, getContext().NullPtrTy,
3374 getContext().BoolTy, getContext().WCharTy,
3375 getContext().CharTy, getContext().UnsignedCharTy,
3376 getContext().SignedCharTy, getContext().ShortTy,
3377 getContext().UnsignedShortTy, getContext().IntTy,
3378 getContext().UnsignedIntTy, getContext().LongTy,
3379 getContext().UnsignedLongTy, getContext().LongLongTy,
Richard Smith4a382012016-02-03 01:32:42 +00003380 getContext().UnsignedLongLongTy, getContext().Int128Ty,
3381 getContext().UnsignedInt128Ty, getContext().HalfTy,
David Majnemere2cb8d12014-07-07 06:20:47 +00003382 getContext().FloatTy, getContext().DoubleTy,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00003383 getContext().LongDoubleTy, getContext().Float128Ty,
3384 getContext().Char16Ty, getContext().Char32Ty
David Majnemere2cb8d12014-07-07 06:20:47 +00003385 };
3386 for (const QualType &FundamentalType : FundamentalTypes)
3387 EmitFundamentalRTTIDescriptor(FundamentalType);
3388}
3389
3390/// What sort of uniqueness rules should we use for the RTTI for the
3391/// given type?
3392ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
3393 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
3394 if (shouldRTTIBeUnique())
3395 return RUK_Unique;
3396
3397 // It's only necessary for linkonce_odr or weak_odr linkage.
3398 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
3399 Linkage != llvm::GlobalValue::WeakODRLinkage)
3400 return RUK_Unique;
3401
3402 // It's only necessary with default visibility.
3403 if (CanTy->getVisibility() != DefaultVisibility)
3404 return RUK_Unique;
3405
3406 // If we're not required to publish this symbol, hide it.
3407 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3408 return RUK_NonUniqueHidden;
3409
3410 // If we're required to publish this symbol, as we might be under an
3411 // explicit instantiation, leave it with default visibility but
3412 // enable string-comparisons.
3413 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
3414 return RUK_NonUniqueVisible;
3415}
Rafael Espindola91f68b42014-09-15 19:20:10 +00003416
Rafael Espindola1e4df922014-09-16 15:18:21 +00003417// Find out how to codegen the complete destructor and constructor
3418namespace {
3419enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
3420}
3421static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
3422 const CXXMethodDecl *MD) {
3423 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
3424 return StructorCodegen::Emit;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003425
Rafael Espindola1e4df922014-09-16 15:18:21 +00003426 // The complete and base structors are not equivalent if there are any virtual
3427 // bases, so emit separate functions.
3428 if (MD->getParent()->getNumVBases())
3429 return StructorCodegen::Emit;
3430
3431 GlobalDecl AliasDecl;
3432 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3433 AliasDecl = GlobalDecl(DD, Dtor_Complete);
3434 } else {
3435 const auto *CD = cast<CXXConstructorDecl>(MD);
3436 AliasDecl = GlobalDecl(CD, Ctor_Complete);
3437 }
3438 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3439
3440 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
3441 return StructorCodegen::RAUW;
3442
3443 // FIXME: Should we allow available_externally aliases?
3444 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
3445 return StructorCodegen::RAUW;
3446
Rafael Espindola0806f982014-09-16 20:19:43 +00003447 if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
3448 // Only ELF supports COMDATs with arbitrary names (C5/D5).
3449 if (CGM.getTarget().getTriple().isOSBinFormatELF())
3450 return StructorCodegen::COMDAT;
3451 return StructorCodegen::Emit;
3452 }
Rafael Espindola1e4df922014-09-16 15:18:21 +00003453
3454 return StructorCodegen::Alias;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003455}
3456
Rafael Espindola1e4df922014-09-16 15:18:21 +00003457static void emitConstructorDestructorAlias(CodeGenModule &CGM,
3458 GlobalDecl AliasDecl,
3459 GlobalDecl TargetDecl) {
3460 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3461
3462 StringRef MangledName = CGM.getMangledName(AliasDecl);
3463 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
3464 if (Entry && !Entry->isDeclaration())
3465 return;
3466
3467 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
Rafael Espindola1e4df922014-09-16 15:18:21 +00003468
3469 // Create the alias with no name.
David Blaikie2a791d72015-09-14 18:38:22 +00003470 auto *Alias = llvm::GlobalAlias::create(Linkage, "", Aliasee);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003471
3472 // Switch any previous uses to the alias.
3473 if (Entry) {
NAKAMURA Takumie9621042015-09-15 01:39:27 +00003474 assert(Entry->getType() == Aliasee->getType() &&
Rafael Espindola1e4df922014-09-16 15:18:21 +00003475 "declaration exists with different type");
3476 Alias->takeName(Entry);
3477 Entry->replaceAllUsesWith(Alias);
3478 Entry->eraseFromParent();
3479 } else {
3480 Alias->setName(MangledName);
3481 }
3482
3483 // Finally, set up the alias with its proper name and attributes.
Dario Domiziolic4fb8ca72014-09-19 22:06:24 +00003484 CGM.setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003485}
3486
3487void ItaniumCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
3488 StructorType Type) {
3489 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
3490 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
3491
3492 StructorCodegen CGType = getCodegenToUse(CGM, MD);
3493
3494 if (Type == StructorType::Complete) {
3495 GlobalDecl CompleteDecl;
3496 GlobalDecl BaseDecl;
3497 if (CD) {
3498 CompleteDecl = GlobalDecl(CD, Ctor_Complete);
3499 BaseDecl = GlobalDecl(CD, Ctor_Base);
3500 } else {
3501 CompleteDecl = GlobalDecl(DD, Dtor_Complete);
3502 BaseDecl = GlobalDecl(DD, Dtor_Base);
3503 }
3504
3505 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
3506 emitConstructorDestructorAlias(CGM, CompleteDecl, BaseDecl);
3507 return;
3508 }
3509
3510 if (CGType == StructorCodegen::RAUW) {
3511 StringRef MangledName = CGM.getMangledName(CompleteDecl);
Andrey Bokhankocab58582015-08-31 13:20:44 +00003512 auto *Aliasee = CGM.GetAddrOfGlobal(BaseDecl);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003513 CGM.addReplacement(MangledName, Aliasee);
3514 return;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003515 }
3516 }
3517
3518 // The base destructor is equivalent to the base destructor of its
3519 // base class if there is exactly one non-virtual base class with a
3520 // non-trivial destructor, there are no fields with a non-trivial
3521 // destructor, and the body of the destructor is trivial.
Rafael Espindola1e4df922014-09-16 15:18:21 +00003522 if (DD && Type == StructorType::Base && CGType != StructorCodegen::COMDAT &&
3523 !CGM.TryEmitBaseDestructorAsAlias(DD))
Rafael Espindola91f68b42014-09-15 19:20:10 +00003524 return;
3525
Rafael Espindola1e4df922014-09-16 15:18:21 +00003526 llvm::Function *Fn = CGM.codegenCXXStructor(MD, Type);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003527
Rafael Espindola1e4df922014-09-16 15:18:21 +00003528 if (CGType == StructorCodegen::COMDAT) {
3529 SmallString<256> Buffer;
3530 llvm::raw_svector_ostream Out(Buffer);
3531 if (DD)
3532 getMangleContext().mangleCXXDtorComdat(DD, Out);
3533 else
3534 getMangleContext().mangleCXXCtorComdat(CD, Out);
3535 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
3536 Fn->setComdat(C);
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003537 } else {
3538 CGM.maybeSetTrivialComdat(*MD, *Fn);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003539 }
Rafael Espindola91f68b42014-09-15 19:20:10 +00003540}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003541
3542static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) {
3543 // void *__cxa_begin_catch(void*);
3544 llvm::FunctionType *FTy = llvm::FunctionType::get(
3545 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3546
3547 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
3548}
3549
3550static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) {
3551 // void __cxa_end_catch();
3552 llvm::FunctionType *FTy =
3553 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
3554
3555 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
3556}
3557
3558static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) {
3559 // void *__cxa_get_exception_ptr(void*);
3560 llvm::FunctionType *FTy = llvm::FunctionType::get(
3561 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3562
3563 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
3564}
3565
3566namespace {
3567 /// A cleanup to call __cxa_end_catch. In many cases, the caught
3568 /// exception type lets us state definitively that the thrown exception
3569 /// type does not have a destructor. In particular:
3570 /// - Catch-alls tell us nothing, so we have to conservatively
3571 /// assume that the thrown exception might have a destructor.
3572 /// - Catches by reference behave according to their base types.
3573 /// - Catches of non-record types will only trigger for exceptions
3574 /// of non-record types, which never have destructors.
3575 /// - Catches of record types can trigger for arbitrary subclasses
3576 /// of the caught type, so we have to assume the actual thrown
3577 /// exception type might have a throwing destructor, even if the
3578 /// caught type's destructor is trivial or nothrow.
David Blaikie7e70d682015-08-18 22:40:54 +00003579 struct CallEndCatch final : EHScopeStack::Cleanup {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003580 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
3581 bool MightThrow;
3582
3583 void Emit(CodeGenFunction &CGF, Flags flags) override {
3584 if (!MightThrow) {
3585 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
3586 return;
3587 }
3588
3589 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
3590 }
3591 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003592}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003593
3594/// Emits a call to __cxa_begin_catch and enters a cleanup to call
3595/// __cxa_end_catch.
3596///
3597/// \param EndMightThrow - true if __cxa_end_catch might throw
3598static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
3599 llvm::Value *Exn,
3600 bool EndMightThrow) {
3601 llvm::CallInst *call =
3602 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
3603
3604 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
3605
3606 return call;
3607}
3608
3609/// A "special initializer" callback for initializing a catch
3610/// parameter during catch initialization.
3611static void InitCatchParam(CodeGenFunction &CGF,
3612 const VarDecl &CatchParam,
John McCall7f416cc2015-09-08 08:05:57 +00003613 Address ParamAddr,
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003614 SourceLocation Loc) {
3615 // Load the exception from where the landing pad saved it.
3616 llvm::Value *Exn = CGF.getExceptionFromSlot();
3617
3618 CanQualType CatchType =
3619 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
3620 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
3621
3622 // If we're catching by reference, we can just cast the object
3623 // pointer to the appropriate pointer.
3624 if (isa<ReferenceType>(CatchType)) {
3625 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
3626 bool EndCatchMightThrow = CaughtType->isRecordType();
3627
3628 // __cxa_begin_catch returns the adjusted object pointer.
3629 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
3630
3631 // We have no way to tell the personality function that we're
3632 // catching by reference, so if we're catching a pointer,
3633 // __cxa_begin_catch will actually return that pointer by value.
3634 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
3635 QualType PointeeType = PT->getPointeeType();
3636
3637 // When catching by reference, generally we should just ignore
3638 // this by-value pointer and use the exception object instead.
3639 if (!PointeeType->isRecordType()) {
3640
3641 // Exn points to the struct _Unwind_Exception header, which
3642 // we have to skip past in order to reach the exception data.
3643 unsigned HeaderSize =
3644 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
3645 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
3646
3647 // However, if we're catching a pointer-to-record type that won't
3648 // work, because the personality function might have adjusted
3649 // the pointer. There's actually no way for us to fully satisfy
3650 // the language/ABI contract here: we can't use Exn because it
3651 // might have the wrong adjustment, but we can't use the by-value
3652 // pointer because it's off by a level of abstraction.
3653 //
3654 // The current solution is to dump the adjusted pointer into an
3655 // alloca, which breaks language semantics (because changing the
3656 // pointer doesn't change the exception) but at least works.
3657 // The better solution would be to filter out non-exact matches
3658 // and rethrow them, but this is tricky because the rethrow
3659 // really needs to be catchable by other sites at this landing
3660 // pad. The best solution is to fix the personality function.
3661 } else {
3662 // Pull the pointer for the reference type off.
3663 llvm::Type *PtrTy =
3664 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
3665
3666 // Create the temporary and write the adjusted pointer into it.
John McCall7f416cc2015-09-08 08:05:57 +00003667 Address ExnPtrTmp =
3668 CGF.CreateTempAlloca(PtrTy, CGF.getPointerAlign(), "exn.byref.tmp");
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003669 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3670 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
3671
3672 // Bind the reference to the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00003673 AdjustedExn = ExnPtrTmp.getPointer();
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003674 }
3675 }
3676
3677 llvm::Value *ExnCast =
3678 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
3679 CGF.Builder.CreateStore(ExnCast, ParamAddr);
3680 return;
3681 }
3682
3683 // Scalars and complexes.
3684 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
3685 if (TEK != TEK_Aggregate) {
3686 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
3687
3688 // If the catch type is a pointer type, __cxa_begin_catch returns
3689 // the pointer by value.
3690 if (CatchType->hasPointerRepresentation()) {
3691 llvm::Value *CastExn =
3692 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
3693
3694 switch (CatchType.getQualifiers().getObjCLifetime()) {
3695 case Qualifiers::OCL_Strong:
3696 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
3697 // fallthrough
3698
3699 case Qualifiers::OCL_None:
3700 case Qualifiers::OCL_ExplicitNone:
3701 case Qualifiers::OCL_Autoreleasing:
3702 CGF.Builder.CreateStore(CastExn, ParamAddr);
3703 return;
3704
3705 case Qualifiers::OCL_Weak:
3706 CGF.EmitARCInitWeak(ParamAddr, CastExn);
3707 return;
3708 }
3709 llvm_unreachable("bad ownership qualifier!");
3710 }
3711
3712 // Otherwise, it returns a pointer into the exception object.
3713
3714 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3715 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3716
3717 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
John McCall7f416cc2015-09-08 08:05:57 +00003718 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003719 switch (TEK) {
3720 case TEK_Complex:
3721 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
3722 /*init*/ true);
3723 return;
3724 case TEK_Scalar: {
3725 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
3726 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
3727 return;
3728 }
3729 case TEK_Aggregate:
3730 llvm_unreachable("evaluation kind filtered out!");
3731 }
3732 llvm_unreachable("bad evaluation kind");
3733 }
3734
3735 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
John McCall7f416cc2015-09-08 08:05:57 +00003736 auto catchRD = CatchType->getAsCXXRecordDecl();
3737 CharUnits caughtExnAlignment = CGF.CGM.getClassPointerAlignment(catchRD);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003738
3739 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3740
3741 // Check for a copy expression. If we don't have a copy expression,
3742 // that means a trivial copy is okay.
3743 const Expr *copyExpr = CatchParam.getInit();
3744 if (!copyExpr) {
3745 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
John McCall7f416cc2015-09-08 08:05:57 +00003746 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3747 caughtExnAlignment);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003748 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
3749 return;
3750 }
3751
3752 // We have to call __cxa_get_exception_ptr to get the adjusted
3753 // pointer before copying.
3754 llvm::CallInst *rawAdjustedExn =
3755 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
3756
3757 // Cast that to the appropriate type.
John McCall7f416cc2015-09-08 08:05:57 +00003758 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3759 caughtExnAlignment);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003760
3761 // The copy expression is defined in terms of an OpaqueValueExpr.
3762 // Find it and map it to the adjusted expression.
3763 CodeGenFunction::OpaqueValueMapping
3764 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
3765 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
3766
3767 // Call the copy ctor in a terminate scope.
3768 CGF.EHStack.pushTerminate();
3769
3770 // Perform the copy construction.
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003771 CGF.EmitAggExpr(copyExpr,
John McCall7f416cc2015-09-08 08:05:57 +00003772 AggValueSlot::forAddr(ParamAddr, Qualifiers(),
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003773 AggValueSlot::IsNotDestructed,
3774 AggValueSlot::DoesNotNeedGCBarriers,
3775 AggValueSlot::IsNotAliased));
3776
3777 // Leave the terminate scope.
3778 CGF.EHStack.popTerminate();
3779
3780 // Undo the opaque value mapping.
3781 opaque.pop();
3782
3783 // Finally we can call __cxa_begin_catch.
3784 CallBeginCatch(CGF, Exn, true);
3785}
3786
3787/// Begins a catch statement by initializing the catch variable and
3788/// calling __cxa_begin_catch.
3789void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF,
3790 const CXXCatchStmt *S) {
3791 // We have to be very careful with the ordering of cleanups here:
3792 // C++ [except.throw]p4:
3793 // The destruction [of the exception temporary] occurs
3794 // immediately after the destruction of the object declared in
3795 // the exception-declaration in the handler.
3796 //
3797 // So the precise ordering is:
3798 // 1. Construct catch variable.
3799 // 2. __cxa_begin_catch
3800 // 3. Enter __cxa_end_catch cleanup
3801 // 4. Enter dtor cleanup
3802 //
3803 // We do this by using a slightly abnormal initialization process.
3804 // Delegation sequence:
3805 // - ExitCXXTryStmt opens a RunCleanupsScope
3806 // - EmitAutoVarAlloca creates the variable and debug info
3807 // - InitCatchParam initializes the variable from the exception
3808 // - CallBeginCatch calls __cxa_begin_catch
3809 // - CallBeginCatch enters the __cxa_end_catch cleanup
3810 // - EmitAutoVarCleanups enters the variable destructor cleanup
3811 // - EmitCXXTryStmt emits the code for the catch body
3812 // - EmitCXXTryStmt close the RunCleanupsScope
3813
3814 VarDecl *CatchParam = S->getExceptionDecl();
3815 if (!CatchParam) {
3816 llvm::Value *Exn = CGF.getExceptionFromSlot();
3817 CallBeginCatch(CGF, Exn, true);
3818 return;
3819 }
3820
3821 // Emit the local.
3822 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
3823 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
3824 CGF.EmitAutoVarCleanups(var);
3825}
3826
3827/// Get or define the following function:
3828/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
3829/// This code is used only in C++.
3830static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
3831 llvm::FunctionType *fnTy =
3832 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3833 llvm::Constant *fnRef =
3834 CGM.CreateRuntimeFunction(fnTy, "__clang_call_terminate");
3835
3836 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
3837 if (fn && fn->empty()) {
3838 fn->setDoesNotThrow();
3839 fn->setDoesNotReturn();
3840
3841 // What we really want is to massively penalize inlining without
3842 // forbidding it completely. The difference between that and
3843 // 'noinline' is negligible.
3844 fn->addFnAttr(llvm::Attribute::NoInline);
3845
3846 // Allow this function to be shared across translation units, but
3847 // we don't want it to turn into an exported symbol.
3848 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
3849 fn->setVisibility(llvm::Function::HiddenVisibility);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00003850 if (CGM.supportsCOMDAT())
3851 fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003852
3853 // Set up the function.
3854 llvm::BasicBlock *entry =
3855 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
John McCall7f416cc2015-09-08 08:05:57 +00003856 CGBuilderTy builder(CGM, entry);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003857
3858 // Pull the exception pointer out of the parameter list.
3859 llvm::Value *exn = &*fn->arg_begin();
3860
3861 // Call __cxa_begin_catch(exn).
3862 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
3863 catchCall->setDoesNotThrow();
3864 catchCall->setCallingConv(CGM.getRuntimeCC());
3865
3866 // Call std::terminate().
David Blaikie4ba525b2015-07-14 17:27:39 +00003867 llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn());
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003868 termCall->setDoesNotThrow();
3869 termCall->setDoesNotReturn();
3870 termCall->setCallingConv(CGM.getRuntimeCC());
3871
3872 // std::terminate cannot return.
3873 builder.CreateUnreachable();
3874 }
3875
3876 return fnRef;
3877}
3878
3879llvm::CallInst *
3880ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
3881 llvm::Value *Exn) {
3882 // In C++, we want to call __cxa_begin_catch() before terminating.
3883 if (Exn) {
3884 assert(CGF.CGM.getLangOpts().CPlusPlus);
3885 return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn);
3886 }
3887 return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
3888}