blob: 31be2f98653049a22db437288d140df901713b8a [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
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000246 bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,
247 CodeGenFunction::VPtr Vptr) override;
248
249 bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override {
250 return true;
251 }
252
253 llvm::Constant *
254 getVTableAddressPoint(BaseSubobject Base,
255 const CXXRecordDecl *VTableClass) override;
256
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000257 llvm::Value *getVTableAddressPointInStructor(
258 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000259 BaseSubobject Base, const CXXRecordDecl *NearestVBase) override;
260
261 llvm::Value *getVTableAddressPointInStructorWithVTT(
262 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
263 BaseSubobject Base, const CXXRecordDecl *NearestVBase);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000264
265 llvm::Constant *
266 getVTableAddressPointForConstExpr(BaseSubobject Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000267 const CXXRecordDecl *VTableClass) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000268
269 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
Craig Topper4f12f102014-03-12 06:41:41 +0000270 CharUnits VPtrOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000271
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000272 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
John McCall7f416cc2015-09-08 08:05:57 +0000273 Address This, llvm::Type *Ty,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +0000274 SourceLocation Loc) override;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000275
David Majnemer0c0b6d92014-10-31 20:09:12 +0000276 llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
277 const CXXDestructorDecl *Dtor,
278 CXXDtorType DtorType,
John McCall7f416cc2015-09-08 08:05:57 +0000279 Address This,
David Majnemer0c0b6d92014-10-31 20:09:12 +0000280 const CXXMemberCallExpr *CE) override;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000281
Craig Topper4f12f102014-03-12 06:41:41 +0000282 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
Reid Kleckner7810af02013-06-19 15:20:38 +0000283
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000284 bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const override;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000285
Hans Wennborgc94391d2014-06-06 20:04:01 +0000286 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
287 bool ReturnAdjustment) override {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000288 // Allow inlining of thunks by emitting them with available_externally
289 // linkage together with vtables when needed.
Peter Collingbourne8fabc1b2015-07-01 02:10:26 +0000290 if (ForVTable && !Thunk->hasLocalLinkage())
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000291 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
292 }
293
John McCall7f416cc2015-09-08 08:05:57 +0000294 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This,
Craig Topper4f12f102014-03-12 06:41:41 +0000295 const ThisAdjustment &TA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000296
John McCall7f416cc2015-09-08 08:05:57 +0000297 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
Craig Topper4f12f102014-03-12 06:41:41 +0000298 const ReturnAdjustment &RA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000299
David Majnemer196ac332014-09-11 23:05:02 +0000300 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
301 FunctionArgList &Args) const override {
302 assert(!Args.empty() && "expected the arglist to not be empty!");
303 return Args.size() - 1;
304 }
305
Craig Topper4f12f102014-03-12 06:41:41 +0000306 StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
307 StringRef GetDeletedVirtualCallName() override
308 { return "__cxa_deleted_virtual"; }
Joao Matos2ce88ef2012-07-17 17:10:11 +0000309
Craig Topper4f12f102014-03-12 06:41:41 +0000310 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall7f416cc2015-09-08 08:05:57 +0000311 Address InitializeArrayCookie(CodeGenFunction &CGF,
312 Address NewPtr,
313 llvm::Value *NumElements,
314 const CXXNewExpr *expr,
315 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000316 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000317 Address allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000318 CharUnits cookieSize) override;
John McCall68ff0372010-09-08 01:44:27 +0000319
John McCallcdf7ef52010-11-06 09:44:32 +0000320 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000321 llvm::GlobalVariable *DeclPtr,
322 bool PerformInit) override;
Richard Smithdbf74ba2013-04-14 23:01:42 +0000323 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000324 llvm::Constant *dtor, llvm::Constant *addr) override;
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000325
326 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +0000327 llvm::Value *Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000328 void EmitThreadLocalInitFuncs(
David Majnemerb3341ea2014-10-05 05:05:40 +0000329 CodeGenModule &CGM,
330 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *>>
331 CXXThreadLocals,
332 ArrayRef<llvm::Function *> CXXThreadLocalInits,
333 ArrayRef<llvm::GlobalVariable *> CXXThreadLocalInitVars) override;
334
335 bool usesThreadWrapperFunction() const override { return true; }
Richard Smith0f383742014-03-26 22:48:22 +0000336 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
337 QualType LValType) override;
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000338
Craig Topper4f12f102014-03-12 06:41:41 +0000339 bool NeedsVTTParameter(GlobalDecl GD) override;
David Majnemere2cb8d12014-07-07 06:20:47 +0000340
341 /**************************** RTTI Uniqueness ******************************/
342
343protected:
344 /// Returns true if the ABI requires RTTI type_info objects to be unique
345 /// across a program.
346 virtual bool shouldRTTIBeUnique() const { return true; }
347
348public:
349 /// What sort of unique-RTTI behavior should we use?
350 enum RTTIUniquenessKind {
351 /// We are guaranteeing, or need to guarantee, that the RTTI string
352 /// is unique.
353 RUK_Unique,
354
355 /// We are not guaranteeing uniqueness for the RTTI string, so we
356 /// can demote to hidden visibility but must use string comparisons.
357 RUK_NonUniqueHidden,
358
359 /// We are not guaranteeing uniqueness for the RTTI string, so we
360 /// have to use string comparisons, but we also have to emit it with
361 /// non-hidden visibility.
362 RUK_NonUniqueVisible
363 };
364
365 /// Return the required visibility status for the given type and linkage in
366 /// the current ABI.
367 RTTIUniquenessKind
368 classifyRTTIUniqueness(QualType CanTy,
369 llvm::GlobalValue::LinkageTypes Linkage) const;
370 friend class ItaniumRTTIBuilder;
Rafael Espindola91f68b42014-09-15 19:20:10 +0000371
372 void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000373
374 private:
Piotr Padlewski1d02f682015-08-19 20:09:09 +0000375 bool hasAnyUsedVirtualInlineFunction(const CXXRecordDecl *RD) const {
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000376 const auto &VtableLayout =
377 CGM.getItaniumVTableContext().getVTableLayout(RD);
378
379 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
Piotr Padlewski1d02f682015-08-19 20:09:09 +0000380 if (!VtableComponent.isUsedFunctionPointerKind())
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000381 continue;
382
Piotr Padlewski1d02f682015-08-19 20:09:09 +0000383 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000384 if (Method->getCanonicalDecl()->isInlined())
385 return true;
386 }
387 return false;
388 }
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000389
390 bool isVTableHidden(const CXXRecordDecl *RD) const {
391 const auto &VtableLayout =
392 CGM.getItaniumVTableContext().getVTableLayout(RD);
393
394 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
395 if (VtableComponent.isRTTIKind()) {
396 const CXXRecordDecl *RTTIDecl = VtableComponent.getRTTIDecl();
397 if (RTTIDecl->getVisibility() == Visibility::HiddenVisibility)
398 return true;
399 } else if (VtableComponent.isUsedFunctionPointerKind()) {
400 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
401 if (Method->getVisibility() == Visibility::HiddenVisibility &&
402 !Method->isDefined())
403 return true;
404 }
405 }
406 return false;
407 }
Charles Davis4e786dd2010-05-25 19:52:27 +0000408};
John McCall86353412010-08-21 22:46:04 +0000409
410class ARMCXXABI : public ItaniumCXXABI {
411public:
Mark Seabornedf0d382013-07-24 16:25:13 +0000412 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
413 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
414 /* UseARMGuardVarABI = */ true) {}
John McCall5d865c322010-08-31 07:33:07 +0000415
Craig Topper4f12f102014-03-12 06:41:41 +0000416 bool HasThisReturn(GlobalDecl GD) const override {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000417 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
418 isa<CXXDestructorDecl>(GD.getDecl()) &&
419 GD.getDtorType() != Dtor_Deleting));
420 }
John McCall5d865c322010-08-31 07:33:07 +0000421
Craig Topper4f12f102014-03-12 06:41:41 +0000422 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
423 QualType ResTy) override;
John McCall5d865c322010-08-31 07:33:07 +0000424
Craig Topper4f12f102014-03-12 06:41:41 +0000425 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall7f416cc2015-09-08 08:05:57 +0000426 Address InitializeArrayCookie(CodeGenFunction &CGF,
427 Address NewPtr,
428 llvm::Value *NumElements,
429 const CXXNewExpr *expr,
430 QualType ElementType) override;
431 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, Address allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000432 CharUnits cookieSize) override;
John McCall86353412010-08-21 22:46:04 +0000433};
Tim Northovera2ee4332014-03-29 15:09:45 +0000434
435class iOS64CXXABI : public ARMCXXABI {
436public:
437 iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {}
Tim Northover65f582f2014-03-30 17:32:48 +0000438
439 // ARM64 libraries are prepared for non-unique RTTI.
David Majnemere2cb8d12014-07-07 06:20:47 +0000440 bool shouldRTTIBeUnique() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +0000441};
Dan Gohmanc2853072015-09-03 22:51:53 +0000442
443class WebAssemblyCXXABI final : public ItaniumCXXABI {
444public:
445 explicit WebAssemblyCXXABI(CodeGen::CodeGenModule &CGM)
446 : ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
447 /*UseARMGuardVarABI=*/true) {}
448
449private:
450 bool HasThisReturn(GlobalDecl GD) const override {
451 return isa<CXXConstructorDecl>(GD.getDecl()) ||
452 (isa<CXXDestructorDecl>(GD.getDecl()) &&
453 GD.getDtorType() != Dtor_Deleting);
454 }
455};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000456}
Charles Davis4e786dd2010-05-25 19:52:27 +0000457
Charles Davis53c59df2010-08-16 03:33:14 +0000458CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000459 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000460 // For IR-generation purposes, there's no significant difference
461 // between the ARM and iOS ABIs.
462 case TargetCXXABI::GenericARM:
463 case TargetCXXABI::iOS:
464 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000465
Tim Northovera2ee4332014-03-29 15:09:45 +0000466 case TargetCXXABI::iOS64:
467 return new iOS64CXXABI(CGM);
468
Tim Northover9bb857a2013-01-31 12:13:10 +0000469 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
470 // include the other 32-bit ARM oddities: constructor/destructor return values
471 // and array cookies.
472 case TargetCXXABI::GenericAArch64:
Mark Seabornedf0d382013-07-24 16:25:13 +0000473 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
474 /* UseARMGuardVarABI = */ true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000475
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000476 case TargetCXXABI::GenericMIPS:
477 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true);
478
Dan Gohmanc2853072015-09-03 22:51:53 +0000479 case TargetCXXABI::WebAssembly:
480 return new WebAssemblyCXXABI(CGM);
481
John McCall57625922013-01-25 23:36:14 +0000482 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000483 if (CGM.getContext().getTargetInfo().getTriple().getArch()
484 == llvm::Triple::le32) {
485 // For PNaCl, use ARM-style method pointers so that PNaCl code
486 // does not assume anything about the alignment of function
487 // pointers.
488 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
489 /* UseARMGuardVarABI = */ false);
490 }
John McCall57625922013-01-25 23:36:14 +0000491 return new ItaniumCXXABI(CGM);
492
493 case TargetCXXABI::Microsoft:
494 llvm_unreachable("Microsoft ABI is not Itanium-based");
495 }
496 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000497}
498
Chris Lattnera5f58b02011-07-09 17:41:47 +0000499llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000500ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
501 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000502 return CGM.PtrDiffTy;
Reid Kleckneree7cf842014-12-01 22:02:27 +0000503 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, nullptr);
John McCall1c456c82010-08-22 06:43:33 +0000504}
505
John McCalld9c6c0b2010-08-22 00:59:17 +0000506/// In the Itanium and ARM ABIs, method pointers have the form:
507/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
508///
509/// In the Itanium ABI:
510/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
511/// - the this-adjustment is (memptr.adj)
512/// - the virtual offset is (memptr.ptr - 1)
513///
514/// In the ARM ABI:
515/// - method pointers are virtual if (memptr.adj & 1) is nonzero
516/// - the this-adjustment is (memptr.adj >> 1)
517/// - the virtual offset is (memptr.ptr)
518/// ARM uses 'adj' for the virtual flag because Thumb functions
519/// may be only single-byte aligned.
520///
521/// If the member is virtual, the adjusted 'this' pointer points
522/// to a vtable pointer from which the virtual offset is applied.
523///
524/// If the member is non-virtual, memptr.ptr is the address of
525/// the function to call.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000526llvm::Value *ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
John McCall7f416cc2015-09-08 08:05:57 +0000527 CodeGenFunction &CGF, const Expr *E, Address ThisAddr,
528 llvm::Value *&ThisPtrForCall,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000529 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
John McCall475999d2010-08-22 00:05:51 +0000530 CGBuilderTy &Builder = CGF.Builder;
531
532 const FunctionProtoType *FPT =
533 MPT->getPointeeType()->getAs<FunctionProtoType>();
534 const CXXRecordDecl *RD =
535 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
536
Chris Lattner2192fe52011-07-18 04:24:23 +0000537 llvm::FunctionType *FTy =
John McCalla729c622012-02-17 03:33:10 +0000538 CGM.getTypes().GetFunctionType(
539 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
John McCall475999d2010-08-22 00:05:51 +0000540
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000541 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000542
John McCalld9c6c0b2010-08-22 00:59:17 +0000543 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
544 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
545 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
546
John McCalla1dee5302010-08-22 10:59:02 +0000547 // Extract memptr.adj, which is in the second field.
548 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000549
550 // Compute the true adjustment.
551 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000552 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000553 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000554
555 // Apply the adjustment and cast back to the original struct type
556 // for consistency.
John McCall7f416cc2015-09-08 08:05:57 +0000557 llvm::Value *This = ThisAddr.getPointer();
John McCalld9c6c0b2010-08-22 00:59:17 +0000558 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
559 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
560 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall7f416cc2015-09-08 08:05:57 +0000561 ThisPtrForCall = This;
John McCall475999d2010-08-22 00:05:51 +0000562
563 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000564 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall475999d2010-08-22 00:05:51 +0000565
566 // If the LSB in the function pointer is 1, the function pointer points to
567 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000568 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000569 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000570 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
571 else
572 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
573 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000574 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
575
576 // In the virtual path, the adjustment left 'This' pointing to the
577 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000578 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000579 CGF.EmitBlock(FnVirtual);
580
581 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000582 llvm::Type *VTableTy = Builder.getInt8PtrTy();
John McCall7f416cc2015-09-08 08:05:57 +0000583 CharUnits VTablePtrAlign =
584 CGF.CGM.getDynamicOffsetAlignment(ThisAddr.getAlignment(), RD,
585 CGF.getPointerAlign());
586 llvm::Value *VTable =
587 CGF.GetVTablePtr(Address(This, VTablePtrAlign), VTableTy);
John McCall475999d2010-08-22 00:05:51 +0000588
589 // Apply the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000590 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000591 if (!UseARMMethodPtrABI)
592 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld9c6c0b2010-08-22 00:59:17 +0000593 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall475999d2010-08-22 00:05:51 +0000594
595 // Load the virtual function to call.
596 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCall7f416cc2015-09-08 08:05:57 +0000597 llvm::Value *VirtualFn =
598 Builder.CreateAlignedLoad(VTable, CGF.getPointerAlign(),
599 "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000600 CGF.EmitBranch(FnEnd);
601
602 // In the non-virtual path, the function pointer is actually a
603 // function pointer.
604 CGF.EmitBlock(FnNonVirtual);
605 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000606 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall475999d2010-08-22 00:05:51 +0000607
608 // We're done.
609 CGF.EmitBlock(FnEnd);
Jay Foad20c0f022011-03-30 11:28:58 +0000610 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
John McCall475999d2010-08-22 00:05:51 +0000611 Callee->addIncoming(VirtualFn, FnVirtual);
612 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
613 return Callee;
614}
John McCalla8bbb822010-08-22 03:04:22 +0000615
John McCallc134eb52010-08-31 21:07:20 +0000616/// Compute an l-value by applying the given pointer-to-member to a
617/// base object.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000618llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
John McCall7f416cc2015-09-08 08:05:57 +0000619 CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000620 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000621 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000622
623 CGBuilderTy &Builder = CGF.Builder;
624
John McCallc134eb52010-08-31 21:07:20 +0000625 // Cast to char*.
John McCall7f416cc2015-09-08 08:05:57 +0000626 Base = Builder.CreateElementBitCast(Base, CGF.Int8Ty);
John McCallc134eb52010-08-31 21:07:20 +0000627
628 // Apply the offset, which we assume is non-null.
John McCall7f416cc2015-09-08 08:05:57 +0000629 llvm::Value *Addr =
630 Builder.CreateInBoundsGEP(Base.getPointer(), MemPtr, "memptr.offset");
John McCallc134eb52010-08-31 21:07:20 +0000631
632 // Cast the address to the appropriate pointer type, adopting the
633 // address space of the base pointer.
John McCall7f416cc2015-09-08 08:05:57 +0000634 llvm::Type *PType = CGF.ConvertTypeForMem(MPT->getPointeeType())
635 ->getPointerTo(Base.getAddressSpace());
John McCallc134eb52010-08-31 21:07:20 +0000636 return Builder.CreateBitCast(Addr, PType);
637}
638
John McCallc62bb392012-02-15 01:22:51 +0000639/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
640/// conversion.
641///
642/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000643///
644/// Obligatory offset/adjustment diagram:
645/// <-- offset --> <-- adjustment -->
646/// |--------------------------|----------------------|--------------------|
647/// ^Derived address point ^Base address point ^Member address point
648///
649/// So when converting a base member pointer to a derived member pointer,
650/// we add the offset to the adjustment because the address point has
651/// decreased; and conversely, when converting a derived MP to a base MP
652/// we subtract the offset from the adjustment because the address point
653/// has increased.
654///
655/// The standard forbids (at compile time) conversion to and from
656/// virtual bases, which is why we don't have to consider them here.
657///
658/// The standard forbids (at run time) casting a derived MP to a base
659/// MP when the derived MP does not point to a member of the base.
660/// This is why -1 is a reasonable choice for null data member
661/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000662llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000663ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
664 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000665 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000666 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000667 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
668 E->getCastKind() == CK_ReinterpretMemberPointer);
669
670 // Under Itanium, reinterprets don't require any additional processing.
671 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
672
673 // Use constant emission if we can.
674 if (isa<llvm::Constant>(src))
675 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
676
677 llvm::Constant *adj = getMemberPointerAdjustment(E);
678 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000679
680 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000681 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000682
John McCallc62bb392012-02-15 01:22:51 +0000683 const MemberPointerType *destTy =
684 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000685
John McCall7a9aac22010-08-23 01:21:21 +0000686 // For member data pointers, this is just a matter of adding the
687 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000688 if (destTy->isMemberDataPointer()) {
689 llvm::Value *dst;
690 if (isDerivedToBase)
691 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000692 else
John McCallc62bb392012-02-15 01:22:51 +0000693 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000694
695 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000696 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
697 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
698 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000699 }
700
John McCalla1dee5302010-08-22 10:59:02 +0000701 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000702 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000703 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
704 offset <<= 1;
705 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000706 }
707
John McCallc62bb392012-02-15 01:22:51 +0000708 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
709 llvm::Value *dstAdj;
710 if (isDerivedToBase)
711 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000712 else
John McCallc62bb392012-02-15 01:22:51 +0000713 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000714
John McCallc62bb392012-02-15 01:22:51 +0000715 return Builder.CreateInsertValue(src, dstAdj, 1);
716}
717
718llvm::Constant *
719ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
720 llvm::Constant *src) {
721 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
722 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
723 E->getCastKind() == CK_ReinterpretMemberPointer);
724
725 // Under Itanium, reinterprets don't require any additional processing.
726 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
727
728 // If the adjustment is trivial, we don't need to do anything.
729 llvm::Constant *adj = getMemberPointerAdjustment(E);
730 if (!adj) return src;
731
732 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
733
734 const MemberPointerType *destTy =
735 E->getType()->castAs<MemberPointerType>();
736
737 // For member data pointers, this is just a matter of adding the
738 // offset if the source is non-null.
739 if (destTy->isMemberDataPointer()) {
740 // null maps to null.
741 if (src->isAllOnesValue()) return src;
742
743 if (isDerivedToBase)
744 return llvm::ConstantExpr::getNSWSub(src, adj);
745 else
746 return llvm::ConstantExpr::getNSWAdd(src, adj);
747 }
748
749 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000750 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000751 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
752 offset <<= 1;
753 adj = llvm::ConstantInt::get(adj->getType(), offset);
754 }
755
756 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
757 llvm::Constant *dstAdj;
758 if (isDerivedToBase)
759 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
760 else
761 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
762
763 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000764}
John McCall84fa5102010-08-22 04:16:24 +0000765
766llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000767ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000768 // Itanium C++ ABI 2.3:
769 // A NULL pointer is represented as -1.
770 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000771 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000772
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000773 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000774 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000775 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000776}
777
John McCallf3a88602011-02-03 08:15:49 +0000778llvm::Constant *
779ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
780 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000781 // Itanium C++ ABI 2.3:
782 // A pointer to data member is an offset from the base address of
783 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000784 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000785}
786
David Majnemere2be95b2015-06-23 07:31:01 +0000787llvm::Constant *
788ItaniumCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000789 return BuildMemberPointer(MD, CharUnits::Zero());
790}
791
792llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
793 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000794 assert(MD->isInstance() && "Member function must not be static!");
795 MD = MD->getCanonicalDecl();
796
797 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000798
799 // Get the function pointer (or index if this is a virtual function).
800 llvm::Constant *MemPtr[2];
801 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000802 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000803
Ken Dyckdf016282011-04-09 01:30:02 +0000804 const ASTContext &Context = getContext();
805 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000806 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000807 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000808
Mark Seabornedf0d382013-07-24 16:25:13 +0000809 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000810 // ARM C++ ABI 3.2.1:
811 // This ABI specifies that adj contains twice the this
812 // adjustment, plus 1 if the member function is virtual. The
813 // least significant bit of adj then makes exactly the same
814 // discrimination as the least significant bit of ptr does for
815 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000816 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
817 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000818 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000819 } else {
820 // Itanium C++ ABI 2.3:
821 // For a virtual function, [the pointer field] is 1 plus the
822 // virtual table offset (in bytes) of the function,
823 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000824 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
825 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000826 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000827 }
828 } else {
John McCall2979fe02011-04-12 00:42:48 +0000829 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000830 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000831 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000832 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000833 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000834 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000835 } else {
John McCall2979fe02011-04-12 00:42:48 +0000836 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
837 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000838 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000839 }
John McCall2979fe02011-04-12 00:42:48 +0000840 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000841
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000842 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000843 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
844 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000845 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000846 }
John McCall1c456c82010-08-22 06:43:33 +0000847
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000848 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000849}
850
Richard Smithdafff942012-01-14 04:30:29 +0000851llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
852 QualType MPType) {
853 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
854 const ValueDecl *MPD = MP.getMemberPointerDecl();
855 if (!MPD)
856 return EmitNullMemberPointer(MPT);
857
Reid Kleckner452abac2013-05-09 21:01:17 +0000858 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000859
860 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
861 return BuildMemberPointer(MD, ThisAdjustment);
862
863 CharUnits FieldOffset =
864 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
865 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
866}
867
John McCall131d97d2010-08-22 08:30:07 +0000868/// The comparison algorithm is pretty easy: the member pointers are
869/// the same if they're either bitwise identical *or* both null.
870///
871/// ARM is different here only because null-ness is more complicated.
872llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000873ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
874 llvm::Value *L,
875 llvm::Value *R,
876 const MemberPointerType *MPT,
877 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000878 CGBuilderTy &Builder = CGF.Builder;
879
John McCall131d97d2010-08-22 08:30:07 +0000880 llvm::ICmpInst::Predicate Eq;
881 llvm::Instruction::BinaryOps And, Or;
882 if (Inequality) {
883 Eq = llvm::ICmpInst::ICMP_NE;
884 And = llvm::Instruction::Or;
885 Or = llvm::Instruction::And;
886 } else {
887 Eq = llvm::ICmpInst::ICMP_EQ;
888 And = llvm::Instruction::And;
889 Or = llvm::Instruction::Or;
890 }
891
John McCall7a9aac22010-08-23 01:21:21 +0000892 // Member data pointers are easy because there's a unique null
893 // value, so it just comes down to bitwise equality.
894 if (MPT->isMemberDataPointer())
895 return Builder.CreateICmp(Eq, L, R);
896
897 // For member function pointers, the tautologies are more complex.
898 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000899 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000900 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000901 // (L == R) <==> (L.ptr == R.ptr &&
902 // (L.adj == R.adj ||
903 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000904 // The inequality tautologies have exactly the same structure, except
905 // applying De Morgan's laws.
906
907 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
908 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
909
John McCall131d97d2010-08-22 08:30:07 +0000910 // This condition tests whether L.ptr == R.ptr. This must always be
911 // true for equality to hold.
912 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
913
914 // This condition, together with the assumption that L.ptr == R.ptr,
915 // tests whether the pointers are both null. ARM imposes an extra
916 // condition.
917 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
918 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
919
920 // This condition tests whether L.adj == R.adj. If this isn't
921 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +0000922 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
923 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000924 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
925
926 // Null member function pointers on ARM clear the low bit of Adj,
927 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000928 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000929 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
930
931 // Compute (l.adj | r.adj) & 1 and test it against zero.
932 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
933 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
934 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
935 "cmp.or.adj");
936 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
937 }
938
939 // Tie together all our conditions.
940 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
941 Result = Builder.CreateBinOp(And, PtrEq, Result,
942 Inequality ? "memptr.ne" : "memptr.eq");
943 return Result;
944}
945
946llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000947ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
948 llvm::Value *MemPtr,
949 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +0000950 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +0000951
952 /// For member data pointers, this is just a check against -1.
953 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000954 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +0000955 llvm::Value *NegativeOne =
956 llvm::Constant::getAllOnesValue(MemPtr->getType());
957 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
958 }
John McCall131d97d2010-08-22 08:30:07 +0000959
Daniel Dunbar914bc412011-04-19 23:10:47 +0000960 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +0000961 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +0000962
963 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
964 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
965
Daniel Dunbar914bc412011-04-19 23:10:47 +0000966 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
967 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000968 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000969 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +0000970 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000971 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +0000972 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
973 "memptr.isvirtual");
974 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +0000975 }
976
977 return Result;
978}
John McCall1c456c82010-08-22 06:43:33 +0000979
Reid Kleckner40ca9132014-05-13 22:05:45 +0000980bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
981 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
982 if (!RD)
983 return false;
984
Reid Klecknerd355ca72014-05-15 01:26:32 +0000985 // Return indirectly if we have a non-trivial copy ctor or non-trivial dtor.
986 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
987 // special members.
988 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor()) {
John McCall7f416cc2015-09-08 08:05:57 +0000989 auto Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
990 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
Reid Kleckner40ca9132014-05-13 22:05:45 +0000991 return true;
992 }
Reid Kleckner40ca9132014-05-13 22:05:45 +0000993 return false;
994}
995
John McCall614dbdc2010-08-22 21:01:12 +0000996/// The Itanium ABI requires non-zero initialization only for data
997/// member pointers, for which '0' is a valid offset.
998bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
David Majnemer5fd33e02015-04-24 01:25:08 +0000999 return MPT->isMemberFunctionPointer();
John McCall84fa5102010-08-22 04:16:24 +00001000}
John McCall5d865c322010-08-31 07:33:07 +00001001
John McCall82fb8922012-09-25 10:10:39 +00001002/// The Itanium ABI always places an offset to the complete object
1003/// at entry -2 in the vtable.
David Majnemer08681372014-11-01 07:37:17 +00001004void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
1005 const CXXDeleteExpr *DE,
John McCall7f416cc2015-09-08 08:05:57 +00001006 Address Ptr,
David Majnemer08681372014-11-01 07:37:17 +00001007 QualType ElementType,
1008 const CXXDestructorDecl *Dtor) {
1009 bool UseGlobalDelete = DE->isGlobalDelete();
David Majnemer0c0b6d92014-10-31 20:09:12 +00001010 if (UseGlobalDelete) {
1011 // Derive the complete-object pointer, which is what we need
1012 // to pass to the deallocation function.
John McCall82fb8922012-09-25 10:10:39 +00001013
David Majnemer0c0b6d92014-10-31 20:09:12 +00001014 // Grab the vtable pointer as an intptr_t*.
1015 llvm::Value *VTable = CGF.GetVTablePtr(Ptr, CGF.IntPtrTy->getPointerTo());
John McCall82fb8922012-09-25 10:10:39 +00001016
David Majnemer0c0b6d92014-10-31 20:09:12 +00001017 // Track back to entry -2 and pull out the offset there.
1018 llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
1019 VTable, -2, "complete-offset.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001020 llvm::Value *Offset =
1021 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
David Majnemer0c0b6d92014-10-31 20:09:12 +00001022
1023 // Apply the offset.
John McCall7f416cc2015-09-08 08:05:57 +00001024 llvm::Value *CompletePtr =
1025 CGF.Builder.CreateBitCast(Ptr.getPointer(), CGF.Int8PtrTy);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001026 CompletePtr = CGF.Builder.CreateInBoundsGEP(CompletePtr, Offset);
1027
1028 // If we're supposed to call the global delete, make sure we do so
1029 // even if the destructor throws.
David Majnemer08681372014-11-01 07:37:17 +00001030 CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr,
1031 ElementType);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001032 }
1033
1034 // FIXME: Provide a source location here even though there's no
1035 // CXXMemberCallExpr for dtor call.
1036 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
1037 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr);
1038
1039 if (UseGlobalDelete)
1040 CGF.PopCleanupBlock();
John McCall82fb8922012-09-25 10:10:39 +00001041}
1042
David Majnemer442d0a22014-11-25 07:20:20 +00001043void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
1044 // void __cxa_rethrow();
1045
1046 llvm::FunctionType *FTy =
1047 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
1048
1049 llvm::Constant *Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
1050
1051 if (isNoReturn)
1052 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, None);
1053 else
1054 CGF.EmitRuntimeCallOrInvoke(Fn);
1055}
1056
David Majnemer7c237072015-03-05 00:46:22 +00001057static llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) {
1058 // void *__cxa_allocate_exception(size_t thrown_size);
1059
1060 llvm::FunctionType *FTy =
1061 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false);
1062
1063 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
1064}
1065
1066static llvm::Constant *getThrowFn(CodeGenModule &CGM) {
1067 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
1068 // void (*dest) (void *));
1069
1070 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
1071 llvm::FunctionType *FTy =
1072 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
1073
1074 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
1075}
1076
1077void ItaniumCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
1078 QualType ThrowType = E->getSubExpr()->getType();
1079 // Now allocate the exception object.
1080 llvm::Type *SizeTy = CGF.ConvertType(getContext().getSizeType());
1081 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
1082
1083 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM);
1084 llvm::CallInst *ExceptionPtr = CGF.EmitNounwindRuntimeCall(
1085 AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception");
1086
John McCall7f416cc2015-09-08 08:05:57 +00001087 CharUnits ExnAlign = getAlignmentOfExnObject();
1088 CGF.EmitAnyExprToExn(E->getSubExpr(), Address(ExceptionPtr, ExnAlign));
David Majnemer7c237072015-03-05 00:46:22 +00001089
1090 // Now throw the exception.
1091 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
1092 /*ForEH=*/true);
1093
1094 // The address of the destructor. If the exception type has a
1095 // trivial destructor (or isn't a record), we just pass null.
1096 llvm::Constant *Dtor = nullptr;
1097 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
1098 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
1099 if (!Record->hasTrivialDestructor()) {
1100 CXXDestructorDecl *DtorD = Record->getDestructor();
1101 Dtor = CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete);
1102 Dtor = llvm::ConstantExpr::getBitCast(Dtor, CGM.Int8PtrTy);
1103 }
1104 }
1105 if (!Dtor) Dtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
1106
1107 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
1108 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
1109}
1110
David Majnemer1162d252014-06-22 19:05:33 +00001111static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) {
1112 // void *__dynamic_cast(const void *sub,
1113 // const abi::__class_type_info *src,
1114 // const abi::__class_type_info *dst,
1115 // std::ptrdiff_t src2dst_offset);
1116
1117 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1118 llvm::Type *PtrDiffTy =
1119 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1120
1121 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
1122
1123 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
1124
1125 // Mark the function as nounwind readonly.
1126 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
1127 llvm::Attribute::ReadOnly };
1128 llvm::AttributeSet Attrs = llvm::AttributeSet::get(
1129 CGF.getLLVMContext(), llvm::AttributeSet::FunctionIndex, FuncAttrs);
1130
1131 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
1132}
1133
1134static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1135 // void __cxa_bad_cast();
1136 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1137 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1138}
1139
1140/// \brief Compute the src2dst_offset hint as described in the
1141/// Itanium C++ ABI [2.9.7]
1142static CharUnits computeOffsetHint(ASTContext &Context,
1143 const CXXRecordDecl *Src,
1144 const CXXRecordDecl *Dst) {
1145 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1146 /*DetectVirtual=*/false);
1147
1148 // If Dst is not derived from Src we can skip the whole computation below and
1149 // return that Src is not a public base of Dst. Record all inheritance paths.
1150 if (!Dst->isDerivedFrom(Src, Paths))
1151 return CharUnits::fromQuantity(-2ULL);
1152
1153 unsigned NumPublicPaths = 0;
1154 CharUnits Offset;
1155
1156 // Now walk all possible inheritance paths.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001157 for (const CXXBasePath &Path : Paths) {
1158 if (Path.Access != AS_public) // Ignore non-public inheritance.
David Majnemer1162d252014-06-22 19:05:33 +00001159 continue;
1160
1161 ++NumPublicPaths;
1162
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001163 for (const CXXBasePathElement &PathElement : Path) {
David Majnemer1162d252014-06-22 19:05:33 +00001164 // If the path contains a virtual base class we can't give any hint.
1165 // -1: no hint.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001166 if (PathElement.Base->isVirtual())
David Majnemer1162d252014-06-22 19:05:33 +00001167 return CharUnits::fromQuantity(-1ULL);
1168
1169 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
1170 continue;
1171
1172 // Accumulate the base class offsets.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001173 const ASTRecordLayout &L = Context.getASTRecordLayout(PathElement.Class);
1174 Offset += L.getBaseClassOffset(
1175 PathElement.Base->getType()->getAsCXXRecordDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001176 }
1177 }
1178
1179 // -2: Src is not a public base of Dst.
1180 if (NumPublicPaths == 0)
1181 return CharUnits::fromQuantity(-2ULL);
1182
1183 // -3: Src is a multiple public base type but never a virtual base type.
1184 if (NumPublicPaths > 1)
1185 return CharUnits::fromQuantity(-3ULL);
1186
1187 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
1188 // Return the offset of Src from the origin of Dst.
1189 return Offset;
1190}
1191
1192static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1193 // void __cxa_bad_typeid();
1194 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1195
1196 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1197}
1198
1199bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
1200 QualType SrcRecordTy) {
1201 return IsDeref;
1202}
1203
1204void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
1205 llvm::Value *Fn = getBadTypeidFn(CGF);
1206 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1207 CGF.Builder.CreateUnreachable();
1208}
1209
1210llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
1211 QualType SrcRecordTy,
John McCall7f416cc2015-09-08 08:05:57 +00001212 Address ThisPtr,
David Majnemer1162d252014-06-22 19:05:33 +00001213 llvm::Type *StdTypeInfoPtrTy) {
1214 llvm::Value *Value =
1215 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo());
1216
1217 // Load the type info.
1218 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001219 return CGF.Builder.CreateAlignedLoad(Value, CGF.getPointerAlign());
David Majnemer1162d252014-06-22 19:05:33 +00001220}
1221
1222bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1223 QualType SrcRecordTy) {
1224 return SrcIsPtr;
1225}
1226
1227llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
John McCall7f416cc2015-09-08 08:05:57 +00001228 CodeGenFunction &CGF, Address ThisAddr, QualType SrcRecordTy,
David Majnemer1162d252014-06-22 19:05:33 +00001229 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1230 llvm::Type *PtrDiffLTy =
1231 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1232 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1233
1234 llvm::Value *SrcRTTI =
1235 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1236 llvm::Value *DestRTTI =
1237 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1238
1239 // Compute the offset hint.
1240 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1241 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1242 llvm::Value *OffsetHint = llvm::ConstantInt::get(
1243 PtrDiffLTy,
1244 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
1245
1246 // Emit the call to __dynamic_cast.
John McCall7f416cc2015-09-08 08:05:57 +00001247 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001248 Value = CGF.EmitCastToVoidPtr(Value);
1249
1250 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
1251 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
1252 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1253
1254 /// C++ [expr.dynamic.cast]p9:
1255 /// A failed cast to reference type throws std::bad_cast
1256 if (DestTy->isReferenceType()) {
1257 llvm::BasicBlock *BadCastBlock =
1258 CGF.createBasicBlock("dynamic_cast.bad_cast");
1259
1260 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1261 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1262
1263 CGF.EmitBlock(BadCastBlock);
1264 EmitBadCastCall(CGF);
1265 }
1266
1267 return Value;
1268}
1269
1270llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001271 Address ThisAddr,
David Majnemer1162d252014-06-22 19:05:33 +00001272 QualType SrcRecordTy,
1273 QualType DestTy) {
1274 llvm::Type *PtrDiffLTy =
1275 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1276 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1277
1278 // Get the vtable pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001279 llvm::Value *VTable = CGF.GetVTablePtr(ThisAddr, PtrDiffLTy->getPointerTo());
David Majnemer1162d252014-06-22 19:05:33 +00001280
1281 // Get the offset-to-top from the vtable.
1282 llvm::Value *OffsetToTop =
1283 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001284 OffsetToTop =
1285 CGF.Builder.CreateAlignedLoad(OffsetToTop, CGF.getPointerAlign(),
1286 "offset.to.top");
David Majnemer1162d252014-06-22 19:05:33 +00001287
1288 // Finally, add the offset to the pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001289 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001290 Value = CGF.EmitCastToVoidPtr(Value);
1291 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1292
1293 return CGF.Builder.CreateBitCast(Value, DestLTy);
1294}
1295
1296bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1297 llvm::Value *Fn = getBadCastFn(CGF);
1298 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1299 CGF.Builder.CreateUnreachable();
1300 return true;
1301}
1302
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001303llvm::Value *
1304ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001305 Address This,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001306 const CXXRecordDecl *ClassDecl,
1307 const CXXRecordDecl *BaseClassDecl) {
1308 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy);
1309 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001310 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1311 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001312
1313 llvm::Value *VBaseOffsetPtr =
1314 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1315 "vbase.offset.ptr");
1316 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1317 CGM.PtrDiffTy->getPointerTo());
1318
1319 llvm::Value *VBaseOffset =
John McCall7f416cc2015-09-08 08:05:57 +00001320 CGF.Builder.CreateAlignedLoad(VBaseOffsetPtr, CGF.getPointerAlign(),
1321 "vbase.offset");
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001322
1323 return VBaseOffset;
1324}
1325
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001326void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1327 // Just make sure we're in sync with TargetCXXABI.
1328 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1329
Rafael Espindolac3cde362013-12-09 14:51:17 +00001330 // The constructor used for constructing this as a base class;
1331 // ignores virtual bases.
1332 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1333
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001334 // The constructor used for constructing this as a complete class;
Nico Weber4c2ffb22015-01-07 05:25:05 +00001335 // constructs the virtual bases, then calls the base constructor.
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001336 if (!D->getParent()->isAbstract()) {
1337 // We don't need to emit the complete ctor if the class is abstract.
1338 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1339 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001340}
1341
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001342void
1343ItaniumCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
1344 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +00001345 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001346
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001347 // All parameters are already in place except VTT, which goes after 'this'.
1348 // These are Clang types, so we don't need to worry about sret yet.
John McCall5d865c322010-08-31 07:33:07 +00001349
1350 // Check if we need to add a VTT parameter (which has type void **).
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001351 if (T == StructorType::Base && MD->getParent()->getNumVBases() != 0)
1352 ArgTys.insert(ArgTys.begin() + 1,
1353 Context.getPointerType(Context.VoidPtrTy));
John McCall5d865c322010-08-31 07:33:07 +00001354}
1355
Reid Klecknere7de47e2013-07-22 13:51:44 +00001356void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
Rafael Espindolac3cde362013-12-09 14:51:17 +00001357 // The destructor used for destructing this as a base class; ignores
1358 // virtual bases.
1359 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001360
1361 // The destructor used for destructing this as a most-derived class;
1362 // call the base destructor and then destructs any virtual bases.
1363 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1364
Rafael Espindolac3cde362013-12-09 14:51:17 +00001365 // The destructor in a virtual table is always a 'deleting'
1366 // destructor, which calls the complete destructor and then uses the
1367 // appropriate operator delete.
1368 if (D->isVirtual())
1369 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001370}
1371
Reid Kleckner89077a12013-12-17 19:46:40 +00001372void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1373 QualType &ResTy,
1374 FunctionArgList &Params) {
John McCall5d865c322010-08-31 07:33:07 +00001375 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +00001376 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
John McCall5d865c322010-08-31 07:33:07 +00001377
1378 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001379 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +00001380 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001381
1382 // FIXME: avoid the fake decl
1383 QualType T = Context.getPointerType(Context.VoidPtrTy);
1384 ImplicitParamDecl *VTTDecl
Craig Topper8a13c412014-05-21 05:09:00 +00001385 = ImplicitParamDecl::Create(Context, nullptr, MD->getLocation(),
John McCall5d865c322010-08-31 07:33:07 +00001386 &Context.Idents.get("vtt"), T);
Reid Kleckner89077a12013-12-17 19:46:40 +00001387 Params.insert(Params.begin() + 1, VTTDecl);
Reid Kleckner2af6d732013-12-13 00:09:59 +00001388 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +00001389 }
1390}
1391
John McCall5d865c322010-08-31 07:33:07 +00001392void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1393 /// Initialize the 'this' slot.
1394 EmitThisParam(CGF);
1395
1396 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +00001397 if (getStructorImplicitParamDecl(CGF)) {
1398 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1399 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +00001400 }
John McCall5d865c322010-08-31 07:33:07 +00001401
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001402 /// If this is a function that the ABI specifies returns 'this', initialize
1403 /// the return slot to 'this' at the start of the function.
1404 ///
1405 /// Unlike the setting of return types, this is done within the ABI
1406 /// implementation instead of by clients of CGCXXABI because:
1407 /// 1) getThisValue is currently protected
1408 /// 2) in theory, an ABI could implement 'this' returns some other way;
1409 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +00001410 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +00001411 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +00001412}
1413
Reid Kleckner89077a12013-12-17 19:46:40 +00001414unsigned ItaniumCXXABI::addImplicitConstructorArgs(
1415 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1416 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1417 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
1418 return 0;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001419
Reid Kleckner89077a12013-12-17 19:46:40 +00001420 // Insert the implicit 'vtt' argument as the second argument.
1421 llvm::Value *VTT =
1422 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1423 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1424 Args.insert(Args.begin() + 1,
1425 CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false));
1426 return 1; // Added one arg.
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001427}
1428
1429void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1430 const CXXDestructorDecl *DD,
1431 CXXDtorType Type, bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +00001432 bool Delegating, Address This) {
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001433 GlobalDecl GD(DD, Type);
1434 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1435 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1436
Craig Topper8a13c412014-05-21 05:09:00 +00001437 llvm::Value *Callee = nullptr;
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001438 if (getContext().getLangOpts().AppleKext)
1439 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
1440
1441 if (!Callee)
Rafael Espindola1ac0ec82014-09-11 15:42:06 +00001442 Callee = CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type));
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001443
John McCall7f416cc2015-09-08 08:05:57 +00001444 CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(),
1445 This.getPointer(), VTT, VTTTy, nullptr);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001446}
1447
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001448void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1449 const CXXRecordDecl *RD) {
1450 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1451 if (VTable->hasInitializer())
1452 return;
1453
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001454 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001455 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1456 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
David Majnemerd905da42014-07-01 20:30:31 +00001457 llvm::Constant *RTTI =
1458 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001459
1460 // Create and set the initializer.
1461 llvm::Constant *Init = CGVT.CreateVTableInitializer(
1462 RD, VTLayout.vtable_component_begin(), VTLayout.getNumVTableComponents(),
David Majnemerd905da42014-07-01 20:30:31 +00001463 VTLayout.vtable_thunk_begin(), VTLayout.getNumVTableThunks(), RTTI);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001464 VTable->setInitializer(Init);
1465
1466 // Set the correct linkage.
1467 VTable->setLinkage(Linkage);
1468
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001469 if (CGM.supportsCOMDAT() && VTable->isWeakForLinker())
1470 VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName()));
Rafael Espindolacb92c192015-01-15 23:18:01 +00001471
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001472 // Set the right visibility.
John McCall8f80a612014-02-08 00:41:16 +00001473 CGM.setGlobalVisibility(VTable, RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001474
Benjamin Kramer5d34a2b2014-09-10 12:50:59 +00001475 // Use pointer alignment for the vtable. Otherwise we would align them based
1476 // on the size of the initializer which doesn't make sense as only single
1477 // values are read.
1478 unsigned PAlign = CGM.getTarget().getPointerAlign(0);
1479 VTable->setAlignment(getContext().toCharUnitsFromBits(PAlign).getQuantity());
1480
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001481 // If this is the magic class __cxxabiv1::__fundamental_type_info,
1482 // we will emit the typeinfo for the fundamental types. This is the
1483 // same behaviour as GCC.
1484 const DeclContext *DC = RD->getDeclContext();
1485 if (RD->getIdentifier() &&
1486 RD->getIdentifier()->isStr("__fundamental_type_info") &&
1487 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1488 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1489 DC->getParent()->isTranslationUnit())
David Majnemere2cb8d12014-07-07 06:20:47 +00001490 EmitFundamentalRTTIDescriptors();
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001491
1492 CGM.EmitVTableBitSetEntries(VTable, VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001493}
1494
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001495bool ItaniumCXXABI::isVirtualOffsetNeededForVTableField(
1496 CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
1497 if (Vptr.NearestVBase == nullptr)
1498 return false;
1499 return NeedsVTTParameter(CGF.CurGD);
Piotr Padlewski255652e2015-09-09 22:20:28 +00001500}
1501
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001502llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1503 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1504 const CXXRecordDecl *NearestVBase) {
1505
1506 if ((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1507 NeedsVTTParameter(CGF.CurGD)) {
1508 return getVTableAddressPointInStructorWithVTT(CGF, VTableClass, Base,
1509 NearestVBase);
1510 }
1511 return getVTableAddressPoint(Base, VTableClass);
1512}
1513
1514llvm::Constant *
1515ItaniumCXXABI::getVTableAddressPoint(BaseSubobject Base,
1516 const CXXRecordDecl *VTableClass) {
1517 llvm::GlobalValue *VTable = getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001518
1519 // Find the appropriate vtable within the vtable group.
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001520 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1521 .getVTableLayout(VTableClass)
1522 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001523 llvm::Value *Indices[] = {
1524 llvm::ConstantInt::get(CGM.Int64Ty, 0),
1525 llvm::ConstantInt::get(CGM.Int64Ty, AddressPoint)
1526 };
1527
David Blaikiee3b172a2015-04-02 18:55:21 +00001528 return llvm::ConstantExpr::getInBoundsGetElementPtr(VTable->getValueType(),
1529 VTable, Indices);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001530}
1531
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001532llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructorWithVTT(
1533 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1534 const CXXRecordDecl *NearestVBase) {
1535 assert((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1536 NeedsVTTParameter(CGF.CurGD) && "This class doesn't have VTT");
1537
1538 // Get the secondary vpointer index.
1539 uint64_t VirtualPointerIndex =
1540 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1541
1542 /// Load the VTT.
1543 llvm::Value *VTT = CGF.LoadCXXVTT();
1544 if (VirtualPointerIndex)
1545 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1546
1547 // And load the address point from the VTT.
1548 return CGF.Builder.CreateAlignedLoad(VTT, CGF.getPointerAlign());
1549}
1550
1551llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1552 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1553 return getVTableAddressPoint(Base, VTableClass);
1554}
1555
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001556llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1557 CharUnits VPtrOffset) {
1558 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1559
1560 llvm::GlobalVariable *&VTable = VTables[RD];
1561 if (VTable)
1562 return VTable;
1563
1564 // Queue up this v-table for possible deferred emission.
1565 CGM.addDeferredVTable(RD);
1566
Yaron Kerene46f7ed2015-07-29 14:21:47 +00001567 SmallString<256> Name;
1568 llvm::raw_svector_ostream Out(Name);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001569 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001570
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001571 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001572 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
1573 CGM.Int8PtrTy, VTContext.getVTableLayout(RD).getNumVTableComponents());
1574
1575 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
1576 Name, ArrayType, llvm::GlobalValue::ExternalLinkage);
1577 VTable->setUnnamedAddr(true);
Hans Wennborgda24e9c2014-06-02 23:13:03 +00001578
1579 if (RD->hasAttr<DLLImportAttr>())
1580 VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1581 else if (RD->hasAttr<DLLExportAttr>())
1582 VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1583
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001584 return VTable;
1585}
1586
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001587llvm::Value *ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1588 GlobalDecl GD,
John McCall7f416cc2015-09-08 08:05:57 +00001589 Address This,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001590 llvm::Type *Ty,
1591 SourceLocation Loc) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001592 GD = GD.getCanonicalDecl();
1593 Ty = Ty->getPointerTo()->getPointerTo();
1594 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty);
1595
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00001596 if (CGF.SanOpts.has(SanitizerKind::CFIVCall))
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001597 CGF.EmitVTablePtrCheckForCall(cast<CXXMethodDecl>(GD.getDecl()), VTable,
1598 CodeGenFunction::CFITCK_VCall, Loc);
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001599
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001600 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001601 llvm::Value *VFuncPtr =
1602 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
John McCall7f416cc2015-09-08 08:05:57 +00001603 return CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign());
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001604}
1605
David Majnemer0c0b6d92014-10-31 20:09:12 +00001606llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
1607 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
John McCall7f416cc2015-09-08 08:05:57 +00001608 Address This, const CXXMemberCallExpr *CE) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001609 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001610 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1611
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001612 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1613 Dtor, getFromDtorType(DtorType));
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001614 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001615 llvm::Value *Callee =
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001616 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty,
1617 CE ? CE->getLocStart() : SourceLocation());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001618
John McCall7f416cc2015-09-08 08:05:57 +00001619 CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(),
1620 This.getPointer(), /*ImplicitParam=*/nullptr,
1621 QualType(), CE);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001622 return nullptr;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001623}
1624
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001625void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001626 CodeGenVTables &VTables = CGM.getVTables();
1627 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001628 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001629}
1630
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001631bool ItaniumCXXABI::canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const {
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001632 // We don't emit available_externally vtables if we are in -fapple-kext mode
1633 // because kext mode does not permit devirtualization.
1634 if (CGM.getLangOpts().AppleKext)
1635 return false;
1636
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001637 // If we don't have any inline virtual functions, and if vtable is not hidden,
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001638 // then we are safe to emit available_externally copy of vtable.
1639 // FIXME we can still emit a copy of the vtable if we
1640 // can emit definition of the inline functions.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001641 return !hasAnyUsedVirtualInlineFunction(RD) && !isVTableHidden(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001642}
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001643static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001644 Address InitialPtr,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001645 int64_t NonVirtualAdjustment,
1646 int64_t VirtualAdjustment,
1647 bool IsReturnAdjustment) {
1648 if (!NonVirtualAdjustment && !VirtualAdjustment)
John McCall7f416cc2015-09-08 08:05:57 +00001649 return InitialPtr.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001650
John McCall7f416cc2015-09-08 08:05:57 +00001651 Address V = CGF.Builder.CreateElementBitCast(InitialPtr, CGF.Int8Ty);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001652
John McCall7f416cc2015-09-08 08:05:57 +00001653 // In a base-to-derived cast, the non-virtual adjustment is applied first.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001654 if (NonVirtualAdjustment && !IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001655 V = CGF.Builder.CreateConstInBoundsByteGEP(V,
1656 CharUnits::fromQuantity(NonVirtualAdjustment));
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001657 }
1658
John McCall7f416cc2015-09-08 08:05:57 +00001659 // Perform the virtual adjustment if we have one.
1660 llvm::Value *ResultPtr;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001661 if (VirtualAdjustment) {
1662 llvm::Type *PtrDiffTy =
1663 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1664
John McCall7f416cc2015-09-08 08:05:57 +00001665 Address VTablePtrPtr = CGF.Builder.CreateElementBitCast(V, CGF.Int8PtrTy);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001666 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1667
1668 llvm::Value *OffsetPtr =
1669 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1670
1671 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1672
1673 // Load the adjustment offset from the vtable.
John McCall7f416cc2015-09-08 08:05:57 +00001674 llvm::Value *Offset =
1675 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001676
1677 // Adjust our pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001678 ResultPtr = CGF.Builder.CreateInBoundsGEP(V.getPointer(), Offset);
1679 } else {
1680 ResultPtr = V.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001681 }
1682
John McCall7f416cc2015-09-08 08:05:57 +00001683 // In a derived-to-base conversion, the non-virtual adjustment is
1684 // applied second.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001685 if (NonVirtualAdjustment && IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001686 ResultPtr = CGF.Builder.CreateConstInBoundsGEP1_64(ResultPtr,
1687 NonVirtualAdjustment);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001688 }
1689
1690 // Cast back to the original type.
John McCall7f416cc2015-09-08 08:05:57 +00001691 return CGF.Builder.CreateBitCast(ResultPtr, InitialPtr.getType());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001692}
1693
1694llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001695 Address This,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001696 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001697 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1698 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001699 /*IsReturnAdjustment=*/false);
1700}
1701
1702llvm::Value *
John McCall7f416cc2015-09-08 08:05:57 +00001703ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001704 const ReturnAdjustment &RA) {
1705 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1706 RA.Virtual.Itanium.VBaseOffsetOffset,
1707 /*IsReturnAdjustment=*/true);
1708}
1709
John McCall5d865c322010-08-31 07:33:07 +00001710void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1711 RValue RV, QualType ResultType) {
1712 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1713 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1714
1715 // Destructor thunks in the ARM ABI have indeterminate results.
John McCall7f416cc2015-09-08 08:05:57 +00001716 llvm::Type *T = CGF.ReturnValue.getElementType();
John McCall5d865c322010-08-31 07:33:07 +00001717 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1718 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1719}
John McCall8ed55a52010-09-02 09:58:18 +00001720
1721/************************** Array allocation cookies **************************/
1722
John McCallb91cd662012-05-01 05:23:51 +00001723CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1724 // The array cookie is a size_t; pad that up to the element alignment.
1725 // The cookie is actually right-justified in that space.
1726 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1727 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001728}
1729
John McCall7f416cc2015-09-08 08:05:57 +00001730Address ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1731 Address NewPtr,
1732 llvm::Value *NumElements,
1733 const CXXNewExpr *expr,
1734 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001735 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001736
John McCall7f416cc2015-09-08 08:05:57 +00001737 unsigned AS = NewPtr.getAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001738
John McCall9bca9232010-09-02 10:25:57 +00001739 ASTContext &Ctx = getContext();
John McCall7f416cc2015-09-08 08:05:57 +00001740 CharUnits SizeSize = CGF.getSizeSize();
John McCall8ed55a52010-09-02 09:58:18 +00001741
1742 // The size of the cookie.
1743 CharUnits CookieSize =
1744 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001745 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001746
1747 // Compute an offset to the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001748 Address CookiePtr = NewPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001749 CharUnits CookieOffset = CookieSize - SizeSize;
1750 if (!CookieOffset.isZero())
John McCall7f416cc2015-09-08 08:05:57 +00001751 CookiePtr = CGF.Builder.CreateConstInBoundsByteGEP(CookiePtr, CookieOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001752
1753 // Write the number of elements into the appropriate slot.
John McCall7f416cc2015-09-08 08:05:57 +00001754 Address NumElementsPtr =
1755 CGF.Builder.CreateElementBitCast(CookiePtr, CGF.SizeTy);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001756 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
John McCall7f416cc2015-09-08 08:05:57 +00001757
1758 // Handle the array cookie specially in ASan.
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001759 if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 &&
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001760 expr->getOperatorNew()->isReplaceableGlobalAllocationFunction()) {
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001761 // The store to the CookiePtr does not need to be instrumented.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001762 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
1763 llvm::FunctionType *FTy =
John McCall7f416cc2015-09-08 08:05:57 +00001764 llvm::FunctionType::get(CGM.VoidTy, NumElementsPtr.getType(), false);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001765 llvm::Constant *F =
1766 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001767 CGF.Builder.CreateCall(F, NumElementsPtr.getPointer());
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001768 }
John McCall8ed55a52010-09-02 09:58:18 +00001769
1770 // Finally, compute a pointer to the actual data buffer by skipping
1771 // over the cookie completely.
John McCall7f416cc2015-09-08 08:05:57 +00001772 return CGF.Builder.CreateConstInBoundsByteGEP(NewPtr, CookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001773}
1774
John McCallb91cd662012-05-01 05:23:51 +00001775llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001776 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00001777 CharUnits cookieSize) {
1778 // The element size is right-justified in the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001779 Address numElementsPtr = allocPtr;
1780 CharUnits numElementsOffset = cookieSize - CGF.getSizeSize();
John McCallb91cd662012-05-01 05:23:51 +00001781 if (!numElementsOffset.isZero())
1782 numElementsPtr =
John McCall7f416cc2015-09-08 08:05:57 +00001783 CGF.Builder.CreateConstInBoundsByteGEP(numElementsPtr, numElementsOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001784
John McCall7f416cc2015-09-08 08:05:57 +00001785 unsigned AS = allocPtr.getAddressSpace();
1786 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001787 if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0)
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001788 return CGF.Builder.CreateLoad(numElementsPtr);
1789 // In asan mode emit a function call instead of a regular load and let the
1790 // run-time deal with it: if the shadow is properly poisoned return the
1791 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
1792 // We can't simply ignore this load using nosanitize metadata because
1793 // the metadata may be lost.
1794 llvm::FunctionType *FTy =
1795 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
1796 llvm::Constant *F =
1797 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001798 return CGF.Builder.CreateCall(F, numElementsPtr.getPointer());
John McCall8ed55a52010-09-02 09:58:18 +00001799}
1800
John McCallb91cd662012-05-01 05:23:51 +00001801CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001802 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001803 // struct array_cookie {
1804 // std::size_t element_size; // element_size != 0
1805 // std::size_t element_count;
1806 // };
John McCallc19c7062013-01-25 23:36:19 +00001807 // But the base ABI doesn't give anything an alignment greater than
1808 // 8, so we can dismiss this as typical ABI-author blindness to
1809 // actual language complexity and round up to the element alignment.
1810 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1811 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001812}
1813
John McCall7f416cc2015-09-08 08:05:57 +00001814Address ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1815 Address newPtr,
1816 llvm::Value *numElements,
1817 const CXXNewExpr *expr,
1818 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001819 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001820
John McCall8ed55a52010-09-02 09:58:18 +00001821 // The cookie is always at the start of the buffer.
John McCall7f416cc2015-09-08 08:05:57 +00001822 Address cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001823
1824 // The first element is the element size.
John McCall7f416cc2015-09-08 08:05:57 +00001825 cookie = CGF.Builder.CreateElementBitCast(cookie, CGF.SizeTy);
John McCallc19c7062013-01-25 23:36:19 +00001826 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1827 getContext().getTypeSizeInChars(elementType).getQuantity());
1828 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001829
1830 // The second element is the element count.
John McCall7f416cc2015-09-08 08:05:57 +00001831 cookie = CGF.Builder.CreateConstInBoundsGEP(cookie, 1, CGF.getSizeSize());
John McCallc19c7062013-01-25 23:36:19 +00001832 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001833
1834 // Finally, compute a pointer to the actual data buffer by skipping
1835 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001836 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
John McCall7f416cc2015-09-08 08:05:57 +00001837 return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001838}
1839
John McCallb91cd662012-05-01 05:23:51 +00001840llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001841 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00001842 CharUnits cookieSize) {
1843 // The number of elements is at offset sizeof(size_t) relative to
1844 // the allocated pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001845 Address numElementsPtr
1846 = CGF.Builder.CreateConstInBoundsByteGEP(allocPtr, CGF.getSizeSize());
John McCall8ed55a52010-09-02 09:58:18 +00001847
John McCall7f416cc2015-09-08 08:05:57 +00001848 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
John McCallb91cd662012-05-01 05:23:51 +00001849 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001850}
1851
John McCall68ff0372010-09-08 01:44:27 +00001852/*********************** Static local initialization **************************/
1853
1854static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001855 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001856 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001857 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001858 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001859 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001860 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001861 llvm::AttributeSet::get(CGM.getLLVMContext(),
1862 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001863 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001864}
1865
1866static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001867 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001868 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001869 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001870 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001871 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001872 llvm::AttributeSet::get(CGM.getLLVMContext(),
1873 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001874 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001875}
1876
1877static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001878 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001879 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001880 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001881 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001882 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001883 llvm::AttributeSet::get(CGM.getLLVMContext(),
1884 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001885 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001886}
1887
1888namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001889 struct CallGuardAbort final : EHScopeStack::Cleanup {
John McCall68ff0372010-09-08 01:44:27 +00001890 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001891 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001892
Craig Topper4f12f102014-03-12 06:41:41 +00001893 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00001894 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1895 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001896 }
1897 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001898}
John McCall68ff0372010-09-08 01:44:27 +00001899
1900/// The ARM code here follows the Itanium code closely enough that we
1901/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001902void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1903 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001904 llvm::GlobalVariable *var,
1905 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00001906 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00001907
Richard Smithdbf74ba2013-04-14 23:01:42 +00001908 // We only need to use thread-safe statics for local non-TLS variables;
John McCallcdf7ef52010-11-06 09:44:32 +00001909 // global initialization is always single-threaded.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001910 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
1911 D.isLocalVarDecl() && !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001912
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001913 // If we have a global variable with internal linkage and thread-safe statics
1914 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00001915 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1916
1917 llvm::IntegerType *guardTy;
John McCall7f416cc2015-09-08 08:05:57 +00001918 CharUnits guardAlignment;
John McCall5aa52592011-06-17 07:33:57 +00001919 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00001920 guardTy = CGF.Int8Ty;
John McCall7f416cc2015-09-08 08:05:57 +00001921 guardAlignment = CharUnits::One();
John McCall5aa52592011-06-17 07:33:57 +00001922 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00001923 // Guard variables are 64 bits in the generic ABI and size width on ARM
1924 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
John McCall7f416cc2015-09-08 08:05:57 +00001925 if (UseARMGuardVarABI) {
1926 guardTy = CGF.SizeTy;
1927 guardAlignment = CGF.getSizeAlign();
1928 } else {
1929 guardTy = CGF.Int64Ty;
1930 guardAlignment = CharUnits::fromQuantity(
1931 CGM.getDataLayout().getABITypeAlignment(guardTy));
1932 }
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001933 }
John McCallb88a5662012-03-30 21:00:39 +00001934 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00001935
John McCallb88a5662012-03-30 21:00:39 +00001936 // Create the guard variable if we don't already have it (as we
1937 // might if we're double-emitting this function body).
1938 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1939 if (!guard) {
1940 // Mangle the name for the guard.
1941 SmallString<256> guardName;
1942 {
1943 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00001944 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00001945 }
John McCall8e7cb6d2010-11-02 21:04:24 +00001946
John McCallb88a5662012-03-30 21:00:39 +00001947 // Create the guard variable with a zero-initializer.
1948 // Just absorb linkage and visibility from the guarded variable.
1949 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1950 false, var->getLinkage(),
1951 llvm::ConstantInt::get(guardTy, 0),
1952 guardName.str());
1953 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00001954 // If the variable is thread-local, so is its guard variable.
1955 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCall7f416cc2015-09-08 08:05:57 +00001956 guard->setAlignment(guardAlignment.getQuantity());
John McCallb88a5662012-03-30 21:00:39 +00001957
Yaron Keren5bfa1082015-09-03 20:33:29 +00001958 // The ABI says: "It is suggested that it be emitted in the same COMDAT
1959 // group as the associated data object." In practice, this doesn't work for
1960 // non-ELF object formats, so only do it for ELF.
Rafael Espindola0d4fb982015-01-12 22:13:53 +00001961 llvm::Comdat *C = var->getComdat();
Yaron Keren5bfa1082015-09-03 20:33:29 +00001962 if (!D.isLocalVarDecl() && C &&
1963 CGM.getTarget().getTriple().isOSBinFormatELF()) {
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001964 guard->setComdat(C);
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001965 CGF.CurFn->setComdat(C);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001966 } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) {
1967 guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName()));
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001968 }
1969
John McCallb88a5662012-03-30 21:00:39 +00001970 CGM.setStaticLocalDeclGuardAddress(&D, guard);
1971 }
John McCall87590e62012-03-30 07:09:50 +00001972
John McCall7f416cc2015-09-08 08:05:57 +00001973 Address guardAddr = Address(guard, guardAlignment);
1974
John McCall68ff0372010-09-08 01:44:27 +00001975 // Test whether the variable has completed initialization.
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001976 //
John McCall68ff0372010-09-08 01:44:27 +00001977 // Itanium C++ ABI 3.3.2:
1978 // The following is pseudo-code showing how these functions can be used:
1979 // if (obj_guard.first_byte == 0) {
1980 // if ( __cxa_guard_acquire (&obj_guard) ) {
1981 // try {
1982 // ... initialize the object ...;
1983 // } catch (...) {
1984 // __cxa_guard_abort (&obj_guard);
1985 // throw;
1986 // }
1987 // ... queue object destructor with __cxa_atexit() ...;
1988 // __cxa_guard_release (&obj_guard);
1989 // }
1990 // }
Tim Northovera2ee4332014-03-29 15:09:45 +00001991
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001992 // Load the first byte of the guard variable.
1993 llvm::LoadInst *LI =
John McCall7f416cc2015-09-08 08:05:57 +00001994 Builder.CreateLoad(Builder.CreateElementBitCast(guardAddr, CGM.Int8Ty));
John McCall68ff0372010-09-08 01:44:27 +00001995
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001996 // Itanium ABI:
1997 // An implementation supporting thread-safety on multiprocessor
1998 // systems must also guarantee that references to the initialized
1999 // object do not occur before the load of the initialization flag.
2000 //
2001 // In LLVM, we do this by marking the load Acquire.
2002 if (threadsafe)
2003 LI->setAtomic(llvm::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00002004
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002005 // For ARM, we should only check the first bit, rather than the entire byte:
2006 //
2007 // ARM C++ ABI 3.2.3.1:
2008 // To support the potential use of initialization guard variables
2009 // as semaphores that are the target of ARM SWP and LDREX/STREX
2010 // synchronizing instructions we define a static initialization
2011 // guard variable to be a 4-byte aligned, 4-byte word with the
2012 // following inline access protocol.
2013 // #define INITIALIZED 1
2014 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
2015 // if (__cxa_guard_acquire(&obj_guard))
2016 // ...
2017 // }
2018 //
2019 // and similarly for ARM64:
2020 //
2021 // ARM64 C++ ABI 3.2.2:
2022 // This ABI instead only specifies the value bit 0 of the static guard
2023 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
2024 // variable is not initialized and 1 when it is.
2025 llvm::Value *V =
2026 (UseARMGuardVarABI && !useInt8GuardVariable)
2027 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
2028 : LI;
2029 llvm::Value *isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00002030
2031 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
2032 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2033
2034 // Check if the first byte of the guard variable is zero.
John McCallb88a5662012-03-30 21:00:39 +00002035 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall68ff0372010-09-08 01:44:27 +00002036
2037 CGF.EmitBlock(InitCheckBlock);
2038
2039 // Variables used when coping with thread-safe statics and exceptions.
John McCall5aa52592011-06-17 07:33:57 +00002040 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002041 // Call __cxa_guard_acquire.
2042 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00002043 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00002044
2045 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2046
2047 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
2048 InitBlock, EndBlock);
2049
2050 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00002051 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall68ff0372010-09-08 01:44:27 +00002052
2053 CGF.EmitBlock(InitBlock);
2054 }
2055
2056 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00002057 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00002058
John McCall5aa52592011-06-17 07:33:57 +00002059 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002060 // Pop the guard-abort cleanup if we pushed one.
2061 CGF.PopCleanupBlock();
2062
2063 // Call __cxa_guard_release. This cannot throw.
John McCall7f416cc2015-09-08 08:05:57 +00002064 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy),
2065 guardAddr.getPointer());
John McCall68ff0372010-09-08 01:44:27 +00002066 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002067 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guardAddr);
John McCall68ff0372010-09-08 01:44:27 +00002068 }
2069
2070 CGF.EmitBlock(EndBlock);
2071}
John McCallc84ed6a2012-05-01 06:13:13 +00002072
2073/// Register a global destructor using __cxa_atexit.
2074static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
2075 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00002076 llvm::Constant *addr,
2077 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00002078 const char *Name = "__cxa_atexit";
2079 if (TLS) {
2080 const llvm::Triple &T = CGF.getTarget().getTriple();
2081 Name = T.isMacOSX() ? "_tlv_atexit" : "__cxa_thread_atexit";
2082 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00002083
John McCallc84ed6a2012-05-01 06:13:13 +00002084 // We're assuming that the destructor function is something we can
2085 // reasonably call with the default CC. Go ahead and cast it to the
2086 // right prototype.
2087 llvm::Type *dtorTy =
2088 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
2089
2090 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
2091 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
2092 llvm::FunctionType *atexitTy =
2093 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
2094
2095 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002096 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00002097 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
2098 fn->setDoesNotThrow();
2099
2100 // Create a variable that binds the atexit to this shared object.
2101 llvm::Constant *handle =
2102 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
2103
2104 llvm::Value *args[] = {
2105 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
2106 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
2107 handle
2108 };
John McCall882987f2013-02-28 19:01:20 +00002109 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00002110}
2111
2112/// Register a global destructor as best as we know how.
2113void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00002114 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00002115 llvm::Constant *dtor,
2116 llvm::Constant *addr) {
2117 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002118 if (CGM.getCodeGenOpts().CXAAtExit)
2119 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
2120
2121 if (D.getTLSKind())
2122 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00002123
2124 // In Apple kexts, we want to add a global destructor entry.
2125 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00002126 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00002127 // Generate a global destructor entry.
2128 return CGM.AddCXXDtorEntry(dtor, addr);
2129 }
2130
David Blaikieebe87e12013-08-27 23:57:18 +00002131 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00002132}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002133
David Majnemer9b21c332014-07-11 20:28:10 +00002134static bool isThreadWrapperReplaceable(const VarDecl *VD,
2135 CodeGen::CodeGenModule &CGM) {
2136 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
2137 // OS X prefers to have references to thread local variables to go through
2138 // the thread wrapper instead of directly referencing the backing variable.
2139 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
2140 CGM.getTarget().getTriple().isMacOSX();
2141}
2142
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002143/// Get the appropriate linkage for the wrapper function. This is essentially
David Majnemer4632e1e2014-06-27 16:56:27 +00002144/// the weak form of the variable's linkage; every translation unit which needs
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002145/// the wrapper emits a copy, and we want the linker to merge them.
David Majnemer35ab3282014-06-11 04:08:55 +00002146static llvm::GlobalValue::LinkageTypes
2147getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
2148 llvm::GlobalValue::LinkageTypes VarLinkage =
2149 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
2150
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002151 // For internal linkage variables, we don't need an external or weak wrapper.
2152 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
2153 return VarLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00002154
David Majnemer9b21c332014-07-11 20:28:10 +00002155 // If the thread wrapper is replaceable, give it appropriate linkage.
2156 if (isThreadWrapperReplaceable(VD, CGM)) {
2157 if (llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) ||
2158 llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
2159 return llvm::GlobalVariable::WeakAnyLinkage;
2160 return VarLinkage;
2161 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002162 return llvm::GlobalValue::WeakODRLinkage;
2163}
2164
2165llvm::Function *
2166ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +00002167 llvm::Value *Val) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002168 // Mangle the name for the thread_local wrapper function.
2169 SmallString<256> WrapperName;
2170 {
2171 llvm::raw_svector_ostream Out(WrapperName);
2172 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002173 }
2174
Alexander Musmanf94c3182014-09-26 06:28:25 +00002175 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002176 return cast<llvm::Function>(V);
2177
Alexander Musmanf94c3182014-09-26 06:28:25 +00002178 llvm::Type *RetTy = Val->getType();
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002179 if (VD->getType()->isReferenceType())
2180 RetTy = RetTy->getPointerElementType();
2181
2182 llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, false);
David Majnemer35ab3282014-06-11 04:08:55 +00002183 llvm::Function *Wrapper =
2184 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
2185 WrapperName.str(), &CGM.getModule());
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002186 // Always resolve references to the wrapper at link time.
David Majnemer9b21c332014-07-11 20:28:10 +00002187 if (!Wrapper->hasLocalLinkage() && !isThreadWrapperReplaceable(VD, CGM))
Duncan P. N. Exon Smith4434d362014-05-07 22:36:11 +00002188 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002189 return Wrapper;
2190}
2191
2192void ItaniumCXXABI::EmitThreadLocalInitFuncs(
David Majnemerb3341ea2014-10-05 05:05:40 +00002193 CodeGenModule &CGM,
2194 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *>>
2195 CXXThreadLocals, ArrayRef<llvm::Function *> CXXThreadLocalInits,
2196 ArrayRef<llvm::GlobalVariable *> CXXThreadLocalInitVars) {
2197 llvm::Function *InitFunc = nullptr;
2198 if (!CXXThreadLocalInits.empty()) {
2199 // Generate a guarded initialization function.
2200 llvm::FunctionType *FTy =
2201 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
2202 InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init",
Alexey Samsonov1444bb92014-10-17 00:20:19 +00002203 SourceLocation(),
David Majnemerb3341ea2014-10-05 05:05:40 +00002204 /*TLS=*/true);
2205 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
2206 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
2207 llvm::GlobalVariable::InternalLinkage,
2208 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
2209 Guard->setThreadLocal(true);
John McCall7f416cc2015-09-08 08:05:57 +00002210
2211 CharUnits GuardAlign = CharUnits::One();
2212 Guard->setAlignment(GuardAlign.getQuantity());
2213
David Majnemerb3341ea2014-10-05 05:05:40 +00002214 CodeGenFunction(CGM)
John McCall7f416cc2015-09-08 08:05:57 +00002215 .GenerateCXXGlobalInitFunc(InitFunc, CXXThreadLocalInits,
2216 Address(Guard, GuardAlign));
David Majnemerb3341ea2014-10-05 05:05:40 +00002217 }
Yaron Kerenede60302015-08-01 19:11:36 +00002218 for (auto &I : CXXThreadLocals) {
2219 const VarDecl *VD = I.first;
2220 llvm::GlobalVariable *Var = I.second;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002221
David Majnemer9b21c332014-07-11 20:28:10 +00002222 // Some targets require that all access to thread local variables go through
2223 // the thread wrapper. This means that we cannot attempt to create a thread
2224 // wrapper or a thread helper.
2225 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition())
2226 continue;
2227
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002228 // Mangle the name for the thread_local initialization function.
2229 SmallString<256> InitFnName;
2230 {
2231 llvm::raw_svector_ostream Out(InitFnName);
2232 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002233 }
2234
2235 // If we have a definition for the variable, emit the initialization
2236 // function as an alias to the global Init function (if any). Otherwise,
2237 // produce a declaration of the initialization function.
Craig Topper8a13c412014-05-21 05:09:00 +00002238 llvm::GlobalValue *Init = nullptr;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002239 bool InitIsInitFunc = false;
2240 if (VD->hasDefinition()) {
2241 InitIsInitFunc = true;
2242 if (InitFunc)
Rafael Espindola234405b2014-05-17 21:30:14 +00002243 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
2244 InitFunc);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002245 } else {
2246 // Emit a weak global function referring to the initialization function.
2247 // This function will not exist if the TU defining the thread_local
2248 // variable in question does not need any dynamic initialization for
2249 // its thread_local variables.
2250 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
2251 Init = llvm::Function::Create(
2252 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
2253 &CGM.getModule());
2254 }
2255
2256 if (Init)
2257 Init->setVisibility(Var->getVisibility());
2258
2259 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
2260 llvm::LLVMContext &Context = CGM.getModule().getContext();
2261 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
John McCall7f416cc2015-09-08 08:05:57 +00002262 CGBuilderTy Builder(CGM, Entry);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002263 if (InitIsInitFunc) {
2264 if (Init)
David Blaikie4ba525b2015-07-14 17:27:39 +00002265 Builder.CreateCall(Init);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002266 } else {
2267 // Don't know whether we have an init function. Call it if it exists.
2268 llvm::Value *Have = Builder.CreateIsNotNull(Init);
2269 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2270 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2271 Builder.CreateCondBr(Have, InitBB, ExitBB);
2272
2273 Builder.SetInsertPoint(InitBB);
David Blaikie4ba525b2015-07-14 17:27:39 +00002274 Builder.CreateCall(Init);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002275 Builder.CreateBr(ExitBB);
2276
2277 Builder.SetInsertPoint(ExitBB);
2278 }
2279
2280 // For a reference, the result of the wrapper function is a pointer to
2281 // the referenced object.
2282 llvm::Value *Val = Var;
2283 if (VD->getType()->isReferenceType()) {
John McCall7f416cc2015-09-08 08:05:57 +00002284 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2285 Val = Builder.CreateAlignedLoad(Val, Align);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002286 }
Alexander Musmanf94c3182014-09-26 06:28:25 +00002287 if (Val->getType() != Wrapper->getReturnType())
2288 Val = Builder.CreatePointerBitCastOrAddrSpaceCast(
2289 Val, Wrapper->getReturnType(), "");
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002290 Builder.CreateRet(Val);
2291 }
2292}
2293
Richard Smith0f383742014-03-26 22:48:22 +00002294LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2295 const VarDecl *VD,
2296 QualType LValType) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002297 QualType T = VD->getType();
2298 llvm::Type *Ty = CGF.getTypes().ConvertTypeForMem(T);
2299 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD, Ty);
Alexander Musmanf94c3182014-09-26 06:28:25 +00002300 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002301
David Blaikie4ba525b2015-07-14 17:27:39 +00002302 Val = CGF.Builder.CreateCall(Wrapper);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002303
2304 LValue LV;
2305 if (VD->getType()->isReferenceType())
Richard Smith0f383742014-03-26 22:48:22 +00002306 LV = CGF.MakeNaturalAlignAddrLValue(Val, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002307 else
Richard Smith0f383742014-03-26 22:48:22 +00002308 LV = CGF.MakeAddrLValue(Val, LValType, CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002309 // FIXME: need setObjCGCLValueClass?
2310 return LV;
2311}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002312
2313/// Return whether the given global decl needs a VTT parameter, which it does
2314/// if it's a base constructor or destructor with virtual bases.
2315bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
2316 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
2317
2318 // We don't have any virtual bases, just return early.
2319 if (!MD->getParent()->getNumVBases())
2320 return false;
2321
2322 // Check if we have a base constructor.
2323 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
2324 return true;
2325
2326 // Check if we have a base destructor.
2327 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2328 return true;
2329
2330 return false;
2331}
David Majnemere2cb8d12014-07-07 06:20:47 +00002332
2333namespace {
2334class ItaniumRTTIBuilder {
2335 CodeGenModule &CGM; // Per-module state.
2336 llvm::LLVMContext &VMContext;
2337 const ItaniumCXXABI &CXXABI; // Per-module state.
2338
2339 /// Fields - The fields of the RTTI descriptor currently being built.
2340 SmallVector<llvm::Constant *, 16> Fields;
2341
2342 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2343 llvm::GlobalVariable *
2344 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2345
2346 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2347 /// descriptor of the given type.
2348 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2349
2350 /// BuildVTablePointer - Build the vtable pointer for the given type.
2351 void BuildVTablePointer(const Type *Ty);
2352
2353 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2354 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2355 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2356
2357 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2358 /// classes with bases that do not satisfy the abi::__si_class_type_info
2359 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2360 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2361
2362 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2363 /// for pointer types.
2364 void BuildPointerTypeInfo(QualType PointeeTy);
2365
2366 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2367 /// type_info for an object type.
2368 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2369
2370 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2371 /// struct, used for member pointer types.
2372 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2373
2374public:
2375 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2376 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2377
2378 // Pointer type info flags.
2379 enum {
2380 /// PTI_Const - Type has const qualifier.
2381 PTI_Const = 0x1,
2382
2383 /// PTI_Volatile - Type has volatile qualifier.
2384 PTI_Volatile = 0x2,
2385
2386 /// PTI_Restrict - Type has restrict qualifier.
2387 PTI_Restrict = 0x4,
2388
2389 /// PTI_Incomplete - Type is incomplete.
2390 PTI_Incomplete = 0x8,
2391
2392 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2393 /// (in pointer to member).
2394 PTI_ContainingClassIncomplete = 0x10
2395 };
2396
2397 // VMI type info flags.
2398 enum {
2399 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2400 VMI_NonDiamondRepeat = 0x1,
2401
2402 /// VMI_DiamondShaped - Class is diamond shaped.
2403 VMI_DiamondShaped = 0x2
2404 };
2405
2406 // Base class type info flags.
2407 enum {
2408 /// BCTI_Virtual - Base class is virtual.
2409 BCTI_Virtual = 0x1,
2410
2411 /// BCTI_Public - Base class is public.
2412 BCTI_Public = 0x2
2413 };
2414
2415 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
2416 ///
2417 /// \param Force - true to force the creation of this RTTI value
2418 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false);
2419};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002420}
David Majnemere2cb8d12014-07-07 06:20:47 +00002421
2422llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2423 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002424 SmallString<256> Name;
2425 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002426 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002427
2428 // We know that the mangled name of the type starts at index 4 of the
2429 // mangled name of the typename, so we can just index into it in order to
2430 // get the mangled name of the type.
2431 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2432 Name.substr(4));
2433
2434 llvm::GlobalVariable *GV =
2435 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
2436
2437 GV->setInitializer(Init);
2438
2439 return GV;
2440}
2441
2442llvm::Constant *
2443ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2444 // Mangle the RTTI name.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002445 SmallString<256> Name;
2446 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002447 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002448
2449 // Look for an existing global.
2450 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2451
2452 if (!GV) {
2453 // Create a new global variable.
2454 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2455 /*Constant=*/true,
2456 llvm::GlobalValue::ExternalLinkage, nullptr,
2457 Name);
David Majnemer1fb1a042014-11-07 07:26:38 +00002458 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2459 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2460 if (RD->hasAttr<DLLImportAttr>())
2461 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2462 }
David Majnemere2cb8d12014-07-07 06:20:47 +00002463 }
2464
2465 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2466}
2467
2468/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2469/// info for that type is defined in the standard library.
2470static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2471 // Itanium C++ ABI 2.9.2:
2472 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
2473 // the run-time support library. Specifically, the run-time support
2474 // library should contain type_info objects for the types X, X* and
2475 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2476 // unsigned char, signed char, short, unsigned short, int, unsigned int,
2477 // long, unsigned long, long long, unsigned long long, float, double,
2478 // long double, char16_t, char32_t, and the IEEE 754r decimal and
2479 // half-precision floating point types.
2480 switch (Ty->getKind()) {
2481 case BuiltinType::Void:
2482 case BuiltinType::NullPtr:
2483 case BuiltinType::Bool:
2484 case BuiltinType::WChar_S:
2485 case BuiltinType::WChar_U:
2486 case BuiltinType::Char_U:
2487 case BuiltinType::Char_S:
2488 case BuiltinType::UChar:
2489 case BuiltinType::SChar:
2490 case BuiltinType::Short:
2491 case BuiltinType::UShort:
2492 case BuiltinType::Int:
2493 case BuiltinType::UInt:
2494 case BuiltinType::Long:
2495 case BuiltinType::ULong:
2496 case BuiltinType::LongLong:
2497 case BuiltinType::ULongLong:
2498 case BuiltinType::Half:
2499 case BuiltinType::Float:
2500 case BuiltinType::Double:
2501 case BuiltinType::LongDouble:
2502 case BuiltinType::Char16:
2503 case BuiltinType::Char32:
2504 case BuiltinType::Int128:
2505 case BuiltinType::UInt128:
2506 case BuiltinType::OCLImage1d:
2507 case BuiltinType::OCLImage1dArray:
2508 case BuiltinType::OCLImage1dBuffer:
2509 case BuiltinType::OCLImage2d:
2510 case BuiltinType::OCLImage2dArray:
2511 case BuiltinType::OCLImage3d:
2512 case BuiltinType::OCLSampler:
2513 case BuiltinType::OCLEvent:
2514 return true;
2515
2516 case BuiltinType::Dependent:
2517#define BUILTIN_TYPE(Id, SingletonId)
2518#define PLACEHOLDER_TYPE(Id, SingletonId) \
2519 case BuiltinType::Id:
2520#include "clang/AST/BuiltinTypes.def"
2521 llvm_unreachable("asking for RRTI for a placeholder type!");
2522
2523 case BuiltinType::ObjCId:
2524 case BuiltinType::ObjCClass:
2525 case BuiltinType::ObjCSel:
2526 llvm_unreachable("FIXME: Objective-C types are unsupported!");
2527 }
2528
2529 llvm_unreachable("Invalid BuiltinType Kind!");
2530}
2531
2532static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2533 QualType PointeeTy = PointerTy->getPointeeType();
2534 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2535 if (!BuiltinTy)
2536 return false;
2537
2538 // Check the qualifiers.
2539 Qualifiers Quals = PointeeTy.getQualifiers();
2540 Quals.removeConst();
2541
2542 if (!Quals.empty())
2543 return false;
2544
2545 return TypeInfoIsInStandardLibrary(BuiltinTy);
2546}
2547
2548/// IsStandardLibraryRTTIDescriptor - Returns whether the type
2549/// information for the given type exists in the standard library.
2550static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2551 // Type info for builtin types is defined in the standard library.
2552 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2553 return TypeInfoIsInStandardLibrary(BuiltinTy);
2554
2555 // Type info for some pointer types to builtin types is defined in the
2556 // standard library.
2557 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2558 return TypeInfoIsInStandardLibrary(PointerTy);
2559
2560 return false;
2561}
2562
2563/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
2564/// the given type exists somewhere else, and that we should not emit the type
2565/// information in this translation unit. Assumes that it is not a
2566/// standard-library type.
2567static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
2568 QualType Ty) {
2569 ASTContext &Context = CGM.getContext();
2570
2571 // If RTTI is disabled, assume it might be disabled in the
2572 // translation unit that defines any potential key function, too.
2573 if (!Context.getLangOpts().RTTI) return false;
2574
2575 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2576 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2577 if (!RD->hasDefinition())
2578 return false;
2579
2580 if (!RD->isDynamicClass())
2581 return false;
2582
2583 // FIXME: this may need to be reconsidered if the key function
2584 // changes.
David Majnemerbe9022c2015-08-06 20:56:55 +00002585 // N.B. We must always emit the RTTI data ourselves if there exists a key
2586 // function.
2587 bool IsDLLImport = RD->hasAttr<DLLImportAttr>();
David Majnemer1fb1a042014-11-07 07:26:38 +00002588 if (CGM.getVTables().isVTableExternal(RD))
David Majnemerbe9022c2015-08-06 20:56:55 +00002589 return IsDLLImport ? false : true;
David Majnemer1fb1a042014-11-07 07:26:38 +00002590
David Majnemerbe9022c2015-08-06 20:56:55 +00002591 if (IsDLLImport)
David Majnemer1fb1a042014-11-07 07:26:38 +00002592 return true;
David Majnemere2cb8d12014-07-07 06:20:47 +00002593 }
2594
2595 return false;
2596}
2597
2598/// IsIncompleteClassType - Returns whether the given record type is incomplete.
2599static bool IsIncompleteClassType(const RecordType *RecordTy) {
2600 return !RecordTy->getDecl()->isCompleteDefinition();
2601}
2602
2603/// ContainsIncompleteClassType - Returns whether the given type contains an
2604/// incomplete class type. This is true if
2605///
2606/// * The given type is an incomplete class type.
2607/// * The given type is a pointer type whose pointee type contains an
2608/// incomplete class type.
2609/// * The given type is a member pointer type whose class is an incomplete
2610/// class type.
2611/// * The given type is a member pointer type whoise pointee type contains an
2612/// incomplete class type.
2613/// is an indirect or direct pointer to an incomplete class type.
2614static bool ContainsIncompleteClassType(QualType Ty) {
2615 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2616 if (IsIncompleteClassType(RecordTy))
2617 return true;
2618 }
2619
2620 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2621 return ContainsIncompleteClassType(PointerTy->getPointeeType());
2622
2623 if (const MemberPointerType *MemberPointerTy =
2624 dyn_cast<MemberPointerType>(Ty)) {
2625 // Check if the class type is incomplete.
2626 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
2627 if (IsIncompleteClassType(ClassType))
2628 return true;
2629
2630 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
2631 }
2632
2633 return false;
2634}
2635
2636// CanUseSingleInheritance - Return whether the given record decl has a "single,
2637// public, non-virtual base at offset zero (i.e. the derived class is dynamic
2638// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
2639static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
2640 // Check the number of bases.
2641 if (RD->getNumBases() != 1)
2642 return false;
2643
2644 // Get the base.
2645 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
2646
2647 // Check that the base is not virtual.
2648 if (Base->isVirtual())
2649 return false;
2650
2651 // Check that the base is public.
2652 if (Base->getAccessSpecifier() != AS_public)
2653 return false;
2654
2655 // Check that the class is dynamic iff the base is.
2656 const CXXRecordDecl *BaseDecl =
2657 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2658 if (!BaseDecl->isEmpty() &&
2659 BaseDecl->isDynamicClass() != RD->isDynamicClass())
2660 return false;
2661
2662 return true;
2663}
2664
2665void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
2666 // abi::__class_type_info.
2667 static const char * const ClassTypeInfo =
2668 "_ZTVN10__cxxabiv117__class_type_infoE";
2669 // abi::__si_class_type_info.
2670 static const char * const SIClassTypeInfo =
2671 "_ZTVN10__cxxabiv120__si_class_type_infoE";
2672 // abi::__vmi_class_type_info.
2673 static const char * const VMIClassTypeInfo =
2674 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
2675
2676 const char *VTableName = nullptr;
2677
2678 switch (Ty->getTypeClass()) {
2679#define TYPE(Class, Base)
2680#define ABSTRACT_TYPE(Class, Base)
2681#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2682#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2683#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2684#include "clang/AST/TypeNodes.def"
2685 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2686
2687 case Type::LValueReference:
2688 case Type::RValueReference:
2689 llvm_unreachable("References shouldn't get here");
2690
2691 case Type::Auto:
2692 llvm_unreachable("Undeduced auto type shouldn't get here");
2693
2694 case Type::Builtin:
2695 // GCC treats vector and complex types as fundamental types.
2696 case Type::Vector:
2697 case Type::ExtVector:
2698 case Type::Complex:
2699 case Type::Atomic:
2700 // FIXME: GCC treats block pointers as fundamental types?!
2701 case Type::BlockPointer:
2702 // abi::__fundamental_type_info.
2703 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
2704 break;
2705
2706 case Type::ConstantArray:
2707 case Type::IncompleteArray:
2708 case Type::VariableArray:
2709 // abi::__array_type_info.
2710 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
2711 break;
2712
2713 case Type::FunctionNoProto:
2714 case Type::FunctionProto:
2715 // abi::__function_type_info.
2716 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
2717 break;
2718
2719 case Type::Enum:
2720 // abi::__enum_type_info.
2721 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
2722 break;
2723
2724 case Type::Record: {
2725 const CXXRecordDecl *RD =
2726 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2727
2728 if (!RD->hasDefinition() || !RD->getNumBases()) {
2729 VTableName = ClassTypeInfo;
2730 } else if (CanUseSingleInheritance(RD)) {
2731 VTableName = SIClassTypeInfo;
2732 } else {
2733 VTableName = VMIClassTypeInfo;
2734 }
2735
2736 break;
2737 }
2738
2739 case Type::ObjCObject:
2740 // Ignore protocol qualifiers.
2741 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
2742
2743 // Handle id and Class.
2744 if (isa<BuiltinType>(Ty)) {
2745 VTableName = ClassTypeInfo;
2746 break;
2747 }
2748
2749 assert(isa<ObjCInterfaceType>(Ty));
2750 // Fall through.
2751
2752 case Type::ObjCInterface:
2753 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
2754 VTableName = SIClassTypeInfo;
2755 } else {
2756 VTableName = ClassTypeInfo;
2757 }
2758 break;
2759
2760 case Type::ObjCObjectPointer:
2761 case Type::Pointer:
2762 // abi::__pointer_type_info.
2763 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
2764 break;
2765
2766 case Type::MemberPointer:
2767 // abi::__pointer_to_member_type_info.
2768 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
2769 break;
2770 }
2771
2772 llvm::Constant *VTable =
2773 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
2774
2775 llvm::Type *PtrDiffTy =
2776 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
2777
2778 // The vtable address point is 2.
2779 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00002780 VTable =
2781 llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.Int8PtrTy, VTable, Two);
David Majnemere2cb8d12014-07-07 06:20:47 +00002782 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
2783
2784 Fields.push_back(VTable);
2785}
2786
2787/// \brief Return the linkage that the type info and type info name constants
2788/// should have for the given type.
2789static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
2790 QualType Ty) {
2791 // Itanium C++ ABI 2.9.5p7:
2792 // In addition, it and all of the intermediate abi::__pointer_type_info
2793 // structs in the chain down to the abi::__class_type_info for the
2794 // incomplete class type must be prevented from resolving to the
2795 // corresponding type_info structs for the complete class type, possibly
2796 // by making them local static objects. Finally, a dummy class RTTI is
2797 // generated for the incomplete type that will not resolve to the final
2798 // complete class RTTI (because the latter need not exist), possibly by
2799 // making it a local static object.
2800 if (ContainsIncompleteClassType(Ty))
2801 return llvm::GlobalValue::InternalLinkage;
2802
2803 switch (Ty->getLinkage()) {
2804 case NoLinkage:
2805 case InternalLinkage:
2806 case UniqueExternalLinkage:
2807 return llvm::GlobalValue::InternalLinkage;
2808
2809 case VisibleNoLinkage:
2810 case ExternalLinkage:
2811 if (!CGM.getLangOpts().RTTI) {
2812 // RTTI is not enabled, which means that this type info struct is going
2813 // to be used for exception handling. Give it linkonce_odr linkage.
2814 return llvm::GlobalValue::LinkOnceODRLinkage;
2815 }
2816
2817 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
2818 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2819 if (RD->hasAttr<WeakAttr>())
2820 return llvm::GlobalValue::WeakODRLinkage;
David Majnemerbe9022c2015-08-06 20:56:55 +00002821 if (RD->isDynamicClass()) {
2822 llvm::GlobalValue::LinkageTypes LT = CGM.getVTableLinkage(RD);
2823 // MinGW won't export the RTTI information when there is a key function.
2824 // Make sure we emit our own copy instead of attempting to dllimport it.
2825 if (RD->hasAttr<DLLImportAttr>() &&
2826 llvm::GlobalValue::isAvailableExternallyLinkage(LT))
2827 LT = llvm::GlobalValue::LinkOnceODRLinkage;
2828 return LT;
2829 }
David Majnemere2cb8d12014-07-07 06:20:47 +00002830 }
2831
2832 return llvm::GlobalValue::LinkOnceODRLinkage;
2833 }
2834
2835 llvm_unreachable("Invalid linkage!");
2836}
2837
2838llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force) {
2839 // We want to operate on the canonical type.
2840 Ty = CGM.getContext().getCanonicalType(Ty);
2841
2842 // Check if we've already emitted an RTTI descriptor for this type.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002843 SmallString<256> Name;
2844 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002845 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002846
2847 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
2848 if (OldGV && !OldGV->isDeclaration()) {
2849 assert(!OldGV->hasAvailableExternallyLinkage() &&
2850 "available_externally typeinfos not yet implemented");
2851
2852 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
2853 }
2854
2855 // Check if there is already an external RTTI descriptor for this type.
2856 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
2857 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
2858 return GetAddrOfExternalRTTIDescriptor(Ty);
2859
2860 // Emit the standard library with external linkage.
2861 llvm::GlobalVariable::LinkageTypes Linkage;
2862 if (IsStdLib)
2863 Linkage = llvm::GlobalValue::ExternalLinkage;
2864 else
2865 Linkage = getTypeInfoLinkage(CGM, Ty);
2866
2867 // Add the vtable pointer.
2868 BuildVTablePointer(cast<Type>(Ty));
2869
2870 // And the name.
2871 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
2872 llvm::Constant *TypeNameField;
2873
2874 // If we're supposed to demote the visibility, be sure to set a flag
2875 // to use a string comparison for type_info comparisons.
2876 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
2877 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
2878 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
2879 // The flag is the sign bit, which on ARM64 is defined to be clear
2880 // for global pointers. This is very ARM64-specific.
2881 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
2882 llvm::Constant *flag =
2883 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
2884 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
2885 TypeNameField =
2886 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
2887 } else {
2888 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
2889 }
2890 Fields.push_back(TypeNameField);
2891
2892 switch (Ty->getTypeClass()) {
2893#define TYPE(Class, Base)
2894#define ABSTRACT_TYPE(Class, Base)
2895#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2896#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2897#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2898#include "clang/AST/TypeNodes.def"
2899 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2900
2901 // GCC treats vector types as fundamental types.
2902 case Type::Builtin:
2903 case Type::Vector:
2904 case Type::ExtVector:
2905 case Type::Complex:
2906 case Type::BlockPointer:
2907 // Itanium C++ ABI 2.9.5p4:
2908 // abi::__fundamental_type_info adds no data members to std::type_info.
2909 break;
2910
2911 case Type::LValueReference:
2912 case Type::RValueReference:
2913 llvm_unreachable("References shouldn't get here");
2914
2915 case Type::Auto:
2916 llvm_unreachable("Undeduced auto type shouldn't get here");
2917
2918 case Type::ConstantArray:
2919 case Type::IncompleteArray:
2920 case Type::VariableArray:
2921 // Itanium C++ ABI 2.9.5p5:
2922 // abi::__array_type_info adds no data members to std::type_info.
2923 break;
2924
2925 case Type::FunctionNoProto:
2926 case Type::FunctionProto:
2927 // Itanium C++ ABI 2.9.5p5:
2928 // abi::__function_type_info adds no data members to std::type_info.
2929 break;
2930
2931 case Type::Enum:
2932 // Itanium C++ ABI 2.9.5p5:
2933 // abi::__enum_type_info adds no data members to std::type_info.
2934 break;
2935
2936 case Type::Record: {
2937 const CXXRecordDecl *RD =
2938 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2939 if (!RD->hasDefinition() || !RD->getNumBases()) {
2940 // We don't need to emit any fields.
2941 break;
2942 }
2943
2944 if (CanUseSingleInheritance(RD))
2945 BuildSIClassTypeInfo(RD);
2946 else
2947 BuildVMIClassTypeInfo(RD);
2948
2949 break;
2950 }
2951
2952 case Type::ObjCObject:
2953 case Type::ObjCInterface:
2954 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
2955 break;
2956
2957 case Type::ObjCObjectPointer:
2958 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
2959 break;
2960
2961 case Type::Pointer:
2962 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
2963 break;
2964
2965 case Type::MemberPointer:
2966 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
2967 break;
2968
2969 case Type::Atomic:
2970 // No fields, at least for the moment.
2971 break;
2972 }
2973
2974 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
2975
Rafael Espindolacb92c192015-01-15 23:18:01 +00002976 llvm::Module &M = CGM.getModule();
David Majnemere2cb8d12014-07-07 06:20:47 +00002977 llvm::GlobalVariable *GV =
Rafael Espindolacb92c192015-01-15 23:18:01 +00002978 new llvm::GlobalVariable(M, Init->getType(),
2979 /*Constant=*/true, Linkage, Init, Name);
2980
David Majnemere2cb8d12014-07-07 06:20:47 +00002981 // If there's already an old global variable, replace it with the new one.
2982 if (OldGV) {
2983 GV->takeName(OldGV);
2984 llvm::Constant *NewPtr =
2985 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2986 OldGV->replaceAllUsesWith(NewPtr);
2987 OldGV->eraseFromParent();
2988 }
2989
Yaron Keren04da2382015-07-29 15:42:28 +00002990 if (CGM.supportsCOMDAT() && GV->isWeakForLinker())
2991 GV->setComdat(M.getOrInsertComdat(GV->getName()));
2992
David Majnemere2cb8d12014-07-07 06:20:47 +00002993 // The Itanium ABI specifies that type_info objects must be globally
2994 // unique, with one exception: if the type is an incomplete class
2995 // type or a (possibly indirect) pointer to one. That exception
2996 // affects the general case of comparing type_info objects produced
2997 // by the typeid operator, which is why the comparison operators on
2998 // std::type_info generally use the type_info name pointers instead
2999 // of the object addresses. However, the language's built-in uses
3000 // of RTTI generally require class types to be complete, even when
3001 // manipulating pointers to those class types. This allows the
3002 // implementation of dynamic_cast to rely on address equality tests,
3003 // which is much faster.
3004
3005 // All of this is to say that it's important that both the type_info
3006 // object and the type_info name be uniqued when weakly emitted.
3007
3008 // Give the type_info object and name the formal visibility of the
3009 // type itself.
3010 llvm::GlobalValue::VisibilityTypes llvmVisibility;
3011 if (llvm::GlobalValue::isLocalLinkage(Linkage))
3012 // If the linkage is local, only default visibility makes sense.
3013 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
3014 else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden)
3015 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
3016 else
3017 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
3018 TypeName->setVisibility(llvmVisibility);
3019 GV->setVisibility(llvmVisibility);
3020
3021 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
3022}
3023
3024/// ComputeQualifierFlags - Compute the pointer type info flags from the
3025/// given qualifier.
3026static unsigned ComputeQualifierFlags(Qualifiers Quals) {
3027 unsigned Flags = 0;
3028
3029 if (Quals.hasConst())
3030 Flags |= ItaniumRTTIBuilder::PTI_Const;
3031 if (Quals.hasVolatile())
3032 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
3033 if (Quals.hasRestrict())
3034 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
3035
3036 return Flags;
3037}
3038
3039/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
3040/// for the given Objective-C object type.
3041void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
3042 // Drop qualifiers.
3043 const Type *T = OT->getBaseType().getTypePtr();
3044 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
3045
3046 // The builtin types are abi::__class_type_infos and don't require
3047 // extra fields.
3048 if (isa<BuiltinType>(T)) return;
3049
3050 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
3051 ObjCInterfaceDecl *Super = Class->getSuperClass();
3052
3053 // Root classes are also __class_type_info.
3054 if (!Super) return;
3055
3056 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
3057
3058 // Everything else is single inheritance.
3059 llvm::Constant *BaseTypeInfo =
3060 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
3061 Fields.push_back(BaseTypeInfo);
3062}
3063
3064/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
3065/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
3066void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
3067 // Itanium C++ ABI 2.9.5p6b:
3068 // It adds to abi::__class_type_info a single member pointing to the
3069 // type_info structure for the base type,
3070 llvm::Constant *BaseTypeInfo =
3071 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
3072 Fields.push_back(BaseTypeInfo);
3073}
3074
3075namespace {
3076 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
3077 /// a class hierarchy.
3078 struct SeenBases {
3079 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
3080 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
3081 };
3082}
3083
3084/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
3085/// abi::__vmi_class_type_info.
3086///
3087static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
3088 SeenBases &Bases) {
3089
3090 unsigned Flags = 0;
3091
3092 const CXXRecordDecl *BaseDecl =
3093 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
3094
3095 if (Base->isVirtual()) {
3096 // Mark the virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003097 if (!Bases.VirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003098 // If this virtual base has been seen before, then the class is diamond
3099 // shaped.
3100 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
3101 } else {
3102 if (Bases.NonVirtualBases.count(BaseDecl))
3103 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3104 }
3105 } else {
3106 // Mark the non-virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003107 if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003108 // If this non-virtual base has been seen before, then the class has non-
3109 // diamond shaped repeated inheritance.
3110 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3111 } else {
3112 if (Bases.VirtualBases.count(BaseDecl))
3113 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3114 }
3115 }
3116
3117 // Walk all bases.
3118 for (const auto &I : BaseDecl->bases())
3119 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3120
3121 return Flags;
3122}
3123
3124static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
3125 unsigned Flags = 0;
3126 SeenBases Bases;
3127
3128 // Walk all bases.
3129 for (const auto &I : RD->bases())
3130 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3131
3132 return Flags;
3133}
3134
3135/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
3136/// classes with bases that do not satisfy the abi::__si_class_type_info
3137/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
3138void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
3139 llvm::Type *UnsignedIntLTy =
3140 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3141
3142 // Itanium C++ ABI 2.9.5p6c:
3143 // __flags is a word with flags describing details about the class
3144 // structure, which may be referenced by using the __flags_masks
3145 // enumeration. These flags refer to both direct and indirect bases.
3146 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
3147 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3148
3149 // Itanium C++ ABI 2.9.5p6c:
3150 // __base_count is a word with the number of direct proper base class
3151 // descriptions that follow.
3152 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
3153
3154 if (!RD->getNumBases())
3155 return;
3156
3157 llvm::Type *LongLTy =
3158 CGM.getTypes().ConvertType(CGM.getContext().LongTy);
3159
3160 // Now add the base class descriptions.
3161
3162 // Itanium C++ ABI 2.9.5p6c:
3163 // __base_info[] is an array of base class descriptions -- one for every
3164 // direct proper base. Each description is of the type:
3165 //
3166 // struct abi::__base_class_type_info {
3167 // public:
3168 // const __class_type_info *__base_type;
3169 // long __offset_flags;
3170 //
3171 // enum __offset_flags_masks {
3172 // __virtual_mask = 0x1,
3173 // __public_mask = 0x2,
3174 // __offset_shift = 8
3175 // };
3176 // };
3177 for (const auto &Base : RD->bases()) {
3178 // The __base_type member points to the RTTI for the base type.
3179 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
3180
3181 const CXXRecordDecl *BaseDecl =
3182 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
3183
3184 int64_t OffsetFlags = 0;
3185
3186 // All but the lower 8 bits of __offset_flags are a signed offset.
3187 // For a non-virtual base, this is the offset in the object of the base
3188 // subobject. For a virtual base, this is the offset in the virtual table of
3189 // the virtual base offset for the virtual base referenced (negative).
3190 CharUnits Offset;
3191 if (Base.isVirtual())
3192 Offset =
3193 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
3194 else {
3195 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
3196 Offset = Layout.getBaseClassOffset(BaseDecl);
3197 };
3198
3199 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
3200
3201 // The low-order byte of __offset_flags contains flags, as given by the
3202 // masks from the enumeration __offset_flags_masks.
3203 if (Base.isVirtual())
3204 OffsetFlags |= BCTI_Virtual;
3205 if (Base.getAccessSpecifier() == AS_public)
3206 OffsetFlags |= BCTI_Public;
3207
3208 Fields.push_back(llvm::ConstantInt::get(LongLTy, OffsetFlags));
3209 }
3210}
3211
3212/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
3213/// used for pointer types.
3214void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
3215 Qualifiers Quals;
3216 QualType UnqualifiedPointeeTy =
3217 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
3218
3219 // Itanium C++ ABI 2.9.5p7:
3220 // __flags is a flag word describing the cv-qualification and other
3221 // attributes of the type pointed to
3222 unsigned Flags = ComputeQualifierFlags(Quals);
3223
3224 // Itanium C++ ABI 2.9.5p7:
3225 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3226 // incomplete class type, the incomplete target type flag is set.
3227 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
3228 Flags |= PTI_Incomplete;
3229
3230 llvm::Type *UnsignedIntLTy =
3231 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3232 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3233
3234 // Itanium C++ ABI 2.9.5p7:
3235 // __pointee is a pointer to the std::type_info derivation for the
3236 // unqualified type being pointed to.
3237 llvm::Constant *PointeeTypeInfo =
3238 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
3239 Fields.push_back(PointeeTypeInfo);
3240}
3241
3242/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
3243/// struct, used for member pointer types.
3244void
3245ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
3246 QualType PointeeTy = Ty->getPointeeType();
3247
3248 Qualifiers Quals;
3249 QualType UnqualifiedPointeeTy =
3250 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
3251
3252 // Itanium C++ ABI 2.9.5p7:
3253 // __flags is a flag word describing the cv-qualification and other
3254 // attributes of the type pointed to.
3255 unsigned Flags = ComputeQualifierFlags(Quals);
3256
3257 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
3258
3259 // Itanium C++ ABI 2.9.5p7:
3260 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3261 // incomplete class type, the incomplete target type flag is set.
3262 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
3263 Flags |= PTI_Incomplete;
3264
3265 if (IsIncompleteClassType(ClassType))
3266 Flags |= PTI_ContainingClassIncomplete;
3267
3268 llvm::Type *UnsignedIntLTy =
3269 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3270 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3271
3272 // Itanium C++ ABI 2.9.5p7:
3273 // __pointee is a pointer to the std::type_info derivation for the
3274 // unqualified type being pointed to.
3275 llvm::Constant *PointeeTypeInfo =
3276 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
3277 Fields.push_back(PointeeTypeInfo);
3278
3279 // Itanium C++ ABI 2.9.5p9:
3280 // __context is a pointer to an abi::__class_type_info corresponding to the
3281 // class type containing the member pointed to
3282 // (e.g., the "A" in "int A::*").
3283 Fields.push_back(
3284 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
3285}
3286
David Majnemer443250f2015-03-17 20:35:00 +00003287llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003288 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
3289}
3290
3291void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type) {
3292 QualType PointerType = getContext().getPointerType(Type);
3293 QualType PointerTypeConst = getContext().getPointerType(Type.withConst());
3294 ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, true);
3295 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, true);
3296 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, true);
3297}
3298
3299void ItaniumCXXABI::EmitFundamentalRTTIDescriptors() {
3300 QualType FundamentalTypes[] = {
3301 getContext().VoidTy, getContext().NullPtrTy,
3302 getContext().BoolTy, getContext().WCharTy,
3303 getContext().CharTy, getContext().UnsignedCharTy,
3304 getContext().SignedCharTy, getContext().ShortTy,
3305 getContext().UnsignedShortTy, getContext().IntTy,
3306 getContext().UnsignedIntTy, getContext().LongTy,
3307 getContext().UnsignedLongTy, getContext().LongLongTy,
3308 getContext().UnsignedLongLongTy, getContext().HalfTy,
3309 getContext().FloatTy, getContext().DoubleTy,
3310 getContext().LongDoubleTy, getContext().Char16Ty,
3311 getContext().Char32Ty,
3312 };
3313 for (const QualType &FundamentalType : FundamentalTypes)
3314 EmitFundamentalRTTIDescriptor(FundamentalType);
3315}
3316
3317/// What sort of uniqueness rules should we use for the RTTI for the
3318/// given type?
3319ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
3320 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
3321 if (shouldRTTIBeUnique())
3322 return RUK_Unique;
3323
3324 // It's only necessary for linkonce_odr or weak_odr linkage.
3325 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
3326 Linkage != llvm::GlobalValue::WeakODRLinkage)
3327 return RUK_Unique;
3328
3329 // It's only necessary with default visibility.
3330 if (CanTy->getVisibility() != DefaultVisibility)
3331 return RUK_Unique;
3332
3333 // If we're not required to publish this symbol, hide it.
3334 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3335 return RUK_NonUniqueHidden;
3336
3337 // If we're required to publish this symbol, as we might be under an
3338 // explicit instantiation, leave it with default visibility but
3339 // enable string-comparisons.
3340 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
3341 return RUK_NonUniqueVisible;
3342}
Rafael Espindola91f68b42014-09-15 19:20:10 +00003343
Rafael Espindola1e4df922014-09-16 15:18:21 +00003344// Find out how to codegen the complete destructor and constructor
3345namespace {
3346enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
3347}
3348static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
3349 const CXXMethodDecl *MD) {
3350 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
3351 return StructorCodegen::Emit;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003352
Rafael Espindola1e4df922014-09-16 15:18:21 +00003353 // The complete and base structors are not equivalent if there are any virtual
3354 // bases, so emit separate functions.
3355 if (MD->getParent()->getNumVBases())
3356 return StructorCodegen::Emit;
3357
3358 GlobalDecl AliasDecl;
3359 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3360 AliasDecl = GlobalDecl(DD, Dtor_Complete);
3361 } else {
3362 const auto *CD = cast<CXXConstructorDecl>(MD);
3363 AliasDecl = GlobalDecl(CD, Ctor_Complete);
3364 }
3365 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3366
3367 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
3368 return StructorCodegen::RAUW;
3369
3370 // FIXME: Should we allow available_externally aliases?
3371 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
3372 return StructorCodegen::RAUW;
3373
Rafael Espindola0806f982014-09-16 20:19:43 +00003374 if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
3375 // Only ELF supports COMDATs with arbitrary names (C5/D5).
3376 if (CGM.getTarget().getTriple().isOSBinFormatELF())
3377 return StructorCodegen::COMDAT;
3378 return StructorCodegen::Emit;
3379 }
Rafael Espindola1e4df922014-09-16 15:18:21 +00003380
3381 return StructorCodegen::Alias;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003382}
3383
Rafael Espindola1e4df922014-09-16 15:18:21 +00003384static void emitConstructorDestructorAlias(CodeGenModule &CGM,
3385 GlobalDecl AliasDecl,
3386 GlobalDecl TargetDecl) {
3387 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3388
3389 StringRef MangledName = CGM.getMangledName(AliasDecl);
3390 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
3391 if (Entry && !Entry->isDeclaration())
3392 return;
3393
3394 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
3395 llvm::PointerType *AliasType = Aliasee->getType();
3396
3397 // Create the alias with no name.
David Blaikie2a791d72015-09-14 18:38:22 +00003398 auto *Alias = llvm::GlobalAlias::create(Linkage, "", Aliasee);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003399
3400 // Switch any previous uses to the alias.
3401 if (Entry) {
3402 assert(Entry->getType() == AliasType &&
3403 "declaration exists with different type");
3404 Alias->takeName(Entry);
3405 Entry->replaceAllUsesWith(Alias);
3406 Entry->eraseFromParent();
3407 } else {
3408 Alias->setName(MangledName);
3409 }
3410
3411 // Finally, set up the alias with its proper name and attributes.
Dario Domiziolic4fb8ca72014-09-19 22:06:24 +00003412 CGM.setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003413}
3414
3415void ItaniumCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
3416 StructorType Type) {
3417 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
3418 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
3419
3420 StructorCodegen CGType = getCodegenToUse(CGM, MD);
3421
3422 if (Type == StructorType::Complete) {
3423 GlobalDecl CompleteDecl;
3424 GlobalDecl BaseDecl;
3425 if (CD) {
3426 CompleteDecl = GlobalDecl(CD, Ctor_Complete);
3427 BaseDecl = GlobalDecl(CD, Ctor_Base);
3428 } else {
3429 CompleteDecl = GlobalDecl(DD, Dtor_Complete);
3430 BaseDecl = GlobalDecl(DD, Dtor_Base);
3431 }
3432
3433 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
3434 emitConstructorDestructorAlias(CGM, CompleteDecl, BaseDecl);
3435 return;
3436 }
3437
3438 if (CGType == StructorCodegen::RAUW) {
3439 StringRef MangledName = CGM.getMangledName(CompleteDecl);
Andrey Bokhankocab58582015-08-31 13:20:44 +00003440 auto *Aliasee = CGM.GetAddrOfGlobal(BaseDecl);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003441 CGM.addReplacement(MangledName, Aliasee);
3442 return;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003443 }
3444 }
3445
3446 // The base destructor is equivalent to the base destructor of its
3447 // base class if there is exactly one non-virtual base class with a
3448 // non-trivial destructor, there are no fields with a non-trivial
3449 // destructor, and the body of the destructor is trivial.
Rafael Espindola1e4df922014-09-16 15:18:21 +00003450 if (DD && Type == StructorType::Base && CGType != StructorCodegen::COMDAT &&
3451 !CGM.TryEmitBaseDestructorAsAlias(DD))
Rafael Espindola91f68b42014-09-15 19:20:10 +00003452 return;
3453
Rafael Espindola1e4df922014-09-16 15:18:21 +00003454 llvm::Function *Fn = CGM.codegenCXXStructor(MD, Type);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003455
Rafael Espindola1e4df922014-09-16 15:18:21 +00003456 if (CGType == StructorCodegen::COMDAT) {
3457 SmallString<256> Buffer;
3458 llvm::raw_svector_ostream Out(Buffer);
3459 if (DD)
3460 getMangleContext().mangleCXXDtorComdat(DD, Out);
3461 else
3462 getMangleContext().mangleCXXCtorComdat(CD, Out);
3463 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
3464 Fn->setComdat(C);
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003465 } else {
3466 CGM.maybeSetTrivialComdat(*MD, *Fn);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003467 }
Rafael Espindola91f68b42014-09-15 19:20:10 +00003468}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003469
3470static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) {
3471 // void *__cxa_begin_catch(void*);
3472 llvm::FunctionType *FTy = llvm::FunctionType::get(
3473 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3474
3475 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
3476}
3477
3478static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) {
3479 // void __cxa_end_catch();
3480 llvm::FunctionType *FTy =
3481 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
3482
3483 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
3484}
3485
3486static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) {
3487 // void *__cxa_get_exception_ptr(void*);
3488 llvm::FunctionType *FTy = llvm::FunctionType::get(
3489 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3490
3491 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
3492}
3493
3494namespace {
3495 /// A cleanup to call __cxa_end_catch. In many cases, the caught
3496 /// exception type lets us state definitively that the thrown exception
3497 /// type does not have a destructor. In particular:
3498 /// - Catch-alls tell us nothing, so we have to conservatively
3499 /// assume that the thrown exception might have a destructor.
3500 /// - Catches by reference behave according to their base types.
3501 /// - Catches of non-record types will only trigger for exceptions
3502 /// of non-record types, which never have destructors.
3503 /// - Catches of record types can trigger for arbitrary subclasses
3504 /// of the caught type, so we have to assume the actual thrown
3505 /// exception type might have a throwing destructor, even if the
3506 /// caught type's destructor is trivial or nothrow.
David Blaikie7e70d682015-08-18 22:40:54 +00003507 struct CallEndCatch final : EHScopeStack::Cleanup {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003508 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
3509 bool MightThrow;
3510
3511 void Emit(CodeGenFunction &CGF, Flags flags) override {
3512 if (!MightThrow) {
3513 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
3514 return;
3515 }
3516
3517 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
3518 }
3519 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003520}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003521
3522/// Emits a call to __cxa_begin_catch and enters a cleanup to call
3523/// __cxa_end_catch.
3524///
3525/// \param EndMightThrow - true if __cxa_end_catch might throw
3526static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
3527 llvm::Value *Exn,
3528 bool EndMightThrow) {
3529 llvm::CallInst *call =
3530 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
3531
3532 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
3533
3534 return call;
3535}
3536
3537/// A "special initializer" callback for initializing a catch
3538/// parameter during catch initialization.
3539static void InitCatchParam(CodeGenFunction &CGF,
3540 const VarDecl &CatchParam,
John McCall7f416cc2015-09-08 08:05:57 +00003541 Address ParamAddr,
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003542 SourceLocation Loc) {
3543 // Load the exception from where the landing pad saved it.
3544 llvm::Value *Exn = CGF.getExceptionFromSlot();
3545
3546 CanQualType CatchType =
3547 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
3548 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
3549
3550 // If we're catching by reference, we can just cast the object
3551 // pointer to the appropriate pointer.
3552 if (isa<ReferenceType>(CatchType)) {
3553 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
3554 bool EndCatchMightThrow = CaughtType->isRecordType();
3555
3556 // __cxa_begin_catch returns the adjusted object pointer.
3557 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
3558
3559 // We have no way to tell the personality function that we're
3560 // catching by reference, so if we're catching a pointer,
3561 // __cxa_begin_catch will actually return that pointer by value.
3562 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
3563 QualType PointeeType = PT->getPointeeType();
3564
3565 // When catching by reference, generally we should just ignore
3566 // this by-value pointer and use the exception object instead.
3567 if (!PointeeType->isRecordType()) {
3568
3569 // Exn points to the struct _Unwind_Exception header, which
3570 // we have to skip past in order to reach the exception data.
3571 unsigned HeaderSize =
3572 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
3573 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
3574
3575 // However, if we're catching a pointer-to-record type that won't
3576 // work, because the personality function might have adjusted
3577 // the pointer. There's actually no way for us to fully satisfy
3578 // the language/ABI contract here: we can't use Exn because it
3579 // might have the wrong adjustment, but we can't use the by-value
3580 // pointer because it's off by a level of abstraction.
3581 //
3582 // The current solution is to dump the adjusted pointer into an
3583 // alloca, which breaks language semantics (because changing the
3584 // pointer doesn't change the exception) but at least works.
3585 // The better solution would be to filter out non-exact matches
3586 // and rethrow them, but this is tricky because the rethrow
3587 // really needs to be catchable by other sites at this landing
3588 // pad. The best solution is to fix the personality function.
3589 } else {
3590 // Pull the pointer for the reference type off.
3591 llvm::Type *PtrTy =
3592 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
3593
3594 // Create the temporary and write the adjusted pointer into it.
John McCall7f416cc2015-09-08 08:05:57 +00003595 Address ExnPtrTmp =
3596 CGF.CreateTempAlloca(PtrTy, CGF.getPointerAlign(), "exn.byref.tmp");
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003597 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3598 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
3599
3600 // Bind the reference to the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00003601 AdjustedExn = ExnPtrTmp.getPointer();
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003602 }
3603 }
3604
3605 llvm::Value *ExnCast =
3606 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
3607 CGF.Builder.CreateStore(ExnCast, ParamAddr);
3608 return;
3609 }
3610
3611 // Scalars and complexes.
3612 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
3613 if (TEK != TEK_Aggregate) {
3614 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
3615
3616 // If the catch type is a pointer type, __cxa_begin_catch returns
3617 // the pointer by value.
3618 if (CatchType->hasPointerRepresentation()) {
3619 llvm::Value *CastExn =
3620 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
3621
3622 switch (CatchType.getQualifiers().getObjCLifetime()) {
3623 case Qualifiers::OCL_Strong:
3624 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
3625 // fallthrough
3626
3627 case Qualifiers::OCL_None:
3628 case Qualifiers::OCL_ExplicitNone:
3629 case Qualifiers::OCL_Autoreleasing:
3630 CGF.Builder.CreateStore(CastExn, ParamAddr);
3631 return;
3632
3633 case Qualifiers::OCL_Weak:
3634 CGF.EmitARCInitWeak(ParamAddr, CastExn);
3635 return;
3636 }
3637 llvm_unreachable("bad ownership qualifier!");
3638 }
3639
3640 // Otherwise, it returns a pointer into the exception object.
3641
3642 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3643 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3644
3645 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
John McCall7f416cc2015-09-08 08:05:57 +00003646 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003647 switch (TEK) {
3648 case TEK_Complex:
3649 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
3650 /*init*/ true);
3651 return;
3652 case TEK_Scalar: {
3653 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
3654 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
3655 return;
3656 }
3657 case TEK_Aggregate:
3658 llvm_unreachable("evaluation kind filtered out!");
3659 }
3660 llvm_unreachable("bad evaluation kind");
3661 }
3662
3663 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
John McCall7f416cc2015-09-08 08:05:57 +00003664 auto catchRD = CatchType->getAsCXXRecordDecl();
3665 CharUnits caughtExnAlignment = CGF.CGM.getClassPointerAlignment(catchRD);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003666
3667 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3668
3669 // Check for a copy expression. If we don't have a copy expression,
3670 // that means a trivial copy is okay.
3671 const Expr *copyExpr = CatchParam.getInit();
3672 if (!copyExpr) {
3673 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
John McCall7f416cc2015-09-08 08:05:57 +00003674 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3675 caughtExnAlignment);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003676 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
3677 return;
3678 }
3679
3680 // We have to call __cxa_get_exception_ptr to get the adjusted
3681 // pointer before copying.
3682 llvm::CallInst *rawAdjustedExn =
3683 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
3684
3685 // Cast that to the appropriate type.
John McCall7f416cc2015-09-08 08:05:57 +00003686 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3687 caughtExnAlignment);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003688
3689 // The copy expression is defined in terms of an OpaqueValueExpr.
3690 // Find it and map it to the adjusted expression.
3691 CodeGenFunction::OpaqueValueMapping
3692 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
3693 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
3694
3695 // Call the copy ctor in a terminate scope.
3696 CGF.EHStack.pushTerminate();
3697
3698 // Perform the copy construction.
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003699 CGF.EmitAggExpr(copyExpr,
John McCall7f416cc2015-09-08 08:05:57 +00003700 AggValueSlot::forAddr(ParamAddr, Qualifiers(),
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003701 AggValueSlot::IsNotDestructed,
3702 AggValueSlot::DoesNotNeedGCBarriers,
3703 AggValueSlot::IsNotAliased));
3704
3705 // Leave the terminate scope.
3706 CGF.EHStack.popTerminate();
3707
3708 // Undo the opaque value mapping.
3709 opaque.pop();
3710
3711 // Finally we can call __cxa_begin_catch.
3712 CallBeginCatch(CGF, Exn, true);
3713}
3714
3715/// Begins a catch statement by initializing the catch variable and
3716/// calling __cxa_begin_catch.
3717void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF,
3718 const CXXCatchStmt *S) {
3719 // We have to be very careful with the ordering of cleanups here:
3720 // C++ [except.throw]p4:
3721 // The destruction [of the exception temporary] occurs
3722 // immediately after the destruction of the object declared in
3723 // the exception-declaration in the handler.
3724 //
3725 // So the precise ordering is:
3726 // 1. Construct catch variable.
3727 // 2. __cxa_begin_catch
3728 // 3. Enter __cxa_end_catch cleanup
3729 // 4. Enter dtor cleanup
3730 //
3731 // We do this by using a slightly abnormal initialization process.
3732 // Delegation sequence:
3733 // - ExitCXXTryStmt opens a RunCleanupsScope
3734 // - EmitAutoVarAlloca creates the variable and debug info
3735 // - InitCatchParam initializes the variable from the exception
3736 // - CallBeginCatch calls __cxa_begin_catch
3737 // - CallBeginCatch enters the __cxa_end_catch cleanup
3738 // - EmitAutoVarCleanups enters the variable destructor cleanup
3739 // - EmitCXXTryStmt emits the code for the catch body
3740 // - EmitCXXTryStmt close the RunCleanupsScope
3741
3742 VarDecl *CatchParam = S->getExceptionDecl();
3743 if (!CatchParam) {
3744 llvm::Value *Exn = CGF.getExceptionFromSlot();
3745 CallBeginCatch(CGF, Exn, true);
3746 return;
3747 }
3748
3749 // Emit the local.
3750 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
3751 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
3752 CGF.EmitAutoVarCleanups(var);
3753}
3754
3755/// Get or define the following function:
3756/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
3757/// This code is used only in C++.
3758static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
3759 llvm::FunctionType *fnTy =
3760 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3761 llvm::Constant *fnRef =
3762 CGM.CreateRuntimeFunction(fnTy, "__clang_call_terminate");
3763
3764 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
3765 if (fn && fn->empty()) {
3766 fn->setDoesNotThrow();
3767 fn->setDoesNotReturn();
3768
3769 // What we really want is to massively penalize inlining without
3770 // forbidding it completely. The difference between that and
3771 // 'noinline' is negligible.
3772 fn->addFnAttr(llvm::Attribute::NoInline);
3773
3774 // Allow this function to be shared across translation units, but
3775 // we don't want it to turn into an exported symbol.
3776 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
3777 fn->setVisibility(llvm::Function::HiddenVisibility);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00003778 if (CGM.supportsCOMDAT())
3779 fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003780
3781 // Set up the function.
3782 llvm::BasicBlock *entry =
3783 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
John McCall7f416cc2015-09-08 08:05:57 +00003784 CGBuilderTy builder(CGM, entry);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003785
3786 // Pull the exception pointer out of the parameter list.
3787 llvm::Value *exn = &*fn->arg_begin();
3788
3789 // Call __cxa_begin_catch(exn).
3790 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
3791 catchCall->setDoesNotThrow();
3792 catchCall->setCallingConv(CGM.getRuntimeCC());
3793
3794 // Call std::terminate().
David Blaikie4ba525b2015-07-14 17:27:39 +00003795 llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn());
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003796 termCall->setDoesNotThrow();
3797 termCall->setDoesNotReturn();
3798 termCall->setCallingConv(CGM.getRuntimeCC());
3799
3800 // std::terminate cannot return.
3801 builder.CreateUnreachable();
3802 }
3803
3804 return fnRef;
3805}
3806
3807llvm::CallInst *
3808ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
3809 llvm::Value *Exn) {
3810 // In C++, we want to call __cxa_begin_catch() before terminating.
3811 if (Exn) {
3812 assert(CGF.CGM.getLangOpts().CPlusPlus);
3813 return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn);
3814 }
3815 return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
3816}