blob: 9ae9b3a80032339091dfc07d4ddfc137978a9021 [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
14#include "CodeGenFunction.h"
Anders Carlsson2f1986b2009-10-06 22:43:30 +000015#include "clang/AST/CXXInheritance.h"
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000016#include "clang/AST/RecordLayout.h"
John McCall9fc6a772010-02-19 09:25:03 +000017#include "clang/AST/StmtCXX.h"
Anders Carlsson2f1986b2009-10-06 22:43:30 +000018
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000019using namespace clang;
20using namespace CodeGen;
21
Anders Carlsson2f1986b2009-10-06 22:43:30 +000022static uint64_t
Anders Carlsson34a2d382010-04-24 21:06:20 +000023ComputeNonVirtualBaseClassOffset(ASTContext &Context,
24 const CXXRecordDecl *DerivedClass,
John McCallf871d0c2010-08-07 06:22:56 +000025 CastExpr::path_const_iterator Start,
26 CastExpr::path_const_iterator End) {
Anders Carlsson34a2d382010-04-24 21:06:20 +000027 uint64_t Offset = 0;
28
29 const CXXRecordDecl *RD = DerivedClass;
30
John McCallf871d0c2010-08-07 06:22:56 +000031 for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
Anders Carlsson34a2d382010-04-24 21:06:20 +000032 const CXXBaseSpecifier *Base = *I;
33 assert(!Base->isVirtual() && "Should not see virtual bases here!");
34
35 // Get the layout.
36 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
37
38 const CXXRecordDecl *BaseDecl =
39 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
40
41 // Add the offset.
42 Offset += Layout.getBaseClassOffset(BaseDecl);
43
44 RD = BaseDecl;
45 }
46
47 // FIXME: We should not use / 8 here.
48 return Offset / 8;
49}
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000050
Anders Carlsson84080ec2009-09-29 03:13:20 +000051llvm::Constant *
Anders Carlssona04efdf2010-04-24 21:23:59 +000052CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +000053 CastExpr::path_const_iterator PathBegin,
54 CastExpr::path_const_iterator PathEnd) {
55 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssona04efdf2010-04-24 21:23:59 +000056
57 uint64_t Offset =
John McCallf871d0c2010-08-07 06:22:56 +000058 ComputeNonVirtualBaseClassOffset(getContext(), ClassDecl,
59 PathBegin, PathEnd);
Anders Carlssona04efdf2010-04-24 21:23:59 +000060 if (!Offset)
61 return 0;
62
63 const llvm::Type *PtrDiffTy =
64 Types.ConvertType(getContext().getPointerDiffType());
65
66 return llvm::ConstantInt::get(PtrDiffTy, Offset);
Anders Carlsson84080ec2009-09-29 03:13:20 +000067}
68
Anders Carlsson8561a862010-04-24 23:01:49 +000069/// Gets the address of a direct base class within a complete object.
John McCallbff225e2010-02-16 04:15:37 +000070/// This should only be used for (1) non-virtual bases or (2) virtual bases
71/// when the type is known to be complete (e.g. in complete destructors).
72///
73/// The object pointed to by 'This' is assumed to be non-null.
74llvm::Value *
Anders Carlsson8561a862010-04-24 23:01:49 +000075CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(llvm::Value *This,
76 const CXXRecordDecl *Derived,
77 const CXXRecordDecl *Base,
78 bool BaseIsVirtual) {
John McCallbff225e2010-02-16 04:15:37 +000079 // 'this' must be a pointer (in some address space) to Derived.
80 assert(This->getType()->isPointerTy() &&
81 cast<llvm::PointerType>(This->getType())->getElementType()
82 == ConvertType(Derived));
83
84 // Compute the offset of the virtual base.
85 uint64_t Offset;
86 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
Anders Carlsson8561a862010-04-24 23:01:49 +000087 if (BaseIsVirtual)
John McCallbff225e2010-02-16 04:15:37 +000088 Offset = Layout.getVBaseClassOffset(Base);
89 else
90 Offset = Layout.getBaseClassOffset(Base);
91
92 // Shift and cast down to the base type.
93 // TODO: for complete types, this should be possible with a GEP.
94 llvm::Value *V = This;
95 if (Offset) {
96 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
97 V = Builder.CreateBitCast(V, Int8PtrTy);
98 V = Builder.CreateConstInBoundsGEP1_64(V, Offset / 8);
99 }
100 V = Builder.CreateBitCast(V, ConvertType(Base)->getPointerTo());
101
102 return V;
Anders Carlssond103f9f2010-03-28 19:40:00 +0000103}
John McCallbff225e2010-02-16 04:15:37 +0000104
Anders Carlsson9dc228a2010-04-20 16:03:35 +0000105static llvm::Value *
106ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, llvm::Value *ThisPtr,
107 uint64_t NonVirtual, llvm::Value *Virtual) {
108 const llvm::Type *PtrDiffTy =
109 CGF.ConvertType(CGF.getContext().getPointerDiffType());
110
111 llvm::Value *NonVirtualOffset = 0;
112 if (NonVirtual)
113 NonVirtualOffset = llvm::ConstantInt::get(PtrDiffTy, NonVirtual);
114
115 llvm::Value *BaseOffset;
116 if (Virtual) {
117 if (NonVirtualOffset)
118 BaseOffset = CGF.Builder.CreateAdd(Virtual, NonVirtualOffset);
119 else
120 BaseOffset = Virtual;
121 } else
122 BaseOffset = NonVirtualOffset;
123
124 // Apply the base offset.
125 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
126 ThisPtr = CGF.Builder.CreateBitCast(ThisPtr, Int8PtrTy);
127 ThisPtr = CGF.Builder.CreateGEP(ThisPtr, BaseOffset, "add.ptr");
128
129 return ThisPtr;
130}
131
Anders Carlsson5d58a1d2009-09-12 04:27:24 +0000132llvm::Value *
Anders Carlsson34a2d382010-04-24 21:06:20 +0000133CodeGenFunction::GetAddressOfBaseClass(llvm::Value *Value,
Anders Carlsson8561a862010-04-24 23:01:49 +0000134 const CXXRecordDecl *Derived,
John McCallf871d0c2010-08-07 06:22:56 +0000135 CastExpr::path_const_iterator PathBegin,
136 CastExpr::path_const_iterator PathEnd,
Anders Carlsson34a2d382010-04-24 21:06:20 +0000137 bool NullCheckValue) {
John McCallf871d0c2010-08-07 06:22:56 +0000138 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlsson34a2d382010-04-24 21:06:20 +0000139
John McCallf871d0c2010-08-07 06:22:56 +0000140 CastExpr::path_const_iterator Start = PathBegin;
Anders Carlsson34a2d382010-04-24 21:06:20 +0000141 const CXXRecordDecl *VBase = 0;
142
143 // Get the virtual base.
144 if ((*Start)->isVirtual()) {
145 VBase =
146 cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
147 ++Start;
148 }
149
150 uint64_t NonVirtualOffset =
Anders Carlsson8561a862010-04-24 23:01:49 +0000151 ComputeNonVirtualBaseClassOffset(getContext(), VBase ? VBase : Derived,
John McCallf871d0c2010-08-07 06:22:56 +0000152 Start, PathEnd);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000153
154 // Get the base pointer type.
155 const llvm::Type *BasePtrTy =
John McCallf871d0c2010-08-07 06:22:56 +0000156 ConvertType((PathEnd[-1])->getType())->getPointerTo();
Anders Carlsson34a2d382010-04-24 21:06:20 +0000157
158 if (!NonVirtualOffset && !VBase) {
159 // Just cast back.
160 return Builder.CreateBitCast(Value, BasePtrTy);
161 }
162
163 llvm::BasicBlock *CastNull = 0;
164 llvm::BasicBlock *CastNotNull = 0;
165 llvm::BasicBlock *CastEnd = 0;
166
167 if (NullCheckValue) {
168 CastNull = createBasicBlock("cast.null");
169 CastNotNull = createBasicBlock("cast.notnull");
170 CastEnd = createBasicBlock("cast.end");
171
172 llvm::Value *IsNull =
173 Builder.CreateICmpEQ(Value,
174 llvm::Constant::getNullValue(Value->getType()));
175 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
176 EmitBlock(CastNotNull);
177 }
178
179 llvm::Value *VirtualOffset = 0;
180
181 if (VBase)
Anders Carlsson8561a862010-04-24 23:01:49 +0000182 VirtualOffset = GetVirtualBaseClassOffset(Value, Derived, VBase);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000183
184 // Apply the offsets.
185 Value = ApplyNonVirtualAndVirtualOffset(*this, Value, NonVirtualOffset,
186 VirtualOffset);
187
188 // Cast back.
189 Value = Builder.CreateBitCast(Value, BasePtrTy);
190
191 if (NullCheckValue) {
192 Builder.CreateBr(CastEnd);
193 EmitBlock(CastNull);
194 Builder.CreateBr(CastEnd);
195 EmitBlock(CastEnd);
196
197 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType());
198 PHI->reserveOperandSpace(2);
199 PHI->addIncoming(Value, CastNotNull);
200 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
201 CastNull);
202 Value = PHI;
203 }
204
205 return Value;
206}
207
208llvm::Value *
Anders Carlssona3697c92009-11-23 17:57:54 +0000209CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value,
Anders Carlsson8561a862010-04-24 23:01:49 +0000210 const CXXRecordDecl *Derived,
John McCallf871d0c2010-08-07 06:22:56 +0000211 CastExpr::path_const_iterator PathBegin,
212 CastExpr::path_const_iterator PathEnd,
Anders Carlssona3697c92009-11-23 17:57:54 +0000213 bool NullCheckValue) {
John McCallf871d0c2010-08-07 06:22:56 +0000214 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssona04efdf2010-04-24 21:23:59 +0000215
Anders Carlssona3697c92009-11-23 17:57:54 +0000216 QualType DerivedTy =
Anders Carlsson8561a862010-04-24 23:01:49 +0000217 getContext().getCanonicalType(getContext().getTagDeclType(Derived));
Anders Carlssona3697c92009-11-23 17:57:54 +0000218 const llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
219
Anders Carlssona552ea72010-01-31 01:43:37 +0000220 llvm::Value *NonVirtualOffset =
John McCallf871d0c2010-08-07 06:22:56 +0000221 CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
Anders Carlssona552ea72010-01-31 01:43:37 +0000222
223 if (!NonVirtualOffset) {
224 // No offset, we can just cast back.
225 return Builder.CreateBitCast(Value, DerivedPtrTy);
226 }
227
Anders Carlssona3697c92009-11-23 17:57:54 +0000228 llvm::BasicBlock *CastNull = 0;
229 llvm::BasicBlock *CastNotNull = 0;
230 llvm::BasicBlock *CastEnd = 0;
231
232 if (NullCheckValue) {
233 CastNull = createBasicBlock("cast.null");
234 CastNotNull = createBasicBlock("cast.notnull");
235 CastEnd = createBasicBlock("cast.end");
236
237 llvm::Value *IsNull =
238 Builder.CreateICmpEQ(Value,
239 llvm::Constant::getNullValue(Value->getType()));
240 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
241 EmitBlock(CastNotNull);
242 }
243
Anders Carlssona552ea72010-01-31 01:43:37 +0000244 // Apply the offset.
245 Value = Builder.CreatePtrToInt(Value, NonVirtualOffset->getType());
246 Value = Builder.CreateSub(Value, NonVirtualOffset);
247 Value = Builder.CreateIntToPtr(Value, DerivedPtrTy);
248
249 // Just cast.
250 Value = Builder.CreateBitCast(Value, DerivedPtrTy);
Anders Carlssona3697c92009-11-23 17:57:54 +0000251
252 if (NullCheckValue) {
253 Builder.CreateBr(CastEnd);
254 EmitBlock(CastNull);
255 Builder.CreateBr(CastEnd);
256 EmitBlock(CastEnd);
257
258 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType());
259 PHI->reserveOperandSpace(2);
260 PHI->addIncoming(Value, CastNotNull);
261 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
262 CastNull);
263 Value = PHI;
264 }
265
266 return Value;
Anders Carlsson5d58a1d2009-09-12 04:27:24 +0000267}
Anders Carlsson21c9ad92010-03-30 03:27:09 +0000268
Anders Carlssonc997d422010-01-02 01:01:18 +0000269/// GetVTTParameter - Return the VTT parameter that should be passed to a
270/// base constructor/destructor with virtual bases.
Anders Carlsson314e6222010-05-02 23:33:10 +0000271static llvm::Value *GetVTTParameter(CodeGenFunction &CGF, GlobalDecl GD,
272 bool ForVirtualBase) {
Anders Carlssonaf440352010-03-23 04:11:45 +0000273 if (!CodeGenVTables::needsVTTParameter(GD)) {
Anders Carlssonc997d422010-01-02 01:01:18 +0000274 // This constructor/destructor does not need a VTT parameter.
275 return 0;
276 }
277
278 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CGF.CurFuncDecl)->getParent();
279 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
John McCall3b477332010-02-18 19:59:28 +0000280
Anders Carlssonc997d422010-01-02 01:01:18 +0000281 llvm::Value *VTT;
282
John McCall3b477332010-02-18 19:59:28 +0000283 uint64_t SubVTTIndex;
284
285 // If the record matches the base, this is the complete ctor/dtor
286 // variant calling the base variant in a class with virtual bases.
287 if (RD == Base) {
Anders Carlssonaf440352010-03-23 04:11:45 +0000288 assert(!CodeGenVTables::needsVTTParameter(CGF.CurGD) &&
John McCall3b477332010-02-18 19:59:28 +0000289 "doing no-op VTT offset in base dtor/ctor?");
Anders Carlsson314e6222010-05-02 23:33:10 +0000290 assert(!ForVirtualBase && "Can't have same class as virtual base!");
John McCall3b477332010-02-18 19:59:28 +0000291 SubVTTIndex = 0;
292 } else {
Anders Carlssonc11bb212010-05-02 23:53:25 +0000293 const ASTRecordLayout &Layout =
294 CGF.getContext().getASTRecordLayout(RD);
295 uint64_t BaseOffset = ForVirtualBase ?
296 Layout.getVBaseClassOffset(Base) : Layout.getBaseClassOffset(Base);
297
298 SubVTTIndex =
299 CGF.CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
John McCall3b477332010-02-18 19:59:28 +0000300 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
301 }
Anders Carlssonc997d422010-01-02 01:01:18 +0000302
Anders Carlssonaf440352010-03-23 04:11:45 +0000303 if (CodeGenVTables::needsVTTParameter(CGF.CurGD)) {
Anders Carlssonc997d422010-01-02 01:01:18 +0000304 // A VTT parameter was passed to the constructor, use it.
305 VTT = CGF.LoadCXXVTT();
306 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
307 } else {
308 // We're the complete constructor, so get the VTT by name.
Anders Carlssonaf440352010-03-23 04:11:45 +0000309 VTT = CGF.CGM.getVTables().getVTT(RD);
Anders Carlssonc997d422010-01-02 01:01:18 +0000310 VTT = CGF.Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
311 }
312
313 return VTT;
314}
315
John McCall182ab512010-07-21 01:23:41 +0000316namespace {
John McCall50da2ca2010-07-21 05:30:47 +0000317 /// Call the destructor for a direct base class.
John McCall1f0fca52010-07-21 07:22:38 +0000318 struct CallBaseDtor : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000319 const CXXRecordDecl *BaseClass;
320 bool BaseIsVirtual;
321 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
322 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
John McCall182ab512010-07-21 01:23:41 +0000323
324 void Emit(CodeGenFunction &CGF, bool IsForEH) {
John McCall50da2ca2010-07-21 05:30:47 +0000325 const CXXRecordDecl *DerivedClass =
326 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
327
328 const CXXDestructorDecl *D = BaseClass->getDestructor();
329 llvm::Value *Addr =
330 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThis(),
331 DerivedClass, BaseClass,
332 BaseIsVirtual);
333 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual, Addr);
John McCall182ab512010-07-21 01:23:41 +0000334 }
335 };
336}
337
Anders Carlsson607d0372009-12-24 22:46:43 +0000338static void EmitBaseInitializer(CodeGenFunction &CGF,
339 const CXXRecordDecl *ClassDecl,
340 CXXBaseOrMemberInitializer *BaseInit,
341 CXXCtorType CtorType) {
342 assert(BaseInit->isBaseInitializer() &&
343 "Must have base initializer!");
344
345 llvm::Value *ThisPtr = CGF.LoadCXXThis();
346
347 const Type *BaseType = BaseInit->getBaseClass();
348 CXXRecordDecl *BaseClassDecl =
349 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
350
Anders Carlsson80638c52010-04-12 00:51:03 +0000351 bool isBaseVirtual = BaseInit->isBaseVirtual();
Anders Carlsson607d0372009-12-24 22:46:43 +0000352
353 // The base constructor doesn't construct virtual bases.
354 if (CtorType == Ctor_Base && isBaseVirtual)
355 return;
356
John McCallbff225e2010-02-16 04:15:37 +0000357 // We can pretend to be a complete class because it only matters for
358 // virtual bases, and we only do virtual bases for complete ctors.
Anders Carlsson8561a862010-04-24 23:01:49 +0000359 llvm::Value *V =
360 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
John McCall50da2ca2010-07-21 05:30:47 +0000361 BaseClassDecl,
362 isBaseVirtual);
John McCallbff225e2010-02-16 04:15:37 +0000363
Douglas Gregor9db7dbb2010-01-31 09:12:51 +0000364 CGF.EmitAggExpr(BaseInit->getInit(), V, false, false, true);
Anders Carlsson594d5e82010-02-06 20:00:21 +0000365
John McCall182ab512010-07-21 01:23:41 +0000366 if (CGF.Exceptions && !BaseClassDecl->hasTrivialDestructor())
John McCall1f0fca52010-07-21 07:22:38 +0000367 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
368 isBaseVirtual);
Anders Carlsson607d0372009-12-24 22:46:43 +0000369}
370
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000371static void EmitAggMemberInitializer(CodeGenFunction &CGF,
372 LValue LHS,
373 llvm::Value *ArrayIndexVar,
374 CXXBaseOrMemberInitializer *MemberInit,
375 QualType T,
376 unsigned Index) {
377 if (Index == MemberInit->getNumArrayIndices()) {
John McCallf1549f62010-07-06 01:34:17 +0000378 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000379
380 llvm::Value *Dest = LHS.getAddress();
381 if (ArrayIndexVar) {
382 // If we have an array index variable, load it and use it as an offset.
383 // Then, increment the value.
384 llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar);
385 Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress");
386 llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1);
387 Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc");
388 CGF.Builder.CreateStore(Next, ArrayIndexVar);
389 }
390
391 CGF.EmitAggExpr(MemberInit->getInit(), Dest,
392 LHS.isVolatileQualified(),
393 /*IgnoreResult*/ false,
394 /*IsInitializer*/ true);
395
396 return;
397 }
398
399 const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T);
400 assert(Array && "Array initialization without the array type?");
401 llvm::Value *IndexVar
402 = CGF.GetAddrOfLocalVar(MemberInit->getArrayIndex(Index));
403 assert(IndexVar && "Array index variable not loaded");
404
405 // Initialize this index variable to zero.
406 llvm::Value* Zero
407 = llvm::Constant::getNullValue(
408 CGF.ConvertType(CGF.getContext().getSizeType()));
409 CGF.Builder.CreateStore(Zero, IndexVar);
410
411 // Start the loop with a block that tests the condition.
412 llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond");
413 llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end");
414
415 CGF.EmitBlock(CondBlock);
416
417 llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body");
418 // Generate: if (loop-index < number-of-elements) fall to the loop body,
419 // otherwise, go to the block after the for-loop.
420 uint64_t NumElements = Array->getSize().getZExtValue();
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000421 llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
Chris Lattner985f7392010-05-06 06:35:23 +0000422 llvm::Value *NumElementsPtr =
423 llvm::ConstantInt::get(Counter->getType(), NumElements);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000424 llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr,
425 "isless");
426
427 // If the condition is true, execute the body.
428 CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor);
429
430 CGF.EmitBlock(ForBody);
431 llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc");
432
433 {
John McCallf1549f62010-07-06 01:34:17 +0000434 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000435
436 // Inside the loop body recurse to emit the inner loop or, eventually, the
437 // constructor call.
438 EmitAggMemberInitializer(CGF, LHS, ArrayIndexVar, MemberInit,
439 Array->getElementType(), Index + 1);
440 }
441
442 CGF.EmitBlock(ContinueBlock);
443
444 // Emit the increment of the loop counter.
445 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
446 Counter = CGF.Builder.CreateLoad(IndexVar);
447 NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc");
448 CGF.Builder.CreateStore(NextVal, IndexVar);
449
450 // Finally, branch back up to the condition for the next iteration.
451 CGF.EmitBranch(CondBlock);
452
453 // Emit the fall-through block.
454 CGF.EmitBlock(AfterFor, true);
455}
John McCall182ab512010-07-21 01:23:41 +0000456
457namespace {
John McCall1f0fca52010-07-21 07:22:38 +0000458 struct CallMemberDtor : EHScopeStack::Cleanup {
John McCall182ab512010-07-21 01:23:41 +0000459 FieldDecl *Field;
460 CXXDestructorDecl *Dtor;
461
462 CallMemberDtor(FieldDecl *Field, CXXDestructorDecl *Dtor)
463 : Field(Field), Dtor(Dtor) {}
464
465 void Emit(CodeGenFunction &CGF, bool IsForEH) {
466 // FIXME: Is this OK for C++0x delegating constructors?
467 llvm::Value *ThisPtr = CGF.LoadCXXThis();
468 LValue LHS = CGF.EmitLValueForField(ThisPtr, Field, 0);
469
470 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
471 LHS.getAddress());
472 }
473 };
474}
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000475
Anders Carlsson607d0372009-12-24 22:46:43 +0000476static void EmitMemberInitializer(CodeGenFunction &CGF,
477 const CXXRecordDecl *ClassDecl,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000478 CXXBaseOrMemberInitializer *MemberInit,
479 const CXXConstructorDecl *Constructor,
480 FunctionArgList &Args) {
Anders Carlsson607d0372009-12-24 22:46:43 +0000481 assert(MemberInit->isMemberInitializer() &&
482 "Must have member initializer!");
483
484 // non-static data member initializers.
485 FieldDecl *Field = MemberInit->getMember();
486 QualType FieldType = CGF.getContext().getCanonicalType(Field->getType());
487
488 llvm::Value *ThisPtr = CGF.LoadCXXThis();
John McCalla9976d32010-05-21 01:18:57 +0000489 LValue LHS;
Anders Carlsson06a29702010-01-29 05:24:29 +0000490
Anders Carlsson607d0372009-12-24 22:46:43 +0000491 // If we are initializing an anonymous union field, drill down to the field.
492 if (MemberInit->getAnonUnionMember()) {
493 Field = MemberInit->getAnonUnionMember();
John McCalla9976d32010-05-21 01:18:57 +0000494 LHS = CGF.EmitLValueForAnonRecordField(ThisPtr, Field, 0);
Anders Carlsson607d0372009-12-24 22:46:43 +0000495 FieldType = Field->getType();
John McCalla9976d32010-05-21 01:18:57 +0000496 } else {
497 LHS = CGF.EmitLValueForFieldInitialization(ThisPtr, Field, 0);
Anders Carlsson607d0372009-12-24 22:46:43 +0000498 }
499
Douglas Gregor9db7dbb2010-01-31 09:12:51 +0000500 // FIXME: If there's no initializer and the CXXBaseOrMemberInitializer
501 // was implicitly generated, we shouldn't be zeroing memory.
Anders Carlsson607d0372009-12-24 22:46:43 +0000502 RValue RHS;
503 if (FieldType->isReferenceType()) {
Anders Carlsson32f36ba2010-06-26 16:35:32 +0000504 RHS = CGF.EmitReferenceBindingToExpr(MemberInit->getInit(), Field);
Anders Carlsson607d0372009-12-24 22:46:43 +0000505 CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
Eli Friedman3bb94122010-01-31 19:07:50 +0000506 } else if (FieldType->isArrayType() && !MemberInit->getInit()) {
Anders Carlsson1884eb02010-05-22 17:35:42 +0000507 CGF.EmitNullInitialization(LHS.getAddress(), Field->getType());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +0000508 } else if (!CGF.hasAggregateLLVMType(Field->getType())) {
Eli Friedman0b292272010-06-03 19:58:07 +0000509 RHS = RValue::get(CGF.EmitScalarExpr(MemberInit->getInit()));
Anders Carlsson607d0372009-12-24 22:46:43 +0000510 CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +0000511 } else if (MemberInit->getInit()->getType()->isAnyComplexType()) {
512 CGF.EmitComplexExprIntoAddr(MemberInit->getInit(), LHS.getAddress(),
Anders Carlsson607d0372009-12-24 22:46:43 +0000513 LHS.isVolatileQualified());
514 } else {
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000515 llvm::Value *ArrayIndexVar = 0;
516 const ConstantArrayType *Array
517 = CGF.getContext().getAsConstantArrayType(FieldType);
518 if (Array && Constructor->isImplicit() &&
519 Constructor->isCopyConstructor()) {
520 const llvm::Type *SizeTy
521 = CGF.ConvertType(CGF.getContext().getSizeType());
522
523 // The LHS is a pointer to the first object we'll be constructing, as
524 // a flat array.
525 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
526 const llvm::Type *BasePtr = CGF.ConvertType(BaseElementTy);
527 BasePtr = llvm::PointerType::getUnqual(BasePtr);
528 llvm::Value *BaseAddrPtr = CGF.Builder.CreateBitCast(LHS.getAddress(),
529 BasePtr);
530 LHS = LValue::MakeAddr(BaseAddrPtr, CGF.MakeQualifiers(BaseElementTy));
531
532 // Create an array index that will be used to walk over all of the
533 // objects we're constructing.
534 ArrayIndexVar = CGF.CreateTempAlloca(SizeTy, "object.index");
535 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
536 CGF.Builder.CreateStore(Zero, ArrayIndexVar);
537
538 // If we are copying an array of scalars or classes with trivial copy
539 // constructors, perform a single aggregate copy.
540 const RecordType *Record = BaseElementTy->getAs<RecordType>();
541 if (!Record ||
542 cast<CXXRecordDecl>(Record->getDecl())->hasTrivialCopyConstructor()) {
543 // Find the source pointer. We knows it's the last argument because
544 // we know we're in a copy constructor.
545 unsigned SrcArgIndex = Args.size() - 1;
546 llvm::Value *SrcPtr
547 = CGF.Builder.CreateLoad(
548 CGF.GetAddrOfLocalVar(Args[SrcArgIndex].first));
549 LValue Src = CGF.EmitLValueForFieldInitialization(SrcPtr, Field, 0);
550
551 // Copy the aggregate.
552 CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
553 LHS.isVolatileQualified());
554 return;
555 }
556
557 // Emit the block variables for the array indices, if any.
558 for (unsigned I = 0, N = MemberInit->getNumArrayIndices(); I != N; ++I)
559 CGF.EmitLocalBlockVarDecl(*MemberInit->getArrayIndex(I));
560 }
561
562 EmitAggMemberInitializer(CGF, LHS, ArrayIndexVar, MemberInit, FieldType, 0);
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000563
564 if (!CGF.Exceptions)
565 return;
566
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000567 // FIXME: If we have an array of classes w/ non-trivial destructors,
568 // we need to destroy in reverse order of construction along the exception
569 // path.
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000570 const RecordType *RT = FieldType->getAs<RecordType>();
571 if (!RT)
572 return;
573
574 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall182ab512010-07-21 01:23:41 +0000575 if (!RD->hasTrivialDestructor())
John McCall1f0fca52010-07-21 07:22:38 +0000576 CGF.EHStack.pushCleanup<CallMemberDtor>(EHCleanup, Field,
577 RD->getDestructor());
Anders Carlsson607d0372009-12-24 22:46:43 +0000578 }
579}
580
John McCallc0bf4622010-02-23 00:48:20 +0000581/// Checks whether the given constructor is a valid subject for the
582/// complete-to-base constructor delegation optimization, i.e.
583/// emitting the complete constructor as a simple call to the base
584/// constructor.
585static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
586
587 // Currently we disable the optimization for classes with virtual
588 // bases because (1) the addresses of parameter variables need to be
589 // consistent across all initializers but (2) the delegate function
590 // call necessarily creates a second copy of the parameter variable.
591 //
592 // The limiting example (purely theoretical AFAIK):
593 // struct A { A(int &c) { c++; } };
594 // struct B : virtual A {
595 // B(int count) : A(count) { printf("%d\n", count); }
596 // };
597 // ...although even this example could in principle be emitted as a
598 // delegation since the address of the parameter doesn't escape.
599 if (Ctor->getParent()->getNumVBases()) {
600 // TODO: white-list trivial vbase initializers. This case wouldn't
601 // be subject to the restrictions below.
602
603 // TODO: white-list cases where:
604 // - there are no non-reference parameters to the constructor
605 // - the initializers don't access any non-reference parameters
606 // - the initializers don't take the address of non-reference
607 // parameters
608 // - etc.
609 // If we ever add any of the above cases, remember that:
610 // - function-try-blocks will always blacklist this optimization
611 // - we need to perform the constructor prologue and cleanup in
612 // EmitConstructorBody.
613
614 return false;
615 }
616
617 // We also disable the optimization for variadic functions because
618 // it's impossible to "re-pass" varargs.
619 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
620 return false;
621
622 return true;
623}
624
John McCall9fc6a772010-02-19 09:25:03 +0000625/// EmitConstructorBody - Emits the body of the current constructor.
626void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
627 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
628 CXXCtorType CtorType = CurGD.getCtorType();
629
John McCallc0bf4622010-02-23 00:48:20 +0000630 // Before we go any further, try the complete->base constructor
631 // delegation optimization.
632 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor)) {
633 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args);
634 return;
635 }
636
John McCall9fc6a772010-02-19 09:25:03 +0000637 Stmt *Body = Ctor->getBody();
638
John McCallc0bf4622010-02-23 00:48:20 +0000639 // Enter the function-try-block before the constructor prologue if
640 // applicable.
John McCallc0bf4622010-02-23 00:48:20 +0000641 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallc0bf4622010-02-23 00:48:20 +0000642 if (IsTryBody)
John McCall59a70002010-07-07 06:56:46 +0000643 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000644
John McCallf1549f62010-07-06 01:34:17 +0000645 EHScopeStack::stable_iterator CleanupDepth = EHStack.stable_begin();
John McCall9fc6a772010-02-19 09:25:03 +0000646
John McCallc0bf4622010-02-23 00:48:20 +0000647 // Emit the constructor prologue, i.e. the base and member
648 // initializers.
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000649 EmitCtorPrologue(Ctor, CtorType, Args);
John McCall9fc6a772010-02-19 09:25:03 +0000650
651 // Emit the body of the statement.
John McCallc0bf4622010-02-23 00:48:20 +0000652 if (IsTryBody)
John McCall9fc6a772010-02-19 09:25:03 +0000653 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
654 else if (Body)
655 EmitStmt(Body);
John McCall9fc6a772010-02-19 09:25:03 +0000656
657 // Emit any cleanup blocks associated with the member or base
658 // initializers, which includes (along the exceptional path) the
659 // destructors for those members and bases that were fully
660 // constructed.
John McCallf1549f62010-07-06 01:34:17 +0000661 PopCleanupBlocks(CleanupDepth);
John McCall9fc6a772010-02-19 09:25:03 +0000662
John McCallc0bf4622010-02-23 00:48:20 +0000663 if (IsTryBody)
John McCall59a70002010-07-07 06:56:46 +0000664 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000665}
666
Anders Carlsson607d0372009-12-24 22:46:43 +0000667/// EmitCtorPrologue - This routine generates necessary code to initialize
668/// base classes and non-static data members belonging to this constructor.
Anders Carlsson607d0372009-12-24 22:46:43 +0000669void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000670 CXXCtorType CtorType,
671 FunctionArgList &Args) {
Anders Carlsson607d0372009-12-24 22:46:43 +0000672 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000673
674 llvm::SmallVector<CXXBaseOrMemberInitializer *, 8> MemberInitializers;
Anders Carlsson607d0372009-12-24 22:46:43 +0000675
Anders Carlsson607d0372009-12-24 22:46:43 +0000676 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
677 E = CD->init_end();
678 B != E; ++B) {
679 CXXBaseOrMemberInitializer *Member = (*B);
680
Anders Carlsson607d0372009-12-24 22:46:43 +0000681 if (Member->isBaseInitializer())
682 EmitBaseInitializer(*this, ClassDecl, Member, CtorType);
683 else
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000684 MemberInitializers.push_back(Member);
Anders Carlsson607d0372009-12-24 22:46:43 +0000685 }
686
Anders Carlsson603d6d12010-03-28 21:07:49 +0000687 InitializeVTablePointers(ClassDecl);
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000688
John McCallf1549f62010-07-06 01:34:17 +0000689 for (unsigned I = 0, E = MemberInitializers.size(); I != E; ++I)
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000690 EmitMemberInitializer(*this, ClassDecl, MemberInitializers[I], CD, Args);
Anders Carlsson607d0372009-12-24 22:46:43 +0000691}
692
John McCall9fc6a772010-02-19 09:25:03 +0000693/// EmitDestructorBody - Emits the body of the current destructor.
694void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
695 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
696 CXXDtorType DtorType = CurGD.getDtorType();
697
John McCall50da2ca2010-07-21 05:30:47 +0000698 // The call to operator delete in a deleting destructor happens
699 // outside of the function-try-block, which means it's always
700 // possible to delegate the destructor body to the complete
701 // destructor. Do so.
702 if (DtorType == Dtor_Deleting) {
703 EnterDtorCleanups(Dtor, Dtor_Deleting);
704 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
705 LoadCXXThis());
706 PopCleanupBlock();
707 return;
708 }
709
John McCall9fc6a772010-02-19 09:25:03 +0000710 Stmt *Body = Dtor->getBody();
711
712 // If the body is a function-try-block, enter the try before
John McCall50da2ca2010-07-21 05:30:47 +0000713 // anything else.
714 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCall9fc6a772010-02-19 09:25:03 +0000715 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +0000716 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000717
John McCall50da2ca2010-07-21 05:30:47 +0000718 // Enter the epilogue cleanups.
719 RunCleanupsScope DtorEpilogue(*this);
720
John McCall9fc6a772010-02-19 09:25:03 +0000721 // If this is the complete variant, just invoke the base variant;
722 // the epilogue will destruct the virtual bases. But we can't do
723 // this optimization if the body is a function-try-block, because
724 // we'd introduce *two* handler blocks.
John McCall50da2ca2010-07-21 05:30:47 +0000725 switch (DtorType) {
726 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
727
728 case Dtor_Complete:
729 // Enter the cleanup scopes for virtual bases.
730 EnterDtorCleanups(Dtor, Dtor_Complete);
731
732 if (!isTryBody) {
733 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
734 LoadCXXThis());
735 break;
736 }
737 // Fallthrough: act like we're in the base variant.
John McCall9fc6a772010-02-19 09:25:03 +0000738
John McCall50da2ca2010-07-21 05:30:47 +0000739 case Dtor_Base:
740 // Enter the cleanup scopes for fields and non-virtual bases.
741 EnterDtorCleanups(Dtor, Dtor_Base);
742
743 // Initialize the vtable pointers before entering the body.
Anders Carlsson603d6d12010-03-28 21:07:49 +0000744 InitializeVTablePointers(Dtor->getParent());
John McCall50da2ca2010-07-21 05:30:47 +0000745
746 if (isTryBody)
747 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
748 else if (Body)
749 EmitStmt(Body);
750 else {
751 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
752 // nothing to do besides what's in the epilogue
753 }
754 break;
John McCall9fc6a772010-02-19 09:25:03 +0000755 }
756
John McCall50da2ca2010-07-21 05:30:47 +0000757 // Jump out through the epilogue cleanups.
758 DtorEpilogue.ForceCleanup();
John McCall9fc6a772010-02-19 09:25:03 +0000759
760 // Exit the try if applicable.
761 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +0000762 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000763}
764
John McCall50da2ca2010-07-21 05:30:47 +0000765namespace {
766 /// Call the operator delete associated with the current destructor.
John McCall1f0fca52010-07-21 07:22:38 +0000767 struct CallDtorDelete : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000768 CallDtorDelete() {}
769
770 void Emit(CodeGenFunction &CGF, bool IsForEH) {
771 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
772 const CXXRecordDecl *ClassDecl = Dtor->getParent();
773 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
774 CGF.getContext().getTagDeclType(ClassDecl));
775 }
776 };
777
John McCall1f0fca52010-07-21 07:22:38 +0000778 struct CallArrayFieldDtor : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000779 const FieldDecl *Field;
780 CallArrayFieldDtor(const FieldDecl *Field) : Field(Field) {}
781
782 void Emit(CodeGenFunction &CGF, bool IsForEH) {
783 QualType FieldType = Field->getType();
784 const ConstantArrayType *Array =
785 CGF.getContext().getAsConstantArrayType(FieldType);
786
787 QualType BaseType =
788 CGF.getContext().getBaseElementType(Array->getElementType());
789 const CXXRecordDecl *FieldClassDecl = BaseType->getAsCXXRecordDecl();
790
791 llvm::Value *ThisPtr = CGF.LoadCXXThis();
792 LValue LHS = CGF.EmitLValueForField(ThisPtr, Field,
793 // FIXME: Qualifiers?
794 /*CVRQualifiers=*/0);
795
796 const llvm::Type *BasePtr = CGF.ConvertType(BaseType)->getPointerTo();
797 llvm::Value *BaseAddrPtr =
798 CGF.Builder.CreateBitCast(LHS.getAddress(), BasePtr);
799 CGF.EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(),
800 Array, BaseAddrPtr);
801 }
802 };
803
John McCall1f0fca52010-07-21 07:22:38 +0000804 struct CallFieldDtor : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000805 const FieldDecl *Field;
806 CallFieldDtor(const FieldDecl *Field) : Field(Field) {}
807
808 void Emit(CodeGenFunction &CGF, bool IsForEH) {
809 const CXXRecordDecl *FieldClassDecl =
810 Field->getType()->getAsCXXRecordDecl();
811
812 llvm::Value *ThisPtr = CGF.LoadCXXThis();
813 LValue LHS = CGF.EmitLValueForField(ThisPtr, Field,
814 // FIXME: Qualifiers?
815 /*CVRQualifiers=*/0);
816
817 CGF.EmitCXXDestructorCall(FieldClassDecl->getDestructor(),
818 Dtor_Complete, /*ForVirtualBase=*/false,
819 LHS.getAddress());
820 }
821 };
822}
823
Anders Carlsson607d0372009-12-24 22:46:43 +0000824/// EmitDtorEpilogue - Emit all code that comes at the end of class's
825/// destructor. This is to call destructors on members and base classes
826/// in reverse order of their construction.
John McCall50da2ca2010-07-21 05:30:47 +0000827void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
828 CXXDtorType DtorType) {
Anders Carlsson607d0372009-12-24 22:46:43 +0000829 assert(!DD->isTrivial() &&
830 "Should not emit dtor epilogue for trivial dtor!");
831
John McCall50da2ca2010-07-21 05:30:47 +0000832 // The deleting-destructor phase just needs to call the appropriate
833 // operator delete that Sema picked up.
John McCall3b477332010-02-18 19:59:28 +0000834 if (DtorType == Dtor_Deleting) {
835 assert(DD->getOperatorDelete() &&
836 "operator delete missing - EmitDtorEpilogue");
John McCall1f0fca52010-07-21 07:22:38 +0000837 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
John McCall3b477332010-02-18 19:59:28 +0000838 return;
839 }
840
John McCall50da2ca2010-07-21 05:30:47 +0000841 const CXXRecordDecl *ClassDecl = DD->getParent();
842
843 // The complete-destructor phase just destructs all the virtual bases.
John McCall3b477332010-02-18 19:59:28 +0000844 if (DtorType == Dtor_Complete) {
John McCall50da2ca2010-07-21 05:30:47 +0000845
846 // We push them in the forward order so that they'll be popped in
847 // the reverse order.
848 for (CXXRecordDecl::base_class_const_iterator I =
849 ClassDecl->vbases_begin(), E = ClassDecl->vbases_end();
John McCall3b477332010-02-18 19:59:28 +0000850 I != E; ++I) {
851 const CXXBaseSpecifier &Base = *I;
852 CXXRecordDecl *BaseClassDecl
853 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
854
855 // Ignore trivial destructors.
856 if (BaseClassDecl->hasTrivialDestructor())
857 continue;
John McCall50da2ca2010-07-21 05:30:47 +0000858
John McCall1f0fca52010-07-21 07:22:38 +0000859 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
860 BaseClassDecl,
861 /*BaseIsVirtual*/ true);
John McCall3b477332010-02-18 19:59:28 +0000862 }
John McCall50da2ca2010-07-21 05:30:47 +0000863
John McCall3b477332010-02-18 19:59:28 +0000864 return;
865 }
866
867 assert(DtorType == Dtor_Base);
John McCall50da2ca2010-07-21 05:30:47 +0000868
869 // Destroy non-virtual bases.
870 for (CXXRecordDecl::base_class_const_iterator I =
871 ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) {
872 const CXXBaseSpecifier &Base = *I;
873
874 // Ignore virtual bases.
875 if (Base.isVirtual())
876 continue;
877
878 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
879
880 // Ignore trivial destructors.
881 if (BaseClassDecl->hasTrivialDestructor())
882 continue;
John McCall3b477332010-02-18 19:59:28 +0000883
John McCall1f0fca52010-07-21 07:22:38 +0000884 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
885 BaseClassDecl,
886 /*BaseIsVirtual*/ false);
John McCall50da2ca2010-07-21 05:30:47 +0000887 }
888
889 // Destroy direct fields.
Anders Carlsson607d0372009-12-24 22:46:43 +0000890 llvm::SmallVector<const FieldDecl *, 16> FieldDecls;
891 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
892 E = ClassDecl->field_end(); I != E; ++I) {
893 const FieldDecl *Field = *I;
894
895 QualType FieldType = getContext().getCanonicalType(Field->getType());
John McCall50da2ca2010-07-21 05:30:47 +0000896 const ConstantArrayType *Array =
897 getContext().getAsConstantArrayType(FieldType);
898 if (Array)
899 FieldType = getContext().getBaseElementType(Array->getElementType());
Anders Carlsson607d0372009-12-24 22:46:43 +0000900
901 const RecordType *RT = FieldType->getAs<RecordType>();
902 if (!RT)
903 continue;
904
905 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
906 if (FieldClassDecl->hasTrivialDestructor())
907 continue;
John McCall50da2ca2010-07-21 05:30:47 +0000908
Anders Carlsson607d0372009-12-24 22:46:43 +0000909 if (Array)
John McCall1f0fca52010-07-21 07:22:38 +0000910 EHStack.pushCleanup<CallArrayFieldDtor>(NormalAndEHCleanup, Field);
John McCall50da2ca2010-07-21 05:30:47 +0000911 else
John McCall1f0fca52010-07-21 07:22:38 +0000912 EHStack.pushCleanup<CallFieldDtor>(NormalAndEHCleanup, Field);
Anders Carlsson607d0372009-12-24 22:46:43 +0000913 }
Anders Carlsson607d0372009-12-24 22:46:43 +0000914}
915
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000916/// EmitCXXAggrConstructorCall - This routine essentially creates a (nested)
917/// for-loop to call the default constructor on individual members of the
918/// array.
919/// 'D' is the default constructor for elements of the array, 'ArrayTy' is the
920/// array type and 'ArrayPtr' points to the beginning fo the array.
921/// It is assumed that all relevant checks have been made by the caller.
Douglas Gregor59174c02010-07-21 01:10:17 +0000922///
923/// \param ZeroInitialization True if each element should be zero-initialized
924/// before it is constructed.
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000925void
926CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
Douglas Gregor59174c02010-07-21 01:10:17 +0000927 const ConstantArrayType *ArrayTy,
928 llvm::Value *ArrayPtr,
929 CallExpr::const_arg_iterator ArgBeg,
930 CallExpr::const_arg_iterator ArgEnd,
931 bool ZeroInitialization) {
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000932
933 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
934 llvm::Value * NumElements =
935 llvm::ConstantInt::get(SizeTy,
936 getContext().getConstantArrayElementCount(ArrayTy));
937
Douglas Gregor59174c02010-07-21 01:10:17 +0000938 EmitCXXAggrConstructorCall(D, NumElements, ArrayPtr, ArgBeg, ArgEnd,
939 ZeroInitialization);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000940}
941
942void
943CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
944 llvm::Value *NumElements,
945 llvm::Value *ArrayPtr,
946 CallExpr::const_arg_iterator ArgBeg,
Douglas Gregor59174c02010-07-21 01:10:17 +0000947 CallExpr::const_arg_iterator ArgEnd,
948 bool ZeroInitialization) {
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000949 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
950
951 // Create a temporary for the loop index and initialize it with 0.
952 llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index");
953 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
954 Builder.CreateStore(Zero, IndexPtr);
955
956 // Start the loop with a block that tests the condition.
957 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
958 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
959
960 EmitBlock(CondBlock);
961
962 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
963
964 // Generate: if (loop-index < number-of-elements fall to the loop body,
965 // otherwise, go to the block after the for-loop.
966 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
967 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless");
968 // If the condition is true, execute the body.
969 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
970
971 EmitBlock(ForBody);
972
973 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
974 // Inside the loop body, emit the constructor call on the array element.
975 Counter = Builder.CreateLoad(IndexPtr);
976 llvm::Value *Address = Builder.CreateInBoundsGEP(ArrayPtr, Counter,
977 "arrayidx");
978
Douglas Gregor59174c02010-07-21 01:10:17 +0000979 // Zero initialize the storage, if requested.
980 if (ZeroInitialization)
981 EmitNullInitialization(Address,
982 getContext().getTypeDeclType(D->getParent()));
983
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000984 // C++ [class.temporary]p4:
985 // There are two contexts in which temporaries are destroyed at a different
986 // point than the end of the full-expression. The first context is when a
987 // default constructor is called to initialize an element of an array.
988 // If the constructor has one or more default arguments, the destruction of
989 // every temporary created in a default argument expression is sequenced
990 // before the construction of the next array element, if any.
991
992 // Keep track of the current number of live temporaries.
Anders Carlsson44ec82b2010-03-30 03:14:41 +0000993 {
John McCallf1549f62010-07-06 01:34:17 +0000994 RunCleanupsScope Scope(*this);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000995
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000996 EmitCXXConstructorCall(D, Ctor_Complete, /*ForVirtualBase=*/false, Address,
Anders Carlsson24eb78e2010-05-02 23:01:10 +0000997 ArgBeg, ArgEnd);
Anders Carlsson44ec82b2010-03-30 03:14:41 +0000998 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000999
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001000 EmitBlock(ContinueBlock);
1001
1002 // Emit the increment of the loop counter.
1003 llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1);
1004 Counter = Builder.CreateLoad(IndexPtr);
1005 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1006 Builder.CreateStore(NextVal, IndexPtr);
1007
1008 // Finally, branch back up to the condition for the next iteration.
1009 EmitBranch(CondBlock);
1010
1011 // Emit the fall-through block.
1012 EmitBlock(AfterFor, true);
1013}
1014
1015/// EmitCXXAggrDestructorCall - calls the default destructor on array
1016/// elements in reverse order of construction.
1017void
1018CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
1019 const ArrayType *Array,
1020 llvm::Value *This) {
1021 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1022 assert(CA && "Do we support VLA for destruction ?");
1023 uint64_t ElementCount = getContext().getConstantArrayElementCount(CA);
1024
1025 const llvm::Type *SizeLTy = ConvertType(getContext().getSizeType());
1026 llvm::Value* ElementCountPtr = llvm::ConstantInt::get(SizeLTy, ElementCount);
1027 EmitCXXAggrDestructorCall(D, ElementCountPtr, This);
1028}
1029
1030/// EmitCXXAggrDestructorCall - calls the default destructor on array
1031/// elements in reverse order of construction.
1032void
1033CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
1034 llvm::Value *UpperCount,
1035 llvm::Value *This) {
1036 const llvm::Type *SizeLTy = ConvertType(getContext().getSizeType());
1037 llvm::Value *One = llvm::ConstantInt::get(SizeLTy, 1);
1038
1039 // Create a temporary for the loop index and initialize it with count of
1040 // array elements.
1041 llvm::Value *IndexPtr = CreateTempAlloca(SizeLTy, "loop.index");
1042
1043 // Store the number of elements in the index pointer.
1044 Builder.CreateStore(UpperCount, IndexPtr);
1045
1046 // Start the loop with a block that tests the condition.
1047 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1048 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1049
1050 EmitBlock(CondBlock);
1051
1052 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1053
1054 // Generate: if (loop-index != 0 fall to the loop body,
1055 // otherwise, go to the block after the for-loop.
1056 llvm::Value* zeroConstant =
1057 llvm::Constant::getNullValue(SizeLTy);
1058 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1059 llvm::Value *IsNE = Builder.CreateICmpNE(Counter, zeroConstant,
1060 "isne");
1061 // If the condition is true, execute the body.
1062 Builder.CreateCondBr(IsNE, ForBody, AfterFor);
1063
1064 EmitBlock(ForBody);
1065
1066 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1067 // Inside the loop body, emit the constructor call on the array element.
1068 Counter = Builder.CreateLoad(IndexPtr);
1069 Counter = Builder.CreateSub(Counter, One);
1070 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
Anders Carlsson8e6404c2010-05-02 23:29:11 +00001071 EmitCXXDestructorCall(D, Dtor_Complete, /*ForVirtualBase=*/false, Address);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001072
1073 EmitBlock(ContinueBlock);
1074
1075 // Emit the decrement of the loop counter.
1076 Counter = Builder.CreateLoad(IndexPtr);
1077 Counter = Builder.CreateSub(Counter, One, "dec");
1078 Builder.CreateStore(Counter, IndexPtr);
1079
1080 // Finally, branch back up to the condition for the next iteration.
1081 EmitBranch(CondBlock);
1082
1083 // Emit the fall-through block.
1084 EmitBlock(AfterFor, true);
1085}
1086
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001087void
1088CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
Anders Carlsson155ed4a2010-05-02 23:20:53 +00001089 CXXCtorType Type, bool ForVirtualBase,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001090 llvm::Value *This,
1091 CallExpr::const_arg_iterator ArgBeg,
1092 CallExpr::const_arg_iterator ArgEnd) {
John McCall8b6bbeb2010-02-06 00:25:16 +00001093 if (D->isTrivial()) {
1094 if (ArgBeg == ArgEnd) {
1095 // Trivial default constructor, no codegen required.
1096 assert(D->isDefaultConstructor() &&
1097 "trivial 0-arg ctor not a default ctor");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001098 return;
1099 }
John McCall8b6bbeb2010-02-06 00:25:16 +00001100
1101 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
1102 assert(D->isCopyConstructor() && "trivial 1-arg ctor not a copy ctor");
1103
John McCall8b6bbeb2010-02-06 00:25:16 +00001104 const Expr *E = (*ArgBeg);
1105 QualType Ty = E->getType();
1106 llvm::Value *Src = EmitLValue(E).getAddress();
1107 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001108 return;
1109 }
1110
Anders Carlsson314e6222010-05-02 23:33:10 +00001111 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(D, Type), ForVirtualBase);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001112 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
1113
Anders Carlssonc997d422010-01-02 01:01:18 +00001114 EmitCXXMemberCall(D, Callee, ReturnValueSlot(), This, VTT, ArgBeg, ArgEnd);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001115}
1116
John McCallc0bf4622010-02-23 00:48:20 +00001117void
1118CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1119 CXXCtorType CtorType,
1120 const FunctionArgList &Args) {
1121 CallArgList DelegateArgs;
1122
1123 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
1124 assert(I != E && "no parameters to constructor");
1125
1126 // this
1127 DelegateArgs.push_back(std::make_pair(RValue::get(LoadCXXThis()),
1128 I->second));
1129 ++I;
1130
1131 // vtt
Anders Carlsson314e6222010-05-02 23:33:10 +00001132 if (llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(Ctor, CtorType),
1133 /*ForVirtualBase=*/false)) {
John McCallc0bf4622010-02-23 00:48:20 +00001134 QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
1135 DelegateArgs.push_back(std::make_pair(RValue::get(VTT), VoidPP));
1136
Anders Carlssonaf440352010-03-23 04:11:45 +00001137 if (CodeGenVTables::needsVTTParameter(CurGD)) {
John McCallc0bf4622010-02-23 00:48:20 +00001138 assert(I != E && "cannot skip vtt parameter, already done with args");
1139 assert(I->second == VoidPP && "skipping parameter not of vtt type");
1140 ++I;
1141 }
1142 }
1143
1144 // Explicit arguments.
1145 for (; I != E; ++I) {
John McCallc0bf4622010-02-23 00:48:20 +00001146 const VarDecl *Param = I->first;
1147 QualType ArgType = Param->getType(); // because we're passing it to itself
John McCall27360712010-05-26 22:34:26 +00001148 RValue Arg = EmitDelegateCallArg(Param);
John McCallc0bf4622010-02-23 00:48:20 +00001149
1150 DelegateArgs.push_back(std::make_pair(Arg, ArgType));
1151 }
1152
1153 EmitCall(CGM.getTypes().getFunctionInfo(Ctor, CtorType),
1154 CGM.GetAddrOfCXXConstructor(Ctor, CtorType),
1155 ReturnValueSlot(), DelegateArgs, Ctor);
1156}
1157
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001158void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
1159 CXXDtorType Type,
Anders Carlsson8e6404c2010-05-02 23:29:11 +00001160 bool ForVirtualBase,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001161 llvm::Value *This) {
Anders Carlsson314e6222010-05-02 23:33:10 +00001162 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(DD, Type),
1163 ForVirtualBase);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001164 llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
1165
Anders Carlssonc997d422010-01-02 01:01:18 +00001166 EmitCXXMemberCall(DD, Callee, ReturnValueSlot(), This, VTT, 0, 0);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001167}
1168
John McCall291ae942010-07-21 01:41:18 +00001169namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001170 struct CallLocalDtor : EHScopeStack::Cleanup {
John McCall291ae942010-07-21 01:41:18 +00001171 const CXXDestructorDecl *Dtor;
1172 llvm::Value *Addr;
1173
1174 CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
1175 : Dtor(D), Addr(Addr) {}
1176
1177 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1178 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1179 /*ForVirtualBase=*/false, Addr);
1180 }
1181 };
1182}
1183
John McCall81407d42010-07-21 06:29:51 +00001184void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
1185 llvm::Value *Addr) {
John McCall1f0fca52010-07-21 07:22:38 +00001186 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
John McCall81407d42010-07-21 06:29:51 +00001187}
1188
John McCallf1549f62010-07-06 01:34:17 +00001189void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
1190 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
1191 if (!ClassDecl) return;
1192 if (ClassDecl->hasTrivialDestructor()) return;
1193
1194 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCall81407d42010-07-21 06:29:51 +00001195 PushDestructorCleanup(D, Addr);
John McCallf1549f62010-07-06 01:34:17 +00001196}
1197
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001198llvm::Value *
Anders Carlssonbb7e17b2010-01-31 01:36:53 +00001199CodeGenFunction::GetVirtualBaseClassOffset(llvm::Value *This,
1200 const CXXRecordDecl *ClassDecl,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001201 const CXXRecordDecl *BaseClassDecl) {
1202 const llvm::Type *Int8PtrTy =
1203 llvm::Type::getInt8Ty(VMContext)->getPointerTo();
1204
1205 llvm::Value *VTablePtr = Builder.CreateBitCast(This,
1206 Int8PtrTy->getPointerTo());
1207 VTablePtr = Builder.CreateLoad(VTablePtr, "vtable");
1208
Anders Carlssonbba16072010-03-11 07:15:17 +00001209 int64_t VBaseOffsetOffset =
Anders Carlssonaf440352010-03-23 04:11:45 +00001210 CGM.getVTables().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001211
1212 llvm::Value *VBaseOffsetPtr =
Anders Carlssonbba16072010-03-11 07:15:17 +00001213 Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset, "vbase.offset.ptr");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001214 const llvm::Type *PtrDiffTy =
1215 ConvertType(getContext().getPointerDiffType());
1216
1217 VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr,
1218 PtrDiffTy->getPointerTo());
1219
1220 llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1221
1222 return VBaseOffset;
1223}
1224
Anders Carlssond103f9f2010-03-28 19:40:00 +00001225void
1226CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001227 const CXXRecordDecl *NearestVBase,
Anders Carlsson42358402010-05-03 00:07:07 +00001228 uint64_t OffsetFromNearestVBase,
Anders Carlssond103f9f2010-03-28 19:40:00 +00001229 llvm::Constant *VTable,
1230 const CXXRecordDecl *VTableClass) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001231 const CXXRecordDecl *RD = Base.getBase();
1232
Anders Carlssond103f9f2010-03-28 19:40:00 +00001233 // Compute the address point.
Anders Carlssonc83f1062010-03-29 01:08:49 +00001234 llvm::Value *VTableAddressPoint;
Anders Carlsson851853d2010-03-29 02:38:51 +00001235
Anders Carlssonc83f1062010-03-29 01:08:49 +00001236 // Check if we need to use a vtable from the VTT.
Anders Carlsson851853d2010-03-29 02:38:51 +00001237 if (CodeGenVTables::needsVTTParameter(CurGD) &&
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001238 (RD->getNumVBases() || NearestVBase)) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001239 // Get the secondary vpointer index.
1240 uint64_t VirtualPointerIndex =
1241 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1242
1243 /// Load the VTT.
1244 llvm::Value *VTT = LoadCXXVTT();
1245 if (VirtualPointerIndex)
1246 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1247
1248 // And load the address point from the VTT.
1249 VTableAddressPoint = Builder.CreateLoad(VTT);
1250 } else {
Anders Carlsson64c9eca2010-03-29 02:08:26 +00001251 uint64_t AddressPoint = CGM.getVTables().getAddressPoint(Base, VTableClass);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001252 VTableAddressPoint =
Anders Carlssond103f9f2010-03-28 19:40:00 +00001253 Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001254 }
Anders Carlssond103f9f2010-03-28 19:40:00 +00001255
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001256 // Compute where to store the address point.
Anders Carlsson8246cc72010-05-03 00:29:58 +00001257 llvm::Value *VirtualOffset = 0;
1258 uint64_t NonVirtualOffset = 0;
Anders Carlsson3e79c302010-04-20 18:05:10 +00001259
1260 if (CodeGenVTables::needsVTTParameter(CurGD) && NearestVBase) {
1261 // We need to use the virtual base offset offset because the virtual base
1262 // might have a different offset in the most derived class.
Anders Carlsson8246cc72010-05-03 00:29:58 +00001263 VirtualOffset = GetVirtualBaseClassOffset(LoadCXXThis(), VTableClass,
1264 NearestVBase);
1265 NonVirtualOffset = OffsetFromNearestVBase / 8;
Anders Carlsson3e79c302010-04-20 18:05:10 +00001266 } else {
Anders Carlsson8246cc72010-05-03 00:29:58 +00001267 // We can just use the base offset in the complete class.
1268 NonVirtualOffset = Base.getBaseOffset() / 8;
Anders Carlsson3e79c302010-04-20 18:05:10 +00001269 }
Anders Carlsson8246cc72010-05-03 00:29:58 +00001270
1271 // Apply the offsets.
1272 llvm::Value *VTableField = LoadCXXThis();
1273
1274 if (NonVirtualOffset || VirtualOffset)
1275 VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
1276 NonVirtualOffset,
1277 VirtualOffset);
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001278
Anders Carlssond103f9f2010-03-28 19:40:00 +00001279 // Finally, store the address point.
1280 const llvm::Type *AddressPointPtrTy =
1281 VTableAddressPoint->getType()->getPointerTo();
1282 VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
1283 Builder.CreateStore(VTableAddressPoint, VTableField);
1284}
1285
Anders Carlsson603d6d12010-03-28 21:07:49 +00001286void
1287CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001288 const CXXRecordDecl *NearestVBase,
Anders Carlsson42358402010-05-03 00:07:07 +00001289 uint64_t OffsetFromNearestVBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001290 bool BaseIsNonVirtualPrimaryBase,
1291 llvm::Constant *VTable,
1292 const CXXRecordDecl *VTableClass,
1293 VisitedVirtualBasesSetTy& VBases) {
1294 // If this base is a non-virtual primary base the address point has already
1295 // been set.
1296 if (!BaseIsNonVirtualPrimaryBase) {
1297 // Initialize the vtable pointer for this base.
Anders Carlsson42358402010-05-03 00:07:07 +00001298 InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
1299 VTable, VTableClass);
Anders Carlsson603d6d12010-03-28 21:07:49 +00001300 }
1301
1302 const CXXRecordDecl *RD = Base.getBase();
1303
1304 // Traverse bases.
1305 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1306 E = RD->bases_end(); I != E; ++I) {
1307 CXXRecordDecl *BaseDecl
1308 = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1309
1310 // Ignore classes without a vtable.
1311 if (!BaseDecl->isDynamicClass())
1312 continue;
1313
1314 uint64_t BaseOffset;
Anders Carlsson42358402010-05-03 00:07:07 +00001315 uint64_t BaseOffsetFromNearestVBase;
Anders Carlsson14da9de2010-03-29 01:16:41 +00001316 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001317
1318 if (I->isVirtual()) {
1319 // Check if we've visited this virtual base before.
1320 if (!VBases.insert(BaseDecl))
1321 continue;
1322
1323 const ASTRecordLayout &Layout =
1324 getContext().getASTRecordLayout(VTableClass);
1325
Anders Carlsson603d6d12010-03-28 21:07:49 +00001326 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
Anders Carlsson42358402010-05-03 00:07:07 +00001327 BaseOffsetFromNearestVBase = 0;
Anders Carlsson14da9de2010-03-29 01:16:41 +00001328 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001329 } else {
1330 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1331
1332 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson42358402010-05-03 00:07:07 +00001333 BaseOffsetFromNearestVBase =
Anders Carlsson8246cc72010-05-03 00:29:58 +00001334 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson14da9de2010-03-29 01:16:41 +00001335 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001336 }
1337
1338 InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001339 I->isVirtual() ? BaseDecl : NearestVBase,
Anders Carlsson42358402010-05-03 00:07:07 +00001340 BaseOffsetFromNearestVBase,
Anders Carlsson14da9de2010-03-29 01:16:41 +00001341 BaseDeclIsNonVirtualPrimaryBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001342 VTable, VTableClass, VBases);
1343 }
1344}
1345
1346void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
1347 // Ignore classes without a vtable.
Anders Carlsson07036902010-03-26 04:39:42 +00001348 if (!RD->isDynamicClass())
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001349 return;
1350
Anders Carlsson07036902010-03-26 04:39:42 +00001351 // Get the VTable.
1352 llvm::Constant *VTable = CGM.getVTables().GetAddrOfVTable(RD);
Anders Carlsson5c6c1d92010-03-24 03:57:14 +00001353
Anders Carlsson603d6d12010-03-28 21:07:49 +00001354 // Initialize the vtable pointers for this class and all of its bases.
1355 VisitedVirtualBasesSetTy VBases;
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001356 InitializeVTablePointers(BaseSubobject(RD, 0), /*NearestVBase=*/0,
Anders Carlsson42358402010-05-03 00:07:07 +00001357 /*OffsetFromNearestVBase=*/0,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001358 /*BaseIsNonVirtualPrimaryBase=*/false,
1359 VTable, RD, VBases);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001360}