blob: 313ee57f7ff9f9afb03395da8010bc30d8aacfd9 [file] [log] [blame]
Anders Carlsson5b955922009-11-24 05:51:11 +00001//===--- CGClass.cpp - Emit LLVM Code for C++ classes ---------------------===//
Anders Carlsson5d58a1d2009-09-12 04:27:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with C++ code generation of classes
11//
12//===----------------------------------------------------------------------===//
13
Devang Pateld67ef0e2010-08-11 21:04:37 +000014#include "CGDebugInfo.h"
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000015#include "CodeGenFunction.h"
Anders Carlsson2f1986b2009-10-06 22:43:30 +000016#include "clang/AST/CXXInheritance.h"
John McCall7e1dff72010-09-17 02:31:44 +000017#include "clang/AST/EvaluatedExprVisitor.h"
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000018#include "clang/AST/RecordLayout.h"
John McCall9fc6a772010-02-19 09:25:03 +000019#include "clang/AST/StmtCXX.h"
Devang Patel3ee36af2011-02-22 20:55:26 +000020#include "clang/Frontend/CodeGenOptions.h"
Anders Carlsson2f1986b2009-10-06 22:43:30 +000021
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000022using namespace clang;
23using namespace CodeGen;
24
Ken Dyck55c02582011-03-22 00:53:26 +000025static CharUnits
Anders Carlsson34a2d382010-04-24 21:06:20 +000026ComputeNonVirtualBaseClassOffset(ASTContext &Context,
27 const CXXRecordDecl *DerivedClass,
John McCallf871d0c2010-08-07 06:22:56 +000028 CastExpr::path_const_iterator Start,
29 CastExpr::path_const_iterator End) {
Ken Dyck55c02582011-03-22 00:53:26 +000030 CharUnits Offset = CharUnits::Zero();
Anders Carlsson34a2d382010-04-24 21:06:20 +000031
32 const CXXRecordDecl *RD = DerivedClass;
33
John McCallf871d0c2010-08-07 06:22:56 +000034 for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
Anders Carlsson34a2d382010-04-24 21:06:20 +000035 const CXXBaseSpecifier *Base = *I;
36 assert(!Base->isVirtual() && "Should not see virtual bases here!");
37
38 // Get the layout.
39 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
40
41 const CXXRecordDecl *BaseDecl =
42 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
43
44 // Add the offset.
Ken Dyck55c02582011-03-22 00:53:26 +000045 Offset += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson34a2d382010-04-24 21:06:20 +000046
47 RD = BaseDecl;
48 }
49
Ken Dyck55c02582011-03-22 00:53:26 +000050 return Offset;
Anders Carlsson34a2d382010-04-24 21:06:20 +000051}
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000052
Anders Carlsson84080ec2009-09-29 03:13:20 +000053llvm::Constant *
Anders Carlssona04efdf2010-04-24 21:23:59 +000054CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +000055 CastExpr::path_const_iterator PathBegin,
56 CastExpr::path_const_iterator PathEnd) {
57 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssona04efdf2010-04-24 21:23:59 +000058
Ken Dyck55c02582011-03-22 00:53:26 +000059 CharUnits Offset =
John McCallf871d0c2010-08-07 06:22:56 +000060 ComputeNonVirtualBaseClassOffset(getContext(), ClassDecl,
61 PathBegin, PathEnd);
Ken Dyck55c02582011-03-22 00:53:26 +000062 if (Offset.isZero())
Anders Carlssona04efdf2010-04-24 21:23:59 +000063 return 0;
64
65 const llvm::Type *PtrDiffTy =
66 Types.ConvertType(getContext().getPointerDiffType());
67
Ken Dyck55c02582011-03-22 00:53:26 +000068 return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
Anders Carlsson84080ec2009-09-29 03:13:20 +000069}
70
Anders Carlsson8561a862010-04-24 23:01:49 +000071/// Gets the address of a direct base class within a complete object.
John McCallbff225e2010-02-16 04:15:37 +000072/// This should only be used for (1) non-virtual bases or (2) virtual bases
73/// when the type is known to be complete (e.g. in complete destructors).
74///
75/// The object pointed to by 'This' is assumed to be non-null.
76llvm::Value *
Anders Carlsson8561a862010-04-24 23:01:49 +000077CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(llvm::Value *This,
78 const CXXRecordDecl *Derived,
79 const CXXRecordDecl *Base,
80 bool BaseIsVirtual) {
John McCallbff225e2010-02-16 04:15:37 +000081 // 'this' must be a pointer (in some address space) to Derived.
82 assert(This->getType()->isPointerTy() &&
83 cast<llvm::PointerType>(This->getType())->getElementType()
84 == ConvertType(Derived));
85
86 // Compute the offset of the virtual base.
Ken Dyck5fff46b2011-03-22 01:21:15 +000087 CharUnits Offset;
John McCallbff225e2010-02-16 04:15:37 +000088 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
Anders Carlsson8561a862010-04-24 23:01:49 +000089 if (BaseIsVirtual)
Ken Dyck5fff46b2011-03-22 01:21:15 +000090 Offset = Layout.getVBaseClassOffset(Base);
John McCallbff225e2010-02-16 04:15:37 +000091 else
Ken Dyck5fff46b2011-03-22 01:21:15 +000092 Offset = Layout.getBaseClassOffset(Base);
John McCallbff225e2010-02-16 04:15:37 +000093
94 // Shift and cast down to the base type.
95 // TODO: for complete types, this should be possible with a GEP.
96 llvm::Value *V = This;
Ken Dyck5fff46b2011-03-22 01:21:15 +000097 if (Offset.isPositive()) {
John McCallbff225e2010-02-16 04:15:37 +000098 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
99 V = Builder.CreateBitCast(V, Int8PtrTy);
Ken Dyck5fff46b2011-03-22 01:21:15 +0000100 V = Builder.CreateConstInBoundsGEP1_64(V, Offset.getQuantity());
John McCallbff225e2010-02-16 04:15:37 +0000101 }
102 V = Builder.CreateBitCast(V, ConvertType(Base)->getPointerTo());
103
104 return V;
Anders Carlssond103f9f2010-03-28 19:40:00 +0000105}
John McCallbff225e2010-02-16 04:15:37 +0000106
Anders Carlsson9dc228a2010-04-20 16:03:35 +0000107static llvm::Value *
108ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, llvm::Value *ThisPtr,
Ken Dyck9a8ad9b2011-03-23 00:45:26 +0000109 CharUnits NonVirtual, llvm::Value *Virtual) {
Anders Carlsson9dc228a2010-04-20 16:03:35 +0000110 const llvm::Type *PtrDiffTy =
111 CGF.ConvertType(CGF.getContext().getPointerDiffType());
112
113 llvm::Value *NonVirtualOffset = 0;
Ken Dyck9a8ad9b2011-03-23 00:45:26 +0000114 if (!NonVirtual.isZero())
115 NonVirtualOffset = llvm::ConstantInt::get(PtrDiffTy,
116 NonVirtual.getQuantity());
Anders Carlsson9dc228a2010-04-20 16:03:35 +0000117
118 llvm::Value *BaseOffset;
119 if (Virtual) {
120 if (NonVirtualOffset)
121 BaseOffset = CGF.Builder.CreateAdd(Virtual, NonVirtualOffset);
122 else
123 BaseOffset = Virtual;
124 } else
125 BaseOffset = NonVirtualOffset;
126
127 // Apply the base offset.
128 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
129 ThisPtr = CGF.Builder.CreateBitCast(ThisPtr, Int8PtrTy);
130 ThisPtr = CGF.Builder.CreateGEP(ThisPtr, BaseOffset, "add.ptr");
131
132 return ThisPtr;
133}
134
Anders Carlsson5d58a1d2009-09-12 04:27:24 +0000135llvm::Value *
Anders Carlsson34a2d382010-04-24 21:06:20 +0000136CodeGenFunction::GetAddressOfBaseClass(llvm::Value *Value,
Anders Carlsson8561a862010-04-24 23:01:49 +0000137 const CXXRecordDecl *Derived,
John McCallf871d0c2010-08-07 06:22:56 +0000138 CastExpr::path_const_iterator PathBegin,
139 CastExpr::path_const_iterator PathEnd,
Anders Carlsson34a2d382010-04-24 21:06:20 +0000140 bool NullCheckValue) {
John McCallf871d0c2010-08-07 06:22:56 +0000141 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlsson34a2d382010-04-24 21:06:20 +0000142
John McCallf871d0c2010-08-07 06:22:56 +0000143 CastExpr::path_const_iterator Start = PathBegin;
Anders Carlsson34a2d382010-04-24 21:06:20 +0000144 const CXXRecordDecl *VBase = 0;
145
146 // Get the virtual base.
147 if ((*Start)->isVirtual()) {
148 VBase =
149 cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
150 ++Start;
151 }
152
Ken Dyck55c02582011-03-22 00:53:26 +0000153 CharUnits NonVirtualOffset =
Anders Carlsson8561a862010-04-24 23:01:49 +0000154 ComputeNonVirtualBaseClassOffset(getContext(), VBase ? VBase : Derived,
John McCallf871d0c2010-08-07 06:22:56 +0000155 Start, PathEnd);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000156
157 // Get the base pointer type.
158 const llvm::Type *BasePtrTy =
John McCallf871d0c2010-08-07 06:22:56 +0000159 ConvertType((PathEnd[-1])->getType())->getPointerTo();
Anders Carlsson34a2d382010-04-24 21:06:20 +0000160
Ken Dyck55c02582011-03-22 00:53:26 +0000161 if (NonVirtualOffset.isZero() && !VBase) {
Anders Carlsson34a2d382010-04-24 21:06:20 +0000162 // Just cast back.
163 return Builder.CreateBitCast(Value, BasePtrTy);
164 }
165
166 llvm::BasicBlock *CastNull = 0;
167 llvm::BasicBlock *CastNotNull = 0;
168 llvm::BasicBlock *CastEnd = 0;
169
170 if (NullCheckValue) {
171 CastNull = createBasicBlock("cast.null");
172 CastNotNull = createBasicBlock("cast.notnull");
173 CastEnd = createBasicBlock("cast.end");
174
Anders Carlssonb9241242011-04-11 00:30:07 +0000175 llvm::Value *IsNull = Builder.CreateIsNull(Value);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000176 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
177 EmitBlock(CastNotNull);
178 }
179
180 llvm::Value *VirtualOffset = 0;
181
Anders Carlsson336a7dc2011-01-29 03:18:56 +0000182 if (VBase) {
183 if (Derived->hasAttr<FinalAttr>()) {
184 VirtualOffset = 0;
185
186 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
187
Ken Dyck55c02582011-03-22 00:53:26 +0000188 CharUnits VBaseOffset = Layout.getVBaseClassOffset(VBase);
189 NonVirtualOffset += VBaseOffset;
Anders Carlsson336a7dc2011-01-29 03:18:56 +0000190 } else
191 VirtualOffset = GetVirtualBaseClassOffset(Value, Derived, VBase);
192 }
Anders Carlsson34a2d382010-04-24 21:06:20 +0000193
194 // Apply the offsets.
Ken Dyck55c02582011-03-22 00:53:26 +0000195 Value = ApplyNonVirtualAndVirtualOffset(*this, Value,
Ken Dyck9a8ad9b2011-03-23 00:45:26 +0000196 NonVirtualOffset,
Anders Carlsson34a2d382010-04-24 21:06:20 +0000197 VirtualOffset);
198
199 // Cast back.
200 Value = Builder.CreateBitCast(Value, BasePtrTy);
201
202 if (NullCheckValue) {
203 Builder.CreateBr(CastEnd);
204 EmitBlock(CastNull);
205 Builder.CreateBr(CastEnd);
206 EmitBlock(CastEnd);
207
Jay Foadbbf3bac2011-03-30 11:28:58 +0000208 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000209 PHI->addIncoming(Value, CastNotNull);
210 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
211 CastNull);
212 Value = PHI;
213 }
214
215 return Value;
216}
217
218llvm::Value *
Anders Carlssona3697c92009-11-23 17:57:54 +0000219CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value,
Anders Carlsson8561a862010-04-24 23:01:49 +0000220 const CXXRecordDecl *Derived,
John McCallf871d0c2010-08-07 06:22:56 +0000221 CastExpr::path_const_iterator PathBegin,
222 CastExpr::path_const_iterator PathEnd,
Anders Carlssona3697c92009-11-23 17:57:54 +0000223 bool NullCheckValue) {
John McCallf871d0c2010-08-07 06:22:56 +0000224 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssona04efdf2010-04-24 21:23:59 +0000225
Anders Carlssona3697c92009-11-23 17:57:54 +0000226 QualType DerivedTy =
Anders Carlsson8561a862010-04-24 23:01:49 +0000227 getContext().getCanonicalType(getContext().getTagDeclType(Derived));
Anders Carlssona3697c92009-11-23 17:57:54 +0000228 const llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
229
Anders Carlssona552ea72010-01-31 01:43:37 +0000230 llvm::Value *NonVirtualOffset =
John McCallf871d0c2010-08-07 06:22:56 +0000231 CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
Anders Carlssona552ea72010-01-31 01:43:37 +0000232
233 if (!NonVirtualOffset) {
234 // No offset, we can just cast back.
235 return Builder.CreateBitCast(Value, DerivedPtrTy);
236 }
237
Anders Carlssona3697c92009-11-23 17:57:54 +0000238 llvm::BasicBlock *CastNull = 0;
239 llvm::BasicBlock *CastNotNull = 0;
240 llvm::BasicBlock *CastEnd = 0;
241
242 if (NullCheckValue) {
243 CastNull = createBasicBlock("cast.null");
244 CastNotNull = createBasicBlock("cast.notnull");
245 CastEnd = createBasicBlock("cast.end");
246
Anders Carlssonb9241242011-04-11 00:30:07 +0000247 llvm::Value *IsNull = Builder.CreateIsNull(Value);
Anders Carlssona3697c92009-11-23 17:57:54 +0000248 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
249 EmitBlock(CastNotNull);
250 }
251
Anders Carlssona552ea72010-01-31 01:43:37 +0000252 // Apply the offset.
253 Value = Builder.CreatePtrToInt(Value, NonVirtualOffset->getType());
254 Value = Builder.CreateSub(Value, NonVirtualOffset);
255 Value = Builder.CreateIntToPtr(Value, DerivedPtrTy);
256
257 // Just cast.
258 Value = Builder.CreateBitCast(Value, DerivedPtrTy);
Anders Carlssona3697c92009-11-23 17:57:54 +0000259
260 if (NullCheckValue) {
261 Builder.CreateBr(CastEnd);
262 EmitBlock(CastNull);
263 Builder.CreateBr(CastEnd);
264 EmitBlock(CastEnd);
265
Jay Foadbbf3bac2011-03-30 11:28:58 +0000266 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
Anders Carlssona3697c92009-11-23 17:57:54 +0000267 PHI->addIncoming(Value, CastNotNull);
268 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
269 CastNull);
270 Value = PHI;
271 }
272
273 return Value;
Anders Carlsson5d58a1d2009-09-12 04:27:24 +0000274}
Anders Carlsson21c9ad92010-03-30 03:27:09 +0000275
Anders Carlssonc997d422010-01-02 01:01:18 +0000276/// GetVTTParameter - Return the VTT parameter that should be passed to a
277/// base constructor/destructor with virtual bases.
Anders Carlsson314e6222010-05-02 23:33:10 +0000278static llvm::Value *GetVTTParameter(CodeGenFunction &CGF, GlobalDecl GD,
279 bool ForVirtualBase) {
Anders Carlssonaf440352010-03-23 04:11:45 +0000280 if (!CodeGenVTables::needsVTTParameter(GD)) {
Anders Carlssonc997d422010-01-02 01:01:18 +0000281 // This constructor/destructor does not need a VTT parameter.
282 return 0;
283 }
284
285 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CGF.CurFuncDecl)->getParent();
286 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
John McCall3b477332010-02-18 19:59:28 +0000287
Anders Carlssonc997d422010-01-02 01:01:18 +0000288 llvm::Value *VTT;
289
John McCall3b477332010-02-18 19:59:28 +0000290 uint64_t SubVTTIndex;
291
292 // If the record matches the base, this is the complete ctor/dtor
293 // variant calling the base variant in a class with virtual bases.
294 if (RD == Base) {
Anders Carlssonaf440352010-03-23 04:11:45 +0000295 assert(!CodeGenVTables::needsVTTParameter(CGF.CurGD) &&
John McCall3b477332010-02-18 19:59:28 +0000296 "doing no-op VTT offset in base dtor/ctor?");
Anders Carlsson314e6222010-05-02 23:33:10 +0000297 assert(!ForVirtualBase && "Can't have same class as virtual base!");
John McCall3b477332010-02-18 19:59:28 +0000298 SubVTTIndex = 0;
299 } else {
Anders Carlssonc11bb212010-05-02 23:53:25 +0000300 const ASTRecordLayout &Layout =
301 CGF.getContext().getASTRecordLayout(RD);
Ken Dyck4230d522011-03-24 01:21:01 +0000302 CharUnits BaseOffset = ForVirtualBase ?
303 Layout.getVBaseClassOffset(Base) :
304 Layout.getBaseClassOffset(Base);
Anders Carlssonc11bb212010-05-02 23:53:25 +0000305
306 SubVTTIndex =
307 CGF.CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
John McCall3b477332010-02-18 19:59:28 +0000308 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
309 }
Anders Carlssonc997d422010-01-02 01:01:18 +0000310
Anders Carlssonaf440352010-03-23 04:11:45 +0000311 if (CodeGenVTables::needsVTTParameter(CGF.CurGD)) {
Anders Carlssonc997d422010-01-02 01:01:18 +0000312 // A VTT parameter was passed to the constructor, use it.
313 VTT = CGF.LoadCXXVTT();
314 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
315 } else {
316 // We're the complete constructor, so get the VTT by name.
Anders Carlsson1cbce122011-01-29 19:16:51 +0000317 VTT = CGF.CGM.getVTables().GetAddrOfVTT(RD);
Anders Carlssonc997d422010-01-02 01:01:18 +0000318 VTT = CGF.Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
319 }
320
321 return VTT;
322}
323
John McCall182ab512010-07-21 01:23:41 +0000324namespace {
John McCall50da2ca2010-07-21 05:30:47 +0000325 /// Call the destructor for a direct base class.
John McCall1f0fca52010-07-21 07:22:38 +0000326 struct CallBaseDtor : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000327 const CXXRecordDecl *BaseClass;
328 bool BaseIsVirtual;
329 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
330 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
John McCall182ab512010-07-21 01:23:41 +0000331
332 void Emit(CodeGenFunction &CGF, bool IsForEH) {
John McCall50da2ca2010-07-21 05:30:47 +0000333 const CXXRecordDecl *DerivedClass =
334 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
335
336 const CXXDestructorDecl *D = BaseClass->getDestructor();
337 llvm::Value *Addr =
338 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThis(),
339 DerivedClass, BaseClass,
340 BaseIsVirtual);
341 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual, Addr);
John McCall182ab512010-07-21 01:23:41 +0000342 }
343 };
John McCall7e1dff72010-09-17 02:31:44 +0000344
345 /// A visitor which checks whether an initializer uses 'this' in a
346 /// way which requires the vtable to be properly set.
347 struct DynamicThisUseChecker : EvaluatedExprVisitor<DynamicThisUseChecker> {
348 typedef EvaluatedExprVisitor<DynamicThisUseChecker> super;
349
350 bool UsesThis;
351
352 DynamicThisUseChecker(ASTContext &C) : super(C), UsesThis(false) {}
353
354 // Black-list all explicit and implicit references to 'this'.
355 //
356 // Do we need to worry about external references to 'this' derived
357 // from arbitrary code? If so, then anything which runs arbitrary
358 // external code might potentially access the vtable.
359 void VisitCXXThisExpr(CXXThisExpr *E) { UsesThis = true; }
360 };
361}
362
363static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
364 DynamicThisUseChecker Checker(C);
365 Checker.Visit(const_cast<Expr*>(Init));
366 return Checker.UsesThis;
John McCall182ab512010-07-21 01:23:41 +0000367}
368
Anders Carlsson607d0372009-12-24 22:46:43 +0000369static void EmitBaseInitializer(CodeGenFunction &CGF,
370 const CXXRecordDecl *ClassDecl,
Sean Huntcbb67482011-01-08 20:30:50 +0000371 CXXCtorInitializer *BaseInit,
Anders Carlsson607d0372009-12-24 22:46:43 +0000372 CXXCtorType CtorType) {
373 assert(BaseInit->isBaseInitializer() &&
374 "Must have base initializer!");
375
376 llvm::Value *ThisPtr = CGF.LoadCXXThis();
377
378 const Type *BaseType = BaseInit->getBaseClass();
379 CXXRecordDecl *BaseClassDecl =
380 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
381
Anders Carlsson80638c52010-04-12 00:51:03 +0000382 bool isBaseVirtual = BaseInit->isBaseVirtual();
Anders Carlsson607d0372009-12-24 22:46:43 +0000383
384 // The base constructor doesn't construct virtual bases.
385 if (CtorType == Ctor_Base && isBaseVirtual)
386 return;
387
John McCall7e1dff72010-09-17 02:31:44 +0000388 // If the initializer for the base (other than the constructor
389 // itself) accesses 'this' in any way, we need to initialize the
390 // vtables.
391 if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
392 CGF.InitializeVTablePointers(ClassDecl);
393
John McCallbff225e2010-02-16 04:15:37 +0000394 // We can pretend to be a complete class because it only matters for
395 // virtual bases, and we only do virtual bases for complete ctors.
Anders Carlsson8561a862010-04-24 23:01:49 +0000396 llvm::Value *V =
397 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
John McCall50da2ca2010-07-21 05:30:47 +0000398 BaseClassDecl,
399 isBaseVirtual);
John McCallbff225e2010-02-16 04:15:37 +0000400
John McCallf85e1932011-06-15 23:02:42 +0000401 AggValueSlot AggSlot = AggValueSlot::forAddr(V, Qualifiers(),
402 /*Lifetime*/ true);
John McCall558d2ab2010-09-15 10:14:12 +0000403
404 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
Anders Carlsson594d5e82010-02-06 20:00:21 +0000405
Anders Carlsson7a178512011-02-28 00:33:03 +0000406 if (CGF.CGM.getLangOptions().Exceptions &&
Anders Carlssonc1cfdf82011-02-20 00:20:27 +0000407 !BaseClassDecl->hasTrivialDestructor())
John McCall1f0fca52010-07-21 07:22:38 +0000408 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
409 isBaseVirtual);
Anders Carlsson607d0372009-12-24 22:46:43 +0000410}
411
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000412static void EmitAggMemberInitializer(CodeGenFunction &CGF,
413 LValue LHS,
414 llvm::Value *ArrayIndexVar,
Sean Huntcbb67482011-01-08 20:30:50 +0000415 CXXCtorInitializer *MemberInit,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000416 QualType T,
417 unsigned Index) {
418 if (Index == MemberInit->getNumArrayIndices()) {
John McCallf1549f62010-07-06 01:34:17 +0000419 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000420
421 llvm::Value *Dest = LHS.getAddress();
422 if (ArrayIndexVar) {
423 // If we have an array index variable, load it and use it as an offset.
424 // Then, increment the value.
425 llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar);
426 Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress");
427 llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1);
428 Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc");
429 CGF.Builder.CreateStore(Next, ArrayIndexVar);
430 }
John McCall558d2ab2010-09-15 10:14:12 +0000431
John McCallf85e1932011-06-15 23:02:42 +0000432 if (!CGF.hasAggregateLLVMType(T)) {
John McCalla07398e2011-06-16 04:16:24 +0000433 LValue lvalue = CGF.MakeAddrLValue(Dest, T);
434 CGF.EmitScalarInit(MemberInit->getInit(), /*decl*/ 0, lvalue, false);
John McCallf85e1932011-06-15 23:02:42 +0000435 } else if (T->isAnyComplexType()) {
436 CGF.EmitComplexExprIntoAddr(MemberInit->getInit(), Dest,
437 LHS.isVolatileQualified());
438 } else {
439 AggValueSlot Slot = AggValueSlot::forAddr(Dest, LHS.getQuals(),
440 /*Lifetime*/ true);
441
442 CGF.EmitAggExpr(MemberInit->getInit(), Slot);
443 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000444
445 return;
446 }
447
448 const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T);
449 assert(Array && "Array initialization without the array type?");
450 llvm::Value *IndexVar
451 = CGF.GetAddrOfLocalVar(MemberInit->getArrayIndex(Index));
452 assert(IndexVar && "Array index variable not loaded");
453
454 // Initialize this index variable to zero.
455 llvm::Value* Zero
456 = llvm::Constant::getNullValue(
457 CGF.ConvertType(CGF.getContext().getSizeType()));
458 CGF.Builder.CreateStore(Zero, IndexVar);
459
460 // Start the loop with a block that tests the condition.
461 llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond");
462 llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end");
463
464 CGF.EmitBlock(CondBlock);
465
466 llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body");
467 // Generate: if (loop-index < number-of-elements) fall to the loop body,
468 // otherwise, go to the block after the for-loop.
469 uint64_t NumElements = Array->getSize().getZExtValue();
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000470 llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
Chris Lattner985f7392010-05-06 06:35:23 +0000471 llvm::Value *NumElementsPtr =
472 llvm::ConstantInt::get(Counter->getType(), NumElements);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000473 llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr,
474 "isless");
475
476 // If the condition is true, execute the body.
477 CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor);
478
479 CGF.EmitBlock(ForBody);
480 llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc");
481
482 {
John McCallf1549f62010-07-06 01:34:17 +0000483 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000484
485 // Inside the loop body recurse to emit the inner loop or, eventually, the
486 // constructor call.
487 EmitAggMemberInitializer(CGF, LHS, ArrayIndexVar, MemberInit,
488 Array->getElementType(), Index + 1);
489 }
490
491 CGF.EmitBlock(ContinueBlock);
492
493 // Emit the increment of the loop counter.
494 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
495 Counter = CGF.Builder.CreateLoad(IndexVar);
496 NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc");
497 CGF.Builder.CreateStore(NextVal, IndexVar);
498
499 // Finally, branch back up to the condition for the next iteration.
500 CGF.EmitBranch(CondBlock);
501
502 // Emit the fall-through block.
503 CGF.EmitBlock(AfterFor, true);
504}
John McCall182ab512010-07-21 01:23:41 +0000505
506namespace {
John McCall1f0fca52010-07-21 07:22:38 +0000507 struct CallMemberDtor : EHScopeStack::Cleanup {
John McCall182ab512010-07-21 01:23:41 +0000508 FieldDecl *Field;
509 CXXDestructorDecl *Dtor;
510
511 CallMemberDtor(FieldDecl *Field, CXXDestructorDecl *Dtor)
512 : Field(Field), Dtor(Dtor) {}
513
514 void Emit(CodeGenFunction &CGF, bool IsForEH) {
515 // FIXME: Is this OK for C++0x delegating constructors?
516 llvm::Value *ThisPtr = CGF.LoadCXXThis();
517 LValue LHS = CGF.EmitLValueForField(ThisPtr, Field, 0);
518
519 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
520 LHS.getAddress());
521 }
522 };
523}
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000524
Anders Carlsson607d0372009-12-24 22:46:43 +0000525static void EmitMemberInitializer(CodeGenFunction &CGF,
526 const CXXRecordDecl *ClassDecl,
Sean Huntcbb67482011-01-08 20:30:50 +0000527 CXXCtorInitializer *MemberInit,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000528 const CXXConstructorDecl *Constructor,
529 FunctionArgList &Args) {
Francois Pichet00eb3f92010-12-04 09:14:42 +0000530 assert(MemberInit->isAnyMemberInitializer() &&
Anders Carlsson607d0372009-12-24 22:46:43 +0000531 "Must have member initializer!");
Richard Smith7a614d82011-06-11 17:19:42 +0000532 assert(MemberInit->getInit() && "Must have initializer!");
Anders Carlsson607d0372009-12-24 22:46:43 +0000533
534 // non-static data member initializers.
Francois Pichet00eb3f92010-12-04 09:14:42 +0000535 FieldDecl *Field = MemberInit->getAnyMember();
Anders Carlsson607d0372009-12-24 22:46:43 +0000536 QualType FieldType = CGF.getContext().getCanonicalType(Field->getType());
537
538 llvm::Value *ThisPtr = CGF.LoadCXXThis();
John McCalla9976d32010-05-21 01:18:57 +0000539 LValue LHS;
Anders Carlsson06a29702010-01-29 05:24:29 +0000540
Anders Carlsson607d0372009-12-24 22:46:43 +0000541 // If we are initializing an anonymous union field, drill down to the field.
Francois Pichet00eb3f92010-12-04 09:14:42 +0000542 if (MemberInit->isIndirectMemberInitializer()) {
543 LHS = CGF.EmitLValueForAnonRecordField(ThisPtr,
544 MemberInit->getIndirectMember(), 0);
545 FieldType = MemberInit->getIndirectMember()->getAnonField()->getType();
John McCalla9976d32010-05-21 01:18:57 +0000546 } else {
547 LHS = CGF.EmitLValueForFieldInitialization(ThisPtr, Field, 0);
Anders Carlsson607d0372009-12-24 22:46:43 +0000548 }
549
Sean Huntcbb67482011-01-08 20:30:50 +0000550 // FIXME: If there's no initializer and the CXXCtorInitializer
Douglas Gregor9db7dbb2010-01-31 09:12:51 +0000551 // was implicitly generated, we shouldn't be zeroing memory.
John McCallf85e1932011-06-15 23:02:42 +0000552 if (FieldType->isArrayType() && !MemberInit->getInit()) {
Anders Carlsson1884eb02010-05-22 17:35:42 +0000553 CGF.EmitNullInitialization(LHS.getAddress(), Field->getType());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +0000554 } else if (!CGF.hasAggregateLLVMType(Field->getType())) {
John McCallf85e1932011-06-15 23:02:42 +0000555 if (LHS.isSimple()) {
John McCalla07398e2011-06-16 04:16:24 +0000556 CGF.EmitExprAsInit(MemberInit->getInit(), Field, LHS, false);
John McCallf85e1932011-06-15 23:02:42 +0000557 } else {
558 RValue RHS = RValue::get(CGF.EmitScalarExpr(MemberInit->getInit()));
John McCall545d9962011-06-25 02:11:03 +0000559 CGF.EmitStoreThroughLValue(RHS, LHS);
John McCallf85e1932011-06-15 23:02:42 +0000560 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +0000561 } else if (MemberInit->getInit()->getType()->isAnyComplexType()) {
562 CGF.EmitComplexExprIntoAddr(MemberInit->getInit(), LHS.getAddress(),
Anders Carlsson607d0372009-12-24 22:46:43 +0000563 LHS.isVolatileQualified());
564 } else {
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000565 llvm::Value *ArrayIndexVar = 0;
566 const ConstantArrayType *Array
567 = CGF.getContext().getAsConstantArrayType(FieldType);
568 if (Array && Constructor->isImplicit() &&
569 Constructor->isCopyConstructor()) {
570 const llvm::Type *SizeTy
571 = CGF.ConvertType(CGF.getContext().getSizeType());
572
573 // The LHS is a pointer to the first object we'll be constructing, as
574 // a flat array.
575 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
576 const llvm::Type *BasePtr = CGF.ConvertType(BaseElementTy);
577 BasePtr = llvm::PointerType::getUnqual(BasePtr);
578 llvm::Value *BaseAddrPtr = CGF.Builder.CreateBitCast(LHS.getAddress(),
579 BasePtr);
Daniel Dunbar9f553f52010-08-21 03:08:16 +0000580 LHS = CGF.MakeAddrLValue(BaseAddrPtr, BaseElementTy);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000581
582 // Create an array index that will be used to walk over all of the
583 // objects we're constructing.
584 ArrayIndexVar = CGF.CreateTempAlloca(SizeTy, "object.index");
585 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
586 CGF.Builder.CreateStore(Zero, ArrayIndexVar);
587
John McCallf85e1932011-06-15 23:02:42 +0000588 // If we are copying an array of PODs or classes with trivial copy
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000589 // constructors, perform a single aggregate copy.
John McCallf85e1932011-06-15 23:02:42 +0000590 const CXXRecordDecl *Record = BaseElementTy->getAsCXXRecordDecl();
591 if (BaseElementTy.isPODType(CGF.getContext()) ||
592 (Record && Record->hasTrivialCopyConstructor())) {
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000593 // Find the source pointer. We knows it's the last argument because
594 // we know we're in a copy constructor.
595 unsigned SrcArgIndex = Args.size() - 1;
596 llvm::Value *SrcPtr
John McCalld26bc762011-03-09 04:27:21 +0000597 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000598 LValue Src = CGF.EmitLValueForFieldInitialization(SrcPtr, Field, 0);
599
600 // Copy the aggregate.
601 CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
602 LHS.isVolatileQualified());
603 return;
604 }
605
606 // Emit the block variables for the array indices, if any.
607 for (unsigned I = 0, N = MemberInit->getNumArrayIndices(); I != N; ++I)
John McCallb6bbcc92010-10-15 04:57:14 +0000608 CGF.EmitAutoVarDecl(*MemberInit->getArrayIndex(I));
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000609 }
610
611 EmitAggMemberInitializer(CGF, LHS, ArrayIndexVar, MemberInit, FieldType, 0);
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000612
Anders Carlsson7a178512011-02-28 00:33:03 +0000613 if (!CGF.CGM.getLangOptions().Exceptions)
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000614 return;
615
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000616 // FIXME: If we have an array of classes w/ non-trivial destructors,
617 // we need to destroy in reverse order of construction along the exception
618 // path.
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000619 const RecordType *RT = FieldType->getAs<RecordType>();
620 if (!RT)
621 return;
622
623 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall182ab512010-07-21 01:23:41 +0000624 if (!RD->hasTrivialDestructor())
John McCall1f0fca52010-07-21 07:22:38 +0000625 CGF.EHStack.pushCleanup<CallMemberDtor>(EHCleanup, Field,
626 RD->getDestructor());
Anders Carlsson607d0372009-12-24 22:46:43 +0000627 }
628}
629
John McCallc0bf4622010-02-23 00:48:20 +0000630/// Checks whether the given constructor is a valid subject for the
631/// complete-to-base constructor delegation optimization, i.e.
632/// emitting the complete constructor as a simple call to the base
633/// constructor.
634static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
635
636 // Currently we disable the optimization for classes with virtual
637 // bases because (1) the addresses of parameter variables need to be
638 // consistent across all initializers but (2) the delegate function
639 // call necessarily creates a second copy of the parameter variable.
640 //
641 // The limiting example (purely theoretical AFAIK):
642 // struct A { A(int &c) { c++; } };
643 // struct B : virtual A {
644 // B(int count) : A(count) { printf("%d\n", count); }
645 // };
646 // ...although even this example could in principle be emitted as a
647 // delegation since the address of the parameter doesn't escape.
648 if (Ctor->getParent()->getNumVBases()) {
649 // TODO: white-list trivial vbase initializers. This case wouldn't
650 // be subject to the restrictions below.
651
652 // TODO: white-list cases where:
653 // - there are no non-reference parameters to the constructor
654 // - the initializers don't access any non-reference parameters
655 // - the initializers don't take the address of non-reference
656 // parameters
657 // - etc.
658 // If we ever add any of the above cases, remember that:
659 // - function-try-blocks will always blacklist this optimization
660 // - we need to perform the constructor prologue and cleanup in
661 // EmitConstructorBody.
662
663 return false;
664 }
665
666 // We also disable the optimization for variadic functions because
667 // it's impossible to "re-pass" varargs.
668 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
669 return false;
670
Sean Hunt059ce0d2011-05-01 07:04:31 +0000671 // FIXME: Decide if we can do a delegation of a delegating constructor.
672 if (Ctor->isDelegatingConstructor())
673 return false;
674
John McCallc0bf4622010-02-23 00:48:20 +0000675 return true;
676}
677
John McCall9fc6a772010-02-19 09:25:03 +0000678/// EmitConstructorBody - Emits the body of the current constructor.
679void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
680 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
681 CXXCtorType CtorType = CurGD.getCtorType();
682
John McCallc0bf4622010-02-23 00:48:20 +0000683 // Before we go any further, try the complete->base constructor
684 // delegation optimization.
685 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor)) {
Devang Pateld67ef0e2010-08-11 21:04:37 +0000686 if (CGDebugInfo *DI = getDebugInfo())
687 DI->EmitStopPoint(Builder);
John McCallc0bf4622010-02-23 00:48:20 +0000688 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args);
689 return;
690 }
691
John McCall9fc6a772010-02-19 09:25:03 +0000692 Stmt *Body = Ctor->getBody();
693
John McCallc0bf4622010-02-23 00:48:20 +0000694 // Enter the function-try-block before the constructor prologue if
695 // applicable.
John McCallc0bf4622010-02-23 00:48:20 +0000696 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallc0bf4622010-02-23 00:48:20 +0000697 if (IsTryBody)
John McCall59a70002010-07-07 06:56:46 +0000698 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000699
John McCallf1549f62010-07-06 01:34:17 +0000700 EHScopeStack::stable_iterator CleanupDepth = EHStack.stable_begin();
John McCall9fc6a772010-02-19 09:25:03 +0000701
John McCallc0bf4622010-02-23 00:48:20 +0000702 // Emit the constructor prologue, i.e. the base and member
703 // initializers.
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000704 EmitCtorPrologue(Ctor, CtorType, Args);
John McCall9fc6a772010-02-19 09:25:03 +0000705
706 // Emit the body of the statement.
John McCallc0bf4622010-02-23 00:48:20 +0000707 if (IsTryBody)
John McCall9fc6a772010-02-19 09:25:03 +0000708 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
709 else if (Body)
710 EmitStmt(Body);
John McCall9fc6a772010-02-19 09:25:03 +0000711
712 // Emit any cleanup blocks associated with the member or base
713 // initializers, which includes (along the exceptional path) the
714 // destructors for those members and bases that were fully
715 // constructed.
John McCallf1549f62010-07-06 01:34:17 +0000716 PopCleanupBlocks(CleanupDepth);
John McCall9fc6a772010-02-19 09:25:03 +0000717
John McCallc0bf4622010-02-23 00:48:20 +0000718 if (IsTryBody)
John McCall59a70002010-07-07 06:56:46 +0000719 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000720}
721
Anders Carlsson607d0372009-12-24 22:46:43 +0000722/// EmitCtorPrologue - This routine generates necessary code to initialize
723/// base classes and non-static data members belonging to this constructor.
Anders Carlsson607d0372009-12-24 22:46:43 +0000724void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000725 CXXCtorType CtorType,
726 FunctionArgList &Args) {
Sean Hunt059ce0d2011-05-01 07:04:31 +0000727 if (CD->isDelegatingConstructor())
728 return EmitDelegatingCXXConstructorCall(CD, Args);
729
Anders Carlsson607d0372009-12-24 22:46:43 +0000730 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000731
Sean Huntcbb67482011-01-08 20:30:50 +0000732 llvm::SmallVector<CXXCtorInitializer *, 8> MemberInitializers;
Anders Carlsson607d0372009-12-24 22:46:43 +0000733
Anders Carlsson607d0372009-12-24 22:46:43 +0000734 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
735 E = CD->init_end();
736 B != E; ++B) {
Sean Huntcbb67482011-01-08 20:30:50 +0000737 CXXCtorInitializer *Member = (*B);
Anders Carlsson607d0372009-12-24 22:46:43 +0000738
Sean Huntd49bd552011-05-03 20:19:28 +0000739 if (Member->isBaseInitializer()) {
Anders Carlsson607d0372009-12-24 22:46:43 +0000740 EmitBaseInitializer(*this, ClassDecl, Member, CtorType);
Sean Huntd49bd552011-05-03 20:19:28 +0000741 } else {
742 assert(Member->isAnyMemberInitializer() &&
743 "Delegating initializer on non-delegating constructor");
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000744 MemberInitializers.push_back(Member);
Sean Huntd49bd552011-05-03 20:19:28 +0000745 }
Anders Carlsson607d0372009-12-24 22:46:43 +0000746 }
747
Anders Carlsson603d6d12010-03-28 21:07:49 +0000748 InitializeVTablePointers(ClassDecl);
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000749
John McCallf1549f62010-07-06 01:34:17 +0000750 for (unsigned I = 0, E = MemberInitializers.size(); I != E; ++I)
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000751 EmitMemberInitializer(*this, ClassDecl, MemberInitializers[I], CD, Args);
Anders Carlsson607d0372009-12-24 22:46:43 +0000752}
753
Anders Carlssonadf5dc32011-05-15 17:36:21 +0000754static bool
755FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
756
757static bool
758HasTrivialDestructorBody(ASTContext &Context,
759 const CXXRecordDecl *BaseClassDecl,
760 const CXXRecordDecl *MostDerivedClassDecl)
761{
762 // If the destructor is trivial we don't have to check anything else.
763 if (BaseClassDecl->hasTrivialDestructor())
764 return true;
765
766 if (!BaseClassDecl->getDestructor()->hasTrivialBody())
767 return false;
768
769 // Check fields.
770 for (CXXRecordDecl::field_iterator I = BaseClassDecl->field_begin(),
771 E = BaseClassDecl->field_end(); I != E; ++I) {
772 const FieldDecl *Field = *I;
773
774 if (!FieldHasTrivialDestructorBody(Context, Field))
775 return false;
776 }
777
778 // Check non-virtual bases.
779 for (CXXRecordDecl::base_class_const_iterator I =
780 BaseClassDecl->bases_begin(), E = BaseClassDecl->bases_end();
781 I != E; ++I) {
782 if (I->isVirtual())
783 continue;
784
785 const CXXRecordDecl *NonVirtualBase =
786 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
787 if (!HasTrivialDestructorBody(Context, NonVirtualBase,
788 MostDerivedClassDecl))
789 return false;
790 }
791
792 if (BaseClassDecl == MostDerivedClassDecl) {
793 // Check virtual bases.
794 for (CXXRecordDecl::base_class_const_iterator I =
795 BaseClassDecl->vbases_begin(), E = BaseClassDecl->vbases_end();
796 I != E; ++I) {
797 const CXXRecordDecl *VirtualBase =
798 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
799 if (!HasTrivialDestructorBody(Context, VirtualBase,
800 MostDerivedClassDecl))
801 return false;
802 }
803 }
804
805 return true;
806}
807
808static bool
809FieldHasTrivialDestructorBody(ASTContext &Context,
810 const FieldDecl *Field)
811{
812 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
813
814 const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
815 if (!RT)
816 return true;
817
818 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
819 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
820}
821
Anders Carlssonffb945f2011-05-14 23:26:09 +0000822/// CanSkipVTablePointerInitialization - Check whether we need to initialize
823/// any vtable pointers before calling this destructor.
824static bool CanSkipVTablePointerInitialization(ASTContext &Context,
Anders Carlssone3d6cf22011-05-16 04:08:36 +0000825 const CXXDestructorDecl *Dtor) {
Anders Carlssonffb945f2011-05-14 23:26:09 +0000826 if (!Dtor->hasTrivialBody())
827 return false;
828
829 // Check the fields.
830 const CXXRecordDecl *ClassDecl = Dtor->getParent();
831 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
832 E = ClassDecl->field_end(); I != E; ++I) {
833 const FieldDecl *Field = *I;
Anders Carlssonffb945f2011-05-14 23:26:09 +0000834
Anders Carlssonadf5dc32011-05-15 17:36:21 +0000835 if (!FieldHasTrivialDestructorBody(Context, Field))
836 return false;
Anders Carlssonffb945f2011-05-14 23:26:09 +0000837 }
838
839 return true;
840}
841
John McCall9fc6a772010-02-19 09:25:03 +0000842/// EmitDestructorBody - Emits the body of the current destructor.
843void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
844 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
845 CXXDtorType DtorType = CurGD.getDtorType();
846
John McCall50da2ca2010-07-21 05:30:47 +0000847 // The call to operator delete in a deleting destructor happens
848 // outside of the function-try-block, which means it's always
849 // possible to delegate the destructor body to the complete
850 // destructor. Do so.
851 if (DtorType == Dtor_Deleting) {
852 EnterDtorCleanups(Dtor, Dtor_Deleting);
853 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
854 LoadCXXThis());
855 PopCleanupBlock();
856 return;
857 }
858
John McCall9fc6a772010-02-19 09:25:03 +0000859 Stmt *Body = Dtor->getBody();
860
861 // If the body is a function-try-block, enter the try before
John McCall50da2ca2010-07-21 05:30:47 +0000862 // anything else.
863 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCall9fc6a772010-02-19 09:25:03 +0000864 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +0000865 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000866
John McCall50da2ca2010-07-21 05:30:47 +0000867 // Enter the epilogue cleanups.
868 RunCleanupsScope DtorEpilogue(*this);
869
John McCall9fc6a772010-02-19 09:25:03 +0000870 // If this is the complete variant, just invoke the base variant;
871 // the epilogue will destruct the virtual bases. But we can't do
872 // this optimization if the body is a function-try-block, because
873 // we'd introduce *two* handler blocks.
John McCall50da2ca2010-07-21 05:30:47 +0000874 switch (DtorType) {
875 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
876
877 case Dtor_Complete:
878 // Enter the cleanup scopes for virtual bases.
879 EnterDtorCleanups(Dtor, Dtor_Complete);
880
881 if (!isTryBody) {
882 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
883 LoadCXXThis());
884 break;
885 }
886 // Fallthrough: act like we're in the base variant.
John McCall9fc6a772010-02-19 09:25:03 +0000887
John McCall50da2ca2010-07-21 05:30:47 +0000888 case Dtor_Base:
889 // Enter the cleanup scopes for fields and non-virtual bases.
890 EnterDtorCleanups(Dtor, Dtor_Base);
891
892 // Initialize the vtable pointers before entering the body.
Anders Carlssonffb945f2011-05-14 23:26:09 +0000893 if (!CanSkipVTablePointerInitialization(getContext(), Dtor))
894 InitializeVTablePointers(Dtor->getParent());
John McCall50da2ca2010-07-21 05:30:47 +0000895
896 if (isTryBody)
897 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
898 else if (Body)
899 EmitStmt(Body);
900 else {
901 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
902 // nothing to do besides what's in the epilogue
903 }
Fariborz Jahanian5abec142011-02-02 23:12:46 +0000904 // -fapple-kext must inline any call to this dtor into
905 // the caller's body.
906 if (getContext().getLangOptions().AppleKext)
907 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
John McCall50da2ca2010-07-21 05:30:47 +0000908 break;
John McCall9fc6a772010-02-19 09:25:03 +0000909 }
910
John McCall50da2ca2010-07-21 05:30:47 +0000911 // Jump out through the epilogue cleanups.
912 DtorEpilogue.ForceCleanup();
John McCall9fc6a772010-02-19 09:25:03 +0000913
914 // Exit the try if applicable.
915 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +0000916 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000917}
918
John McCall50da2ca2010-07-21 05:30:47 +0000919namespace {
920 /// Call the operator delete associated with the current destructor.
John McCall1f0fca52010-07-21 07:22:38 +0000921 struct CallDtorDelete : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000922 CallDtorDelete() {}
923
924 void Emit(CodeGenFunction &CGF, bool IsForEH) {
925 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
926 const CXXRecordDecl *ClassDecl = Dtor->getParent();
927 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
928 CGF.getContext().getTagDeclType(ClassDecl));
929 }
930 };
931
John McCall1f0fca52010-07-21 07:22:38 +0000932 struct CallArrayFieldDtor : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000933 const FieldDecl *Field;
934 CallArrayFieldDtor(const FieldDecl *Field) : Field(Field) {}
935
936 void Emit(CodeGenFunction &CGF, bool IsForEH) {
John McCallf85e1932011-06-15 23:02:42 +0000937 QualType FieldType = Field->getType();
938 QualType BaseType = CGF.getContext().getBaseElementType(FieldType);
John McCall50da2ca2010-07-21 05:30:47 +0000939 const CXXRecordDecl *FieldClassDecl = BaseType->getAsCXXRecordDecl();
940
941 llvm::Value *ThisPtr = CGF.LoadCXXThis();
942 LValue LHS = CGF.EmitLValueForField(ThisPtr, Field,
943 // FIXME: Qualifiers?
944 /*CVRQualifiers=*/0);
945
John McCallf85e1932011-06-15 23:02:42 +0000946 const llvm::Type *BasePtr
947 = CGF.ConvertType(BaseType)->getPointerTo();
948 llvm::Value *BaseAddrPtr
949 = CGF.Builder.CreateBitCast(LHS.getAddress(), BasePtr);
950 const ConstantArrayType *Array
951 = CGF.getContext().getAsConstantArrayType(FieldType);
John McCall50da2ca2010-07-21 05:30:47 +0000952 CGF.EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(),
953 Array, BaseAddrPtr);
954 }
955 };
956
John McCall1f0fca52010-07-21 07:22:38 +0000957 struct CallFieldDtor : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000958 const FieldDecl *Field;
959 CallFieldDtor(const FieldDecl *Field) : Field(Field) {}
960
961 void Emit(CodeGenFunction &CGF, bool IsForEH) {
962 const CXXRecordDecl *FieldClassDecl =
963 Field->getType()->getAsCXXRecordDecl();
964
965 llvm::Value *ThisPtr = CGF.LoadCXXThis();
966 LValue LHS = CGF.EmitLValueForField(ThisPtr, Field,
967 // FIXME: Qualifiers?
968 /*CVRQualifiers=*/0);
969
970 CGF.EmitCXXDestructorCall(FieldClassDecl->getDestructor(),
971 Dtor_Complete, /*ForVirtualBase=*/false,
972 LHS.getAddress());
973 }
974 };
975}
976
Anders Carlsson607d0372009-12-24 22:46:43 +0000977/// EmitDtorEpilogue - Emit all code that comes at the end of class's
978/// destructor. This is to call destructors on members and base classes
979/// in reverse order of their construction.
John McCall50da2ca2010-07-21 05:30:47 +0000980void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
981 CXXDtorType DtorType) {
Anders Carlsson607d0372009-12-24 22:46:43 +0000982 assert(!DD->isTrivial() &&
983 "Should not emit dtor epilogue for trivial dtor!");
984
John McCall50da2ca2010-07-21 05:30:47 +0000985 // The deleting-destructor phase just needs to call the appropriate
986 // operator delete that Sema picked up.
John McCall3b477332010-02-18 19:59:28 +0000987 if (DtorType == Dtor_Deleting) {
988 assert(DD->getOperatorDelete() &&
989 "operator delete missing - EmitDtorEpilogue");
John McCall1f0fca52010-07-21 07:22:38 +0000990 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
John McCall3b477332010-02-18 19:59:28 +0000991 return;
992 }
993
John McCall50da2ca2010-07-21 05:30:47 +0000994 const CXXRecordDecl *ClassDecl = DD->getParent();
995
996 // The complete-destructor phase just destructs all the virtual bases.
John McCall3b477332010-02-18 19:59:28 +0000997 if (DtorType == Dtor_Complete) {
John McCall50da2ca2010-07-21 05:30:47 +0000998
999 // We push them in the forward order so that they'll be popped in
1000 // the reverse order.
1001 for (CXXRecordDecl::base_class_const_iterator I =
1002 ClassDecl->vbases_begin(), E = ClassDecl->vbases_end();
John McCall3b477332010-02-18 19:59:28 +00001003 I != E; ++I) {
1004 const CXXBaseSpecifier &Base = *I;
1005 CXXRecordDecl *BaseClassDecl
1006 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1007
1008 // Ignore trivial destructors.
1009 if (BaseClassDecl->hasTrivialDestructor())
1010 continue;
John McCall50da2ca2010-07-21 05:30:47 +00001011
John McCall1f0fca52010-07-21 07:22:38 +00001012 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1013 BaseClassDecl,
1014 /*BaseIsVirtual*/ true);
John McCall3b477332010-02-18 19:59:28 +00001015 }
John McCall50da2ca2010-07-21 05:30:47 +00001016
John McCall3b477332010-02-18 19:59:28 +00001017 return;
1018 }
1019
1020 assert(DtorType == Dtor_Base);
John McCall50da2ca2010-07-21 05:30:47 +00001021
1022 // Destroy non-virtual bases.
1023 for (CXXRecordDecl::base_class_const_iterator I =
1024 ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) {
1025 const CXXBaseSpecifier &Base = *I;
1026
1027 // Ignore virtual bases.
1028 if (Base.isVirtual())
1029 continue;
1030
1031 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
1032
1033 // Ignore trivial destructors.
1034 if (BaseClassDecl->hasTrivialDestructor())
1035 continue;
John McCall3b477332010-02-18 19:59:28 +00001036
John McCall1f0fca52010-07-21 07:22:38 +00001037 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1038 BaseClassDecl,
1039 /*BaseIsVirtual*/ false);
John McCall50da2ca2010-07-21 05:30:47 +00001040 }
1041
1042 // Destroy direct fields.
Anders Carlsson607d0372009-12-24 22:46:43 +00001043 llvm::SmallVector<const FieldDecl *, 16> FieldDecls;
1044 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1045 E = ClassDecl->field_end(); I != E; ++I) {
1046 const FieldDecl *Field = *I;
1047
1048 QualType FieldType = getContext().getCanonicalType(Field->getType());
John McCall50da2ca2010-07-21 05:30:47 +00001049 const ConstantArrayType *Array =
1050 getContext().getAsConstantArrayType(FieldType);
1051 if (Array)
1052 FieldType = getContext().getBaseElementType(Array->getElementType());
John McCall50da2ca2010-07-21 05:30:47 +00001053
John McCallf85e1932011-06-15 23:02:42 +00001054 switch (FieldType.isDestructedType()) {
1055 case QualType::DK_none:
1056 continue;
1057
1058 case QualType::DK_cxx_destructor:
1059 if (Array)
1060 EHStack.pushCleanup<CallArrayFieldDtor>(NormalAndEHCleanup, Field);
1061 else
1062 EHStack.pushCleanup<CallFieldDtor>(NormalAndEHCleanup, Field);
1063 break;
1064
1065 case QualType::DK_objc_strong_lifetime:
1066 PushARCFieldReleaseCleanup(getARCCleanupKind(), Field);
1067 break;
1068
1069 case QualType::DK_objc_weak_lifetime:
1070 PushARCFieldWeakReleaseCleanup(getARCCleanupKind(), Field);
1071 break;
1072 }
Anders Carlsson607d0372009-12-24 22:46:43 +00001073 }
Anders Carlsson607d0372009-12-24 22:46:43 +00001074}
1075
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001076/// EmitCXXAggrConstructorCall - This routine essentially creates a (nested)
1077/// for-loop to call the default constructor on individual members of the
1078/// array.
1079/// 'D' is the default constructor for elements of the array, 'ArrayTy' is the
1080/// array type and 'ArrayPtr' points to the beginning fo the array.
1081/// It is assumed that all relevant checks have been made by the caller.
Douglas Gregor59174c02010-07-21 01:10:17 +00001082///
1083/// \param ZeroInitialization True if each element should be zero-initialized
1084/// before it is constructed.
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001085void
1086CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
Douglas Gregor59174c02010-07-21 01:10:17 +00001087 const ConstantArrayType *ArrayTy,
1088 llvm::Value *ArrayPtr,
1089 CallExpr::const_arg_iterator ArgBeg,
1090 CallExpr::const_arg_iterator ArgEnd,
1091 bool ZeroInitialization) {
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001092
1093 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
1094 llvm::Value * NumElements =
1095 llvm::ConstantInt::get(SizeTy,
1096 getContext().getConstantArrayElementCount(ArrayTy));
1097
Douglas Gregor59174c02010-07-21 01:10:17 +00001098 EmitCXXAggrConstructorCall(D, NumElements, ArrayPtr, ArgBeg, ArgEnd,
1099 ZeroInitialization);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001100}
1101
1102void
1103CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
1104 llvm::Value *NumElements,
1105 llvm::Value *ArrayPtr,
1106 CallExpr::const_arg_iterator ArgBeg,
Douglas Gregor59174c02010-07-21 01:10:17 +00001107 CallExpr::const_arg_iterator ArgEnd,
1108 bool ZeroInitialization) {
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001109 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
1110
1111 // Create a temporary for the loop index and initialize it with 0.
1112 llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index");
1113 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
1114 Builder.CreateStore(Zero, IndexPtr);
1115
1116 // Start the loop with a block that tests the condition.
1117 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1118 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1119
1120 EmitBlock(CondBlock);
1121
1122 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1123
1124 // Generate: if (loop-index < number-of-elements fall to the loop body,
1125 // otherwise, go to the block after the for-loop.
1126 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1127 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless");
1128 // If the condition is true, execute the body.
1129 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
1130
1131 EmitBlock(ForBody);
1132
1133 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1134 // Inside the loop body, emit the constructor call on the array element.
1135 Counter = Builder.CreateLoad(IndexPtr);
1136 llvm::Value *Address = Builder.CreateInBoundsGEP(ArrayPtr, Counter,
1137 "arrayidx");
1138
Douglas Gregor59174c02010-07-21 01:10:17 +00001139 // Zero initialize the storage, if requested.
1140 if (ZeroInitialization)
1141 EmitNullInitialization(Address,
1142 getContext().getTypeDeclType(D->getParent()));
1143
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001144 // C++ [class.temporary]p4:
1145 // There are two contexts in which temporaries are destroyed at a different
1146 // point than the end of the full-expression. The first context is when a
1147 // default constructor is called to initialize an element of an array.
1148 // If the constructor has one or more default arguments, the destruction of
1149 // every temporary created in a default argument expression is sequenced
1150 // before the construction of the next array element, if any.
1151
1152 // Keep track of the current number of live temporaries.
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001153 {
John McCallf1549f62010-07-06 01:34:17 +00001154 RunCleanupsScope Scope(*this);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001155
Anders Carlsson155ed4a2010-05-02 23:20:53 +00001156 EmitCXXConstructorCall(D, Ctor_Complete, /*ForVirtualBase=*/false, Address,
Anders Carlsson24eb78e2010-05-02 23:01:10 +00001157 ArgBeg, ArgEnd);
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001158 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001159
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001160 EmitBlock(ContinueBlock);
1161
1162 // Emit the increment of the loop counter.
1163 llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1);
1164 Counter = Builder.CreateLoad(IndexPtr);
1165 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1166 Builder.CreateStore(NextVal, IndexPtr);
1167
1168 // Finally, branch back up to the condition for the next iteration.
1169 EmitBranch(CondBlock);
1170
1171 // Emit the fall-through block.
1172 EmitBlock(AfterFor, true);
1173}
1174
1175/// EmitCXXAggrDestructorCall - calls the default destructor on array
1176/// elements in reverse order of construction.
1177void
1178CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
1179 const ArrayType *Array,
1180 llvm::Value *This) {
1181 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1182 assert(CA && "Do we support VLA for destruction ?");
1183 uint64_t ElementCount = getContext().getConstantArrayElementCount(CA);
1184
1185 const llvm::Type *SizeLTy = ConvertType(getContext().getSizeType());
1186 llvm::Value* ElementCountPtr = llvm::ConstantInt::get(SizeLTy, ElementCount);
1187 EmitCXXAggrDestructorCall(D, ElementCountPtr, This);
1188}
1189
1190/// EmitCXXAggrDestructorCall - calls the default destructor on array
1191/// elements in reverse order of construction.
1192void
1193CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
1194 llvm::Value *UpperCount,
1195 llvm::Value *This) {
1196 const llvm::Type *SizeLTy = ConvertType(getContext().getSizeType());
1197 llvm::Value *One = llvm::ConstantInt::get(SizeLTy, 1);
1198
1199 // Create a temporary for the loop index and initialize it with count of
1200 // array elements.
1201 llvm::Value *IndexPtr = CreateTempAlloca(SizeLTy, "loop.index");
1202
1203 // Store the number of elements in the index pointer.
1204 Builder.CreateStore(UpperCount, IndexPtr);
1205
1206 // Start the loop with a block that tests the condition.
1207 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1208 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1209
1210 EmitBlock(CondBlock);
1211
1212 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1213
1214 // Generate: if (loop-index != 0 fall to the loop body,
1215 // otherwise, go to the block after the for-loop.
1216 llvm::Value* zeroConstant =
1217 llvm::Constant::getNullValue(SizeLTy);
1218 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1219 llvm::Value *IsNE = Builder.CreateICmpNE(Counter, zeroConstant,
1220 "isne");
1221 // If the condition is true, execute the body.
1222 Builder.CreateCondBr(IsNE, ForBody, AfterFor);
1223
1224 EmitBlock(ForBody);
1225
1226 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1227 // Inside the loop body, emit the constructor call on the array element.
1228 Counter = Builder.CreateLoad(IndexPtr);
1229 Counter = Builder.CreateSub(Counter, One);
1230 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
Anders Carlsson8e6404c2010-05-02 23:29:11 +00001231 EmitCXXDestructorCall(D, Dtor_Complete, /*ForVirtualBase=*/false, Address);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001232
1233 EmitBlock(ContinueBlock);
1234
1235 // Emit the decrement of the loop counter.
1236 Counter = Builder.CreateLoad(IndexPtr);
1237 Counter = Builder.CreateSub(Counter, One, "dec");
1238 Builder.CreateStore(Counter, IndexPtr);
1239
1240 // Finally, branch back up to the condition for the next iteration.
1241 EmitBranch(CondBlock);
1242
1243 // Emit the fall-through block.
1244 EmitBlock(AfterFor, true);
1245}
1246
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001247void
1248CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
Anders Carlsson155ed4a2010-05-02 23:20:53 +00001249 CXXCtorType Type, bool ForVirtualBase,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001250 llvm::Value *This,
1251 CallExpr::const_arg_iterator ArgBeg,
1252 CallExpr::const_arg_iterator ArgEnd) {
Devang Patel3ee36af2011-02-22 20:55:26 +00001253
1254 CGDebugInfo *DI = getDebugInfo();
1255 if (DI && CGM.getCodeGenOpts().LimitDebugInfo) {
1256 // If debug info for this class has been emitted then this is the right time
1257 // to do so.
1258 const CXXRecordDecl *Parent = D->getParent();
1259 DI->getOrCreateRecordType(CGM.getContext().getTypeDeclType(Parent),
1260 Parent->getLocation());
1261 }
1262
John McCall8b6bbeb2010-02-06 00:25:16 +00001263 if (D->isTrivial()) {
1264 if (ArgBeg == ArgEnd) {
1265 // Trivial default constructor, no codegen required.
1266 assert(D->isDefaultConstructor() &&
1267 "trivial 0-arg ctor not a default ctor");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001268 return;
1269 }
John McCall8b6bbeb2010-02-06 00:25:16 +00001270
1271 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
1272 assert(D->isCopyConstructor() && "trivial 1-arg ctor not a copy ctor");
1273
John McCall8b6bbeb2010-02-06 00:25:16 +00001274 const Expr *E = (*ArgBeg);
1275 QualType Ty = E->getType();
1276 llvm::Value *Src = EmitLValue(E).getAddress();
1277 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001278 return;
1279 }
1280
Anders Carlsson314e6222010-05-02 23:33:10 +00001281 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(D, Type), ForVirtualBase);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001282 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
1283
Anders Carlssonc997d422010-01-02 01:01:18 +00001284 EmitCXXMemberCall(D, Callee, ReturnValueSlot(), This, VTT, ArgBeg, ArgEnd);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001285}
1286
John McCallc0bf4622010-02-23 00:48:20 +00001287void
Fariborz Jahanian34999872010-11-13 21:53:34 +00001288CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
1289 llvm::Value *This, llvm::Value *Src,
1290 CallExpr::const_arg_iterator ArgBeg,
1291 CallExpr::const_arg_iterator ArgEnd) {
1292 if (D->isTrivial()) {
1293 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
1294 assert(D->isCopyConstructor() && "trivial 1-arg ctor not a copy ctor");
1295 EmitAggregateCopy(This, Src, (*ArgBeg)->getType());
1296 return;
1297 }
1298 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D,
1299 clang::Ctor_Complete);
1300 assert(D->isInstance() &&
1301 "Trying to emit a member call expr on a static method!");
1302
1303 const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
1304
1305 CallArgList Args;
1306
1307 // Push the this ptr.
Eli Friedman04c9a492011-05-02 17:57:46 +00001308 Args.add(RValue::get(This), D->getThisType(getContext()));
Fariborz Jahanian34999872010-11-13 21:53:34 +00001309
1310
1311 // Push the src ptr.
1312 QualType QT = *(FPT->arg_type_begin());
1313 const llvm::Type *t = CGM.getTypes().ConvertType(QT);
1314 Src = Builder.CreateBitCast(Src, t);
Eli Friedman04c9a492011-05-02 17:57:46 +00001315 Args.add(RValue::get(Src), QT);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001316
1317 // Skip over first argument (Src).
1318 ++ArgBeg;
1319 CallExpr::const_arg_iterator Arg = ArgBeg;
1320 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin()+1,
1321 E = FPT->arg_type_end(); I != E; ++I, ++Arg) {
1322 assert(Arg != ArgEnd && "Running over edge of argument list!");
John McCall413ebdb2011-03-11 20:59:21 +00001323 EmitCallArg(Args, *Arg, *I);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001324 }
1325 // Either we've emitted all the call args, or we have a call to a
1326 // variadic function.
1327 assert((Arg == ArgEnd || FPT->isVariadic()) &&
1328 "Extra arguments in non-variadic function!");
1329 // If we still have any arguments, emit them using the type of the argument.
1330 for (; Arg != ArgEnd; ++Arg) {
1331 QualType ArgType = Arg->getType();
John McCall413ebdb2011-03-11 20:59:21 +00001332 EmitCallArg(Args, *Arg, ArgType);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001333 }
1334
1335 QualType ResultType = FPT->getResultType();
1336 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args,
1337 FPT->getExtInfo()),
1338 Callee, ReturnValueSlot(), Args, D);
1339}
1340
1341void
John McCallc0bf4622010-02-23 00:48:20 +00001342CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1343 CXXCtorType CtorType,
1344 const FunctionArgList &Args) {
1345 CallArgList DelegateArgs;
1346
1347 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
1348 assert(I != E && "no parameters to constructor");
1349
1350 // this
Eli Friedman04c9a492011-05-02 17:57:46 +00001351 DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType());
John McCallc0bf4622010-02-23 00:48:20 +00001352 ++I;
1353
1354 // vtt
Anders Carlsson314e6222010-05-02 23:33:10 +00001355 if (llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(Ctor, CtorType),
1356 /*ForVirtualBase=*/false)) {
John McCallc0bf4622010-02-23 00:48:20 +00001357 QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
Eli Friedman04c9a492011-05-02 17:57:46 +00001358 DelegateArgs.add(RValue::get(VTT), VoidPP);
John McCallc0bf4622010-02-23 00:48:20 +00001359
Anders Carlssonaf440352010-03-23 04:11:45 +00001360 if (CodeGenVTables::needsVTTParameter(CurGD)) {
John McCallc0bf4622010-02-23 00:48:20 +00001361 assert(I != E && "cannot skip vtt parameter, already done with args");
John McCalld26bc762011-03-09 04:27:21 +00001362 assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
John McCallc0bf4622010-02-23 00:48:20 +00001363 ++I;
1364 }
1365 }
1366
1367 // Explicit arguments.
1368 for (; I != E; ++I) {
John McCall413ebdb2011-03-11 20:59:21 +00001369 const VarDecl *param = *I;
1370 EmitDelegateCallArg(DelegateArgs, param);
John McCallc0bf4622010-02-23 00:48:20 +00001371 }
1372
1373 EmitCall(CGM.getTypes().getFunctionInfo(Ctor, CtorType),
1374 CGM.GetAddrOfCXXConstructor(Ctor, CtorType),
1375 ReturnValueSlot(), DelegateArgs, Ctor);
1376}
1377
Sean Huntb76af9c2011-05-03 23:05:34 +00001378namespace {
1379 struct CallDelegatingCtorDtor : EHScopeStack::Cleanup {
1380 const CXXDestructorDecl *Dtor;
1381 llvm::Value *Addr;
1382 CXXDtorType Type;
1383
1384 CallDelegatingCtorDtor(const CXXDestructorDecl *D, llvm::Value *Addr,
1385 CXXDtorType Type)
1386 : Dtor(D), Addr(Addr), Type(Type) {}
1387
1388 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1389 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
1390 Addr);
1391 }
1392 };
1393}
1394
Sean Hunt059ce0d2011-05-01 07:04:31 +00001395void
1396CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
1397 const FunctionArgList &Args) {
1398 assert(Ctor->isDelegatingConstructor());
1399
1400 llvm::Value *ThisPtr = LoadCXXThis();
1401
John McCallf85e1932011-06-15 23:02:42 +00001402 AggValueSlot AggSlot =
1403 AggValueSlot::forAddr(ThisPtr, Qualifiers(), /*Lifetime*/ true);
Sean Hunt059ce0d2011-05-01 07:04:31 +00001404
1405 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
Sean Hunt059ce0d2011-05-01 07:04:31 +00001406
Sean Huntb76af9c2011-05-03 23:05:34 +00001407 const CXXRecordDecl *ClassDecl = Ctor->getParent();
1408 if (CGM.getLangOptions().Exceptions && !ClassDecl->hasTrivialDestructor()) {
1409 CXXDtorType Type =
1410 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
1411
1412 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
1413 ClassDecl->getDestructor(),
1414 ThisPtr, Type);
1415 }
1416}
Sean Hunt059ce0d2011-05-01 07:04:31 +00001417
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001418void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
1419 CXXDtorType Type,
Anders Carlsson8e6404c2010-05-02 23:29:11 +00001420 bool ForVirtualBase,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001421 llvm::Value *This) {
Anders Carlsson314e6222010-05-02 23:33:10 +00001422 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(DD, Type),
1423 ForVirtualBase);
Fariborz Jahanianccd52592011-02-01 23:22:34 +00001424 llvm::Value *Callee = 0;
1425 if (getContext().getLangOptions().AppleKext)
Fariborz Jahanian771c6782011-02-03 19:27:17 +00001426 Callee = BuildAppleKextVirtualDestructorCall(DD, Type,
1427 DD->getParent());
Fariborz Jahanianccd52592011-02-01 23:22:34 +00001428
1429 if (!Callee)
1430 Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001431
Anders Carlssonc997d422010-01-02 01:01:18 +00001432 EmitCXXMemberCall(DD, Callee, ReturnValueSlot(), This, VTT, 0, 0);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001433}
1434
John McCall291ae942010-07-21 01:41:18 +00001435namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001436 struct CallLocalDtor : EHScopeStack::Cleanup {
John McCall291ae942010-07-21 01:41:18 +00001437 const CXXDestructorDecl *Dtor;
1438 llvm::Value *Addr;
1439
1440 CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
1441 : Dtor(D), Addr(Addr) {}
1442
1443 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1444 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1445 /*ForVirtualBase=*/false, Addr);
1446 }
1447 };
1448}
1449
John McCall81407d42010-07-21 06:29:51 +00001450void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
1451 llvm::Value *Addr) {
John McCall1f0fca52010-07-21 07:22:38 +00001452 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
John McCall81407d42010-07-21 06:29:51 +00001453}
1454
John McCallf1549f62010-07-06 01:34:17 +00001455void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
1456 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
1457 if (!ClassDecl) return;
1458 if (ClassDecl->hasTrivialDestructor()) return;
1459
1460 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCall642a75f2011-04-28 02:15:35 +00001461 assert(D && D->isUsed() && "destructor not marked as used!");
John McCall81407d42010-07-21 06:29:51 +00001462 PushDestructorCleanup(D, Addr);
John McCallf1549f62010-07-06 01:34:17 +00001463}
1464
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001465llvm::Value *
Anders Carlssonbb7e17b2010-01-31 01:36:53 +00001466CodeGenFunction::GetVirtualBaseClassOffset(llvm::Value *This,
1467 const CXXRecordDecl *ClassDecl,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001468 const CXXRecordDecl *BaseClassDecl) {
Dan Gohman043fb9a2010-10-26 18:44:08 +00001469 llvm::Value *VTablePtr = GetVTablePtr(This, Int8PtrTy);
Ken Dyck14c65ca2011-04-07 12:37:09 +00001470 CharUnits VBaseOffsetOffset =
Anders Carlssonaf440352010-03-23 04:11:45 +00001471 CGM.getVTables().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001472
1473 llvm::Value *VBaseOffsetPtr =
Ken Dyck14c65ca2011-04-07 12:37:09 +00001474 Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1475 "vbase.offset.ptr");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001476 const llvm::Type *PtrDiffTy =
1477 ConvertType(getContext().getPointerDiffType());
1478
1479 VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr,
1480 PtrDiffTy->getPointerTo());
1481
1482 llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1483
1484 return VBaseOffset;
1485}
1486
Anders Carlssond103f9f2010-03-28 19:40:00 +00001487void
1488CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001489 const CXXRecordDecl *NearestVBase,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001490 CharUnits OffsetFromNearestVBase,
Anders Carlssond103f9f2010-03-28 19:40:00 +00001491 llvm::Constant *VTable,
1492 const CXXRecordDecl *VTableClass) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001493 const CXXRecordDecl *RD = Base.getBase();
1494
Anders Carlssond103f9f2010-03-28 19:40:00 +00001495 // Compute the address point.
Anders Carlssonc83f1062010-03-29 01:08:49 +00001496 llvm::Value *VTableAddressPoint;
Anders Carlsson851853d2010-03-29 02:38:51 +00001497
Anders Carlssonc83f1062010-03-29 01:08:49 +00001498 // Check if we need to use a vtable from the VTT.
Anders Carlsson851853d2010-03-29 02:38:51 +00001499 if (CodeGenVTables::needsVTTParameter(CurGD) &&
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001500 (RD->getNumVBases() || NearestVBase)) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001501 // Get the secondary vpointer index.
1502 uint64_t VirtualPointerIndex =
1503 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1504
1505 /// Load the VTT.
1506 llvm::Value *VTT = LoadCXXVTT();
1507 if (VirtualPointerIndex)
1508 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1509
1510 // And load the address point from the VTT.
1511 VTableAddressPoint = Builder.CreateLoad(VTT);
1512 } else {
Anders Carlsson64c9eca2010-03-29 02:08:26 +00001513 uint64_t AddressPoint = CGM.getVTables().getAddressPoint(Base, VTableClass);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001514 VTableAddressPoint =
Anders Carlssond103f9f2010-03-28 19:40:00 +00001515 Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001516 }
Anders Carlssond103f9f2010-03-28 19:40:00 +00001517
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001518 // Compute where to store the address point.
Anders Carlsson8246cc72010-05-03 00:29:58 +00001519 llvm::Value *VirtualOffset = 0;
Ken Dyck9a8ad9b2011-03-23 00:45:26 +00001520 CharUnits NonVirtualOffset = CharUnits::Zero();
Anders Carlsson3e79c302010-04-20 18:05:10 +00001521
1522 if (CodeGenVTables::needsVTTParameter(CurGD) && NearestVBase) {
1523 // We need to use the virtual base offset offset because the virtual base
1524 // might have a different offset in the most derived class.
Anders Carlsson8246cc72010-05-03 00:29:58 +00001525 VirtualOffset = GetVirtualBaseClassOffset(LoadCXXThis(), VTableClass,
1526 NearestVBase);
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001527 NonVirtualOffset = OffsetFromNearestVBase;
Anders Carlsson3e79c302010-04-20 18:05:10 +00001528 } else {
Anders Carlsson8246cc72010-05-03 00:29:58 +00001529 // We can just use the base offset in the complete class.
Ken Dyck4230d522011-03-24 01:21:01 +00001530 NonVirtualOffset = Base.getBaseOffset();
Anders Carlsson3e79c302010-04-20 18:05:10 +00001531 }
Anders Carlsson8246cc72010-05-03 00:29:58 +00001532
1533 // Apply the offsets.
1534 llvm::Value *VTableField = LoadCXXThis();
1535
Ken Dyck9a8ad9b2011-03-23 00:45:26 +00001536 if (!NonVirtualOffset.isZero() || VirtualOffset)
Anders Carlsson8246cc72010-05-03 00:29:58 +00001537 VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
1538 NonVirtualOffset,
1539 VirtualOffset);
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001540
Anders Carlssond103f9f2010-03-28 19:40:00 +00001541 // Finally, store the address point.
1542 const llvm::Type *AddressPointPtrTy =
1543 VTableAddressPoint->getType()->getPointerTo();
1544 VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
1545 Builder.CreateStore(VTableAddressPoint, VTableField);
1546}
1547
Anders Carlsson603d6d12010-03-28 21:07:49 +00001548void
1549CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001550 const CXXRecordDecl *NearestVBase,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001551 CharUnits OffsetFromNearestVBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001552 bool BaseIsNonVirtualPrimaryBase,
1553 llvm::Constant *VTable,
1554 const CXXRecordDecl *VTableClass,
1555 VisitedVirtualBasesSetTy& VBases) {
1556 // If this base is a non-virtual primary base the address point has already
1557 // been set.
1558 if (!BaseIsNonVirtualPrimaryBase) {
1559 // Initialize the vtable pointer for this base.
Anders Carlsson42358402010-05-03 00:07:07 +00001560 InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
1561 VTable, VTableClass);
Anders Carlsson603d6d12010-03-28 21:07:49 +00001562 }
1563
1564 const CXXRecordDecl *RD = Base.getBase();
1565
1566 // Traverse bases.
1567 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1568 E = RD->bases_end(); I != E; ++I) {
1569 CXXRecordDecl *BaseDecl
1570 = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1571
1572 // Ignore classes without a vtable.
1573 if (!BaseDecl->isDynamicClass())
1574 continue;
1575
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001576 CharUnits BaseOffset;
1577 CharUnits BaseOffsetFromNearestVBase;
Anders Carlsson14da9de2010-03-29 01:16:41 +00001578 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001579
1580 if (I->isVirtual()) {
1581 // Check if we've visited this virtual base before.
1582 if (!VBases.insert(BaseDecl))
1583 continue;
1584
1585 const ASTRecordLayout &Layout =
1586 getContext().getASTRecordLayout(VTableClass);
1587
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001588 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
1589 BaseOffsetFromNearestVBase = CharUnits::Zero();
Anders Carlsson14da9de2010-03-29 01:16:41 +00001590 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001591 } else {
1592 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1593
Ken Dyck4230d522011-03-24 01:21:01 +00001594 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson42358402010-05-03 00:07:07 +00001595 BaseOffsetFromNearestVBase =
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001596 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson14da9de2010-03-29 01:16:41 +00001597 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001598 }
1599
Ken Dyck4230d522011-03-24 01:21:01 +00001600 InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001601 I->isVirtual() ? BaseDecl : NearestVBase,
Anders Carlsson42358402010-05-03 00:07:07 +00001602 BaseOffsetFromNearestVBase,
Anders Carlsson14da9de2010-03-29 01:16:41 +00001603 BaseDeclIsNonVirtualPrimaryBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001604 VTable, VTableClass, VBases);
1605 }
1606}
1607
1608void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
1609 // Ignore classes without a vtable.
Anders Carlsson07036902010-03-26 04:39:42 +00001610 if (!RD->isDynamicClass())
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001611 return;
1612
Anders Carlsson07036902010-03-26 04:39:42 +00001613 // Get the VTable.
1614 llvm::Constant *VTable = CGM.getVTables().GetAddrOfVTable(RD);
Anders Carlsson5c6c1d92010-03-24 03:57:14 +00001615
Anders Carlsson603d6d12010-03-28 21:07:49 +00001616 // Initialize the vtable pointers for this class and all of its bases.
1617 VisitedVirtualBasesSetTy VBases;
Ken Dyck4230d522011-03-24 01:21:01 +00001618 InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()),
1619 /*NearestVBase=*/0,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001620 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
Anders Carlsson603d6d12010-03-28 21:07:49 +00001621 /*BaseIsNonVirtualPrimaryBase=*/false,
1622 VTable, RD, VBases);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001623}
Dan Gohman043fb9a2010-10-26 18:44:08 +00001624
1625llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
1626 const llvm::Type *Ty) {
1627 llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
1628 return Builder.CreateLoad(VTablePtrSrc, "vtable");
1629}
Anders Carlssona2447e02011-05-08 20:32:23 +00001630
1631static const CXXRecordDecl *getMostDerivedClassDecl(const Expr *Base) {
1632 const Expr *E = Base;
1633
1634 while (true) {
1635 E = E->IgnoreParens();
1636 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
1637 if (CE->getCastKind() == CK_DerivedToBase ||
1638 CE->getCastKind() == CK_UncheckedDerivedToBase ||
1639 CE->getCastKind() == CK_NoOp) {
1640 E = CE->getSubExpr();
1641 continue;
1642 }
1643 }
1644
1645 break;
1646 }
1647
1648 QualType DerivedType = E->getType();
1649 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
1650 DerivedType = PTy->getPointeeType();
1651
1652 return cast<CXXRecordDecl>(DerivedType->castAs<RecordType>()->getDecl());
1653}
1654
1655// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
1656// quite what we want.
1657static const Expr *skipNoOpCastsAndParens(const Expr *E) {
1658 while (true) {
1659 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
1660 E = PE->getSubExpr();
1661 continue;
1662 }
1663
1664 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
1665 if (CE->getCastKind() == CK_NoOp) {
1666 E = CE->getSubExpr();
1667 continue;
1668 }
1669 }
1670 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1671 if (UO->getOpcode() == UO_Extension) {
1672 E = UO->getSubExpr();
1673 continue;
1674 }
1675 }
1676 return E;
1677 }
1678}
1679
1680/// canDevirtualizeMemberFunctionCall - Checks whether the given virtual member
1681/// function call on the given expr can be devirtualized.
1682/// expr can be devirtualized.
1683static bool canDevirtualizeMemberFunctionCall(const Expr *Base,
1684 const CXXMethodDecl *MD) {
1685 // If the most derived class is marked final, we know that no subclass can
1686 // override this member function and so we can devirtualize it. For example:
1687 //
1688 // struct A { virtual void f(); }
1689 // struct B final : A { };
1690 //
1691 // void f(B *b) {
1692 // b->f();
1693 // }
1694 //
1695 const CXXRecordDecl *MostDerivedClassDecl = getMostDerivedClassDecl(Base);
1696 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
1697 return true;
1698
1699 // If the member function is marked 'final', we know that it can't be
1700 // overridden and can therefore devirtualize it.
1701 if (MD->hasAttr<FinalAttr>())
1702 return true;
1703
1704 // Similarly, if the class itself is marked 'final' it can't be overridden
1705 // and we can therefore devirtualize the member function call.
1706 if (MD->getParent()->hasAttr<FinalAttr>())
1707 return true;
1708
1709 Base = skipNoOpCastsAndParens(Base);
1710 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
1711 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
1712 // This is a record decl. We know the type and can devirtualize it.
1713 return VD->getType()->isRecordType();
1714 }
1715
1716 return false;
1717 }
1718
1719 // We can always devirtualize calls on temporary object expressions.
1720 if (isa<CXXConstructExpr>(Base))
1721 return true;
1722
1723 // And calls on bound temporaries.
1724 if (isa<CXXBindTemporaryExpr>(Base))
1725 return true;
1726
1727 // Check if this is a call expr that returns a record type.
1728 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
1729 return CE->getCallReturnType()->isRecordType();
1730
1731 // We can't devirtualize the call.
1732 return false;
1733}
1734
1735static bool UseVirtualCall(ASTContext &Context,
1736 const CXXOperatorCallExpr *CE,
1737 const CXXMethodDecl *MD) {
1738 if (!MD->isVirtual())
1739 return false;
1740
1741 // When building with -fapple-kext, all calls must go through the vtable since
1742 // the kernel linker can do runtime patching of vtables.
1743 if (Context.getLangOptions().AppleKext)
1744 return true;
1745
1746 return !canDevirtualizeMemberFunctionCall(CE->getArg(0), MD);
1747}
1748
1749llvm::Value *
1750CodeGenFunction::EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E,
1751 const CXXMethodDecl *MD,
1752 llvm::Value *This) {
1753 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1754 const llvm::Type *Ty =
1755 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1756 FPT->isVariadic());
1757
1758 if (UseVirtualCall(getContext(), E, MD))
1759 return BuildVirtualCall(MD, This, Ty);
1760
1761 return CGM.GetAddrOfFunction(MD, Ty);
1762}