blob: 08c86176abcff0989f57a565c336b0aa703968bc [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 McCalld23b27e2016-09-16 02:40:45 +000048 bool Use32BitVTableOffsetABI;
John McCall7a9aac22010-08-23 01:21:21 +000049
Timur Iskhodzhanov67455222013-10-03 06:26:13 +000050 ItaniumMangleContext &getMangleContext() {
51 return cast<ItaniumMangleContext>(CodeGen::CGCXXABI::getMangleContext());
52 }
53
Charles Davis4e786dd2010-05-25 19:52:27 +000054public:
Mark Seabornedf0d382013-07-24 16:25:13 +000055 ItaniumCXXABI(CodeGen::CodeGenModule &CGM,
56 bool UseARMMethodPtrABI = false,
57 bool UseARMGuardVarABI = false) :
58 CGCXXABI(CGM), UseARMMethodPtrABI(UseARMMethodPtrABI),
John McCalld23b27e2016-09-16 02:40:45 +000059 UseARMGuardVarABI(UseARMGuardVarABI),
60 Use32BitVTableOffsetABI(false) { }
John McCall475999d2010-08-22 00:05:51 +000061
Reid Kleckner40ca9132014-05-13 22:05:45 +000062 bool classifyReturnType(CGFunctionInfo &FI) const override;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000063
Craig Topper4f12f102014-03-12 06:41:41 +000064 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override {
Reid Klecknerd355ca72014-05-15 01:26:32 +000065 // Structures with either a non-trivial destructor or a non-trivial
66 // copy constructor are always indirect.
67 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
68 // special members.
69 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor())
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000070 return RAA_Indirect;
71 return RAA_Default;
72 }
73
John McCall7f416cc2015-09-08 08:05:57 +000074 bool isThisCompleteObject(GlobalDecl GD) const override {
75 // The Itanium ABI has separate complete-object vs. base-object
76 // variants of both constructors and destructors.
77 if (isa<CXXDestructorDecl>(GD.getDecl())) {
78 switch (GD.getDtorType()) {
79 case Dtor_Complete:
80 case Dtor_Deleting:
81 return true;
82
83 case Dtor_Base:
84 return false;
85
86 case Dtor_Comdat:
87 llvm_unreachable("emitting dtor comdat as function?");
88 }
89 llvm_unreachable("bad dtor kind");
90 }
91 if (isa<CXXConstructorDecl>(GD.getDecl())) {
92 switch (GD.getCtorType()) {
93 case Ctor_Complete:
94 return true;
95
96 case Ctor_Base:
97 return false;
98
99 case Ctor_CopyingClosure:
100 case Ctor_DefaultClosure:
101 llvm_unreachable("closure ctors in Itanium ABI?");
102
103 case Ctor_Comdat:
104 llvm_unreachable("emitting ctor comdat as function?");
105 }
106 llvm_unreachable("bad dtor kind");
107 }
108
109 // No other kinds.
110 return false;
111 }
112
Craig Topper4f12f102014-03-12 06:41:41 +0000113 bool isZeroInitializable(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +0000114
Craig Topper4f12f102014-03-12 06:41:41 +0000115 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
John McCall7a9aac22010-08-23 01:21:21 +0000116
Craig Topper4f12f102014-03-12 06:41:41 +0000117 llvm::Value *
118 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
119 const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000120 Address This,
121 llvm::Value *&ThisPtrForCall,
Craig Topper4f12f102014-03-12 06:41:41 +0000122 llvm::Value *MemFnPtr,
123 const MemberPointerType *MPT) override;
John McCalla8bbb822010-08-22 03:04:22 +0000124
Craig Topper4f12f102014-03-12 06:41:41 +0000125 llvm::Value *
126 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000127 Address Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000128 llvm::Value *MemPtr,
129 const MemberPointerType *MPT) override;
John McCallc134eb52010-08-31 21:07:20 +0000130
John McCall7a9aac22010-08-23 01:21:21 +0000131 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
132 const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +0000133 llvm::Value *Src) override;
John McCallc62bb392012-02-15 01:22:51 +0000134 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +0000135 llvm::Constant *Src) override;
John McCall84fa5102010-08-22 04:16:24 +0000136
Craig Topper4f12f102014-03-12 06:41:41 +0000137 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +0000138
David Majnemere2be95b2015-06-23 07:31:01 +0000139 llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD) override;
John McCallf3a88602011-02-03 08:15:49 +0000140 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +0000141 CharUnits offset) override;
142 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
Richard Smithdafff942012-01-14 04:30:29 +0000143 llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
144 CharUnits ThisAdjustment);
John McCall1c456c82010-08-22 06:43:33 +0000145
John McCall7a9aac22010-08-23 01:21:21 +0000146 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000147 llvm::Value *L, llvm::Value *R,
John McCall7a9aac22010-08-23 01:21:21 +0000148 const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +0000149 bool Inequality) override;
John McCall131d97d2010-08-22 08:30:07 +0000150
John McCall7a9aac22010-08-23 01:21:21 +0000151 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000152 llvm::Value *Addr,
153 const MemberPointerType *MPT) override;
John McCall5d865c322010-08-31 07:33:07 +0000154
David Majnemer08681372014-11-01 07:37:17 +0000155 void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,
John McCall7f416cc2015-09-08 08:05:57 +0000156 Address Ptr, QualType ElementType,
David Majnemer0c0b6d92014-10-31 20:09:12 +0000157 const CXXDestructorDecl *Dtor) override;
John McCall82fb8922012-09-25 10:10:39 +0000158
John McCall7f416cc2015-09-08 08:05:57 +0000159 CharUnits getAlignmentOfExnObject() {
Akira Hatanaka68ab7fe2016-03-31 06:36:07 +0000160 unsigned Align = CGM.getContext().getTargetInfo().getExnObjectAlignment();
161 return CGM.getContext().toCharUnitsFromBits(Align);
John McCall7f416cc2015-09-08 08:05:57 +0000162 }
163
David Majnemer442d0a22014-11-25 07:20:20 +0000164 void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
David Majnemer7c237072015-03-05 00:46:22 +0000165 void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override;
David Majnemer442d0a22014-11-25 07:20:20 +0000166
Reid Klecknerfff8e7f2015-03-03 19:21:04 +0000167 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
168
169 llvm::CallInst *
170 emitTerminateForUnexpectedException(CodeGenFunction &CGF,
171 llvm::Value *Exn) override;
172
David Majnemere2cb8d12014-07-07 06:20:47 +0000173 void EmitFundamentalRTTIDescriptor(QualType Type);
174 void EmitFundamentalRTTIDescriptors();
David Majnemer443250f2015-03-17 20:35:00 +0000175 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
Reid Kleckner10aa7702015-09-16 20:15:55 +0000176 CatchTypeInfo
David Majnemer37b417f2015-03-29 21:55:10 +0000177 getAddrOfCXXCatchHandlerType(QualType Ty,
178 QualType CatchHandlerType) override {
Reid Kleckner10aa7702015-09-16 20:15:55 +0000179 return CatchTypeInfo{getAddrOfRTTIDescriptor(Ty), 0};
David Majnemer443250f2015-03-17 20:35:00 +0000180 }
David Majnemere2cb8d12014-07-07 06:20:47 +0000181
David Majnemer1162d252014-06-22 19:05:33 +0000182 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
183 void EmitBadTypeidCall(CodeGenFunction &CGF) override;
184 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
John McCall7f416cc2015-09-08 08:05:57 +0000185 Address ThisPtr,
David Majnemer1162d252014-06-22 19:05:33 +0000186 llvm::Type *StdTypeInfoPtrTy) override;
187
188 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
189 QualType SrcRecordTy) override;
190
John McCall7f416cc2015-09-08 08:05:57 +0000191 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, Address Value,
David Majnemer1162d252014-06-22 19:05:33 +0000192 QualType SrcRecordTy, QualType DestTy,
193 QualType DestRecordTy,
194 llvm::BasicBlock *CastEnd) override;
195
John McCall7f416cc2015-09-08 08:05:57 +0000196 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
David Majnemer1162d252014-06-22 19:05:33 +0000197 QualType SrcRecordTy,
198 QualType DestTy) override;
199
200 bool EmitBadCastCall(CodeGenFunction &CGF) override;
201
Craig Topper4f12f102014-03-12 06:41:41 +0000202 llvm::Value *
John McCall7f416cc2015-09-08 08:05:57 +0000203 GetVirtualBaseClassOffset(CodeGenFunction &CGF, Address This,
Craig Topper4f12f102014-03-12 06:41:41 +0000204 const CXXRecordDecl *ClassDecl,
205 const CXXRecordDecl *BaseClassDecl) override;
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000206
Craig Topper4f12f102014-03-12 06:41:41 +0000207 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000208
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000209 void buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
210 SmallVectorImpl<CanQualType> &ArgTys) override;
John McCall5d865c322010-08-31 07:33:07 +0000211
Reid Klecknere7de47e2013-07-22 13:51:44 +0000212 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
Craig Topper4f12f102014-03-12 06:41:41 +0000213 CXXDtorType DT) const override {
Reid Klecknere7de47e2013-07-22 13:51:44 +0000214 // Itanium does not emit any destructor variant as an inline thunk.
215 // Delegating may occur as an optimization, but all variants are either
216 // emitted with external linkage or as linkonce if they are inline and used.
217 return false;
218 }
219
Craig Topper4f12f102014-03-12 06:41:41 +0000220 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
Reid Klecknere7de47e2013-07-22 13:51:44 +0000221
Reid Kleckner89077a12013-12-17 19:46:40 +0000222 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
Craig Topper4f12f102014-03-12 06:41:41 +0000223 FunctionArgList &Params) override;
John McCall5d865c322010-08-31 07:33:07 +0000224
Craig Topper4f12f102014-03-12 06:41:41 +0000225 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
John McCall8ed55a52010-09-02 09:58:18 +0000226
Reid Kleckner89077a12013-12-17 19:46:40 +0000227 unsigned addImplicitConstructorArgs(CodeGenFunction &CGF,
228 const CXXConstructorDecl *D,
229 CXXCtorType Type, bool ForVirtualBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000230 bool Delegating,
231 CallArgList &Args) override;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000232
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000233 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
234 CXXDtorType Type, bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +0000235 bool Delegating, Address This) override;
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000236
Craig Topper4f12f102014-03-12 06:41:41 +0000237 void emitVTableDefinitions(CodeGenVTables &CGVT,
238 const CXXRecordDecl *RD) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000239
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000240 bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,
241 CodeGenFunction::VPtr Vptr) override;
242
243 bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override {
244 return true;
245 }
246
247 llvm::Constant *
248 getVTableAddressPoint(BaseSubobject Base,
249 const CXXRecordDecl *VTableClass) override;
250
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000251 llvm::Value *getVTableAddressPointInStructor(
252 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000253 BaseSubobject Base, const CXXRecordDecl *NearestVBase) override;
254
255 llvm::Value *getVTableAddressPointInStructorWithVTT(
256 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
257 BaseSubobject Base, const CXXRecordDecl *NearestVBase);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000258
259 llvm::Constant *
260 getVTableAddressPointForConstExpr(BaseSubobject Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000261 const CXXRecordDecl *VTableClass) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000262
263 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
Craig Topper4f12f102014-03-12 06:41:41 +0000264 CharUnits VPtrOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000265
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000266 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
John McCall7f416cc2015-09-08 08:05:57 +0000267 Address This, llvm::Type *Ty,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +0000268 SourceLocation Loc) override;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000269
David Majnemer0c0b6d92014-10-31 20:09:12 +0000270 llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
271 const CXXDestructorDecl *Dtor,
272 CXXDtorType DtorType,
John McCall7f416cc2015-09-08 08:05:57 +0000273 Address This,
David Majnemer0c0b6d92014-10-31 20:09:12 +0000274 const CXXMemberCallExpr *CE) override;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000275
Craig Topper4f12f102014-03-12 06:41:41 +0000276 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
Reid Kleckner7810af02013-06-19 15:20:38 +0000277
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000278 bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const override;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000279
Hans Wennborgc94391d2014-06-06 20:04:01 +0000280 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
281 bool ReturnAdjustment) override {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000282 // Allow inlining of thunks by emitting them with available_externally
283 // linkage together with vtables when needed.
Peter Collingbourne8fabc1b2015-07-01 02:10:26 +0000284 if (ForVTable && !Thunk->hasLocalLinkage())
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000285 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
286 }
287
John McCall7f416cc2015-09-08 08:05:57 +0000288 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This,
Craig Topper4f12f102014-03-12 06:41:41 +0000289 const ThisAdjustment &TA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000290
John McCall7f416cc2015-09-08 08:05:57 +0000291 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
Craig Topper4f12f102014-03-12 06:41:41 +0000292 const ReturnAdjustment &RA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000293
David Majnemer196ac332014-09-11 23:05:02 +0000294 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
295 FunctionArgList &Args) const override {
296 assert(!Args.empty() && "expected the arglist to not be empty!");
297 return Args.size() - 1;
298 }
299
Craig Topper4f12f102014-03-12 06:41:41 +0000300 StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
301 StringRef GetDeletedVirtualCallName() override
302 { return "__cxa_deleted_virtual"; }
Joao Matos2ce88ef2012-07-17 17:10:11 +0000303
Craig Topper4f12f102014-03-12 06:41:41 +0000304 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall7f416cc2015-09-08 08:05:57 +0000305 Address InitializeArrayCookie(CodeGenFunction &CGF,
306 Address NewPtr,
307 llvm::Value *NumElements,
308 const CXXNewExpr *expr,
309 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000310 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000311 Address allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000312 CharUnits cookieSize) override;
John McCall68ff0372010-09-08 01:44:27 +0000313
John McCallcdf7ef52010-11-06 09:44:32 +0000314 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000315 llvm::GlobalVariable *DeclPtr,
316 bool PerformInit) override;
Richard Smithdbf74ba2013-04-14 23:01:42 +0000317 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000318 llvm::Constant *dtor, llvm::Constant *addr) override;
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000319
320 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +0000321 llvm::Value *Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000322 void EmitThreadLocalInitFuncs(
David Majnemerb3341ea2014-10-05 05:05:40 +0000323 CodeGenModule &CGM,
Richard Smith5a99c492015-12-01 01:10:48 +0000324 ArrayRef<const VarDecl *> CXXThreadLocals,
David Majnemerb3341ea2014-10-05 05:05:40 +0000325 ArrayRef<llvm::Function *> CXXThreadLocalInits,
Richard Smith5a99c492015-12-01 01:10:48 +0000326 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) override;
David Majnemerb3341ea2014-10-05 05:05:40 +0000327
328 bool usesThreadWrapperFunction() const override { return true; }
Richard Smith0f383742014-03-26 22:48:22 +0000329 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
330 QualType LValType) override;
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000331
Craig Topper4f12f102014-03-12 06:41:41 +0000332 bool NeedsVTTParameter(GlobalDecl GD) override;
David Majnemere2cb8d12014-07-07 06:20:47 +0000333
334 /**************************** RTTI Uniqueness ******************************/
335
336protected:
337 /// Returns true if the ABI requires RTTI type_info objects to be unique
338 /// across a program.
339 virtual bool shouldRTTIBeUnique() const { return true; }
340
341public:
342 /// What sort of unique-RTTI behavior should we use?
343 enum RTTIUniquenessKind {
344 /// We are guaranteeing, or need to guarantee, that the RTTI string
345 /// is unique.
346 RUK_Unique,
347
348 /// We are not guaranteeing uniqueness for the RTTI string, so we
349 /// can demote to hidden visibility but must use string comparisons.
350 RUK_NonUniqueHidden,
351
352 /// We are not guaranteeing uniqueness for the RTTI string, so we
353 /// have to use string comparisons, but we also have to emit it with
354 /// non-hidden visibility.
355 RUK_NonUniqueVisible
356 };
357
358 /// Return the required visibility status for the given type and linkage in
359 /// the current ABI.
360 RTTIUniquenessKind
361 classifyRTTIUniqueness(QualType CanTy,
362 llvm::GlobalValue::LinkageTypes Linkage) const;
363 friend class ItaniumRTTIBuilder;
Rafael Espindola91f68b42014-09-15 19:20:10 +0000364
365 void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000366
367 private:
Piotr Padlewski1d02f682015-08-19 20:09:09 +0000368 bool hasAnyUsedVirtualInlineFunction(const CXXRecordDecl *RD) const {
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000369 const auto &VtableLayout =
370 CGM.getItaniumVTableContext().getVTableLayout(RD);
371
372 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
Piotr Padlewski1d02f682015-08-19 20:09:09 +0000373 if (!VtableComponent.isUsedFunctionPointerKind())
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000374 continue;
375
Piotr Padlewski1d02f682015-08-19 20:09:09 +0000376 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000377 if (Method->getCanonicalDecl()->isInlined())
378 return true;
379 }
380 return false;
381 }
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000382
383 bool isVTableHidden(const CXXRecordDecl *RD) const {
384 const auto &VtableLayout =
385 CGM.getItaniumVTableContext().getVTableLayout(RD);
386
387 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
388 if (VtableComponent.isRTTIKind()) {
389 const CXXRecordDecl *RTTIDecl = VtableComponent.getRTTIDecl();
390 if (RTTIDecl->getVisibility() == Visibility::HiddenVisibility)
391 return true;
392 } else if (VtableComponent.isUsedFunctionPointerKind()) {
393 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
394 if (Method->getVisibility() == Visibility::HiddenVisibility &&
395 !Method->isDefined())
396 return true;
397 }
398 }
399 return false;
400 }
Charles Davis4e786dd2010-05-25 19:52:27 +0000401};
John McCall86353412010-08-21 22:46:04 +0000402
403class ARMCXXABI : public ItaniumCXXABI {
404public:
Mark Seabornedf0d382013-07-24 16:25:13 +0000405 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
406 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
407 /* UseARMGuardVarABI = */ true) {}
John McCall5d865c322010-08-31 07:33:07 +0000408
Craig Topper4f12f102014-03-12 06:41:41 +0000409 bool HasThisReturn(GlobalDecl GD) const override {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000410 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
411 isa<CXXDestructorDecl>(GD.getDecl()) &&
412 GD.getDtorType() != Dtor_Deleting));
413 }
John McCall5d865c322010-08-31 07:33:07 +0000414
Craig Topper4f12f102014-03-12 06:41:41 +0000415 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
416 QualType ResTy) override;
John McCall5d865c322010-08-31 07:33:07 +0000417
Craig Topper4f12f102014-03-12 06:41:41 +0000418 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall7f416cc2015-09-08 08:05:57 +0000419 Address InitializeArrayCookie(CodeGenFunction &CGF,
420 Address NewPtr,
421 llvm::Value *NumElements,
422 const CXXNewExpr *expr,
423 QualType ElementType) override;
424 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, Address allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000425 CharUnits cookieSize) override;
John McCall86353412010-08-21 22:46:04 +0000426};
Tim Northovera2ee4332014-03-29 15:09:45 +0000427
428class iOS64CXXABI : public ARMCXXABI {
429public:
John McCalld23b27e2016-09-16 02:40:45 +0000430 iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {
431 Use32BitVTableOffsetABI = true;
432 }
Tim Northover65f582f2014-03-30 17:32:48 +0000433
434 // ARM64 libraries are prepared for non-unique RTTI.
David Majnemere2cb8d12014-07-07 06:20:47 +0000435 bool shouldRTTIBeUnique() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +0000436};
Dan Gohmanc2853072015-09-03 22:51:53 +0000437
438class WebAssemblyCXXABI final : public ItaniumCXXABI {
439public:
440 explicit WebAssemblyCXXABI(CodeGen::CodeGenModule &CGM)
441 : ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
442 /*UseARMGuardVarABI=*/true) {}
443
444private:
445 bool HasThisReturn(GlobalDecl GD) const override {
446 return isa<CXXConstructorDecl>(GD.getDecl()) ||
447 (isa<CXXDestructorDecl>(GD.getDecl()) &&
448 GD.getDtorType() != Dtor_Deleting);
449 }
Derek Schuff8179be42016-05-10 17:44:55 +0000450 bool canCallMismatchedFunctionType() const override { return false; }
Dan Gohmanc2853072015-09-03 22:51:53 +0000451};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000452}
Charles Davis4e786dd2010-05-25 19:52:27 +0000453
Charles Davis53c59df2010-08-16 03:33:14 +0000454CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000455 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000456 // For IR-generation purposes, there's no significant difference
457 // between the ARM and iOS ABIs.
458 case TargetCXXABI::GenericARM:
459 case TargetCXXABI::iOS:
Tim Northover756447a2015-10-30 16:30:36 +0000460 case TargetCXXABI::WatchOS:
John McCall57625922013-01-25 23:36:14 +0000461 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000462
Tim Northovera2ee4332014-03-29 15:09:45 +0000463 case TargetCXXABI::iOS64:
464 return new iOS64CXXABI(CGM);
465
Tim Northover9bb857a2013-01-31 12:13:10 +0000466 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
467 // include the other 32-bit ARM oddities: constructor/destructor return values
468 // and array cookies.
469 case TargetCXXABI::GenericAArch64:
Mark Seabornedf0d382013-07-24 16:25:13 +0000470 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
471 /* UseARMGuardVarABI = */ true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000472
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000473 case TargetCXXABI::GenericMIPS:
474 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true);
475
Dan Gohmanc2853072015-09-03 22:51:53 +0000476 case TargetCXXABI::WebAssembly:
477 return new WebAssemblyCXXABI(CGM);
478
John McCall57625922013-01-25 23:36:14 +0000479 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000480 if (CGM.getContext().getTargetInfo().getTriple().getArch()
481 == llvm::Triple::le32) {
482 // For PNaCl, use ARM-style method pointers so that PNaCl code
483 // does not assume anything about the alignment of function
484 // pointers.
485 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
486 /* UseARMGuardVarABI = */ false);
487 }
John McCall57625922013-01-25 23:36:14 +0000488 return new ItaniumCXXABI(CGM);
489
490 case TargetCXXABI::Microsoft:
491 llvm_unreachable("Microsoft ABI is not Itanium-based");
492 }
493 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000494}
495
Chris Lattnera5f58b02011-07-09 17:41:47 +0000496llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000497ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
498 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000499 return CGM.PtrDiffTy;
Reid Kleckneree7cf842014-12-01 22:02:27 +0000500 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, nullptr);
John McCall1c456c82010-08-22 06:43:33 +0000501}
502
John McCalld9c6c0b2010-08-22 00:59:17 +0000503/// In the Itanium and ARM ABIs, method pointers have the form:
504/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
505///
506/// In the Itanium ABI:
507/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
508/// - the this-adjustment is (memptr.adj)
509/// - the virtual offset is (memptr.ptr - 1)
510///
511/// In the ARM ABI:
512/// - method pointers are virtual if (memptr.adj & 1) is nonzero
513/// - the this-adjustment is (memptr.adj >> 1)
514/// - the virtual offset is (memptr.ptr)
515/// ARM uses 'adj' for the virtual flag because Thumb functions
516/// may be only single-byte aligned.
517///
518/// If the member is virtual, the adjusted 'this' pointer points
519/// to a vtable pointer from which the virtual offset is applied.
520///
521/// If the member is non-virtual, memptr.ptr is the address of
522/// the function to call.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000523llvm::Value *ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
John McCall7f416cc2015-09-08 08:05:57 +0000524 CodeGenFunction &CGF, const Expr *E, Address ThisAddr,
525 llvm::Value *&ThisPtrForCall,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000526 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
John McCall475999d2010-08-22 00:05:51 +0000527 CGBuilderTy &Builder = CGF.Builder;
528
529 const FunctionProtoType *FPT =
530 MPT->getPointeeType()->getAs<FunctionProtoType>();
531 const CXXRecordDecl *RD =
532 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
533
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000534 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(
535 CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr));
John McCall475999d2010-08-22 00:05:51 +0000536
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000537 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000538
John McCalld9c6c0b2010-08-22 00:59:17 +0000539 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
540 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
541 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
542
John McCalla1dee5302010-08-22 10:59:02 +0000543 // Extract memptr.adj, which is in the second field.
544 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000545
546 // Compute the true adjustment.
547 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000548 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000549 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000550
551 // Apply the adjustment and cast back to the original struct type
552 // for consistency.
John McCall7f416cc2015-09-08 08:05:57 +0000553 llvm::Value *This = ThisAddr.getPointer();
John McCalld9c6c0b2010-08-22 00:59:17 +0000554 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
555 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
556 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall7f416cc2015-09-08 08:05:57 +0000557 ThisPtrForCall = This;
John McCall475999d2010-08-22 00:05:51 +0000558
559 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000560 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall475999d2010-08-22 00:05:51 +0000561
562 // If the LSB in the function pointer is 1, the function pointer points to
563 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000564 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000565 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000566 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
567 else
568 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
569 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000570 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
571
572 // In the virtual path, the adjustment left 'This' pointing to the
573 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000574 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000575 CGF.EmitBlock(FnVirtual);
576
577 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000578 llvm::Type *VTableTy = Builder.getInt8PtrTy();
John McCall7f416cc2015-09-08 08:05:57 +0000579 CharUnits VTablePtrAlign =
580 CGF.CGM.getDynamicOffsetAlignment(ThisAddr.getAlignment(), RD,
581 CGF.getPointerAlign());
582 llvm::Value *VTable =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000583 CGF.GetVTablePtr(Address(This, VTablePtrAlign), VTableTy, RD);
John McCall475999d2010-08-22 00:05:51 +0000584
585 // Apply the offset.
John McCalld23b27e2016-09-16 02:40:45 +0000586 // On ARM64, to reserve extra space in virtual member function pointers,
587 // we only pay attention to the low 32 bits of the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000588 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000589 if (!UseARMMethodPtrABI)
590 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld23b27e2016-09-16 02:40:45 +0000591 if (Use32BitVTableOffsetABI) {
592 VTableOffset = Builder.CreateTrunc(VTableOffset, CGF.Int32Ty);
593 VTableOffset = Builder.CreateZExt(VTableOffset, CGM.PtrDiffTy);
594 }
John McCalld9c6c0b2010-08-22 00:59:17 +0000595 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall475999d2010-08-22 00:05:51 +0000596
597 // Load the virtual function to call.
598 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCall7f416cc2015-09-08 08:05:57 +0000599 llvm::Value *VirtualFn =
600 Builder.CreateAlignedLoad(VTable, CGF.getPointerAlign(),
601 "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000602 CGF.EmitBranch(FnEnd);
603
604 // In the non-virtual path, the function pointer is actually a
605 // function pointer.
606 CGF.EmitBlock(FnNonVirtual);
607 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000608 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall475999d2010-08-22 00:05:51 +0000609
610 // We're done.
611 CGF.EmitBlock(FnEnd);
Jay Foad20c0f022011-03-30 11:28:58 +0000612 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
John McCall475999d2010-08-22 00:05:51 +0000613 Callee->addIncoming(VirtualFn, FnVirtual);
614 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
615 return Callee;
616}
John McCalla8bbb822010-08-22 03:04:22 +0000617
John McCallc134eb52010-08-31 21:07:20 +0000618/// Compute an l-value by applying the given pointer-to-member to a
619/// base object.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000620llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
John McCall7f416cc2015-09-08 08:05:57 +0000621 CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000622 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000623 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000624
625 CGBuilderTy &Builder = CGF.Builder;
626
John McCallc134eb52010-08-31 21:07:20 +0000627 // Cast to char*.
John McCall7f416cc2015-09-08 08:05:57 +0000628 Base = Builder.CreateElementBitCast(Base, CGF.Int8Ty);
John McCallc134eb52010-08-31 21:07:20 +0000629
630 // Apply the offset, which we assume is non-null.
John McCall7f416cc2015-09-08 08:05:57 +0000631 llvm::Value *Addr =
632 Builder.CreateInBoundsGEP(Base.getPointer(), MemPtr, "memptr.offset");
John McCallc134eb52010-08-31 21:07:20 +0000633
634 // Cast the address to the appropriate pointer type, adopting the
635 // address space of the base pointer.
John McCall7f416cc2015-09-08 08:05:57 +0000636 llvm::Type *PType = CGF.ConvertTypeForMem(MPT->getPointeeType())
637 ->getPointerTo(Base.getAddressSpace());
John McCallc134eb52010-08-31 21:07:20 +0000638 return Builder.CreateBitCast(Addr, PType);
639}
640
John McCallc62bb392012-02-15 01:22:51 +0000641/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
642/// conversion.
643///
644/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000645///
646/// Obligatory offset/adjustment diagram:
647/// <-- offset --> <-- adjustment -->
648/// |--------------------------|----------------------|--------------------|
649/// ^Derived address point ^Base address point ^Member address point
650///
651/// So when converting a base member pointer to a derived member pointer,
652/// we add the offset to the adjustment because the address point has
653/// decreased; and conversely, when converting a derived MP to a base MP
654/// we subtract the offset from the adjustment because the address point
655/// has increased.
656///
657/// The standard forbids (at compile time) conversion to and from
658/// virtual bases, which is why we don't have to consider them here.
659///
660/// The standard forbids (at run time) casting a derived MP to a base
661/// MP when the derived MP does not point to a member of the base.
662/// This is why -1 is a reasonable choice for null data member
663/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000664llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000665ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
666 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000667 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000668 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000669 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
670 E->getCastKind() == CK_ReinterpretMemberPointer);
671
672 // Under Itanium, reinterprets don't require any additional processing.
673 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
674
675 // Use constant emission if we can.
676 if (isa<llvm::Constant>(src))
677 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
678
679 llvm::Constant *adj = getMemberPointerAdjustment(E);
680 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000681
682 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000683 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000684
John McCallc62bb392012-02-15 01:22:51 +0000685 const MemberPointerType *destTy =
686 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000687
John McCall7a9aac22010-08-23 01:21:21 +0000688 // For member data pointers, this is just a matter of adding the
689 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000690 if (destTy->isMemberDataPointer()) {
691 llvm::Value *dst;
692 if (isDerivedToBase)
693 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000694 else
John McCallc62bb392012-02-15 01:22:51 +0000695 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000696
697 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000698 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
699 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
700 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000701 }
702
John McCalla1dee5302010-08-22 10:59:02 +0000703 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000704 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000705 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
706 offset <<= 1;
707 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000708 }
709
John McCallc62bb392012-02-15 01:22:51 +0000710 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
711 llvm::Value *dstAdj;
712 if (isDerivedToBase)
713 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000714 else
John McCallc62bb392012-02-15 01:22:51 +0000715 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000716
John McCallc62bb392012-02-15 01:22:51 +0000717 return Builder.CreateInsertValue(src, dstAdj, 1);
718}
719
720llvm::Constant *
721ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
722 llvm::Constant *src) {
723 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
724 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
725 E->getCastKind() == CK_ReinterpretMemberPointer);
726
727 // Under Itanium, reinterprets don't require any additional processing.
728 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
729
730 // If the adjustment is trivial, we don't need to do anything.
731 llvm::Constant *adj = getMemberPointerAdjustment(E);
732 if (!adj) return src;
733
734 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
735
736 const MemberPointerType *destTy =
737 E->getType()->castAs<MemberPointerType>();
738
739 // For member data pointers, this is just a matter of adding the
740 // offset if the source is non-null.
741 if (destTy->isMemberDataPointer()) {
742 // null maps to null.
743 if (src->isAllOnesValue()) return src;
744
745 if (isDerivedToBase)
746 return llvm::ConstantExpr::getNSWSub(src, adj);
747 else
748 return llvm::ConstantExpr::getNSWAdd(src, adj);
749 }
750
751 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000752 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000753 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
754 offset <<= 1;
755 adj = llvm::ConstantInt::get(adj->getType(), offset);
756 }
757
758 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
759 llvm::Constant *dstAdj;
760 if (isDerivedToBase)
761 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
762 else
763 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
764
765 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000766}
John McCall84fa5102010-08-22 04:16:24 +0000767
768llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000769ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000770 // Itanium C++ ABI 2.3:
771 // A NULL pointer is represented as -1.
772 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000773 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000774
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000775 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000776 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000777 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000778}
779
John McCallf3a88602011-02-03 08:15:49 +0000780llvm::Constant *
781ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
782 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000783 // Itanium C++ ABI 2.3:
784 // A pointer to data member is an offset from the base address of
785 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000786 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000787}
788
David Majnemere2be95b2015-06-23 07:31:01 +0000789llvm::Constant *
790ItaniumCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000791 return BuildMemberPointer(MD, CharUnits::Zero());
792}
793
794llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
795 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000796 assert(MD->isInstance() && "Member function must not be static!");
797 MD = MD->getCanonicalDecl();
798
799 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000800
801 // Get the function pointer (or index if this is a virtual function).
802 llvm::Constant *MemPtr[2];
803 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000804 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000805
Ken Dyckdf016282011-04-09 01:30:02 +0000806 const ASTContext &Context = getContext();
807 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000808 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000809 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000810
Mark Seabornedf0d382013-07-24 16:25:13 +0000811 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000812 // ARM C++ ABI 3.2.1:
813 // This ABI specifies that adj contains twice the this
814 // adjustment, plus 1 if the member function is virtual. The
815 // least significant bit of adj then makes exactly the same
816 // discrimination as the least significant bit of ptr does for
817 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000818 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
819 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000820 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000821 } else {
822 // Itanium C++ ABI 2.3:
823 // For a virtual function, [the pointer field] is 1 plus the
824 // virtual table offset (in bytes) of the function,
825 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000826 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
827 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000828 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000829 }
830 } else {
John McCall2979fe02011-04-12 00:42:48 +0000831 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000832 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000833 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000834 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000835 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000836 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000837 } else {
John McCall2979fe02011-04-12 00:42:48 +0000838 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
839 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000840 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000841 }
John McCall2979fe02011-04-12 00:42:48 +0000842 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000843
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000844 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000845 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
846 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000847 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000848 }
John McCall1c456c82010-08-22 06:43:33 +0000849
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000850 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000851}
852
Richard Smithdafff942012-01-14 04:30:29 +0000853llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
854 QualType MPType) {
855 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
856 const ValueDecl *MPD = MP.getMemberPointerDecl();
857 if (!MPD)
858 return EmitNullMemberPointer(MPT);
859
Reid Kleckner452abac2013-05-09 21:01:17 +0000860 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000861
862 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
863 return BuildMemberPointer(MD, ThisAdjustment);
864
865 CharUnits FieldOffset =
866 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
867 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
868}
869
John McCall131d97d2010-08-22 08:30:07 +0000870/// The comparison algorithm is pretty easy: the member pointers are
871/// the same if they're either bitwise identical *or* both null.
872///
873/// ARM is different here only because null-ness is more complicated.
874llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000875ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
876 llvm::Value *L,
877 llvm::Value *R,
878 const MemberPointerType *MPT,
879 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000880 CGBuilderTy &Builder = CGF.Builder;
881
John McCall131d97d2010-08-22 08:30:07 +0000882 llvm::ICmpInst::Predicate Eq;
883 llvm::Instruction::BinaryOps And, Or;
884 if (Inequality) {
885 Eq = llvm::ICmpInst::ICMP_NE;
886 And = llvm::Instruction::Or;
887 Or = llvm::Instruction::And;
888 } else {
889 Eq = llvm::ICmpInst::ICMP_EQ;
890 And = llvm::Instruction::And;
891 Or = llvm::Instruction::Or;
892 }
893
John McCall7a9aac22010-08-23 01:21:21 +0000894 // Member data pointers are easy because there's a unique null
895 // value, so it just comes down to bitwise equality.
896 if (MPT->isMemberDataPointer())
897 return Builder.CreateICmp(Eq, L, R);
898
899 // For member function pointers, the tautologies are more complex.
900 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000901 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000902 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000903 // (L == R) <==> (L.ptr == R.ptr &&
904 // (L.adj == R.adj ||
905 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000906 // The inequality tautologies have exactly the same structure, except
907 // applying De Morgan's laws.
908
909 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
910 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
911
John McCall131d97d2010-08-22 08:30:07 +0000912 // This condition tests whether L.ptr == R.ptr. This must always be
913 // true for equality to hold.
914 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
915
916 // This condition, together with the assumption that L.ptr == R.ptr,
917 // tests whether the pointers are both null. ARM imposes an extra
918 // condition.
919 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
920 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
921
922 // This condition tests whether L.adj == R.adj. If this isn't
923 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +0000924 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
925 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000926 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
927
928 // Null member function pointers on ARM clear the low bit of Adj,
929 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000930 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000931 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
932
933 // Compute (l.adj | r.adj) & 1 and test it against zero.
934 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
935 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
936 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
937 "cmp.or.adj");
938 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
939 }
940
941 // Tie together all our conditions.
942 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
943 Result = Builder.CreateBinOp(And, PtrEq, Result,
944 Inequality ? "memptr.ne" : "memptr.eq");
945 return Result;
946}
947
948llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000949ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
950 llvm::Value *MemPtr,
951 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +0000952 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +0000953
954 /// For member data pointers, this is just a check against -1.
955 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000956 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +0000957 llvm::Value *NegativeOne =
958 llvm::Constant::getAllOnesValue(MemPtr->getType());
959 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
960 }
John McCall131d97d2010-08-22 08:30:07 +0000961
Daniel Dunbar914bc412011-04-19 23:10:47 +0000962 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +0000963 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +0000964
965 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
966 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
967
Daniel Dunbar914bc412011-04-19 23:10:47 +0000968 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
969 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000970 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000971 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +0000972 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000973 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +0000974 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
975 "memptr.isvirtual");
976 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +0000977 }
978
979 return Result;
980}
John McCall1c456c82010-08-22 06:43:33 +0000981
Reid Kleckner40ca9132014-05-13 22:05:45 +0000982bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
983 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
984 if (!RD)
985 return false;
986
Reid Klecknerd355ca72014-05-15 01:26:32 +0000987 // Return indirectly if we have a non-trivial copy ctor or non-trivial dtor.
988 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
989 // special members.
990 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor()) {
John McCall7f416cc2015-09-08 08:05:57 +0000991 auto Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
992 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
Reid Kleckner40ca9132014-05-13 22:05:45 +0000993 return true;
994 }
Reid Kleckner40ca9132014-05-13 22:05:45 +0000995 return false;
996}
997
John McCall614dbdc2010-08-22 21:01:12 +0000998/// The Itanium ABI requires non-zero initialization only for data
999/// member pointers, for which '0' is a valid offset.
1000bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
David Majnemer5fd33e02015-04-24 01:25:08 +00001001 return MPT->isMemberFunctionPointer();
John McCall84fa5102010-08-22 04:16:24 +00001002}
John McCall5d865c322010-08-31 07:33:07 +00001003
John McCall82fb8922012-09-25 10:10:39 +00001004/// The Itanium ABI always places an offset to the complete object
1005/// at entry -2 in the vtable.
David Majnemer08681372014-11-01 07:37:17 +00001006void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
1007 const CXXDeleteExpr *DE,
John McCall7f416cc2015-09-08 08:05:57 +00001008 Address Ptr,
David Majnemer08681372014-11-01 07:37:17 +00001009 QualType ElementType,
1010 const CXXDestructorDecl *Dtor) {
1011 bool UseGlobalDelete = DE->isGlobalDelete();
David Majnemer0c0b6d92014-10-31 20:09:12 +00001012 if (UseGlobalDelete) {
1013 // Derive the complete-object pointer, which is what we need
1014 // to pass to the deallocation function.
John McCall82fb8922012-09-25 10:10:39 +00001015
David Majnemer0c0b6d92014-10-31 20:09:12 +00001016 // Grab the vtable pointer as an intptr_t*.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001017 auto *ClassDecl =
1018 cast<CXXRecordDecl>(ElementType->getAs<RecordType>()->getDecl());
1019 llvm::Value *VTable =
1020 CGF.GetVTablePtr(Ptr, CGF.IntPtrTy->getPointerTo(), ClassDecl);
John McCall82fb8922012-09-25 10:10:39 +00001021
David Majnemer0c0b6d92014-10-31 20:09:12 +00001022 // Track back to entry -2 and pull out the offset there.
1023 llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
1024 VTable, -2, "complete-offset.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001025 llvm::Value *Offset =
1026 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
David Majnemer0c0b6d92014-10-31 20:09:12 +00001027
1028 // Apply the offset.
John McCall7f416cc2015-09-08 08:05:57 +00001029 llvm::Value *CompletePtr =
1030 CGF.Builder.CreateBitCast(Ptr.getPointer(), CGF.Int8PtrTy);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001031 CompletePtr = CGF.Builder.CreateInBoundsGEP(CompletePtr, Offset);
1032
1033 // If we're supposed to call the global delete, make sure we do so
1034 // even if the destructor throws.
David Majnemer08681372014-11-01 07:37:17 +00001035 CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr,
1036 ElementType);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001037 }
1038
1039 // FIXME: Provide a source location here even though there's no
1040 // CXXMemberCallExpr for dtor call.
1041 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
1042 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr);
1043
1044 if (UseGlobalDelete)
1045 CGF.PopCleanupBlock();
John McCall82fb8922012-09-25 10:10:39 +00001046}
1047
David Majnemer442d0a22014-11-25 07:20:20 +00001048void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
1049 // void __cxa_rethrow();
1050
1051 llvm::FunctionType *FTy =
1052 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
1053
1054 llvm::Constant *Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
1055
1056 if (isNoReturn)
1057 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, None);
1058 else
1059 CGF.EmitRuntimeCallOrInvoke(Fn);
1060}
1061
David Majnemer7c237072015-03-05 00:46:22 +00001062static llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) {
1063 // void *__cxa_allocate_exception(size_t thrown_size);
1064
1065 llvm::FunctionType *FTy =
1066 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false);
1067
1068 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
1069}
1070
1071static llvm::Constant *getThrowFn(CodeGenModule &CGM) {
1072 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
1073 // void (*dest) (void *));
1074
1075 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
1076 llvm::FunctionType *FTy =
1077 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
1078
1079 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
1080}
1081
1082void ItaniumCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
1083 QualType ThrowType = E->getSubExpr()->getType();
1084 // Now allocate the exception object.
1085 llvm::Type *SizeTy = CGF.ConvertType(getContext().getSizeType());
1086 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
1087
1088 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM);
1089 llvm::CallInst *ExceptionPtr = CGF.EmitNounwindRuntimeCall(
1090 AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception");
1091
John McCall7f416cc2015-09-08 08:05:57 +00001092 CharUnits ExnAlign = getAlignmentOfExnObject();
1093 CGF.EmitAnyExprToExn(E->getSubExpr(), Address(ExceptionPtr, ExnAlign));
David Majnemer7c237072015-03-05 00:46:22 +00001094
1095 // Now throw the exception.
1096 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
1097 /*ForEH=*/true);
1098
1099 // The address of the destructor. If the exception type has a
1100 // trivial destructor (or isn't a record), we just pass null.
1101 llvm::Constant *Dtor = nullptr;
1102 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
1103 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
1104 if (!Record->hasTrivialDestructor()) {
1105 CXXDestructorDecl *DtorD = Record->getDestructor();
1106 Dtor = CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete);
1107 Dtor = llvm::ConstantExpr::getBitCast(Dtor, CGM.Int8PtrTy);
1108 }
1109 }
1110 if (!Dtor) Dtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
1111
1112 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
1113 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
1114}
1115
David Majnemer1162d252014-06-22 19:05:33 +00001116static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) {
1117 // void *__dynamic_cast(const void *sub,
1118 // const abi::__class_type_info *src,
1119 // const abi::__class_type_info *dst,
1120 // std::ptrdiff_t src2dst_offset);
1121
1122 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1123 llvm::Type *PtrDiffTy =
1124 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1125
1126 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
1127
1128 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
1129
1130 // Mark the function as nounwind readonly.
1131 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
1132 llvm::Attribute::ReadOnly };
1133 llvm::AttributeSet Attrs = llvm::AttributeSet::get(
1134 CGF.getLLVMContext(), llvm::AttributeSet::FunctionIndex, FuncAttrs);
1135
1136 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
1137}
1138
1139static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1140 // void __cxa_bad_cast();
1141 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1142 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1143}
1144
1145/// \brief Compute the src2dst_offset hint as described in the
1146/// Itanium C++ ABI [2.9.7]
1147static CharUnits computeOffsetHint(ASTContext &Context,
1148 const CXXRecordDecl *Src,
1149 const CXXRecordDecl *Dst) {
1150 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1151 /*DetectVirtual=*/false);
1152
1153 // If Dst is not derived from Src we can skip the whole computation below and
1154 // return that Src is not a public base of Dst. Record all inheritance paths.
1155 if (!Dst->isDerivedFrom(Src, Paths))
1156 return CharUnits::fromQuantity(-2ULL);
1157
1158 unsigned NumPublicPaths = 0;
1159 CharUnits Offset;
1160
1161 // Now walk all possible inheritance paths.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001162 for (const CXXBasePath &Path : Paths) {
1163 if (Path.Access != AS_public) // Ignore non-public inheritance.
David Majnemer1162d252014-06-22 19:05:33 +00001164 continue;
1165
1166 ++NumPublicPaths;
1167
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001168 for (const CXXBasePathElement &PathElement : Path) {
David Majnemer1162d252014-06-22 19:05:33 +00001169 // If the path contains a virtual base class we can't give any hint.
1170 // -1: no hint.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001171 if (PathElement.Base->isVirtual())
David Majnemer1162d252014-06-22 19:05:33 +00001172 return CharUnits::fromQuantity(-1ULL);
1173
1174 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
1175 continue;
1176
1177 // Accumulate the base class offsets.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001178 const ASTRecordLayout &L = Context.getASTRecordLayout(PathElement.Class);
1179 Offset += L.getBaseClassOffset(
1180 PathElement.Base->getType()->getAsCXXRecordDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001181 }
1182 }
1183
1184 // -2: Src is not a public base of Dst.
1185 if (NumPublicPaths == 0)
1186 return CharUnits::fromQuantity(-2ULL);
1187
1188 // -3: Src is a multiple public base type but never a virtual base type.
1189 if (NumPublicPaths > 1)
1190 return CharUnits::fromQuantity(-3ULL);
1191
1192 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
1193 // Return the offset of Src from the origin of Dst.
1194 return Offset;
1195}
1196
1197static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1198 // void __cxa_bad_typeid();
1199 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1200
1201 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1202}
1203
1204bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
1205 QualType SrcRecordTy) {
1206 return IsDeref;
1207}
1208
1209void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
1210 llvm::Value *Fn = getBadTypeidFn(CGF);
1211 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1212 CGF.Builder.CreateUnreachable();
1213}
1214
1215llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
1216 QualType SrcRecordTy,
John McCall7f416cc2015-09-08 08:05:57 +00001217 Address ThisPtr,
David Majnemer1162d252014-06-22 19:05:33 +00001218 llvm::Type *StdTypeInfoPtrTy) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001219 auto *ClassDecl =
1220 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001221 llvm::Value *Value =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001222 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo(), ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001223
1224 // Load the type info.
1225 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001226 return CGF.Builder.CreateAlignedLoad(Value, CGF.getPointerAlign());
David Majnemer1162d252014-06-22 19:05:33 +00001227}
1228
1229bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1230 QualType SrcRecordTy) {
1231 return SrcIsPtr;
1232}
1233
1234llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
John McCall7f416cc2015-09-08 08:05:57 +00001235 CodeGenFunction &CGF, Address ThisAddr, QualType SrcRecordTy,
David Majnemer1162d252014-06-22 19:05:33 +00001236 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1237 llvm::Type *PtrDiffLTy =
1238 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1239 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1240
1241 llvm::Value *SrcRTTI =
1242 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1243 llvm::Value *DestRTTI =
1244 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1245
1246 // Compute the offset hint.
1247 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1248 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1249 llvm::Value *OffsetHint = llvm::ConstantInt::get(
1250 PtrDiffLTy,
1251 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
1252
1253 // Emit the call to __dynamic_cast.
John McCall7f416cc2015-09-08 08:05:57 +00001254 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001255 Value = CGF.EmitCastToVoidPtr(Value);
1256
1257 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
1258 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
1259 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1260
1261 /// C++ [expr.dynamic.cast]p9:
1262 /// A failed cast to reference type throws std::bad_cast
1263 if (DestTy->isReferenceType()) {
1264 llvm::BasicBlock *BadCastBlock =
1265 CGF.createBasicBlock("dynamic_cast.bad_cast");
1266
1267 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1268 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1269
1270 CGF.EmitBlock(BadCastBlock);
1271 EmitBadCastCall(CGF);
1272 }
1273
1274 return Value;
1275}
1276
1277llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001278 Address ThisAddr,
David Majnemer1162d252014-06-22 19:05:33 +00001279 QualType SrcRecordTy,
1280 QualType DestTy) {
1281 llvm::Type *PtrDiffLTy =
1282 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1283 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1284
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001285 auto *ClassDecl =
1286 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001287 // Get the vtable pointer.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001288 llvm::Value *VTable = CGF.GetVTablePtr(ThisAddr, PtrDiffLTy->getPointerTo(),
1289 ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001290
1291 // Get the offset-to-top from the vtable.
1292 llvm::Value *OffsetToTop =
1293 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001294 OffsetToTop =
1295 CGF.Builder.CreateAlignedLoad(OffsetToTop, CGF.getPointerAlign(),
1296 "offset.to.top");
David Majnemer1162d252014-06-22 19:05:33 +00001297
1298 // Finally, add the offset to the pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001299 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001300 Value = CGF.EmitCastToVoidPtr(Value);
1301 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1302
1303 return CGF.Builder.CreateBitCast(Value, DestLTy);
1304}
1305
1306bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1307 llvm::Value *Fn = getBadCastFn(CGF);
1308 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1309 CGF.Builder.CreateUnreachable();
1310 return true;
1311}
1312
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001313llvm::Value *
1314ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001315 Address This,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001316 const CXXRecordDecl *ClassDecl,
1317 const CXXRecordDecl *BaseClassDecl) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001318 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy, ClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001319 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001320 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1321 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001322
1323 llvm::Value *VBaseOffsetPtr =
1324 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1325 "vbase.offset.ptr");
1326 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1327 CGM.PtrDiffTy->getPointerTo());
1328
1329 llvm::Value *VBaseOffset =
John McCall7f416cc2015-09-08 08:05:57 +00001330 CGF.Builder.CreateAlignedLoad(VBaseOffsetPtr, CGF.getPointerAlign(),
1331 "vbase.offset");
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001332
1333 return VBaseOffset;
1334}
1335
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001336void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1337 // Just make sure we're in sync with TargetCXXABI.
1338 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1339
Rafael Espindolac3cde362013-12-09 14:51:17 +00001340 // The constructor used for constructing this as a base class;
1341 // ignores virtual bases.
1342 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1343
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001344 // The constructor used for constructing this as a complete class;
Nico Weber4c2ffb22015-01-07 05:25:05 +00001345 // constructs the virtual bases, then calls the base constructor.
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001346 if (!D->getParent()->isAbstract()) {
1347 // We don't need to emit the complete ctor if the class is abstract.
1348 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1349 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001350}
1351
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001352void
1353ItaniumCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
1354 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +00001355 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001356
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001357 // All parameters are already in place except VTT, which goes after 'this'.
1358 // These are Clang types, so we don't need to worry about sret yet.
John McCall5d865c322010-08-31 07:33:07 +00001359
1360 // Check if we need to add a VTT parameter (which has type void **).
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001361 if (T == StructorType::Base && MD->getParent()->getNumVBases() != 0)
1362 ArgTys.insert(ArgTys.begin() + 1,
1363 Context.getPointerType(Context.VoidPtrTy));
John McCall5d865c322010-08-31 07:33:07 +00001364}
1365
Reid Klecknere7de47e2013-07-22 13:51:44 +00001366void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
Rafael Espindolac3cde362013-12-09 14:51:17 +00001367 // The destructor used for destructing this as a base class; ignores
1368 // virtual bases.
1369 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001370
1371 // The destructor used for destructing this as a most-derived class;
1372 // call the base destructor and then destructs any virtual bases.
1373 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1374
Rafael Espindolac3cde362013-12-09 14:51:17 +00001375 // The destructor in a virtual table is always a 'deleting'
1376 // destructor, which calls the complete destructor and then uses the
1377 // appropriate operator delete.
1378 if (D->isVirtual())
1379 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001380}
1381
Reid Kleckner89077a12013-12-17 19:46:40 +00001382void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1383 QualType &ResTy,
1384 FunctionArgList &Params) {
John McCall5d865c322010-08-31 07:33:07 +00001385 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +00001386 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
John McCall5d865c322010-08-31 07:33:07 +00001387
1388 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001389 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +00001390 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001391
1392 // FIXME: avoid the fake decl
1393 QualType T = Context.getPointerType(Context.VoidPtrTy);
1394 ImplicitParamDecl *VTTDecl
Craig Topper8a13c412014-05-21 05:09:00 +00001395 = ImplicitParamDecl::Create(Context, nullptr, MD->getLocation(),
John McCall5d865c322010-08-31 07:33:07 +00001396 &Context.Idents.get("vtt"), T);
Reid Kleckner89077a12013-12-17 19:46:40 +00001397 Params.insert(Params.begin() + 1, VTTDecl);
Reid Kleckner2af6d732013-12-13 00:09:59 +00001398 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +00001399 }
1400}
1401
John McCall5d865c322010-08-31 07:33:07 +00001402void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
Justin Lebared4f1722016-07-27 22:04:24 +00001403 // Naked functions have no prolog.
1404 if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>())
1405 return;
1406
John McCall5d865c322010-08-31 07:33:07 +00001407 /// Initialize the 'this' slot.
1408 EmitThisParam(CGF);
1409
1410 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +00001411 if (getStructorImplicitParamDecl(CGF)) {
1412 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1413 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +00001414 }
John McCall5d865c322010-08-31 07:33:07 +00001415
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001416 /// If this is a function that the ABI specifies returns 'this', initialize
1417 /// the return slot to 'this' at the start of the function.
1418 ///
1419 /// Unlike the setting of return types, this is done within the ABI
1420 /// implementation instead of by clients of CGCXXABI because:
1421 /// 1) getThisValue is currently protected
1422 /// 2) in theory, an ABI could implement 'this' returns some other way;
1423 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +00001424 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +00001425 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +00001426}
1427
Reid Kleckner89077a12013-12-17 19:46:40 +00001428unsigned ItaniumCXXABI::addImplicitConstructorArgs(
1429 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1430 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1431 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
1432 return 0;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001433
Reid Kleckner89077a12013-12-17 19:46:40 +00001434 // Insert the implicit 'vtt' argument as the second argument.
1435 llvm::Value *VTT =
1436 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1437 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1438 Args.insert(Args.begin() + 1,
1439 CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false));
1440 return 1; // Added one arg.
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001441}
1442
1443void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1444 const CXXDestructorDecl *DD,
1445 CXXDtorType Type, bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +00001446 bool Delegating, Address This) {
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001447 GlobalDecl GD(DD, Type);
1448 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1449 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1450
Craig Topper8a13c412014-05-21 05:09:00 +00001451 llvm::Value *Callee = nullptr;
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001452 if (getContext().getLangOpts().AppleKext)
1453 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
1454
1455 if (!Callee)
Rafael Espindola1ac0ec82014-09-11 15:42:06 +00001456 Callee = CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type));
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001457
John McCall7f416cc2015-09-08 08:05:57 +00001458 CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(),
1459 This.getPointer(), VTT, VTTTy, nullptr);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001460}
1461
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001462void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1463 const CXXRecordDecl *RD) {
1464 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1465 if (VTable->hasInitializer())
1466 return;
1467
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001468 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001469 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1470 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
David Majnemerd905da42014-07-01 20:30:31 +00001471 llvm::Constant *RTTI =
1472 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001473
1474 // Create and set the initializer.
Peter Collingbournee53683f2016-09-08 01:14:39 +00001475 llvm::Constant *Init = CGVT.CreateVTableInitializer(VTLayout, RTTI);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001476 VTable->setInitializer(Init);
1477
1478 // Set the correct linkage.
1479 VTable->setLinkage(Linkage);
1480
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001481 if (CGM.supportsCOMDAT() && VTable->isWeakForLinker())
1482 VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName()));
Rafael Espindolacb92c192015-01-15 23:18:01 +00001483
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001484 // Set the right visibility.
John McCall8f80a612014-02-08 00:41:16 +00001485 CGM.setGlobalVisibility(VTable, RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001486
Benjamin Kramer5d34a2b2014-09-10 12:50:59 +00001487 // Use pointer alignment for the vtable. Otherwise we would align them based
1488 // on the size of the initializer which doesn't make sense as only single
1489 // values are read.
1490 unsigned PAlign = CGM.getTarget().getPointerAlign(0);
1491 VTable->setAlignment(getContext().toCharUnitsFromBits(PAlign).getQuantity());
1492
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001493 // If this is the magic class __cxxabiv1::__fundamental_type_info,
1494 // we will emit the typeinfo for the fundamental types. This is the
1495 // same behaviour as GCC.
1496 const DeclContext *DC = RD->getDeclContext();
1497 if (RD->getIdentifier() &&
1498 RD->getIdentifier()->isStr("__fundamental_type_info") &&
1499 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1500 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1501 DC->getParent()->isTranslationUnit())
David Majnemere2cb8d12014-07-07 06:20:47 +00001502 EmitFundamentalRTTIDescriptors();
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001503
Evgeniy Stepanov93987df2016-01-23 01:20:18 +00001504 if (!VTable->isDeclarationForLinker())
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001505 CGM.EmitVTableTypeMetadata(VTable, VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001506}
1507
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001508bool ItaniumCXXABI::isVirtualOffsetNeededForVTableField(
1509 CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
1510 if (Vptr.NearestVBase == nullptr)
1511 return false;
1512 return NeedsVTTParameter(CGF.CurGD);
Piotr Padlewski255652e2015-09-09 22:20:28 +00001513}
1514
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001515llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1516 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1517 const CXXRecordDecl *NearestVBase) {
1518
1519 if ((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1520 NeedsVTTParameter(CGF.CurGD)) {
1521 return getVTableAddressPointInStructorWithVTT(CGF, VTableClass, Base,
1522 NearestVBase);
1523 }
1524 return getVTableAddressPoint(Base, VTableClass);
1525}
1526
1527llvm::Constant *
1528ItaniumCXXABI::getVTableAddressPoint(BaseSubobject Base,
1529 const CXXRecordDecl *VTableClass) {
1530 llvm::GlobalValue *VTable = getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001531
1532 // Find the appropriate vtable within the vtable group.
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001533 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1534 .getVTableLayout(VTableClass)
1535 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001536 llvm::Value *Indices[] = {
Peter Collingbourne4e6a5402016-03-14 19:07:10 +00001537 llvm::ConstantInt::get(CGM.Int32Ty, 0),
1538 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint)
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001539 };
1540
David Blaikiee3b172a2015-04-02 18:55:21 +00001541 return llvm::ConstantExpr::getInBoundsGetElementPtr(VTable->getValueType(),
1542 VTable, Indices);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001543}
1544
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001545llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructorWithVTT(
1546 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1547 const CXXRecordDecl *NearestVBase) {
1548 assert((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1549 NeedsVTTParameter(CGF.CurGD) && "This class doesn't have VTT");
1550
1551 // Get the secondary vpointer index.
1552 uint64_t VirtualPointerIndex =
1553 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1554
1555 /// Load the VTT.
1556 llvm::Value *VTT = CGF.LoadCXXVTT();
1557 if (VirtualPointerIndex)
1558 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1559
1560 // And load the address point from the VTT.
1561 return CGF.Builder.CreateAlignedLoad(VTT, CGF.getPointerAlign());
1562}
1563
1564llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1565 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1566 return getVTableAddressPoint(Base, VTableClass);
1567}
1568
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001569llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1570 CharUnits VPtrOffset) {
1571 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1572
1573 llvm::GlobalVariable *&VTable = VTables[RD];
1574 if (VTable)
1575 return VTable;
1576
Eric Christopherd160c502016-01-29 01:35:53 +00001577 // Queue up this vtable for possible deferred emission.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001578 CGM.addDeferredVTable(RD);
1579
Yaron Kerene46f7ed2015-07-29 14:21:47 +00001580 SmallString<256> Name;
1581 llvm::raw_svector_ostream Out(Name);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001582 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001583
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001584 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001585 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
Peter Collingbournee53683f2016-09-08 01:14:39 +00001586 CGM.Int8PtrTy, VTContext.getVTableLayout(RD).vtable_components().size());
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001587
1588 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
1589 Name, ArrayType, llvm::GlobalValue::ExternalLinkage);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001590 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Hans Wennborgda24e9c2014-06-02 23:13:03 +00001591
1592 if (RD->hasAttr<DLLImportAttr>())
1593 VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1594 else if (RD->hasAttr<DLLExportAttr>())
1595 VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1596
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001597 return VTable;
1598}
1599
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001600llvm::Value *ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1601 GlobalDecl GD,
John McCall7f416cc2015-09-08 08:05:57 +00001602 Address This,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001603 llvm::Type *Ty,
1604 SourceLocation Loc) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001605 GD = GD.getCanonicalDecl();
1606 Ty = Ty->getPointerTo()->getPointerTo();
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001607 auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
1608 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty, MethodDecl->getParent());
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001609
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001610 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001611 if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) {
1612 return CGF.EmitVTableTypeCheckedLoad(
1613 MethodDecl->getParent(), VTable,
1614 VTableIndex * CGM.getContext().getTargetInfo().getPointerWidth(0) / 8);
1615 } else {
1616 CGF.EmitTypeMetadataCodeForVCall(MethodDecl->getParent(), VTable, Loc);
1617
1618 llvm::Value *VFuncPtr =
1619 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1620 return CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign());
1621 }
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001622}
1623
David Majnemer0c0b6d92014-10-31 20:09:12 +00001624llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
1625 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
John McCall7f416cc2015-09-08 08:05:57 +00001626 Address This, const CXXMemberCallExpr *CE) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001627 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001628 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1629
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001630 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1631 Dtor, getFromDtorType(DtorType));
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001632 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001633 llvm::Value *Callee =
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001634 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty,
1635 CE ? CE->getLocStart() : SourceLocation());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001636
John McCall7f416cc2015-09-08 08:05:57 +00001637 CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(),
1638 This.getPointer(), /*ImplicitParam=*/nullptr,
1639 QualType(), CE);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001640 return nullptr;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001641}
1642
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001643void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001644 CodeGenVTables &VTables = CGM.getVTables();
1645 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001646 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001647}
1648
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001649bool ItaniumCXXABI::canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const {
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001650 // We don't emit available_externally vtables if we are in -fapple-kext mode
1651 // because kext mode does not permit devirtualization.
1652 if (CGM.getLangOpts().AppleKext)
1653 return false;
1654
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001655 // If we don't have any inline virtual functions, and if vtable is not hidden,
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001656 // then we are safe to emit available_externally copy of vtable.
1657 // FIXME we can still emit a copy of the vtable if we
1658 // can emit definition of the inline functions.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001659 return !hasAnyUsedVirtualInlineFunction(RD) && !isVTableHidden(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001660}
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001661static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001662 Address InitialPtr,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001663 int64_t NonVirtualAdjustment,
1664 int64_t VirtualAdjustment,
1665 bool IsReturnAdjustment) {
1666 if (!NonVirtualAdjustment && !VirtualAdjustment)
John McCall7f416cc2015-09-08 08:05:57 +00001667 return InitialPtr.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001668
John McCall7f416cc2015-09-08 08:05:57 +00001669 Address V = CGF.Builder.CreateElementBitCast(InitialPtr, CGF.Int8Ty);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001670
John McCall7f416cc2015-09-08 08:05:57 +00001671 // In a base-to-derived cast, the non-virtual adjustment is applied first.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001672 if (NonVirtualAdjustment && !IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001673 V = CGF.Builder.CreateConstInBoundsByteGEP(V,
1674 CharUnits::fromQuantity(NonVirtualAdjustment));
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001675 }
1676
John McCall7f416cc2015-09-08 08:05:57 +00001677 // Perform the virtual adjustment if we have one.
1678 llvm::Value *ResultPtr;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001679 if (VirtualAdjustment) {
1680 llvm::Type *PtrDiffTy =
1681 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1682
John McCall7f416cc2015-09-08 08:05:57 +00001683 Address VTablePtrPtr = CGF.Builder.CreateElementBitCast(V, CGF.Int8PtrTy);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001684 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1685
1686 llvm::Value *OffsetPtr =
1687 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1688
1689 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1690
1691 // Load the adjustment offset from the vtable.
John McCall7f416cc2015-09-08 08:05:57 +00001692 llvm::Value *Offset =
1693 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001694
1695 // Adjust our pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001696 ResultPtr = CGF.Builder.CreateInBoundsGEP(V.getPointer(), Offset);
1697 } else {
1698 ResultPtr = V.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001699 }
1700
John McCall7f416cc2015-09-08 08:05:57 +00001701 // In a derived-to-base conversion, the non-virtual adjustment is
1702 // applied second.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001703 if (NonVirtualAdjustment && IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001704 ResultPtr = CGF.Builder.CreateConstInBoundsGEP1_64(ResultPtr,
1705 NonVirtualAdjustment);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001706 }
1707
1708 // Cast back to the original type.
John McCall7f416cc2015-09-08 08:05:57 +00001709 return CGF.Builder.CreateBitCast(ResultPtr, InitialPtr.getType());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001710}
1711
1712llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001713 Address This,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001714 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001715 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1716 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001717 /*IsReturnAdjustment=*/false);
1718}
1719
1720llvm::Value *
John McCall7f416cc2015-09-08 08:05:57 +00001721ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001722 const ReturnAdjustment &RA) {
1723 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1724 RA.Virtual.Itanium.VBaseOffsetOffset,
1725 /*IsReturnAdjustment=*/true);
1726}
1727
John McCall5d865c322010-08-31 07:33:07 +00001728void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1729 RValue RV, QualType ResultType) {
1730 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1731 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1732
1733 // Destructor thunks in the ARM ABI have indeterminate results.
John McCall7f416cc2015-09-08 08:05:57 +00001734 llvm::Type *T = CGF.ReturnValue.getElementType();
John McCall5d865c322010-08-31 07:33:07 +00001735 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1736 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1737}
John McCall8ed55a52010-09-02 09:58:18 +00001738
1739/************************** Array allocation cookies **************************/
1740
John McCallb91cd662012-05-01 05:23:51 +00001741CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1742 // The array cookie is a size_t; pad that up to the element alignment.
1743 // The cookie is actually right-justified in that space.
1744 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1745 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001746}
1747
John McCall7f416cc2015-09-08 08:05:57 +00001748Address ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1749 Address NewPtr,
1750 llvm::Value *NumElements,
1751 const CXXNewExpr *expr,
1752 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001753 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001754
John McCall7f416cc2015-09-08 08:05:57 +00001755 unsigned AS = NewPtr.getAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001756
John McCall9bca9232010-09-02 10:25:57 +00001757 ASTContext &Ctx = getContext();
John McCall7f416cc2015-09-08 08:05:57 +00001758 CharUnits SizeSize = CGF.getSizeSize();
John McCall8ed55a52010-09-02 09:58:18 +00001759
1760 // The size of the cookie.
1761 CharUnits CookieSize =
1762 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001763 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001764
1765 // Compute an offset to the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001766 Address CookiePtr = NewPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001767 CharUnits CookieOffset = CookieSize - SizeSize;
1768 if (!CookieOffset.isZero())
John McCall7f416cc2015-09-08 08:05:57 +00001769 CookiePtr = CGF.Builder.CreateConstInBoundsByteGEP(CookiePtr, CookieOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001770
1771 // Write the number of elements into the appropriate slot.
John McCall7f416cc2015-09-08 08:05:57 +00001772 Address NumElementsPtr =
1773 CGF.Builder.CreateElementBitCast(CookiePtr, CGF.SizeTy);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001774 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
John McCall7f416cc2015-09-08 08:05:57 +00001775
1776 // Handle the array cookie specially in ASan.
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001777 if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 &&
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001778 expr->getOperatorNew()->isReplaceableGlobalAllocationFunction()) {
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001779 // The store to the CookiePtr does not need to be instrumented.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001780 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
1781 llvm::FunctionType *FTy =
John McCall7f416cc2015-09-08 08:05:57 +00001782 llvm::FunctionType::get(CGM.VoidTy, NumElementsPtr.getType(), false);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001783 llvm::Constant *F =
1784 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001785 CGF.Builder.CreateCall(F, NumElementsPtr.getPointer());
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001786 }
John McCall8ed55a52010-09-02 09:58:18 +00001787
1788 // Finally, compute a pointer to the actual data buffer by skipping
1789 // over the cookie completely.
John McCall7f416cc2015-09-08 08:05:57 +00001790 return CGF.Builder.CreateConstInBoundsByteGEP(NewPtr, CookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001791}
1792
John McCallb91cd662012-05-01 05:23:51 +00001793llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001794 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00001795 CharUnits cookieSize) {
1796 // The element size is right-justified in the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001797 Address numElementsPtr = allocPtr;
1798 CharUnits numElementsOffset = cookieSize - CGF.getSizeSize();
John McCallb91cd662012-05-01 05:23:51 +00001799 if (!numElementsOffset.isZero())
1800 numElementsPtr =
John McCall7f416cc2015-09-08 08:05:57 +00001801 CGF.Builder.CreateConstInBoundsByteGEP(numElementsPtr, numElementsOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001802
John McCall7f416cc2015-09-08 08:05:57 +00001803 unsigned AS = allocPtr.getAddressSpace();
1804 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001805 if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0)
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001806 return CGF.Builder.CreateLoad(numElementsPtr);
1807 // In asan mode emit a function call instead of a regular load and let the
1808 // run-time deal with it: if the shadow is properly poisoned return the
1809 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
1810 // We can't simply ignore this load using nosanitize metadata because
1811 // the metadata may be lost.
1812 llvm::FunctionType *FTy =
1813 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
1814 llvm::Constant *F =
1815 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001816 return CGF.Builder.CreateCall(F, numElementsPtr.getPointer());
John McCall8ed55a52010-09-02 09:58:18 +00001817}
1818
John McCallb91cd662012-05-01 05:23:51 +00001819CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001820 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001821 // struct array_cookie {
1822 // std::size_t element_size; // element_size != 0
1823 // std::size_t element_count;
1824 // };
John McCallc19c7062013-01-25 23:36:19 +00001825 // But the base ABI doesn't give anything an alignment greater than
1826 // 8, so we can dismiss this as typical ABI-author blindness to
1827 // actual language complexity and round up to the element alignment.
1828 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1829 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001830}
1831
John McCall7f416cc2015-09-08 08:05:57 +00001832Address ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1833 Address newPtr,
1834 llvm::Value *numElements,
1835 const CXXNewExpr *expr,
1836 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001837 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001838
John McCall8ed55a52010-09-02 09:58:18 +00001839 // The cookie is always at the start of the buffer.
John McCall7f416cc2015-09-08 08:05:57 +00001840 Address cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001841
1842 // The first element is the element size.
John McCall7f416cc2015-09-08 08:05:57 +00001843 cookie = CGF.Builder.CreateElementBitCast(cookie, CGF.SizeTy);
John McCallc19c7062013-01-25 23:36:19 +00001844 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1845 getContext().getTypeSizeInChars(elementType).getQuantity());
1846 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001847
1848 // The second element is the element count.
John McCall7f416cc2015-09-08 08:05:57 +00001849 cookie = CGF.Builder.CreateConstInBoundsGEP(cookie, 1, CGF.getSizeSize());
John McCallc19c7062013-01-25 23:36:19 +00001850 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001851
1852 // Finally, compute a pointer to the actual data buffer by skipping
1853 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001854 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
John McCall7f416cc2015-09-08 08:05:57 +00001855 return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001856}
1857
John McCallb91cd662012-05-01 05:23:51 +00001858llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001859 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00001860 CharUnits cookieSize) {
1861 // The number of elements is at offset sizeof(size_t) relative to
1862 // the allocated pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001863 Address numElementsPtr
1864 = CGF.Builder.CreateConstInBoundsByteGEP(allocPtr, CGF.getSizeSize());
John McCall8ed55a52010-09-02 09:58:18 +00001865
John McCall7f416cc2015-09-08 08:05:57 +00001866 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
John McCallb91cd662012-05-01 05:23:51 +00001867 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001868}
1869
John McCall68ff0372010-09-08 01:44:27 +00001870/*********************** Static local initialization **************************/
1871
1872static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001873 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001874 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001875 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001876 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001877 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001878 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001879 llvm::AttributeSet::get(CGM.getLLVMContext(),
1880 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001881 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001882}
1883
1884static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001885 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001886 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001887 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001888 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001889 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001890 llvm::AttributeSet::get(CGM.getLLVMContext(),
1891 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001892 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001893}
1894
1895static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001896 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001897 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001898 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001899 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001900 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001901 llvm::AttributeSet::get(CGM.getLLVMContext(),
1902 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001903 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001904}
1905
1906namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001907 struct CallGuardAbort final : EHScopeStack::Cleanup {
John McCall68ff0372010-09-08 01:44:27 +00001908 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001909 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001910
Craig Topper4f12f102014-03-12 06:41:41 +00001911 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00001912 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1913 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001914 }
1915 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001916}
John McCall68ff0372010-09-08 01:44:27 +00001917
1918/// The ARM code here follows the Itanium code closely enough that we
1919/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001920void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1921 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001922 llvm::GlobalVariable *var,
1923 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00001924 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00001925
Richard Smith62f19e72016-06-25 00:15:56 +00001926 // Inline variables that weren't instantiated from variable templates have
1927 // partially-ordered initialization within their translation unit.
1928 bool NonTemplateInline =
1929 D.isInline() &&
1930 !isTemplateInstantiation(D.getTemplateSpecializationKind());
1931
1932 // We only need to use thread-safe statics for local non-TLS variables and
1933 // inline variables; other global initialization is always single-threaded
1934 // or (through lazy dynamic loading in multiple threads) unsequenced.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001935 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
Richard Smith62f19e72016-06-25 00:15:56 +00001936 (D.isLocalVarDecl() || NonTemplateInline) &&
1937 !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001938
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001939 // If we have a global variable with internal linkage and thread-safe statics
1940 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00001941 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1942
1943 llvm::IntegerType *guardTy;
John McCall7f416cc2015-09-08 08:05:57 +00001944 CharUnits guardAlignment;
John McCall5aa52592011-06-17 07:33:57 +00001945 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00001946 guardTy = CGF.Int8Ty;
John McCall7f416cc2015-09-08 08:05:57 +00001947 guardAlignment = CharUnits::One();
John McCall5aa52592011-06-17 07:33:57 +00001948 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00001949 // Guard variables are 64 bits in the generic ABI and size width on ARM
1950 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
John McCall7f416cc2015-09-08 08:05:57 +00001951 if (UseARMGuardVarABI) {
1952 guardTy = CGF.SizeTy;
1953 guardAlignment = CGF.getSizeAlign();
1954 } else {
1955 guardTy = CGF.Int64Ty;
1956 guardAlignment = CharUnits::fromQuantity(
1957 CGM.getDataLayout().getABITypeAlignment(guardTy));
1958 }
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001959 }
John McCallb88a5662012-03-30 21:00:39 +00001960 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00001961
John McCallb88a5662012-03-30 21:00:39 +00001962 // Create the guard variable if we don't already have it (as we
1963 // might if we're double-emitting this function body).
1964 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1965 if (!guard) {
1966 // Mangle the name for the guard.
1967 SmallString<256> guardName;
1968 {
1969 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00001970 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00001971 }
John McCall8e7cb6d2010-11-02 21:04:24 +00001972
John McCallb88a5662012-03-30 21:00:39 +00001973 // Create the guard variable with a zero-initializer.
1974 // Just absorb linkage and visibility from the guarded variable.
1975 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1976 false, var->getLinkage(),
1977 llvm::ConstantInt::get(guardTy, 0),
1978 guardName.str());
1979 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00001980 // If the variable is thread-local, so is its guard variable.
1981 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCall7f416cc2015-09-08 08:05:57 +00001982 guard->setAlignment(guardAlignment.getQuantity());
John McCallb88a5662012-03-30 21:00:39 +00001983
Yaron Keren5bfa1082015-09-03 20:33:29 +00001984 // The ABI says: "It is suggested that it be emitted in the same COMDAT
1985 // group as the associated data object." In practice, this doesn't work for
1986 // non-ELF object formats, so only do it for ELF.
Rafael Espindola0d4fb982015-01-12 22:13:53 +00001987 llvm::Comdat *C = var->getComdat();
Yaron Keren5bfa1082015-09-03 20:33:29 +00001988 if (!D.isLocalVarDecl() && C &&
1989 CGM.getTarget().getTriple().isOSBinFormatELF()) {
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001990 guard->setComdat(C);
Richard Smith62f19e72016-06-25 00:15:56 +00001991 // An inline variable's guard function is run from the per-TU
1992 // initialization function, not via a dedicated global ctor function, so
1993 // we can't put it in a comdat.
1994 if (!NonTemplateInline)
1995 CGF.CurFn->setComdat(C);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001996 } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) {
1997 guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName()));
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001998 }
1999
John McCallb88a5662012-03-30 21:00:39 +00002000 CGM.setStaticLocalDeclGuardAddress(&D, guard);
2001 }
John McCall87590e62012-03-30 07:09:50 +00002002
John McCall7f416cc2015-09-08 08:05:57 +00002003 Address guardAddr = Address(guard, guardAlignment);
2004
John McCall68ff0372010-09-08 01:44:27 +00002005 // Test whether the variable has completed initialization.
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002006 //
John McCall68ff0372010-09-08 01:44:27 +00002007 // Itanium C++ ABI 3.3.2:
2008 // The following is pseudo-code showing how these functions can be used:
2009 // if (obj_guard.first_byte == 0) {
2010 // if ( __cxa_guard_acquire (&obj_guard) ) {
2011 // try {
2012 // ... initialize the object ...;
2013 // } catch (...) {
2014 // __cxa_guard_abort (&obj_guard);
2015 // throw;
2016 // }
2017 // ... queue object destructor with __cxa_atexit() ...;
2018 // __cxa_guard_release (&obj_guard);
2019 // }
2020 // }
Tim Northovera2ee4332014-03-29 15:09:45 +00002021
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002022 // Load the first byte of the guard variable.
2023 llvm::LoadInst *LI =
John McCall7f416cc2015-09-08 08:05:57 +00002024 Builder.CreateLoad(Builder.CreateElementBitCast(guardAddr, CGM.Int8Ty));
John McCall68ff0372010-09-08 01:44:27 +00002025
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002026 // Itanium ABI:
2027 // An implementation supporting thread-safety on multiprocessor
2028 // systems must also guarantee that references to the initialized
2029 // object do not occur before the load of the initialization flag.
2030 //
2031 // In LLVM, we do this by marking the load Acquire.
2032 if (threadsafe)
JF Bastien92f4ef12016-04-06 17:26:42 +00002033 LI->setAtomic(llvm::AtomicOrdering::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00002034
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002035 // For ARM, we should only check the first bit, rather than the entire byte:
2036 //
2037 // ARM C++ ABI 3.2.3.1:
2038 // To support the potential use of initialization guard variables
2039 // as semaphores that are the target of ARM SWP and LDREX/STREX
2040 // synchronizing instructions we define a static initialization
2041 // guard variable to be a 4-byte aligned, 4-byte word with the
2042 // following inline access protocol.
2043 // #define INITIALIZED 1
2044 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
2045 // if (__cxa_guard_acquire(&obj_guard))
2046 // ...
2047 // }
2048 //
2049 // and similarly for ARM64:
2050 //
2051 // ARM64 C++ ABI 3.2.2:
2052 // This ABI instead only specifies the value bit 0 of the static guard
2053 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
2054 // variable is not initialized and 1 when it is.
2055 llvm::Value *V =
2056 (UseARMGuardVarABI && !useInt8GuardVariable)
2057 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
2058 : LI;
2059 llvm::Value *isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00002060
2061 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
2062 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2063
2064 // Check if the first byte of the guard variable is zero.
John McCallb88a5662012-03-30 21:00:39 +00002065 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall68ff0372010-09-08 01:44:27 +00002066
2067 CGF.EmitBlock(InitCheckBlock);
2068
2069 // Variables used when coping with thread-safe statics and exceptions.
John McCall5aa52592011-06-17 07:33:57 +00002070 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002071 // Call __cxa_guard_acquire.
2072 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00002073 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00002074
2075 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2076
2077 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
2078 InitBlock, EndBlock);
2079
2080 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00002081 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall68ff0372010-09-08 01:44:27 +00002082
2083 CGF.EmitBlock(InitBlock);
2084 }
2085
2086 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00002087 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00002088
John McCall5aa52592011-06-17 07:33:57 +00002089 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002090 // Pop the guard-abort cleanup if we pushed one.
2091 CGF.PopCleanupBlock();
2092
2093 // Call __cxa_guard_release. This cannot throw.
John McCall7f416cc2015-09-08 08:05:57 +00002094 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy),
2095 guardAddr.getPointer());
John McCall68ff0372010-09-08 01:44:27 +00002096 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002097 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guardAddr);
John McCall68ff0372010-09-08 01:44:27 +00002098 }
2099
2100 CGF.EmitBlock(EndBlock);
2101}
John McCallc84ed6a2012-05-01 06:13:13 +00002102
2103/// Register a global destructor using __cxa_atexit.
2104static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
2105 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00002106 llvm::Constant *addr,
2107 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00002108 const char *Name = "__cxa_atexit";
2109 if (TLS) {
2110 const llvm::Triple &T = CGF.getTarget().getTriple();
Manman Renf93fff22015-11-11 23:08:18 +00002111 Name = T.isOSDarwin() ? "_tlv_atexit" : "__cxa_thread_atexit";
Bill Wendling95cae882013-05-02 19:18:03 +00002112 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00002113
John McCallc84ed6a2012-05-01 06:13:13 +00002114 // We're assuming that the destructor function is something we can
2115 // reasonably call with the default CC. Go ahead and cast it to the
2116 // right prototype.
2117 llvm::Type *dtorTy =
2118 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
2119
2120 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
2121 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
2122 llvm::FunctionType *atexitTy =
2123 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
2124
2125 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002126 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00002127 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
2128 fn->setDoesNotThrow();
2129
2130 // Create a variable that binds the atexit to this shared object.
2131 llvm::Constant *handle =
2132 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
2133
2134 llvm::Value *args[] = {
2135 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
2136 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
2137 handle
2138 };
John McCall882987f2013-02-28 19:01:20 +00002139 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00002140}
2141
2142/// Register a global destructor as best as we know how.
2143void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00002144 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00002145 llvm::Constant *dtor,
2146 llvm::Constant *addr) {
2147 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002148 if (CGM.getCodeGenOpts().CXAAtExit)
2149 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
2150
2151 if (D.getTLSKind())
2152 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00002153
2154 // In Apple kexts, we want to add a global destructor entry.
2155 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00002156 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00002157 // Generate a global destructor entry.
2158 return CGM.AddCXXDtorEntry(dtor, addr);
2159 }
2160
David Blaikieebe87e12013-08-27 23:57:18 +00002161 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00002162}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002163
David Majnemer9b21c332014-07-11 20:28:10 +00002164static bool isThreadWrapperReplaceable(const VarDecl *VD,
2165 CodeGen::CodeGenModule &CGM) {
2166 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
Manman Renf93fff22015-11-11 23:08:18 +00002167 // Darwin prefers to have references to thread local variables to go through
David Majnemer9b21c332014-07-11 20:28:10 +00002168 // the thread wrapper instead of directly referencing the backing variable.
2169 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
Manman Renf93fff22015-11-11 23:08:18 +00002170 CGM.getTarget().getTriple().isOSDarwin();
David Majnemer9b21c332014-07-11 20:28:10 +00002171}
2172
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002173/// Get the appropriate linkage for the wrapper function. This is essentially
David Majnemer4632e1e2014-06-27 16:56:27 +00002174/// the weak form of the variable's linkage; every translation unit which needs
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002175/// the wrapper emits a copy, and we want the linker to merge them.
David Majnemer35ab3282014-06-11 04:08:55 +00002176static llvm::GlobalValue::LinkageTypes
2177getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
2178 llvm::GlobalValue::LinkageTypes VarLinkage =
2179 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
2180
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002181 // For internal linkage variables, we don't need an external or weak wrapper.
2182 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
2183 return VarLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00002184
David Majnemer9b21c332014-07-11 20:28:10 +00002185 // If the thread wrapper is replaceable, give it appropriate linkage.
Manman Ren68150262015-11-11 22:42:31 +00002186 if (isThreadWrapperReplaceable(VD, CGM))
2187 if (!llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) &&
2188 !llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
2189 return VarLinkage;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002190 return llvm::GlobalValue::WeakODRLinkage;
2191}
2192
2193llvm::Function *
2194ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +00002195 llvm::Value *Val) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002196 // Mangle the name for the thread_local wrapper function.
2197 SmallString<256> WrapperName;
2198 {
2199 llvm::raw_svector_ostream Out(WrapperName);
2200 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002201 }
2202
Akira Hatanaka26907f92016-01-15 03:34:06 +00002203 // FIXME: If VD is a definition, we should regenerate the function attributes
2204 // before returning.
Alexander Musmanf94c3182014-09-26 06:28:25 +00002205 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002206 return cast<llvm::Function>(V);
2207
Akira Hatanaka26907f92016-01-15 03:34:06 +00002208 QualType RetQT = VD->getType();
2209 if (RetQT->isReferenceType())
2210 RetQT = RetQT.getNonReferenceType();
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002211
John McCallc56a8b32016-03-11 04:30:31 +00002212 const CGFunctionInfo &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2213 getContext().getPointerType(RetQT), FunctionArgList());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002214
2215 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FI);
David Majnemer35ab3282014-06-11 04:08:55 +00002216 llvm::Function *Wrapper =
2217 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
2218 WrapperName.str(), &CGM.getModule());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002219
2220 CGM.SetLLVMFunctionAttributes(nullptr, FI, Wrapper);
2221
2222 if (VD->hasDefinition())
2223 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Wrapper);
2224
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002225 // Always resolve references to the wrapper at link time.
Manman Ren68150262015-11-11 22:42:31 +00002226 if (!Wrapper->hasLocalLinkage() && !(isThreadWrapperReplaceable(VD, CGM) &&
2227 !llvm::GlobalVariable::isLinkOnceLinkage(Wrapper->getLinkage()) &&
2228 !llvm::GlobalVariable::isWeakODRLinkage(Wrapper->getLinkage())))
Duncan P. N. Exon Smith4434d362014-05-07 22:36:11 +00002229 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
Manman Renb0b3af72015-12-17 00:42:36 +00002230
2231 if (isThreadWrapperReplaceable(VD, CGM)) {
2232 Wrapper->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2233 Wrapper->addFnAttr(llvm::Attribute::NoUnwind);
2234 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002235 return Wrapper;
2236}
2237
2238void ItaniumCXXABI::EmitThreadLocalInitFuncs(
Richard Smith5a99c492015-12-01 01:10:48 +00002239 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
2240 ArrayRef<llvm::Function *> CXXThreadLocalInits,
2241 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
David Majnemerb3341ea2014-10-05 05:05:40 +00002242 llvm::Function *InitFunc = nullptr;
2243 if (!CXXThreadLocalInits.empty()) {
2244 // Generate a guarded initialization function.
2245 llvm::FunctionType *FTy =
2246 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002247 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2248 InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init", FI,
Alexey Samsonov1444bb92014-10-17 00:20:19 +00002249 SourceLocation(),
David Majnemerb3341ea2014-10-05 05:05:40 +00002250 /*TLS=*/true);
2251 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
2252 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
2253 llvm::GlobalVariable::InternalLinkage,
2254 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
2255 Guard->setThreadLocal(true);
John McCall7f416cc2015-09-08 08:05:57 +00002256
2257 CharUnits GuardAlign = CharUnits::One();
2258 Guard->setAlignment(GuardAlign.getQuantity());
2259
David Majnemerb3341ea2014-10-05 05:05:40 +00002260 CodeGenFunction(CGM)
John McCall7f416cc2015-09-08 08:05:57 +00002261 .GenerateCXXGlobalInitFunc(InitFunc, CXXThreadLocalInits,
2262 Address(Guard, GuardAlign));
Manman Ren5e5d0462016-03-18 23:35:21 +00002263 // On Darwin platforms, use CXX_FAST_TLS calling convention.
2264 if (CGM.getTarget().getTriple().isOSDarwin()) {
2265 InitFunc->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2266 InitFunc->addFnAttr(llvm::Attribute::NoUnwind);
2267 }
David Majnemerb3341ea2014-10-05 05:05:40 +00002268 }
Richard Smith5a99c492015-12-01 01:10:48 +00002269 for (const VarDecl *VD : CXXThreadLocals) {
2270 llvm::GlobalVariable *Var =
2271 cast<llvm::GlobalVariable>(CGM.GetGlobalValue(CGM.getMangledName(VD)));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002272
David Majnemer9b21c332014-07-11 20:28:10 +00002273 // Some targets require that all access to thread local variables go through
2274 // the thread wrapper. This means that we cannot attempt to create a thread
2275 // wrapper or a thread helper.
2276 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition())
2277 continue;
2278
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002279 // Mangle the name for the thread_local initialization function.
2280 SmallString<256> InitFnName;
2281 {
2282 llvm::raw_svector_ostream Out(InitFnName);
2283 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002284 }
2285
2286 // If we have a definition for the variable, emit the initialization
2287 // function as an alias to the global Init function (if any). Otherwise,
2288 // produce a declaration of the initialization function.
Craig Topper8a13c412014-05-21 05:09:00 +00002289 llvm::GlobalValue *Init = nullptr;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002290 bool InitIsInitFunc = false;
2291 if (VD->hasDefinition()) {
2292 InitIsInitFunc = true;
2293 if (InitFunc)
Rafael Espindola234405b2014-05-17 21:30:14 +00002294 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
2295 InitFunc);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002296 } else {
2297 // Emit a weak global function referring to the initialization function.
2298 // This function will not exist if the TU defining the thread_local
2299 // variable in question does not need any dynamic initialization for
2300 // its thread_local variables.
2301 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
2302 Init = llvm::Function::Create(
2303 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
2304 &CGM.getModule());
John McCallc56a8b32016-03-11 04:30:31 +00002305 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
Akira Hatanaka26907f92016-01-15 03:34:06 +00002306 CGM.SetLLVMFunctionAttributes(nullptr, FI, cast<llvm::Function>(Init));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002307 }
2308
2309 if (Init)
2310 Init->setVisibility(Var->getVisibility());
2311
2312 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
2313 llvm::LLVMContext &Context = CGM.getModule().getContext();
2314 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
John McCall7f416cc2015-09-08 08:05:57 +00002315 CGBuilderTy Builder(CGM, Entry);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002316 if (InitIsInitFunc) {
Manman Ren5e5d0462016-03-18 23:35:21 +00002317 if (Init) {
2318 llvm::CallInst *CallVal = Builder.CreateCall(Init);
2319 if (isThreadWrapperReplaceable(VD, CGM))
2320 CallVal->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2321 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002322 } else {
2323 // Don't know whether we have an init function. Call it if it exists.
2324 llvm::Value *Have = Builder.CreateIsNotNull(Init);
2325 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2326 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2327 Builder.CreateCondBr(Have, InitBB, ExitBB);
2328
2329 Builder.SetInsertPoint(InitBB);
David Blaikie4ba525b2015-07-14 17:27:39 +00002330 Builder.CreateCall(Init);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002331 Builder.CreateBr(ExitBB);
2332
2333 Builder.SetInsertPoint(ExitBB);
2334 }
2335
2336 // For a reference, the result of the wrapper function is a pointer to
2337 // the referenced object.
2338 llvm::Value *Val = Var;
2339 if (VD->getType()->isReferenceType()) {
John McCall7f416cc2015-09-08 08:05:57 +00002340 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2341 Val = Builder.CreateAlignedLoad(Val, Align);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002342 }
Alexander Musmanf94c3182014-09-26 06:28:25 +00002343 if (Val->getType() != Wrapper->getReturnType())
2344 Val = Builder.CreatePointerBitCastOrAddrSpaceCast(
2345 Val, Wrapper->getReturnType(), "");
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002346 Builder.CreateRet(Val);
2347 }
2348}
2349
Richard Smith0f383742014-03-26 22:48:22 +00002350LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2351 const VarDecl *VD,
2352 QualType LValType) {
Richard Smith5a99c492015-12-01 01:10:48 +00002353 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD);
Alexander Musmanf94c3182014-09-26 06:28:25 +00002354 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002355
Manman Renb0b3af72015-12-17 00:42:36 +00002356 llvm::CallInst *CallVal = CGF.Builder.CreateCall(Wrapper);
Saleem Abdulrasool4a7130a2016-08-01 21:31:24 +00002357 CallVal->setCallingConv(Wrapper->getCallingConv());
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002358
2359 LValue LV;
2360 if (VD->getType()->isReferenceType())
Manman Renb0b3af72015-12-17 00:42:36 +00002361 LV = CGF.MakeNaturalAlignAddrLValue(CallVal, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002362 else
Manman Renb0b3af72015-12-17 00:42:36 +00002363 LV = CGF.MakeAddrLValue(CallVal, LValType,
2364 CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002365 // FIXME: need setObjCGCLValueClass?
2366 return LV;
2367}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002368
2369/// Return whether the given global decl needs a VTT parameter, which it does
2370/// if it's a base constructor or destructor with virtual bases.
2371bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
2372 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
2373
2374 // We don't have any virtual bases, just return early.
2375 if (!MD->getParent()->getNumVBases())
2376 return false;
2377
2378 // Check if we have a base constructor.
2379 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
2380 return true;
2381
2382 // Check if we have a base destructor.
2383 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2384 return true;
2385
2386 return false;
2387}
David Majnemere2cb8d12014-07-07 06:20:47 +00002388
2389namespace {
2390class ItaniumRTTIBuilder {
2391 CodeGenModule &CGM; // Per-module state.
2392 llvm::LLVMContext &VMContext;
2393 const ItaniumCXXABI &CXXABI; // Per-module state.
2394
2395 /// Fields - The fields of the RTTI descriptor currently being built.
2396 SmallVector<llvm::Constant *, 16> Fields;
2397
2398 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2399 llvm::GlobalVariable *
2400 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2401
2402 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2403 /// descriptor of the given type.
2404 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2405
2406 /// BuildVTablePointer - Build the vtable pointer for the given type.
2407 void BuildVTablePointer(const Type *Ty);
2408
2409 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2410 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2411 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2412
2413 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2414 /// classes with bases that do not satisfy the abi::__si_class_type_info
2415 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2416 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2417
2418 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2419 /// for pointer types.
2420 void BuildPointerTypeInfo(QualType PointeeTy);
2421
2422 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2423 /// type_info for an object type.
2424 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2425
2426 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2427 /// struct, used for member pointer types.
2428 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2429
2430public:
2431 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2432 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2433
2434 // Pointer type info flags.
2435 enum {
2436 /// PTI_Const - Type has const qualifier.
2437 PTI_Const = 0x1,
2438
2439 /// PTI_Volatile - Type has volatile qualifier.
2440 PTI_Volatile = 0x2,
2441
2442 /// PTI_Restrict - Type has restrict qualifier.
2443 PTI_Restrict = 0x4,
2444
2445 /// PTI_Incomplete - Type is incomplete.
2446 PTI_Incomplete = 0x8,
2447
2448 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2449 /// (in pointer to member).
2450 PTI_ContainingClassIncomplete = 0x10
2451 };
2452
2453 // VMI type info flags.
2454 enum {
2455 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2456 VMI_NonDiamondRepeat = 0x1,
2457
2458 /// VMI_DiamondShaped - Class is diamond shaped.
2459 VMI_DiamondShaped = 0x2
2460 };
2461
2462 // Base class type info flags.
2463 enum {
2464 /// BCTI_Virtual - Base class is virtual.
2465 BCTI_Virtual = 0x1,
2466
2467 /// BCTI_Public - Base class is public.
2468 BCTI_Public = 0x2
2469 };
2470
2471 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
2472 ///
2473 /// \param Force - true to force the creation of this RTTI value
2474 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false);
2475};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002476}
David Majnemere2cb8d12014-07-07 06:20:47 +00002477
2478llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2479 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002480 SmallString<256> Name;
2481 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002482 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002483
2484 // We know that the mangled name of the type starts at index 4 of the
2485 // mangled name of the typename, so we can just index into it in order to
2486 // get the mangled name of the type.
2487 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2488 Name.substr(4));
2489
2490 llvm::GlobalVariable *GV =
2491 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
2492
2493 GV->setInitializer(Init);
2494
2495 return GV;
2496}
2497
2498llvm::Constant *
2499ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2500 // Mangle the RTTI name.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002501 SmallString<256> Name;
2502 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002503 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002504
2505 // Look for an existing global.
2506 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2507
2508 if (!GV) {
2509 // Create a new global variable.
2510 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2511 /*Constant=*/true,
2512 llvm::GlobalValue::ExternalLinkage, nullptr,
2513 Name);
David Majnemer1fb1a042014-11-07 07:26:38 +00002514 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2515 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2516 if (RD->hasAttr<DLLImportAttr>())
2517 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2518 }
David Majnemere2cb8d12014-07-07 06:20:47 +00002519 }
2520
2521 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2522}
2523
2524/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2525/// info for that type is defined in the standard library.
2526static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2527 // Itanium C++ ABI 2.9.2:
2528 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
2529 // the run-time support library. Specifically, the run-time support
2530 // library should contain type_info objects for the types X, X* and
2531 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2532 // unsigned char, signed char, short, unsigned short, int, unsigned int,
2533 // long, unsigned long, long long, unsigned long long, float, double,
2534 // long double, char16_t, char32_t, and the IEEE 754r decimal and
2535 // half-precision floating point types.
Richard Smith4a382012016-02-03 01:32:42 +00002536 //
2537 // GCC also emits RTTI for __int128.
2538 // FIXME: We do not emit RTTI information for decimal types here.
2539
2540 // Types added here must also be added to EmitFundamentalRTTIDescriptors.
David Majnemere2cb8d12014-07-07 06:20:47 +00002541 switch (Ty->getKind()) {
2542 case BuiltinType::Void:
2543 case BuiltinType::NullPtr:
2544 case BuiltinType::Bool:
2545 case BuiltinType::WChar_S:
2546 case BuiltinType::WChar_U:
2547 case BuiltinType::Char_U:
2548 case BuiltinType::Char_S:
2549 case BuiltinType::UChar:
2550 case BuiltinType::SChar:
2551 case BuiltinType::Short:
2552 case BuiltinType::UShort:
2553 case BuiltinType::Int:
2554 case BuiltinType::UInt:
2555 case BuiltinType::Long:
2556 case BuiltinType::ULong:
2557 case BuiltinType::LongLong:
2558 case BuiltinType::ULongLong:
2559 case BuiltinType::Half:
2560 case BuiltinType::Float:
2561 case BuiltinType::Double:
2562 case BuiltinType::LongDouble:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002563 case BuiltinType::Float128:
David Majnemere2cb8d12014-07-07 06:20:47 +00002564 case BuiltinType::Char16:
2565 case BuiltinType::Char32:
2566 case BuiltinType::Int128:
2567 case BuiltinType::UInt128:
Richard Smith4a382012016-02-03 01:32:42 +00002568 return true;
2569
Alexey Bader954ba212016-04-08 13:40:33 +00002570#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2571 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00002572#include "clang/Basic/OpenCLImageTypes.def"
David Majnemere2cb8d12014-07-07 06:20:47 +00002573 case BuiltinType::OCLSampler:
2574 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002575 case BuiltinType::OCLClkEvent:
2576 case BuiltinType::OCLQueue:
2577 case BuiltinType::OCLNDRange:
2578 case BuiltinType::OCLReserveID:
Richard Smith4a382012016-02-03 01:32:42 +00002579 return false;
David Majnemere2cb8d12014-07-07 06:20:47 +00002580
2581 case BuiltinType::Dependent:
2582#define BUILTIN_TYPE(Id, SingletonId)
2583#define PLACEHOLDER_TYPE(Id, SingletonId) \
2584 case BuiltinType::Id:
2585#include "clang/AST/BuiltinTypes.def"
2586 llvm_unreachable("asking for RRTI for a placeholder type!");
2587
2588 case BuiltinType::ObjCId:
2589 case BuiltinType::ObjCClass:
2590 case BuiltinType::ObjCSel:
2591 llvm_unreachable("FIXME: Objective-C types are unsupported!");
2592 }
2593
2594 llvm_unreachable("Invalid BuiltinType Kind!");
2595}
2596
2597static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2598 QualType PointeeTy = PointerTy->getPointeeType();
2599 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2600 if (!BuiltinTy)
2601 return false;
2602
2603 // Check the qualifiers.
2604 Qualifiers Quals = PointeeTy.getQualifiers();
2605 Quals.removeConst();
2606
2607 if (!Quals.empty())
2608 return false;
2609
2610 return TypeInfoIsInStandardLibrary(BuiltinTy);
2611}
2612
2613/// IsStandardLibraryRTTIDescriptor - Returns whether the type
2614/// information for the given type exists in the standard library.
2615static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2616 // Type info for builtin types is defined in the standard library.
2617 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2618 return TypeInfoIsInStandardLibrary(BuiltinTy);
2619
2620 // Type info for some pointer types to builtin types is defined in the
2621 // standard library.
2622 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2623 return TypeInfoIsInStandardLibrary(PointerTy);
2624
2625 return false;
2626}
2627
2628/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
2629/// the given type exists somewhere else, and that we should not emit the type
2630/// information in this translation unit. Assumes that it is not a
2631/// standard-library type.
2632static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
2633 QualType Ty) {
2634 ASTContext &Context = CGM.getContext();
2635
2636 // If RTTI is disabled, assume it might be disabled in the
2637 // translation unit that defines any potential key function, too.
2638 if (!Context.getLangOpts().RTTI) return false;
2639
2640 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2641 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2642 if (!RD->hasDefinition())
2643 return false;
2644
2645 if (!RD->isDynamicClass())
2646 return false;
2647
2648 // FIXME: this may need to be reconsidered if the key function
2649 // changes.
David Majnemerbe9022c2015-08-06 20:56:55 +00002650 // N.B. We must always emit the RTTI data ourselves if there exists a key
2651 // function.
2652 bool IsDLLImport = RD->hasAttr<DLLImportAttr>();
David Majnemer1fb1a042014-11-07 07:26:38 +00002653 if (CGM.getVTables().isVTableExternal(RD))
David Majnemerbe9022c2015-08-06 20:56:55 +00002654 return IsDLLImport ? false : true;
David Majnemer1fb1a042014-11-07 07:26:38 +00002655
David Majnemerbe9022c2015-08-06 20:56:55 +00002656 if (IsDLLImport)
David Majnemer1fb1a042014-11-07 07:26:38 +00002657 return true;
David Majnemere2cb8d12014-07-07 06:20:47 +00002658 }
2659
2660 return false;
2661}
2662
2663/// IsIncompleteClassType - Returns whether the given record type is incomplete.
2664static bool IsIncompleteClassType(const RecordType *RecordTy) {
2665 return !RecordTy->getDecl()->isCompleteDefinition();
2666}
2667
2668/// ContainsIncompleteClassType - Returns whether the given type contains an
2669/// incomplete class type. This is true if
2670///
2671/// * The given type is an incomplete class type.
2672/// * The given type is a pointer type whose pointee type contains an
2673/// incomplete class type.
2674/// * The given type is a member pointer type whose class is an incomplete
2675/// class type.
2676/// * The given type is a member pointer type whoise pointee type contains an
2677/// incomplete class type.
2678/// is an indirect or direct pointer to an incomplete class type.
2679static bool ContainsIncompleteClassType(QualType Ty) {
2680 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2681 if (IsIncompleteClassType(RecordTy))
2682 return true;
2683 }
2684
2685 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2686 return ContainsIncompleteClassType(PointerTy->getPointeeType());
2687
2688 if (const MemberPointerType *MemberPointerTy =
2689 dyn_cast<MemberPointerType>(Ty)) {
2690 // Check if the class type is incomplete.
2691 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
2692 if (IsIncompleteClassType(ClassType))
2693 return true;
2694
2695 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
2696 }
2697
2698 return false;
2699}
2700
2701// CanUseSingleInheritance - Return whether the given record decl has a "single,
2702// public, non-virtual base at offset zero (i.e. the derived class is dynamic
2703// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
2704static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
2705 // Check the number of bases.
2706 if (RD->getNumBases() != 1)
2707 return false;
2708
2709 // Get the base.
2710 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
2711
2712 // Check that the base is not virtual.
2713 if (Base->isVirtual())
2714 return false;
2715
2716 // Check that the base is public.
2717 if (Base->getAccessSpecifier() != AS_public)
2718 return false;
2719
2720 // Check that the class is dynamic iff the base is.
2721 const CXXRecordDecl *BaseDecl =
2722 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2723 if (!BaseDecl->isEmpty() &&
2724 BaseDecl->isDynamicClass() != RD->isDynamicClass())
2725 return false;
2726
2727 return true;
2728}
2729
2730void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
2731 // abi::__class_type_info.
2732 static const char * const ClassTypeInfo =
2733 "_ZTVN10__cxxabiv117__class_type_infoE";
2734 // abi::__si_class_type_info.
2735 static const char * const SIClassTypeInfo =
2736 "_ZTVN10__cxxabiv120__si_class_type_infoE";
2737 // abi::__vmi_class_type_info.
2738 static const char * const VMIClassTypeInfo =
2739 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
2740
2741 const char *VTableName = nullptr;
2742
2743 switch (Ty->getTypeClass()) {
2744#define TYPE(Class, Base)
2745#define ABSTRACT_TYPE(Class, Base)
2746#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2747#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2748#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2749#include "clang/AST/TypeNodes.def"
2750 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2751
2752 case Type::LValueReference:
2753 case Type::RValueReference:
2754 llvm_unreachable("References shouldn't get here");
2755
2756 case Type::Auto:
2757 llvm_unreachable("Undeduced auto type shouldn't get here");
2758
Xiuli Pan9c14e282016-01-09 12:53:17 +00002759 case Type::Pipe:
2760 llvm_unreachable("Pipe types shouldn't get here");
2761
David Majnemere2cb8d12014-07-07 06:20:47 +00002762 case Type::Builtin:
2763 // GCC treats vector and complex types as fundamental types.
2764 case Type::Vector:
2765 case Type::ExtVector:
2766 case Type::Complex:
2767 case Type::Atomic:
2768 // FIXME: GCC treats block pointers as fundamental types?!
2769 case Type::BlockPointer:
2770 // abi::__fundamental_type_info.
2771 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
2772 break;
2773
2774 case Type::ConstantArray:
2775 case Type::IncompleteArray:
2776 case Type::VariableArray:
2777 // abi::__array_type_info.
2778 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
2779 break;
2780
2781 case Type::FunctionNoProto:
2782 case Type::FunctionProto:
2783 // abi::__function_type_info.
2784 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
2785 break;
2786
2787 case Type::Enum:
2788 // abi::__enum_type_info.
2789 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
2790 break;
2791
2792 case Type::Record: {
2793 const CXXRecordDecl *RD =
2794 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2795
2796 if (!RD->hasDefinition() || !RD->getNumBases()) {
2797 VTableName = ClassTypeInfo;
2798 } else if (CanUseSingleInheritance(RD)) {
2799 VTableName = SIClassTypeInfo;
2800 } else {
2801 VTableName = VMIClassTypeInfo;
2802 }
2803
2804 break;
2805 }
2806
2807 case Type::ObjCObject:
2808 // Ignore protocol qualifiers.
2809 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
2810
2811 // Handle id and Class.
2812 if (isa<BuiltinType>(Ty)) {
2813 VTableName = ClassTypeInfo;
2814 break;
2815 }
2816
2817 assert(isa<ObjCInterfaceType>(Ty));
2818 // Fall through.
2819
2820 case Type::ObjCInterface:
2821 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
2822 VTableName = SIClassTypeInfo;
2823 } else {
2824 VTableName = ClassTypeInfo;
2825 }
2826 break;
2827
2828 case Type::ObjCObjectPointer:
2829 case Type::Pointer:
2830 // abi::__pointer_type_info.
2831 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
2832 break;
2833
2834 case Type::MemberPointer:
2835 // abi::__pointer_to_member_type_info.
2836 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
2837 break;
2838 }
2839
2840 llvm::Constant *VTable =
2841 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
2842
2843 llvm::Type *PtrDiffTy =
2844 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
2845
2846 // The vtable address point is 2.
2847 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00002848 VTable =
2849 llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.Int8PtrTy, VTable, Two);
David Majnemere2cb8d12014-07-07 06:20:47 +00002850 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
2851
2852 Fields.push_back(VTable);
2853}
2854
2855/// \brief Return the linkage that the type info and type info name constants
2856/// should have for the given type.
2857static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
2858 QualType Ty) {
2859 // Itanium C++ ABI 2.9.5p7:
2860 // In addition, it and all of the intermediate abi::__pointer_type_info
2861 // structs in the chain down to the abi::__class_type_info for the
2862 // incomplete class type must be prevented from resolving to the
2863 // corresponding type_info structs for the complete class type, possibly
2864 // by making them local static objects. Finally, a dummy class RTTI is
2865 // generated for the incomplete type that will not resolve to the final
2866 // complete class RTTI (because the latter need not exist), possibly by
2867 // making it a local static object.
2868 if (ContainsIncompleteClassType(Ty))
2869 return llvm::GlobalValue::InternalLinkage;
2870
2871 switch (Ty->getLinkage()) {
2872 case NoLinkage:
2873 case InternalLinkage:
2874 case UniqueExternalLinkage:
2875 return llvm::GlobalValue::InternalLinkage;
2876
2877 case VisibleNoLinkage:
2878 case ExternalLinkage:
2879 if (!CGM.getLangOpts().RTTI) {
2880 // RTTI is not enabled, which means that this type info struct is going
2881 // to be used for exception handling. Give it linkonce_odr linkage.
2882 return llvm::GlobalValue::LinkOnceODRLinkage;
2883 }
2884
2885 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
2886 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2887 if (RD->hasAttr<WeakAttr>())
2888 return llvm::GlobalValue::WeakODRLinkage;
David Majnemerbe9022c2015-08-06 20:56:55 +00002889 if (RD->isDynamicClass()) {
2890 llvm::GlobalValue::LinkageTypes LT = CGM.getVTableLinkage(RD);
2891 // MinGW won't export the RTTI information when there is a key function.
2892 // Make sure we emit our own copy instead of attempting to dllimport it.
2893 if (RD->hasAttr<DLLImportAttr>() &&
2894 llvm::GlobalValue::isAvailableExternallyLinkage(LT))
2895 LT = llvm::GlobalValue::LinkOnceODRLinkage;
2896 return LT;
2897 }
David Majnemere2cb8d12014-07-07 06:20:47 +00002898 }
2899
2900 return llvm::GlobalValue::LinkOnceODRLinkage;
2901 }
2902
2903 llvm_unreachable("Invalid linkage!");
2904}
2905
2906llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force) {
2907 // We want to operate on the canonical type.
Yaron Kerenebd14262016-03-16 12:14:43 +00002908 Ty = Ty.getCanonicalType();
David Majnemere2cb8d12014-07-07 06:20:47 +00002909
2910 // Check if we've already emitted an RTTI descriptor for this type.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002911 SmallString<256> Name;
2912 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002913 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002914
2915 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
2916 if (OldGV && !OldGV->isDeclaration()) {
2917 assert(!OldGV->hasAvailableExternallyLinkage() &&
2918 "available_externally typeinfos not yet implemented");
2919
2920 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
2921 }
2922
2923 // Check if there is already an external RTTI descriptor for this type.
2924 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
2925 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
2926 return GetAddrOfExternalRTTIDescriptor(Ty);
2927
2928 // Emit the standard library with external linkage.
2929 llvm::GlobalVariable::LinkageTypes Linkage;
2930 if (IsStdLib)
2931 Linkage = llvm::GlobalValue::ExternalLinkage;
2932 else
2933 Linkage = getTypeInfoLinkage(CGM, Ty);
2934
2935 // Add the vtable pointer.
2936 BuildVTablePointer(cast<Type>(Ty));
2937
2938 // And the name.
2939 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
2940 llvm::Constant *TypeNameField;
2941
2942 // If we're supposed to demote the visibility, be sure to set a flag
2943 // to use a string comparison for type_info comparisons.
2944 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
2945 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
2946 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
2947 // The flag is the sign bit, which on ARM64 is defined to be clear
2948 // for global pointers. This is very ARM64-specific.
2949 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
2950 llvm::Constant *flag =
2951 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
2952 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
2953 TypeNameField =
2954 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
2955 } else {
2956 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
2957 }
2958 Fields.push_back(TypeNameField);
2959
2960 switch (Ty->getTypeClass()) {
2961#define TYPE(Class, Base)
2962#define ABSTRACT_TYPE(Class, Base)
2963#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2964#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2965#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2966#include "clang/AST/TypeNodes.def"
2967 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2968
2969 // GCC treats vector types as fundamental types.
2970 case Type::Builtin:
2971 case Type::Vector:
2972 case Type::ExtVector:
2973 case Type::Complex:
2974 case Type::BlockPointer:
2975 // Itanium C++ ABI 2.9.5p4:
2976 // abi::__fundamental_type_info adds no data members to std::type_info.
2977 break;
2978
2979 case Type::LValueReference:
2980 case Type::RValueReference:
2981 llvm_unreachable("References shouldn't get here");
2982
2983 case Type::Auto:
2984 llvm_unreachable("Undeduced auto type shouldn't get here");
2985
Xiuli Pan9c14e282016-01-09 12:53:17 +00002986 case Type::Pipe:
2987 llvm_unreachable("Pipe type shouldn't get here");
2988
David Majnemere2cb8d12014-07-07 06:20:47 +00002989 case Type::ConstantArray:
2990 case Type::IncompleteArray:
2991 case Type::VariableArray:
2992 // Itanium C++ ABI 2.9.5p5:
2993 // abi::__array_type_info adds no data members to std::type_info.
2994 break;
2995
2996 case Type::FunctionNoProto:
2997 case Type::FunctionProto:
2998 // Itanium C++ ABI 2.9.5p5:
2999 // abi::__function_type_info adds no data members to std::type_info.
3000 break;
3001
3002 case Type::Enum:
3003 // Itanium C++ ABI 2.9.5p5:
3004 // abi::__enum_type_info adds no data members to std::type_info.
3005 break;
3006
3007 case Type::Record: {
3008 const CXXRecordDecl *RD =
3009 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
3010 if (!RD->hasDefinition() || !RD->getNumBases()) {
3011 // We don't need to emit any fields.
3012 break;
3013 }
3014
3015 if (CanUseSingleInheritance(RD))
3016 BuildSIClassTypeInfo(RD);
3017 else
3018 BuildVMIClassTypeInfo(RD);
3019
3020 break;
3021 }
3022
3023 case Type::ObjCObject:
3024 case Type::ObjCInterface:
3025 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
3026 break;
3027
3028 case Type::ObjCObjectPointer:
3029 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
3030 break;
3031
3032 case Type::Pointer:
3033 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
3034 break;
3035
3036 case Type::MemberPointer:
3037 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
3038 break;
3039
3040 case Type::Atomic:
3041 // No fields, at least for the moment.
3042 break;
3043 }
3044
3045 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
3046
Rafael Espindolacb92c192015-01-15 23:18:01 +00003047 llvm::Module &M = CGM.getModule();
David Majnemere2cb8d12014-07-07 06:20:47 +00003048 llvm::GlobalVariable *GV =
Rafael Espindolacb92c192015-01-15 23:18:01 +00003049 new llvm::GlobalVariable(M, Init->getType(),
3050 /*Constant=*/true, Linkage, Init, Name);
3051
David Majnemere2cb8d12014-07-07 06:20:47 +00003052 // If there's already an old global variable, replace it with the new one.
3053 if (OldGV) {
3054 GV->takeName(OldGV);
3055 llvm::Constant *NewPtr =
3056 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3057 OldGV->replaceAllUsesWith(NewPtr);
3058 OldGV->eraseFromParent();
3059 }
3060
Yaron Keren04da2382015-07-29 15:42:28 +00003061 if (CGM.supportsCOMDAT() && GV->isWeakForLinker())
3062 GV->setComdat(M.getOrInsertComdat(GV->getName()));
3063
David Majnemere2cb8d12014-07-07 06:20:47 +00003064 // The Itanium ABI specifies that type_info objects must be globally
3065 // unique, with one exception: if the type is an incomplete class
3066 // type or a (possibly indirect) pointer to one. That exception
3067 // affects the general case of comparing type_info objects produced
3068 // by the typeid operator, which is why the comparison operators on
3069 // std::type_info generally use the type_info name pointers instead
3070 // of the object addresses. However, the language's built-in uses
3071 // of RTTI generally require class types to be complete, even when
3072 // manipulating pointers to those class types. This allows the
3073 // implementation of dynamic_cast to rely on address equality tests,
3074 // which is much faster.
3075
3076 // All of this is to say that it's important that both the type_info
3077 // object and the type_info name be uniqued when weakly emitted.
3078
3079 // Give the type_info object and name the formal visibility of the
3080 // type itself.
3081 llvm::GlobalValue::VisibilityTypes llvmVisibility;
3082 if (llvm::GlobalValue::isLocalLinkage(Linkage))
3083 // If the linkage is local, only default visibility makes sense.
3084 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
3085 else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden)
3086 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
3087 else
3088 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
3089 TypeName->setVisibility(llvmVisibility);
3090 GV->setVisibility(llvmVisibility);
3091
3092 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
3093}
3094
3095/// ComputeQualifierFlags - Compute the pointer type info flags from the
3096/// given qualifier.
3097static unsigned ComputeQualifierFlags(Qualifiers Quals) {
3098 unsigned Flags = 0;
3099
3100 if (Quals.hasConst())
3101 Flags |= ItaniumRTTIBuilder::PTI_Const;
3102 if (Quals.hasVolatile())
3103 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
3104 if (Quals.hasRestrict())
3105 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
3106
3107 return Flags;
3108}
3109
3110/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
3111/// for the given Objective-C object type.
3112void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
3113 // Drop qualifiers.
3114 const Type *T = OT->getBaseType().getTypePtr();
3115 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
3116
3117 // The builtin types are abi::__class_type_infos and don't require
3118 // extra fields.
3119 if (isa<BuiltinType>(T)) return;
3120
3121 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
3122 ObjCInterfaceDecl *Super = Class->getSuperClass();
3123
3124 // Root classes are also __class_type_info.
3125 if (!Super) return;
3126
3127 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
3128
3129 // Everything else is single inheritance.
3130 llvm::Constant *BaseTypeInfo =
3131 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
3132 Fields.push_back(BaseTypeInfo);
3133}
3134
3135/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
3136/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
3137void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
3138 // Itanium C++ ABI 2.9.5p6b:
3139 // It adds to abi::__class_type_info a single member pointing to the
3140 // type_info structure for the base type,
3141 llvm::Constant *BaseTypeInfo =
3142 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
3143 Fields.push_back(BaseTypeInfo);
3144}
3145
3146namespace {
3147 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
3148 /// a class hierarchy.
3149 struct SeenBases {
3150 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
3151 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
3152 };
3153}
3154
3155/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
3156/// abi::__vmi_class_type_info.
3157///
3158static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
3159 SeenBases &Bases) {
3160
3161 unsigned Flags = 0;
3162
3163 const CXXRecordDecl *BaseDecl =
3164 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
3165
3166 if (Base->isVirtual()) {
3167 // Mark the virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003168 if (!Bases.VirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003169 // If this virtual base has been seen before, then the class is diamond
3170 // shaped.
3171 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
3172 } else {
3173 if (Bases.NonVirtualBases.count(BaseDecl))
3174 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3175 }
3176 } else {
3177 // Mark the non-virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003178 if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003179 // If this non-virtual base has been seen before, then the class has non-
3180 // diamond shaped repeated inheritance.
3181 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3182 } else {
3183 if (Bases.VirtualBases.count(BaseDecl))
3184 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3185 }
3186 }
3187
3188 // Walk all bases.
3189 for (const auto &I : BaseDecl->bases())
3190 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3191
3192 return Flags;
3193}
3194
3195static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
3196 unsigned Flags = 0;
3197 SeenBases Bases;
3198
3199 // Walk all bases.
3200 for (const auto &I : RD->bases())
3201 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3202
3203 return Flags;
3204}
3205
3206/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
3207/// classes with bases that do not satisfy the abi::__si_class_type_info
3208/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
3209void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
3210 llvm::Type *UnsignedIntLTy =
3211 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3212
3213 // Itanium C++ ABI 2.9.5p6c:
3214 // __flags is a word with flags describing details about the class
3215 // structure, which may be referenced by using the __flags_masks
3216 // enumeration. These flags refer to both direct and indirect bases.
3217 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
3218 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3219
3220 // Itanium C++ ABI 2.9.5p6c:
3221 // __base_count is a word with the number of direct proper base class
3222 // descriptions that follow.
3223 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
3224
3225 if (!RD->getNumBases())
3226 return;
3227
David Majnemere2cb8d12014-07-07 06:20:47 +00003228 // Now add the base class descriptions.
3229
3230 // Itanium C++ ABI 2.9.5p6c:
3231 // __base_info[] is an array of base class descriptions -- one for every
3232 // direct proper base. Each description is of the type:
3233 //
3234 // struct abi::__base_class_type_info {
3235 // public:
3236 // const __class_type_info *__base_type;
3237 // long __offset_flags;
3238 //
3239 // enum __offset_flags_masks {
3240 // __virtual_mask = 0x1,
3241 // __public_mask = 0x2,
3242 // __offset_shift = 8
3243 // };
3244 // };
Reid Klecknerd8b04662016-08-25 22:16:30 +00003245
3246 // If we're in mingw and 'long' isn't wide enough for a pointer, use 'long
3247 // long' instead of 'long' for __offset_flags. libstdc++abi uses long long on
3248 // LLP64 platforms.
3249 // FIXME: Consider updating libc++abi to match, and extend this logic to all
3250 // LLP64 platforms.
3251 QualType OffsetFlagsTy = CGM.getContext().LongTy;
3252 const TargetInfo &TI = CGM.getContext().getTargetInfo();
3253 if (TI.getTriple().isOSCygMing() && TI.getPointerWidth(0) > TI.getLongWidth())
3254 OffsetFlagsTy = CGM.getContext().LongLongTy;
3255 llvm::Type *OffsetFlagsLTy =
3256 CGM.getTypes().ConvertType(OffsetFlagsTy);
3257
David Majnemere2cb8d12014-07-07 06:20:47 +00003258 for (const auto &Base : RD->bases()) {
3259 // The __base_type member points to the RTTI for the base type.
3260 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
3261
3262 const CXXRecordDecl *BaseDecl =
3263 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
3264
3265 int64_t OffsetFlags = 0;
3266
3267 // All but the lower 8 bits of __offset_flags are a signed offset.
3268 // For a non-virtual base, this is the offset in the object of the base
3269 // subobject. For a virtual base, this is the offset in the virtual table of
3270 // the virtual base offset for the virtual base referenced (negative).
3271 CharUnits Offset;
3272 if (Base.isVirtual())
3273 Offset =
3274 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
3275 else {
3276 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
3277 Offset = Layout.getBaseClassOffset(BaseDecl);
3278 };
3279
3280 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
3281
3282 // The low-order byte of __offset_flags contains flags, as given by the
3283 // masks from the enumeration __offset_flags_masks.
3284 if (Base.isVirtual())
3285 OffsetFlags |= BCTI_Virtual;
3286 if (Base.getAccessSpecifier() == AS_public)
3287 OffsetFlags |= BCTI_Public;
3288
Reid Klecknerd8b04662016-08-25 22:16:30 +00003289 Fields.push_back(llvm::ConstantInt::get(OffsetFlagsLTy, OffsetFlags));
David Majnemere2cb8d12014-07-07 06:20:47 +00003290 }
3291}
3292
3293/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
3294/// used for pointer types.
3295void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
3296 Qualifiers Quals;
3297 QualType UnqualifiedPointeeTy =
3298 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
3299
3300 // Itanium C++ ABI 2.9.5p7:
3301 // __flags is a flag word describing the cv-qualification and other
3302 // attributes of the type pointed to
3303 unsigned Flags = ComputeQualifierFlags(Quals);
3304
3305 // Itanium C++ ABI 2.9.5p7:
3306 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3307 // incomplete class type, the incomplete target type flag is set.
3308 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
3309 Flags |= PTI_Incomplete;
3310
3311 llvm::Type *UnsignedIntLTy =
3312 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3313 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3314
3315 // Itanium C++ ABI 2.9.5p7:
3316 // __pointee is a pointer to the std::type_info derivation for the
3317 // unqualified type being pointed to.
3318 llvm::Constant *PointeeTypeInfo =
3319 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
3320 Fields.push_back(PointeeTypeInfo);
3321}
3322
3323/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
3324/// struct, used for member pointer types.
3325void
3326ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
3327 QualType PointeeTy = Ty->getPointeeType();
3328
3329 Qualifiers Quals;
3330 QualType UnqualifiedPointeeTy =
3331 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
3332
3333 // Itanium C++ ABI 2.9.5p7:
3334 // __flags is a flag word describing the cv-qualification and other
3335 // attributes of the type pointed to.
3336 unsigned Flags = ComputeQualifierFlags(Quals);
3337
3338 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
3339
3340 // Itanium C++ ABI 2.9.5p7:
3341 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3342 // incomplete class type, the incomplete target type flag is set.
3343 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
3344 Flags |= PTI_Incomplete;
3345
3346 if (IsIncompleteClassType(ClassType))
3347 Flags |= PTI_ContainingClassIncomplete;
3348
3349 llvm::Type *UnsignedIntLTy =
3350 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3351 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3352
3353 // Itanium C++ ABI 2.9.5p7:
3354 // __pointee is a pointer to the std::type_info derivation for the
3355 // unqualified type being pointed to.
3356 llvm::Constant *PointeeTypeInfo =
3357 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
3358 Fields.push_back(PointeeTypeInfo);
3359
3360 // Itanium C++ ABI 2.9.5p9:
3361 // __context is a pointer to an abi::__class_type_info corresponding to the
3362 // class type containing the member pointed to
3363 // (e.g., the "A" in "int A::*").
3364 Fields.push_back(
3365 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
3366}
3367
David Majnemer443250f2015-03-17 20:35:00 +00003368llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003369 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
3370}
3371
3372void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type) {
3373 QualType PointerType = getContext().getPointerType(Type);
3374 QualType PointerTypeConst = getContext().getPointerType(Type.withConst());
3375 ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, true);
3376 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, true);
3377 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, true);
3378}
3379
3380void ItaniumCXXABI::EmitFundamentalRTTIDescriptors() {
Richard Smith4a382012016-02-03 01:32:42 +00003381 // Types added here must also be added to TypeInfoIsInStandardLibrary.
David Majnemere2cb8d12014-07-07 06:20:47 +00003382 QualType FundamentalTypes[] = {
3383 getContext().VoidTy, getContext().NullPtrTy,
3384 getContext().BoolTy, getContext().WCharTy,
3385 getContext().CharTy, getContext().UnsignedCharTy,
3386 getContext().SignedCharTy, getContext().ShortTy,
3387 getContext().UnsignedShortTy, getContext().IntTy,
3388 getContext().UnsignedIntTy, getContext().LongTy,
3389 getContext().UnsignedLongTy, getContext().LongLongTy,
Richard Smith4a382012016-02-03 01:32:42 +00003390 getContext().UnsignedLongLongTy, getContext().Int128Ty,
3391 getContext().UnsignedInt128Ty, getContext().HalfTy,
David Majnemere2cb8d12014-07-07 06:20:47 +00003392 getContext().FloatTy, getContext().DoubleTy,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00003393 getContext().LongDoubleTy, getContext().Float128Ty,
3394 getContext().Char16Ty, getContext().Char32Ty
David Majnemere2cb8d12014-07-07 06:20:47 +00003395 };
3396 for (const QualType &FundamentalType : FundamentalTypes)
3397 EmitFundamentalRTTIDescriptor(FundamentalType);
3398}
3399
3400/// What sort of uniqueness rules should we use for the RTTI for the
3401/// given type?
3402ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
3403 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
3404 if (shouldRTTIBeUnique())
3405 return RUK_Unique;
3406
3407 // It's only necessary for linkonce_odr or weak_odr linkage.
3408 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
3409 Linkage != llvm::GlobalValue::WeakODRLinkage)
3410 return RUK_Unique;
3411
3412 // It's only necessary with default visibility.
3413 if (CanTy->getVisibility() != DefaultVisibility)
3414 return RUK_Unique;
3415
3416 // If we're not required to publish this symbol, hide it.
3417 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3418 return RUK_NonUniqueHidden;
3419
3420 // If we're required to publish this symbol, as we might be under an
3421 // explicit instantiation, leave it with default visibility but
3422 // enable string-comparisons.
3423 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
3424 return RUK_NonUniqueVisible;
3425}
Rafael Espindola91f68b42014-09-15 19:20:10 +00003426
Rafael Espindola1e4df922014-09-16 15:18:21 +00003427// Find out how to codegen the complete destructor and constructor
3428namespace {
3429enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
3430}
3431static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
3432 const CXXMethodDecl *MD) {
3433 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
3434 return StructorCodegen::Emit;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003435
Rafael Espindola1e4df922014-09-16 15:18:21 +00003436 // The complete and base structors are not equivalent if there are any virtual
3437 // bases, so emit separate functions.
3438 if (MD->getParent()->getNumVBases())
3439 return StructorCodegen::Emit;
3440
3441 GlobalDecl AliasDecl;
3442 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3443 AliasDecl = GlobalDecl(DD, Dtor_Complete);
3444 } else {
3445 const auto *CD = cast<CXXConstructorDecl>(MD);
3446 AliasDecl = GlobalDecl(CD, Ctor_Complete);
3447 }
3448 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3449
3450 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
3451 return StructorCodegen::RAUW;
3452
3453 // FIXME: Should we allow available_externally aliases?
3454 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
3455 return StructorCodegen::RAUW;
3456
Rafael Espindola0806f982014-09-16 20:19:43 +00003457 if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
3458 // Only ELF supports COMDATs with arbitrary names (C5/D5).
3459 if (CGM.getTarget().getTriple().isOSBinFormatELF())
3460 return StructorCodegen::COMDAT;
3461 return StructorCodegen::Emit;
3462 }
Rafael Espindola1e4df922014-09-16 15:18:21 +00003463
3464 return StructorCodegen::Alias;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003465}
3466
Rafael Espindola1e4df922014-09-16 15:18:21 +00003467static void emitConstructorDestructorAlias(CodeGenModule &CGM,
3468 GlobalDecl AliasDecl,
3469 GlobalDecl TargetDecl) {
3470 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3471
3472 StringRef MangledName = CGM.getMangledName(AliasDecl);
3473 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
3474 if (Entry && !Entry->isDeclaration())
3475 return;
3476
3477 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
Rafael Espindola1e4df922014-09-16 15:18:21 +00003478
3479 // Create the alias with no name.
David Blaikie2a791d72015-09-14 18:38:22 +00003480 auto *Alias = llvm::GlobalAlias::create(Linkage, "", Aliasee);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003481
3482 // Switch any previous uses to the alias.
3483 if (Entry) {
NAKAMURA Takumie9621042015-09-15 01:39:27 +00003484 assert(Entry->getType() == Aliasee->getType() &&
Rafael Espindola1e4df922014-09-16 15:18:21 +00003485 "declaration exists with different type");
3486 Alias->takeName(Entry);
3487 Entry->replaceAllUsesWith(Alias);
3488 Entry->eraseFromParent();
3489 } else {
3490 Alias->setName(MangledName);
3491 }
3492
3493 // Finally, set up the alias with its proper name and attributes.
Dario Domiziolic4fb8ca72014-09-19 22:06:24 +00003494 CGM.setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003495}
3496
3497void ItaniumCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
3498 StructorType Type) {
3499 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
3500 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
3501
3502 StructorCodegen CGType = getCodegenToUse(CGM, MD);
3503
3504 if (Type == StructorType::Complete) {
3505 GlobalDecl CompleteDecl;
3506 GlobalDecl BaseDecl;
3507 if (CD) {
3508 CompleteDecl = GlobalDecl(CD, Ctor_Complete);
3509 BaseDecl = GlobalDecl(CD, Ctor_Base);
3510 } else {
3511 CompleteDecl = GlobalDecl(DD, Dtor_Complete);
3512 BaseDecl = GlobalDecl(DD, Dtor_Base);
3513 }
3514
3515 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
3516 emitConstructorDestructorAlias(CGM, CompleteDecl, BaseDecl);
3517 return;
3518 }
3519
3520 if (CGType == StructorCodegen::RAUW) {
3521 StringRef MangledName = CGM.getMangledName(CompleteDecl);
Andrey Bokhankocab58582015-08-31 13:20:44 +00003522 auto *Aliasee = CGM.GetAddrOfGlobal(BaseDecl);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003523 CGM.addReplacement(MangledName, Aliasee);
3524 return;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003525 }
3526 }
3527
3528 // The base destructor is equivalent to the base destructor of its
3529 // base class if there is exactly one non-virtual base class with a
3530 // non-trivial destructor, there are no fields with a non-trivial
3531 // destructor, and the body of the destructor is trivial.
Rafael Espindola1e4df922014-09-16 15:18:21 +00003532 if (DD && Type == StructorType::Base && CGType != StructorCodegen::COMDAT &&
3533 !CGM.TryEmitBaseDestructorAsAlias(DD))
Rafael Espindola91f68b42014-09-15 19:20:10 +00003534 return;
3535
Rafael Espindola1e4df922014-09-16 15:18:21 +00003536 llvm::Function *Fn = CGM.codegenCXXStructor(MD, Type);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003537
Rafael Espindola1e4df922014-09-16 15:18:21 +00003538 if (CGType == StructorCodegen::COMDAT) {
3539 SmallString<256> Buffer;
3540 llvm::raw_svector_ostream Out(Buffer);
3541 if (DD)
3542 getMangleContext().mangleCXXDtorComdat(DD, Out);
3543 else
3544 getMangleContext().mangleCXXCtorComdat(CD, Out);
3545 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
3546 Fn->setComdat(C);
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003547 } else {
3548 CGM.maybeSetTrivialComdat(*MD, *Fn);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003549 }
Rafael Espindola91f68b42014-09-15 19:20:10 +00003550}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003551
3552static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) {
3553 // void *__cxa_begin_catch(void*);
3554 llvm::FunctionType *FTy = llvm::FunctionType::get(
3555 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3556
3557 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
3558}
3559
3560static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) {
3561 // void __cxa_end_catch();
3562 llvm::FunctionType *FTy =
3563 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
3564
3565 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
3566}
3567
3568static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) {
3569 // void *__cxa_get_exception_ptr(void*);
3570 llvm::FunctionType *FTy = llvm::FunctionType::get(
3571 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3572
3573 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
3574}
3575
3576namespace {
3577 /// A cleanup to call __cxa_end_catch. In many cases, the caught
3578 /// exception type lets us state definitively that the thrown exception
3579 /// type does not have a destructor. In particular:
3580 /// - Catch-alls tell us nothing, so we have to conservatively
3581 /// assume that the thrown exception might have a destructor.
3582 /// - Catches by reference behave according to their base types.
3583 /// - Catches of non-record types will only trigger for exceptions
3584 /// of non-record types, which never have destructors.
3585 /// - Catches of record types can trigger for arbitrary subclasses
3586 /// of the caught type, so we have to assume the actual thrown
3587 /// exception type might have a throwing destructor, even if the
3588 /// caught type's destructor is trivial or nothrow.
David Blaikie7e70d682015-08-18 22:40:54 +00003589 struct CallEndCatch final : EHScopeStack::Cleanup {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003590 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
3591 bool MightThrow;
3592
3593 void Emit(CodeGenFunction &CGF, Flags flags) override {
3594 if (!MightThrow) {
3595 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
3596 return;
3597 }
3598
3599 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
3600 }
3601 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003602}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003603
3604/// Emits a call to __cxa_begin_catch and enters a cleanup to call
3605/// __cxa_end_catch.
3606///
3607/// \param EndMightThrow - true if __cxa_end_catch might throw
3608static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
3609 llvm::Value *Exn,
3610 bool EndMightThrow) {
3611 llvm::CallInst *call =
3612 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
3613
3614 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
3615
3616 return call;
3617}
3618
3619/// A "special initializer" callback for initializing a catch
3620/// parameter during catch initialization.
3621static void InitCatchParam(CodeGenFunction &CGF,
3622 const VarDecl &CatchParam,
John McCall7f416cc2015-09-08 08:05:57 +00003623 Address ParamAddr,
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003624 SourceLocation Loc) {
3625 // Load the exception from where the landing pad saved it.
3626 llvm::Value *Exn = CGF.getExceptionFromSlot();
3627
3628 CanQualType CatchType =
3629 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
3630 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
3631
3632 // If we're catching by reference, we can just cast the object
3633 // pointer to the appropriate pointer.
3634 if (isa<ReferenceType>(CatchType)) {
3635 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
3636 bool EndCatchMightThrow = CaughtType->isRecordType();
3637
3638 // __cxa_begin_catch returns the adjusted object pointer.
3639 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
3640
3641 // We have no way to tell the personality function that we're
3642 // catching by reference, so if we're catching a pointer,
3643 // __cxa_begin_catch will actually return that pointer by value.
3644 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
3645 QualType PointeeType = PT->getPointeeType();
3646
3647 // When catching by reference, generally we should just ignore
3648 // this by-value pointer and use the exception object instead.
3649 if (!PointeeType->isRecordType()) {
3650
3651 // Exn points to the struct _Unwind_Exception header, which
3652 // we have to skip past in order to reach the exception data.
3653 unsigned HeaderSize =
3654 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
3655 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
3656
3657 // However, if we're catching a pointer-to-record type that won't
3658 // work, because the personality function might have adjusted
3659 // the pointer. There's actually no way for us to fully satisfy
3660 // the language/ABI contract here: we can't use Exn because it
3661 // might have the wrong adjustment, but we can't use the by-value
3662 // pointer because it's off by a level of abstraction.
3663 //
3664 // The current solution is to dump the adjusted pointer into an
3665 // alloca, which breaks language semantics (because changing the
3666 // pointer doesn't change the exception) but at least works.
3667 // The better solution would be to filter out non-exact matches
3668 // and rethrow them, but this is tricky because the rethrow
3669 // really needs to be catchable by other sites at this landing
3670 // pad. The best solution is to fix the personality function.
3671 } else {
3672 // Pull the pointer for the reference type off.
3673 llvm::Type *PtrTy =
3674 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
3675
3676 // Create the temporary and write the adjusted pointer into it.
John McCall7f416cc2015-09-08 08:05:57 +00003677 Address ExnPtrTmp =
3678 CGF.CreateTempAlloca(PtrTy, CGF.getPointerAlign(), "exn.byref.tmp");
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003679 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3680 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
3681
3682 // Bind the reference to the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00003683 AdjustedExn = ExnPtrTmp.getPointer();
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003684 }
3685 }
3686
3687 llvm::Value *ExnCast =
3688 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
3689 CGF.Builder.CreateStore(ExnCast, ParamAddr);
3690 return;
3691 }
3692
3693 // Scalars and complexes.
3694 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
3695 if (TEK != TEK_Aggregate) {
3696 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
3697
3698 // If the catch type is a pointer type, __cxa_begin_catch returns
3699 // the pointer by value.
3700 if (CatchType->hasPointerRepresentation()) {
3701 llvm::Value *CastExn =
3702 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
3703
3704 switch (CatchType.getQualifiers().getObjCLifetime()) {
3705 case Qualifiers::OCL_Strong:
3706 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
3707 // fallthrough
3708
3709 case Qualifiers::OCL_None:
3710 case Qualifiers::OCL_ExplicitNone:
3711 case Qualifiers::OCL_Autoreleasing:
3712 CGF.Builder.CreateStore(CastExn, ParamAddr);
3713 return;
3714
3715 case Qualifiers::OCL_Weak:
3716 CGF.EmitARCInitWeak(ParamAddr, CastExn);
3717 return;
3718 }
3719 llvm_unreachable("bad ownership qualifier!");
3720 }
3721
3722 // Otherwise, it returns a pointer into the exception object.
3723
3724 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3725 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3726
3727 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
John McCall7f416cc2015-09-08 08:05:57 +00003728 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003729 switch (TEK) {
3730 case TEK_Complex:
3731 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
3732 /*init*/ true);
3733 return;
3734 case TEK_Scalar: {
3735 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
3736 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
3737 return;
3738 }
3739 case TEK_Aggregate:
3740 llvm_unreachable("evaluation kind filtered out!");
3741 }
3742 llvm_unreachable("bad evaluation kind");
3743 }
3744
3745 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
John McCall7f416cc2015-09-08 08:05:57 +00003746 auto catchRD = CatchType->getAsCXXRecordDecl();
3747 CharUnits caughtExnAlignment = CGF.CGM.getClassPointerAlignment(catchRD);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003748
3749 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3750
3751 // Check for a copy expression. If we don't have a copy expression,
3752 // that means a trivial copy is okay.
3753 const Expr *copyExpr = CatchParam.getInit();
3754 if (!copyExpr) {
3755 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
John McCall7f416cc2015-09-08 08:05:57 +00003756 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3757 caughtExnAlignment);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003758 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
3759 return;
3760 }
3761
3762 // We have to call __cxa_get_exception_ptr to get the adjusted
3763 // pointer before copying.
3764 llvm::CallInst *rawAdjustedExn =
3765 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
3766
3767 // Cast that to the appropriate type.
John McCall7f416cc2015-09-08 08:05:57 +00003768 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3769 caughtExnAlignment);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003770
3771 // The copy expression is defined in terms of an OpaqueValueExpr.
3772 // Find it and map it to the adjusted expression.
3773 CodeGenFunction::OpaqueValueMapping
3774 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
3775 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
3776
3777 // Call the copy ctor in a terminate scope.
3778 CGF.EHStack.pushTerminate();
3779
3780 // Perform the copy construction.
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003781 CGF.EmitAggExpr(copyExpr,
John McCall7f416cc2015-09-08 08:05:57 +00003782 AggValueSlot::forAddr(ParamAddr, Qualifiers(),
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003783 AggValueSlot::IsNotDestructed,
3784 AggValueSlot::DoesNotNeedGCBarriers,
3785 AggValueSlot::IsNotAliased));
3786
3787 // Leave the terminate scope.
3788 CGF.EHStack.popTerminate();
3789
3790 // Undo the opaque value mapping.
3791 opaque.pop();
3792
3793 // Finally we can call __cxa_begin_catch.
3794 CallBeginCatch(CGF, Exn, true);
3795}
3796
3797/// Begins a catch statement by initializing the catch variable and
3798/// calling __cxa_begin_catch.
3799void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF,
3800 const CXXCatchStmt *S) {
3801 // We have to be very careful with the ordering of cleanups here:
3802 // C++ [except.throw]p4:
3803 // The destruction [of the exception temporary] occurs
3804 // immediately after the destruction of the object declared in
3805 // the exception-declaration in the handler.
3806 //
3807 // So the precise ordering is:
3808 // 1. Construct catch variable.
3809 // 2. __cxa_begin_catch
3810 // 3. Enter __cxa_end_catch cleanup
3811 // 4. Enter dtor cleanup
3812 //
3813 // We do this by using a slightly abnormal initialization process.
3814 // Delegation sequence:
3815 // - ExitCXXTryStmt opens a RunCleanupsScope
3816 // - EmitAutoVarAlloca creates the variable and debug info
3817 // - InitCatchParam initializes the variable from the exception
3818 // - CallBeginCatch calls __cxa_begin_catch
3819 // - CallBeginCatch enters the __cxa_end_catch cleanup
3820 // - EmitAutoVarCleanups enters the variable destructor cleanup
3821 // - EmitCXXTryStmt emits the code for the catch body
3822 // - EmitCXXTryStmt close the RunCleanupsScope
3823
3824 VarDecl *CatchParam = S->getExceptionDecl();
3825 if (!CatchParam) {
3826 llvm::Value *Exn = CGF.getExceptionFromSlot();
3827 CallBeginCatch(CGF, Exn, true);
3828 return;
3829 }
3830
3831 // Emit the local.
3832 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
3833 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
3834 CGF.EmitAutoVarCleanups(var);
3835}
3836
3837/// Get or define the following function:
3838/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
3839/// This code is used only in C++.
3840static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
3841 llvm::FunctionType *fnTy =
3842 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3843 llvm::Constant *fnRef =
3844 CGM.CreateRuntimeFunction(fnTy, "__clang_call_terminate");
3845
3846 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
3847 if (fn && fn->empty()) {
3848 fn->setDoesNotThrow();
3849 fn->setDoesNotReturn();
3850
3851 // What we really want is to massively penalize inlining without
3852 // forbidding it completely. The difference between that and
3853 // 'noinline' is negligible.
3854 fn->addFnAttr(llvm::Attribute::NoInline);
3855
3856 // Allow this function to be shared across translation units, but
3857 // we don't want it to turn into an exported symbol.
3858 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
3859 fn->setVisibility(llvm::Function::HiddenVisibility);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00003860 if (CGM.supportsCOMDAT())
3861 fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003862
3863 // Set up the function.
3864 llvm::BasicBlock *entry =
3865 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
John McCall7f416cc2015-09-08 08:05:57 +00003866 CGBuilderTy builder(CGM, entry);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003867
3868 // Pull the exception pointer out of the parameter list.
3869 llvm::Value *exn = &*fn->arg_begin();
3870
3871 // Call __cxa_begin_catch(exn).
3872 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
3873 catchCall->setDoesNotThrow();
3874 catchCall->setCallingConv(CGM.getRuntimeCC());
3875
3876 // Call std::terminate().
David Blaikie4ba525b2015-07-14 17:27:39 +00003877 llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn());
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003878 termCall->setDoesNotThrow();
3879 termCall->setDoesNotReturn();
3880 termCall->setCallingConv(CGM.getRuntimeCC());
3881
3882 // std::terminate cannot return.
3883 builder.CreateUnreachable();
3884 }
3885
3886 return fnRef;
3887}
3888
3889llvm::CallInst *
3890ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
3891 llvm::Value *Exn) {
3892 // In C++, we want to call __cxa_begin_catch() before terminating.
3893 if (Exn) {
3894 assert(CGF.CGM.getLangOpts().CPlusPlus);
3895 return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn);
3896 }
3897 return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
3898}