blob: 453bae2940bee5b79e0f9f4244b12a2fb544ea62 [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"
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000017#include "clang/AST/RecordLayout.h"
John McCall9fc6a772010-02-19 09:25:03 +000018#include "clang/AST/StmtCXX.h"
Anders Carlsson2f1986b2009-10-06 22:43:30 +000019
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000020using namespace clang;
21using namespace CodeGen;
22
Anders Carlsson2f1986b2009-10-06 22:43:30 +000023static uint64_t
Anders Carlsson34a2d382010-04-24 21:06:20 +000024ComputeNonVirtualBaseClassOffset(ASTContext &Context,
25 const CXXRecordDecl *DerivedClass,
John McCallf871d0c2010-08-07 06:22:56 +000026 CastExpr::path_const_iterator Start,
27 CastExpr::path_const_iterator End) {
Anders Carlsson34a2d382010-04-24 21:06:20 +000028 uint64_t Offset = 0;
29
30 const CXXRecordDecl *RD = DerivedClass;
31
John McCallf871d0c2010-08-07 06:22:56 +000032 for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
Anders Carlsson34a2d382010-04-24 21:06:20 +000033 const CXXBaseSpecifier *Base = *I;
34 assert(!Base->isVirtual() && "Should not see virtual bases here!");
35
36 // Get the layout.
37 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
38
39 const CXXRecordDecl *BaseDecl =
40 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
41
42 // Add the offset.
43 Offset += Layout.getBaseClassOffset(BaseDecl);
44
45 RD = BaseDecl;
46 }
47
48 // FIXME: We should not use / 8 here.
49 return Offset / 8;
50}
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000051
Anders Carlsson84080ec2009-09-29 03:13:20 +000052llvm::Constant *
Anders Carlssona04efdf2010-04-24 21:23:59 +000053CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +000054 CastExpr::path_const_iterator PathBegin,
55 CastExpr::path_const_iterator PathEnd) {
56 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssona04efdf2010-04-24 21:23:59 +000057
58 uint64_t Offset =
John McCallf871d0c2010-08-07 06:22:56 +000059 ComputeNonVirtualBaseClassOffset(getContext(), ClassDecl,
60 PathBegin, PathEnd);
Anders Carlssona04efdf2010-04-24 21:23:59 +000061 if (!Offset)
62 return 0;
63
64 const llvm::Type *PtrDiffTy =
65 Types.ConvertType(getContext().getPointerDiffType());
66
67 return llvm::ConstantInt::get(PtrDiffTy, Offset);
Anders Carlsson84080ec2009-09-29 03:13:20 +000068}
69
Anders Carlsson8561a862010-04-24 23:01:49 +000070/// Gets the address of a direct base class within a complete object.
John McCallbff225e2010-02-16 04:15:37 +000071/// This should only be used for (1) non-virtual bases or (2) virtual bases
72/// when the type is known to be complete (e.g. in complete destructors).
73///
74/// The object pointed to by 'This' is assumed to be non-null.
75llvm::Value *
Anders Carlsson8561a862010-04-24 23:01:49 +000076CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(llvm::Value *This,
77 const CXXRecordDecl *Derived,
78 const CXXRecordDecl *Base,
79 bool BaseIsVirtual) {
John McCallbff225e2010-02-16 04:15:37 +000080 // 'this' must be a pointer (in some address space) to Derived.
81 assert(This->getType()->isPointerTy() &&
82 cast<llvm::PointerType>(This->getType())->getElementType()
83 == ConvertType(Derived));
84
85 // Compute the offset of the virtual base.
86 uint64_t Offset;
87 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
Anders Carlsson8561a862010-04-24 23:01:49 +000088 if (BaseIsVirtual)
John McCallbff225e2010-02-16 04:15:37 +000089 Offset = Layout.getVBaseClassOffset(Base);
90 else
91 Offset = Layout.getBaseClassOffset(Base);
92
93 // Shift and cast down to the base type.
94 // TODO: for complete types, this should be possible with a GEP.
95 llvm::Value *V = This;
96 if (Offset) {
97 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
98 V = Builder.CreateBitCast(V, Int8PtrTy);
99 V = Builder.CreateConstInBoundsGEP1_64(V, Offset / 8);
100 }
101 V = Builder.CreateBitCast(V, ConvertType(Base)->getPointerTo());
102
103 return V;
Anders Carlssond103f9f2010-03-28 19:40:00 +0000104}
John McCallbff225e2010-02-16 04:15:37 +0000105
Anders Carlsson9dc228a2010-04-20 16:03:35 +0000106static llvm::Value *
107ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, llvm::Value *ThisPtr,
108 uint64_t NonVirtual, llvm::Value *Virtual) {
109 const llvm::Type *PtrDiffTy =
110 CGF.ConvertType(CGF.getContext().getPointerDiffType());
111
112 llvm::Value *NonVirtualOffset = 0;
113 if (NonVirtual)
114 NonVirtualOffset = llvm::ConstantInt::get(PtrDiffTy, NonVirtual);
115
116 llvm::Value *BaseOffset;
117 if (Virtual) {
118 if (NonVirtualOffset)
119 BaseOffset = CGF.Builder.CreateAdd(Virtual, NonVirtualOffset);
120 else
121 BaseOffset = Virtual;
122 } else
123 BaseOffset = NonVirtualOffset;
124
125 // Apply the base offset.
126 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
127 ThisPtr = CGF.Builder.CreateBitCast(ThisPtr, Int8PtrTy);
128 ThisPtr = CGF.Builder.CreateGEP(ThisPtr, BaseOffset, "add.ptr");
129
130 return ThisPtr;
131}
132
Anders Carlsson5d58a1d2009-09-12 04:27:24 +0000133llvm::Value *
Anders Carlsson34a2d382010-04-24 21:06:20 +0000134CodeGenFunction::GetAddressOfBaseClass(llvm::Value *Value,
Anders Carlsson8561a862010-04-24 23:01:49 +0000135 const CXXRecordDecl *Derived,
John McCallf871d0c2010-08-07 06:22:56 +0000136 CastExpr::path_const_iterator PathBegin,
137 CastExpr::path_const_iterator PathEnd,
Anders Carlsson34a2d382010-04-24 21:06:20 +0000138 bool NullCheckValue) {
John McCallf871d0c2010-08-07 06:22:56 +0000139 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlsson34a2d382010-04-24 21:06:20 +0000140
John McCallf871d0c2010-08-07 06:22:56 +0000141 CastExpr::path_const_iterator Start = PathBegin;
Anders Carlsson34a2d382010-04-24 21:06:20 +0000142 const CXXRecordDecl *VBase = 0;
143
144 // Get the virtual base.
145 if ((*Start)->isVirtual()) {
146 VBase =
147 cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
148 ++Start;
149 }
150
151 uint64_t NonVirtualOffset =
Anders Carlsson8561a862010-04-24 23:01:49 +0000152 ComputeNonVirtualBaseClassOffset(getContext(), VBase ? VBase : Derived,
John McCallf871d0c2010-08-07 06:22:56 +0000153 Start, PathEnd);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000154
155 // Get the base pointer type.
156 const llvm::Type *BasePtrTy =
John McCallf871d0c2010-08-07 06:22:56 +0000157 ConvertType((PathEnd[-1])->getType())->getPointerTo();
Anders Carlsson34a2d382010-04-24 21:06:20 +0000158
159 if (!NonVirtualOffset && !VBase) {
160 // Just cast back.
161 return Builder.CreateBitCast(Value, BasePtrTy);
162 }
163
164 llvm::BasicBlock *CastNull = 0;
165 llvm::BasicBlock *CastNotNull = 0;
166 llvm::BasicBlock *CastEnd = 0;
167
168 if (NullCheckValue) {
169 CastNull = createBasicBlock("cast.null");
170 CastNotNull = createBasicBlock("cast.notnull");
171 CastEnd = createBasicBlock("cast.end");
172
173 llvm::Value *IsNull =
174 Builder.CreateICmpEQ(Value,
175 llvm::Constant::getNullValue(Value->getType()));
176 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
177 EmitBlock(CastNotNull);
178 }
179
180 llvm::Value *VirtualOffset = 0;
181
182 if (VBase)
Anders Carlsson8561a862010-04-24 23:01:49 +0000183 VirtualOffset = GetVirtualBaseClassOffset(Value, Derived, VBase);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000184
185 // Apply the offsets.
186 Value = ApplyNonVirtualAndVirtualOffset(*this, Value, NonVirtualOffset,
187 VirtualOffset);
188
189 // Cast back.
190 Value = Builder.CreateBitCast(Value, BasePtrTy);
191
192 if (NullCheckValue) {
193 Builder.CreateBr(CastEnd);
194 EmitBlock(CastNull);
195 Builder.CreateBr(CastEnd);
196 EmitBlock(CastEnd);
197
198 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType());
199 PHI->reserveOperandSpace(2);
200 PHI->addIncoming(Value, CastNotNull);
201 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
202 CastNull);
203 Value = PHI;
204 }
205
206 return Value;
207}
208
209llvm::Value *
Anders Carlssona3697c92009-11-23 17:57:54 +0000210CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value,
Anders Carlsson8561a862010-04-24 23:01:49 +0000211 const CXXRecordDecl *Derived,
John McCallf871d0c2010-08-07 06:22:56 +0000212 CastExpr::path_const_iterator PathBegin,
213 CastExpr::path_const_iterator PathEnd,
Anders Carlssona3697c92009-11-23 17:57:54 +0000214 bool NullCheckValue) {
John McCallf871d0c2010-08-07 06:22:56 +0000215 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssona04efdf2010-04-24 21:23:59 +0000216
Anders Carlssona3697c92009-11-23 17:57:54 +0000217 QualType DerivedTy =
Anders Carlsson8561a862010-04-24 23:01:49 +0000218 getContext().getCanonicalType(getContext().getTagDeclType(Derived));
Anders Carlssona3697c92009-11-23 17:57:54 +0000219 const llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
220
Anders Carlssona552ea72010-01-31 01:43:37 +0000221 llvm::Value *NonVirtualOffset =
John McCallf871d0c2010-08-07 06:22:56 +0000222 CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
Anders Carlssona552ea72010-01-31 01:43:37 +0000223
224 if (!NonVirtualOffset) {
225 // No offset, we can just cast back.
226 return Builder.CreateBitCast(Value, DerivedPtrTy);
227 }
228
Anders Carlssona3697c92009-11-23 17:57:54 +0000229 llvm::BasicBlock *CastNull = 0;
230 llvm::BasicBlock *CastNotNull = 0;
231 llvm::BasicBlock *CastEnd = 0;
232
233 if (NullCheckValue) {
234 CastNull = createBasicBlock("cast.null");
235 CastNotNull = createBasicBlock("cast.notnull");
236 CastEnd = createBasicBlock("cast.end");
237
238 llvm::Value *IsNull =
239 Builder.CreateICmpEQ(Value,
240 llvm::Constant::getNullValue(Value->getType()));
241 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
242 EmitBlock(CastNotNull);
243 }
244
Anders Carlssona552ea72010-01-31 01:43:37 +0000245 // Apply the offset.
246 Value = Builder.CreatePtrToInt(Value, NonVirtualOffset->getType());
247 Value = Builder.CreateSub(Value, NonVirtualOffset);
248 Value = Builder.CreateIntToPtr(Value, DerivedPtrTy);
249
250 // Just cast.
251 Value = Builder.CreateBitCast(Value, DerivedPtrTy);
Anders Carlssona3697c92009-11-23 17:57:54 +0000252
253 if (NullCheckValue) {
254 Builder.CreateBr(CastEnd);
255 EmitBlock(CastNull);
256 Builder.CreateBr(CastEnd);
257 EmitBlock(CastEnd);
258
259 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType());
260 PHI->reserveOperandSpace(2);
261 PHI->addIncoming(Value, CastNotNull);
262 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
263 CastNull);
264 Value = PHI;
265 }
266
267 return Value;
Anders Carlsson5d58a1d2009-09-12 04:27:24 +0000268}
Anders Carlsson21c9ad92010-03-30 03:27:09 +0000269
Anders Carlssonc997d422010-01-02 01:01:18 +0000270/// GetVTTParameter - Return the VTT parameter that should be passed to a
271/// base constructor/destructor with virtual bases.
Anders Carlsson314e6222010-05-02 23:33:10 +0000272static llvm::Value *GetVTTParameter(CodeGenFunction &CGF, GlobalDecl GD,
273 bool ForVirtualBase) {
Anders Carlssonaf440352010-03-23 04:11:45 +0000274 if (!CodeGenVTables::needsVTTParameter(GD)) {
Anders Carlssonc997d422010-01-02 01:01:18 +0000275 // This constructor/destructor does not need a VTT parameter.
276 return 0;
277 }
278
279 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CGF.CurFuncDecl)->getParent();
280 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
John McCall3b477332010-02-18 19:59:28 +0000281
Anders Carlssonc997d422010-01-02 01:01:18 +0000282 llvm::Value *VTT;
283
John McCall3b477332010-02-18 19:59:28 +0000284 uint64_t SubVTTIndex;
285
286 // If the record matches the base, this is the complete ctor/dtor
287 // variant calling the base variant in a class with virtual bases.
288 if (RD == Base) {
Anders Carlssonaf440352010-03-23 04:11:45 +0000289 assert(!CodeGenVTables::needsVTTParameter(CGF.CurGD) &&
John McCall3b477332010-02-18 19:59:28 +0000290 "doing no-op VTT offset in base dtor/ctor?");
Anders Carlsson314e6222010-05-02 23:33:10 +0000291 assert(!ForVirtualBase && "Can't have same class as virtual base!");
John McCall3b477332010-02-18 19:59:28 +0000292 SubVTTIndex = 0;
293 } else {
Anders Carlssonc11bb212010-05-02 23:53:25 +0000294 const ASTRecordLayout &Layout =
295 CGF.getContext().getASTRecordLayout(RD);
296 uint64_t BaseOffset = ForVirtualBase ?
297 Layout.getVBaseClassOffset(Base) : Layout.getBaseClassOffset(Base);
298
299 SubVTTIndex =
300 CGF.CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
John McCall3b477332010-02-18 19:59:28 +0000301 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
302 }
Anders Carlssonc997d422010-01-02 01:01:18 +0000303
Anders Carlssonaf440352010-03-23 04:11:45 +0000304 if (CodeGenVTables::needsVTTParameter(CGF.CurGD)) {
Anders Carlssonc997d422010-01-02 01:01:18 +0000305 // A VTT parameter was passed to the constructor, use it.
306 VTT = CGF.LoadCXXVTT();
307 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
308 } else {
309 // We're the complete constructor, so get the VTT by name.
Anders Carlssonaf440352010-03-23 04:11:45 +0000310 VTT = CGF.CGM.getVTables().getVTT(RD);
Anders Carlssonc997d422010-01-02 01:01:18 +0000311 VTT = CGF.Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
312 }
313
314 return VTT;
315}
316
John McCall182ab512010-07-21 01:23:41 +0000317namespace {
John McCall50da2ca2010-07-21 05:30:47 +0000318 /// Call the destructor for a direct base class.
John McCall1f0fca52010-07-21 07:22:38 +0000319 struct CallBaseDtor : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000320 const CXXRecordDecl *BaseClass;
321 bool BaseIsVirtual;
322 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
323 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
John McCall182ab512010-07-21 01:23:41 +0000324
325 void Emit(CodeGenFunction &CGF, bool IsForEH) {
John McCall50da2ca2010-07-21 05:30:47 +0000326 const CXXRecordDecl *DerivedClass =
327 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
328
329 const CXXDestructorDecl *D = BaseClass->getDestructor();
330 llvm::Value *Addr =
331 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThis(),
332 DerivedClass, BaseClass,
333 BaseIsVirtual);
334 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual, Addr);
John McCall182ab512010-07-21 01:23:41 +0000335 }
336 };
337}
338
Anders Carlsson607d0372009-12-24 22:46:43 +0000339static void EmitBaseInitializer(CodeGenFunction &CGF,
340 const CXXRecordDecl *ClassDecl,
341 CXXBaseOrMemberInitializer *BaseInit,
342 CXXCtorType CtorType) {
343 assert(BaseInit->isBaseInitializer() &&
344 "Must have base initializer!");
345
346 llvm::Value *ThisPtr = CGF.LoadCXXThis();
347
348 const Type *BaseType = BaseInit->getBaseClass();
349 CXXRecordDecl *BaseClassDecl =
350 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
351
Anders Carlsson80638c52010-04-12 00:51:03 +0000352 bool isBaseVirtual = BaseInit->isBaseVirtual();
Anders Carlsson607d0372009-12-24 22:46:43 +0000353
354 // The base constructor doesn't construct virtual bases.
355 if (CtorType == Ctor_Base && isBaseVirtual)
356 return;
357
John McCallbff225e2010-02-16 04:15:37 +0000358 // We can pretend to be a complete class because it only matters for
359 // virtual bases, and we only do virtual bases for complete ctors.
Anders Carlsson8561a862010-04-24 23:01:49 +0000360 llvm::Value *V =
361 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
John McCall50da2ca2010-07-21 05:30:47 +0000362 BaseClassDecl,
363 isBaseVirtual);
John McCallbff225e2010-02-16 04:15:37 +0000364
Douglas Gregor9db7dbb2010-01-31 09:12:51 +0000365 CGF.EmitAggExpr(BaseInit->getInit(), V, false, false, true);
Anders Carlsson594d5e82010-02-06 20:00:21 +0000366
John McCall182ab512010-07-21 01:23:41 +0000367 if (CGF.Exceptions && !BaseClassDecl->hasTrivialDestructor())
John McCall1f0fca52010-07-21 07:22:38 +0000368 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
369 isBaseVirtual);
Anders Carlsson607d0372009-12-24 22:46:43 +0000370}
371
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000372static void EmitAggMemberInitializer(CodeGenFunction &CGF,
373 LValue LHS,
374 llvm::Value *ArrayIndexVar,
375 CXXBaseOrMemberInitializer *MemberInit,
376 QualType T,
377 unsigned Index) {
378 if (Index == MemberInit->getNumArrayIndices()) {
John McCallf1549f62010-07-06 01:34:17 +0000379 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000380
381 llvm::Value *Dest = LHS.getAddress();
382 if (ArrayIndexVar) {
383 // If we have an array index variable, load it and use it as an offset.
384 // Then, increment the value.
385 llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar);
386 Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress");
387 llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1);
388 Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc");
389 CGF.Builder.CreateStore(Next, ArrayIndexVar);
390 }
391
392 CGF.EmitAggExpr(MemberInit->getInit(), Dest,
393 LHS.isVolatileQualified(),
394 /*IgnoreResult*/ false,
395 /*IsInitializer*/ true);
396
397 return;
398 }
399
400 const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T);
401 assert(Array && "Array initialization without the array type?");
402 llvm::Value *IndexVar
403 = CGF.GetAddrOfLocalVar(MemberInit->getArrayIndex(Index));
404 assert(IndexVar && "Array index variable not loaded");
405
406 // Initialize this index variable to zero.
407 llvm::Value* Zero
408 = llvm::Constant::getNullValue(
409 CGF.ConvertType(CGF.getContext().getSizeType()));
410 CGF.Builder.CreateStore(Zero, IndexVar);
411
412 // Start the loop with a block that tests the condition.
413 llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond");
414 llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end");
415
416 CGF.EmitBlock(CondBlock);
417
418 llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body");
419 // Generate: if (loop-index < number-of-elements) fall to the loop body,
420 // otherwise, go to the block after the for-loop.
421 uint64_t NumElements = Array->getSize().getZExtValue();
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000422 llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
Chris Lattner985f7392010-05-06 06:35:23 +0000423 llvm::Value *NumElementsPtr =
424 llvm::ConstantInt::get(Counter->getType(), NumElements);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000425 llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr,
426 "isless");
427
428 // If the condition is true, execute the body.
429 CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor);
430
431 CGF.EmitBlock(ForBody);
432 llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc");
433
434 {
John McCallf1549f62010-07-06 01:34:17 +0000435 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000436
437 // Inside the loop body recurse to emit the inner loop or, eventually, the
438 // constructor call.
439 EmitAggMemberInitializer(CGF, LHS, ArrayIndexVar, MemberInit,
440 Array->getElementType(), Index + 1);
441 }
442
443 CGF.EmitBlock(ContinueBlock);
444
445 // Emit the increment of the loop counter.
446 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
447 Counter = CGF.Builder.CreateLoad(IndexVar);
448 NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc");
449 CGF.Builder.CreateStore(NextVal, IndexVar);
450
451 // Finally, branch back up to the condition for the next iteration.
452 CGF.EmitBranch(CondBlock);
453
454 // Emit the fall-through block.
455 CGF.EmitBlock(AfterFor, true);
456}
John McCall182ab512010-07-21 01:23:41 +0000457
458namespace {
John McCall1f0fca52010-07-21 07:22:38 +0000459 struct CallMemberDtor : EHScopeStack::Cleanup {
John McCall182ab512010-07-21 01:23:41 +0000460 FieldDecl *Field;
461 CXXDestructorDecl *Dtor;
462
463 CallMemberDtor(FieldDecl *Field, CXXDestructorDecl *Dtor)
464 : Field(Field), Dtor(Dtor) {}
465
466 void Emit(CodeGenFunction &CGF, bool IsForEH) {
467 // FIXME: Is this OK for C++0x delegating constructors?
468 llvm::Value *ThisPtr = CGF.LoadCXXThis();
469 LValue LHS = CGF.EmitLValueForField(ThisPtr, Field, 0);
470
471 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
472 LHS.getAddress());
473 }
474 };
475}
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000476
Anders Carlsson607d0372009-12-24 22:46:43 +0000477static void EmitMemberInitializer(CodeGenFunction &CGF,
478 const CXXRecordDecl *ClassDecl,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000479 CXXBaseOrMemberInitializer *MemberInit,
480 const CXXConstructorDecl *Constructor,
481 FunctionArgList &Args) {
Anders Carlsson607d0372009-12-24 22:46:43 +0000482 assert(MemberInit->isMemberInitializer() &&
483 "Must have member initializer!");
484
485 // non-static data member initializers.
486 FieldDecl *Field = MemberInit->getMember();
487 QualType FieldType = CGF.getContext().getCanonicalType(Field->getType());
488
489 llvm::Value *ThisPtr = CGF.LoadCXXThis();
John McCalla9976d32010-05-21 01:18:57 +0000490 LValue LHS;
Anders Carlsson06a29702010-01-29 05:24:29 +0000491
Anders Carlsson607d0372009-12-24 22:46:43 +0000492 // If we are initializing an anonymous union field, drill down to the field.
493 if (MemberInit->getAnonUnionMember()) {
494 Field = MemberInit->getAnonUnionMember();
John McCalla9976d32010-05-21 01:18:57 +0000495 LHS = CGF.EmitLValueForAnonRecordField(ThisPtr, Field, 0);
Anders Carlsson607d0372009-12-24 22:46:43 +0000496 FieldType = Field->getType();
John McCalla9976d32010-05-21 01:18:57 +0000497 } else {
498 LHS = CGF.EmitLValueForFieldInitialization(ThisPtr, Field, 0);
Anders Carlsson607d0372009-12-24 22:46:43 +0000499 }
500
Douglas Gregor9db7dbb2010-01-31 09:12:51 +0000501 // FIXME: If there's no initializer and the CXXBaseOrMemberInitializer
502 // was implicitly generated, we shouldn't be zeroing memory.
Anders Carlsson607d0372009-12-24 22:46:43 +0000503 RValue RHS;
504 if (FieldType->isReferenceType()) {
Anders Carlsson32f36ba2010-06-26 16:35:32 +0000505 RHS = CGF.EmitReferenceBindingToExpr(MemberInit->getInit(), Field);
Anders Carlsson607d0372009-12-24 22:46:43 +0000506 CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
Eli Friedman3bb94122010-01-31 19:07:50 +0000507 } else if (FieldType->isArrayType() && !MemberInit->getInit()) {
Anders Carlsson1884eb02010-05-22 17:35:42 +0000508 CGF.EmitNullInitialization(LHS.getAddress(), Field->getType());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +0000509 } else if (!CGF.hasAggregateLLVMType(Field->getType())) {
Eli Friedman0b292272010-06-03 19:58:07 +0000510 RHS = RValue::get(CGF.EmitScalarExpr(MemberInit->getInit()));
Anders Carlsson607d0372009-12-24 22:46:43 +0000511 CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +0000512 } else if (MemberInit->getInit()->getType()->isAnyComplexType()) {
513 CGF.EmitComplexExprIntoAddr(MemberInit->getInit(), LHS.getAddress(),
Anders Carlsson607d0372009-12-24 22:46:43 +0000514 LHS.isVolatileQualified());
515 } else {
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000516 llvm::Value *ArrayIndexVar = 0;
517 const ConstantArrayType *Array
518 = CGF.getContext().getAsConstantArrayType(FieldType);
519 if (Array && Constructor->isImplicit() &&
520 Constructor->isCopyConstructor()) {
521 const llvm::Type *SizeTy
522 = CGF.ConvertType(CGF.getContext().getSizeType());
523
524 // The LHS is a pointer to the first object we'll be constructing, as
525 // a flat array.
526 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
527 const llvm::Type *BasePtr = CGF.ConvertType(BaseElementTy);
528 BasePtr = llvm::PointerType::getUnqual(BasePtr);
529 llvm::Value *BaseAddrPtr = CGF.Builder.CreateBitCast(LHS.getAddress(),
530 BasePtr);
531 LHS = LValue::MakeAddr(BaseAddrPtr, CGF.MakeQualifiers(BaseElementTy));
532
533 // Create an array index that will be used to walk over all of the
534 // objects we're constructing.
535 ArrayIndexVar = CGF.CreateTempAlloca(SizeTy, "object.index");
536 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
537 CGF.Builder.CreateStore(Zero, ArrayIndexVar);
538
539 // If we are copying an array of scalars or classes with trivial copy
540 // constructors, perform a single aggregate copy.
541 const RecordType *Record = BaseElementTy->getAs<RecordType>();
542 if (!Record ||
543 cast<CXXRecordDecl>(Record->getDecl())->hasTrivialCopyConstructor()) {
544 // Find the source pointer. We knows it's the last argument because
545 // we know we're in a copy constructor.
546 unsigned SrcArgIndex = Args.size() - 1;
547 llvm::Value *SrcPtr
548 = CGF.Builder.CreateLoad(
549 CGF.GetAddrOfLocalVar(Args[SrcArgIndex].first));
550 LValue Src = CGF.EmitLValueForFieldInitialization(SrcPtr, Field, 0);
551
552 // Copy the aggregate.
553 CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
554 LHS.isVolatileQualified());
555 return;
556 }
557
558 // Emit the block variables for the array indices, if any.
559 for (unsigned I = 0, N = MemberInit->getNumArrayIndices(); I != N; ++I)
560 CGF.EmitLocalBlockVarDecl(*MemberInit->getArrayIndex(I));
561 }
562
563 EmitAggMemberInitializer(CGF, LHS, ArrayIndexVar, MemberInit, FieldType, 0);
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000564
565 if (!CGF.Exceptions)
566 return;
567
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000568 // FIXME: If we have an array of classes w/ non-trivial destructors,
569 // we need to destroy in reverse order of construction along the exception
570 // path.
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000571 const RecordType *RT = FieldType->getAs<RecordType>();
572 if (!RT)
573 return;
574
575 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall182ab512010-07-21 01:23:41 +0000576 if (!RD->hasTrivialDestructor())
John McCall1f0fca52010-07-21 07:22:38 +0000577 CGF.EHStack.pushCleanup<CallMemberDtor>(EHCleanup, Field,
578 RD->getDestructor());
Anders Carlsson607d0372009-12-24 22:46:43 +0000579 }
580}
581
John McCallc0bf4622010-02-23 00:48:20 +0000582/// Checks whether the given constructor is a valid subject for the
583/// complete-to-base constructor delegation optimization, i.e.
584/// emitting the complete constructor as a simple call to the base
585/// constructor.
586static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
587
588 // Currently we disable the optimization for classes with virtual
589 // bases because (1) the addresses of parameter variables need to be
590 // consistent across all initializers but (2) the delegate function
591 // call necessarily creates a second copy of the parameter variable.
592 //
593 // The limiting example (purely theoretical AFAIK):
594 // struct A { A(int &c) { c++; } };
595 // struct B : virtual A {
596 // B(int count) : A(count) { printf("%d\n", count); }
597 // };
598 // ...although even this example could in principle be emitted as a
599 // delegation since the address of the parameter doesn't escape.
600 if (Ctor->getParent()->getNumVBases()) {
601 // TODO: white-list trivial vbase initializers. This case wouldn't
602 // be subject to the restrictions below.
603
604 // TODO: white-list cases where:
605 // - there are no non-reference parameters to the constructor
606 // - the initializers don't access any non-reference parameters
607 // - the initializers don't take the address of non-reference
608 // parameters
609 // - etc.
610 // If we ever add any of the above cases, remember that:
611 // - function-try-blocks will always blacklist this optimization
612 // - we need to perform the constructor prologue and cleanup in
613 // EmitConstructorBody.
614
615 return false;
616 }
617
618 // We also disable the optimization for variadic functions because
619 // it's impossible to "re-pass" varargs.
620 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
621 return false;
622
623 return true;
624}
625
John McCall9fc6a772010-02-19 09:25:03 +0000626/// EmitConstructorBody - Emits the body of the current constructor.
627void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
628 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
629 CXXCtorType CtorType = CurGD.getCtorType();
630
John McCallc0bf4622010-02-23 00:48:20 +0000631 // Before we go any further, try the complete->base constructor
632 // delegation optimization.
633 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor)) {
Devang Pateld67ef0e2010-08-11 21:04:37 +0000634 if (CGDebugInfo *DI = getDebugInfo())
635 DI->EmitStopPoint(Builder);
John McCallc0bf4622010-02-23 00:48:20 +0000636 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args);
637 return;
638 }
639
John McCall9fc6a772010-02-19 09:25:03 +0000640 Stmt *Body = Ctor->getBody();
641
John McCallc0bf4622010-02-23 00:48:20 +0000642 // Enter the function-try-block before the constructor prologue if
643 // applicable.
John McCallc0bf4622010-02-23 00:48:20 +0000644 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallc0bf4622010-02-23 00:48:20 +0000645 if (IsTryBody)
John McCall59a70002010-07-07 06:56:46 +0000646 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000647
John McCallf1549f62010-07-06 01:34:17 +0000648 EHScopeStack::stable_iterator CleanupDepth = EHStack.stable_begin();
John McCall9fc6a772010-02-19 09:25:03 +0000649
John McCallc0bf4622010-02-23 00:48:20 +0000650 // Emit the constructor prologue, i.e. the base and member
651 // initializers.
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000652 EmitCtorPrologue(Ctor, CtorType, Args);
John McCall9fc6a772010-02-19 09:25:03 +0000653
654 // Emit the body of the statement.
John McCallc0bf4622010-02-23 00:48:20 +0000655 if (IsTryBody)
John McCall9fc6a772010-02-19 09:25:03 +0000656 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
657 else if (Body)
658 EmitStmt(Body);
John McCall9fc6a772010-02-19 09:25:03 +0000659
660 // Emit any cleanup blocks associated with the member or base
661 // initializers, which includes (along the exceptional path) the
662 // destructors for those members and bases that were fully
663 // constructed.
John McCallf1549f62010-07-06 01:34:17 +0000664 PopCleanupBlocks(CleanupDepth);
John McCall9fc6a772010-02-19 09:25:03 +0000665
John McCallc0bf4622010-02-23 00:48:20 +0000666 if (IsTryBody)
John McCall59a70002010-07-07 06:56:46 +0000667 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000668}
669
Anders Carlsson607d0372009-12-24 22:46:43 +0000670/// EmitCtorPrologue - This routine generates necessary code to initialize
671/// base classes and non-static data members belonging to this constructor.
Anders Carlsson607d0372009-12-24 22:46:43 +0000672void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000673 CXXCtorType CtorType,
674 FunctionArgList &Args) {
Anders Carlsson607d0372009-12-24 22:46:43 +0000675 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000676
677 llvm::SmallVector<CXXBaseOrMemberInitializer *, 8> MemberInitializers;
Anders Carlsson607d0372009-12-24 22:46:43 +0000678
Anders Carlsson607d0372009-12-24 22:46:43 +0000679 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
680 E = CD->init_end();
681 B != E; ++B) {
682 CXXBaseOrMemberInitializer *Member = (*B);
683
Anders Carlsson607d0372009-12-24 22:46:43 +0000684 if (Member->isBaseInitializer())
685 EmitBaseInitializer(*this, ClassDecl, Member, CtorType);
686 else
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000687 MemberInitializers.push_back(Member);
Anders Carlsson607d0372009-12-24 22:46:43 +0000688 }
689
Anders Carlsson603d6d12010-03-28 21:07:49 +0000690 InitializeVTablePointers(ClassDecl);
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000691
John McCallf1549f62010-07-06 01:34:17 +0000692 for (unsigned I = 0, E = MemberInitializers.size(); I != E; ++I)
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000693 EmitMemberInitializer(*this, ClassDecl, MemberInitializers[I], CD, Args);
Anders Carlsson607d0372009-12-24 22:46:43 +0000694}
695
John McCall9fc6a772010-02-19 09:25:03 +0000696/// EmitDestructorBody - Emits the body of the current destructor.
697void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
698 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
699 CXXDtorType DtorType = CurGD.getDtorType();
700
John McCall50da2ca2010-07-21 05:30:47 +0000701 // The call to operator delete in a deleting destructor happens
702 // outside of the function-try-block, which means it's always
703 // possible to delegate the destructor body to the complete
704 // destructor. Do so.
705 if (DtorType == Dtor_Deleting) {
706 EnterDtorCleanups(Dtor, Dtor_Deleting);
707 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
708 LoadCXXThis());
709 PopCleanupBlock();
710 return;
711 }
712
John McCall9fc6a772010-02-19 09:25:03 +0000713 Stmt *Body = Dtor->getBody();
714
715 // If the body is a function-try-block, enter the try before
John McCall50da2ca2010-07-21 05:30:47 +0000716 // anything else.
717 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCall9fc6a772010-02-19 09:25:03 +0000718 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +0000719 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000720
John McCall50da2ca2010-07-21 05:30:47 +0000721 // Enter the epilogue cleanups.
722 RunCleanupsScope DtorEpilogue(*this);
723
John McCall9fc6a772010-02-19 09:25:03 +0000724 // If this is the complete variant, just invoke the base variant;
725 // the epilogue will destruct the virtual bases. But we can't do
726 // this optimization if the body is a function-try-block, because
727 // we'd introduce *two* handler blocks.
John McCall50da2ca2010-07-21 05:30:47 +0000728 switch (DtorType) {
729 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
730
731 case Dtor_Complete:
732 // Enter the cleanup scopes for virtual bases.
733 EnterDtorCleanups(Dtor, Dtor_Complete);
734
735 if (!isTryBody) {
736 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
737 LoadCXXThis());
738 break;
739 }
740 // Fallthrough: act like we're in the base variant.
John McCall9fc6a772010-02-19 09:25:03 +0000741
John McCall50da2ca2010-07-21 05:30:47 +0000742 case Dtor_Base:
743 // Enter the cleanup scopes for fields and non-virtual bases.
744 EnterDtorCleanups(Dtor, Dtor_Base);
745
746 // Initialize the vtable pointers before entering the body.
Anders Carlsson603d6d12010-03-28 21:07:49 +0000747 InitializeVTablePointers(Dtor->getParent());
John McCall50da2ca2010-07-21 05:30:47 +0000748
749 if (isTryBody)
750 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
751 else if (Body)
752 EmitStmt(Body);
753 else {
754 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
755 // nothing to do besides what's in the epilogue
756 }
757 break;
John McCall9fc6a772010-02-19 09:25:03 +0000758 }
759
John McCall50da2ca2010-07-21 05:30:47 +0000760 // Jump out through the epilogue cleanups.
761 DtorEpilogue.ForceCleanup();
John McCall9fc6a772010-02-19 09:25:03 +0000762
763 // Exit the try if applicable.
764 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +0000765 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000766}
767
John McCall50da2ca2010-07-21 05:30:47 +0000768namespace {
769 /// Call the operator delete associated with the current destructor.
John McCall1f0fca52010-07-21 07:22:38 +0000770 struct CallDtorDelete : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000771 CallDtorDelete() {}
772
773 void Emit(CodeGenFunction &CGF, bool IsForEH) {
774 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
775 const CXXRecordDecl *ClassDecl = Dtor->getParent();
776 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
777 CGF.getContext().getTagDeclType(ClassDecl));
778 }
779 };
780
John McCall1f0fca52010-07-21 07:22:38 +0000781 struct CallArrayFieldDtor : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000782 const FieldDecl *Field;
783 CallArrayFieldDtor(const FieldDecl *Field) : Field(Field) {}
784
785 void Emit(CodeGenFunction &CGF, bool IsForEH) {
786 QualType FieldType = Field->getType();
787 const ConstantArrayType *Array =
788 CGF.getContext().getAsConstantArrayType(FieldType);
789
790 QualType BaseType =
791 CGF.getContext().getBaseElementType(Array->getElementType());
792 const CXXRecordDecl *FieldClassDecl = BaseType->getAsCXXRecordDecl();
793
794 llvm::Value *ThisPtr = CGF.LoadCXXThis();
795 LValue LHS = CGF.EmitLValueForField(ThisPtr, Field,
796 // FIXME: Qualifiers?
797 /*CVRQualifiers=*/0);
798
799 const llvm::Type *BasePtr = CGF.ConvertType(BaseType)->getPointerTo();
800 llvm::Value *BaseAddrPtr =
801 CGF.Builder.CreateBitCast(LHS.getAddress(), BasePtr);
802 CGF.EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(),
803 Array, BaseAddrPtr);
804 }
805 };
806
John McCall1f0fca52010-07-21 07:22:38 +0000807 struct CallFieldDtor : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000808 const FieldDecl *Field;
809 CallFieldDtor(const FieldDecl *Field) : Field(Field) {}
810
811 void Emit(CodeGenFunction &CGF, bool IsForEH) {
812 const CXXRecordDecl *FieldClassDecl =
813 Field->getType()->getAsCXXRecordDecl();
814
815 llvm::Value *ThisPtr = CGF.LoadCXXThis();
816 LValue LHS = CGF.EmitLValueForField(ThisPtr, Field,
817 // FIXME: Qualifiers?
818 /*CVRQualifiers=*/0);
819
820 CGF.EmitCXXDestructorCall(FieldClassDecl->getDestructor(),
821 Dtor_Complete, /*ForVirtualBase=*/false,
822 LHS.getAddress());
823 }
824 };
825}
826
Anders Carlsson607d0372009-12-24 22:46:43 +0000827/// EmitDtorEpilogue - Emit all code that comes at the end of class's
828/// destructor. This is to call destructors on members and base classes
829/// in reverse order of their construction.
John McCall50da2ca2010-07-21 05:30:47 +0000830void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
831 CXXDtorType DtorType) {
Anders Carlsson607d0372009-12-24 22:46:43 +0000832 assert(!DD->isTrivial() &&
833 "Should not emit dtor epilogue for trivial dtor!");
834
John McCall50da2ca2010-07-21 05:30:47 +0000835 // The deleting-destructor phase just needs to call the appropriate
836 // operator delete that Sema picked up.
John McCall3b477332010-02-18 19:59:28 +0000837 if (DtorType == Dtor_Deleting) {
838 assert(DD->getOperatorDelete() &&
839 "operator delete missing - EmitDtorEpilogue");
John McCall1f0fca52010-07-21 07:22:38 +0000840 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
John McCall3b477332010-02-18 19:59:28 +0000841 return;
842 }
843
John McCall50da2ca2010-07-21 05:30:47 +0000844 const CXXRecordDecl *ClassDecl = DD->getParent();
845
846 // The complete-destructor phase just destructs all the virtual bases.
John McCall3b477332010-02-18 19:59:28 +0000847 if (DtorType == Dtor_Complete) {
John McCall50da2ca2010-07-21 05:30:47 +0000848
849 // We push them in the forward order so that they'll be popped in
850 // the reverse order.
851 for (CXXRecordDecl::base_class_const_iterator I =
852 ClassDecl->vbases_begin(), E = ClassDecl->vbases_end();
John McCall3b477332010-02-18 19:59:28 +0000853 I != E; ++I) {
854 const CXXBaseSpecifier &Base = *I;
855 CXXRecordDecl *BaseClassDecl
856 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
857
858 // Ignore trivial destructors.
859 if (BaseClassDecl->hasTrivialDestructor())
860 continue;
John McCall50da2ca2010-07-21 05:30:47 +0000861
John McCall1f0fca52010-07-21 07:22:38 +0000862 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
863 BaseClassDecl,
864 /*BaseIsVirtual*/ true);
John McCall3b477332010-02-18 19:59:28 +0000865 }
John McCall50da2ca2010-07-21 05:30:47 +0000866
John McCall3b477332010-02-18 19:59:28 +0000867 return;
868 }
869
870 assert(DtorType == Dtor_Base);
John McCall50da2ca2010-07-21 05:30:47 +0000871
872 // Destroy non-virtual bases.
873 for (CXXRecordDecl::base_class_const_iterator I =
874 ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) {
875 const CXXBaseSpecifier &Base = *I;
876
877 // Ignore virtual bases.
878 if (Base.isVirtual())
879 continue;
880
881 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
882
883 // Ignore trivial destructors.
884 if (BaseClassDecl->hasTrivialDestructor())
885 continue;
John McCall3b477332010-02-18 19:59:28 +0000886
John McCall1f0fca52010-07-21 07:22:38 +0000887 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
888 BaseClassDecl,
889 /*BaseIsVirtual*/ false);
John McCall50da2ca2010-07-21 05:30:47 +0000890 }
891
892 // Destroy direct fields.
Anders Carlsson607d0372009-12-24 22:46:43 +0000893 llvm::SmallVector<const FieldDecl *, 16> FieldDecls;
894 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
895 E = ClassDecl->field_end(); I != E; ++I) {
896 const FieldDecl *Field = *I;
897
898 QualType FieldType = getContext().getCanonicalType(Field->getType());
John McCall50da2ca2010-07-21 05:30:47 +0000899 const ConstantArrayType *Array =
900 getContext().getAsConstantArrayType(FieldType);
901 if (Array)
902 FieldType = getContext().getBaseElementType(Array->getElementType());
Anders Carlsson607d0372009-12-24 22:46:43 +0000903
904 const RecordType *RT = FieldType->getAs<RecordType>();
905 if (!RT)
906 continue;
907
908 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
909 if (FieldClassDecl->hasTrivialDestructor())
910 continue;
John McCall50da2ca2010-07-21 05:30:47 +0000911
Anders Carlsson607d0372009-12-24 22:46:43 +0000912 if (Array)
John McCall1f0fca52010-07-21 07:22:38 +0000913 EHStack.pushCleanup<CallArrayFieldDtor>(NormalAndEHCleanup, Field);
John McCall50da2ca2010-07-21 05:30:47 +0000914 else
John McCall1f0fca52010-07-21 07:22:38 +0000915 EHStack.pushCleanup<CallFieldDtor>(NormalAndEHCleanup, Field);
Anders Carlsson607d0372009-12-24 22:46:43 +0000916 }
Anders Carlsson607d0372009-12-24 22:46:43 +0000917}
918
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000919/// EmitCXXAggrConstructorCall - This routine essentially creates a (nested)
920/// for-loop to call the default constructor on individual members of the
921/// array.
922/// 'D' is the default constructor for elements of the array, 'ArrayTy' is the
923/// array type and 'ArrayPtr' points to the beginning fo the array.
924/// It is assumed that all relevant checks have been made by the caller.
Douglas Gregor59174c02010-07-21 01:10:17 +0000925///
926/// \param ZeroInitialization True if each element should be zero-initialized
927/// before it is constructed.
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000928void
929CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
Douglas Gregor59174c02010-07-21 01:10:17 +0000930 const ConstantArrayType *ArrayTy,
931 llvm::Value *ArrayPtr,
932 CallExpr::const_arg_iterator ArgBeg,
933 CallExpr::const_arg_iterator ArgEnd,
934 bool ZeroInitialization) {
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000935
936 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
937 llvm::Value * NumElements =
938 llvm::ConstantInt::get(SizeTy,
939 getContext().getConstantArrayElementCount(ArrayTy));
940
Douglas Gregor59174c02010-07-21 01:10:17 +0000941 EmitCXXAggrConstructorCall(D, NumElements, ArrayPtr, ArgBeg, ArgEnd,
942 ZeroInitialization);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000943}
944
945void
946CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
947 llvm::Value *NumElements,
948 llvm::Value *ArrayPtr,
949 CallExpr::const_arg_iterator ArgBeg,
Douglas Gregor59174c02010-07-21 01:10:17 +0000950 CallExpr::const_arg_iterator ArgEnd,
951 bool ZeroInitialization) {
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000952 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
953
954 // Create a temporary for the loop index and initialize it with 0.
955 llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index");
956 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
957 Builder.CreateStore(Zero, IndexPtr);
958
959 // Start the loop with a block that tests the condition.
960 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
961 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
962
963 EmitBlock(CondBlock);
964
965 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
966
967 // Generate: if (loop-index < number-of-elements fall to the loop body,
968 // otherwise, go to the block after the for-loop.
969 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
970 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless");
971 // If the condition is true, execute the body.
972 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
973
974 EmitBlock(ForBody);
975
976 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
977 // Inside the loop body, emit the constructor call on the array element.
978 Counter = Builder.CreateLoad(IndexPtr);
979 llvm::Value *Address = Builder.CreateInBoundsGEP(ArrayPtr, Counter,
980 "arrayidx");
981
Douglas Gregor59174c02010-07-21 01:10:17 +0000982 // Zero initialize the storage, if requested.
983 if (ZeroInitialization)
984 EmitNullInitialization(Address,
985 getContext().getTypeDeclType(D->getParent()));
986
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000987 // C++ [class.temporary]p4:
988 // There are two contexts in which temporaries are destroyed at a different
989 // point than the end of the full-expression. The first context is when a
990 // default constructor is called to initialize an element of an array.
991 // If the constructor has one or more default arguments, the destruction of
992 // every temporary created in a default argument expression is sequenced
993 // before the construction of the next array element, if any.
994
995 // Keep track of the current number of live temporaries.
Anders Carlsson44ec82b2010-03-30 03:14:41 +0000996 {
John McCallf1549f62010-07-06 01:34:17 +0000997 RunCleanupsScope Scope(*this);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000998
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000999 EmitCXXConstructorCall(D, Ctor_Complete, /*ForVirtualBase=*/false, Address,
Anders Carlsson24eb78e2010-05-02 23:01:10 +00001000 ArgBeg, ArgEnd);
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001001 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001002
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001003 EmitBlock(ContinueBlock);
1004
1005 // Emit the increment of the loop counter.
1006 llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1);
1007 Counter = Builder.CreateLoad(IndexPtr);
1008 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1009 Builder.CreateStore(NextVal, IndexPtr);
1010
1011 // Finally, branch back up to the condition for the next iteration.
1012 EmitBranch(CondBlock);
1013
1014 // Emit the fall-through block.
1015 EmitBlock(AfterFor, true);
1016}
1017
1018/// EmitCXXAggrDestructorCall - calls the default destructor on array
1019/// elements in reverse order of construction.
1020void
1021CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
1022 const ArrayType *Array,
1023 llvm::Value *This) {
1024 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1025 assert(CA && "Do we support VLA for destruction ?");
1026 uint64_t ElementCount = getContext().getConstantArrayElementCount(CA);
1027
1028 const llvm::Type *SizeLTy = ConvertType(getContext().getSizeType());
1029 llvm::Value* ElementCountPtr = llvm::ConstantInt::get(SizeLTy, ElementCount);
1030 EmitCXXAggrDestructorCall(D, ElementCountPtr, This);
1031}
1032
1033/// EmitCXXAggrDestructorCall - calls the default destructor on array
1034/// elements in reverse order of construction.
1035void
1036CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
1037 llvm::Value *UpperCount,
1038 llvm::Value *This) {
1039 const llvm::Type *SizeLTy = ConvertType(getContext().getSizeType());
1040 llvm::Value *One = llvm::ConstantInt::get(SizeLTy, 1);
1041
1042 // Create a temporary for the loop index and initialize it with count of
1043 // array elements.
1044 llvm::Value *IndexPtr = CreateTempAlloca(SizeLTy, "loop.index");
1045
1046 // Store the number of elements in the index pointer.
1047 Builder.CreateStore(UpperCount, IndexPtr);
1048
1049 // Start the loop with a block that tests the condition.
1050 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1051 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1052
1053 EmitBlock(CondBlock);
1054
1055 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1056
1057 // Generate: if (loop-index != 0 fall to the loop body,
1058 // otherwise, go to the block after the for-loop.
1059 llvm::Value* zeroConstant =
1060 llvm::Constant::getNullValue(SizeLTy);
1061 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1062 llvm::Value *IsNE = Builder.CreateICmpNE(Counter, zeroConstant,
1063 "isne");
1064 // If the condition is true, execute the body.
1065 Builder.CreateCondBr(IsNE, ForBody, AfterFor);
1066
1067 EmitBlock(ForBody);
1068
1069 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1070 // Inside the loop body, emit the constructor call on the array element.
1071 Counter = Builder.CreateLoad(IndexPtr);
1072 Counter = Builder.CreateSub(Counter, One);
1073 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
Anders Carlsson8e6404c2010-05-02 23:29:11 +00001074 EmitCXXDestructorCall(D, Dtor_Complete, /*ForVirtualBase=*/false, Address);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001075
1076 EmitBlock(ContinueBlock);
1077
1078 // Emit the decrement of the loop counter.
1079 Counter = Builder.CreateLoad(IndexPtr);
1080 Counter = Builder.CreateSub(Counter, One, "dec");
1081 Builder.CreateStore(Counter, IndexPtr);
1082
1083 // Finally, branch back up to the condition for the next iteration.
1084 EmitBranch(CondBlock);
1085
1086 // Emit the fall-through block.
1087 EmitBlock(AfterFor, true);
1088}
1089
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001090void
1091CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
Anders Carlsson155ed4a2010-05-02 23:20:53 +00001092 CXXCtorType Type, bool ForVirtualBase,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001093 llvm::Value *This,
1094 CallExpr::const_arg_iterator ArgBeg,
1095 CallExpr::const_arg_iterator ArgEnd) {
John McCall8b6bbeb2010-02-06 00:25:16 +00001096 if (D->isTrivial()) {
1097 if (ArgBeg == ArgEnd) {
1098 // Trivial default constructor, no codegen required.
1099 assert(D->isDefaultConstructor() &&
1100 "trivial 0-arg ctor not a default ctor");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001101 return;
1102 }
John McCall8b6bbeb2010-02-06 00:25:16 +00001103
1104 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
1105 assert(D->isCopyConstructor() && "trivial 1-arg ctor not a copy ctor");
1106
John McCall8b6bbeb2010-02-06 00:25:16 +00001107 const Expr *E = (*ArgBeg);
1108 QualType Ty = E->getType();
1109 llvm::Value *Src = EmitLValue(E).getAddress();
1110 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001111 return;
1112 }
1113
Anders Carlsson314e6222010-05-02 23:33:10 +00001114 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(D, Type), ForVirtualBase);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001115 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
1116
Anders Carlssonc997d422010-01-02 01:01:18 +00001117 EmitCXXMemberCall(D, Callee, ReturnValueSlot(), This, VTT, ArgBeg, ArgEnd);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001118}
1119
John McCallc0bf4622010-02-23 00:48:20 +00001120void
1121CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1122 CXXCtorType CtorType,
1123 const FunctionArgList &Args) {
1124 CallArgList DelegateArgs;
1125
1126 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
1127 assert(I != E && "no parameters to constructor");
1128
1129 // this
1130 DelegateArgs.push_back(std::make_pair(RValue::get(LoadCXXThis()),
1131 I->second));
1132 ++I;
1133
1134 // vtt
Anders Carlsson314e6222010-05-02 23:33:10 +00001135 if (llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(Ctor, CtorType),
1136 /*ForVirtualBase=*/false)) {
John McCallc0bf4622010-02-23 00:48:20 +00001137 QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
1138 DelegateArgs.push_back(std::make_pair(RValue::get(VTT), VoidPP));
1139
Anders Carlssonaf440352010-03-23 04:11:45 +00001140 if (CodeGenVTables::needsVTTParameter(CurGD)) {
John McCallc0bf4622010-02-23 00:48:20 +00001141 assert(I != E && "cannot skip vtt parameter, already done with args");
1142 assert(I->second == VoidPP && "skipping parameter not of vtt type");
1143 ++I;
1144 }
1145 }
1146
1147 // Explicit arguments.
1148 for (; I != E; ++I) {
John McCallc0bf4622010-02-23 00:48:20 +00001149 const VarDecl *Param = I->first;
1150 QualType ArgType = Param->getType(); // because we're passing it to itself
John McCall27360712010-05-26 22:34:26 +00001151 RValue Arg = EmitDelegateCallArg(Param);
John McCallc0bf4622010-02-23 00:48:20 +00001152
1153 DelegateArgs.push_back(std::make_pair(Arg, ArgType));
1154 }
1155
1156 EmitCall(CGM.getTypes().getFunctionInfo(Ctor, CtorType),
1157 CGM.GetAddrOfCXXConstructor(Ctor, CtorType),
1158 ReturnValueSlot(), DelegateArgs, Ctor);
1159}
1160
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001161void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
1162 CXXDtorType Type,
Anders Carlsson8e6404c2010-05-02 23:29:11 +00001163 bool ForVirtualBase,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001164 llvm::Value *This) {
Anders Carlsson314e6222010-05-02 23:33:10 +00001165 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(DD, Type),
1166 ForVirtualBase);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001167 llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
1168
Anders Carlssonc997d422010-01-02 01:01:18 +00001169 EmitCXXMemberCall(DD, Callee, ReturnValueSlot(), This, VTT, 0, 0);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001170}
1171
John McCall291ae942010-07-21 01:41:18 +00001172namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001173 struct CallLocalDtor : EHScopeStack::Cleanup {
John McCall291ae942010-07-21 01:41:18 +00001174 const CXXDestructorDecl *Dtor;
1175 llvm::Value *Addr;
1176
1177 CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
1178 : Dtor(D), Addr(Addr) {}
1179
1180 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1181 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1182 /*ForVirtualBase=*/false, Addr);
1183 }
1184 };
1185}
1186
John McCall81407d42010-07-21 06:29:51 +00001187void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
1188 llvm::Value *Addr) {
John McCall1f0fca52010-07-21 07:22:38 +00001189 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
John McCall81407d42010-07-21 06:29:51 +00001190}
1191
John McCallf1549f62010-07-06 01:34:17 +00001192void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
1193 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
1194 if (!ClassDecl) return;
1195 if (ClassDecl->hasTrivialDestructor()) return;
1196
1197 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCall81407d42010-07-21 06:29:51 +00001198 PushDestructorCleanup(D, Addr);
John McCallf1549f62010-07-06 01:34:17 +00001199}
1200
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001201llvm::Value *
Anders Carlssonbb7e17b2010-01-31 01:36:53 +00001202CodeGenFunction::GetVirtualBaseClassOffset(llvm::Value *This,
1203 const CXXRecordDecl *ClassDecl,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001204 const CXXRecordDecl *BaseClassDecl) {
1205 const llvm::Type *Int8PtrTy =
1206 llvm::Type::getInt8Ty(VMContext)->getPointerTo();
1207
1208 llvm::Value *VTablePtr = Builder.CreateBitCast(This,
1209 Int8PtrTy->getPointerTo());
1210 VTablePtr = Builder.CreateLoad(VTablePtr, "vtable");
1211
Anders Carlssonbba16072010-03-11 07:15:17 +00001212 int64_t VBaseOffsetOffset =
Anders Carlssonaf440352010-03-23 04:11:45 +00001213 CGM.getVTables().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001214
1215 llvm::Value *VBaseOffsetPtr =
Anders Carlssonbba16072010-03-11 07:15:17 +00001216 Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset, "vbase.offset.ptr");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001217 const llvm::Type *PtrDiffTy =
1218 ConvertType(getContext().getPointerDiffType());
1219
1220 VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr,
1221 PtrDiffTy->getPointerTo());
1222
1223 llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1224
1225 return VBaseOffset;
1226}
1227
Anders Carlssond103f9f2010-03-28 19:40:00 +00001228void
1229CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001230 const CXXRecordDecl *NearestVBase,
Anders Carlsson42358402010-05-03 00:07:07 +00001231 uint64_t OffsetFromNearestVBase,
Anders Carlssond103f9f2010-03-28 19:40:00 +00001232 llvm::Constant *VTable,
1233 const CXXRecordDecl *VTableClass) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001234 const CXXRecordDecl *RD = Base.getBase();
1235
Anders Carlssond103f9f2010-03-28 19:40:00 +00001236 // Compute the address point.
Anders Carlssonc83f1062010-03-29 01:08:49 +00001237 llvm::Value *VTableAddressPoint;
Anders Carlsson851853d2010-03-29 02:38:51 +00001238
Anders Carlssonc83f1062010-03-29 01:08:49 +00001239 // Check if we need to use a vtable from the VTT.
Anders Carlsson851853d2010-03-29 02:38:51 +00001240 if (CodeGenVTables::needsVTTParameter(CurGD) &&
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001241 (RD->getNumVBases() || NearestVBase)) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001242 // Get the secondary vpointer index.
1243 uint64_t VirtualPointerIndex =
1244 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1245
1246 /// Load the VTT.
1247 llvm::Value *VTT = LoadCXXVTT();
1248 if (VirtualPointerIndex)
1249 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1250
1251 // And load the address point from the VTT.
1252 VTableAddressPoint = Builder.CreateLoad(VTT);
1253 } else {
Anders Carlsson64c9eca2010-03-29 02:08:26 +00001254 uint64_t AddressPoint = CGM.getVTables().getAddressPoint(Base, VTableClass);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001255 VTableAddressPoint =
Anders Carlssond103f9f2010-03-28 19:40:00 +00001256 Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001257 }
Anders Carlssond103f9f2010-03-28 19:40:00 +00001258
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001259 // Compute where to store the address point.
Anders Carlsson8246cc72010-05-03 00:29:58 +00001260 llvm::Value *VirtualOffset = 0;
1261 uint64_t NonVirtualOffset = 0;
Anders Carlsson3e79c302010-04-20 18:05:10 +00001262
1263 if (CodeGenVTables::needsVTTParameter(CurGD) && NearestVBase) {
1264 // We need to use the virtual base offset offset because the virtual base
1265 // might have a different offset in the most derived class.
Anders Carlsson8246cc72010-05-03 00:29:58 +00001266 VirtualOffset = GetVirtualBaseClassOffset(LoadCXXThis(), VTableClass,
1267 NearestVBase);
1268 NonVirtualOffset = OffsetFromNearestVBase / 8;
Anders Carlsson3e79c302010-04-20 18:05:10 +00001269 } else {
Anders Carlsson8246cc72010-05-03 00:29:58 +00001270 // We can just use the base offset in the complete class.
1271 NonVirtualOffset = Base.getBaseOffset() / 8;
Anders Carlsson3e79c302010-04-20 18:05:10 +00001272 }
Anders Carlsson8246cc72010-05-03 00:29:58 +00001273
1274 // Apply the offsets.
1275 llvm::Value *VTableField = LoadCXXThis();
1276
1277 if (NonVirtualOffset || VirtualOffset)
1278 VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
1279 NonVirtualOffset,
1280 VirtualOffset);
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001281
Anders Carlssond103f9f2010-03-28 19:40:00 +00001282 // Finally, store the address point.
1283 const llvm::Type *AddressPointPtrTy =
1284 VTableAddressPoint->getType()->getPointerTo();
1285 VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
1286 Builder.CreateStore(VTableAddressPoint, VTableField);
1287}
1288
Anders Carlsson603d6d12010-03-28 21:07:49 +00001289void
1290CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001291 const CXXRecordDecl *NearestVBase,
Anders Carlsson42358402010-05-03 00:07:07 +00001292 uint64_t OffsetFromNearestVBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001293 bool BaseIsNonVirtualPrimaryBase,
1294 llvm::Constant *VTable,
1295 const CXXRecordDecl *VTableClass,
1296 VisitedVirtualBasesSetTy& VBases) {
1297 // If this base is a non-virtual primary base the address point has already
1298 // been set.
1299 if (!BaseIsNonVirtualPrimaryBase) {
1300 // Initialize the vtable pointer for this base.
Anders Carlsson42358402010-05-03 00:07:07 +00001301 InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
1302 VTable, VTableClass);
Anders Carlsson603d6d12010-03-28 21:07:49 +00001303 }
1304
1305 const CXXRecordDecl *RD = Base.getBase();
1306
1307 // Traverse bases.
1308 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1309 E = RD->bases_end(); I != E; ++I) {
1310 CXXRecordDecl *BaseDecl
1311 = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1312
1313 // Ignore classes without a vtable.
1314 if (!BaseDecl->isDynamicClass())
1315 continue;
1316
1317 uint64_t BaseOffset;
Anders Carlsson42358402010-05-03 00:07:07 +00001318 uint64_t BaseOffsetFromNearestVBase;
Anders Carlsson14da9de2010-03-29 01:16:41 +00001319 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001320
1321 if (I->isVirtual()) {
1322 // Check if we've visited this virtual base before.
1323 if (!VBases.insert(BaseDecl))
1324 continue;
1325
1326 const ASTRecordLayout &Layout =
1327 getContext().getASTRecordLayout(VTableClass);
1328
Anders Carlsson603d6d12010-03-28 21:07:49 +00001329 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
Anders Carlsson42358402010-05-03 00:07:07 +00001330 BaseOffsetFromNearestVBase = 0;
Anders Carlsson14da9de2010-03-29 01:16:41 +00001331 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001332 } else {
1333 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1334
1335 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson42358402010-05-03 00:07:07 +00001336 BaseOffsetFromNearestVBase =
Anders Carlsson8246cc72010-05-03 00:29:58 +00001337 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson14da9de2010-03-29 01:16:41 +00001338 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001339 }
1340
1341 InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001342 I->isVirtual() ? BaseDecl : NearestVBase,
Anders Carlsson42358402010-05-03 00:07:07 +00001343 BaseOffsetFromNearestVBase,
Anders Carlsson14da9de2010-03-29 01:16:41 +00001344 BaseDeclIsNonVirtualPrimaryBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001345 VTable, VTableClass, VBases);
1346 }
1347}
1348
1349void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
1350 // Ignore classes without a vtable.
Anders Carlsson07036902010-03-26 04:39:42 +00001351 if (!RD->isDynamicClass())
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001352 return;
1353
Anders Carlsson07036902010-03-26 04:39:42 +00001354 // Get the VTable.
1355 llvm::Constant *VTable = CGM.getVTables().GetAddrOfVTable(RD);
Anders Carlsson5c6c1d92010-03-24 03:57:14 +00001356
Anders Carlsson603d6d12010-03-28 21:07:49 +00001357 // Initialize the vtable pointers for this class and all of its bases.
1358 VisitedVirtualBasesSetTy VBases;
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001359 InitializeVTablePointers(BaseSubobject(RD, 0), /*NearestVBase=*/0,
Anders Carlsson42358402010-05-03 00:07:07 +00001360 /*OffsetFromNearestVBase=*/0,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001361 /*BaseIsNonVirtualPrimaryBase=*/false,
1362 VTable, RD, VBases);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001363}