blob: 554d2403c013d8266a01f6632690938cb7498c6b [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 McCall1e7fe752010-09-02 09:58:18 +000050 bool NeedsArrayCookie(QualType ElementType);
51
Charles Davis3a811f12010-05-25 19:52:27 +000052public:
John McCallbabc9a92010-08-22 00:59:17 +000053 ItaniumCXXABI(CodeGen::CodeGenModule &CGM, bool IsARM = false) :
Peter Collingbourne14110472011-01-13 18:57:25 +000054 CGCXXABI(CGM), PtrDiffTy(0), IsARM(IsARM) { }
John McCall93d557b2010-08-22 00:05:51 +000055
John McCallf16aa102010-08-22 21:01:12 +000056 bool isZeroInitializable(const MemberPointerType *MPT);
John McCallcf2c85e2010-08-22 04:16:24 +000057
John McCall0bab0cd2010-08-23 01:21:21 +000058 const llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT);
59
John McCall93d557b2010-08-22 00:05:51 +000060 llvm::Value *EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
61 llvm::Value *&This,
62 llvm::Value *MemFnPtr,
63 const MemberPointerType *MPT);
John McCall3023def2010-08-22 03:04:22 +000064
John McCall6c2ab1d2010-08-31 21:07:20 +000065 llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF,
66 llvm::Value *Base,
67 llvm::Value *MemPtr,
68 const MemberPointerType *MPT);
69
John McCall0bab0cd2010-08-23 01:21:21 +000070 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
71 const CastExpr *E,
72 llvm::Value *Src);
John McCallcf2c85e2010-08-22 04:16:24 +000073
John McCall0bab0cd2010-08-23 01:21:21 +000074 llvm::Constant *EmitMemberPointerConversion(llvm::Constant *C,
75 const CastExpr *E);
John McCallcf2c85e2010-08-22 04:16:24 +000076
John McCall0bab0cd2010-08-23 01:21:21 +000077 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
John McCallcf2c85e2010-08-22 04:16:24 +000078
John McCall0bab0cd2010-08-23 01:21:21 +000079 llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
80 llvm::Constant *EmitMemberPointer(const FieldDecl *FD);
John McCall875ab102010-08-22 06:43:33 +000081
John McCall0bab0cd2010-08-23 01:21:21 +000082 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
83 llvm::Value *L,
84 llvm::Value *R,
85 const MemberPointerType *MPT,
86 bool Inequality);
John McCalle9fd7eb2010-08-22 08:30:07 +000087
John McCall0bab0cd2010-08-23 01:21:21 +000088 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
89 llvm::Value *Addr,
90 const MemberPointerType *MPT);
John McCall4c40d982010-08-31 07:33:07 +000091
92 void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
93 CXXCtorType T,
94 CanQualType &ResTy,
95 llvm::SmallVectorImpl<CanQualType> &ArgTys);
96
97 void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
98 CXXDtorType T,
99 CanQualType &ResTy,
100 llvm::SmallVectorImpl<CanQualType> &ArgTys);
101
102 void BuildInstanceFunctionParams(CodeGenFunction &CGF,
103 QualType &ResTy,
104 FunctionArgList &Params);
105
106 void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
John McCall1e7fe752010-09-02 09:58:18 +0000107
108 CharUnits GetArrayCookieSize(QualType ElementType);
109 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
110 llvm::Value *NewPtr,
111 llvm::Value *NumElements,
112 QualType ElementType);
113 void ReadArrayCookie(CodeGenFunction &CGF, llvm::Value *Ptr,
114 QualType ElementType, llvm::Value *&NumElements,
115 llvm::Value *&AllocPtr, CharUnits &CookieSize);
John McCall5cd91b52010-09-08 01:44:27 +0000116
John McCall3030eb82010-11-06 09:44:32 +0000117 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
118 llvm::GlobalVariable *DeclPtr);
Charles Davis3a811f12010-05-25 19:52:27 +0000119};
John McCallee79a4c2010-08-21 22:46:04 +0000120
121class ARMCXXABI : public ItaniumCXXABI {
122public:
John McCallbabc9a92010-08-22 00:59:17 +0000123 ARMCXXABI(CodeGen::CodeGenModule &CGM) : ItaniumCXXABI(CGM, /*ARM*/ true) {}
John McCall4c40d982010-08-31 07:33:07 +0000124
125 void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
126 CXXCtorType T,
127 CanQualType &ResTy,
128 llvm::SmallVectorImpl<CanQualType> &ArgTys);
129
130 void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
131 CXXDtorType T,
132 CanQualType &ResTy,
133 llvm::SmallVectorImpl<CanQualType> &ArgTys);
134
135 void BuildInstanceFunctionParams(CodeGenFunction &CGF,
136 QualType &ResTy,
137 FunctionArgList &Params);
138
139 void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
140
141 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV, QualType ResTy);
142
John McCall1e7fe752010-09-02 09:58:18 +0000143 CharUnits GetArrayCookieSize(QualType ElementType);
144 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
145 llvm::Value *NewPtr,
146 llvm::Value *NumElements,
147 QualType ElementType);
148 void ReadArrayCookie(CodeGenFunction &CGF, llvm::Value *Ptr,
149 QualType ElementType, llvm::Value *&NumElements,
150 llvm::Value *&AllocPtr, CharUnits &CookieSize);
John McCall4c40d982010-08-31 07:33:07 +0000151
152private:
153 /// \brief Returns true if the given instance method is one of the
154 /// kinds that the ARM ABI says returns 'this'.
155 static bool HasThisReturn(GlobalDecl GD) {
156 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
157 return ((isa<CXXDestructorDecl>(MD) && GD.getDtorType() != Dtor_Deleting) ||
158 (isa<CXXConstructorDecl>(MD)));
159 }
John McCallee79a4c2010-08-21 22:46:04 +0000160};
Charles Davis3a811f12010-05-25 19:52:27 +0000161}
162
Charles Davis071cc7d2010-08-16 03:33:14 +0000163CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
Charles Davis3a811f12010-05-25 19:52:27 +0000164 return new ItaniumCXXABI(CGM);
165}
166
John McCallee79a4c2010-08-21 22:46:04 +0000167CodeGen::CGCXXABI *CodeGen::CreateARMCXXABI(CodeGenModule &CGM) {
168 return new ARMCXXABI(CGM);
169}
170
John McCall0bab0cd2010-08-23 01:21:21 +0000171const llvm::Type *
172ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
173 if (MPT->isMemberDataPointer())
174 return getPtrDiffTy();
175 else
176 return llvm::StructType::get(CGM.getLLVMContext(),
177 getPtrDiffTy(), getPtrDiffTy(), NULL);
John McCall875ab102010-08-22 06:43:33 +0000178}
179
John McCallbabc9a92010-08-22 00:59:17 +0000180/// In the Itanium and ARM ABIs, method pointers have the form:
181/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
182///
183/// In the Itanium ABI:
184/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
185/// - the this-adjustment is (memptr.adj)
186/// - the virtual offset is (memptr.ptr - 1)
187///
188/// In the ARM ABI:
189/// - method pointers are virtual if (memptr.adj & 1) is nonzero
190/// - the this-adjustment is (memptr.adj >> 1)
191/// - the virtual offset is (memptr.ptr)
192/// ARM uses 'adj' for the virtual flag because Thumb functions
193/// may be only single-byte aligned.
194///
195/// If the member is virtual, the adjusted 'this' pointer points
196/// to a vtable pointer from which the virtual offset is applied.
197///
198/// If the member is non-virtual, memptr.ptr is the address of
199/// the function to call.
John McCall93d557b2010-08-22 00:05:51 +0000200llvm::Value *
201ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
202 llvm::Value *&This,
203 llvm::Value *MemFnPtr,
204 const MemberPointerType *MPT) {
205 CGBuilderTy &Builder = CGF.Builder;
206
207 const FunctionProtoType *FPT =
208 MPT->getPointeeType()->getAs<FunctionProtoType>();
209 const CXXRecordDecl *RD =
210 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
211
212 const llvm::FunctionType *FTy =
213 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(RD, FPT),
214 FPT->isVariadic());
215
John McCall0bab0cd2010-08-23 01:21:21 +0000216 const llvm::IntegerType *ptrdiff = getPtrDiffTy();
John McCallbabc9a92010-08-22 00:59:17 +0000217 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(ptrdiff, 1);
John McCall93d557b2010-08-22 00:05:51 +0000218
John McCallbabc9a92010-08-22 00:59:17 +0000219 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
220 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
221 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
222
John McCalld608cdb2010-08-22 10:59:02 +0000223 // Extract memptr.adj, which is in the second field.
224 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCallbabc9a92010-08-22 00:59:17 +0000225
226 // Compute the true adjustment.
227 llvm::Value *Adj = RawAdj;
228 if (IsARM)
229 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall93d557b2010-08-22 00:05:51 +0000230
231 // Apply the adjustment and cast back to the original struct type
232 // for consistency.
John McCallbabc9a92010-08-22 00:59:17 +0000233 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
234 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
235 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall93d557b2010-08-22 00:05:51 +0000236
237 // Load the function pointer.
John McCalld608cdb2010-08-22 10:59:02 +0000238 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall93d557b2010-08-22 00:05:51 +0000239
240 // If the LSB in the function pointer is 1, the function pointer points to
241 // a virtual function.
John McCallbabc9a92010-08-22 00:59:17 +0000242 llvm::Value *IsVirtual;
243 if (IsARM)
244 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
245 else
246 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
247 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall93d557b2010-08-22 00:05:51 +0000248 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
249
250 // In the virtual path, the adjustment left 'This' pointing to the
251 // vtable of the correct base subobject. The "function pointer" is an
John McCallbabc9a92010-08-22 00:59:17 +0000252 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall93d557b2010-08-22 00:05:51 +0000253 CGF.EmitBlock(FnVirtual);
254
255 // Cast the adjusted this to a pointer to vtable pointer and load.
256 const llvm::Type *VTableTy = Builder.getInt8PtrTy();
257 llvm::Value *VTable = Builder.CreateBitCast(This, VTableTy->getPointerTo());
John McCallbabc9a92010-08-22 00:59:17 +0000258 VTable = Builder.CreateLoad(VTable, "memptr.vtable");
John McCall93d557b2010-08-22 00:05:51 +0000259
260 // Apply the offset.
John McCallbabc9a92010-08-22 00:59:17 +0000261 llvm::Value *VTableOffset = FnAsInt;
262 if (!IsARM) VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
263 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall93d557b2010-08-22 00:05:51 +0000264
265 // Load the virtual function to call.
266 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCallbabc9a92010-08-22 00:59:17 +0000267 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
John McCall93d557b2010-08-22 00:05:51 +0000268 CGF.EmitBranch(FnEnd);
269
270 // In the non-virtual path, the function pointer is actually a
271 // function pointer.
272 CGF.EmitBlock(FnNonVirtual);
273 llvm::Value *NonVirtualFn =
John McCallbabc9a92010-08-22 00:59:17 +0000274 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall93d557b2010-08-22 00:05:51 +0000275
276 // We're done.
277 CGF.EmitBlock(FnEnd);
278 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo());
279 Callee->reserveOperandSpace(2);
280 Callee->addIncoming(VirtualFn, FnVirtual);
281 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
282 return Callee;
283}
John McCall3023def2010-08-22 03:04:22 +0000284
John McCall6c2ab1d2010-08-31 21:07:20 +0000285/// Compute an l-value by applying the given pointer-to-member to a
286/// base object.
287llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF,
288 llvm::Value *Base,
289 llvm::Value *MemPtr,
290 const MemberPointerType *MPT) {
291 assert(MemPtr->getType() == getPtrDiffTy());
292
293 CGBuilderTy &Builder = CGF.Builder;
294
295 unsigned AS = cast<llvm::PointerType>(Base->getType())->getAddressSpace();
296
297 // Cast to char*.
298 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
299
300 // Apply the offset, which we assume is non-null.
301 llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
302
303 // Cast the address to the appropriate pointer type, adopting the
304 // address space of the base pointer.
Douglas Gregoreede61a2010-09-02 17:38:50 +0000305 const llvm::Type *PType
306 = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
John McCall6c2ab1d2010-08-31 21:07:20 +0000307 return Builder.CreateBitCast(Addr, PType);
308}
309
John McCall3023def2010-08-22 03:04:22 +0000310/// Perform a derived-to-base or base-to-derived member pointer conversion.
John McCall0bab0cd2010-08-23 01:21:21 +0000311///
312/// Obligatory offset/adjustment diagram:
313/// <-- offset --> <-- adjustment -->
314/// |--------------------------|----------------------|--------------------|
315/// ^Derived address point ^Base address point ^Member address point
316///
317/// So when converting a base member pointer to a derived member pointer,
318/// we add the offset to the adjustment because the address point has
319/// decreased; and conversely, when converting a derived MP to a base MP
320/// we subtract the offset from the adjustment because the address point
321/// has increased.
322///
323/// The standard forbids (at compile time) conversion to and from
324/// virtual bases, which is why we don't have to consider them here.
325///
326/// The standard forbids (at run time) casting a derived MP to a base
327/// MP when the derived MP does not point to a member of the base.
328/// This is why -1 is a reasonable choice for null data member
329/// pointers.
John McCalld608cdb2010-08-22 10:59:02 +0000330llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000331ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
332 const CastExpr *E,
333 llvm::Value *Src) {
John McCall2de56d12010-08-25 11:45:40 +0000334 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
335 E->getCastKind() == CK_BaseToDerivedMemberPointer);
John McCall3023def2010-08-22 03:04:22 +0000336
John McCalld608cdb2010-08-22 10:59:02 +0000337 if (isa<llvm::Constant>(Src))
John McCall0bab0cd2010-08-23 01:21:21 +0000338 return EmitMemberPointerConversion(cast<llvm::Constant>(Src), E);
John McCalld608cdb2010-08-22 10:59:02 +0000339
John McCall3023def2010-08-22 03:04:22 +0000340 CGBuilderTy &Builder = CGF.Builder;
341
342 const MemberPointerType *SrcTy =
343 E->getSubExpr()->getType()->getAs<MemberPointerType>();
344 const MemberPointerType *DestTy = E->getType()->getAs<MemberPointerType>();
345
346 const CXXRecordDecl *SrcDecl = SrcTy->getClass()->getAsCXXRecordDecl();
347 const CXXRecordDecl *DestDecl = DestTy->getClass()->getAsCXXRecordDecl();
348
John McCall3023def2010-08-22 03:04:22 +0000349 bool DerivedToBase =
John McCall2de56d12010-08-25 11:45:40 +0000350 E->getCastKind() == CK_DerivedToBaseMemberPointer;
John McCall3023def2010-08-22 03:04:22 +0000351
352 const CXXRecordDecl *BaseDecl, *DerivedDecl;
353 if (DerivedToBase)
354 DerivedDecl = SrcDecl, BaseDecl = DestDecl;
355 else
356 BaseDecl = SrcDecl, DerivedDecl = DestDecl;
357
John McCalld608cdb2010-08-22 10:59:02 +0000358 llvm::Constant *Adj =
359 CGF.CGM.GetNonVirtualBaseClassOffset(DerivedDecl,
360 E->path_begin(),
361 E->path_end());
362 if (!Adj) return Src;
John McCall875ab102010-08-22 06:43:33 +0000363
John McCall0bab0cd2010-08-23 01:21:21 +0000364 // For member data pointers, this is just a matter of adding the
365 // offset if the source is non-null.
366 if (SrcTy->isMemberDataPointer()) {
367 llvm::Value *Dst;
368 if (DerivedToBase)
369 Dst = Builder.CreateNSWSub(Src, Adj, "adj");
370 else
371 Dst = Builder.CreateNSWAdd(Src, Adj, "adj");
372
373 // Null check.
374 llvm::Value *Null = llvm::Constant::getAllOnesValue(Src->getType());
375 llvm::Value *IsNull = Builder.CreateICmpEQ(Src, Null, "memptr.isnull");
376 return Builder.CreateSelect(IsNull, Src, Dst);
377 }
378
John McCalld608cdb2010-08-22 10:59:02 +0000379 // The this-adjustment is left-shifted by 1 on ARM.
380 if (IsARM) {
381 uint64_t Offset = cast<llvm::ConstantInt>(Adj)->getZExtValue();
382 Offset <<= 1;
383 Adj = llvm::ConstantInt::get(Adj->getType(), Offset);
384 }
385
John McCalle14add42010-08-22 11:04:31 +0000386 llvm::Value *SrcAdj = Builder.CreateExtractValue(Src, 1, "src.adj");
John McCalld608cdb2010-08-22 10:59:02 +0000387 llvm::Value *DstAdj;
388 if (DerivedToBase)
John McCall0bab0cd2010-08-23 01:21:21 +0000389 DstAdj = Builder.CreateNSWSub(SrcAdj, Adj, "adj");
John McCalld608cdb2010-08-22 10:59:02 +0000390 else
John McCall0bab0cd2010-08-23 01:21:21 +0000391 DstAdj = Builder.CreateNSWAdd(SrcAdj, Adj, "adj");
John McCalld608cdb2010-08-22 10:59:02 +0000392
John McCalle14add42010-08-22 11:04:31 +0000393 return Builder.CreateInsertValue(Src, DstAdj, 1);
John McCall3023def2010-08-22 03:04:22 +0000394}
John McCallcf2c85e2010-08-22 04:16:24 +0000395
396llvm::Constant *
John McCall0bab0cd2010-08-23 01:21:21 +0000397ItaniumCXXABI::EmitMemberPointerConversion(llvm::Constant *C,
398 const CastExpr *E) {
John McCallcf2c85e2010-08-22 04:16:24 +0000399 const MemberPointerType *SrcTy =
400 E->getSubExpr()->getType()->getAs<MemberPointerType>();
401 const MemberPointerType *DestTy =
402 E->getType()->getAs<MemberPointerType>();
403
404 bool DerivedToBase =
John McCall2de56d12010-08-25 11:45:40 +0000405 E->getCastKind() == CK_DerivedToBaseMemberPointer;
John McCallcf2c85e2010-08-22 04:16:24 +0000406
407 const CXXRecordDecl *DerivedDecl;
408 if (DerivedToBase)
409 DerivedDecl = SrcTy->getClass()->getAsCXXRecordDecl();
410 else
411 DerivedDecl = DestTy->getClass()->getAsCXXRecordDecl();
412
413 // Calculate the offset to the base class.
414 llvm::Constant *Offset =
415 CGM.GetNonVirtualBaseClassOffset(DerivedDecl,
416 E->path_begin(),
417 E->path_end());
418 // If there's no offset, we're done.
419 if (!Offset) return C;
420
John McCall0bab0cd2010-08-23 01:21:21 +0000421 // If the source is a member data pointer, we have to do a null
422 // check and then add the offset. In the common case, we can fold
423 // away the offset.
424 if (SrcTy->isMemberDataPointer()) {
425 assert(C->getType() == getPtrDiffTy());
426
427 // If it's a constant int, just create a new constant int.
428 if (llvm::ConstantInt *CI = dyn_cast<llvm::ConstantInt>(C)) {
429 int64_t Src = CI->getSExtValue();
430
431 // Null converts to null.
432 if (Src == -1) return CI;
433
434 // Otherwise, just add the offset.
435 int64_t OffsetV = cast<llvm::ConstantInt>(Offset)->getSExtValue();
436 int64_t Dst = (DerivedToBase ? Src - OffsetV : Src + OffsetV);
437 return llvm::ConstantInt::get(CI->getType(), Dst, /*signed*/ true);
438 }
439
440 // Otherwise, we have to form a constant select expression.
441 llvm::Constant *Null = llvm::Constant::getAllOnesValue(C->getType());
442
443 llvm::Constant *IsNull =
444 llvm::ConstantExpr::getICmp(llvm::ICmpInst::ICMP_EQ, C, Null);
445
446 llvm::Constant *Dst;
447 if (DerivedToBase)
448 Dst = llvm::ConstantExpr::getNSWSub(C, Offset);
449 else
450 Dst = llvm::ConstantExpr::getNSWAdd(C, Offset);
451
452 return llvm::ConstantExpr::getSelect(IsNull, Null, Dst);
453 }
454
John McCall875ab102010-08-22 06:43:33 +0000455 // The this-adjustment is left-shifted by 1 on ARM.
456 if (IsARM) {
John McCall0bab0cd2010-08-23 01:21:21 +0000457 int64_t OffsetV = cast<llvm::ConstantInt>(Offset)->getSExtValue();
John McCall875ab102010-08-22 06:43:33 +0000458 OffsetV <<= 1;
459 Offset = llvm::ConstantInt::get(Offset->getType(), OffsetV);
460 }
461
John McCallcf2c85e2010-08-22 04:16:24 +0000462 llvm::ConstantStruct *CS = cast<llvm::ConstantStruct>(C);
463
John McCall0bab0cd2010-08-23 01:21:21 +0000464 llvm::Constant *Values[2] = { CS->getOperand(0), 0 };
465 if (DerivedToBase)
466 Values[1] = llvm::ConstantExpr::getSub(CS->getOperand(1), Offset);
467 else
468 Values[1] = llvm::ConstantExpr::getAdd(CS->getOperand(1), Offset);
469
John McCallcf2c85e2010-08-22 04:16:24 +0000470 return llvm::ConstantStruct::get(CGM.getLLVMContext(), Values, 2,
471 /*Packed=*/false);
472}
473
474
John McCallcf2c85e2010-08-22 04:16:24 +0000475llvm::Constant *
John McCall0bab0cd2010-08-23 01:21:21 +0000476ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
477 const llvm::Type *ptrdiff_t = getPtrDiffTy();
478
479 // Itanium C++ ABI 2.3:
480 // A NULL pointer is represented as -1.
481 if (MPT->isMemberDataPointer())
482 return llvm::ConstantInt::get(ptrdiff_t, -1ULL, /*isSigned=*/true);
John McCalld608cdb2010-08-22 10:59:02 +0000483
484 llvm::Constant *Zero = llvm::ConstantInt::get(ptrdiff_t, 0);
485 llvm::Constant *Values[2] = { Zero, Zero };
486 return llvm::ConstantStruct::get(CGM.getLLVMContext(), Values, 2,
487 /*Packed=*/false);
John McCallcf2c85e2010-08-22 04:16:24 +0000488}
489
John McCall0bab0cd2010-08-23 01:21:21 +0000490llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const FieldDecl *FD) {
491 // Itanium C++ ABI 2.3:
492 // A pointer to data member is an offset from the base address of
493 // the class object containing it, represented as a ptrdiff_t
494
John McCall0bab0cd2010-08-23 01:21:21 +0000495 const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(FD->getParent());
Anders Carlsson8a9dc4f2010-11-24 21:53:50 +0000496 const llvm::StructType *ClassLTy = RL.getLLVMType();
497
John McCall0bab0cd2010-08-23 01:21:21 +0000498 unsigned FieldNo = RL.getLLVMFieldNo(FD);
499 uint64_t Offset =
500 CGM.getTargetData().getStructLayout(ClassLTy)->getElementOffset(FieldNo);
501
502 return llvm::ConstantInt::get(getPtrDiffTy(), Offset);
503}
504
505llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
John McCalld608cdb2010-08-22 10:59:02 +0000506 assert(MD->isInstance() && "Member function must not be static!");
507 MD = MD->getCanonicalDecl();
508
509 CodeGenTypes &Types = CGM.getTypes();
John McCall0bab0cd2010-08-23 01:21:21 +0000510 const llvm::Type *ptrdiff_t = getPtrDiffTy();
John McCalld608cdb2010-08-22 10:59:02 +0000511
512 // Get the function pointer (or index if this is a virtual function).
513 llvm::Constant *MemPtr[2];
514 if (MD->isVirtual()) {
515 uint64_t Index = CGM.getVTables().getMethodVTableIndex(MD);
516
517 // FIXME: We shouldn't use / 8 here.
518 uint64_t PointerWidthInBytes =
John McCall9cb2cee2010-09-02 10:25:57 +0000519 getContext().Target.getPointerWidth(0) / 8;
John McCalld608cdb2010-08-22 10:59:02 +0000520 uint64_t VTableOffset = (Index * PointerWidthInBytes);
521
522 if (IsARM) {
523 // ARM C++ ABI 3.2.1:
524 // This ABI specifies that adj contains twice the this
525 // adjustment, plus 1 if the member function is virtual. The
526 // least significant bit of adj then makes exactly the same
527 // discrimination as the least significant bit of ptr does for
528 // Itanium.
529 MemPtr[0] = llvm::ConstantInt::get(ptrdiff_t, VTableOffset);
530 MemPtr[1] = llvm::ConstantInt::get(ptrdiff_t, 1);
531 } else {
532 // Itanium C++ ABI 2.3:
533 // For a virtual function, [the pointer field] is 1 plus the
534 // virtual table offset (in bytes) of the function,
535 // represented as a ptrdiff_t.
536 MemPtr[0] = llvm::ConstantInt::get(ptrdiff_t, VTableOffset + 1);
537 MemPtr[1] = llvm::ConstantInt::get(ptrdiff_t, 0);
538 }
539 } else {
540 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
541 const llvm::Type *Ty;
542 // Check whether the function has a computable LLVM signature.
543 if (!CodeGenTypes::VerifyFuncTypeComplete(FPT)) {
544 // The function has a computable LLVM signature; use the correct type.
545 Ty = Types.GetFunctionType(Types.getFunctionInfo(MD), FPT->isVariadic());
546 } else {
547 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
548 // function type is incomplete.
549 Ty = ptrdiff_t;
550 }
551
552 llvm::Constant *Addr = CGM.GetAddrOfFunction(MD, Ty);
553 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(Addr, ptrdiff_t);
554 MemPtr[1] = llvm::ConstantInt::get(ptrdiff_t, 0);
555 }
John McCall875ab102010-08-22 06:43:33 +0000556
557 return llvm::ConstantStruct::get(CGM.getLLVMContext(),
John McCalld608cdb2010-08-22 10:59:02 +0000558 MemPtr, 2, /*Packed=*/false);
John McCall875ab102010-08-22 06:43:33 +0000559}
560
John McCalle9fd7eb2010-08-22 08:30:07 +0000561/// The comparison algorithm is pretty easy: the member pointers are
562/// the same if they're either bitwise identical *or* both null.
563///
564/// ARM is different here only because null-ness is more complicated.
565llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000566ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
567 llvm::Value *L,
568 llvm::Value *R,
569 const MemberPointerType *MPT,
570 bool Inequality) {
John McCalle9fd7eb2010-08-22 08:30:07 +0000571 CGBuilderTy &Builder = CGF.Builder;
572
John McCalle9fd7eb2010-08-22 08:30:07 +0000573 llvm::ICmpInst::Predicate Eq;
574 llvm::Instruction::BinaryOps And, Or;
575 if (Inequality) {
576 Eq = llvm::ICmpInst::ICMP_NE;
577 And = llvm::Instruction::Or;
578 Or = llvm::Instruction::And;
579 } else {
580 Eq = llvm::ICmpInst::ICMP_EQ;
581 And = llvm::Instruction::And;
582 Or = llvm::Instruction::Or;
583 }
584
John McCall0bab0cd2010-08-23 01:21:21 +0000585 // Member data pointers are easy because there's a unique null
586 // value, so it just comes down to bitwise equality.
587 if (MPT->isMemberDataPointer())
588 return Builder.CreateICmp(Eq, L, R);
589
590 // For member function pointers, the tautologies are more complex.
591 // The Itanium tautology is:
John McCallde719f72010-08-23 06:56:36 +0000592 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall0bab0cd2010-08-23 01:21:21 +0000593 // The ARM tautology is:
John McCallde719f72010-08-23 06:56:36 +0000594 // (L == R) <==> (L.ptr == R.ptr &&
595 // (L.adj == R.adj ||
596 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall0bab0cd2010-08-23 01:21:21 +0000597 // The inequality tautologies have exactly the same structure, except
598 // applying De Morgan's laws.
599
600 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
601 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
602
John McCalle9fd7eb2010-08-22 08:30:07 +0000603 // This condition tests whether L.ptr == R.ptr. This must always be
604 // true for equality to hold.
605 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
606
607 // This condition, together with the assumption that L.ptr == R.ptr,
608 // tests whether the pointers are both null. ARM imposes an extra
609 // condition.
610 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
611 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
612
613 // This condition tests whether L.adj == R.adj. If this isn't
614 // true, the pointers are unequal unless they're both null.
John McCalld608cdb2010-08-22 10:59:02 +0000615 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
616 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCalle9fd7eb2010-08-22 08:30:07 +0000617 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
618
619 // Null member function pointers on ARM clear the low bit of Adj,
620 // so the zero condition has to check that neither low bit is set.
621 if (IsARM) {
622 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
623
624 // Compute (l.adj | r.adj) & 1 and test it against zero.
625 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
626 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
627 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
628 "cmp.or.adj");
629 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
630 }
631
632 // Tie together all our conditions.
633 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
634 Result = Builder.CreateBinOp(And, PtrEq, Result,
635 Inequality ? "memptr.ne" : "memptr.eq");
636 return Result;
637}
638
639llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000640ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
641 llvm::Value *MemPtr,
642 const MemberPointerType *MPT) {
John McCalle9fd7eb2010-08-22 08:30:07 +0000643 CGBuilderTy &Builder = CGF.Builder;
John McCall0bab0cd2010-08-23 01:21:21 +0000644
645 /// For member data pointers, this is just a check against -1.
646 if (MPT->isMemberDataPointer()) {
647 assert(MemPtr->getType() == getPtrDiffTy());
648 llvm::Value *NegativeOne =
649 llvm::Constant::getAllOnesValue(MemPtr->getType());
650 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
651 }
John McCalle9fd7eb2010-08-22 08:30:07 +0000652
653 // In Itanium, a member function pointer is null if 'ptr' is null.
John McCalld608cdb2010-08-22 10:59:02 +0000654 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCalle9fd7eb2010-08-22 08:30:07 +0000655
656 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
657 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
658
659 // In ARM, it's that, plus the low bit of 'adj' must be zero.
660 if (IsARM) {
661 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalld608cdb2010-08-22 10:59:02 +0000662 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCalle9fd7eb2010-08-22 08:30:07 +0000663 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
664 llvm::Value *IsNotVirtual = Builder.CreateICmpEQ(VirtualBit, Zero,
665 "memptr.notvirtual");
666 Result = Builder.CreateAnd(Result, IsNotVirtual);
667 }
668
669 return Result;
670}
John McCall875ab102010-08-22 06:43:33 +0000671
John McCallf16aa102010-08-22 21:01:12 +0000672/// The Itanium ABI requires non-zero initialization only for data
673/// member pointers, for which '0' is a valid offset.
674bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
675 return MPT->getPointeeType()->isFunctionType();
John McCallcf2c85e2010-08-22 04:16:24 +0000676}
John McCall4c40d982010-08-31 07:33:07 +0000677
678/// The generic ABI passes 'this', plus a VTT if it's initializing a
679/// base subobject.
680void ItaniumCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
681 CXXCtorType Type,
682 CanQualType &ResTy,
683 llvm::SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9cb2cee2010-09-02 10:25:57 +0000684 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000685
686 // 'this' is already there.
687
688 // Check if we need to add a VTT parameter (which has type void **).
689 if (Type == Ctor_Base && Ctor->getParent()->getNumVBases() != 0)
690 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
691}
692
693/// The ARM ABI does the same as the Itanium ABI, but returns 'this'.
694void ARMCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
695 CXXCtorType Type,
696 CanQualType &ResTy,
697 llvm::SmallVectorImpl<CanQualType> &ArgTys) {
698 ItaniumCXXABI::BuildConstructorSignature(Ctor, Type, ResTy, ArgTys);
699 ResTy = ArgTys[0];
700}
701
702/// The generic ABI passes 'this', plus a VTT if it's destroying a
703/// base subobject.
704void ItaniumCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
705 CXXDtorType Type,
706 CanQualType &ResTy,
707 llvm::SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9cb2cee2010-09-02 10:25:57 +0000708 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000709
710 // 'this' is already there.
711
712 // Check if we need to add a VTT parameter (which has type void **).
713 if (Type == Dtor_Base && Dtor->getParent()->getNumVBases() != 0)
714 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
715}
716
717/// The ARM ABI does the same as the Itanium ABI, but returns 'this'
718/// for non-deleting destructors.
719void ARMCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
720 CXXDtorType Type,
721 CanQualType &ResTy,
722 llvm::SmallVectorImpl<CanQualType> &ArgTys) {
723 ItaniumCXXABI::BuildDestructorSignature(Dtor, Type, ResTy, ArgTys);
724
725 if (Type != Dtor_Deleting)
726 ResTy = ArgTys[0];
727}
728
729void ItaniumCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
730 QualType &ResTy,
731 FunctionArgList &Params) {
732 /// Create the 'this' variable.
733 BuildThisParam(CGF, Params);
734
735 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
736 assert(MD->isInstance());
737
738 // Check if we need a VTT parameter as well.
739 if (CodeGenVTables::needsVTTParameter(CGF.CurGD)) {
John McCall9cb2cee2010-09-02 10:25:57 +0000740 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000741
742 // FIXME: avoid the fake decl
743 QualType T = Context.getPointerType(Context.VoidPtrTy);
744 ImplicitParamDecl *VTTDecl
745 = ImplicitParamDecl::Create(Context, 0, MD->getLocation(),
746 &Context.Idents.get("vtt"), T);
747 Params.push_back(std::make_pair(VTTDecl, VTTDecl->getType()));
748 getVTTDecl(CGF) = VTTDecl;
749 }
750}
751
752void ARMCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
753 QualType &ResTy,
754 FunctionArgList &Params) {
755 ItaniumCXXABI::BuildInstanceFunctionParams(CGF, ResTy, Params);
756
757 // Return 'this' from certain constructors and destructors.
758 if (HasThisReturn(CGF.CurGD))
759 ResTy = Params[0].second;
760}
761
762void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
763 /// Initialize the 'this' slot.
764 EmitThisParam(CGF);
765
766 /// Initialize the 'vtt' slot if needed.
767 if (getVTTDecl(CGF)) {
768 getVTTValue(CGF)
769 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(getVTTDecl(CGF)),
770 "vtt");
771 }
772}
773
774void ARMCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
775 ItaniumCXXABI::EmitInstanceFunctionProlog(CGF);
776
777 /// Initialize the return slot to 'this' at the start of the
778 /// function.
779 if (HasThisReturn(CGF.CurGD))
780 CGF.Builder.CreateStore(CGF.LoadCXXThis(), CGF.ReturnValue);
781}
782
783void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
784 RValue RV, QualType ResultType) {
785 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
786 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
787
788 // Destructor thunks in the ARM ABI have indeterminate results.
789 const llvm::Type *T =
790 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
791 RValue Undef = RValue::get(llvm::UndefValue::get(T));
792 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
793}
John McCall1e7fe752010-09-02 09:58:18 +0000794
795/************************** Array allocation cookies **************************/
796
797bool ItaniumCXXABI::NeedsArrayCookie(QualType ElementType) {
John McCall9cb2cee2010-09-02 10:25:57 +0000798 ElementType = getContext().getBaseElementType(ElementType);
John McCall1e7fe752010-09-02 09:58:18 +0000799 const RecordType *RT = ElementType->getAs<RecordType>();
800 if (!RT) return false;
801
802 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
803
804 // If the class has a non-trivial destructor, it always needs a cookie.
805 if (!RD->hasTrivialDestructor()) return true;
806
807 // If the class's usual deallocation function takes two arguments,
808 // it needs a cookie. Otherwise we don't need a cookie.
809 const CXXMethodDecl *UsualDeallocationFunction = 0;
810
811 // Usual deallocation functions of this form are always found on the
812 // class.
813 //
814 // FIXME: what exactly is this code supposed to do if there's an
815 // ambiguity? That's possible with using declarations.
816 DeclarationName OpName =
John McCall9cb2cee2010-09-02 10:25:57 +0000817 getContext().DeclarationNames.getCXXOperatorName(OO_Array_Delete);
John McCall1e7fe752010-09-02 09:58:18 +0000818 DeclContext::lookup_const_iterator Op, OpEnd;
819 for (llvm::tie(Op, OpEnd) = RD->lookup(OpName); Op != OpEnd; ++Op) {
820 const CXXMethodDecl *Delete =
821 cast<CXXMethodDecl>((*Op)->getUnderlyingDecl());
822
823 if (Delete->isUsualDeallocationFunction()) {
824 UsualDeallocationFunction = Delete;
825 break;
826 }
827 }
828
829 // No usual deallocation function, we don't need a cookie.
830 if (!UsualDeallocationFunction)
831 return false;
832
833 // The usual deallocation function doesn't take a size_t argument,
834 // so we don't need a cookie.
835 if (UsualDeallocationFunction->getNumParams() == 1)
836 return false;
837
838 assert(UsualDeallocationFunction->getNumParams() == 2 &&
839 "Unexpected deallocation function type!");
840 return true;
841}
842
843CharUnits ItaniumCXXABI::GetArrayCookieSize(QualType ElementType) {
844 if (!NeedsArrayCookie(ElementType))
845 return CharUnits::Zero();
846
847 // Padding is the maximum of sizeof(size_t) and alignof(ElementType)
John McCall9cb2cee2010-09-02 10:25:57 +0000848 ASTContext &Ctx = getContext();
John McCall1e7fe752010-09-02 09:58:18 +0000849 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
850 Ctx.getTypeAlignInChars(ElementType));
851}
852
853llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
854 llvm::Value *NewPtr,
855 llvm::Value *NumElements,
856 QualType ElementType) {
857 assert(NeedsArrayCookie(ElementType));
858
859 unsigned AS = cast<llvm::PointerType>(NewPtr->getType())->getAddressSpace();
860
John McCall9cb2cee2010-09-02 10:25:57 +0000861 ASTContext &Ctx = getContext();
John McCall1e7fe752010-09-02 09:58:18 +0000862 QualType SizeTy = Ctx.getSizeType();
863 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
864
865 // The size of the cookie.
866 CharUnits CookieSize =
867 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
868
869 // Compute an offset to the cookie.
870 llvm::Value *CookiePtr = NewPtr;
871 CharUnits CookieOffset = CookieSize - SizeSize;
872 if (!CookieOffset.isZero())
873 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
874 CookieOffset.getQuantity());
875
876 // Write the number of elements into the appropriate slot.
877 llvm::Value *NumElementsPtr
878 = CGF.Builder.CreateBitCast(CookiePtr,
879 CGF.ConvertType(SizeTy)->getPointerTo(AS));
880 CGF.Builder.CreateStore(NumElements, NumElementsPtr);
881
882 // Finally, compute a pointer to the actual data buffer by skipping
883 // over the cookie completely.
884 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
885 CookieSize.getQuantity());
886}
887
888void ItaniumCXXABI::ReadArrayCookie(CodeGenFunction &CGF,
889 llvm::Value *Ptr,
890 QualType ElementType,
891 llvm::Value *&NumElements,
892 llvm::Value *&AllocPtr,
893 CharUnits &CookieSize) {
894 // Derive a char* in the same address space as the pointer.
895 unsigned AS = cast<llvm::PointerType>(Ptr->getType())->getAddressSpace();
896 const llvm::Type *CharPtrTy = CGF.Builder.getInt8Ty()->getPointerTo(AS);
897
898 // If we don't need an array cookie, bail out early.
899 if (!NeedsArrayCookie(ElementType)) {
900 AllocPtr = CGF.Builder.CreateBitCast(Ptr, CharPtrTy);
901 NumElements = 0;
902 CookieSize = CharUnits::Zero();
903 return;
904 }
905
John McCall9cb2cee2010-09-02 10:25:57 +0000906 QualType SizeTy = getContext().getSizeType();
907 CharUnits SizeSize = getContext().getTypeSizeInChars(SizeTy);
John McCall1e7fe752010-09-02 09:58:18 +0000908 const llvm::Type *SizeLTy = CGF.ConvertType(SizeTy);
909
910 CookieSize
John McCall9cb2cee2010-09-02 10:25:57 +0000911 = std::max(SizeSize, getContext().getTypeAlignInChars(ElementType));
John McCall1e7fe752010-09-02 09:58:18 +0000912
913 CharUnits NumElementsOffset = CookieSize - SizeSize;
914
915 // Compute the allocated pointer.
916 AllocPtr = CGF.Builder.CreateBitCast(Ptr, CharPtrTy);
917 AllocPtr = CGF.Builder.CreateConstInBoundsGEP1_64(AllocPtr,
918 -CookieSize.getQuantity());
919
920 llvm::Value *NumElementsPtr = AllocPtr;
921 if (!NumElementsOffset.isZero())
922 NumElementsPtr =
923 CGF.Builder.CreateConstInBoundsGEP1_64(NumElementsPtr,
924 NumElementsOffset.getQuantity());
925 NumElementsPtr =
926 CGF.Builder.CreateBitCast(NumElementsPtr, SizeLTy->getPointerTo(AS));
927 NumElements = CGF.Builder.CreateLoad(NumElementsPtr);
928}
929
930CharUnits ARMCXXABI::GetArrayCookieSize(QualType ElementType) {
931 if (!NeedsArrayCookie(ElementType))
932 return CharUnits::Zero();
933
934 // On ARM, the cookie is always:
935 // struct array_cookie {
936 // std::size_t element_size; // element_size != 0
937 // std::size_t element_count;
938 // };
939 // TODO: what should we do if the allocated type actually wants
940 // greater alignment?
941 return getContext().getTypeSizeInChars(getContext().getSizeType()) * 2;
942}
943
944llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
945 llvm::Value *NewPtr,
946 llvm::Value *NumElements,
947 QualType ElementType) {
948 assert(NeedsArrayCookie(ElementType));
949
950 // NewPtr is a char*.
951
952 unsigned AS = cast<llvm::PointerType>(NewPtr->getType())->getAddressSpace();
953
John McCall9cb2cee2010-09-02 10:25:57 +0000954 ASTContext &Ctx = getContext();
John McCall1e7fe752010-09-02 09:58:18 +0000955 CharUnits SizeSize = Ctx.getTypeSizeInChars(Ctx.getSizeType());
956 const llvm::IntegerType *SizeTy =
957 cast<llvm::IntegerType>(CGF.ConvertType(Ctx.getSizeType()));
958
959 // The cookie is always at the start of the buffer.
960 llvm::Value *CookiePtr = NewPtr;
961
962 // The first element is the element size.
963 CookiePtr = CGF.Builder.CreateBitCast(CookiePtr, SizeTy->getPointerTo(AS));
964 llvm::Value *ElementSize = llvm::ConstantInt::get(SizeTy,
965 Ctx.getTypeSizeInChars(ElementType).getQuantity());
966 CGF.Builder.CreateStore(ElementSize, CookiePtr);
967
968 // The second element is the element count.
969 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_32(CookiePtr, 1);
970 CGF.Builder.CreateStore(NumElements, CookiePtr);
971
972 // Finally, compute a pointer to the actual data buffer by skipping
973 // over the cookie completely.
974 CharUnits CookieSize = 2 * SizeSize;
975 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
976 CookieSize.getQuantity());
977}
978
979void ARMCXXABI::ReadArrayCookie(CodeGenFunction &CGF,
980 llvm::Value *Ptr,
981 QualType ElementType,
982 llvm::Value *&NumElements,
983 llvm::Value *&AllocPtr,
984 CharUnits &CookieSize) {
985 // Derive a char* in the same address space as the pointer.
986 unsigned AS = cast<llvm::PointerType>(Ptr->getType())->getAddressSpace();
987 const llvm::Type *CharPtrTy = CGF.Builder.getInt8Ty()->getPointerTo(AS);
988
989 // If we don't need an array cookie, bail out early.
990 if (!NeedsArrayCookie(ElementType)) {
991 AllocPtr = CGF.Builder.CreateBitCast(Ptr, CharPtrTy);
992 NumElements = 0;
993 CookieSize = CharUnits::Zero();
994 return;
995 }
996
John McCall9cb2cee2010-09-02 10:25:57 +0000997 QualType SizeTy = getContext().getSizeType();
998 CharUnits SizeSize = getContext().getTypeSizeInChars(SizeTy);
John McCall1e7fe752010-09-02 09:58:18 +0000999 const llvm::Type *SizeLTy = CGF.ConvertType(SizeTy);
1000
1001 // The cookie size is always 2 * sizeof(size_t).
1002 CookieSize = 2 * SizeSize;
1003 CharUnits NumElementsOffset = CookieSize - SizeSize;
1004
1005 // The allocated pointer is the input ptr, minus that amount.
1006 AllocPtr = CGF.Builder.CreateBitCast(Ptr, CharPtrTy);
1007 AllocPtr = CGF.Builder.CreateConstInBoundsGEP1_64(AllocPtr,
1008 -CookieSize.getQuantity());
1009
1010 // The number of elements is at offset sizeof(size_t) relative to that.
1011 llvm::Value *NumElementsPtr
1012 = CGF.Builder.CreateConstInBoundsGEP1_64(AllocPtr,
1013 SizeSize.getQuantity());
1014 NumElementsPtr =
1015 CGF.Builder.CreateBitCast(NumElementsPtr, SizeLTy->getPointerTo(AS));
1016 NumElements = CGF.Builder.CreateLoad(NumElementsPtr);
1017}
1018
John McCall5cd91b52010-09-08 01:44:27 +00001019/*********************** Static local initialization **************************/
1020
1021static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
1022 const llvm::PointerType *GuardPtrTy) {
1023 // int __cxa_guard_acquire(__guard *guard_object);
1024
1025 std::vector<const llvm::Type*> Args(1, GuardPtrTy);
1026 const llvm::FunctionType *FTy =
1027 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
1028 Args, /*isVarArg=*/false);
1029
1030 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire");
1031}
1032
1033static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
1034 const llvm::PointerType *GuardPtrTy) {
1035 // void __cxa_guard_release(__guard *guard_object);
1036
1037 std::vector<const llvm::Type*> Args(1, GuardPtrTy);
1038
1039 const llvm::FunctionType *FTy =
1040 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
1041 Args, /*isVarArg=*/false);
1042
1043 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release");
1044}
1045
1046static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
1047 const llvm::PointerType *GuardPtrTy) {
1048 // void __cxa_guard_abort(__guard *guard_object);
1049
1050 std::vector<const llvm::Type*> Args(1, GuardPtrTy);
1051
1052 const llvm::FunctionType *FTy =
1053 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
1054 Args, /*isVarArg=*/false);
1055
1056 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort");
1057}
1058
1059namespace {
1060 struct CallGuardAbort : EHScopeStack::Cleanup {
1061 llvm::GlobalVariable *Guard;
1062 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
1063
1064 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1065 CGF.Builder.CreateCall(getGuardAbortFn(CGF.CGM, Guard->getType()), Guard)
1066 ->setDoesNotThrow();
1067 }
1068 };
1069}
1070
1071/// The ARM code here follows the Itanium code closely enough that we
1072/// just special-case it at particular places.
John McCall3030eb82010-11-06 09:44:32 +00001073void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1074 const VarDecl &D,
1075 llvm::GlobalVariable *GV) {
John McCall5cd91b52010-09-08 01:44:27 +00001076 CGBuilderTy &Builder = CGF.Builder;
John McCall3030eb82010-11-06 09:44:32 +00001077
1078 // We only need to use thread-safe statics for local variables;
1079 // global initialization is always single-threaded.
1080 bool ThreadsafeStatics = (getContext().getLangOptions().ThreadsafeStatics &&
1081 D.isLocalVarDecl());
John McCall5cd91b52010-09-08 01:44:27 +00001082
1083 // Guard variables are 64 bits in the generic ABI and 32 bits on ARM.
1084 const llvm::IntegerType *GuardTy
1085 = (IsARM ? Builder.getInt32Ty() : Builder.getInt64Ty());
1086 const llvm::PointerType *GuardPtrTy = GuardTy->getPointerTo();
1087
1088 // Create the guard variable.
1089 llvm::SmallString<256> GuardVName;
1090 getMangleContext().mangleItaniumGuardVariable(&D, GuardVName);
John McCall112c9672010-11-02 21:04:24 +00001091
John McCall3030eb82010-11-06 09:44:32 +00001092 // Just absorb linkage and visibility from the variable.
John McCall5cd91b52010-09-08 01:44:27 +00001093 llvm::GlobalVariable *GuardVariable =
1094 new llvm::GlobalVariable(CGM.getModule(), GuardTy,
John McCall3030eb82010-11-06 09:44:32 +00001095 false, GV->getLinkage(),
John McCall5cd91b52010-09-08 01:44:27 +00001096 llvm::ConstantInt::get(GuardTy, 0),
1097 GuardVName.str());
John McCall112c9672010-11-02 21:04:24 +00001098 GuardVariable->setVisibility(GV->getVisibility());
John McCall5cd91b52010-09-08 01:44:27 +00001099
1100 // Test whether the variable has completed initialization.
1101 llvm::Value *IsInitialized;
1102
1103 // ARM C++ ABI 3.2.3.1:
1104 // To support the potential use of initialization guard variables
1105 // as semaphores that are the target of ARM SWP and LDREX/STREX
1106 // synchronizing instructions we define a static initialization
1107 // guard variable to be a 4-byte aligned, 4- byte word with the
1108 // following inline access protocol.
1109 // #define INITIALIZED 1
1110 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
1111 // if (__cxa_guard_acquire(&obj_guard))
1112 // ...
1113 // }
1114 if (IsARM) {
1115 llvm::Value *V = Builder.CreateLoad(GuardVariable);
1116 V = Builder.CreateAnd(V, Builder.getInt32(1));
1117 IsInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
1118
1119 // Itanium C++ ABI 3.3.2:
1120 // The following is pseudo-code showing how these functions can be used:
1121 // if (obj_guard.first_byte == 0) {
1122 // if ( __cxa_guard_acquire (&obj_guard) ) {
1123 // try {
1124 // ... initialize the object ...;
1125 // } catch (...) {
1126 // __cxa_guard_abort (&obj_guard);
1127 // throw;
1128 // }
1129 // ... queue object destructor with __cxa_atexit() ...;
1130 // __cxa_guard_release (&obj_guard);
1131 // }
1132 // }
1133 } else {
1134 // Load the first byte of the guard variable.
1135 const llvm::Type *PtrTy = Builder.getInt8PtrTy();
1136 llvm::Value *V =
1137 Builder.CreateLoad(Builder.CreateBitCast(GuardVariable, PtrTy), "tmp");
1138
1139 IsInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
1140 }
1141
1142 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1143 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1144
1145 // Check if the first byte of the guard variable is zero.
1146 Builder.CreateCondBr(IsInitialized, InitCheckBlock, EndBlock);
1147
1148 CGF.EmitBlock(InitCheckBlock);
1149
1150 // Variables used when coping with thread-safe statics and exceptions.
1151 if (ThreadsafeStatics) {
1152 // Call __cxa_guard_acquire.
1153 llvm::Value *V
1154 = Builder.CreateCall(getGuardAcquireFn(CGM, GuardPtrTy), GuardVariable);
1155
1156 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1157
1158 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1159 InitBlock, EndBlock);
1160
1161 // Call __cxa_guard_abort along the exceptional edge.
1162 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, GuardVariable);
1163
1164 CGF.EmitBlock(InitBlock);
1165 }
1166
1167 // Emit the initializer and add a global destructor if appropriate.
1168 CGF.EmitCXXGlobalVarDeclInit(D, GV);
1169
1170 if (ThreadsafeStatics) {
1171 // Pop the guard-abort cleanup if we pushed one.
1172 CGF.PopCleanupBlock();
1173
1174 // Call __cxa_guard_release. This cannot throw.
1175 Builder.CreateCall(getGuardReleaseFn(CGM, GuardPtrTy), GuardVariable);
1176 } else {
1177 Builder.CreateStore(llvm::ConstantInt::get(GuardTy, 1), GuardVariable);
1178 }
1179
1180 CGF.EmitBlock(EndBlock);
1181}