blob: 0c6a6d751c7b6eec3f9cf616efc2574e99920cc9 [file] [log] [blame]
Charles Davis4e786dd2010-05-25 19:52:27 +00001//===------- ItaniumCXXABI.cpp - Emit LLVM Code from ASTs for a Module ----===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattner57540c52011-04-15 05:22:18 +000010// This provides C++ code generation targeting the Itanium C++ ABI. The class
Charles Davis4e786dd2010-05-25 19:52:27 +000011// in this file generates structures that follow the Itanium C++ ABI, which is
12// documented at:
13// http://www.codesourcery.com/public/cxx-abi/abi.html
14// http://www.codesourcery.com/public/cxx-abi/abi-eh.html
John McCall86353412010-08-21 22:46:04 +000015//
16// It also supports the closely-related ARM ABI, documented at:
17// http://infocenter.arm.com/help/topic/com.arm.doc.ihi0041c/IHI0041C_cppabi.pdf
18//
Charles Davis4e786dd2010-05-25 19:52:27 +000019//===----------------------------------------------------------------------===//
20
21#include "CGCXXABI.h"
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000022#include "CGCleanup.h"
John McCall7a9aac22010-08-23 01:21:21 +000023#include "CGRecordLayout.h"
Charles Davisa325a6e2012-06-23 23:44:00 +000024#include "CGVTables.h"
John McCall475999d2010-08-22 00:05:51 +000025#include "CodeGenFunction.h"
Charles Davis4e786dd2010-05-25 19:52:27 +000026#include "CodeGenModule.h"
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000027#include "TargetInfo.h"
Craig Topperc9ee1d02012-09-15 18:47:51 +000028#include "clang/AST/Mangle.h"
29#include "clang/AST/Type.h"
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000030#include "clang/AST/StmtCXX.h"
David Majnemer1162d252014-06-22 19:05:33 +000031#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000032#include "llvm/IR/DataLayout.h"
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000033#include "llvm/IR/Instructions.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000034#include "llvm/IR/Intrinsics.h"
35#include "llvm/IR/Value.h"
Charles Davis4e786dd2010-05-25 19:52:27 +000036
37using namespace clang;
John McCall475999d2010-08-22 00:05:51 +000038using namespace CodeGen;
Charles Davis4e786dd2010-05-25 19:52:27 +000039
40namespace {
Charles Davis53c59df2010-08-16 03:33:14 +000041class ItaniumCXXABI : public CodeGen::CGCXXABI {
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +000042 /// VTables - All the vtables which have been defined.
43 llvm::DenseMap<const CXXRecordDecl *, llvm::GlobalVariable *> VTables;
44
John McCall475999d2010-08-22 00:05:51 +000045protected:
Mark Seabornedf0d382013-07-24 16:25:13 +000046 bool UseARMMethodPtrABI;
47 bool UseARMGuardVarABI;
John McCall7a9aac22010-08-23 01:21:21 +000048
Timur Iskhodzhanov67455222013-10-03 06:26:13 +000049 ItaniumMangleContext &getMangleContext() {
50 return cast<ItaniumMangleContext>(CodeGen::CGCXXABI::getMangleContext());
51 }
52
Charles Davis4e786dd2010-05-25 19:52:27 +000053public:
Mark Seabornedf0d382013-07-24 16:25:13 +000054 ItaniumCXXABI(CodeGen::CodeGenModule &CGM,
55 bool UseARMMethodPtrABI = false,
56 bool UseARMGuardVarABI = false) :
57 CGCXXABI(CGM), UseARMMethodPtrABI(UseARMMethodPtrABI),
58 UseARMGuardVarABI(UseARMGuardVarABI) { }
John McCall475999d2010-08-22 00:05:51 +000059
Reid Kleckner40ca9132014-05-13 22:05:45 +000060 bool classifyReturnType(CGFunctionInfo &FI) const override;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000061
Craig Topper4f12f102014-03-12 06:41:41 +000062 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override {
Reid Klecknerd355ca72014-05-15 01:26:32 +000063 // Structures with either a non-trivial destructor or a non-trivial
64 // copy constructor are always indirect.
65 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
66 // special members.
67 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor())
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000068 return RAA_Indirect;
69 return RAA_Default;
70 }
71
John McCall7f416cc2015-09-08 08:05:57 +000072 bool isThisCompleteObject(GlobalDecl GD) const override {
73 // The Itanium ABI has separate complete-object vs. base-object
74 // variants of both constructors and destructors.
75 if (isa<CXXDestructorDecl>(GD.getDecl())) {
76 switch (GD.getDtorType()) {
77 case Dtor_Complete:
78 case Dtor_Deleting:
79 return true;
80
81 case Dtor_Base:
82 return false;
83
84 case Dtor_Comdat:
85 llvm_unreachable("emitting dtor comdat as function?");
86 }
87 llvm_unreachable("bad dtor kind");
88 }
89 if (isa<CXXConstructorDecl>(GD.getDecl())) {
90 switch (GD.getCtorType()) {
91 case Ctor_Complete:
92 return true;
93
94 case Ctor_Base:
95 return false;
96
97 case Ctor_CopyingClosure:
98 case Ctor_DefaultClosure:
99 llvm_unreachable("closure ctors in Itanium ABI?");
100
101 case Ctor_Comdat:
102 llvm_unreachable("emitting ctor comdat as function?");
103 }
104 llvm_unreachable("bad dtor kind");
105 }
106
107 // No other kinds.
108 return false;
109 }
110
Craig Topper4f12f102014-03-12 06:41:41 +0000111 bool isZeroInitializable(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +0000112
Craig Topper4f12f102014-03-12 06:41:41 +0000113 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
John McCall7a9aac22010-08-23 01:21:21 +0000114
Craig Topper4f12f102014-03-12 06:41:41 +0000115 llvm::Value *
116 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
117 const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000118 Address This,
119 llvm::Value *&ThisPtrForCall,
Craig Topper4f12f102014-03-12 06:41:41 +0000120 llvm::Value *MemFnPtr,
121 const MemberPointerType *MPT) override;
John McCalla8bbb822010-08-22 03:04:22 +0000122
Craig Topper4f12f102014-03-12 06:41:41 +0000123 llvm::Value *
124 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000125 Address Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000126 llvm::Value *MemPtr,
127 const MemberPointerType *MPT) override;
John McCallc134eb52010-08-31 21:07:20 +0000128
John McCall7a9aac22010-08-23 01:21:21 +0000129 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
130 const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +0000131 llvm::Value *Src) override;
John McCallc62bb392012-02-15 01:22:51 +0000132 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +0000133 llvm::Constant *Src) override;
John McCall84fa5102010-08-22 04:16:24 +0000134
Craig Topper4f12f102014-03-12 06:41:41 +0000135 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +0000136
David Majnemere2be95b2015-06-23 07:31:01 +0000137 llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD) override;
John McCallf3a88602011-02-03 08:15:49 +0000138 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +0000139 CharUnits offset) override;
140 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
Richard Smithdafff942012-01-14 04:30:29 +0000141 llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
142 CharUnits ThisAdjustment);
John McCall1c456c82010-08-22 06:43:33 +0000143
John McCall7a9aac22010-08-23 01:21:21 +0000144 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000145 llvm::Value *L, llvm::Value *R,
John McCall7a9aac22010-08-23 01:21:21 +0000146 const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +0000147 bool Inequality) override;
John McCall131d97d2010-08-22 08:30:07 +0000148
John McCall7a9aac22010-08-23 01:21:21 +0000149 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000150 llvm::Value *Addr,
151 const MemberPointerType *MPT) override;
John McCall5d865c322010-08-31 07:33:07 +0000152
David Majnemer08681372014-11-01 07:37:17 +0000153 void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,
John McCall7f416cc2015-09-08 08:05:57 +0000154 Address Ptr, QualType ElementType,
David Majnemer0c0b6d92014-10-31 20:09:12 +0000155 const CXXDestructorDecl *Dtor) override;
John McCall82fb8922012-09-25 10:10:39 +0000156
John McCall7f416cc2015-09-08 08:05:57 +0000157 /// Itanium says that an _Unwind_Exception has to be "double-word"
158 /// aligned (and thus the end of it is also so-aligned), meaning 16
159 /// bytes. Of course, that was written for the actual Itanium,
160 /// which is a 64-bit platform. Classically, the ABI doesn't really
161 /// specify the alignment on other platforms, but in practice
162 /// libUnwind declares the struct with __attribute__((aligned)), so
163 /// we assume that alignment here. (It's generally 16 bytes, but
164 /// some targets overwrite it.)
165 CharUnits getAlignmentOfExnObject() {
166 auto align = CGM.getContext().getTargetDefaultAlignForAttributeAligned();
167 return CGM.getContext().toCharUnitsFromBits(align);
168 }
169
David Majnemer442d0a22014-11-25 07:20:20 +0000170 void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
David Majnemer7c237072015-03-05 00:46:22 +0000171 void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override;
David Majnemer442d0a22014-11-25 07:20:20 +0000172
Reid Klecknerfff8e7f2015-03-03 19:21:04 +0000173 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
174
175 llvm::CallInst *
176 emitTerminateForUnexpectedException(CodeGenFunction &CGF,
177 llvm::Value *Exn) override;
178
David Majnemere2cb8d12014-07-07 06:20:47 +0000179 void EmitFundamentalRTTIDescriptor(QualType Type);
180 void EmitFundamentalRTTIDescriptors();
David Majnemer443250f2015-03-17 20:35:00 +0000181 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
Justin Bogner0729afa2015-03-17 22:31:34 +0000182 llvm::Constant *
David Majnemer37b417f2015-03-29 21:55:10 +0000183 getAddrOfCXXCatchHandlerType(QualType Ty,
184 QualType CatchHandlerType) override {
David Majnemer443250f2015-03-17 20:35:00 +0000185 return getAddrOfRTTIDescriptor(Ty);
186 }
David Majnemere2cb8d12014-07-07 06:20:47 +0000187
David Majnemer1162d252014-06-22 19:05:33 +0000188 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
189 void EmitBadTypeidCall(CodeGenFunction &CGF) override;
190 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
John McCall7f416cc2015-09-08 08:05:57 +0000191 Address ThisPtr,
David Majnemer1162d252014-06-22 19:05:33 +0000192 llvm::Type *StdTypeInfoPtrTy) override;
193
194 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
195 QualType SrcRecordTy) override;
196
John McCall7f416cc2015-09-08 08:05:57 +0000197 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, Address Value,
David Majnemer1162d252014-06-22 19:05:33 +0000198 QualType SrcRecordTy, QualType DestTy,
199 QualType DestRecordTy,
200 llvm::BasicBlock *CastEnd) override;
201
John McCall7f416cc2015-09-08 08:05:57 +0000202 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
David Majnemer1162d252014-06-22 19:05:33 +0000203 QualType SrcRecordTy,
204 QualType DestTy) override;
205
206 bool EmitBadCastCall(CodeGenFunction &CGF) override;
207
Craig Topper4f12f102014-03-12 06:41:41 +0000208 llvm::Value *
John McCall7f416cc2015-09-08 08:05:57 +0000209 GetVirtualBaseClassOffset(CodeGenFunction &CGF, Address This,
Craig Topper4f12f102014-03-12 06:41:41 +0000210 const CXXRecordDecl *ClassDecl,
211 const CXXRecordDecl *BaseClassDecl) override;
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000212
Craig Topper4f12f102014-03-12 06:41:41 +0000213 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000214
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000215 void buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
216 SmallVectorImpl<CanQualType> &ArgTys) override;
John McCall5d865c322010-08-31 07:33:07 +0000217
Reid Klecknere7de47e2013-07-22 13:51:44 +0000218 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
Craig Topper4f12f102014-03-12 06:41:41 +0000219 CXXDtorType DT) const override {
Reid Klecknere7de47e2013-07-22 13:51:44 +0000220 // Itanium does not emit any destructor variant as an inline thunk.
221 // Delegating may occur as an optimization, but all variants are either
222 // emitted with external linkage or as linkonce if they are inline and used.
223 return false;
224 }
225
Craig Topper4f12f102014-03-12 06:41:41 +0000226 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
Reid Klecknere7de47e2013-07-22 13:51:44 +0000227
Reid Kleckner89077a12013-12-17 19:46:40 +0000228 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
Craig Topper4f12f102014-03-12 06:41:41 +0000229 FunctionArgList &Params) override;
John McCall5d865c322010-08-31 07:33:07 +0000230
Craig Topper4f12f102014-03-12 06:41:41 +0000231 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
John McCall8ed55a52010-09-02 09:58:18 +0000232
Reid Kleckner89077a12013-12-17 19:46:40 +0000233 unsigned addImplicitConstructorArgs(CodeGenFunction &CGF,
234 const CXXConstructorDecl *D,
235 CXXCtorType Type, bool ForVirtualBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000236 bool Delegating,
237 CallArgList &Args) override;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000238
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000239 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
240 CXXDtorType Type, bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +0000241 bool Delegating, Address This) override;
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000242
Craig Topper4f12f102014-03-12 06:41:41 +0000243 void emitVTableDefinitions(CodeGenVTables &CGVT,
244 const CXXRecordDecl *RD) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000245
246 llvm::Value *getVTableAddressPointInStructor(
247 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
Steven Wu5528da72015-08-28 07:14:10 +0000248 BaseSubobject Base, const CXXRecordDecl *NearestVBase,
249 bool &NeedsVirtualOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000250
251 llvm::Constant *
252 getVTableAddressPointForConstExpr(BaseSubobject Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000253 const CXXRecordDecl *VTableClass) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000254
255 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
Craig Topper4f12f102014-03-12 06:41:41 +0000256 CharUnits VPtrOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000257
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000258 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
John McCall7f416cc2015-09-08 08:05:57 +0000259 Address This, llvm::Type *Ty,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +0000260 SourceLocation Loc) override;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000261
David Majnemer0c0b6d92014-10-31 20:09:12 +0000262 llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
263 const CXXDestructorDecl *Dtor,
264 CXXDtorType DtorType,
John McCall7f416cc2015-09-08 08:05:57 +0000265 Address This,
David Majnemer0c0b6d92014-10-31 20:09:12 +0000266 const CXXMemberCallExpr *CE) override;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000267
Craig Topper4f12f102014-03-12 06:41:41 +0000268 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
Reid Kleckner7810af02013-06-19 15:20:38 +0000269
Steven Wu5528da72015-08-28 07:14:10 +0000270 bool canEmitAvailableExternallyVTable(const CXXRecordDecl *RD) const override;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000271
Hans Wennborgc94391d2014-06-06 20:04:01 +0000272 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
273 bool ReturnAdjustment) override {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000274 // Allow inlining of thunks by emitting them with available_externally
275 // linkage together with vtables when needed.
Peter Collingbourne8fabc1b2015-07-01 02:10:26 +0000276 if (ForVTable && !Thunk->hasLocalLinkage())
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000277 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
278 }
279
John McCall7f416cc2015-09-08 08:05:57 +0000280 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This,
Craig Topper4f12f102014-03-12 06:41:41 +0000281 const ThisAdjustment &TA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000282
John McCall7f416cc2015-09-08 08:05:57 +0000283 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
Craig Topper4f12f102014-03-12 06:41:41 +0000284 const ReturnAdjustment &RA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000285
David Majnemer196ac332014-09-11 23:05:02 +0000286 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
287 FunctionArgList &Args) const override {
288 assert(!Args.empty() && "expected the arglist to not be empty!");
289 return Args.size() - 1;
290 }
291
Craig Topper4f12f102014-03-12 06:41:41 +0000292 StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
293 StringRef GetDeletedVirtualCallName() override
294 { return "__cxa_deleted_virtual"; }
Joao Matos2ce88ef2012-07-17 17:10:11 +0000295
Craig Topper4f12f102014-03-12 06:41:41 +0000296 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall7f416cc2015-09-08 08:05:57 +0000297 Address InitializeArrayCookie(CodeGenFunction &CGF,
298 Address NewPtr,
299 llvm::Value *NumElements,
300 const CXXNewExpr *expr,
301 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000302 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000303 Address allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000304 CharUnits cookieSize) override;
John McCall68ff0372010-09-08 01:44:27 +0000305
John McCallcdf7ef52010-11-06 09:44:32 +0000306 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000307 llvm::GlobalVariable *DeclPtr,
308 bool PerformInit) override;
Richard Smithdbf74ba2013-04-14 23:01:42 +0000309 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000310 llvm::Constant *dtor, llvm::Constant *addr) override;
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000311
312 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +0000313 llvm::Value *Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000314 void EmitThreadLocalInitFuncs(
David Majnemerb3341ea2014-10-05 05:05:40 +0000315 CodeGenModule &CGM,
316 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *>>
317 CXXThreadLocals,
318 ArrayRef<llvm::Function *> CXXThreadLocalInits,
319 ArrayRef<llvm::GlobalVariable *> CXXThreadLocalInitVars) override;
320
321 bool usesThreadWrapperFunction() const override { return true; }
Richard Smith0f383742014-03-26 22:48:22 +0000322 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
323 QualType LValType) override;
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000324
Craig Topper4f12f102014-03-12 06:41:41 +0000325 bool NeedsVTTParameter(GlobalDecl GD) override;
David Majnemere2cb8d12014-07-07 06:20:47 +0000326
327 /**************************** RTTI Uniqueness ******************************/
328
329protected:
330 /// Returns true if the ABI requires RTTI type_info objects to be unique
331 /// across a program.
332 virtual bool shouldRTTIBeUnique() const { return true; }
333
334public:
335 /// What sort of unique-RTTI behavior should we use?
336 enum RTTIUniquenessKind {
337 /// We are guaranteeing, or need to guarantee, that the RTTI string
338 /// is unique.
339 RUK_Unique,
340
341 /// We are not guaranteeing uniqueness for the RTTI string, so we
342 /// can demote to hidden visibility but must use string comparisons.
343 RUK_NonUniqueHidden,
344
345 /// We are not guaranteeing uniqueness for the RTTI string, so we
346 /// have to use string comparisons, but we also have to emit it with
347 /// non-hidden visibility.
348 RUK_NonUniqueVisible
349 };
350
351 /// Return the required visibility status for the given type and linkage in
352 /// the current ABI.
353 RTTIUniquenessKind
354 classifyRTTIUniqueness(QualType CanTy,
355 llvm::GlobalValue::LinkageTypes Linkage) const;
356 friend class ItaniumRTTIBuilder;
Rafael Espindola91f68b42014-09-15 19:20:10 +0000357
358 void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000359
360 private:
Piotr Padlewski1d02f682015-08-19 20:09:09 +0000361 bool hasAnyUsedVirtualInlineFunction(const CXXRecordDecl *RD) const {
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000362 const auto &VtableLayout =
363 CGM.getItaniumVTableContext().getVTableLayout(RD);
364
365 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
Piotr Padlewski1d02f682015-08-19 20:09:09 +0000366 if (!VtableComponent.isUsedFunctionPointerKind())
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000367 continue;
368
Piotr Padlewski1d02f682015-08-19 20:09:09 +0000369 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000370 if (Method->getCanonicalDecl()->isInlined())
371 return true;
372 }
373 return false;
374 }
Charles Davis4e786dd2010-05-25 19:52:27 +0000375};
John McCall86353412010-08-21 22:46:04 +0000376
377class ARMCXXABI : public ItaniumCXXABI {
378public:
Mark Seabornedf0d382013-07-24 16:25:13 +0000379 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
380 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
381 /* UseARMGuardVarABI = */ true) {}
John McCall5d865c322010-08-31 07:33:07 +0000382
Craig Topper4f12f102014-03-12 06:41:41 +0000383 bool HasThisReturn(GlobalDecl GD) const override {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000384 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
385 isa<CXXDestructorDecl>(GD.getDecl()) &&
386 GD.getDtorType() != Dtor_Deleting));
387 }
John McCall5d865c322010-08-31 07:33:07 +0000388
Craig Topper4f12f102014-03-12 06:41:41 +0000389 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
390 QualType ResTy) override;
John McCall5d865c322010-08-31 07:33:07 +0000391
Craig Topper4f12f102014-03-12 06:41:41 +0000392 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall7f416cc2015-09-08 08:05:57 +0000393 Address InitializeArrayCookie(CodeGenFunction &CGF,
394 Address NewPtr,
395 llvm::Value *NumElements,
396 const CXXNewExpr *expr,
397 QualType ElementType) override;
398 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, Address allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000399 CharUnits cookieSize) override;
John McCall86353412010-08-21 22:46:04 +0000400};
Tim Northovera2ee4332014-03-29 15:09:45 +0000401
402class iOS64CXXABI : public ARMCXXABI {
403public:
404 iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {}
Tim Northover65f582f2014-03-30 17:32:48 +0000405
406 // ARM64 libraries are prepared for non-unique RTTI.
David Majnemere2cb8d12014-07-07 06:20:47 +0000407 bool shouldRTTIBeUnique() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +0000408};
Dan Gohmanc2853072015-09-03 22:51:53 +0000409
410class WebAssemblyCXXABI final : public ItaniumCXXABI {
411public:
412 explicit WebAssemblyCXXABI(CodeGen::CodeGenModule &CGM)
413 : ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
414 /*UseARMGuardVarABI=*/true) {}
415
416private:
417 bool HasThisReturn(GlobalDecl GD) const override {
418 return isa<CXXConstructorDecl>(GD.getDecl()) ||
419 (isa<CXXDestructorDecl>(GD.getDecl()) &&
420 GD.getDtorType() != Dtor_Deleting);
421 }
422};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000423}
Charles Davis4e786dd2010-05-25 19:52:27 +0000424
Charles Davis53c59df2010-08-16 03:33:14 +0000425CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000426 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000427 // For IR-generation purposes, there's no significant difference
428 // between the ARM and iOS ABIs.
429 case TargetCXXABI::GenericARM:
430 case TargetCXXABI::iOS:
431 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000432
Tim Northovera2ee4332014-03-29 15:09:45 +0000433 case TargetCXXABI::iOS64:
434 return new iOS64CXXABI(CGM);
435
Tim Northover9bb857a2013-01-31 12:13:10 +0000436 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
437 // include the other 32-bit ARM oddities: constructor/destructor return values
438 // and array cookies.
439 case TargetCXXABI::GenericAArch64:
Mark Seabornedf0d382013-07-24 16:25:13 +0000440 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
441 /* UseARMGuardVarABI = */ true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000442
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000443 case TargetCXXABI::GenericMIPS:
444 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true);
445
Dan Gohmanc2853072015-09-03 22:51:53 +0000446 case TargetCXXABI::WebAssembly:
447 return new WebAssemblyCXXABI(CGM);
448
John McCall57625922013-01-25 23:36:14 +0000449 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000450 if (CGM.getContext().getTargetInfo().getTriple().getArch()
451 == llvm::Triple::le32) {
452 // For PNaCl, use ARM-style method pointers so that PNaCl code
453 // does not assume anything about the alignment of function
454 // pointers.
455 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
456 /* UseARMGuardVarABI = */ false);
457 }
John McCall57625922013-01-25 23:36:14 +0000458 return new ItaniumCXXABI(CGM);
459
460 case TargetCXXABI::Microsoft:
461 llvm_unreachable("Microsoft ABI is not Itanium-based");
462 }
463 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000464}
465
Chris Lattnera5f58b02011-07-09 17:41:47 +0000466llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000467ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
468 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000469 return CGM.PtrDiffTy;
Reid Kleckneree7cf842014-12-01 22:02:27 +0000470 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, nullptr);
John McCall1c456c82010-08-22 06:43:33 +0000471}
472
John McCalld9c6c0b2010-08-22 00:59:17 +0000473/// In the Itanium and ARM ABIs, method pointers have the form:
474/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
475///
476/// In the Itanium ABI:
477/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
478/// - the this-adjustment is (memptr.adj)
479/// - the virtual offset is (memptr.ptr - 1)
480///
481/// In the ARM ABI:
482/// - method pointers are virtual if (memptr.adj & 1) is nonzero
483/// - the this-adjustment is (memptr.adj >> 1)
484/// - the virtual offset is (memptr.ptr)
485/// ARM uses 'adj' for the virtual flag because Thumb functions
486/// may be only single-byte aligned.
487///
488/// If the member is virtual, the adjusted 'this' pointer points
489/// to a vtable pointer from which the virtual offset is applied.
490///
491/// If the member is non-virtual, memptr.ptr is the address of
492/// the function to call.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000493llvm::Value *ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
John McCall7f416cc2015-09-08 08:05:57 +0000494 CodeGenFunction &CGF, const Expr *E, Address ThisAddr,
495 llvm::Value *&ThisPtrForCall,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000496 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
John McCall475999d2010-08-22 00:05:51 +0000497 CGBuilderTy &Builder = CGF.Builder;
498
499 const FunctionProtoType *FPT =
500 MPT->getPointeeType()->getAs<FunctionProtoType>();
501 const CXXRecordDecl *RD =
502 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
503
Chris Lattner2192fe52011-07-18 04:24:23 +0000504 llvm::FunctionType *FTy =
John McCalla729c622012-02-17 03:33:10 +0000505 CGM.getTypes().GetFunctionType(
506 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
John McCall475999d2010-08-22 00:05:51 +0000507
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000508 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000509
John McCalld9c6c0b2010-08-22 00:59:17 +0000510 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
511 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
512 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
513
John McCalla1dee5302010-08-22 10:59:02 +0000514 // Extract memptr.adj, which is in the second field.
515 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000516
517 // Compute the true adjustment.
518 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000519 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000520 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000521
522 // Apply the adjustment and cast back to the original struct type
523 // for consistency.
John McCall7f416cc2015-09-08 08:05:57 +0000524 llvm::Value *This = ThisAddr.getPointer();
John McCalld9c6c0b2010-08-22 00:59:17 +0000525 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
526 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
527 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall7f416cc2015-09-08 08:05:57 +0000528 ThisPtrForCall = This;
John McCall475999d2010-08-22 00:05:51 +0000529
530 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000531 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall475999d2010-08-22 00:05:51 +0000532
533 // If the LSB in the function pointer is 1, the function pointer points to
534 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000535 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000536 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000537 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
538 else
539 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
540 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000541 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
542
543 // In the virtual path, the adjustment left 'This' pointing to the
544 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000545 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000546 CGF.EmitBlock(FnVirtual);
547
548 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000549 llvm::Type *VTableTy = Builder.getInt8PtrTy();
John McCall7f416cc2015-09-08 08:05:57 +0000550 CharUnits VTablePtrAlign =
551 CGF.CGM.getDynamicOffsetAlignment(ThisAddr.getAlignment(), RD,
552 CGF.getPointerAlign());
553 llvm::Value *VTable =
554 CGF.GetVTablePtr(Address(This, VTablePtrAlign), VTableTy);
John McCall475999d2010-08-22 00:05:51 +0000555
556 // Apply the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000557 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000558 if (!UseARMMethodPtrABI)
559 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld9c6c0b2010-08-22 00:59:17 +0000560 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall475999d2010-08-22 00:05:51 +0000561
562 // Load the virtual function to call.
563 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCall7f416cc2015-09-08 08:05:57 +0000564 llvm::Value *VirtualFn =
565 Builder.CreateAlignedLoad(VTable, CGF.getPointerAlign(),
566 "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000567 CGF.EmitBranch(FnEnd);
568
569 // In the non-virtual path, the function pointer is actually a
570 // function pointer.
571 CGF.EmitBlock(FnNonVirtual);
572 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000573 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall475999d2010-08-22 00:05:51 +0000574
575 // We're done.
576 CGF.EmitBlock(FnEnd);
Jay Foad20c0f022011-03-30 11:28:58 +0000577 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
John McCall475999d2010-08-22 00:05:51 +0000578 Callee->addIncoming(VirtualFn, FnVirtual);
579 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
580 return Callee;
581}
John McCalla8bbb822010-08-22 03:04:22 +0000582
John McCallc134eb52010-08-31 21:07:20 +0000583/// Compute an l-value by applying the given pointer-to-member to a
584/// base object.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000585llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
John McCall7f416cc2015-09-08 08:05:57 +0000586 CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000587 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000588 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000589
590 CGBuilderTy &Builder = CGF.Builder;
591
John McCallc134eb52010-08-31 21:07:20 +0000592 // Cast to char*.
John McCall7f416cc2015-09-08 08:05:57 +0000593 Base = Builder.CreateElementBitCast(Base, CGF.Int8Ty);
John McCallc134eb52010-08-31 21:07:20 +0000594
595 // Apply the offset, which we assume is non-null.
John McCall7f416cc2015-09-08 08:05:57 +0000596 llvm::Value *Addr =
597 Builder.CreateInBoundsGEP(Base.getPointer(), MemPtr, "memptr.offset");
John McCallc134eb52010-08-31 21:07:20 +0000598
599 // Cast the address to the appropriate pointer type, adopting the
600 // address space of the base pointer.
John McCall7f416cc2015-09-08 08:05:57 +0000601 llvm::Type *PType = CGF.ConvertTypeForMem(MPT->getPointeeType())
602 ->getPointerTo(Base.getAddressSpace());
John McCallc134eb52010-08-31 21:07:20 +0000603 return Builder.CreateBitCast(Addr, PType);
604}
605
John McCallc62bb392012-02-15 01:22:51 +0000606/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
607/// conversion.
608///
609/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000610///
611/// Obligatory offset/adjustment diagram:
612/// <-- offset --> <-- adjustment -->
613/// |--------------------------|----------------------|--------------------|
614/// ^Derived address point ^Base address point ^Member address point
615///
616/// So when converting a base member pointer to a derived member pointer,
617/// we add the offset to the adjustment because the address point has
618/// decreased; and conversely, when converting a derived MP to a base MP
619/// we subtract the offset from the adjustment because the address point
620/// has increased.
621///
622/// The standard forbids (at compile time) conversion to and from
623/// virtual bases, which is why we don't have to consider them here.
624///
625/// The standard forbids (at run time) casting a derived MP to a base
626/// MP when the derived MP does not point to a member of the base.
627/// This is why -1 is a reasonable choice for null data member
628/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000629llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000630ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
631 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000632 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000633 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000634 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
635 E->getCastKind() == CK_ReinterpretMemberPointer);
636
637 // Under Itanium, reinterprets don't require any additional processing.
638 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
639
640 // Use constant emission if we can.
641 if (isa<llvm::Constant>(src))
642 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
643
644 llvm::Constant *adj = getMemberPointerAdjustment(E);
645 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000646
647 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000648 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000649
John McCallc62bb392012-02-15 01:22:51 +0000650 const MemberPointerType *destTy =
651 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000652
John McCall7a9aac22010-08-23 01:21:21 +0000653 // For member data pointers, this is just a matter of adding the
654 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000655 if (destTy->isMemberDataPointer()) {
656 llvm::Value *dst;
657 if (isDerivedToBase)
658 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000659 else
John McCallc62bb392012-02-15 01:22:51 +0000660 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000661
662 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000663 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
664 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
665 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000666 }
667
John McCalla1dee5302010-08-22 10:59:02 +0000668 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000669 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000670 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
671 offset <<= 1;
672 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000673 }
674
John McCallc62bb392012-02-15 01:22:51 +0000675 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
676 llvm::Value *dstAdj;
677 if (isDerivedToBase)
678 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000679 else
John McCallc62bb392012-02-15 01:22:51 +0000680 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000681
John McCallc62bb392012-02-15 01:22:51 +0000682 return Builder.CreateInsertValue(src, dstAdj, 1);
683}
684
685llvm::Constant *
686ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
687 llvm::Constant *src) {
688 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
689 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
690 E->getCastKind() == CK_ReinterpretMemberPointer);
691
692 // Under Itanium, reinterprets don't require any additional processing.
693 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
694
695 // If the adjustment is trivial, we don't need to do anything.
696 llvm::Constant *adj = getMemberPointerAdjustment(E);
697 if (!adj) return src;
698
699 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
700
701 const MemberPointerType *destTy =
702 E->getType()->castAs<MemberPointerType>();
703
704 // For member data pointers, this is just a matter of adding the
705 // offset if the source is non-null.
706 if (destTy->isMemberDataPointer()) {
707 // null maps to null.
708 if (src->isAllOnesValue()) return src;
709
710 if (isDerivedToBase)
711 return llvm::ConstantExpr::getNSWSub(src, adj);
712 else
713 return llvm::ConstantExpr::getNSWAdd(src, adj);
714 }
715
716 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000717 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000718 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
719 offset <<= 1;
720 adj = llvm::ConstantInt::get(adj->getType(), offset);
721 }
722
723 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
724 llvm::Constant *dstAdj;
725 if (isDerivedToBase)
726 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
727 else
728 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
729
730 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000731}
John McCall84fa5102010-08-22 04:16:24 +0000732
733llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000734ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000735 // Itanium C++ ABI 2.3:
736 // A NULL pointer is represented as -1.
737 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000738 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000739
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000740 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000741 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000742 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000743}
744
John McCallf3a88602011-02-03 08:15:49 +0000745llvm::Constant *
746ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
747 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000748 // Itanium C++ ABI 2.3:
749 // A pointer to data member is an offset from the base address of
750 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000751 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000752}
753
David Majnemere2be95b2015-06-23 07:31:01 +0000754llvm::Constant *
755ItaniumCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000756 return BuildMemberPointer(MD, CharUnits::Zero());
757}
758
759llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
760 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000761 assert(MD->isInstance() && "Member function must not be static!");
762 MD = MD->getCanonicalDecl();
763
764 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000765
766 // Get the function pointer (or index if this is a virtual function).
767 llvm::Constant *MemPtr[2];
768 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000769 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000770
Ken Dyckdf016282011-04-09 01:30:02 +0000771 const ASTContext &Context = getContext();
772 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000773 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000774 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000775
Mark Seabornedf0d382013-07-24 16:25:13 +0000776 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000777 // ARM C++ ABI 3.2.1:
778 // This ABI specifies that adj contains twice the this
779 // adjustment, plus 1 if the member function is virtual. The
780 // least significant bit of adj then makes exactly the same
781 // discrimination as the least significant bit of ptr does for
782 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000783 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
784 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000785 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000786 } else {
787 // Itanium C++ ABI 2.3:
788 // For a virtual function, [the pointer field] is 1 plus the
789 // virtual table offset (in bytes) of the function,
790 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000791 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
792 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000793 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000794 }
795 } else {
John McCall2979fe02011-04-12 00:42:48 +0000796 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000797 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000798 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000799 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000800 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000801 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000802 } else {
John McCall2979fe02011-04-12 00:42:48 +0000803 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
804 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000805 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000806 }
John McCall2979fe02011-04-12 00:42:48 +0000807 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000808
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000809 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000810 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
811 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000812 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000813 }
John McCall1c456c82010-08-22 06:43:33 +0000814
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000815 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000816}
817
Richard Smithdafff942012-01-14 04:30:29 +0000818llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
819 QualType MPType) {
820 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
821 const ValueDecl *MPD = MP.getMemberPointerDecl();
822 if (!MPD)
823 return EmitNullMemberPointer(MPT);
824
Reid Kleckner452abac2013-05-09 21:01:17 +0000825 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000826
827 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
828 return BuildMemberPointer(MD, ThisAdjustment);
829
830 CharUnits FieldOffset =
831 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
832 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
833}
834
John McCall131d97d2010-08-22 08:30:07 +0000835/// The comparison algorithm is pretty easy: the member pointers are
836/// the same if they're either bitwise identical *or* both null.
837///
838/// ARM is different here only because null-ness is more complicated.
839llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000840ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
841 llvm::Value *L,
842 llvm::Value *R,
843 const MemberPointerType *MPT,
844 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000845 CGBuilderTy &Builder = CGF.Builder;
846
John McCall131d97d2010-08-22 08:30:07 +0000847 llvm::ICmpInst::Predicate Eq;
848 llvm::Instruction::BinaryOps And, Or;
849 if (Inequality) {
850 Eq = llvm::ICmpInst::ICMP_NE;
851 And = llvm::Instruction::Or;
852 Or = llvm::Instruction::And;
853 } else {
854 Eq = llvm::ICmpInst::ICMP_EQ;
855 And = llvm::Instruction::And;
856 Or = llvm::Instruction::Or;
857 }
858
John McCall7a9aac22010-08-23 01:21:21 +0000859 // Member data pointers are easy because there's a unique null
860 // value, so it just comes down to bitwise equality.
861 if (MPT->isMemberDataPointer())
862 return Builder.CreateICmp(Eq, L, R);
863
864 // For member function pointers, the tautologies are more complex.
865 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000866 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000867 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000868 // (L == R) <==> (L.ptr == R.ptr &&
869 // (L.adj == R.adj ||
870 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000871 // The inequality tautologies have exactly the same structure, except
872 // applying De Morgan's laws.
873
874 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
875 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
876
John McCall131d97d2010-08-22 08:30:07 +0000877 // This condition tests whether L.ptr == R.ptr. This must always be
878 // true for equality to hold.
879 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
880
881 // This condition, together with the assumption that L.ptr == R.ptr,
882 // tests whether the pointers are both null. ARM imposes an extra
883 // condition.
884 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
885 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
886
887 // This condition tests whether L.adj == R.adj. If this isn't
888 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +0000889 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
890 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000891 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
892
893 // Null member function pointers on ARM clear the low bit of Adj,
894 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000895 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000896 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
897
898 // Compute (l.adj | r.adj) & 1 and test it against zero.
899 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
900 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
901 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
902 "cmp.or.adj");
903 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
904 }
905
906 // Tie together all our conditions.
907 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
908 Result = Builder.CreateBinOp(And, PtrEq, Result,
909 Inequality ? "memptr.ne" : "memptr.eq");
910 return Result;
911}
912
913llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000914ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
915 llvm::Value *MemPtr,
916 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +0000917 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +0000918
919 /// For member data pointers, this is just a check against -1.
920 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000921 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +0000922 llvm::Value *NegativeOne =
923 llvm::Constant::getAllOnesValue(MemPtr->getType());
924 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
925 }
John McCall131d97d2010-08-22 08:30:07 +0000926
Daniel Dunbar914bc412011-04-19 23:10:47 +0000927 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +0000928 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +0000929
930 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
931 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
932
Daniel Dunbar914bc412011-04-19 23:10:47 +0000933 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
934 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000935 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000936 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +0000937 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000938 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +0000939 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
940 "memptr.isvirtual");
941 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +0000942 }
943
944 return Result;
945}
John McCall1c456c82010-08-22 06:43:33 +0000946
Reid Kleckner40ca9132014-05-13 22:05:45 +0000947bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
948 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
949 if (!RD)
950 return false;
951
Reid Klecknerd355ca72014-05-15 01:26:32 +0000952 // Return indirectly if we have a non-trivial copy ctor or non-trivial dtor.
953 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
954 // special members.
955 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor()) {
John McCall7f416cc2015-09-08 08:05:57 +0000956 auto Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
957 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
Reid Kleckner40ca9132014-05-13 22:05:45 +0000958 return true;
959 }
Reid Kleckner40ca9132014-05-13 22:05:45 +0000960 return false;
961}
962
John McCall614dbdc2010-08-22 21:01:12 +0000963/// The Itanium ABI requires non-zero initialization only for data
964/// member pointers, for which '0' is a valid offset.
965bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
David Majnemer5fd33e02015-04-24 01:25:08 +0000966 return MPT->isMemberFunctionPointer();
John McCall84fa5102010-08-22 04:16:24 +0000967}
John McCall5d865c322010-08-31 07:33:07 +0000968
John McCall82fb8922012-09-25 10:10:39 +0000969/// The Itanium ABI always places an offset to the complete object
970/// at entry -2 in the vtable.
David Majnemer08681372014-11-01 07:37:17 +0000971void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
972 const CXXDeleteExpr *DE,
John McCall7f416cc2015-09-08 08:05:57 +0000973 Address Ptr,
David Majnemer08681372014-11-01 07:37:17 +0000974 QualType ElementType,
975 const CXXDestructorDecl *Dtor) {
976 bool UseGlobalDelete = DE->isGlobalDelete();
David Majnemer0c0b6d92014-10-31 20:09:12 +0000977 if (UseGlobalDelete) {
978 // Derive the complete-object pointer, which is what we need
979 // to pass to the deallocation function.
John McCall82fb8922012-09-25 10:10:39 +0000980
David Majnemer0c0b6d92014-10-31 20:09:12 +0000981 // Grab the vtable pointer as an intptr_t*.
982 llvm::Value *VTable = CGF.GetVTablePtr(Ptr, CGF.IntPtrTy->getPointerTo());
John McCall82fb8922012-09-25 10:10:39 +0000983
David Majnemer0c0b6d92014-10-31 20:09:12 +0000984 // Track back to entry -2 and pull out the offset there.
985 llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
986 VTable, -2, "complete-offset.ptr");
John McCall7f416cc2015-09-08 08:05:57 +0000987 llvm::Value *Offset =
988 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
David Majnemer0c0b6d92014-10-31 20:09:12 +0000989
990 // Apply the offset.
John McCall7f416cc2015-09-08 08:05:57 +0000991 llvm::Value *CompletePtr =
992 CGF.Builder.CreateBitCast(Ptr.getPointer(), CGF.Int8PtrTy);
David Majnemer0c0b6d92014-10-31 20:09:12 +0000993 CompletePtr = CGF.Builder.CreateInBoundsGEP(CompletePtr, Offset);
994
995 // If we're supposed to call the global delete, make sure we do so
996 // even if the destructor throws.
David Majnemer08681372014-11-01 07:37:17 +0000997 CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr,
998 ElementType);
David Majnemer0c0b6d92014-10-31 20:09:12 +0000999 }
1000
1001 // FIXME: Provide a source location here even though there's no
1002 // CXXMemberCallExpr for dtor call.
1003 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
1004 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr);
1005
1006 if (UseGlobalDelete)
1007 CGF.PopCleanupBlock();
John McCall82fb8922012-09-25 10:10:39 +00001008}
1009
David Majnemer442d0a22014-11-25 07:20:20 +00001010void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
1011 // void __cxa_rethrow();
1012
1013 llvm::FunctionType *FTy =
1014 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
1015
1016 llvm::Constant *Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
1017
1018 if (isNoReturn)
1019 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, None);
1020 else
1021 CGF.EmitRuntimeCallOrInvoke(Fn);
1022}
1023
David Majnemer7c237072015-03-05 00:46:22 +00001024static llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) {
1025 // void *__cxa_allocate_exception(size_t thrown_size);
1026
1027 llvm::FunctionType *FTy =
1028 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false);
1029
1030 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
1031}
1032
1033static llvm::Constant *getThrowFn(CodeGenModule &CGM) {
1034 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
1035 // void (*dest) (void *));
1036
1037 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
1038 llvm::FunctionType *FTy =
1039 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
1040
1041 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
1042}
1043
1044void ItaniumCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
1045 QualType ThrowType = E->getSubExpr()->getType();
1046 // Now allocate the exception object.
1047 llvm::Type *SizeTy = CGF.ConvertType(getContext().getSizeType());
1048 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
1049
1050 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM);
1051 llvm::CallInst *ExceptionPtr = CGF.EmitNounwindRuntimeCall(
1052 AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception");
1053
John McCall7f416cc2015-09-08 08:05:57 +00001054 CharUnits ExnAlign = getAlignmentOfExnObject();
1055 CGF.EmitAnyExprToExn(E->getSubExpr(), Address(ExceptionPtr, ExnAlign));
David Majnemer7c237072015-03-05 00:46:22 +00001056
1057 // Now throw the exception.
1058 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
1059 /*ForEH=*/true);
1060
1061 // The address of the destructor. If the exception type has a
1062 // trivial destructor (or isn't a record), we just pass null.
1063 llvm::Constant *Dtor = nullptr;
1064 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
1065 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
1066 if (!Record->hasTrivialDestructor()) {
1067 CXXDestructorDecl *DtorD = Record->getDestructor();
1068 Dtor = CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete);
1069 Dtor = llvm::ConstantExpr::getBitCast(Dtor, CGM.Int8PtrTy);
1070 }
1071 }
1072 if (!Dtor) Dtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
1073
1074 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
1075 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
1076}
1077
David Majnemer1162d252014-06-22 19:05:33 +00001078static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) {
1079 // void *__dynamic_cast(const void *sub,
1080 // const abi::__class_type_info *src,
1081 // const abi::__class_type_info *dst,
1082 // std::ptrdiff_t src2dst_offset);
1083
1084 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1085 llvm::Type *PtrDiffTy =
1086 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1087
1088 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
1089
1090 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
1091
1092 // Mark the function as nounwind readonly.
1093 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
1094 llvm::Attribute::ReadOnly };
1095 llvm::AttributeSet Attrs = llvm::AttributeSet::get(
1096 CGF.getLLVMContext(), llvm::AttributeSet::FunctionIndex, FuncAttrs);
1097
1098 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
1099}
1100
1101static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1102 // void __cxa_bad_cast();
1103 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1104 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1105}
1106
1107/// \brief Compute the src2dst_offset hint as described in the
1108/// Itanium C++ ABI [2.9.7]
1109static CharUnits computeOffsetHint(ASTContext &Context,
1110 const CXXRecordDecl *Src,
1111 const CXXRecordDecl *Dst) {
1112 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1113 /*DetectVirtual=*/false);
1114
1115 // If Dst is not derived from Src we can skip the whole computation below and
1116 // return that Src is not a public base of Dst. Record all inheritance paths.
1117 if (!Dst->isDerivedFrom(Src, Paths))
1118 return CharUnits::fromQuantity(-2ULL);
1119
1120 unsigned NumPublicPaths = 0;
1121 CharUnits Offset;
1122
1123 // Now walk all possible inheritance paths.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001124 for (const CXXBasePath &Path : Paths) {
1125 if (Path.Access != AS_public) // Ignore non-public inheritance.
David Majnemer1162d252014-06-22 19:05:33 +00001126 continue;
1127
1128 ++NumPublicPaths;
1129
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001130 for (const CXXBasePathElement &PathElement : Path) {
David Majnemer1162d252014-06-22 19:05:33 +00001131 // If the path contains a virtual base class we can't give any hint.
1132 // -1: no hint.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001133 if (PathElement.Base->isVirtual())
David Majnemer1162d252014-06-22 19:05:33 +00001134 return CharUnits::fromQuantity(-1ULL);
1135
1136 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
1137 continue;
1138
1139 // Accumulate the base class offsets.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001140 const ASTRecordLayout &L = Context.getASTRecordLayout(PathElement.Class);
1141 Offset += L.getBaseClassOffset(
1142 PathElement.Base->getType()->getAsCXXRecordDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001143 }
1144 }
1145
1146 // -2: Src is not a public base of Dst.
1147 if (NumPublicPaths == 0)
1148 return CharUnits::fromQuantity(-2ULL);
1149
1150 // -3: Src is a multiple public base type but never a virtual base type.
1151 if (NumPublicPaths > 1)
1152 return CharUnits::fromQuantity(-3ULL);
1153
1154 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
1155 // Return the offset of Src from the origin of Dst.
1156 return Offset;
1157}
1158
1159static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1160 // void __cxa_bad_typeid();
1161 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1162
1163 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1164}
1165
1166bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
1167 QualType SrcRecordTy) {
1168 return IsDeref;
1169}
1170
1171void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
1172 llvm::Value *Fn = getBadTypeidFn(CGF);
1173 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1174 CGF.Builder.CreateUnreachable();
1175}
1176
1177llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
1178 QualType SrcRecordTy,
John McCall7f416cc2015-09-08 08:05:57 +00001179 Address ThisPtr,
David Majnemer1162d252014-06-22 19:05:33 +00001180 llvm::Type *StdTypeInfoPtrTy) {
1181 llvm::Value *Value =
1182 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo());
1183
1184 // Load the type info.
1185 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001186 return CGF.Builder.CreateAlignedLoad(Value, CGF.getPointerAlign());
David Majnemer1162d252014-06-22 19:05:33 +00001187}
1188
1189bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1190 QualType SrcRecordTy) {
1191 return SrcIsPtr;
1192}
1193
1194llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
John McCall7f416cc2015-09-08 08:05:57 +00001195 CodeGenFunction &CGF, Address ThisAddr, QualType SrcRecordTy,
David Majnemer1162d252014-06-22 19:05:33 +00001196 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1197 llvm::Type *PtrDiffLTy =
1198 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1199 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1200
1201 llvm::Value *SrcRTTI =
1202 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1203 llvm::Value *DestRTTI =
1204 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1205
1206 // Compute the offset hint.
1207 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1208 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1209 llvm::Value *OffsetHint = llvm::ConstantInt::get(
1210 PtrDiffLTy,
1211 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
1212
1213 // Emit the call to __dynamic_cast.
John McCall7f416cc2015-09-08 08:05:57 +00001214 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001215 Value = CGF.EmitCastToVoidPtr(Value);
1216
1217 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
1218 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
1219 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1220
1221 /// C++ [expr.dynamic.cast]p9:
1222 /// A failed cast to reference type throws std::bad_cast
1223 if (DestTy->isReferenceType()) {
1224 llvm::BasicBlock *BadCastBlock =
1225 CGF.createBasicBlock("dynamic_cast.bad_cast");
1226
1227 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1228 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1229
1230 CGF.EmitBlock(BadCastBlock);
1231 EmitBadCastCall(CGF);
1232 }
1233
1234 return Value;
1235}
1236
1237llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001238 Address ThisAddr,
David Majnemer1162d252014-06-22 19:05:33 +00001239 QualType SrcRecordTy,
1240 QualType DestTy) {
1241 llvm::Type *PtrDiffLTy =
1242 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1243 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1244
1245 // Get the vtable pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001246 llvm::Value *VTable = CGF.GetVTablePtr(ThisAddr, PtrDiffLTy->getPointerTo());
David Majnemer1162d252014-06-22 19:05:33 +00001247
1248 // Get the offset-to-top from the vtable.
1249 llvm::Value *OffsetToTop =
1250 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001251 OffsetToTop =
1252 CGF.Builder.CreateAlignedLoad(OffsetToTop, CGF.getPointerAlign(),
1253 "offset.to.top");
David Majnemer1162d252014-06-22 19:05:33 +00001254
1255 // Finally, add the offset to the pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001256 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001257 Value = CGF.EmitCastToVoidPtr(Value);
1258 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1259
1260 return CGF.Builder.CreateBitCast(Value, DestLTy);
1261}
1262
1263bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1264 llvm::Value *Fn = getBadCastFn(CGF);
1265 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1266 CGF.Builder.CreateUnreachable();
1267 return true;
1268}
1269
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001270llvm::Value *
1271ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001272 Address This,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001273 const CXXRecordDecl *ClassDecl,
1274 const CXXRecordDecl *BaseClassDecl) {
1275 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy);
1276 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001277 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1278 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001279
1280 llvm::Value *VBaseOffsetPtr =
1281 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1282 "vbase.offset.ptr");
1283 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1284 CGM.PtrDiffTy->getPointerTo());
1285
1286 llvm::Value *VBaseOffset =
John McCall7f416cc2015-09-08 08:05:57 +00001287 CGF.Builder.CreateAlignedLoad(VBaseOffsetPtr, CGF.getPointerAlign(),
1288 "vbase.offset");
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001289
1290 return VBaseOffset;
1291}
1292
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001293void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1294 // Just make sure we're in sync with TargetCXXABI.
1295 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1296
Rafael Espindolac3cde362013-12-09 14:51:17 +00001297 // The constructor used for constructing this as a base class;
1298 // ignores virtual bases.
1299 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1300
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001301 // The constructor used for constructing this as a complete class;
Nico Weber4c2ffb22015-01-07 05:25:05 +00001302 // constructs the virtual bases, then calls the base constructor.
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001303 if (!D->getParent()->isAbstract()) {
1304 // We don't need to emit the complete ctor if the class is abstract.
1305 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1306 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001307}
1308
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001309void
1310ItaniumCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
1311 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +00001312 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001313
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001314 // All parameters are already in place except VTT, which goes after 'this'.
1315 // These are Clang types, so we don't need to worry about sret yet.
John McCall5d865c322010-08-31 07:33:07 +00001316
1317 // Check if we need to add a VTT parameter (which has type void **).
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001318 if (T == StructorType::Base && MD->getParent()->getNumVBases() != 0)
1319 ArgTys.insert(ArgTys.begin() + 1,
1320 Context.getPointerType(Context.VoidPtrTy));
John McCall5d865c322010-08-31 07:33:07 +00001321}
1322
Reid Klecknere7de47e2013-07-22 13:51:44 +00001323void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
Rafael Espindolac3cde362013-12-09 14:51:17 +00001324 // The destructor used for destructing this as a base class; ignores
1325 // virtual bases.
1326 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001327
1328 // The destructor used for destructing this as a most-derived class;
1329 // call the base destructor and then destructs any virtual bases.
1330 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1331
Rafael Espindolac3cde362013-12-09 14:51:17 +00001332 // The destructor in a virtual table is always a 'deleting'
1333 // destructor, which calls the complete destructor and then uses the
1334 // appropriate operator delete.
1335 if (D->isVirtual())
1336 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001337}
1338
Reid Kleckner89077a12013-12-17 19:46:40 +00001339void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1340 QualType &ResTy,
1341 FunctionArgList &Params) {
John McCall5d865c322010-08-31 07:33:07 +00001342 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +00001343 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
John McCall5d865c322010-08-31 07:33:07 +00001344
1345 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001346 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +00001347 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001348
1349 // FIXME: avoid the fake decl
1350 QualType T = Context.getPointerType(Context.VoidPtrTy);
1351 ImplicitParamDecl *VTTDecl
Craig Topper8a13c412014-05-21 05:09:00 +00001352 = ImplicitParamDecl::Create(Context, nullptr, MD->getLocation(),
John McCall5d865c322010-08-31 07:33:07 +00001353 &Context.Idents.get("vtt"), T);
Reid Kleckner89077a12013-12-17 19:46:40 +00001354 Params.insert(Params.begin() + 1, VTTDecl);
Reid Kleckner2af6d732013-12-13 00:09:59 +00001355 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +00001356 }
1357}
1358
John McCall5d865c322010-08-31 07:33:07 +00001359void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1360 /// Initialize the 'this' slot.
1361 EmitThisParam(CGF);
1362
1363 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +00001364 if (getStructorImplicitParamDecl(CGF)) {
1365 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1366 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +00001367 }
John McCall5d865c322010-08-31 07:33:07 +00001368
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001369 /// If this is a function that the ABI specifies returns 'this', initialize
1370 /// the return slot to 'this' at the start of the function.
1371 ///
1372 /// Unlike the setting of return types, this is done within the ABI
1373 /// implementation instead of by clients of CGCXXABI because:
1374 /// 1) getThisValue is currently protected
1375 /// 2) in theory, an ABI could implement 'this' returns some other way;
1376 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +00001377 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +00001378 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +00001379}
1380
Reid Kleckner89077a12013-12-17 19:46:40 +00001381unsigned ItaniumCXXABI::addImplicitConstructorArgs(
1382 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1383 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1384 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
1385 return 0;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001386
Reid Kleckner89077a12013-12-17 19:46:40 +00001387 // Insert the implicit 'vtt' argument as the second argument.
1388 llvm::Value *VTT =
1389 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1390 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1391 Args.insert(Args.begin() + 1,
1392 CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false));
1393 return 1; // Added one arg.
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001394}
1395
1396void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1397 const CXXDestructorDecl *DD,
1398 CXXDtorType Type, bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +00001399 bool Delegating, Address This) {
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001400 GlobalDecl GD(DD, Type);
1401 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1402 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1403
Craig Topper8a13c412014-05-21 05:09:00 +00001404 llvm::Value *Callee = nullptr;
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001405 if (getContext().getLangOpts().AppleKext)
1406 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
1407
1408 if (!Callee)
Rafael Espindola1ac0ec82014-09-11 15:42:06 +00001409 Callee = CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type));
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001410
John McCall7f416cc2015-09-08 08:05:57 +00001411 CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(),
1412 This.getPointer(), VTT, VTTTy, nullptr);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001413}
1414
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001415void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1416 const CXXRecordDecl *RD) {
1417 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1418 if (VTable->hasInitializer())
1419 return;
1420
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001421 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001422 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1423 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
David Majnemerd905da42014-07-01 20:30:31 +00001424 llvm::Constant *RTTI =
1425 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001426
1427 // Create and set the initializer.
1428 llvm::Constant *Init = CGVT.CreateVTableInitializer(
1429 RD, VTLayout.vtable_component_begin(), VTLayout.getNumVTableComponents(),
David Majnemerd905da42014-07-01 20:30:31 +00001430 VTLayout.vtable_thunk_begin(), VTLayout.getNumVTableThunks(), RTTI);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001431 VTable->setInitializer(Init);
1432
1433 // Set the correct linkage.
1434 VTable->setLinkage(Linkage);
1435
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001436 if (CGM.supportsCOMDAT() && VTable->isWeakForLinker())
1437 VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName()));
Rafael Espindolacb92c192015-01-15 23:18:01 +00001438
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001439 // Set the right visibility.
John McCall8f80a612014-02-08 00:41:16 +00001440 CGM.setGlobalVisibility(VTable, RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001441
Benjamin Kramer5d34a2b2014-09-10 12:50:59 +00001442 // Use pointer alignment for the vtable. Otherwise we would align them based
1443 // on the size of the initializer which doesn't make sense as only single
1444 // values are read.
1445 unsigned PAlign = CGM.getTarget().getPointerAlign(0);
1446 VTable->setAlignment(getContext().toCharUnitsFromBits(PAlign).getQuantity());
1447
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001448 // If this is the magic class __cxxabiv1::__fundamental_type_info,
1449 // we will emit the typeinfo for the fundamental types. This is the
1450 // same behaviour as GCC.
1451 const DeclContext *DC = RD->getDeclContext();
1452 if (RD->getIdentifier() &&
1453 RD->getIdentifier()->isStr("__fundamental_type_info") &&
1454 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1455 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1456 DC->getParent()->isTranslationUnit())
David Majnemere2cb8d12014-07-07 06:20:47 +00001457 EmitFundamentalRTTIDescriptors();
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001458
1459 CGM.EmitVTableBitSetEntries(VTable, VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001460}
1461
Piotr Padlewski525f7462015-08-27 21:35:37 +00001462llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1463 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
Steven Wu5528da72015-08-28 07:14:10 +00001464 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
1465 bool NeedsVTTParam = CGM.getCXXABI().NeedsVTTParameter(CGF.CurGD);
1466 NeedsVirtualOffset = (NeedsVTTParam && NearestVBase);
Piotr Padlewski525f7462015-08-27 21:35:37 +00001467
Steven Wu5528da72015-08-28 07:14:10 +00001468 llvm::Value *VTableAddressPoint;
1469 if (NeedsVTTParam && (Base.getBase()->getNumVBases() || NearestVBase)) {
1470 // Get the secondary vpointer index.
1471 uint64_t VirtualPointerIndex =
1472 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1473
1474 /// Load the VTT.
1475 llvm::Value *VTT = CGF.LoadCXXVTT();
1476 if (VirtualPointerIndex)
1477 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1478
1479 // And load the address point from the VTT.
John McCall7f416cc2015-09-08 08:05:57 +00001480 VTableAddressPoint = CGF.Builder.CreateAlignedLoad(VTT, CGF.getPointerAlign());
Steven Wu5528da72015-08-28 07:14:10 +00001481 } else {
1482 llvm::Constant *VTable =
1483 CGM.getCXXABI().getAddrOfVTable(VTableClass, CharUnits());
1484 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1485 .getVTableLayout(VTableClass)
1486 .getAddressPoint(Base);
1487 VTableAddressPoint =
1488 CGF.Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
Piotr Padlewski525f7462015-08-27 21:35:37 +00001489 }
Steven Wu5528da72015-08-28 07:14:10 +00001490
1491 return VTableAddressPoint;
Piotr Padlewski525f7462015-08-27 21:35:37 +00001492}
1493
Steven Wu5528da72015-08-28 07:14:10 +00001494llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1495 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1496 auto *VTable = getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001497
1498 // Find the appropriate vtable within the vtable group.
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001499 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1500 .getVTableLayout(VTableClass)
1501 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001502 llvm::Value *Indices[] = {
1503 llvm::ConstantInt::get(CGM.Int64Ty, 0),
1504 llvm::ConstantInt::get(CGM.Int64Ty, AddressPoint)
1505 };
1506
David Blaikiee3b172a2015-04-02 18:55:21 +00001507 return llvm::ConstantExpr::getInBoundsGetElementPtr(VTable->getValueType(),
1508 VTable, Indices);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001509}
1510
1511llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1512 CharUnits VPtrOffset) {
1513 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1514
1515 llvm::GlobalVariable *&VTable = VTables[RD];
1516 if (VTable)
1517 return VTable;
1518
1519 // Queue up this v-table for possible deferred emission.
1520 CGM.addDeferredVTable(RD);
1521
Yaron Kerene46f7ed2015-07-29 14:21:47 +00001522 SmallString<256> Name;
1523 llvm::raw_svector_ostream Out(Name);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001524 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001525
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001526 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001527 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
1528 CGM.Int8PtrTy, VTContext.getVTableLayout(RD).getNumVTableComponents());
1529
1530 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
1531 Name, ArrayType, llvm::GlobalValue::ExternalLinkage);
1532 VTable->setUnnamedAddr(true);
Hans Wennborgda24e9c2014-06-02 23:13:03 +00001533
1534 if (RD->hasAttr<DLLImportAttr>())
1535 VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1536 else if (RD->hasAttr<DLLExportAttr>())
1537 VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1538
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001539 return VTable;
1540}
1541
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001542llvm::Value *ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1543 GlobalDecl GD,
John McCall7f416cc2015-09-08 08:05:57 +00001544 Address This,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001545 llvm::Type *Ty,
1546 SourceLocation Loc) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001547 GD = GD.getCanonicalDecl();
1548 Ty = Ty->getPointerTo()->getPointerTo();
1549 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty);
1550
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00001551 if (CGF.SanOpts.has(SanitizerKind::CFIVCall))
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001552 CGF.EmitVTablePtrCheckForCall(cast<CXXMethodDecl>(GD.getDecl()), VTable,
1553 CodeGenFunction::CFITCK_VCall, Loc);
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001554
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001555 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001556 llvm::Value *VFuncPtr =
1557 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
John McCall7f416cc2015-09-08 08:05:57 +00001558 return CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign());
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001559}
1560
David Majnemer0c0b6d92014-10-31 20:09:12 +00001561llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
1562 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
John McCall7f416cc2015-09-08 08:05:57 +00001563 Address This, const CXXMemberCallExpr *CE) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001564 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001565 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1566
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001567 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1568 Dtor, getFromDtorType(DtorType));
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001569 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001570 llvm::Value *Callee =
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001571 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty,
1572 CE ? CE->getLocStart() : SourceLocation());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001573
John McCall7f416cc2015-09-08 08:05:57 +00001574 CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(),
1575 This.getPointer(), /*ImplicitParam=*/nullptr,
1576 QualType(), CE);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001577 return nullptr;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001578}
1579
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001580void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001581 CodeGenVTables &VTables = CGM.getVTables();
1582 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001583 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001584}
1585
Steven Wu5528da72015-08-28 07:14:10 +00001586bool ItaniumCXXABI::canEmitAvailableExternallyVTable(
1587 const CXXRecordDecl *RD) const {
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001588 // We don't emit available_externally vtables if we are in -fapple-kext mode
1589 // because kext mode does not permit devirtualization.
1590 if (CGM.getLangOpts().AppleKext)
1591 return false;
1592
1593 // If we don't have any inline virtual functions,
1594 // then we are safe to emit available_externally copy of vtable.
1595 // FIXME we can still emit a copy of the vtable if we
1596 // can emit definition of the inline functions.
Piotr Padlewski1d02f682015-08-19 20:09:09 +00001597 return !hasAnyUsedVirtualInlineFunction(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001598}
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001599static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001600 Address InitialPtr,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001601 int64_t NonVirtualAdjustment,
1602 int64_t VirtualAdjustment,
1603 bool IsReturnAdjustment) {
1604 if (!NonVirtualAdjustment && !VirtualAdjustment)
John McCall7f416cc2015-09-08 08:05:57 +00001605 return InitialPtr.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001606
John McCall7f416cc2015-09-08 08:05:57 +00001607 Address V = CGF.Builder.CreateElementBitCast(InitialPtr, CGF.Int8Ty);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001608
John McCall7f416cc2015-09-08 08:05:57 +00001609 // In a base-to-derived cast, the non-virtual adjustment is applied first.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001610 if (NonVirtualAdjustment && !IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001611 V = CGF.Builder.CreateConstInBoundsByteGEP(V,
1612 CharUnits::fromQuantity(NonVirtualAdjustment));
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001613 }
1614
John McCall7f416cc2015-09-08 08:05:57 +00001615 // Perform the virtual adjustment if we have one.
1616 llvm::Value *ResultPtr;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001617 if (VirtualAdjustment) {
1618 llvm::Type *PtrDiffTy =
1619 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1620
John McCall7f416cc2015-09-08 08:05:57 +00001621 Address VTablePtrPtr = CGF.Builder.CreateElementBitCast(V, CGF.Int8PtrTy);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001622 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1623
1624 llvm::Value *OffsetPtr =
1625 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1626
1627 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1628
1629 // Load the adjustment offset from the vtable.
John McCall7f416cc2015-09-08 08:05:57 +00001630 llvm::Value *Offset =
1631 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001632
1633 // Adjust our pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001634 ResultPtr = CGF.Builder.CreateInBoundsGEP(V.getPointer(), Offset);
1635 } else {
1636 ResultPtr = V.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001637 }
1638
John McCall7f416cc2015-09-08 08:05:57 +00001639 // In a derived-to-base conversion, the non-virtual adjustment is
1640 // applied second.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001641 if (NonVirtualAdjustment && IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001642 ResultPtr = CGF.Builder.CreateConstInBoundsGEP1_64(ResultPtr,
1643 NonVirtualAdjustment);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001644 }
1645
1646 // Cast back to the original type.
John McCall7f416cc2015-09-08 08:05:57 +00001647 return CGF.Builder.CreateBitCast(ResultPtr, InitialPtr.getType());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001648}
1649
1650llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001651 Address This,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001652 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001653 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1654 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001655 /*IsReturnAdjustment=*/false);
1656}
1657
1658llvm::Value *
John McCall7f416cc2015-09-08 08:05:57 +00001659ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001660 const ReturnAdjustment &RA) {
1661 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1662 RA.Virtual.Itanium.VBaseOffsetOffset,
1663 /*IsReturnAdjustment=*/true);
1664}
1665
John McCall5d865c322010-08-31 07:33:07 +00001666void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1667 RValue RV, QualType ResultType) {
1668 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1669 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1670
1671 // Destructor thunks in the ARM ABI have indeterminate results.
John McCall7f416cc2015-09-08 08:05:57 +00001672 llvm::Type *T = CGF.ReturnValue.getElementType();
John McCall5d865c322010-08-31 07:33:07 +00001673 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1674 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1675}
John McCall8ed55a52010-09-02 09:58:18 +00001676
1677/************************** Array allocation cookies **************************/
1678
John McCallb91cd662012-05-01 05:23:51 +00001679CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1680 // The array cookie is a size_t; pad that up to the element alignment.
1681 // The cookie is actually right-justified in that space.
1682 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1683 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001684}
1685
John McCall7f416cc2015-09-08 08:05:57 +00001686Address ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1687 Address NewPtr,
1688 llvm::Value *NumElements,
1689 const CXXNewExpr *expr,
1690 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001691 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001692
John McCall7f416cc2015-09-08 08:05:57 +00001693 unsigned AS = NewPtr.getAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001694
John McCall9bca9232010-09-02 10:25:57 +00001695 ASTContext &Ctx = getContext();
John McCall7f416cc2015-09-08 08:05:57 +00001696 CharUnits SizeSize = CGF.getSizeSize();
John McCall8ed55a52010-09-02 09:58:18 +00001697
1698 // The size of the cookie.
1699 CharUnits CookieSize =
1700 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001701 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001702
1703 // Compute an offset to the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001704 Address CookiePtr = NewPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001705 CharUnits CookieOffset = CookieSize - SizeSize;
1706 if (!CookieOffset.isZero())
John McCall7f416cc2015-09-08 08:05:57 +00001707 CookiePtr = CGF.Builder.CreateConstInBoundsByteGEP(CookiePtr, CookieOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001708
1709 // Write the number of elements into the appropriate slot.
John McCall7f416cc2015-09-08 08:05:57 +00001710 Address NumElementsPtr =
1711 CGF.Builder.CreateElementBitCast(CookiePtr, CGF.SizeTy);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001712 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
John McCall7f416cc2015-09-08 08:05:57 +00001713
1714 // Handle the array cookie specially in ASan.
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001715 if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 &&
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001716 expr->getOperatorNew()->isReplaceableGlobalAllocationFunction()) {
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001717 // The store to the CookiePtr does not need to be instrumented.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001718 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
1719 llvm::FunctionType *FTy =
John McCall7f416cc2015-09-08 08:05:57 +00001720 llvm::FunctionType::get(CGM.VoidTy, NumElementsPtr.getType(), false);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001721 llvm::Constant *F =
1722 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001723 CGF.Builder.CreateCall(F, NumElementsPtr.getPointer());
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001724 }
John McCall8ed55a52010-09-02 09:58:18 +00001725
1726 // Finally, compute a pointer to the actual data buffer by skipping
1727 // over the cookie completely.
John McCall7f416cc2015-09-08 08:05:57 +00001728 return CGF.Builder.CreateConstInBoundsByteGEP(NewPtr, CookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001729}
1730
John McCallb91cd662012-05-01 05:23:51 +00001731llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001732 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00001733 CharUnits cookieSize) {
1734 // The element size is right-justified in the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001735 Address numElementsPtr = allocPtr;
1736 CharUnits numElementsOffset = cookieSize - CGF.getSizeSize();
John McCallb91cd662012-05-01 05:23:51 +00001737 if (!numElementsOffset.isZero())
1738 numElementsPtr =
John McCall7f416cc2015-09-08 08:05:57 +00001739 CGF.Builder.CreateConstInBoundsByteGEP(numElementsPtr, numElementsOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001740
John McCall7f416cc2015-09-08 08:05:57 +00001741 unsigned AS = allocPtr.getAddressSpace();
1742 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001743 if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0)
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001744 return CGF.Builder.CreateLoad(numElementsPtr);
1745 // In asan mode emit a function call instead of a regular load and let the
1746 // run-time deal with it: if the shadow is properly poisoned return the
1747 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
1748 // We can't simply ignore this load using nosanitize metadata because
1749 // the metadata may be lost.
1750 llvm::FunctionType *FTy =
1751 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
1752 llvm::Constant *F =
1753 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001754 return CGF.Builder.CreateCall(F, numElementsPtr.getPointer());
John McCall8ed55a52010-09-02 09:58:18 +00001755}
1756
John McCallb91cd662012-05-01 05:23:51 +00001757CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001758 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001759 // struct array_cookie {
1760 // std::size_t element_size; // element_size != 0
1761 // std::size_t element_count;
1762 // };
John McCallc19c7062013-01-25 23:36:19 +00001763 // But the base ABI doesn't give anything an alignment greater than
1764 // 8, so we can dismiss this as typical ABI-author blindness to
1765 // actual language complexity and round up to the element alignment.
1766 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1767 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001768}
1769
John McCall7f416cc2015-09-08 08:05:57 +00001770Address ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1771 Address newPtr,
1772 llvm::Value *numElements,
1773 const CXXNewExpr *expr,
1774 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001775 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001776
John McCall8ed55a52010-09-02 09:58:18 +00001777 // The cookie is always at the start of the buffer.
John McCall7f416cc2015-09-08 08:05:57 +00001778 Address cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001779
1780 // The first element is the element size.
John McCall7f416cc2015-09-08 08:05:57 +00001781 cookie = CGF.Builder.CreateElementBitCast(cookie, CGF.SizeTy);
John McCallc19c7062013-01-25 23:36:19 +00001782 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1783 getContext().getTypeSizeInChars(elementType).getQuantity());
1784 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001785
1786 // The second element is the element count.
John McCall7f416cc2015-09-08 08:05:57 +00001787 cookie = CGF.Builder.CreateConstInBoundsGEP(cookie, 1, CGF.getSizeSize());
John McCallc19c7062013-01-25 23:36:19 +00001788 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001789
1790 // Finally, compute a pointer to the actual data buffer by skipping
1791 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001792 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
John McCall7f416cc2015-09-08 08:05:57 +00001793 return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001794}
1795
John McCallb91cd662012-05-01 05:23:51 +00001796llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001797 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00001798 CharUnits cookieSize) {
1799 // The number of elements is at offset sizeof(size_t) relative to
1800 // the allocated pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001801 Address numElementsPtr
1802 = CGF.Builder.CreateConstInBoundsByteGEP(allocPtr, CGF.getSizeSize());
John McCall8ed55a52010-09-02 09:58:18 +00001803
John McCall7f416cc2015-09-08 08:05:57 +00001804 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
John McCallb91cd662012-05-01 05:23:51 +00001805 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001806}
1807
John McCall68ff0372010-09-08 01:44:27 +00001808/*********************** Static local initialization **************************/
1809
1810static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001811 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001812 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001813 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001814 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001815 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001816 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001817 llvm::AttributeSet::get(CGM.getLLVMContext(),
1818 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001819 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001820}
1821
1822static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001823 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001824 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001825 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001826 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001827 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001828 llvm::AttributeSet::get(CGM.getLLVMContext(),
1829 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001830 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001831}
1832
1833static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001834 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001835 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001836 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001837 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001838 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001839 llvm::AttributeSet::get(CGM.getLLVMContext(),
1840 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001841 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001842}
1843
1844namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001845 struct CallGuardAbort final : EHScopeStack::Cleanup {
John McCall68ff0372010-09-08 01:44:27 +00001846 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001847 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001848
Craig Topper4f12f102014-03-12 06:41:41 +00001849 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00001850 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1851 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001852 }
1853 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001854}
John McCall68ff0372010-09-08 01:44:27 +00001855
1856/// The ARM code here follows the Itanium code closely enough that we
1857/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001858void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1859 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001860 llvm::GlobalVariable *var,
1861 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00001862 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00001863
Richard Smithdbf74ba2013-04-14 23:01:42 +00001864 // We only need to use thread-safe statics for local non-TLS variables;
John McCallcdf7ef52010-11-06 09:44:32 +00001865 // global initialization is always single-threaded.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001866 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
1867 D.isLocalVarDecl() && !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001868
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001869 // If we have a global variable with internal linkage and thread-safe statics
1870 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00001871 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1872
1873 llvm::IntegerType *guardTy;
John McCall7f416cc2015-09-08 08:05:57 +00001874 CharUnits guardAlignment;
John McCall5aa52592011-06-17 07:33:57 +00001875 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00001876 guardTy = CGF.Int8Ty;
John McCall7f416cc2015-09-08 08:05:57 +00001877 guardAlignment = CharUnits::One();
John McCall5aa52592011-06-17 07:33:57 +00001878 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00001879 // Guard variables are 64 bits in the generic ABI and size width on ARM
1880 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
John McCall7f416cc2015-09-08 08:05:57 +00001881 if (UseARMGuardVarABI) {
1882 guardTy = CGF.SizeTy;
1883 guardAlignment = CGF.getSizeAlign();
1884 } else {
1885 guardTy = CGF.Int64Ty;
1886 guardAlignment = CharUnits::fromQuantity(
1887 CGM.getDataLayout().getABITypeAlignment(guardTy));
1888 }
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001889 }
John McCallb88a5662012-03-30 21:00:39 +00001890 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00001891
John McCallb88a5662012-03-30 21:00:39 +00001892 // Create the guard variable if we don't already have it (as we
1893 // might if we're double-emitting this function body).
1894 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1895 if (!guard) {
1896 // Mangle the name for the guard.
1897 SmallString<256> guardName;
1898 {
1899 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00001900 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00001901 }
John McCall8e7cb6d2010-11-02 21:04:24 +00001902
John McCallb88a5662012-03-30 21:00:39 +00001903 // Create the guard variable with a zero-initializer.
1904 // Just absorb linkage and visibility from the guarded variable.
1905 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1906 false, var->getLinkage(),
1907 llvm::ConstantInt::get(guardTy, 0),
1908 guardName.str());
1909 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00001910 // If the variable is thread-local, so is its guard variable.
1911 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCall7f416cc2015-09-08 08:05:57 +00001912 guard->setAlignment(guardAlignment.getQuantity());
John McCallb88a5662012-03-30 21:00:39 +00001913
Yaron Keren5bfa1082015-09-03 20:33:29 +00001914 // The ABI says: "It is suggested that it be emitted in the same COMDAT
1915 // group as the associated data object." In practice, this doesn't work for
1916 // non-ELF object formats, so only do it for ELF.
Rafael Espindola0d4fb982015-01-12 22:13:53 +00001917 llvm::Comdat *C = var->getComdat();
Yaron Keren5bfa1082015-09-03 20:33:29 +00001918 if (!D.isLocalVarDecl() && C &&
1919 CGM.getTarget().getTriple().isOSBinFormatELF()) {
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001920 guard->setComdat(C);
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001921 CGF.CurFn->setComdat(C);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001922 } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) {
1923 guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName()));
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001924 }
1925
John McCallb88a5662012-03-30 21:00:39 +00001926 CGM.setStaticLocalDeclGuardAddress(&D, guard);
1927 }
John McCall87590e62012-03-30 07:09:50 +00001928
John McCall7f416cc2015-09-08 08:05:57 +00001929 Address guardAddr = Address(guard, guardAlignment);
1930
John McCall68ff0372010-09-08 01:44:27 +00001931 // Test whether the variable has completed initialization.
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001932 //
John McCall68ff0372010-09-08 01:44:27 +00001933 // Itanium C++ ABI 3.3.2:
1934 // The following is pseudo-code showing how these functions can be used:
1935 // if (obj_guard.first_byte == 0) {
1936 // if ( __cxa_guard_acquire (&obj_guard) ) {
1937 // try {
1938 // ... initialize the object ...;
1939 // } catch (...) {
1940 // __cxa_guard_abort (&obj_guard);
1941 // throw;
1942 // }
1943 // ... queue object destructor with __cxa_atexit() ...;
1944 // __cxa_guard_release (&obj_guard);
1945 // }
1946 // }
Tim Northovera2ee4332014-03-29 15:09:45 +00001947
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001948 // Load the first byte of the guard variable.
1949 llvm::LoadInst *LI =
John McCall7f416cc2015-09-08 08:05:57 +00001950 Builder.CreateLoad(Builder.CreateElementBitCast(guardAddr, CGM.Int8Ty));
John McCall68ff0372010-09-08 01:44:27 +00001951
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001952 // Itanium ABI:
1953 // An implementation supporting thread-safety on multiprocessor
1954 // systems must also guarantee that references to the initialized
1955 // object do not occur before the load of the initialization flag.
1956 //
1957 // In LLVM, we do this by marking the load Acquire.
1958 if (threadsafe)
1959 LI->setAtomic(llvm::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00001960
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001961 // For ARM, we should only check the first bit, rather than the entire byte:
1962 //
1963 // ARM C++ ABI 3.2.3.1:
1964 // To support the potential use of initialization guard variables
1965 // as semaphores that are the target of ARM SWP and LDREX/STREX
1966 // synchronizing instructions we define a static initialization
1967 // guard variable to be a 4-byte aligned, 4-byte word with the
1968 // following inline access protocol.
1969 // #define INITIALIZED 1
1970 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
1971 // if (__cxa_guard_acquire(&obj_guard))
1972 // ...
1973 // }
1974 //
1975 // and similarly for ARM64:
1976 //
1977 // ARM64 C++ ABI 3.2.2:
1978 // This ABI instead only specifies the value bit 0 of the static guard
1979 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
1980 // variable is not initialized and 1 when it is.
1981 llvm::Value *V =
1982 (UseARMGuardVarABI && !useInt8GuardVariable)
1983 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
1984 : LI;
1985 llvm::Value *isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00001986
1987 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1988 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1989
1990 // Check if the first byte of the guard variable is zero.
John McCallb88a5662012-03-30 21:00:39 +00001991 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall68ff0372010-09-08 01:44:27 +00001992
1993 CGF.EmitBlock(InitCheckBlock);
1994
1995 // Variables used when coping with thread-safe statics and exceptions.
John McCall5aa52592011-06-17 07:33:57 +00001996 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001997 // Call __cxa_guard_acquire.
1998 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00001999 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00002000
2001 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2002
2003 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
2004 InitBlock, EndBlock);
2005
2006 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00002007 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall68ff0372010-09-08 01:44:27 +00002008
2009 CGF.EmitBlock(InitBlock);
2010 }
2011
2012 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00002013 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00002014
John McCall5aa52592011-06-17 07:33:57 +00002015 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002016 // Pop the guard-abort cleanup if we pushed one.
2017 CGF.PopCleanupBlock();
2018
2019 // Call __cxa_guard_release. This cannot throw.
John McCall7f416cc2015-09-08 08:05:57 +00002020 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy),
2021 guardAddr.getPointer());
John McCall68ff0372010-09-08 01:44:27 +00002022 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002023 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guardAddr);
John McCall68ff0372010-09-08 01:44:27 +00002024 }
2025
2026 CGF.EmitBlock(EndBlock);
2027}
John McCallc84ed6a2012-05-01 06:13:13 +00002028
2029/// Register a global destructor using __cxa_atexit.
2030static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
2031 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00002032 llvm::Constant *addr,
2033 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00002034 const char *Name = "__cxa_atexit";
2035 if (TLS) {
2036 const llvm::Triple &T = CGF.getTarget().getTriple();
2037 Name = T.isMacOSX() ? "_tlv_atexit" : "__cxa_thread_atexit";
2038 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00002039
John McCallc84ed6a2012-05-01 06:13:13 +00002040 // We're assuming that the destructor function is something we can
2041 // reasonably call with the default CC. Go ahead and cast it to the
2042 // right prototype.
2043 llvm::Type *dtorTy =
2044 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
2045
2046 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
2047 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
2048 llvm::FunctionType *atexitTy =
2049 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
2050
2051 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002052 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00002053 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
2054 fn->setDoesNotThrow();
2055
2056 // Create a variable that binds the atexit to this shared object.
2057 llvm::Constant *handle =
2058 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
2059
2060 llvm::Value *args[] = {
2061 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
2062 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
2063 handle
2064 };
John McCall882987f2013-02-28 19:01:20 +00002065 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00002066}
2067
2068/// Register a global destructor as best as we know how.
2069void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00002070 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00002071 llvm::Constant *dtor,
2072 llvm::Constant *addr) {
2073 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002074 if (CGM.getCodeGenOpts().CXAAtExit)
2075 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
2076
2077 if (D.getTLSKind())
2078 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00002079
2080 // In Apple kexts, we want to add a global destructor entry.
2081 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00002082 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00002083 // Generate a global destructor entry.
2084 return CGM.AddCXXDtorEntry(dtor, addr);
2085 }
2086
David Blaikieebe87e12013-08-27 23:57:18 +00002087 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00002088}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002089
David Majnemer9b21c332014-07-11 20:28:10 +00002090static bool isThreadWrapperReplaceable(const VarDecl *VD,
2091 CodeGen::CodeGenModule &CGM) {
2092 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
2093 // OS X prefers to have references to thread local variables to go through
2094 // the thread wrapper instead of directly referencing the backing variable.
2095 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
2096 CGM.getTarget().getTriple().isMacOSX();
2097}
2098
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002099/// Get the appropriate linkage for the wrapper function. This is essentially
David Majnemer4632e1e2014-06-27 16:56:27 +00002100/// the weak form of the variable's linkage; every translation unit which needs
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002101/// the wrapper emits a copy, and we want the linker to merge them.
David Majnemer35ab3282014-06-11 04:08:55 +00002102static llvm::GlobalValue::LinkageTypes
2103getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
2104 llvm::GlobalValue::LinkageTypes VarLinkage =
2105 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
2106
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002107 // For internal linkage variables, we don't need an external or weak wrapper.
2108 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
2109 return VarLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00002110
David Majnemer9b21c332014-07-11 20:28:10 +00002111 // If the thread wrapper is replaceable, give it appropriate linkage.
2112 if (isThreadWrapperReplaceable(VD, CGM)) {
2113 if (llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) ||
2114 llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
2115 return llvm::GlobalVariable::WeakAnyLinkage;
2116 return VarLinkage;
2117 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002118 return llvm::GlobalValue::WeakODRLinkage;
2119}
2120
2121llvm::Function *
2122ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +00002123 llvm::Value *Val) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002124 // Mangle the name for the thread_local wrapper function.
2125 SmallString<256> WrapperName;
2126 {
2127 llvm::raw_svector_ostream Out(WrapperName);
2128 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002129 }
2130
Alexander Musmanf94c3182014-09-26 06:28:25 +00002131 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002132 return cast<llvm::Function>(V);
2133
Alexander Musmanf94c3182014-09-26 06:28:25 +00002134 llvm::Type *RetTy = Val->getType();
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002135 if (VD->getType()->isReferenceType())
2136 RetTy = RetTy->getPointerElementType();
2137
2138 llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, false);
David Majnemer35ab3282014-06-11 04:08:55 +00002139 llvm::Function *Wrapper =
2140 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
2141 WrapperName.str(), &CGM.getModule());
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002142 // Always resolve references to the wrapper at link time.
David Majnemer9b21c332014-07-11 20:28:10 +00002143 if (!Wrapper->hasLocalLinkage() && !isThreadWrapperReplaceable(VD, CGM))
Duncan P. N. Exon Smith4434d362014-05-07 22:36:11 +00002144 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002145 return Wrapper;
2146}
2147
2148void ItaniumCXXABI::EmitThreadLocalInitFuncs(
David Majnemerb3341ea2014-10-05 05:05:40 +00002149 CodeGenModule &CGM,
2150 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *>>
2151 CXXThreadLocals, ArrayRef<llvm::Function *> CXXThreadLocalInits,
2152 ArrayRef<llvm::GlobalVariable *> CXXThreadLocalInitVars) {
2153 llvm::Function *InitFunc = nullptr;
2154 if (!CXXThreadLocalInits.empty()) {
2155 // Generate a guarded initialization function.
2156 llvm::FunctionType *FTy =
2157 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
2158 InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init",
Alexey Samsonov1444bb92014-10-17 00:20:19 +00002159 SourceLocation(),
David Majnemerb3341ea2014-10-05 05:05:40 +00002160 /*TLS=*/true);
2161 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
2162 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
2163 llvm::GlobalVariable::InternalLinkage,
2164 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
2165 Guard->setThreadLocal(true);
John McCall7f416cc2015-09-08 08:05:57 +00002166
2167 CharUnits GuardAlign = CharUnits::One();
2168 Guard->setAlignment(GuardAlign.getQuantity());
2169
David Majnemerb3341ea2014-10-05 05:05:40 +00002170 CodeGenFunction(CGM)
John McCall7f416cc2015-09-08 08:05:57 +00002171 .GenerateCXXGlobalInitFunc(InitFunc, CXXThreadLocalInits,
2172 Address(Guard, GuardAlign));
David Majnemerb3341ea2014-10-05 05:05:40 +00002173 }
Yaron Kerenede60302015-08-01 19:11:36 +00002174 for (auto &I : CXXThreadLocals) {
2175 const VarDecl *VD = I.first;
2176 llvm::GlobalVariable *Var = I.second;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002177
David Majnemer9b21c332014-07-11 20:28:10 +00002178 // Some targets require that all access to thread local variables go through
2179 // the thread wrapper. This means that we cannot attempt to create a thread
2180 // wrapper or a thread helper.
2181 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition())
2182 continue;
2183
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002184 // Mangle the name for the thread_local initialization function.
2185 SmallString<256> InitFnName;
2186 {
2187 llvm::raw_svector_ostream Out(InitFnName);
2188 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002189 }
2190
2191 // If we have a definition for the variable, emit the initialization
2192 // function as an alias to the global Init function (if any). Otherwise,
2193 // produce a declaration of the initialization function.
Craig Topper8a13c412014-05-21 05:09:00 +00002194 llvm::GlobalValue *Init = nullptr;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002195 bool InitIsInitFunc = false;
2196 if (VD->hasDefinition()) {
2197 InitIsInitFunc = true;
2198 if (InitFunc)
Rafael Espindola234405b2014-05-17 21:30:14 +00002199 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
2200 InitFunc);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002201 } else {
2202 // Emit a weak global function referring to the initialization function.
2203 // This function will not exist if the TU defining the thread_local
2204 // variable in question does not need any dynamic initialization for
2205 // its thread_local variables.
2206 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
2207 Init = llvm::Function::Create(
2208 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
2209 &CGM.getModule());
2210 }
2211
2212 if (Init)
2213 Init->setVisibility(Var->getVisibility());
2214
2215 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
2216 llvm::LLVMContext &Context = CGM.getModule().getContext();
2217 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
John McCall7f416cc2015-09-08 08:05:57 +00002218 CGBuilderTy Builder(CGM, Entry);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002219 if (InitIsInitFunc) {
2220 if (Init)
David Blaikie4ba525b2015-07-14 17:27:39 +00002221 Builder.CreateCall(Init);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002222 } else {
2223 // Don't know whether we have an init function. Call it if it exists.
2224 llvm::Value *Have = Builder.CreateIsNotNull(Init);
2225 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2226 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2227 Builder.CreateCondBr(Have, InitBB, ExitBB);
2228
2229 Builder.SetInsertPoint(InitBB);
David Blaikie4ba525b2015-07-14 17:27:39 +00002230 Builder.CreateCall(Init);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002231 Builder.CreateBr(ExitBB);
2232
2233 Builder.SetInsertPoint(ExitBB);
2234 }
2235
2236 // For a reference, the result of the wrapper function is a pointer to
2237 // the referenced object.
2238 llvm::Value *Val = Var;
2239 if (VD->getType()->isReferenceType()) {
John McCall7f416cc2015-09-08 08:05:57 +00002240 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2241 Val = Builder.CreateAlignedLoad(Val, Align);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002242 }
Alexander Musmanf94c3182014-09-26 06:28:25 +00002243 if (Val->getType() != Wrapper->getReturnType())
2244 Val = Builder.CreatePointerBitCastOrAddrSpaceCast(
2245 Val, Wrapper->getReturnType(), "");
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002246 Builder.CreateRet(Val);
2247 }
2248}
2249
Richard Smith0f383742014-03-26 22:48:22 +00002250LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2251 const VarDecl *VD,
2252 QualType LValType) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002253 QualType T = VD->getType();
2254 llvm::Type *Ty = CGF.getTypes().ConvertTypeForMem(T);
2255 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD, Ty);
Alexander Musmanf94c3182014-09-26 06:28:25 +00002256 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002257
David Blaikie4ba525b2015-07-14 17:27:39 +00002258 Val = CGF.Builder.CreateCall(Wrapper);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002259
2260 LValue LV;
2261 if (VD->getType()->isReferenceType())
Richard Smith0f383742014-03-26 22:48:22 +00002262 LV = CGF.MakeNaturalAlignAddrLValue(Val, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002263 else
Richard Smith0f383742014-03-26 22:48:22 +00002264 LV = CGF.MakeAddrLValue(Val, LValType, CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002265 // FIXME: need setObjCGCLValueClass?
2266 return LV;
2267}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002268
2269/// Return whether the given global decl needs a VTT parameter, which it does
2270/// if it's a base constructor or destructor with virtual bases.
2271bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
2272 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
2273
2274 // We don't have any virtual bases, just return early.
2275 if (!MD->getParent()->getNumVBases())
2276 return false;
2277
2278 // Check if we have a base constructor.
2279 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
2280 return true;
2281
2282 // Check if we have a base destructor.
2283 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2284 return true;
2285
2286 return false;
2287}
David Majnemere2cb8d12014-07-07 06:20:47 +00002288
2289namespace {
2290class ItaniumRTTIBuilder {
2291 CodeGenModule &CGM; // Per-module state.
2292 llvm::LLVMContext &VMContext;
2293 const ItaniumCXXABI &CXXABI; // Per-module state.
2294
2295 /// Fields - The fields of the RTTI descriptor currently being built.
2296 SmallVector<llvm::Constant *, 16> Fields;
2297
2298 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2299 llvm::GlobalVariable *
2300 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2301
2302 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2303 /// descriptor of the given type.
2304 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2305
2306 /// BuildVTablePointer - Build the vtable pointer for the given type.
2307 void BuildVTablePointer(const Type *Ty);
2308
2309 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2310 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2311 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2312
2313 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2314 /// classes with bases that do not satisfy the abi::__si_class_type_info
2315 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2316 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2317
2318 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2319 /// for pointer types.
2320 void BuildPointerTypeInfo(QualType PointeeTy);
2321
2322 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2323 /// type_info for an object type.
2324 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2325
2326 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2327 /// struct, used for member pointer types.
2328 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2329
2330public:
2331 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2332 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2333
2334 // Pointer type info flags.
2335 enum {
2336 /// PTI_Const - Type has const qualifier.
2337 PTI_Const = 0x1,
2338
2339 /// PTI_Volatile - Type has volatile qualifier.
2340 PTI_Volatile = 0x2,
2341
2342 /// PTI_Restrict - Type has restrict qualifier.
2343 PTI_Restrict = 0x4,
2344
2345 /// PTI_Incomplete - Type is incomplete.
2346 PTI_Incomplete = 0x8,
2347
2348 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2349 /// (in pointer to member).
2350 PTI_ContainingClassIncomplete = 0x10
2351 };
2352
2353 // VMI type info flags.
2354 enum {
2355 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2356 VMI_NonDiamondRepeat = 0x1,
2357
2358 /// VMI_DiamondShaped - Class is diamond shaped.
2359 VMI_DiamondShaped = 0x2
2360 };
2361
2362 // Base class type info flags.
2363 enum {
2364 /// BCTI_Virtual - Base class is virtual.
2365 BCTI_Virtual = 0x1,
2366
2367 /// BCTI_Public - Base class is public.
2368 BCTI_Public = 0x2
2369 };
2370
2371 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
2372 ///
2373 /// \param Force - true to force the creation of this RTTI value
2374 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false);
2375};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002376}
David Majnemere2cb8d12014-07-07 06:20:47 +00002377
2378llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2379 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002380 SmallString<256> Name;
2381 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002382 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002383
2384 // We know that the mangled name of the type starts at index 4 of the
2385 // mangled name of the typename, so we can just index into it in order to
2386 // get the mangled name of the type.
2387 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2388 Name.substr(4));
2389
2390 llvm::GlobalVariable *GV =
2391 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
2392
2393 GV->setInitializer(Init);
2394
2395 return GV;
2396}
2397
2398llvm::Constant *
2399ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2400 // Mangle the RTTI name.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002401 SmallString<256> Name;
2402 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002403 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002404
2405 // Look for an existing global.
2406 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2407
2408 if (!GV) {
2409 // Create a new global variable.
2410 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2411 /*Constant=*/true,
2412 llvm::GlobalValue::ExternalLinkage, nullptr,
2413 Name);
David Majnemer1fb1a042014-11-07 07:26:38 +00002414 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2415 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2416 if (RD->hasAttr<DLLImportAttr>())
2417 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2418 }
David Majnemere2cb8d12014-07-07 06:20:47 +00002419 }
2420
2421 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2422}
2423
2424/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2425/// info for that type is defined in the standard library.
2426static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2427 // Itanium C++ ABI 2.9.2:
2428 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
2429 // the run-time support library. Specifically, the run-time support
2430 // library should contain type_info objects for the types X, X* and
2431 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2432 // unsigned char, signed char, short, unsigned short, int, unsigned int,
2433 // long, unsigned long, long long, unsigned long long, float, double,
2434 // long double, char16_t, char32_t, and the IEEE 754r decimal and
2435 // half-precision floating point types.
2436 switch (Ty->getKind()) {
2437 case BuiltinType::Void:
2438 case BuiltinType::NullPtr:
2439 case BuiltinType::Bool:
2440 case BuiltinType::WChar_S:
2441 case BuiltinType::WChar_U:
2442 case BuiltinType::Char_U:
2443 case BuiltinType::Char_S:
2444 case BuiltinType::UChar:
2445 case BuiltinType::SChar:
2446 case BuiltinType::Short:
2447 case BuiltinType::UShort:
2448 case BuiltinType::Int:
2449 case BuiltinType::UInt:
2450 case BuiltinType::Long:
2451 case BuiltinType::ULong:
2452 case BuiltinType::LongLong:
2453 case BuiltinType::ULongLong:
2454 case BuiltinType::Half:
2455 case BuiltinType::Float:
2456 case BuiltinType::Double:
2457 case BuiltinType::LongDouble:
2458 case BuiltinType::Char16:
2459 case BuiltinType::Char32:
2460 case BuiltinType::Int128:
2461 case BuiltinType::UInt128:
2462 case BuiltinType::OCLImage1d:
2463 case BuiltinType::OCLImage1dArray:
2464 case BuiltinType::OCLImage1dBuffer:
2465 case BuiltinType::OCLImage2d:
2466 case BuiltinType::OCLImage2dArray:
2467 case BuiltinType::OCLImage3d:
2468 case BuiltinType::OCLSampler:
2469 case BuiltinType::OCLEvent:
2470 return true;
2471
2472 case BuiltinType::Dependent:
2473#define BUILTIN_TYPE(Id, SingletonId)
2474#define PLACEHOLDER_TYPE(Id, SingletonId) \
2475 case BuiltinType::Id:
2476#include "clang/AST/BuiltinTypes.def"
2477 llvm_unreachable("asking for RRTI for a placeholder type!");
2478
2479 case BuiltinType::ObjCId:
2480 case BuiltinType::ObjCClass:
2481 case BuiltinType::ObjCSel:
2482 llvm_unreachable("FIXME: Objective-C types are unsupported!");
2483 }
2484
2485 llvm_unreachable("Invalid BuiltinType Kind!");
2486}
2487
2488static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2489 QualType PointeeTy = PointerTy->getPointeeType();
2490 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2491 if (!BuiltinTy)
2492 return false;
2493
2494 // Check the qualifiers.
2495 Qualifiers Quals = PointeeTy.getQualifiers();
2496 Quals.removeConst();
2497
2498 if (!Quals.empty())
2499 return false;
2500
2501 return TypeInfoIsInStandardLibrary(BuiltinTy);
2502}
2503
2504/// IsStandardLibraryRTTIDescriptor - Returns whether the type
2505/// information for the given type exists in the standard library.
2506static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2507 // Type info for builtin types is defined in the standard library.
2508 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2509 return TypeInfoIsInStandardLibrary(BuiltinTy);
2510
2511 // Type info for some pointer types to builtin types is defined in the
2512 // standard library.
2513 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2514 return TypeInfoIsInStandardLibrary(PointerTy);
2515
2516 return false;
2517}
2518
2519/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
2520/// the given type exists somewhere else, and that we should not emit the type
2521/// information in this translation unit. Assumes that it is not a
2522/// standard-library type.
2523static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
2524 QualType Ty) {
2525 ASTContext &Context = CGM.getContext();
2526
2527 // If RTTI is disabled, assume it might be disabled in the
2528 // translation unit that defines any potential key function, too.
2529 if (!Context.getLangOpts().RTTI) return false;
2530
2531 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2532 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2533 if (!RD->hasDefinition())
2534 return false;
2535
2536 if (!RD->isDynamicClass())
2537 return false;
2538
2539 // FIXME: this may need to be reconsidered if the key function
2540 // changes.
David Majnemerbe9022c2015-08-06 20:56:55 +00002541 // N.B. We must always emit the RTTI data ourselves if there exists a key
2542 // function.
2543 bool IsDLLImport = RD->hasAttr<DLLImportAttr>();
David Majnemer1fb1a042014-11-07 07:26:38 +00002544 if (CGM.getVTables().isVTableExternal(RD))
David Majnemerbe9022c2015-08-06 20:56:55 +00002545 return IsDLLImport ? false : true;
David Majnemer1fb1a042014-11-07 07:26:38 +00002546
David Majnemerbe9022c2015-08-06 20:56:55 +00002547 if (IsDLLImport)
David Majnemer1fb1a042014-11-07 07:26:38 +00002548 return true;
David Majnemere2cb8d12014-07-07 06:20:47 +00002549 }
2550
2551 return false;
2552}
2553
2554/// IsIncompleteClassType - Returns whether the given record type is incomplete.
2555static bool IsIncompleteClassType(const RecordType *RecordTy) {
2556 return !RecordTy->getDecl()->isCompleteDefinition();
2557}
2558
2559/// ContainsIncompleteClassType - Returns whether the given type contains an
2560/// incomplete class type. This is true if
2561///
2562/// * The given type is an incomplete class type.
2563/// * The given type is a pointer type whose pointee type contains an
2564/// incomplete class type.
2565/// * The given type is a member pointer type whose class is an incomplete
2566/// class type.
2567/// * The given type is a member pointer type whoise pointee type contains an
2568/// incomplete class type.
2569/// is an indirect or direct pointer to an incomplete class type.
2570static bool ContainsIncompleteClassType(QualType Ty) {
2571 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2572 if (IsIncompleteClassType(RecordTy))
2573 return true;
2574 }
2575
2576 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2577 return ContainsIncompleteClassType(PointerTy->getPointeeType());
2578
2579 if (const MemberPointerType *MemberPointerTy =
2580 dyn_cast<MemberPointerType>(Ty)) {
2581 // Check if the class type is incomplete.
2582 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
2583 if (IsIncompleteClassType(ClassType))
2584 return true;
2585
2586 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
2587 }
2588
2589 return false;
2590}
2591
2592// CanUseSingleInheritance - Return whether the given record decl has a "single,
2593// public, non-virtual base at offset zero (i.e. the derived class is dynamic
2594// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
2595static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
2596 // Check the number of bases.
2597 if (RD->getNumBases() != 1)
2598 return false;
2599
2600 // Get the base.
2601 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
2602
2603 // Check that the base is not virtual.
2604 if (Base->isVirtual())
2605 return false;
2606
2607 // Check that the base is public.
2608 if (Base->getAccessSpecifier() != AS_public)
2609 return false;
2610
2611 // Check that the class is dynamic iff the base is.
2612 const CXXRecordDecl *BaseDecl =
2613 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2614 if (!BaseDecl->isEmpty() &&
2615 BaseDecl->isDynamicClass() != RD->isDynamicClass())
2616 return false;
2617
2618 return true;
2619}
2620
2621void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
2622 // abi::__class_type_info.
2623 static const char * const ClassTypeInfo =
2624 "_ZTVN10__cxxabiv117__class_type_infoE";
2625 // abi::__si_class_type_info.
2626 static const char * const SIClassTypeInfo =
2627 "_ZTVN10__cxxabiv120__si_class_type_infoE";
2628 // abi::__vmi_class_type_info.
2629 static const char * const VMIClassTypeInfo =
2630 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
2631
2632 const char *VTableName = nullptr;
2633
2634 switch (Ty->getTypeClass()) {
2635#define TYPE(Class, Base)
2636#define ABSTRACT_TYPE(Class, Base)
2637#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2638#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2639#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2640#include "clang/AST/TypeNodes.def"
2641 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2642
2643 case Type::LValueReference:
2644 case Type::RValueReference:
2645 llvm_unreachable("References shouldn't get here");
2646
2647 case Type::Auto:
2648 llvm_unreachable("Undeduced auto type shouldn't get here");
2649
2650 case Type::Builtin:
2651 // GCC treats vector and complex types as fundamental types.
2652 case Type::Vector:
2653 case Type::ExtVector:
2654 case Type::Complex:
2655 case Type::Atomic:
2656 // FIXME: GCC treats block pointers as fundamental types?!
2657 case Type::BlockPointer:
2658 // abi::__fundamental_type_info.
2659 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
2660 break;
2661
2662 case Type::ConstantArray:
2663 case Type::IncompleteArray:
2664 case Type::VariableArray:
2665 // abi::__array_type_info.
2666 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
2667 break;
2668
2669 case Type::FunctionNoProto:
2670 case Type::FunctionProto:
2671 // abi::__function_type_info.
2672 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
2673 break;
2674
2675 case Type::Enum:
2676 // abi::__enum_type_info.
2677 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
2678 break;
2679
2680 case Type::Record: {
2681 const CXXRecordDecl *RD =
2682 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2683
2684 if (!RD->hasDefinition() || !RD->getNumBases()) {
2685 VTableName = ClassTypeInfo;
2686 } else if (CanUseSingleInheritance(RD)) {
2687 VTableName = SIClassTypeInfo;
2688 } else {
2689 VTableName = VMIClassTypeInfo;
2690 }
2691
2692 break;
2693 }
2694
2695 case Type::ObjCObject:
2696 // Ignore protocol qualifiers.
2697 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
2698
2699 // Handle id and Class.
2700 if (isa<BuiltinType>(Ty)) {
2701 VTableName = ClassTypeInfo;
2702 break;
2703 }
2704
2705 assert(isa<ObjCInterfaceType>(Ty));
2706 // Fall through.
2707
2708 case Type::ObjCInterface:
2709 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
2710 VTableName = SIClassTypeInfo;
2711 } else {
2712 VTableName = ClassTypeInfo;
2713 }
2714 break;
2715
2716 case Type::ObjCObjectPointer:
2717 case Type::Pointer:
2718 // abi::__pointer_type_info.
2719 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
2720 break;
2721
2722 case Type::MemberPointer:
2723 // abi::__pointer_to_member_type_info.
2724 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
2725 break;
2726 }
2727
2728 llvm::Constant *VTable =
2729 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
2730
2731 llvm::Type *PtrDiffTy =
2732 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
2733
2734 // The vtable address point is 2.
2735 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00002736 VTable =
2737 llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.Int8PtrTy, VTable, Two);
David Majnemere2cb8d12014-07-07 06:20:47 +00002738 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
2739
2740 Fields.push_back(VTable);
2741}
2742
2743/// \brief Return the linkage that the type info and type info name constants
2744/// should have for the given type.
2745static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
2746 QualType Ty) {
2747 // Itanium C++ ABI 2.9.5p7:
2748 // In addition, it and all of the intermediate abi::__pointer_type_info
2749 // structs in the chain down to the abi::__class_type_info for the
2750 // incomplete class type must be prevented from resolving to the
2751 // corresponding type_info structs for the complete class type, possibly
2752 // by making them local static objects. Finally, a dummy class RTTI is
2753 // generated for the incomplete type that will not resolve to the final
2754 // complete class RTTI (because the latter need not exist), possibly by
2755 // making it a local static object.
2756 if (ContainsIncompleteClassType(Ty))
2757 return llvm::GlobalValue::InternalLinkage;
2758
2759 switch (Ty->getLinkage()) {
2760 case NoLinkage:
2761 case InternalLinkage:
2762 case UniqueExternalLinkage:
2763 return llvm::GlobalValue::InternalLinkage;
2764
2765 case VisibleNoLinkage:
2766 case ExternalLinkage:
2767 if (!CGM.getLangOpts().RTTI) {
2768 // RTTI is not enabled, which means that this type info struct is going
2769 // to be used for exception handling. Give it linkonce_odr linkage.
2770 return llvm::GlobalValue::LinkOnceODRLinkage;
2771 }
2772
2773 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
2774 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2775 if (RD->hasAttr<WeakAttr>())
2776 return llvm::GlobalValue::WeakODRLinkage;
David Majnemerbe9022c2015-08-06 20:56:55 +00002777 if (RD->isDynamicClass()) {
2778 llvm::GlobalValue::LinkageTypes LT = CGM.getVTableLinkage(RD);
2779 // MinGW won't export the RTTI information when there is a key function.
2780 // Make sure we emit our own copy instead of attempting to dllimport it.
2781 if (RD->hasAttr<DLLImportAttr>() &&
2782 llvm::GlobalValue::isAvailableExternallyLinkage(LT))
2783 LT = llvm::GlobalValue::LinkOnceODRLinkage;
2784 return LT;
2785 }
David Majnemere2cb8d12014-07-07 06:20:47 +00002786 }
2787
2788 return llvm::GlobalValue::LinkOnceODRLinkage;
2789 }
2790
2791 llvm_unreachable("Invalid linkage!");
2792}
2793
2794llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force) {
2795 // We want to operate on the canonical type.
2796 Ty = CGM.getContext().getCanonicalType(Ty);
2797
2798 // Check if we've already emitted an RTTI descriptor for this type.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002799 SmallString<256> Name;
2800 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002801 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002802
2803 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
2804 if (OldGV && !OldGV->isDeclaration()) {
2805 assert(!OldGV->hasAvailableExternallyLinkage() &&
2806 "available_externally typeinfos not yet implemented");
2807
2808 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
2809 }
2810
2811 // Check if there is already an external RTTI descriptor for this type.
2812 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
2813 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
2814 return GetAddrOfExternalRTTIDescriptor(Ty);
2815
2816 // Emit the standard library with external linkage.
2817 llvm::GlobalVariable::LinkageTypes Linkage;
2818 if (IsStdLib)
2819 Linkage = llvm::GlobalValue::ExternalLinkage;
2820 else
2821 Linkage = getTypeInfoLinkage(CGM, Ty);
2822
2823 // Add the vtable pointer.
2824 BuildVTablePointer(cast<Type>(Ty));
2825
2826 // And the name.
2827 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
2828 llvm::Constant *TypeNameField;
2829
2830 // If we're supposed to demote the visibility, be sure to set a flag
2831 // to use a string comparison for type_info comparisons.
2832 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
2833 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
2834 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
2835 // The flag is the sign bit, which on ARM64 is defined to be clear
2836 // for global pointers. This is very ARM64-specific.
2837 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
2838 llvm::Constant *flag =
2839 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
2840 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
2841 TypeNameField =
2842 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
2843 } else {
2844 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
2845 }
2846 Fields.push_back(TypeNameField);
2847
2848 switch (Ty->getTypeClass()) {
2849#define TYPE(Class, Base)
2850#define ABSTRACT_TYPE(Class, Base)
2851#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2852#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2853#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2854#include "clang/AST/TypeNodes.def"
2855 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2856
2857 // GCC treats vector types as fundamental types.
2858 case Type::Builtin:
2859 case Type::Vector:
2860 case Type::ExtVector:
2861 case Type::Complex:
2862 case Type::BlockPointer:
2863 // Itanium C++ ABI 2.9.5p4:
2864 // abi::__fundamental_type_info adds no data members to std::type_info.
2865 break;
2866
2867 case Type::LValueReference:
2868 case Type::RValueReference:
2869 llvm_unreachable("References shouldn't get here");
2870
2871 case Type::Auto:
2872 llvm_unreachable("Undeduced auto type shouldn't get here");
2873
2874 case Type::ConstantArray:
2875 case Type::IncompleteArray:
2876 case Type::VariableArray:
2877 // Itanium C++ ABI 2.9.5p5:
2878 // abi::__array_type_info adds no data members to std::type_info.
2879 break;
2880
2881 case Type::FunctionNoProto:
2882 case Type::FunctionProto:
2883 // Itanium C++ ABI 2.9.5p5:
2884 // abi::__function_type_info adds no data members to std::type_info.
2885 break;
2886
2887 case Type::Enum:
2888 // Itanium C++ ABI 2.9.5p5:
2889 // abi::__enum_type_info adds no data members to std::type_info.
2890 break;
2891
2892 case Type::Record: {
2893 const CXXRecordDecl *RD =
2894 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2895 if (!RD->hasDefinition() || !RD->getNumBases()) {
2896 // We don't need to emit any fields.
2897 break;
2898 }
2899
2900 if (CanUseSingleInheritance(RD))
2901 BuildSIClassTypeInfo(RD);
2902 else
2903 BuildVMIClassTypeInfo(RD);
2904
2905 break;
2906 }
2907
2908 case Type::ObjCObject:
2909 case Type::ObjCInterface:
2910 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
2911 break;
2912
2913 case Type::ObjCObjectPointer:
2914 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
2915 break;
2916
2917 case Type::Pointer:
2918 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
2919 break;
2920
2921 case Type::MemberPointer:
2922 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
2923 break;
2924
2925 case Type::Atomic:
2926 // No fields, at least for the moment.
2927 break;
2928 }
2929
2930 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
2931
Rafael Espindolacb92c192015-01-15 23:18:01 +00002932 llvm::Module &M = CGM.getModule();
David Majnemere2cb8d12014-07-07 06:20:47 +00002933 llvm::GlobalVariable *GV =
Rafael Espindolacb92c192015-01-15 23:18:01 +00002934 new llvm::GlobalVariable(M, Init->getType(),
2935 /*Constant=*/true, Linkage, Init, Name);
2936
David Majnemere2cb8d12014-07-07 06:20:47 +00002937 // If there's already an old global variable, replace it with the new one.
2938 if (OldGV) {
2939 GV->takeName(OldGV);
2940 llvm::Constant *NewPtr =
2941 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2942 OldGV->replaceAllUsesWith(NewPtr);
2943 OldGV->eraseFromParent();
2944 }
2945
Yaron Keren04da2382015-07-29 15:42:28 +00002946 if (CGM.supportsCOMDAT() && GV->isWeakForLinker())
2947 GV->setComdat(M.getOrInsertComdat(GV->getName()));
2948
David Majnemere2cb8d12014-07-07 06:20:47 +00002949 // The Itanium ABI specifies that type_info objects must be globally
2950 // unique, with one exception: if the type is an incomplete class
2951 // type or a (possibly indirect) pointer to one. That exception
2952 // affects the general case of comparing type_info objects produced
2953 // by the typeid operator, which is why the comparison operators on
2954 // std::type_info generally use the type_info name pointers instead
2955 // of the object addresses. However, the language's built-in uses
2956 // of RTTI generally require class types to be complete, even when
2957 // manipulating pointers to those class types. This allows the
2958 // implementation of dynamic_cast to rely on address equality tests,
2959 // which is much faster.
2960
2961 // All of this is to say that it's important that both the type_info
2962 // object and the type_info name be uniqued when weakly emitted.
2963
2964 // Give the type_info object and name the formal visibility of the
2965 // type itself.
2966 llvm::GlobalValue::VisibilityTypes llvmVisibility;
2967 if (llvm::GlobalValue::isLocalLinkage(Linkage))
2968 // If the linkage is local, only default visibility makes sense.
2969 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
2970 else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden)
2971 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
2972 else
2973 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
2974 TypeName->setVisibility(llvmVisibility);
2975 GV->setVisibility(llvmVisibility);
2976
2977 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2978}
2979
2980/// ComputeQualifierFlags - Compute the pointer type info flags from the
2981/// given qualifier.
2982static unsigned ComputeQualifierFlags(Qualifiers Quals) {
2983 unsigned Flags = 0;
2984
2985 if (Quals.hasConst())
2986 Flags |= ItaniumRTTIBuilder::PTI_Const;
2987 if (Quals.hasVolatile())
2988 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
2989 if (Quals.hasRestrict())
2990 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
2991
2992 return Flags;
2993}
2994
2995/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
2996/// for the given Objective-C object type.
2997void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
2998 // Drop qualifiers.
2999 const Type *T = OT->getBaseType().getTypePtr();
3000 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
3001
3002 // The builtin types are abi::__class_type_infos and don't require
3003 // extra fields.
3004 if (isa<BuiltinType>(T)) return;
3005
3006 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
3007 ObjCInterfaceDecl *Super = Class->getSuperClass();
3008
3009 // Root classes are also __class_type_info.
3010 if (!Super) return;
3011
3012 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
3013
3014 // Everything else is single inheritance.
3015 llvm::Constant *BaseTypeInfo =
3016 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
3017 Fields.push_back(BaseTypeInfo);
3018}
3019
3020/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
3021/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
3022void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
3023 // Itanium C++ ABI 2.9.5p6b:
3024 // It adds to abi::__class_type_info a single member pointing to the
3025 // type_info structure for the base type,
3026 llvm::Constant *BaseTypeInfo =
3027 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
3028 Fields.push_back(BaseTypeInfo);
3029}
3030
3031namespace {
3032 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
3033 /// a class hierarchy.
3034 struct SeenBases {
3035 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
3036 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
3037 };
3038}
3039
3040/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
3041/// abi::__vmi_class_type_info.
3042///
3043static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
3044 SeenBases &Bases) {
3045
3046 unsigned Flags = 0;
3047
3048 const CXXRecordDecl *BaseDecl =
3049 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
3050
3051 if (Base->isVirtual()) {
3052 // Mark the virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003053 if (!Bases.VirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003054 // If this virtual base has been seen before, then the class is diamond
3055 // shaped.
3056 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
3057 } else {
3058 if (Bases.NonVirtualBases.count(BaseDecl))
3059 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3060 }
3061 } else {
3062 // Mark the non-virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003063 if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003064 // If this non-virtual base has been seen before, then the class has non-
3065 // diamond shaped repeated inheritance.
3066 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3067 } else {
3068 if (Bases.VirtualBases.count(BaseDecl))
3069 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3070 }
3071 }
3072
3073 // Walk all bases.
3074 for (const auto &I : BaseDecl->bases())
3075 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3076
3077 return Flags;
3078}
3079
3080static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
3081 unsigned Flags = 0;
3082 SeenBases Bases;
3083
3084 // Walk all bases.
3085 for (const auto &I : RD->bases())
3086 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3087
3088 return Flags;
3089}
3090
3091/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
3092/// classes with bases that do not satisfy the abi::__si_class_type_info
3093/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
3094void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
3095 llvm::Type *UnsignedIntLTy =
3096 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3097
3098 // Itanium C++ ABI 2.9.5p6c:
3099 // __flags is a word with flags describing details about the class
3100 // structure, which may be referenced by using the __flags_masks
3101 // enumeration. These flags refer to both direct and indirect bases.
3102 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
3103 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3104
3105 // Itanium C++ ABI 2.9.5p6c:
3106 // __base_count is a word with the number of direct proper base class
3107 // descriptions that follow.
3108 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
3109
3110 if (!RD->getNumBases())
3111 return;
3112
3113 llvm::Type *LongLTy =
3114 CGM.getTypes().ConvertType(CGM.getContext().LongTy);
3115
3116 // Now add the base class descriptions.
3117
3118 // Itanium C++ ABI 2.9.5p6c:
3119 // __base_info[] is an array of base class descriptions -- one for every
3120 // direct proper base. Each description is of the type:
3121 //
3122 // struct abi::__base_class_type_info {
3123 // public:
3124 // const __class_type_info *__base_type;
3125 // long __offset_flags;
3126 //
3127 // enum __offset_flags_masks {
3128 // __virtual_mask = 0x1,
3129 // __public_mask = 0x2,
3130 // __offset_shift = 8
3131 // };
3132 // };
3133 for (const auto &Base : RD->bases()) {
3134 // The __base_type member points to the RTTI for the base type.
3135 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
3136
3137 const CXXRecordDecl *BaseDecl =
3138 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
3139
3140 int64_t OffsetFlags = 0;
3141
3142 // All but the lower 8 bits of __offset_flags are a signed offset.
3143 // For a non-virtual base, this is the offset in the object of the base
3144 // subobject. For a virtual base, this is the offset in the virtual table of
3145 // the virtual base offset for the virtual base referenced (negative).
3146 CharUnits Offset;
3147 if (Base.isVirtual())
3148 Offset =
3149 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
3150 else {
3151 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
3152 Offset = Layout.getBaseClassOffset(BaseDecl);
3153 };
3154
3155 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
3156
3157 // The low-order byte of __offset_flags contains flags, as given by the
3158 // masks from the enumeration __offset_flags_masks.
3159 if (Base.isVirtual())
3160 OffsetFlags |= BCTI_Virtual;
3161 if (Base.getAccessSpecifier() == AS_public)
3162 OffsetFlags |= BCTI_Public;
3163
3164 Fields.push_back(llvm::ConstantInt::get(LongLTy, OffsetFlags));
3165 }
3166}
3167
3168/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
3169/// used for pointer types.
3170void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
3171 Qualifiers Quals;
3172 QualType UnqualifiedPointeeTy =
3173 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
3174
3175 // Itanium C++ ABI 2.9.5p7:
3176 // __flags is a flag word describing the cv-qualification and other
3177 // attributes of the type pointed to
3178 unsigned Flags = ComputeQualifierFlags(Quals);
3179
3180 // Itanium C++ ABI 2.9.5p7:
3181 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3182 // incomplete class type, the incomplete target type flag is set.
3183 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
3184 Flags |= PTI_Incomplete;
3185
3186 llvm::Type *UnsignedIntLTy =
3187 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3188 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3189
3190 // Itanium C++ ABI 2.9.5p7:
3191 // __pointee is a pointer to the std::type_info derivation for the
3192 // unqualified type being pointed to.
3193 llvm::Constant *PointeeTypeInfo =
3194 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
3195 Fields.push_back(PointeeTypeInfo);
3196}
3197
3198/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
3199/// struct, used for member pointer types.
3200void
3201ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
3202 QualType PointeeTy = Ty->getPointeeType();
3203
3204 Qualifiers Quals;
3205 QualType UnqualifiedPointeeTy =
3206 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
3207
3208 // Itanium C++ ABI 2.9.5p7:
3209 // __flags is a flag word describing the cv-qualification and other
3210 // attributes of the type pointed to.
3211 unsigned Flags = ComputeQualifierFlags(Quals);
3212
3213 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
3214
3215 // Itanium C++ ABI 2.9.5p7:
3216 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3217 // incomplete class type, the incomplete target type flag is set.
3218 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
3219 Flags |= PTI_Incomplete;
3220
3221 if (IsIncompleteClassType(ClassType))
3222 Flags |= PTI_ContainingClassIncomplete;
3223
3224 llvm::Type *UnsignedIntLTy =
3225 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3226 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3227
3228 // Itanium C++ ABI 2.9.5p7:
3229 // __pointee is a pointer to the std::type_info derivation for the
3230 // unqualified type being pointed to.
3231 llvm::Constant *PointeeTypeInfo =
3232 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
3233 Fields.push_back(PointeeTypeInfo);
3234
3235 // Itanium C++ ABI 2.9.5p9:
3236 // __context is a pointer to an abi::__class_type_info corresponding to the
3237 // class type containing the member pointed to
3238 // (e.g., the "A" in "int A::*").
3239 Fields.push_back(
3240 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
3241}
3242
David Majnemer443250f2015-03-17 20:35:00 +00003243llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003244 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
3245}
3246
3247void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type) {
3248 QualType PointerType = getContext().getPointerType(Type);
3249 QualType PointerTypeConst = getContext().getPointerType(Type.withConst());
3250 ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, true);
3251 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, true);
3252 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, true);
3253}
3254
3255void ItaniumCXXABI::EmitFundamentalRTTIDescriptors() {
3256 QualType FundamentalTypes[] = {
3257 getContext().VoidTy, getContext().NullPtrTy,
3258 getContext().BoolTy, getContext().WCharTy,
3259 getContext().CharTy, getContext().UnsignedCharTy,
3260 getContext().SignedCharTy, getContext().ShortTy,
3261 getContext().UnsignedShortTy, getContext().IntTy,
3262 getContext().UnsignedIntTy, getContext().LongTy,
3263 getContext().UnsignedLongTy, getContext().LongLongTy,
3264 getContext().UnsignedLongLongTy, getContext().HalfTy,
3265 getContext().FloatTy, getContext().DoubleTy,
3266 getContext().LongDoubleTy, getContext().Char16Ty,
3267 getContext().Char32Ty,
3268 };
3269 for (const QualType &FundamentalType : FundamentalTypes)
3270 EmitFundamentalRTTIDescriptor(FundamentalType);
3271}
3272
3273/// What sort of uniqueness rules should we use for the RTTI for the
3274/// given type?
3275ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
3276 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
3277 if (shouldRTTIBeUnique())
3278 return RUK_Unique;
3279
3280 // It's only necessary for linkonce_odr or weak_odr linkage.
3281 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
3282 Linkage != llvm::GlobalValue::WeakODRLinkage)
3283 return RUK_Unique;
3284
3285 // It's only necessary with default visibility.
3286 if (CanTy->getVisibility() != DefaultVisibility)
3287 return RUK_Unique;
3288
3289 // If we're not required to publish this symbol, hide it.
3290 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3291 return RUK_NonUniqueHidden;
3292
3293 // If we're required to publish this symbol, as we might be under an
3294 // explicit instantiation, leave it with default visibility but
3295 // enable string-comparisons.
3296 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
3297 return RUK_NonUniqueVisible;
3298}
Rafael Espindola91f68b42014-09-15 19:20:10 +00003299
Rafael Espindola1e4df922014-09-16 15:18:21 +00003300// Find out how to codegen the complete destructor and constructor
3301namespace {
3302enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
3303}
3304static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
3305 const CXXMethodDecl *MD) {
3306 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
3307 return StructorCodegen::Emit;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003308
Rafael Espindola1e4df922014-09-16 15:18:21 +00003309 // The complete and base structors are not equivalent if there are any virtual
3310 // bases, so emit separate functions.
3311 if (MD->getParent()->getNumVBases())
3312 return StructorCodegen::Emit;
3313
3314 GlobalDecl AliasDecl;
3315 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3316 AliasDecl = GlobalDecl(DD, Dtor_Complete);
3317 } else {
3318 const auto *CD = cast<CXXConstructorDecl>(MD);
3319 AliasDecl = GlobalDecl(CD, Ctor_Complete);
3320 }
3321 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3322
3323 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
3324 return StructorCodegen::RAUW;
3325
3326 // FIXME: Should we allow available_externally aliases?
3327 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
3328 return StructorCodegen::RAUW;
3329
Rafael Espindola0806f982014-09-16 20:19:43 +00003330 if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
3331 // Only ELF supports COMDATs with arbitrary names (C5/D5).
3332 if (CGM.getTarget().getTriple().isOSBinFormatELF())
3333 return StructorCodegen::COMDAT;
3334 return StructorCodegen::Emit;
3335 }
Rafael Espindola1e4df922014-09-16 15:18:21 +00003336
3337 return StructorCodegen::Alias;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003338}
3339
Rafael Espindola1e4df922014-09-16 15:18:21 +00003340static void emitConstructorDestructorAlias(CodeGenModule &CGM,
3341 GlobalDecl AliasDecl,
3342 GlobalDecl TargetDecl) {
3343 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3344
3345 StringRef MangledName = CGM.getMangledName(AliasDecl);
3346 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
3347 if (Entry && !Entry->isDeclaration())
3348 return;
3349
3350 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
3351 llvm::PointerType *AliasType = Aliasee->getType();
3352
3353 // Create the alias with no name.
David Blaikie881b2342015-04-29 21:22:47 +00003354 auto *Alias = llvm::GlobalAlias::create(AliasType, Linkage, "", Aliasee,
3355 &CGM.getModule());
Rafael Espindola1e4df922014-09-16 15:18:21 +00003356
3357 // Switch any previous uses to the alias.
3358 if (Entry) {
3359 assert(Entry->getType() == AliasType &&
3360 "declaration exists with different type");
3361 Alias->takeName(Entry);
3362 Entry->replaceAllUsesWith(Alias);
3363 Entry->eraseFromParent();
3364 } else {
3365 Alias->setName(MangledName);
3366 }
3367
3368 // Finally, set up the alias with its proper name and attributes.
Dario Domiziolic4fb8ca72014-09-19 22:06:24 +00003369 CGM.setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003370}
3371
3372void ItaniumCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
3373 StructorType Type) {
3374 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
3375 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
3376
3377 StructorCodegen CGType = getCodegenToUse(CGM, MD);
3378
3379 if (Type == StructorType::Complete) {
3380 GlobalDecl CompleteDecl;
3381 GlobalDecl BaseDecl;
3382 if (CD) {
3383 CompleteDecl = GlobalDecl(CD, Ctor_Complete);
3384 BaseDecl = GlobalDecl(CD, Ctor_Base);
3385 } else {
3386 CompleteDecl = GlobalDecl(DD, Dtor_Complete);
3387 BaseDecl = GlobalDecl(DD, Dtor_Base);
3388 }
3389
3390 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
3391 emitConstructorDestructorAlias(CGM, CompleteDecl, BaseDecl);
3392 return;
3393 }
3394
3395 if (CGType == StructorCodegen::RAUW) {
3396 StringRef MangledName = CGM.getMangledName(CompleteDecl);
Andrey Bokhankocab58582015-08-31 13:20:44 +00003397 auto *Aliasee = CGM.GetAddrOfGlobal(BaseDecl);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003398 CGM.addReplacement(MangledName, Aliasee);
3399 return;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003400 }
3401 }
3402
3403 // The base destructor is equivalent to the base destructor of its
3404 // base class if there is exactly one non-virtual base class with a
3405 // non-trivial destructor, there are no fields with a non-trivial
3406 // destructor, and the body of the destructor is trivial.
Rafael Espindola1e4df922014-09-16 15:18:21 +00003407 if (DD && Type == StructorType::Base && CGType != StructorCodegen::COMDAT &&
3408 !CGM.TryEmitBaseDestructorAsAlias(DD))
Rafael Espindola91f68b42014-09-15 19:20:10 +00003409 return;
3410
Rafael Espindola1e4df922014-09-16 15:18:21 +00003411 llvm::Function *Fn = CGM.codegenCXXStructor(MD, Type);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003412
Rafael Espindola1e4df922014-09-16 15:18:21 +00003413 if (CGType == StructorCodegen::COMDAT) {
3414 SmallString<256> Buffer;
3415 llvm::raw_svector_ostream Out(Buffer);
3416 if (DD)
3417 getMangleContext().mangleCXXDtorComdat(DD, Out);
3418 else
3419 getMangleContext().mangleCXXCtorComdat(CD, Out);
3420 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
3421 Fn->setComdat(C);
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003422 } else {
3423 CGM.maybeSetTrivialComdat(*MD, *Fn);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003424 }
Rafael Espindola91f68b42014-09-15 19:20:10 +00003425}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003426
3427static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) {
3428 // void *__cxa_begin_catch(void*);
3429 llvm::FunctionType *FTy = llvm::FunctionType::get(
3430 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3431
3432 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
3433}
3434
3435static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) {
3436 // void __cxa_end_catch();
3437 llvm::FunctionType *FTy =
3438 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
3439
3440 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
3441}
3442
3443static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) {
3444 // void *__cxa_get_exception_ptr(void*);
3445 llvm::FunctionType *FTy = llvm::FunctionType::get(
3446 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3447
3448 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
3449}
3450
3451namespace {
3452 /// A cleanup to call __cxa_end_catch. In many cases, the caught
3453 /// exception type lets us state definitively that the thrown exception
3454 /// type does not have a destructor. In particular:
3455 /// - Catch-alls tell us nothing, so we have to conservatively
3456 /// assume that the thrown exception might have a destructor.
3457 /// - Catches by reference behave according to their base types.
3458 /// - Catches of non-record types will only trigger for exceptions
3459 /// of non-record types, which never have destructors.
3460 /// - Catches of record types can trigger for arbitrary subclasses
3461 /// of the caught type, so we have to assume the actual thrown
3462 /// exception type might have a throwing destructor, even if the
3463 /// caught type's destructor is trivial or nothrow.
David Blaikie7e70d682015-08-18 22:40:54 +00003464 struct CallEndCatch final : EHScopeStack::Cleanup {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003465 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
3466 bool MightThrow;
3467
3468 void Emit(CodeGenFunction &CGF, Flags flags) override {
3469 if (!MightThrow) {
3470 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
3471 return;
3472 }
3473
3474 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
3475 }
3476 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003477}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003478
3479/// Emits a call to __cxa_begin_catch and enters a cleanup to call
3480/// __cxa_end_catch.
3481///
3482/// \param EndMightThrow - true if __cxa_end_catch might throw
3483static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
3484 llvm::Value *Exn,
3485 bool EndMightThrow) {
3486 llvm::CallInst *call =
3487 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
3488
3489 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
3490
3491 return call;
3492}
3493
3494/// A "special initializer" callback for initializing a catch
3495/// parameter during catch initialization.
3496static void InitCatchParam(CodeGenFunction &CGF,
3497 const VarDecl &CatchParam,
John McCall7f416cc2015-09-08 08:05:57 +00003498 Address ParamAddr,
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003499 SourceLocation Loc) {
3500 // Load the exception from where the landing pad saved it.
3501 llvm::Value *Exn = CGF.getExceptionFromSlot();
3502
3503 CanQualType CatchType =
3504 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
3505 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
3506
3507 // If we're catching by reference, we can just cast the object
3508 // pointer to the appropriate pointer.
3509 if (isa<ReferenceType>(CatchType)) {
3510 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
3511 bool EndCatchMightThrow = CaughtType->isRecordType();
3512
3513 // __cxa_begin_catch returns the adjusted object pointer.
3514 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
3515
3516 // We have no way to tell the personality function that we're
3517 // catching by reference, so if we're catching a pointer,
3518 // __cxa_begin_catch will actually return that pointer by value.
3519 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
3520 QualType PointeeType = PT->getPointeeType();
3521
3522 // When catching by reference, generally we should just ignore
3523 // this by-value pointer and use the exception object instead.
3524 if (!PointeeType->isRecordType()) {
3525
3526 // Exn points to the struct _Unwind_Exception header, which
3527 // we have to skip past in order to reach the exception data.
3528 unsigned HeaderSize =
3529 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
3530 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
3531
3532 // However, if we're catching a pointer-to-record type that won't
3533 // work, because the personality function might have adjusted
3534 // the pointer. There's actually no way for us to fully satisfy
3535 // the language/ABI contract here: we can't use Exn because it
3536 // might have the wrong adjustment, but we can't use the by-value
3537 // pointer because it's off by a level of abstraction.
3538 //
3539 // The current solution is to dump the adjusted pointer into an
3540 // alloca, which breaks language semantics (because changing the
3541 // pointer doesn't change the exception) but at least works.
3542 // The better solution would be to filter out non-exact matches
3543 // and rethrow them, but this is tricky because the rethrow
3544 // really needs to be catchable by other sites at this landing
3545 // pad. The best solution is to fix the personality function.
3546 } else {
3547 // Pull the pointer for the reference type off.
3548 llvm::Type *PtrTy =
3549 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
3550
3551 // Create the temporary and write the adjusted pointer into it.
John McCall7f416cc2015-09-08 08:05:57 +00003552 Address ExnPtrTmp =
3553 CGF.CreateTempAlloca(PtrTy, CGF.getPointerAlign(), "exn.byref.tmp");
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003554 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3555 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
3556
3557 // Bind the reference to the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00003558 AdjustedExn = ExnPtrTmp.getPointer();
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003559 }
3560 }
3561
3562 llvm::Value *ExnCast =
3563 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
3564 CGF.Builder.CreateStore(ExnCast, ParamAddr);
3565 return;
3566 }
3567
3568 // Scalars and complexes.
3569 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
3570 if (TEK != TEK_Aggregate) {
3571 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
3572
3573 // If the catch type is a pointer type, __cxa_begin_catch returns
3574 // the pointer by value.
3575 if (CatchType->hasPointerRepresentation()) {
3576 llvm::Value *CastExn =
3577 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
3578
3579 switch (CatchType.getQualifiers().getObjCLifetime()) {
3580 case Qualifiers::OCL_Strong:
3581 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
3582 // fallthrough
3583
3584 case Qualifiers::OCL_None:
3585 case Qualifiers::OCL_ExplicitNone:
3586 case Qualifiers::OCL_Autoreleasing:
3587 CGF.Builder.CreateStore(CastExn, ParamAddr);
3588 return;
3589
3590 case Qualifiers::OCL_Weak:
3591 CGF.EmitARCInitWeak(ParamAddr, CastExn);
3592 return;
3593 }
3594 llvm_unreachable("bad ownership qualifier!");
3595 }
3596
3597 // Otherwise, it returns a pointer into the exception object.
3598
3599 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3600 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3601
3602 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
John McCall7f416cc2015-09-08 08:05:57 +00003603 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003604 switch (TEK) {
3605 case TEK_Complex:
3606 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
3607 /*init*/ true);
3608 return;
3609 case TEK_Scalar: {
3610 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
3611 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
3612 return;
3613 }
3614 case TEK_Aggregate:
3615 llvm_unreachable("evaluation kind filtered out!");
3616 }
3617 llvm_unreachable("bad evaluation kind");
3618 }
3619
3620 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
John McCall7f416cc2015-09-08 08:05:57 +00003621 auto catchRD = CatchType->getAsCXXRecordDecl();
3622 CharUnits caughtExnAlignment = CGF.CGM.getClassPointerAlignment(catchRD);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003623
3624 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3625
3626 // Check for a copy expression. If we don't have a copy expression,
3627 // that means a trivial copy is okay.
3628 const Expr *copyExpr = CatchParam.getInit();
3629 if (!copyExpr) {
3630 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
John McCall7f416cc2015-09-08 08:05:57 +00003631 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3632 caughtExnAlignment);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003633 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
3634 return;
3635 }
3636
3637 // We have to call __cxa_get_exception_ptr to get the adjusted
3638 // pointer before copying.
3639 llvm::CallInst *rawAdjustedExn =
3640 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
3641
3642 // Cast that to the appropriate type.
John McCall7f416cc2015-09-08 08:05:57 +00003643 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3644 caughtExnAlignment);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003645
3646 // The copy expression is defined in terms of an OpaqueValueExpr.
3647 // Find it and map it to the adjusted expression.
3648 CodeGenFunction::OpaqueValueMapping
3649 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
3650 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
3651
3652 // Call the copy ctor in a terminate scope.
3653 CGF.EHStack.pushTerminate();
3654
3655 // Perform the copy construction.
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003656 CGF.EmitAggExpr(copyExpr,
John McCall7f416cc2015-09-08 08:05:57 +00003657 AggValueSlot::forAddr(ParamAddr, Qualifiers(),
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003658 AggValueSlot::IsNotDestructed,
3659 AggValueSlot::DoesNotNeedGCBarriers,
3660 AggValueSlot::IsNotAliased));
3661
3662 // Leave the terminate scope.
3663 CGF.EHStack.popTerminate();
3664
3665 // Undo the opaque value mapping.
3666 opaque.pop();
3667
3668 // Finally we can call __cxa_begin_catch.
3669 CallBeginCatch(CGF, Exn, true);
3670}
3671
3672/// Begins a catch statement by initializing the catch variable and
3673/// calling __cxa_begin_catch.
3674void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF,
3675 const CXXCatchStmt *S) {
3676 // We have to be very careful with the ordering of cleanups here:
3677 // C++ [except.throw]p4:
3678 // The destruction [of the exception temporary] occurs
3679 // immediately after the destruction of the object declared in
3680 // the exception-declaration in the handler.
3681 //
3682 // So the precise ordering is:
3683 // 1. Construct catch variable.
3684 // 2. __cxa_begin_catch
3685 // 3. Enter __cxa_end_catch cleanup
3686 // 4. Enter dtor cleanup
3687 //
3688 // We do this by using a slightly abnormal initialization process.
3689 // Delegation sequence:
3690 // - ExitCXXTryStmt opens a RunCleanupsScope
3691 // - EmitAutoVarAlloca creates the variable and debug info
3692 // - InitCatchParam initializes the variable from the exception
3693 // - CallBeginCatch calls __cxa_begin_catch
3694 // - CallBeginCatch enters the __cxa_end_catch cleanup
3695 // - EmitAutoVarCleanups enters the variable destructor cleanup
3696 // - EmitCXXTryStmt emits the code for the catch body
3697 // - EmitCXXTryStmt close the RunCleanupsScope
3698
3699 VarDecl *CatchParam = S->getExceptionDecl();
3700 if (!CatchParam) {
3701 llvm::Value *Exn = CGF.getExceptionFromSlot();
3702 CallBeginCatch(CGF, Exn, true);
3703 return;
3704 }
3705
3706 // Emit the local.
3707 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
3708 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
3709 CGF.EmitAutoVarCleanups(var);
3710}
3711
3712/// Get or define the following function:
3713/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
3714/// This code is used only in C++.
3715static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
3716 llvm::FunctionType *fnTy =
3717 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3718 llvm::Constant *fnRef =
3719 CGM.CreateRuntimeFunction(fnTy, "__clang_call_terminate");
3720
3721 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
3722 if (fn && fn->empty()) {
3723 fn->setDoesNotThrow();
3724 fn->setDoesNotReturn();
3725
3726 // What we really want is to massively penalize inlining without
3727 // forbidding it completely. The difference between that and
3728 // 'noinline' is negligible.
3729 fn->addFnAttr(llvm::Attribute::NoInline);
3730
3731 // Allow this function to be shared across translation units, but
3732 // we don't want it to turn into an exported symbol.
3733 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
3734 fn->setVisibility(llvm::Function::HiddenVisibility);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00003735 if (CGM.supportsCOMDAT())
3736 fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003737
3738 // Set up the function.
3739 llvm::BasicBlock *entry =
3740 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
John McCall7f416cc2015-09-08 08:05:57 +00003741 CGBuilderTy builder(CGM, entry);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003742
3743 // Pull the exception pointer out of the parameter list.
3744 llvm::Value *exn = &*fn->arg_begin();
3745
3746 // Call __cxa_begin_catch(exn).
3747 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
3748 catchCall->setDoesNotThrow();
3749 catchCall->setCallingConv(CGM.getRuntimeCC());
3750
3751 // Call std::terminate().
David Blaikie4ba525b2015-07-14 17:27:39 +00003752 llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn());
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003753 termCall->setDoesNotThrow();
3754 termCall->setDoesNotReturn();
3755 termCall->setCallingConv(CGM.getRuntimeCC());
3756
3757 // std::terminate cannot return.
3758 builder.CreateUnreachable();
3759 }
3760
3761 return fnRef;
3762}
3763
3764llvm::CallInst *
3765ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
3766 llvm::Value *Exn) {
3767 // In C++, we want to call __cxa_begin_catch() before terminating.
3768 if (Exn) {
3769 assert(CGF.CGM.getLangOpts().CPlusPlus);
3770 return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn);
3771 }
3772 return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
3773}