blob: 99575dfc8f5346d701db80ba4dc9f32a6a0c3050 [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"
25#include "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:
Charles Davis3a811f12010-05-25 19:52:27 +000038 CodeGen::MangleContext MangleCtx;
John McCallbabc9a92010-08-22 00:59:17 +000039 bool IsARM;
John McCall0bab0cd2010-08-23 01:21:21 +000040
41 // It's a little silly for us to cache this.
42 const llvm::IntegerType *getPtrDiffTy() {
43 if (!PtrDiffTy) {
John McCall9cb2cee2010-09-02 10:25:57 +000044 QualType T = getContext().getPointerDiffType();
John McCall0bab0cd2010-08-23 01:21:21 +000045 const llvm::Type *Ty = CGM.getTypes().ConvertTypeRecursive(T);
46 PtrDiffTy = cast<llvm::IntegerType>(Ty);
47 }
48 return PtrDiffTy;
49 }
50
John McCall1e7fe752010-09-02 09:58:18 +000051 bool NeedsArrayCookie(QualType ElementType);
52
Charles Davis3a811f12010-05-25 19:52:27 +000053public:
John McCallbabc9a92010-08-22 00:59:17 +000054 ItaniumCXXABI(CodeGen::CodeGenModule &CGM, bool IsARM = false) :
John McCall9cb2cee2010-09-02 10:25:57 +000055 CGCXXABI(CGM), PtrDiffTy(0), MangleCtx(getContext(), CGM.getDiags()),
John McCall0bab0cd2010-08-23 01:21:21 +000056 IsARM(IsARM) { }
Charles Davis3a811f12010-05-25 19:52:27 +000057
58 CodeGen::MangleContext &getMangleContext() {
59 return MangleCtx;
60 }
John McCall93d557b2010-08-22 00:05:51 +000061
John McCallf16aa102010-08-22 21:01:12 +000062 bool isZeroInitializable(const MemberPointerType *MPT);
John McCallcf2c85e2010-08-22 04:16:24 +000063
John McCall0bab0cd2010-08-23 01:21:21 +000064 const llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT);
65
John McCall93d557b2010-08-22 00:05:51 +000066 llvm::Value *EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
67 llvm::Value *&This,
68 llvm::Value *MemFnPtr,
69 const MemberPointerType *MPT);
John McCall3023def2010-08-22 03:04:22 +000070
John McCall6c2ab1d2010-08-31 21:07:20 +000071 llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF,
72 llvm::Value *Base,
73 llvm::Value *MemPtr,
74 const MemberPointerType *MPT);
75
John McCall0bab0cd2010-08-23 01:21:21 +000076 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
77 const CastExpr *E,
78 llvm::Value *Src);
John McCallcf2c85e2010-08-22 04:16:24 +000079
John McCall0bab0cd2010-08-23 01:21:21 +000080 llvm::Constant *EmitMemberPointerConversion(llvm::Constant *C,
81 const CastExpr *E);
John McCallcf2c85e2010-08-22 04:16:24 +000082
John McCall0bab0cd2010-08-23 01:21:21 +000083 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
John McCallcf2c85e2010-08-22 04:16:24 +000084
John McCall0bab0cd2010-08-23 01:21:21 +000085 llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
86 llvm::Constant *EmitMemberPointer(const FieldDecl *FD);
John McCall875ab102010-08-22 06:43:33 +000087
John McCall0bab0cd2010-08-23 01:21:21 +000088 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
89 llvm::Value *L,
90 llvm::Value *R,
91 const MemberPointerType *MPT,
92 bool Inequality);
John McCalle9fd7eb2010-08-22 08:30:07 +000093
John McCall0bab0cd2010-08-23 01:21:21 +000094 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
95 llvm::Value *Addr,
96 const MemberPointerType *MPT);
John McCall4c40d982010-08-31 07:33:07 +000097
98 void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
99 CXXCtorType T,
100 CanQualType &ResTy,
101 llvm::SmallVectorImpl<CanQualType> &ArgTys);
102
103 void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
104 CXXDtorType T,
105 CanQualType &ResTy,
106 llvm::SmallVectorImpl<CanQualType> &ArgTys);
107
108 void BuildInstanceFunctionParams(CodeGenFunction &CGF,
109 QualType &ResTy,
110 FunctionArgList &Params);
111
112 void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
John McCall1e7fe752010-09-02 09:58:18 +0000113
114 CharUnits GetArrayCookieSize(QualType ElementType);
115 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
116 llvm::Value *NewPtr,
117 llvm::Value *NumElements,
118 QualType ElementType);
119 void ReadArrayCookie(CodeGenFunction &CGF, llvm::Value *Ptr,
120 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 McCall1e7fe752010-09-02 09:58:18 +0000149 CharUnits GetArrayCookieSize(QualType ElementType);
150 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
151 llvm::Value *NewPtr,
152 llvm::Value *NumElements,
153 QualType ElementType);
154 void ReadArrayCookie(CodeGenFunction &CGF, llvm::Value *Ptr,
155 QualType ElementType, llvm::Value *&NumElements,
156 llvm::Value *&AllocPtr, CharUnits &CookieSize);
John McCall4c40d982010-08-31 07:33:07 +0000157
158private:
159 /// \brief Returns true if the given instance method is one of the
160 /// kinds that the ARM ABI says returns 'this'.
161 static bool HasThisReturn(GlobalDecl GD) {
162 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
163 return ((isa<CXXDestructorDecl>(MD) && GD.getDtorType() != Dtor_Deleting) ||
164 (isa<CXXConstructorDecl>(MD)));
165 }
John McCallee79a4c2010-08-21 22:46:04 +0000166};
Charles Davis3a811f12010-05-25 19:52:27 +0000167}
168
Charles Davis071cc7d2010-08-16 03:33:14 +0000169CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
Charles Davis3a811f12010-05-25 19:52:27 +0000170 return new ItaniumCXXABI(CGM);
171}
172
John McCallee79a4c2010-08-21 22:46:04 +0000173CodeGen::CGCXXABI *CodeGen::CreateARMCXXABI(CodeGenModule &CGM) {
174 return new ARMCXXABI(CGM);
175}
176
John McCall0bab0cd2010-08-23 01:21:21 +0000177const llvm::Type *
178ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
179 if (MPT->isMemberDataPointer())
180 return getPtrDiffTy();
181 else
182 return llvm::StructType::get(CGM.getLLVMContext(),
183 getPtrDiffTy(), getPtrDiffTy(), NULL);
John McCall875ab102010-08-22 06:43:33 +0000184}
185
John McCallbabc9a92010-08-22 00:59:17 +0000186/// In the Itanium and ARM ABIs, method pointers have the form:
187/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
188///
189/// In the Itanium ABI:
190/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
191/// - the this-adjustment is (memptr.adj)
192/// - the virtual offset is (memptr.ptr - 1)
193///
194/// In the ARM ABI:
195/// - method pointers are virtual if (memptr.adj & 1) is nonzero
196/// - the this-adjustment is (memptr.adj >> 1)
197/// - the virtual offset is (memptr.ptr)
198/// ARM uses 'adj' for the virtual flag because Thumb functions
199/// may be only single-byte aligned.
200///
201/// If the member is virtual, the adjusted 'this' pointer points
202/// to a vtable pointer from which the virtual offset is applied.
203///
204/// If the member is non-virtual, memptr.ptr is the address of
205/// the function to call.
John McCall93d557b2010-08-22 00:05:51 +0000206llvm::Value *
207ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
208 llvm::Value *&This,
209 llvm::Value *MemFnPtr,
210 const MemberPointerType *MPT) {
211 CGBuilderTy &Builder = CGF.Builder;
212
213 const FunctionProtoType *FPT =
214 MPT->getPointeeType()->getAs<FunctionProtoType>();
215 const CXXRecordDecl *RD =
216 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
217
218 const llvm::FunctionType *FTy =
219 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(RD, FPT),
220 FPT->isVariadic());
221
John McCall0bab0cd2010-08-23 01:21:21 +0000222 const llvm::IntegerType *ptrdiff = getPtrDiffTy();
John McCallbabc9a92010-08-22 00:59:17 +0000223 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(ptrdiff, 1);
John McCall93d557b2010-08-22 00:05:51 +0000224
John McCallbabc9a92010-08-22 00:59:17 +0000225 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
226 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
227 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
228
John McCalld608cdb2010-08-22 10:59:02 +0000229 // Extract memptr.adj, which is in the second field.
230 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCallbabc9a92010-08-22 00:59:17 +0000231
232 // Compute the true adjustment.
233 llvm::Value *Adj = RawAdj;
234 if (IsARM)
235 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall93d557b2010-08-22 00:05:51 +0000236
237 // Apply the adjustment and cast back to the original struct type
238 // for consistency.
John McCallbabc9a92010-08-22 00:59:17 +0000239 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
240 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
241 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall93d557b2010-08-22 00:05:51 +0000242
243 // Load the function pointer.
John McCalld608cdb2010-08-22 10:59:02 +0000244 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall93d557b2010-08-22 00:05:51 +0000245
246 // If the LSB in the function pointer is 1, the function pointer points to
247 // a virtual function.
John McCallbabc9a92010-08-22 00:59:17 +0000248 llvm::Value *IsVirtual;
249 if (IsARM)
250 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
251 else
252 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
253 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall93d557b2010-08-22 00:05:51 +0000254 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
255
256 // In the virtual path, the adjustment left 'This' pointing to the
257 // vtable of the correct base subobject. The "function pointer" is an
John McCallbabc9a92010-08-22 00:59:17 +0000258 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall93d557b2010-08-22 00:05:51 +0000259 CGF.EmitBlock(FnVirtual);
260
261 // Cast the adjusted this to a pointer to vtable pointer and load.
262 const llvm::Type *VTableTy = Builder.getInt8PtrTy();
263 llvm::Value *VTable = Builder.CreateBitCast(This, VTableTy->getPointerTo());
John McCallbabc9a92010-08-22 00:59:17 +0000264 VTable = Builder.CreateLoad(VTable, "memptr.vtable");
John McCall93d557b2010-08-22 00:05:51 +0000265
266 // Apply the offset.
John McCallbabc9a92010-08-22 00:59:17 +0000267 llvm::Value *VTableOffset = FnAsInt;
268 if (!IsARM) VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
269 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall93d557b2010-08-22 00:05:51 +0000270
271 // Load the virtual function to call.
272 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCallbabc9a92010-08-22 00:59:17 +0000273 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
John McCall93d557b2010-08-22 00:05:51 +0000274 CGF.EmitBranch(FnEnd);
275
276 // In the non-virtual path, the function pointer is actually a
277 // function pointer.
278 CGF.EmitBlock(FnNonVirtual);
279 llvm::Value *NonVirtualFn =
John McCallbabc9a92010-08-22 00:59:17 +0000280 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall93d557b2010-08-22 00:05:51 +0000281
282 // We're done.
283 CGF.EmitBlock(FnEnd);
284 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo());
285 Callee->reserveOperandSpace(2);
286 Callee->addIncoming(VirtualFn, FnVirtual);
287 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
288 return Callee;
289}
John McCall3023def2010-08-22 03:04:22 +0000290
John McCall6c2ab1d2010-08-31 21:07:20 +0000291/// Compute an l-value by applying the given pointer-to-member to a
292/// base object.
293llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF,
294 llvm::Value *Base,
295 llvm::Value *MemPtr,
296 const MemberPointerType *MPT) {
297 assert(MemPtr->getType() == getPtrDiffTy());
298
299 CGBuilderTy &Builder = CGF.Builder;
300
301 unsigned AS = cast<llvm::PointerType>(Base->getType())->getAddressSpace();
302
303 // Cast to char*.
304 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
305
306 // Apply the offset, which we assume is non-null.
307 llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
308
309 // Cast the address to the appropriate pointer type, adopting the
310 // address space of the base pointer.
Douglas Gregoreede61a2010-09-02 17:38:50 +0000311 const llvm::Type *PType
312 = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
John McCall6c2ab1d2010-08-31 21:07:20 +0000313 return Builder.CreateBitCast(Addr, PType);
314}
315
John McCall3023def2010-08-22 03:04:22 +0000316/// Perform a derived-to-base or base-to-derived member pointer conversion.
John McCall0bab0cd2010-08-23 01:21:21 +0000317///
318/// Obligatory offset/adjustment diagram:
319/// <-- offset --> <-- adjustment -->
320/// |--------------------------|----------------------|--------------------|
321/// ^Derived address point ^Base address point ^Member address point
322///
323/// So when converting a base member pointer to a derived member pointer,
324/// we add the offset to the adjustment because the address point has
325/// decreased; and conversely, when converting a derived MP to a base MP
326/// we subtract the offset from the adjustment because the address point
327/// has increased.
328///
329/// The standard forbids (at compile time) conversion to and from
330/// virtual bases, which is why we don't have to consider them here.
331///
332/// The standard forbids (at run time) casting a derived MP to a base
333/// MP when the derived MP does not point to a member of the base.
334/// This is why -1 is a reasonable choice for null data member
335/// pointers.
John McCalld608cdb2010-08-22 10:59:02 +0000336llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000337ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
338 const CastExpr *E,
339 llvm::Value *Src) {
John McCall2de56d12010-08-25 11:45:40 +0000340 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
341 E->getCastKind() == CK_BaseToDerivedMemberPointer);
John McCall3023def2010-08-22 03:04:22 +0000342
John McCalld608cdb2010-08-22 10:59:02 +0000343 if (isa<llvm::Constant>(Src))
John McCall0bab0cd2010-08-23 01:21:21 +0000344 return EmitMemberPointerConversion(cast<llvm::Constant>(Src), E);
John McCalld608cdb2010-08-22 10:59:02 +0000345
John McCall3023def2010-08-22 03:04:22 +0000346 CGBuilderTy &Builder = CGF.Builder;
347
348 const MemberPointerType *SrcTy =
349 E->getSubExpr()->getType()->getAs<MemberPointerType>();
350 const MemberPointerType *DestTy = E->getType()->getAs<MemberPointerType>();
351
352 const CXXRecordDecl *SrcDecl = SrcTy->getClass()->getAsCXXRecordDecl();
353 const CXXRecordDecl *DestDecl = DestTy->getClass()->getAsCXXRecordDecl();
354
John McCall3023def2010-08-22 03:04:22 +0000355 bool DerivedToBase =
John McCall2de56d12010-08-25 11:45:40 +0000356 E->getCastKind() == CK_DerivedToBaseMemberPointer;
John McCall3023def2010-08-22 03:04:22 +0000357
358 const CXXRecordDecl *BaseDecl, *DerivedDecl;
359 if (DerivedToBase)
360 DerivedDecl = SrcDecl, BaseDecl = DestDecl;
361 else
362 BaseDecl = SrcDecl, DerivedDecl = DestDecl;
363
John McCalld608cdb2010-08-22 10:59:02 +0000364 llvm::Constant *Adj =
365 CGF.CGM.GetNonVirtualBaseClassOffset(DerivedDecl,
366 E->path_begin(),
367 E->path_end());
368 if (!Adj) return Src;
John McCall875ab102010-08-22 06:43:33 +0000369
John McCall0bab0cd2010-08-23 01:21:21 +0000370 // For member data pointers, this is just a matter of adding the
371 // offset if the source is non-null.
372 if (SrcTy->isMemberDataPointer()) {
373 llvm::Value *Dst;
374 if (DerivedToBase)
375 Dst = Builder.CreateNSWSub(Src, Adj, "adj");
376 else
377 Dst = Builder.CreateNSWAdd(Src, Adj, "adj");
378
379 // Null check.
380 llvm::Value *Null = llvm::Constant::getAllOnesValue(Src->getType());
381 llvm::Value *IsNull = Builder.CreateICmpEQ(Src, Null, "memptr.isnull");
382 return Builder.CreateSelect(IsNull, Src, Dst);
383 }
384
John McCalld608cdb2010-08-22 10:59:02 +0000385 // The this-adjustment is left-shifted by 1 on ARM.
386 if (IsARM) {
387 uint64_t Offset = cast<llvm::ConstantInt>(Adj)->getZExtValue();
388 Offset <<= 1;
389 Adj = llvm::ConstantInt::get(Adj->getType(), Offset);
390 }
391
John McCalle14add42010-08-22 11:04:31 +0000392 llvm::Value *SrcAdj = Builder.CreateExtractValue(Src, 1, "src.adj");
John McCalld608cdb2010-08-22 10:59:02 +0000393 llvm::Value *DstAdj;
394 if (DerivedToBase)
John McCall0bab0cd2010-08-23 01:21:21 +0000395 DstAdj = Builder.CreateNSWSub(SrcAdj, Adj, "adj");
John McCalld608cdb2010-08-22 10:59:02 +0000396 else
John McCall0bab0cd2010-08-23 01:21:21 +0000397 DstAdj = Builder.CreateNSWAdd(SrcAdj, Adj, "adj");
John McCalld608cdb2010-08-22 10:59:02 +0000398
John McCalle14add42010-08-22 11:04:31 +0000399 return Builder.CreateInsertValue(Src, DstAdj, 1);
John McCall3023def2010-08-22 03:04:22 +0000400}
John McCallcf2c85e2010-08-22 04:16:24 +0000401
402llvm::Constant *
John McCall0bab0cd2010-08-23 01:21:21 +0000403ItaniumCXXABI::EmitMemberPointerConversion(llvm::Constant *C,
404 const CastExpr *E) {
John McCallcf2c85e2010-08-22 04:16:24 +0000405 const MemberPointerType *SrcTy =
406 E->getSubExpr()->getType()->getAs<MemberPointerType>();
407 const MemberPointerType *DestTy =
408 E->getType()->getAs<MemberPointerType>();
409
410 bool DerivedToBase =
John McCall2de56d12010-08-25 11:45:40 +0000411 E->getCastKind() == CK_DerivedToBaseMemberPointer;
John McCallcf2c85e2010-08-22 04:16:24 +0000412
413 const CXXRecordDecl *DerivedDecl;
414 if (DerivedToBase)
415 DerivedDecl = SrcTy->getClass()->getAsCXXRecordDecl();
416 else
417 DerivedDecl = DestTy->getClass()->getAsCXXRecordDecl();
418
419 // Calculate the offset to the base class.
420 llvm::Constant *Offset =
421 CGM.GetNonVirtualBaseClassOffset(DerivedDecl,
422 E->path_begin(),
423 E->path_end());
424 // If there's no offset, we're done.
425 if (!Offset) return C;
426
John McCall0bab0cd2010-08-23 01:21:21 +0000427 // If the source is a member data pointer, we have to do a null
428 // check and then add the offset. In the common case, we can fold
429 // away the offset.
430 if (SrcTy->isMemberDataPointer()) {
431 assert(C->getType() == getPtrDiffTy());
432
433 // If it's a constant int, just create a new constant int.
434 if (llvm::ConstantInt *CI = dyn_cast<llvm::ConstantInt>(C)) {
435 int64_t Src = CI->getSExtValue();
436
437 // Null converts to null.
438 if (Src == -1) return CI;
439
440 // Otherwise, just add the offset.
441 int64_t OffsetV = cast<llvm::ConstantInt>(Offset)->getSExtValue();
442 int64_t Dst = (DerivedToBase ? Src - OffsetV : Src + OffsetV);
443 return llvm::ConstantInt::get(CI->getType(), Dst, /*signed*/ true);
444 }
445
446 // Otherwise, we have to form a constant select expression.
447 llvm::Constant *Null = llvm::Constant::getAllOnesValue(C->getType());
448
449 llvm::Constant *IsNull =
450 llvm::ConstantExpr::getICmp(llvm::ICmpInst::ICMP_EQ, C, Null);
451
452 llvm::Constant *Dst;
453 if (DerivedToBase)
454 Dst = llvm::ConstantExpr::getNSWSub(C, Offset);
455 else
456 Dst = llvm::ConstantExpr::getNSWAdd(C, Offset);
457
458 return llvm::ConstantExpr::getSelect(IsNull, Null, Dst);
459 }
460
John McCall875ab102010-08-22 06:43:33 +0000461 // The this-adjustment is left-shifted by 1 on ARM.
462 if (IsARM) {
John McCall0bab0cd2010-08-23 01:21:21 +0000463 int64_t OffsetV = cast<llvm::ConstantInt>(Offset)->getSExtValue();
John McCall875ab102010-08-22 06:43:33 +0000464 OffsetV <<= 1;
465 Offset = llvm::ConstantInt::get(Offset->getType(), OffsetV);
466 }
467
John McCallcf2c85e2010-08-22 04:16:24 +0000468 llvm::ConstantStruct *CS = cast<llvm::ConstantStruct>(C);
469
John McCall0bab0cd2010-08-23 01:21:21 +0000470 llvm::Constant *Values[2] = { CS->getOperand(0), 0 };
471 if (DerivedToBase)
472 Values[1] = llvm::ConstantExpr::getSub(CS->getOperand(1), Offset);
473 else
474 Values[1] = llvm::ConstantExpr::getAdd(CS->getOperand(1), Offset);
475
John McCallcf2c85e2010-08-22 04:16:24 +0000476 return llvm::ConstantStruct::get(CGM.getLLVMContext(), Values, 2,
477 /*Packed=*/false);
478}
479
480
John McCallcf2c85e2010-08-22 04:16:24 +0000481llvm::Constant *
John McCall0bab0cd2010-08-23 01:21:21 +0000482ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
483 const llvm::Type *ptrdiff_t = getPtrDiffTy();
484
485 // Itanium C++ ABI 2.3:
486 // A NULL pointer is represented as -1.
487 if (MPT->isMemberDataPointer())
488 return llvm::ConstantInt::get(ptrdiff_t, -1ULL, /*isSigned=*/true);
John McCalld608cdb2010-08-22 10:59:02 +0000489
490 llvm::Constant *Zero = llvm::ConstantInt::get(ptrdiff_t, 0);
491 llvm::Constant *Values[2] = { Zero, Zero };
492 return llvm::ConstantStruct::get(CGM.getLLVMContext(), Values, 2,
493 /*Packed=*/false);
John McCallcf2c85e2010-08-22 04:16:24 +0000494}
495
John McCall0bab0cd2010-08-23 01:21:21 +0000496llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const FieldDecl *FD) {
497 // Itanium C++ ABI 2.3:
498 // A pointer to data member is an offset from the base address of
499 // the class object containing it, represented as a ptrdiff_t
500
John McCall0bab0cd2010-08-23 01:21:21 +0000501 const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(FD->getParent());
Anders Carlsson8a9dc4f2010-11-24 21:53:50 +0000502 const llvm::StructType *ClassLTy = RL.getLLVMType();
503
John McCall0bab0cd2010-08-23 01:21:21 +0000504 unsigned FieldNo = RL.getLLVMFieldNo(FD);
505 uint64_t Offset =
506 CGM.getTargetData().getStructLayout(ClassLTy)->getElementOffset(FieldNo);
507
508 return llvm::ConstantInt::get(getPtrDiffTy(), Offset);
509}
510
511llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
John McCalld608cdb2010-08-22 10:59:02 +0000512 assert(MD->isInstance() && "Member function must not be static!");
513 MD = MD->getCanonicalDecl();
514
515 CodeGenTypes &Types = CGM.getTypes();
John McCall0bab0cd2010-08-23 01:21:21 +0000516 const llvm::Type *ptrdiff_t = getPtrDiffTy();
John McCalld608cdb2010-08-22 10:59:02 +0000517
518 // Get the function pointer (or index if this is a virtual function).
519 llvm::Constant *MemPtr[2];
520 if (MD->isVirtual()) {
521 uint64_t Index = CGM.getVTables().getMethodVTableIndex(MD);
522
523 // FIXME: We shouldn't use / 8 here.
524 uint64_t PointerWidthInBytes =
John McCall9cb2cee2010-09-02 10:25:57 +0000525 getContext().Target.getPointerWidth(0) / 8;
John McCalld608cdb2010-08-22 10:59:02 +0000526 uint64_t VTableOffset = (Index * PointerWidthInBytes);
527
528 if (IsARM) {
529 // ARM C++ ABI 3.2.1:
530 // This ABI specifies that adj contains twice the this
531 // adjustment, plus 1 if the member function is virtual. The
532 // least significant bit of adj then makes exactly the same
533 // discrimination as the least significant bit of ptr does for
534 // Itanium.
535 MemPtr[0] = llvm::ConstantInt::get(ptrdiff_t, VTableOffset);
536 MemPtr[1] = llvm::ConstantInt::get(ptrdiff_t, 1);
537 } else {
538 // Itanium C++ ABI 2.3:
539 // For a virtual function, [the pointer field] is 1 plus the
540 // virtual table offset (in bytes) of the function,
541 // represented as a ptrdiff_t.
542 MemPtr[0] = llvm::ConstantInt::get(ptrdiff_t, VTableOffset + 1);
543 MemPtr[1] = llvm::ConstantInt::get(ptrdiff_t, 0);
544 }
545 } else {
546 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
547 const llvm::Type *Ty;
548 // Check whether the function has a computable LLVM signature.
549 if (!CodeGenTypes::VerifyFuncTypeComplete(FPT)) {
550 // The function has a computable LLVM signature; use the correct type.
551 Ty = Types.GetFunctionType(Types.getFunctionInfo(MD), FPT->isVariadic());
552 } else {
553 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
554 // function type is incomplete.
555 Ty = ptrdiff_t;
556 }
557
558 llvm::Constant *Addr = CGM.GetAddrOfFunction(MD, Ty);
559 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(Addr, ptrdiff_t);
560 MemPtr[1] = llvm::ConstantInt::get(ptrdiff_t, 0);
561 }
John McCall875ab102010-08-22 06:43:33 +0000562
563 return llvm::ConstantStruct::get(CGM.getLLVMContext(),
John McCalld608cdb2010-08-22 10:59:02 +0000564 MemPtr, 2, /*Packed=*/false);
John McCall875ab102010-08-22 06:43:33 +0000565}
566
John McCalle9fd7eb2010-08-22 08:30:07 +0000567/// The comparison algorithm is pretty easy: the member pointers are
568/// the same if they're either bitwise identical *or* both null.
569///
570/// ARM is different here only because null-ness is more complicated.
571llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000572ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
573 llvm::Value *L,
574 llvm::Value *R,
575 const MemberPointerType *MPT,
576 bool Inequality) {
John McCalle9fd7eb2010-08-22 08:30:07 +0000577 CGBuilderTy &Builder = CGF.Builder;
578
John McCalle9fd7eb2010-08-22 08:30:07 +0000579 llvm::ICmpInst::Predicate Eq;
580 llvm::Instruction::BinaryOps And, Or;
581 if (Inequality) {
582 Eq = llvm::ICmpInst::ICMP_NE;
583 And = llvm::Instruction::Or;
584 Or = llvm::Instruction::And;
585 } else {
586 Eq = llvm::ICmpInst::ICMP_EQ;
587 And = llvm::Instruction::And;
588 Or = llvm::Instruction::Or;
589 }
590
John McCall0bab0cd2010-08-23 01:21:21 +0000591 // Member data pointers are easy because there's a unique null
592 // value, so it just comes down to bitwise equality.
593 if (MPT->isMemberDataPointer())
594 return Builder.CreateICmp(Eq, L, R);
595
596 // For member function pointers, the tautologies are more complex.
597 // The Itanium tautology is:
John McCallde719f72010-08-23 06:56:36 +0000598 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall0bab0cd2010-08-23 01:21:21 +0000599 // The ARM tautology is:
John McCallde719f72010-08-23 06:56:36 +0000600 // (L == R) <==> (L.ptr == R.ptr &&
601 // (L.adj == R.adj ||
602 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall0bab0cd2010-08-23 01:21:21 +0000603 // The inequality tautologies have exactly the same structure, except
604 // applying De Morgan's laws.
605
606 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
607 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
608
John McCalle9fd7eb2010-08-22 08:30:07 +0000609 // This condition tests whether L.ptr == R.ptr. This must always be
610 // true for equality to hold.
611 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
612
613 // This condition, together with the assumption that L.ptr == R.ptr,
614 // tests whether the pointers are both null. ARM imposes an extra
615 // condition.
616 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
617 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
618
619 // This condition tests whether L.adj == R.adj. If this isn't
620 // true, the pointers are unequal unless they're both null.
John McCalld608cdb2010-08-22 10:59:02 +0000621 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
622 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCalle9fd7eb2010-08-22 08:30:07 +0000623 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
624
625 // Null member function pointers on ARM clear the low bit of Adj,
626 // so the zero condition has to check that neither low bit is set.
627 if (IsARM) {
628 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
629
630 // Compute (l.adj | r.adj) & 1 and test it against zero.
631 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
632 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
633 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
634 "cmp.or.adj");
635 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
636 }
637
638 // Tie together all our conditions.
639 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
640 Result = Builder.CreateBinOp(And, PtrEq, Result,
641 Inequality ? "memptr.ne" : "memptr.eq");
642 return Result;
643}
644
645llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000646ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
647 llvm::Value *MemPtr,
648 const MemberPointerType *MPT) {
John McCalle9fd7eb2010-08-22 08:30:07 +0000649 CGBuilderTy &Builder = CGF.Builder;
John McCall0bab0cd2010-08-23 01:21:21 +0000650
651 /// For member data pointers, this is just a check against -1.
652 if (MPT->isMemberDataPointer()) {
653 assert(MemPtr->getType() == getPtrDiffTy());
654 llvm::Value *NegativeOne =
655 llvm::Constant::getAllOnesValue(MemPtr->getType());
656 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
657 }
John McCalle9fd7eb2010-08-22 08:30:07 +0000658
659 // In Itanium, a member function pointer is null if 'ptr' is null.
John McCalld608cdb2010-08-22 10:59:02 +0000660 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCalle9fd7eb2010-08-22 08:30:07 +0000661
662 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
663 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
664
665 // In ARM, it's that, plus the low bit of 'adj' must be zero.
666 if (IsARM) {
667 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalld608cdb2010-08-22 10:59:02 +0000668 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCalle9fd7eb2010-08-22 08:30:07 +0000669 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
670 llvm::Value *IsNotVirtual = Builder.CreateICmpEQ(VirtualBit, Zero,
671 "memptr.notvirtual");
672 Result = Builder.CreateAnd(Result, IsNotVirtual);
673 }
674
675 return Result;
676}
John McCall875ab102010-08-22 06:43:33 +0000677
John McCallf16aa102010-08-22 21:01:12 +0000678/// The Itanium ABI requires non-zero initialization only for data
679/// member pointers, for which '0' is a valid offset.
680bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
681 return MPT->getPointeeType()->isFunctionType();
John McCallcf2c85e2010-08-22 04:16:24 +0000682}
John McCall4c40d982010-08-31 07:33:07 +0000683
684/// The generic ABI passes 'this', plus a VTT if it's initializing a
685/// base subobject.
686void ItaniumCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
687 CXXCtorType Type,
688 CanQualType &ResTy,
689 llvm::SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9cb2cee2010-09-02 10:25:57 +0000690 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000691
692 // 'this' is already there.
693
694 // Check if we need to add a VTT parameter (which has type void **).
695 if (Type == Ctor_Base && Ctor->getParent()->getNumVBases() != 0)
696 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
697}
698
699/// The ARM ABI does the same as the Itanium ABI, but returns 'this'.
700void ARMCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
701 CXXCtorType Type,
702 CanQualType &ResTy,
703 llvm::SmallVectorImpl<CanQualType> &ArgTys) {
704 ItaniumCXXABI::BuildConstructorSignature(Ctor, Type, ResTy, ArgTys);
705 ResTy = ArgTys[0];
706}
707
708/// The generic ABI passes 'this', plus a VTT if it's destroying a
709/// base subobject.
710void ItaniumCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
711 CXXDtorType Type,
712 CanQualType &ResTy,
713 llvm::SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9cb2cee2010-09-02 10:25:57 +0000714 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000715
716 // 'this' is already there.
717
718 // Check if we need to add a VTT parameter (which has type void **).
719 if (Type == Dtor_Base && Dtor->getParent()->getNumVBases() != 0)
720 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
721}
722
723/// The ARM ABI does the same as the Itanium ABI, but returns 'this'
724/// for non-deleting destructors.
725void ARMCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
726 CXXDtorType Type,
727 CanQualType &ResTy,
728 llvm::SmallVectorImpl<CanQualType> &ArgTys) {
729 ItaniumCXXABI::BuildDestructorSignature(Dtor, Type, ResTy, ArgTys);
730
731 if (Type != Dtor_Deleting)
732 ResTy = ArgTys[0];
733}
734
735void ItaniumCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
736 QualType &ResTy,
737 FunctionArgList &Params) {
738 /// Create the 'this' variable.
739 BuildThisParam(CGF, Params);
740
741 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
742 assert(MD->isInstance());
743
744 // Check if we need a VTT parameter as well.
745 if (CodeGenVTables::needsVTTParameter(CGF.CurGD)) {
John McCall9cb2cee2010-09-02 10:25:57 +0000746 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000747
748 // FIXME: avoid the fake decl
749 QualType T = Context.getPointerType(Context.VoidPtrTy);
750 ImplicitParamDecl *VTTDecl
751 = ImplicitParamDecl::Create(Context, 0, MD->getLocation(),
752 &Context.Idents.get("vtt"), T);
753 Params.push_back(std::make_pair(VTTDecl, VTTDecl->getType()));
754 getVTTDecl(CGF) = VTTDecl;
755 }
756}
757
758void ARMCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
759 QualType &ResTy,
760 FunctionArgList &Params) {
761 ItaniumCXXABI::BuildInstanceFunctionParams(CGF, ResTy, Params);
762
763 // Return 'this' from certain constructors and destructors.
764 if (HasThisReturn(CGF.CurGD))
765 ResTy = Params[0].second;
766}
767
768void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
769 /// Initialize the 'this' slot.
770 EmitThisParam(CGF);
771
772 /// Initialize the 'vtt' slot if needed.
773 if (getVTTDecl(CGF)) {
774 getVTTValue(CGF)
775 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(getVTTDecl(CGF)),
776 "vtt");
777 }
778}
779
780void ARMCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
781 ItaniumCXXABI::EmitInstanceFunctionProlog(CGF);
782
783 /// Initialize the return slot to 'this' at the start of the
784 /// function.
785 if (HasThisReturn(CGF.CurGD))
786 CGF.Builder.CreateStore(CGF.LoadCXXThis(), CGF.ReturnValue);
787}
788
789void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
790 RValue RV, QualType ResultType) {
791 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
792 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
793
794 // Destructor thunks in the ARM ABI have indeterminate results.
795 const llvm::Type *T =
796 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
797 RValue Undef = RValue::get(llvm::UndefValue::get(T));
798 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
799}
John McCall1e7fe752010-09-02 09:58:18 +0000800
801/************************** Array allocation cookies **************************/
802
803bool ItaniumCXXABI::NeedsArrayCookie(QualType ElementType) {
John McCall9cb2cee2010-09-02 10:25:57 +0000804 ElementType = getContext().getBaseElementType(ElementType);
John McCall1e7fe752010-09-02 09:58:18 +0000805 const RecordType *RT = ElementType->getAs<RecordType>();
806 if (!RT) return false;
807
808 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
809
810 // If the class has a non-trivial destructor, it always needs a cookie.
811 if (!RD->hasTrivialDestructor()) return true;
812
813 // If the class's usual deallocation function takes two arguments,
814 // it needs a cookie. Otherwise we don't need a cookie.
815 const CXXMethodDecl *UsualDeallocationFunction = 0;
816
817 // Usual deallocation functions of this form are always found on the
818 // class.
819 //
820 // FIXME: what exactly is this code supposed to do if there's an
821 // ambiguity? That's possible with using declarations.
822 DeclarationName OpName =
John McCall9cb2cee2010-09-02 10:25:57 +0000823 getContext().DeclarationNames.getCXXOperatorName(OO_Array_Delete);
John McCall1e7fe752010-09-02 09:58:18 +0000824 DeclContext::lookup_const_iterator Op, OpEnd;
825 for (llvm::tie(Op, OpEnd) = RD->lookup(OpName); Op != OpEnd; ++Op) {
826 const CXXMethodDecl *Delete =
827 cast<CXXMethodDecl>((*Op)->getUnderlyingDecl());
828
829 if (Delete->isUsualDeallocationFunction()) {
830 UsualDeallocationFunction = Delete;
831 break;
832 }
833 }
834
835 // No usual deallocation function, we don't need a cookie.
836 if (!UsualDeallocationFunction)
837 return false;
838
839 // The usual deallocation function doesn't take a size_t argument,
840 // so we don't need a cookie.
841 if (UsualDeallocationFunction->getNumParams() == 1)
842 return false;
843
844 assert(UsualDeallocationFunction->getNumParams() == 2 &&
845 "Unexpected deallocation function type!");
846 return true;
847}
848
849CharUnits ItaniumCXXABI::GetArrayCookieSize(QualType ElementType) {
850 if (!NeedsArrayCookie(ElementType))
851 return CharUnits::Zero();
852
853 // Padding is the maximum of sizeof(size_t) and alignof(ElementType)
John McCall9cb2cee2010-09-02 10:25:57 +0000854 ASTContext &Ctx = getContext();
John McCall1e7fe752010-09-02 09:58:18 +0000855 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
856 Ctx.getTypeAlignInChars(ElementType));
857}
858
859llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
860 llvm::Value *NewPtr,
861 llvm::Value *NumElements,
862 QualType ElementType) {
863 assert(NeedsArrayCookie(ElementType));
864
865 unsigned AS = cast<llvm::PointerType>(NewPtr->getType())->getAddressSpace();
866
John McCall9cb2cee2010-09-02 10:25:57 +0000867 ASTContext &Ctx = getContext();
John McCall1e7fe752010-09-02 09:58:18 +0000868 QualType SizeTy = Ctx.getSizeType();
869 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
870
871 // The size of the cookie.
872 CharUnits CookieSize =
873 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
874
875 // Compute an offset to the cookie.
876 llvm::Value *CookiePtr = NewPtr;
877 CharUnits CookieOffset = CookieSize - SizeSize;
878 if (!CookieOffset.isZero())
879 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
880 CookieOffset.getQuantity());
881
882 // Write the number of elements into the appropriate slot.
883 llvm::Value *NumElementsPtr
884 = CGF.Builder.CreateBitCast(CookiePtr,
885 CGF.ConvertType(SizeTy)->getPointerTo(AS));
886 CGF.Builder.CreateStore(NumElements, NumElementsPtr);
887
888 // Finally, compute a pointer to the actual data buffer by skipping
889 // over the cookie completely.
890 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
891 CookieSize.getQuantity());
892}
893
894void ItaniumCXXABI::ReadArrayCookie(CodeGenFunction &CGF,
895 llvm::Value *Ptr,
896 QualType ElementType,
897 llvm::Value *&NumElements,
898 llvm::Value *&AllocPtr,
899 CharUnits &CookieSize) {
900 // Derive a char* in the same address space as the pointer.
901 unsigned AS = cast<llvm::PointerType>(Ptr->getType())->getAddressSpace();
902 const llvm::Type *CharPtrTy = CGF.Builder.getInt8Ty()->getPointerTo(AS);
903
904 // If we don't need an array cookie, bail out early.
905 if (!NeedsArrayCookie(ElementType)) {
906 AllocPtr = CGF.Builder.CreateBitCast(Ptr, CharPtrTy);
907 NumElements = 0;
908 CookieSize = CharUnits::Zero();
909 return;
910 }
911
John McCall9cb2cee2010-09-02 10:25:57 +0000912 QualType SizeTy = getContext().getSizeType();
913 CharUnits SizeSize = getContext().getTypeSizeInChars(SizeTy);
John McCall1e7fe752010-09-02 09:58:18 +0000914 const llvm::Type *SizeLTy = CGF.ConvertType(SizeTy);
915
916 CookieSize
John McCall9cb2cee2010-09-02 10:25:57 +0000917 = std::max(SizeSize, getContext().getTypeAlignInChars(ElementType));
John McCall1e7fe752010-09-02 09:58:18 +0000918
919 CharUnits NumElementsOffset = CookieSize - SizeSize;
920
921 // Compute the allocated pointer.
922 AllocPtr = CGF.Builder.CreateBitCast(Ptr, CharPtrTy);
923 AllocPtr = CGF.Builder.CreateConstInBoundsGEP1_64(AllocPtr,
924 -CookieSize.getQuantity());
925
926 llvm::Value *NumElementsPtr = AllocPtr;
927 if (!NumElementsOffset.isZero())
928 NumElementsPtr =
929 CGF.Builder.CreateConstInBoundsGEP1_64(NumElementsPtr,
930 NumElementsOffset.getQuantity());
931 NumElementsPtr =
932 CGF.Builder.CreateBitCast(NumElementsPtr, SizeLTy->getPointerTo(AS));
933 NumElements = CGF.Builder.CreateLoad(NumElementsPtr);
934}
935
936CharUnits ARMCXXABI::GetArrayCookieSize(QualType ElementType) {
937 if (!NeedsArrayCookie(ElementType))
938 return CharUnits::Zero();
939
940 // On ARM, the cookie is always:
941 // struct array_cookie {
942 // std::size_t element_size; // element_size != 0
943 // std::size_t element_count;
944 // };
945 // TODO: what should we do if the allocated type actually wants
946 // greater alignment?
947 return getContext().getTypeSizeInChars(getContext().getSizeType()) * 2;
948}
949
950llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
951 llvm::Value *NewPtr,
952 llvm::Value *NumElements,
953 QualType ElementType) {
954 assert(NeedsArrayCookie(ElementType));
955
956 // NewPtr is a char*.
957
958 unsigned AS = cast<llvm::PointerType>(NewPtr->getType())->getAddressSpace();
959
John McCall9cb2cee2010-09-02 10:25:57 +0000960 ASTContext &Ctx = getContext();
John McCall1e7fe752010-09-02 09:58:18 +0000961 CharUnits SizeSize = Ctx.getTypeSizeInChars(Ctx.getSizeType());
962 const llvm::IntegerType *SizeTy =
963 cast<llvm::IntegerType>(CGF.ConvertType(Ctx.getSizeType()));
964
965 // The cookie is always at the start of the buffer.
966 llvm::Value *CookiePtr = NewPtr;
967
968 // The first element is the element size.
969 CookiePtr = CGF.Builder.CreateBitCast(CookiePtr, SizeTy->getPointerTo(AS));
970 llvm::Value *ElementSize = llvm::ConstantInt::get(SizeTy,
971 Ctx.getTypeSizeInChars(ElementType).getQuantity());
972 CGF.Builder.CreateStore(ElementSize, CookiePtr);
973
974 // The second element is the element count.
975 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_32(CookiePtr, 1);
976 CGF.Builder.CreateStore(NumElements, CookiePtr);
977
978 // Finally, compute a pointer to the actual data buffer by skipping
979 // over the cookie completely.
980 CharUnits CookieSize = 2 * SizeSize;
981 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
982 CookieSize.getQuantity());
983}
984
985void ARMCXXABI::ReadArrayCookie(CodeGenFunction &CGF,
986 llvm::Value *Ptr,
987 QualType ElementType,
988 llvm::Value *&NumElements,
989 llvm::Value *&AllocPtr,
990 CharUnits &CookieSize) {
991 // Derive a char* in the same address space as the pointer.
992 unsigned AS = cast<llvm::PointerType>(Ptr->getType())->getAddressSpace();
993 const llvm::Type *CharPtrTy = CGF.Builder.getInt8Ty()->getPointerTo(AS);
994
995 // If we don't need an array cookie, bail out early.
996 if (!NeedsArrayCookie(ElementType)) {
997 AllocPtr = CGF.Builder.CreateBitCast(Ptr, CharPtrTy);
998 NumElements = 0;
999 CookieSize = CharUnits::Zero();
1000 return;
1001 }
1002
John McCall9cb2cee2010-09-02 10:25:57 +00001003 QualType SizeTy = getContext().getSizeType();
1004 CharUnits SizeSize = getContext().getTypeSizeInChars(SizeTy);
John McCall1e7fe752010-09-02 09:58:18 +00001005 const llvm::Type *SizeLTy = CGF.ConvertType(SizeTy);
1006
1007 // The cookie size is always 2 * sizeof(size_t).
1008 CookieSize = 2 * SizeSize;
1009 CharUnits NumElementsOffset = CookieSize - SizeSize;
1010
1011 // The allocated pointer is the input ptr, minus that amount.
1012 AllocPtr = CGF.Builder.CreateBitCast(Ptr, CharPtrTy);
1013 AllocPtr = CGF.Builder.CreateConstInBoundsGEP1_64(AllocPtr,
1014 -CookieSize.getQuantity());
1015
1016 // The number of elements is at offset sizeof(size_t) relative to that.
1017 llvm::Value *NumElementsPtr
1018 = CGF.Builder.CreateConstInBoundsGEP1_64(AllocPtr,
1019 SizeSize.getQuantity());
1020 NumElementsPtr =
1021 CGF.Builder.CreateBitCast(NumElementsPtr, SizeLTy->getPointerTo(AS));
1022 NumElements = CGF.Builder.CreateLoad(NumElementsPtr);
1023}
1024
John McCall5cd91b52010-09-08 01:44:27 +00001025/*********************** Static local initialization **************************/
1026
1027static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
1028 const llvm::PointerType *GuardPtrTy) {
1029 // int __cxa_guard_acquire(__guard *guard_object);
1030
1031 std::vector<const llvm::Type*> Args(1, GuardPtrTy);
1032 const llvm::FunctionType *FTy =
1033 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
1034 Args, /*isVarArg=*/false);
1035
1036 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire");
1037}
1038
1039static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
1040 const llvm::PointerType *GuardPtrTy) {
1041 // void __cxa_guard_release(__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_release");
1050}
1051
1052static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
1053 const llvm::PointerType *GuardPtrTy) {
1054 // void __cxa_guard_abort(__guard *guard_object);
1055
1056 std::vector<const llvm::Type*> Args(1, GuardPtrTy);
1057
1058 const llvm::FunctionType *FTy =
1059 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
1060 Args, /*isVarArg=*/false);
1061
1062 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort");
1063}
1064
1065namespace {
1066 struct CallGuardAbort : EHScopeStack::Cleanup {
1067 llvm::GlobalVariable *Guard;
1068 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
1069
1070 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1071 CGF.Builder.CreateCall(getGuardAbortFn(CGF.CGM, Guard->getType()), Guard)
1072 ->setDoesNotThrow();
1073 }
1074 };
1075}
1076
1077/// The ARM code here follows the Itanium code closely enough that we
1078/// just special-case it at particular places.
John McCall3030eb82010-11-06 09:44:32 +00001079void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1080 const VarDecl &D,
1081 llvm::GlobalVariable *GV) {
John McCall5cd91b52010-09-08 01:44:27 +00001082 CGBuilderTy &Builder = CGF.Builder;
John McCall3030eb82010-11-06 09:44:32 +00001083
1084 // We only need to use thread-safe statics for local variables;
1085 // global initialization is always single-threaded.
1086 bool ThreadsafeStatics = (getContext().getLangOptions().ThreadsafeStatics &&
1087 D.isLocalVarDecl());
John McCall5cd91b52010-09-08 01:44:27 +00001088
1089 // Guard variables are 64 bits in the generic ABI and 32 bits on ARM.
1090 const llvm::IntegerType *GuardTy
1091 = (IsARM ? Builder.getInt32Ty() : Builder.getInt64Ty());
1092 const llvm::PointerType *GuardPtrTy = GuardTy->getPointerTo();
1093
1094 // Create the guard variable.
1095 llvm::SmallString<256> GuardVName;
1096 getMangleContext().mangleItaniumGuardVariable(&D, GuardVName);
John McCall112c9672010-11-02 21:04:24 +00001097
John McCall3030eb82010-11-06 09:44:32 +00001098 // Just absorb linkage and visibility from the variable.
John McCall5cd91b52010-09-08 01:44:27 +00001099 llvm::GlobalVariable *GuardVariable =
1100 new llvm::GlobalVariable(CGM.getModule(), GuardTy,
John McCall3030eb82010-11-06 09:44:32 +00001101 false, GV->getLinkage(),
John McCall5cd91b52010-09-08 01:44:27 +00001102 llvm::ConstantInt::get(GuardTy, 0),
1103 GuardVName.str());
John McCall112c9672010-11-02 21:04:24 +00001104 GuardVariable->setVisibility(GV->getVisibility());
John McCall5cd91b52010-09-08 01:44:27 +00001105
1106 // Test whether the variable has completed initialization.
1107 llvm::Value *IsInitialized;
1108
1109 // ARM C++ ABI 3.2.3.1:
1110 // To support the potential use of initialization guard variables
1111 // as semaphores that are the target of ARM SWP and LDREX/STREX
1112 // synchronizing instructions we define a static initialization
1113 // guard variable to be a 4-byte aligned, 4- byte word with the
1114 // following inline access protocol.
1115 // #define INITIALIZED 1
1116 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
1117 // if (__cxa_guard_acquire(&obj_guard))
1118 // ...
1119 // }
1120 if (IsARM) {
1121 llvm::Value *V = Builder.CreateLoad(GuardVariable);
1122 V = Builder.CreateAnd(V, Builder.getInt32(1));
1123 IsInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
1124
1125 // Itanium C++ ABI 3.3.2:
1126 // The following is pseudo-code showing how these functions can be used:
1127 // if (obj_guard.first_byte == 0) {
1128 // if ( __cxa_guard_acquire (&obj_guard) ) {
1129 // try {
1130 // ... initialize the object ...;
1131 // } catch (...) {
1132 // __cxa_guard_abort (&obj_guard);
1133 // throw;
1134 // }
1135 // ... queue object destructor with __cxa_atexit() ...;
1136 // __cxa_guard_release (&obj_guard);
1137 // }
1138 // }
1139 } else {
1140 // Load the first byte of the guard variable.
1141 const llvm::Type *PtrTy = Builder.getInt8PtrTy();
1142 llvm::Value *V =
1143 Builder.CreateLoad(Builder.CreateBitCast(GuardVariable, PtrTy), "tmp");
1144
1145 IsInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
1146 }
1147
1148 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1149 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1150
1151 // Check if the first byte of the guard variable is zero.
1152 Builder.CreateCondBr(IsInitialized, InitCheckBlock, EndBlock);
1153
1154 CGF.EmitBlock(InitCheckBlock);
1155
1156 // Variables used when coping with thread-safe statics and exceptions.
1157 if (ThreadsafeStatics) {
1158 // Call __cxa_guard_acquire.
1159 llvm::Value *V
1160 = Builder.CreateCall(getGuardAcquireFn(CGM, GuardPtrTy), GuardVariable);
1161
1162 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1163
1164 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1165 InitBlock, EndBlock);
1166
1167 // Call __cxa_guard_abort along the exceptional edge.
1168 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, GuardVariable);
1169
1170 CGF.EmitBlock(InitBlock);
1171 }
1172
1173 // Emit the initializer and add a global destructor if appropriate.
1174 CGF.EmitCXXGlobalVarDeclInit(D, GV);
1175
1176 if (ThreadsafeStatics) {
1177 // Pop the guard-abort cleanup if we pushed one.
1178 CGF.PopCleanupBlock();
1179
1180 // Call __cxa_guard_release. This cannot throw.
1181 Builder.CreateCall(getGuardReleaseFn(CGM, GuardPtrTy), GuardVariable);
1182 } else {
1183 Builder.CreateStore(llvm::ConstantInt::get(GuardTy, 1), GuardVariable);
1184 }
1185
1186 CGF.EmitBlock(EndBlock);
1187}