blob: 6c864ca7f41edde0d2c2bd558152414dc2628549 [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//
10// This provides C++ code generation targetting the Itanium C++ ABI. The class
11// 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"
John McCall93d557b2010-08-22 00:05:51 +000023#include "CodeGenFunction.h"
Charles Davis3a811f12010-05-25 19:52:27 +000024#include "CodeGenModule.h"
Peter Collingbourne14110472011-01-13 18:57:25 +000025#include <clang/AST/Mangle.h>
John McCall93d557b2010-08-22 00:05:51 +000026#include <clang/AST/Type.h>
John McCall0bab0cd2010-08-23 01:21:21 +000027#include <llvm/Target/TargetData.h>
John McCall93d557b2010-08-22 00:05:51 +000028#include <llvm/Value.h>
Charles Davis3a811f12010-05-25 19:52:27 +000029
30using namespace clang;
John McCall93d557b2010-08-22 00:05:51 +000031using namespace CodeGen;
Charles Davis3a811f12010-05-25 19:52:27 +000032
33namespace {
Charles Davis071cc7d2010-08-16 03:33:14 +000034class ItaniumCXXABI : public CodeGen::CGCXXABI {
John McCall0bab0cd2010-08-23 01:21:21 +000035private:
36 const llvm::IntegerType *PtrDiffTy;
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
40 // It's a little silly for us to cache this.
41 const llvm::IntegerType *getPtrDiffTy() {
42 if (!PtrDiffTy) {
John McCall9cb2cee2010-09-02 10:25:57 +000043 QualType T = getContext().getPointerDiffType();
John McCall0bab0cd2010-08-23 01:21:21 +000044 const llvm::Type *Ty = CGM.getTypes().ConvertTypeRecursive(T);
45 PtrDiffTy = cast<llvm::IntegerType>(Ty);
46 }
47 return PtrDiffTy;
48 }
49
John McCall6ec278d2011-01-27 09:37:56 +000050 bool NeedsArrayCookie(const CXXNewExpr *expr);
51 bool NeedsArrayCookie(const CXXDeleteExpr *expr,
52 QualType elementType);
John McCall1e7fe752010-09-02 09:58:18 +000053
Charles Davis3a811f12010-05-25 19:52:27 +000054public:
John McCallbabc9a92010-08-22 00:59:17 +000055 ItaniumCXXABI(CodeGen::CodeGenModule &CGM, bool IsARM = false) :
Peter Collingbourne14110472011-01-13 18:57:25 +000056 CGCXXABI(CGM), PtrDiffTy(0), IsARM(IsARM) { }
John McCall93d557b2010-08-22 00:05:51 +000057
John McCallf16aa102010-08-22 21:01:12 +000058 bool isZeroInitializable(const MemberPointerType *MPT);
John McCallcf2c85e2010-08-22 04:16:24 +000059
John McCall0bab0cd2010-08-23 01:21:21 +000060 const llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT);
61
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 McCallcf2c85e2010-08-22 04:16:24 +000075
John McCall0bab0cd2010-08-23 01:21:21 +000076 llvm::Constant *EmitMemberPointerConversion(llvm::Constant *C,
77 const CastExpr *E);
John McCallcf2c85e2010-08-22 04:16:24 +000078
John McCall0bab0cd2010-08-23 01:21:21 +000079 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
John McCallcf2c85e2010-08-22 04:16:24 +000080
John McCall379b5152011-04-11 07:02:50 +000081 llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD,
82 QualType unknownType);
John McCall5808ce42011-02-03 08:15:49 +000083 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
84 CharUnits offset);
John McCall875ab102010-08-22 06:43:33 +000085
John McCall0bab0cd2010-08-23 01:21:21 +000086 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
87 llvm::Value *L,
88 llvm::Value *R,
89 const MemberPointerType *MPT,
90 bool Inequality);
John McCalle9fd7eb2010-08-22 08:30:07 +000091
John McCall0bab0cd2010-08-23 01:21:21 +000092 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
93 llvm::Value *Addr,
94 const MemberPointerType *MPT);
John McCall4c40d982010-08-31 07:33:07 +000095
96 void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
97 CXXCtorType T,
98 CanQualType &ResTy,
99 llvm::SmallVectorImpl<CanQualType> &ArgTys);
100
101 void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
102 CXXDtorType T,
103 CanQualType &ResTy,
104 llvm::SmallVectorImpl<CanQualType> &ArgTys);
105
106 void BuildInstanceFunctionParams(CodeGenFunction &CGF,
107 QualType &ResTy,
108 FunctionArgList &Params);
109
110 void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
John McCall1e7fe752010-09-02 09:58:18 +0000111
John McCall6ec278d2011-01-27 09:37:56 +0000112 CharUnits GetArrayCookieSize(const CXXNewExpr *expr);
John McCall1e7fe752010-09-02 09:58:18 +0000113 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
114 llvm::Value *NewPtr,
115 llvm::Value *NumElements,
John McCall6ec278d2011-01-27 09:37:56 +0000116 const CXXNewExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000117 QualType ElementType);
118 void ReadArrayCookie(CodeGenFunction &CGF, llvm::Value *Ptr,
John McCall6ec278d2011-01-27 09:37:56 +0000119 const CXXDeleteExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000120 QualType ElementType, llvm::Value *&NumElements,
121 llvm::Value *&AllocPtr, CharUnits &CookieSize);
John McCall5cd91b52010-09-08 01:44:27 +0000122
John McCall3030eb82010-11-06 09:44:32 +0000123 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
124 llvm::GlobalVariable *DeclPtr);
Charles Davis3a811f12010-05-25 19:52:27 +0000125};
John McCallee79a4c2010-08-21 22:46:04 +0000126
127class ARMCXXABI : public ItaniumCXXABI {
128public:
John McCallbabc9a92010-08-22 00:59:17 +0000129 ARMCXXABI(CodeGen::CodeGenModule &CGM) : ItaniumCXXABI(CGM, /*ARM*/ true) {}
John McCall4c40d982010-08-31 07:33:07 +0000130
131 void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
132 CXXCtorType T,
133 CanQualType &ResTy,
134 llvm::SmallVectorImpl<CanQualType> &ArgTys);
135
136 void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
137 CXXDtorType T,
138 CanQualType &ResTy,
139 llvm::SmallVectorImpl<CanQualType> &ArgTys);
140
141 void BuildInstanceFunctionParams(CodeGenFunction &CGF,
142 QualType &ResTy,
143 FunctionArgList &Params);
144
145 void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
146
147 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV, QualType ResTy);
148
John McCall6ec278d2011-01-27 09:37:56 +0000149 CharUnits GetArrayCookieSize(const CXXNewExpr *expr);
John McCall1e7fe752010-09-02 09:58:18 +0000150 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
151 llvm::Value *NewPtr,
152 llvm::Value *NumElements,
John McCall6ec278d2011-01-27 09:37:56 +0000153 const CXXNewExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000154 QualType ElementType);
155 void ReadArrayCookie(CodeGenFunction &CGF, llvm::Value *Ptr,
John McCall6ec278d2011-01-27 09:37:56 +0000156 const CXXDeleteExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000157 QualType ElementType, llvm::Value *&NumElements,
158 llvm::Value *&AllocPtr, CharUnits &CookieSize);
John McCall4c40d982010-08-31 07:33:07 +0000159
160private:
161 /// \brief Returns true if the given instance method is one of the
162 /// kinds that the ARM ABI says returns 'this'.
163 static bool HasThisReturn(GlobalDecl GD) {
164 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
165 return ((isa<CXXDestructorDecl>(MD) && GD.getDtorType() != Dtor_Deleting) ||
166 (isa<CXXConstructorDecl>(MD)));
167 }
John McCallee79a4c2010-08-21 22:46:04 +0000168};
Charles Davis3a811f12010-05-25 19:52:27 +0000169}
170
Charles Davis071cc7d2010-08-16 03:33:14 +0000171CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
Charles Davis3a811f12010-05-25 19:52:27 +0000172 return new ItaniumCXXABI(CGM);
173}
174
John McCallee79a4c2010-08-21 22:46:04 +0000175CodeGen::CGCXXABI *CodeGen::CreateARMCXXABI(CodeGenModule &CGM) {
176 return new ARMCXXABI(CGM);
177}
178
John McCall0bab0cd2010-08-23 01:21:21 +0000179const llvm::Type *
180ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
181 if (MPT->isMemberDataPointer())
182 return getPtrDiffTy();
183 else
184 return llvm::StructType::get(CGM.getLLVMContext(),
185 getPtrDiffTy(), getPtrDiffTy(), NULL);
John McCall875ab102010-08-22 06:43:33 +0000186}
187
John McCallbabc9a92010-08-22 00:59:17 +0000188/// In the Itanium and ARM ABIs, method pointers have the form:
189/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
190///
191/// In the Itanium ABI:
192/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
193/// - the this-adjustment is (memptr.adj)
194/// - the virtual offset is (memptr.ptr - 1)
195///
196/// In the ARM ABI:
197/// - method pointers are virtual if (memptr.adj & 1) is nonzero
198/// - the this-adjustment is (memptr.adj >> 1)
199/// - the virtual offset is (memptr.ptr)
200/// ARM uses 'adj' for the virtual flag because Thumb functions
201/// may be only single-byte aligned.
202///
203/// If the member is virtual, the adjusted 'this' pointer points
204/// to a vtable pointer from which the virtual offset is applied.
205///
206/// If the member is non-virtual, memptr.ptr is the address of
207/// the function to call.
John McCall93d557b2010-08-22 00:05:51 +0000208llvm::Value *
209ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
210 llvm::Value *&This,
211 llvm::Value *MemFnPtr,
212 const MemberPointerType *MPT) {
213 CGBuilderTy &Builder = CGF.Builder;
214
215 const FunctionProtoType *FPT =
216 MPT->getPointeeType()->getAs<FunctionProtoType>();
217 const CXXRecordDecl *RD =
218 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
219
220 const llvm::FunctionType *FTy =
221 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(RD, FPT),
222 FPT->isVariadic());
223
John McCall0bab0cd2010-08-23 01:21:21 +0000224 const llvm::IntegerType *ptrdiff = getPtrDiffTy();
John McCallbabc9a92010-08-22 00:59:17 +0000225 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(ptrdiff, 1);
John McCall93d557b2010-08-22 00:05:51 +0000226
John McCallbabc9a92010-08-22 00:59:17 +0000227 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
228 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
229 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
230
John McCalld608cdb2010-08-22 10:59:02 +0000231 // Extract memptr.adj, which is in the second field.
232 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCallbabc9a92010-08-22 00:59:17 +0000233
234 // Compute the true adjustment.
235 llvm::Value *Adj = RawAdj;
236 if (IsARM)
237 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall93d557b2010-08-22 00:05:51 +0000238
239 // Apply the adjustment and cast back to the original struct type
240 // for consistency.
John McCallbabc9a92010-08-22 00:59:17 +0000241 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
242 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
243 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall93d557b2010-08-22 00:05:51 +0000244
245 // Load the function pointer.
John McCalld608cdb2010-08-22 10:59:02 +0000246 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall93d557b2010-08-22 00:05:51 +0000247
248 // If the LSB in the function pointer is 1, the function pointer points to
249 // a virtual function.
John McCallbabc9a92010-08-22 00:59:17 +0000250 llvm::Value *IsVirtual;
251 if (IsARM)
252 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
253 else
254 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
255 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall93d557b2010-08-22 00:05:51 +0000256 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
257
258 // In the virtual path, the adjustment left 'This' pointing to the
259 // vtable of the correct base subobject. The "function pointer" is an
John McCallbabc9a92010-08-22 00:59:17 +0000260 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall93d557b2010-08-22 00:05:51 +0000261 CGF.EmitBlock(FnVirtual);
262
263 // Cast the adjusted this to a pointer to vtable pointer and load.
264 const llvm::Type *VTableTy = Builder.getInt8PtrTy();
265 llvm::Value *VTable = Builder.CreateBitCast(This, VTableTy->getPointerTo());
John McCallbabc9a92010-08-22 00:59:17 +0000266 VTable = Builder.CreateLoad(VTable, "memptr.vtable");
John McCall93d557b2010-08-22 00:05:51 +0000267
268 // Apply the offset.
John McCallbabc9a92010-08-22 00:59:17 +0000269 llvm::Value *VTableOffset = FnAsInt;
270 if (!IsARM) VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
271 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall93d557b2010-08-22 00:05:51 +0000272
273 // Load the virtual function to call.
274 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCallbabc9a92010-08-22 00:59:17 +0000275 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
John McCall93d557b2010-08-22 00:05:51 +0000276 CGF.EmitBranch(FnEnd);
277
278 // In the non-virtual path, the function pointer is actually a
279 // function pointer.
280 CGF.EmitBlock(FnNonVirtual);
281 llvm::Value *NonVirtualFn =
John McCallbabc9a92010-08-22 00:59:17 +0000282 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall93d557b2010-08-22 00:05:51 +0000283
284 // We're done.
285 CGF.EmitBlock(FnEnd);
Jay Foadbbf3bac2011-03-30 11:28:58 +0000286 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
John McCall93d557b2010-08-22 00:05:51 +0000287 Callee->addIncoming(VirtualFn, FnVirtual);
288 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
289 return Callee;
290}
John McCall3023def2010-08-22 03:04:22 +0000291
John McCall6c2ab1d2010-08-31 21:07:20 +0000292/// Compute an l-value by applying the given pointer-to-member to a
293/// base object.
294llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF,
295 llvm::Value *Base,
296 llvm::Value *MemPtr,
297 const MemberPointerType *MPT) {
298 assert(MemPtr->getType() == getPtrDiffTy());
299
300 CGBuilderTy &Builder = CGF.Builder;
301
302 unsigned AS = cast<llvm::PointerType>(Base->getType())->getAddressSpace();
303
304 // Cast to char*.
305 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
306
307 // Apply the offset, which we assume is non-null.
308 llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
309
310 // Cast the address to the appropriate pointer type, adopting the
311 // address space of the base pointer.
Douglas Gregoreede61a2010-09-02 17:38:50 +0000312 const llvm::Type *PType
313 = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
John McCall6c2ab1d2010-08-31 21:07:20 +0000314 return Builder.CreateBitCast(Addr, PType);
315}
316
John McCall3023def2010-08-22 03:04:22 +0000317/// Perform a derived-to-base or base-to-derived member pointer conversion.
John McCall0bab0cd2010-08-23 01:21:21 +0000318///
319/// Obligatory offset/adjustment diagram:
320/// <-- offset --> <-- adjustment -->
321/// |--------------------------|----------------------|--------------------|
322/// ^Derived address point ^Base address point ^Member address point
323///
324/// So when converting a base member pointer to a derived member pointer,
325/// we add the offset to the adjustment because the address point has
326/// decreased; and conversely, when converting a derived MP to a base MP
327/// we subtract the offset from the adjustment because the address point
328/// has increased.
329///
330/// The standard forbids (at compile time) conversion to and from
331/// virtual bases, which is why we don't have to consider them here.
332///
333/// The standard forbids (at run time) casting a derived MP to a base
334/// MP when the derived MP does not point to a member of the base.
335/// This is why -1 is a reasonable choice for null data member
336/// pointers.
John McCalld608cdb2010-08-22 10:59:02 +0000337llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000338ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
339 const CastExpr *E,
340 llvm::Value *Src) {
John McCall2de56d12010-08-25 11:45:40 +0000341 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
342 E->getCastKind() == CK_BaseToDerivedMemberPointer);
John McCall3023def2010-08-22 03:04:22 +0000343
John McCalld608cdb2010-08-22 10:59:02 +0000344 if (isa<llvm::Constant>(Src))
John McCall0bab0cd2010-08-23 01:21:21 +0000345 return EmitMemberPointerConversion(cast<llvm::Constant>(Src), E);
John McCalld608cdb2010-08-22 10:59:02 +0000346
John McCall3023def2010-08-22 03:04:22 +0000347 CGBuilderTy &Builder = CGF.Builder;
348
349 const MemberPointerType *SrcTy =
350 E->getSubExpr()->getType()->getAs<MemberPointerType>();
351 const MemberPointerType *DestTy = E->getType()->getAs<MemberPointerType>();
352
353 const CXXRecordDecl *SrcDecl = SrcTy->getClass()->getAsCXXRecordDecl();
354 const CXXRecordDecl *DestDecl = DestTy->getClass()->getAsCXXRecordDecl();
355
John McCall3023def2010-08-22 03:04:22 +0000356 bool DerivedToBase =
John McCall2de56d12010-08-25 11:45:40 +0000357 E->getCastKind() == CK_DerivedToBaseMemberPointer;
John McCall3023def2010-08-22 03:04:22 +0000358
Jeffrey Yasskindec09842011-01-18 02:00:16 +0000359 const CXXRecordDecl *DerivedDecl;
John McCall3023def2010-08-22 03:04:22 +0000360 if (DerivedToBase)
Jeffrey Yasskindec09842011-01-18 02:00:16 +0000361 DerivedDecl = SrcDecl;
John McCall3023def2010-08-22 03:04:22 +0000362 else
Jeffrey Yasskindec09842011-01-18 02:00:16 +0000363 DerivedDecl = DestDecl;
John McCall3023def2010-08-22 03:04:22 +0000364
John McCalld608cdb2010-08-22 10:59:02 +0000365 llvm::Constant *Adj =
366 CGF.CGM.GetNonVirtualBaseClassOffset(DerivedDecl,
367 E->path_begin(),
368 E->path_end());
369 if (!Adj) return Src;
John McCall875ab102010-08-22 06:43:33 +0000370
John McCall0bab0cd2010-08-23 01:21:21 +0000371 // For member data pointers, this is just a matter of adding the
372 // offset if the source is non-null.
373 if (SrcTy->isMemberDataPointer()) {
374 llvm::Value *Dst;
375 if (DerivedToBase)
376 Dst = Builder.CreateNSWSub(Src, Adj, "adj");
377 else
378 Dst = Builder.CreateNSWAdd(Src, Adj, "adj");
379
380 // Null check.
381 llvm::Value *Null = llvm::Constant::getAllOnesValue(Src->getType());
382 llvm::Value *IsNull = Builder.CreateICmpEQ(Src, Null, "memptr.isnull");
383 return Builder.CreateSelect(IsNull, Src, Dst);
384 }
385
John McCalld608cdb2010-08-22 10:59:02 +0000386 // The this-adjustment is left-shifted by 1 on ARM.
387 if (IsARM) {
388 uint64_t Offset = cast<llvm::ConstantInt>(Adj)->getZExtValue();
389 Offset <<= 1;
390 Adj = llvm::ConstantInt::get(Adj->getType(), Offset);
391 }
392
John McCalle14add42010-08-22 11:04:31 +0000393 llvm::Value *SrcAdj = Builder.CreateExtractValue(Src, 1, "src.adj");
John McCalld608cdb2010-08-22 10:59:02 +0000394 llvm::Value *DstAdj;
395 if (DerivedToBase)
John McCall0bab0cd2010-08-23 01:21:21 +0000396 DstAdj = Builder.CreateNSWSub(SrcAdj, Adj, "adj");
John McCalld608cdb2010-08-22 10:59:02 +0000397 else
John McCall0bab0cd2010-08-23 01:21:21 +0000398 DstAdj = Builder.CreateNSWAdd(SrcAdj, Adj, "adj");
John McCalld608cdb2010-08-22 10:59:02 +0000399
John McCalle14add42010-08-22 11:04:31 +0000400 return Builder.CreateInsertValue(Src, DstAdj, 1);
John McCall3023def2010-08-22 03:04:22 +0000401}
John McCallcf2c85e2010-08-22 04:16:24 +0000402
403llvm::Constant *
John McCall0bab0cd2010-08-23 01:21:21 +0000404ItaniumCXXABI::EmitMemberPointerConversion(llvm::Constant *C,
405 const CastExpr *E) {
John McCallcf2c85e2010-08-22 04:16:24 +0000406 const MemberPointerType *SrcTy =
407 E->getSubExpr()->getType()->getAs<MemberPointerType>();
408 const MemberPointerType *DestTy =
409 E->getType()->getAs<MemberPointerType>();
410
411 bool DerivedToBase =
John McCall2de56d12010-08-25 11:45:40 +0000412 E->getCastKind() == CK_DerivedToBaseMemberPointer;
John McCallcf2c85e2010-08-22 04:16:24 +0000413
414 const CXXRecordDecl *DerivedDecl;
415 if (DerivedToBase)
416 DerivedDecl = SrcTy->getClass()->getAsCXXRecordDecl();
417 else
418 DerivedDecl = DestTy->getClass()->getAsCXXRecordDecl();
419
420 // Calculate the offset to the base class.
421 llvm::Constant *Offset =
422 CGM.GetNonVirtualBaseClassOffset(DerivedDecl,
423 E->path_begin(),
424 E->path_end());
425 // If there's no offset, we're done.
426 if (!Offset) return C;
427
John McCall0bab0cd2010-08-23 01:21:21 +0000428 // If the source is a member data pointer, we have to do a null
429 // check and then add the offset. In the common case, we can fold
430 // away the offset.
431 if (SrcTy->isMemberDataPointer()) {
432 assert(C->getType() == getPtrDiffTy());
433
434 // If it's a constant int, just create a new constant int.
435 if (llvm::ConstantInt *CI = dyn_cast<llvm::ConstantInt>(C)) {
436 int64_t Src = CI->getSExtValue();
437
438 // Null converts to null.
439 if (Src == -1) return CI;
440
441 // Otherwise, just add the offset.
442 int64_t OffsetV = cast<llvm::ConstantInt>(Offset)->getSExtValue();
443 int64_t Dst = (DerivedToBase ? Src - OffsetV : Src + OffsetV);
444 return llvm::ConstantInt::get(CI->getType(), Dst, /*signed*/ true);
445 }
446
447 // Otherwise, we have to form a constant select expression.
448 llvm::Constant *Null = llvm::Constant::getAllOnesValue(C->getType());
449
450 llvm::Constant *IsNull =
451 llvm::ConstantExpr::getICmp(llvm::ICmpInst::ICMP_EQ, C, Null);
452
453 llvm::Constant *Dst;
454 if (DerivedToBase)
455 Dst = llvm::ConstantExpr::getNSWSub(C, Offset);
456 else
457 Dst = llvm::ConstantExpr::getNSWAdd(C, Offset);
458
459 return llvm::ConstantExpr::getSelect(IsNull, Null, Dst);
460 }
461
John McCall875ab102010-08-22 06:43:33 +0000462 // The this-adjustment is left-shifted by 1 on ARM.
463 if (IsARM) {
John McCall0bab0cd2010-08-23 01:21:21 +0000464 int64_t OffsetV = cast<llvm::ConstantInt>(Offset)->getSExtValue();
John McCall875ab102010-08-22 06:43:33 +0000465 OffsetV <<= 1;
466 Offset = llvm::ConstantInt::get(Offset->getType(), OffsetV);
467 }
468
John McCallcf2c85e2010-08-22 04:16:24 +0000469 llvm::ConstantStruct *CS = cast<llvm::ConstantStruct>(C);
470
John McCall0bab0cd2010-08-23 01:21:21 +0000471 llvm::Constant *Values[2] = { CS->getOperand(0), 0 };
472 if (DerivedToBase)
473 Values[1] = llvm::ConstantExpr::getSub(CS->getOperand(1), Offset);
474 else
475 Values[1] = llvm::ConstantExpr::getAdd(CS->getOperand(1), Offset);
476
John McCallcf2c85e2010-08-22 04:16:24 +0000477 return llvm::ConstantStruct::get(CGM.getLLVMContext(), Values, 2,
478 /*Packed=*/false);
479}
480
481
John McCallcf2c85e2010-08-22 04:16:24 +0000482llvm::Constant *
John McCall0bab0cd2010-08-23 01:21:21 +0000483ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
484 const llvm::Type *ptrdiff_t = getPtrDiffTy();
485
486 // Itanium C++ ABI 2.3:
487 // A NULL pointer is represented as -1.
488 if (MPT->isMemberDataPointer())
489 return llvm::ConstantInt::get(ptrdiff_t, -1ULL, /*isSigned=*/true);
John McCalld608cdb2010-08-22 10:59:02 +0000490
491 llvm::Constant *Zero = llvm::ConstantInt::get(ptrdiff_t, 0);
492 llvm::Constant *Values[2] = { Zero, Zero };
493 return llvm::ConstantStruct::get(CGM.getLLVMContext(), Values, 2,
494 /*Packed=*/false);
John McCallcf2c85e2010-08-22 04:16:24 +0000495}
496
John McCall5808ce42011-02-03 08:15:49 +0000497llvm::Constant *
498ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
499 CharUnits offset) {
John McCall0bab0cd2010-08-23 01:21:21 +0000500 // Itanium C++ ABI 2.3:
501 // A pointer to data member is an offset from the base address of
502 // the class object containing it, represented as a ptrdiff_t
John McCall5808ce42011-02-03 08:15:49 +0000503 return llvm::ConstantInt::get(getPtrDiffTy(), offset.getQuantity());
John McCall0bab0cd2010-08-23 01:21:21 +0000504}
505
John McCall379b5152011-04-11 07:02:50 +0000506llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD,
507 QualType unknownType) {
John McCalld608cdb2010-08-22 10:59:02 +0000508 assert(MD->isInstance() && "Member function must not be static!");
509 MD = MD->getCanonicalDecl();
510
511 CodeGenTypes &Types = CGM.getTypes();
John McCall0bab0cd2010-08-23 01:21:21 +0000512 const llvm::Type *ptrdiff_t = getPtrDiffTy();
John McCalld608cdb2010-08-22 10:59:02 +0000513
514 // Get the function pointer (or index if this is a virtual function).
515 llvm::Constant *MemPtr[2];
516 if (MD->isVirtual()) {
517 uint64_t Index = CGM.getVTables().getMethodVTableIndex(MD);
518
Ken Dyck1246ba62011-04-09 01:30:02 +0000519 const ASTContext &Context = getContext();
520 CharUnits PointerWidth =
521 Context.toCharUnitsFromBits(Context.Target.getPointerWidth(0));
522 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalld608cdb2010-08-22 10:59:02 +0000523
524 if (IsARM) {
525 // ARM C++ ABI 3.2.1:
526 // This ABI specifies that adj contains twice the this
527 // adjustment, plus 1 if the member function is virtual. The
528 // least significant bit of adj then makes exactly the same
529 // discrimination as the least significant bit of ptr does for
530 // Itanium.
531 MemPtr[0] = llvm::ConstantInt::get(ptrdiff_t, VTableOffset);
532 MemPtr[1] = llvm::ConstantInt::get(ptrdiff_t, 1);
533 } else {
534 // Itanium C++ ABI 2.3:
535 // For a virtual function, [the pointer field] is 1 plus the
536 // virtual table offset (in bytes) of the function,
537 // represented as a ptrdiff_t.
538 MemPtr[0] = llvm::ConstantInt::get(ptrdiff_t, VTableOffset + 1);
539 MemPtr[1] = llvm::ConstantInt::get(ptrdiff_t, 0);
540 }
541 } else {
John McCall379b5152011-04-11 07:02:50 +0000542 llvm::Constant *addr;
543 if (!unknownType.isNull()) {
544 addr = CGM.getAddrOfUnknownAnyDecl(MD, unknownType);
John McCalld608cdb2010-08-22 10:59:02 +0000545 } else {
John McCall379b5152011-04-11 07:02:50 +0000546 QualType fnType = MD->getType();
547 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
548 const llvm::Type *Ty;
549 // Check whether the function has a computable LLVM signature.
550 if (!CodeGenTypes::VerifyFuncTypeComplete(FPT)) {
551 // The function has a computable LLVM signature; use the correct type.
552 Ty = Types.GetFunctionType(Types.getFunctionInfo(MD),
553 FPT->isVariadic());
554 } else {
555 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
556 // function type is incomplete.
557 Ty = ptrdiff_t;
558 }
559 addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalld608cdb2010-08-22 10:59:02 +0000560 }
561
John McCall379b5152011-04-11 07:02:50 +0000562 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, ptrdiff_t);
John McCalld608cdb2010-08-22 10:59:02 +0000563 MemPtr[1] = llvm::ConstantInt::get(ptrdiff_t, 0);
564 }
John McCall875ab102010-08-22 06:43:33 +0000565
566 return llvm::ConstantStruct::get(CGM.getLLVMContext(),
John McCalld608cdb2010-08-22 10:59:02 +0000567 MemPtr, 2, /*Packed=*/false);
John McCall875ab102010-08-22 06:43:33 +0000568}
569
John McCalle9fd7eb2010-08-22 08:30:07 +0000570/// The comparison algorithm is pretty easy: the member pointers are
571/// the same if they're either bitwise identical *or* both null.
572///
573/// ARM is different here only because null-ness is more complicated.
574llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000575ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
576 llvm::Value *L,
577 llvm::Value *R,
578 const MemberPointerType *MPT,
579 bool Inequality) {
John McCalle9fd7eb2010-08-22 08:30:07 +0000580 CGBuilderTy &Builder = CGF.Builder;
581
John McCalle9fd7eb2010-08-22 08:30:07 +0000582 llvm::ICmpInst::Predicate Eq;
583 llvm::Instruction::BinaryOps And, Or;
584 if (Inequality) {
585 Eq = llvm::ICmpInst::ICMP_NE;
586 And = llvm::Instruction::Or;
587 Or = llvm::Instruction::And;
588 } else {
589 Eq = llvm::ICmpInst::ICMP_EQ;
590 And = llvm::Instruction::And;
591 Or = llvm::Instruction::Or;
592 }
593
John McCall0bab0cd2010-08-23 01:21:21 +0000594 // Member data pointers are easy because there's a unique null
595 // value, so it just comes down to bitwise equality.
596 if (MPT->isMemberDataPointer())
597 return Builder.CreateICmp(Eq, L, R);
598
599 // For member function pointers, the tautologies are more complex.
600 // The Itanium tautology is:
John McCallde719f72010-08-23 06:56:36 +0000601 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall0bab0cd2010-08-23 01:21:21 +0000602 // The ARM tautology is:
John McCallde719f72010-08-23 06:56:36 +0000603 // (L == R) <==> (L.ptr == R.ptr &&
604 // (L.adj == R.adj ||
605 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall0bab0cd2010-08-23 01:21:21 +0000606 // The inequality tautologies have exactly the same structure, except
607 // applying De Morgan's laws.
608
609 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
610 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
611
John McCalle9fd7eb2010-08-22 08:30:07 +0000612 // This condition tests whether L.ptr == R.ptr. This must always be
613 // true for equality to hold.
614 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
615
616 // This condition, together with the assumption that L.ptr == R.ptr,
617 // tests whether the pointers are both null. ARM imposes an extra
618 // condition.
619 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
620 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
621
622 // This condition tests whether L.adj == R.adj. If this isn't
623 // true, the pointers are unequal unless they're both null.
John McCalld608cdb2010-08-22 10:59:02 +0000624 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
625 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCalle9fd7eb2010-08-22 08:30:07 +0000626 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
627
628 // Null member function pointers on ARM clear the low bit of Adj,
629 // so the zero condition has to check that neither low bit is set.
630 if (IsARM) {
631 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
632
633 // Compute (l.adj | r.adj) & 1 and test it against zero.
634 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
635 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
636 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
637 "cmp.or.adj");
638 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
639 }
640
641 // Tie together all our conditions.
642 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
643 Result = Builder.CreateBinOp(And, PtrEq, Result,
644 Inequality ? "memptr.ne" : "memptr.eq");
645 return Result;
646}
647
648llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000649ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
650 llvm::Value *MemPtr,
651 const MemberPointerType *MPT) {
John McCalle9fd7eb2010-08-22 08:30:07 +0000652 CGBuilderTy &Builder = CGF.Builder;
John McCall0bab0cd2010-08-23 01:21:21 +0000653
654 /// For member data pointers, this is just a check against -1.
655 if (MPT->isMemberDataPointer()) {
656 assert(MemPtr->getType() == getPtrDiffTy());
657 llvm::Value *NegativeOne =
658 llvm::Constant::getAllOnesValue(MemPtr->getType());
659 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
660 }
John McCalle9fd7eb2010-08-22 08:30:07 +0000661
662 // In Itanium, a member function pointer is null if 'ptr' is null.
John McCalld608cdb2010-08-22 10:59:02 +0000663 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCalle9fd7eb2010-08-22 08:30:07 +0000664
665 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
666 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
667
668 // In ARM, it's that, plus the low bit of 'adj' must be zero.
669 if (IsARM) {
670 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalld608cdb2010-08-22 10:59:02 +0000671 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCalle9fd7eb2010-08-22 08:30:07 +0000672 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
673 llvm::Value *IsNotVirtual = Builder.CreateICmpEQ(VirtualBit, Zero,
674 "memptr.notvirtual");
675 Result = Builder.CreateAnd(Result, IsNotVirtual);
676 }
677
678 return Result;
679}
John McCall875ab102010-08-22 06:43:33 +0000680
John McCallf16aa102010-08-22 21:01:12 +0000681/// The Itanium ABI requires non-zero initialization only for data
682/// member pointers, for which '0' is a valid offset.
683bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
684 return MPT->getPointeeType()->isFunctionType();
John McCallcf2c85e2010-08-22 04:16:24 +0000685}
John McCall4c40d982010-08-31 07:33:07 +0000686
687/// The generic ABI passes 'this', plus a VTT if it's initializing a
688/// base subobject.
689void ItaniumCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
690 CXXCtorType Type,
691 CanQualType &ResTy,
692 llvm::SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9cb2cee2010-09-02 10:25:57 +0000693 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000694
695 // 'this' is already there.
696
697 // Check if we need to add a VTT parameter (which has type void **).
698 if (Type == Ctor_Base && Ctor->getParent()->getNumVBases() != 0)
699 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
700}
701
702/// The ARM ABI does the same as the Itanium ABI, but returns 'this'.
703void ARMCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
704 CXXCtorType Type,
705 CanQualType &ResTy,
706 llvm::SmallVectorImpl<CanQualType> &ArgTys) {
707 ItaniumCXXABI::BuildConstructorSignature(Ctor, Type, ResTy, ArgTys);
708 ResTy = ArgTys[0];
709}
710
711/// The generic ABI passes 'this', plus a VTT if it's destroying a
712/// base subobject.
713void ItaniumCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
714 CXXDtorType Type,
715 CanQualType &ResTy,
716 llvm::SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9cb2cee2010-09-02 10:25:57 +0000717 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000718
719 // 'this' is already there.
720
721 // Check if we need to add a VTT parameter (which has type void **).
722 if (Type == Dtor_Base && Dtor->getParent()->getNumVBases() != 0)
723 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
724}
725
726/// The ARM ABI does the same as the Itanium ABI, but returns 'this'
727/// for non-deleting destructors.
728void ARMCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
729 CXXDtorType Type,
730 CanQualType &ResTy,
731 llvm::SmallVectorImpl<CanQualType> &ArgTys) {
732 ItaniumCXXABI::BuildDestructorSignature(Dtor, Type, ResTy, ArgTys);
733
734 if (Type != Dtor_Deleting)
735 ResTy = ArgTys[0];
736}
737
738void ItaniumCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
739 QualType &ResTy,
740 FunctionArgList &Params) {
741 /// Create the 'this' variable.
742 BuildThisParam(CGF, Params);
743
744 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
745 assert(MD->isInstance());
746
747 // Check if we need a VTT parameter as well.
748 if (CodeGenVTables::needsVTTParameter(CGF.CurGD)) {
John McCall9cb2cee2010-09-02 10:25:57 +0000749 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000750
751 // FIXME: avoid the fake decl
752 QualType T = Context.getPointerType(Context.VoidPtrTy);
753 ImplicitParamDecl *VTTDecl
754 = ImplicitParamDecl::Create(Context, 0, MD->getLocation(),
755 &Context.Idents.get("vtt"), T);
John McCalld26bc762011-03-09 04:27:21 +0000756 Params.push_back(VTTDecl);
John McCall4c40d982010-08-31 07:33:07 +0000757 getVTTDecl(CGF) = VTTDecl;
758 }
759}
760
761void ARMCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
762 QualType &ResTy,
763 FunctionArgList &Params) {
764 ItaniumCXXABI::BuildInstanceFunctionParams(CGF, ResTy, Params);
765
766 // Return 'this' from certain constructors and destructors.
767 if (HasThisReturn(CGF.CurGD))
John McCalld26bc762011-03-09 04:27:21 +0000768 ResTy = Params[0]->getType();
John McCall4c40d982010-08-31 07:33:07 +0000769}
770
771void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
772 /// Initialize the 'this' slot.
773 EmitThisParam(CGF);
774
775 /// Initialize the 'vtt' slot if needed.
776 if (getVTTDecl(CGF)) {
777 getVTTValue(CGF)
778 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(getVTTDecl(CGF)),
779 "vtt");
780 }
781}
782
783void ARMCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
784 ItaniumCXXABI::EmitInstanceFunctionProlog(CGF);
785
786 /// Initialize the return slot to 'this' at the start of the
787 /// function.
788 if (HasThisReturn(CGF.CurGD))
789 CGF.Builder.CreateStore(CGF.LoadCXXThis(), CGF.ReturnValue);
790}
791
792void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
793 RValue RV, QualType ResultType) {
794 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
795 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
796
797 // Destructor thunks in the ARM ABI have indeterminate results.
798 const llvm::Type *T =
799 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
800 RValue Undef = RValue::get(llvm::UndefValue::get(T));
801 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
802}
John McCall1e7fe752010-09-02 09:58:18 +0000803
804/************************** Array allocation cookies **************************/
805
John McCall6ec278d2011-01-27 09:37:56 +0000806bool ItaniumCXXABI::NeedsArrayCookie(const CXXNewExpr *expr) {
John McCall1e7fe752010-09-02 09:58:18 +0000807 // If the class's usual deallocation function takes two arguments,
John McCall6ec278d2011-01-27 09:37:56 +0000808 // it needs a cookie.
809 if (expr->doesUsualArrayDeleteWantSize())
810 return true;
John McCall1e7fe752010-09-02 09:58:18 +0000811
John McCall6ec278d2011-01-27 09:37:56 +0000812 // Otherwise, if the class has a non-trivial destructor, it always
813 // needs a cookie.
814 const CXXRecordDecl *record =
815 expr->getAllocatedType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
816 return (record && !record->hasTrivialDestructor());
John McCall1e7fe752010-09-02 09:58:18 +0000817}
818
John McCall6ec278d2011-01-27 09:37:56 +0000819bool ItaniumCXXABI::NeedsArrayCookie(const CXXDeleteExpr *expr,
820 QualType elementType) {
821 // If the class's usual deallocation function takes two arguments,
822 // it needs a cookie.
823 if (expr->doesUsualArrayDeleteWantSize())
824 return true;
825
826 // Otherwise, if the class has a non-trivial destructor, it always
827 // needs a cookie.
828 const CXXRecordDecl *record =
829 elementType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
830 return (record && !record->hasTrivialDestructor());
831}
832
833CharUnits ItaniumCXXABI::GetArrayCookieSize(const CXXNewExpr *expr) {
834 if (!NeedsArrayCookie(expr))
John McCall1e7fe752010-09-02 09:58:18 +0000835 return CharUnits::Zero();
836
John McCall6ec278d2011-01-27 09:37:56 +0000837 // Padding is the maximum of sizeof(size_t) and alignof(elementType)
John McCall9cb2cee2010-09-02 10:25:57 +0000838 ASTContext &Ctx = getContext();
John McCall1e7fe752010-09-02 09:58:18 +0000839 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
John McCall6ec278d2011-01-27 09:37:56 +0000840 Ctx.getTypeAlignInChars(expr->getAllocatedType()));
John McCall1e7fe752010-09-02 09:58:18 +0000841}
842
843llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
844 llvm::Value *NewPtr,
845 llvm::Value *NumElements,
John McCall6ec278d2011-01-27 09:37:56 +0000846 const CXXNewExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000847 QualType ElementType) {
John McCall6ec278d2011-01-27 09:37:56 +0000848 assert(NeedsArrayCookie(expr));
John McCall1e7fe752010-09-02 09:58:18 +0000849
850 unsigned AS = cast<llvm::PointerType>(NewPtr->getType())->getAddressSpace();
851
John McCall9cb2cee2010-09-02 10:25:57 +0000852 ASTContext &Ctx = getContext();
John McCall1e7fe752010-09-02 09:58:18 +0000853 QualType SizeTy = Ctx.getSizeType();
854 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
855
856 // The size of the cookie.
857 CharUnits CookieSize =
858 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
859
860 // Compute an offset to the cookie.
861 llvm::Value *CookiePtr = NewPtr;
862 CharUnits CookieOffset = CookieSize - SizeSize;
863 if (!CookieOffset.isZero())
864 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
865 CookieOffset.getQuantity());
866
867 // Write the number of elements into the appropriate slot.
868 llvm::Value *NumElementsPtr
869 = CGF.Builder.CreateBitCast(CookiePtr,
870 CGF.ConvertType(SizeTy)->getPointerTo(AS));
871 CGF.Builder.CreateStore(NumElements, NumElementsPtr);
872
873 // Finally, compute a pointer to the actual data buffer by skipping
874 // over the cookie completely.
875 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
876 CookieSize.getQuantity());
877}
878
879void ItaniumCXXABI::ReadArrayCookie(CodeGenFunction &CGF,
880 llvm::Value *Ptr,
John McCall6ec278d2011-01-27 09:37:56 +0000881 const CXXDeleteExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000882 QualType ElementType,
883 llvm::Value *&NumElements,
884 llvm::Value *&AllocPtr,
885 CharUnits &CookieSize) {
886 // Derive a char* in the same address space as the pointer.
887 unsigned AS = cast<llvm::PointerType>(Ptr->getType())->getAddressSpace();
888 const llvm::Type *CharPtrTy = CGF.Builder.getInt8Ty()->getPointerTo(AS);
889
890 // If we don't need an array cookie, bail out early.
John McCall6ec278d2011-01-27 09:37:56 +0000891 if (!NeedsArrayCookie(expr, ElementType)) {
John McCall1e7fe752010-09-02 09:58:18 +0000892 AllocPtr = CGF.Builder.CreateBitCast(Ptr, CharPtrTy);
893 NumElements = 0;
894 CookieSize = CharUnits::Zero();
895 return;
896 }
897
John McCall9cb2cee2010-09-02 10:25:57 +0000898 QualType SizeTy = getContext().getSizeType();
899 CharUnits SizeSize = getContext().getTypeSizeInChars(SizeTy);
John McCall1e7fe752010-09-02 09:58:18 +0000900 const llvm::Type *SizeLTy = CGF.ConvertType(SizeTy);
901
902 CookieSize
John McCall9cb2cee2010-09-02 10:25:57 +0000903 = std::max(SizeSize, getContext().getTypeAlignInChars(ElementType));
John McCall1e7fe752010-09-02 09:58:18 +0000904
905 CharUnits NumElementsOffset = CookieSize - SizeSize;
906
907 // Compute the allocated pointer.
908 AllocPtr = CGF.Builder.CreateBitCast(Ptr, CharPtrTy);
909 AllocPtr = CGF.Builder.CreateConstInBoundsGEP1_64(AllocPtr,
910 -CookieSize.getQuantity());
911
912 llvm::Value *NumElementsPtr = AllocPtr;
913 if (!NumElementsOffset.isZero())
914 NumElementsPtr =
915 CGF.Builder.CreateConstInBoundsGEP1_64(NumElementsPtr,
916 NumElementsOffset.getQuantity());
917 NumElementsPtr =
918 CGF.Builder.CreateBitCast(NumElementsPtr, SizeLTy->getPointerTo(AS));
919 NumElements = CGF.Builder.CreateLoad(NumElementsPtr);
920}
921
John McCall6ec278d2011-01-27 09:37:56 +0000922CharUnits ARMCXXABI::GetArrayCookieSize(const CXXNewExpr *expr) {
923 if (!NeedsArrayCookie(expr))
John McCall1e7fe752010-09-02 09:58:18 +0000924 return CharUnits::Zero();
925
926 // On ARM, the cookie is always:
927 // struct array_cookie {
928 // std::size_t element_size; // element_size != 0
929 // std::size_t element_count;
930 // };
931 // TODO: what should we do if the allocated type actually wants
932 // greater alignment?
933 return getContext().getTypeSizeInChars(getContext().getSizeType()) * 2;
934}
935
936llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
937 llvm::Value *NewPtr,
938 llvm::Value *NumElements,
John McCall6ec278d2011-01-27 09:37:56 +0000939 const CXXNewExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000940 QualType ElementType) {
John McCall6ec278d2011-01-27 09:37:56 +0000941 assert(NeedsArrayCookie(expr));
John McCall1e7fe752010-09-02 09:58:18 +0000942
943 // NewPtr is a char*.
944
945 unsigned AS = cast<llvm::PointerType>(NewPtr->getType())->getAddressSpace();
946
John McCall9cb2cee2010-09-02 10:25:57 +0000947 ASTContext &Ctx = getContext();
John McCall1e7fe752010-09-02 09:58:18 +0000948 CharUnits SizeSize = Ctx.getTypeSizeInChars(Ctx.getSizeType());
949 const llvm::IntegerType *SizeTy =
950 cast<llvm::IntegerType>(CGF.ConvertType(Ctx.getSizeType()));
951
952 // The cookie is always at the start of the buffer.
953 llvm::Value *CookiePtr = NewPtr;
954
955 // The first element is the element size.
956 CookiePtr = CGF.Builder.CreateBitCast(CookiePtr, SizeTy->getPointerTo(AS));
957 llvm::Value *ElementSize = llvm::ConstantInt::get(SizeTy,
958 Ctx.getTypeSizeInChars(ElementType).getQuantity());
959 CGF.Builder.CreateStore(ElementSize, CookiePtr);
960
961 // The second element is the element count.
962 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_32(CookiePtr, 1);
963 CGF.Builder.CreateStore(NumElements, CookiePtr);
964
965 // Finally, compute a pointer to the actual data buffer by skipping
966 // over the cookie completely.
967 CharUnits CookieSize = 2 * SizeSize;
968 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
969 CookieSize.getQuantity());
970}
971
972void ARMCXXABI::ReadArrayCookie(CodeGenFunction &CGF,
973 llvm::Value *Ptr,
John McCall6ec278d2011-01-27 09:37:56 +0000974 const CXXDeleteExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000975 QualType ElementType,
976 llvm::Value *&NumElements,
977 llvm::Value *&AllocPtr,
978 CharUnits &CookieSize) {
979 // Derive a char* in the same address space as the pointer.
980 unsigned AS = cast<llvm::PointerType>(Ptr->getType())->getAddressSpace();
981 const llvm::Type *CharPtrTy = CGF.Builder.getInt8Ty()->getPointerTo(AS);
982
983 // If we don't need an array cookie, bail out early.
John McCall6ec278d2011-01-27 09:37:56 +0000984 if (!NeedsArrayCookie(expr, ElementType)) {
John McCall1e7fe752010-09-02 09:58:18 +0000985 AllocPtr = CGF.Builder.CreateBitCast(Ptr, CharPtrTy);
986 NumElements = 0;
987 CookieSize = CharUnits::Zero();
988 return;
989 }
990
John McCall9cb2cee2010-09-02 10:25:57 +0000991 QualType SizeTy = getContext().getSizeType();
992 CharUnits SizeSize = getContext().getTypeSizeInChars(SizeTy);
John McCall1e7fe752010-09-02 09:58:18 +0000993 const llvm::Type *SizeLTy = CGF.ConvertType(SizeTy);
994
995 // The cookie size is always 2 * sizeof(size_t).
996 CookieSize = 2 * SizeSize;
John McCall1e7fe752010-09-02 09:58:18 +0000997
998 // The allocated pointer is the input ptr, minus that amount.
999 AllocPtr = CGF.Builder.CreateBitCast(Ptr, CharPtrTy);
1000 AllocPtr = CGF.Builder.CreateConstInBoundsGEP1_64(AllocPtr,
1001 -CookieSize.getQuantity());
1002
1003 // The number of elements is at offset sizeof(size_t) relative to that.
1004 llvm::Value *NumElementsPtr
1005 = CGF.Builder.CreateConstInBoundsGEP1_64(AllocPtr,
1006 SizeSize.getQuantity());
1007 NumElementsPtr =
1008 CGF.Builder.CreateBitCast(NumElementsPtr, SizeLTy->getPointerTo(AS));
1009 NumElements = CGF.Builder.CreateLoad(NumElementsPtr);
1010}
1011
John McCall5cd91b52010-09-08 01:44:27 +00001012/*********************** Static local initialization **************************/
1013
1014static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
1015 const llvm::PointerType *GuardPtrTy) {
1016 // int __cxa_guard_acquire(__guard *guard_object);
1017
1018 std::vector<const llvm::Type*> Args(1, GuardPtrTy);
1019 const llvm::FunctionType *FTy =
1020 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
1021 Args, /*isVarArg=*/false);
1022
1023 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire");
1024}
1025
1026static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
1027 const llvm::PointerType *GuardPtrTy) {
1028 // void __cxa_guard_release(__guard *guard_object);
1029
1030 std::vector<const llvm::Type*> Args(1, GuardPtrTy);
1031
1032 const llvm::FunctionType *FTy =
1033 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
1034 Args, /*isVarArg=*/false);
1035
1036 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release");
1037}
1038
1039static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
1040 const llvm::PointerType *GuardPtrTy) {
1041 // void __cxa_guard_abort(__guard *guard_object);
1042
1043 std::vector<const llvm::Type*> Args(1, GuardPtrTy);
1044
1045 const llvm::FunctionType *FTy =
1046 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
1047 Args, /*isVarArg=*/false);
1048
1049 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort");
1050}
1051
1052namespace {
1053 struct CallGuardAbort : EHScopeStack::Cleanup {
1054 llvm::GlobalVariable *Guard;
1055 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
1056
1057 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1058 CGF.Builder.CreateCall(getGuardAbortFn(CGF.CGM, Guard->getType()), Guard)
1059 ->setDoesNotThrow();
1060 }
1061 };
1062}
1063
1064/// The ARM code here follows the Itanium code closely enough that we
1065/// just special-case it at particular places.
John McCall3030eb82010-11-06 09:44:32 +00001066void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1067 const VarDecl &D,
1068 llvm::GlobalVariable *GV) {
John McCall5cd91b52010-09-08 01:44:27 +00001069 CGBuilderTy &Builder = CGF.Builder;
John McCall3030eb82010-11-06 09:44:32 +00001070
1071 // We only need to use thread-safe statics for local variables;
1072 // global initialization is always single-threaded.
1073 bool ThreadsafeStatics = (getContext().getLangOptions().ThreadsafeStatics &&
1074 D.isLocalVarDecl());
John McCall5cd91b52010-09-08 01:44:27 +00001075
1076 // Guard variables are 64 bits in the generic ABI and 32 bits on ARM.
1077 const llvm::IntegerType *GuardTy
1078 = (IsARM ? Builder.getInt32Ty() : Builder.getInt64Ty());
1079 const llvm::PointerType *GuardPtrTy = GuardTy->getPointerTo();
1080
1081 // Create the guard variable.
1082 llvm::SmallString<256> GuardVName;
Rafael Espindolaf0be9792011-02-11 02:52:17 +00001083 llvm::raw_svector_ostream Out(GuardVName);
1084 getMangleContext().mangleItaniumGuardVariable(&D, Out);
1085 Out.flush();
John McCall112c9672010-11-02 21:04:24 +00001086
John McCall3030eb82010-11-06 09:44:32 +00001087 // Just absorb linkage and visibility from the variable.
John McCall5cd91b52010-09-08 01:44:27 +00001088 llvm::GlobalVariable *GuardVariable =
1089 new llvm::GlobalVariable(CGM.getModule(), GuardTy,
John McCall3030eb82010-11-06 09:44:32 +00001090 false, GV->getLinkage(),
John McCall5cd91b52010-09-08 01:44:27 +00001091 llvm::ConstantInt::get(GuardTy, 0),
1092 GuardVName.str());
John McCall112c9672010-11-02 21:04:24 +00001093 GuardVariable->setVisibility(GV->getVisibility());
John McCall5cd91b52010-09-08 01:44:27 +00001094
1095 // Test whether the variable has completed initialization.
1096 llvm::Value *IsInitialized;
1097
1098 // ARM C++ ABI 3.2.3.1:
1099 // To support the potential use of initialization guard variables
1100 // as semaphores that are the target of ARM SWP and LDREX/STREX
1101 // synchronizing instructions we define a static initialization
1102 // guard variable to be a 4-byte aligned, 4- byte word with the
1103 // following inline access protocol.
1104 // #define INITIALIZED 1
1105 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
1106 // if (__cxa_guard_acquire(&obj_guard))
1107 // ...
1108 // }
1109 if (IsARM) {
1110 llvm::Value *V = Builder.CreateLoad(GuardVariable);
1111 V = Builder.CreateAnd(V, Builder.getInt32(1));
1112 IsInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
1113
1114 // Itanium C++ ABI 3.3.2:
1115 // The following is pseudo-code showing how these functions can be used:
1116 // if (obj_guard.first_byte == 0) {
1117 // if ( __cxa_guard_acquire (&obj_guard) ) {
1118 // try {
1119 // ... initialize the object ...;
1120 // } catch (...) {
1121 // __cxa_guard_abort (&obj_guard);
1122 // throw;
1123 // }
1124 // ... queue object destructor with __cxa_atexit() ...;
1125 // __cxa_guard_release (&obj_guard);
1126 // }
1127 // }
1128 } else {
1129 // Load the first byte of the guard variable.
1130 const llvm::Type *PtrTy = Builder.getInt8PtrTy();
1131 llvm::Value *V =
1132 Builder.CreateLoad(Builder.CreateBitCast(GuardVariable, PtrTy), "tmp");
1133
1134 IsInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
1135 }
1136
1137 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1138 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1139
1140 // Check if the first byte of the guard variable is zero.
1141 Builder.CreateCondBr(IsInitialized, InitCheckBlock, EndBlock);
1142
1143 CGF.EmitBlock(InitCheckBlock);
1144
1145 // Variables used when coping with thread-safe statics and exceptions.
1146 if (ThreadsafeStatics) {
1147 // Call __cxa_guard_acquire.
1148 llvm::Value *V
1149 = Builder.CreateCall(getGuardAcquireFn(CGM, GuardPtrTy), GuardVariable);
1150
1151 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1152
1153 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1154 InitBlock, EndBlock);
1155
1156 // Call __cxa_guard_abort along the exceptional edge.
1157 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, GuardVariable);
1158
1159 CGF.EmitBlock(InitBlock);
1160 }
1161
1162 // Emit the initializer and add a global destructor if appropriate.
1163 CGF.EmitCXXGlobalVarDeclInit(D, GV);
1164
1165 if (ThreadsafeStatics) {
1166 // Pop the guard-abort cleanup if we pushed one.
1167 CGF.PopCleanupBlock();
1168
1169 // Call __cxa_guard_release. This cannot throw.
1170 Builder.CreateCall(getGuardReleaseFn(CGM, GuardPtrTy), GuardVariable);
1171 } else {
1172 Builder.CreateStore(llvm::ConstantInt::get(GuardTy, 1), GuardVariable);
1173 }
1174
1175 CGF.EmitBlock(EndBlock);
1176}