blob: 066f0d5c7d7ab8f4df36d5de32e513d72eca0b83 [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)) {
433 CGF.EmitScalarInit(MemberInit->getInit(), 0, Dest, false,
434 LHS.isVolatileQualified(),
435 CGF.getContext().getTypeAlign(T),
436 T);
437 } else if (T->isAnyComplexType()) {
438 CGF.EmitComplexExprIntoAddr(MemberInit->getInit(), Dest,
439 LHS.isVolatileQualified());
440 } else {
441 AggValueSlot Slot = AggValueSlot::forAddr(Dest, LHS.getQuals(),
442 /*Lifetime*/ true);
443
444 CGF.EmitAggExpr(MemberInit->getInit(), Slot);
445 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000446
447 return;
448 }
449
450 const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T);
451 assert(Array && "Array initialization without the array type?");
452 llvm::Value *IndexVar
453 = CGF.GetAddrOfLocalVar(MemberInit->getArrayIndex(Index));
454 assert(IndexVar && "Array index variable not loaded");
455
456 // Initialize this index variable to zero.
457 llvm::Value* Zero
458 = llvm::Constant::getNullValue(
459 CGF.ConvertType(CGF.getContext().getSizeType()));
460 CGF.Builder.CreateStore(Zero, IndexVar);
461
462 // Start the loop with a block that tests the condition.
463 llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond");
464 llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end");
465
466 CGF.EmitBlock(CondBlock);
467
468 llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body");
469 // Generate: if (loop-index < number-of-elements) fall to the loop body,
470 // otherwise, go to the block after the for-loop.
471 uint64_t NumElements = Array->getSize().getZExtValue();
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000472 llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
Chris Lattner985f7392010-05-06 06:35:23 +0000473 llvm::Value *NumElementsPtr =
474 llvm::ConstantInt::get(Counter->getType(), NumElements);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000475 llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr,
476 "isless");
477
478 // If the condition is true, execute the body.
479 CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor);
480
481 CGF.EmitBlock(ForBody);
482 llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc");
483
484 {
John McCallf1549f62010-07-06 01:34:17 +0000485 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000486
487 // Inside the loop body recurse to emit the inner loop or, eventually, the
488 // constructor call.
489 EmitAggMemberInitializer(CGF, LHS, ArrayIndexVar, MemberInit,
490 Array->getElementType(), Index + 1);
491 }
492
493 CGF.EmitBlock(ContinueBlock);
494
495 // Emit the increment of the loop counter.
496 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
497 Counter = CGF.Builder.CreateLoad(IndexVar);
498 NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc");
499 CGF.Builder.CreateStore(NextVal, IndexVar);
500
501 // Finally, branch back up to the condition for the next iteration.
502 CGF.EmitBranch(CondBlock);
503
504 // Emit the fall-through block.
505 CGF.EmitBlock(AfterFor, true);
506}
John McCall182ab512010-07-21 01:23:41 +0000507
508namespace {
John McCall1f0fca52010-07-21 07:22:38 +0000509 struct CallMemberDtor : EHScopeStack::Cleanup {
John McCall182ab512010-07-21 01:23:41 +0000510 FieldDecl *Field;
511 CXXDestructorDecl *Dtor;
512
513 CallMemberDtor(FieldDecl *Field, CXXDestructorDecl *Dtor)
514 : Field(Field), Dtor(Dtor) {}
515
516 void Emit(CodeGenFunction &CGF, bool IsForEH) {
517 // FIXME: Is this OK for C++0x delegating constructors?
518 llvm::Value *ThisPtr = CGF.LoadCXXThis();
519 LValue LHS = CGF.EmitLValueForField(ThisPtr, Field, 0);
520
521 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
522 LHS.getAddress());
523 }
524 };
525}
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000526
Anders Carlsson607d0372009-12-24 22:46:43 +0000527static void EmitMemberInitializer(CodeGenFunction &CGF,
528 const CXXRecordDecl *ClassDecl,
Sean Huntcbb67482011-01-08 20:30:50 +0000529 CXXCtorInitializer *MemberInit,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000530 const CXXConstructorDecl *Constructor,
531 FunctionArgList &Args) {
Francois Pichet00eb3f92010-12-04 09:14:42 +0000532 assert(MemberInit->isAnyMemberInitializer() &&
Anders Carlsson607d0372009-12-24 22:46:43 +0000533 "Must have member initializer!");
Richard Smith7a614d82011-06-11 17:19:42 +0000534 assert(MemberInit->getInit() && "Must have initializer!");
Anders Carlsson607d0372009-12-24 22:46:43 +0000535
536 // non-static data member initializers.
Francois Pichet00eb3f92010-12-04 09:14:42 +0000537 FieldDecl *Field = MemberInit->getAnyMember();
Anders Carlsson607d0372009-12-24 22:46:43 +0000538 QualType FieldType = CGF.getContext().getCanonicalType(Field->getType());
539
540 llvm::Value *ThisPtr = CGF.LoadCXXThis();
John McCalla9976d32010-05-21 01:18:57 +0000541 LValue LHS;
Anders Carlsson06a29702010-01-29 05:24:29 +0000542
Anders Carlsson607d0372009-12-24 22:46:43 +0000543 // If we are initializing an anonymous union field, drill down to the field.
Francois Pichet00eb3f92010-12-04 09:14:42 +0000544 if (MemberInit->isIndirectMemberInitializer()) {
545 LHS = CGF.EmitLValueForAnonRecordField(ThisPtr,
546 MemberInit->getIndirectMember(), 0);
547 FieldType = MemberInit->getIndirectMember()->getAnonField()->getType();
John McCalla9976d32010-05-21 01:18:57 +0000548 } else {
549 LHS = CGF.EmitLValueForFieldInitialization(ThisPtr, Field, 0);
Anders Carlsson607d0372009-12-24 22:46:43 +0000550 }
551
Sean Huntcbb67482011-01-08 20:30:50 +0000552 // FIXME: If there's no initializer and the CXXCtorInitializer
Douglas Gregor9db7dbb2010-01-31 09:12:51 +0000553 // was implicitly generated, we shouldn't be zeroing memory.
John McCallf85e1932011-06-15 23:02:42 +0000554 if (FieldType->isArrayType() && !MemberInit->getInit()) {
Anders Carlsson1884eb02010-05-22 17:35:42 +0000555 CGF.EmitNullInitialization(LHS.getAddress(), Field->getType());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +0000556 } else if (!CGF.hasAggregateLLVMType(Field->getType())) {
John McCallf85e1932011-06-15 23:02:42 +0000557 if (LHS.isSimple()) {
558 CGF.EmitExprAsInit(MemberInit->getInit(), Field, LHS.getAddress(),
559 CGF.getContext().getDeclAlign(Field), false);
560 } else {
561 RValue RHS = RValue::get(CGF.EmitScalarExpr(MemberInit->getInit()));
562 CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
563 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +0000564 } else if (MemberInit->getInit()->getType()->isAnyComplexType()) {
565 CGF.EmitComplexExprIntoAddr(MemberInit->getInit(), LHS.getAddress(),
Anders Carlsson607d0372009-12-24 22:46:43 +0000566 LHS.isVolatileQualified());
567 } else {
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000568 llvm::Value *ArrayIndexVar = 0;
569 const ConstantArrayType *Array
570 = CGF.getContext().getAsConstantArrayType(FieldType);
571 if (Array && Constructor->isImplicit() &&
572 Constructor->isCopyConstructor()) {
573 const llvm::Type *SizeTy
574 = CGF.ConvertType(CGF.getContext().getSizeType());
575
576 // The LHS is a pointer to the first object we'll be constructing, as
577 // a flat array.
578 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
579 const llvm::Type *BasePtr = CGF.ConvertType(BaseElementTy);
580 BasePtr = llvm::PointerType::getUnqual(BasePtr);
581 llvm::Value *BaseAddrPtr = CGF.Builder.CreateBitCast(LHS.getAddress(),
582 BasePtr);
Daniel Dunbar9f553f52010-08-21 03:08:16 +0000583 LHS = CGF.MakeAddrLValue(BaseAddrPtr, BaseElementTy);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000584
585 // Create an array index that will be used to walk over all of the
586 // objects we're constructing.
587 ArrayIndexVar = CGF.CreateTempAlloca(SizeTy, "object.index");
588 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
589 CGF.Builder.CreateStore(Zero, ArrayIndexVar);
590
John McCallf85e1932011-06-15 23:02:42 +0000591 // If we are copying an array of PODs or classes with trivial copy
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000592 // constructors, perform a single aggregate copy.
John McCallf85e1932011-06-15 23:02:42 +0000593 const CXXRecordDecl *Record = BaseElementTy->getAsCXXRecordDecl();
594 if (BaseElementTy.isPODType(CGF.getContext()) ||
595 (Record && Record->hasTrivialCopyConstructor())) {
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000596 // Find the source pointer. We knows it's the last argument because
597 // we know we're in a copy constructor.
598 unsigned SrcArgIndex = Args.size() - 1;
599 llvm::Value *SrcPtr
John McCalld26bc762011-03-09 04:27:21 +0000600 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000601 LValue Src = CGF.EmitLValueForFieldInitialization(SrcPtr, Field, 0);
602
603 // Copy the aggregate.
604 CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
605 LHS.isVolatileQualified());
606 return;
607 }
608
609 // Emit the block variables for the array indices, if any.
610 for (unsigned I = 0, N = MemberInit->getNumArrayIndices(); I != N; ++I)
John McCallb6bbcc92010-10-15 04:57:14 +0000611 CGF.EmitAutoVarDecl(*MemberInit->getArrayIndex(I));
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000612 }
613
614 EmitAggMemberInitializer(CGF, LHS, ArrayIndexVar, MemberInit, FieldType, 0);
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000615
Anders Carlsson7a178512011-02-28 00:33:03 +0000616 if (!CGF.CGM.getLangOptions().Exceptions)
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000617 return;
618
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000619 // FIXME: If we have an array of classes w/ non-trivial destructors,
620 // we need to destroy in reverse order of construction along the exception
621 // path.
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000622 const RecordType *RT = FieldType->getAs<RecordType>();
623 if (!RT)
624 return;
625
626 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall182ab512010-07-21 01:23:41 +0000627 if (!RD->hasTrivialDestructor())
John McCall1f0fca52010-07-21 07:22:38 +0000628 CGF.EHStack.pushCleanup<CallMemberDtor>(EHCleanup, Field,
629 RD->getDestructor());
Anders Carlsson607d0372009-12-24 22:46:43 +0000630 }
631}
632
John McCallc0bf4622010-02-23 00:48:20 +0000633/// Checks whether the given constructor is a valid subject for the
634/// complete-to-base constructor delegation optimization, i.e.
635/// emitting the complete constructor as a simple call to the base
636/// constructor.
637static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
638
639 // Currently we disable the optimization for classes with virtual
640 // bases because (1) the addresses of parameter variables need to be
641 // consistent across all initializers but (2) the delegate function
642 // call necessarily creates a second copy of the parameter variable.
643 //
644 // The limiting example (purely theoretical AFAIK):
645 // struct A { A(int &c) { c++; } };
646 // struct B : virtual A {
647 // B(int count) : A(count) { printf("%d\n", count); }
648 // };
649 // ...although even this example could in principle be emitted as a
650 // delegation since the address of the parameter doesn't escape.
651 if (Ctor->getParent()->getNumVBases()) {
652 // TODO: white-list trivial vbase initializers. This case wouldn't
653 // be subject to the restrictions below.
654
655 // TODO: white-list cases where:
656 // - there are no non-reference parameters to the constructor
657 // - the initializers don't access any non-reference parameters
658 // - the initializers don't take the address of non-reference
659 // parameters
660 // - etc.
661 // If we ever add any of the above cases, remember that:
662 // - function-try-blocks will always blacklist this optimization
663 // - we need to perform the constructor prologue and cleanup in
664 // EmitConstructorBody.
665
666 return false;
667 }
668
669 // We also disable the optimization for variadic functions because
670 // it's impossible to "re-pass" varargs.
671 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
672 return false;
673
Sean Hunt059ce0d2011-05-01 07:04:31 +0000674 // FIXME: Decide if we can do a delegation of a delegating constructor.
675 if (Ctor->isDelegatingConstructor())
676 return false;
677
John McCallc0bf4622010-02-23 00:48:20 +0000678 return true;
679}
680
John McCall9fc6a772010-02-19 09:25:03 +0000681/// EmitConstructorBody - Emits the body of the current constructor.
682void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
683 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
684 CXXCtorType CtorType = CurGD.getCtorType();
685
John McCallc0bf4622010-02-23 00:48:20 +0000686 // Before we go any further, try the complete->base constructor
687 // delegation optimization.
688 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor)) {
Devang Pateld67ef0e2010-08-11 21:04:37 +0000689 if (CGDebugInfo *DI = getDebugInfo())
690 DI->EmitStopPoint(Builder);
John McCallc0bf4622010-02-23 00:48:20 +0000691 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args);
692 return;
693 }
694
John McCall9fc6a772010-02-19 09:25:03 +0000695 Stmt *Body = Ctor->getBody();
696
John McCallc0bf4622010-02-23 00:48:20 +0000697 // Enter the function-try-block before the constructor prologue if
698 // applicable.
John McCallc0bf4622010-02-23 00:48:20 +0000699 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallc0bf4622010-02-23 00:48:20 +0000700 if (IsTryBody)
John McCall59a70002010-07-07 06:56:46 +0000701 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000702
John McCallf1549f62010-07-06 01:34:17 +0000703 EHScopeStack::stable_iterator CleanupDepth = EHStack.stable_begin();
John McCall9fc6a772010-02-19 09:25:03 +0000704
John McCallc0bf4622010-02-23 00:48:20 +0000705 // Emit the constructor prologue, i.e. the base and member
706 // initializers.
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000707 EmitCtorPrologue(Ctor, CtorType, Args);
John McCall9fc6a772010-02-19 09:25:03 +0000708
709 // Emit the body of the statement.
John McCallc0bf4622010-02-23 00:48:20 +0000710 if (IsTryBody)
John McCall9fc6a772010-02-19 09:25:03 +0000711 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
712 else if (Body)
713 EmitStmt(Body);
John McCall9fc6a772010-02-19 09:25:03 +0000714
715 // Emit any cleanup blocks associated with the member or base
716 // initializers, which includes (along the exceptional path) the
717 // destructors for those members and bases that were fully
718 // constructed.
John McCallf1549f62010-07-06 01:34:17 +0000719 PopCleanupBlocks(CleanupDepth);
John McCall9fc6a772010-02-19 09:25:03 +0000720
John McCallc0bf4622010-02-23 00:48:20 +0000721 if (IsTryBody)
John McCall59a70002010-07-07 06:56:46 +0000722 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000723}
724
Anders Carlsson607d0372009-12-24 22:46:43 +0000725/// EmitCtorPrologue - This routine generates necessary code to initialize
726/// base classes and non-static data members belonging to this constructor.
Anders Carlsson607d0372009-12-24 22:46:43 +0000727void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000728 CXXCtorType CtorType,
729 FunctionArgList &Args) {
Sean Hunt059ce0d2011-05-01 07:04:31 +0000730 if (CD->isDelegatingConstructor())
731 return EmitDelegatingCXXConstructorCall(CD, Args);
732
Anders Carlsson607d0372009-12-24 22:46:43 +0000733 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000734
Sean Huntcbb67482011-01-08 20:30:50 +0000735 llvm::SmallVector<CXXCtorInitializer *, 8> MemberInitializers;
Anders Carlsson607d0372009-12-24 22:46:43 +0000736
Anders Carlsson607d0372009-12-24 22:46:43 +0000737 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
738 E = CD->init_end();
739 B != E; ++B) {
Sean Huntcbb67482011-01-08 20:30:50 +0000740 CXXCtorInitializer *Member = (*B);
Anders Carlsson607d0372009-12-24 22:46:43 +0000741
Sean Huntd49bd552011-05-03 20:19:28 +0000742 if (Member->isBaseInitializer()) {
Anders Carlsson607d0372009-12-24 22:46:43 +0000743 EmitBaseInitializer(*this, ClassDecl, Member, CtorType);
Sean Huntd49bd552011-05-03 20:19:28 +0000744 } else {
745 assert(Member->isAnyMemberInitializer() &&
746 "Delegating initializer on non-delegating constructor");
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000747 MemberInitializers.push_back(Member);
Sean Huntd49bd552011-05-03 20:19:28 +0000748 }
Anders Carlsson607d0372009-12-24 22:46:43 +0000749 }
750
Anders Carlsson603d6d12010-03-28 21:07:49 +0000751 InitializeVTablePointers(ClassDecl);
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000752
John McCallf1549f62010-07-06 01:34:17 +0000753 for (unsigned I = 0, E = MemberInitializers.size(); I != E; ++I)
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000754 EmitMemberInitializer(*this, ClassDecl, MemberInitializers[I], CD, Args);
Anders Carlsson607d0372009-12-24 22:46:43 +0000755}
756
Anders Carlssonadf5dc32011-05-15 17:36:21 +0000757static bool
758FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
759
760static bool
761HasTrivialDestructorBody(ASTContext &Context,
762 const CXXRecordDecl *BaseClassDecl,
763 const CXXRecordDecl *MostDerivedClassDecl)
764{
765 // If the destructor is trivial we don't have to check anything else.
766 if (BaseClassDecl->hasTrivialDestructor())
767 return true;
768
769 if (!BaseClassDecl->getDestructor()->hasTrivialBody())
770 return false;
771
772 // Check fields.
773 for (CXXRecordDecl::field_iterator I = BaseClassDecl->field_begin(),
774 E = BaseClassDecl->field_end(); I != E; ++I) {
775 const FieldDecl *Field = *I;
776
777 if (!FieldHasTrivialDestructorBody(Context, Field))
778 return false;
779 }
780
781 // Check non-virtual bases.
782 for (CXXRecordDecl::base_class_const_iterator I =
783 BaseClassDecl->bases_begin(), E = BaseClassDecl->bases_end();
784 I != E; ++I) {
785 if (I->isVirtual())
786 continue;
787
788 const CXXRecordDecl *NonVirtualBase =
789 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
790 if (!HasTrivialDestructorBody(Context, NonVirtualBase,
791 MostDerivedClassDecl))
792 return false;
793 }
794
795 if (BaseClassDecl == MostDerivedClassDecl) {
796 // Check virtual bases.
797 for (CXXRecordDecl::base_class_const_iterator I =
798 BaseClassDecl->vbases_begin(), E = BaseClassDecl->vbases_end();
799 I != E; ++I) {
800 const CXXRecordDecl *VirtualBase =
801 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
802 if (!HasTrivialDestructorBody(Context, VirtualBase,
803 MostDerivedClassDecl))
804 return false;
805 }
806 }
807
808 return true;
809}
810
811static bool
812FieldHasTrivialDestructorBody(ASTContext &Context,
813 const FieldDecl *Field)
814{
815 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
816
817 const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
818 if (!RT)
819 return true;
820
821 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
822 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
823}
824
Anders Carlssonffb945f2011-05-14 23:26:09 +0000825/// CanSkipVTablePointerInitialization - Check whether we need to initialize
826/// any vtable pointers before calling this destructor.
827static bool CanSkipVTablePointerInitialization(ASTContext &Context,
Anders Carlssone3d6cf22011-05-16 04:08:36 +0000828 const CXXDestructorDecl *Dtor) {
Anders Carlssonffb945f2011-05-14 23:26:09 +0000829 if (!Dtor->hasTrivialBody())
830 return false;
831
832 // Check the fields.
833 const CXXRecordDecl *ClassDecl = Dtor->getParent();
834 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
835 E = ClassDecl->field_end(); I != E; ++I) {
836 const FieldDecl *Field = *I;
Anders Carlssonffb945f2011-05-14 23:26:09 +0000837
Anders Carlssonadf5dc32011-05-15 17:36:21 +0000838 if (!FieldHasTrivialDestructorBody(Context, Field))
839 return false;
Anders Carlssonffb945f2011-05-14 23:26:09 +0000840 }
841
842 return true;
843}
844
John McCall9fc6a772010-02-19 09:25:03 +0000845/// EmitDestructorBody - Emits the body of the current destructor.
846void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
847 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
848 CXXDtorType DtorType = CurGD.getDtorType();
849
John McCall50da2ca2010-07-21 05:30:47 +0000850 // The call to operator delete in a deleting destructor happens
851 // outside of the function-try-block, which means it's always
852 // possible to delegate the destructor body to the complete
853 // destructor. Do so.
854 if (DtorType == Dtor_Deleting) {
855 EnterDtorCleanups(Dtor, Dtor_Deleting);
856 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
857 LoadCXXThis());
858 PopCleanupBlock();
859 return;
860 }
861
John McCall9fc6a772010-02-19 09:25:03 +0000862 Stmt *Body = Dtor->getBody();
863
864 // If the body is a function-try-block, enter the try before
John McCall50da2ca2010-07-21 05:30:47 +0000865 // anything else.
866 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCall9fc6a772010-02-19 09:25:03 +0000867 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +0000868 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000869
John McCall50da2ca2010-07-21 05:30:47 +0000870 // Enter the epilogue cleanups.
871 RunCleanupsScope DtorEpilogue(*this);
872
John McCall9fc6a772010-02-19 09:25:03 +0000873 // If this is the complete variant, just invoke the base variant;
874 // the epilogue will destruct the virtual bases. But we can't do
875 // this optimization if the body is a function-try-block, because
876 // we'd introduce *two* handler blocks.
John McCall50da2ca2010-07-21 05:30:47 +0000877 switch (DtorType) {
878 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
879
880 case Dtor_Complete:
881 // Enter the cleanup scopes for virtual bases.
882 EnterDtorCleanups(Dtor, Dtor_Complete);
883
884 if (!isTryBody) {
885 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
886 LoadCXXThis());
887 break;
888 }
889 // Fallthrough: act like we're in the base variant.
John McCall9fc6a772010-02-19 09:25:03 +0000890
John McCall50da2ca2010-07-21 05:30:47 +0000891 case Dtor_Base:
892 // Enter the cleanup scopes for fields and non-virtual bases.
893 EnterDtorCleanups(Dtor, Dtor_Base);
894
895 // Initialize the vtable pointers before entering the body.
Anders Carlssonffb945f2011-05-14 23:26:09 +0000896 if (!CanSkipVTablePointerInitialization(getContext(), Dtor))
897 InitializeVTablePointers(Dtor->getParent());
John McCall50da2ca2010-07-21 05:30:47 +0000898
899 if (isTryBody)
900 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
901 else if (Body)
902 EmitStmt(Body);
903 else {
904 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
905 // nothing to do besides what's in the epilogue
906 }
Fariborz Jahanian5abec142011-02-02 23:12:46 +0000907 // -fapple-kext must inline any call to this dtor into
908 // the caller's body.
909 if (getContext().getLangOptions().AppleKext)
910 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
John McCall50da2ca2010-07-21 05:30:47 +0000911 break;
John McCall9fc6a772010-02-19 09:25:03 +0000912 }
913
John McCall50da2ca2010-07-21 05:30:47 +0000914 // Jump out through the epilogue cleanups.
915 DtorEpilogue.ForceCleanup();
John McCall9fc6a772010-02-19 09:25:03 +0000916
917 // Exit the try if applicable.
918 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +0000919 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000920}
921
John McCall50da2ca2010-07-21 05:30:47 +0000922namespace {
923 /// Call the operator delete associated with the current destructor.
John McCall1f0fca52010-07-21 07:22:38 +0000924 struct CallDtorDelete : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000925 CallDtorDelete() {}
926
927 void Emit(CodeGenFunction &CGF, bool IsForEH) {
928 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
929 const CXXRecordDecl *ClassDecl = Dtor->getParent();
930 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
931 CGF.getContext().getTagDeclType(ClassDecl));
932 }
933 };
934
John McCall1f0fca52010-07-21 07:22:38 +0000935 struct CallArrayFieldDtor : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000936 const FieldDecl *Field;
937 CallArrayFieldDtor(const FieldDecl *Field) : Field(Field) {}
938
939 void Emit(CodeGenFunction &CGF, bool IsForEH) {
John McCallf85e1932011-06-15 23:02:42 +0000940 QualType FieldType = Field->getType();
941 QualType BaseType = CGF.getContext().getBaseElementType(FieldType);
John McCall50da2ca2010-07-21 05:30:47 +0000942 const CXXRecordDecl *FieldClassDecl = BaseType->getAsCXXRecordDecl();
943
944 llvm::Value *ThisPtr = CGF.LoadCXXThis();
945 LValue LHS = CGF.EmitLValueForField(ThisPtr, Field,
946 // FIXME: Qualifiers?
947 /*CVRQualifiers=*/0);
948
John McCallf85e1932011-06-15 23:02:42 +0000949 const llvm::Type *BasePtr
950 = CGF.ConvertType(BaseType)->getPointerTo();
951 llvm::Value *BaseAddrPtr
952 = CGF.Builder.CreateBitCast(LHS.getAddress(), BasePtr);
953 const ConstantArrayType *Array
954 = CGF.getContext().getAsConstantArrayType(FieldType);
John McCall50da2ca2010-07-21 05:30:47 +0000955 CGF.EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(),
956 Array, BaseAddrPtr);
957 }
958 };
959
John McCall1f0fca52010-07-21 07:22:38 +0000960 struct CallFieldDtor : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000961 const FieldDecl *Field;
962 CallFieldDtor(const FieldDecl *Field) : Field(Field) {}
963
964 void Emit(CodeGenFunction &CGF, bool IsForEH) {
965 const CXXRecordDecl *FieldClassDecl =
966 Field->getType()->getAsCXXRecordDecl();
967
968 llvm::Value *ThisPtr = CGF.LoadCXXThis();
969 LValue LHS = CGF.EmitLValueForField(ThisPtr, Field,
970 // FIXME: Qualifiers?
971 /*CVRQualifiers=*/0);
972
973 CGF.EmitCXXDestructorCall(FieldClassDecl->getDestructor(),
974 Dtor_Complete, /*ForVirtualBase=*/false,
975 LHS.getAddress());
976 }
977 };
978}
979
Anders Carlsson607d0372009-12-24 22:46:43 +0000980/// EmitDtorEpilogue - Emit all code that comes at the end of class's
981/// destructor. This is to call destructors on members and base classes
982/// in reverse order of their construction.
John McCall50da2ca2010-07-21 05:30:47 +0000983void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
984 CXXDtorType DtorType) {
Anders Carlsson607d0372009-12-24 22:46:43 +0000985 assert(!DD->isTrivial() &&
986 "Should not emit dtor epilogue for trivial dtor!");
987
John McCall50da2ca2010-07-21 05:30:47 +0000988 // The deleting-destructor phase just needs to call the appropriate
989 // operator delete that Sema picked up.
John McCall3b477332010-02-18 19:59:28 +0000990 if (DtorType == Dtor_Deleting) {
991 assert(DD->getOperatorDelete() &&
992 "operator delete missing - EmitDtorEpilogue");
John McCall1f0fca52010-07-21 07:22:38 +0000993 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
John McCall3b477332010-02-18 19:59:28 +0000994 return;
995 }
996
John McCall50da2ca2010-07-21 05:30:47 +0000997 const CXXRecordDecl *ClassDecl = DD->getParent();
998
999 // The complete-destructor phase just destructs all the virtual bases.
John McCall3b477332010-02-18 19:59:28 +00001000 if (DtorType == Dtor_Complete) {
John McCall50da2ca2010-07-21 05:30:47 +00001001
1002 // We push them in the forward order so that they'll be popped in
1003 // the reverse order.
1004 for (CXXRecordDecl::base_class_const_iterator I =
1005 ClassDecl->vbases_begin(), E = ClassDecl->vbases_end();
John McCall3b477332010-02-18 19:59:28 +00001006 I != E; ++I) {
1007 const CXXBaseSpecifier &Base = *I;
1008 CXXRecordDecl *BaseClassDecl
1009 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1010
1011 // Ignore trivial destructors.
1012 if (BaseClassDecl->hasTrivialDestructor())
1013 continue;
John McCall50da2ca2010-07-21 05:30:47 +00001014
John McCall1f0fca52010-07-21 07:22:38 +00001015 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1016 BaseClassDecl,
1017 /*BaseIsVirtual*/ true);
John McCall3b477332010-02-18 19:59:28 +00001018 }
John McCall50da2ca2010-07-21 05:30:47 +00001019
John McCall3b477332010-02-18 19:59:28 +00001020 return;
1021 }
1022
1023 assert(DtorType == Dtor_Base);
John McCall50da2ca2010-07-21 05:30:47 +00001024
1025 // Destroy non-virtual bases.
1026 for (CXXRecordDecl::base_class_const_iterator I =
1027 ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) {
1028 const CXXBaseSpecifier &Base = *I;
1029
1030 // Ignore virtual bases.
1031 if (Base.isVirtual())
1032 continue;
1033
1034 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
1035
1036 // Ignore trivial destructors.
1037 if (BaseClassDecl->hasTrivialDestructor())
1038 continue;
John McCall3b477332010-02-18 19:59:28 +00001039
John McCall1f0fca52010-07-21 07:22:38 +00001040 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1041 BaseClassDecl,
1042 /*BaseIsVirtual*/ false);
John McCall50da2ca2010-07-21 05:30:47 +00001043 }
1044
1045 // Destroy direct fields.
Anders Carlsson607d0372009-12-24 22:46:43 +00001046 llvm::SmallVector<const FieldDecl *, 16> FieldDecls;
1047 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1048 E = ClassDecl->field_end(); I != E; ++I) {
1049 const FieldDecl *Field = *I;
1050
1051 QualType FieldType = getContext().getCanonicalType(Field->getType());
John McCall50da2ca2010-07-21 05:30:47 +00001052 const ConstantArrayType *Array =
1053 getContext().getAsConstantArrayType(FieldType);
1054 if (Array)
1055 FieldType = getContext().getBaseElementType(Array->getElementType());
John McCall50da2ca2010-07-21 05:30:47 +00001056
John McCallf85e1932011-06-15 23:02:42 +00001057 switch (FieldType.isDestructedType()) {
1058 case QualType::DK_none:
1059 continue;
1060
1061 case QualType::DK_cxx_destructor:
1062 if (Array)
1063 EHStack.pushCleanup<CallArrayFieldDtor>(NormalAndEHCleanup, Field);
1064 else
1065 EHStack.pushCleanup<CallFieldDtor>(NormalAndEHCleanup, Field);
1066 break;
1067
1068 case QualType::DK_objc_strong_lifetime:
1069 PushARCFieldReleaseCleanup(getARCCleanupKind(), Field);
1070 break;
1071
1072 case QualType::DK_objc_weak_lifetime:
1073 PushARCFieldWeakReleaseCleanup(getARCCleanupKind(), Field);
1074 break;
1075 }
Anders Carlsson607d0372009-12-24 22:46:43 +00001076 }
Anders Carlsson607d0372009-12-24 22:46:43 +00001077}
1078
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001079/// EmitCXXAggrConstructorCall - This routine essentially creates a (nested)
1080/// for-loop to call the default constructor on individual members of the
1081/// array.
1082/// 'D' is the default constructor for elements of the array, 'ArrayTy' is the
1083/// array type and 'ArrayPtr' points to the beginning fo the array.
1084/// It is assumed that all relevant checks have been made by the caller.
Douglas Gregor59174c02010-07-21 01:10:17 +00001085///
1086/// \param ZeroInitialization True if each element should be zero-initialized
1087/// before it is constructed.
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001088void
1089CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
Douglas Gregor59174c02010-07-21 01:10:17 +00001090 const ConstantArrayType *ArrayTy,
1091 llvm::Value *ArrayPtr,
1092 CallExpr::const_arg_iterator ArgBeg,
1093 CallExpr::const_arg_iterator ArgEnd,
1094 bool ZeroInitialization) {
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001095
1096 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
1097 llvm::Value * NumElements =
1098 llvm::ConstantInt::get(SizeTy,
1099 getContext().getConstantArrayElementCount(ArrayTy));
1100
Douglas Gregor59174c02010-07-21 01:10:17 +00001101 EmitCXXAggrConstructorCall(D, NumElements, ArrayPtr, ArgBeg, ArgEnd,
1102 ZeroInitialization);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001103}
1104
1105void
1106CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
1107 llvm::Value *NumElements,
1108 llvm::Value *ArrayPtr,
1109 CallExpr::const_arg_iterator ArgBeg,
Douglas Gregor59174c02010-07-21 01:10:17 +00001110 CallExpr::const_arg_iterator ArgEnd,
1111 bool ZeroInitialization) {
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001112 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
1113
1114 // Create a temporary for the loop index and initialize it with 0.
1115 llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index");
1116 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
1117 Builder.CreateStore(Zero, IndexPtr);
1118
1119 // Start the loop with a block that tests the condition.
1120 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1121 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1122
1123 EmitBlock(CondBlock);
1124
1125 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1126
1127 // Generate: if (loop-index < number-of-elements fall to the loop body,
1128 // otherwise, go to the block after the for-loop.
1129 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1130 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless");
1131 // If the condition is true, execute the body.
1132 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
1133
1134 EmitBlock(ForBody);
1135
1136 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1137 // Inside the loop body, emit the constructor call on the array element.
1138 Counter = Builder.CreateLoad(IndexPtr);
1139 llvm::Value *Address = Builder.CreateInBoundsGEP(ArrayPtr, Counter,
1140 "arrayidx");
1141
Douglas Gregor59174c02010-07-21 01:10:17 +00001142 // Zero initialize the storage, if requested.
1143 if (ZeroInitialization)
1144 EmitNullInitialization(Address,
1145 getContext().getTypeDeclType(D->getParent()));
1146
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001147 // C++ [class.temporary]p4:
1148 // There are two contexts in which temporaries are destroyed at a different
1149 // point than the end of the full-expression. The first context is when a
1150 // default constructor is called to initialize an element of an array.
1151 // If the constructor has one or more default arguments, the destruction of
1152 // every temporary created in a default argument expression is sequenced
1153 // before the construction of the next array element, if any.
1154
1155 // Keep track of the current number of live temporaries.
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001156 {
John McCallf1549f62010-07-06 01:34:17 +00001157 RunCleanupsScope Scope(*this);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001158
Anders Carlsson155ed4a2010-05-02 23:20:53 +00001159 EmitCXXConstructorCall(D, Ctor_Complete, /*ForVirtualBase=*/false, Address,
Anders Carlsson24eb78e2010-05-02 23:01:10 +00001160 ArgBeg, ArgEnd);
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001161 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001162
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001163 EmitBlock(ContinueBlock);
1164
1165 // Emit the increment of the loop counter.
1166 llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1);
1167 Counter = Builder.CreateLoad(IndexPtr);
1168 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1169 Builder.CreateStore(NextVal, IndexPtr);
1170
1171 // Finally, branch back up to the condition for the next iteration.
1172 EmitBranch(CondBlock);
1173
1174 // Emit the fall-through block.
1175 EmitBlock(AfterFor, true);
1176}
1177
1178/// EmitCXXAggrDestructorCall - calls the default destructor on array
1179/// elements in reverse order of construction.
1180void
1181CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
1182 const ArrayType *Array,
1183 llvm::Value *This) {
1184 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1185 assert(CA && "Do we support VLA for destruction ?");
1186 uint64_t ElementCount = getContext().getConstantArrayElementCount(CA);
1187
1188 const llvm::Type *SizeLTy = ConvertType(getContext().getSizeType());
1189 llvm::Value* ElementCountPtr = llvm::ConstantInt::get(SizeLTy, ElementCount);
1190 EmitCXXAggrDestructorCall(D, ElementCountPtr, This);
1191}
1192
1193/// EmitCXXAggrDestructorCall - calls the default destructor on array
1194/// elements in reverse order of construction.
1195void
1196CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
1197 llvm::Value *UpperCount,
1198 llvm::Value *This) {
1199 const llvm::Type *SizeLTy = ConvertType(getContext().getSizeType());
1200 llvm::Value *One = llvm::ConstantInt::get(SizeLTy, 1);
1201
1202 // Create a temporary for the loop index and initialize it with count of
1203 // array elements.
1204 llvm::Value *IndexPtr = CreateTempAlloca(SizeLTy, "loop.index");
1205
1206 // Store the number of elements in the index pointer.
1207 Builder.CreateStore(UpperCount, IndexPtr);
1208
1209 // Start the loop with a block that tests the condition.
1210 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1211 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1212
1213 EmitBlock(CondBlock);
1214
1215 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1216
1217 // Generate: if (loop-index != 0 fall to the loop body,
1218 // otherwise, go to the block after the for-loop.
1219 llvm::Value* zeroConstant =
1220 llvm::Constant::getNullValue(SizeLTy);
1221 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1222 llvm::Value *IsNE = Builder.CreateICmpNE(Counter, zeroConstant,
1223 "isne");
1224 // If the condition is true, execute the body.
1225 Builder.CreateCondBr(IsNE, ForBody, AfterFor);
1226
1227 EmitBlock(ForBody);
1228
1229 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1230 // Inside the loop body, emit the constructor call on the array element.
1231 Counter = Builder.CreateLoad(IndexPtr);
1232 Counter = Builder.CreateSub(Counter, One);
1233 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
Anders Carlsson8e6404c2010-05-02 23:29:11 +00001234 EmitCXXDestructorCall(D, Dtor_Complete, /*ForVirtualBase=*/false, Address);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001235
1236 EmitBlock(ContinueBlock);
1237
1238 // Emit the decrement of the loop counter.
1239 Counter = Builder.CreateLoad(IndexPtr);
1240 Counter = Builder.CreateSub(Counter, One, "dec");
1241 Builder.CreateStore(Counter, IndexPtr);
1242
1243 // Finally, branch back up to the condition for the next iteration.
1244 EmitBranch(CondBlock);
1245
1246 // Emit the fall-through block.
1247 EmitBlock(AfterFor, true);
1248}
1249
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001250void
1251CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
Anders Carlsson155ed4a2010-05-02 23:20:53 +00001252 CXXCtorType Type, bool ForVirtualBase,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001253 llvm::Value *This,
1254 CallExpr::const_arg_iterator ArgBeg,
1255 CallExpr::const_arg_iterator ArgEnd) {
Devang Patel3ee36af2011-02-22 20:55:26 +00001256
1257 CGDebugInfo *DI = getDebugInfo();
1258 if (DI && CGM.getCodeGenOpts().LimitDebugInfo) {
1259 // If debug info for this class has been emitted then this is the right time
1260 // to do so.
1261 const CXXRecordDecl *Parent = D->getParent();
1262 DI->getOrCreateRecordType(CGM.getContext().getTypeDeclType(Parent),
1263 Parent->getLocation());
1264 }
1265
John McCall8b6bbeb2010-02-06 00:25:16 +00001266 if (D->isTrivial()) {
1267 if (ArgBeg == ArgEnd) {
1268 // Trivial default constructor, no codegen required.
1269 assert(D->isDefaultConstructor() &&
1270 "trivial 0-arg ctor not a default ctor");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001271 return;
1272 }
John McCall8b6bbeb2010-02-06 00:25:16 +00001273
1274 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
1275 assert(D->isCopyConstructor() && "trivial 1-arg ctor not a copy ctor");
1276
John McCall8b6bbeb2010-02-06 00:25:16 +00001277 const Expr *E = (*ArgBeg);
1278 QualType Ty = E->getType();
1279 llvm::Value *Src = EmitLValue(E).getAddress();
1280 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001281 return;
1282 }
1283
Anders Carlsson314e6222010-05-02 23:33:10 +00001284 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(D, Type), ForVirtualBase);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001285 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
1286
Anders Carlssonc997d422010-01-02 01:01:18 +00001287 EmitCXXMemberCall(D, Callee, ReturnValueSlot(), This, VTT, ArgBeg, ArgEnd);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001288}
1289
John McCallc0bf4622010-02-23 00:48:20 +00001290void
Fariborz Jahanian34999872010-11-13 21:53:34 +00001291CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
1292 llvm::Value *This, llvm::Value *Src,
1293 CallExpr::const_arg_iterator ArgBeg,
1294 CallExpr::const_arg_iterator ArgEnd) {
1295 if (D->isTrivial()) {
1296 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
1297 assert(D->isCopyConstructor() && "trivial 1-arg ctor not a copy ctor");
1298 EmitAggregateCopy(This, Src, (*ArgBeg)->getType());
1299 return;
1300 }
1301 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D,
1302 clang::Ctor_Complete);
1303 assert(D->isInstance() &&
1304 "Trying to emit a member call expr on a static method!");
1305
1306 const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
1307
1308 CallArgList Args;
1309
1310 // Push the this ptr.
Eli Friedman04c9a492011-05-02 17:57:46 +00001311 Args.add(RValue::get(This), D->getThisType(getContext()));
Fariborz Jahanian34999872010-11-13 21:53:34 +00001312
1313
1314 // Push the src ptr.
1315 QualType QT = *(FPT->arg_type_begin());
1316 const llvm::Type *t = CGM.getTypes().ConvertType(QT);
1317 Src = Builder.CreateBitCast(Src, t);
Eli Friedman04c9a492011-05-02 17:57:46 +00001318 Args.add(RValue::get(Src), QT);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001319
1320 // Skip over first argument (Src).
1321 ++ArgBeg;
1322 CallExpr::const_arg_iterator Arg = ArgBeg;
1323 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin()+1,
1324 E = FPT->arg_type_end(); I != E; ++I, ++Arg) {
1325 assert(Arg != ArgEnd && "Running over edge of argument list!");
John McCall413ebdb2011-03-11 20:59:21 +00001326 EmitCallArg(Args, *Arg, *I);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001327 }
1328 // Either we've emitted all the call args, or we have a call to a
1329 // variadic function.
1330 assert((Arg == ArgEnd || FPT->isVariadic()) &&
1331 "Extra arguments in non-variadic function!");
1332 // If we still have any arguments, emit them using the type of the argument.
1333 for (; Arg != ArgEnd; ++Arg) {
1334 QualType ArgType = Arg->getType();
John McCall413ebdb2011-03-11 20:59:21 +00001335 EmitCallArg(Args, *Arg, ArgType);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001336 }
1337
1338 QualType ResultType = FPT->getResultType();
1339 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args,
1340 FPT->getExtInfo()),
1341 Callee, ReturnValueSlot(), Args, D);
1342}
1343
1344void
John McCallc0bf4622010-02-23 00:48:20 +00001345CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1346 CXXCtorType CtorType,
1347 const FunctionArgList &Args) {
1348 CallArgList DelegateArgs;
1349
1350 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
1351 assert(I != E && "no parameters to constructor");
1352
1353 // this
Eli Friedman04c9a492011-05-02 17:57:46 +00001354 DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType());
John McCallc0bf4622010-02-23 00:48:20 +00001355 ++I;
1356
1357 // vtt
Anders Carlsson314e6222010-05-02 23:33:10 +00001358 if (llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(Ctor, CtorType),
1359 /*ForVirtualBase=*/false)) {
John McCallc0bf4622010-02-23 00:48:20 +00001360 QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
Eli Friedman04c9a492011-05-02 17:57:46 +00001361 DelegateArgs.add(RValue::get(VTT), VoidPP);
John McCallc0bf4622010-02-23 00:48:20 +00001362
Anders Carlssonaf440352010-03-23 04:11:45 +00001363 if (CodeGenVTables::needsVTTParameter(CurGD)) {
John McCallc0bf4622010-02-23 00:48:20 +00001364 assert(I != E && "cannot skip vtt parameter, already done with args");
John McCalld26bc762011-03-09 04:27:21 +00001365 assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
John McCallc0bf4622010-02-23 00:48:20 +00001366 ++I;
1367 }
1368 }
1369
1370 // Explicit arguments.
1371 for (; I != E; ++I) {
John McCall413ebdb2011-03-11 20:59:21 +00001372 const VarDecl *param = *I;
1373 EmitDelegateCallArg(DelegateArgs, param);
John McCallc0bf4622010-02-23 00:48:20 +00001374 }
1375
1376 EmitCall(CGM.getTypes().getFunctionInfo(Ctor, CtorType),
1377 CGM.GetAddrOfCXXConstructor(Ctor, CtorType),
1378 ReturnValueSlot(), DelegateArgs, Ctor);
1379}
1380
Sean Huntb76af9c2011-05-03 23:05:34 +00001381namespace {
1382 struct CallDelegatingCtorDtor : EHScopeStack::Cleanup {
1383 const CXXDestructorDecl *Dtor;
1384 llvm::Value *Addr;
1385 CXXDtorType Type;
1386
1387 CallDelegatingCtorDtor(const CXXDestructorDecl *D, llvm::Value *Addr,
1388 CXXDtorType Type)
1389 : Dtor(D), Addr(Addr), Type(Type) {}
1390
1391 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1392 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
1393 Addr);
1394 }
1395 };
1396}
1397
Sean Hunt059ce0d2011-05-01 07:04:31 +00001398void
1399CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
1400 const FunctionArgList &Args) {
1401 assert(Ctor->isDelegatingConstructor());
1402
1403 llvm::Value *ThisPtr = LoadCXXThis();
1404
John McCallf85e1932011-06-15 23:02:42 +00001405 AggValueSlot AggSlot =
1406 AggValueSlot::forAddr(ThisPtr, Qualifiers(), /*Lifetime*/ true);
Sean Hunt059ce0d2011-05-01 07:04:31 +00001407
1408 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
Sean Hunt059ce0d2011-05-01 07:04:31 +00001409
Sean Huntb76af9c2011-05-03 23:05:34 +00001410 const CXXRecordDecl *ClassDecl = Ctor->getParent();
1411 if (CGM.getLangOptions().Exceptions && !ClassDecl->hasTrivialDestructor()) {
1412 CXXDtorType Type =
1413 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
1414
1415 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
1416 ClassDecl->getDestructor(),
1417 ThisPtr, Type);
1418 }
1419}
Sean Hunt059ce0d2011-05-01 07:04:31 +00001420
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001421void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
1422 CXXDtorType Type,
Anders Carlsson8e6404c2010-05-02 23:29:11 +00001423 bool ForVirtualBase,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001424 llvm::Value *This) {
Anders Carlsson314e6222010-05-02 23:33:10 +00001425 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(DD, Type),
1426 ForVirtualBase);
Fariborz Jahanianccd52592011-02-01 23:22:34 +00001427 llvm::Value *Callee = 0;
1428 if (getContext().getLangOptions().AppleKext)
Fariborz Jahanian771c6782011-02-03 19:27:17 +00001429 Callee = BuildAppleKextVirtualDestructorCall(DD, Type,
1430 DD->getParent());
Fariborz Jahanianccd52592011-02-01 23:22:34 +00001431
1432 if (!Callee)
1433 Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001434
Anders Carlssonc997d422010-01-02 01:01:18 +00001435 EmitCXXMemberCall(DD, Callee, ReturnValueSlot(), This, VTT, 0, 0);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001436}
1437
John McCall291ae942010-07-21 01:41:18 +00001438namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001439 struct CallLocalDtor : EHScopeStack::Cleanup {
John McCall291ae942010-07-21 01:41:18 +00001440 const CXXDestructorDecl *Dtor;
1441 llvm::Value *Addr;
1442
1443 CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
1444 : Dtor(D), Addr(Addr) {}
1445
1446 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1447 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1448 /*ForVirtualBase=*/false, Addr);
1449 }
1450 };
1451}
1452
John McCall81407d42010-07-21 06:29:51 +00001453void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
1454 llvm::Value *Addr) {
John McCall1f0fca52010-07-21 07:22:38 +00001455 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
John McCall81407d42010-07-21 06:29:51 +00001456}
1457
John McCallf1549f62010-07-06 01:34:17 +00001458void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
1459 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
1460 if (!ClassDecl) return;
1461 if (ClassDecl->hasTrivialDestructor()) return;
1462
1463 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCall642a75f2011-04-28 02:15:35 +00001464 assert(D && D->isUsed() && "destructor not marked as used!");
John McCall81407d42010-07-21 06:29:51 +00001465 PushDestructorCleanup(D, Addr);
John McCallf1549f62010-07-06 01:34:17 +00001466}
1467
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001468llvm::Value *
Anders Carlssonbb7e17b2010-01-31 01:36:53 +00001469CodeGenFunction::GetVirtualBaseClassOffset(llvm::Value *This,
1470 const CXXRecordDecl *ClassDecl,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001471 const CXXRecordDecl *BaseClassDecl) {
Dan Gohman043fb9a2010-10-26 18:44:08 +00001472 llvm::Value *VTablePtr = GetVTablePtr(This, Int8PtrTy);
Ken Dyck14c65ca2011-04-07 12:37:09 +00001473 CharUnits VBaseOffsetOffset =
Anders Carlssonaf440352010-03-23 04:11:45 +00001474 CGM.getVTables().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001475
1476 llvm::Value *VBaseOffsetPtr =
Ken Dyck14c65ca2011-04-07 12:37:09 +00001477 Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1478 "vbase.offset.ptr");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001479 const llvm::Type *PtrDiffTy =
1480 ConvertType(getContext().getPointerDiffType());
1481
1482 VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr,
1483 PtrDiffTy->getPointerTo());
1484
1485 llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1486
1487 return VBaseOffset;
1488}
1489
Anders Carlssond103f9f2010-03-28 19:40:00 +00001490void
1491CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001492 const CXXRecordDecl *NearestVBase,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001493 CharUnits OffsetFromNearestVBase,
Anders Carlssond103f9f2010-03-28 19:40:00 +00001494 llvm::Constant *VTable,
1495 const CXXRecordDecl *VTableClass) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001496 const CXXRecordDecl *RD = Base.getBase();
1497
Anders Carlssond103f9f2010-03-28 19:40:00 +00001498 // Compute the address point.
Anders Carlssonc83f1062010-03-29 01:08:49 +00001499 llvm::Value *VTableAddressPoint;
Anders Carlsson851853d2010-03-29 02:38:51 +00001500
Anders Carlssonc83f1062010-03-29 01:08:49 +00001501 // Check if we need to use a vtable from the VTT.
Anders Carlsson851853d2010-03-29 02:38:51 +00001502 if (CodeGenVTables::needsVTTParameter(CurGD) &&
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001503 (RD->getNumVBases() || NearestVBase)) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001504 // Get the secondary vpointer index.
1505 uint64_t VirtualPointerIndex =
1506 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1507
1508 /// Load the VTT.
1509 llvm::Value *VTT = LoadCXXVTT();
1510 if (VirtualPointerIndex)
1511 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1512
1513 // And load the address point from the VTT.
1514 VTableAddressPoint = Builder.CreateLoad(VTT);
1515 } else {
Anders Carlsson64c9eca2010-03-29 02:08:26 +00001516 uint64_t AddressPoint = CGM.getVTables().getAddressPoint(Base, VTableClass);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001517 VTableAddressPoint =
Anders Carlssond103f9f2010-03-28 19:40:00 +00001518 Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001519 }
Anders Carlssond103f9f2010-03-28 19:40:00 +00001520
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001521 // Compute where to store the address point.
Anders Carlsson8246cc72010-05-03 00:29:58 +00001522 llvm::Value *VirtualOffset = 0;
Ken Dyck9a8ad9b2011-03-23 00:45:26 +00001523 CharUnits NonVirtualOffset = CharUnits::Zero();
Anders Carlsson3e79c302010-04-20 18:05:10 +00001524
1525 if (CodeGenVTables::needsVTTParameter(CurGD) && NearestVBase) {
1526 // We need to use the virtual base offset offset because the virtual base
1527 // might have a different offset in the most derived class.
Anders Carlsson8246cc72010-05-03 00:29:58 +00001528 VirtualOffset = GetVirtualBaseClassOffset(LoadCXXThis(), VTableClass,
1529 NearestVBase);
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001530 NonVirtualOffset = OffsetFromNearestVBase;
Anders Carlsson3e79c302010-04-20 18:05:10 +00001531 } else {
Anders Carlsson8246cc72010-05-03 00:29:58 +00001532 // We can just use the base offset in the complete class.
Ken Dyck4230d522011-03-24 01:21:01 +00001533 NonVirtualOffset = Base.getBaseOffset();
Anders Carlsson3e79c302010-04-20 18:05:10 +00001534 }
Anders Carlsson8246cc72010-05-03 00:29:58 +00001535
1536 // Apply the offsets.
1537 llvm::Value *VTableField = LoadCXXThis();
1538
Ken Dyck9a8ad9b2011-03-23 00:45:26 +00001539 if (!NonVirtualOffset.isZero() || VirtualOffset)
Anders Carlsson8246cc72010-05-03 00:29:58 +00001540 VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
1541 NonVirtualOffset,
1542 VirtualOffset);
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001543
Anders Carlssond103f9f2010-03-28 19:40:00 +00001544 // Finally, store the address point.
1545 const llvm::Type *AddressPointPtrTy =
1546 VTableAddressPoint->getType()->getPointerTo();
1547 VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
1548 Builder.CreateStore(VTableAddressPoint, VTableField);
1549}
1550
Anders Carlsson603d6d12010-03-28 21:07:49 +00001551void
1552CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001553 const CXXRecordDecl *NearestVBase,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001554 CharUnits OffsetFromNearestVBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001555 bool BaseIsNonVirtualPrimaryBase,
1556 llvm::Constant *VTable,
1557 const CXXRecordDecl *VTableClass,
1558 VisitedVirtualBasesSetTy& VBases) {
1559 // If this base is a non-virtual primary base the address point has already
1560 // been set.
1561 if (!BaseIsNonVirtualPrimaryBase) {
1562 // Initialize the vtable pointer for this base.
Anders Carlsson42358402010-05-03 00:07:07 +00001563 InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
1564 VTable, VTableClass);
Anders Carlsson603d6d12010-03-28 21:07:49 +00001565 }
1566
1567 const CXXRecordDecl *RD = Base.getBase();
1568
1569 // Traverse bases.
1570 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1571 E = RD->bases_end(); I != E; ++I) {
1572 CXXRecordDecl *BaseDecl
1573 = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1574
1575 // Ignore classes without a vtable.
1576 if (!BaseDecl->isDynamicClass())
1577 continue;
1578
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001579 CharUnits BaseOffset;
1580 CharUnits BaseOffsetFromNearestVBase;
Anders Carlsson14da9de2010-03-29 01:16:41 +00001581 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001582
1583 if (I->isVirtual()) {
1584 // Check if we've visited this virtual base before.
1585 if (!VBases.insert(BaseDecl))
1586 continue;
1587
1588 const ASTRecordLayout &Layout =
1589 getContext().getASTRecordLayout(VTableClass);
1590
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001591 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
1592 BaseOffsetFromNearestVBase = CharUnits::Zero();
Anders Carlsson14da9de2010-03-29 01:16:41 +00001593 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001594 } else {
1595 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1596
Ken Dyck4230d522011-03-24 01:21:01 +00001597 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson42358402010-05-03 00:07:07 +00001598 BaseOffsetFromNearestVBase =
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001599 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson14da9de2010-03-29 01:16:41 +00001600 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001601 }
1602
Ken Dyck4230d522011-03-24 01:21:01 +00001603 InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001604 I->isVirtual() ? BaseDecl : NearestVBase,
Anders Carlsson42358402010-05-03 00:07:07 +00001605 BaseOffsetFromNearestVBase,
Anders Carlsson14da9de2010-03-29 01:16:41 +00001606 BaseDeclIsNonVirtualPrimaryBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001607 VTable, VTableClass, VBases);
1608 }
1609}
1610
1611void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
1612 // Ignore classes without a vtable.
Anders Carlsson07036902010-03-26 04:39:42 +00001613 if (!RD->isDynamicClass())
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001614 return;
1615
Anders Carlsson07036902010-03-26 04:39:42 +00001616 // Get the VTable.
1617 llvm::Constant *VTable = CGM.getVTables().GetAddrOfVTable(RD);
Anders Carlsson5c6c1d92010-03-24 03:57:14 +00001618
Anders Carlsson603d6d12010-03-28 21:07:49 +00001619 // Initialize the vtable pointers for this class and all of its bases.
1620 VisitedVirtualBasesSetTy VBases;
Ken Dyck4230d522011-03-24 01:21:01 +00001621 InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()),
1622 /*NearestVBase=*/0,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001623 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
Anders Carlsson603d6d12010-03-28 21:07:49 +00001624 /*BaseIsNonVirtualPrimaryBase=*/false,
1625 VTable, RD, VBases);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001626}
Dan Gohman043fb9a2010-10-26 18:44:08 +00001627
1628llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
1629 const llvm::Type *Ty) {
1630 llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
1631 return Builder.CreateLoad(VTablePtrSrc, "vtable");
1632}
Anders Carlssona2447e02011-05-08 20:32:23 +00001633
1634static const CXXRecordDecl *getMostDerivedClassDecl(const Expr *Base) {
1635 const Expr *E = Base;
1636
1637 while (true) {
1638 E = E->IgnoreParens();
1639 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
1640 if (CE->getCastKind() == CK_DerivedToBase ||
1641 CE->getCastKind() == CK_UncheckedDerivedToBase ||
1642 CE->getCastKind() == CK_NoOp) {
1643 E = CE->getSubExpr();
1644 continue;
1645 }
1646 }
1647
1648 break;
1649 }
1650
1651 QualType DerivedType = E->getType();
1652 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
1653 DerivedType = PTy->getPointeeType();
1654
1655 return cast<CXXRecordDecl>(DerivedType->castAs<RecordType>()->getDecl());
1656}
1657
1658// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
1659// quite what we want.
1660static const Expr *skipNoOpCastsAndParens(const Expr *E) {
1661 while (true) {
1662 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
1663 E = PE->getSubExpr();
1664 continue;
1665 }
1666
1667 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
1668 if (CE->getCastKind() == CK_NoOp) {
1669 E = CE->getSubExpr();
1670 continue;
1671 }
1672 }
1673 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1674 if (UO->getOpcode() == UO_Extension) {
1675 E = UO->getSubExpr();
1676 continue;
1677 }
1678 }
1679 return E;
1680 }
1681}
1682
1683/// canDevirtualizeMemberFunctionCall - Checks whether the given virtual member
1684/// function call on the given expr can be devirtualized.
1685/// expr can be devirtualized.
1686static bool canDevirtualizeMemberFunctionCall(const Expr *Base,
1687 const CXXMethodDecl *MD) {
1688 // If the most derived class is marked final, we know that no subclass can
1689 // override this member function and so we can devirtualize it. For example:
1690 //
1691 // struct A { virtual void f(); }
1692 // struct B final : A { };
1693 //
1694 // void f(B *b) {
1695 // b->f();
1696 // }
1697 //
1698 const CXXRecordDecl *MostDerivedClassDecl = getMostDerivedClassDecl(Base);
1699 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
1700 return true;
1701
1702 // If the member function is marked 'final', we know that it can't be
1703 // overridden and can therefore devirtualize it.
1704 if (MD->hasAttr<FinalAttr>())
1705 return true;
1706
1707 // Similarly, if the class itself is marked 'final' it can't be overridden
1708 // and we can therefore devirtualize the member function call.
1709 if (MD->getParent()->hasAttr<FinalAttr>())
1710 return true;
1711
1712 Base = skipNoOpCastsAndParens(Base);
1713 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
1714 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
1715 // This is a record decl. We know the type and can devirtualize it.
1716 return VD->getType()->isRecordType();
1717 }
1718
1719 return false;
1720 }
1721
1722 // We can always devirtualize calls on temporary object expressions.
1723 if (isa<CXXConstructExpr>(Base))
1724 return true;
1725
1726 // And calls on bound temporaries.
1727 if (isa<CXXBindTemporaryExpr>(Base))
1728 return true;
1729
1730 // Check if this is a call expr that returns a record type.
1731 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
1732 return CE->getCallReturnType()->isRecordType();
1733
1734 // We can't devirtualize the call.
1735 return false;
1736}
1737
1738static bool UseVirtualCall(ASTContext &Context,
1739 const CXXOperatorCallExpr *CE,
1740 const CXXMethodDecl *MD) {
1741 if (!MD->isVirtual())
1742 return false;
1743
1744 // When building with -fapple-kext, all calls must go through the vtable since
1745 // the kernel linker can do runtime patching of vtables.
1746 if (Context.getLangOptions().AppleKext)
1747 return true;
1748
1749 return !canDevirtualizeMemberFunctionCall(CE->getArg(0), MD);
1750}
1751
1752llvm::Value *
1753CodeGenFunction::EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E,
1754 const CXXMethodDecl *MD,
1755 llvm::Value *This) {
1756 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1757 const llvm::Type *Ty =
1758 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1759 FPT->isVariadic());
1760
1761 if (UseVirtualCall(getContext(), E, MD))
1762 return BuildVirtualCall(MD, This, Ty);
1763
1764 return CGM.GetAddrOfFunction(MD, Ty);
1765}