blob: 9d7b4da2c53bdb39bf05607e011b720f1425530e [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;
Reid Kleckner10aa7702015-09-16 20:15:55 +0000182 CatchTypeInfo
David Majnemer37b417f2015-03-29 21:55:10 +0000183 getAddrOfCXXCatchHandlerType(QualType Ty,
184 QualType CatchHandlerType) override {
Reid Kleckner10aa7702015-09-16 20:15:55 +0000185 return CatchTypeInfo{getAddrOfRTTIDescriptor(Ty), 0};
David Majnemer443250f2015-03-17 20:35:00 +0000186 }
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,
Richard Smith5a99c492015-12-01 01:10:48 +0000330 ArrayRef<const VarDecl *> CXXThreadLocals,
David Majnemerb3341ea2014-10-05 05:05:40 +0000331 ArrayRef<llvm::Function *> CXXThreadLocalInits,
Richard Smith5a99c492015-12-01 01:10:48 +0000332 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) override;
David Majnemerb3341ea2014-10-05 05:05:40 +0000333
334 bool usesThreadWrapperFunction() const override { return true; }
Richard Smith0f383742014-03-26 22:48:22 +0000335 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
336 QualType LValType) override;
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000337
Craig Topper4f12f102014-03-12 06:41:41 +0000338 bool NeedsVTTParameter(GlobalDecl GD) override;
David Majnemere2cb8d12014-07-07 06:20:47 +0000339
340 /**************************** RTTI Uniqueness ******************************/
341
342protected:
343 /// Returns true if the ABI requires RTTI type_info objects to be unique
344 /// across a program.
345 virtual bool shouldRTTIBeUnique() const { return true; }
346
347public:
348 /// What sort of unique-RTTI behavior should we use?
349 enum RTTIUniquenessKind {
350 /// We are guaranteeing, or need to guarantee, that the RTTI string
351 /// is unique.
352 RUK_Unique,
353
354 /// We are not guaranteeing uniqueness for the RTTI string, so we
355 /// can demote to hidden visibility but must use string comparisons.
356 RUK_NonUniqueHidden,
357
358 /// We are not guaranteeing uniqueness for the RTTI string, so we
359 /// have to use string comparisons, but we also have to emit it with
360 /// non-hidden visibility.
361 RUK_NonUniqueVisible
362 };
363
364 /// Return the required visibility status for the given type and linkage in
365 /// the current ABI.
366 RTTIUniquenessKind
367 classifyRTTIUniqueness(QualType CanTy,
368 llvm::GlobalValue::LinkageTypes Linkage) const;
369 friend class ItaniumRTTIBuilder;
Rafael Espindola91f68b42014-09-15 19:20:10 +0000370
371 void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000372
373 private:
Piotr Padlewski1d02f682015-08-19 20:09:09 +0000374 bool hasAnyUsedVirtualInlineFunction(const CXXRecordDecl *RD) const {
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000375 const auto &VtableLayout =
376 CGM.getItaniumVTableContext().getVTableLayout(RD);
377
378 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
Piotr Padlewski1d02f682015-08-19 20:09:09 +0000379 if (!VtableComponent.isUsedFunctionPointerKind())
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000380 continue;
381
Piotr Padlewski1d02f682015-08-19 20:09:09 +0000382 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000383 if (Method->getCanonicalDecl()->isInlined())
384 return true;
385 }
386 return false;
387 }
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000388
389 bool isVTableHidden(const CXXRecordDecl *RD) const {
390 const auto &VtableLayout =
391 CGM.getItaniumVTableContext().getVTableLayout(RD);
392
393 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
394 if (VtableComponent.isRTTIKind()) {
395 const CXXRecordDecl *RTTIDecl = VtableComponent.getRTTIDecl();
396 if (RTTIDecl->getVisibility() == Visibility::HiddenVisibility)
397 return true;
398 } else if (VtableComponent.isUsedFunctionPointerKind()) {
399 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
400 if (Method->getVisibility() == Visibility::HiddenVisibility &&
401 !Method->isDefined())
402 return true;
403 }
404 }
405 return false;
406 }
Charles Davis4e786dd2010-05-25 19:52:27 +0000407};
John McCall86353412010-08-21 22:46:04 +0000408
409class ARMCXXABI : public ItaniumCXXABI {
410public:
Mark Seabornedf0d382013-07-24 16:25:13 +0000411 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
412 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
413 /* UseARMGuardVarABI = */ true) {}
John McCall5d865c322010-08-31 07:33:07 +0000414
Craig Topper4f12f102014-03-12 06:41:41 +0000415 bool HasThisReturn(GlobalDecl GD) const override {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000416 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
417 isa<CXXDestructorDecl>(GD.getDecl()) &&
418 GD.getDtorType() != Dtor_Deleting));
419 }
John McCall5d865c322010-08-31 07:33:07 +0000420
Craig Topper4f12f102014-03-12 06:41:41 +0000421 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
422 QualType ResTy) override;
John McCall5d865c322010-08-31 07:33:07 +0000423
Craig Topper4f12f102014-03-12 06:41:41 +0000424 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall7f416cc2015-09-08 08:05:57 +0000425 Address InitializeArrayCookie(CodeGenFunction &CGF,
426 Address NewPtr,
427 llvm::Value *NumElements,
428 const CXXNewExpr *expr,
429 QualType ElementType) override;
430 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, Address allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000431 CharUnits cookieSize) override;
John McCall86353412010-08-21 22:46:04 +0000432};
Tim Northovera2ee4332014-03-29 15:09:45 +0000433
434class iOS64CXXABI : public ARMCXXABI {
435public:
436 iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {}
Tim Northover65f582f2014-03-30 17:32:48 +0000437
438 // ARM64 libraries are prepared for non-unique RTTI.
David Majnemere2cb8d12014-07-07 06:20:47 +0000439 bool shouldRTTIBeUnique() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +0000440};
Dan Gohmanc2853072015-09-03 22:51:53 +0000441
442class WebAssemblyCXXABI final : public ItaniumCXXABI {
443public:
444 explicit WebAssemblyCXXABI(CodeGen::CodeGenModule &CGM)
445 : ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
446 /*UseARMGuardVarABI=*/true) {}
447
448private:
449 bool HasThisReturn(GlobalDecl GD) const override {
450 return isa<CXXConstructorDecl>(GD.getDecl()) ||
451 (isa<CXXDestructorDecl>(GD.getDecl()) &&
452 GD.getDtorType() != Dtor_Deleting);
453 }
454};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000455}
Charles Davis4e786dd2010-05-25 19:52:27 +0000456
Charles Davis53c59df2010-08-16 03:33:14 +0000457CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000458 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000459 // For IR-generation purposes, there's no significant difference
460 // between the ARM and iOS ABIs.
461 case TargetCXXABI::GenericARM:
462 case TargetCXXABI::iOS:
Tim Northover756447a2015-10-30 16:30:36 +0000463 case TargetCXXABI::WatchOS:
John McCall57625922013-01-25 23:36:14 +0000464 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
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000537 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(
538 CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr));
John McCall475999d2010-08-22 00:05:51 +0000539
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000540 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000541
John McCalld9c6c0b2010-08-22 00:59:17 +0000542 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
543 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
544 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
545
John McCalla1dee5302010-08-22 10:59:02 +0000546 // Extract memptr.adj, which is in the second field.
547 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000548
549 // Compute the true adjustment.
550 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000551 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000552 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000553
554 // Apply the adjustment and cast back to the original struct type
555 // for consistency.
John McCall7f416cc2015-09-08 08:05:57 +0000556 llvm::Value *This = ThisAddr.getPointer();
John McCalld9c6c0b2010-08-22 00:59:17 +0000557 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
558 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
559 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall7f416cc2015-09-08 08:05:57 +0000560 ThisPtrForCall = This;
John McCall475999d2010-08-22 00:05:51 +0000561
562 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000563 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall475999d2010-08-22 00:05:51 +0000564
565 // If the LSB in the function pointer is 1, the function pointer points to
566 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000567 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000568 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000569 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
570 else
571 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
572 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000573 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
574
575 // In the virtual path, the adjustment left 'This' pointing to the
576 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000577 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000578 CGF.EmitBlock(FnVirtual);
579
580 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000581 llvm::Type *VTableTy = Builder.getInt8PtrTy();
John McCall7f416cc2015-09-08 08:05:57 +0000582 CharUnits VTablePtrAlign =
583 CGF.CGM.getDynamicOffsetAlignment(ThisAddr.getAlignment(), RD,
584 CGF.getPointerAlign());
585 llvm::Value *VTable =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000586 CGF.GetVTablePtr(Address(This, VTablePtrAlign), VTableTy, RD);
John McCall475999d2010-08-22 00:05:51 +0000587
588 // Apply the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000589 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000590 if (!UseARMMethodPtrABI)
591 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld9c6c0b2010-08-22 00:59:17 +0000592 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall475999d2010-08-22 00:05:51 +0000593
594 // Load the virtual function to call.
595 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCall7f416cc2015-09-08 08:05:57 +0000596 llvm::Value *VirtualFn =
597 Builder.CreateAlignedLoad(VTable, CGF.getPointerAlign(),
598 "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000599 CGF.EmitBranch(FnEnd);
600
601 // In the non-virtual path, the function pointer is actually a
602 // function pointer.
603 CGF.EmitBlock(FnNonVirtual);
604 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000605 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall475999d2010-08-22 00:05:51 +0000606
607 // We're done.
608 CGF.EmitBlock(FnEnd);
Jay Foad20c0f022011-03-30 11:28:58 +0000609 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
John McCall475999d2010-08-22 00:05:51 +0000610 Callee->addIncoming(VirtualFn, FnVirtual);
611 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
612 return Callee;
613}
John McCalla8bbb822010-08-22 03:04:22 +0000614
John McCallc134eb52010-08-31 21:07:20 +0000615/// Compute an l-value by applying the given pointer-to-member to a
616/// base object.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000617llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
John McCall7f416cc2015-09-08 08:05:57 +0000618 CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000619 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000620 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000621
622 CGBuilderTy &Builder = CGF.Builder;
623
John McCallc134eb52010-08-31 21:07:20 +0000624 // Cast to char*.
John McCall7f416cc2015-09-08 08:05:57 +0000625 Base = Builder.CreateElementBitCast(Base, CGF.Int8Ty);
John McCallc134eb52010-08-31 21:07:20 +0000626
627 // Apply the offset, which we assume is non-null.
John McCall7f416cc2015-09-08 08:05:57 +0000628 llvm::Value *Addr =
629 Builder.CreateInBoundsGEP(Base.getPointer(), MemPtr, "memptr.offset");
John McCallc134eb52010-08-31 21:07:20 +0000630
631 // Cast the address to the appropriate pointer type, adopting the
632 // address space of the base pointer.
John McCall7f416cc2015-09-08 08:05:57 +0000633 llvm::Type *PType = CGF.ConvertTypeForMem(MPT->getPointeeType())
634 ->getPointerTo(Base.getAddressSpace());
John McCallc134eb52010-08-31 21:07:20 +0000635 return Builder.CreateBitCast(Addr, PType);
636}
637
John McCallc62bb392012-02-15 01:22:51 +0000638/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
639/// conversion.
640///
641/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000642///
643/// Obligatory offset/adjustment diagram:
644/// <-- offset --> <-- adjustment -->
645/// |--------------------------|----------------------|--------------------|
646/// ^Derived address point ^Base address point ^Member address point
647///
648/// So when converting a base member pointer to a derived member pointer,
649/// we add the offset to the adjustment because the address point has
650/// decreased; and conversely, when converting a derived MP to a base MP
651/// we subtract the offset from the adjustment because the address point
652/// has increased.
653///
654/// The standard forbids (at compile time) conversion to and from
655/// virtual bases, which is why we don't have to consider them here.
656///
657/// The standard forbids (at run time) casting a derived MP to a base
658/// MP when the derived MP does not point to a member of the base.
659/// This is why -1 is a reasonable choice for null data member
660/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000661llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000662ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
663 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000664 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000665 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000666 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
667 E->getCastKind() == CK_ReinterpretMemberPointer);
668
669 // Under Itanium, reinterprets don't require any additional processing.
670 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
671
672 // Use constant emission if we can.
673 if (isa<llvm::Constant>(src))
674 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
675
676 llvm::Constant *adj = getMemberPointerAdjustment(E);
677 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000678
679 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000680 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000681
John McCallc62bb392012-02-15 01:22:51 +0000682 const MemberPointerType *destTy =
683 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000684
John McCall7a9aac22010-08-23 01:21:21 +0000685 // For member data pointers, this is just a matter of adding the
686 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000687 if (destTy->isMemberDataPointer()) {
688 llvm::Value *dst;
689 if (isDerivedToBase)
690 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000691 else
John McCallc62bb392012-02-15 01:22:51 +0000692 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000693
694 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000695 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
696 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
697 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000698 }
699
John McCalla1dee5302010-08-22 10:59:02 +0000700 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000701 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000702 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
703 offset <<= 1;
704 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000705 }
706
John McCallc62bb392012-02-15 01:22:51 +0000707 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
708 llvm::Value *dstAdj;
709 if (isDerivedToBase)
710 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000711 else
John McCallc62bb392012-02-15 01:22:51 +0000712 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000713
John McCallc62bb392012-02-15 01:22:51 +0000714 return Builder.CreateInsertValue(src, dstAdj, 1);
715}
716
717llvm::Constant *
718ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
719 llvm::Constant *src) {
720 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
721 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
722 E->getCastKind() == CK_ReinterpretMemberPointer);
723
724 // Under Itanium, reinterprets don't require any additional processing.
725 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
726
727 // If the adjustment is trivial, we don't need to do anything.
728 llvm::Constant *adj = getMemberPointerAdjustment(E);
729 if (!adj) return src;
730
731 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
732
733 const MemberPointerType *destTy =
734 E->getType()->castAs<MemberPointerType>();
735
736 // For member data pointers, this is just a matter of adding the
737 // offset if the source is non-null.
738 if (destTy->isMemberDataPointer()) {
739 // null maps to null.
740 if (src->isAllOnesValue()) return src;
741
742 if (isDerivedToBase)
743 return llvm::ConstantExpr::getNSWSub(src, adj);
744 else
745 return llvm::ConstantExpr::getNSWAdd(src, adj);
746 }
747
748 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000749 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000750 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
751 offset <<= 1;
752 adj = llvm::ConstantInt::get(adj->getType(), offset);
753 }
754
755 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
756 llvm::Constant *dstAdj;
757 if (isDerivedToBase)
758 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
759 else
760 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
761
762 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000763}
John McCall84fa5102010-08-22 04:16:24 +0000764
765llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000766ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000767 // Itanium C++ ABI 2.3:
768 // A NULL pointer is represented as -1.
769 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000770 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000771
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000772 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000773 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000774 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000775}
776
John McCallf3a88602011-02-03 08:15:49 +0000777llvm::Constant *
778ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
779 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000780 // Itanium C++ ABI 2.3:
781 // A pointer to data member is an offset from the base address of
782 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000783 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000784}
785
David Majnemere2be95b2015-06-23 07:31:01 +0000786llvm::Constant *
787ItaniumCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000788 return BuildMemberPointer(MD, CharUnits::Zero());
789}
790
791llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
792 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000793 assert(MD->isInstance() && "Member function must not be static!");
794 MD = MD->getCanonicalDecl();
795
796 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000797
798 // Get the function pointer (or index if this is a virtual function).
799 llvm::Constant *MemPtr[2];
800 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000801 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000802
Ken Dyckdf016282011-04-09 01:30:02 +0000803 const ASTContext &Context = getContext();
804 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000805 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000806 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000807
Mark Seabornedf0d382013-07-24 16:25:13 +0000808 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000809 // ARM C++ ABI 3.2.1:
810 // This ABI specifies that adj contains twice the this
811 // adjustment, plus 1 if the member function is virtual. The
812 // least significant bit of adj then makes exactly the same
813 // discrimination as the least significant bit of ptr does for
814 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000815 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
816 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000817 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000818 } else {
819 // Itanium C++ ABI 2.3:
820 // For a virtual function, [the pointer field] is 1 plus the
821 // virtual table offset (in bytes) of the function,
822 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000823 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
824 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000825 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000826 }
827 } else {
John McCall2979fe02011-04-12 00:42:48 +0000828 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000829 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000830 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000831 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000832 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000833 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000834 } else {
John McCall2979fe02011-04-12 00:42:48 +0000835 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
836 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000837 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000838 }
John McCall2979fe02011-04-12 00:42:48 +0000839 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000840
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000841 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000842 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
843 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000844 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000845 }
John McCall1c456c82010-08-22 06:43:33 +0000846
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000847 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000848}
849
Richard Smithdafff942012-01-14 04:30:29 +0000850llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
851 QualType MPType) {
852 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
853 const ValueDecl *MPD = MP.getMemberPointerDecl();
854 if (!MPD)
855 return EmitNullMemberPointer(MPT);
856
Reid Kleckner452abac2013-05-09 21:01:17 +0000857 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000858
859 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
860 return BuildMemberPointer(MD, ThisAdjustment);
861
862 CharUnits FieldOffset =
863 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
864 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
865}
866
John McCall131d97d2010-08-22 08:30:07 +0000867/// The comparison algorithm is pretty easy: the member pointers are
868/// the same if they're either bitwise identical *or* both null.
869///
870/// ARM is different here only because null-ness is more complicated.
871llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000872ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
873 llvm::Value *L,
874 llvm::Value *R,
875 const MemberPointerType *MPT,
876 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000877 CGBuilderTy &Builder = CGF.Builder;
878
John McCall131d97d2010-08-22 08:30:07 +0000879 llvm::ICmpInst::Predicate Eq;
880 llvm::Instruction::BinaryOps And, Or;
881 if (Inequality) {
882 Eq = llvm::ICmpInst::ICMP_NE;
883 And = llvm::Instruction::Or;
884 Or = llvm::Instruction::And;
885 } else {
886 Eq = llvm::ICmpInst::ICMP_EQ;
887 And = llvm::Instruction::And;
888 Or = llvm::Instruction::Or;
889 }
890
John McCall7a9aac22010-08-23 01:21:21 +0000891 // Member data pointers are easy because there's a unique null
892 // value, so it just comes down to bitwise equality.
893 if (MPT->isMemberDataPointer())
894 return Builder.CreateICmp(Eq, L, R);
895
896 // For member function pointers, the tautologies are more complex.
897 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000898 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000899 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000900 // (L == R) <==> (L.ptr == R.ptr &&
901 // (L.adj == R.adj ||
902 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000903 // The inequality tautologies have exactly the same structure, except
904 // applying De Morgan's laws.
905
906 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
907 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
908
John McCall131d97d2010-08-22 08:30:07 +0000909 // This condition tests whether L.ptr == R.ptr. This must always be
910 // true for equality to hold.
911 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
912
913 // This condition, together with the assumption that L.ptr == R.ptr,
914 // tests whether the pointers are both null. ARM imposes an extra
915 // condition.
916 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
917 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
918
919 // This condition tests whether L.adj == R.adj. If this isn't
920 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +0000921 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
922 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000923 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
924
925 // Null member function pointers on ARM clear the low bit of Adj,
926 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000927 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000928 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
929
930 // Compute (l.adj | r.adj) & 1 and test it against zero.
931 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
932 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
933 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
934 "cmp.or.adj");
935 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
936 }
937
938 // Tie together all our conditions.
939 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
940 Result = Builder.CreateBinOp(And, PtrEq, Result,
941 Inequality ? "memptr.ne" : "memptr.eq");
942 return Result;
943}
944
945llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000946ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
947 llvm::Value *MemPtr,
948 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +0000949 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +0000950
951 /// For member data pointers, this is just a check against -1.
952 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000953 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +0000954 llvm::Value *NegativeOne =
955 llvm::Constant::getAllOnesValue(MemPtr->getType());
956 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
957 }
John McCall131d97d2010-08-22 08:30:07 +0000958
Daniel Dunbar914bc412011-04-19 23:10:47 +0000959 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +0000960 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +0000961
962 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
963 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
964
Daniel Dunbar914bc412011-04-19 23:10:47 +0000965 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
966 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000967 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000968 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +0000969 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000970 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +0000971 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
972 "memptr.isvirtual");
973 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +0000974 }
975
976 return Result;
977}
John McCall1c456c82010-08-22 06:43:33 +0000978
Reid Kleckner40ca9132014-05-13 22:05:45 +0000979bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
980 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
981 if (!RD)
982 return false;
983
Reid Klecknerd355ca72014-05-15 01:26:32 +0000984 // Return indirectly if we have a non-trivial copy ctor or non-trivial dtor.
985 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
986 // special members.
987 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor()) {
John McCall7f416cc2015-09-08 08:05:57 +0000988 auto Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
989 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
Reid Kleckner40ca9132014-05-13 22:05:45 +0000990 return true;
991 }
Reid Kleckner40ca9132014-05-13 22:05:45 +0000992 return false;
993}
994
John McCall614dbdc2010-08-22 21:01:12 +0000995/// The Itanium ABI requires non-zero initialization only for data
996/// member pointers, for which '0' is a valid offset.
997bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
David Majnemer5fd33e02015-04-24 01:25:08 +0000998 return MPT->isMemberFunctionPointer();
John McCall84fa5102010-08-22 04:16:24 +0000999}
John McCall5d865c322010-08-31 07:33:07 +00001000
John McCall82fb8922012-09-25 10:10:39 +00001001/// The Itanium ABI always places an offset to the complete object
1002/// at entry -2 in the vtable.
David Majnemer08681372014-11-01 07:37:17 +00001003void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
1004 const CXXDeleteExpr *DE,
John McCall7f416cc2015-09-08 08:05:57 +00001005 Address Ptr,
David Majnemer08681372014-11-01 07:37:17 +00001006 QualType ElementType,
1007 const CXXDestructorDecl *Dtor) {
1008 bool UseGlobalDelete = DE->isGlobalDelete();
David Majnemer0c0b6d92014-10-31 20:09:12 +00001009 if (UseGlobalDelete) {
1010 // Derive the complete-object pointer, which is what we need
1011 // to pass to the deallocation function.
John McCall82fb8922012-09-25 10:10:39 +00001012
David Majnemer0c0b6d92014-10-31 20:09:12 +00001013 // Grab the vtable pointer as an intptr_t*.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001014 auto *ClassDecl =
1015 cast<CXXRecordDecl>(ElementType->getAs<RecordType>()->getDecl());
1016 llvm::Value *VTable =
1017 CGF.GetVTablePtr(Ptr, CGF.IntPtrTy->getPointerTo(), ClassDecl);
John McCall82fb8922012-09-25 10:10:39 +00001018
David Majnemer0c0b6d92014-10-31 20:09:12 +00001019 // Track back to entry -2 and pull out the offset there.
1020 llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
1021 VTable, -2, "complete-offset.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001022 llvm::Value *Offset =
1023 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
David Majnemer0c0b6d92014-10-31 20:09:12 +00001024
1025 // Apply the offset.
John McCall7f416cc2015-09-08 08:05:57 +00001026 llvm::Value *CompletePtr =
1027 CGF.Builder.CreateBitCast(Ptr.getPointer(), CGF.Int8PtrTy);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001028 CompletePtr = CGF.Builder.CreateInBoundsGEP(CompletePtr, Offset);
1029
1030 // If we're supposed to call the global delete, make sure we do so
1031 // even if the destructor throws.
David Majnemer08681372014-11-01 07:37:17 +00001032 CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr,
1033 ElementType);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001034 }
1035
1036 // FIXME: Provide a source location here even though there's no
1037 // CXXMemberCallExpr for dtor call.
1038 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
1039 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr);
1040
1041 if (UseGlobalDelete)
1042 CGF.PopCleanupBlock();
John McCall82fb8922012-09-25 10:10:39 +00001043}
1044
David Majnemer442d0a22014-11-25 07:20:20 +00001045void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
1046 // void __cxa_rethrow();
1047
1048 llvm::FunctionType *FTy =
1049 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
1050
1051 llvm::Constant *Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
1052
1053 if (isNoReturn)
1054 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, None);
1055 else
1056 CGF.EmitRuntimeCallOrInvoke(Fn);
1057}
1058
David Majnemer7c237072015-03-05 00:46:22 +00001059static llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) {
1060 // void *__cxa_allocate_exception(size_t thrown_size);
1061
1062 llvm::FunctionType *FTy =
1063 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false);
1064
1065 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
1066}
1067
1068static llvm::Constant *getThrowFn(CodeGenModule &CGM) {
1069 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
1070 // void (*dest) (void *));
1071
1072 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
1073 llvm::FunctionType *FTy =
1074 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
1075
1076 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
1077}
1078
1079void ItaniumCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
1080 QualType ThrowType = E->getSubExpr()->getType();
1081 // Now allocate the exception object.
1082 llvm::Type *SizeTy = CGF.ConvertType(getContext().getSizeType());
1083 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
1084
1085 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM);
1086 llvm::CallInst *ExceptionPtr = CGF.EmitNounwindRuntimeCall(
1087 AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception");
1088
John McCall7f416cc2015-09-08 08:05:57 +00001089 CharUnits ExnAlign = getAlignmentOfExnObject();
1090 CGF.EmitAnyExprToExn(E->getSubExpr(), Address(ExceptionPtr, ExnAlign));
David Majnemer7c237072015-03-05 00:46:22 +00001091
1092 // Now throw the exception.
1093 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
1094 /*ForEH=*/true);
1095
1096 // The address of the destructor. If the exception type has a
1097 // trivial destructor (or isn't a record), we just pass null.
1098 llvm::Constant *Dtor = nullptr;
1099 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
1100 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
1101 if (!Record->hasTrivialDestructor()) {
1102 CXXDestructorDecl *DtorD = Record->getDestructor();
1103 Dtor = CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete);
1104 Dtor = llvm::ConstantExpr::getBitCast(Dtor, CGM.Int8PtrTy);
1105 }
1106 }
1107 if (!Dtor) Dtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
1108
1109 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
1110 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
1111}
1112
David Majnemer1162d252014-06-22 19:05:33 +00001113static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) {
1114 // void *__dynamic_cast(const void *sub,
1115 // const abi::__class_type_info *src,
1116 // const abi::__class_type_info *dst,
1117 // std::ptrdiff_t src2dst_offset);
1118
1119 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1120 llvm::Type *PtrDiffTy =
1121 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1122
1123 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
1124
1125 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
1126
1127 // Mark the function as nounwind readonly.
1128 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
1129 llvm::Attribute::ReadOnly };
1130 llvm::AttributeSet Attrs = llvm::AttributeSet::get(
1131 CGF.getLLVMContext(), llvm::AttributeSet::FunctionIndex, FuncAttrs);
1132
1133 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
1134}
1135
1136static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1137 // void __cxa_bad_cast();
1138 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1139 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1140}
1141
1142/// \brief Compute the src2dst_offset hint as described in the
1143/// Itanium C++ ABI [2.9.7]
1144static CharUnits computeOffsetHint(ASTContext &Context,
1145 const CXXRecordDecl *Src,
1146 const CXXRecordDecl *Dst) {
1147 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1148 /*DetectVirtual=*/false);
1149
1150 // If Dst is not derived from Src we can skip the whole computation below and
1151 // return that Src is not a public base of Dst. Record all inheritance paths.
1152 if (!Dst->isDerivedFrom(Src, Paths))
1153 return CharUnits::fromQuantity(-2ULL);
1154
1155 unsigned NumPublicPaths = 0;
1156 CharUnits Offset;
1157
1158 // Now walk all possible inheritance paths.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001159 for (const CXXBasePath &Path : Paths) {
1160 if (Path.Access != AS_public) // Ignore non-public inheritance.
David Majnemer1162d252014-06-22 19:05:33 +00001161 continue;
1162
1163 ++NumPublicPaths;
1164
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001165 for (const CXXBasePathElement &PathElement : Path) {
David Majnemer1162d252014-06-22 19:05:33 +00001166 // If the path contains a virtual base class we can't give any hint.
1167 // -1: no hint.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001168 if (PathElement.Base->isVirtual())
David Majnemer1162d252014-06-22 19:05:33 +00001169 return CharUnits::fromQuantity(-1ULL);
1170
1171 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
1172 continue;
1173
1174 // Accumulate the base class offsets.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001175 const ASTRecordLayout &L = Context.getASTRecordLayout(PathElement.Class);
1176 Offset += L.getBaseClassOffset(
1177 PathElement.Base->getType()->getAsCXXRecordDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001178 }
1179 }
1180
1181 // -2: Src is not a public base of Dst.
1182 if (NumPublicPaths == 0)
1183 return CharUnits::fromQuantity(-2ULL);
1184
1185 // -3: Src is a multiple public base type but never a virtual base type.
1186 if (NumPublicPaths > 1)
1187 return CharUnits::fromQuantity(-3ULL);
1188
1189 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
1190 // Return the offset of Src from the origin of Dst.
1191 return Offset;
1192}
1193
1194static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1195 // void __cxa_bad_typeid();
1196 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1197
1198 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1199}
1200
1201bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
1202 QualType SrcRecordTy) {
1203 return IsDeref;
1204}
1205
1206void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
1207 llvm::Value *Fn = getBadTypeidFn(CGF);
1208 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1209 CGF.Builder.CreateUnreachable();
1210}
1211
1212llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
1213 QualType SrcRecordTy,
John McCall7f416cc2015-09-08 08:05:57 +00001214 Address ThisPtr,
David Majnemer1162d252014-06-22 19:05:33 +00001215 llvm::Type *StdTypeInfoPtrTy) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001216 auto *ClassDecl =
1217 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001218 llvm::Value *Value =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001219 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo(), ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001220
1221 // Load the type info.
1222 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001223 return CGF.Builder.CreateAlignedLoad(Value, CGF.getPointerAlign());
David Majnemer1162d252014-06-22 19:05:33 +00001224}
1225
1226bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1227 QualType SrcRecordTy) {
1228 return SrcIsPtr;
1229}
1230
1231llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
John McCall7f416cc2015-09-08 08:05:57 +00001232 CodeGenFunction &CGF, Address ThisAddr, QualType SrcRecordTy,
David Majnemer1162d252014-06-22 19:05:33 +00001233 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1234 llvm::Type *PtrDiffLTy =
1235 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1236 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1237
1238 llvm::Value *SrcRTTI =
1239 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1240 llvm::Value *DestRTTI =
1241 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1242
1243 // Compute the offset hint.
1244 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1245 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1246 llvm::Value *OffsetHint = llvm::ConstantInt::get(
1247 PtrDiffLTy,
1248 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
1249
1250 // Emit the call to __dynamic_cast.
John McCall7f416cc2015-09-08 08:05:57 +00001251 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001252 Value = CGF.EmitCastToVoidPtr(Value);
1253
1254 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
1255 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
1256 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1257
1258 /// C++ [expr.dynamic.cast]p9:
1259 /// A failed cast to reference type throws std::bad_cast
1260 if (DestTy->isReferenceType()) {
1261 llvm::BasicBlock *BadCastBlock =
1262 CGF.createBasicBlock("dynamic_cast.bad_cast");
1263
1264 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1265 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1266
1267 CGF.EmitBlock(BadCastBlock);
1268 EmitBadCastCall(CGF);
1269 }
1270
1271 return Value;
1272}
1273
1274llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001275 Address ThisAddr,
David Majnemer1162d252014-06-22 19:05:33 +00001276 QualType SrcRecordTy,
1277 QualType DestTy) {
1278 llvm::Type *PtrDiffLTy =
1279 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1280 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1281
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001282 auto *ClassDecl =
1283 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001284 // Get the vtable pointer.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001285 llvm::Value *VTable = CGF.GetVTablePtr(ThisAddr, PtrDiffLTy->getPointerTo(),
1286 ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001287
1288 // Get the offset-to-top from the vtable.
1289 llvm::Value *OffsetToTop =
1290 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001291 OffsetToTop =
1292 CGF.Builder.CreateAlignedLoad(OffsetToTop, CGF.getPointerAlign(),
1293 "offset.to.top");
David Majnemer1162d252014-06-22 19:05:33 +00001294
1295 // Finally, add the offset to the pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001296 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001297 Value = CGF.EmitCastToVoidPtr(Value);
1298 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1299
1300 return CGF.Builder.CreateBitCast(Value, DestLTy);
1301}
1302
1303bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1304 llvm::Value *Fn = getBadCastFn(CGF);
1305 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1306 CGF.Builder.CreateUnreachable();
1307 return true;
1308}
1309
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001310llvm::Value *
1311ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001312 Address This,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001313 const CXXRecordDecl *ClassDecl,
1314 const CXXRecordDecl *BaseClassDecl) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001315 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy, ClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001316 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001317 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1318 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001319
1320 llvm::Value *VBaseOffsetPtr =
1321 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1322 "vbase.offset.ptr");
1323 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1324 CGM.PtrDiffTy->getPointerTo());
1325
1326 llvm::Value *VBaseOffset =
John McCall7f416cc2015-09-08 08:05:57 +00001327 CGF.Builder.CreateAlignedLoad(VBaseOffsetPtr, CGF.getPointerAlign(),
1328 "vbase.offset");
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001329
1330 return VBaseOffset;
1331}
1332
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001333void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1334 // Just make sure we're in sync with TargetCXXABI.
1335 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1336
Rafael Espindolac3cde362013-12-09 14:51:17 +00001337 // The constructor used for constructing this as a base class;
1338 // ignores virtual bases.
1339 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1340
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001341 // The constructor used for constructing this as a complete class;
Nico Weber4c2ffb22015-01-07 05:25:05 +00001342 // constructs the virtual bases, then calls the base constructor.
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001343 if (!D->getParent()->isAbstract()) {
1344 // We don't need to emit the complete ctor if the class is abstract.
1345 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1346 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001347}
1348
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001349void
1350ItaniumCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
1351 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +00001352 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001353
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001354 // All parameters are already in place except VTT, which goes after 'this'.
1355 // These are Clang types, so we don't need to worry about sret yet.
John McCall5d865c322010-08-31 07:33:07 +00001356
1357 // Check if we need to add a VTT parameter (which has type void **).
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001358 if (T == StructorType::Base && MD->getParent()->getNumVBases() != 0)
1359 ArgTys.insert(ArgTys.begin() + 1,
1360 Context.getPointerType(Context.VoidPtrTy));
John McCall5d865c322010-08-31 07:33:07 +00001361}
1362
Reid Klecknere7de47e2013-07-22 13:51:44 +00001363void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
Rafael Espindolac3cde362013-12-09 14:51:17 +00001364 // The destructor used for destructing this as a base class; ignores
1365 // virtual bases.
1366 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001367
1368 // The destructor used for destructing this as a most-derived class;
1369 // call the base destructor and then destructs any virtual bases.
1370 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1371
Rafael Espindolac3cde362013-12-09 14:51:17 +00001372 // The destructor in a virtual table is always a 'deleting'
1373 // destructor, which calls the complete destructor and then uses the
1374 // appropriate operator delete.
1375 if (D->isVirtual())
1376 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001377}
1378
Reid Kleckner89077a12013-12-17 19:46:40 +00001379void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1380 QualType &ResTy,
1381 FunctionArgList &Params) {
John McCall5d865c322010-08-31 07:33:07 +00001382 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +00001383 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
John McCall5d865c322010-08-31 07:33:07 +00001384
1385 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001386 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +00001387 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001388
1389 // FIXME: avoid the fake decl
1390 QualType T = Context.getPointerType(Context.VoidPtrTy);
1391 ImplicitParamDecl *VTTDecl
Craig Topper8a13c412014-05-21 05:09:00 +00001392 = ImplicitParamDecl::Create(Context, nullptr, MD->getLocation(),
John McCall5d865c322010-08-31 07:33:07 +00001393 &Context.Idents.get("vtt"), T);
Reid Kleckner89077a12013-12-17 19:46:40 +00001394 Params.insert(Params.begin() + 1, VTTDecl);
Reid Kleckner2af6d732013-12-13 00:09:59 +00001395 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +00001396 }
1397}
1398
John McCall5d865c322010-08-31 07:33:07 +00001399void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1400 /// Initialize the 'this' slot.
1401 EmitThisParam(CGF);
1402
1403 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +00001404 if (getStructorImplicitParamDecl(CGF)) {
1405 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1406 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +00001407 }
John McCall5d865c322010-08-31 07:33:07 +00001408
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001409 /// If this is a function that the ABI specifies returns 'this', initialize
1410 /// the return slot to 'this' at the start of the function.
1411 ///
1412 /// Unlike the setting of return types, this is done within the ABI
1413 /// implementation instead of by clients of CGCXXABI because:
1414 /// 1) getThisValue is currently protected
1415 /// 2) in theory, an ABI could implement 'this' returns some other way;
1416 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +00001417 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +00001418 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +00001419}
1420
Reid Kleckner89077a12013-12-17 19:46:40 +00001421unsigned ItaniumCXXABI::addImplicitConstructorArgs(
1422 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1423 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1424 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
1425 return 0;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001426
Reid Kleckner89077a12013-12-17 19:46:40 +00001427 // Insert the implicit 'vtt' argument as the second argument.
1428 llvm::Value *VTT =
1429 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1430 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1431 Args.insert(Args.begin() + 1,
1432 CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false));
1433 return 1; // Added one arg.
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001434}
1435
1436void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1437 const CXXDestructorDecl *DD,
1438 CXXDtorType Type, bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +00001439 bool Delegating, Address This) {
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001440 GlobalDecl GD(DD, Type);
1441 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1442 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1443
Craig Topper8a13c412014-05-21 05:09:00 +00001444 llvm::Value *Callee = nullptr;
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001445 if (getContext().getLangOpts().AppleKext)
1446 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
1447
1448 if (!Callee)
Rafael Espindola1ac0ec82014-09-11 15:42:06 +00001449 Callee = CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type));
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001450
John McCall7f416cc2015-09-08 08:05:57 +00001451 CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(),
1452 This.getPointer(), VTT, VTTTy, nullptr);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001453}
1454
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001455void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1456 const CXXRecordDecl *RD) {
1457 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1458 if (VTable->hasInitializer())
1459 return;
1460
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001461 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001462 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1463 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
David Majnemerd905da42014-07-01 20:30:31 +00001464 llvm::Constant *RTTI =
1465 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001466
1467 // Create and set the initializer.
1468 llvm::Constant *Init = CGVT.CreateVTableInitializer(
1469 RD, VTLayout.vtable_component_begin(), VTLayout.getNumVTableComponents(),
David Majnemerd905da42014-07-01 20:30:31 +00001470 VTLayout.vtable_thunk_begin(), VTLayout.getNumVTableThunks(), RTTI);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001471 VTable->setInitializer(Init);
1472
1473 // Set the correct linkage.
1474 VTable->setLinkage(Linkage);
1475
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001476 if (CGM.supportsCOMDAT() && VTable->isWeakForLinker())
1477 VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName()));
Rafael Espindolacb92c192015-01-15 23:18:01 +00001478
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001479 // Set the right visibility.
John McCall8f80a612014-02-08 00:41:16 +00001480 CGM.setGlobalVisibility(VTable, RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001481
Benjamin Kramer5d34a2b2014-09-10 12:50:59 +00001482 // Use pointer alignment for the vtable. Otherwise we would align them based
1483 // on the size of the initializer which doesn't make sense as only single
1484 // values are read.
1485 unsigned PAlign = CGM.getTarget().getPointerAlign(0);
1486 VTable->setAlignment(getContext().toCharUnitsFromBits(PAlign).getQuantity());
1487
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001488 // If this is the magic class __cxxabiv1::__fundamental_type_info,
1489 // we will emit the typeinfo for the fundamental types. This is the
1490 // same behaviour as GCC.
1491 const DeclContext *DC = RD->getDeclContext();
1492 if (RD->getIdentifier() &&
1493 RD->getIdentifier()->isStr("__fundamental_type_info") &&
1494 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1495 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1496 DC->getParent()->isTranslationUnit())
David Majnemere2cb8d12014-07-07 06:20:47 +00001497 EmitFundamentalRTTIDescriptors();
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001498
Evgeniy Stepanov93987df2016-01-23 01:20:18 +00001499 if (!VTable->isDeclarationForLinker())
1500 CGM.EmitVTableBitSetEntries(VTable, VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001501}
1502
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001503bool ItaniumCXXABI::isVirtualOffsetNeededForVTableField(
1504 CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
1505 if (Vptr.NearestVBase == nullptr)
1506 return false;
1507 return NeedsVTTParameter(CGF.CurGD);
Piotr Padlewski255652e2015-09-09 22:20:28 +00001508}
1509
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001510llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1511 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1512 const CXXRecordDecl *NearestVBase) {
1513
1514 if ((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1515 NeedsVTTParameter(CGF.CurGD)) {
1516 return getVTableAddressPointInStructorWithVTT(CGF, VTableClass, Base,
1517 NearestVBase);
1518 }
1519 return getVTableAddressPoint(Base, VTableClass);
1520}
1521
1522llvm::Constant *
1523ItaniumCXXABI::getVTableAddressPoint(BaseSubobject Base,
1524 const CXXRecordDecl *VTableClass) {
1525 llvm::GlobalValue *VTable = getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001526
1527 // Find the appropriate vtable within the vtable group.
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001528 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1529 .getVTableLayout(VTableClass)
1530 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001531 llvm::Value *Indices[] = {
1532 llvm::ConstantInt::get(CGM.Int64Ty, 0),
1533 llvm::ConstantInt::get(CGM.Int64Ty, AddressPoint)
1534 };
1535
David Blaikiee3b172a2015-04-02 18:55:21 +00001536 return llvm::ConstantExpr::getInBoundsGetElementPtr(VTable->getValueType(),
1537 VTable, Indices);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001538}
1539
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001540llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructorWithVTT(
1541 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1542 const CXXRecordDecl *NearestVBase) {
1543 assert((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1544 NeedsVTTParameter(CGF.CurGD) && "This class doesn't have VTT");
1545
1546 // Get the secondary vpointer index.
1547 uint64_t VirtualPointerIndex =
1548 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1549
1550 /// Load the VTT.
1551 llvm::Value *VTT = CGF.LoadCXXVTT();
1552 if (VirtualPointerIndex)
1553 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1554
1555 // And load the address point from the VTT.
1556 return CGF.Builder.CreateAlignedLoad(VTT, CGF.getPointerAlign());
1557}
1558
1559llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1560 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1561 return getVTableAddressPoint(Base, VTableClass);
1562}
1563
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001564llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1565 CharUnits VPtrOffset) {
1566 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1567
1568 llvm::GlobalVariable *&VTable = VTables[RD];
1569 if (VTable)
1570 return VTable;
1571
Eric Christopherd160c502016-01-29 01:35:53 +00001572 // Queue up this vtable for possible deferred emission.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001573 CGM.addDeferredVTable(RD);
1574
Yaron Kerene46f7ed2015-07-29 14:21:47 +00001575 SmallString<256> Name;
1576 llvm::raw_svector_ostream Out(Name);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001577 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001578
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001579 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001580 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
1581 CGM.Int8PtrTy, VTContext.getVTableLayout(RD).getNumVTableComponents());
1582
1583 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
1584 Name, ArrayType, llvm::GlobalValue::ExternalLinkage);
1585 VTable->setUnnamedAddr(true);
Hans Wennborgda24e9c2014-06-02 23:13:03 +00001586
1587 if (RD->hasAttr<DLLImportAttr>())
1588 VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1589 else if (RD->hasAttr<DLLExportAttr>())
1590 VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1591
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001592 return VTable;
1593}
1594
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001595llvm::Value *ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1596 GlobalDecl GD,
John McCall7f416cc2015-09-08 08:05:57 +00001597 Address This,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001598 llvm::Type *Ty,
1599 SourceLocation Loc) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001600 GD = GD.getCanonicalDecl();
1601 Ty = Ty->getPointerTo()->getPointerTo();
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001602 auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
1603 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty, MethodDecl->getParent());
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001604
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00001605 if (CGF.SanOpts.has(SanitizerKind::CFIVCall))
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001606 CGF.EmitVTablePtrCheckForCall(MethodDecl, VTable,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001607 CodeGenFunction::CFITCK_VCall, Loc);
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001608
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001609 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001610 llvm::Value *VFuncPtr =
1611 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
Renato Golin41106182015-10-01 12:58:41 +00001612 return CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign());
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001613}
1614
David Majnemer0c0b6d92014-10-31 20:09:12 +00001615llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
1616 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
John McCall7f416cc2015-09-08 08:05:57 +00001617 Address This, const CXXMemberCallExpr *CE) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001618 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001619 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1620
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001621 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1622 Dtor, getFromDtorType(DtorType));
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001623 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001624 llvm::Value *Callee =
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001625 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty,
1626 CE ? CE->getLocStart() : SourceLocation());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001627
John McCall7f416cc2015-09-08 08:05:57 +00001628 CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(),
1629 This.getPointer(), /*ImplicitParam=*/nullptr,
1630 QualType(), CE);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001631 return nullptr;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001632}
1633
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001634void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001635 CodeGenVTables &VTables = CGM.getVTables();
1636 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001637 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001638}
1639
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001640bool ItaniumCXXABI::canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const {
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001641 // We don't emit available_externally vtables if we are in -fapple-kext mode
1642 // because kext mode does not permit devirtualization.
1643 if (CGM.getLangOpts().AppleKext)
1644 return false;
1645
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001646 // If we don't have any inline virtual functions, and if vtable is not hidden,
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001647 // then we are safe to emit available_externally copy of vtable.
1648 // FIXME we can still emit a copy of the vtable if we
1649 // can emit definition of the inline functions.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001650 return !hasAnyUsedVirtualInlineFunction(RD) && !isVTableHidden(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001651}
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001652static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001653 Address InitialPtr,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001654 int64_t NonVirtualAdjustment,
1655 int64_t VirtualAdjustment,
1656 bool IsReturnAdjustment) {
1657 if (!NonVirtualAdjustment && !VirtualAdjustment)
John McCall7f416cc2015-09-08 08:05:57 +00001658 return InitialPtr.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001659
John McCall7f416cc2015-09-08 08:05:57 +00001660 Address V = CGF.Builder.CreateElementBitCast(InitialPtr, CGF.Int8Ty);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001661
John McCall7f416cc2015-09-08 08:05:57 +00001662 // In a base-to-derived cast, the non-virtual adjustment is applied first.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001663 if (NonVirtualAdjustment && !IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001664 V = CGF.Builder.CreateConstInBoundsByteGEP(V,
1665 CharUnits::fromQuantity(NonVirtualAdjustment));
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001666 }
1667
John McCall7f416cc2015-09-08 08:05:57 +00001668 // Perform the virtual adjustment if we have one.
1669 llvm::Value *ResultPtr;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001670 if (VirtualAdjustment) {
1671 llvm::Type *PtrDiffTy =
1672 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1673
John McCall7f416cc2015-09-08 08:05:57 +00001674 Address VTablePtrPtr = CGF.Builder.CreateElementBitCast(V, CGF.Int8PtrTy);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001675 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1676
1677 llvm::Value *OffsetPtr =
1678 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1679
1680 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1681
1682 // Load the adjustment offset from the vtable.
John McCall7f416cc2015-09-08 08:05:57 +00001683 llvm::Value *Offset =
1684 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001685
1686 // Adjust our pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001687 ResultPtr = CGF.Builder.CreateInBoundsGEP(V.getPointer(), Offset);
1688 } else {
1689 ResultPtr = V.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001690 }
1691
John McCall7f416cc2015-09-08 08:05:57 +00001692 // In a derived-to-base conversion, the non-virtual adjustment is
1693 // applied second.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001694 if (NonVirtualAdjustment && IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001695 ResultPtr = CGF.Builder.CreateConstInBoundsGEP1_64(ResultPtr,
1696 NonVirtualAdjustment);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001697 }
1698
1699 // Cast back to the original type.
John McCall7f416cc2015-09-08 08:05:57 +00001700 return CGF.Builder.CreateBitCast(ResultPtr, InitialPtr.getType());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001701}
1702
1703llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001704 Address This,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001705 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001706 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1707 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001708 /*IsReturnAdjustment=*/false);
1709}
1710
1711llvm::Value *
John McCall7f416cc2015-09-08 08:05:57 +00001712ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001713 const ReturnAdjustment &RA) {
1714 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1715 RA.Virtual.Itanium.VBaseOffsetOffset,
1716 /*IsReturnAdjustment=*/true);
1717}
1718
John McCall5d865c322010-08-31 07:33:07 +00001719void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1720 RValue RV, QualType ResultType) {
1721 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1722 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1723
1724 // Destructor thunks in the ARM ABI have indeterminate results.
John McCall7f416cc2015-09-08 08:05:57 +00001725 llvm::Type *T = CGF.ReturnValue.getElementType();
John McCall5d865c322010-08-31 07:33:07 +00001726 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1727 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1728}
John McCall8ed55a52010-09-02 09:58:18 +00001729
1730/************************** Array allocation cookies **************************/
1731
John McCallb91cd662012-05-01 05:23:51 +00001732CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1733 // The array cookie is a size_t; pad that up to the element alignment.
1734 // The cookie is actually right-justified in that space.
1735 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1736 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001737}
1738
John McCall7f416cc2015-09-08 08:05:57 +00001739Address ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1740 Address NewPtr,
1741 llvm::Value *NumElements,
1742 const CXXNewExpr *expr,
1743 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001744 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001745
John McCall7f416cc2015-09-08 08:05:57 +00001746 unsigned AS = NewPtr.getAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001747
John McCall9bca9232010-09-02 10:25:57 +00001748 ASTContext &Ctx = getContext();
John McCall7f416cc2015-09-08 08:05:57 +00001749 CharUnits SizeSize = CGF.getSizeSize();
John McCall8ed55a52010-09-02 09:58:18 +00001750
1751 // The size of the cookie.
1752 CharUnits CookieSize =
1753 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001754 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001755
1756 // Compute an offset to the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001757 Address CookiePtr = NewPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001758 CharUnits CookieOffset = CookieSize - SizeSize;
1759 if (!CookieOffset.isZero())
John McCall7f416cc2015-09-08 08:05:57 +00001760 CookiePtr = CGF.Builder.CreateConstInBoundsByteGEP(CookiePtr, CookieOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001761
1762 // Write the number of elements into the appropriate slot.
John McCall7f416cc2015-09-08 08:05:57 +00001763 Address NumElementsPtr =
1764 CGF.Builder.CreateElementBitCast(CookiePtr, CGF.SizeTy);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001765 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
John McCall7f416cc2015-09-08 08:05:57 +00001766
1767 // Handle the array cookie specially in ASan.
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001768 if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 &&
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001769 expr->getOperatorNew()->isReplaceableGlobalAllocationFunction()) {
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001770 // The store to the CookiePtr does not need to be instrumented.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001771 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
1772 llvm::FunctionType *FTy =
John McCall7f416cc2015-09-08 08:05:57 +00001773 llvm::FunctionType::get(CGM.VoidTy, NumElementsPtr.getType(), false);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001774 llvm::Constant *F =
1775 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001776 CGF.Builder.CreateCall(F, NumElementsPtr.getPointer());
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001777 }
John McCall8ed55a52010-09-02 09:58:18 +00001778
1779 // Finally, compute a pointer to the actual data buffer by skipping
1780 // over the cookie completely.
John McCall7f416cc2015-09-08 08:05:57 +00001781 return CGF.Builder.CreateConstInBoundsByteGEP(NewPtr, CookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001782}
1783
John McCallb91cd662012-05-01 05:23:51 +00001784llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001785 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00001786 CharUnits cookieSize) {
1787 // The element size is right-justified in the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001788 Address numElementsPtr = allocPtr;
1789 CharUnits numElementsOffset = cookieSize - CGF.getSizeSize();
John McCallb91cd662012-05-01 05:23:51 +00001790 if (!numElementsOffset.isZero())
1791 numElementsPtr =
John McCall7f416cc2015-09-08 08:05:57 +00001792 CGF.Builder.CreateConstInBoundsByteGEP(numElementsPtr, numElementsOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001793
John McCall7f416cc2015-09-08 08:05:57 +00001794 unsigned AS = allocPtr.getAddressSpace();
1795 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001796 if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0)
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001797 return CGF.Builder.CreateLoad(numElementsPtr);
1798 // In asan mode emit a function call instead of a regular load and let the
1799 // run-time deal with it: if the shadow is properly poisoned return the
1800 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
1801 // We can't simply ignore this load using nosanitize metadata because
1802 // the metadata may be lost.
1803 llvm::FunctionType *FTy =
1804 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
1805 llvm::Constant *F =
1806 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001807 return CGF.Builder.CreateCall(F, numElementsPtr.getPointer());
John McCall8ed55a52010-09-02 09:58:18 +00001808}
1809
John McCallb91cd662012-05-01 05:23:51 +00001810CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001811 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001812 // struct array_cookie {
1813 // std::size_t element_size; // element_size != 0
1814 // std::size_t element_count;
1815 // };
John McCallc19c7062013-01-25 23:36:19 +00001816 // But the base ABI doesn't give anything an alignment greater than
1817 // 8, so we can dismiss this as typical ABI-author blindness to
1818 // actual language complexity and round up to the element alignment.
1819 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1820 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001821}
1822
John McCall7f416cc2015-09-08 08:05:57 +00001823Address ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1824 Address newPtr,
1825 llvm::Value *numElements,
1826 const CXXNewExpr *expr,
1827 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001828 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001829
John McCall8ed55a52010-09-02 09:58:18 +00001830 // The cookie is always at the start of the buffer.
John McCall7f416cc2015-09-08 08:05:57 +00001831 Address cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001832
1833 // The first element is the element size.
John McCall7f416cc2015-09-08 08:05:57 +00001834 cookie = CGF.Builder.CreateElementBitCast(cookie, CGF.SizeTy);
John McCallc19c7062013-01-25 23:36:19 +00001835 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1836 getContext().getTypeSizeInChars(elementType).getQuantity());
1837 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001838
1839 // The second element is the element count.
John McCall7f416cc2015-09-08 08:05:57 +00001840 cookie = CGF.Builder.CreateConstInBoundsGEP(cookie, 1, CGF.getSizeSize());
John McCallc19c7062013-01-25 23:36:19 +00001841 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001842
1843 // Finally, compute a pointer to the actual data buffer by skipping
1844 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001845 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
John McCall7f416cc2015-09-08 08:05:57 +00001846 return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001847}
1848
John McCallb91cd662012-05-01 05:23:51 +00001849llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001850 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00001851 CharUnits cookieSize) {
1852 // The number of elements is at offset sizeof(size_t) relative to
1853 // the allocated pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001854 Address numElementsPtr
1855 = CGF.Builder.CreateConstInBoundsByteGEP(allocPtr, CGF.getSizeSize());
John McCall8ed55a52010-09-02 09:58:18 +00001856
John McCall7f416cc2015-09-08 08:05:57 +00001857 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
John McCallb91cd662012-05-01 05:23:51 +00001858 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001859}
1860
John McCall68ff0372010-09-08 01:44:27 +00001861/*********************** Static local initialization **************************/
1862
1863static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001864 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001865 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001866 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001867 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001868 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001869 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001870 llvm::AttributeSet::get(CGM.getLLVMContext(),
1871 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001872 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001873}
1874
1875static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001876 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001877 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001878 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001879 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001880 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001881 llvm::AttributeSet::get(CGM.getLLVMContext(),
1882 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001883 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001884}
1885
1886static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001887 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001888 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001889 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001890 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001891 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001892 llvm::AttributeSet::get(CGM.getLLVMContext(),
1893 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001894 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001895}
1896
1897namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001898 struct CallGuardAbort final : EHScopeStack::Cleanup {
John McCall68ff0372010-09-08 01:44:27 +00001899 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001900 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001901
Craig Topper4f12f102014-03-12 06:41:41 +00001902 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00001903 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1904 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001905 }
1906 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001907}
John McCall68ff0372010-09-08 01:44:27 +00001908
1909/// The ARM code here follows the Itanium code closely enough that we
1910/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001911void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1912 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001913 llvm::GlobalVariable *var,
1914 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00001915 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00001916
Richard Smithdbf74ba2013-04-14 23:01:42 +00001917 // We only need to use thread-safe statics for local non-TLS variables;
John McCallcdf7ef52010-11-06 09:44:32 +00001918 // global initialization is always single-threaded.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001919 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
1920 D.isLocalVarDecl() && !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001921
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001922 // If we have a global variable with internal linkage and thread-safe statics
1923 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00001924 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1925
1926 llvm::IntegerType *guardTy;
John McCall7f416cc2015-09-08 08:05:57 +00001927 CharUnits guardAlignment;
John McCall5aa52592011-06-17 07:33:57 +00001928 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00001929 guardTy = CGF.Int8Ty;
John McCall7f416cc2015-09-08 08:05:57 +00001930 guardAlignment = CharUnits::One();
John McCall5aa52592011-06-17 07:33:57 +00001931 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00001932 // Guard variables are 64 bits in the generic ABI and size width on ARM
1933 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
John McCall7f416cc2015-09-08 08:05:57 +00001934 if (UseARMGuardVarABI) {
1935 guardTy = CGF.SizeTy;
1936 guardAlignment = CGF.getSizeAlign();
1937 } else {
1938 guardTy = CGF.Int64Ty;
1939 guardAlignment = CharUnits::fromQuantity(
1940 CGM.getDataLayout().getABITypeAlignment(guardTy));
1941 }
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001942 }
John McCallb88a5662012-03-30 21:00:39 +00001943 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00001944
John McCallb88a5662012-03-30 21:00:39 +00001945 // Create the guard variable if we don't already have it (as we
1946 // might if we're double-emitting this function body).
1947 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1948 if (!guard) {
1949 // Mangle the name for the guard.
1950 SmallString<256> guardName;
1951 {
1952 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00001953 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00001954 }
John McCall8e7cb6d2010-11-02 21:04:24 +00001955
John McCallb88a5662012-03-30 21:00:39 +00001956 // Create the guard variable with a zero-initializer.
1957 // Just absorb linkage and visibility from the guarded variable.
1958 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1959 false, var->getLinkage(),
1960 llvm::ConstantInt::get(guardTy, 0),
1961 guardName.str());
1962 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00001963 // If the variable is thread-local, so is its guard variable.
1964 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCall7f416cc2015-09-08 08:05:57 +00001965 guard->setAlignment(guardAlignment.getQuantity());
John McCallb88a5662012-03-30 21:00:39 +00001966
Yaron Keren5bfa1082015-09-03 20:33:29 +00001967 // The ABI says: "It is suggested that it be emitted in the same COMDAT
1968 // group as the associated data object." In practice, this doesn't work for
1969 // non-ELF object formats, so only do it for ELF.
Rafael Espindola0d4fb982015-01-12 22:13:53 +00001970 llvm::Comdat *C = var->getComdat();
Yaron Keren5bfa1082015-09-03 20:33:29 +00001971 if (!D.isLocalVarDecl() && C &&
1972 CGM.getTarget().getTriple().isOSBinFormatELF()) {
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001973 guard->setComdat(C);
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001974 CGF.CurFn->setComdat(C);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001975 } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) {
1976 guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName()));
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001977 }
1978
John McCallb88a5662012-03-30 21:00:39 +00001979 CGM.setStaticLocalDeclGuardAddress(&D, guard);
1980 }
John McCall87590e62012-03-30 07:09:50 +00001981
John McCall7f416cc2015-09-08 08:05:57 +00001982 Address guardAddr = Address(guard, guardAlignment);
1983
John McCall68ff0372010-09-08 01:44:27 +00001984 // Test whether the variable has completed initialization.
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001985 //
John McCall68ff0372010-09-08 01:44:27 +00001986 // Itanium C++ ABI 3.3.2:
1987 // The following is pseudo-code showing how these functions can be used:
1988 // if (obj_guard.first_byte == 0) {
1989 // if ( __cxa_guard_acquire (&obj_guard) ) {
1990 // try {
1991 // ... initialize the object ...;
1992 // } catch (...) {
1993 // __cxa_guard_abort (&obj_guard);
1994 // throw;
1995 // }
1996 // ... queue object destructor with __cxa_atexit() ...;
1997 // __cxa_guard_release (&obj_guard);
1998 // }
1999 // }
Tim Northovera2ee4332014-03-29 15:09:45 +00002000
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002001 // Load the first byte of the guard variable.
2002 llvm::LoadInst *LI =
John McCall7f416cc2015-09-08 08:05:57 +00002003 Builder.CreateLoad(Builder.CreateElementBitCast(guardAddr, CGM.Int8Ty));
John McCall68ff0372010-09-08 01:44:27 +00002004
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002005 // Itanium ABI:
2006 // An implementation supporting thread-safety on multiprocessor
2007 // systems must also guarantee that references to the initialized
2008 // object do not occur before the load of the initialization flag.
2009 //
2010 // In LLVM, we do this by marking the load Acquire.
2011 if (threadsafe)
2012 LI->setAtomic(llvm::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00002013
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002014 // For ARM, we should only check the first bit, rather than the entire byte:
2015 //
2016 // ARM C++ ABI 3.2.3.1:
2017 // To support the potential use of initialization guard variables
2018 // as semaphores that are the target of ARM SWP and LDREX/STREX
2019 // synchronizing instructions we define a static initialization
2020 // guard variable to be a 4-byte aligned, 4-byte word with the
2021 // following inline access protocol.
2022 // #define INITIALIZED 1
2023 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
2024 // if (__cxa_guard_acquire(&obj_guard))
2025 // ...
2026 // }
2027 //
2028 // and similarly for ARM64:
2029 //
2030 // ARM64 C++ ABI 3.2.2:
2031 // This ABI instead only specifies the value bit 0 of the static guard
2032 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
2033 // variable is not initialized and 1 when it is.
2034 llvm::Value *V =
2035 (UseARMGuardVarABI && !useInt8GuardVariable)
2036 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
2037 : LI;
2038 llvm::Value *isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00002039
2040 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
2041 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2042
2043 // Check if the first byte of the guard variable is zero.
John McCallb88a5662012-03-30 21:00:39 +00002044 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall68ff0372010-09-08 01:44:27 +00002045
2046 CGF.EmitBlock(InitCheckBlock);
2047
2048 // Variables used when coping with thread-safe statics and exceptions.
John McCall5aa52592011-06-17 07:33:57 +00002049 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002050 // Call __cxa_guard_acquire.
2051 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00002052 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00002053
2054 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2055
2056 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
2057 InitBlock, EndBlock);
2058
2059 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00002060 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall68ff0372010-09-08 01:44:27 +00002061
2062 CGF.EmitBlock(InitBlock);
2063 }
2064
2065 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00002066 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00002067
John McCall5aa52592011-06-17 07:33:57 +00002068 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002069 // Pop the guard-abort cleanup if we pushed one.
2070 CGF.PopCleanupBlock();
2071
2072 // Call __cxa_guard_release. This cannot throw.
John McCall7f416cc2015-09-08 08:05:57 +00002073 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy),
2074 guardAddr.getPointer());
John McCall68ff0372010-09-08 01:44:27 +00002075 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002076 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guardAddr);
John McCall68ff0372010-09-08 01:44:27 +00002077 }
2078
2079 CGF.EmitBlock(EndBlock);
2080}
John McCallc84ed6a2012-05-01 06:13:13 +00002081
2082/// Register a global destructor using __cxa_atexit.
2083static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
2084 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00002085 llvm::Constant *addr,
2086 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00002087 const char *Name = "__cxa_atexit";
2088 if (TLS) {
2089 const llvm::Triple &T = CGF.getTarget().getTriple();
Manman Renf93fff22015-11-11 23:08:18 +00002090 Name = T.isOSDarwin() ? "_tlv_atexit" : "__cxa_thread_atexit";
Bill Wendling95cae882013-05-02 19:18:03 +00002091 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00002092
John McCallc84ed6a2012-05-01 06:13:13 +00002093 // We're assuming that the destructor function is something we can
2094 // reasonably call with the default CC. Go ahead and cast it to the
2095 // right prototype.
2096 llvm::Type *dtorTy =
2097 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
2098
2099 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
2100 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
2101 llvm::FunctionType *atexitTy =
2102 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
2103
2104 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002105 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00002106 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
2107 fn->setDoesNotThrow();
2108
2109 // Create a variable that binds the atexit to this shared object.
2110 llvm::Constant *handle =
2111 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
2112
2113 llvm::Value *args[] = {
2114 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
2115 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
2116 handle
2117 };
John McCall882987f2013-02-28 19:01:20 +00002118 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00002119}
2120
2121/// Register a global destructor as best as we know how.
2122void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00002123 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00002124 llvm::Constant *dtor,
2125 llvm::Constant *addr) {
2126 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002127 if (CGM.getCodeGenOpts().CXAAtExit)
2128 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
2129
2130 if (D.getTLSKind())
2131 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00002132
2133 // In Apple kexts, we want to add a global destructor entry.
2134 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00002135 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00002136 // Generate a global destructor entry.
2137 return CGM.AddCXXDtorEntry(dtor, addr);
2138 }
2139
David Blaikieebe87e12013-08-27 23:57:18 +00002140 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00002141}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002142
David Majnemer9b21c332014-07-11 20:28:10 +00002143static bool isThreadWrapperReplaceable(const VarDecl *VD,
2144 CodeGen::CodeGenModule &CGM) {
2145 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
Manman Renf93fff22015-11-11 23:08:18 +00002146 // Darwin prefers to have references to thread local variables to go through
David Majnemer9b21c332014-07-11 20:28:10 +00002147 // the thread wrapper instead of directly referencing the backing variable.
2148 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
Manman Renf93fff22015-11-11 23:08:18 +00002149 CGM.getTarget().getTriple().isOSDarwin();
David Majnemer9b21c332014-07-11 20:28:10 +00002150}
2151
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002152/// Get the appropriate linkage for the wrapper function. This is essentially
David Majnemer4632e1e2014-06-27 16:56:27 +00002153/// the weak form of the variable's linkage; every translation unit which needs
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002154/// the wrapper emits a copy, and we want the linker to merge them.
David Majnemer35ab3282014-06-11 04:08:55 +00002155static llvm::GlobalValue::LinkageTypes
2156getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
2157 llvm::GlobalValue::LinkageTypes VarLinkage =
2158 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
2159
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002160 // For internal linkage variables, we don't need an external or weak wrapper.
2161 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
2162 return VarLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00002163
David Majnemer9b21c332014-07-11 20:28:10 +00002164 // If the thread wrapper is replaceable, give it appropriate linkage.
Manman Ren68150262015-11-11 22:42:31 +00002165 if (isThreadWrapperReplaceable(VD, CGM))
2166 if (!llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) &&
2167 !llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
2168 return VarLinkage;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002169 return llvm::GlobalValue::WeakODRLinkage;
2170}
2171
2172llvm::Function *
2173ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +00002174 llvm::Value *Val) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002175 // Mangle the name for the thread_local wrapper function.
2176 SmallString<256> WrapperName;
2177 {
2178 llvm::raw_svector_ostream Out(WrapperName);
2179 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002180 }
2181
Akira Hatanaka26907f92016-01-15 03:34:06 +00002182 // FIXME: If VD is a definition, we should regenerate the function attributes
2183 // before returning.
Alexander Musmanf94c3182014-09-26 06:28:25 +00002184 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002185 return cast<llvm::Function>(V);
2186
Akira Hatanaka26907f92016-01-15 03:34:06 +00002187 QualType RetQT = VD->getType();
2188 if (RetQT->isReferenceType())
2189 RetQT = RetQT.getNonReferenceType();
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002190
Akira Hatanaka26907f92016-01-15 03:34:06 +00002191 const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
2192 getContext().getPointerType(RetQT), FunctionArgList(),
2193 FunctionType::ExtInfo(), false);
2194
2195 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FI);
David Majnemer35ab3282014-06-11 04:08:55 +00002196 llvm::Function *Wrapper =
2197 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
2198 WrapperName.str(), &CGM.getModule());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002199
2200 CGM.SetLLVMFunctionAttributes(nullptr, FI, Wrapper);
2201
2202 if (VD->hasDefinition())
2203 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Wrapper);
2204
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002205 // Always resolve references to the wrapper at link time.
Manman Ren68150262015-11-11 22:42:31 +00002206 if (!Wrapper->hasLocalLinkage() && !(isThreadWrapperReplaceable(VD, CGM) &&
2207 !llvm::GlobalVariable::isLinkOnceLinkage(Wrapper->getLinkage()) &&
2208 !llvm::GlobalVariable::isWeakODRLinkage(Wrapper->getLinkage())))
Duncan P. N. Exon Smith4434d362014-05-07 22:36:11 +00002209 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
Manman Renb0b3af72015-12-17 00:42:36 +00002210
2211 if (isThreadWrapperReplaceable(VD, CGM)) {
2212 Wrapper->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2213 Wrapper->addFnAttr(llvm::Attribute::NoUnwind);
2214 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002215 return Wrapper;
2216}
2217
2218void ItaniumCXXABI::EmitThreadLocalInitFuncs(
Richard Smith5a99c492015-12-01 01:10:48 +00002219 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
2220 ArrayRef<llvm::Function *> CXXThreadLocalInits,
2221 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
David Majnemerb3341ea2014-10-05 05:05:40 +00002222 llvm::Function *InitFunc = nullptr;
2223 if (!CXXThreadLocalInits.empty()) {
2224 // Generate a guarded initialization function.
2225 llvm::FunctionType *FTy =
2226 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002227 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2228 InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init", FI,
Alexey Samsonov1444bb92014-10-17 00:20:19 +00002229 SourceLocation(),
David Majnemerb3341ea2014-10-05 05:05:40 +00002230 /*TLS=*/true);
2231 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
2232 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
2233 llvm::GlobalVariable::InternalLinkage,
2234 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
2235 Guard->setThreadLocal(true);
John McCall7f416cc2015-09-08 08:05:57 +00002236
2237 CharUnits GuardAlign = CharUnits::One();
2238 Guard->setAlignment(GuardAlign.getQuantity());
2239
David Majnemerb3341ea2014-10-05 05:05:40 +00002240 CodeGenFunction(CGM)
John McCall7f416cc2015-09-08 08:05:57 +00002241 .GenerateCXXGlobalInitFunc(InitFunc, CXXThreadLocalInits,
2242 Address(Guard, GuardAlign));
David Majnemerb3341ea2014-10-05 05:05:40 +00002243 }
Richard Smith5a99c492015-12-01 01:10:48 +00002244 for (const VarDecl *VD : CXXThreadLocals) {
2245 llvm::GlobalVariable *Var =
2246 cast<llvm::GlobalVariable>(CGM.GetGlobalValue(CGM.getMangledName(VD)));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002247
David Majnemer9b21c332014-07-11 20:28:10 +00002248 // Some targets require that all access to thread local variables go through
2249 // the thread wrapper. This means that we cannot attempt to create a thread
2250 // wrapper or a thread helper.
2251 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition())
2252 continue;
2253
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002254 // Mangle the name for the thread_local initialization function.
2255 SmallString<256> InitFnName;
2256 {
2257 llvm::raw_svector_ostream Out(InitFnName);
2258 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002259 }
2260
2261 // If we have a definition for the variable, emit the initialization
2262 // function as an alias to the global Init function (if any). Otherwise,
2263 // produce a declaration of the initialization function.
Craig Topper8a13c412014-05-21 05:09:00 +00002264 llvm::GlobalValue *Init = nullptr;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002265 bool InitIsInitFunc = false;
2266 if (VD->hasDefinition()) {
2267 InitIsInitFunc = true;
2268 if (InitFunc)
Rafael Espindola234405b2014-05-17 21:30:14 +00002269 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
2270 InitFunc);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002271 } else {
2272 // Emit a weak global function referring to the initialization function.
2273 // This function will not exist if the TU defining the thread_local
2274 // variable in question does not need any dynamic initialization for
2275 // its thread_local variables.
2276 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
2277 Init = llvm::Function::Create(
2278 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
2279 &CGM.getModule());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002280 const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
2281 CGM.getContext().VoidTy, FunctionArgList(), FunctionType::ExtInfo(),
2282 false);
2283 CGM.SetLLVMFunctionAttributes(nullptr, FI, cast<llvm::Function>(Init));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002284 }
2285
2286 if (Init)
2287 Init->setVisibility(Var->getVisibility());
2288
2289 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
2290 llvm::LLVMContext &Context = CGM.getModule().getContext();
2291 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
John McCall7f416cc2015-09-08 08:05:57 +00002292 CGBuilderTy Builder(CGM, Entry);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002293 if (InitIsInitFunc) {
2294 if (Init)
David Blaikie4ba525b2015-07-14 17:27:39 +00002295 Builder.CreateCall(Init);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002296 } else {
2297 // Don't know whether we have an init function. Call it if it exists.
2298 llvm::Value *Have = Builder.CreateIsNotNull(Init);
2299 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2300 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2301 Builder.CreateCondBr(Have, InitBB, ExitBB);
2302
2303 Builder.SetInsertPoint(InitBB);
David Blaikie4ba525b2015-07-14 17:27:39 +00002304 Builder.CreateCall(Init);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002305 Builder.CreateBr(ExitBB);
2306
2307 Builder.SetInsertPoint(ExitBB);
2308 }
2309
2310 // For a reference, the result of the wrapper function is a pointer to
2311 // the referenced object.
2312 llvm::Value *Val = Var;
2313 if (VD->getType()->isReferenceType()) {
John McCall7f416cc2015-09-08 08:05:57 +00002314 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2315 Val = Builder.CreateAlignedLoad(Val, Align);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002316 }
Alexander Musmanf94c3182014-09-26 06:28:25 +00002317 if (Val->getType() != Wrapper->getReturnType())
2318 Val = Builder.CreatePointerBitCastOrAddrSpaceCast(
2319 Val, Wrapper->getReturnType(), "");
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002320 Builder.CreateRet(Val);
2321 }
2322}
2323
Richard Smith0f383742014-03-26 22:48:22 +00002324LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2325 const VarDecl *VD,
2326 QualType LValType) {
Richard Smith5a99c492015-12-01 01:10:48 +00002327 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD);
Alexander Musmanf94c3182014-09-26 06:28:25 +00002328 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002329
Manman Renb0b3af72015-12-17 00:42:36 +00002330 llvm::CallInst *CallVal = CGF.Builder.CreateCall(Wrapper);
2331 if (isThreadWrapperReplaceable(VD, CGF.CGM))
2332 CallVal->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002333
2334 LValue LV;
2335 if (VD->getType()->isReferenceType())
Manman Renb0b3af72015-12-17 00:42:36 +00002336 LV = CGF.MakeNaturalAlignAddrLValue(CallVal, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002337 else
Manman Renb0b3af72015-12-17 00:42:36 +00002338 LV = CGF.MakeAddrLValue(CallVal, LValType,
2339 CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002340 // FIXME: need setObjCGCLValueClass?
2341 return LV;
2342}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002343
2344/// Return whether the given global decl needs a VTT parameter, which it does
2345/// if it's a base constructor or destructor with virtual bases.
2346bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
2347 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
2348
2349 // We don't have any virtual bases, just return early.
2350 if (!MD->getParent()->getNumVBases())
2351 return false;
2352
2353 // Check if we have a base constructor.
2354 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
2355 return true;
2356
2357 // Check if we have a base destructor.
2358 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2359 return true;
2360
2361 return false;
2362}
David Majnemere2cb8d12014-07-07 06:20:47 +00002363
2364namespace {
2365class ItaniumRTTIBuilder {
2366 CodeGenModule &CGM; // Per-module state.
2367 llvm::LLVMContext &VMContext;
2368 const ItaniumCXXABI &CXXABI; // Per-module state.
2369
2370 /// Fields - The fields of the RTTI descriptor currently being built.
2371 SmallVector<llvm::Constant *, 16> Fields;
2372
2373 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2374 llvm::GlobalVariable *
2375 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2376
2377 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2378 /// descriptor of the given type.
2379 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2380
2381 /// BuildVTablePointer - Build the vtable pointer for the given type.
2382 void BuildVTablePointer(const Type *Ty);
2383
2384 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2385 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2386 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2387
2388 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2389 /// classes with bases that do not satisfy the abi::__si_class_type_info
2390 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2391 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2392
2393 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2394 /// for pointer types.
2395 void BuildPointerTypeInfo(QualType PointeeTy);
2396
2397 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2398 /// type_info for an object type.
2399 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2400
2401 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2402 /// struct, used for member pointer types.
2403 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2404
2405public:
2406 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2407 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2408
2409 // Pointer type info flags.
2410 enum {
2411 /// PTI_Const - Type has const qualifier.
2412 PTI_Const = 0x1,
2413
2414 /// PTI_Volatile - Type has volatile qualifier.
2415 PTI_Volatile = 0x2,
2416
2417 /// PTI_Restrict - Type has restrict qualifier.
2418 PTI_Restrict = 0x4,
2419
2420 /// PTI_Incomplete - Type is incomplete.
2421 PTI_Incomplete = 0x8,
2422
2423 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2424 /// (in pointer to member).
2425 PTI_ContainingClassIncomplete = 0x10
2426 };
2427
2428 // VMI type info flags.
2429 enum {
2430 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2431 VMI_NonDiamondRepeat = 0x1,
2432
2433 /// VMI_DiamondShaped - Class is diamond shaped.
2434 VMI_DiamondShaped = 0x2
2435 };
2436
2437 // Base class type info flags.
2438 enum {
2439 /// BCTI_Virtual - Base class is virtual.
2440 BCTI_Virtual = 0x1,
2441
2442 /// BCTI_Public - Base class is public.
2443 BCTI_Public = 0x2
2444 };
2445
2446 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
2447 ///
2448 /// \param Force - true to force the creation of this RTTI value
2449 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false);
2450};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002451}
David Majnemere2cb8d12014-07-07 06:20:47 +00002452
2453llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2454 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002455 SmallString<256> Name;
2456 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002457 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002458
2459 // We know that the mangled name of the type starts at index 4 of the
2460 // mangled name of the typename, so we can just index into it in order to
2461 // get the mangled name of the type.
2462 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2463 Name.substr(4));
2464
2465 llvm::GlobalVariable *GV =
2466 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
2467
2468 GV->setInitializer(Init);
2469
2470 return GV;
2471}
2472
2473llvm::Constant *
2474ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2475 // Mangle the RTTI name.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002476 SmallString<256> Name;
2477 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002478 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002479
2480 // Look for an existing global.
2481 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2482
2483 if (!GV) {
2484 // Create a new global variable.
2485 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2486 /*Constant=*/true,
2487 llvm::GlobalValue::ExternalLinkage, nullptr,
2488 Name);
David Majnemer1fb1a042014-11-07 07:26:38 +00002489 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2490 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2491 if (RD->hasAttr<DLLImportAttr>())
2492 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2493 }
David Majnemere2cb8d12014-07-07 06:20:47 +00002494 }
2495
2496 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2497}
2498
2499/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2500/// info for that type is defined in the standard library.
2501static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2502 // Itanium C++ ABI 2.9.2:
2503 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
2504 // the run-time support library. Specifically, the run-time support
2505 // library should contain type_info objects for the types X, X* and
2506 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2507 // unsigned char, signed char, short, unsigned short, int, unsigned int,
2508 // long, unsigned long, long long, unsigned long long, float, double,
2509 // long double, char16_t, char32_t, and the IEEE 754r decimal and
2510 // half-precision floating point types.
Richard Smith4a382012016-02-03 01:32:42 +00002511 //
2512 // GCC also emits RTTI for __int128.
2513 // FIXME: We do not emit RTTI information for decimal types here.
2514
2515 // Types added here must also be added to EmitFundamentalRTTIDescriptors.
David Majnemere2cb8d12014-07-07 06:20:47 +00002516 switch (Ty->getKind()) {
2517 case BuiltinType::Void:
2518 case BuiltinType::NullPtr:
2519 case BuiltinType::Bool:
2520 case BuiltinType::WChar_S:
2521 case BuiltinType::WChar_U:
2522 case BuiltinType::Char_U:
2523 case BuiltinType::Char_S:
2524 case BuiltinType::UChar:
2525 case BuiltinType::SChar:
2526 case BuiltinType::Short:
2527 case BuiltinType::UShort:
2528 case BuiltinType::Int:
2529 case BuiltinType::UInt:
2530 case BuiltinType::Long:
2531 case BuiltinType::ULong:
2532 case BuiltinType::LongLong:
2533 case BuiltinType::ULongLong:
2534 case BuiltinType::Half:
2535 case BuiltinType::Float:
2536 case BuiltinType::Double:
2537 case BuiltinType::LongDouble:
2538 case BuiltinType::Char16:
2539 case BuiltinType::Char32:
2540 case BuiltinType::Int128:
2541 case BuiltinType::UInt128:
Richard Smith4a382012016-02-03 01:32:42 +00002542 return true;
2543
David Majnemere2cb8d12014-07-07 06:20:47 +00002544 case BuiltinType::OCLImage1d:
2545 case BuiltinType::OCLImage1dArray:
2546 case BuiltinType::OCLImage1dBuffer:
2547 case BuiltinType::OCLImage2d:
2548 case BuiltinType::OCLImage2dArray:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002549 case BuiltinType::OCLImage2dDepth:
2550 case BuiltinType::OCLImage2dArrayDepth:
2551 case BuiltinType::OCLImage2dMSAA:
2552 case BuiltinType::OCLImage2dArrayMSAA:
2553 case BuiltinType::OCLImage2dMSAADepth:
2554 case BuiltinType::OCLImage2dArrayMSAADepth:
David Majnemere2cb8d12014-07-07 06:20:47 +00002555 case BuiltinType::OCLImage3d:
2556 case BuiltinType::OCLSampler:
2557 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002558 case BuiltinType::OCLClkEvent:
2559 case BuiltinType::OCLQueue:
2560 case BuiltinType::OCLNDRange:
2561 case BuiltinType::OCLReserveID:
Richard Smith4a382012016-02-03 01:32:42 +00002562 return false;
David Majnemere2cb8d12014-07-07 06:20:47 +00002563
2564 case BuiltinType::Dependent:
2565#define BUILTIN_TYPE(Id, SingletonId)
2566#define PLACEHOLDER_TYPE(Id, SingletonId) \
2567 case BuiltinType::Id:
2568#include "clang/AST/BuiltinTypes.def"
2569 llvm_unreachable("asking for RRTI for a placeholder type!");
2570
2571 case BuiltinType::ObjCId:
2572 case BuiltinType::ObjCClass:
2573 case BuiltinType::ObjCSel:
2574 llvm_unreachable("FIXME: Objective-C types are unsupported!");
2575 }
2576
2577 llvm_unreachable("Invalid BuiltinType Kind!");
2578}
2579
2580static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2581 QualType PointeeTy = PointerTy->getPointeeType();
2582 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2583 if (!BuiltinTy)
2584 return false;
2585
2586 // Check the qualifiers.
2587 Qualifiers Quals = PointeeTy.getQualifiers();
2588 Quals.removeConst();
2589
2590 if (!Quals.empty())
2591 return false;
2592
2593 return TypeInfoIsInStandardLibrary(BuiltinTy);
2594}
2595
2596/// IsStandardLibraryRTTIDescriptor - Returns whether the type
2597/// information for the given type exists in the standard library.
2598static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2599 // Type info for builtin types is defined in the standard library.
2600 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2601 return TypeInfoIsInStandardLibrary(BuiltinTy);
2602
2603 // Type info for some pointer types to builtin types is defined in the
2604 // standard library.
2605 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2606 return TypeInfoIsInStandardLibrary(PointerTy);
2607
2608 return false;
2609}
2610
2611/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
2612/// the given type exists somewhere else, and that we should not emit the type
2613/// information in this translation unit. Assumes that it is not a
2614/// standard-library type.
2615static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
2616 QualType Ty) {
2617 ASTContext &Context = CGM.getContext();
2618
2619 // If RTTI is disabled, assume it might be disabled in the
2620 // translation unit that defines any potential key function, too.
2621 if (!Context.getLangOpts().RTTI) return false;
2622
2623 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2624 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2625 if (!RD->hasDefinition())
2626 return false;
2627
2628 if (!RD->isDynamicClass())
2629 return false;
2630
2631 // FIXME: this may need to be reconsidered if the key function
2632 // changes.
David Majnemerbe9022c2015-08-06 20:56:55 +00002633 // N.B. We must always emit the RTTI data ourselves if there exists a key
2634 // function.
2635 bool IsDLLImport = RD->hasAttr<DLLImportAttr>();
David Majnemer1fb1a042014-11-07 07:26:38 +00002636 if (CGM.getVTables().isVTableExternal(RD))
David Majnemerbe9022c2015-08-06 20:56:55 +00002637 return IsDLLImport ? false : true;
David Majnemer1fb1a042014-11-07 07:26:38 +00002638
David Majnemerbe9022c2015-08-06 20:56:55 +00002639 if (IsDLLImport)
David Majnemer1fb1a042014-11-07 07:26:38 +00002640 return true;
David Majnemere2cb8d12014-07-07 06:20:47 +00002641 }
2642
2643 return false;
2644}
2645
2646/// IsIncompleteClassType - Returns whether the given record type is incomplete.
2647static bool IsIncompleteClassType(const RecordType *RecordTy) {
2648 return !RecordTy->getDecl()->isCompleteDefinition();
2649}
2650
2651/// ContainsIncompleteClassType - Returns whether the given type contains an
2652/// incomplete class type. This is true if
2653///
2654/// * The given type is an incomplete class type.
2655/// * The given type is a pointer type whose pointee type contains an
2656/// incomplete class type.
2657/// * The given type is a member pointer type whose class is an incomplete
2658/// class type.
2659/// * The given type is a member pointer type whoise pointee type contains an
2660/// incomplete class type.
2661/// is an indirect or direct pointer to an incomplete class type.
2662static bool ContainsIncompleteClassType(QualType Ty) {
2663 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2664 if (IsIncompleteClassType(RecordTy))
2665 return true;
2666 }
2667
2668 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2669 return ContainsIncompleteClassType(PointerTy->getPointeeType());
2670
2671 if (const MemberPointerType *MemberPointerTy =
2672 dyn_cast<MemberPointerType>(Ty)) {
2673 // Check if the class type is incomplete.
2674 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
2675 if (IsIncompleteClassType(ClassType))
2676 return true;
2677
2678 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
2679 }
2680
2681 return false;
2682}
2683
2684// CanUseSingleInheritance - Return whether the given record decl has a "single,
2685// public, non-virtual base at offset zero (i.e. the derived class is dynamic
2686// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
2687static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
2688 // Check the number of bases.
2689 if (RD->getNumBases() != 1)
2690 return false;
2691
2692 // Get the base.
2693 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
2694
2695 // Check that the base is not virtual.
2696 if (Base->isVirtual())
2697 return false;
2698
2699 // Check that the base is public.
2700 if (Base->getAccessSpecifier() != AS_public)
2701 return false;
2702
2703 // Check that the class is dynamic iff the base is.
2704 const CXXRecordDecl *BaseDecl =
2705 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2706 if (!BaseDecl->isEmpty() &&
2707 BaseDecl->isDynamicClass() != RD->isDynamicClass())
2708 return false;
2709
2710 return true;
2711}
2712
2713void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
2714 // abi::__class_type_info.
2715 static const char * const ClassTypeInfo =
2716 "_ZTVN10__cxxabiv117__class_type_infoE";
2717 // abi::__si_class_type_info.
2718 static const char * const SIClassTypeInfo =
2719 "_ZTVN10__cxxabiv120__si_class_type_infoE";
2720 // abi::__vmi_class_type_info.
2721 static const char * const VMIClassTypeInfo =
2722 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
2723
2724 const char *VTableName = nullptr;
2725
2726 switch (Ty->getTypeClass()) {
2727#define TYPE(Class, Base)
2728#define ABSTRACT_TYPE(Class, Base)
2729#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2730#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2731#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2732#include "clang/AST/TypeNodes.def"
2733 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2734
2735 case Type::LValueReference:
2736 case Type::RValueReference:
2737 llvm_unreachable("References shouldn't get here");
2738
2739 case Type::Auto:
2740 llvm_unreachable("Undeduced auto type shouldn't get here");
2741
Xiuli Pan9c14e282016-01-09 12:53:17 +00002742 case Type::Pipe:
2743 llvm_unreachable("Pipe types shouldn't get here");
2744
David Majnemere2cb8d12014-07-07 06:20:47 +00002745 case Type::Builtin:
2746 // GCC treats vector and complex types as fundamental types.
2747 case Type::Vector:
2748 case Type::ExtVector:
2749 case Type::Complex:
2750 case Type::Atomic:
2751 // FIXME: GCC treats block pointers as fundamental types?!
2752 case Type::BlockPointer:
2753 // abi::__fundamental_type_info.
2754 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
2755 break;
2756
2757 case Type::ConstantArray:
2758 case Type::IncompleteArray:
2759 case Type::VariableArray:
2760 // abi::__array_type_info.
2761 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
2762 break;
2763
2764 case Type::FunctionNoProto:
2765 case Type::FunctionProto:
2766 // abi::__function_type_info.
2767 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
2768 break;
2769
2770 case Type::Enum:
2771 // abi::__enum_type_info.
2772 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
2773 break;
2774
2775 case Type::Record: {
2776 const CXXRecordDecl *RD =
2777 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2778
2779 if (!RD->hasDefinition() || !RD->getNumBases()) {
2780 VTableName = ClassTypeInfo;
2781 } else if (CanUseSingleInheritance(RD)) {
2782 VTableName = SIClassTypeInfo;
2783 } else {
2784 VTableName = VMIClassTypeInfo;
2785 }
2786
2787 break;
2788 }
2789
2790 case Type::ObjCObject:
2791 // Ignore protocol qualifiers.
2792 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
2793
2794 // Handle id and Class.
2795 if (isa<BuiltinType>(Ty)) {
2796 VTableName = ClassTypeInfo;
2797 break;
2798 }
2799
2800 assert(isa<ObjCInterfaceType>(Ty));
2801 // Fall through.
2802
2803 case Type::ObjCInterface:
2804 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
2805 VTableName = SIClassTypeInfo;
2806 } else {
2807 VTableName = ClassTypeInfo;
2808 }
2809 break;
2810
2811 case Type::ObjCObjectPointer:
2812 case Type::Pointer:
2813 // abi::__pointer_type_info.
2814 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
2815 break;
2816
2817 case Type::MemberPointer:
2818 // abi::__pointer_to_member_type_info.
2819 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
2820 break;
2821 }
2822
2823 llvm::Constant *VTable =
2824 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
2825
2826 llvm::Type *PtrDiffTy =
2827 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
2828
2829 // The vtable address point is 2.
2830 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00002831 VTable =
2832 llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.Int8PtrTy, VTable, Two);
David Majnemere2cb8d12014-07-07 06:20:47 +00002833 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
2834
2835 Fields.push_back(VTable);
2836}
2837
2838/// \brief Return the linkage that the type info and type info name constants
2839/// should have for the given type.
2840static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
2841 QualType Ty) {
2842 // Itanium C++ ABI 2.9.5p7:
2843 // In addition, it and all of the intermediate abi::__pointer_type_info
2844 // structs in the chain down to the abi::__class_type_info for the
2845 // incomplete class type must be prevented from resolving to the
2846 // corresponding type_info structs for the complete class type, possibly
2847 // by making them local static objects. Finally, a dummy class RTTI is
2848 // generated for the incomplete type that will not resolve to the final
2849 // complete class RTTI (because the latter need not exist), possibly by
2850 // making it a local static object.
2851 if (ContainsIncompleteClassType(Ty))
2852 return llvm::GlobalValue::InternalLinkage;
2853
2854 switch (Ty->getLinkage()) {
2855 case NoLinkage:
2856 case InternalLinkage:
2857 case UniqueExternalLinkage:
2858 return llvm::GlobalValue::InternalLinkage;
2859
2860 case VisibleNoLinkage:
2861 case ExternalLinkage:
2862 if (!CGM.getLangOpts().RTTI) {
2863 // RTTI is not enabled, which means that this type info struct is going
2864 // to be used for exception handling. Give it linkonce_odr linkage.
2865 return llvm::GlobalValue::LinkOnceODRLinkage;
2866 }
2867
2868 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
2869 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2870 if (RD->hasAttr<WeakAttr>())
2871 return llvm::GlobalValue::WeakODRLinkage;
David Majnemerbe9022c2015-08-06 20:56:55 +00002872 if (RD->isDynamicClass()) {
2873 llvm::GlobalValue::LinkageTypes LT = CGM.getVTableLinkage(RD);
2874 // MinGW won't export the RTTI information when there is a key function.
2875 // Make sure we emit our own copy instead of attempting to dllimport it.
2876 if (RD->hasAttr<DLLImportAttr>() &&
2877 llvm::GlobalValue::isAvailableExternallyLinkage(LT))
2878 LT = llvm::GlobalValue::LinkOnceODRLinkage;
2879 return LT;
2880 }
David Majnemere2cb8d12014-07-07 06:20:47 +00002881 }
2882
2883 return llvm::GlobalValue::LinkOnceODRLinkage;
2884 }
2885
2886 llvm_unreachable("Invalid linkage!");
2887}
2888
2889llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force) {
2890 // We want to operate on the canonical type.
2891 Ty = CGM.getContext().getCanonicalType(Ty);
2892
2893 // Check if we've already emitted an RTTI descriptor for this type.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002894 SmallString<256> Name;
2895 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002896 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002897
2898 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
2899 if (OldGV && !OldGV->isDeclaration()) {
2900 assert(!OldGV->hasAvailableExternallyLinkage() &&
2901 "available_externally typeinfos not yet implemented");
2902
2903 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
2904 }
2905
2906 // Check if there is already an external RTTI descriptor for this type.
2907 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
2908 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
2909 return GetAddrOfExternalRTTIDescriptor(Ty);
2910
2911 // Emit the standard library with external linkage.
2912 llvm::GlobalVariable::LinkageTypes Linkage;
2913 if (IsStdLib)
2914 Linkage = llvm::GlobalValue::ExternalLinkage;
2915 else
2916 Linkage = getTypeInfoLinkage(CGM, Ty);
2917
2918 // Add the vtable pointer.
2919 BuildVTablePointer(cast<Type>(Ty));
2920
2921 // And the name.
2922 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
2923 llvm::Constant *TypeNameField;
2924
2925 // If we're supposed to demote the visibility, be sure to set a flag
2926 // to use a string comparison for type_info comparisons.
2927 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
2928 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
2929 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
2930 // The flag is the sign bit, which on ARM64 is defined to be clear
2931 // for global pointers. This is very ARM64-specific.
2932 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
2933 llvm::Constant *flag =
2934 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
2935 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
2936 TypeNameField =
2937 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
2938 } else {
2939 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
2940 }
2941 Fields.push_back(TypeNameField);
2942
2943 switch (Ty->getTypeClass()) {
2944#define TYPE(Class, Base)
2945#define ABSTRACT_TYPE(Class, Base)
2946#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2947#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2948#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2949#include "clang/AST/TypeNodes.def"
2950 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2951
2952 // GCC treats vector types as fundamental types.
2953 case Type::Builtin:
2954 case Type::Vector:
2955 case Type::ExtVector:
2956 case Type::Complex:
2957 case Type::BlockPointer:
2958 // Itanium C++ ABI 2.9.5p4:
2959 // abi::__fundamental_type_info adds no data members to std::type_info.
2960 break;
2961
2962 case Type::LValueReference:
2963 case Type::RValueReference:
2964 llvm_unreachable("References shouldn't get here");
2965
2966 case Type::Auto:
2967 llvm_unreachable("Undeduced auto type shouldn't get here");
2968
Xiuli Pan9c14e282016-01-09 12:53:17 +00002969 case Type::Pipe:
2970 llvm_unreachable("Pipe type shouldn't get here");
2971
David Majnemere2cb8d12014-07-07 06:20:47 +00002972 case Type::ConstantArray:
2973 case Type::IncompleteArray:
2974 case Type::VariableArray:
2975 // Itanium C++ ABI 2.9.5p5:
2976 // abi::__array_type_info adds no data members to std::type_info.
2977 break;
2978
2979 case Type::FunctionNoProto:
2980 case Type::FunctionProto:
2981 // Itanium C++ ABI 2.9.5p5:
2982 // abi::__function_type_info adds no data members to std::type_info.
2983 break;
2984
2985 case Type::Enum:
2986 // Itanium C++ ABI 2.9.5p5:
2987 // abi::__enum_type_info adds no data members to std::type_info.
2988 break;
2989
2990 case Type::Record: {
2991 const CXXRecordDecl *RD =
2992 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2993 if (!RD->hasDefinition() || !RD->getNumBases()) {
2994 // We don't need to emit any fields.
2995 break;
2996 }
2997
2998 if (CanUseSingleInheritance(RD))
2999 BuildSIClassTypeInfo(RD);
3000 else
3001 BuildVMIClassTypeInfo(RD);
3002
3003 break;
3004 }
3005
3006 case Type::ObjCObject:
3007 case Type::ObjCInterface:
3008 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
3009 break;
3010
3011 case Type::ObjCObjectPointer:
3012 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
3013 break;
3014
3015 case Type::Pointer:
3016 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
3017 break;
3018
3019 case Type::MemberPointer:
3020 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
3021 break;
3022
3023 case Type::Atomic:
3024 // No fields, at least for the moment.
3025 break;
3026 }
3027
3028 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
3029
Rafael Espindolacb92c192015-01-15 23:18:01 +00003030 llvm::Module &M = CGM.getModule();
David Majnemere2cb8d12014-07-07 06:20:47 +00003031 llvm::GlobalVariable *GV =
Rafael Espindolacb92c192015-01-15 23:18:01 +00003032 new llvm::GlobalVariable(M, Init->getType(),
3033 /*Constant=*/true, Linkage, Init, Name);
3034
David Majnemere2cb8d12014-07-07 06:20:47 +00003035 // If there's already an old global variable, replace it with the new one.
3036 if (OldGV) {
3037 GV->takeName(OldGV);
3038 llvm::Constant *NewPtr =
3039 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3040 OldGV->replaceAllUsesWith(NewPtr);
3041 OldGV->eraseFromParent();
3042 }
3043
Yaron Keren04da2382015-07-29 15:42:28 +00003044 if (CGM.supportsCOMDAT() && GV->isWeakForLinker())
3045 GV->setComdat(M.getOrInsertComdat(GV->getName()));
3046
David Majnemere2cb8d12014-07-07 06:20:47 +00003047 // The Itanium ABI specifies that type_info objects must be globally
3048 // unique, with one exception: if the type is an incomplete class
3049 // type or a (possibly indirect) pointer to one. That exception
3050 // affects the general case of comparing type_info objects produced
3051 // by the typeid operator, which is why the comparison operators on
3052 // std::type_info generally use the type_info name pointers instead
3053 // of the object addresses. However, the language's built-in uses
3054 // of RTTI generally require class types to be complete, even when
3055 // manipulating pointers to those class types. This allows the
3056 // implementation of dynamic_cast to rely on address equality tests,
3057 // which is much faster.
3058
3059 // All of this is to say that it's important that both the type_info
3060 // object and the type_info name be uniqued when weakly emitted.
3061
3062 // Give the type_info object and name the formal visibility of the
3063 // type itself.
3064 llvm::GlobalValue::VisibilityTypes llvmVisibility;
3065 if (llvm::GlobalValue::isLocalLinkage(Linkage))
3066 // If the linkage is local, only default visibility makes sense.
3067 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
3068 else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden)
3069 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
3070 else
3071 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
3072 TypeName->setVisibility(llvmVisibility);
3073 GV->setVisibility(llvmVisibility);
3074
3075 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
3076}
3077
3078/// ComputeQualifierFlags - Compute the pointer type info flags from the
3079/// given qualifier.
3080static unsigned ComputeQualifierFlags(Qualifiers Quals) {
3081 unsigned Flags = 0;
3082
3083 if (Quals.hasConst())
3084 Flags |= ItaniumRTTIBuilder::PTI_Const;
3085 if (Quals.hasVolatile())
3086 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
3087 if (Quals.hasRestrict())
3088 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
3089
3090 return Flags;
3091}
3092
3093/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
3094/// for the given Objective-C object type.
3095void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
3096 // Drop qualifiers.
3097 const Type *T = OT->getBaseType().getTypePtr();
3098 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
3099
3100 // The builtin types are abi::__class_type_infos and don't require
3101 // extra fields.
3102 if (isa<BuiltinType>(T)) return;
3103
3104 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
3105 ObjCInterfaceDecl *Super = Class->getSuperClass();
3106
3107 // Root classes are also __class_type_info.
3108 if (!Super) return;
3109
3110 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
3111
3112 // Everything else is single inheritance.
3113 llvm::Constant *BaseTypeInfo =
3114 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
3115 Fields.push_back(BaseTypeInfo);
3116}
3117
3118/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
3119/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
3120void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
3121 // Itanium C++ ABI 2.9.5p6b:
3122 // It adds to abi::__class_type_info a single member pointing to the
3123 // type_info structure for the base type,
3124 llvm::Constant *BaseTypeInfo =
3125 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
3126 Fields.push_back(BaseTypeInfo);
3127}
3128
3129namespace {
3130 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
3131 /// a class hierarchy.
3132 struct SeenBases {
3133 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
3134 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
3135 };
3136}
3137
3138/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
3139/// abi::__vmi_class_type_info.
3140///
3141static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
3142 SeenBases &Bases) {
3143
3144 unsigned Flags = 0;
3145
3146 const CXXRecordDecl *BaseDecl =
3147 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
3148
3149 if (Base->isVirtual()) {
3150 // Mark the virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003151 if (!Bases.VirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003152 // If this virtual base has been seen before, then the class is diamond
3153 // shaped.
3154 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
3155 } else {
3156 if (Bases.NonVirtualBases.count(BaseDecl))
3157 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3158 }
3159 } else {
3160 // Mark the non-virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003161 if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003162 // If this non-virtual base has been seen before, then the class has non-
3163 // diamond shaped repeated inheritance.
3164 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3165 } else {
3166 if (Bases.VirtualBases.count(BaseDecl))
3167 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3168 }
3169 }
3170
3171 // Walk all bases.
3172 for (const auto &I : BaseDecl->bases())
3173 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3174
3175 return Flags;
3176}
3177
3178static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
3179 unsigned Flags = 0;
3180 SeenBases Bases;
3181
3182 // Walk all bases.
3183 for (const auto &I : RD->bases())
3184 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3185
3186 return Flags;
3187}
3188
3189/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
3190/// classes with bases that do not satisfy the abi::__si_class_type_info
3191/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
3192void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
3193 llvm::Type *UnsignedIntLTy =
3194 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3195
3196 // Itanium C++ ABI 2.9.5p6c:
3197 // __flags is a word with flags describing details about the class
3198 // structure, which may be referenced by using the __flags_masks
3199 // enumeration. These flags refer to both direct and indirect bases.
3200 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
3201 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3202
3203 // Itanium C++ ABI 2.9.5p6c:
3204 // __base_count is a word with the number of direct proper base class
3205 // descriptions that follow.
3206 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
3207
3208 if (!RD->getNumBases())
3209 return;
3210
3211 llvm::Type *LongLTy =
3212 CGM.getTypes().ConvertType(CGM.getContext().LongTy);
3213
3214 // Now add the base class descriptions.
3215
3216 // Itanium C++ ABI 2.9.5p6c:
3217 // __base_info[] is an array of base class descriptions -- one for every
3218 // direct proper base. Each description is of the type:
3219 //
3220 // struct abi::__base_class_type_info {
3221 // public:
3222 // const __class_type_info *__base_type;
3223 // long __offset_flags;
3224 //
3225 // enum __offset_flags_masks {
3226 // __virtual_mask = 0x1,
3227 // __public_mask = 0x2,
3228 // __offset_shift = 8
3229 // };
3230 // };
3231 for (const auto &Base : RD->bases()) {
3232 // The __base_type member points to the RTTI for the base type.
3233 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
3234
3235 const CXXRecordDecl *BaseDecl =
3236 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
3237
3238 int64_t OffsetFlags = 0;
3239
3240 // All but the lower 8 bits of __offset_flags are a signed offset.
3241 // For a non-virtual base, this is the offset in the object of the base
3242 // subobject. For a virtual base, this is the offset in the virtual table of
3243 // the virtual base offset for the virtual base referenced (negative).
3244 CharUnits Offset;
3245 if (Base.isVirtual())
3246 Offset =
3247 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
3248 else {
3249 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
3250 Offset = Layout.getBaseClassOffset(BaseDecl);
3251 };
3252
3253 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
3254
3255 // The low-order byte of __offset_flags contains flags, as given by the
3256 // masks from the enumeration __offset_flags_masks.
3257 if (Base.isVirtual())
3258 OffsetFlags |= BCTI_Virtual;
3259 if (Base.getAccessSpecifier() == AS_public)
3260 OffsetFlags |= BCTI_Public;
3261
3262 Fields.push_back(llvm::ConstantInt::get(LongLTy, OffsetFlags));
3263 }
3264}
3265
3266/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
3267/// used for pointer types.
3268void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
3269 Qualifiers Quals;
3270 QualType UnqualifiedPointeeTy =
3271 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
3272
3273 // Itanium C++ ABI 2.9.5p7:
3274 // __flags is a flag word describing the cv-qualification and other
3275 // attributes of the type pointed to
3276 unsigned Flags = ComputeQualifierFlags(Quals);
3277
3278 // Itanium C++ ABI 2.9.5p7:
3279 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3280 // incomplete class type, the incomplete target type flag is set.
3281 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
3282 Flags |= PTI_Incomplete;
3283
3284 llvm::Type *UnsignedIntLTy =
3285 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3286 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3287
3288 // Itanium C++ ABI 2.9.5p7:
3289 // __pointee is a pointer to the std::type_info derivation for the
3290 // unqualified type being pointed to.
3291 llvm::Constant *PointeeTypeInfo =
3292 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
3293 Fields.push_back(PointeeTypeInfo);
3294}
3295
3296/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
3297/// struct, used for member pointer types.
3298void
3299ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
3300 QualType PointeeTy = Ty->getPointeeType();
3301
3302 Qualifiers Quals;
3303 QualType UnqualifiedPointeeTy =
3304 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
3305
3306 // Itanium C++ ABI 2.9.5p7:
3307 // __flags is a flag word describing the cv-qualification and other
3308 // attributes of the type pointed to.
3309 unsigned Flags = ComputeQualifierFlags(Quals);
3310
3311 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
3312
3313 // Itanium C++ ABI 2.9.5p7:
3314 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3315 // incomplete class type, the incomplete target type flag is set.
3316 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
3317 Flags |= PTI_Incomplete;
3318
3319 if (IsIncompleteClassType(ClassType))
3320 Flags |= PTI_ContainingClassIncomplete;
3321
3322 llvm::Type *UnsignedIntLTy =
3323 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3324 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3325
3326 // Itanium C++ ABI 2.9.5p7:
3327 // __pointee is a pointer to the std::type_info derivation for the
3328 // unqualified type being pointed to.
3329 llvm::Constant *PointeeTypeInfo =
3330 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
3331 Fields.push_back(PointeeTypeInfo);
3332
3333 // Itanium C++ ABI 2.9.5p9:
3334 // __context is a pointer to an abi::__class_type_info corresponding to the
3335 // class type containing the member pointed to
3336 // (e.g., the "A" in "int A::*").
3337 Fields.push_back(
3338 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
3339}
3340
David Majnemer443250f2015-03-17 20:35:00 +00003341llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003342 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
3343}
3344
3345void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type) {
3346 QualType PointerType = getContext().getPointerType(Type);
3347 QualType PointerTypeConst = getContext().getPointerType(Type.withConst());
3348 ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, true);
3349 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, true);
3350 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, true);
3351}
3352
3353void ItaniumCXXABI::EmitFundamentalRTTIDescriptors() {
Richard Smith4a382012016-02-03 01:32:42 +00003354 // Types added here must also be added to TypeInfoIsInStandardLibrary.
David Majnemere2cb8d12014-07-07 06:20:47 +00003355 QualType FundamentalTypes[] = {
3356 getContext().VoidTy, getContext().NullPtrTy,
3357 getContext().BoolTy, getContext().WCharTy,
3358 getContext().CharTy, getContext().UnsignedCharTy,
3359 getContext().SignedCharTy, getContext().ShortTy,
3360 getContext().UnsignedShortTy, getContext().IntTy,
3361 getContext().UnsignedIntTy, getContext().LongTy,
3362 getContext().UnsignedLongTy, getContext().LongLongTy,
Richard Smith4a382012016-02-03 01:32:42 +00003363 getContext().UnsignedLongLongTy, getContext().Int128Ty,
3364 getContext().UnsignedInt128Ty, getContext().HalfTy,
David Majnemere2cb8d12014-07-07 06:20:47 +00003365 getContext().FloatTy, getContext().DoubleTy,
3366 getContext().LongDoubleTy, getContext().Char16Ty,
3367 getContext().Char32Ty,
3368 };
3369 for (const QualType &FundamentalType : FundamentalTypes)
3370 EmitFundamentalRTTIDescriptor(FundamentalType);
3371}
3372
3373/// What sort of uniqueness rules should we use for the RTTI for the
3374/// given type?
3375ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
3376 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
3377 if (shouldRTTIBeUnique())
3378 return RUK_Unique;
3379
3380 // It's only necessary for linkonce_odr or weak_odr linkage.
3381 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
3382 Linkage != llvm::GlobalValue::WeakODRLinkage)
3383 return RUK_Unique;
3384
3385 // It's only necessary with default visibility.
3386 if (CanTy->getVisibility() != DefaultVisibility)
3387 return RUK_Unique;
3388
3389 // If we're not required to publish this symbol, hide it.
3390 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3391 return RUK_NonUniqueHidden;
3392
3393 // If we're required to publish this symbol, as we might be under an
3394 // explicit instantiation, leave it with default visibility but
3395 // enable string-comparisons.
3396 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
3397 return RUK_NonUniqueVisible;
3398}
Rafael Espindola91f68b42014-09-15 19:20:10 +00003399
Rafael Espindola1e4df922014-09-16 15:18:21 +00003400// Find out how to codegen the complete destructor and constructor
3401namespace {
3402enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
3403}
3404static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
3405 const CXXMethodDecl *MD) {
3406 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
3407 return StructorCodegen::Emit;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003408
Rafael Espindola1e4df922014-09-16 15:18:21 +00003409 // The complete and base structors are not equivalent if there are any virtual
3410 // bases, so emit separate functions.
3411 if (MD->getParent()->getNumVBases())
3412 return StructorCodegen::Emit;
3413
3414 GlobalDecl AliasDecl;
3415 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3416 AliasDecl = GlobalDecl(DD, Dtor_Complete);
3417 } else {
3418 const auto *CD = cast<CXXConstructorDecl>(MD);
3419 AliasDecl = GlobalDecl(CD, Ctor_Complete);
3420 }
3421 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3422
3423 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
3424 return StructorCodegen::RAUW;
3425
3426 // FIXME: Should we allow available_externally aliases?
3427 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
3428 return StructorCodegen::RAUW;
3429
Rafael Espindola0806f982014-09-16 20:19:43 +00003430 if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
3431 // Only ELF supports COMDATs with arbitrary names (C5/D5).
3432 if (CGM.getTarget().getTriple().isOSBinFormatELF())
3433 return StructorCodegen::COMDAT;
3434 return StructorCodegen::Emit;
3435 }
Rafael Espindola1e4df922014-09-16 15:18:21 +00003436
3437 return StructorCodegen::Alias;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003438}
3439
Rafael Espindola1e4df922014-09-16 15:18:21 +00003440static void emitConstructorDestructorAlias(CodeGenModule &CGM,
3441 GlobalDecl AliasDecl,
3442 GlobalDecl TargetDecl) {
3443 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3444
3445 StringRef MangledName = CGM.getMangledName(AliasDecl);
3446 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
3447 if (Entry && !Entry->isDeclaration())
3448 return;
3449
3450 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
Rafael Espindola1e4df922014-09-16 15:18:21 +00003451
3452 // Create the alias with no name.
David Blaikie2a791d72015-09-14 18:38:22 +00003453 auto *Alias = llvm::GlobalAlias::create(Linkage, "", Aliasee);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003454
3455 // Switch any previous uses to the alias.
3456 if (Entry) {
NAKAMURA Takumie9621042015-09-15 01:39:27 +00003457 assert(Entry->getType() == Aliasee->getType() &&
Rafael Espindola1e4df922014-09-16 15:18:21 +00003458 "declaration exists with different type");
3459 Alias->takeName(Entry);
3460 Entry->replaceAllUsesWith(Alias);
3461 Entry->eraseFromParent();
3462 } else {
3463 Alias->setName(MangledName);
3464 }
3465
3466 // Finally, set up the alias with its proper name and attributes.
Dario Domiziolic4fb8ca72014-09-19 22:06:24 +00003467 CGM.setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003468}
3469
3470void ItaniumCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
3471 StructorType Type) {
3472 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
3473 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
3474
3475 StructorCodegen CGType = getCodegenToUse(CGM, MD);
3476
3477 if (Type == StructorType::Complete) {
3478 GlobalDecl CompleteDecl;
3479 GlobalDecl BaseDecl;
3480 if (CD) {
3481 CompleteDecl = GlobalDecl(CD, Ctor_Complete);
3482 BaseDecl = GlobalDecl(CD, Ctor_Base);
3483 } else {
3484 CompleteDecl = GlobalDecl(DD, Dtor_Complete);
3485 BaseDecl = GlobalDecl(DD, Dtor_Base);
3486 }
3487
3488 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
3489 emitConstructorDestructorAlias(CGM, CompleteDecl, BaseDecl);
3490 return;
3491 }
3492
3493 if (CGType == StructorCodegen::RAUW) {
3494 StringRef MangledName = CGM.getMangledName(CompleteDecl);
Andrey Bokhankocab58582015-08-31 13:20:44 +00003495 auto *Aliasee = CGM.GetAddrOfGlobal(BaseDecl);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003496 CGM.addReplacement(MangledName, Aliasee);
3497 return;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003498 }
3499 }
3500
3501 // The base destructor is equivalent to the base destructor of its
3502 // base class if there is exactly one non-virtual base class with a
3503 // non-trivial destructor, there are no fields with a non-trivial
3504 // destructor, and the body of the destructor is trivial.
Rafael Espindola1e4df922014-09-16 15:18:21 +00003505 if (DD && Type == StructorType::Base && CGType != StructorCodegen::COMDAT &&
3506 !CGM.TryEmitBaseDestructorAsAlias(DD))
Rafael Espindola91f68b42014-09-15 19:20:10 +00003507 return;
3508
Rafael Espindola1e4df922014-09-16 15:18:21 +00003509 llvm::Function *Fn = CGM.codegenCXXStructor(MD, Type);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003510
Rafael Espindola1e4df922014-09-16 15:18:21 +00003511 if (CGType == StructorCodegen::COMDAT) {
3512 SmallString<256> Buffer;
3513 llvm::raw_svector_ostream Out(Buffer);
3514 if (DD)
3515 getMangleContext().mangleCXXDtorComdat(DD, Out);
3516 else
3517 getMangleContext().mangleCXXCtorComdat(CD, Out);
3518 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
3519 Fn->setComdat(C);
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003520 } else {
3521 CGM.maybeSetTrivialComdat(*MD, *Fn);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003522 }
Rafael Espindola91f68b42014-09-15 19:20:10 +00003523}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003524
3525static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) {
3526 // void *__cxa_begin_catch(void*);
3527 llvm::FunctionType *FTy = llvm::FunctionType::get(
3528 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3529
3530 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
3531}
3532
3533static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) {
3534 // void __cxa_end_catch();
3535 llvm::FunctionType *FTy =
3536 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
3537
3538 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
3539}
3540
3541static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) {
3542 // void *__cxa_get_exception_ptr(void*);
3543 llvm::FunctionType *FTy = llvm::FunctionType::get(
3544 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3545
3546 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
3547}
3548
3549namespace {
3550 /// A cleanup to call __cxa_end_catch. In many cases, the caught
3551 /// exception type lets us state definitively that the thrown exception
3552 /// type does not have a destructor. In particular:
3553 /// - Catch-alls tell us nothing, so we have to conservatively
3554 /// assume that the thrown exception might have a destructor.
3555 /// - Catches by reference behave according to their base types.
3556 /// - Catches of non-record types will only trigger for exceptions
3557 /// of non-record types, which never have destructors.
3558 /// - Catches of record types can trigger for arbitrary subclasses
3559 /// of the caught type, so we have to assume the actual thrown
3560 /// exception type might have a throwing destructor, even if the
3561 /// caught type's destructor is trivial or nothrow.
David Blaikie7e70d682015-08-18 22:40:54 +00003562 struct CallEndCatch final : EHScopeStack::Cleanup {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003563 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
3564 bool MightThrow;
3565
3566 void Emit(CodeGenFunction &CGF, Flags flags) override {
3567 if (!MightThrow) {
3568 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
3569 return;
3570 }
3571
3572 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
3573 }
3574 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003575}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003576
3577/// Emits a call to __cxa_begin_catch and enters a cleanup to call
3578/// __cxa_end_catch.
3579///
3580/// \param EndMightThrow - true if __cxa_end_catch might throw
3581static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
3582 llvm::Value *Exn,
3583 bool EndMightThrow) {
3584 llvm::CallInst *call =
3585 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
3586
3587 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
3588
3589 return call;
3590}
3591
3592/// A "special initializer" callback for initializing a catch
3593/// parameter during catch initialization.
3594static void InitCatchParam(CodeGenFunction &CGF,
3595 const VarDecl &CatchParam,
John McCall7f416cc2015-09-08 08:05:57 +00003596 Address ParamAddr,
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003597 SourceLocation Loc) {
3598 // Load the exception from where the landing pad saved it.
3599 llvm::Value *Exn = CGF.getExceptionFromSlot();
3600
3601 CanQualType CatchType =
3602 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
3603 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
3604
3605 // If we're catching by reference, we can just cast the object
3606 // pointer to the appropriate pointer.
3607 if (isa<ReferenceType>(CatchType)) {
3608 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
3609 bool EndCatchMightThrow = CaughtType->isRecordType();
3610
3611 // __cxa_begin_catch returns the adjusted object pointer.
3612 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
3613
3614 // We have no way to tell the personality function that we're
3615 // catching by reference, so if we're catching a pointer,
3616 // __cxa_begin_catch will actually return that pointer by value.
3617 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
3618 QualType PointeeType = PT->getPointeeType();
3619
3620 // When catching by reference, generally we should just ignore
3621 // this by-value pointer and use the exception object instead.
3622 if (!PointeeType->isRecordType()) {
3623
3624 // Exn points to the struct _Unwind_Exception header, which
3625 // we have to skip past in order to reach the exception data.
3626 unsigned HeaderSize =
3627 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
3628 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
3629
3630 // However, if we're catching a pointer-to-record type that won't
3631 // work, because the personality function might have adjusted
3632 // the pointer. There's actually no way for us to fully satisfy
3633 // the language/ABI contract here: we can't use Exn because it
3634 // might have the wrong adjustment, but we can't use the by-value
3635 // pointer because it's off by a level of abstraction.
3636 //
3637 // The current solution is to dump the adjusted pointer into an
3638 // alloca, which breaks language semantics (because changing the
3639 // pointer doesn't change the exception) but at least works.
3640 // The better solution would be to filter out non-exact matches
3641 // and rethrow them, but this is tricky because the rethrow
3642 // really needs to be catchable by other sites at this landing
3643 // pad. The best solution is to fix the personality function.
3644 } else {
3645 // Pull the pointer for the reference type off.
3646 llvm::Type *PtrTy =
3647 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
3648
3649 // Create the temporary and write the adjusted pointer into it.
John McCall7f416cc2015-09-08 08:05:57 +00003650 Address ExnPtrTmp =
3651 CGF.CreateTempAlloca(PtrTy, CGF.getPointerAlign(), "exn.byref.tmp");
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003652 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3653 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
3654
3655 // Bind the reference to the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00003656 AdjustedExn = ExnPtrTmp.getPointer();
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003657 }
3658 }
3659
3660 llvm::Value *ExnCast =
3661 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
3662 CGF.Builder.CreateStore(ExnCast, ParamAddr);
3663 return;
3664 }
3665
3666 // Scalars and complexes.
3667 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
3668 if (TEK != TEK_Aggregate) {
3669 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
3670
3671 // If the catch type is a pointer type, __cxa_begin_catch returns
3672 // the pointer by value.
3673 if (CatchType->hasPointerRepresentation()) {
3674 llvm::Value *CastExn =
3675 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
3676
3677 switch (CatchType.getQualifiers().getObjCLifetime()) {
3678 case Qualifiers::OCL_Strong:
3679 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
3680 // fallthrough
3681
3682 case Qualifiers::OCL_None:
3683 case Qualifiers::OCL_ExplicitNone:
3684 case Qualifiers::OCL_Autoreleasing:
3685 CGF.Builder.CreateStore(CastExn, ParamAddr);
3686 return;
3687
3688 case Qualifiers::OCL_Weak:
3689 CGF.EmitARCInitWeak(ParamAddr, CastExn);
3690 return;
3691 }
3692 llvm_unreachable("bad ownership qualifier!");
3693 }
3694
3695 // Otherwise, it returns a pointer into the exception object.
3696
3697 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3698 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3699
3700 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
John McCall7f416cc2015-09-08 08:05:57 +00003701 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003702 switch (TEK) {
3703 case TEK_Complex:
3704 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
3705 /*init*/ true);
3706 return;
3707 case TEK_Scalar: {
3708 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
3709 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
3710 return;
3711 }
3712 case TEK_Aggregate:
3713 llvm_unreachable("evaluation kind filtered out!");
3714 }
3715 llvm_unreachable("bad evaluation kind");
3716 }
3717
3718 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
John McCall7f416cc2015-09-08 08:05:57 +00003719 auto catchRD = CatchType->getAsCXXRecordDecl();
3720 CharUnits caughtExnAlignment = CGF.CGM.getClassPointerAlignment(catchRD);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003721
3722 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3723
3724 // Check for a copy expression. If we don't have a copy expression,
3725 // that means a trivial copy is okay.
3726 const Expr *copyExpr = CatchParam.getInit();
3727 if (!copyExpr) {
3728 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
John McCall7f416cc2015-09-08 08:05:57 +00003729 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3730 caughtExnAlignment);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003731 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
3732 return;
3733 }
3734
3735 // We have to call __cxa_get_exception_ptr to get the adjusted
3736 // pointer before copying.
3737 llvm::CallInst *rawAdjustedExn =
3738 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
3739
3740 // Cast that to the appropriate type.
John McCall7f416cc2015-09-08 08:05:57 +00003741 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3742 caughtExnAlignment);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003743
3744 // The copy expression is defined in terms of an OpaqueValueExpr.
3745 // Find it and map it to the adjusted expression.
3746 CodeGenFunction::OpaqueValueMapping
3747 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
3748 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
3749
3750 // Call the copy ctor in a terminate scope.
3751 CGF.EHStack.pushTerminate();
3752
3753 // Perform the copy construction.
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003754 CGF.EmitAggExpr(copyExpr,
John McCall7f416cc2015-09-08 08:05:57 +00003755 AggValueSlot::forAddr(ParamAddr, Qualifiers(),
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003756 AggValueSlot::IsNotDestructed,
3757 AggValueSlot::DoesNotNeedGCBarriers,
3758 AggValueSlot::IsNotAliased));
3759
3760 // Leave the terminate scope.
3761 CGF.EHStack.popTerminate();
3762
3763 // Undo the opaque value mapping.
3764 opaque.pop();
3765
3766 // Finally we can call __cxa_begin_catch.
3767 CallBeginCatch(CGF, Exn, true);
3768}
3769
3770/// Begins a catch statement by initializing the catch variable and
3771/// calling __cxa_begin_catch.
3772void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF,
3773 const CXXCatchStmt *S) {
3774 // We have to be very careful with the ordering of cleanups here:
3775 // C++ [except.throw]p4:
3776 // The destruction [of the exception temporary] occurs
3777 // immediately after the destruction of the object declared in
3778 // the exception-declaration in the handler.
3779 //
3780 // So the precise ordering is:
3781 // 1. Construct catch variable.
3782 // 2. __cxa_begin_catch
3783 // 3. Enter __cxa_end_catch cleanup
3784 // 4. Enter dtor cleanup
3785 //
3786 // We do this by using a slightly abnormal initialization process.
3787 // Delegation sequence:
3788 // - ExitCXXTryStmt opens a RunCleanupsScope
3789 // - EmitAutoVarAlloca creates the variable and debug info
3790 // - InitCatchParam initializes the variable from the exception
3791 // - CallBeginCatch calls __cxa_begin_catch
3792 // - CallBeginCatch enters the __cxa_end_catch cleanup
3793 // - EmitAutoVarCleanups enters the variable destructor cleanup
3794 // - EmitCXXTryStmt emits the code for the catch body
3795 // - EmitCXXTryStmt close the RunCleanupsScope
3796
3797 VarDecl *CatchParam = S->getExceptionDecl();
3798 if (!CatchParam) {
3799 llvm::Value *Exn = CGF.getExceptionFromSlot();
3800 CallBeginCatch(CGF, Exn, true);
3801 return;
3802 }
3803
3804 // Emit the local.
3805 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
3806 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
3807 CGF.EmitAutoVarCleanups(var);
3808}
3809
3810/// Get or define the following function:
3811/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
3812/// This code is used only in C++.
3813static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
3814 llvm::FunctionType *fnTy =
3815 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3816 llvm::Constant *fnRef =
3817 CGM.CreateRuntimeFunction(fnTy, "__clang_call_terminate");
3818
3819 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
3820 if (fn && fn->empty()) {
3821 fn->setDoesNotThrow();
3822 fn->setDoesNotReturn();
3823
3824 // What we really want is to massively penalize inlining without
3825 // forbidding it completely. The difference between that and
3826 // 'noinline' is negligible.
3827 fn->addFnAttr(llvm::Attribute::NoInline);
3828
3829 // Allow this function to be shared across translation units, but
3830 // we don't want it to turn into an exported symbol.
3831 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
3832 fn->setVisibility(llvm::Function::HiddenVisibility);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00003833 if (CGM.supportsCOMDAT())
3834 fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003835
3836 // Set up the function.
3837 llvm::BasicBlock *entry =
3838 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
John McCall7f416cc2015-09-08 08:05:57 +00003839 CGBuilderTy builder(CGM, entry);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003840
3841 // Pull the exception pointer out of the parameter list.
3842 llvm::Value *exn = &*fn->arg_begin();
3843
3844 // Call __cxa_begin_catch(exn).
3845 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
3846 catchCall->setDoesNotThrow();
3847 catchCall->setCallingConv(CGM.getRuntimeCC());
3848
3849 // Call std::terminate().
David Blaikie4ba525b2015-07-14 17:27:39 +00003850 llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn());
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003851 termCall->setDoesNotThrow();
3852 termCall->setDoesNotReturn();
3853 termCall->setCallingConv(CGM.getRuntimeCC());
3854
3855 // std::terminate cannot return.
3856 builder.CreateUnreachable();
3857 }
3858
3859 return fnRef;
3860}
3861
3862llvm::CallInst *
3863ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
3864 llvm::Value *Exn) {
3865 // In C++, we want to call __cxa_begin_catch() before terminating.
3866 if (Exn) {
3867 assert(CGF.CGM.getLangOpts().CPlusPlus);
3868 return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn);
3869 }
3870 return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
3871}