blob: 2a92258b8469d73b58f1e899c17ec5f604e3d64e [file] [log] [blame]
Anders Carlsson5b955922009-11-24 05:51:11 +00001//===--- CGClass.cpp - Emit LLVM Code for C++ classes ---------------------===//
Anders Carlsson5d58a1d2009-09-12 04:27:24 +00002//
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 contains code dealing with C++ code generation of classes
11//
12//===----------------------------------------------------------------------===//
13
Devang Pateld67ef0e2010-08-11 21:04:37 +000014#include "CGDebugInfo.h"
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000015#include "CodeGenFunction.h"
Anders Carlsson2f1986b2009-10-06 22:43:30 +000016#include "clang/AST/CXXInheritance.h"
John McCall7e1dff72010-09-17 02:31:44 +000017#include "clang/AST/EvaluatedExprVisitor.h"
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000018#include "clang/AST/RecordLayout.h"
John McCall9fc6a772010-02-19 09:25:03 +000019#include "clang/AST/StmtCXX.h"
Anders Carlsson2f1986b2009-10-06 22:43:30 +000020
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000021using namespace clang;
22using namespace CodeGen;
23
Anders Carlsson2f1986b2009-10-06 22:43:30 +000024static uint64_t
Anders Carlsson34a2d382010-04-24 21:06:20 +000025ComputeNonVirtualBaseClassOffset(ASTContext &Context,
26 const CXXRecordDecl *DerivedClass,
John McCallf871d0c2010-08-07 06:22:56 +000027 CastExpr::path_const_iterator Start,
28 CastExpr::path_const_iterator End) {
Anders Carlsson34a2d382010-04-24 21:06:20 +000029 uint64_t Offset = 0;
30
31 const CXXRecordDecl *RD = DerivedClass;
32
John McCallf871d0c2010-08-07 06:22:56 +000033 for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
Anders Carlsson34a2d382010-04-24 21:06:20 +000034 const CXXBaseSpecifier *Base = *I;
35 assert(!Base->isVirtual() && "Should not see virtual bases here!");
36
37 // Get the layout.
38 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
39
40 const CXXRecordDecl *BaseDecl =
41 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
42
43 // Add the offset.
Anders Carlssona14f5972010-10-31 23:22:37 +000044 Offset += Layout.getBaseClassOffsetInBits(BaseDecl);
Anders Carlsson34a2d382010-04-24 21:06:20 +000045
46 RD = BaseDecl;
47 }
48
49 // FIXME: We should not use / 8 here.
50 return Offset / 8;
51}
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000052
Anders Carlsson84080ec2009-09-29 03:13:20 +000053llvm::Constant *
Anders Carlssona04efdf2010-04-24 21:23:59 +000054CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +000055 CastExpr::path_const_iterator PathBegin,
56 CastExpr::path_const_iterator PathEnd) {
57 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssona04efdf2010-04-24 21:23:59 +000058
59 uint64_t Offset =
John McCallf871d0c2010-08-07 06:22:56 +000060 ComputeNonVirtualBaseClassOffset(getContext(), ClassDecl,
61 PathBegin, PathEnd);
Anders Carlssona04efdf2010-04-24 21:23:59 +000062 if (!Offset)
63 return 0;
64
65 const llvm::Type *PtrDiffTy =
66 Types.ConvertType(getContext().getPointerDiffType());
67
68 return llvm::ConstantInt::get(PtrDiffTy, Offset);
Anders Carlsson84080ec2009-09-29 03:13:20 +000069}
70
Anders Carlsson8561a862010-04-24 23:01:49 +000071/// Gets the address of a direct base class within a complete object.
John McCallbff225e2010-02-16 04:15:37 +000072/// This should only be used for (1) non-virtual bases or (2) virtual bases
73/// when the type is known to be complete (e.g. in complete destructors).
74///
75/// The object pointed to by 'This' is assumed to be non-null.
76llvm::Value *
Anders Carlsson8561a862010-04-24 23:01:49 +000077CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(llvm::Value *This,
78 const CXXRecordDecl *Derived,
79 const CXXRecordDecl *Base,
80 bool BaseIsVirtual) {
John McCallbff225e2010-02-16 04:15:37 +000081 // 'this' must be a pointer (in some address space) to Derived.
82 assert(This->getType()->isPointerTy() &&
83 cast<llvm::PointerType>(This->getType())->getElementType()
84 == ConvertType(Derived));
85
86 // Compute the offset of the virtual base.
87 uint64_t Offset;
88 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
Anders Carlsson8561a862010-04-24 23:01:49 +000089 if (BaseIsVirtual)
Anders Carlssona14f5972010-10-31 23:22:37 +000090 Offset = Layout.getVBaseClassOffsetInBits(Base);
John McCallbff225e2010-02-16 04:15:37 +000091 else
Anders Carlssona14f5972010-10-31 23:22:37 +000092 Offset = Layout.getBaseClassOffsetInBits(Base);
John McCallbff225e2010-02-16 04:15:37 +000093
94 // Shift and cast down to the base type.
95 // TODO: for complete types, this should be possible with a GEP.
96 llvm::Value *V = This;
97 if (Offset) {
98 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
99 V = Builder.CreateBitCast(V, Int8PtrTy);
100 V = Builder.CreateConstInBoundsGEP1_64(V, Offset / 8);
101 }
102 V = Builder.CreateBitCast(V, ConvertType(Base)->getPointerTo());
103
104 return V;
Anders Carlssond103f9f2010-03-28 19:40:00 +0000105}
John McCallbff225e2010-02-16 04:15:37 +0000106
Anders Carlsson9dc228a2010-04-20 16:03:35 +0000107static llvm::Value *
108ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, llvm::Value *ThisPtr,
109 uint64_t NonVirtual, llvm::Value *Virtual) {
110 const llvm::Type *PtrDiffTy =
111 CGF.ConvertType(CGF.getContext().getPointerDiffType());
112
113 llvm::Value *NonVirtualOffset = 0;
114 if (NonVirtual)
115 NonVirtualOffset = llvm::ConstantInt::get(PtrDiffTy, NonVirtual);
116
117 llvm::Value *BaseOffset;
118 if (Virtual) {
119 if (NonVirtualOffset)
120 BaseOffset = CGF.Builder.CreateAdd(Virtual, NonVirtualOffset);
121 else
122 BaseOffset = Virtual;
123 } else
124 BaseOffset = NonVirtualOffset;
125
126 // Apply the base offset.
127 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
128 ThisPtr = CGF.Builder.CreateBitCast(ThisPtr, Int8PtrTy);
129 ThisPtr = CGF.Builder.CreateGEP(ThisPtr, BaseOffset, "add.ptr");
130
131 return ThisPtr;
132}
133
Anders Carlsson5d58a1d2009-09-12 04:27:24 +0000134llvm::Value *
Anders Carlsson34a2d382010-04-24 21:06:20 +0000135CodeGenFunction::GetAddressOfBaseClass(llvm::Value *Value,
Anders Carlsson8561a862010-04-24 23:01:49 +0000136 const CXXRecordDecl *Derived,
John McCallf871d0c2010-08-07 06:22:56 +0000137 CastExpr::path_const_iterator PathBegin,
138 CastExpr::path_const_iterator PathEnd,
Anders Carlsson34a2d382010-04-24 21:06:20 +0000139 bool NullCheckValue) {
John McCallf871d0c2010-08-07 06:22:56 +0000140 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlsson34a2d382010-04-24 21:06:20 +0000141
John McCallf871d0c2010-08-07 06:22:56 +0000142 CastExpr::path_const_iterator Start = PathBegin;
Anders Carlsson34a2d382010-04-24 21:06:20 +0000143 const CXXRecordDecl *VBase = 0;
144
145 // Get the virtual base.
146 if ((*Start)->isVirtual()) {
147 VBase =
148 cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
149 ++Start;
150 }
151
152 uint64_t NonVirtualOffset =
Anders Carlsson8561a862010-04-24 23:01:49 +0000153 ComputeNonVirtualBaseClassOffset(getContext(), VBase ? VBase : Derived,
John McCallf871d0c2010-08-07 06:22:56 +0000154 Start, PathEnd);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000155
156 // Get the base pointer type.
157 const llvm::Type *BasePtrTy =
John McCallf871d0c2010-08-07 06:22:56 +0000158 ConvertType((PathEnd[-1])->getType())->getPointerTo();
Anders Carlsson34a2d382010-04-24 21:06:20 +0000159
160 if (!NonVirtualOffset && !VBase) {
161 // Just cast back.
162 return Builder.CreateBitCast(Value, BasePtrTy);
163 }
164
165 llvm::BasicBlock *CastNull = 0;
166 llvm::BasicBlock *CastNotNull = 0;
167 llvm::BasicBlock *CastEnd = 0;
168
169 if (NullCheckValue) {
170 CastNull = createBasicBlock("cast.null");
171 CastNotNull = createBasicBlock("cast.notnull");
172 CastEnd = createBasicBlock("cast.end");
173
174 llvm::Value *IsNull =
175 Builder.CreateICmpEQ(Value,
176 llvm::Constant::getNullValue(Value->getType()));
177 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
178 EmitBlock(CastNotNull);
179 }
180
181 llvm::Value *VirtualOffset = 0;
182
183 if (VBase)
Anders Carlsson8561a862010-04-24 23:01:49 +0000184 VirtualOffset = GetVirtualBaseClassOffset(Value, Derived, VBase);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000185
186 // Apply the offsets.
187 Value = ApplyNonVirtualAndVirtualOffset(*this, Value, NonVirtualOffset,
188 VirtualOffset);
189
190 // Cast back.
191 Value = Builder.CreateBitCast(Value, BasePtrTy);
192
193 if (NullCheckValue) {
194 Builder.CreateBr(CastEnd);
195 EmitBlock(CastNull);
196 Builder.CreateBr(CastEnd);
197 EmitBlock(CastEnd);
198
199 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType());
200 PHI->reserveOperandSpace(2);
201 PHI->addIncoming(Value, CastNotNull);
202 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
203 CastNull);
204 Value = PHI;
205 }
206
207 return Value;
208}
209
210llvm::Value *
Anders Carlssona3697c92009-11-23 17:57:54 +0000211CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value,
Anders Carlsson8561a862010-04-24 23:01:49 +0000212 const CXXRecordDecl *Derived,
John McCallf871d0c2010-08-07 06:22:56 +0000213 CastExpr::path_const_iterator PathBegin,
214 CastExpr::path_const_iterator PathEnd,
Anders Carlssona3697c92009-11-23 17:57:54 +0000215 bool NullCheckValue) {
John McCallf871d0c2010-08-07 06:22:56 +0000216 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssona04efdf2010-04-24 21:23:59 +0000217
Anders Carlssona3697c92009-11-23 17:57:54 +0000218 QualType DerivedTy =
Anders Carlsson8561a862010-04-24 23:01:49 +0000219 getContext().getCanonicalType(getContext().getTagDeclType(Derived));
Anders Carlssona3697c92009-11-23 17:57:54 +0000220 const llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
221
Anders Carlssona552ea72010-01-31 01:43:37 +0000222 llvm::Value *NonVirtualOffset =
John McCallf871d0c2010-08-07 06:22:56 +0000223 CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
Anders Carlssona552ea72010-01-31 01:43:37 +0000224
225 if (!NonVirtualOffset) {
226 // No offset, we can just cast back.
227 return Builder.CreateBitCast(Value, DerivedPtrTy);
228 }
229
Anders Carlssona3697c92009-11-23 17:57:54 +0000230 llvm::BasicBlock *CastNull = 0;
231 llvm::BasicBlock *CastNotNull = 0;
232 llvm::BasicBlock *CastEnd = 0;
233
234 if (NullCheckValue) {
235 CastNull = createBasicBlock("cast.null");
236 CastNotNull = createBasicBlock("cast.notnull");
237 CastEnd = createBasicBlock("cast.end");
238
239 llvm::Value *IsNull =
240 Builder.CreateICmpEQ(Value,
241 llvm::Constant::getNullValue(Value->getType()));
242 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
243 EmitBlock(CastNotNull);
244 }
245
Anders Carlssona552ea72010-01-31 01:43:37 +0000246 // Apply the offset.
247 Value = Builder.CreatePtrToInt(Value, NonVirtualOffset->getType());
248 Value = Builder.CreateSub(Value, NonVirtualOffset);
249 Value = Builder.CreateIntToPtr(Value, DerivedPtrTy);
250
251 // Just cast.
252 Value = Builder.CreateBitCast(Value, DerivedPtrTy);
Anders Carlssona3697c92009-11-23 17:57:54 +0000253
254 if (NullCheckValue) {
255 Builder.CreateBr(CastEnd);
256 EmitBlock(CastNull);
257 Builder.CreateBr(CastEnd);
258 EmitBlock(CastEnd);
259
260 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType());
261 PHI->reserveOperandSpace(2);
262 PHI->addIncoming(Value, CastNotNull);
263 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
264 CastNull);
265 Value = PHI;
266 }
267
268 return Value;
Anders Carlsson5d58a1d2009-09-12 04:27:24 +0000269}
Anders Carlsson21c9ad92010-03-30 03:27:09 +0000270
Anders Carlssonc997d422010-01-02 01:01:18 +0000271/// GetVTTParameter - Return the VTT parameter that should be passed to a
272/// base constructor/destructor with virtual bases.
Anders Carlsson314e6222010-05-02 23:33:10 +0000273static llvm::Value *GetVTTParameter(CodeGenFunction &CGF, GlobalDecl GD,
274 bool ForVirtualBase) {
Anders Carlssonaf440352010-03-23 04:11:45 +0000275 if (!CodeGenVTables::needsVTTParameter(GD)) {
Anders Carlssonc997d422010-01-02 01:01:18 +0000276 // This constructor/destructor does not need a VTT parameter.
277 return 0;
278 }
279
280 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CGF.CurFuncDecl)->getParent();
281 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
John McCall3b477332010-02-18 19:59:28 +0000282
Anders Carlssonc997d422010-01-02 01:01:18 +0000283 llvm::Value *VTT;
284
John McCall3b477332010-02-18 19:59:28 +0000285 uint64_t SubVTTIndex;
286
287 // If the record matches the base, this is the complete ctor/dtor
288 // variant calling the base variant in a class with virtual bases.
289 if (RD == Base) {
Anders Carlssonaf440352010-03-23 04:11:45 +0000290 assert(!CodeGenVTables::needsVTTParameter(CGF.CurGD) &&
John McCall3b477332010-02-18 19:59:28 +0000291 "doing no-op VTT offset in base dtor/ctor?");
Anders Carlsson314e6222010-05-02 23:33:10 +0000292 assert(!ForVirtualBase && "Can't have same class as virtual base!");
John McCall3b477332010-02-18 19:59:28 +0000293 SubVTTIndex = 0;
294 } else {
Anders Carlssonc11bb212010-05-02 23:53:25 +0000295 const ASTRecordLayout &Layout =
296 CGF.getContext().getASTRecordLayout(RD);
297 uint64_t BaseOffset = ForVirtualBase ?
Anders Carlssona14f5972010-10-31 23:22:37 +0000298 Layout.getVBaseClassOffsetInBits(Base) :
299 Layout.getBaseClassOffsetInBits(Base);
Anders Carlssonc11bb212010-05-02 23:53:25 +0000300
301 SubVTTIndex =
302 CGF.CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
John McCall3b477332010-02-18 19:59:28 +0000303 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
304 }
Anders Carlssonc997d422010-01-02 01:01:18 +0000305
Anders Carlssonaf440352010-03-23 04:11:45 +0000306 if (CodeGenVTables::needsVTTParameter(CGF.CurGD)) {
Anders Carlssonc997d422010-01-02 01:01:18 +0000307 // A VTT parameter was passed to the constructor, use it.
308 VTT = CGF.LoadCXXVTT();
309 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
310 } else {
311 // We're the complete constructor, so get the VTT by name.
Anders Carlssonaf440352010-03-23 04:11:45 +0000312 VTT = CGF.CGM.getVTables().getVTT(RD);
Anders Carlssonc997d422010-01-02 01:01:18 +0000313 VTT = CGF.Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
314 }
315
316 return VTT;
317}
318
John McCall182ab512010-07-21 01:23:41 +0000319namespace {
John McCall50da2ca2010-07-21 05:30:47 +0000320 /// Call the destructor for a direct base class.
John McCall1f0fca52010-07-21 07:22:38 +0000321 struct CallBaseDtor : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000322 const CXXRecordDecl *BaseClass;
323 bool BaseIsVirtual;
324 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
325 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
John McCall182ab512010-07-21 01:23:41 +0000326
327 void Emit(CodeGenFunction &CGF, bool IsForEH) {
John McCall50da2ca2010-07-21 05:30:47 +0000328 const CXXRecordDecl *DerivedClass =
329 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
330
331 const CXXDestructorDecl *D = BaseClass->getDestructor();
332 llvm::Value *Addr =
333 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThis(),
334 DerivedClass, BaseClass,
335 BaseIsVirtual);
336 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual, Addr);
John McCall182ab512010-07-21 01:23:41 +0000337 }
338 };
John McCall7e1dff72010-09-17 02:31:44 +0000339
340 /// A visitor which checks whether an initializer uses 'this' in a
341 /// way which requires the vtable to be properly set.
342 struct DynamicThisUseChecker : EvaluatedExprVisitor<DynamicThisUseChecker> {
343 typedef EvaluatedExprVisitor<DynamicThisUseChecker> super;
344
345 bool UsesThis;
346
347 DynamicThisUseChecker(ASTContext &C) : super(C), UsesThis(false) {}
348
349 // Black-list all explicit and implicit references to 'this'.
350 //
351 // Do we need to worry about external references to 'this' derived
352 // from arbitrary code? If so, then anything which runs arbitrary
353 // external code might potentially access the vtable.
354 void VisitCXXThisExpr(CXXThisExpr *E) { UsesThis = true; }
355 };
356}
357
358static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
359 DynamicThisUseChecker Checker(C);
360 Checker.Visit(const_cast<Expr*>(Init));
361 return Checker.UsesThis;
John McCall182ab512010-07-21 01:23:41 +0000362}
363
Anders Carlsson607d0372009-12-24 22:46:43 +0000364static void EmitBaseInitializer(CodeGenFunction &CGF,
365 const CXXRecordDecl *ClassDecl,
Sean Huntcbb67482011-01-08 20:30:50 +0000366 CXXCtorInitializer *BaseInit,
Anders Carlsson607d0372009-12-24 22:46:43 +0000367 CXXCtorType CtorType) {
368 assert(BaseInit->isBaseInitializer() &&
369 "Must have base initializer!");
370
371 llvm::Value *ThisPtr = CGF.LoadCXXThis();
372
373 const Type *BaseType = BaseInit->getBaseClass();
374 CXXRecordDecl *BaseClassDecl =
375 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
376
Anders Carlsson80638c52010-04-12 00:51:03 +0000377 bool isBaseVirtual = BaseInit->isBaseVirtual();
Anders Carlsson607d0372009-12-24 22:46:43 +0000378
379 // The base constructor doesn't construct virtual bases.
380 if (CtorType == Ctor_Base && isBaseVirtual)
381 return;
382
John McCall7e1dff72010-09-17 02:31:44 +0000383 // If the initializer for the base (other than the constructor
384 // itself) accesses 'this' in any way, we need to initialize the
385 // vtables.
386 if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
387 CGF.InitializeVTablePointers(ClassDecl);
388
John McCallbff225e2010-02-16 04:15:37 +0000389 // We can pretend to be a complete class because it only matters for
390 // virtual bases, and we only do virtual bases for complete ctors.
Anders Carlsson8561a862010-04-24 23:01:49 +0000391 llvm::Value *V =
392 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
John McCall50da2ca2010-07-21 05:30:47 +0000393 BaseClassDecl,
394 isBaseVirtual);
John McCallbff225e2010-02-16 04:15:37 +0000395
John McCall558d2ab2010-09-15 10:14:12 +0000396 AggValueSlot AggSlot = AggValueSlot::forAddr(V, false, /*Lifetime*/ true);
397
398 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
Anders Carlsson594d5e82010-02-06 20:00:21 +0000399
John McCall182ab512010-07-21 01:23:41 +0000400 if (CGF.Exceptions && !BaseClassDecl->hasTrivialDestructor())
John McCall1f0fca52010-07-21 07:22:38 +0000401 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
402 isBaseVirtual);
Anders Carlsson607d0372009-12-24 22:46:43 +0000403}
404
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000405static void EmitAggMemberInitializer(CodeGenFunction &CGF,
406 LValue LHS,
407 llvm::Value *ArrayIndexVar,
Sean Huntcbb67482011-01-08 20:30:50 +0000408 CXXCtorInitializer *MemberInit,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000409 QualType T,
410 unsigned Index) {
411 if (Index == MemberInit->getNumArrayIndices()) {
John McCallf1549f62010-07-06 01:34:17 +0000412 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000413
414 llvm::Value *Dest = LHS.getAddress();
415 if (ArrayIndexVar) {
416 // If we have an array index variable, load it and use it as an offset.
417 // Then, increment the value.
418 llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar);
419 Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress");
420 llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1);
421 Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc");
422 CGF.Builder.CreateStore(Next, ArrayIndexVar);
423 }
John McCall558d2ab2010-09-15 10:14:12 +0000424
425 AggValueSlot Slot = AggValueSlot::forAddr(Dest, LHS.isVolatileQualified(),
426 /*Lifetime*/ true);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000427
John McCall558d2ab2010-09-15 10:14:12 +0000428 CGF.EmitAggExpr(MemberInit->getInit(), Slot);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000429
430 return;
431 }
432
433 const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T);
434 assert(Array && "Array initialization without the array type?");
435 llvm::Value *IndexVar
436 = CGF.GetAddrOfLocalVar(MemberInit->getArrayIndex(Index));
437 assert(IndexVar && "Array index variable not loaded");
438
439 // Initialize this index variable to zero.
440 llvm::Value* Zero
441 = llvm::Constant::getNullValue(
442 CGF.ConvertType(CGF.getContext().getSizeType()));
443 CGF.Builder.CreateStore(Zero, IndexVar);
444
445 // Start the loop with a block that tests the condition.
446 llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond");
447 llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end");
448
449 CGF.EmitBlock(CondBlock);
450
451 llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body");
452 // Generate: if (loop-index < number-of-elements) fall to the loop body,
453 // otherwise, go to the block after the for-loop.
454 uint64_t NumElements = Array->getSize().getZExtValue();
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000455 llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
Chris Lattner985f7392010-05-06 06:35:23 +0000456 llvm::Value *NumElementsPtr =
457 llvm::ConstantInt::get(Counter->getType(), NumElements);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000458 llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr,
459 "isless");
460
461 // If the condition is true, execute the body.
462 CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor);
463
464 CGF.EmitBlock(ForBody);
465 llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc");
466
467 {
John McCallf1549f62010-07-06 01:34:17 +0000468 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000469
470 // Inside the loop body recurse to emit the inner loop or, eventually, the
471 // constructor call.
472 EmitAggMemberInitializer(CGF, LHS, ArrayIndexVar, MemberInit,
473 Array->getElementType(), Index + 1);
474 }
475
476 CGF.EmitBlock(ContinueBlock);
477
478 // Emit the increment of the loop counter.
479 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
480 Counter = CGF.Builder.CreateLoad(IndexVar);
481 NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc");
482 CGF.Builder.CreateStore(NextVal, IndexVar);
483
484 // Finally, branch back up to the condition for the next iteration.
485 CGF.EmitBranch(CondBlock);
486
487 // Emit the fall-through block.
488 CGF.EmitBlock(AfterFor, true);
489}
John McCall182ab512010-07-21 01:23:41 +0000490
491namespace {
John McCall1f0fca52010-07-21 07:22:38 +0000492 struct CallMemberDtor : EHScopeStack::Cleanup {
John McCall182ab512010-07-21 01:23:41 +0000493 FieldDecl *Field;
494 CXXDestructorDecl *Dtor;
495
496 CallMemberDtor(FieldDecl *Field, CXXDestructorDecl *Dtor)
497 : Field(Field), Dtor(Dtor) {}
498
499 void Emit(CodeGenFunction &CGF, bool IsForEH) {
500 // FIXME: Is this OK for C++0x delegating constructors?
501 llvm::Value *ThisPtr = CGF.LoadCXXThis();
502 LValue LHS = CGF.EmitLValueForField(ThisPtr, Field, 0);
503
504 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
505 LHS.getAddress());
506 }
507 };
508}
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000509
Anders Carlsson607d0372009-12-24 22:46:43 +0000510static void EmitMemberInitializer(CodeGenFunction &CGF,
511 const CXXRecordDecl *ClassDecl,
Sean Huntcbb67482011-01-08 20:30:50 +0000512 CXXCtorInitializer *MemberInit,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000513 const CXXConstructorDecl *Constructor,
514 FunctionArgList &Args) {
Francois Pichet00eb3f92010-12-04 09:14:42 +0000515 assert(MemberInit->isAnyMemberInitializer() &&
Anders Carlsson607d0372009-12-24 22:46:43 +0000516 "Must have member initializer!");
517
518 // non-static data member initializers.
Francois Pichet00eb3f92010-12-04 09:14:42 +0000519 FieldDecl *Field = MemberInit->getAnyMember();
Anders Carlsson607d0372009-12-24 22:46:43 +0000520 QualType FieldType = CGF.getContext().getCanonicalType(Field->getType());
521
522 llvm::Value *ThisPtr = CGF.LoadCXXThis();
John McCalla9976d32010-05-21 01:18:57 +0000523 LValue LHS;
Anders Carlsson06a29702010-01-29 05:24:29 +0000524
Anders Carlsson607d0372009-12-24 22:46:43 +0000525 // If we are initializing an anonymous union field, drill down to the field.
Francois Pichet00eb3f92010-12-04 09:14:42 +0000526 if (MemberInit->isIndirectMemberInitializer()) {
527 LHS = CGF.EmitLValueForAnonRecordField(ThisPtr,
528 MemberInit->getIndirectMember(), 0);
529 FieldType = MemberInit->getIndirectMember()->getAnonField()->getType();
John McCalla9976d32010-05-21 01:18:57 +0000530 } else {
531 LHS = CGF.EmitLValueForFieldInitialization(ThisPtr, Field, 0);
Anders Carlsson607d0372009-12-24 22:46:43 +0000532 }
533
Sean Huntcbb67482011-01-08 20:30:50 +0000534 // FIXME: If there's no initializer and the CXXCtorInitializer
Douglas Gregor9db7dbb2010-01-31 09:12:51 +0000535 // was implicitly generated, we shouldn't be zeroing memory.
Anders Carlsson607d0372009-12-24 22:46:43 +0000536 RValue RHS;
537 if (FieldType->isReferenceType()) {
Anders Carlsson32f36ba2010-06-26 16:35:32 +0000538 RHS = CGF.EmitReferenceBindingToExpr(MemberInit->getInit(), Field);
Anders Carlsson607d0372009-12-24 22:46:43 +0000539 CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
Eli Friedman3bb94122010-01-31 19:07:50 +0000540 } else if (FieldType->isArrayType() && !MemberInit->getInit()) {
Anders Carlsson1884eb02010-05-22 17:35:42 +0000541 CGF.EmitNullInitialization(LHS.getAddress(), Field->getType());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +0000542 } else if (!CGF.hasAggregateLLVMType(Field->getType())) {
Eli Friedman0b292272010-06-03 19:58:07 +0000543 RHS = RValue::get(CGF.EmitScalarExpr(MemberInit->getInit()));
Anders Carlsson607d0372009-12-24 22:46:43 +0000544 CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +0000545 } else if (MemberInit->getInit()->getType()->isAnyComplexType()) {
546 CGF.EmitComplexExprIntoAddr(MemberInit->getInit(), LHS.getAddress(),
Anders Carlsson607d0372009-12-24 22:46:43 +0000547 LHS.isVolatileQualified());
548 } else {
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000549 llvm::Value *ArrayIndexVar = 0;
550 const ConstantArrayType *Array
551 = CGF.getContext().getAsConstantArrayType(FieldType);
552 if (Array && Constructor->isImplicit() &&
553 Constructor->isCopyConstructor()) {
554 const llvm::Type *SizeTy
555 = CGF.ConvertType(CGF.getContext().getSizeType());
556
557 // The LHS is a pointer to the first object we'll be constructing, as
558 // a flat array.
559 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
560 const llvm::Type *BasePtr = CGF.ConvertType(BaseElementTy);
561 BasePtr = llvm::PointerType::getUnqual(BasePtr);
562 llvm::Value *BaseAddrPtr = CGF.Builder.CreateBitCast(LHS.getAddress(),
563 BasePtr);
Daniel Dunbar9f553f52010-08-21 03:08:16 +0000564 LHS = CGF.MakeAddrLValue(BaseAddrPtr, BaseElementTy);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000565
566 // Create an array index that will be used to walk over all of the
567 // objects we're constructing.
568 ArrayIndexVar = CGF.CreateTempAlloca(SizeTy, "object.index");
569 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
570 CGF.Builder.CreateStore(Zero, ArrayIndexVar);
571
572 // If we are copying an array of scalars or classes with trivial copy
573 // constructors, perform a single aggregate copy.
574 const RecordType *Record = BaseElementTy->getAs<RecordType>();
575 if (!Record ||
576 cast<CXXRecordDecl>(Record->getDecl())->hasTrivialCopyConstructor()) {
577 // Find the source pointer. We knows it's the last argument because
578 // we know we're in a copy constructor.
579 unsigned SrcArgIndex = Args.size() - 1;
580 llvm::Value *SrcPtr
581 = CGF.Builder.CreateLoad(
582 CGF.GetAddrOfLocalVar(Args[SrcArgIndex].first));
583 LValue Src = CGF.EmitLValueForFieldInitialization(SrcPtr, Field, 0);
584
585 // Copy the aggregate.
586 CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
587 LHS.isVolatileQualified());
588 return;
589 }
590
591 // Emit the block variables for the array indices, if any.
592 for (unsigned I = 0, N = MemberInit->getNumArrayIndices(); I != N; ++I)
John McCallb6bbcc92010-10-15 04:57:14 +0000593 CGF.EmitAutoVarDecl(*MemberInit->getArrayIndex(I));
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000594 }
595
596 EmitAggMemberInitializer(CGF, LHS, ArrayIndexVar, MemberInit, FieldType, 0);
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000597
598 if (!CGF.Exceptions)
599 return;
600
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000601 // FIXME: If we have an array of classes w/ non-trivial destructors,
602 // we need to destroy in reverse order of construction along the exception
603 // path.
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000604 const RecordType *RT = FieldType->getAs<RecordType>();
605 if (!RT)
606 return;
607
608 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall182ab512010-07-21 01:23:41 +0000609 if (!RD->hasTrivialDestructor())
John McCall1f0fca52010-07-21 07:22:38 +0000610 CGF.EHStack.pushCleanup<CallMemberDtor>(EHCleanup, Field,
611 RD->getDestructor());
Anders Carlsson607d0372009-12-24 22:46:43 +0000612 }
613}
614
John McCallc0bf4622010-02-23 00:48:20 +0000615/// Checks whether the given constructor is a valid subject for the
616/// complete-to-base constructor delegation optimization, i.e.
617/// emitting the complete constructor as a simple call to the base
618/// constructor.
619static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
620
621 // Currently we disable the optimization for classes with virtual
622 // bases because (1) the addresses of parameter variables need to be
623 // consistent across all initializers but (2) the delegate function
624 // call necessarily creates a second copy of the parameter variable.
625 //
626 // The limiting example (purely theoretical AFAIK):
627 // struct A { A(int &c) { c++; } };
628 // struct B : virtual A {
629 // B(int count) : A(count) { printf("%d\n", count); }
630 // };
631 // ...although even this example could in principle be emitted as a
632 // delegation since the address of the parameter doesn't escape.
633 if (Ctor->getParent()->getNumVBases()) {
634 // TODO: white-list trivial vbase initializers. This case wouldn't
635 // be subject to the restrictions below.
636
637 // TODO: white-list cases where:
638 // - there are no non-reference parameters to the constructor
639 // - the initializers don't access any non-reference parameters
640 // - the initializers don't take the address of non-reference
641 // parameters
642 // - etc.
643 // If we ever add any of the above cases, remember that:
644 // - function-try-blocks will always blacklist this optimization
645 // - we need to perform the constructor prologue and cleanup in
646 // EmitConstructorBody.
647
648 return false;
649 }
650
651 // We also disable the optimization for variadic functions because
652 // it's impossible to "re-pass" varargs.
653 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
654 return false;
655
656 return true;
657}
658
John McCall9fc6a772010-02-19 09:25:03 +0000659/// EmitConstructorBody - Emits the body of the current constructor.
660void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
661 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
662 CXXCtorType CtorType = CurGD.getCtorType();
663
John McCallc0bf4622010-02-23 00:48:20 +0000664 // Before we go any further, try the complete->base constructor
665 // delegation optimization.
666 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor)) {
Devang Pateld67ef0e2010-08-11 21:04:37 +0000667 if (CGDebugInfo *DI = getDebugInfo())
668 DI->EmitStopPoint(Builder);
John McCallc0bf4622010-02-23 00:48:20 +0000669 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args);
670 return;
671 }
672
John McCall9fc6a772010-02-19 09:25:03 +0000673 Stmt *Body = Ctor->getBody();
674
John McCallc0bf4622010-02-23 00:48:20 +0000675 // Enter the function-try-block before the constructor prologue if
676 // applicable.
John McCallc0bf4622010-02-23 00:48:20 +0000677 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallc0bf4622010-02-23 00:48:20 +0000678 if (IsTryBody)
John McCall59a70002010-07-07 06:56:46 +0000679 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000680
John McCallf1549f62010-07-06 01:34:17 +0000681 EHScopeStack::stable_iterator CleanupDepth = EHStack.stable_begin();
John McCall9fc6a772010-02-19 09:25:03 +0000682
John McCallc0bf4622010-02-23 00:48:20 +0000683 // Emit the constructor prologue, i.e. the base and member
684 // initializers.
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000685 EmitCtorPrologue(Ctor, CtorType, Args);
John McCall9fc6a772010-02-19 09:25:03 +0000686
687 // Emit the body of the statement.
John McCallc0bf4622010-02-23 00:48:20 +0000688 if (IsTryBody)
John McCall9fc6a772010-02-19 09:25:03 +0000689 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
690 else if (Body)
691 EmitStmt(Body);
John McCall9fc6a772010-02-19 09:25:03 +0000692
693 // Emit any cleanup blocks associated with the member or base
694 // initializers, which includes (along the exceptional path) the
695 // destructors for those members and bases that were fully
696 // constructed.
John McCallf1549f62010-07-06 01:34:17 +0000697 PopCleanupBlocks(CleanupDepth);
John McCall9fc6a772010-02-19 09:25:03 +0000698
John McCallc0bf4622010-02-23 00:48:20 +0000699 if (IsTryBody)
John McCall59a70002010-07-07 06:56:46 +0000700 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000701}
702
Anders Carlsson607d0372009-12-24 22:46:43 +0000703/// EmitCtorPrologue - This routine generates necessary code to initialize
704/// base classes and non-static data members belonging to this constructor.
Anders Carlsson607d0372009-12-24 22:46:43 +0000705void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000706 CXXCtorType CtorType,
707 FunctionArgList &Args) {
Anders Carlsson607d0372009-12-24 22:46:43 +0000708 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000709
Sean Huntcbb67482011-01-08 20:30:50 +0000710 llvm::SmallVector<CXXCtorInitializer *, 8> MemberInitializers;
Anders Carlsson607d0372009-12-24 22:46:43 +0000711
Anders Carlsson607d0372009-12-24 22:46:43 +0000712 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
713 E = CD->init_end();
714 B != E; ++B) {
Sean Huntcbb67482011-01-08 20:30:50 +0000715 CXXCtorInitializer *Member = (*B);
Anders Carlsson607d0372009-12-24 22:46:43 +0000716
Anders Carlsson607d0372009-12-24 22:46:43 +0000717 if (Member->isBaseInitializer())
718 EmitBaseInitializer(*this, ClassDecl, Member, CtorType);
719 else
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000720 MemberInitializers.push_back(Member);
Anders Carlsson607d0372009-12-24 22:46:43 +0000721 }
722
Anders Carlsson603d6d12010-03-28 21:07:49 +0000723 InitializeVTablePointers(ClassDecl);
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000724
John McCallf1549f62010-07-06 01:34:17 +0000725 for (unsigned I = 0, E = MemberInitializers.size(); I != E; ++I)
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000726 EmitMemberInitializer(*this, ClassDecl, MemberInitializers[I], CD, Args);
Anders Carlsson607d0372009-12-24 22:46:43 +0000727}
728
John McCall9fc6a772010-02-19 09:25:03 +0000729/// EmitDestructorBody - Emits the body of the current destructor.
730void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
731 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
732 CXXDtorType DtorType = CurGD.getDtorType();
733
John McCall50da2ca2010-07-21 05:30:47 +0000734 // The call to operator delete in a deleting destructor happens
735 // outside of the function-try-block, which means it's always
736 // possible to delegate the destructor body to the complete
737 // destructor. Do so.
738 if (DtorType == Dtor_Deleting) {
739 EnterDtorCleanups(Dtor, Dtor_Deleting);
740 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
741 LoadCXXThis());
742 PopCleanupBlock();
743 return;
744 }
745
John McCall9fc6a772010-02-19 09:25:03 +0000746 Stmt *Body = Dtor->getBody();
747
748 // If the body is a function-try-block, enter the try before
John McCall50da2ca2010-07-21 05:30:47 +0000749 // anything else.
750 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCall9fc6a772010-02-19 09:25:03 +0000751 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +0000752 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000753
John McCall50da2ca2010-07-21 05:30:47 +0000754 // Enter the epilogue cleanups.
755 RunCleanupsScope DtorEpilogue(*this);
756
John McCall9fc6a772010-02-19 09:25:03 +0000757 // If this is the complete variant, just invoke the base variant;
758 // the epilogue will destruct the virtual bases. But we can't do
759 // this optimization if the body is a function-try-block, because
760 // we'd introduce *two* handler blocks.
John McCall50da2ca2010-07-21 05:30:47 +0000761 switch (DtorType) {
762 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
763
764 case Dtor_Complete:
765 // Enter the cleanup scopes for virtual bases.
766 EnterDtorCleanups(Dtor, Dtor_Complete);
767
768 if (!isTryBody) {
769 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
770 LoadCXXThis());
771 break;
772 }
773 // Fallthrough: act like we're in the base variant.
John McCall9fc6a772010-02-19 09:25:03 +0000774
John McCall50da2ca2010-07-21 05:30:47 +0000775 case Dtor_Base:
776 // Enter the cleanup scopes for fields and non-virtual bases.
777 EnterDtorCleanups(Dtor, Dtor_Base);
778
779 // Initialize the vtable pointers before entering the body.
Anders Carlsson603d6d12010-03-28 21:07:49 +0000780 InitializeVTablePointers(Dtor->getParent());
John McCall50da2ca2010-07-21 05:30:47 +0000781
782 if (isTryBody)
783 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
784 else if (Body)
785 EmitStmt(Body);
786 else {
787 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
788 // nothing to do besides what's in the epilogue
789 }
790 break;
John McCall9fc6a772010-02-19 09:25:03 +0000791 }
792
John McCall50da2ca2010-07-21 05:30:47 +0000793 // Jump out through the epilogue cleanups.
794 DtorEpilogue.ForceCleanup();
John McCall9fc6a772010-02-19 09:25:03 +0000795
796 // Exit the try if applicable.
797 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +0000798 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000799}
800
John McCall50da2ca2010-07-21 05:30:47 +0000801namespace {
802 /// Call the operator delete associated with the current destructor.
John McCall1f0fca52010-07-21 07:22:38 +0000803 struct CallDtorDelete : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000804 CallDtorDelete() {}
805
806 void Emit(CodeGenFunction &CGF, bool IsForEH) {
807 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
808 const CXXRecordDecl *ClassDecl = Dtor->getParent();
809 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
810 CGF.getContext().getTagDeclType(ClassDecl));
811 }
812 };
813
John McCall1f0fca52010-07-21 07:22:38 +0000814 struct CallArrayFieldDtor : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000815 const FieldDecl *Field;
816 CallArrayFieldDtor(const FieldDecl *Field) : Field(Field) {}
817
818 void Emit(CodeGenFunction &CGF, bool IsForEH) {
819 QualType FieldType = Field->getType();
820 const ConstantArrayType *Array =
821 CGF.getContext().getAsConstantArrayType(FieldType);
822
823 QualType BaseType =
824 CGF.getContext().getBaseElementType(Array->getElementType());
825 const CXXRecordDecl *FieldClassDecl = BaseType->getAsCXXRecordDecl();
826
827 llvm::Value *ThisPtr = CGF.LoadCXXThis();
828 LValue LHS = CGF.EmitLValueForField(ThisPtr, Field,
829 // FIXME: Qualifiers?
830 /*CVRQualifiers=*/0);
831
832 const llvm::Type *BasePtr = CGF.ConvertType(BaseType)->getPointerTo();
833 llvm::Value *BaseAddrPtr =
834 CGF.Builder.CreateBitCast(LHS.getAddress(), BasePtr);
835 CGF.EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(),
836 Array, BaseAddrPtr);
837 }
838 };
839
John McCall1f0fca52010-07-21 07:22:38 +0000840 struct CallFieldDtor : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000841 const FieldDecl *Field;
842 CallFieldDtor(const FieldDecl *Field) : Field(Field) {}
843
844 void Emit(CodeGenFunction &CGF, bool IsForEH) {
845 const CXXRecordDecl *FieldClassDecl =
846 Field->getType()->getAsCXXRecordDecl();
847
848 llvm::Value *ThisPtr = CGF.LoadCXXThis();
849 LValue LHS = CGF.EmitLValueForField(ThisPtr, Field,
850 // FIXME: Qualifiers?
851 /*CVRQualifiers=*/0);
852
853 CGF.EmitCXXDestructorCall(FieldClassDecl->getDestructor(),
854 Dtor_Complete, /*ForVirtualBase=*/false,
855 LHS.getAddress());
856 }
857 };
858}
859
Anders Carlsson607d0372009-12-24 22:46:43 +0000860/// EmitDtorEpilogue - Emit all code that comes at the end of class's
861/// destructor. This is to call destructors on members and base classes
862/// in reverse order of their construction.
John McCall50da2ca2010-07-21 05:30:47 +0000863void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
864 CXXDtorType DtorType) {
Anders Carlsson607d0372009-12-24 22:46:43 +0000865 assert(!DD->isTrivial() &&
866 "Should not emit dtor epilogue for trivial dtor!");
867
John McCall50da2ca2010-07-21 05:30:47 +0000868 // The deleting-destructor phase just needs to call the appropriate
869 // operator delete that Sema picked up.
John McCall3b477332010-02-18 19:59:28 +0000870 if (DtorType == Dtor_Deleting) {
871 assert(DD->getOperatorDelete() &&
872 "operator delete missing - EmitDtorEpilogue");
John McCall1f0fca52010-07-21 07:22:38 +0000873 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
John McCall3b477332010-02-18 19:59:28 +0000874 return;
875 }
876
John McCall50da2ca2010-07-21 05:30:47 +0000877 const CXXRecordDecl *ClassDecl = DD->getParent();
878
879 // The complete-destructor phase just destructs all the virtual bases.
John McCall3b477332010-02-18 19:59:28 +0000880 if (DtorType == Dtor_Complete) {
John McCall50da2ca2010-07-21 05:30:47 +0000881
882 // We push them in the forward order so that they'll be popped in
883 // the reverse order.
884 for (CXXRecordDecl::base_class_const_iterator I =
885 ClassDecl->vbases_begin(), E = ClassDecl->vbases_end();
John McCall3b477332010-02-18 19:59:28 +0000886 I != E; ++I) {
887 const CXXBaseSpecifier &Base = *I;
888 CXXRecordDecl *BaseClassDecl
889 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
890
891 // Ignore trivial destructors.
892 if (BaseClassDecl->hasTrivialDestructor())
893 continue;
John McCall50da2ca2010-07-21 05:30:47 +0000894
John McCall1f0fca52010-07-21 07:22:38 +0000895 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
896 BaseClassDecl,
897 /*BaseIsVirtual*/ true);
John McCall3b477332010-02-18 19:59:28 +0000898 }
John McCall50da2ca2010-07-21 05:30:47 +0000899
John McCall3b477332010-02-18 19:59:28 +0000900 return;
901 }
902
903 assert(DtorType == Dtor_Base);
John McCall50da2ca2010-07-21 05:30:47 +0000904
905 // Destroy non-virtual bases.
906 for (CXXRecordDecl::base_class_const_iterator I =
907 ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) {
908 const CXXBaseSpecifier &Base = *I;
909
910 // Ignore virtual bases.
911 if (Base.isVirtual())
912 continue;
913
914 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
915
916 // Ignore trivial destructors.
917 if (BaseClassDecl->hasTrivialDestructor())
918 continue;
John McCall3b477332010-02-18 19:59:28 +0000919
John McCall1f0fca52010-07-21 07:22:38 +0000920 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
921 BaseClassDecl,
922 /*BaseIsVirtual*/ false);
John McCall50da2ca2010-07-21 05:30:47 +0000923 }
924
925 // Destroy direct fields.
Anders Carlsson607d0372009-12-24 22:46:43 +0000926 llvm::SmallVector<const FieldDecl *, 16> FieldDecls;
927 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
928 E = ClassDecl->field_end(); I != E; ++I) {
929 const FieldDecl *Field = *I;
930
931 QualType FieldType = getContext().getCanonicalType(Field->getType());
John McCall50da2ca2010-07-21 05:30:47 +0000932 const ConstantArrayType *Array =
933 getContext().getAsConstantArrayType(FieldType);
934 if (Array)
935 FieldType = getContext().getBaseElementType(Array->getElementType());
Anders Carlsson607d0372009-12-24 22:46:43 +0000936
937 const RecordType *RT = FieldType->getAs<RecordType>();
938 if (!RT)
939 continue;
940
941 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
942 if (FieldClassDecl->hasTrivialDestructor())
943 continue;
John McCall50da2ca2010-07-21 05:30:47 +0000944
Anders Carlsson607d0372009-12-24 22:46:43 +0000945 if (Array)
John McCall1f0fca52010-07-21 07:22:38 +0000946 EHStack.pushCleanup<CallArrayFieldDtor>(NormalAndEHCleanup, Field);
John McCall50da2ca2010-07-21 05:30:47 +0000947 else
John McCall1f0fca52010-07-21 07:22:38 +0000948 EHStack.pushCleanup<CallFieldDtor>(NormalAndEHCleanup, Field);
Anders Carlsson607d0372009-12-24 22:46:43 +0000949 }
Anders Carlsson607d0372009-12-24 22:46:43 +0000950}
951
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000952/// EmitCXXAggrConstructorCall - This routine essentially creates a (nested)
953/// for-loop to call the default constructor on individual members of the
954/// array.
955/// 'D' is the default constructor for elements of the array, 'ArrayTy' is the
956/// array type and 'ArrayPtr' points to the beginning fo the array.
957/// It is assumed that all relevant checks have been made by the caller.
Douglas Gregor59174c02010-07-21 01:10:17 +0000958///
959/// \param ZeroInitialization True if each element should be zero-initialized
960/// before it is constructed.
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000961void
962CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
Douglas Gregor59174c02010-07-21 01:10:17 +0000963 const ConstantArrayType *ArrayTy,
964 llvm::Value *ArrayPtr,
965 CallExpr::const_arg_iterator ArgBeg,
966 CallExpr::const_arg_iterator ArgEnd,
967 bool ZeroInitialization) {
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000968
969 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
970 llvm::Value * NumElements =
971 llvm::ConstantInt::get(SizeTy,
972 getContext().getConstantArrayElementCount(ArrayTy));
973
Douglas Gregor59174c02010-07-21 01:10:17 +0000974 EmitCXXAggrConstructorCall(D, NumElements, ArrayPtr, ArgBeg, ArgEnd,
975 ZeroInitialization);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000976}
977
978void
979CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
980 llvm::Value *NumElements,
981 llvm::Value *ArrayPtr,
982 CallExpr::const_arg_iterator ArgBeg,
Douglas Gregor59174c02010-07-21 01:10:17 +0000983 CallExpr::const_arg_iterator ArgEnd,
984 bool ZeroInitialization) {
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000985 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
986
987 // Create a temporary for the loop index and initialize it with 0.
988 llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index");
989 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
990 Builder.CreateStore(Zero, IndexPtr);
991
992 // Start the loop with a block that tests the condition.
993 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
994 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
995
996 EmitBlock(CondBlock);
997
998 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
999
1000 // Generate: if (loop-index < number-of-elements fall to the loop body,
1001 // otherwise, go to the block after the for-loop.
1002 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1003 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless");
1004 // If the condition is true, execute the body.
1005 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
1006
1007 EmitBlock(ForBody);
1008
1009 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1010 // Inside the loop body, emit the constructor call on the array element.
1011 Counter = Builder.CreateLoad(IndexPtr);
1012 llvm::Value *Address = Builder.CreateInBoundsGEP(ArrayPtr, Counter,
1013 "arrayidx");
1014
Douglas Gregor59174c02010-07-21 01:10:17 +00001015 // Zero initialize the storage, if requested.
1016 if (ZeroInitialization)
1017 EmitNullInitialization(Address,
1018 getContext().getTypeDeclType(D->getParent()));
1019
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001020 // C++ [class.temporary]p4:
1021 // There are two contexts in which temporaries are destroyed at a different
1022 // point than the end of the full-expression. The first context is when a
1023 // default constructor is called to initialize an element of an array.
1024 // If the constructor has one or more default arguments, the destruction of
1025 // every temporary created in a default argument expression is sequenced
1026 // before the construction of the next array element, if any.
1027
1028 // Keep track of the current number of live temporaries.
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001029 {
John McCallf1549f62010-07-06 01:34:17 +00001030 RunCleanupsScope Scope(*this);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001031
Anders Carlsson155ed4a2010-05-02 23:20:53 +00001032 EmitCXXConstructorCall(D, Ctor_Complete, /*ForVirtualBase=*/false, Address,
Anders Carlsson24eb78e2010-05-02 23:01:10 +00001033 ArgBeg, ArgEnd);
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001034 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001035
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001036 EmitBlock(ContinueBlock);
1037
1038 // Emit the increment of the loop counter.
1039 llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1);
1040 Counter = Builder.CreateLoad(IndexPtr);
1041 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1042 Builder.CreateStore(NextVal, IndexPtr);
1043
1044 // Finally, branch back up to the condition for the next iteration.
1045 EmitBranch(CondBlock);
1046
1047 // Emit the fall-through block.
1048 EmitBlock(AfterFor, true);
1049}
1050
1051/// EmitCXXAggrDestructorCall - calls the default destructor on array
1052/// elements in reverse order of construction.
1053void
1054CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
1055 const ArrayType *Array,
1056 llvm::Value *This) {
1057 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1058 assert(CA && "Do we support VLA for destruction ?");
1059 uint64_t ElementCount = getContext().getConstantArrayElementCount(CA);
1060
1061 const llvm::Type *SizeLTy = ConvertType(getContext().getSizeType());
1062 llvm::Value* ElementCountPtr = llvm::ConstantInt::get(SizeLTy, ElementCount);
1063 EmitCXXAggrDestructorCall(D, ElementCountPtr, This);
1064}
1065
1066/// EmitCXXAggrDestructorCall - calls the default destructor on array
1067/// elements in reverse order of construction.
1068void
1069CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
1070 llvm::Value *UpperCount,
1071 llvm::Value *This) {
1072 const llvm::Type *SizeLTy = ConvertType(getContext().getSizeType());
1073 llvm::Value *One = llvm::ConstantInt::get(SizeLTy, 1);
1074
1075 // Create a temporary for the loop index and initialize it with count of
1076 // array elements.
1077 llvm::Value *IndexPtr = CreateTempAlloca(SizeLTy, "loop.index");
1078
1079 // Store the number of elements in the index pointer.
1080 Builder.CreateStore(UpperCount, IndexPtr);
1081
1082 // Start the loop with a block that tests the condition.
1083 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1084 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1085
1086 EmitBlock(CondBlock);
1087
1088 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1089
1090 // Generate: if (loop-index != 0 fall to the loop body,
1091 // otherwise, go to the block after the for-loop.
1092 llvm::Value* zeroConstant =
1093 llvm::Constant::getNullValue(SizeLTy);
1094 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1095 llvm::Value *IsNE = Builder.CreateICmpNE(Counter, zeroConstant,
1096 "isne");
1097 // If the condition is true, execute the body.
1098 Builder.CreateCondBr(IsNE, ForBody, AfterFor);
1099
1100 EmitBlock(ForBody);
1101
1102 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1103 // Inside the loop body, emit the constructor call on the array element.
1104 Counter = Builder.CreateLoad(IndexPtr);
1105 Counter = Builder.CreateSub(Counter, One);
1106 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
Anders Carlsson8e6404c2010-05-02 23:29:11 +00001107 EmitCXXDestructorCall(D, Dtor_Complete, /*ForVirtualBase=*/false, Address);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001108
1109 EmitBlock(ContinueBlock);
1110
1111 // Emit the decrement of the loop counter.
1112 Counter = Builder.CreateLoad(IndexPtr);
1113 Counter = Builder.CreateSub(Counter, One, "dec");
1114 Builder.CreateStore(Counter, IndexPtr);
1115
1116 // Finally, branch back up to the condition for the next iteration.
1117 EmitBranch(CondBlock);
1118
1119 // Emit the fall-through block.
1120 EmitBlock(AfterFor, true);
1121}
1122
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001123void
1124CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
Anders Carlsson155ed4a2010-05-02 23:20:53 +00001125 CXXCtorType Type, bool ForVirtualBase,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001126 llvm::Value *This,
1127 CallExpr::const_arg_iterator ArgBeg,
1128 CallExpr::const_arg_iterator ArgEnd) {
John McCall8b6bbeb2010-02-06 00:25:16 +00001129 if (D->isTrivial()) {
1130 if (ArgBeg == ArgEnd) {
1131 // Trivial default constructor, no codegen required.
1132 assert(D->isDefaultConstructor() &&
1133 "trivial 0-arg ctor not a default ctor");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001134 return;
1135 }
John McCall8b6bbeb2010-02-06 00:25:16 +00001136
1137 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
1138 assert(D->isCopyConstructor() && "trivial 1-arg ctor not a copy ctor");
1139
John McCall8b6bbeb2010-02-06 00:25:16 +00001140 const Expr *E = (*ArgBeg);
1141 QualType Ty = E->getType();
1142 llvm::Value *Src = EmitLValue(E).getAddress();
1143 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001144 return;
1145 }
1146
Anders Carlsson314e6222010-05-02 23:33:10 +00001147 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(D, Type), ForVirtualBase);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001148 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
1149
Anders Carlssonc997d422010-01-02 01:01:18 +00001150 EmitCXXMemberCall(D, Callee, ReturnValueSlot(), This, VTT, ArgBeg, ArgEnd);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001151}
1152
John McCallc0bf4622010-02-23 00:48:20 +00001153void
Fariborz Jahanian34999872010-11-13 21:53:34 +00001154CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
1155 llvm::Value *This, llvm::Value *Src,
1156 CallExpr::const_arg_iterator ArgBeg,
1157 CallExpr::const_arg_iterator ArgEnd) {
1158 if (D->isTrivial()) {
1159 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
1160 assert(D->isCopyConstructor() && "trivial 1-arg ctor not a copy ctor");
1161 EmitAggregateCopy(This, Src, (*ArgBeg)->getType());
1162 return;
1163 }
1164 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D,
1165 clang::Ctor_Complete);
1166 assert(D->isInstance() &&
1167 "Trying to emit a member call expr on a static method!");
1168
1169 const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
1170
1171 CallArgList Args;
1172
1173 // Push the this ptr.
1174 Args.push_back(std::make_pair(RValue::get(This),
1175 D->getThisType(getContext())));
1176
1177
1178 // Push the src ptr.
1179 QualType QT = *(FPT->arg_type_begin());
1180 const llvm::Type *t = CGM.getTypes().ConvertType(QT);
1181 Src = Builder.CreateBitCast(Src, t);
1182 Args.push_back(std::make_pair(RValue::get(Src), QT));
1183
1184 // Skip over first argument (Src).
1185 ++ArgBeg;
1186 CallExpr::const_arg_iterator Arg = ArgBeg;
1187 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin()+1,
1188 E = FPT->arg_type_end(); I != E; ++I, ++Arg) {
1189 assert(Arg != ArgEnd && "Running over edge of argument list!");
1190 QualType ArgType = *I;
1191 Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType),
1192 ArgType));
1193 }
1194 // Either we've emitted all the call args, or we have a call to a
1195 // variadic function.
1196 assert((Arg == ArgEnd || FPT->isVariadic()) &&
1197 "Extra arguments in non-variadic function!");
1198 // If we still have any arguments, emit them using the type of the argument.
1199 for (; Arg != ArgEnd; ++Arg) {
1200 QualType ArgType = Arg->getType();
1201 Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType),
1202 ArgType));
1203 }
1204
1205 QualType ResultType = FPT->getResultType();
1206 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args,
1207 FPT->getExtInfo()),
1208 Callee, ReturnValueSlot(), Args, D);
1209}
1210
1211void
John McCallc0bf4622010-02-23 00:48:20 +00001212CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1213 CXXCtorType CtorType,
1214 const FunctionArgList &Args) {
1215 CallArgList DelegateArgs;
1216
1217 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
1218 assert(I != E && "no parameters to constructor");
1219
1220 // this
1221 DelegateArgs.push_back(std::make_pair(RValue::get(LoadCXXThis()),
1222 I->second));
1223 ++I;
1224
1225 // vtt
Anders Carlsson314e6222010-05-02 23:33:10 +00001226 if (llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(Ctor, CtorType),
1227 /*ForVirtualBase=*/false)) {
John McCallc0bf4622010-02-23 00:48:20 +00001228 QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
1229 DelegateArgs.push_back(std::make_pair(RValue::get(VTT), VoidPP));
1230
Anders Carlssonaf440352010-03-23 04:11:45 +00001231 if (CodeGenVTables::needsVTTParameter(CurGD)) {
John McCallc0bf4622010-02-23 00:48:20 +00001232 assert(I != E && "cannot skip vtt parameter, already done with args");
1233 assert(I->second == VoidPP && "skipping parameter not of vtt type");
1234 ++I;
1235 }
1236 }
1237
1238 // Explicit arguments.
1239 for (; I != E; ++I) {
John McCallc0bf4622010-02-23 00:48:20 +00001240 const VarDecl *Param = I->first;
1241 QualType ArgType = Param->getType(); // because we're passing it to itself
John McCall27360712010-05-26 22:34:26 +00001242 RValue Arg = EmitDelegateCallArg(Param);
John McCallc0bf4622010-02-23 00:48:20 +00001243
1244 DelegateArgs.push_back(std::make_pair(Arg, ArgType));
1245 }
1246
1247 EmitCall(CGM.getTypes().getFunctionInfo(Ctor, CtorType),
1248 CGM.GetAddrOfCXXConstructor(Ctor, CtorType),
1249 ReturnValueSlot(), DelegateArgs, Ctor);
1250}
1251
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001252void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
1253 CXXDtorType Type,
Anders Carlsson8e6404c2010-05-02 23:29:11 +00001254 bool ForVirtualBase,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001255 llvm::Value *This) {
Anders Carlsson314e6222010-05-02 23:33:10 +00001256 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(DD, Type),
1257 ForVirtualBase);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001258 llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
1259
Anders Carlssonc997d422010-01-02 01:01:18 +00001260 EmitCXXMemberCall(DD, Callee, ReturnValueSlot(), This, VTT, 0, 0);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001261}
1262
John McCall291ae942010-07-21 01:41:18 +00001263namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001264 struct CallLocalDtor : EHScopeStack::Cleanup {
John McCall291ae942010-07-21 01:41:18 +00001265 const CXXDestructorDecl *Dtor;
1266 llvm::Value *Addr;
1267
1268 CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
1269 : Dtor(D), Addr(Addr) {}
1270
1271 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1272 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1273 /*ForVirtualBase=*/false, Addr);
1274 }
1275 };
1276}
1277
John McCall81407d42010-07-21 06:29:51 +00001278void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
1279 llvm::Value *Addr) {
John McCall1f0fca52010-07-21 07:22:38 +00001280 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
John McCall81407d42010-07-21 06:29:51 +00001281}
1282
John McCallf1549f62010-07-06 01:34:17 +00001283void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
1284 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
1285 if (!ClassDecl) return;
1286 if (ClassDecl->hasTrivialDestructor()) return;
1287
1288 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCall81407d42010-07-21 06:29:51 +00001289 PushDestructorCleanup(D, Addr);
John McCallf1549f62010-07-06 01:34:17 +00001290}
1291
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001292llvm::Value *
Anders Carlssonbb7e17b2010-01-31 01:36:53 +00001293CodeGenFunction::GetVirtualBaseClassOffset(llvm::Value *This,
1294 const CXXRecordDecl *ClassDecl,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001295 const CXXRecordDecl *BaseClassDecl) {
1296 const llvm::Type *Int8PtrTy =
1297 llvm::Type::getInt8Ty(VMContext)->getPointerTo();
1298
Dan Gohman043fb9a2010-10-26 18:44:08 +00001299 llvm::Value *VTablePtr = GetVTablePtr(This, Int8PtrTy);
Anders Carlssonbba16072010-03-11 07:15:17 +00001300 int64_t VBaseOffsetOffset =
Anders Carlssonaf440352010-03-23 04:11:45 +00001301 CGM.getVTables().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001302
1303 llvm::Value *VBaseOffsetPtr =
Anders Carlssonbba16072010-03-11 07:15:17 +00001304 Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset, "vbase.offset.ptr");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001305 const llvm::Type *PtrDiffTy =
1306 ConvertType(getContext().getPointerDiffType());
1307
1308 VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr,
1309 PtrDiffTy->getPointerTo());
1310
1311 llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1312
1313 return VBaseOffset;
1314}
1315
Anders Carlssond103f9f2010-03-28 19:40:00 +00001316void
1317CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001318 const CXXRecordDecl *NearestVBase,
Anders Carlsson42358402010-05-03 00:07:07 +00001319 uint64_t OffsetFromNearestVBase,
Anders Carlssond103f9f2010-03-28 19:40:00 +00001320 llvm::Constant *VTable,
1321 const CXXRecordDecl *VTableClass) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001322 const CXXRecordDecl *RD = Base.getBase();
1323
Anders Carlssond103f9f2010-03-28 19:40:00 +00001324 // Compute the address point.
Anders Carlssonc83f1062010-03-29 01:08:49 +00001325 llvm::Value *VTableAddressPoint;
Anders Carlsson851853d2010-03-29 02:38:51 +00001326
Anders Carlssonc83f1062010-03-29 01:08:49 +00001327 // Check if we need to use a vtable from the VTT.
Anders Carlsson851853d2010-03-29 02:38:51 +00001328 if (CodeGenVTables::needsVTTParameter(CurGD) &&
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001329 (RD->getNumVBases() || NearestVBase)) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001330 // Get the secondary vpointer index.
1331 uint64_t VirtualPointerIndex =
1332 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1333
1334 /// Load the VTT.
1335 llvm::Value *VTT = LoadCXXVTT();
1336 if (VirtualPointerIndex)
1337 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1338
1339 // And load the address point from the VTT.
1340 VTableAddressPoint = Builder.CreateLoad(VTT);
1341 } else {
Anders Carlsson64c9eca2010-03-29 02:08:26 +00001342 uint64_t AddressPoint = CGM.getVTables().getAddressPoint(Base, VTableClass);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001343 VTableAddressPoint =
Anders Carlssond103f9f2010-03-28 19:40:00 +00001344 Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001345 }
Anders Carlssond103f9f2010-03-28 19:40:00 +00001346
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001347 // Compute where to store the address point.
Anders Carlsson8246cc72010-05-03 00:29:58 +00001348 llvm::Value *VirtualOffset = 0;
1349 uint64_t NonVirtualOffset = 0;
Anders Carlsson3e79c302010-04-20 18:05:10 +00001350
1351 if (CodeGenVTables::needsVTTParameter(CurGD) && NearestVBase) {
1352 // We need to use the virtual base offset offset because the virtual base
1353 // might have a different offset in the most derived class.
Anders Carlsson8246cc72010-05-03 00:29:58 +00001354 VirtualOffset = GetVirtualBaseClassOffset(LoadCXXThis(), VTableClass,
1355 NearestVBase);
1356 NonVirtualOffset = OffsetFromNearestVBase / 8;
Anders Carlsson3e79c302010-04-20 18:05:10 +00001357 } else {
Anders Carlsson8246cc72010-05-03 00:29:58 +00001358 // We can just use the base offset in the complete class.
1359 NonVirtualOffset = Base.getBaseOffset() / 8;
Anders Carlsson3e79c302010-04-20 18:05:10 +00001360 }
Anders Carlsson8246cc72010-05-03 00:29:58 +00001361
1362 // Apply the offsets.
1363 llvm::Value *VTableField = LoadCXXThis();
1364
1365 if (NonVirtualOffset || VirtualOffset)
1366 VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
1367 NonVirtualOffset,
1368 VirtualOffset);
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001369
Anders Carlssond103f9f2010-03-28 19:40:00 +00001370 // Finally, store the address point.
1371 const llvm::Type *AddressPointPtrTy =
1372 VTableAddressPoint->getType()->getPointerTo();
1373 VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
1374 Builder.CreateStore(VTableAddressPoint, VTableField);
1375}
1376
Anders Carlsson603d6d12010-03-28 21:07:49 +00001377void
1378CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001379 const CXXRecordDecl *NearestVBase,
Anders Carlsson42358402010-05-03 00:07:07 +00001380 uint64_t OffsetFromNearestVBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001381 bool BaseIsNonVirtualPrimaryBase,
1382 llvm::Constant *VTable,
1383 const CXXRecordDecl *VTableClass,
1384 VisitedVirtualBasesSetTy& VBases) {
1385 // If this base is a non-virtual primary base the address point has already
1386 // been set.
1387 if (!BaseIsNonVirtualPrimaryBase) {
1388 // Initialize the vtable pointer for this base.
Anders Carlsson42358402010-05-03 00:07:07 +00001389 InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
1390 VTable, VTableClass);
Anders Carlsson603d6d12010-03-28 21:07:49 +00001391 }
1392
1393 const CXXRecordDecl *RD = Base.getBase();
1394
1395 // Traverse bases.
1396 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1397 E = RD->bases_end(); I != E; ++I) {
1398 CXXRecordDecl *BaseDecl
1399 = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1400
1401 // Ignore classes without a vtable.
1402 if (!BaseDecl->isDynamicClass())
1403 continue;
1404
1405 uint64_t BaseOffset;
Anders Carlsson42358402010-05-03 00:07:07 +00001406 uint64_t BaseOffsetFromNearestVBase;
Anders Carlsson14da9de2010-03-29 01:16:41 +00001407 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001408
1409 if (I->isVirtual()) {
1410 // Check if we've visited this virtual base before.
1411 if (!VBases.insert(BaseDecl))
1412 continue;
1413
1414 const ASTRecordLayout &Layout =
1415 getContext().getASTRecordLayout(VTableClass);
1416
Anders Carlssona14f5972010-10-31 23:22:37 +00001417 BaseOffset = Layout.getVBaseClassOffsetInBits(BaseDecl);
Anders Carlsson42358402010-05-03 00:07:07 +00001418 BaseOffsetFromNearestVBase = 0;
Anders Carlsson14da9de2010-03-29 01:16:41 +00001419 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001420 } else {
1421 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1422
Anders Carlssona14f5972010-10-31 23:22:37 +00001423 BaseOffset =
1424 Base.getBaseOffset() + Layout.getBaseClassOffsetInBits(BaseDecl);
Anders Carlsson42358402010-05-03 00:07:07 +00001425 BaseOffsetFromNearestVBase =
Anders Carlssona14f5972010-10-31 23:22:37 +00001426 OffsetFromNearestVBase + Layout.getBaseClassOffsetInBits(BaseDecl);
Anders Carlsson14da9de2010-03-29 01:16:41 +00001427 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001428 }
1429
1430 InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001431 I->isVirtual() ? BaseDecl : NearestVBase,
Anders Carlsson42358402010-05-03 00:07:07 +00001432 BaseOffsetFromNearestVBase,
Anders Carlsson14da9de2010-03-29 01:16:41 +00001433 BaseDeclIsNonVirtualPrimaryBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001434 VTable, VTableClass, VBases);
1435 }
1436}
1437
1438void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
1439 // Ignore classes without a vtable.
Anders Carlsson07036902010-03-26 04:39:42 +00001440 if (!RD->isDynamicClass())
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001441 return;
1442
Anders Carlsson07036902010-03-26 04:39:42 +00001443 // Get the VTable.
1444 llvm::Constant *VTable = CGM.getVTables().GetAddrOfVTable(RD);
Anders Carlsson5c6c1d92010-03-24 03:57:14 +00001445
Anders Carlsson603d6d12010-03-28 21:07:49 +00001446 // Initialize the vtable pointers for this class and all of its bases.
1447 VisitedVirtualBasesSetTy VBases;
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001448 InitializeVTablePointers(BaseSubobject(RD, 0), /*NearestVBase=*/0,
Anders Carlsson42358402010-05-03 00:07:07 +00001449 /*OffsetFromNearestVBase=*/0,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001450 /*BaseIsNonVirtualPrimaryBase=*/false,
1451 VTable, RD, VBases);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001452}
Dan Gohman043fb9a2010-10-26 18:44:08 +00001453
1454llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
1455 const llvm::Type *Ty) {
1456 llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
1457 return Builder.CreateLoad(VTablePtrSrc, "vtable");
1458}