blob: 55814b455bbf67f425b168767a7d266f8d37a816 [file] [log] [blame]
Charles Davis3a811f12010-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 Lattnerfc8f0e12011-04-15 05:22:18 +000010// This provides C++ code generation targeting the Itanium C++ ABI. The class
Charles Davis3a811f12010-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 McCallee79a4c2010-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 Davis3a811f12010-05-25 19:52:27 +000019//===----------------------------------------------------------------------===//
20
21#include "CGCXXABI.h"
John McCall0bab0cd2010-08-23 01:21:21 +000022#include "CGRecordLayout.h"
Charles Davis9ee494f2012-06-23 23:44:00 +000023#include "CGVTables.h"
John McCall93d557b2010-08-22 00:05:51 +000024#include "CodeGenFunction.h"
Charles Davis3a811f12010-05-25 19:52:27 +000025#include "CodeGenModule.h"
Craig Topperba77cb92012-09-15 18:47:51 +000026#include "clang/AST/Mangle.h"
27#include "clang/AST/Type.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000028#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/Intrinsics.h"
30#include "llvm/IR/Value.h"
Charles Davis3a811f12010-05-25 19:52:27 +000031
32using namespace clang;
John McCall93d557b2010-08-22 00:05:51 +000033using namespace CodeGen;
Charles Davis3a811f12010-05-25 19:52:27 +000034
35namespace {
Charles Davis071cc7d2010-08-16 03:33:14 +000036class ItaniumCXXABI : public CodeGen::CGCXXABI {
John McCall93d557b2010-08-22 00:05:51 +000037protected:
John McCallbabc9a92010-08-22 00:59:17 +000038 bool IsARM;
John McCall0bab0cd2010-08-23 01:21:21 +000039
Charles Davis3a811f12010-05-25 19:52:27 +000040public:
John McCallbabc9a92010-08-22 00:59:17 +000041 ItaniumCXXABI(CodeGen::CodeGenModule &CGM, bool IsARM = false) :
Reid Kleckner92e44d92013-03-22 16:13:10 +000042 CGCXXABI(CGM), IsARM(IsARM) { }
John McCall93d557b2010-08-22 00:05:51 +000043
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000044 bool isReturnTypeIndirect(const CXXRecordDecl *RD) const {
45 // Structures with either a non-trivial destructor or a non-trivial
46 // copy constructor are always indirect.
47 return !RD->hasTrivialDestructor() || RD->hasNonTrivialCopyConstructor();
48 }
49
50 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const {
51 // Structures with either a non-trivial destructor or a non-trivial
52 // copy constructor are always indirect.
53 if (!RD->hasTrivialDestructor() || RD->hasNonTrivialCopyConstructor())
54 return RAA_Indirect;
55 return RAA_Default;
56 }
57
John McCallf16aa102010-08-22 21:01:12 +000058 bool isZeroInitializable(const MemberPointerType *MPT);
John McCallcf2c85e2010-08-22 04:16:24 +000059
Chris Lattner9cbe4f02011-07-09 17:41:47 +000060 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT);
John McCall0bab0cd2010-08-23 01:21:21 +000061
John McCall93d557b2010-08-22 00:05:51 +000062 llvm::Value *EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
63 llvm::Value *&This,
64 llvm::Value *MemFnPtr,
65 const MemberPointerType *MPT);
John McCall3023def2010-08-22 03:04:22 +000066
John McCall6c2ab1d2010-08-31 21:07:20 +000067 llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF,
68 llvm::Value *Base,
69 llvm::Value *MemPtr,
70 const MemberPointerType *MPT);
71
John McCall0bab0cd2010-08-23 01:21:21 +000072 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
73 const CastExpr *E,
74 llvm::Value *Src);
John McCall4d4e5c12012-02-15 01:22:51 +000075 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
76 llvm::Constant *Src);
John McCallcf2c85e2010-08-22 04:16:24 +000077
John McCall0bab0cd2010-08-23 01:21:21 +000078 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
John McCallcf2c85e2010-08-22 04:16:24 +000079
John McCall755d8492011-04-12 00:42:48 +000080 llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
John McCall5808ce42011-02-03 08:15:49 +000081 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
82 CharUnits offset);
Richard Smith2d6a5672012-01-14 04:30:29 +000083 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
84 llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
85 CharUnits ThisAdjustment);
John McCall875ab102010-08-22 06:43:33 +000086
John McCall0bab0cd2010-08-23 01:21:21 +000087 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
88 llvm::Value *L,
89 llvm::Value *R,
90 const MemberPointerType *MPT,
91 bool Inequality);
John McCalle9fd7eb2010-08-22 08:30:07 +000092
John McCall0bab0cd2010-08-23 01:21:21 +000093 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
94 llvm::Value *Addr,
95 const MemberPointerType *MPT);
John McCall4c40d982010-08-31 07:33:07 +000096
John McCallecd03b42012-09-25 10:10:39 +000097 llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF,
98 llvm::Value *ptr,
99 QualType type);
100
Reid Klecknerb0f533e2013-05-29 18:02:47 +0000101 llvm::Value *GetVirtualBaseClassOffset(CodeGenFunction &CGF,
102 llvm::Value *This,
103 const CXXRecordDecl *ClassDecl,
104 const CXXRecordDecl *BaseClassDecl);
105
John McCall4c40d982010-08-31 07:33:07 +0000106 void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
107 CXXCtorType T,
108 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000109 SmallVectorImpl<CanQualType> &ArgTys);
John McCall4c40d982010-08-31 07:33:07 +0000110
111 void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
112 CXXDtorType T,
113 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000114 SmallVectorImpl<CanQualType> &ArgTys);
John McCall4c40d982010-08-31 07:33:07 +0000115
Reid Klecknera4130ba2013-07-22 13:51:44 +0000116 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
117 CXXDtorType DT) const {
118 // Itanium does not emit any destructor variant as an inline thunk.
119 // Delegating may occur as an optimization, but all variants are either
120 // emitted with external linkage or as linkonce if they are inline and used.
121 return false;
122 }
123
124 void EmitCXXDestructors(const CXXDestructorDecl *D);
125
John McCall4c40d982010-08-31 07:33:07 +0000126 void BuildInstanceFunctionParams(CodeGenFunction &CGF,
127 QualType &ResTy,
128 FunctionArgList &Params);
129
130 void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
John McCall1e7fe752010-09-02 09:58:18 +0000131
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000132 void EmitConstructorCall(CodeGenFunction &CGF,
133 const CXXConstructorDecl *D, CXXCtorType Type,
134 bool ForVirtualBase, bool Delegating,
Stephen Lin4444dbb2013-06-19 18:10:35 +0000135 llvm::Value *This,
136 CallExpr::const_arg_iterator ArgBeg,
137 CallExpr::const_arg_iterator ArgEnd);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000138
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000139 void EmitVirtualDestructorCall(CodeGenFunction &CGF,
140 const CXXDestructorDecl *Dtor,
141 CXXDtorType DtorType, SourceLocation CallLoc,
142 llvm::Value *This);
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000143
Reid Kleckner90633022013-06-19 15:20:38 +0000144 void EmitVirtualInheritanceTables(llvm::GlobalVariable::LinkageTypes Linkage,
145 const CXXRecordDecl *RD);
146
Joao Matos285baac2012-07-17 17:10:11 +0000147 StringRef GetPureVirtualCallName() { return "__cxa_pure_virtual"; }
David Blaikie2eb9a952012-10-16 22:56:05 +0000148 StringRef GetDeletedVirtualCallName() { return "__cxa_deleted_virtual"; }
Joao Matos285baac2012-07-17 17:10:11 +0000149
John McCalle2b45e22012-05-01 05:23:51 +0000150 CharUnits getArrayCookieSizeImpl(QualType elementType);
John McCall1e7fe752010-09-02 09:58:18 +0000151 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
152 llvm::Value *NewPtr,
153 llvm::Value *NumElements,
John McCall6ec278d2011-01-27 09:37:56 +0000154 const CXXNewExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000155 QualType ElementType);
John McCalle2b45e22012-05-01 05:23:51 +0000156 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
157 llvm::Value *allocPtr,
158 CharUnits cookieSize);
John McCall5cd91b52010-09-08 01:44:27 +0000159
John McCall3030eb82010-11-06 09:44:32 +0000160 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Chandler Carruth0f30a122012-03-30 19:44:53 +0000161 llvm::GlobalVariable *DeclPtr, bool PerformInit);
Richard Smith04e51762013-04-14 23:01:42 +0000162 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
163 llvm::Constant *dtor, llvm::Constant *addr);
Richard Smithb80a16e2013-04-19 16:42:07 +0000164
165 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
166 llvm::GlobalVariable *Var);
167 void EmitThreadLocalInitFuncs(
168 llvm::ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
169 llvm::Function *InitFunc);
170 LValue EmitThreadLocalDeclRefExpr(CodeGenFunction &CGF,
171 const DeclRefExpr *DRE);
Peter Collingbournee1e35f72013-06-28 20:45:28 +0000172
173 bool NeedsVTTParameter(GlobalDecl GD);
Charles Davis3a811f12010-05-25 19:52:27 +0000174};
John McCallee79a4c2010-08-21 22:46:04 +0000175
176class ARMCXXABI : public ItaniumCXXABI {
177public:
John McCallbabc9a92010-08-22 00:59:17 +0000178 ARMCXXABI(CodeGen::CodeGenModule &CGM) : ItaniumCXXABI(CGM, /*ARM*/ true) {}
John McCall4c40d982010-08-31 07:33:07 +0000179
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000180 bool HasThisReturn(GlobalDecl GD) const {
181 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
182 isa<CXXDestructorDecl>(GD.getDecl()) &&
183 GD.getDtorType() != Dtor_Deleting));
184 }
John McCall4c40d982010-08-31 07:33:07 +0000185
186 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV, QualType ResTy);
187
John McCalle2b45e22012-05-01 05:23:51 +0000188 CharUnits getArrayCookieSizeImpl(QualType elementType);
John McCall1e7fe752010-09-02 09:58:18 +0000189 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
190 llvm::Value *NewPtr,
191 llvm::Value *NumElements,
John McCall6ec278d2011-01-27 09:37:56 +0000192 const CXXNewExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000193 QualType ElementType);
John McCalle2b45e22012-05-01 05:23:51 +0000194 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *allocPtr,
195 CharUnits cookieSize);
John McCallee79a4c2010-08-21 22:46:04 +0000196};
Charles Davis3a811f12010-05-25 19:52:27 +0000197}
198
Charles Davis071cc7d2010-08-16 03:33:14 +0000199CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCall64aa4b32013-04-16 22:48:15 +0000200 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall96fcde02013-01-25 23:36:14 +0000201 // For IR-generation purposes, there's no significant difference
202 // between the ARM and iOS ABIs.
203 case TargetCXXABI::GenericARM:
204 case TargetCXXABI::iOS:
205 return new ARMCXXABI(CGM);
Charles Davis3a811f12010-05-25 19:52:27 +0000206
Tim Northoverc264e162013-01-31 12:13:10 +0000207 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
208 // include the other 32-bit ARM oddities: constructor/destructor return values
209 // and array cookies.
210 case TargetCXXABI::GenericAArch64:
211 return new ItaniumCXXABI(CGM, /*IsARM = */ true);
212
John McCall96fcde02013-01-25 23:36:14 +0000213 case TargetCXXABI::GenericItanium:
214 return new ItaniumCXXABI(CGM);
215
216 case TargetCXXABI::Microsoft:
217 llvm_unreachable("Microsoft ABI is not Itanium-based");
218 }
219 llvm_unreachable("bad ABI kind");
John McCallee79a4c2010-08-21 22:46:04 +0000220}
221
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000222llvm::Type *
John McCall0bab0cd2010-08-23 01:21:21 +0000223ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
224 if (MPT->isMemberDataPointer())
Reid Kleckner92e44d92013-03-22 16:13:10 +0000225 return CGM.PtrDiffTy;
226 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, NULL);
John McCall875ab102010-08-22 06:43:33 +0000227}
228
John McCallbabc9a92010-08-22 00:59:17 +0000229/// In the Itanium and ARM ABIs, method pointers have the form:
230/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
231///
232/// In the Itanium ABI:
233/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
234/// - the this-adjustment is (memptr.adj)
235/// - the virtual offset is (memptr.ptr - 1)
236///
237/// In the ARM ABI:
238/// - method pointers are virtual if (memptr.adj & 1) is nonzero
239/// - the this-adjustment is (memptr.adj >> 1)
240/// - the virtual offset is (memptr.ptr)
241/// ARM uses 'adj' for the virtual flag because Thumb functions
242/// may be only single-byte aligned.
243///
244/// If the member is virtual, the adjusted 'this' pointer points
245/// to a vtable pointer from which the virtual offset is applied.
246///
247/// If the member is non-virtual, memptr.ptr is the address of
248/// the function to call.
John McCall93d557b2010-08-22 00:05:51 +0000249llvm::Value *
250ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
251 llvm::Value *&This,
252 llvm::Value *MemFnPtr,
253 const MemberPointerType *MPT) {
254 CGBuilderTy &Builder = CGF.Builder;
255
256 const FunctionProtoType *FPT =
257 MPT->getPointeeType()->getAs<FunctionProtoType>();
258 const CXXRecordDecl *RD =
259 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
260
Chris Lattner2acc6e32011-07-18 04:24:23 +0000261 llvm::FunctionType *FTy =
John McCallde5d3c72012-02-17 03:33:10 +0000262 CGM.getTypes().GetFunctionType(
263 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
John McCall93d557b2010-08-22 00:05:51 +0000264
Reid Kleckner92e44d92013-03-22 16:13:10 +0000265 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall93d557b2010-08-22 00:05:51 +0000266
John McCallbabc9a92010-08-22 00:59:17 +0000267 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
268 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
269 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
270
John McCalld608cdb2010-08-22 10:59:02 +0000271 // Extract memptr.adj, which is in the second field.
272 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCallbabc9a92010-08-22 00:59:17 +0000273
274 // Compute the true adjustment.
275 llvm::Value *Adj = RawAdj;
276 if (IsARM)
277 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall93d557b2010-08-22 00:05:51 +0000278
279 // Apply the adjustment and cast back to the original struct type
280 // for consistency.
John McCallbabc9a92010-08-22 00:59:17 +0000281 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
282 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
283 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall93d557b2010-08-22 00:05:51 +0000284
285 // Load the function pointer.
John McCalld608cdb2010-08-22 10:59:02 +0000286 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall93d557b2010-08-22 00:05:51 +0000287
288 // If the LSB in the function pointer is 1, the function pointer points to
289 // a virtual function.
John McCallbabc9a92010-08-22 00:59:17 +0000290 llvm::Value *IsVirtual;
291 if (IsARM)
292 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
293 else
294 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
295 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall93d557b2010-08-22 00:05:51 +0000296 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
297
298 // In the virtual path, the adjustment left 'This' pointing to the
299 // vtable of the correct base subobject. The "function pointer" is an
John McCallbabc9a92010-08-22 00:59:17 +0000300 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall93d557b2010-08-22 00:05:51 +0000301 CGF.EmitBlock(FnVirtual);
302
303 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000304 llvm::Type *VTableTy = Builder.getInt8PtrTy();
John McCall93d557b2010-08-22 00:05:51 +0000305 llvm::Value *VTable = Builder.CreateBitCast(This, VTableTy->getPointerTo());
John McCallbabc9a92010-08-22 00:59:17 +0000306 VTable = Builder.CreateLoad(VTable, "memptr.vtable");
John McCall93d557b2010-08-22 00:05:51 +0000307
308 // Apply the offset.
John McCallbabc9a92010-08-22 00:59:17 +0000309 llvm::Value *VTableOffset = FnAsInt;
310 if (!IsARM) VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
311 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall93d557b2010-08-22 00:05:51 +0000312
313 // Load the virtual function to call.
314 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCallbabc9a92010-08-22 00:59:17 +0000315 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
John McCall93d557b2010-08-22 00:05:51 +0000316 CGF.EmitBranch(FnEnd);
317
318 // In the non-virtual path, the function pointer is actually a
319 // function pointer.
320 CGF.EmitBlock(FnNonVirtual);
321 llvm::Value *NonVirtualFn =
John McCallbabc9a92010-08-22 00:59:17 +0000322 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall93d557b2010-08-22 00:05:51 +0000323
324 // We're done.
325 CGF.EmitBlock(FnEnd);
Jay Foadbbf3bac2011-03-30 11:28:58 +0000326 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
John McCall93d557b2010-08-22 00:05:51 +0000327 Callee->addIncoming(VirtualFn, FnVirtual);
328 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
329 return Callee;
330}
John McCall3023def2010-08-22 03:04:22 +0000331
John McCall6c2ab1d2010-08-31 21:07:20 +0000332/// Compute an l-value by applying the given pointer-to-member to a
333/// base object.
334llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF,
335 llvm::Value *Base,
336 llvm::Value *MemPtr,
337 const MemberPointerType *MPT) {
Reid Kleckner92e44d92013-03-22 16:13:10 +0000338 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall6c2ab1d2010-08-31 21:07:20 +0000339
340 CGBuilderTy &Builder = CGF.Builder;
341
Micah Villmow956a5a12012-10-25 15:39:14 +0000342 unsigned AS = Base->getType()->getPointerAddressSpace();
John McCall6c2ab1d2010-08-31 21:07:20 +0000343
344 // Cast to char*.
345 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
346
347 // Apply the offset, which we assume is non-null.
348 llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
349
350 // Cast the address to the appropriate pointer type, adopting the
351 // address space of the base pointer.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000352 llvm::Type *PType
Douglas Gregoreede61a2010-09-02 17:38:50 +0000353 = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
John McCall6c2ab1d2010-08-31 21:07:20 +0000354 return Builder.CreateBitCast(Addr, PType);
355}
356
John McCall4d4e5c12012-02-15 01:22:51 +0000357/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
358/// conversion.
359///
360/// Bitcast conversions are always a no-op under Itanium.
John McCall0bab0cd2010-08-23 01:21:21 +0000361///
362/// Obligatory offset/adjustment diagram:
363/// <-- offset --> <-- adjustment -->
364/// |--------------------------|----------------------|--------------------|
365/// ^Derived address point ^Base address point ^Member address point
366///
367/// So when converting a base member pointer to a derived member pointer,
368/// we add the offset to the adjustment because the address point has
369/// decreased; and conversely, when converting a derived MP to a base MP
370/// we subtract the offset from the adjustment because the address point
371/// has increased.
372///
373/// The standard forbids (at compile time) conversion to and from
374/// virtual bases, which is why we don't have to consider them here.
375///
376/// The standard forbids (at run time) casting a derived MP to a base
377/// MP when the derived MP does not point to a member of the base.
378/// This is why -1 is a reasonable choice for null data member
379/// pointers.
John McCalld608cdb2010-08-22 10:59:02 +0000380llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000381ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
382 const CastExpr *E,
John McCall4d4e5c12012-02-15 01:22:51 +0000383 llvm::Value *src) {
John McCall2de56d12010-08-25 11:45:40 +0000384 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCall4d4e5c12012-02-15 01:22:51 +0000385 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
386 E->getCastKind() == CK_ReinterpretMemberPointer);
387
388 // Under Itanium, reinterprets don't require any additional processing.
389 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
390
391 // Use constant emission if we can.
392 if (isa<llvm::Constant>(src))
393 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
394
395 llvm::Constant *adj = getMemberPointerAdjustment(E);
396 if (!adj) return src;
John McCall3023def2010-08-22 03:04:22 +0000397
398 CGBuilderTy &Builder = CGF.Builder;
John McCall4d4e5c12012-02-15 01:22:51 +0000399 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCall3023def2010-08-22 03:04:22 +0000400
John McCall4d4e5c12012-02-15 01:22:51 +0000401 const MemberPointerType *destTy =
402 E->getType()->castAs<MemberPointerType>();
John McCall875ab102010-08-22 06:43:33 +0000403
John McCall0bab0cd2010-08-23 01:21:21 +0000404 // For member data pointers, this is just a matter of adding the
405 // offset if the source is non-null.
John McCall4d4e5c12012-02-15 01:22:51 +0000406 if (destTy->isMemberDataPointer()) {
407 llvm::Value *dst;
408 if (isDerivedToBase)
409 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall0bab0cd2010-08-23 01:21:21 +0000410 else
John McCall4d4e5c12012-02-15 01:22:51 +0000411 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall0bab0cd2010-08-23 01:21:21 +0000412
413 // Null check.
John McCall4d4e5c12012-02-15 01:22:51 +0000414 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
415 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
416 return Builder.CreateSelect(isNull, src, dst);
John McCall0bab0cd2010-08-23 01:21:21 +0000417 }
418
John McCalld608cdb2010-08-22 10:59:02 +0000419 // The this-adjustment is left-shifted by 1 on ARM.
420 if (IsARM) {
John McCall4d4e5c12012-02-15 01:22:51 +0000421 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
422 offset <<= 1;
423 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalld608cdb2010-08-22 10:59:02 +0000424 }
425
John McCall4d4e5c12012-02-15 01:22:51 +0000426 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
427 llvm::Value *dstAdj;
428 if (isDerivedToBase)
429 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalld608cdb2010-08-22 10:59:02 +0000430 else
John McCall4d4e5c12012-02-15 01:22:51 +0000431 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalld608cdb2010-08-22 10:59:02 +0000432
John McCall4d4e5c12012-02-15 01:22:51 +0000433 return Builder.CreateInsertValue(src, dstAdj, 1);
434}
435
436llvm::Constant *
437ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
438 llvm::Constant *src) {
439 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
440 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
441 E->getCastKind() == CK_ReinterpretMemberPointer);
442
443 // Under Itanium, reinterprets don't require any additional processing.
444 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
445
446 // If the adjustment is trivial, we don't need to do anything.
447 llvm::Constant *adj = getMemberPointerAdjustment(E);
448 if (!adj) return src;
449
450 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
451
452 const MemberPointerType *destTy =
453 E->getType()->castAs<MemberPointerType>();
454
455 // For member data pointers, this is just a matter of adding the
456 // offset if the source is non-null.
457 if (destTy->isMemberDataPointer()) {
458 // null maps to null.
459 if (src->isAllOnesValue()) return src;
460
461 if (isDerivedToBase)
462 return llvm::ConstantExpr::getNSWSub(src, adj);
463 else
464 return llvm::ConstantExpr::getNSWAdd(src, adj);
465 }
466
467 // The this-adjustment is left-shifted by 1 on ARM.
468 if (IsARM) {
469 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
470 offset <<= 1;
471 adj = llvm::ConstantInt::get(adj->getType(), offset);
472 }
473
474 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
475 llvm::Constant *dstAdj;
476 if (isDerivedToBase)
477 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
478 else
479 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
480
481 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCall3023def2010-08-22 03:04:22 +0000482}
John McCallcf2c85e2010-08-22 04:16:24 +0000483
484llvm::Constant *
John McCall0bab0cd2010-08-23 01:21:21 +0000485ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall0bab0cd2010-08-23 01:21:21 +0000486 // Itanium C++ ABI 2.3:
487 // A NULL pointer is represented as -1.
488 if (MPT->isMemberDataPointer())
Reid Kleckner92e44d92013-03-22 16:13:10 +0000489 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalld608cdb2010-08-22 10:59:02 +0000490
Reid Kleckner92e44d92013-03-22 16:13:10 +0000491 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalld608cdb2010-08-22 10:59:02 +0000492 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000493 return llvm::ConstantStruct::getAnon(Values);
John McCallcf2c85e2010-08-22 04:16:24 +0000494}
495
John McCall5808ce42011-02-03 08:15:49 +0000496llvm::Constant *
497ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
498 CharUnits offset) {
John McCall0bab0cd2010-08-23 01:21:21 +0000499 // Itanium C++ ABI 2.3:
500 // A pointer to data member is an offset from the base address of
501 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner92e44d92013-03-22 16:13:10 +0000502 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall0bab0cd2010-08-23 01:21:21 +0000503}
504
John McCall755d8492011-04-12 00:42:48 +0000505llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
Richard Smith2d6a5672012-01-14 04:30:29 +0000506 return BuildMemberPointer(MD, CharUnits::Zero());
507}
508
509llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
510 CharUnits ThisAdjustment) {
John McCalld608cdb2010-08-22 10:59:02 +0000511 assert(MD->isInstance() && "Member function must not be static!");
512 MD = MD->getCanonicalDecl();
513
514 CodeGenTypes &Types = CGM.getTypes();
John McCalld608cdb2010-08-22 10:59:02 +0000515
516 // Get the function pointer (or index if this is a virtual function).
517 llvm::Constant *MemPtr[2];
518 if (MD->isVirtual()) {
Peter Collingbourne1d2b3172011-09-26 01:56:30 +0000519 uint64_t Index = CGM.getVTableContext().getMethodVTableIndex(MD);
John McCalld608cdb2010-08-22 10:59:02 +0000520
Ken Dyck1246ba62011-04-09 01:30:02 +0000521 const ASTContext &Context = getContext();
522 CharUnits PointerWidth =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000523 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyck1246ba62011-04-09 01:30:02 +0000524 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalld608cdb2010-08-22 10:59:02 +0000525
526 if (IsARM) {
527 // ARM C++ ABI 3.2.1:
528 // This ABI specifies that adj contains twice the this
529 // adjustment, plus 1 if the member function is virtual. The
530 // least significant bit of adj then makes exactly the same
531 // discrimination as the least significant bit of ptr does for
532 // Itanium.
Reid Kleckner92e44d92013-03-22 16:13:10 +0000533 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
534 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smith2d6a5672012-01-14 04:30:29 +0000535 2 * ThisAdjustment.getQuantity() + 1);
John McCalld608cdb2010-08-22 10:59:02 +0000536 } else {
537 // Itanium C++ ABI 2.3:
538 // For a virtual function, [the pointer field] is 1 plus the
539 // virtual table offset (in bytes) of the function,
540 // represented as a ptrdiff_t.
Reid Kleckner92e44d92013-03-22 16:13:10 +0000541 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
542 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smith2d6a5672012-01-14 04:30:29 +0000543 ThisAdjustment.getQuantity());
John McCalld608cdb2010-08-22 10:59:02 +0000544 }
545 } else {
John McCall755d8492011-04-12 00:42:48 +0000546 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000547 llvm::Type *Ty;
John McCall755d8492011-04-12 00:42:48 +0000548 // Check whether the function has a computable LLVM signature.
Chris Lattnerf742eb02011-07-10 00:18:59 +0000549 if (Types.isFuncTypeConvertible(FPT)) {
John McCall755d8492011-04-12 00:42:48 +0000550 // The function has a computable LLVM signature; use the correct type.
John McCallde5d3c72012-02-17 03:33:10 +0000551 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalld608cdb2010-08-22 10:59:02 +0000552 } else {
John McCall755d8492011-04-12 00:42:48 +0000553 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
554 // function type is incomplete.
Reid Kleckner92e44d92013-03-22 16:13:10 +0000555 Ty = CGM.PtrDiffTy;
John McCalld608cdb2010-08-22 10:59:02 +0000556 }
John McCall755d8492011-04-12 00:42:48 +0000557 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalld608cdb2010-08-22 10:59:02 +0000558
Reid Kleckner92e44d92013-03-22 16:13:10 +0000559 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
560 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy, (IsARM ? 2 : 1) *
Richard Smith2d6a5672012-01-14 04:30:29 +0000561 ThisAdjustment.getQuantity());
John McCalld608cdb2010-08-22 10:59:02 +0000562 }
John McCall875ab102010-08-22 06:43:33 +0000563
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000564 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall875ab102010-08-22 06:43:33 +0000565}
566
Richard Smith2d6a5672012-01-14 04:30:29 +0000567llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
568 QualType MPType) {
569 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
570 const ValueDecl *MPD = MP.getMemberPointerDecl();
571 if (!MPD)
572 return EmitNullMemberPointer(MPT);
573
Reid Klecknerf6327302013-05-09 21:01:17 +0000574 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smith2d6a5672012-01-14 04:30:29 +0000575
576 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
577 return BuildMemberPointer(MD, ThisAdjustment);
578
579 CharUnits FieldOffset =
580 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
581 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
582}
583
John McCalle9fd7eb2010-08-22 08:30:07 +0000584/// The comparison algorithm is pretty easy: the member pointers are
585/// the same if they're either bitwise identical *or* both null.
586///
587/// ARM is different here only because null-ness is more complicated.
588llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000589ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
590 llvm::Value *L,
591 llvm::Value *R,
592 const MemberPointerType *MPT,
593 bool Inequality) {
John McCalle9fd7eb2010-08-22 08:30:07 +0000594 CGBuilderTy &Builder = CGF.Builder;
595
John McCalle9fd7eb2010-08-22 08:30:07 +0000596 llvm::ICmpInst::Predicate Eq;
597 llvm::Instruction::BinaryOps And, Or;
598 if (Inequality) {
599 Eq = llvm::ICmpInst::ICMP_NE;
600 And = llvm::Instruction::Or;
601 Or = llvm::Instruction::And;
602 } else {
603 Eq = llvm::ICmpInst::ICMP_EQ;
604 And = llvm::Instruction::And;
605 Or = llvm::Instruction::Or;
606 }
607
John McCall0bab0cd2010-08-23 01:21:21 +0000608 // Member data pointers are easy because there's a unique null
609 // value, so it just comes down to bitwise equality.
610 if (MPT->isMemberDataPointer())
611 return Builder.CreateICmp(Eq, L, R);
612
613 // For member function pointers, the tautologies are more complex.
614 // The Itanium tautology is:
John McCallde719f72010-08-23 06:56:36 +0000615 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall0bab0cd2010-08-23 01:21:21 +0000616 // The ARM tautology is:
John McCallde719f72010-08-23 06:56:36 +0000617 // (L == R) <==> (L.ptr == R.ptr &&
618 // (L.adj == R.adj ||
619 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall0bab0cd2010-08-23 01:21:21 +0000620 // The inequality tautologies have exactly the same structure, except
621 // applying De Morgan's laws.
622
623 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
624 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
625
John McCalle9fd7eb2010-08-22 08:30:07 +0000626 // This condition tests whether L.ptr == R.ptr. This must always be
627 // true for equality to hold.
628 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
629
630 // This condition, together with the assumption that L.ptr == R.ptr,
631 // tests whether the pointers are both null. ARM imposes an extra
632 // condition.
633 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
634 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
635
636 // This condition tests whether L.adj == R.adj. If this isn't
637 // true, the pointers are unequal unless they're both null.
John McCalld608cdb2010-08-22 10:59:02 +0000638 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
639 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCalle9fd7eb2010-08-22 08:30:07 +0000640 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
641
642 // Null member function pointers on ARM clear the low bit of Adj,
643 // so the zero condition has to check that neither low bit is set.
644 if (IsARM) {
645 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
646
647 // Compute (l.adj | r.adj) & 1 and test it against zero.
648 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
649 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
650 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
651 "cmp.or.adj");
652 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
653 }
654
655 // Tie together all our conditions.
656 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
657 Result = Builder.CreateBinOp(And, PtrEq, Result,
658 Inequality ? "memptr.ne" : "memptr.eq");
659 return Result;
660}
661
662llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000663ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
664 llvm::Value *MemPtr,
665 const MemberPointerType *MPT) {
John McCalle9fd7eb2010-08-22 08:30:07 +0000666 CGBuilderTy &Builder = CGF.Builder;
John McCall0bab0cd2010-08-23 01:21:21 +0000667
668 /// For member data pointers, this is just a check against -1.
669 if (MPT->isMemberDataPointer()) {
Reid Kleckner92e44d92013-03-22 16:13:10 +0000670 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall0bab0cd2010-08-23 01:21:21 +0000671 llvm::Value *NegativeOne =
672 llvm::Constant::getAllOnesValue(MemPtr->getType());
673 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
674 }
John McCalle9fd7eb2010-08-22 08:30:07 +0000675
Daniel Dunbardb27b5f2011-04-19 23:10:47 +0000676 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalld608cdb2010-08-22 10:59:02 +0000677 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCalle9fd7eb2010-08-22 08:30:07 +0000678
679 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
680 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
681
Daniel Dunbardb27b5f2011-04-19 23:10:47 +0000682 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
683 // (the virtual bit) is set.
John McCalle9fd7eb2010-08-22 08:30:07 +0000684 if (IsARM) {
685 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalld608cdb2010-08-22 10:59:02 +0000686 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCalle9fd7eb2010-08-22 08:30:07 +0000687 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbardb27b5f2011-04-19 23:10:47 +0000688 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
689 "memptr.isvirtual");
690 Result = Builder.CreateOr(Result, IsVirtual);
John McCalle9fd7eb2010-08-22 08:30:07 +0000691 }
692
693 return Result;
694}
John McCall875ab102010-08-22 06:43:33 +0000695
John McCallf16aa102010-08-22 21:01:12 +0000696/// The Itanium ABI requires non-zero initialization only for data
697/// member pointers, for which '0' is a valid offset.
698bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
699 return MPT->getPointeeType()->isFunctionType();
John McCallcf2c85e2010-08-22 04:16:24 +0000700}
John McCall4c40d982010-08-31 07:33:07 +0000701
John McCallecd03b42012-09-25 10:10:39 +0000702/// The Itanium ABI always places an offset to the complete object
703/// at entry -2 in the vtable.
704llvm::Value *ItaniumCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
705 llvm::Value *ptr,
706 QualType type) {
707 // Grab the vtable pointer as an intptr_t*.
708 llvm::Value *vtable = CGF.GetVTablePtr(ptr, CGF.IntPtrTy->getPointerTo());
709
710 // Track back to entry -2 and pull out the offset there.
711 llvm::Value *offsetPtr =
712 CGF.Builder.CreateConstInBoundsGEP1_64(vtable, -2, "complete-offset.ptr");
713 llvm::LoadInst *offset = CGF.Builder.CreateLoad(offsetPtr);
714 offset->setAlignment(CGF.PointerAlignInBytes);
715
716 // Apply the offset.
717 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
718 return CGF.Builder.CreateInBoundsGEP(ptr, offset);
719}
720
Reid Klecknerb0f533e2013-05-29 18:02:47 +0000721llvm::Value *
722ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
723 llvm::Value *This,
724 const CXXRecordDecl *ClassDecl,
725 const CXXRecordDecl *BaseClassDecl) {
726 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy);
727 CharUnits VBaseOffsetOffset =
728 CGM.getVTableContext().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl);
729
730 llvm::Value *VBaseOffsetPtr =
731 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
732 "vbase.offset.ptr");
733 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
734 CGM.PtrDiffTy->getPointerTo());
735
736 llvm::Value *VBaseOffset =
737 CGF.Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
738
739 return VBaseOffset;
740}
741
John McCall4c40d982010-08-31 07:33:07 +0000742/// The generic ABI passes 'this', plus a VTT if it's initializing a
743/// base subobject.
744void ItaniumCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
745 CXXCtorType Type,
746 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000747 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9cb2cee2010-09-02 10:25:57 +0000748 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000749
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000750 // 'this' parameter is already there, as well as 'this' return if
751 // HasThisReturn(GlobalDecl(Ctor, Type)) is true
John McCall4c40d982010-08-31 07:33:07 +0000752
753 // Check if we need to add a VTT parameter (which has type void **).
754 if (Type == Ctor_Base && Ctor->getParent()->getNumVBases() != 0)
755 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
756}
757
John McCall4c40d982010-08-31 07:33:07 +0000758/// The generic ABI passes 'this', plus a VTT if it's destroying a
759/// base subobject.
760void ItaniumCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
761 CXXDtorType Type,
762 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000763 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9cb2cee2010-09-02 10:25:57 +0000764 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000765
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000766 // 'this' parameter is already there, as well as 'this' return if
767 // HasThisReturn(GlobalDecl(Dtor, Type)) is true
John McCall4c40d982010-08-31 07:33:07 +0000768
769 // Check if we need to add a VTT parameter (which has type void **).
770 if (Type == Dtor_Base && Dtor->getParent()->getNumVBases() != 0)
771 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
772}
773
Reid Klecknera4130ba2013-07-22 13:51:44 +0000774void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
775 // The destructor in a virtual table is always a 'deleting'
776 // destructor, which calls the complete destructor and then uses the
777 // appropriate operator delete.
778 if (D->isVirtual())
779 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
780
781 // The destructor used for destructing this as a most-derived class;
782 // call the base destructor and then destructs any virtual bases.
783 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
784
785 // The destructor used for destructing this as a base class; ignores
786 // virtual bases.
787 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
788}
789
John McCall4c40d982010-08-31 07:33:07 +0000790void ItaniumCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
791 QualType &ResTy,
792 FunctionArgList &Params) {
793 /// Create the 'this' variable.
794 BuildThisParam(CGF, Params);
795
796 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
797 assert(MD->isInstance());
798
799 // Check if we need a VTT parameter as well.
Peter Collingbournee1e35f72013-06-28 20:45:28 +0000800 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9cb2cee2010-09-02 10:25:57 +0000801 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000802
803 // FIXME: avoid the fake decl
804 QualType T = Context.getPointerType(Context.VoidPtrTy);
805 ImplicitParamDecl *VTTDecl
806 = ImplicitParamDecl::Create(Context, 0, MD->getLocation(),
807 &Context.Idents.get("vtt"), T);
John McCalld26bc762011-03-09 04:27:21 +0000808 Params.push_back(VTTDecl);
John McCall4c40d982010-08-31 07:33:07 +0000809 getVTTDecl(CGF) = VTTDecl;
810 }
811}
812
John McCall4c40d982010-08-31 07:33:07 +0000813void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
814 /// Initialize the 'this' slot.
815 EmitThisParam(CGF);
816
817 /// Initialize the 'vtt' slot if needed.
818 if (getVTTDecl(CGF)) {
819 getVTTValue(CGF)
820 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(getVTTDecl(CGF)),
821 "vtt");
822 }
John McCall4c40d982010-08-31 07:33:07 +0000823
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000824 /// If this is a function that the ABI specifies returns 'this', initialize
825 /// the return slot to 'this' at the start of the function.
826 ///
827 /// Unlike the setting of return types, this is done within the ABI
828 /// implementation instead of by clients of CGCXXABI because:
829 /// 1) getThisValue is currently protected
830 /// 2) in theory, an ABI could implement 'this' returns some other way;
831 /// HasThisReturn only specifies a contract, not the implementation
John McCall4c40d982010-08-31 07:33:07 +0000832 if (HasThisReturn(CGF.CurGD))
Eli Friedmancec5ebd2012-02-11 02:57:39 +0000833 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall4c40d982010-08-31 07:33:07 +0000834}
835
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000836void ItaniumCXXABI::EmitConstructorCall(CodeGenFunction &CGF,
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000837 const CXXConstructorDecl *D,
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000838 CXXCtorType Type,
839 bool ForVirtualBase, bool Delegating,
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000840 llvm::Value *This,
841 CallExpr::const_arg_iterator ArgBeg,
842 CallExpr::const_arg_iterator ArgEnd) {
843 llvm::Value *VTT = CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase,
844 Delegating);
845 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
846 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
847
848 // FIXME: Provide a source location here.
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000849 CGF.EmitCXXMemberCall(D, SourceLocation(), Callee, ReturnValueSlot(),
850 This, VTT, VTTTy, ArgBeg, ArgEnd);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000851}
852
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000853void ItaniumCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
854 const CXXDestructorDecl *Dtor,
855 CXXDtorType DtorType,
856 SourceLocation CallLoc,
857 llvm::Value *This) {
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000858 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
859
860 const CGFunctionInfo *FInfo
861 = &CGM.getTypes().arrangeCXXDestructor(Dtor, DtorType);
862 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov6e007f92013-07-19 08:14:45 +0000863 llvm::Value *Callee
864 = CGF.BuildVirtualCall(GlobalDecl(Dtor, DtorType), This, Ty);
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000865
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000866 CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValueSlot(), This,
867 /*ImplicitParam=*/0, QualType(), 0, 0);
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000868}
869
Reid Kleckner90633022013-06-19 15:20:38 +0000870void ItaniumCXXABI::EmitVirtualInheritanceTables(
871 llvm::GlobalVariable::LinkageTypes Linkage, const CXXRecordDecl *RD) {
872 CodeGenVTables &VTables = CGM.getVTables();
873 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
874 VTables.EmitVTTDefinition(VTT, Linkage, RD);
875}
876
John McCall4c40d982010-08-31 07:33:07 +0000877void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
878 RValue RV, QualType ResultType) {
879 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
880 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
881
882 // Destructor thunks in the ARM ABI have indeterminate results.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000883 llvm::Type *T =
John McCall4c40d982010-08-31 07:33:07 +0000884 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
885 RValue Undef = RValue::get(llvm::UndefValue::get(T));
886 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
887}
John McCall1e7fe752010-09-02 09:58:18 +0000888
889/************************** Array allocation cookies **************************/
890
John McCalle2b45e22012-05-01 05:23:51 +0000891CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
892 // The array cookie is a size_t; pad that up to the element alignment.
893 // The cookie is actually right-justified in that space.
894 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
895 CGM.getContext().getTypeAlignInChars(elementType));
John McCall1e7fe752010-09-02 09:58:18 +0000896}
897
898llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
899 llvm::Value *NewPtr,
900 llvm::Value *NumElements,
John McCall6ec278d2011-01-27 09:37:56 +0000901 const CXXNewExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000902 QualType ElementType) {
John McCalle2b45e22012-05-01 05:23:51 +0000903 assert(requiresArrayCookie(expr));
John McCall1e7fe752010-09-02 09:58:18 +0000904
Micah Villmow956a5a12012-10-25 15:39:14 +0000905 unsigned AS = NewPtr->getType()->getPointerAddressSpace();
John McCall1e7fe752010-09-02 09:58:18 +0000906
John McCall9cb2cee2010-09-02 10:25:57 +0000907 ASTContext &Ctx = getContext();
John McCall1e7fe752010-09-02 09:58:18 +0000908 QualType SizeTy = Ctx.getSizeType();
909 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
910
911 // The size of the cookie.
912 CharUnits CookieSize =
913 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCalle2b45e22012-05-01 05:23:51 +0000914 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall1e7fe752010-09-02 09:58:18 +0000915
916 // Compute an offset to the cookie.
917 llvm::Value *CookiePtr = NewPtr;
918 CharUnits CookieOffset = CookieSize - SizeSize;
919 if (!CookieOffset.isZero())
920 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
921 CookieOffset.getQuantity());
922
923 // Write the number of elements into the appropriate slot.
924 llvm::Value *NumElementsPtr
925 = CGF.Builder.CreateBitCast(CookiePtr,
926 CGF.ConvertType(SizeTy)->getPointerTo(AS));
927 CGF.Builder.CreateStore(NumElements, NumElementsPtr);
928
929 // Finally, compute a pointer to the actual data buffer by skipping
930 // over the cookie completely.
931 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
932 CookieSize.getQuantity());
933}
934
John McCalle2b45e22012-05-01 05:23:51 +0000935llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
936 llvm::Value *allocPtr,
937 CharUnits cookieSize) {
938 // The element size is right-justified in the cookie.
939 llvm::Value *numElementsPtr = allocPtr;
940 CharUnits numElementsOffset =
941 cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes);
942 if (!numElementsOffset.isZero())
943 numElementsPtr =
944 CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr,
945 numElementsOffset.getQuantity());
John McCall1e7fe752010-09-02 09:58:18 +0000946
Micah Villmow956a5a12012-10-25 15:39:14 +0000947 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCalle2b45e22012-05-01 05:23:51 +0000948 numElementsPtr =
949 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
950 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall1e7fe752010-09-02 09:58:18 +0000951}
952
John McCalle2b45e22012-05-01 05:23:51 +0000953CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallf3bbb152013-01-25 23:36:19 +0000954 // ARM says that the cookie is always:
John McCall1e7fe752010-09-02 09:58:18 +0000955 // struct array_cookie {
956 // std::size_t element_size; // element_size != 0
957 // std::size_t element_count;
958 // };
John McCallf3bbb152013-01-25 23:36:19 +0000959 // But the base ABI doesn't give anything an alignment greater than
960 // 8, so we can dismiss this as typical ABI-author blindness to
961 // actual language complexity and round up to the element alignment.
962 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
963 CGM.getContext().getTypeAlignInChars(elementType));
John McCall1e7fe752010-09-02 09:58:18 +0000964}
965
966llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
John McCallf3bbb152013-01-25 23:36:19 +0000967 llvm::Value *newPtr,
968 llvm::Value *numElements,
John McCall6ec278d2011-01-27 09:37:56 +0000969 const CXXNewExpr *expr,
John McCallf3bbb152013-01-25 23:36:19 +0000970 QualType elementType) {
John McCalle2b45e22012-05-01 05:23:51 +0000971 assert(requiresArrayCookie(expr));
John McCall1e7fe752010-09-02 09:58:18 +0000972
John McCallf3bbb152013-01-25 23:36:19 +0000973 // NewPtr is a char*, but we generalize to arbitrary addrspaces.
974 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCall1e7fe752010-09-02 09:58:18 +0000975
976 // The cookie is always at the start of the buffer.
John McCallf3bbb152013-01-25 23:36:19 +0000977 llvm::Value *cookie = newPtr;
John McCall1e7fe752010-09-02 09:58:18 +0000978
979 // The first element is the element size.
John McCallf3bbb152013-01-25 23:36:19 +0000980 cookie = CGF.Builder.CreateBitCast(cookie, CGF.SizeTy->getPointerTo(AS));
981 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
982 getContext().getTypeSizeInChars(elementType).getQuantity());
983 CGF.Builder.CreateStore(elementSize, cookie);
John McCall1e7fe752010-09-02 09:58:18 +0000984
985 // The second element is the element count.
John McCallf3bbb152013-01-25 23:36:19 +0000986 cookie = CGF.Builder.CreateConstInBoundsGEP1_32(cookie, 1);
987 CGF.Builder.CreateStore(numElements, cookie);
John McCall1e7fe752010-09-02 09:58:18 +0000988
989 // Finally, compute a pointer to the actual data buffer by skipping
990 // over the cookie completely.
John McCallf3bbb152013-01-25 23:36:19 +0000991 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
992 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
993 cookieSize.getQuantity());
John McCall1e7fe752010-09-02 09:58:18 +0000994}
995
John McCalle2b45e22012-05-01 05:23:51 +0000996llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
997 llvm::Value *allocPtr,
998 CharUnits cookieSize) {
999 // The number of elements is at offset sizeof(size_t) relative to
1000 // the allocated pointer.
1001 llvm::Value *numElementsPtr
1002 = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes);
John McCall1e7fe752010-09-02 09:58:18 +00001003
Micah Villmow956a5a12012-10-25 15:39:14 +00001004 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCalle2b45e22012-05-01 05:23:51 +00001005 numElementsPtr =
1006 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1007 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall1e7fe752010-09-02 09:58:18 +00001008}
1009
John McCall5cd91b52010-09-08 01:44:27 +00001010/*********************** Static local initialization **************************/
1011
1012static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001013 llvm::PointerType *GuardPtrTy) {
John McCall5cd91b52010-09-08 01:44:27 +00001014 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001015 llvm::FunctionType *FTy =
John McCall5cd91b52010-09-08 01:44:27 +00001016 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foadda549e82011-07-29 13:56:53 +00001017 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckye76872e2012-02-13 23:45:02 +00001018 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendlingc4c62fd2013-01-31 00:30:05 +00001019 llvm::AttributeSet::get(CGM.getLLVMContext(),
1020 llvm::AttributeSet::FunctionIndex,
Bill Wendling72390b32012-12-20 19:27:06 +00001021 llvm::Attribute::NoUnwind));
John McCall5cd91b52010-09-08 01:44:27 +00001022}
1023
1024static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001025 llvm::PointerType *GuardPtrTy) {
John McCall5cd91b52010-09-08 01:44:27 +00001026 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001027 llvm::FunctionType *FTy =
Chris Lattner8b418682012-02-07 00:39:47 +00001028 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckye76872e2012-02-13 23:45:02 +00001029 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendlingc4c62fd2013-01-31 00:30:05 +00001030 llvm::AttributeSet::get(CGM.getLLVMContext(),
1031 llvm::AttributeSet::FunctionIndex,
Bill Wendling72390b32012-12-20 19:27:06 +00001032 llvm::Attribute::NoUnwind));
John McCall5cd91b52010-09-08 01:44:27 +00001033}
1034
1035static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001036 llvm::PointerType *GuardPtrTy) {
John McCall5cd91b52010-09-08 01:44:27 +00001037 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001038 llvm::FunctionType *FTy =
Chris Lattner8b418682012-02-07 00:39:47 +00001039 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckye76872e2012-02-13 23:45:02 +00001040 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendlingc4c62fd2013-01-31 00:30:05 +00001041 llvm::AttributeSet::get(CGM.getLLVMContext(),
1042 llvm::AttributeSet::FunctionIndex,
Bill Wendling72390b32012-12-20 19:27:06 +00001043 llvm::Attribute::NoUnwind));
John McCall5cd91b52010-09-08 01:44:27 +00001044}
1045
1046namespace {
1047 struct CallGuardAbort : EHScopeStack::Cleanup {
1048 llvm::GlobalVariable *Guard;
Chandler Carruth0f30a122012-03-30 19:44:53 +00001049 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall5cd91b52010-09-08 01:44:27 +00001050
John McCallad346f42011-07-12 20:27:29 +00001051 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallbd7370a2013-02-28 19:01:20 +00001052 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1053 Guard);
John McCall5cd91b52010-09-08 01:44:27 +00001054 }
1055 };
1056}
1057
1058/// The ARM code here follows the Itanium code closely enough that we
1059/// just special-case it at particular places.
John McCall3030eb82010-11-06 09:44:32 +00001060void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1061 const VarDecl &D,
John McCall355bba72012-03-30 21:00:39 +00001062 llvm::GlobalVariable *var,
1063 bool shouldPerformInit) {
John McCall5cd91b52010-09-08 01:44:27 +00001064 CGBuilderTy &Builder = CGF.Builder;
John McCall3030eb82010-11-06 09:44:32 +00001065
Richard Smith04e51762013-04-14 23:01:42 +00001066 // We only need to use thread-safe statics for local non-TLS variables;
John McCall3030eb82010-11-06 09:44:32 +00001067 // global initialization is always single-threaded.
Richard Smith04e51762013-04-14 23:01:42 +00001068 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
1069 D.isLocalVarDecl() && !D.getTLSKind();
Anders Carlsson173d5122011-04-27 04:37:08 +00001070
Anders Carlsson173d5122011-04-27 04:37:08 +00001071 // If we have a global variable with internal linkage and thread-safe statics
1072 // are disabled, we can just let the guard variable be of type i8.
John McCall355bba72012-03-30 21:00:39 +00001073 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1074
1075 llvm::IntegerType *guardTy;
John McCall0502a222011-06-17 07:33:57 +00001076 if (useInt8GuardVariable) {
John McCall355bba72012-03-30 21:00:39 +00001077 guardTy = CGF.Int8Ty;
John McCall0502a222011-06-17 07:33:57 +00001078 } else {
Tim Northoverc264e162013-01-31 12:13:10 +00001079 // Guard variables are 64 bits in the generic ABI and size width on ARM
1080 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
1081 guardTy = (IsARM ? CGF.SizeTy : CGF.Int64Ty);
Anders Carlsson173d5122011-04-27 04:37:08 +00001082 }
John McCall355bba72012-03-30 21:00:39 +00001083 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall5cd91b52010-09-08 01:44:27 +00001084
John McCall355bba72012-03-30 21:00:39 +00001085 // Create the guard variable if we don't already have it (as we
1086 // might if we're double-emitting this function body).
1087 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1088 if (!guard) {
1089 // Mangle the name for the guard.
1090 SmallString<256> guardName;
1091 {
1092 llvm::raw_svector_ostream out(guardName);
1093 getMangleContext().mangleItaniumGuardVariable(&D, out);
1094 out.flush();
1095 }
John McCall112c9672010-11-02 21:04:24 +00001096
John McCall355bba72012-03-30 21:00:39 +00001097 // Create the guard variable with a zero-initializer.
1098 // Just absorb linkage and visibility from the guarded variable.
1099 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1100 false, var->getLinkage(),
1101 llvm::ConstantInt::get(guardTy, 0),
1102 guardName.str());
1103 guard->setVisibility(var->getVisibility());
Richard Smith04e51762013-04-14 23:01:42 +00001104 // If the variable is thread-local, so is its guard variable.
1105 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCall355bba72012-03-30 21:00:39 +00001106
1107 CGM.setStaticLocalDeclGuardAddress(&D, guard);
1108 }
John McCall49d26d22012-03-30 07:09:50 +00001109
John McCall5cd91b52010-09-08 01:44:27 +00001110 // Test whether the variable has completed initialization.
John McCall355bba72012-03-30 21:00:39 +00001111 llvm::Value *isInitialized;
John McCall5cd91b52010-09-08 01:44:27 +00001112
1113 // ARM C++ ABI 3.2.3.1:
1114 // To support the potential use of initialization guard variables
1115 // as semaphores that are the target of ARM SWP and LDREX/STREX
1116 // synchronizing instructions we define a static initialization
1117 // guard variable to be a 4-byte aligned, 4- byte word with the
1118 // following inline access protocol.
1119 // #define INITIALIZED 1
1120 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
1121 // if (__cxa_guard_acquire(&obj_guard))
1122 // ...
1123 // }
John McCall0502a222011-06-17 07:33:57 +00001124 if (IsARM && !useInt8GuardVariable) {
John McCall355bba72012-03-30 21:00:39 +00001125 llvm::Value *V = Builder.CreateLoad(guard);
Tim Northoverc264e162013-01-31 12:13:10 +00001126 llvm::Value *Test1 = llvm::ConstantInt::get(guardTy, 1);
1127 V = Builder.CreateAnd(V, Test1);
John McCall355bba72012-03-30 21:00:39 +00001128 isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall5cd91b52010-09-08 01:44:27 +00001129
1130 // Itanium C++ ABI 3.3.2:
1131 // The following is pseudo-code showing how these functions can be used:
1132 // if (obj_guard.first_byte == 0) {
1133 // if ( __cxa_guard_acquire (&obj_guard) ) {
1134 // try {
1135 // ... initialize the object ...;
1136 // } catch (...) {
1137 // __cxa_guard_abort (&obj_guard);
1138 // throw;
1139 // }
1140 // ... queue object destructor with __cxa_atexit() ...;
1141 // __cxa_guard_release (&obj_guard);
1142 // }
1143 // }
1144 } else {
1145 // Load the first byte of the guard variable.
Chandler Carruth0f30a122012-03-30 19:44:53 +00001146 llvm::LoadInst *LI =
John McCall355bba72012-03-30 21:00:39 +00001147 Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
Chandler Carruth0f30a122012-03-30 19:44:53 +00001148 LI->setAlignment(1);
John McCall5cd91b52010-09-08 01:44:27 +00001149
Eli Friedmaneb43f4a2011-09-13 22:21:56 +00001150 // Itanium ABI:
1151 // An implementation supporting thread-safety on multiprocessor
1152 // systems must also guarantee that references to the initialized
1153 // object do not occur before the load of the initialization flag.
1154 //
1155 // In LLVM, we do this by marking the load Acquire.
1156 if (threadsafe)
Chandler Carruth0f30a122012-03-30 19:44:53 +00001157 LI->setAtomic(llvm::Acquire);
Eli Friedmaneb43f4a2011-09-13 22:21:56 +00001158
John McCall355bba72012-03-30 21:00:39 +00001159 isInitialized = Builder.CreateIsNull(LI, "guard.uninitialized");
John McCall5cd91b52010-09-08 01:44:27 +00001160 }
1161
1162 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1163 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1164
1165 // Check if the first byte of the guard variable is zero.
John McCall355bba72012-03-30 21:00:39 +00001166 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall5cd91b52010-09-08 01:44:27 +00001167
1168 CGF.EmitBlock(InitCheckBlock);
1169
1170 // Variables used when coping with thread-safe statics and exceptions.
John McCall0502a222011-06-17 07:33:57 +00001171 if (threadsafe) {
John McCall5cd91b52010-09-08 01:44:27 +00001172 // Call __cxa_guard_acquire.
1173 llvm::Value *V
John McCallbd7370a2013-02-28 19:01:20 +00001174 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall5cd91b52010-09-08 01:44:27 +00001175
1176 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1177
1178 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1179 InitBlock, EndBlock);
1180
1181 // Call __cxa_guard_abort along the exceptional edge.
John McCall355bba72012-03-30 21:00:39 +00001182 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall5cd91b52010-09-08 01:44:27 +00001183
1184 CGF.EmitBlock(InitBlock);
1185 }
1186
1187 // Emit the initializer and add a global destructor if appropriate.
John McCall355bba72012-03-30 21:00:39 +00001188 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall5cd91b52010-09-08 01:44:27 +00001189
John McCall0502a222011-06-17 07:33:57 +00001190 if (threadsafe) {
John McCall5cd91b52010-09-08 01:44:27 +00001191 // Pop the guard-abort cleanup if we pushed one.
1192 CGF.PopCleanupBlock();
1193
1194 // Call __cxa_guard_release. This cannot throw.
John McCallbd7370a2013-02-28 19:01:20 +00001195 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
John McCall5cd91b52010-09-08 01:44:27 +00001196 } else {
John McCall355bba72012-03-30 21:00:39 +00001197 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
John McCall5cd91b52010-09-08 01:44:27 +00001198 }
1199
1200 CGF.EmitBlock(EndBlock);
1201}
John McCall20bb1752012-05-01 06:13:13 +00001202
1203/// Register a global destructor using __cxa_atexit.
1204static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
1205 llvm::Constant *dtor,
Richard Smith04e51762013-04-14 23:01:42 +00001206 llvm::Constant *addr,
1207 bool TLS) {
Bill Wendling4e3b54b2013-05-02 19:18:03 +00001208 const char *Name = "__cxa_atexit";
1209 if (TLS) {
1210 const llvm::Triple &T = CGF.getTarget().getTriple();
1211 Name = T.isMacOSX() ? "_tlv_atexit" : "__cxa_thread_atexit";
1212 }
Richard Smith04e51762013-04-14 23:01:42 +00001213
John McCall20bb1752012-05-01 06:13:13 +00001214 // We're assuming that the destructor function is something we can
1215 // reasonably call with the default CC. Go ahead and cast it to the
1216 // right prototype.
1217 llvm::Type *dtorTy =
1218 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
1219
1220 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
1221 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
1222 llvm::FunctionType *atexitTy =
1223 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
1224
1225 // Fetch the actual function.
Richard Smith04e51762013-04-14 23:01:42 +00001226 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCall20bb1752012-05-01 06:13:13 +00001227 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
1228 fn->setDoesNotThrow();
1229
1230 // Create a variable that binds the atexit to this shared object.
1231 llvm::Constant *handle =
1232 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
1233
1234 llvm::Value *args[] = {
1235 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
1236 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
1237 handle
1238 };
John McCallbd7370a2013-02-28 19:01:20 +00001239 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCall20bb1752012-05-01 06:13:13 +00001240}
1241
1242/// Register a global destructor as best as we know how.
1243void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smith04e51762013-04-14 23:01:42 +00001244 const VarDecl &D,
John McCall20bb1752012-05-01 06:13:13 +00001245 llvm::Constant *dtor,
1246 llvm::Constant *addr) {
1247 // Use __cxa_atexit if available.
Richard Smith04e51762013-04-14 23:01:42 +00001248 if (CGM.getCodeGenOpts().CXAAtExit)
1249 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
1250
1251 if (D.getTLSKind())
1252 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCall20bb1752012-05-01 06:13:13 +00001253
1254 // In Apple kexts, we want to add a global destructor entry.
1255 // FIXME: shouldn't this be guarded by some variable?
Richard Smith7edf9e32012-11-01 22:30:59 +00001256 if (CGM.getLangOpts().AppleKext) {
John McCall20bb1752012-05-01 06:13:13 +00001257 // Generate a global destructor entry.
1258 return CGM.AddCXXDtorEntry(dtor, addr);
1259 }
1260
1261 CGF.registerGlobalDtorWithAtExit(dtor, addr);
1262}
Richard Smithb80a16e2013-04-19 16:42:07 +00001263
1264/// Get the appropriate linkage for the wrapper function. This is essentially
1265/// the weak form of the variable's linkage; every translation unit which wneeds
1266/// the wrapper emits a copy, and we want the linker to merge them.
1267static llvm::GlobalValue::LinkageTypes getThreadLocalWrapperLinkage(
1268 llvm::GlobalValue::LinkageTypes VarLinkage) {
1269 if (llvm::GlobalValue::isLinkerPrivateLinkage(VarLinkage))
1270 return llvm::GlobalValue::LinkerPrivateWeakLinkage;
1271 // For internal linkage variables, we don't need an external or weak wrapper.
1272 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
1273 return VarLinkage;
1274 return llvm::GlobalValue::WeakODRLinkage;
1275}
1276
1277llvm::Function *
1278ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
1279 llvm::GlobalVariable *Var) {
1280 // Mangle the name for the thread_local wrapper function.
1281 SmallString<256> WrapperName;
1282 {
1283 llvm::raw_svector_ostream Out(WrapperName);
1284 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
1285 Out.flush();
1286 }
1287
1288 if (llvm::Value *V = Var->getParent()->getNamedValue(WrapperName))
1289 return cast<llvm::Function>(V);
1290
1291 llvm::Type *RetTy = Var->getType();
1292 if (VD->getType()->isReferenceType())
1293 RetTy = RetTy->getPointerElementType();
1294
1295 llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, false);
1296 llvm::Function *Wrapper = llvm::Function::Create(
1297 FnTy, getThreadLocalWrapperLinkage(Var->getLinkage()), WrapperName.str(),
1298 &CGM.getModule());
1299 // Always resolve references to the wrapper at link time.
1300 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
1301 return Wrapper;
1302}
1303
1304void ItaniumCXXABI::EmitThreadLocalInitFuncs(
1305 llvm::ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
1306 llvm::Function *InitFunc) {
1307 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1308 const VarDecl *VD = Decls[I].first;
1309 llvm::GlobalVariable *Var = Decls[I].second;
1310
1311 // Mangle the name for the thread_local initialization function.
1312 SmallString<256> InitFnName;
1313 {
1314 llvm::raw_svector_ostream Out(InitFnName);
1315 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
1316 Out.flush();
1317 }
1318
1319 // If we have a definition for the variable, emit the initialization
1320 // function as an alias to the global Init function (if any). Otherwise,
1321 // produce a declaration of the initialization function.
1322 llvm::GlobalValue *Init = 0;
1323 bool InitIsInitFunc = false;
1324 if (VD->hasDefinition()) {
1325 InitIsInitFunc = true;
1326 if (InitFunc)
1327 Init =
1328 new llvm::GlobalAlias(InitFunc->getType(), Var->getLinkage(),
1329 InitFnName.str(), InitFunc, &CGM.getModule());
1330 } else {
1331 // Emit a weak global function referring to the initialization function.
1332 // This function will not exist if the TU defining the thread_local
1333 // variable in question does not need any dynamic initialization for
1334 // its thread_local variables.
1335 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
1336 Init = llvm::Function::Create(
1337 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
1338 &CGM.getModule());
1339 }
1340
1341 if (Init)
1342 Init->setVisibility(Var->getVisibility());
1343
1344 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
1345 llvm::LLVMContext &Context = CGM.getModule().getContext();
1346 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
1347 CGBuilderTy Builder(Entry);
1348 if (InitIsInitFunc) {
1349 if (Init)
1350 Builder.CreateCall(Init);
1351 } else {
1352 // Don't know whether we have an init function. Call it if it exists.
1353 llvm::Value *Have = Builder.CreateIsNotNull(Init);
1354 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1355 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1356 Builder.CreateCondBr(Have, InitBB, ExitBB);
1357
1358 Builder.SetInsertPoint(InitBB);
1359 Builder.CreateCall(Init);
1360 Builder.CreateBr(ExitBB);
1361
1362 Builder.SetInsertPoint(ExitBB);
1363 }
1364
1365 // For a reference, the result of the wrapper function is a pointer to
1366 // the referenced object.
1367 llvm::Value *Val = Var;
1368 if (VD->getType()->isReferenceType()) {
1369 llvm::LoadInst *LI = Builder.CreateLoad(Val);
1370 LI->setAlignment(CGM.getContext().getDeclAlign(VD).getQuantity());
1371 Val = LI;
1372 }
1373
1374 Builder.CreateRet(Val);
1375 }
1376}
1377
1378LValue ItaniumCXXABI::EmitThreadLocalDeclRefExpr(CodeGenFunction &CGF,
1379 const DeclRefExpr *DRE) {
1380 const VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1381 QualType T = VD->getType();
1382 llvm::Type *Ty = CGF.getTypes().ConvertTypeForMem(T);
1383 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD, Ty);
1384 llvm::Function *Wrapper =
1385 getOrCreateThreadLocalWrapper(VD, cast<llvm::GlobalVariable>(Val));
1386
1387 Val = CGF.Builder.CreateCall(Wrapper);
1388
1389 LValue LV;
1390 if (VD->getType()->isReferenceType())
1391 LV = CGF.MakeNaturalAlignAddrLValue(Val, T);
1392 else
1393 LV = CGF.MakeAddrLValue(Val, DRE->getType(),
1394 CGF.getContext().getDeclAlign(VD));
1395 // FIXME: need setObjCGCLValueClass?
1396 return LV;
1397}
Peter Collingbournee1e35f72013-06-28 20:45:28 +00001398
1399/// Return whether the given global decl needs a VTT parameter, which it does
1400/// if it's a base constructor or destructor with virtual bases.
1401bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
1402 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1403
1404 // We don't have any virtual bases, just return early.
1405 if (!MD->getParent()->getNumVBases())
1406 return false;
1407
1408 // Check if we have a base constructor.
1409 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
1410 return true;
1411
1412 // Check if we have a base destructor.
1413 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
1414 return true;
1415
1416 return false;
1417}