blob: 1a0a59e6c38613730dff333e6b9431001f9cc4b1 [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
John McCalld26bc762011-03-09 04:27:21 +0000592 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000593 LValue Src = CGF.EmitLValueForFieldInitialization(SrcPtr, Field, 0);
594
595 // Copy the aggregate.
596 CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
597 LHS.isVolatileQualified());
598 return;
599 }
600
601 // Emit the block variables for the array indices, if any.
602 for (unsigned I = 0, N = MemberInit->getNumArrayIndices(); I != N; ++I)
John McCallb6bbcc92010-10-15 04:57:14 +0000603 CGF.EmitAutoVarDecl(*MemberInit->getArrayIndex(I));
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000604 }
605
606 EmitAggMemberInitializer(CGF, LHS, ArrayIndexVar, MemberInit, FieldType, 0);
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000607
Anders Carlsson7a178512011-02-28 00:33:03 +0000608 if (!CGF.CGM.getLangOptions().Exceptions)
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000609 return;
610
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000611 // FIXME: If we have an array of classes w/ non-trivial destructors,
612 // we need to destroy in reverse order of construction along the exception
613 // path.
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000614 const RecordType *RT = FieldType->getAs<RecordType>();
615 if (!RT)
616 return;
617
618 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall182ab512010-07-21 01:23:41 +0000619 if (!RD->hasTrivialDestructor())
John McCall1f0fca52010-07-21 07:22:38 +0000620 CGF.EHStack.pushCleanup<CallMemberDtor>(EHCleanup, Field,
621 RD->getDestructor());
Anders Carlsson607d0372009-12-24 22:46:43 +0000622 }
623}
624
John McCallc0bf4622010-02-23 00:48:20 +0000625/// Checks whether the given constructor is a valid subject for the
626/// complete-to-base constructor delegation optimization, i.e.
627/// emitting the complete constructor as a simple call to the base
628/// constructor.
629static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
630
631 // Currently we disable the optimization for classes with virtual
632 // bases because (1) the addresses of parameter variables need to be
633 // consistent across all initializers but (2) the delegate function
634 // call necessarily creates a second copy of the parameter variable.
635 //
636 // The limiting example (purely theoretical AFAIK):
637 // struct A { A(int &c) { c++; } };
638 // struct B : virtual A {
639 // B(int count) : A(count) { printf("%d\n", count); }
640 // };
641 // ...although even this example could in principle be emitted as a
642 // delegation since the address of the parameter doesn't escape.
643 if (Ctor->getParent()->getNumVBases()) {
644 // TODO: white-list trivial vbase initializers. This case wouldn't
645 // be subject to the restrictions below.
646
647 // TODO: white-list cases where:
648 // - there are no non-reference parameters to the constructor
649 // - the initializers don't access any non-reference parameters
650 // - the initializers don't take the address of non-reference
651 // parameters
652 // - etc.
653 // If we ever add any of the above cases, remember that:
654 // - function-try-blocks will always blacklist this optimization
655 // - we need to perform the constructor prologue and cleanup in
656 // EmitConstructorBody.
657
658 return false;
659 }
660
661 // We also disable the optimization for variadic functions because
662 // it's impossible to "re-pass" varargs.
663 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
664 return false;
665
666 return true;
667}
668
John McCall9fc6a772010-02-19 09:25:03 +0000669/// EmitConstructorBody - Emits the body of the current constructor.
670void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
671 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
672 CXXCtorType CtorType = CurGD.getCtorType();
673
John McCallc0bf4622010-02-23 00:48:20 +0000674 // Before we go any further, try the complete->base constructor
675 // delegation optimization.
676 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor)) {
Devang Pateld67ef0e2010-08-11 21:04:37 +0000677 if (CGDebugInfo *DI = getDebugInfo())
678 DI->EmitStopPoint(Builder);
John McCallc0bf4622010-02-23 00:48:20 +0000679 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args);
680 return;
681 }
682
John McCall9fc6a772010-02-19 09:25:03 +0000683 Stmt *Body = Ctor->getBody();
684
John McCallc0bf4622010-02-23 00:48:20 +0000685 // Enter the function-try-block before the constructor prologue if
686 // applicable.
John McCallc0bf4622010-02-23 00:48:20 +0000687 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallc0bf4622010-02-23 00:48:20 +0000688 if (IsTryBody)
John McCall59a70002010-07-07 06:56:46 +0000689 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000690
John McCallf1549f62010-07-06 01:34:17 +0000691 EHScopeStack::stable_iterator CleanupDepth = EHStack.stable_begin();
John McCall9fc6a772010-02-19 09:25:03 +0000692
John McCallc0bf4622010-02-23 00:48:20 +0000693 // Emit the constructor prologue, i.e. the base and member
694 // initializers.
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000695 EmitCtorPrologue(Ctor, CtorType, Args);
John McCall9fc6a772010-02-19 09:25:03 +0000696
697 // Emit the body of the statement.
John McCallc0bf4622010-02-23 00:48:20 +0000698 if (IsTryBody)
John McCall9fc6a772010-02-19 09:25:03 +0000699 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
700 else if (Body)
701 EmitStmt(Body);
John McCall9fc6a772010-02-19 09:25:03 +0000702
703 // Emit any cleanup blocks associated with the member or base
704 // initializers, which includes (along the exceptional path) the
705 // destructors for those members and bases that were fully
706 // constructed.
John McCallf1549f62010-07-06 01:34:17 +0000707 PopCleanupBlocks(CleanupDepth);
John McCall9fc6a772010-02-19 09:25:03 +0000708
John McCallc0bf4622010-02-23 00:48:20 +0000709 if (IsTryBody)
John McCall59a70002010-07-07 06:56:46 +0000710 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000711}
712
Anders Carlsson607d0372009-12-24 22:46:43 +0000713/// EmitCtorPrologue - This routine generates necessary code to initialize
714/// base classes and non-static data members belonging to this constructor.
Anders Carlsson607d0372009-12-24 22:46:43 +0000715void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000716 CXXCtorType CtorType,
717 FunctionArgList &Args) {
Anders Carlsson607d0372009-12-24 22:46:43 +0000718 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000719
Sean Huntcbb67482011-01-08 20:30:50 +0000720 llvm::SmallVector<CXXCtorInitializer *, 8> MemberInitializers;
Anders Carlsson607d0372009-12-24 22:46:43 +0000721
Anders Carlsson607d0372009-12-24 22:46:43 +0000722 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
723 E = CD->init_end();
724 B != E; ++B) {
Sean Huntcbb67482011-01-08 20:30:50 +0000725 CXXCtorInitializer *Member = (*B);
Anders Carlsson607d0372009-12-24 22:46:43 +0000726
Anders Carlsson607d0372009-12-24 22:46:43 +0000727 if (Member->isBaseInitializer())
728 EmitBaseInitializer(*this, ClassDecl, Member, CtorType);
729 else
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000730 MemberInitializers.push_back(Member);
Anders Carlsson607d0372009-12-24 22:46:43 +0000731 }
732
Anders Carlsson603d6d12010-03-28 21:07:49 +0000733 InitializeVTablePointers(ClassDecl);
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000734
John McCallf1549f62010-07-06 01:34:17 +0000735 for (unsigned I = 0, E = MemberInitializers.size(); I != E; ++I)
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000736 EmitMemberInitializer(*this, ClassDecl, MemberInitializers[I], CD, Args);
Anders Carlsson607d0372009-12-24 22:46:43 +0000737}
738
John McCall9fc6a772010-02-19 09:25:03 +0000739/// EmitDestructorBody - Emits the body of the current destructor.
740void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
741 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
742 CXXDtorType DtorType = CurGD.getDtorType();
743
John McCall50da2ca2010-07-21 05:30:47 +0000744 // The call to operator delete in a deleting destructor happens
745 // outside of the function-try-block, which means it's always
746 // possible to delegate the destructor body to the complete
747 // destructor. Do so.
748 if (DtorType == Dtor_Deleting) {
749 EnterDtorCleanups(Dtor, Dtor_Deleting);
750 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
751 LoadCXXThis());
752 PopCleanupBlock();
753 return;
754 }
755
John McCall9fc6a772010-02-19 09:25:03 +0000756 Stmt *Body = Dtor->getBody();
757
758 // If the body is a function-try-block, enter the try before
John McCall50da2ca2010-07-21 05:30:47 +0000759 // anything else.
760 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCall9fc6a772010-02-19 09:25:03 +0000761 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +0000762 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000763
John McCall50da2ca2010-07-21 05:30:47 +0000764 // Enter the epilogue cleanups.
765 RunCleanupsScope DtorEpilogue(*this);
766
John McCall9fc6a772010-02-19 09:25:03 +0000767 // If this is the complete variant, just invoke the base variant;
768 // the epilogue will destruct the virtual bases. But we can't do
769 // this optimization if the body is a function-try-block, because
770 // we'd introduce *two* handler blocks.
John McCall50da2ca2010-07-21 05:30:47 +0000771 switch (DtorType) {
772 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
773
774 case Dtor_Complete:
775 // Enter the cleanup scopes for virtual bases.
776 EnterDtorCleanups(Dtor, Dtor_Complete);
777
778 if (!isTryBody) {
779 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
780 LoadCXXThis());
781 break;
782 }
783 // Fallthrough: act like we're in the base variant.
John McCall9fc6a772010-02-19 09:25:03 +0000784
John McCall50da2ca2010-07-21 05:30:47 +0000785 case Dtor_Base:
786 // Enter the cleanup scopes for fields and non-virtual bases.
787 EnterDtorCleanups(Dtor, Dtor_Base);
788
789 // Initialize the vtable pointers before entering the body.
Anders Carlsson603d6d12010-03-28 21:07:49 +0000790 InitializeVTablePointers(Dtor->getParent());
John McCall50da2ca2010-07-21 05:30:47 +0000791
792 if (isTryBody)
793 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
794 else if (Body)
795 EmitStmt(Body);
796 else {
797 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
798 // nothing to do besides what's in the epilogue
799 }
Fariborz Jahanian5abec142011-02-02 23:12:46 +0000800 // -fapple-kext must inline any call to this dtor into
801 // the caller's body.
802 if (getContext().getLangOptions().AppleKext)
803 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
John McCall50da2ca2010-07-21 05:30:47 +0000804 break;
John McCall9fc6a772010-02-19 09:25:03 +0000805 }
806
John McCall50da2ca2010-07-21 05:30:47 +0000807 // Jump out through the epilogue cleanups.
808 DtorEpilogue.ForceCleanup();
John McCall9fc6a772010-02-19 09:25:03 +0000809
810 // Exit the try if applicable.
811 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +0000812 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000813}
814
John McCall50da2ca2010-07-21 05:30:47 +0000815namespace {
816 /// Call the operator delete associated with the current destructor.
John McCall1f0fca52010-07-21 07:22:38 +0000817 struct CallDtorDelete : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000818 CallDtorDelete() {}
819
820 void Emit(CodeGenFunction &CGF, bool IsForEH) {
821 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
822 const CXXRecordDecl *ClassDecl = Dtor->getParent();
823 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
824 CGF.getContext().getTagDeclType(ClassDecl));
825 }
826 };
827
John McCall1f0fca52010-07-21 07:22:38 +0000828 struct CallArrayFieldDtor : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000829 const FieldDecl *Field;
830 CallArrayFieldDtor(const FieldDecl *Field) : Field(Field) {}
831
832 void Emit(CodeGenFunction &CGF, bool IsForEH) {
833 QualType FieldType = Field->getType();
834 const ConstantArrayType *Array =
835 CGF.getContext().getAsConstantArrayType(FieldType);
836
837 QualType BaseType =
838 CGF.getContext().getBaseElementType(Array->getElementType());
839 const CXXRecordDecl *FieldClassDecl = BaseType->getAsCXXRecordDecl();
840
841 llvm::Value *ThisPtr = CGF.LoadCXXThis();
842 LValue LHS = CGF.EmitLValueForField(ThisPtr, Field,
843 // FIXME: Qualifiers?
844 /*CVRQualifiers=*/0);
845
846 const llvm::Type *BasePtr = CGF.ConvertType(BaseType)->getPointerTo();
847 llvm::Value *BaseAddrPtr =
848 CGF.Builder.CreateBitCast(LHS.getAddress(), BasePtr);
849 CGF.EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(),
850 Array, BaseAddrPtr);
851 }
852 };
853
John McCall1f0fca52010-07-21 07:22:38 +0000854 struct CallFieldDtor : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000855 const FieldDecl *Field;
856 CallFieldDtor(const FieldDecl *Field) : Field(Field) {}
857
858 void Emit(CodeGenFunction &CGF, bool IsForEH) {
859 const CXXRecordDecl *FieldClassDecl =
860 Field->getType()->getAsCXXRecordDecl();
861
862 llvm::Value *ThisPtr = CGF.LoadCXXThis();
863 LValue LHS = CGF.EmitLValueForField(ThisPtr, Field,
864 // FIXME: Qualifiers?
865 /*CVRQualifiers=*/0);
866
867 CGF.EmitCXXDestructorCall(FieldClassDecl->getDestructor(),
868 Dtor_Complete, /*ForVirtualBase=*/false,
869 LHS.getAddress());
870 }
871 };
872}
873
Anders Carlsson607d0372009-12-24 22:46:43 +0000874/// EmitDtorEpilogue - Emit all code that comes at the end of class's
875/// destructor. This is to call destructors on members and base classes
876/// in reverse order of their construction.
John McCall50da2ca2010-07-21 05:30:47 +0000877void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
878 CXXDtorType DtorType) {
Anders Carlsson607d0372009-12-24 22:46:43 +0000879 assert(!DD->isTrivial() &&
880 "Should not emit dtor epilogue for trivial dtor!");
881
John McCall50da2ca2010-07-21 05:30:47 +0000882 // The deleting-destructor phase just needs to call the appropriate
883 // operator delete that Sema picked up.
John McCall3b477332010-02-18 19:59:28 +0000884 if (DtorType == Dtor_Deleting) {
885 assert(DD->getOperatorDelete() &&
886 "operator delete missing - EmitDtorEpilogue");
John McCall1f0fca52010-07-21 07:22:38 +0000887 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
John McCall3b477332010-02-18 19:59:28 +0000888 return;
889 }
890
John McCall50da2ca2010-07-21 05:30:47 +0000891 const CXXRecordDecl *ClassDecl = DD->getParent();
892
893 // The complete-destructor phase just destructs all the virtual bases.
John McCall3b477332010-02-18 19:59:28 +0000894 if (DtorType == Dtor_Complete) {
John McCall50da2ca2010-07-21 05:30:47 +0000895
896 // We push them in the forward order so that they'll be popped in
897 // the reverse order.
898 for (CXXRecordDecl::base_class_const_iterator I =
899 ClassDecl->vbases_begin(), E = ClassDecl->vbases_end();
John McCall3b477332010-02-18 19:59:28 +0000900 I != E; ++I) {
901 const CXXBaseSpecifier &Base = *I;
902 CXXRecordDecl *BaseClassDecl
903 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
904
905 // Ignore trivial destructors.
906 if (BaseClassDecl->hasTrivialDestructor())
907 continue;
John McCall50da2ca2010-07-21 05:30:47 +0000908
John McCall1f0fca52010-07-21 07:22:38 +0000909 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
910 BaseClassDecl,
911 /*BaseIsVirtual*/ true);
John McCall3b477332010-02-18 19:59:28 +0000912 }
John McCall50da2ca2010-07-21 05:30:47 +0000913
John McCall3b477332010-02-18 19:59:28 +0000914 return;
915 }
916
917 assert(DtorType == Dtor_Base);
John McCall50da2ca2010-07-21 05:30:47 +0000918
919 // Destroy non-virtual bases.
920 for (CXXRecordDecl::base_class_const_iterator I =
921 ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) {
922 const CXXBaseSpecifier &Base = *I;
923
924 // Ignore virtual bases.
925 if (Base.isVirtual())
926 continue;
927
928 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
929
930 // Ignore trivial destructors.
931 if (BaseClassDecl->hasTrivialDestructor())
932 continue;
John McCall3b477332010-02-18 19:59:28 +0000933
John McCall1f0fca52010-07-21 07:22:38 +0000934 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
935 BaseClassDecl,
936 /*BaseIsVirtual*/ false);
John McCall50da2ca2010-07-21 05:30:47 +0000937 }
938
939 // Destroy direct fields.
Anders Carlsson607d0372009-12-24 22:46:43 +0000940 llvm::SmallVector<const FieldDecl *, 16> FieldDecls;
941 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
942 E = ClassDecl->field_end(); I != E; ++I) {
943 const FieldDecl *Field = *I;
944
945 QualType FieldType = getContext().getCanonicalType(Field->getType());
John McCall50da2ca2010-07-21 05:30:47 +0000946 const ConstantArrayType *Array =
947 getContext().getAsConstantArrayType(FieldType);
948 if (Array)
949 FieldType = getContext().getBaseElementType(Array->getElementType());
Anders Carlsson607d0372009-12-24 22:46:43 +0000950
951 const RecordType *RT = FieldType->getAs<RecordType>();
952 if (!RT)
953 continue;
954
955 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
956 if (FieldClassDecl->hasTrivialDestructor())
957 continue;
John McCall50da2ca2010-07-21 05:30:47 +0000958
Anders Carlsson607d0372009-12-24 22:46:43 +0000959 if (Array)
John McCall1f0fca52010-07-21 07:22:38 +0000960 EHStack.pushCleanup<CallArrayFieldDtor>(NormalAndEHCleanup, Field);
John McCall50da2ca2010-07-21 05:30:47 +0000961 else
John McCall1f0fca52010-07-21 07:22:38 +0000962 EHStack.pushCleanup<CallFieldDtor>(NormalAndEHCleanup, Field);
Anders Carlsson607d0372009-12-24 22:46:43 +0000963 }
Anders Carlsson607d0372009-12-24 22:46:43 +0000964}
965
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000966/// EmitCXXAggrConstructorCall - This routine essentially creates a (nested)
967/// for-loop to call the default constructor on individual members of the
968/// array.
969/// 'D' is the default constructor for elements of the array, 'ArrayTy' is the
970/// array type and 'ArrayPtr' points to the beginning fo the array.
971/// It is assumed that all relevant checks have been made by the caller.
Douglas Gregor59174c02010-07-21 01:10:17 +0000972///
973/// \param ZeroInitialization True if each element should be zero-initialized
974/// before it is constructed.
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000975void
976CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
Douglas Gregor59174c02010-07-21 01:10:17 +0000977 const ConstantArrayType *ArrayTy,
978 llvm::Value *ArrayPtr,
979 CallExpr::const_arg_iterator ArgBeg,
980 CallExpr::const_arg_iterator ArgEnd,
981 bool ZeroInitialization) {
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000982
983 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
984 llvm::Value * NumElements =
985 llvm::ConstantInt::get(SizeTy,
986 getContext().getConstantArrayElementCount(ArrayTy));
987
Douglas Gregor59174c02010-07-21 01:10:17 +0000988 EmitCXXAggrConstructorCall(D, NumElements, ArrayPtr, ArgBeg, ArgEnd,
989 ZeroInitialization);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000990}
991
992void
993CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
994 llvm::Value *NumElements,
995 llvm::Value *ArrayPtr,
996 CallExpr::const_arg_iterator ArgBeg,
Douglas Gregor59174c02010-07-21 01:10:17 +0000997 CallExpr::const_arg_iterator ArgEnd,
998 bool ZeroInitialization) {
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000999 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
1000
1001 // Create a temporary for the loop index and initialize it with 0.
1002 llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index");
1003 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
1004 Builder.CreateStore(Zero, IndexPtr);
1005
1006 // Start the loop with a block that tests the condition.
1007 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1008 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1009
1010 EmitBlock(CondBlock);
1011
1012 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1013
1014 // Generate: if (loop-index < number-of-elements fall to the loop body,
1015 // otherwise, go to the block after the for-loop.
1016 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1017 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless");
1018 // If the condition is true, execute the body.
1019 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
1020
1021 EmitBlock(ForBody);
1022
1023 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1024 // Inside the loop body, emit the constructor call on the array element.
1025 Counter = Builder.CreateLoad(IndexPtr);
1026 llvm::Value *Address = Builder.CreateInBoundsGEP(ArrayPtr, Counter,
1027 "arrayidx");
1028
Douglas Gregor59174c02010-07-21 01:10:17 +00001029 // Zero initialize the storage, if requested.
1030 if (ZeroInitialization)
1031 EmitNullInitialization(Address,
1032 getContext().getTypeDeclType(D->getParent()));
1033
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001034 // C++ [class.temporary]p4:
1035 // There are two contexts in which temporaries are destroyed at a different
1036 // point than the end of the full-expression. The first context is when a
1037 // default constructor is called to initialize an element of an array.
1038 // If the constructor has one or more default arguments, the destruction of
1039 // every temporary created in a default argument expression is sequenced
1040 // before the construction of the next array element, if any.
1041
1042 // Keep track of the current number of live temporaries.
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001043 {
John McCallf1549f62010-07-06 01:34:17 +00001044 RunCleanupsScope Scope(*this);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001045
Anders Carlsson155ed4a2010-05-02 23:20:53 +00001046 EmitCXXConstructorCall(D, Ctor_Complete, /*ForVirtualBase=*/false, Address,
Anders Carlsson24eb78e2010-05-02 23:01:10 +00001047 ArgBeg, ArgEnd);
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001048 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001049
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001050 EmitBlock(ContinueBlock);
1051
1052 // Emit the increment of the loop counter.
1053 llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1);
1054 Counter = Builder.CreateLoad(IndexPtr);
1055 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1056 Builder.CreateStore(NextVal, IndexPtr);
1057
1058 // Finally, branch back up to the condition for the next iteration.
1059 EmitBranch(CondBlock);
1060
1061 // Emit the fall-through block.
1062 EmitBlock(AfterFor, true);
1063}
1064
1065/// EmitCXXAggrDestructorCall - calls the default destructor on array
1066/// elements in reverse order of construction.
1067void
1068CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
1069 const ArrayType *Array,
1070 llvm::Value *This) {
1071 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1072 assert(CA && "Do we support VLA for destruction ?");
1073 uint64_t ElementCount = getContext().getConstantArrayElementCount(CA);
1074
1075 const llvm::Type *SizeLTy = ConvertType(getContext().getSizeType());
1076 llvm::Value* ElementCountPtr = llvm::ConstantInt::get(SizeLTy, ElementCount);
1077 EmitCXXAggrDestructorCall(D, ElementCountPtr, This);
1078}
1079
1080/// EmitCXXAggrDestructorCall - calls the default destructor on array
1081/// elements in reverse order of construction.
1082void
1083CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
1084 llvm::Value *UpperCount,
1085 llvm::Value *This) {
1086 const llvm::Type *SizeLTy = ConvertType(getContext().getSizeType());
1087 llvm::Value *One = llvm::ConstantInt::get(SizeLTy, 1);
1088
1089 // Create a temporary for the loop index and initialize it with count of
1090 // array elements.
1091 llvm::Value *IndexPtr = CreateTempAlloca(SizeLTy, "loop.index");
1092
1093 // Store the number of elements in the index pointer.
1094 Builder.CreateStore(UpperCount, IndexPtr);
1095
1096 // Start the loop with a block that tests the condition.
1097 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1098 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1099
1100 EmitBlock(CondBlock);
1101
1102 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1103
1104 // Generate: if (loop-index != 0 fall to the loop body,
1105 // otherwise, go to the block after the for-loop.
1106 llvm::Value* zeroConstant =
1107 llvm::Constant::getNullValue(SizeLTy);
1108 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1109 llvm::Value *IsNE = Builder.CreateICmpNE(Counter, zeroConstant,
1110 "isne");
1111 // If the condition is true, execute the body.
1112 Builder.CreateCondBr(IsNE, ForBody, AfterFor);
1113
1114 EmitBlock(ForBody);
1115
1116 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1117 // Inside the loop body, emit the constructor call on the array element.
1118 Counter = Builder.CreateLoad(IndexPtr);
1119 Counter = Builder.CreateSub(Counter, One);
1120 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
Anders Carlsson8e6404c2010-05-02 23:29:11 +00001121 EmitCXXDestructorCall(D, Dtor_Complete, /*ForVirtualBase=*/false, Address);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001122
1123 EmitBlock(ContinueBlock);
1124
1125 // Emit the decrement of the loop counter.
1126 Counter = Builder.CreateLoad(IndexPtr);
1127 Counter = Builder.CreateSub(Counter, One, "dec");
1128 Builder.CreateStore(Counter, IndexPtr);
1129
1130 // Finally, branch back up to the condition for the next iteration.
1131 EmitBranch(CondBlock);
1132
1133 // Emit the fall-through block.
1134 EmitBlock(AfterFor, true);
1135}
1136
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001137void
1138CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
Anders Carlsson155ed4a2010-05-02 23:20:53 +00001139 CXXCtorType Type, bool ForVirtualBase,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001140 llvm::Value *This,
1141 CallExpr::const_arg_iterator ArgBeg,
1142 CallExpr::const_arg_iterator ArgEnd) {
Devang Patel3ee36af2011-02-22 20:55:26 +00001143
1144 CGDebugInfo *DI = getDebugInfo();
1145 if (DI && CGM.getCodeGenOpts().LimitDebugInfo) {
1146 // If debug info for this class has been emitted then this is the right time
1147 // to do so.
1148 const CXXRecordDecl *Parent = D->getParent();
1149 DI->getOrCreateRecordType(CGM.getContext().getTypeDeclType(Parent),
1150 Parent->getLocation());
1151 }
1152
John McCall8b6bbeb2010-02-06 00:25:16 +00001153 if (D->isTrivial()) {
1154 if (ArgBeg == ArgEnd) {
1155 // Trivial default constructor, no codegen required.
1156 assert(D->isDefaultConstructor() &&
1157 "trivial 0-arg ctor not a default ctor");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001158 return;
1159 }
John McCall8b6bbeb2010-02-06 00:25:16 +00001160
1161 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
1162 assert(D->isCopyConstructor() && "trivial 1-arg ctor not a copy ctor");
1163
John McCall8b6bbeb2010-02-06 00:25:16 +00001164 const Expr *E = (*ArgBeg);
1165 QualType Ty = E->getType();
1166 llvm::Value *Src = EmitLValue(E).getAddress();
1167 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001168 return;
1169 }
1170
Anders Carlsson314e6222010-05-02 23:33:10 +00001171 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(D, Type), ForVirtualBase);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001172 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
1173
Anders Carlssonc997d422010-01-02 01:01:18 +00001174 EmitCXXMemberCall(D, Callee, ReturnValueSlot(), This, VTT, ArgBeg, ArgEnd);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001175}
1176
John McCallc0bf4622010-02-23 00:48:20 +00001177void
Fariborz Jahanian34999872010-11-13 21:53:34 +00001178CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
1179 llvm::Value *This, llvm::Value *Src,
1180 CallExpr::const_arg_iterator ArgBeg,
1181 CallExpr::const_arg_iterator ArgEnd) {
1182 if (D->isTrivial()) {
1183 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
1184 assert(D->isCopyConstructor() && "trivial 1-arg ctor not a copy ctor");
1185 EmitAggregateCopy(This, Src, (*ArgBeg)->getType());
1186 return;
1187 }
1188 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D,
1189 clang::Ctor_Complete);
1190 assert(D->isInstance() &&
1191 "Trying to emit a member call expr on a static method!");
1192
1193 const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
1194
1195 CallArgList Args;
1196
1197 // Push the this ptr.
1198 Args.push_back(std::make_pair(RValue::get(This),
1199 D->getThisType(getContext())));
1200
1201
1202 // Push the src ptr.
1203 QualType QT = *(FPT->arg_type_begin());
1204 const llvm::Type *t = CGM.getTypes().ConvertType(QT);
1205 Src = Builder.CreateBitCast(Src, t);
1206 Args.push_back(std::make_pair(RValue::get(Src), QT));
1207
1208 // Skip over first argument (Src).
1209 ++ArgBeg;
1210 CallExpr::const_arg_iterator Arg = ArgBeg;
1211 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin()+1,
1212 E = FPT->arg_type_end(); I != E; ++I, ++Arg) {
1213 assert(Arg != ArgEnd && "Running over edge of argument list!");
1214 QualType ArgType = *I;
1215 Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType),
1216 ArgType));
1217 }
1218 // Either we've emitted all the call args, or we have a call to a
1219 // variadic function.
1220 assert((Arg == ArgEnd || FPT->isVariadic()) &&
1221 "Extra arguments in non-variadic function!");
1222 // If we still have any arguments, emit them using the type of the argument.
1223 for (; Arg != ArgEnd; ++Arg) {
1224 QualType ArgType = Arg->getType();
1225 Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType),
1226 ArgType));
1227 }
1228
1229 QualType ResultType = FPT->getResultType();
1230 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args,
1231 FPT->getExtInfo()),
1232 Callee, ReturnValueSlot(), Args, D);
1233}
1234
1235void
John McCallc0bf4622010-02-23 00:48:20 +00001236CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1237 CXXCtorType CtorType,
1238 const FunctionArgList &Args) {
1239 CallArgList DelegateArgs;
1240
1241 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
1242 assert(I != E && "no parameters to constructor");
1243
1244 // this
1245 DelegateArgs.push_back(std::make_pair(RValue::get(LoadCXXThis()),
John McCalld26bc762011-03-09 04:27:21 +00001246 (*I)->getType()));
John McCallc0bf4622010-02-23 00:48:20 +00001247 ++I;
1248
1249 // vtt
Anders Carlsson314e6222010-05-02 23:33:10 +00001250 if (llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(Ctor, CtorType),
1251 /*ForVirtualBase=*/false)) {
John McCallc0bf4622010-02-23 00:48:20 +00001252 QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
1253 DelegateArgs.push_back(std::make_pair(RValue::get(VTT), VoidPP));
1254
Anders Carlssonaf440352010-03-23 04:11:45 +00001255 if (CodeGenVTables::needsVTTParameter(CurGD)) {
John McCallc0bf4622010-02-23 00:48:20 +00001256 assert(I != E && "cannot skip vtt parameter, already done with args");
John McCalld26bc762011-03-09 04:27:21 +00001257 assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
John McCallc0bf4622010-02-23 00:48:20 +00001258 ++I;
1259 }
1260 }
1261
1262 // Explicit arguments.
1263 for (; I != E; ++I) {
John McCalld26bc762011-03-09 04:27:21 +00001264 const VarDecl *Param = *I;
John McCallc0bf4622010-02-23 00:48:20 +00001265 QualType ArgType = Param->getType(); // because we're passing it to itself
John McCall27360712010-05-26 22:34:26 +00001266 RValue Arg = EmitDelegateCallArg(Param);
John McCallc0bf4622010-02-23 00:48:20 +00001267
1268 DelegateArgs.push_back(std::make_pair(Arg, ArgType));
1269 }
1270
1271 EmitCall(CGM.getTypes().getFunctionInfo(Ctor, CtorType),
1272 CGM.GetAddrOfCXXConstructor(Ctor, CtorType),
1273 ReturnValueSlot(), DelegateArgs, Ctor);
1274}
1275
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001276void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
1277 CXXDtorType Type,
Anders Carlsson8e6404c2010-05-02 23:29:11 +00001278 bool ForVirtualBase,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001279 llvm::Value *This) {
Anders Carlsson314e6222010-05-02 23:33:10 +00001280 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(DD, Type),
1281 ForVirtualBase);
Fariborz Jahanianccd52592011-02-01 23:22:34 +00001282 llvm::Value *Callee = 0;
1283 if (getContext().getLangOptions().AppleKext)
Fariborz Jahanian771c6782011-02-03 19:27:17 +00001284 Callee = BuildAppleKextVirtualDestructorCall(DD, Type,
1285 DD->getParent());
Fariborz Jahanianccd52592011-02-01 23:22:34 +00001286
1287 if (!Callee)
1288 Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001289
Anders Carlssonc997d422010-01-02 01:01:18 +00001290 EmitCXXMemberCall(DD, Callee, ReturnValueSlot(), This, VTT, 0, 0);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001291}
1292
John McCall291ae942010-07-21 01:41:18 +00001293namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001294 struct CallLocalDtor : EHScopeStack::Cleanup {
John McCall291ae942010-07-21 01:41:18 +00001295 const CXXDestructorDecl *Dtor;
1296 llvm::Value *Addr;
1297
1298 CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
1299 : Dtor(D), Addr(Addr) {}
1300
1301 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1302 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1303 /*ForVirtualBase=*/false, Addr);
1304 }
1305 };
1306}
1307
John McCall81407d42010-07-21 06:29:51 +00001308void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
1309 llvm::Value *Addr) {
John McCall1f0fca52010-07-21 07:22:38 +00001310 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
John McCall81407d42010-07-21 06:29:51 +00001311}
1312
John McCallf1549f62010-07-06 01:34:17 +00001313void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
1314 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
1315 if (!ClassDecl) return;
1316 if (ClassDecl->hasTrivialDestructor()) return;
1317
1318 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCall81407d42010-07-21 06:29:51 +00001319 PushDestructorCleanup(D, Addr);
John McCallf1549f62010-07-06 01:34:17 +00001320}
1321
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001322llvm::Value *
Anders Carlssonbb7e17b2010-01-31 01:36:53 +00001323CodeGenFunction::GetVirtualBaseClassOffset(llvm::Value *This,
1324 const CXXRecordDecl *ClassDecl,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001325 const CXXRecordDecl *BaseClassDecl) {
Dan Gohman043fb9a2010-10-26 18:44:08 +00001326 llvm::Value *VTablePtr = GetVTablePtr(This, Int8PtrTy);
Anders Carlssonbba16072010-03-11 07:15:17 +00001327 int64_t VBaseOffsetOffset =
Anders Carlssonaf440352010-03-23 04:11:45 +00001328 CGM.getVTables().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001329
1330 llvm::Value *VBaseOffsetPtr =
Anders Carlssonbba16072010-03-11 07:15:17 +00001331 Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset, "vbase.offset.ptr");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001332 const llvm::Type *PtrDiffTy =
1333 ConvertType(getContext().getPointerDiffType());
1334
1335 VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr,
1336 PtrDiffTy->getPointerTo());
1337
1338 llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1339
1340 return VBaseOffset;
1341}
1342
Anders Carlssond103f9f2010-03-28 19:40:00 +00001343void
1344CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001345 const CXXRecordDecl *NearestVBase,
Anders Carlsson42358402010-05-03 00:07:07 +00001346 uint64_t OffsetFromNearestVBase,
Anders Carlssond103f9f2010-03-28 19:40:00 +00001347 llvm::Constant *VTable,
1348 const CXXRecordDecl *VTableClass) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001349 const CXXRecordDecl *RD = Base.getBase();
1350
Anders Carlssond103f9f2010-03-28 19:40:00 +00001351 // Compute the address point.
Anders Carlssonc83f1062010-03-29 01:08:49 +00001352 llvm::Value *VTableAddressPoint;
Anders Carlsson851853d2010-03-29 02:38:51 +00001353
Anders Carlssonc83f1062010-03-29 01:08:49 +00001354 // Check if we need to use a vtable from the VTT.
Anders Carlsson851853d2010-03-29 02:38:51 +00001355 if (CodeGenVTables::needsVTTParameter(CurGD) &&
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001356 (RD->getNumVBases() || NearestVBase)) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001357 // Get the secondary vpointer index.
1358 uint64_t VirtualPointerIndex =
1359 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1360
1361 /// Load the VTT.
1362 llvm::Value *VTT = LoadCXXVTT();
1363 if (VirtualPointerIndex)
1364 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1365
1366 // And load the address point from the VTT.
1367 VTableAddressPoint = Builder.CreateLoad(VTT);
1368 } else {
Anders Carlsson64c9eca2010-03-29 02:08:26 +00001369 uint64_t AddressPoint = CGM.getVTables().getAddressPoint(Base, VTableClass);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001370 VTableAddressPoint =
Anders Carlssond103f9f2010-03-28 19:40:00 +00001371 Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001372 }
Anders Carlssond103f9f2010-03-28 19:40:00 +00001373
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001374 // Compute where to store the address point.
Anders Carlsson8246cc72010-05-03 00:29:58 +00001375 llvm::Value *VirtualOffset = 0;
1376 uint64_t NonVirtualOffset = 0;
Anders Carlsson3e79c302010-04-20 18:05:10 +00001377
1378 if (CodeGenVTables::needsVTTParameter(CurGD) && NearestVBase) {
1379 // We need to use the virtual base offset offset because the virtual base
1380 // might have a different offset in the most derived class.
Anders Carlsson8246cc72010-05-03 00:29:58 +00001381 VirtualOffset = GetVirtualBaseClassOffset(LoadCXXThis(), VTableClass,
1382 NearestVBase);
1383 NonVirtualOffset = OffsetFromNearestVBase / 8;
Anders Carlsson3e79c302010-04-20 18:05:10 +00001384 } else {
Anders Carlsson8246cc72010-05-03 00:29:58 +00001385 // We can just use the base offset in the complete class.
1386 NonVirtualOffset = Base.getBaseOffset() / 8;
Anders Carlsson3e79c302010-04-20 18:05:10 +00001387 }
Anders Carlsson8246cc72010-05-03 00:29:58 +00001388
1389 // Apply the offsets.
1390 llvm::Value *VTableField = LoadCXXThis();
1391
1392 if (NonVirtualOffset || VirtualOffset)
1393 VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
1394 NonVirtualOffset,
1395 VirtualOffset);
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001396
Anders Carlssond103f9f2010-03-28 19:40:00 +00001397 // Finally, store the address point.
1398 const llvm::Type *AddressPointPtrTy =
1399 VTableAddressPoint->getType()->getPointerTo();
1400 VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
1401 Builder.CreateStore(VTableAddressPoint, VTableField);
1402}
1403
Anders Carlsson603d6d12010-03-28 21:07:49 +00001404void
1405CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001406 const CXXRecordDecl *NearestVBase,
Anders Carlsson42358402010-05-03 00:07:07 +00001407 uint64_t OffsetFromNearestVBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001408 bool BaseIsNonVirtualPrimaryBase,
1409 llvm::Constant *VTable,
1410 const CXXRecordDecl *VTableClass,
1411 VisitedVirtualBasesSetTy& VBases) {
1412 // If this base is a non-virtual primary base the address point has already
1413 // been set.
1414 if (!BaseIsNonVirtualPrimaryBase) {
1415 // Initialize the vtable pointer for this base.
Anders Carlsson42358402010-05-03 00:07:07 +00001416 InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
1417 VTable, VTableClass);
Anders Carlsson603d6d12010-03-28 21:07:49 +00001418 }
1419
1420 const CXXRecordDecl *RD = Base.getBase();
1421
1422 // Traverse bases.
1423 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1424 E = RD->bases_end(); I != E; ++I) {
1425 CXXRecordDecl *BaseDecl
1426 = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1427
1428 // Ignore classes without a vtable.
1429 if (!BaseDecl->isDynamicClass())
1430 continue;
1431
1432 uint64_t BaseOffset;
Anders Carlsson42358402010-05-03 00:07:07 +00001433 uint64_t BaseOffsetFromNearestVBase;
Anders Carlsson14da9de2010-03-29 01:16:41 +00001434 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001435
1436 if (I->isVirtual()) {
1437 // Check if we've visited this virtual base before.
1438 if (!VBases.insert(BaseDecl))
1439 continue;
1440
1441 const ASTRecordLayout &Layout =
1442 getContext().getASTRecordLayout(VTableClass);
1443
Anders Carlssona14f5972010-10-31 23:22:37 +00001444 BaseOffset = Layout.getVBaseClassOffsetInBits(BaseDecl);
Anders Carlsson42358402010-05-03 00:07:07 +00001445 BaseOffsetFromNearestVBase = 0;
Anders Carlsson14da9de2010-03-29 01:16:41 +00001446 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001447 } else {
1448 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1449
Anders Carlssona14f5972010-10-31 23:22:37 +00001450 BaseOffset =
1451 Base.getBaseOffset() + Layout.getBaseClassOffsetInBits(BaseDecl);
Anders Carlsson42358402010-05-03 00:07:07 +00001452 BaseOffsetFromNearestVBase =
Anders Carlssona14f5972010-10-31 23:22:37 +00001453 OffsetFromNearestVBase + Layout.getBaseClassOffsetInBits(BaseDecl);
Anders Carlsson14da9de2010-03-29 01:16:41 +00001454 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001455 }
1456
1457 InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001458 I->isVirtual() ? BaseDecl : NearestVBase,
Anders Carlsson42358402010-05-03 00:07:07 +00001459 BaseOffsetFromNearestVBase,
Anders Carlsson14da9de2010-03-29 01:16:41 +00001460 BaseDeclIsNonVirtualPrimaryBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001461 VTable, VTableClass, VBases);
1462 }
1463}
1464
1465void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
1466 // Ignore classes without a vtable.
Anders Carlsson07036902010-03-26 04:39:42 +00001467 if (!RD->isDynamicClass())
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001468 return;
1469
Anders Carlsson07036902010-03-26 04:39:42 +00001470 // Get the VTable.
1471 llvm::Constant *VTable = CGM.getVTables().GetAddrOfVTable(RD);
Anders Carlsson5c6c1d92010-03-24 03:57:14 +00001472
Anders Carlsson603d6d12010-03-28 21:07:49 +00001473 // Initialize the vtable pointers for this class and all of its bases.
1474 VisitedVirtualBasesSetTy VBases;
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001475 InitializeVTablePointers(BaseSubobject(RD, 0), /*NearestVBase=*/0,
Anders Carlsson42358402010-05-03 00:07:07 +00001476 /*OffsetFromNearestVBase=*/0,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001477 /*BaseIsNonVirtualPrimaryBase=*/false,
1478 VTable, RD, VBases);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001479}
Dan Gohman043fb9a2010-10-26 18:44:08 +00001480
1481llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
1482 const llvm::Type *Ty) {
1483 llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
1484 return Builder.CreateLoad(VTablePtrSrc, "vtable");
1485}