blob: fbc5f3f030c8f798f3671b82449773dc588251eb [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"
Devang Patel3ee36af2011-02-22 20:55:26 +000020#include "clang/Frontend/CodeGenOptions.h"
Anders Carlsson2f1986b2009-10-06 22:43:30 +000021
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000022using namespace clang;
23using namespace CodeGen;
24
Anders Carlsson2f1986b2009-10-06 22:43:30 +000025static uint64_t
Anders Carlsson34a2d382010-04-24 21:06:20 +000026ComputeNonVirtualBaseClassOffset(ASTContext &Context,
27 const CXXRecordDecl *DerivedClass,
John McCallf871d0c2010-08-07 06:22:56 +000028 CastExpr::path_const_iterator Start,
29 CastExpr::path_const_iterator End) {
Anders Carlsson34a2d382010-04-24 21:06:20 +000030 uint64_t Offset = 0;
31
32 const CXXRecordDecl *RD = DerivedClass;
33
John McCallf871d0c2010-08-07 06:22:56 +000034 for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
Anders Carlsson34a2d382010-04-24 21:06:20 +000035 const CXXBaseSpecifier *Base = *I;
36 assert(!Base->isVirtual() && "Should not see virtual bases here!");
37
38 // Get the layout.
39 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
40
41 const CXXRecordDecl *BaseDecl =
42 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
43
44 // Add the offset.
Anders Carlssona14f5972010-10-31 23:22:37 +000045 Offset += Layout.getBaseClassOffsetInBits(BaseDecl);
Anders Carlsson34a2d382010-04-24 21:06:20 +000046
47 RD = BaseDecl;
48 }
49
50 // FIXME: We should not use / 8 here.
51 return Offset / 8;
52}
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000053
Anders Carlsson84080ec2009-09-29 03:13:20 +000054llvm::Constant *
Anders Carlssona04efdf2010-04-24 21:23:59 +000055CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +000056 CastExpr::path_const_iterator PathBegin,
57 CastExpr::path_const_iterator PathEnd) {
58 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssona04efdf2010-04-24 21:23:59 +000059
60 uint64_t Offset =
John McCallf871d0c2010-08-07 06:22:56 +000061 ComputeNonVirtualBaseClassOffset(getContext(), ClassDecl,
62 PathBegin, PathEnd);
Anders Carlssona04efdf2010-04-24 21:23:59 +000063 if (!Offset)
64 return 0;
65
66 const llvm::Type *PtrDiffTy =
67 Types.ConvertType(getContext().getPointerDiffType());
68
69 return llvm::ConstantInt::get(PtrDiffTy, Offset);
Anders Carlsson84080ec2009-09-29 03:13:20 +000070}
71
Anders Carlsson8561a862010-04-24 23:01:49 +000072/// Gets the address of a direct base class within a complete object.
John McCallbff225e2010-02-16 04:15:37 +000073/// This should only be used for (1) non-virtual bases or (2) virtual bases
74/// when the type is known to be complete (e.g. in complete destructors).
75///
76/// The object pointed to by 'This' is assumed to be non-null.
77llvm::Value *
Anders Carlsson8561a862010-04-24 23:01:49 +000078CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(llvm::Value *This,
79 const CXXRecordDecl *Derived,
80 const CXXRecordDecl *Base,
81 bool BaseIsVirtual) {
John McCallbff225e2010-02-16 04:15:37 +000082 // 'this' must be a pointer (in some address space) to Derived.
83 assert(This->getType()->isPointerTy() &&
84 cast<llvm::PointerType>(This->getType())->getElementType()
85 == ConvertType(Derived));
86
87 // Compute the offset of the virtual base.
88 uint64_t Offset;
89 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
Anders Carlsson8561a862010-04-24 23:01:49 +000090 if (BaseIsVirtual)
Anders Carlssona14f5972010-10-31 23:22:37 +000091 Offset = Layout.getVBaseClassOffsetInBits(Base);
John McCallbff225e2010-02-16 04:15:37 +000092 else
Anders Carlssona14f5972010-10-31 23:22:37 +000093 Offset = Layout.getBaseClassOffsetInBits(Base);
John McCallbff225e2010-02-16 04:15:37 +000094
95 // Shift and cast down to the base type.
96 // TODO: for complete types, this should be possible with a GEP.
97 llvm::Value *V = This;
98 if (Offset) {
99 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
100 V = Builder.CreateBitCast(V, Int8PtrTy);
101 V = Builder.CreateConstInBoundsGEP1_64(V, Offset / 8);
102 }
103 V = Builder.CreateBitCast(V, ConvertType(Base)->getPointerTo());
104
105 return V;
Anders Carlssond103f9f2010-03-28 19:40:00 +0000106}
John McCallbff225e2010-02-16 04:15:37 +0000107
Anders Carlsson9dc228a2010-04-20 16:03:35 +0000108static llvm::Value *
109ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, llvm::Value *ThisPtr,
110 uint64_t NonVirtual, llvm::Value *Virtual) {
111 const llvm::Type *PtrDiffTy =
112 CGF.ConvertType(CGF.getContext().getPointerDiffType());
113
114 llvm::Value *NonVirtualOffset = 0;
115 if (NonVirtual)
116 NonVirtualOffset = llvm::ConstantInt::get(PtrDiffTy, NonVirtual);
117
118 llvm::Value *BaseOffset;
119 if (Virtual) {
120 if (NonVirtualOffset)
121 BaseOffset = CGF.Builder.CreateAdd(Virtual, NonVirtualOffset);
122 else
123 BaseOffset = Virtual;
124 } else
125 BaseOffset = NonVirtualOffset;
126
127 // Apply the base offset.
128 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
129 ThisPtr = CGF.Builder.CreateBitCast(ThisPtr, Int8PtrTy);
130 ThisPtr = CGF.Builder.CreateGEP(ThisPtr, BaseOffset, "add.ptr");
131
132 return ThisPtr;
133}
134
Anders Carlsson5d58a1d2009-09-12 04:27:24 +0000135llvm::Value *
Anders Carlsson34a2d382010-04-24 21:06:20 +0000136CodeGenFunction::GetAddressOfBaseClass(llvm::Value *Value,
Anders Carlsson8561a862010-04-24 23:01:49 +0000137 const CXXRecordDecl *Derived,
John McCallf871d0c2010-08-07 06:22:56 +0000138 CastExpr::path_const_iterator PathBegin,
139 CastExpr::path_const_iterator PathEnd,
Anders Carlsson34a2d382010-04-24 21:06:20 +0000140 bool NullCheckValue) {
John McCallf871d0c2010-08-07 06:22:56 +0000141 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlsson34a2d382010-04-24 21:06:20 +0000142
John McCallf871d0c2010-08-07 06:22:56 +0000143 CastExpr::path_const_iterator Start = PathBegin;
Anders Carlsson34a2d382010-04-24 21:06:20 +0000144 const CXXRecordDecl *VBase = 0;
145
146 // Get the virtual base.
147 if ((*Start)->isVirtual()) {
148 VBase =
149 cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
150 ++Start;
151 }
152
153 uint64_t NonVirtualOffset =
Anders Carlsson8561a862010-04-24 23:01:49 +0000154 ComputeNonVirtualBaseClassOffset(getContext(), VBase ? VBase : Derived,
John McCallf871d0c2010-08-07 06:22:56 +0000155 Start, PathEnd);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000156
157 // Get the base pointer type.
158 const llvm::Type *BasePtrTy =
John McCallf871d0c2010-08-07 06:22:56 +0000159 ConvertType((PathEnd[-1])->getType())->getPointerTo();
Anders Carlsson34a2d382010-04-24 21:06:20 +0000160
161 if (!NonVirtualOffset && !VBase) {
162 // Just cast back.
163 return Builder.CreateBitCast(Value, BasePtrTy);
164 }
165
166 llvm::BasicBlock *CastNull = 0;
167 llvm::BasicBlock *CastNotNull = 0;
168 llvm::BasicBlock *CastEnd = 0;
169
170 if (NullCheckValue) {
171 CastNull = createBasicBlock("cast.null");
172 CastNotNull = createBasicBlock("cast.notnull");
173 CastEnd = createBasicBlock("cast.end");
174
175 llvm::Value *IsNull =
176 Builder.CreateICmpEQ(Value,
177 llvm::Constant::getNullValue(Value->getType()));
178 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
179 EmitBlock(CastNotNull);
180 }
181
182 llvm::Value *VirtualOffset = 0;
183
Anders Carlsson336a7dc2011-01-29 03:18:56 +0000184 if (VBase) {
185 if (Derived->hasAttr<FinalAttr>()) {
186 VirtualOffset = 0;
187
188 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
189
190 uint64_t VBaseOffset = Layout.getVBaseClassOffsetInBits(VBase);
191 NonVirtualOffset += VBaseOffset / 8;
192 } else
193 VirtualOffset = GetVirtualBaseClassOffset(Value, Derived, VBase);
194 }
Anders Carlsson34a2d382010-04-24 21:06:20 +0000195
196 // Apply the offsets.
197 Value = ApplyNonVirtualAndVirtualOffset(*this, Value, NonVirtualOffset,
198 VirtualOffset);
199
200 // Cast back.
201 Value = Builder.CreateBitCast(Value, BasePtrTy);
202
203 if (NullCheckValue) {
204 Builder.CreateBr(CastEnd);
205 EmitBlock(CastNull);
206 Builder.CreateBr(CastEnd);
207 EmitBlock(CastEnd);
208
209 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType());
210 PHI->reserveOperandSpace(2);
211 PHI->addIncoming(Value, CastNotNull);
212 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
213 CastNull);
214 Value = PHI;
215 }
216
217 return Value;
218}
219
220llvm::Value *
Anders Carlssona3697c92009-11-23 17:57:54 +0000221CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value,
Anders Carlsson8561a862010-04-24 23:01:49 +0000222 const CXXRecordDecl *Derived,
John McCallf871d0c2010-08-07 06:22:56 +0000223 CastExpr::path_const_iterator PathBegin,
224 CastExpr::path_const_iterator PathEnd,
Anders Carlssona3697c92009-11-23 17:57:54 +0000225 bool NullCheckValue) {
John McCallf871d0c2010-08-07 06:22:56 +0000226 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssona04efdf2010-04-24 21:23:59 +0000227
Anders Carlssona3697c92009-11-23 17:57:54 +0000228 QualType DerivedTy =
Anders Carlsson8561a862010-04-24 23:01:49 +0000229 getContext().getCanonicalType(getContext().getTagDeclType(Derived));
Anders Carlssona3697c92009-11-23 17:57:54 +0000230 const llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
231
Anders Carlssona552ea72010-01-31 01:43:37 +0000232 llvm::Value *NonVirtualOffset =
John McCallf871d0c2010-08-07 06:22:56 +0000233 CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
Anders Carlssona552ea72010-01-31 01:43:37 +0000234
235 if (!NonVirtualOffset) {
236 // No offset, we can just cast back.
237 return Builder.CreateBitCast(Value, DerivedPtrTy);
238 }
239
Anders Carlssona3697c92009-11-23 17:57:54 +0000240 llvm::BasicBlock *CastNull = 0;
241 llvm::BasicBlock *CastNotNull = 0;
242 llvm::BasicBlock *CastEnd = 0;
243
244 if (NullCheckValue) {
245 CastNull = createBasicBlock("cast.null");
246 CastNotNull = createBasicBlock("cast.notnull");
247 CastEnd = createBasicBlock("cast.end");
248
249 llvm::Value *IsNull =
250 Builder.CreateICmpEQ(Value,
251 llvm::Constant::getNullValue(Value->getType()));
252 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
253 EmitBlock(CastNotNull);
254 }
255
Anders Carlssona552ea72010-01-31 01:43:37 +0000256 // Apply the offset.
257 Value = Builder.CreatePtrToInt(Value, NonVirtualOffset->getType());
258 Value = Builder.CreateSub(Value, NonVirtualOffset);
259 Value = Builder.CreateIntToPtr(Value, DerivedPtrTy);
260
261 // Just cast.
262 Value = Builder.CreateBitCast(Value, DerivedPtrTy);
Anders Carlssona3697c92009-11-23 17:57:54 +0000263
264 if (NullCheckValue) {
265 Builder.CreateBr(CastEnd);
266 EmitBlock(CastNull);
267 Builder.CreateBr(CastEnd);
268 EmitBlock(CastEnd);
269
270 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType());
271 PHI->reserveOperandSpace(2);
272 PHI->addIncoming(Value, CastNotNull);
273 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
274 CastNull);
275 Value = PHI;
276 }
277
278 return Value;
Anders Carlsson5d58a1d2009-09-12 04:27:24 +0000279}
Anders Carlsson21c9ad92010-03-30 03:27:09 +0000280
Anders Carlssonc997d422010-01-02 01:01:18 +0000281/// GetVTTParameter - Return the VTT parameter that should be passed to a
282/// base constructor/destructor with virtual bases.
Anders Carlsson314e6222010-05-02 23:33:10 +0000283static llvm::Value *GetVTTParameter(CodeGenFunction &CGF, GlobalDecl GD,
284 bool ForVirtualBase) {
Anders Carlssonaf440352010-03-23 04:11:45 +0000285 if (!CodeGenVTables::needsVTTParameter(GD)) {
Anders Carlssonc997d422010-01-02 01:01:18 +0000286 // This constructor/destructor does not need a VTT parameter.
287 return 0;
288 }
289
290 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CGF.CurFuncDecl)->getParent();
291 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
John McCall3b477332010-02-18 19:59:28 +0000292
Anders Carlssonc997d422010-01-02 01:01:18 +0000293 llvm::Value *VTT;
294
John McCall3b477332010-02-18 19:59:28 +0000295 uint64_t SubVTTIndex;
296
297 // If the record matches the base, this is the complete ctor/dtor
298 // variant calling the base variant in a class with virtual bases.
299 if (RD == Base) {
Anders Carlssonaf440352010-03-23 04:11:45 +0000300 assert(!CodeGenVTables::needsVTTParameter(CGF.CurGD) &&
John McCall3b477332010-02-18 19:59:28 +0000301 "doing no-op VTT offset in base dtor/ctor?");
Anders Carlsson314e6222010-05-02 23:33:10 +0000302 assert(!ForVirtualBase && "Can't have same class as virtual base!");
John McCall3b477332010-02-18 19:59:28 +0000303 SubVTTIndex = 0;
304 } else {
Anders Carlssonc11bb212010-05-02 23:53:25 +0000305 const ASTRecordLayout &Layout =
306 CGF.getContext().getASTRecordLayout(RD);
307 uint64_t BaseOffset = ForVirtualBase ?
Anders Carlssona14f5972010-10-31 23:22:37 +0000308 Layout.getVBaseClassOffsetInBits(Base) :
309 Layout.getBaseClassOffsetInBits(Base);
Anders Carlssonc11bb212010-05-02 23:53:25 +0000310
311 SubVTTIndex =
312 CGF.CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
John McCall3b477332010-02-18 19:59:28 +0000313 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
314 }
Anders Carlssonc997d422010-01-02 01:01:18 +0000315
Anders Carlssonaf440352010-03-23 04:11:45 +0000316 if (CodeGenVTables::needsVTTParameter(CGF.CurGD)) {
Anders Carlssonc997d422010-01-02 01:01:18 +0000317 // A VTT parameter was passed to the constructor, use it.
318 VTT = CGF.LoadCXXVTT();
319 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
320 } else {
321 // We're the complete constructor, so get the VTT by name.
Anders Carlsson1cbce122011-01-29 19:16:51 +0000322 VTT = CGF.CGM.getVTables().GetAddrOfVTT(RD);
Anders Carlssonc997d422010-01-02 01:01:18 +0000323 VTT = CGF.Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
324 }
325
326 return VTT;
327}
328
John McCall182ab512010-07-21 01:23:41 +0000329namespace {
John McCall50da2ca2010-07-21 05:30:47 +0000330 /// Call the destructor for a direct base class.
John McCall1f0fca52010-07-21 07:22:38 +0000331 struct CallBaseDtor : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000332 const CXXRecordDecl *BaseClass;
333 bool BaseIsVirtual;
334 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
335 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
John McCall182ab512010-07-21 01:23:41 +0000336
337 void Emit(CodeGenFunction &CGF, bool IsForEH) {
John McCall50da2ca2010-07-21 05:30:47 +0000338 const CXXRecordDecl *DerivedClass =
339 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
340
341 const CXXDestructorDecl *D = BaseClass->getDestructor();
342 llvm::Value *Addr =
343 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThis(),
344 DerivedClass, BaseClass,
345 BaseIsVirtual);
346 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual, Addr);
John McCall182ab512010-07-21 01:23:41 +0000347 }
348 };
John McCall7e1dff72010-09-17 02:31:44 +0000349
350 /// A visitor which checks whether an initializer uses 'this' in a
351 /// way which requires the vtable to be properly set.
352 struct DynamicThisUseChecker : EvaluatedExprVisitor<DynamicThisUseChecker> {
353 typedef EvaluatedExprVisitor<DynamicThisUseChecker> super;
354
355 bool UsesThis;
356
357 DynamicThisUseChecker(ASTContext &C) : super(C), UsesThis(false) {}
358
359 // Black-list all explicit and implicit references to 'this'.
360 //
361 // Do we need to worry about external references to 'this' derived
362 // from arbitrary code? If so, then anything which runs arbitrary
363 // external code might potentially access the vtable.
364 void VisitCXXThisExpr(CXXThisExpr *E) { UsesThis = true; }
365 };
366}
367
368static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
369 DynamicThisUseChecker Checker(C);
370 Checker.Visit(const_cast<Expr*>(Init));
371 return Checker.UsesThis;
John McCall182ab512010-07-21 01:23:41 +0000372}
373
Anders Carlsson607d0372009-12-24 22:46:43 +0000374static void EmitBaseInitializer(CodeGenFunction &CGF,
375 const CXXRecordDecl *ClassDecl,
Sean Huntcbb67482011-01-08 20:30:50 +0000376 CXXCtorInitializer *BaseInit,
Anders Carlsson607d0372009-12-24 22:46:43 +0000377 CXXCtorType CtorType) {
378 assert(BaseInit->isBaseInitializer() &&
379 "Must have base initializer!");
380
381 llvm::Value *ThisPtr = CGF.LoadCXXThis();
382
383 const Type *BaseType = BaseInit->getBaseClass();
384 CXXRecordDecl *BaseClassDecl =
385 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
386
Anders Carlsson80638c52010-04-12 00:51:03 +0000387 bool isBaseVirtual = BaseInit->isBaseVirtual();
Anders Carlsson607d0372009-12-24 22:46:43 +0000388
389 // The base constructor doesn't construct virtual bases.
390 if (CtorType == Ctor_Base && isBaseVirtual)
391 return;
392
John McCall7e1dff72010-09-17 02:31:44 +0000393 // If the initializer for the base (other than the constructor
394 // itself) accesses 'this' in any way, we need to initialize the
395 // vtables.
396 if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
397 CGF.InitializeVTablePointers(ClassDecl);
398
John McCallbff225e2010-02-16 04:15:37 +0000399 // We can pretend to be a complete class because it only matters for
400 // virtual bases, and we only do virtual bases for complete ctors.
Anders Carlsson8561a862010-04-24 23:01:49 +0000401 llvm::Value *V =
402 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
John McCall50da2ca2010-07-21 05:30:47 +0000403 BaseClassDecl,
404 isBaseVirtual);
John McCallbff225e2010-02-16 04:15:37 +0000405
John McCall558d2ab2010-09-15 10:14:12 +0000406 AggValueSlot AggSlot = AggValueSlot::forAddr(V, false, /*Lifetime*/ true);
407
408 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
Anders Carlsson594d5e82010-02-06 20:00:21 +0000409
Anders Carlsson7a178512011-02-28 00:33:03 +0000410 if (CGF.CGM.getLangOptions().Exceptions &&
Anders Carlssonc1cfdf82011-02-20 00:20:27 +0000411 !BaseClassDecl->hasTrivialDestructor())
John McCall1f0fca52010-07-21 07:22:38 +0000412 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
413 isBaseVirtual);
Anders Carlsson607d0372009-12-24 22:46:43 +0000414}
415
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000416static void EmitAggMemberInitializer(CodeGenFunction &CGF,
417 LValue LHS,
418 llvm::Value *ArrayIndexVar,
Sean Huntcbb67482011-01-08 20:30:50 +0000419 CXXCtorInitializer *MemberInit,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000420 QualType T,
421 unsigned Index) {
422 if (Index == MemberInit->getNumArrayIndices()) {
John McCallf1549f62010-07-06 01:34:17 +0000423 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000424
425 llvm::Value *Dest = LHS.getAddress();
426 if (ArrayIndexVar) {
427 // If we have an array index variable, load it and use it as an offset.
428 // Then, increment the value.
429 llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar);
430 Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress");
431 llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1);
432 Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc");
433 CGF.Builder.CreateStore(Next, ArrayIndexVar);
434 }
John McCall558d2ab2010-09-15 10:14:12 +0000435
436 AggValueSlot Slot = AggValueSlot::forAddr(Dest, LHS.isVolatileQualified(),
437 /*Lifetime*/ true);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000438
John McCall558d2ab2010-09-15 10:14:12 +0000439 CGF.EmitAggExpr(MemberInit->getInit(), Slot);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000440
441 return;
442 }
443
444 const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T);
445 assert(Array && "Array initialization without the array type?");
446 llvm::Value *IndexVar
447 = CGF.GetAddrOfLocalVar(MemberInit->getArrayIndex(Index));
448 assert(IndexVar && "Array index variable not loaded");
449
450 // Initialize this index variable to zero.
451 llvm::Value* Zero
452 = llvm::Constant::getNullValue(
453 CGF.ConvertType(CGF.getContext().getSizeType()));
454 CGF.Builder.CreateStore(Zero, IndexVar);
455
456 // Start the loop with a block that tests the condition.
457 llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond");
458 llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end");
459
460 CGF.EmitBlock(CondBlock);
461
462 llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body");
463 // Generate: if (loop-index < number-of-elements) fall to the loop body,
464 // otherwise, go to the block after the for-loop.
465 uint64_t NumElements = Array->getSize().getZExtValue();
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000466 llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
Chris Lattner985f7392010-05-06 06:35:23 +0000467 llvm::Value *NumElementsPtr =
468 llvm::ConstantInt::get(Counter->getType(), NumElements);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000469 llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr,
470 "isless");
471
472 // If the condition is true, execute the body.
473 CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor);
474
475 CGF.EmitBlock(ForBody);
476 llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc");
477
478 {
John McCallf1549f62010-07-06 01:34:17 +0000479 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000480
481 // Inside the loop body recurse to emit the inner loop or, eventually, the
482 // constructor call.
483 EmitAggMemberInitializer(CGF, LHS, ArrayIndexVar, MemberInit,
484 Array->getElementType(), Index + 1);
485 }
486
487 CGF.EmitBlock(ContinueBlock);
488
489 // Emit the increment of the loop counter.
490 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
491 Counter = CGF.Builder.CreateLoad(IndexVar);
492 NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc");
493 CGF.Builder.CreateStore(NextVal, IndexVar);
494
495 // Finally, branch back up to the condition for the next iteration.
496 CGF.EmitBranch(CondBlock);
497
498 // Emit the fall-through block.
499 CGF.EmitBlock(AfterFor, true);
500}
John McCall182ab512010-07-21 01:23:41 +0000501
502namespace {
John McCall1f0fca52010-07-21 07:22:38 +0000503 struct CallMemberDtor : EHScopeStack::Cleanup {
John McCall182ab512010-07-21 01:23:41 +0000504 FieldDecl *Field;
505 CXXDestructorDecl *Dtor;
506
507 CallMemberDtor(FieldDecl *Field, CXXDestructorDecl *Dtor)
508 : Field(Field), Dtor(Dtor) {}
509
510 void Emit(CodeGenFunction &CGF, bool IsForEH) {
511 // FIXME: Is this OK for C++0x delegating constructors?
512 llvm::Value *ThisPtr = CGF.LoadCXXThis();
513 LValue LHS = CGF.EmitLValueForField(ThisPtr, Field, 0);
514
515 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
516 LHS.getAddress());
517 }
518 };
519}
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000520
Anders Carlsson607d0372009-12-24 22:46:43 +0000521static void EmitMemberInitializer(CodeGenFunction &CGF,
522 const CXXRecordDecl *ClassDecl,
Sean Huntcbb67482011-01-08 20:30:50 +0000523 CXXCtorInitializer *MemberInit,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000524 const CXXConstructorDecl *Constructor,
525 FunctionArgList &Args) {
Francois Pichet00eb3f92010-12-04 09:14:42 +0000526 assert(MemberInit->isAnyMemberInitializer() &&
Anders Carlsson607d0372009-12-24 22:46:43 +0000527 "Must have member initializer!");
528
529 // non-static data member initializers.
Francois Pichet00eb3f92010-12-04 09:14:42 +0000530 FieldDecl *Field = MemberInit->getAnyMember();
Anders Carlsson607d0372009-12-24 22:46:43 +0000531 QualType FieldType = CGF.getContext().getCanonicalType(Field->getType());
532
533 llvm::Value *ThisPtr = CGF.LoadCXXThis();
John McCalla9976d32010-05-21 01:18:57 +0000534 LValue LHS;
Anders Carlsson06a29702010-01-29 05:24:29 +0000535
Anders Carlsson607d0372009-12-24 22:46:43 +0000536 // If we are initializing an anonymous union field, drill down to the field.
Francois Pichet00eb3f92010-12-04 09:14:42 +0000537 if (MemberInit->isIndirectMemberInitializer()) {
538 LHS = CGF.EmitLValueForAnonRecordField(ThisPtr,
539 MemberInit->getIndirectMember(), 0);
540 FieldType = MemberInit->getIndirectMember()->getAnonField()->getType();
John McCalla9976d32010-05-21 01:18:57 +0000541 } else {
542 LHS = CGF.EmitLValueForFieldInitialization(ThisPtr, Field, 0);
Anders Carlsson607d0372009-12-24 22:46:43 +0000543 }
544
Sean Huntcbb67482011-01-08 20:30:50 +0000545 // FIXME: If there's no initializer and the CXXCtorInitializer
Douglas Gregor9db7dbb2010-01-31 09:12:51 +0000546 // was implicitly generated, we shouldn't be zeroing memory.
Anders Carlsson607d0372009-12-24 22:46:43 +0000547 RValue RHS;
548 if (FieldType->isReferenceType()) {
Anders Carlsson32f36ba2010-06-26 16:35:32 +0000549 RHS = CGF.EmitReferenceBindingToExpr(MemberInit->getInit(), Field);
Anders Carlsson607d0372009-12-24 22:46:43 +0000550 CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
Eli Friedman3bb94122010-01-31 19:07:50 +0000551 } else if (FieldType->isArrayType() && !MemberInit->getInit()) {
Anders Carlsson1884eb02010-05-22 17:35:42 +0000552 CGF.EmitNullInitialization(LHS.getAddress(), Field->getType());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +0000553 } else if (!CGF.hasAggregateLLVMType(Field->getType())) {
Eli Friedman0b292272010-06-03 19:58:07 +0000554 RHS = RValue::get(CGF.EmitScalarExpr(MemberInit->getInit()));
Anders Carlsson607d0372009-12-24 22:46:43 +0000555 CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +0000556 } else if (MemberInit->getInit()->getType()->isAnyComplexType()) {
557 CGF.EmitComplexExprIntoAddr(MemberInit->getInit(), LHS.getAddress(),
Anders Carlsson607d0372009-12-24 22:46:43 +0000558 LHS.isVolatileQualified());
559 } else {
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000560 llvm::Value *ArrayIndexVar = 0;
561 const ConstantArrayType *Array
562 = CGF.getContext().getAsConstantArrayType(FieldType);
563 if (Array && Constructor->isImplicit() &&
564 Constructor->isCopyConstructor()) {
565 const llvm::Type *SizeTy
566 = CGF.ConvertType(CGF.getContext().getSizeType());
567
568 // The LHS is a pointer to the first object we'll be constructing, as
569 // a flat array.
570 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
571 const llvm::Type *BasePtr = CGF.ConvertType(BaseElementTy);
572 BasePtr = llvm::PointerType::getUnqual(BasePtr);
573 llvm::Value *BaseAddrPtr = CGF.Builder.CreateBitCast(LHS.getAddress(),
574 BasePtr);
Daniel Dunbar9f553f52010-08-21 03:08:16 +0000575 LHS = CGF.MakeAddrLValue(BaseAddrPtr, BaseElementTy);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000576
577 // Create an array index that will be used to walk over all of the
578 // objects we're constructing.
579 ArrayIndexVar = CGF.CreateTempAlloca(SizeTy, "object.index");
580 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
581 CGF.Builder.CreateStore(Zero, ArrayIndexVar);
582
583 // If we are copying an array of scalars or classes with trivial copy
584 // constructors, perform a single aggregate copy.
585 const RecordType *Record = BaseElementTy->getAs<RecordType>();
586 if (!Record ||
587 cast<CXXRecordDecl>(Record->getDecl())->hasTrivialCopyConstructor()) {
588 // Find the source pointer. We knows it's the last argument because
589 // we know we're in a copy constructor.
590 unsigned SrcArgIndex = Args.size() - 1;
591 llvm::Value *SrcPtr
592 = CGF.Builder.CreateLoad(
593 CGF.GetAddrOfLocalVar(Args[SrcArgIndex].first));
594 LValue Src = CGF.EmitLValueForFieldInitialization(SrcPtr, Field, 0);
595
596 // Copy the aggregate.
597 CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
598 LHS.isVolatileQualified());
599 return;
600 }
601
602 // Emit the block variables for the array indices, if any.
603 for (unsigned I = 0, N = MemberInit->getNumArrayIndices(); I != N; ++I)
John McCallb6bbcc92010-10-15 04:57:14 +0000604 CGF.EmitAutoVarDecl(*MemberInit->getArrayIndex(I));
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000605 }
606
607 EmitAggMemberInitializer(CGF, LHS, ArrayIndexVar, MemberInit, FieldType, 0);
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000608
Anders Carlsson7a178512011-02-28 00:33:03 +0000609 if (!CGF.CGM.getLangOptions().Exceptions)
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000610 return;
611
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000612 // FIXME: If we have an array of classes w/ non-trivial destructors,
613 // we need to destroy in reverse order of construction along the exception
614 // path.
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000615 const RecordType *RT = FieldType->getAs<RecordType>();
616 if (!RT)
617 return;
618
619 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall182ab512010-07-21 01:23:41 +0000620 if (!RD->hasTrivialDestructor())
John McCall1f0fca52010-07-21 07:22:38 +0000621 CGF.EHStack.pushCleanup<CallMemberDtor>(EHCleanup, Field,
622 RD->getDestructor());
Anders Carlsson607d0372009-12-24 22:46:43 +0000623 }
624}
625
John McCallc0bf4622010-02-23 00:48:20 +0000626/// Checks whether the given constructor is a valid subject for the
627/// complete-to-base constructor delegation optimization, i.e.
628/// emitting the complete constructor as a simple call to the base
629/// constructor.
630static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
631
632 // Currently we disable the optimization for classes with virtual
633 // bases because (1) the addresses of parameter variables need to be
634 // consistent across all initializers but (2) the delegate function
635 // call necessarily creates a second copy of the parameter variable.
636 //
637 // The limiting example (purely theoretical AFAIK):
638 // struct A { A(int &c) { c++; } };
639 // struct B : virtual A {
640 // B(int count) : A(count) { printf("%d\n", count); }
641 // };
642 // ...although even this example could in principle be emitted as a
643 // delegation since the address of the parameter doesn't escape.
644 if (Ctor->getParent()->getNumVBases()) {
645 // TODO: white-list trivial vbase initializers. This case wouldn't
646 // be subject to the restrictions below.
647
648 // TODO: white-list cases where:
649 // - there are no non-reference parameters to the constructor
650 // - the initializers don't access any non-reference parameters
651 // - the initializers don't take the address of non-reference
652 // parameters
653 // - etc.
654 // If we ever add any of the above cases, remember that:
655 // - function-try-blocks will always blacklist this optimization
656 // - we need to perform the constructor prologue and cleanup in
657 // EmitConstructorBody.
658
659 return false;
660 }
661
662 // We also disable the optimization for variadic functions because
663 // it's impossible to "re-pass" varargs.
664 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
665 return false;
666
667 return true;
668}
669
John McCall9fc6a772010-02-19 09:25:03 +0000670/// EmitConstructorBody - Emits the body of the current constructor.
671void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
672 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
673 CXXCtorType CtorType = CurGD.getCtorType();
674
John McCallc0bf4622010-02-23 00:48:20 +0000675 // Before we go any further, try the complete->base constructor
676 // delegation optimization.
677 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor)) {
Devang Pateld67ef0e2010-08-11 21:04:37 +0000678 if (CGDebugInfo *DI = getDebugInfo())
679 DI->EmitStopPoint(Builder);
John McCallc0bf4622010-02-23 00:48:20 +0000680 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args);
681 return;
682 }
683
John McCall9fc6a772010-02-19 09:25:03 +0000684 Stmt *Body = Ctor->getBody();
685
John McCallc0bf4622010-02-23 00:48:20 +0000686 // Enter the function-try-block before the constructor prologue if
687 // applicable.
John McCallc0bf4622010-02-23 00:48:20 +0000688 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallc0bf4622010-02-23 00:48:20 +0000689 if (IsTryBody)
John McCall59a70002010-07-07 06:56:46 +0000690 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000691
John McCallf1549f62010-07-06 01:34:17 +0000692 EHScopeStack::stable_iterator CleanupDepth = EHStack.stable_begin();
John McCall9fc6a772010-02-19 09:25:03 +0000693
John McCallc0bf4622010-02-23 00:48:20 +0000694 // Emit the constructor prologue, i.e. the base and member
695 // initializers.
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000696 EmitCtorPrologue(Ctor, CtorType, Args);
John McCall9fc6a772010-02-19 09:25:03 +0000697
698 // Emit the body of the statement.
John McCallc0bf4622010-02-23 00:48:20 +0000699 if (IsTryBody)
John McCall9fc6a772010-02-19 09:25:03 +0000700 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
701 else if (Body)
702 EmitStmt(Body);
John McCall9fc6a772010-02-19 09:25:03 +0000703
704 // Emit any cleanup blocks associated with the member or base
705 // initializers, which includes (along the exceptional path) the
706 // destructors for those members and bases that were fully
707 // constructed.
John McCallf1549f62010-07-06 01:34:17 +0000708 PopCleanupBlocks(CleanupDepth);
John McCall9fc6a772010-02-19 09:25:03 +0000709
John McCallc0bf4622010-02-23 00:48:20 +0000710 if (IsTryBody)
John McCall59a70002010-07-07 06:56:46 +0000711 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000712}
713
Anders Carlsson607d0372009-12-24 22:46:43 +0000714/// EmitCtorPrologue - This routine generates necessary code to initialize
715/// base classes and non-static data members belonging to this constructor.
Anders Carlsson607d0372009-12-24 22:46:43 +0000716void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000717 CXXCtorType CtorType,
718 FunctionArgList &Args) {
Anders Carlsson607d0372009-12-24 22:46:43 +0000719 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000720
Sean Huntcbb67482011-01-08 20:30:50 +0000721 llvm::SmallVector<CXXCtorInitializer *, 8> MemberInitializers;
Anders Carlsson607d0372009-12-24 22:46:43 +0000722
Anders Carlsson607d0372009-12-24 22:46:43 +0000723 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
724 E = CD->init_end();
725 B != E; ++B) {
Sean Huntcbb67482011-01-08 20:30:50 +0000726 CXXCtorInitializer *Member = (*B);
Anders Carlsson607d0372009-12-24 22:46:43 +0000727
Anders Carlsson607d0372009-12-24 22:46:43 +0000728 if (Member->isBaseInitializer())
729 EmitBaseInitializer(*this, ClassDecl, Member, CtorType);
730 else
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000731 MemberInitializers.push_back(Member);
Anders Carlsson607d0372009-12-24 22:46:43 +0000732 }
733
Anders Carlsson603d6d12010-03-28 21:07:49 +0000734 InitializeVTablePointers(ClassDecl);
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000735
John McCallf1549f62010-07-06 01:34:17 +0000736 for (unsigned I = 0, E = MemberInitializers.size(); I != E; ++I)
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000737 EmitMemberInitializer(*this, ClassDecl, MemberInitializers[I], CD, Args);
Anders Carlsson607d0372009-12-24 22:46:43 +0000738}
739
John McCall9fc6a772010-02-19 09:25:03 +0000740/// EmitDestructorBody - Emits the body of the current destructor.
741void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
742 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
743 CXXDtorType DtorType = CurGD.getDtorType();
744
John McCall50da2ca2010-07-21 05:30:47 +0000745 // The call to operator delete in a deleting destructor happens
746 // outside of the function-try-block, which means it's always
747 // possible to delegate the destructor body to the complete
748 // destructor. Do so.
749 if (DtorType == Dtor_Deleting) {
750 EnterDtorCleanups(Dtor, Dtor_Deleting);
751 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
752 LoadCXXThis());
753 PopCleanupBlock();
754 return;
755 }
756
John McCall9fc6a772010-02-19 09:25:03 +0000757 Stmt *Body = Dtor->getBody();
758
759 // If the body is a function-try-block, enter the try before
John McCall50da2ca2010-07-21 05:30:47 +0000760 // anything else.
761 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCall9fc6a772010-02-19 09:25:03 +0000762 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +0000763 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000764
John McCall50da2ca2010-07-21 05:30:47 +0000765 // Enter the epilogue cleanups.
766 RunCleanupsScope DtorEpilogue(*this);
767
John McCall9fc6a772010-02-19 09:25:03 +0000768 // If this is the complete variant, just invoke the base variant;
769 // the epilogue will destruct the virtual bases. But we can't do
770 // this optimization if the body is a function-try-block, because
771 // we'd introduce *two* handler blocks.
John McCall50da2ca2010-07-21 05:30:47 +0000772 switch (DtorType) {
773 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
774
775 case Dtor_Complete:
776 // Enter the cleanup scopes for virtual bases.
777 EnterDtorCleanups(Dtor, Dtor_Complete);
778
779 if (!isTryBody) {
780 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
781 LoadCXXThis());
782 break;
783 }
784 // Fallthrough: act like we're in the base variant.
John McCall9fc6a772010-02-19 09:25:03 +0000785
John McCall50da2ca2010-07-21 05:30:47 +0000786 case Dtor_Base:
787 // Enter the cleanup scopes for fields and non-virtual bases.
788 EnterDtorCleanups(Dtor, Dtor_Base);
789
790 // Initialize the vtable pointers before entering the body.
Anders Carlsson603d6d12010-03-28 21:07:49 +0000791 InitializeVTablePointers(Dtor->getParent());
John McCall50da2ca2010-07-21 05:30:47 +0000792
793 if (isTryBody)
794 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
795 else if (Body)
796 EmitStmt(Body);
797 else {
798 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
799 // nothing to do besides what's in the epilogue
800 }
Fariborz Jahanian5abec142011-02-02 23:12:46 +0000801 // -fapple-kext must inline any call to this dtor into
802 // the caller's body.
803 if (getContext().getLangOptions().AppleKext)
804 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
John McCall50da2ca2010-07-21 05:30:47 +0000805 break;
John McCall9fc6a772010-02-19 09:25:03 +0000806 }
807
John McCall50da2ca2010-07-21 05:30:47 +0000808 // Jump out through the epilogue cleanups.
809 DtorEpilogue.ForceCleanup();
John McCall9fc6a772010-02-19 09:25:03 +0000810
811 // Exit the try if applicable.
812 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +0000813 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000814}
815
John McCall50da2ca2010-07-21 05:30:47 +0000816namespace {
817 /// Call the operator delete associated with the current destructor.
John McCall1f0fca52010-07-21 07:22:38 +0000818 struct CallDtorDelete : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000819 CallDtorDelete() {}
820
821 void Emit(CodeGenFunction &CGF, bool IsForEH) {
822 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
823 const CXXRecordDecl *ClassDecl = Dtor->getParent();
824 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
825 CGF.getContext().getTagDeclType(ClassDecl));
826 }
827 };
828
John McCall1f0fca52010-07-21 07:22:38 +0000829 struct CallArrayFieldDtor : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000830 const FieldDecl *Field;
831 CallArrayFieldDtor(const FieldDecl *Field) : Field(Field) {}
832
833 void Emit(CodeGenFunction &CGF, bool IsForEH) {
834 QualType FieldType = Field->getType();
835 const ConstantArrayType *Array =
836 CGF.getContext().getAsConstantArrayType(FieldType);
837
838 QualType BaseType =
839 CGF.getContext().getBaseElementType(Array->getElementType());
840 const CXXRecordDecl *FieldClassDecl = BaseType->getAsCXXRecordDecl();
841
842 llvm::Value *ThisPtr = CGF.LoadCXXThis();
843 LValue LHS = CGF.EmitLValueForField(ThisPtr, Field,
844 // FIXME: Qualifiers?
845 /*CVRQualifiers=*/0);
846
847 const llvm::Type *BasePtr = CGF.ConvertType(BaseType)->getPointerTo();
848 llvm::Value *BaseAddrPtr =
849 CGF.Builder.CreateBitCast(LHS.getAddress(), BasePtr);
850 CGF.EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(),
851 Array, BaseAddrPtr);
852 }
853 };
854
John McCall1f0fca52010-07-21 07:22:38 +0000855 struct CallFieldDtor : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000856 const FieldDecl *Field;
857 CallFieldDtor(const FieldDecl *Field) : Field(Field) {}
858
859 void Emit(CodeGenFunction &CGF, bool IsForEH) {
860 const CXXRecordDecl *FieldClassDecl =
861 Field->getType()->getAsCXXRecordDecl();
862
863 llvm::Value *ThisPtr = CGF.LoadCXXThis();
864 LValue LHS = CGF.EmitLValueForField(ThisPtr, Field,
865 // FIXME: Qualifiers?
866 /*CVRQualifiers=*/0);
867
868 CGF.EmitCXXDestructorCall(FieldClassDecl->getDestructor(),
869 Dtor_Complete, /*ForVirtualBase=*/false,
870 LHS.getAddress());
871 }
872 };
873}
874
Anders Carlsson607d0372009-12-24 22:46:43 +0000875/// EmitDtorEpilogue - Emit all code that comes at the end of class's
876/// destructor. This is to call destructors on members and base classes
877/// in reverse order of their construction.
John McCall50da2ca2010-07-21 05:30:47 +0000878void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
879 CXXDtorType DtorType) {
Anders Carlsson607d0372009-12-24 22:46:43 +0000880 assert(!DD->isTrivial() &&
881 "Should not emit dtor epilogue for trivial dtor!");
882
John McCall50da2ca2010-07-21 05:30:47 +0000883 // The deleting-destructor phase just needs to call the appropriate
884 // operator delete that Sema picked up.
John McCall3b477332010-02-18 19:59:28 +0000885 if (DtorType == Dtor_Deleting) {
886 assert(DD->getOperatorDelete() &&
887 "operator delete missing - EmitDtorEpilogue");
John McCall1f0fca52010-07-21 07:22:38 +0000888 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
John McCall3b477332010-02-18 19:59:28 +0000889 return;
890 }
891
John McCall50da2ca2010-07-21 05:30:47 +0000892 const CXXRecordDecl *ClassDecl = DD->getParent();
893
894 // The complete-destructor phase just destructs all the virtual bases.
John McCall3b477332010-02-18 19:59:28 +0000895 if (DtorType == Dtor_Complete) {
John McCall50da2ca2010-07-21 05:30:47 +0000896
897 // We push them in the forward order so that they'll be popped in
898 // the reverse order.
899 for (CXXRecordDecl::base_class_const_iterator I =
900 ClassDecl->vbases_begin(), E = ClassDecl->vbases_end();
John McCall3b477332010-02-18 19:59:28 +0000901 I != E; ++I) {
902 const CXXBaseSpecifier &Base = *I;
903 CXXRecordDecl *BaseClassDecl
904 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
905
906 // Ignore trivial destructors.
907 if (BaseClassDecl->hasTrivialDestructor())
908 continue;
John McCall50da2ca2010-07-21 05:30:47 +0000909
John McCall1f0fca52010-07-21 07:22:38 +0000910 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
911 BaseClassDecl,
912 /*BaseIsVirtual*/ true);
John McCall3b477332010-02-18 19:59:28 +0000913 }
John McCall50da2ca2010-07-21 05:30:47 +0000914
John McCall3b477332010-02-18 19:59:28 +0000915 return;
916 }
917
918 assert(DtorType == Dtor_Base);
John McCall50da2ca2010-07-21 05:30:47 +0000919
920 // Destroy non-virtual bases.
921 for (CXXRecordDecl::base_class_const_iterator I =
922 ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) {
923 const CXXBaseSpecifier &Base = *I;
924
925 // Ignore virtual bases.
926 if (Base.isVirtual())
927 continue;
928
929 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
930
931 // Ignore trivial destructors.
932 if (BaseClassDecl->hasTrivialDestructor())
933 continue;
John McCall3b477332010-02-18 19:59:28 +0000934
John McCall1f0fca52010-07-21 07:22:38 +0000935 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
936 BaseClassDecl,
937 /*BaseIsVirtual*/ false);
John McCall50da2ca2010-07-21 05:30:47 +0000938 }
939
940 // Destroy direct fields.
Anders Carlsson607d0372009-12-24 22:46:43 +0000941 llvm::SmallVector<const FieldDecl *, 16> FieldDecls;
942 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
943 E = ClassDecl->field_end(); I != E; ++I) {
944 const FieldDecl *Field = *I;
945
946 QualType FieldType = getContext().getCanonicalType(Field->getType());
John McCall50da2ca2010-07-21 05:30:47 +0000947 const ConstantArrayType *Array =
948 getContext().getAsConstantArrayType(FieldType);
949 if (Array)
950 FieldType = getContext().getBaseElementType(Array->getElementType());
Anders Carlsson607d0372009-12-24 22:46:43 +0000951
952 const RecordType *RT = FieldType->getAs<RecordType>();
953 if (!RT)
954 continue;
955
956 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
957 if (FieldClassDecl->hasTrivialDestructor())
958 continue;
John McCall50da2ca2010-07-21 05:30:47 +0000959
Anders Carlsson607d0372009-12-24 22:46:43 +0000960 if (Array)
John McCall1f0fca52010-07-21 07:22:38 +0000961 EHStack.pushCleanup<CallArrayFieldDtor>(NormalAndEHCleanup, Field);
John McCall50da2ca2010-07-21 05:30:47 +0000962 else
John McCall1f0fca52010-07-21 07:22:38 +0000963 EHStack.pushCleanup<CallFieldDtor>(NormalAndEHCleanup, Field);
Anders Carlsson607d0372009-12-24 22:46:43 +0000964 }
Anders Carlsson607d0372009-12-24 22:46:43 +0000965}
966
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000967/// EmitCXXAggrConstructorCall - This routine essentially creates a (nested)
968/// for-loop to call the default constructor on individual members of the
969/// array.
970/// 'D' is the default constructor for elements of the array, 'ArrayTy' is the
971/// array type and 'ArrayPtr' points to the beginning fo the array.
972/// It is assumed that all relevant checks have been made by the caller.
Douglas Gregor59174c02010-07-21 01:10:17 +0000973///
974/// \param ZeroInitialization True if each element should be zero-initialized
975/// before it is constructed.
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000976void
977CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
Douglas Gregor59174c02010-07-21 01:10:17 +0000978 const ConstantArrayType *ArrayTy,
979 llvm::Value *ArrayPtr,
980 CallExpr::const_arg_iterator ArgBeg,
981 CallExpr::const_arg_iterator ArgEnd,
982 bool ZeroInitialization) {
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000983
984 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
985 llvm::Value * NumElements =
986 llvm::ConstantInt::get(SizeTy,
987 getContext().getConstantArrayElementCount(ArrayTy));
988
Douglas Gregor59174c02010-07-21 01:10:17 +0000989 EmitCXXAggrConstructorCall(D, NumElements, ArrayPtr, ArgBeg, ArgEnd,
990 ZeroInitialization);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000991}
992
993void
994CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
995 llvm::Value *NumElements,
996 llvm::Value *ArrayPtr,
997 CallExpr::const_arg_iterator ArgBeg,
Douglas Gregor59174c02010-07-21 01:10:17 +0000998 CallExpr::const_arg_iterator ArgEnd,
999 bool ZeroInitialization) {
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001000 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
1001
1002 // Create a temporary for the loop index and initialize it with 0.
1003 llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index");
1004 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
1005 Builder.CreateStore(Zero, IndexPtr);
1006
1007 // Start the loop with a block that tests the condition.
1008 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1009 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1010
1011 EmitBlock(CondBlock);
1012
1013 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1014
1015 // Generate: if (loop-index < number-of-elements fall to the loop body,
1016 // otherwise, go to the block after the for-loop.
1017 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1018 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless");
1019 // If the condition is true, execute the body.
1020 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
1021
1022 EmitBlock(ForBody);
1023
1024 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1025 // Inside the loop body, emit the constructor call on the array element.
1026 Counter = Builder.CreateLoad(IndexPtr);
1027 llvm::Value *Address = Builder.CreateInBoundsGEP(ArrayPtr, Counter,
1028 "arrayidx");
1029
Douglas Gregor59174c02010-07-21 01:10:17 +00001030 // Zero initialize the storage, if requested.
1031 if (ZeroInitialization)
1032 EmitNullInitialization(Address,
1033 getContext().getTypeDeclType(D->getParent()));
1034
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001035 // C++ [class.temporary]p4:
1036 // There are two contexts in which temporaries are destroyed at a different
1037 // point than the end of the full-expression. The first context is when a
1038 // default constructor is called to initialize an element of an array.
1039 // If the constructor has one or more default arguments, the destruction of
1040 // every temporary created in a default argument expression is sequenced
1041 // before the construction of the next array element, if any.
1042
1043 // Keep track of the current number of live temporaries.
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001044 {
John McCallf1549f62010-07-06 01:34:17 +00001045 RunCleanupsScope Scope(*this);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001046
Anders Carlsson155ed4a2010-05-02 23:20:53 +00001047 EmitCXXConstructorCall(D, Ctor_Complete, /*ForVirtualBase=*/false, Address,
Anders Carlsson24eb78e2010-05-02 23:01:10 +00001048 ArgBeg, ArgEnd);
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001049 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001050
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001051 EmitBlock(ContinueBlock);
1052
1053 // Emit the increment of the loop counter.
1054 llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1);
1055 Counter = Builder.CreateLoad(IndexPtr);
1056 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1057 Builder.CreateStore(NextVal, IndexPtr);
1058
1059 // Finally, branch back up to the condition for the next iteration.
1060 EmitBranch(CondBlock);
1061
1062 // Emit the fall-through block.
1063 EmitBlock(AfterFor, true);
1064}
1065
1066/// EmitCXXAggrDestructorCall - calls the default destructor on array
1067/// elements in reverse order of construction.
1068void
1069CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
1070 const ArrayType *Array,
1071 llvm::Value *This) {
1072 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1073 assert(CA && "Do we support VLA for destruction ?");
1074 uint64_t ElementCount = getContext().getConstantArrayElementCount(CA);
1075
1076 const llvm::Type *SizeLTy = ConvertType(getContext().getSizeType());
1077 llvm::Value* ElementCountPtr = llvm::ConstantInt::get(SizeLTy, ElementCount);
1078 EmitCXXAggrDestructorCall(D, ElementCountPtr, This);
1079}
1080
1081/// EmitCXXAggrDestructorCall - calls the default destructor on array
1082/// elements in reverse order of construction.
1083void
1084CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
1085 llvm::Value *UpperCount,
1086 llvm::Value *This) {
1087 const llvm::Type *SizeLTy = ConvertType(getContext().getSizeType());
1088 llvm::Value *One = llvm::ConstantInt::get(SizeLTy, 1);
1089
1090 // Create a temporary for the loop index and initialize it with count of
1091 // array elements.
1092 llvm::Value *IndexPtr = CreateTempAlloca(SizeLTy, "loop.index");
1093
1094 // Store the number of elements in the index pointer.
1095 Builder.CreateStore(UpperCount, IndexPtr);
1096
1097 // Start the loop with a block that tests the condition.
1098 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1099 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1100
1101 EmitBlock(CondBlock);
1102
1103 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1104
1105 // Generate: if (loop-index != 0 fall to the loop body,
1106 // otherwise, go to the block after the for-loop.
1107 llvm::Value* zeroConstant =
1108 llvm::Constant::getNullValue(SizeLTy);
1109 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1110 llvm::Value *IsNE = Builder.CreateICmpNE(Counter, zeroConstant,
1111 "isne");
1112 // If the condition is true, execute the body.
1113 Builder.CreateCondBr(IsNE, ForBody, AfterFor);
1114
1115 EmitBlock(ForBody);
1116
1117 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1118 // Inside the loop body, emit the constructor call on the array element.
1119 Counter = Builder.CreateLoad(IndexPtr);
1120 Counter = Builder.CreateSub(Counter, One);
1121 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
Anders Carlsson8e6404c2010-05-02 23:29:11 +00001122 EmitCXXDestructorCall(D, Dtor_Complete, /*ForVirtualBase=*/false, Address);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001123
1124 EmitBlock(ContinueBlock);
1125
1126 // Emit the decrement of the loop counter.
1127 Counter = Builder.CreateLoad(IndexPtr);
1128 Counter = Builder.CreateSub(Counter, One, "dec");
1129 Builder.CreateStore(Counter, IndexPtr);
1130
1131 // Finally, branch back up to the condition for the next iteration.
1132 EmitBranch(CondBlock);
1133
1134 // Emit the fall-through block.
1135 EmitBlock(AfterFor, true);
1136}
1137
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001138void
1139CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
Anders Carlsson155ed4a2010-05-02 23:20:53 +00001140 CXXCtorType Type, bool ForVirtualBase,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001141 llvm::Value *This,
1142 CallExpr::const_arg_iterator ArgBeg,
1143 CallExpr::const_arg_iterator ArgEnd) {
Devang Patel3ee36af2011-02-22 20:55:26 +00001144
1145 CGDebugInfo *DI = getDebugInfo();
1146 if (DI && CGM.getCodeGenOpts().LimitDebugInfo) {
1147 // If debug info for this class has been emitted then this is the right time
1148 // to do so.
1149 const CXXRecordDecl *Parent = D->getParent();
1150 DI->getOrCreateRecordType(CGM.getContext().getTypeDeclType(Parent),
1151 Parent->getLocation());
1152 }
1153
John McCall8b6bbeb2010-02-06 00:25:16 +00001154 if (D->isTrivial()) {
1155 if (ArgBeg == ArgEnd) {
1156 // Trivial default constructor, no codegen required.
1157 assert(D->isDefaultConstructor() &&
1158 "trivial 0-arg ctor not a default ctor");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001159 return;
1160 }
John McCall8b6bbeb2010-02-06 00:25:16 +00001161
1162 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
1163 assert(D->isCopyConstructor() && "trivial 1-arg ctor not a copy ctor");
1164
John McCall8b6bbeb2010-02-06 00:25:16 +00001165 const Expr *E = (*ArgBeg);
1166 QualType Ty = E->getType();
1167 llvm::Value *Src = EmitLValue(E).getAddress();
1168 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001169 return;
1170 }
1171
Anders Carlsson314e6222010-05-02 23:33:10 +00001172 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(D, Type), ForVirtualBase);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001173 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
1174
Anders Carlssonc997d422010-01-02 01:01:18 +00001175 EmitCXXMemberCall(D, Callee, ReturnValueSlot(), This, VTT, ArgBeg, ArgEnd);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001176}
1177
John McCallc0bf4622010-02-23 00:48:20 +00001178void
Fariborz Jahanian34999872010-11-13 21:53:34 +00001179CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
1180 llvm::Value *This, llvm::Value *Src,
1181 CallExpr::const_arg_iterator ArgBeg,
1182 CallExpr::const_arg_iterator ArgEnd) {
1183 if (D->isTrivial()) {
1184 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
1185 assert(D->isCopyConstructor() && "trivial 1-arg ctor not a copy ctor");
1186 EmitAggregateCopy(This, Src, (*ArgBeg)->getType());
1187 return;
1188 }
1189 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D,
1190 clang::Ctor_Complete);
1191 assert(D->isInstance() &&
1192 "Trying to emit a member call expr on a static method!");
1193
1194 const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
1195
1196 CallArgList Args;
1197
1198 // Push the this ptr.
1199 Args.push_back(std::make_pair(RValue::get(This),
1200 D->getThisType(getContext())));
1201
1202
1203 // Push the src ptr.
1204 QualType QT = *(FPT->arg_type_begin());
1205 const llvm::Type *t = CGM.getTypes().ConvertType(QT);
1206 Src = Builder.CreateBitCast(Src, t);
1207 Args.push_back(std::make_pair(RValue::get(Src), QT));
1208
1209 // Skip over first argument (Src).
1210 ++ArgBeg;
1211 CallExpr::const_arg_iterator Arg = ArgBeg;
1212 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin()+1,
1213 E = FPT->arg_type_end(); I != E; ++I, ++Arg) {
1214 assert(Arg != ArgEnd && "Running over edge of argument list!");
1215 QualType ArgType = *I;
1216 Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType),
1217 ArgType));
1218 }
1219 // Either we've emitted all the call args, or we have a call to a
1220 // variadic function.
1221 assert((Arg == ArgEnd || FPT->isVariadic()) &&
1222 "Extra arguments in non-variadic function!");
1223 // If we still have any arguments, emit them using the type of the argument.
1224 for (; Arg != ArgEnd; ++Arg) {
1225 QualType ArgType = Arg->getType();
1226 Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType),
1227 ArgType));
1228 }
1229
1230 QualType ResultType = FPT->getResultType();
1231 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args,
1232 FPT->getExtInfo()),
1233 Callee, ReturnValueSlot(), Args, D);
1234}
1235
1236void
John McCallc0bf4622010-02-23 00:48:20 +00001237CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1238 CXXCtorType CtorType,
1239 const FunctionArgList &Args) {
1240 CallArgList DelegateArgs;
1241
1242 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
1243 assert(I != E && "no parameters to constructor");
1244
1245 // this
1246 DelegateArgs.push_back(std::make_pair(RValue::get(LoadCXXThis()),
1247 I->second));
1248 ++I;
1249
1250 // vtt
Anders Carlsson314e6222010-05-02 23:33:10 +00001251 if (llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(Ctor, CtorType),
1252 /*ForVirtualBase=*/false)) {
John McCallc0bf4622010-02-23 00:48:20 +00001253 QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
1254 DelegateArgs.push_back(std::make_pair(RValue::get(VTT), VoidPP));
1255
Anders Carlssonaf440352010-03-23 04:11:45 +00001256 if (CodeGenVTables::needsVTTParameter(CurGD)) {
John McCallc0bf4622010-02-23 00:48:20 +00001257 assert(I != E && "cannot skip vtt parameter, already done with args");
1258 assert(I->second == VoidPP && "skipping parameter not of vtt type");
1259 ++I;
1260 }
1261 }
1262
1263 // Explicit arguments.
1264 for (; I != E; ++I) {
John McCallc0bf4622010-02-23 00:48:20 +00001265 const VarDecl *Param = I->first;
1266 QualType ArgType = Param->getType(); // because we're passing it to itself
John McCall27360712010-05-26 22:34:26 +00001267 RValue Arg = EmitDelegateCallArg(Param);
John McCallc0bf4622010-02-23 00:48:20 +00001268
1269 DelegateArgs.push_back(std::make_pair(Arg, ArgType));
1270 }
1271
1272 EmitCall(CGM.getTypes().getFunctionInfo(Ctor, CtorType),
1273 CGM.GetAddrOfCXXConstructor(Ctor, CtorType),
1274 ReturnValueSlot(), DelegateArgs, Ctor);
1275}
1276
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001277void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
1278 CXXDtorType Type,
Anders Carlsson8e6404c2010-05-02 23:29:11 +00001279 bool ForVirtualBase,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001280 llvm::Value *This) {
Anders Carlsson314e6222010-05-02 23:33:10 +00001281 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(DD, Type),
1282 ForVirtualBase);
Fariborz Jahanianccd52592011-02-01 23:22:34 +00001283 llvm::Value *Callee = 0;
1284 if (getContext().getLangOptions().AppleKext)
Fariborz Jahanian771c6782011-02-03 19:27:17 +00001285 Callee = BuildAppleKextVirtualDestructorCall(DD, Type,
1286 DD->getParent());
Fariborz Jahanianccd52592011-02-01 23:22:34 +00001287
1288 if (!Callee)
1289 Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001290
Anders Carlssonc997d422010-01-02 01:01:18 +00001291 EmitCXXMemberCall(DD, Callee, ReturnValueSlot(), This, VTT, 0, 0);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001292}
1293
John McCall291ae942010-07-21 01:41:18 +00001294namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001295 struct CallLocalDtor : EHScopeStack::Cleanup {
John McCall291ae942010-07-21 01:41:18 +00001296 const CXXDestructorDecl *Dtor;
1297 llvm::Value *Addr;
1298
1299 CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
1300 : Dtor(D), Addr(Addr) {}
1301
1302 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1303 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1304 /*ForVirtualBase=*/false, Addr);
1305 }
1306 };
1307}
1308
John McCall81407d42010-07-21 06:29:51 +00001309void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
1310 llvm::Value *Addr) {
John McCall1f0fca52010-07-21 07:22:38 +00001311 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
John McCall81407d42010-07-21 06:29:51 +00001312}
1313
John McCallf1549f62010-07-06 01:34:17 +00001314void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
1315 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
1316 if (!ClassDecl) return;
1317 if (ClassDecl->hasTrivialDestructor()) return;
1318
1319 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCall81407d42010-07-21 06:29:51 +00001320 PushDestructorCleanup(D, Addr);
John McCallf1549f62010-07-06 01:34:17 +00001321}
1322
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001323llvm::Value *
Anders Carlssonbb7e17b2010-01-31 01:36:53 +00001324CodeGenFunction::GetVirtualBaseClassOffset(llvm::Value *This,
1325 const CXXRecordDecl *ClassDecl,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001326 const CXXRecordDecl *BaseClassDecl) {
Dan Gohman043fb9a2010-10-26 18:44:08 +00001327 llvm::Value *VTablePtr = GetVTablePtr(This, Int8PtrTy);
Anders Carlssonbba16072010-03-11 07:15:17 +00001328 int64_t VBaseOffsetOffset =
Anders Carlssonaf440352010-03-23 04:11:45 +00001329 CGM.getVTables().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001330
1331 llvm::Value *VBaseOffsetPtr =
Anders Carlssonbba16072010-03-11 07:15:17 +00001332 Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset, "vbase.offset.ptr");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001333 const llvm::Type *PtrDiffTy =
1334 ConvertType(getContext().getPointerDiffType());
1335
1336 VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr,
1337 PtrDiffTy->getPointerTo());
1338
1339 llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1340
1341 return VBaseOffset;
1342}
1343
Anders Carlssond103f9f2010-03-28 19:40:00 +00001344void
1345CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001346 const CXXRecordDecl *NearestVBase,
Anders Carlsson42358402010-05-03 00:07:07 +00001347 uint64_t OffsetFromNearestVBase,
Anders Carlssond103f9f2010-03-28 19:40:00 +00001348 llvm::Constant *VTable,
1349 const CXXRecordDecl *VTableClass) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001350 const CXXRecordDecl *RD = Base.getBase();
1351
Anders Carlssond103f9f2010-03-28 19:40:00 +00001352 // Compute the address point.
Anders Carlssonc83f1062010-03-29 01:08:49 +00001353 llvm::Value *VTableAddressPoint;
Anders Carlsson851853d2010-03-29 02:38:51 +00001354
Anders Carlssonc83f1062010-03-29 01:08:49 +00001355 // Check if we need to use a vtable from the VTT.
Anders Carlsson851853d2010-03-29 02:38:51 +00001356 if (CodeGenVTables::needsVTTParameter(CurGD) &&
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001357 (RD->getNumVBases() || NearestVBase)) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001358 // Get the secondary vpointer index.
1359 uint64_t VirtualPointerIndex =
1360 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1361
1362 /// Load the VTT.
1363 llvm::Value *VTT = LoadCXXVTT();
1364 if (VirtualPointerIndex)
1365 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1366
1367 // And load the address point from the VTT.
1368 VTableAddressPoint = Builder.CreateLoad(VTT);
1369 } else {
Anders Carlsson64c9eca2010-03-29 02:08:26 +00001370 uint64_t AddressPoint = CGM.getVTables().getAddressPoint(Base, VTableClass);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001371 VTableAddressPoint =
Anders Carlssond103f9f2010-03-28 19:40:00 +00001372 Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001373 }
Anders Carlssond103f9f2010-03-28 19:40:00 +00001374
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001375 // Compute where to store the address point.
Anders Carlsson8246cc72010-05-03 00:29:58 +00001376 llvm::Value *VirtualOffset = 0;
1377 uint64_t NonVirtualOffset = 0;
Anders Carlsson3e79c302010-04-20 18:05:10 +00001378
1379 if (CodeGenVTables::needsVTTParameter(CurGD) && NearestVBase) {
1380 // We need to use the virtual base offset offset because the virtual base
1381 // might have a different offset in the most derived class.
Anders Carlsson8246cc72010-05-03 00:29:58 +00001382 VirtualOffset = GetVirtualBaseClassOffset(LoadCXXThis(), VTableClass,
1383 NearestVBase);
1384 NonVirtualOffset = OffsetFromNearestVBase / 8;
Anders Carlsson3e79c302010-04-20 18:05:10 +00001385 } else {
Anders Carlsson8246cc72010-05-03 00:29:58 +00001386 // We can just use the base offset in the complete class.
1387 NonVirtualOffset = Base.getBaseOffset() / 8;
Anders Carlsson3e79c302010-04-20 18:05:10 +00001388 }
Anders Carlsson8246cc72010-05-03 00:29:58 +00001389
1390 // Apply the offsets.
1391 llvm::Value *VTableField = LoadCXXThis();
1392
1393 if (NonVirtualOffset || VirtualOffset)
1394 VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
1395 NonVirtualOffset,
1396 VirtualOffset);
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001397
Anders Carlssond103f9f2010-03-28 19:40:00 +00001398 // Finally, store the address point.
1399 const llvm::Type *AddressPointPtrTy =
1400 VTableAddressPoint->getType()->getPointerTo();
1401 VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
1402 Builder.CreateStore(VTableAddressPoint, VTableField);
1403}
1404
Anders Carlsson603d6d12010-03-28 21:07:49 +00001405void
1406CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001407 const CXXRecordDecl *NearestVBase,
Anders Carlsson42358402010-05-03 00:07:07 +00001408 uint64_t OffsetFromNearestVBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001409 bool BaseIsNonVirtualPrimaryBase,
1410 llvm::Constant *VTable,
1411 const CXXRecordDecl *VTableClass,
1412 VisitedVirtualBasesSetTy& VBases) {
1413 // If this base is a non-virtual primary base the address point has already
1414 // been set.
1415 if (!BaseIsNonVirtualPrimaryBase) {
1416 // Initialize the vtable pointer for this base.
Anders Carlsson42358402010-05-03 00:07:07 +00001417 InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
1418 VTable, VTableClass);
Anders Carlsson603d6d12010-03-28 21:07:49 +00001419 }
1420
1421 const CXXRecordDecl *RD = Base.getBase();
1422
1423 // Traverse bases.
1424 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1425 E = RD->bases_end(); I != E; ++I) {
1426 CXXRecordDecl *BaseDecl
1427 = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1428
1429 // Ignore classes without a vtable.
1430 if (!BaseDecl->isDynamicClass())
1431 continue;
1432
1433 uint64_t BaseOffset;
Anders Carlsson42358402010-05-03 00:07:07 +00001434 uint64_t BaseOffsetFromNearestVBase;
Anders Carlsson14da9de2010-03-29 01:16:41 +00001435 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001436
1437 if (I->isVirtual()) {
1438 // Check if we've visited this virtual base before.
1439 if (!VBases.insert(BaseDecl))
1440 continue;
1441
1442 const ASTRecordLayout &Layout =
1443 getContext().getASTRecordLayout(VTableClass);
1444
Anders Carlssona14f5972010-10-31 23:22:37 +00001445 BaseOffset = Layout.getVBaseClassOffsetInBits(BaseDecl);
Anders Carlsson42358402010-05-03 00:07:07 +00001446 BaseOffsetFromNearestVBase = 0;
Anders Carlsson14da9de2010-03-29 01:16:41 +00001447 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001448 } else {
1449 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1450
Anders Carlssona14f5972010-10-31 23:22:37 +00001451 BaseOffset =
1452 Base.getBaseOffset() + Layout.getBaseClassOffsetInBits(BaseDecl);
Anders Carlsson42358402010-05-03 00:07:07 +00001453 BaseOffsetFromNearestVBase =
Anders Carlssona14f5972010-10-31 23:22:37 +00001454 OffsetFromNearestVBase + Layout.getBaseClassOffsetInBits(BaseDecl);
Anders Carlsson14da9de2010-03-29 01:16:41 +00001455 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001456 }
1457
1458 InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001459 I->isVirtual() ? BaseDecl : NearestVBase,
Anders Carlsson42358402010-05-03 00:07:07 +00001460 BaseOffsetFromNearestVBase,
Anders Carlsson14da9de2010-03-29 01:16:41 +00001461 BaseDeclIsNonVirtualPrimaryBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001462 VTable, VTableClass, VBases);
1463 }
1464}
1465
1466void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
1467 // Ignore classes without a vtable.
Anders Carlsson07036902010-03-26 04:39:42 +00001468 if (!RD->isDynamicClass())
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001469 return;
1470
Anders Carlsson07036902010-03-26 04:39:42 +00001471 // Get the VTable.
1472 llvm::Constant *VTable = CGM.getVTables().GetAddrOfVTable(RD);
Anders Carlsson5c6c1d92010-03-24 03:57:14 +00001473
Anders Carlsson603d6d12010-03-28 21:07:49 +00001474 // Initialize the vtable pointers for this class and all of its bases.
1475 VisitedVirtualBasesSetTy VBases;
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001476 InitializeVTablePointers(BaseSubobject(RD, 0), /*NearestVBase=*/0,
Anders Carlsson42358402010-05-03 00:07:07 +00001477 /*OffsetFromNearestVBase=*/0,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001478 /*BaseIsNonVirtualPrimaryBase=*/false,
1479 VTable, RD, VBases);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001480}
Dan Gohman043fb9a2010-10-26 18:44:08 +00001481
1482llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
1483 const llvm::Type *Ty) {
1484 llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
1485 return Builder.CreateLoad(VTablePtrSrc, "vtable");
1486}