blob: 9fa4f06338a40a8e27b72be22939eab51d7f96d9 [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
Craig Topper4f12f102014-03-12 06:41:41 +000072 bool isZeroInitializable(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +000073
Craig Topper4f12f102014-03-12 06:41:41 +000074 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
John McCall7a9aac22010-08-23 01:21:21 +000075
Craig Topper4f12f102014-03-12 06:41:41 +000076 llvm::Value *
77 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
78 const Expr *E,
79 llvm::Value *&This,
80 llvm::Value *MemFnPtr,
81 const MemberPointerType *MPT) override;
John McCalla8bbb822010-08-22 03:04:22 +000082
Craig Topper4f12f102014-03-12 06:41:41 +000083 llvm::Value *
84 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
85 llvm::Value *Base,
86 llvm::Value *MemPtr,
87 const MemberPointerType *MPT) override;
John McCallc134eb52010-08-31 21:07:20 +000088
John McCall7a9aac22010-08-23 01:21:21 +000089 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
90 const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +000091 llvm::Value *Src) override;
John McCallc62bb392012-02-15 01:22:51 +000092 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +000093 llvm::Constant *Src) override;
John McCall84fa5102010-08-22 04:16:24 +000094
Craig Topper4f12f102014-03-12 06:41:41 +000095 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +000096
David Majnemere2be95b2015-06-23 07:31:01 +000097 llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD) override;
John McCallf3a88602011-02-03 08:15:49 +000098 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +000099 CharUnits offset) override;
100 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
Richard Smithdafff942012-01-14 04:30:29 +0000101 llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
102 CharUnits ThisAdjustment);
John McCall1c456c82010-08-22 06:43:33 +0000103
John McCall7a9aac22010-08-23 01:21:21 +0000104 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000105 llvm::Value *L, llvm::Value *R,
John McCall7a9aac22010-08-23 01:21:21 +0000106 const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +0000107 bool Inequality) override;
John McCall131d97d2010-08-22 08:30:07 +0000108
John McCall7a9aac22010-08-23 01:21:21 +0000109 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000110 llvm::Value *Addr,
111 const MemberPointerType *MPT) override;
John McCall5d865c322010-08-31 07:33:07 +0000112
David Majnemer08681372014-11-01 07:37:17 +0000113 void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,
David Majnemer0c0b6d92014-10-31 20:09:12 +0000114 llvm::Value *Ptr, QualType ElementType,
David Majnemer0c0b6d92014-10-31 20:09:12 +0000115 const CXXDestructorDecl *Dtor) override;
John McCall82fb8922012-09-25 10:10:39 +0000116
David Majnemer442d0a22014-11-25 07:20:20 +0000117 void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
David Majnemer7c237072015-03-05 00:46:22 +0000118 void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override;
David Majnemer442d0a22014-11-25 07:20:20 +0000119
Reid Klecknerfff8e7f2015-03-03 19:21:04 +0000120 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
121
122 llvm::CallInst *
123 emitTerminateForUnexpectedException(CodeGenFunction &CGF,
124 llvm::Value *Exn) override;
125
David Majnemere2cb8d12014-07-07 06:20:47 +0000126 void EmitFundamentalRTTIDescriptor(QualType Type);
127 void EmitFundamentalRTTIDescriptors();
David Majnemer443250f2015-03-17 20:35:00 +0000128 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
Justin Bogner0729afa2015-03-17 22:31:34 +0000129 llvm::Constant *
David Majnemer37b417f2015-03-29 21:55:10 +0000130 getAddrOfCXXCatchHandlerType(QualType Ty,
131 QualType CatchHandlerType) override {
David Majnemer443250f2015-03-17 20:35:00 +0000132 return getAddrOfRTTIDescriptor(Ty);
133 }
David Majnemere2cb8d12014-07-07 06:20:47 +0000134
David Majnemer1162d252014-06-22 19:05:33 +0000135 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
136 void EmitBadTypeidCall(CodeGenFunction &CGF) override;
137 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
138 llvm::Value *ThisPtr,
139 llvm::Type *StdTypeInfoPtrTy) override;
140
141 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
142 QualType SrcRecordTy) override;
143
144 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
145 QualType SrcRecordTy, QualType DestTy,
146 QualType DestRecordTy,
147 llvm::BasicBlock *CastEnd) override;
148
149 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, llvm::Value *Value,
150 QualType SrcRecordTy,
151 QualType DestTy) override;
152
153 bool EmitBadCastCall(CodeGenFunction &CGF) override;
154
Craig Topper4f12f102014-03-12 06:41:41 +0000155 llvm::Value *
156 GetVirtualBaseClassOffset(CodeGenFunction &CGF, llvm::Value *This,
157 const CXXRecordDecl *ClassDecl,
158 const CXXRecordDecl *BaseClassDecl) override;
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000159
Craig Topper4f12f102014-03-12 06:41:41 +0000160 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000161
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000162 void buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
163 SmallVectorImpl<CanQualType> &ArgTys) override;
John McCall5d865c322010-08-31 07:33:07 +0000164
Reid Klecknere7de47e2013-07-22 13:51:44 +0000165 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
Craig Topper4f12f102014-03-12 06:41:41 +0000166 CXXDtorType DT) const override {
Reid Klecknere7de47e2013-07-22 13:51:44 +0000167 // Itanium does not emit any destructor variant as an inline thunk.
168 // Delegating may occur as an optimization, but all variants are either
169 // emitted with external linkage or as linkonce if they are inline and used.
170 return false;
171 }
172
Craig Topper4f12f102014-03-12 06:41:41 +0000173 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
Reid Klecknere7de47e2013-07-22 13:51:44 +0000174
Reid Kleckner89077a12013-12-17 19:46:40 +0000175 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
Craig Topper4f12f102014-03-12 06:41:41 +0000176 FunctionArgList &Params) override;
John McCall5d865c322010-08-31 07:33:07 +0000177
Craig Topper4f12f102014-03-12 06:41:41 +0000178 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
John McCall8ed55a52010-09-02 09:58:18 +0000179
Reid Kleckner89077a12013-12-17 19:46:40 +0000180 unsigned addImplicitConstructorArgs(CodeGenFunction &CGF,
181 const CXXConstructorDecl *D,
182 CXXCtorType Type, bool ForVirtualBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000183 bool Delegating,
184 CallArgList &Args) override;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000185
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000186 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
187 CXXDtorType Type, bool ForVirtualBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000188 bool Delegating, llvm::Value *This) override;
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000189
Craig Topper4f12f102014-03-12 06:41:41 +0000190 void emitVTableDefinitions(CodeGenVTables &CGVT,
191 const CXXRecordDecl *RD) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000192
193 llvm::Value *getVTableAddressPointInStructor(
194 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
Steven Wu5528da72015-08-28 07:14:10 +0000195 BaseSubobject Base, const CXXRecordDecl *NearestVBase,
196 bool &NeedsVirtualOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000197
198 llvm::Constant *
199 getVTableAddressPointForConstExpr(BaseSubobject Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000200 const CXXRecordDecl *VTableClass) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000201
202 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
Craig Topper4f12f102014-03-12 06:41:41 +0000203 CharUnits VPtrOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000204
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000205 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
Craig Topper4f12f102014-03-12 06:41:41 +0000206 llvm::Value *This,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +0000207 llvm::Type *Ty,
208 SourceLocation Loc) override;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000209
David Majnemer0c0b6d92014-10-31 20:09:12 +0000210 llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
211 const CXXDestructorDecl *Dtor,
212 CXXDtorType DtorType,
213 llvm::Value *This,
214 const CXXMemberCallExpr *CE) override;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000215
Craig Topper4f12f102014-03-12 06:41:41 +0000216 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
Reid Kleckner7810af02013-06-19 15:20:38 +0000217
Steven Wu5528da72015-08-28 07:14:10 +0000218 bool canEmitAvailableExternallyVTable(const CXXRecordDecl *RD) const override;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000219
Hans Wennborgc94391d2014-06-06 20:04:01 +0000220 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
221 bool ReturnAdjustment) override {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000222 // Allow inlining of thunks by emitting them with available_externally
223 // linkage together with vtables when needed.
Peter Collingbourne8fabc1b2015-07-01 02:10:26 +0000224 if (ForVTable && !Thunk->hasLocalLinkage())
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000225 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
226 }
227
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000228 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This,
Craig Topper4f12f102014-03-12 06:41:41 +0000229 const ThisAdjustment &TA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000230
231 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
Craig Topper4f12f102014-03-12 06:41:41 +0000232 const ReturnAdjustment &RA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000233
David Majnemer196ac332014-09-11 23:05:02 +0000234 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
235 FunctionArgList &Args) const override {
236 assert(!Args.empty() && "expected the arglist to not be empty!");
237 return Args.size() - 1;
238 }
239
Craig Topper4f12f102014-03-12 06:41:41 +0000240 StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
241 StringRef GetDeletedVirtualCallName() override
242 { return "__cxa_deleted_virtual"; }
Joao Matos2ce88ef2012-07-17 17:10:11 +0000243
Craig Topper4f12f102014-03-12 06:41:41 +0000244 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall8ed55a52010-09-02 09:58:18 +0000245 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
246 llvm::Value *NewPtr,
247 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +0000248 const CXXNewExpr *expr,
Craig Topper4f12f102014-03-12 06:41:41 +0000249 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000250 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
251 llvm::Value *allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000252 CharUnits cookieSize) override;
John McCall68ff0372010-09-08 01:44:27 +0000253
John McCallcdf7ef52010-11-06 09:44:32 +0000254 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000255 llvm::GlobalVariable *DeclPtr,
256 bool PerformInit) override;
Richard Smithdbf74ba2013-04-14 23:01:42 +0000257 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000258 llvm::Constant *dtor, llvm::Constant *addr) override;
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000259
260 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +0000261 llvm::Value *Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000262 void EmitThreadLocalInitFuncs(
David Majnemerb3341ea2014-10-05 05:05:40 +0000263 CodeGenModule &CGM,
264 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *>>
265 CXXThreadLocals,
266 ArrayRef<llvm::Function *> CXXThreadLocalInits,
267 ArrayRef<llvm::GlobalVariable *> CXXThreadLocalInitVars) override;
268
269 bool usesThreadWrapperFunction() const override { return true; }
Richard Smith0f383742014-03-26 22:48:22 +0000270 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
271 QualType LValType) override;
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000272
Craig Topper4f12f102014-03-12 06:41:41 +0000273 bool NeedsVTTParameter(GlobalDecl GD) override;
David Majnemere2cb8d12014-07-07 06:20:47 +0000274
275 /**************************** RTTI Uniqueness ******************************/
276
277protected:
278 /// Returns true if the ABI requires RTTI type_info objects to be unique
279 /// across a program.
280 virtual bool shouldRTTIBeUnique() const { return true; }
281
282public:
283 /// What sort of unique-RTTI behavior should we use?
284 enum RTTIUniquenessKind {
285 /// We are guaranteeing, or need to guarantee, that the RTTI string
286 /// is unique.
287 RUK_Unique,
288
289 /// We are not guaranteeing uniqueness for the RTTI string, so we
290 /// can demote to hidden visibility but must use string comparisons.
291 RUK_NonUniqueHidden,
292
293 /// We are not guaranteeing uniqueness for the RTTI string, so we
294 /// have to use string comparisons, but we also have to emit it with
295 /// non-hidden visibility.
296 RUK_NonUniqueVisible
297 };
298
299 /// Return the required visibility status for the given type and linkage in
300 /// the current ABI.
301 RTTIUniquenessKind
302 classifyRTTIUniqueness(QualType CanTy,
303 llvm::GlobalValue::LinkageTypes Linkage) const;
304 friend class ItaniumRTTIBuilder;
Rafael Espindola91f68b42014-09-15 19:20:10 +0000305
306 void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000307
308 private:
Piotr Padlewski1d02f682015-08-19 20:09:09 +0000309 bool hasAnyUsedVirtualInlineFunction(const CXXRecordDecl *RD) const {
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000310 const auto &VtableLayout =
311 CGM.getItaniumVTableContext().getVTableLayout(RD);
312
313 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
Piotr Padlewski1d02f682015-08-19 20:09:09 +0000314 if (!VtableComponent.isUsedFunctionPointerKind())
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000315 continue;
316
Piotr Padlewski1d02f682015-08-19 20:09:09 +0000317 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000318 if (Method->getCanonicalDecl()->isInlined())
319 return true;
320 }
321 return false;
322 }
Charles Davis4e786dd2010-05-25 19:52:27 +0000323};
John McCall86353412010-08-21 22:46:04 +0000324
325class ARMCXXABI : public ItaniumCXXABI {
326public:
Mark Seabornedf0d382013-07-24 16:25:13 +0000327 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
328 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
329 /* UseARMGuardVarABI = */ true) {}
John McCall5d865c322010-08-31 07:33:07 +0000330
Craig Topper4f12f102014-03-12 06:41:41 +0000331 bool HasThisReturn(GlobalDecl GD) const override {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000332 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
333 isa<CXXDestructorDecl>(GD.getDecl()) &&
334 GD.getDtorType() != Dtor_Deleting));
335 }
John McCall5d865c322010-08-31 07:33:07 +0000336
Craig Topper4f12f102014-03-12 06:41:41 +0000337 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
338 QualType ResTy) override;
John McCall5d865c322010-08-31 07:33:07 +0000339
Craig Topper4f12f102014-03-12 06:41:41 +0000340 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall8ed55a52010-09-02 09:58:18 +0000341 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
342 llvm::Value *NewPtr,
343 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +0000344 const CXXNewExpr *expr,
Craig Topper4f12f102014-03-12 06:41:41 +0000345 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000346 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000347 CharUnits cookieSize) override;
John McCall86353412010-08-21 22:46:04 +0000348};
Tim Northovera2ee4332014-03-29 15:09:45 +0000349
350class iOS64CXXABI : public ARMCXXABI {
351public:
352 iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {}
Tim Northover65f582f2014-03-30 17:32:48 +0000353
354 // ARM64 libraries are prepared for non-unique RTTI.
David Majnemere2cb8d12014-07-07 06:20:47 +0000355 bool shouldRTTIBeUnique() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +0000356};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000357}
Charles Davis4e786dd2010-05-25 19:52:27 +0000358
Charles Davis53c59df2010-08-16 03:33:14 +0000359CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000360 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000361 // For IR-generation purposes, there's no significant difference
362 // between the ARM and iOS ABIs.
363 case TargetCXXABI::GenericARM:
364 case TargetCXXABI::iOS:
365 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000366
Tim Northovera2ee4332014-03-29 15:09:45 +0000367 case TargetCXXABI::iOS64:
368 return new iOS64CXXABI(CGM);
369
Tim Northover9bb857a2013-01-31 12:13:10 +0000370 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
371 // include the other 32-bit ARM oddities: constructor/destructor return values
372 // and array cookies.
373 case TargetCXXABI::GenericAArch64:
Mark Seabornedf0d382013-07-24 16:25:13 +0000374 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
375 /* UseARMGuardVarABI = */ true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000376
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000377 case TargetCXXABI::GenericMIPS:
378 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true);
379
John McCall57625922013-01-25 23:36:14 +0000380 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000381 if (CGM.getContext().getTargetInfo().getTriple().getArch()
382 == llvm::Triple::le32) {
383 // For PNaCl, use ARM-style method pointers so that PNaCl code
384 // does not assume anything about the alignment of function
385 // pointers.
386 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
387 /* UseARMGuardVarABI = */ false);
388 }
John McCall57625922013-01-25 23:36:14 +0000389 return new ItaniumCXXABI(CGM);
390
391 case TargetCXXABI::Microsoft:
392 llvm_unreachable("Microsoft ABI is not Itanium-based");
393 }
394 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000395}
396
Chris Lattnera5f58b02011-07-09 17:41:47 +0000397llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000398ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
399 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000400 return CGM.PtrDiffTy;
Reid Kleckneree7cf842014-12-01 22:02:27 +0000401 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, nullptr);
John McCall1c456c82010-08-22 06:43:33 +0000402}
403
John McCalld9c6c0b2010-08-22 00:59:17 +0000404/// In the Itanium and ARM ABIs, method pointers have the form:
405/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
406///
407/// In the Itanium ABI:
408/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
409/// - the this-adjustment is (memptr.adj)
410/// - the virtual offset is (memptr.ptr - 1)
411///
412/// In the ARM ABI:
413/// - method pointers are virtual if (memptr.adj & 1) is nonzero
414/// - the this-adjustment is (memptr.adj >> 1)
415/// - the virtual offset is (memptr.ptr)
416/// ARM uses 'adj' for the virtual flag because Thumb functions
417/// may be only single-byte aligned.
418///
419/// If the member is virtual, the adjusted 'this' pointer points
420/// to a vtable pointer from which the virtual offset is applied.
421///
422/// If the member is non-virtual, memptr.ptr is the address of
423/// the function to call.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000424llvm::Value *ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
425 CodeGenFunction &CGF, const Expr *E, llvm::Value *&This,
426 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
John McCall475999d2010-08-22 00:05:51 +0000427 CGBuilderTy &Builder = CGF.Builder;
428
429 const FunctionProtoType *FPT =
430 MPT->getPointeeType()->getAs<FunctionProtoType>();
431 const CXXRecordDecl *RD =
432 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
433
Chris Lattner2192fe52011-07-18 04:24:23 +0000434 llvm::FunctionType *FTy =
John McCalla729c622012-02-17 03:33:10 +0000435 CGM.getTypes().GetFunctionType(
436 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
John McCall475999d2010-08-22 00:05:51 +0000437
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000438 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000439
John McCalld9c6c0b2010-08-22 00:59:17 +0000440 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
441 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
442 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
443
John McCalla1dee5302010-08-22 10:59:02 +0000444 // Extract memptr.adj, which is in the second field.
445 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000446
447 // Compute the true adjustment.
448 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000449 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000450 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000451
452 // Apply the adjustment and cast back to the original struct type
453 // for consistency.
John McCalld9c6c0b2010-08-22 00:59:17 +0000454 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
455 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
456 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall475999d2010-08-22 00:05:51 +0000457
458 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000459 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall475999d2010-08-22 00:05:51 +0000460
461 // If the LSB in the function pointer is 1, the function pointer points to
462 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000463 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000464 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000465 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
466 else
467 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
468 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000469 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
470
471 // In the virtual path, the adjustment left 'This' pointing to the
472 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000473 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000474 CGF.EmitBlock(FnVirtual);
475
476 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000477 llvm::Type *VTableTy = Builder.getInt8PtrTy();
Richard Smith0fc7bdc2014-03-12 18:26:14 +0000478 llvm::Value *VTable = CGF.GetVTablePtr(This, VTableTy);
John McCall475999d2010-08-22 00:05:51 +0000479
480 // Apply the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000481 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000482 if (!UseARMMethodPtrABI)
483 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld9c6c0b2010-08-22 00:59:17 +0000484 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall475999d2010-08-22 00:05:51 +0000485
486 // Load the virtual function to call.
487 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCalld9c6c0b2010-08-22 00:59:17 +0000488 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000489 CGF.EmitBranch(FnEnd);
490
491 // In the non-virtual path, the function pointer is actually a
492 // function pointer.
493 CGF.EmitBlock(FnNonVirtual);
494 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000495 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall475999d2010-08-22 00:05:51 +0000496
497 // We're done.
498 CGF.EmitBlock(FnEnd);
Jay Foad20c0f022011-03-30 11:28:58 +0000499 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
John McCall475999d2010-08-22 00:05:51 +0000500 Callee->addIncoming(VirtualFn, FnVirtual);
501 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
502 return Callee;
503}
John McCalla8bbb822010-08-22 03:04:22 +0000504
John McCallc134eb52010-08-31 21:07:20 +0000505/// Compute an l-value by applying the given pointer-to-member to a
506/// base object.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000507llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
508 CodeGenFunction &CGF, const Expr *E, llvm::Value *Base, llvm::Value *MemPtr,
509 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000510 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000511
512 CGBuilderTy &Builder = CGF.Builder;
513
Micah Villmowea2fea22012-10-25 15:39:14 +0000514 unsigned AS = Base->getType()->getPointerAddressSpace();
John McCallc134eb52010-08-31 21:07:20 +0000515
516 // Cast to char*.
517 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
518
519 // Apply the offset, which we assume is non-null.
520 llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
521
522 // Cast the address to the appropriate pointer type, adopting the
523 // address space of the base pointer.
Chris Lattner2192fe52011-07-18 04:24:23 +0000524 llvm::Type *PType
Douglas Gregor04f36212010-09-02 17:38:50 +0000525 = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
John McCallc134eb52010-08-31 21:07:20 +0000526 return Builder.CreateBitCast(Addr, PType);
527}
528
John McCallc62bb392012-02-15 01:22:51 +0000529/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
530/// conversion.
531///
532/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000533///
534/// Obligatory offset/adjustment diagram:
535/// <-- offset --> <-- adjustment -->
536/// |--------------------------|----------------------|--------------------|
537/// ^Derived address point ^Base address point ^Member address point
538///
539/// So when converting a base member pointer to a derived member pointer,
540/// we add the offset to the adjustment because the address point has
541/// decreased; and conversely, when converting a derived MP to a base MP
542/// we subtract the offset from the adjustment because the address point
543/// has increased.
544///
545/// The standard forbids (at compile time) conversion to and from
546/// virtual bases, which is why we don't have to consider them here.
547///
548/// The standard forbids (at run time) casting a derived MP to a base
549/// MP when the derived MP does not point to a member of the base.
550/// This is why -1 is a reasonable choice for null data member
551/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000552llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000553ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
554 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000555 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000556 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000557 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
558 E->getCastKind() == CK_ReinterpretMemberPointer);
559
560 // Under Itanium, reinterprets don't require any additional processing.
561 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
562
563 // Use constant emission if we can.
564 if (isa<llvm::Constant>(src))
565 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
566
567 llvm::Constant *adj = getMemberPointerAdjustment(E);
568 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000569
570 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000571 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000572
John McCallc62bb392012-02-15 01:22:51 +0000573 const MemberPointerType *destTy =
574 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000575
John McCall7a9aac22010-08-23 01:21:21 +0000576 // For member data pointers, this is just a matter of adding the
577 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000578 if (destTy->isMemberDataPointer()) {
579 llvm::Value *dst;
580 if (isDerivedToBase)
581 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000582 else
John McCallc62bb392012-02-15 01:22:51 +0000583 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000584
585 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000586 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
587 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
588 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000589 }
590
John McCalla1dee5302010-08-22 10:59:02 +0000591 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000592 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000593 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
594 offset <<= 1;
595 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000596 }
597
John McCallc62bb392012-02-15 01:22:51 +0000598 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
599 llvm::Value *dstAdj;
600 if (isDerivedToBase)
601 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000602 else
John McCallc62bb392012-02-15 01:22:51 +0000603 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000604
John McCallc62bb392012-02-15 01:22:51 +0000605 return Builder.CreateInsertValue(src, dstAdj, 1);
606}
607
608llvm::Constant *
609ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
610 llvm::Constant *src) {
611 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
612 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
613 E->getCastKind() == CK_ReinterpretMemberPointer);
614
615 // Under Itanium, reinterprets don't require any additional processing.
616 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
617
618 // If the adjustment is trivial, we don't need to do anything.
619 llvm::Constant *adj = getMemberPointerAdjustment(E);
620 if (!adj) return src;
621
622 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
623
624 const MemberPointerType *destTy =
625 E->getType()->castAs<MemberPointerType>();
626
627 // For member data pointers, this is just a matter of adding the
628 // offset if the source is non-null.
629 if (destTy->isMemberDataPointer()) {
630 // null maps to null.
631 if (src->isAllOnesValue()) return src;
632
633 if (isDerivedToBase)
634 return llvm::ConstantExpr::getNSWSub(src, adj);
635 else
636 return llvm::ConstantExpr::getNSWAdd(src, adj);
637 }
638
639 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000640 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000641 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
642 offset <<= 1;
643 adj = llvm::ConstantInt::get(adj->getType(), offset);
644 }
645
646 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
647 llvm::Constant *dstAdj;
648 if (isDerivedToBase)
649 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
650 else
651 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
652
653 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000654}
John McCall84fa5102010-08-22 04:16:24 +0000655
656llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000657ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000658 // Itanium C++ ABI 2.3:
659 // A NULL pointer is represented as -1.
660 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000661 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000662
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000663 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000664 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000665 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000666}
667
John McCallf3a88602011-02-03 08:15:49 +0000668llvm::Constant *
669ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
670 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000671 // Itanium C++ ABI 2.3:
672 // A pointer to data member is an offset from the base address of
673 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000674 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000675}
676
David Majnemere2be95b2015-06-23 07:31:01 +0000677llvm::Constant *
678ItaniumCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000679 return BuildMemberPointer(MD, CharUnits::Zero());
680}
681
682llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
683 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000684 assert(MD->isInstance() && "Member function must not be static!");
685 MD = MD->getCanonicalDecl();
686
687 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000688
689 // Get the function pointer (or index if this is a virtual function).
690 llvm::Constant *MemPtr[2];
691 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000692 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000693
Ken Dyckdf016282011-04-09 01:30:02 +0000694 const ASTContext &Context = getContext();
695 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000696 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000697 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000698
Mark Seabornedf0d382013-07-24 16:25:13 +0000699 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000700 // ARM C++ ABI 3.2.1:
701 // This ABI specifies that adj contains twice the this
702 // adjustment, plus 1 if the member function is virtual. The
703 // least significant bit of adj then makes exactly the same
704 // discrimination as the least significant bit of ptr does for
705 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000706 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
707 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000708 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000709 } else {
710 // Itanium C++ ABI 2.3:
711 // For a virtual function, [the pointer field] is 1 plus the
712 // virtual table offset (in bytes) of the function,
713 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000714 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
715 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000716 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000717 }
718 } else {
John McCall2979fe02011-04-12 00:42:48 +0000719 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000720 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000721 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000722 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000723 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000724 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000725 } else {
John McCall2979fe02011-04-12 00:42:48 +0000726 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
727 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000728 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000729 }
John McCall2979fe02011-04-12 00:42:48 +0000730 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000731
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000732 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000733 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
734 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000735 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000736 }
John McCall1c456c82010-08-22 06:43:33 +0000737
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000738 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000739}
740
Richard Smithdafff942012-01-14 04:30:29 +0000741llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
742 QualType MPType) {
743 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
744 const ValueDecl *MPD = MP.getMemberPointerDecl();
745 if (!MPD)
746 return EmitNullMemberPointer(MPT);
747
Reid Kleckner452abac2013-05-09 21:01:17 +0000748 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000749
750 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
751 return BuildMemberPointer(MD, ThisAdjustment);
752
753 CharUnits FieldOffset =
754 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
755 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
756}
757
John McCall131d97d2010-08-22 08:30:07 +0000758/// The comparison algorithm is pretty easy: the member pointers are
759/// the same if they're either bitwise identical *or* both null.
760///
761/// ARM is different here only because null-ness is more complicated.
762llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000763ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
764 llvm::Value *L,
765 llvm::Value *R,
766 const MemberPointerType *MPT,
767 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000768 CGBuilderTy &Builder = CGF.Builder;
769
John McCall131d97d2010-08-22 08:30:07 +0000770 llvm::ICmpInst::Predicate Eq;
771 llvm::Instruction::BinaryOps And, Or;
772 if (Inequality) {
773 Eq = llvm::ICmpInst::ICMP_NE;
774 And = llvm::Instruction::Or;
775 Or = llvm::Instruction::And;
776 } else {
777 Eq = llvm::ICmpInst::ICMP_EQ;
778 And = llvm::Instruction::And;
779 Or = llvm::Instruction::Or;
780 }
781
John McCall7a9aac22010-08-23 01:21:21 +0000782 // Member data pointers are easy because there's a unique null
783 // value, so it just comes down to bitwise equality.
784 if (MPT->isMemberDataPointer())
785 return Builder.CreateICmp(Eq, L, R);
786
787 // For member function pointers, the tautologies are more complex.
788 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000789 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000790 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000791 // (L == R) <==> (L.ptr == R.ptr &&
792 // (L.adj == R.adj ||
793 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000794 // The inequality tautologies have exactly the same structure, except
795 // applying De Morgan's laws.
796
797 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
798 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
799
John McCall131d97d2010-08-22 08:30:07 +0000800 // This condition tests whether L.ptr == R.ptr. This must always be
801 // true for equality to hold.
802 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
803
804 // This condition, together with the assumption that L.ptr == R.ptr,
805 // tests whether the pointers are both null. ARM imposes an extra
806 // condition.
807 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
808 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
809
810 // This condition tests whether L.adj == R.adj. If this isn't
811 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +0000812 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
813 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000814 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
815
816 // Null member function pointers on ARM clear the low bit of Adj,
817 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000818 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000819 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
820
821 // Compute (l.adj | r.adj) & 1 and test it against zero.
822 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
823 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
824 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
825 "cmp.or.adj");
826 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
827 }
828
829 // Tie together all our conditions.
830 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
831 Result = Builder.CreateBinOp(And, PtrEq, Result,
832 Inequality ? "memptr.ne" : "memptr.eq");
833 return Result;
834}
835
836llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000837ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
838 llvm::Value *MemPtr,
839 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +0000840 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +0000841
842 /// For member data pointers, this is just a check against -1.
843 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000844 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +0000845 llvm::Value *NegativeOne =
846 llvm::Constant::getAllOnesValue(MemPtr->getType());
847 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
848 }
John McCall131d97d2010-08-22 08:30:07 +0000849
Daniel Dunbar914bc412011-04-19 23:10:47 +0000850 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +0000851 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +0000852
853 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
854 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
855
Daniel Dunbar914bc412011-04-19 23:10:47 +0000856 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
857 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000858 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000859 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +0000860 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000861 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +0000862 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
863 "memptr.isvirtual");
864 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +0000865 }
866
867 return Result;
868}
John McCall1c456c82010-08-22 06:43:33 +0000869
Reid Kleckner40ca9132014-05-13 22:05:45 +0000870bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
871 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
872 if (!RD)
873 return false;
874
Reid Klecknerd355ca72014-05-15 01:26:32 +0000875 // Return indirectly if we have a non-trivial copy ctor or non-trivial dtor.
876 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
877 // special members.
878 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor()) {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000879 FI.getReturnInfo() = ABIArgInfo::getIndirect(0, /*ByVal=*/false);
880 return true;
881 }
Reid Kleckner40ca9132014-05-13 22:05:45 +0000882 return false;
883}
884
John McCall614dbdc2010-08-22 21:01:12 +0000885/// The Itanium ABI requires non-zero initialization only for data
886/// member pointers, for which '0' is a valid offset.
887bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
David Majnemer5fd33e02015-04-24 01:25:08 +0000888 return MPT->isMemberFunctionPointer();
John McCall84fa5102010-08-22 04:16:24 +0000889}
John McCall5d865c322010-08-31 07:33:07 +0000890
John McCall82fb8922012-09-25 10:10:39 +0000891/// The Itanium ABI always places an offset to the complete object
892/// at entry -2 in the vtable.
David Majnemer08681372014-11-01 07:37:17 +0000893void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
894 const CXXDeleteExpr *DE,
895 llvm::Value *Ptr,
896 QualType ElementType,
897 const CXXDestructorDecl *Dtor) {
898 bool UseGlobalDelete = DE->isGlobalDelete();
David Majnemer0c0b6d92014-10-31 20:09:12 +0000899 if (UseGlobalDelete) {
900 // Derive the complete-object pointer, which is what we need
901 // to pass to the deallocation function.
John McCall82fb8922012-09-25 10:10:39 +0000902
David Majnemer0c0b6d92014-10-31 20:09:12 +0000903 // Grab the vtable pointer as an intptr_t*.
904 llvm::Value *VTable = CGF.GetVTablePtr(Ptr, CGF.IntPtrTy->getPointerTo());
John McCall82fb8922012-09-25 10:10:39 +0000905
David Majnemer0c0b6d92014-10-31 20:09:12 +0000906 // Track back to entry -2 and pull out the offset there.
907 llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
908 VTable, -2, "complete-offset.ptr");
909 llvm::LoadInst *Offset = CGF.Builder.CreateLoad(OffsetPtr);
910 Offset->setAlignment(CGF.PointerAlignInBytes);
911
912 // Apply the offset.
913 llvm::Value *CompletePtr = CGF.Builder.CreateBitCast(Ptr, CGF.Int8PtrTy);
914 CompletePtr = CGF.Builder.CreateInBoundsGEP(CompletePtr, Offset);
915
916 // If we're supposed to call the global delete, make sure we do so
917 // even if the destructor throws.
David Majnemer08681372014-11-01 07:37:17 +0000918 CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr,
919 ElementType);
David Majnemer0c0b6d92014-10-31 20:09:12 +0000920 }
921
922 // FIXME: Provide a source location here even though there's no
923 // CXXMemberCallExpr for dtor call.
924 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
925 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr);
926
927 if (UseGlobalDelete)
928 CGF.PopCleanupBlock();
John McCall82fb8922012-09-25 10:10:39 +0000929}
930
David Majnemer442d0a22014-11-25 07:20:20 +0000931void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
932 // void __cxa_rethrow();
933
934 llvm::FunctionType *FTy =
935 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
936
937 llvm::Constant *Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
938
939 if (isNoReturn)
940 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, None);
941 else
942 CGF.EmitRuntimeCallOrInvoke(Fn);
943}
944
David Majnemer7c237072015-03-05 00:46:22 +0000945static llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) {
946 // void *__cxa_allocate_exception(size_t thrown_size);
947
948 llvm::FunctionType *FTy =
949 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false);
950
951 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
952}
953
954static llvm::Constant *getThrowFn(CodeGenModule &CGM) {
955 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
956 // void (*dest) (void *));
957
958 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
959 llvm::FunctionType *FTy =
960 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
961
962 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
963}
964
965void ItaniumCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
966 QualType ThrowType = E->getSubExpr()->getType();
967 // Now allocate the exception object.
968 llvm::Type *SizeTy = CGF.ConvertType(getContext().getSizeType());
969 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
970
971 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM);
972 llvm::CallInst *ExceptionPtr = CGF.EmitNounwindRuntimeCall(
973 AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception");
974
975 CGF.EmitAnyExprToExn(E->getSubExpr(), ExceptionPtr);
976
977 // Now throw the exception.
978 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
979 /*ForEH=*/true);
980
981 // The address of the destructor. If the exception type has a
982 // trivial destructor (or isn't a record), we just pass null.
983 llvm::Constant *Dtor = nullptr;
984 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
985 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
986 if (!Record->hasTrivialDestructor()) {
987 CXXDestructorDecl *DtorD = Record->getDestructor();
988 Dtor = CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete);
989 Dtor = llvm::ConstantExpr::getBitCast(Dtor, CGM.Int8PtrTy);
990 }
991 }
992 if (!Dtor) Dtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
993
994 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
995 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
996}
997
David Majnemer1162d252014-06-22 19:05:33 +0000998static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) {
999 // void *__dynamic_cast(const void *sub,
1000 // const abi::__class_type_info *src,
1001 // const abi::__class_type_info *dst,
1002 // std::ptrdiff_t src2dst_offset);
1003
1004 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1005 llvm::Type *PtrDiffTy =
1006 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1007
1008 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
1009
1010 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
1011
1012 // Mark the function as nounwind readonly.
1013 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
1014 llvm::Attribute::ReadOnly };
1015 llvm::AttributeSet Attrs = llvm::AttributeSet::get(
1016 CGF.getLLVMContext(), llvm::AttributeSet::FunctionIndex, FuncAttrs);
1017
1018 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
1019}
1020
1021static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1022 // void __cxa_bad_cast();
1023 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1024 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1025}
1026
1027/// \brief Compute the src2dst_offset hint as described in the
1028/// Itanium C++ ABI [2.9.7]
1029static CharUnits computeOffsetHint(ASTContext &Context,
1030 const CXXRecordDecl *Src,
1031 const CXXRecordDecl *Dst) {
1032 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1033 /*DetectVirtual=*/false);
1034
1035 // If Dst is not derived from Src we can skip the whole computation below and
1036 // return that Src is not a public base of Dst. Record all inheritance paths.
1037 if (!Dst->isDerivedFrom(Src, Paths))
1038 return CharUnits::fromQuantity(-2ULL);
1039
1040 unsigned NumPublicPaths = 0;
1041 CharUnits Offset;
1042
1043 // Now walk all possible inheritance paths.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001044 for (const CXXBasePath &Path : Paths) {
1045 if (Path.Access != AS_public) // Ignore non-public inheritance.
David Majnemer1162d252014-06-22 19:05:33 +00001046 continue;
1047
1048 ++NumPublicPaths;
1049
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001050 for (const CXXBasePathElement &PathElement : Path) {
David Majnemer1162d252014-06-22 19:05:33 +00001051 // If the path contains a virtual base class we can't give any hint.
1052 // -1: no hint.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001053 if (PathElement.Base->isVirtual())
David Majnemer1162d252014-06-22 19:05:33 +00001054 return CharUnits::fromQuantity(-1ULL);
1055
1056 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
1057 continue;
1058
1059 // Accumulate the base class offsets.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001060 const ASTRecordLayout &L = Context.getASTRecordLayout(PathElement.Class);
1061 Offset += L.getBaseClassOffset(
1062 PathElement.Base->getType()->getAsCXXRecordDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001063 }
1064 }
1065
1066 // -2: Src is not a public base of Dst.
1067 if (NumPublicPaths == 0)
1068 return CharUnits::fromQuantity(-2ULL);
1069
1070 // -3: Src is a multiple public base type but never a virtual base type.
1071 if (NumPublicPaths > 1)
1072 return CharUnits::fromQuantity(-3ULL);
1073
1074 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
1075 // Return the offset of Src from the origin of Dst.
1076 return Offset;
1077}
1078
1079static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1080 // void __cxa_bad_typeid();
1081 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1082
1083 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1084}
1085
1086bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
1087 QualType SrcRecordTy) {
1088 return IsDeref;
1089}
1090
1091void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
1092 llvm::Value *Fn = getBadTypeidFn(CGF);
1093 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1094 CGF.Builder.CreateUnreachable();
1095}
1096
1097llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
1098 QualType SrcRecordTy,
1099 llvm::Value *ThisPtr,
1100 llvm::Type *StdTypeInfoPtrTy) {
1101 llvm::Value *Value =
1102 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo());
1103
1104 // Load the type info.
1105 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
1106 return CGF.Builder.CreateLoad(Value);
1107}
1108
1109bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1110 QualType SrcRecordTy) {
1111 return SrcIsPtr;
1112}
1113
1114llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
1115 CodeGenFunction &CGF, llvm::Value *Value, QualType SrcRecordTy,
1116 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1117 llvm::Type *PtrDiffLTy =
1118 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1119 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1120
1121 llvm::Value *SrcRTTI =
1122 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1123 llvm::Value *DestRTTI =
1124 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1125
1126 // Compute the offset hint.
1127 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1128 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1129 llvm::Value *OffsetHint = llvm::ConstantInt::get(
1130 PtrDiffLTy,
1131 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
1132
1133 // Emit the call to __dynamic_cast.
1134 Value = CGF.EmitCastToVoidPtr(Value);
1135
1136 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
1137 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
1138 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1139
1140 /// C++ [expr.dynamic.cast]p9:
1141 /// A failed cast to reference type throws std::bad_cast
1142 if (DestTy->isReferenceType()) {
1143 llvm::BasicBlock *BadCastBlock =
1144 CGF.createBasicBlock("dynamic_cast.bad_cast");
1145
1146 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1147 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1148
1149 CGF.EmitBlock(BadCastBlock);
1150 EmitBadCastCall(CGF);
1151 }
1152
1153 return Value;
1154}
1155
1156llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
1157 llvm::Value *Value,
1158 QualType SrcRecordTy,
1159 QualType DestTy) {
1160 llvm::Type *PtrDiffLTy =
1161 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1162 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1163
1164 // Get the vtable pointer.
1165 llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
1166
1167 // Get the offset-to-top from the vtable.
1168 llvm::Value *OffsetToTop =
1169 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1170 OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
1171
1172 // Finally, add the offset to the pointer.
1173 Value = CGF.EmitCastToVoidPtr(Value);
1174 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1175
1176 return CGF.Builder.CreateBitCast(Value, DestLTy);
1177}
1178
1179bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1180 llvm::Value *Fn = getBadCastFn(CGF);
1181 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1182 CGF.Builder.CreateUnreachable();
1183 return true;
1184}
1185
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001186llvm::Value *
1187ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
1188 llvm::Value *This,
1189 const CXXRecordDecl *ClassDecl,
1190 const CXXRecordDecl *BaseClassDecl) {
1191 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy);
1192 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001193 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1194 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001195
1196 llvm::Value *VBaseOffsetPtr =
1197 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1198 "vbase.offset.ptr");
1199 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1200 CGM.PtrDiffTy->getPointerTo());
1201
1202 llvm::Value *VBaseOffset =
1203 CGF.Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1204
1205 return VBaseOffset;
1206}
1207
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001208void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1209 // Just make sure we're in sync with TargetCXXABI.
1210 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1211
Rafael Espindolac3cde362013-12-09 14:51:17 +00001212 // The constructor used for constructing this as a base class;
1213 // ignores virtual bases.
1214 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1215
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001216 // The constructor used for constructing this as a complete class;
Nico Weber4c2ffb22015-01-07 05:25:05 +00001217 // constructs the virtual bases, then calls the base constructor.
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001218 if (!D->getParent()->isAbstract()) {
1219 // We don't need to emit the complete ctor if the class is abstract.
1220 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1221 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001222}
1223
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001224void
1225ItaniumCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
1226 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +00001227 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001228
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001229 // All parameters are already in place except VTT, which goes after 'this'.
1230 // These are Clang types, so we don't need to worry about sret yet.
John McCall5d865c322010-08-31 07:33:07 +00001231
1232 // Check if we need to add a VTT parameter (which has type void **).
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001233 if (T == StructorType::Base && MD->getParent()->getNumVBases() != 0)
1234 ArgTys.insert(ArgTys.begin() + 1,
1235 Context.getPointerType(Context.VoidPtrTy));
John McCall5d865c322010-08-31 07:33:07 +00001236}
1237
Reid Klecknere7de47e2013-07-22 13:51:44 +00001238void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
Rafael Espindolac3cde362013-12-09 14:51:17 +00001239 // The destructor used for destructing this as a base class; ignores
1240 // virtual bases.
1241 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001242
1243 // The destructor used for destructing this as a most-derived class;
1244 // call the base destructor and then destructs any virtual bases.
1245 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1246
Rafael Espindolac3cde362013-12-09 14:51:17 +00001247 // The destructor in a virtual table is always a 'deleting'
1248 // destructor, which calls the complete destructor and then uses the
1249 // appropriate operator delete.
1250 if (D->isVirtual())
1251 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001252}
1253
Reid Kleckner89077a12013-12-17 19:46:40 +00001254void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1255 QualType &ResTy,
1256 FunctionArgList &Params) {
John McCall5d865c322010-08-31 07:33:07 +00001257 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +00001258 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
John McCall5d865c322010-08-31 07:33:07 +00001259
1260 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001261 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +00001262 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001263
1264 // FIXME: avoid the fake decl
1265 QualType T = Context.getPointerType(Context.VoidPtrTy);
1266 ImplicitParamDecl *VTTDecl
Craig Topper8a13c412014-05-21 05:09:00 +00001267 = ImplicitParamDecl::Create(Context, nullptr, MD->getLocation(),
John McCall5d865c322010-08-31 07:33:07 +00001268 &Context.Idents.get("vtt"), T);
Reid Kleckner89077a12013-12-17 19:46:40 +00001269 Params.insert(Params.begin() + 1, VTTDecl);
Reid Kleckner2af6d732013-12-13 00:09:59 +00001270 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +00001271 }
1272}
1273
John McCall5d865c322010-08-31 07:33:07 +00001274void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1275 /// Initialize the 'this' slot.
1276 EmitThisParam(CGF);
1277
1278 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +00001279 if (getStructorImplicitParamDecl(CGF)) {
1280 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1281 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +00001282 }
John McCall5d865c322010-08-31 07:33:07 +00001283
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001284 /// If this is a function that the ABI specifies returns 'this', initialize
1285 /// the return slot to 'this' at the start of the function.
1286 ///
1287 /// Unlike the setting of return types, this is done within the ABI
1288 /// implementation instead of by clients of CGCXXABI because:
1289 /// 1) getThisValue is currently protected
1290 /// 2) in theory, an ABI could implement 'this' returns some other way;
1291 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +00001292 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +00001293 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +00001294}
1295
Reid Kleckner89077a12013-12-17 19:46:40 +00001296unsigned ItaniumCXXABI::addImplicitConstructorArgs(
1297 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1298 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1299 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
1300 return 0;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001301
Reid Kleckner89077a12013-12-17 19:46:40 +00001302 // Insert the implicit 'vtt' argument as the second argument.
1303 llvm::Value *VTT =
1304 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1305 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1306 Args.insert(Args.begin() + 1,
1307 CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false));
1308 return 1; // Added one arg.
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001309}
1310
1311void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1312 const CXXDestructorDecl *DD,
1313 CXXDtorType Type, bool ForVirtualBase,
1314 bool Delegating, llvm::Value *This) {
1315 GlobalDecl GD(DD, Type);
1316 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1317 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1318
Craig Topper8a13c412014-05-21 05:09:00 +00001319 llvm::Value *Callee = nullptr;
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001320 if (getContext().getLangOpts().AppleKext)
1321 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
1322
1323 if (!Callee)
Rafael Espindola1ac0ec82014-09-11 15:42:06 +00001324 Callee = CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type));
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001325
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001326 CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(), This, VTT,
1327 VTTTy, nullptr);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001328}
1329
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001330void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1331 const CXXRecordDecl *RD) {
1332 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1333 if (VTable->hasInitializer())
1334 return;
1335
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001336 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001337 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1338 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
David Majnemerd905da42014-07-01 20:30:31 +00001339 llvm::Constant *RTTI =
1340 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001341
1342 // Create and set the initializer.
1343 llvm::Constant *Init = CGVT.CreateVTableInitializer(
1344 RD, VTLayout.vtable_component_begin(), VTLayout.getNumVTableComponents(),
David Majnemerd905da42014-07-01 20:30:31 +00001345 VTLayout.vtable_thunk_begin(), VTLayout.getNumVTableThunks(), RTTI);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001346 VTable->setInitializer(Init);
1347
1348 // Set the correct linkage.
1349 VTable->setLinkage(Linkage);
1350
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001351 if (CGM.supportsCOMDAT() && VTable->isWeakForLinker())
1352 VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName()));
Rafael Espindolacb92c192015-01-15 23:18:01 +00001353
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001354 // Set the right visibility.
John McCall8f80a612014-02-08 00:41:16 +00001355 CGM.setGlobalVisibility(VTable, RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001356
Benjamin Kramer5d34a2b2014-09-10 12:50:59 +00001357 // Use pointer alignment for the vtable. Otherwise we would align them based
1358 // on the size of the initializer which doesn't make sense as only single
1359 // values are read.
1360 unsigned PAlign = CGM.getTarget().getPointerAlign(0);
1361 VTable->setAlignment(getContext().toCharUnitsFromBits(PAlign).getQuantity());
1362
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001363 // If this is the magic class __cxxabiv1::__fundamental_type_info,
1364 // we will emit the typeinfo for the fundamental types. This is the
1365 // same behaviour as GCC.
1366 const DeclContext *DC = RD->getDeclContext();
1367 if (RD->getIdentifier() &&
1368 RD->getIdentifier()->isStr("__fundamental_type_info") &&
1369 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1370 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1371 DC->getParent()->isTranslationUnit())
David Majnemere2cb8d12014-07-07 06:20:47 +00001372 EmitFundamentalRTTIDescriptors();
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001373
1374 CGM.EmitVTableBitSetEntries(VTable, VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001375}
1376
Piotr Padlewski525f7462015-08-27 21:35:37 +00001377llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1378 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
Steven Wu5528da72015-08-28 07:14:10 +00001379 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
1380 bool NeedsVTTParam = CGM.getCXXABI().NeedsVTTParameter(CGF.CurGD);
1381 NeedsVirtualOffset = (NeedsVTTParam && NearestVBase);
Piotr Padlewski525f7462015-08-27 21:35:37 +00001382
Steven Wu5528da72015-08-28 07:14:10 +00001383 llvm::Value *VTableAddressPoint;
1384 if (NeedsVTTParam && (Base.getBase()->getNumVBases() || NearestVBase)) {
1385 // Get the secondary vpointer index.
1386 uint64_t VirtualPointerIndex =
1387 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1388
1389 /// Load the VTT.
1390 llvm::Value *VTT = CGF.LoadCXXVTT();
1391 if (VirtualPointerIndex)
1392 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1393
1394 // And load the address point from the VTT.
1395 VTableAddressPoint = CGF.Builder.CreateLoad(VTT);
1396 } else {
1397 llvm::Constant *VTable =
1398 CGM.getCXXABI().getAddrOfVTable(VTableClass, CharUnits());
1399 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1400 .getVTableLayout(VTableClass)
1401 .getAddressPoint(Base);
1402 VTableAddressPoint =
1403 CGF.Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
Piotr Padlewski525f7462015-08-27 21:35:37 +00001404 }
Steven Wu5528da72015-08-28 07:14:10 +00001405
1406 return VTableAddressPoint;
Piotr Padlewski525f7462015-08-27 21:35:37 +00001407}
1408
Steven Wu5528da72015-08-28 07:14:10 +00001409llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1410 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1411 auto *VTable = getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001412
1413 // Find the appropriate vtable within the vtable group.
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001414 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1415 .getVTableLayout(VTableClass)
1416 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001417 llvm::Value *Indices[] = {
1418 llvm::ConstantInt::get(CGM.Int64Ty, 0),
1419 llvm::ConstantInt::get(CGM.Int64Ty, AddressPoint)
1420 };
1421
David Blaikiee3b172a2015-04-02 18:55:21 +00001422 return llvm::ConstantExpr::getInBoundsGetElementPtr(VTable->getValueType(),
1423 VTable, Indices);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001424}
1425
1426llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1427 CharUnits VPtrOffset) {
1428 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1429
1430 llvm::GlobalVariable *&VTable = VTables[RD];
1431 if (VTable)
1432 return VTable;
1433
1434 // Queue up this v-table for possible deferred emission.
1435 CGM.addDeferredVTable(RD);
1436
Yaron Kerene46f7ed2015-07-29 14:21:47 +00001437 SmallString<256> Name;
1438 llvm::raw_svector_ostream Out(Name);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001439 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001440
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001441 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001442 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
1443 CGM.Int8PtrTy, VTContext.getVTableLayout(RD).getNumVTableComponents());
1444
1445 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
1446 Name, ArrayType, llvm::GlobalValue::ExternalLinkage);
1447 VTable->setUnnamedAddr(true);
Hans Wennborgda24e9c2014-06-02 23:13:03 +00001448
1449 if (RD->hasAttr<DLLImportAttr>())
1450 VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1451 else if (RD->hasAttr<DLLExportAttr>())
1452 VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1453
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001454 return VTable;
1455}
1456
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001457llvm::Value *ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1458 GlobalDecl GD,
1459 llvm::Value *This,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001460 llvm::Type *Ty,
1461 SourceLocation Loc) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001462 GD = GD.getCanonicalDecl();
1463 Ty = Ty->getPointerTo()->getPointerTo();
1464 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty);
1465
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00001466 if (CGF.SanOpts.has(SanitizerKind::CFIVCall))
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001467 CGF.EmitVTablePtrCheckForCall(cast<CXXMethodDecl>(GD.getDecl()), VTable,
1468 CodeGenFunction::CFITCK_VCall, Loc);
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001469
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001470 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001471 llvm::Value *VFuncPtr =
1472 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1473 return CGF.Builder.CreateLoad(VFuncPtr);
1474}
1475
David Majnemer0c0b6d92014-10-31 20:09:12 +00001476llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
1477 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
1478 llvm::Value *This, const CXXMemberCallExpr *CE) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001479 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001480 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1481
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001482 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1483 Dtor, getFromDtorType(DtorType));
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001484 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001485 llvm::Value *Callee =
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001486 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty,
1487 CE ? CE->getLocStart() : SourceLocation());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001488
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001489 CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(), This,
1490 /*ImplicitParam=*/nullptr, QualType(), CE);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001491 return nullptr;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001492}
1493
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001494void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001495 CodeGenVTables &VTables = CGM.getVTables();
1496 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001497 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001498}
1499
Steven Wu5528da72015-08-28 07:14:10 +00001500bool ItaniumCXXABI::canEmitAvailableExternallyVTable(
1501 const CXXRecordDecl *RD) const {
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001502 // We don't emit available_externally vtables if we are in -fapple-kext mode
1503 // because kext mode does not permit devirtualization.
1504 if (CGM.getLangOpts().AppleKext)
1505 return false;
1506
1507 // If we don't have any inline virtual functions,
1508 // then we are safe to emit available_externally copy of vtable.
1509 // FIXME we can still emit a copy of the vtable if we
1510 // can emit definition of the inline functions.
Piotr Padlewski1d02f682015-08-19 20:09:09 +00001511 return !hasAnyUsedVirtualInlineFunction(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001512}
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001513static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
1514 llvm::Value *Ptr,
1515 int64_t NonVirtualAdjustment,
1516 int64_t VirtualAdjustment,
1517 bool IsReturnAdjustment) {
1518 if (!NonVirtualAdjustment && !VirtualAdjustment)
1519 return Ptr;
1520
1521 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1522 llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
1523
1524 if (NonVirtualAdjustment && !IsReturnAdjustment) {
1525 // Perform the non-virtual adjustment for a base-to-derived cast.
1526 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1527 }
1528
1529 if (VirtualAdjustment) {
1530 llvm::Type *PtrDiffTy =
1531 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1532
1533 // Perform the virtual adjustment.
1534 llvm::Value *VTablePtrPtr =
1535 CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo());
1536
1537 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1538
1539 llvm::Value *OffsetPtr =
1540 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1541
1542 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1543
1544 // Load the adjustment offset from the vtable.
1545 llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr);
1546
1547 // Adjust our pointer.
1548 V = CGF.Builder.CreateInBoundsGEP(V, Offset);
1549 }
1550
1551 if (NonVirtualAdjustment && IsReturnAdjustment) {
1552 // Perform the non-virtual adjustment for a derived-to-base cast.
1553 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1554 }
1555
1556 // Cast back to the original type.
1557 return CGF.Builder.CreateBitCast(V, Ptr->getType());
1558}
1559
1560llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1561 llvm::Value *This,
1562 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001563 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1564 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001565 /*IsReturnAdjustment=*/false);
1566}
1567
1568llvm::Value *
1569ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
1570 const ReturnAdjustment &RA) {
1571 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1572 RA.Virtual.Itanium.VBaseOffsetOffset,
1573 /*IsReturnAdjustment=*/true);
1574}
1575
John McCall5d865c322010-08-31 07:33:07 +00001576void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1577 RValue RV, QualType ResultType) {
1578 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1579 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1580
1581 // Destructor thunks in the ARM ABI have indeterminate results.
Chris Lattner2192fe52011-07-18 04:24:23 +00001582 llvm::Type *T =
John McCall5d865c322010-08-31 07:33:07 +00001583 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
1584 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1585 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1586}
John McCall8ed55a52010-09-02 09:58:18 +00001587
1588/************************** Array allocation cookies **************************/
1589
John McCallb91cd662012-05-01 05:23:51 +00001590CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1591 // The array cookie is a size_t; pad that up to the element alignment.
1592 // The cookie is actually right-justified in that space.
1593 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1594 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001595}
1596
1597llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1598 llvm::Value *NewPtr,
1599 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +00001600 const CXXNewExpr *expr,
John McCall8ed55a52010-09-02 09:58:18 +00001601 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001602 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001603
Micah Villmowea2fea22012-10-25 15:39:14 +00001604 unsigned AS = NewPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001605
John McCall9bca9232010-09-02 10:25:57 +00001606 ASTContext &Ctx = getContext();
John McCall8ed55a52010-09-02 09:58:18 +00001607 QualType SizeTy = Ctx.getSizeType();
1608 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
1609
1610 // The size of the cookie.
1611 CharUnits CookieSize =
1612 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001613 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001614
1615 // Compute an offset to the cookie.
1616 llvm::Value *CookiePtr = NewPtr;
1617 CharUnits CookieOffset = CookieSize - SizeSize;
1618 if (!CookieOffset.isZero())
1619 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
1620 CookieOffset.getQuantity());
1621
1622 // Write the number of elements into the appropriate slot.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001623 llvm::Type *NumElementsTy = CGF.ConvertType(SizeTy)->getPointerTo(AS);
1624 llvm::Value *NumElementsPtr =
1625 CGF.Builder.CreateBitCast(CookiePtr, NumElementsTy);
1626 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001627 if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 &&
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001628 expr->getOperatorNew()->isReplaceableGlobalAllocationFunction()) {
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001629 // The store to the CookiePtr does not need to be instrumented.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001630 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
1631 llvm::FunctionType *FTy =
1632 llvm::FunctionType::get(CGM.VoidTy, NumElementsTy, false);
1633 llvm::Constant *F =
1634 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
1635 CGF.Builder.CreateCall(F, NumElementsPtr);
1636 }
John McCall8ed55a52010-09-02 09:58:18 +00001637
1638 // Finally, compute a pointer to the actual data buffer by skipping
1639 // over the cookie completely.
1640 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
1641 CookieSize.getQuantity());
1642}
1643
John McCallb91cd662012-05-01 05:23:51 +00001644llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1645 llvm::Value *allocPtr,
1646 CharUnits cookieSize) {
1647 // The element size is right-justified in the cookie.
1648 llvm::Value *numElementsPtr = allocPtr;
1649 CharUnits numElementsOffset =
1650 cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes);
1651 if (!numElementsOffset.isZero())
1652 numElementsPtr =
1653 CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr,
1654 numElementsOffset.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001655
Micah Villmowea2fea22012-10-25 15:39:14 +00001656 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001657 numElementsPtr =
1658 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001659 if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0)
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001660 return CGF.Builder.CreateLoad(numElementsPtr);
1661 // In asan mode emit a function call instead of a regular load and let the
1662 // run-time deal with it: if the shadow is properly poisoned return the
1663 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
1664 // We can't simply ignore this load using nosanitize metadata because
1665 // the metadata may be lost.
1666 llvm::FunctionType *FTy =
1667 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
1668 llvm::Constant *F =
1669 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
1670 return CGF.Builder.CreateCall(F, numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001671}
1672
John McCallb91cd662012-05-01 05:23:51 +00001673CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001674 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001675 // struct array_cookie {
1676 // std::size_t element_size; // element_size != 0
1677 // std::size_t element_count;
1678 // };
John McCallc19c7062013-01-25 23:36:19 +00001679 // But the base ABI doesn't give anything an alignment greater than
1680 // 8, so we can dismiss this as typical ABI-author blindness to
1681 // actual language complexity and round up to the element alignment.
1682 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1683 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001684}
1685
1686llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
John McCallc19c7062013-01-25 23:36:19 +00001687 llvm::Value *newPtr,
1688 llvm::Value *numElements,
John McCall284c48f2011-01-27 09:37:56 +00001689 const CXXNewExpr *expr,
John McCallc19c7062013-01-25 23:36:19 +00001690 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001691 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001692
John McCallc19c7062013-01-25 23:36:19 +00001693 // NewPtr is a char*, but we generalize to arbitrary addrspaces.
1694 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001695
1696 // The cookie is always at the start of the buffer.
John McCallc19c7062013-01-25 23:36:19 +00001697 llvm::Value *cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001698
1699 // The first element is the element size.
John McCallc19c7062013-01-25 23:36:19 +00001700 cookie = CGF.Builder.CreateBitCast(cookie, CGF.SizeTy->getPointerTo(AS));
1701 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1702 getContext().getTypeSizeInChars(elementType).getQuantity());
1703 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001704
1705 // The second element is the element count.
David Blaikiefb901c7a2015-04-04 15:12:29 +00001706 cookie = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.SizeTy, cookie, 1);
John McCallc19c7062013-01-25 23:36:19 +00001707 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001708
1709 // Finally, compute a pointer to the actual data buffer by skipping
1710 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001711 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
1712 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1713 cookieSize.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001714}
1715
John McCallb91cd662012-05-01 05:23:51 +00001716llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1717 llvm::Value *allocPtr,
1718 CharUnits cookieSize) {
1719 // The number of elements is at offset sizeof(size_t) relative to
1720 // the allocated pointer.
1721 llvm::Value *numElementsPtr
1722 = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes);
John McCall8ed55a52010-09-02 09:58:18 +00001723
Micah Villmowea2fea22012-10-25 15:39:14 +00001724 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001725 numElementsPtr =
1726 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1727 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001728}
1729
John McCall68ff0372010-09-08 01:44:27 +00001730/*********************** Static local initialization **************************/
1731
1732static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001733 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001734 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001735 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001736 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001737 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001738 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001739 llvm::AttributeSet::get(CGM.getLLVMContext(),
1740 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001741 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001742}
1743
1744static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001745 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001746 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001747 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001748 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001749 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001750 llvm::AttributeSet::get(CGM.getLLVMContext(),
1751 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001752 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001753}
1754
1755static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001756 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001757 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001758 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001759 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001760 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001761 llvm::AttributeSet::get(CGM.getLLVMContext(),
1762 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001763 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001764}
1765
1766namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001767 struct CallGuardAbort final : EHScopeStack::Cleanup {
John McCall68ff0372010-09-08 01:44:27 +00001768 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001769 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001770
Craig Topper4f12f102014-03-12 06:41:41 +00001771 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00001772 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1773 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001774 }
1775 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001776}
John McCall68ff0372010-09-08 01:44:27 +00001777
1778/// The ARM code here follows the Itanium code closely enough that we
1779/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001780void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1781 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001782 llvm::GlobalVariable *var,
1783 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00001784 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00001785
Richard Smithdbf74ba2013-04-14 23:01:42 +00001786 // We only need to use thread-safe statics for local non-TLS variables;
John McCallcdf7ef52010-11-06 09:44:32 +00001787 // global initialization is always single-threaded.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001788 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
1789 D.isLocalVarDecl() && !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001790
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001791 // If we have a global variable with internal linkage and thread-safe statics
1792 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00001793 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1794
1795 llvm::IntegerType *guardTy;
John McCall5aa52592011-06-17 07:33:57 +00001796 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00001797 guardTy = CGF.Int8Ty;
John McCall5aa52592011-06-17 07:33:57 +00001798 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00001799 // Guard variables are 64 bits in the generic ABI and size width on ARM
1800 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
Mark Seabornedf0d382013-07-24 16:25:13 +00001801 guardTy = (UseARMGuardVarABI ? CGF.SizeTy : CGF.Int64Ty);
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001802 }
John McCallb88a5662012-03-30 21:00:39 +00001803 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00001804
John McCallb88a5662012-03-30 21:00:39 +00001805 // Create the guard variable if we don't already have it (as we
1806 // might if we're double-emitting this function body).
1807 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1808 if (!guard) {
1809 // Mangle the name for the guard.
1810 SmallString<256> guardName;
1811 {
1812 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00001813 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00001814 }
John McCall8e7cb6d2010-11-02 21:04:24 +00001815
John McCallb88a5662012-03-30 21:00:39 +00001816 // Create the guard variable with a zero-initializer.
1817 // Just absorb linkage and visibility from the guarded variable.
1818 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1819 false, var->getLinkage(),
1820 llvm::ConstantInt::get(guardTy, 0),
1821 guardName.str());
1822 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00001823 // If the variable is thread-local, so is its guard variable.
1824 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCallb88a5662012-03-30 21:00:39 +00001825
Yaron Keren5bfa1082015-09-03 20:33:29 +00001826 // The ABI says: "It is suggested that it be emitted in the same COMDAT
1827 // group as the associated data object." In practice, this doesn't work for
1828 // non-ELF object formats, so only do it for ELF.
Rafael Espindola0d4fb982015-01-12 22:13:53 +00001829 llvm::Comdat *C = var->getComdat();
Yaron Keren5bfa1082015-09-03 20:33:29 +00001830 if (!D.isLocalVarDecl() && C &&
1831 CGM.getTarget().getTriple().isOSBinFormatELF()) {
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001832 guard->setComdat(C);
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001833 CGF.CurFn->setComdat(C);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001834 } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) {
1835 guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName()));
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001836 }
1837
John McCallb88a5662012-03-30 21:00:39 +00001838 CGM.setStaticLocalDeclGuardAddress(&D, guard);
1839 }
John McCall87590e62012-03-30 07:09:50 +00001840
John McCall68ff0372010-09-08 01:44:27 +00001841 // Test whether the variable has completed initialization.
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001842 //
John McCall68ff0372010-09-08 01:44:27 +00001843 // Itanium C++ ABI 3.3.2:
1844 // The following is pseudo-code showing how these functions can be used:
1845 // if (obj_guard.first_byte == 0) {
1846 // if ( __cxa_guard_acquire (&obj_guard) ) {
1847 // try {
1848 // ... initialize the object ...;
1849 // } catch (...) {
1850 // __cxa_guard_abort (&obj_guard);
1851 // throw;
1852 // }
1853 // ... queue object destructor with __cxa_atexit() ...;
1854 // __cxa_guard_release (&obj_guard);
1855 // }
1856 // }
Tim Northovera2ee4332014-03-29 15:09:45 +00001857
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001858 // Load the first byte of the guard variable.
1859 llvm::LoadInst *LI =
John McCallb88a5662012-03-30 21:00:39 +00001860 Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001861 LI->setAlignment(1);
John McCall68ff0372010-09-08 01:44:27 +00001862
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001863 // Itanium ABI:
1864 // An implementation supporting thread-safety on multiprocessor
1865 // systems must also guarantee that references to the initialized
1866 // object do not occur before the load of the initialization flag.
1867 //
1868 // In LLVM, we do this by marking the load Acquire.
1869 if (threadsafe)
1870 LI->setAtomic(llvm::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00001871
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001872 // For ARM, we should only check the first bit, rather than the entire byte:
1873 //
1874 // ARM C++ ABI 3.2.3.1:
1875 // To support the potential use of initialization guard variables
1876 // as semaphores that are the target of ARM SWP and LDREX/STREX
1877 // synchronizing instructions we define a static initialization
1878 // guard variable to be a 4-byte aligned, 4-byte word with the
1879 // following inline access protocol.
1880 // #define INITIALIZED 1
1881 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
1882 // if (__cxa_guard_acquire(&obj_guard))
1883 // ...
1884 // }
1885 //
1886 // and similarly for ARM64:
1887 //
1888 // ARM64 C++ ABI 3.2.2:
1889 // This ABI instead only specifies the value bit 0 of the static guard
1890 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
1891 // variable is not initialized and 1 when it is.
1892 llvm::Value *V =
1893 (UseARMGuardVarABI && !useInt8GuardVariable)
1894 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
1895 : LI;
1896 llvm::Value *isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00001897
1898 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1899 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1900
1901 // Check if the first byte of the guard variable is zero.
John McCallb88a5662012-03-30 21:00:39 +00001902 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall68ff0372010-09-08 01:44:27 +00001903
1904 CGF.EmitBlock(InitCheckBlock);
1905
1906 // Variables used when coping with thread-safe statics and exceptions.
John McCall5aa52592011-06-17 07:33:57 +00001907 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001908 // Call __cxa_guard_acquire.
1909 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00001910 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001911
1912 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1913
1914 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1915 InitBlock, EndBlock);
1916
1917 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00001918 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall68ff0372010-09-08 01:44:27 +00001919
1920 CGF.EmitBlock(InitBlock);
1921 }
1922
1923 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00001924 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00001925
John McCall5aa52592011-06-17 07:33:57 +00001926 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001927 // Pop the guard-abort cleanup if we pushed one.
1928 CGF.PopCleanupBlock();
1929
1930 // Call __cxa_guard_release. This cannot throw.
John McCall882987f2013-02-28 19:01:20 +00001931 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001932 } else {
John McCallb88a5662012-03-30 21:00:39 +00001933 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
John McCall68ff0372010-09-08 01:44:27 +00001934 }
1935
1936 CGF.EmitBlock(EndBlock);
1937}
John McCallc84ed6a2012-05-01 06:13:13 +00001938
1939/// Register a global destructor using __cxa_atexit.
1940static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
1941 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001942 llvm::Constant *addr,
1943 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00001944 const char *Name = "__cxa_atexit";
1945 if (TLS) {
1946 const llvm::Triple &T = CGF.getTarget().getTriple();
1947 Name = T.isMacOSX() ? "_tlv_atexit" : "__cxa_thread_atexit";
1948 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00001949
John McCallc84ed6a2012-05-01 06:13:13 +00001950 // We're assuming that the destructor function is something we can
1951 // reasonably call with the default CC. Go ahead and cast it to the
1952 // right prototype.
1953 llvm::Type *dtorTy =
1954 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
1955
1956 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
1957 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
1958 llvm::FunctionType *atexitTy =
1959 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
1960
1961 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001962 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00001963 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
1964 fn->setDoesNotThrow();
1965
1966 // Create a variable that binds the atexit to this shared object.
1967 llvm::Constant *handle =
1968 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
1969
1970 llvm::Value *args[] = {
1971 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
1972 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
1973 handle
1974 };
John McCall882987f2013-02-28 19:01:20 +00001975 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00001976}
1977
1978/// Register a global destructor as best as we know how.
1979void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001980 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00001981 llvm::Constant *dtor,
1982 llvm::Constant *addr) {
1983 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001984 if (CGM.getCodeGenOpts().CXAAtExit)
1985 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
1986
1987 if (D.getTLSKind())
1988 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00001989
1990 // In Apple kexts, we want to add a global destructor entry.
1991 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00001992 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00001993 // Generate a global destructor entry.
1994 return CGM.AddCXXDtorEntry(dtor, addr);
1995 }
1996
David Blaikieebe87e12013-08-27 23:57:18 +00001997 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00001998}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001999
David Majnemer9b21c332014-07-11 20:28:10 +00002000static bool isThreadWrapperReplaceable(const VarDecl *VD,
2001 CodeGen::CodeGenModule &CGM) {
2002 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
2003 // OS X prefers to have references to thread local variables to go through
2004 // the thread wrapper instead of directly referencing the backing variable.
2005 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
2006 CGM.getTarget().getTriple().isMacOSX();
2007}
2008
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002009/// Get the appropriate linkage for the wrapper function. This is essentially
David Majnemer4632e1e2014-06-27 16:56:27 +00002010/// the weak form of the variable's linkage; every translation unit which needs
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002011/// the wrapper emits a copy, and we want the linker to merge them.
David Majnemer35ab3282014-06-11 04:08:55 +00002012static llvm::GlobalValue::LinkageTypes
2013getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
2014 llvm::GlobalValue::LinkageTypes VarLinkage =
2015 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
2016
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002017 // For internal linkage variables, we don't need an external or weak wrapper.
2018 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
2019 return VarLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00002020
David Majnemer9b21c332014-07-11 20:28:10 +00002021 // If the thread wrapper is replaceable, give it appropriate linkage.
2022 if (isThreadWrapperReplaceable(VD, CGM)) {
2023 if (llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) ||
2024 llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
2025 return llvm::GlobalVariable::WeakAnyLinkage;
2026 return VarLinkage;
2027 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002028 return llvm::GlobalValue::WeakODRLinkage;
2029}
2030
2031llvm::Function *
2032ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +00002033 llvm::Value *Val) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002034 // Mangle the name for the thread_local wrapper function.
2035 SmallString<256> WrapperName;
2036 {
2037 llvm::raw_svector_ostream Out(WrapperName);
2038 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002039 }
2040
Alexander Musmanf94c3182014-09-26 06:28:25 +00002041 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002042 return cast<llvm::Function>(V);
2043
Alexander Musmanf94c3182014-09-26 06:28:25 +00002044 llvm::Type *RetTy = Val->getType();
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002045 if (VD->getType()->isReferenceType())
2046 RetTy = RetTy->getPointerElementType();
2047
2048 llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, false);
David Majnemer35ab3282014-06-11 04:08:55 +00002049 llvm::Function *Wrapper =
2050 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
2051 WrapperName.str(), &CGM.getModule());
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002052 // Always resolve references to the wrapper at link time.
David Majnemer9b21c332014-07-11 20:28:10 +00002053 if (!Wrapper->hasLocalLinkage() && !isThreadWrapperReplaceable(VD, CGM))
Duncan P. N. Exon Smith4434d362014-05-07 22:36:11 +00002054 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002055 return Wrapper;
2056}
2057
2058void ItaniumCXXABI::EmitThreadLocalInitFuncs(
David Majnemerb3341ea2014-10-05 05:05:40 +00002059 CodeGenModule &CGM,
2060 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *>>
2061 CXXThreadLocals, ArrayRef<llvm::Function *> CXXThreadLocalInits,
2062 ArrayRef<llvm::GlobalVariable *> CXXThreadLocalInitVars) {
2063 llvm::Function *InitFunc = nullptr;
2064 if (!CXXThreadLocalInits.empty()) {
2065 // Generate a guarded initialization function.
2066 llvm::FunctionType *FTy =
2067 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
2068 InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init",
Alexey Samsonov1444bb92014-10-17 00:20:19 +00002069 SourceLocation(),
David Majnemerb3341ea2014-10-05 05:05:40 +00002070 /*TLS=*/true);
2071 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
2072 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
2073 llvm::GlobalVariable::InternalLinkage,
2074 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
2075 Guard->setThreadLocal(true);
2076 CodeGenFunction(CGM)
2077 .GenerateCXXGlobalInitFunc(InitFunc, CXXThreadLocalInits, Guard);
2078 }
Yaron Kerenede60302015-08-01 19:11:36 +00002079 for (auto &I : CXXThreadLocals) {
2080 const VarDecl *VD = I.first;
2081 llvm::GlobalVariable *Var = I.second;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002082
David Majnemer9b21c332014-07-11 20:28:10 +00002083 // Some targets require that all access to thread local variables go through
2084 // the thread wrapper. This means that we cannot attempt to create a thread
2085 // wrapper or a thread helper.
2086 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition())
2087 continue;
2088
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002089 // Mangle the name for the thread_local initialization function.
2090 SmallString<256> InitFnName;
2091 {
2092 llvm::raw_svector_ostream Out(InitFnName);
2093 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002094 }
2095
2096 // If we have a definition for the variable, emit the initialization
2097 // function as an alias to the global Init function (if any). Otherwise,
2098 // produce a declaration of the initialization function.
Craig Topper8a13c412014-05-21 05:09:00 +00002099 llvm::GlobalValue *Init = nullptr;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002100 bool InitIsInitFunc = false;
2101 if (VD->hasDefinition()) {
2102 InitIsInitFunc = true;
2103 if (InitFunc)
Rafael Espindola234405b2014-05-17 21:30:14 +00002104 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
2105 InitFunc);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002106 } else {
2107 // Emit a weak global function referring to the initialization function.
2108 // This function will not exist if the TU defining the thread_local
2109 // variable in question does not need any dynamic initialization for
2110 // its thread_local variables.
2111 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
2112 Init = llvm::Function::Create(
2113 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
2114 &CGM.getModule());
2115 }
2116
2117 if (Init)
2118 Init->setVisibility(Var->getVisibility());
2119
2120 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
2121 llvm::LLVMContext &Context = CGM.getModule().getContext();
2122 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
2123 CGBuilderTy Builder(Entry);
2124 if (InitIsInitFunc) {
2125 if (Init)
David Blaikie4ba525b2015-07-14 17:27:39 +00002126 Builder.CreateCall(Init);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002127 } else {
2128 // Don't know whether we have an init function. Call it if it exists.
2129 llvm::Value *Have = Builder.CreateIsNotNull(Init);
2130 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2131 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2132 Builder.CreateCondBr(Have, InitBB, ExitBB);
2133
2134 Builder.SetInsertPoint(InitBB);
David Blaikie4ba525b2015-07-14 17:27:39 +00002135 Builder.CreateCall(Init);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002136 Builder.CreateBr(ExitBB);
2137
2138 Builder.SetInsertPoint(ExitBB);
2139 }
2140
2141 // For a reference, the result of the wrapper function is a pointer to
2142 // the referenced object.
2143 llvm::Value *Val = Var;
2144 if (VD->getType()->isReferenceType()) {
2145 llvm::LoadInst *LI = Builder.CreateLoad(Val);
2146 LI->setAlignment(CGM.getContext().getDeclAlign(VD).getQuantity());
2147 Val = LI;
2148 }
Alexander Musmanf94c3182014-09-26 06:28:25 +00002149 if (Val->getType() != Wrapper->getReturnType())
2150 Val = Builder.CreatePointerBitCastOrAddrSpaceCast(
2151 Val, Wrapper->getReturnType(), "");
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002152 Builder.CreateRet(Val);
2153 }
2154}
2155
Richard Smith0f383742014-03-26 22:48:22 +00002156LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2157 const VarDecl *VD,
2158 QualType LValType) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002159 QualType T = VD->getType();
2160 llvm::Type *Ty = CGF.getTypes().ConvertTypeForMem(T);
2161 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD, Ty);
Alexander Musmanf94c3182014-09-26 06:28:25 +00002162 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002163
David Blaikie4ba525b2015-07-14 17:27:39 +00002164 Val = CGF.Builder.CreateCall(Wrapper);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002165
2166 LValue LV;
2167 if (VD->getType()->isReferenceType())
Richard Smith0f383742014-03-26 22:48:22 +00002168 LV = CGF.MakeNaturalAlignAddrLValue(Val, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002169 else
Richard Smith0f383742014-03-26 22:48:22 +00002170 LV = CGF.MakeAddrLValue(Val, LValType, CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002171 // FIXME: need setObjCGCLValueClass?
2172 return LV;
2173}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002174
2175/// Return whether the given global decl needs a VTT parameter, which it does
2176/// if it's a base constructor or destructor with virtual bases.
2177bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
2178 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
2179
2180 // We don't have any virtual bases, just return early.
2181 if (!MD->getParent()->getNumVBases())
2182 return false;
2183
2184 // Check if we have a base constructor.
2185 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
2186 return true;
2187
2188 // Check if we have a base destructor.
2189 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2190 return true;
2191
2192 return false;
2193}
David Majnemere2cb8d12014-07-07 06:20:47 +00002194
2195namespace {
2196class ItaniumRTTIBuilder {
2197 CodeGenModule &CGM; // Per-module state.
2198 llvm::LLVMContext &VMContext;
2199 const ItaniumCXXABI &CXXABI; // Per-module state.
2200
2201 /// Fields - The fields of the RTTI descriptor currently being built.
2202 SmallVector<llvm::Constant *, 16> Fields;
2203
2204 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2205 llvm::GlobalVariable *
2206 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2207
2208 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2209 /// descriptor of the given type.
2210 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2211
2212 /// BuildVTablePointer - Build the vtable pointer for the given type.
2213 void BuildVTablePointer(const Type *Ty);
2214
2215 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2216 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2217 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2218
2219 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2220 /// classes with bases that do not satisfy the abi::__si_class_type_info
2221 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2222 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2223
2224 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2225 /// for pointer types.
2226 void BuildPointerTypeInfo(QualType PointeeTy);
2227
2228 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2229 /// type_info for an object type.
2230 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2231
2232 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2233 /// struct, used for member pointer types.
2234 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2235
2236public:
2237 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2238 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2239
2240 // Pointer type info flags.
2241 enum {
2242 /// PTI_Const - Type has const qualifier.
2243 PTI_Const = 0x1,
2244
2245 /// PTI_Volatile - Type has volatile qualifier.
2246 PTI_Volatile = 0x2,
2247
2248 /// PTI_Restrict - Type has restrict qualifier.
2249 PTI_Restrict = 0x4,
2250
2251 /// PTI_Incomplete - Type is incomplete.
2252 PTI_Incomplete = 0x8,
2253
2254 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2255 /// (in pointer to member).
2256 PTI_ContainingClassIncomplete = 0x10
2257 };
2258
2259 // VMI type info flags.
2260 enum {
2261 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2262 VMI_NonDiamondRepeat = 0x1,
2263
2264 /// VMI_DiamondShaped - Class is diamond shaped.
2265 VMI_DiamondShaped = 0x2
2266 };
2267
2268 // Base class type info flags.
2269 enum {
2270 /// BCTI_Virtual - Base class is virtual.
2271 BCTI_Virtual = 0x1,
2272
2273 /// BCTI_Public - Base class is public.
2274 BCTI_Public = 0x2
2275 };
2276
2277 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
2278 ///
2279 /// \param Force - true to force the creation of this RTTI value
2280 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false);
2281};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002282}
David Majnemere2cb8d12014-07-07 06:20:47 +00002283
2284llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2285 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002286 SmallString<256> Name;
2287 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002288 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002289
2290 // We know that the mangled name of the type starts at index 4 of the
2291 // mangled name of the typename, so we can just index into it in order to
2292 // get the mangled name of the type.
2293 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2294 Name.substr(4));
2295
2296 llvm::GlobalVariable *GV =
2297 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
2298
2299 GV->setInitializer(Init);
2300
2301 return GV;
2302}
2303
2304llvm::Constant *
2305ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2306 // Mangle the RTTI name.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002307 SmallString<256> Name;
2308 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002309 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002310
2311 // Look for an existing global.
2312 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2313
2314 if (!GV) {
2315 // Create a new global variable.
2316 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2317 /*Constant=*/true,
2318 llvm::GlobalValue::ExternalLinkage, nullptr,
2319 Name);
David Majnemer1fb1a042014-11-07 07:26:38 +00002320 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2321 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2322 if (RD->hasAttr<DLLImportAttr>())
2323 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2324 }
David Majnemere2cb8d12014-07-07 06:20:47 +00002325 }
2326
2327 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2328}
2329
2330/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2331/// info for that type is defined in the standard library.
2332static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2333 // Itanium C++ ABI 2.9.2:
2334 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
2335 // the run-time support library. Specifically, the run-time support
2336 // library should contain type_info objects for the types X, X* and
2337 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2338 // unsigned char, signed char, short, unsigned short, int, unsigned int,
2339 // long, unsigned long, long long, unsigned long long, float, double,
2340 // long double, char16_t, char32_t, and the IEEE 754r decimal and
2341 // half-precision floating point types.
2342 switch (Ty->getKind()) {
2343 case BuiltinType::Void:
2344 case BuiltinType::NullPtr:
2345 case BuiltinType::Bool:
2346 case BuiltinType::WChar_S:
2347 case BuiltinType::WChar_U:
2348 case BuiltinType::Char_U:
2349 case BuiltinType::Char_S:
2350 case BuiltinType::UChar:
2351 case BuiltinType::SChar:
2352 case BuiltinType::Short:
2353 case BuiltinType::UShort:
2354 case BuiltinType::Int:
2355 case BuiltinType::UInt:
2356 case BuiltinType::Long:
2357 case BuiltinType::ULong:
2358 case BuiltinType::LongLong:
2359 case BuiltinType::ULongLong:
2360 case BuiltinType::Half:
2361 case BuiltinType::Float:
2362 case BuiltinType::Double:
2363 case BuiltinType::LongDouble:
2364 case BuiltinType::Char16:
2365 case BuiltinType::Char32:
2366 case BuiltinType::Int128:
2367 case BuiltinType::UInt128:
2368 case BuiltinType::OCLImage1d:
2369 case BuiltinType::OCLImage1dArray:
2370 case BuiltinType::OCLImage1dBuffer:
2371 case BuiltinType::OCLImage2d:
2372 case BuiltinType::OCLImage2dArray:
2373 case BuiltinType::OCLImage3d:
2374 case BuiltinType::OCLSampler:
2375 case BuiltinType::OCLEvent:
2376 return true;
2377
2378 case BuiltinType::Dependent:
2379#define BUILTIN_TYPE(Id, SingletonId)
2380#define PLACEHOLDER_TYPE(Id, SingletonId) \
2381 case BuiltinType::Id:
2382#include "clang/AST/BuiltinTypes.def"
2383 llvm_unreachable("asking for RRTI for a placeholder type!");
2384
2385 case BuiltinType::ObjCId:
2386 case BuiltinType::ObjCClass:
2387 case BuiltinType::ObjCSel:
2388 llvm_unreachable("FIXME: Objective-C types are unsupported!");
2389 }
2390
2391 llvm_unreachable("Invalid BuiltinType Kind!");
2392}
2393
2394static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2395 QualType PointeeTy = PointerTy->getPointeeType();
2396 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2397 if (!BuiltinTy)
2398 return false;
2399
2400 // Check the qualifiers.
2401 Qualifiers Quals = PointeeTy.getQualifiers();
2402 Quals.removeConst();
2403
2404 if (!Quals.empty())
2405 return false;
2406
2407 return TypeInfoIsInStandardLibrary(BuiltinTy);
2408}
2409
2410/// IsStandardLibraryRTTIDescriptor - Returns whether the type
2411/// information for the given type exists in the standard library.
2412static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2413 // Type info for builtin types is defined in the standard library.
2414 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2415 return TypeInfoIsInStandardLibrary(BuiltinTy);
2416
2417 // Type info for some pointer types to builtin types is defined in the
2418 // standard library.
2419 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2420 return TypeInfoIsInStandardLibrary(PointerTy);
2421
2422 return false;
2423}
2424
2425/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
2426/// the given type exists somewhere else, and that we should not emit the type
2427/// information in this translation unit. Assumes that it is not a
2428/// standard-library type.
2429static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
2430 QualType Ty) {
2431 ASTContext &Context = CGM.getContext();
2432
2433 // If RTTI is disabled, assume it might be disabled in the
2434 // translation unit that defines any potential key function, too.
2435 if (!Context.getLangOpts().RTTI) return false;
2436
2437 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2438 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2439 if (!RD->hasDefinition())
2440 return false;
2441
2442 if (!RD->isDynamicClass())
2443 return false;
2444
2445 // FIXME: this may need to be reconsidered if the key function
2446 // changes.
David Majnemerbe9022c2015-08-06 20:56:55 +00002447 // N.B. We must always emit the RTTI data ourselves if there exists a key
2448 // function.
2449 bool IsDLLImport = RD->hasAttr<DLLImportAttr>();
David Majnemer1fb1a042014-11-07 07:26:38 +00002450 if (CGM.getVTables().isVTableExternal(RD))
David Majnemerbe9022c2015-08-06 20:56:55 +00002451 return IsDLLImport ? false : true;
David Majnemer1fb1a042014-11-07 07:26:38 +00002452
David Majnemerbe9022c2015-08-06 20:56:55 +00002453 if (IsDLLImport)
David Majnemer1fb1a042014-11-07 07:26:38 +00002454 return true;
David Majnemere2cb8d12014-07-07 06:20:47 +00002455 }
2456
2457 return false;
2458}
2459
2460/// IsIncompleteClassType - Returns whether the given record type is incomplete.
2461static bool IsIncompleteClassType(const RecordType *RecordTy) {
2462 return !RecordTy->getDecl()->isCompleteDefinition();
2463}
2464
2465/// ContainsIncompleteClassType - Returns whether the given type contains an
2466/// incomplete class type. This is true if
2467///
2468/// * The given type is an incomplete class type.
2469/// * The given type is a pointer type whose pointee type contains an
2470/// incomplete class type.
2471/// * The given type is a member pointer type whose class is an incomplete
2472/// class type.
2473/// * The given type is a member pointer type whoise pointee type contains an
2474/// incomplete class type.
2475/// is an indirect or direct pointer to an incomplete class type.
2476static bool ContainsIncompleteClassType(QualType Ty) {
2477 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2478 if (IsIncompleteClassType(RecordTy))
2479 return true;
2480 }
2481
2482 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2483 return ContainsIncompleteClassType(PointerTy->getPointeeType());
2484
2485 if (const MemberPointerType *MemberPointerTy =
2486 dyn_cast<MemberPointerType>(Ty)) {
2487 // Check if the class type is incomplete.
2488 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
2489 if (IsIncompleteClassType(ClassType))
2490 return true;
2491
2492 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
2493 }
2494
2495 return false;
2496}
2497
2498// CanUseSingleInheritance - Return whether the given record decl has a "single,
2499// public, non-virtual base at offset zero (i.e. the derived class is dynamic
2500// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
2501static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
2502 // Check the number of bases.
2503 if (RD->getNumBases() != 1)
2504 return false;
2505
2506 // Get the base.
2507 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
2508
2509 // Check that the base is not virtual.
2510 if (Base->isVirtual())
2511 return false;
2512
2513 // Check that the base is public.
2514 if (Base->getAccessSpecifier() != AS_public)
2515 return false;
2516
2517 // Check that the class is dynamic iff the base is.
2518 const CXXRecordDecl *BaseDecl =
2519 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2520 if (!BaseDecl->isEmpty() &&
2521 BaseDecl->isDynamicClass() != RD->isDynamicClass())
2522 return false;
2523
2524 return true;
2525}
2526
2527void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
2528 // abi::__class_type_info.
2529 static const char * const ClassTypeInfo =
2530 "_ZTVN10__cxxabiv117__class_type_infoE";
2531 // abi::__si_class_type_info.
2532 static const char * const SIClassTypeInfo =
2533 "_ZTVN10__cxxabiv120__si_class_type_infoE";
2534 // abi::__vmi_class_type_info.
2535 static const char * const VMIClassTypeInfo =
2536 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
2537
2538 const char *VTableName = nullptr;
2539
2540 switch (Ty->getTypeClass()) {
2541#define TYPE(Class, Base)
2542#define ABSTRACT_TYPE(Class, Base)
2543#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2544#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2545#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2546#include "clang/AST/TypeNodes.def"
2547 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2548
2549 case Type::LValueReference:
2550 case Type::RValueReference:
2551 llvm_unreachable("References shouldn't get here");
2552
2553 case Type::Auto:
2554 llvm_unreachable("Undeduced auto type shouldn't get here");
2555
2556 case Type::Builtin:
2557 // GCC treats vector and complex types as fundamental types.
2558 case Type::Vector:
2559 case Type::ExtVector:
2560 case Type::Complex:
2561 case Type::Atomic:
2562 // FIXME: GCC treats block pointers as fundamental types?!
2563 case Type::BlockPointer:
2564 // abi::__fundamental_type_info.
2565 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
2566 break;
2567
2568 case Type::ConstantArray:
2569 case Type::IncompleteArray:
2570 case Type::VariableArray:
2571 // abi::__array_type_info.
2572 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
2573 break;
2574
2575 case Type::FunctionNoProto:
2576 case Type::FunctionProto:
2577 // abi::__function_type_info.
2578 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
2579 break;
2580
2581 case Type::Enum:
2582 // abi::__enum_type_info.
2583 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
2584 break;
2585
2586 case Type::Record: {
2587 const CXXRecordDecl *RD =
2588 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2589
2590 if (!RD->hasDefinition() || !RD->getNumBases()) {
2591 VTableName = ClassTypeInfo;
2592 } else if (CanUseSingleInheritance(RD)) {
2593 VTableName = SIClassTypeInfo;
2594 } else {
2595 VTableName = VMIClassTypeInfo;
2596 }
2597
2598 break;
2599 }
2600
2601 case Type::ObjCObject:
2602 // Ignore protocol qualifiers.
2603 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
2604
2605 // Handle id and Class.
2606 if (isa<BuiltinType>(Ty)) {
2607 VTableName = ClassTypeInfo;
2608 break;
2609 }
2610
2611 assert(isa<ObjCInterfaceType>(Ty));
2612 // Fall through.
2613
2614 case Type::ObjCInterface:
2615 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
2616 VTableName = SIClassTypeInfo;
2617 } else {
2618 VTableName = ClassTypeInfo;
2619 }
2620 break;
2621
2622 case Type::ObjCObjectPointer:
2623 case Type::Pointer:
2624 // abi::__pointer_type_info.
2625 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
2626 break;
2627
2628 case Type::MemberPointer:
2629 // abi::__pointer_to_member_type_info.
2630 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
2631 break;
2632 }
2633
2634 llvm::Constant *VTable =
2635 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
2636
2637 llvm::Type *PtrDiffTy =
2638 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
2639
2640 // The vtable address point is 2.
2641 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00002642 VTable =
2643 llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.Int8PtrTy, VTable, Two);
David Majnemere2cb8d12014-07-07 06:20:47 +00002644 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
2645
2646 Fields.push_back(VTable);
2647}
2648
2649/// \brief Return the linkage that the type info and type info name constants
2650/// should have for the given type.
2651static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
2652 QualType Ty) {
2653 // Itanium C++ ABI 2.9.5p7:
2654 // In addition, it and all of the intermediate abi::__pointer_type_info
2655 // structs in the chain down to the abi::__class_type_info for the
2656 // incomplete class type must be prevented from resolving to the
2657 // corresponding type_info structs for the complete class type, possibly
2658 // by making them local static objects. Finally, a dummy class RTTI is
2659 // generated for the incomplete type that will not resolve to the final
2660 // complete class RTTI (because the latter need not exist), possibly by
2661 // making it a local static object.
2662 if (ContainsIncompleteClassType(Ty))
2663 return llvm::GlobalValue::InternalLinkage;
2664
2665 switch (Ty->getLinkage()) {
2666 case NoLinkage:
2667 case InternalLinkage:
2668 case UniqueExternalLinkage:
2669 return llvm::GlobalValue::InternalLinkage;
2670
2671 case VisibleNoLinkage:
2672 case ExternalLinkage:
2673 if (!CGM.getLangOpts().RTTI) {
2674 // RTTI is not enabled, which means that this type info struct is going
2675 // to be used for exception handling. Give it linkonce_odr linkage.
2676 return llvm::GlobalValue::LinkOnceODRLinkage;
2677 }
2678
2679 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
2680 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2681 if (RD->hasAttr<WeakAttr>())
2682 return llvm::GlobalValue::WeakODRLinkage;
David Majnemerbe9022c2015-08-06 20:56:55 +00002683 if (RD->isDynamicClass()) {
2684 llvm::GlobalValue::LinkageTypes LT = CGM.getVTableLinkage(RD);
2685 // MinGW won't export the RTTI information when there is a key function.
2686 // Make sure we emit our own copy instead of attempting to dllimport it.
2687 if (RD->hasAttr<DLLImportAttr>() &&
2688 llvm::GlobalValue::isAvailableExternallyLinkage(LT))
2689 LT = llvm::GlobalValue::LinkOnceODRLinkage;
2690 return LT;
2691 }
David Majnemere2cb8d12014-07-07 06:20:47 +00002692 }
2693
2694 return llvm::GlobalValue::LinkOnceODRLinkage;
2695 }
2696
2697 llvm_unreachable("Invalid linkage!");
2698}
2699
2700llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force) {
2701 // We want to operate on the canonical type.
2702 Ty = CGM.getContext().getCanonicalType(Ty);
2703
2704 // Check if we've already emitted an RTTI descriptor for this type.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002705 SmallString<256> Name;
2706 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002707 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002708
2709 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
2710 if (OldGV && !OldGV->isDeclaration()) {
2711 assert(!OldGV->hasAvailableExternallyLinkage() &&
2712 "available_externally typeinfos not yet implemented");
2713
2714 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
2715 }
2716
2717 // Check if there is already an external RTTI descriptor for this type.
2718 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
2719 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
2720 return GetAddrOfExternalRTTIDescriptor(Ty);
2721
2722 // Emit the standard library with external linkage.
2723 llvm::GlobalVariable::LinkageTypes Linkage;
2724 if (IsStdLib)
2725 Linkage = llvm::GlobalValue::ExternalLinkage;
2726 else
2727 Linkage = getTypeInfoLinkage(CGM, Ty);
2728
2729 // Add the vtable pointer.
2730 BuildVTablePointer(cast<Type>(Ty));
2731
2732 // And the name.
2733 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
2734 llvm::Constant *TypeNameField;
2735
2736 // If we're supposed to demote the visibility, be sure to set a flag
2737 // to use a string comparison for type_info comparisons.
2738 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
2739 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
2740 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
2741 // The flag is the sign bit, which on ARM64 is defined to be clear
2742 // for global pointers. This is very ARM64-specific.
2743 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
2744 llvm::Constant *flag =
2745 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
2746 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
2747 TypeNameField =
2748 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
2749 } else {
2750 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
2751 }
2752 Fields.push_back(TypeNameField);
2753
2754 switch (Ty->getTypeClass()) {
2755#define TYPE(Class, Base)
2756#define ABSTRACT_TYPE(Class, Base)
2757#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2758#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2759#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2760#include "clang/AST/TypeNodes.def"
2761 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2762
2763 // GCC treats vector types as fundamental types.
2764 case Type::Builtin:
2765 case Type::Vector:
2766 case Type::ExtVector:
2767 case Type::Complex:
2768 case Type::BlockPointer:
2769 // Itanium C++ ABI 2.9.5p4:
2770 // abi::__fundamental_type_info adds no data members to std::type_info.
2771 break;
2772
2773 case Type::LValueReference:
2774 case Type::RValueReference:
2775 llvm_unreachable("References shouldn't get here");
2776
2777 case Type::Auto:
2778 llvm_unreachable("Undeduced auto type shouldn't get here");
2779
2780 case Type::ConstantArray:
2781 case Type::IncompleteArray:
2782 case Type::VariableArray:
2783 // Itanium C++ ABI 2.9.5p5:
2784 // abi::__array_type_info adds no data members to std::type_info.
2785 break;
2786
2787 case Type::FunctionNoProto:
2788 case Type::FunctionProto:
2789 // Itanium C++ ABI 2.9.5p5:
2790 // abi::__function_type_info adds no data members to std::type_info.
2791 break;
2792
2793 case Type::Enum:
2794 // Itanium C++ ABI 2.9.5p5:
2795 // abi::__enum_type_info adds no data members to std::type_info.
2796 break;
2797
2798 case Type::Record: {
2799 const CXXRecordDecl *RD =
2800 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2801 if (!RD->hasDefinition() || !RD->getNumBases()) {
2802 // We don't need to emit any fields.
2803 break;
2804 }
2805
2806 if (CanUseSingleInheritance(RD))
2807 BuildSIClassTypeInfo(RD);
2808 else
2809 BuildVMIClassTypeInfo(RD);
2810
2811 break;
2812 }
2813
2814 case Type::ObjCObject:
2815 case Type::ObjCInterface:
2816 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
2817 break;
2818
2819 case Type::ObjCObjectPointer:
2820 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
2821 break;
2822
2823 case Type::Pointer:
2824 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
2825 break;
2826
2827 case Type::MemberPointer:
2828 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
2829 break;
2830
2831 case Type::Atomic:
2832 // No fields, at least for the moment.
2833 break;
2834 }
2835
2836 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
2837
Rafael Espindolacb92c192015-01-15 23:18:01 +00002838 llvm::Module &M = CGM.getModule();
David Majnemere2cb8d12014-07-07 06:20:47 +00002839 llvm::GlobalVariable *GV =
Rafael Espindolacb92c192015-01-15 23:18:01 +00002840 new llvm::GlobalVariable(M, Init->getType(),
2841 /*Constant=*/true, Linkage, Init, Name);
2842
David Majnemere2cb8d12014-07-07 06:20:47 +00002843 // If there's already an old global variable, replace it with the new one.
2844 if (OldGV) {
2845 GV->takeName(OldGV);
2846 llvm::Constant *NewPtr =
2847 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2848 OldGV->replaceAllUsesWith(NewPtr);
2849 OldGV->eraseFromParent();
2850 }
2851
Yaron Keren04da2382015-07-29 15:42:28 +00002852 if (CGM.supportsCOMDAT() && GV->isWeakForLinker())
2853 GV->setComdat(M.getOrInsertComdat(GV->getName()));
2854
David Majnemere2cb8d12014-07-07 06:20:47 +00002855 // The Itanium ABI specifies that type_info objects must be globally
2856 // unique, with one exception: if the type is an incomplete class
2857 // type or a (possibly indirect) pointer to one. That exception
2858 // affects the general case of comparing type_info objects produced
2859 // by the typeid operator, which is why the comparison operators on
2860 // std::type_info generally use the type_info name pointers instead
2861 // of the object addresses. However, the language's built-in uses
2862 // of RTTI generally require class types to be complete, even when
2863 // manipulating pointers to those class types. This allows the
2864 // implementation of dynamic_cast to rely on address equality tests,
2865 // which is much faster.
2866
2867 // All of this is to say that it's important that both the type_info
2868 // object and the type_info name be uniqued when weakly emitted.
2869
2870 // Give the type_info object and name the formal visibility of the
2871 // type itself.
2872 llvm::GlobalValue::VisibilityTypes llvmVisibility;
2873 if (llvm::GlobalValue::isLocalLinkage(Linkage))
2874 // If the linkage is local, only default visibility makes sense.
2875 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
2876 else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden)
2877 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
2878 else
2879 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
2880 TypeName->setVisibility(llvmVisibility);
2881 GV->setVisibility(llvmVisibility);
2882
2883 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2884}
2885
2886/// ComputeQualifierFlags - Compute the pointer type info flags from the
2887/// given qualifier.
2888static unsigned ComputeQualifierFlags(Qualifiers Quals) {
2889 unsigned Flags = 0;
2890
2891 if (Quals.hasConst())
2892 Flags |= ItaniumRTTIBuilder::PTI_Const;
2893 if (Quals.hasVolatile())
2894 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
2895 if (Quals.hasRestrict())
2896 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
2897
2898 return Flags;
2899}
2900
2901/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
2902/// for the given Objective-C object type.
2903void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
2904 // Drop qualifiers.
2905 const Type *T = OT->getBaseType().getTypePtr();
2906 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
2907
2908 // The builtin types are abi::__class_type_infos and don't require
2909 // extra fields.
2910 if (isa<BuiltinType>(T)) return;
2911
2912 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
2913 ObjCInterfaceDecl *Super = Class->getSuperClass();
2914
2915 // Root classes are also __class_type_info.
2916 if (!Super) return;
2917
2918 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
2919
2920 // Everything else is single inheritance.
2921 llvm::Constant *BaseTypeInfo =
2922 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
2923 Fields.push_back(BaseTypeInfo);
2924}
2925
2926/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2927/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
2928void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
2929 // Itanium C++ ABI 2.9.5p6b:
2930 // It adds to abi::__class_type_info a single member pointing to the
2931 // type_info structure for the base type,
2932 llvm::Constant *BaseTypeInfo =
2933 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
2934 Fields.push_back(BaseTypeInfo);
2935}
2936
2937namespace {
2938 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
2939 /// a class hierarchy.
2940 struct SeenBases {
2941 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
2942 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
2943 };
2944}
2945
2946/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
2947/// abi::__vmi_class_type_info.
2948///
2949static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
2950 SeenBases &Bases) {
2951
2952 unsigned Flags = 0;
2953
2954 const CXXRecordDecl *BaseDecl =
2955 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2956
2957 if (Base->isVirtual()) {
2958 // Mark the virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00002959 if (!Bases.VirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00002960 // If this virtual base has been seen before, then the class is diamond
2961 // shaped.
2962 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
2963 } else {
2964 if (Bases.NonVirtualBases.count(BaseDecl))
2965 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2966 }
2967 } else {
2968 // Mark the non-virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00002969 if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00002970 // If this non-virtual base has been seen before, then the class has non-
2971 // diamond shaped repeated inheritance.
2972 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2973 } else {
2974 if (Bases.VirtualBases.count(BaseDecl))
2975 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2976 }
2977 }
2978
2979 // Walk all bases.
2980 for (const auto &I : BaseDecl->bases())
2981 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
2982
2983 return Flags;
2984}
2985
2986static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
2987 unsigned Flags = 0;
2988 SeenBases Bases;
2989
2990 // Walk all bases.
2991 for (const auto &I : RD->bases())
2992 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
2993
2994 return Flags;
2995}
2996
2997/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2998/// classes with bases that do not satisfy the abi::__si_class_type_info
2999/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
3000void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
3001 llvm::Type *UnsignedIntLTy =
3002 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3003
3004 // Itanium C++ ABI 2.9.5p6c:
3005 // __flags is a word with flags describing details about the class
3006 // structure, which may be referenced by using the __flags_masks
3007 // enumeration. These flags refer to both direct and indirect bases.
3008 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
3009 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3010
3011 // Itanium C++ ABI 2.9.5p6c:
3012 // __base_count is a word with the number of direct proper base class
3013 // descriptions that follow.
3014 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
3015
3016 if (!RD->getNumBases())
3017 return;
3018
3019 llvm::Type *LongLTy =
3020 CGM.getTypes().ConvertType(CGM.getContext().LongTy);
3021
3022 // Now add the base class descriptions.
3023
3024 // Itanium C++ ABI 2.9.5p6c:
3025 // __base_info[] is an array of base class descriptions -- one for every
3026 // direct proper base. Each description is of the type:
3027 //
3028 // struct abi::__base_class_type_info {
3029 // public:
3030 // const __class_type_info *__base_type;
3031 // long __offset_flags;
3032 //
3033 // enum __offset_flags_masks {
3034 // __virtual_mask = 0x1,
3035 // __public_mask = 0x2,
3036 // __offset_shift = 8
3037 // };
3038 // };
3039 for (const auto &Base : RD->bases()) {
3040 // The __base_type member points to the RTTI for the base type.
3041 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
3042
3043 const CXXRecordDecl *BaseDecl =
3044 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
3045
3046 int64_t OffsetFlags = 0;
3047
3048 // All but the lower 8 bits of __offset_flags are a signed offset.
3049 // For a non-virtual base, this is the offset in the object of the base
3050 // subobject. For a virtual base, this is the offset in the virtual table of
3051 // the virtual base offset for the virtual base referenced (negative).
3052 CharUnits Offset;
3053 if (Base.isVirtual())
3054 Offset =
3055 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
3056 else {
3057 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
3058 Offset = Layout.getBaseClassOffset(BaseDecl);
3059 };
3060
3061 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
3062
3063 // The low-order byte of __offset_flags contains flags, as given by the
3064 // masks from the enumeration __offset_flags_masks.
3065 if (Base.isVirtual())
3066 OffsetFlags |= BCTI_Virtual;
3067 if (Base.getAccessSpecifier() == AS_public)
3068 OffsetFlags |= BCTI_Public;
3069
3070 Fields.push_back(llvm::ConstantInt::get(LongLTy, OffsetFlags));
3071 }
3072}
3073
3074/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
3075/// used for pointer types.
3076void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
3077 Qualifiers Quals;
3078 QualType UnqualifiedPointeeTy =
3079 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
3080
3081 // Itanium C++ ABI 2.9.5p7:
3082 // __flags is a flag word describing the cv-qualification and other
3083 // attributes of the type pointed to
3084 unsigned Flags = ComputeQualifierFlags(Quals);
3085
3086 // Itanium C++ ABI 2.9.5p7:
3087 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3088 // incomplete class type, the incomplete target type flag is set.
3089 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
3090 Flags |= PTI_Incomplete;
3091
3092 llvm::Type *UnsignedIntLTy =
3093 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3094 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3095
3096 // Itanium C++ ABI 2.9.5p7:
3097 // __pointee is a pointer to the std::type_info derivation for the
3098 // unqualified type being pointed to.
3099 llvm::Constant *PointeeTypeInfo =
3100 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
3101 Fields.push_back(PointeeTypeInfo);
3102}
3103
3104/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
3105/// struct, used for member pointer types.
3106void
3107ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
3108 QualType PointeeTy = Ty->getPointeeType();
3109
3110 Qualifiers Quals;
3111 QualType UnqualifiedPointeeTy =
3112 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
3113
3114 // Itanium C++ ABI 2.9.5p7:
3115 // __flags is a flag word describing the cv-qualification and other
3116 // attributes of the type pointed to.
3117 unsigned Flags = ComputeQualifierFlags(Quals);
3118
3119 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
3120
3121 // Itanium C++ ABI 2.9.5p7:
3122 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3123 // incomplete class type, the incomplete target type flag is set.
3124 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
3125 Flags |= PTI_Incomplete;
3126
3127 if (IsIncompleteClassType(ClassType))
3128 Flags |= PTI_ContainingClassIncomplete;
3129
3130 llvm::Type *UnsignedIntLTy =
3131 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3132 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3133
3134 // Itanium C++ ABI 2.9.5p7:
3135 // __pointee is a pointer to the std::type_info derivation for the
3136 // unqualified type being pointed to.
3137 llvm::Constant *PointeeTypeInfo =
3138 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
3139 Fields.push_back(PointeeTypeInfo);
3140
3141 // Itanium C++ ABI 2.9.5p9:
3142 // __context is a pointer to an abi::__class_type_info corresponding to the
3143 // class type containing the member pointed to
3144 // (e.g., the "A" in "int A::*").
3145 Fields.push_back(
3146 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
3147}
3148
David Majnemer443250f2015-03-17 20:35:00 +00003149llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003150 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
3151}
3152
3153void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type) {
3154 QualType PointerType = getContext().getPointerType(Type);
3155 QualType PointerTypeConst = getContext().getPointerType(Type.withConst());
3156 ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, true);
3157 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, true);
3158 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, true);
3159}
3160
3161void ItaniumCXXABI::EmitFundamentalRTTIDescriptors() {
3162 QualType FundamentalTypes[] = {
3163 getContext().VoidTy, getContext().NullPtrTy,
3164 getContext().BoolTy, getContext().WCharTy,
3165 getContext().CharTy, getContext().UnsignedCharTy,
3166 getContext().SignedCharTy, getContext().ShortTy,
3167 getContext().UnsignedShortTy, getContext().IntTy,
3168 getContext().UnsignedIntTy, getContext().LongTy,
3169 getContext().UnsignedLongTy, getContext().LongLongTy,
3170 getContext().UnsignedLongLongTy, getContext().HalfTy,
3171 getContext().FloatTy, getContext().DoubleTy,
3172 getContext().LongDoubleTy, getContext().Char16Ty,
3173 getContext().Char32Ty,
3174 };
3175 for (const QualType &FundamentalType : FundamentalTypes)
3176 EmitFundamentalRTTIDescriptor(FundamentalType);
3177}
3178
3179/// What sort of uniqueness rules should we use for the RTTI for the
3180/// given type?
3181ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
3182 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
3183 if (shouldRTTIBeUnique())
3184 return RUK_Unique;
3185
3186 // It's only necessary for linkonce_odr or weak_odr linkage.
3187 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
3188 Linkage != llvm::GlobalValue::WeakODRLinkage)
3189 return RUK_Unique;
3190
3191 // It's only necessary with default visibility.
3192 if (CanTy->getVisibility() != DefaultVisibility)
3193 return RUK_Unique;
3194
3195 // If we're not required to publish this symbol, hide it.
3196 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3197 return RUK_NonUniqueHidden;
3198
3199 // If we're required to publish this symbol, as we might be under an
3200 // explicit instantiation, leave it with default visibility but
3201 // enable string-comparisons.
3202 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
3203 return RUK_NonUniqueVisible;
3204}
Rafael Espindola91f68b42014-09-15 19:20:10 +00003205
Rafael Espindola1e4df922014-09-16 15:18:21 +00003206// Find out how to codegen the complete destructor and constructor
3207namespace {
3208enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
3209}
3210static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
3211 const CXXMethodDecl *MD) {
3212 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
3213 return StructorCodegen::Emit;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003214
Rafael Espindola1e4df922014-09-16 15:18:21 +00003215 // The complete and base structors are not equivalent if there are any virtual
3216 // bases, so emit separate functions.
3217 if (MD->getParent()->getNumVBases())
3218 return StructorCodegen::Emit;
3219
3220 GlobalDecl AliasDecl;
3221 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3222 AliasDecl = GlobalDecl(DD, Dtor_Complete);
3223 } else {
3224 const auto *CD = cast<CXXConstructorDecl>(MD);
3225 AliasDecl = GlobalDecl(CD, Ctor_Complete);
3226 }
3227 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3228
3229 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
3230 return StructorCodegen::RAUW;
3231
3232 // FIXME: Should we allow available_externally aliases?
3233 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
3234 return StructorCodegen::RAUW;
3235
Rafael Espindola0806f982014-09-16 20:19:43 +00003236 if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
3237 // Only ELF supports COMDATs with arbitrary names (C5/D5).
3238 if (CGM.getTarget().getTriple().isOSBinFormatELF())
3239 return StructorCodegen::COMDAT;
3240 return StructorCodegen::Emit;
3241 }
Rafael Espindola1e4df922014-09-16 15:18:21 +00003242
3243 return StructorCodegen::Alias;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003244}
3245
Rafael Espindola1e4df922014-09-16 15:18:21 +00003246static void emitConstructorDestructorAlias(CodeGenModule &CGM,
3247 GlobalDecl AliasDecl,
3248 GlobalDecl TargetDecl) {
3249 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3250
3251 StringRef MangledName = CGM.getMangledName(AliasDecl);
3252 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
3253 if (Entry && !Entry->isDeclaration())
3254 return;
3255
3256 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
3257 llvm::PointerType *AliasType = Aliasee->getType();
3258
3259 // Create the alias with no name.
David Blaikie881b2342015-04-29 21:22:47 +00003260 auto *Alias = llvm::GlobalAlias::create(AliasType, Linkage, "", Aliasee,
3261 &CGM.getModule());
Rafael Espindola1e4df922014-09-16 15:18:21 +00003262
3263 // Switch any previous uses to the alias.
3264 if (Entry) {
3265 assert(Entry->getType() == AliasType &&
3266 "declaration exists with different type");
3267 Alias->takeName(Entry);
3268 Entry->replaceAllUsesWith(Alias);
3269 Entry->eraseFromParent();
3270 } else {
3271 Alias->setName(MangledName);
3272 }
3273
3274 // Finally, set up the alias with its proper name and attributes.
Dario Domiziolic4fb8ca72014-09-19 22:06:24 +00003275 CGM.setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003276}
3277
3278void ItaniumCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
3279 StructorType Type) {
3280 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
3281 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
3282
3283 StructorCodegen CGType = getCodegenToUse(CGM, MD);
3284
3285 if (Type == StructorType::Complete) {
3286 GlobalDecl CompleteDecl;
3287 GlobalDecl BaseDecl;
3288 if (CD) {
3289 CompleteDecl = GlobalDecl(CD, Ctor_Complete);
3290 BaseDecl = GlobalDecl(CD, Ctor_Base);
3291 } else {
3292 CompleteDecl = GlobalDecl(DD, Dtor_Complete);
3293 BaseDecl = GlobalDecl(DD, Dtor_Base);
3294 }
3295
3296 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
3297 emitConstructorDestructorAlias(CGM, CompleteDecl, BaseDecl);
3298 return;
3299 }
3300
3301 if (CGType == StructorCodegen::RAUW) {
3302 StringRef MangledName = CGM.getMangledName(CompleteDecl);
Andrey Bokhankocab58582015-08-31 13:20:44 +00003303 auto *Aliasee = CGM.GetAddrOfGlobal(BaseDecl);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003304 CGM.addReplacement(MangledName, Aliasee);
3305 return;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003306 }
3307 }
3308
3309 // The base destructor is equivalent to the base destructor of its
3310 // base class if there is exactly one non-virtual base class with a
3311 // non-trivial destructor, there are no fields with a non-trivial
3312 // destructor, and the body of the destructor is trivial.
Rafael Espindola1e4df922014-09-16 15:18:21 +00003313 if (DD && Type == StructorType::Base && CGType != StructorCodegen::COMDAT &&
3314 !CGM.TryEmitBaseDestructorAsAlias(DD))
Rafael Espindola91f68b42014-09-15 19:20:10 +00003315 return;
3316
Rafael Espindola1e4df922014-09-16 15:18:21 +00003317 llvm::Function *Fn = CGM.codegenCXXStructor(MD, Type);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003318
Rafael Espindola1e4df922014-09-16 15:18:21 +00003319 if (CGType == StructorCodegen::COMDAT) {
3320 SmallString<256> Buffer;
3321 llvm::raw_svector_ostream Out(Buffer);
3322 if (DD)
3323 getMangleContext().mangleCXXDtorComdat(DD, Out);
3324 else
3325 getMangleContext().mangleCXXCtorComdat(CD, Out);
3326 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
3327 Fn->setComdat(C);
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003328 } else {
3329 CGM.maybeSetTrivialComdat(*MD, *Fn);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003330 }
Rafael Espindola91f68b42014-09-15 19:20:10 +00003331}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003332
3333static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) {
3334 // void *__cxa_begin_catch(void*);
3335 llvm::FunctionType *FTy = llvm::FunctionType::get(
3336 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3337
3338 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
3339}
3340
3341static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) {
3342 // void __cxa_end_catch();
3343 llvm::FunctionType *FTy =
3344 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
3345
3346 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
3347}
3348
3349static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) {
3350 // void *__cxa_get_exception_ptr(void*);
3351 llvm::FunctionType *FTy = llvm::FunctionType::get(
3352 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3353
3354 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
3355}
3356
3357namespace {
3358 /// A cleanup to call __cxa_end_catch. In many cases, the caught
3359 /// exception type lets us state definitively that the thrown exception
3360 /// type does not have a destructor. In particular:
3361 /// - Catch-alls tell us nothing, so we have to conservatively
3362 /// assume that the thrown exception might have a destructor.
3363 /// - Catches by reference behave according to their base types.
3364 /// - Catches of non-record types will only trigger for exceptions
3365 /// of non-record types, which never have destructors.
3366 /// - Catches of record types can trigger for arbitrary subclasses
3367 /// of the caught type, so we have to assume the actual thrown
3368 /// exception type might have a throwing destructor, even if the
3369 /// caught type's destructor is trivial or nothrow.
David Blaikie7e70d682015-08-18 22:40:54 +00003370 struct CallEndCatch final : EHScopeStack::Cleanup {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003371 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
3372 bool MightThrow;
3373
3374 void Emit(CodeGenFunction &CGF, Flags flags) override {
3375 if (!MightThrow) {
3376 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
3377 return;
3378 }
3379
3380 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
3381 }
3382 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003383}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003384
3385/// Emits a call to __cxa_begin_catch and enters a cleanup to call
3386/// __cxa_end_catch.
3387///
3388/// \param EndMightThrow - true if __cxa_end_catch might throw
3389static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
3390 llvm::Value *Exn,
3391 bool EndMightThrow) {
3392 llvm::CallInst *call =
3393 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
3394
3395 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
3396
3397 return call;
3398}
3399
3400/// A "special initializer" callback for initializing a catch
3401/// parameter during catch initialization.
3402static void InitCatchParam(CodeGenFunction &CGF,
3403 const VarDecl &CatchParam,
3404 llvm::Value *ParamAddr,
3405 SourceLocation Loc) {
3406 // Load the exception from where the landing pad saved it.
3407 llvm::Value *Exn = CGF.getExceptionFromSlot();
3408
3409 CanQualType CatchType =
3410 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
3411 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
3412
3413 // If we're catching by reference, we can just cast the object
3414 // pointer to the appropriate pointer.
3415 if (isa<ReferenceType>(CatchType)) {
3416 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
3417 bool EndCatchMightThrow = CaughtType->isRecordType();
3418
3419 // __cxa_begin_catch returns the adjusted object pointer.
3420 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
3421
3422 // We have no way to tell the personality function that we're
3423 // catching by reference, so if we're catching a pointer,
3424 // __cxa_begin_catch will actually return that pointer by value.
3425 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
3426 QualType PointeeType = PT->getPointeeType();
3427
3428 // When catching by reference, generally we should just ignore
3429 // this by-value pointer and use the exception object instead.
3430 if (!PointeeType->isRecordType()) {
3431
3432 // Exn points to the struct _Unwind_Exception header, which
3433 // we have to skip past in order to reach the exception data.
3434 unsigned HeaderSize =
3435 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
3436 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
3437
3438 // However, if we're catching a pointer-to-record type that won't
3439 // work, because the personality function might have adjusted
3440 // the pointer. There's actually no way for us to fully satisfy
3441 // the language/ABI contract here: we can't use Exn because it
3442 // might have the wrong adjustment, but we can't use the by-value
3443 // pointer because it's off by a level of abstraction.
3444 //
3445 // The current solution is to dump the adjusted pointer into an
3446 // alloca, which breaks language semantics (because changing the
3447 // pointer doesn't change the exception) but at least works.
3448 // The better solution would be to filter out non-exact matches
3449 // and rethrow them, but this is tricky because the rethrow
3450 // really needs to be catchable by other sites at this landing
3451 // pad. The best solution is to fix the personality function.
3452 } else {
3453 // Pull the pointer for the reference type off.
3454 llvm::Type *PtrTy =
3455 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
3456
3457 // Create the temporary and write the adjusted pointer into it.
3458 llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
3459 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3460 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
3461
3462 // Bind the reference to the temporary.
3463 AdjustedExn = ExnPtrTmp;
3464 }
3465 }
3466
3467 llvm::Value *ExnCast =
3468 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
3469 CGF.Builder.CreateStore(ExnCast, ParamAddr);
3470 return;
3471 }
3472
3473 // Scalars and complexes.
3474 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
3475 if (TEK != TEK_Aggregate) {
3476 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
3477
3478 // If the catch type is a pointer type, __cxa_begin_catch returns
3479 // the pointer by value.
3480 if (CatchType->hasPointerRepresentation()) {
3481 llvm::Value *CastExn =
3482 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
3483
3484 switch (CatchType.getQualifiers().getObjCLifetime()) {
3485 case Qualifiers::OCL_Strong:
3486 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
3487 // fallthrough
3488
3489 case Qualifiers::OCL_None:
3490 case Qualifiers::OCL_ExplicitNone:
3491 case Qualifiers::OCL_Autoreleasing:
3492 CGF.Builder.CreateStore(CastExn, ParamAddr);
3493 return;
3494
3495 case Qualifiers::OCL_Weak:
3496 CGF.EmitARCInitWeak(ParamAddr, CastExn);
3497 return;
3498 }
3499 llvm_unreachable("bad ownership qualifier!");
3500 }
3501
3502 // Otherwise, it returns a pointer into the exception object.
3503
3504 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3505 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3506
3507 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
3508 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType,
3509 CGF.getContext().getDeclAlign(&CatchParam));
3510 switch (TEK) {
3511 case TEK_Complex:
3512 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
3513 /*init*/ true);
3514 return;
3515 case TEK_Scalar: {
3516 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
3517 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
3518 return;
3519 }
3520 case TEK_Aggregate:
3521 llvm_unreachable("evaluation kind filtered out!");
3522 }
3523 llvm_unreachable("bad evaluation kind");
3524 }
3525
3526 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
3527
3528 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3529
3530 // Check for a copy expression. If we don't have a copy expression,
3531 // that means a trivial copy is okay.
3532 const Expr *copyExpr = CatchParam.getInit();
3533 if (!copyExpr) {
3534 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
3535 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
3536 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
3537 return;
3538 }
3539
3540 // We have to call __cxa_get_exception_ptr to get the adjusted
3541 // pointer before copying.
3542 llvm::CallInst *rawAdjustedExn =
3543 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
3544
3545 // Cast that to the appropriate type.
3546 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
3547
3548 // The copy expression is defined in terms of an OpaqueValueExpr.
3549 // Find it and map it to the adjusted expression.
3550 CodeGenFunction::OpaqueValueMapping
3551 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
3552 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
3553
3554 // Call the copy ctor in a terminate scope.
3555 CGF.EHStack.pushTerminate();
3556
3557 // Perform the copy construction.
3558 CharUnits Alignment = CGF.getContext().getDeclAlign(&CatchParam);
3559 CGF.EmitAggExpr(copyExpr,
3560 AggValueSlot::forAddr(ParamAddr, Alignment, Qualifiers(),
3561 AggValueSlot::IsNotDestructed,
3562 AggValueSlot::DoesNotNeedGCBarriers,
3563 AggValueSlot::IsNotAliased));
3564
3565 // Leave the terminate scope.
3566 CGF.EHStack.popTerminate();
3567
3568 // Undo the opaque value mapping.
3569 opaque.pop();
3570
3571 // Finally we can call __cxa_begin_catch.
3572 CallBeginCatch(CGF, Exn, true);
3573}
3574
3575/// Begins a catch statement by initializing the catch variable and
3576/// calling __cxa_begin_catch.
3577void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF,
3578 const CXXCatchStmt *S) {
3579 // We have to be very careful with the ordering of cleanups here:
3580 // C++ [except.throw]p4:
3581 // The destruction [of the exception temporary] occurs
3582 // immediately after the destruction of the object declared in
3583 // the exception-declaration in the handler.
3584 //
3585 // So the precise ordering is:
3586 // 1. Construct catch variable.
3587 // 2. __cxa_begin_catch
3588 // 3. Enter __cxa_end_catch cleanup
3589 // 4. Enter dtor cleanup
3590 //
3591 // We do this by using a slightly abnormal initialization process.
3592 // Delegation sequence:
3593 // - ExitCXXTryStmt opens a RunCleanupsScope
3594 // - EmitAutoVarAlloca creates the variable and debug info
3595 // - InitCatchParam initializes the variable from the exception
3596 // - CallBeginCatch calls __cxa_begin_catch
3597 // - CallBeginCatch enters the __cxa_end_catch cleanup
3598 // - EmitAutoVarCleanups enters the variable destructor cleanup
3599 // - EmitCXXTryStmt emits the code for the catch body
3600 // - EmitCXXTryStmt close the RunCleanupsScope
3601
3602 VarDecl *CatchParam = S->getExceptionDecl();
3603 if (!CatchParam) {
3604 llvm::Value *Exn = CGF.getExceptionFromSlot();
3605 CallBeginCatch(CGF, Exn, true);
3606 return;
3607 }
3608
3609 // Emit the local.
3610 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
3611 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
3612 CGF.EmitAutoVarCleanups(var);
3613}
3614
3615/// Get or define the following function:
3616/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
3617/// This code is used only in C++.
3618static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
3619 llvm::FunctionType *fnTy =
3620 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3621 llvm::Constant *fnRef =
3622 CGM.CreateRuntimeFunction(fnTy, "__clang_call_terminate");
3623
3624 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
3625 if (fn && fn->empty()) {
3626 fn->setDoesNotThrow();
3627 fn->setDoesNotReturn();
3628
3629 // What we really want is to massively penalize inlining without
3630 // forbidding it completely. The difference between that and
3631 // 'noinline' is negligible.
3632 fn->addFnAttr(llvm::Attribute::NoInline);
3633
3634 // Allow this function to be shared across translation units, but
3635 // we don't want it to turn into an exported symbol.
3636 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
3637 fn->setVisibility(llvm::Function::HiddenVisibility);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00003638 if (CGM.supportsCOMDAT())
3639 fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003640
3641 // Set up the function.
3642 llvm::BasicBlock *entry =
3643 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
3644 CGBuilderTy builder(entry);
3645
3646 // Pull the exception pointer out of the parameter list.
3647 llvm::Value *exn = &*fn->arg_begin();
3648
3649 // Call __cxa_begin_catch(exn).
3650 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
3651 catchCall->setDoesNotThrow();
3652 catchCall->setCallingConv(CGM.getRuntimeCC());
3653
3654 // Call std::terminate().
David Blaikie4ba525b2015-07-14 17:27:39 +00003655 llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn());
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003656 termCall->setDoesNotThrow();
3657 termCall->setDoesNotReturn();
3658 termCall->setCallingConv(CGM.getRuntimeCC());
3659
3660 // std::terminate cannot return.
3661 builder.CreateUnreachable();
3662 }
3663
3664 return fnRef;
3665}
3666
3667llvm::CallInst *
3668ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
3669 llvm::Value *Exn) {
3670 // In C++, we want to call __cxa_begin_catch() before terminating.
3671 if (Exn) {
3672 assert(CGF.CGM.getLangOpts().CPlusPlus);
3673 return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn);
3674 }
3675 return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
3676}