blob: b3a14772ad04035406663460360b207838167f2a [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
Eli Friedman64bee652012-02-25 02:48:22 +000014#include "CGBlocks.h"
Devang Pateld67ef0e2010-08-11 21:04:37 +000015#include "CGDebugInfo.h"
Lang Hames56c00c42013-02-17 07:22:09 +000016#include "CGRecordLayout.h"
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000017#include "CodeGenFunction.h"
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +000018#include "CGCXXABI.h"
Anders Carlsson2f1986b2009-10-06 22:43:30 +000019#include "clang/AST/CXXInheritance.h"
John McCall7e1dff72010-09-17 02:31:44 +000020#include "clang/AST/EvaluatedExprVisitor.h"
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000021#include "clang/AST/RecordLayout.h"
John McCall9fc6a772010-02-19 09:25:03 +000022#include "clang/AST/StmtCXX.h"
Lang Hames56c00c42013-02-17 07:22:09 +000023#include "clang/Basic/TargetBuiltins.h"
Devang Patel3ee36af2011-02-22 20:55:26 +000024#include "clang/Frontend/CodeGenOptions.h"
Anders Carlsson2f1986b2009-10-06 22:43:30 +000025
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000026using namespace clang;
27using namespace CodeGen;
28
Ken Dyck55c02582011-03-22 00:53:26 +000029static CharUnits
Anders Carlsson34a2d382010-04-24 21:06:20 +000030ComputeNonVirtualBaseClassOffset(ASTContext &Context,
31 const CXXRecordDecl *DerivedClass,
John McCallf871d0c2010-08-07 06:22:56 +000032 CastExpr::path_const_iterator Start,
33 CastExpr::path_const_iterator End) {
Ken Dyck55c02582011-03-22 00:53:26 +000034 CharUnits Offset = CharUnits::Zero();
Anders Carlsson34a2d382010-04-24 21:06:20 +000035
36 const CXXRecordDecl *RD = DerivedClass;
37
John McCallf871d0c2010-08-07 06:22:56 +000038 for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
Anders Carlsson34a2d382010-04-24 21:06:20 +000039 const CXXBaseSpecifier *Base = *I;
40 assert(!Base->isVirtual() && "Should not see virtual bases here!");
41
42 // Get the layout.
43 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
44
45 const CXXRecordDecl *BaseDecl =
46 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
47
48 // Add the offset.
Ken Dyck55c02582011-03-22 00:53:26 +000049 Offset += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson34a2d382010-04-24 21:06:20 +000050
51 RD = BaseDecl;
52 }
53
Ken Dyck55c02582011-03-22 00:53:26 +000054 return Offset;
Anders Carlsson34a2d382010-04-24 21:06:20 +000055}
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000056
Anders Carlsson84080ec2009-09-29 03:13:20 +000057llvm::Constant *
Anders Carlssona04efdf2010-04-24 21:23:59 +000058CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +000059 CastExpr::path_const_iterator PathBegin,
60 CastExpr::path_const_iterator PathEnd) {
61 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssona04efdf2010-04-24 21:23:59 +000062
Ken Dyck55c02582011-03-22 00:53:26 +000063 CharUnits Offset =
John McCallf871d0c2010-08-07 06:22:56 +000064 ComputeNonVirtualBaseClassOffset(getContext(), ClassDecl,
65 PathBegin, PathEnd);
Ken Dyck55c02582011-03-22 00:53:26 +000066 if (Offset.isZero())
Anders Carlssona04efdf2010-04-24 21:23:59 +000067 return 0;
68
Chris Lattner2acc6e32011-07-18 04:24:23 +000069 llvm::Type *PtrDiffTy =
Anders Carlssona04efdf2010-04-24 21:23:59 +000070 Types.ConvertType(getContext().getPointerDiffType());
71
Ken Dyck55c02582011-03-22 00:53:26 +000072 return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
Anders Carlsson84080ec2009-09-29 03:13:20 +000073}
74
Anders Carlsson8561a862010-04-24 23:01:49 +000075/// Gets the address of a direct base class within a complete object.
John McCallbff225e2010-02-16 04:15:37 +000076/// This should only be used for (1) non-virtual bases or (2) virtual bases
77/// when the type is known to be complete (e.g. in complete destructors).
78///
79/// The object pointed to by 'This' is assumed to be non-null.
80llvm::Value *
Anders Carlsson8561a862010-04-24 23:01:49 +000081CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(llvm::Value *This,
82 const CXXRecordDecl *Derived,
83 const CXXRecordDecl *Base,
84 bool BaseIsVirtual) {
John McCallbff225e2010-02-16 04:15:37 +000085 // 'this' must be a pointer (in some address space) to Derived.
86 assert(This->getType()->isPointerTy() &&
87 cast<llvm::PointerType>(This->getType())->getElementType()
88 == ConvertType(Derived));
89
90 // Compute the offset of the virtual base.
Ken Dyck5fff46b2011-03-22 01:21:15 +000091 CharUnits Offset;
John McCallbff225e2010-02-16 04:15:37 +000092 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
Anders Carlsson8561a862010-04-24 23:01:49 +000093 if (BaseIsVirtual)
Ken Dyck5fff46b2011-03-22 01:21:15 +000094 Offset = Layout.getVBaseClassOffset(Base);
John McCallbff225e2010-02-16 04:15:37 +000095 else
Ken Dyck5fff46b2011-03-22 01:21:15 +000096 Offset = Layout.getBaseClassOffset(Base);
John McCallbff225e2010-02-16 04:15:37 +000097
98 // Shift and cast down to the base type.
99 // TODO: for complete types, this should be possible with a GEP.
100 llvm::Value *V = This;
Ken Dyck5fff46b2011-03-22 01:21:15 +0000101 if (Offset.isPositive()) {
John McCallbff225e2010-02-16 04:15:37 +0000102 V = Builder.CreateBitCast(V, Int8PtrTy);
Ken Dyck5fff46b2011-03-22 01:21:15 +0000103 V = Builder.CreateConstInBoundsGEP1_64(V, Offset.getQuantity());
John McCallbff225e2010-02-16 04:15:37 +0000104 }
105 V = Builder.CreateBitCast(V, ConvertType(Base)->getPointerTo());
106
107 return V;
Anders Carlssond103f9f2010-03-28 19:40:00 +0000108}
John McCallbff225e2010-02-16 04:15:37 +0000109
Anders Carlsson9dc228a2010-04-20 16:03:35 +0000110static llvm::Value *
John McCall7916c992012-08-01 05:04:58 +0000111ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, llvm::Value *ptr,
112 CharUnits nonVirtualOffset,
113 llvm::Value *virtualOffset) {
114 // Assert that we have something to do.
115 assert(!nonVirtualOffset.isZero() || virtualOffset != 0);
116
117 // Compute the offset from the static and dynamic components.
118 llvm::Value *baseOffset;
119 if (!nonVirtualOffset.isZero()) {
120 baseOffset = llvm::ConstantInt::get(CGF.PtrDiffTy,
121 nonVirtualOffset.getQuantity());
122 if (virtualOffset) {
123 baseOffset = CGF.Builder.CreateAdd(virtualOffset, baseOffset);
124 }
125 } else {
126 baseOffset = virtualOffset;
127 }
Anders Carlsson9dc228a2010-04-20 16:03:35 +0000128
129 // Apply the base offset.
John McCall7916c992012-08-01 05:04:58 +0000130 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
131 ptr = CGF.Builder.CreateInBoundsGEP(ptr, baseOffset, "add.ptr");
132 return ptr;
Anders Carlsson9dc228a2010-04-20 16:03:35 +0000133}
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
John McCall7916c992012-08-01 05:04:58 +0000146 // Sema has done some convenient canonicalization here: if the
147 // access path involved any virtual steps, the conversion path will
148 // *start* with a step down to the correct virtual base subobject,
149 // and hence will not require any further steps.
Anders Carlsson34a2d382010-04-24 21:06:20 +0000150 if ((*Start)->isVirtual()) {
151 VBase =
152 cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
153 ++Start;
154 }
John McCall7916c992012-08-01 05:04:58 +0000155
156 // Compute the static offset of the ultimate destination within its
157 // allocating subobject (the virtual base, if there is one, or else
158 // the "complete" object that we see).
Ken Dyck55c02582011-03-22 00:53:26 +0000159 CharUnits NonVirtualOffset =
Anders Carlsson8561a862010-04-24 23:01:49 +0000160 ComputeNonVirtualBaseClassOffset(getContext(), VBase ? VBase : Derived,
John McCallf871d0c2010-08-07 06:22:56 +0000161 Start, PathEnd);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000162
John McCall7916c992012-08-01 05:04:58 +0000163 // If there's a virtual step, we can sometimes "devirtualize" it.
164 // For now, that's limited to when the derived type is final.
165 // TODO: "devirtualize" this for accesses to known-complete objects.
166 if (VBase && Derived->hasAttr<FinalAttr>()) {
167 const ASTRecordLayout &layout = getContext().getASTRecordLayout(Derived);
168 CharUnits vBaseOffset = layout.getVBaseClassOffset(VBase);
169 NonVirtualOffset += vBaseOffset;
170 VBase = 0; // we no longer have a virtual step
171 }
172
Anders Carlsson34a2d382010-04-24 21:06:20 +0000173 // Get the base pointer type.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000174 llvm::Type *BasePtrTy =
John McCallf871d0c2010-08-07 06:22:56 +0000175 ConvertType((PathEnd[-1])->getType())->getPointerTo();
John McCall7916c992012-08-01 05:04:58 +0000176
177 // If the static offset is zero and we don't have a virtual step,
178 // just do a bitcast; null checks are unnecessary.
Ken Dyck55c02582011-03-22 00:53:26 +0000179 if (NonVirtualOffset.isZero() && !VBase) {
Anders Carlsson34a2d382010-04-24 21:06:20 +0000180 return Builder.CreateBitCast(Value, BasePtrTy);
181 }
John McCall7916c992012-08-01 05:04:58 +0000182
183 llvm::BasicBlock *origBB = 0;
184 llvm::BasicBlock *endBB = 0;
Anders Carlsson34a2d382010-04-24 21:06:20 +0000185
John McCall7916c992012-08-01 05:04:58 +0000186 // Skip over the offset (and the vtable load) if we're supposed to
187 // null-check the pointer.
Anders Carlsson34a2d382010-04-24 21:06:20 +0000188 if (NullCheckValue) {
John McCall7916c992012-08-01 05:04:58 +0000189 origBB = Builder.GetInsertBlock();
190 llvm::BasicBlock *notNullBB = createBasicBlock("cast.notnull");
191 endBB = createBasicBlock("cast.end");
Anders Carlsson34a2d382010-04-24 21:06:20 +0000192
John McCall7916c992012-08-01 05:04:58 +0000193 llvm::Value *isNull = Builder.CreateIsNull(Value);
194 Builder.CreateCondBr(isNull, endBB, notNullBB);
195 EmitBlock(notNullBB);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000196 }
197
John McCall7916c992012-08-01 05:04:58 +0000198 // Compute the virtual offset.
Anders Carlsson34a2d382010-04-24 21:06:20 +0000199 llvm::Value *VirtualOffset = 0;
Anders Carlsson336a7dc2011-01-29 03:18:56 +0000200 if (VBase) {
Reid Klecknerb0f533e2013-05-29 18:02:47 +0000201 VirtualOffset =
202 CGM.getCXXABI().GetVirtualBaseClassOffset(*this, Value, Derived, VBase);
Anders Carlsson336a7dc2011-01-29 03:18:56 +0000203 }
Anders Carlsson34a2d382010-04-24 21:06:20 +0000204
John McCall7916c992012-08-01 05:04:58 +0000205 // Apply both offsets.
Ken Dyck55c02582011-03-22 00:53:26 +0000206 Value = ApplyNonVirtualAndVirtualOffset(*this, Value,
Ken Dyck9a8ad9b2011-03-23 00:45:26 +0000207 NonVirtualOffset,
Anders Carlsson34a2d382010-04-24 21:06:20 +0000208 VirtualOffset);
209
John McCall7916c992012-08-01 05:04:58 +0000210 // Cast to the destination type.
Anders Carlsson34a2d382010-04-24 21:06:20 +0000211 Value = Builder.CreateBitCast(Value, BasePtrTy);
John McCall7916c992012-08-01 05:04:58 +0000212
213 // Build a phi if we needed a null check.
Anders Carlsson34a2d382010-04-24 21:06:20 +0000214 if (NullCheckValue) {
John McCall7916c992012-08-01 05:04:58 +0000215 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
216 Builder.CreateBr(endBB);
217 EmitBlock(endBB);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000218
John McCall7916c992012-08-01 05:04:58 +0000219 llvm::PHINode *PHI = Builder.CreatePHI(BasePtrTy, 2, "cast.result");
220 PHI->addIncoming(Value, notNullBB);
221 PHI->addIncoming(llvm::Constant::getNullValue(BasePtrTy), origBB);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000222 Value = PHI;
223 }
224
225 return Value;
226}
227
228llvm::Value *
Anders Carlssona3697c92009-11-23 17:57:54 +0000229CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value,
Anders Carlsson8561a862010-04-24 23:01:49 +0000230 const CXXRecordDecl *Derived,
John McCallf871d0c2010-08-07 06:22:56 +0000231 CastExpr::path_const_iterator PathBegin,
232 CastExpr::path_const_iterator PathEnd,
Anders Carlssona3697c92009-11-23 17:57:54 +0000233 bool NullCheckValue) {
John McCallf871d0c2010-08-07 06:22:56 +0000234 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssona04efdf2010-04-24 21:23:59 +0000235
Anders Carlssona3697c92009-11-23 17:57:54 +0000236 QualType DerivedTy =
Anders Carlsson8561a862010-04-24 23:01:49 +0000237 getContext().getCanonicalType(getContext().getTagDeclType(Derived));
Chris Lattner2acc6e32011-07-18 04:24:23 +0000238 llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
Richard Smithc7648302013-02-13 21:18:23 +0000239
Anders Carlssona552ea72010-01-31 01:43:37 +0000240 llvm::Value *NonVirtualOffset =
John McCallf871d0c2010-08-07 06:22:56 +0000241 CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
Anders Carlssona552ea72010-01-31 01:43:37 +0000242
243 if (!NonVirtualOffset) {
244 // No offset, we can just cast back.
245 return Builder.CreateBitCast(Value, DerivedPtrTy);
246 }
247
Anders Carlssona3697c92009-11-23 17:57:54 +0000248 llvm::BasicBlock *CastNull = 0;
249 llvm::BasicBlock *CastNotNull = 0;
250 llvm::BasicBlock *CastEnd = 0;
251
252 if (NullCheckValue) {
253 CastNull = createBasicBlock("cast.null");
254 CastNotNull = createBasicBlock("cast.notnull");
255 CastEnd = createBasicBlock("cast.end");
256
Anders Carlssonb9241242011-04-11 00:30:07 +0000257 llvm::Value *IsNull = Builder.CreateIsNull(Value);
Anders Carlssona3697c92009-11-23 17:57:54 +0000258 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
259 EmitBlock(CastNotNull);
260 }
261
Anders Carlssona552ea72010-01-31 01:43:37 +0000262 // Apply the offset.
Eli Friedmanc5685432012-02-28 22:07:56 +0000263 Value = Builder.CreateBitCast(Value, Int8PtrTy);
264 Value = Builder.CreateGEP(Value, Builder.CreateNeg(NonVirtualOffset),
265 "sub.ptr");
Anders Carlssona552ea72010-01-31 01:43:37 +0000266
267 // Just cast.
268 Value = Builder.CreateBitCast(Value, DerivedPtrTy);
Anders Carlssona3697c92009-11-23 17:57:54 +0000269
270 if (NullCheckValue) {
271 Builder.CreateBr(CastEnd);
272 EmitBlock(CastNull);
273 Builder.CreateBr(CastEnd);
274 EmitBlock(CastEnd);
275
Jay Foadbbf3bac2011-03-30 11:28:58 +0000276 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
Anders Carlssona3697c92009-11-23 17:57:54 +0000277 PHI->addIncoming(Value, CastNotNull);
278 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
279 CastNull);
280 Value = PHI;
281 }
282
283 return Value;
Anders Carlsson5d58a1d2009-09-12 04:27:24 +0000284}
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000285
286llvm::Value *CodeGenFunction::GetVTTParameter(GlobalDecl GD,
287 bool ForVirtualBase,
288 bool Delegating) {
Anders Carlssonaf440352010-03-23 04:11:45 +0000289 if (!CodeGenVTables::needsVTTParameter(GD)) {
Anders Carlssonc997d422010-01-02 01:01:18 +0000290 // This constructor/destructor does not need a VTT parameter.
291 return 0;
292 }
293
John McCallf5ebf9b2013-05-03 07:33:41 +0000294 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CurCodeDecl)->getParent();
Anders Carlssonc997d422010-01-02 01:01:18 +0000295 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
John McCall3b477332010-02-18 19:59:28 +0000296
Anders Carlssonc997d422010-01-02 01:01:18 +0000297 llvm::Value *VTT;
298
John McCall3b477332010-02-18 19:59:28 +0000299 uint64_t SubVTTIndex;
300
Douglas Gregor378e1e72013-01-31 05:50:40 +0000301 if (Delegating) {
302 // If this is a delegating constructor call, just load the VTT.
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000303 return LoadCXXVTT();
Douglas Gregor378e1e72013-01-31 05:50:40 +0000304 } else if (RD == Base) {
305 // If the record matches the base, this is the complete ctor/dtor
306 // variant calling the base variant in a class with virtual bases.
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000307 assert(!CodeGenVTables::needsVTTParameter(CurGD) &&
John McCall3b477332010-02-18 19:59:28 +0000308 "doing no-op VTT offset in base dtor/ctor?");
Anders Carlsson314e6222010-05-02 23:33:10 +0000309 assert(!ForVirtualBase && "Can't have same class as virtual base!");
John McCall3b477332010-02-18 19:59:28 +0000310 SubVTTIndex = 0;
311 } else {
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000312 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Ken Dyck4230d522011-03-24 01:21:01 +0000313 CharUnits BaseOffset = ForVirtualBase ?
314 Layout.getVBaseClassOffset(Base) :
315 Layout.getBaseClassOffset(Base);
Anders Carlssonc11bb212010-05-02 23:53:25 +0000316
317 SubVTTIndex =
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000318 CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
John McCall3b477332010-02-18 19:59:28 +0000319 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
320 }
Anders Carlssonc997d422010-01-02 01:01:18 +0000321
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000322 if (CodeGenVTables::needsVTTParameter(CurGD)) {
Anders Carlssonc997d422010-01-02 01:01:18 +0000323 // A VTT parameter was passed to the constructor, use it.
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000324 VTT = LoadCXXVTT();
325 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
Anders Carlssonc997d422010-01-02 01:01:18 +0000326 } else {
327 // We're the complete constructor, so get the VTT by name.
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000328 VTT = CGM.getVTables().GetAddrOfVTT(RD);
329 VTT = Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
Anders Carlssonc997d422010-01-02 01:01:18 +0000330 }
331
332 return VTT;
333}
334
John McCall182ab512010-07-21 01:23:41 +0000335namespace {
John McCall50da2ca2010-07-21 05:30:47 +0000336 /// Call the destructor for a direct base class.
John McCall1f0fca52010-07-21 07:22:38 +0000337 struct CallBaseDtor : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000338 const CXXRecordDecl *BaseClass;
339 bool BaseIsVirtual;
340 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
341 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
John McCall182ab512010-07-21 01:23:41 +0000342
John McCallad346f42011-07-12 20:27:29 +0000343 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall50da2ca2010-07-21 05:30:47 +0000344 const CXXRecordDecl *DerivedClass =
345 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
346
347 const CXXDestructorDecl *D = BaseClass->getDestructor();
348 llvm::Value *Addr =
349 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThis(),
350 DerivedClass, BaseClass,
351 BaseIsVirtual);
Douglas Gregor378e1e72013-01-31 05:50:40 +0000352 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual,
353 /*Delegating=*/false, Addr);
John McCall182ab512010-07-21 01:23:41 +0000354 }
355 };
John McCall7e1dff72010-09-17 02:31:44 +0000356
357 /// A visitor which checks whether an initializer uses 'this' in a
358 /// way which requires the vtable to be properly set.
359 struct DynamicThisUseChecker : EvaluatedExprVisitor<DynamicThisUseChecker> {
360 typedef EvaluatedExprVisitor<DynamicThisUseChecker> super;
361
362 bool UsesThis;
363
364 DynamicThisUseChecker(ASTContext &C) : super(C), UsesThis(false) {}
365
366 // Black-list all explicit and implicit references to 'this'.
367 //
368 // Do we need to worry about external references to 'this' derived
369 // from arbitrary code? If so, then anything which runs arbitrary
370 // external code might potentially access the vtable.
371 void VisitCXXThisExpr(CXXThisExpr *E) { UsesThis = true; }
372 };
373}
374
375static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
376 DynamicThisUseChecker Checker(C);
377 Checker.Visit(const_cast<Expr*>(Init));
378 return Checker.UsesThis;
John McCall182ab512010-07-21 01:23:41 +0000379}
380
Anders Carlsson607d0372009-12-24 22:46:43 +0000381static void EmitBaseInitializer(CodeGenFunction &CGF,
382 const CXXRecordDecl *ClassDecl,
Sean Huntcbb67482011-01-08 20:30:50 +0000383 CXXCtorInitializer *BaseInit,
Anders Carlsson607d0372009-12-24 22:46:43 +0000384 CXXCtorType CtorType) {
385 assert(BaseInit->isBaseInitializer() &&
386 "Must have base initializer!");
387
388 llvm::Value *ThisPtr = CGF.LoadCXXThis();
389
390 const Type *BaseType = BaseInit->getBaseClass();
391 CXXRecordDecl *BaseClassDecl =
392 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
393
Anders Carlsson80638c52010-04-12 00:51:03 +0000394 bool isBaseVirtual = BaseInit->isBaseVirtual();
Anders Carlsson607d0372009-12-24 22:46:43 +0000395
396 // The base constructor doesn't construct virtual bases.
397 if (CtorType == Ctor_Base && isBaseVirtual)
398 return;
399
John McCall7e1dff72010-09-17 02:31:44 +0000400 // If the initializer for the base (other than the constructor
401 // itself) accesses 'this' in any way, we need to initialize the
402 // vtables.
403 if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
404 CGF.InitializeVTablePointers(ClassDecl);
405
John McCallbff225e2010-02-16 04:15:37 +0000406 // We can pretend to be a complete class because it only matters for
407 // virtual bases, and we only do virtual bases for complete ctors.
Anders Carlsson8561a862010-04-24 23:01:49 +0000408 llvm::Value *V =
409 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
John McCall50da2ca2010-07-21 05:30:47 +0000410 BaseClassDecl,
411 isBaseVirtual);
Eli Friedmand7722d92011-12-03 02:13:40 +0000412 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(BaseType);
John McCall7c2349b2011-08-25 20:40:09 +0000413 AggValueSlot AggSlot =
Eli Friedmanf3940782011-12-03 00:54:26 +0000414 AggValueSlot::forAddr(V, Alignment, Qualifiers(),
John McCall7c2349b2011-08-25 20:40:09 +0000415 AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +0000416 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +0000417 AggValueSlot::IsNotAliased);
John McCall558d2ab2010-09-15 10:14:12 +0000418
419 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
Anders Carlsson594d5e82010-02-06 20:00:21 +0000420
David Blaikie4e4d0842012-03-11 07:00:24 +0000421 if (CGF.CGM.getLangOpts().Exceptions &&
Anders Carlssonc1cfdf82011-02-20 00:20:27 +0000422 !BaseClassDecl->hasTrivialDestructor())
John McCall1f0fca52010-07-21 07:22:38 +0000423 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
424 isBaseVirtual);
Anders Carlsson607d0372009-12-24 22:46:43 +0000425}
426
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000427static void EmitAggMemberInitializer(CodeGenFunction &CGF,
428 LValue LHS,
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000429 Expr *Init,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000430 llvm::Value *ArrayIndexVar,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000431 QualType T,
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000432 ArrayRef<VarDecl *> ArrayIndexes,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000433 unsigned Index) {
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000434 if (Index == ArrayIndexes.size()) {
Eli Friedmanf3940782011-12-03 00:54:26 +0000435 LValue LV = LHS;
Sebastian Redl924db712012-02-19 15:41:54 +0000436 { // Scope for Cleanups.
437 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
Eli Friedmanf3940782011-12-03 00:54:26 +0000438
Sebastian Redl924db712012-02-19 15:41:54 +0000439 if (ArrayIndexVar) {
440 // If we have an array index variable, load it and use it as an offset.
441 // Then, increment the value.
442 llvm::Value *Dest = LHS.getAddress();
443 llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar);
444 Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress");
445 llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1);
446 Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc");
447 CGF.Builder.CreateStore(Next, ArrayIndexVar);
448
449 // Update the LValue.
450 LV.setAddress(Dest);
451 CharUnits Align = CGF.getContext().getTypeAlignInChars(T);
452 LV.setAlignment(std::min(Align, LV.getAlignment()));
453 }
454
John McCall9d232c82013-03-07 21:37:08 +0000455 switch (CGF.getEvaluationKind(T)) {
456 case TEK_Scalar:
Sebastian Redl924db712012-02-19 15:41:54 +0000457 CGF.EmitScalarInit(Init, /*decl*/ 0, LV, false);
John McCall9d232c82013-03-07 21:37:08 +0000458 break;
459 case TEK_Complex:
460 CGF.EmitComplexExprIntoLValue(Init, LV, /*isInit*/ true);
461 break;
462 case TEK_Aggregate: {
Sebastian Redl924db712012-02-19 15:41:54 +0000463 AggValueSlot Slot =
464 AggValueSlot::forLValue(LV,
465 AggValueSlot::IsDestructed,
466 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +0000467 AggValueSlot::IsNotAliased);
Sebastian Redl924db712012-02-19 15:41:54 +0000468
469 CGF.EmitAggExpr(Init, Slot);
John McCall9d232c82013-03-07 21:37:08 +0000470 break;
471 }
Sebastian Redl924db712012-02-19 15:41:54 +0000472 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000473 }
John McCall558d2ab2010-09-15 10:14:12 +0000474
Sebastian Redl924db712012-02-19 15:41:54 +0000475 // Now, outside of the initializer cleanup scope, destroy the backing array
476 // for a std::initializer_list member.
Sebastian Redl972edf02012-02-19 16:03:09 +0000477 CGF.MaybeEmitStdInitializerListCleanup(LV.getAddress(), Init);
Sebastian Redl924db712012-02-19 15:41:54 +0000478
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000479 return;
480 }
481
482 const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T);
483 assert(Array && "Array initialization without the array type?");
484 llvm::Value *IndexVar
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000485 = CGF.GetAddrOfLocalVar(ArrayIndexes[Index]);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000486 assert(IndexVar && "Array index variable not loaded");
487
488 // Initialize this index variable to zero.
489 llvm::Value* Zero
490 = llvm::Constant::getNullValue(
491 CGF.ConvertType(CGF.getContext().getSizeType()));
492 CGF.Builder.CreateStore(Zero, IndexVar);
493
494 // Start the loop with a block that tests the condition.
495 llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond");
496 llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end");
497
498 CGF.EmitBlock(CondBlock);
499
500 llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body");
501 // Generate: if (loop-index < number-of-elements) fall to the loop body,
502 // otherwise, go to the block after the for-loop.
503 uint64_t NumElements = Array->getSize().getZExtValue();
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000504 llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
Chris Lattner985f7392010-05-06 06:35:23 +0000505 llvm::Value *NumElementsPtr =
506 llvm::ConstantInt::get(Counter->getType(), NumElements);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000507 llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr,
508 "isless");
509
510 // If the condition is true, execute the body.
511 CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor);
512
513 CGF.EmitBlock(ForBody);
514 llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc");
515
516 {
John McCallf1549f62010-07-06 01:34:17 +0000517 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000518
519 // Inside the loop body recurse to emit the inner loop or, eventually, the
520 // constructor call.
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000521 EmitAggMemberInitializer(CGF, LHS, Init, ArrayIndexVar,
522 Array->getElementType(), ArrayIndexes, Index + 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000523 }
524
525 CGF.EmitBlock(ContinueBlock);
526
527 // Emit the increment of the loop counter.
528 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
529 Counter = CGF.Builder.CreateLoad(IndexVar);
530 NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc");
531 CGF.Builder.CreateStore(NextVal, IndexVar);
532
533 // Finally, branch back up to the condition for the next iteration.
534 CGF.EmitBranch(CondBlock);
535
536 // Emit the fall-through block.
537 CGF.EmitBlock(AfterFor, true);
538}
John McCall182ab512010-07-21 01:23:41 +0000539
Anders Carlsson607d0372009-12-24 22:46:43 +0000540static void EmitMemberInitializer(CodeGenFunction &CGF,
541 const CXXRecordDecl *ClassDecl,
Sean Huntcbb67482011-01-08 20:30:50 +0000542 CXXCtorInitializer *MemberInit,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000543 const CXXConstructorDecl *Constructor,
544 FunctionArgList &Args) {
Francois Pichet00eb3f92010-12-04 09:14:42 +0000545 assert(MemberInit->isAnyMemberInitializer() &&
Anders Carlsson607d0372009-12-24 22:46:43 +0000546 "Must have member initializer!");
Richard Smith7a614d82011-06-11 17:19:42 +0000547 assert(MemberInit->getInit() && "Must have initializer!");
Anders Carlsson607d0372009-12-24 22:46:43 +0000548
549 // non-static data member initializers.
Francois Pichet00eb3f92010-12-04 09:14:42 +0000550 FieldDecl *Field = MemberInit->getAnyMember();
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000551 QualType FieldType = Field->getType();
Anders Carlsson607d0372009-12-24 22:46:43 +0000552
553 llvm::Value *ThisPtr = CGF.LoadCXXThis();
Eli Friedman377ecc72012-04-16 03:54:45 +0000554 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
Eli Friedman859c65c2012-08-08 03:51:37 +0000555 LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
Eli Friedman377ecc72012-04-16 03:54:45 +0000556
Francois Pichet00eb3f92010-12-04 09:14:42 +0000557 if (MemberInit->isIndirectMemberInitializer()) {
Eli Friedman859c65c2012-08-08 03:51:37 +0000558 // If we are initializing an anonymous union field, drill down to
559 // the field.
560 IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember();
561 IndirectFieldDecl::chain_iterator I = IndirectField->chain_begin(),
562 IEnd = IndirectField->chain_end();
563 for ( ; I != IEnd; ++I)
564 LHS = CGF.EmitLValueForFieldInitialization(LHS, cast<FieldDecl>(*I));
Francois Pichet00eb3f92010-12-04 09:14:42 +0000565 FieldType = MemberInit->getIndirectMember()->getAnonField()->getType();
John McCalla9976d32010-05-21 01:18:57 +0000566 } else {
Eli Friedman859c65c2012-08-08 03:51:37 +0000567 LHS = CGF.EmitLValueForFieldInitialization(LHS, Field);
Anders Carlsson607d0372009-12-24 22:46:43 +0000568 }
569
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000570 // Special case: if we are in a copy or move constructor, and we are copying
571 // an array of PODs or classes with trivial copy constructors, ignore the
572 // AST and perform the copy we know is equivalent.
573 // FIXME: This is hacky at best... if we had a bit more explicit information
574 // in the AST, we could generalize it more easily.
575 const ConstantArrayType *Array
576 = CGF.getContext().getAsConstantArrayType(FieldType);
577 if (Array && Constructor->isImplicitlyDefined() &&
578 Constructor->isCopyOrMoveConstructor()) {
579 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
Richard Smithe9385362012-11-07 23:56:21 +0000580 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000581 if (BaseElementTy.isPODType(CGF.getContext()) ||
Richard Smithe9385362012-11-07 23:56:21 +0000582 (CE && CE->getConstructor()->isTrivial())) {
583 // Find the source pointer. We know it's the last argument because
584 // we know we're in an implicit copy constructor.
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000585 unsigned SrcArgIndex = Args.size() - 1;
586 llvm::Value *SrcPtr
587 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
Eli Friedman377ecc72012-04-16 03:54:45 +0000588 LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
589 LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field);
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000590
591 // Copy the aggregate.
592 CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
Chad Rosier649b4a12012-03-29 17:37:10 +0000593 LHS.isVolatileQualified());
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000594 return;
595 }
596 }
597
598 ArrayRef<VarDecl *> ArrayIndexes;
599 if (MemberInit->getNumArrayIndices())
600 ArrayIndexes = MemberInit->getArrayIndexes();
Eli Friedmanb74ed082012-02-14 02:31:03 +0000601 CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit(), ArrayIndexes);
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000602}
603
Eli Friedmanb74ed082012-02-14 02:31:03 +0000604void CodeGenFunction::EmitInitializerForField(FieldDecl *Field,
605 LValue LHS, Expr *Init,
606 ArrayRef<VarDecl *> ArrayIndexes) {
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000607 QualType FieldType = Field->getType();
John McCall9d232c82013-03-07 21:37:08 +0000608 switch (getEvaluationKind(FieldType)) {
609 case TEK_Scalar:
John McCallf85e1932011-06-15 23:02:42 +0000610 if (LHS.isSimple()) {
Eli Friedmanb74ed082012-02-14 02:31:03 +0000611 EmitExprAsInit(Init, Field, LHS, false);
John McCallf85e1932011-06-15 23:02:42 +0000612 } else {
Eli Friedmanb74ed082012-02-14 02:31:03 +0000613 RValue RHS = RValue::get(EmitScalarExpr(Init));
614 EmitStoreThroughLValue(RHS, LHS);
John McCallf85e1932011-06-15 23:02:42 +0000615 }
John McCall9d232c82013-03-07 21:37:08 +0000616 break;
617 case TEK_Complex:
618 EmitComplexExprIntoLValue(Init, LHS, /*isInit*/ true);
619 break;
620 case TEK_Aggregate: {
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000621 llvm::Value *ArrayIndexVar = 0;
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000622 if (ArrayIndexes.size()) {
Eli Friedmanb74ed082012-02-14 02:31:03 +0000623 llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000624
625 // The LHS is a pointer to the first object we'll be constructing, as
626 // a flat array.
Eli Friedmanb74ed082012-02-14 02:31:03 +0000627 QualType BaseElementTy = getContext().getBaseElementType(FieldType);
628 llvm::Type *BasePtr = ConvertType(BaseElementTy);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000629 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Eli Friedmanb74ed082012-02-14 02:31:03 +0000630 llvm::Value *BaseAddrPtr = Builder.CreateBitCast(LHS.getAddress(),
631 BasePtr);
632 LHS = MakeAddrLValue(BaseAddrPtr, BaseElementTy);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000633
634 // Create an array index that will be used to walk over all of the
635 // objects we're constructing.
Eli Friedmanb74ed082012-02-14 02:31:03 +0000636 ArrayIndexVar = CreateTempAlloca(SizeTy, "object.index");
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000637 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
Eli Friedmanb74ed082012-02-14 02:31:03 +0000638 Builder.CreateStore(Zero, ArrayIndexVar);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000639
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000640
641 // Emit the block variables for the array indices, if any.
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000642 for (unsigned I = 0, N = ArrayIndexes.size(); I != N; ++I)
Eli Friedmanb74ed082012-02-14 02:31:03 +0000643 EmitAutoVarDecl(*ArrayIndexes[I]);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000644 }
645
Eli Friedmanb74ed082012-02-14 02:31:03 +0000646 EmitAggMemberInitializer(*this, LHS, Init, ArrayIndexVar, FieldType,
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000647 ArrayIndexes, 0);
Anders Carlsson607d0372009-12-24 22:46:43 +0000648 }
John McCall9d232c82013-03-07 21:37:08 +0000649 }
John McCall074cae02013-02-01 05:11:40 +0000650
651 // Ensure that we destroy this object if an exception is thrown
652 // later in the constructor.
653 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
654 if (needsEHCleanup(dtorKind))
655 pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
Anders Carlsson607d0372009-12-24 22:46:43 +0000656}
657
John McCallc0bf4622010-02-23 00:48:20 +0000658/// Checks whether the given constructor is a valid subject for the
659/// complete-to-base constructor delegation optimization, i.e.
660/// emitting the complete constructor as a simple call to the base
661/// constructor.
662static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
663
664 // Currently we disable the optimization for classes with virtual
665 // bases because (1) the addresses of parameter variables need to be
666 // consistent across all initializers but (2) the delegate function
667 // call necessarily creates a second copy of the parameter variable.
668 //
669 // The limiting example (purely theoretical AFAIK):
670 // struct A { A(int &c) { c++; } };
671 // struct B : virtual A {
672 // B(int count) : A(count) { printf("%d\n", count); }
673 // };
674 // ...although even this example could in principle be emitted as a
675 // delegation since the address of the parameter doesn't escape.
676 if (Ctor->getParent()->getNumVBases()) {
677 // TODO: white-list trivial vbase initializers. This case wouldn't
678 // be subject to the restrictions below.
679
680 // TODO: white-list cases where:
681 // - there are no non-reference parameters to the constructor
682 // - the initializers don't access any non-reference parameters
683 // - the initializers don't take the address of non-reference
684 // parameters
685 // - etc.
686 // If we ever add any of the above cases, remember that:
687 // - function-try-blocks will always blacklist this optimization
688 // - we need to perform the constructor prologue and cleanup in
689 // EmitConstructorBody.
690
691 return false;
692 }
693
694 // We also disable the optimization for variadic functions because
695 // it's impossible to "re-pass" varargs.
696 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
697 return false;
698
Sean Hunt059ce0d2011-05-01 07:04:31 +0000699 // FIXME: Decide if we can do a delegation of a delegating constructor.
700 if (Ctor->isDelegatingConstructor())
701 return false;
702
John McCallc0bf4622010-02-23 00:48:20 +0000703 return true;
704}
705
John McCall9fc6a772010-02-19 09:25:03 +0000706/// EmitConstructorBody - Emits the body of the current constructor.
707void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
708 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
709 CXXCtorType CtorType = CurGD.getCtorType();
710
John McCallc0bf4622010-02-23 00:48:20 +0000711 // Before we go any further, try the complete->base constructor
712 // delegation optimization.
Timur Iskhodzhanov85607912012-04-20 08:05:00 +0000713 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
John McCall64aa4b32013-04-16 22:48:15 +0000714 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
Devang Pateld67ef0e2010-08-11 21:04:37 +0000715 if (CGDebugInfo *DI = getDebugInfo())
Eric Christopher73fb3502011-10-13 21:45:18 +0000716 DI->EmitLocation(Builder, Ctor->getLocEnd());
John McCallc0bf4622010-02-23 00:48:20 +0000717 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args);
718 return;
719 }
720
John McCall9fc6a772010-02-19 09:25:03 +0000721 Stmt *Body = Ctor->getBody();
722
John McCallc0bf4622010-02-23 00:48:20 +0000723 // Enter the function-try-block before the constructor prologue if
724 // applicable.
John McCallc0bf4622010-02-23 00:48:20 +0000725 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallc0bf4622010-02-23 00:48:20 +0000726 if (IsTryBody)
John McCall59a70002010-07-07 06:56:46 +0000727 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000728
John McCallf1549f62010-07-06 01:34:17 +0000729 EHScopeStack::stable_iterator CleanupDepth = EHStack.stable_begin();
John McCall9fc6a772010-02-19 09:25:03 +0000730
John McCall56ea3772012-03-30 04:25:03 +0000731 // TODO: in restricted cases, we can emit the vbase initializers of
732 // a complete ctor and then delegate to the base ctor.
733
John McCallc0bf4622010-02-23 00:48:20 +0000734 // Emit the constructor prologue, i.e. the base and member
735 // initializers.
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000736 EmitCtorPrologue(Ctor, CtorType, Args);
John McCall9fc6a772010-02-19 09:25:03 +0000737
738 // Emit the body of the statement.
John McCallc0bf4622010-02-23 00:48:20 +0000739 if (IsTryBody)
John McCall9fc6a772010-02-19 09:25:03 +0000740 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
741 else if (Body)
742 EmitStmt(Body);
John McCall9fc6a772010-02-19 09:25:03 +0000743
744 // Emit any cleanup blocks associated with the member or base
745 // initializers, which includes (along the exceptional path) the
746 // destructors for those members and bases that were fully
747 // constructed.
John McCallf1549f62010-07-06 01:34:17 +0000748 PopCleanupBlocks(CleanupDepth);
John McCall9fc6a772010-02-19 09:25:03 +0000749
John McCallc0bf4622010-02-23 00:48:20 +0000750 if (IsTryBody)
John McCall59a70002010-07-07 06:56:46 +0000751 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000752}
753
Lang Hames56c00c42013-02-17 07:22:09 +0000754namespace {
755 class FieldMemcpyizer {
756 public:
757 FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl,
758 const VarDecl *SrcRec)
759 : CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec),
760 RecLayout(CGF.getContext().getASTRecordLayout(ClassDecl)),
761 FirstField(0), LastField(0), FirstFieldOffset(0), LastFieldOffset(0),
762 LastAddedFieldIndex(0) { }
763
764 static bool isMemcpyableField(FieldDecl *F) {
765 Qualifiers Qual = F->getType().getQualifiers();
766 if (Qual.hasVolatile() || Qual.hasObjCLifetime())
767 return false;
768 return true;
769 }
770
771 void addMemcpyableField(FieldDecl *F) {
772 if (FirstField == 0)
773 addInitialField(F);
774 else
775 addNextField(F);
776 }
777
778 CharUnits getMemcpySize() const {
779 unsigned LastFieldSize =
780 LastField->isBitField() ?
781 LastField->getBitWidthValue(CGF.getContext()) :
782 CGF.getContext().getTypeSize(LastField->getType());
783 uint64_t MemcpySizeBits =
784 LastFieldOffset + LastFieldSize - FirstFieldOffset +
785 CGF.getContext().getCharWidth() - 1;
786 CharUnits MemcpySize =
787 CGF.getContext().toCharUnitsFromBits(MemcpySizeBits);
788 return MemcpySize;
789 }
790
791 void emitMemcpy() {
792 // Give the subclass a chance to bail out if it feels the memcpy isn't
793 // worth it (e.g. Hasn't aggregated enough data).
794 if (FirstField == 0) {
795 return;
796 }
797
Lang Hames5e8577e2013-02-27 04:14:49 +0000798 CharUnits Alignment;
Lang Hames56c00c42013-02-17 07:22:09 +0000799
800 if (FirstField->isBitField()) {
801 const CGRecordLayout &RL =
802 CGF.getTypes().getCGRecordLayout(FirstField->getParent());
803 const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField);
Lang Hames5e8577e2013-02-27 04:14:49 +0000804 Alignment = CharUnits::fromQuantity(BFInfo.StorageAlignment);
805 } else {
Lang Hames23742cd2013-03-05 20:27:24 +0000806 Alignment = CGF.getContext().getDeclAlign(FirstField);
Lang Hames5e8577e2013-02-27 04:14:49 +0000807 }
Lang Hames56c00c42013-02-17 07:22:09 +0000808
Lang Hames5e8577e2013-02-27 04:14:49 +0000809 assert((CGF.getContext().toCharUnitsFromBits(FirstFieldOffset) %
810 Alignment) == 0 && "Bad field alignment.");
811
Lang Hames56c00c42013-02-17 07:22:09 +0000812 CharUnits MemcpySize = getMemcpySize();
813 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
814 llvm::Value *ThisPtr = CGF.LoadCXXThis();
815 LValue DestLV = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
816 LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField);
817 llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec));
818 LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
819 LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField);
820
821 emitMemcpyIR(Dest.isBitField() ? Dest.getBitFieldAddr() : Dest.getAddress(),
822 Src.isBitField() ? Src.getBitFieldAddr() : Src.getAddress(),
823 MemcpySize, Alignment);
824 reset();
825 }
826
827 void reset() {
828 FirstField = 0;
829 }
830
831 protected:
832 CodeGenFunction &CGF;
833 const CXXRecordDecl *ClassDecl;
834
835 private:
836
837 void emitMemcpyIR(llvm::Value *DestPtr, llvm::Value *SrcPtr,
838 CharUnits Size, CharUnits Alignment) {
839 llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
840 llvm::Type *DBP =
841 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), DPT->getAddressSpace());
842 DestPtr = CGF.Builder.CreateBitCast(DestPtr, DBP);
843
844 llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
845 llvm::Type *SBP =
846 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), SPT->getAddressSpace());
847 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, SBP);
848
849 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity(),
850 Alignment.getQuantity());
851 }
852
853 void addInitialField(FieldDecl *F) {
854 FirstField = F;
855 LastField = F;
856 FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex());
857 LastFieldOffset = FirstFieldOffset;
858 LastAddedFieldIndex = F->getFieldIndex();
859 return;
860 }
861
862 void addNextField(FieldDecl *F) {
John McCall402cd222013-05-07 05:20:46 +0000863 // For the most part, the following invariant will hold:
864 // F->getFieldIndex() == LastAddedFieldIndex + 1
865 // The one exception is that Sema won't add a copy-initializer for an
866 // unnamed bitfield, which will show up here as a gap in the sequence.
867 assert(F->getFieldIndex() >= LastAddedFieldIndex + 1 &&
868 "Cannot aggregate fields out of order.");
Lang Hames56c00c42013-02-17 07:22:09 +0000869 LastAddedFieldIndex = F->getFieldIndex();
870
871 // The 'first' and 'last' fields are chosen by offset, rather than field
872 // index. This allows the code to support bitfields, as well as regular
873 // fields.
874 uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex());
875 if (FOffset < FirstFieldOffset) {
876 FirstField = F;
877 FirstFieldOffset = FOffset;
878 } else if (FOffset > LastFieldOffset) {
879 LastField = F;
880 LastFieldOffset = FOffset;
881 }
882 }
883
884 const VarDecl *SrcRec;
885 const ASTRecordLayout &RecLayout;
886 FieldDecl *FirstField;
887 FieldDecl *LastField;
888 uint64_t FirstFieldOffset, LastFieldOffset;
889 unsigned LastAddedFieldIndex;
890 };
891
892 class ConstructorMemcpyizer : public FieldMemcpyizer {
893 private:
894
895 /// Get source argument for copy constructor. Returns null if not a copy
896 /// constructor.
897 static const VarDecl* getTrivialCopySource(const CXXConstructorDecl *CD,
898 FunctionArgList &Args) {
899 if (CD->isCopyOrMoveConstructor() && CD->isImplicitlyDefined())
900 return Args[Args.size() - 1];
901 return 0;
902 }
903
904 // Returns true if a CXXCtorInitializer represents a member initialization
905 // that can be rolled into a memcpy.
906 bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const {
907 if (!MemcpyableCtor)
908 return false;
909 FieldDecl *Field = MemberInit->getMember();
910 assert(Field != 0 && "No field for member init.");
911 QualType FieldType = Field->getType();
912 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
913
914 // Bail out on non-POD, not-trivially-constructable members.
915 if (!(CE && CE->getConstructor()->isTrivial()) &&
916 !(FieldType.isTriviallyCopyableType(CGF.getContext()) ||
917 FieldType->isReferenceType()))
918 return false;
919
920 // Bail out on volatile fields.
921 if (!isMemcpyableField(Field))
922 return false;
923
924 // Otherwise we're good.
925 return true;
926 }
927
928 public:
929 ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD,
930 FunctionArgList &Args)
931 : FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CD, Args)),
932 ConstructorDecl(CD),
933 MemcpyableCtor(CD->isImplicitlyDefined() &&
934 CD->isCopyOrMoveConstructor() &&
935 CGF.getLangOpts().getGC() == LangOptions::NonGC),
936 Args(Args) { }
937
938 void addMemberInitializer(CXXCtorInitializer *MemberInit) {
939 if (isMemberInitMemcpyable(MemberInit)) {
940 AggregatedInits.push_back(MemberInit);
941 addMemcpyableField(MemberInit->getMember());
942 } else {
943 emitAggregatedInits();
944 EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit,
945 ConstructorDecl, Args);
946 }
947 }
948
949 void emitAggregatedInits() {
950 if (AggregatedInits.size() <= 1) {
951 // This memcpy is too small to be worthwhile. Fall back on default
952 // codegen.
953 for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
954 EmitMemberInitializer(CGF, ConstructorDecl->getParent(),
955 AggregatedInits[i], ConstructorDecl, Args);
956 }
957 reset();
958 return;
959 }
960
961 pushEHDestructors();
962 emitMemcpy();
963 AggregatedInits.clear();
964 }
965
966 void pushEHDestructors() {
967 llvm::Value *ThisPtr = CGF.LoadCXXThis();
968 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
969 LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
970
971 for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
972 QualType FieldType = AggregatedInits[i]->getMember()->getType();
973 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
974 if (CGF.needsEHCleanup(dtorKind))
975 CGF.pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
976 }
977 }
978
979 void finish() {
980 emitAggregatedInits();
981 }
982
983 private:
984 const CXXConstructorDecl *ConstructorDecl;
985 bool MemcpyableCtor;
986 FunctionArgList &Args;
987 SmallVector<CXXCtorInitializer*, 16> AggregatedInits;
988 };
989
990 class AssignmentMemcpyizer : public FieldMemcpyizer {
991 private:
992
993 // Returns the memcpyable field copied by the given statement, if one
994 // exists. Otherwise r
995 FieldDecl* getMemcpyableField(Stmt *S) {
996 if (!AssignmentsMemcpyable)
997 return 0;
998 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
999 // Recognise trivial assignments.
1000 if (BO->getOpcode() != BO_Assign)
1001 return 0;
1002 MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS());
1003 if (!ME)
1004 return 0;
1005 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1006 if (!Field || !isMemcpyableField(Field))
1007 return 0;
1008 Stmt *RHS = BO->getRHS();
1009 if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS))
1010 RHS = EC->getSubExpr();
1011 if (!RHS)
1012 return 0;
1013 MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS);
1014 if (dyn_cast<FieldDecl>(ME2->getMemberDecl()) != Field)
1015 return 0;
1016 return Field;
1017 } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) {
1018 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl());
1019 if (!(MD && (MD->isCopyAssignmentOperator() ||
1020 MD->isMoveAssignmentOperator()) &&
1021 MD->isTrivial()))
1022 return 0;
1023 MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument());
1024 if (!IOA)
1025 return 0;
1026 FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl());
1027 if (!Field || !isMemcpyableField(Field))
1028 return 0;
1029 MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0));
1030 if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl()))
1031 return 0;
1032 return Field;
1033 } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1034 FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1035 if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy)
1036 return 0;
1037 Expr *DstPtr = CE->getArg(0);
1038 if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr))
1039 DstPtr = DC->getSubExpr();
1040 UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr);
1041 if (!DUO || DUO->getOpcode() != UO_AddrOf)
1042 return 0;
1043 MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr());
1044 if (!ME)
1045 return 0;
1046 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1047 if (!Field || !isMemcpyableField(Field))
1048 return 0;
1049 Expr *SrcPtr = CE->getArg(1);
1050 if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr))
1051 SrcPtr = SC->getSubExpr();
1052 UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr);
1053 if (!SUO || SUO->getOpcode() != UO_AddrOf)
1054 return 0;
1055 MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr());
1056 if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl()))
1057 return 0;
1058 return Field;
1059 }
1060
1061 return 0;
1062 }
1063
1064 bool AssignmentsMemcpyable;
1065 SmallVector<Stmt*, 16> AggregatedStmts;
1066
1067 public:
1068
1069 AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD,
1070 FunctionArgList &Args)
1071 : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]),
1072 AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) {
1073 assert(Args.size() == 2);
1074 }
1075
1076 void emitAssignment(Stmt *S) {
1077 FieldDecl *F = getMemcpyableField(S);
1078 if (F) {
1079 addMemcpyableField(F);
1080 AggregatedStmts.push_back(S);
1081 } else {
1082 emitAggregatedStmts();
1083 CGF.EmitStmt(S);
1084 }
1085 }
1086
1087 void emitAggregatedStmts() {
1088 if (AggregatedStmts.size() <= 1) {
1089 for (unsigned i = 0; i < AggregatedStmts.size(); ++i)
1090 CGF.EmitStmt(AggregatedStmts[i]);
1091 reset();
1092 }
1093
1094 emitMemcpy();
1095 AggregatedStmts.clear();
1096 }
1097
1098 void finish() {
1099 emitAggregatedStmts();
1100 }
1101 };
1102
1103}
1104
Anders Carlsson607d0372009-12-24 22:46:43 +00001105/// EmitCtorPrologue - This routine generates necessary code to initialize
1106/// base classes and non-static data members belonging to this constructor.
Anders Carlsson607d0372009-12-24 22:46:43 +00001107void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001108 CXXCtorType CtorType,
1109 FunctionArgList &Args) {
Sean Hunt059ce0d2011-05-01 07:04:31 +00001110 if (CD->isDelegatingConstructor())
1111 return EmitDelegatingCXXConstructorCall(CD, Args);
1112
Anders Carlsson607d0372009-12-24 22:46:43 +00001113 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlssona78fa2c2010-02-02 19:58:43 +00001114
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001115 CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
1116 E = CD->init_end();
1117
1118 llvm::BasicBlock *BaseCtorContinueBB = 0;
1119 if (ClassDecl->getNumVBases() &&
1120 !CGM.getTarget().getCXXABI().hasConstructorVariants()) {
1121 // The ABIs that don't have constructor variants need to put a branch
1122 // before the virtual base initialization code.
1123 BaseCtorContinueBB = CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this);
1124 assert(BaseCtorContinueBB);
1125 }
1126
1127 // Virtual base initializers first.
1128 for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
1129 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
1130 }
1131
1132 if (BaseCtorContinueBB) {
1133 // Complete object handler should continue to the remaining initializers.
1134 Builder.CreateBr(BaseCtorContinueBB);
1135 EmitBlock(BaseCtorContinueBB);
1136 }
1137
1138 // Then, non-virtual base initializers.
1139 for (; B != E && (*B)->isBaseInitializer(); B++) {
1140 assert(!(*B)->isBaseVirtual());
1141 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
Anders Carlsson607d0372009-12-24 22:46:43 +00001142 }
1143
Anders Carlsson603d6d12010-03-28 21:07:49 +00001144 InitializeVTablePointers(ClassDecl);
Anders Carlssona78fa2c2010-02-02 19:58:43 +00001145
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001146 // And finally, initialize class members.
Richard Smithc3bf52c2013-04-20 22:23:05 +00001147 FieldConstructionScope FCS(*this, CXXThisValue);
Lang Hames56c00c42013-02-17 07:22:09 +00001148 ConstructorMemcpyizer CM(*this, CD, Args);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001149 for (; B != E; B++) {
1150 CXXCtorInitializer *Member = (*B);
1151 assert(!Member->isBaseInitializer());
1152 assert(Member->isAnyMemberInitializer() &&
1153 "Delegating initializer on non-delegating constructor");
1154 CM.addMemberInitializer(Member);
1155 }
Lang Hames56c00c42013-02-17 07:22:09 +00001156 CM.finish();
Anders Carlsson607d0372009-12-24 22:46:43 +00001157}
1158
Anders Carlssonadf5dc32011-05-15 17:36:21 +00001159static bool
1160FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
1161
1162static bool
1163HasTrivialDestructorBody(ASTContext &Context,
1164 const CXXRecordDecl *BaseClassDecl,
1165 const CXXRecordDecl *MostDerivedClassDecl)
1166{
1167 // If the destructor is trivial we don't have to check anything else.
1168 if (BaseClassDecl->hasTrivialDestructor())
1169 return true;
1170
1171 if (!BaseClassDecl->getDestructor()->hasTrivialBody())
1172 return false;
1173
1174 // Check fields.
1175 for (CXXRecordDecl::field_iterator I = BaseClassDecl->field_begin(),
1176 E = BaseClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001177 const FieldDecl *Field = *I;
Anders Carlssonadf5dc32011-05-15 17:36:21 +00001178
1179 if (!FieldHasTrivialDestructorBody(Context, Field))
1180 return false;
1181 }
1182
1183 // Check non-virtual bases.
1184 for (CXXRecordDecl::base_class_const_iterator I =
1185 BaseClassDecl->bases_begin(), E = BaseClassDecl->bases_end();
1186 I != E; ++I) {
1187 if (I->isVirtual())
1188 continue;
1189
1190 const CXXRecordDecl *NonVirtualBase =
1191 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
1192 if (!HasTrivialDestructorBody(Context, NonVirtualBase,
1193 MostDerivedClassDecl))
1194 return false;
1195 }
1196
1197 if (BaseClassDecl == MostDerivedClassDecl) {
1198 // Check virtual bases.
1199 for (CXXRecordDecl::base_class_const_iterator I =
1200 BaseClassDecl->vbases_begin(), E = BaseClassDecl->vbases_end();
1201 I != E; ++I) {
1202 const CXXRecordDecl *VirtualBase =
1203 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
1204 if (!HasTrivialDestructorBody(Context, VirtualBase,
1205 MostDerivedClassDecl))
1206 return false;
1207 }
1208 }
1209
1210 return true;
1211}
1212
1213static bool
1214FieldHasTrivialDestructorBody(ASTContext &Context,
1215 const FieldDecl *Field)
1216{
1217 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
1218
1219 const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
1220 if (!RT)
1221 return true;
1222
1223 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1224 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
1225}
1226
Anders Carlssonffb945f2011-05-14 23:26:09 +00001227/// CanSkipVTablePointerInitialization - Check whether we need to initialize
1228/// any vtable pointers before calling this destructor.
1229static bool CanSkipVTablePointerInitialization(ASTContext &Context,
Anders Carlssone3d6cf22011-05-16 04:08:36 +00001230 const CXXDestructorDecl *Dtor) {
Anders Carlssonffb945f2011-05-14 23:26:09 +00001231 if (!Dtor->hasTrivialBody())
1232 return false;
1233
1234 // Check the fields.
1235 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1236 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1237 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001238 const FieldDecl *Field = *I;
Anders Carlssonffb945f2011-05-14 23:26:09 +00001239
Anders Carlssonadf5dc32011-05-15 17:36:21 +00001240 if (!FieldHasTrivialDestructorBody(Context, Field))
1241 return false;
Anders Carlssonffb945f2011-05-14 23:26:09 +00001242 }
1243
1244 return true;
1245}
1246
John McCall9fc6a772010-02-19 09:25:03 +00001247/// EmitDestructorBody - Emits the body of the current destructor.
1248void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
1249 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
1250 CXXDtorType DtorType = CurGD.getDtorType();
1251
John McCall50da2ca2010-07-21 05:30:47 +00001252 // The call to operator delete in a deleting destructor happens
1253 // outside of the function-try-block, which means it's always
1254 // possible to delegate the destructor body to the complete
1255 // destructor. Do so.
1256 if (DtorType == Dtor_Deleting) {
1257 EnterDtorCleanups(Dtor, Dtor_Deleting);
1258 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001259 /*Delegating=*/false, LoadCXXThis());
John McCall50da2ca2010-07-21 05:30:47 +00001260 PopCleanupBlock();
1261 return;
1262 }
1263
John McCall9fc6a772010-02-19 09:25:03 +00001264 Stmt *Body = Dtor->getBody();
1265
1266 // If the body is a function-try-block, enter the try before
John McCall50da2ca2010-07-21 05:30:47 +00001267 // anything else.
1268 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCall9fc6a772010-02-19 09:25:03 +00001269 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +00001270 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +00001271
John McCall50da2ca2010-07-21 05:30:47 +00001272 // Enter the epilogue cleanups.
1273 RunCleanupsScope DtorEpilogue(*this);
1274
John McCall9fc6a772010-02-19 09:25:03 +00001275 // If this is the complete variant, just invoke the base variant;
1276 // the epilogue will destruct the virtual bases. But we can't do
1277 // this optimization if the body is a function-try-block, because
1278 // we'd introduce *two* handler blocks.
John McCall50da2ca2010-07-21 05:30:47 +00001279 switch (DtorType) {
1280 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
1281
1282 case Dtor_Complete:
1283 // Enter the cleanup scopes for virtual bases.
1284 EnterDtorCleanups(Dtor, Dtor_Complete);
1285
John McCallb8b2c9d2013-01-25 22:30:49 +00001286 if (!isTryBody &&
John McCall64aa4b32013-04-16 22:48:15 +00001287 CGM.getTarget().getCXXABI().hasDestructorVariants()) {
John McCall50da2ca2010-07-21 05:30:47 +00001288 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001289 /*Delegating=*/false, LoadCXXThis());
John McCall50da2ca2010-07-21 05:30:47 +00001290 break;
1291 }
1292 // Fallthrough: act like we're in the base variant.
John McCall9fc6a772010-02-19 09:25:03 +00001293
John McCall50da2ca2010-07-21 05:30:47 +00001294 case Dtor_Base:
1295 // Enter the cleanup scopes for fields and non-virtual bases.
1296 EnterDtorCleanups(Dtor, Dtor_Base);
1297
1298 // Initialize the vtable pointers before entering the body.
Anders Carlssonffb945f2011-05-14 23:26:09 +00001299 if (!CanSkipVTablePointerInitialization(getContext(), Dtor))
1300 InitializeVTablePointers(Dtor->getParent());
John McCall50da2ca2010-07-21 05:30:47 +00001301
1302 if (isTryBody)
1303 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
1304 else if (Body)
1305 EmitStmt(Body);
1306 else {
1307 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
1308 // nothing to do besides what's in the epilogue
1309 }
Fariborz Jahanian5abec142011-02-02 23:12:46 +00001310 // -fapple-kext must inline any call to this dtor into
1311 // the caller's body.
Richard Smith7edf9e32012-11-01 22:30:59 +00001312 if (getLangOpts().AppleKext)
Bill Wendling72390b32012-12-20 19:27:06 +00001313 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
John McCall50da2ca2010-07-21 05:30:47 +00001314 break;
John McCall9fc6a772010-02-19 09:25:03 +00001315 }
1316
John McCall50da2ca2010-07-21 05:30:47 +00001317 // Jump out through the epilogue cleanups.
1318 DtorEpilogue.ForceCleanup();
John McCall9fc6a772010-02-19 09:25:03 +00001319
1320 // Exit the try if applicable.
1321 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +00001322 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +00001323}
1324
Lang Hames56c00c42013-02-17 07:22:09 +00001325void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) {
1326 const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
1327 const Stmt *RootS = AssignOp->getBody();
1328 assert(isa<CompoundStmt>(RootS) &&
1329 "Body of an implicit assignment operator should be compound stmt.");
1330 const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
1331
1332 LexicalScope Scope(*this, RootCS->getSourceRange());
1333
1334 AssignmentMemcpyizer AM(*this, AssignOp, Args);
1335 for (CompoundStmt::const_body_iterator I = RootCS->body_begin(),
1336 E = RootCS->body_end();
1337 I != E; ++I) {
1338 AM.emitAssignment(*I);
1339 }
1340 AM.finish();
1341}
1342
John McCall50da2ca2010-07-21 05:30:47 +00001343namespace {
1344 /// Call the operator delete associated with the current destructor.
John McCall1f0fca52010-07-21 07:22:38 +00001345 struct CallDtorDelete : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +00001346 CallDtorDelete() {}
1347
John McCallad346f42011-07-12 20:27:29 +00001348 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall50da2ca2010-07-21 05:30:47 +00001349 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1350 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1351 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1352 CGF.getContext().getTagDeclType(ClassDecl));
1353 }
1354 };
1355
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +00001356 struct CallDtorDeleteConditional : EHScopeStack::Cleanup {
1357 llvm::Value *ShouldDeleteCondition;
1358 public:
1359 CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
1360 : ShouldDeleteCondition(ShouldDeleteCondition) {
1361 assert(ShouldDeleteCondition != NULL);
1362 }
1363
1364 void Emit(CodeGenFunction &CGF, Flags flags) {
1365 llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
1366 llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
1367 llvm::Value *ShouldCallDelete
1368 = CGF.Builder.CreateIsNull(ShouldDeleteCondition);
1369 CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
1370
1371 CGF.EmitBlock(callDeleteBB);
1372 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1373 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1374 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1375 CGF.getContext().getTagDeclType(ClassDecl));
1376 CGF.Builder.CreateBr(continueBB);
1377
1378 CGF.EmitBlock(continueBB);
1379 }
1380 };
1381
John McCall9928c482011-07-12 16:41:08 +00001382 class DestroyField : public EHScopeStack::Cleanup {
1383 const FieldDecl *field;
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001384 CodeGenFunction::Destroyer *destroyer;
John McCall9928c482011-07-12 16:41:08 +00001385 bool useEHCleanupForArray;
John McCall50da2ca2010-07-21 05:30:47 +00001386
John McCall9928c482011-07-12 16:41:08 +00001387 public:
1388 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
1389 bool useEHCleanupForArray)
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001390 : field(field), destroyer(destroyer),
John McCall9928c482011-07-12 16:41:08 +00001391 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall50da2ca2010-07-21 05:30:47 +00001392
John McCallad346f42011-07-12 20:27:29 +00001393 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall9928c482011-07-12 16:41:08 +00001394 // Find the address of the field.
1395 llvm::Value *thisValue = CGF.LoadCXXThis();
Eli Friedman377ecc72012-04-16 03:54:45 +00001396 QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
1397 LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
1398 LValue LV = CGF.EmitLValueForField(ThisLV, field);
John McCall9928c482011-07-12 16:41:08 +00001399 assert(LV.isSimple());
1400
1401 CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
John McCallad346f42011-07-12 20:27:29 +00001402 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCall50da2ca2010-07-21 05:30:47 +00001403 }
1404 };
1405}
1406
Anders Carlsson607d0372009-12-24 22:46:43 +00001407/// EmitDtorEpilogue - Emit all code that comes at the end of class's
1408/// destructor. This is to call destructors on members and base classes
1409/// in reverse order of their construction.
John McCall50da2ca2010-07-21 05:30:47 +00001410void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
1411 CXXDtorType DtorType) {
Anders Carlsson607d0372009-12-24 22:46:43 +00001412 assert(!DD->isTrivial() &&
1413 "Should not emit dtor epilogue for trivial dtor!");
1414
John McCall50da2ca2010-07-21 05:30:47 +00001415 // The deleting-destructor phase just needs to call the appropriate
1416 // operator delete that Sema picked up.
John McCall3b477332010-02-18 19:59:28 +00001417 if (DtorType == Dtor_Deleting) {
1418 assert(DD->getOperatorDelete() &&
1419 "operator delete missing - EmitDtorEpilogue");
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +00001420 if (CXXStructorImplicitParamValue) {
1421 // If there is an implicit param to the deleting dtor, it's a boolean
1422 // telling whether we should call delete at the end of the dtor.
1423 EHStack.pushCleanup<CallDtorDeleteConditional>(
1424 NormalAndEHCleanup, CXXStructorImplicitParamValue);
1425 } else {
1426 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
1427 }
John McCall3b477332010-02-18 19:59:28 +00001428 return;
1429 }
1430
John McCall50da2ca2010-07-21 05:30:47 +00001431 const CXXRecordDecl *ClassDecl = DD->getParent();
1432
Richard Smith416f63e2011-09-18 12:11:43 +00001433 // Unions have no bases and do not call field destructors.
1434 if (ClassDecl->isUnion())
1435 return;
1436
John McCall50da2ca2010-07-21 05:30:47 +00001437 // The complete-destructor phase just destructs all the virtual bases.
John McCall3b477332010-02-18 19:59:28 +00001438 if (DtorType == Dtor_Complete) {
John McCall50da2ca2010-07-21 05:30:47 +00001439
1440 // We push them in the forward order so that they'll be popped in
1441 // the reverse order.
1442 for (CXXRecordDecl::base_class_const_iterator I =
1443 ClassDecl->vbases_begin(), E = ClassDecl->vbases_end();
John McCall3b477332010-02-18 19:59:28 +00001444 I != E; ++I) {
1445 const CXXBaseSpecifier &Base = *I;
1446 CXXRecordDecl *BaseClassDecl
1447 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1448
1449 // Ignore trivial destructors.
1450 if (BaseClassDecl->hasTrivialDestructor())
1451 continue;
John McCall50da2ca2010-07-21 05:30:47 +00001452
John McCall1f0fca52010-07-21 07:22:38 +00001453 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1454 BaseClassDecl,
1455 /*BaseIsVirtual*/ true);
John McCall3b477332010-02-18 19:59:28 +00001456 }
John McCall50da2ca2010-07-21 05:30:47 +00001457
John McCall3b477332010-02-18 19:59:28 +00001458 return;
1459 }
1460
1461 assert(DtorType == Dtor_Base);
John McCall50da2ca2010-07-21 05:30:47 +00001462
1463 // Destroy non-virtual bases.
1464 for (CXXRecordDecl::base_class_const_iterator I =
1465 ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) {
1466 const CXXBaseSpecifier &Base = *I;
1467
1468 // Ignore virtual bases.
1469 if (Base.isVirtual())
1470 continue;
1471
1472 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
1473
1474 // Ignore trivial destructors.
1475 if (BaseClassDecl->hasTrivialDestructor())
1476 continue;
John McCall3b477332010-02-18 19:59:28 +00001477
John McCall1f0fca52010-07-21 07:22:38 +00001478 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1479 BaseClassDecl,
1480 /*BaseIsVirtual*/ false);
John McCall50da2ca2010-07-21 05:30:47 +00001481 }
1482
1483 // Destroy direct fields.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001484 SmallVector<const FieldDecl *, 16> FieldDecls;
Anders Carlsson607d0372009-12-24 22:46:43 +00001485 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1486 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001487 const FieldDecl *field = *I;
John McCall9928c482011-07-12 16:41:08 +00001488 QualType type = field->getType();
1489 QualType::DestructionKind dtorKind = type.isDestructedType();
1490 if (!dtorKind) continue;
John McCall50da2ca2010-07-21 05:30:47 +00001491
Richard Smith9a561d52012-02-26 09:11:52 +00001492 // Anonymous union members do not have their destructors called.
1493 const RecordType *RT = type->getAsUnionType();
1494 if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
1495
John McCall9928c482011-07-12 16:41:08 +00001496 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1497 EHStack.pushCleanup<DestroyField>(cleanupKind, field,
1498 getDestroyer(dtorKind),
1499 cleanupKind & EHCleanup);
Anders Carlsson607d0372009-12-24 22:46:43 +00001500 }
Anders Carlsson607d0372009-12-24 22:46:43 +00001501}
1502
John McCallc3c07662011-07-13 06:10:41 +00001503/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1504/// constructor for each of several members of an array.
Douglas Gregor59174c02010-07-21 01:10:17 +00001505///
John McCallc3c07662011-07-13 06:10:41 +00001506/// \param ctor the constructor to call for each element
John McCallc3c07662011-07-13 06:10:41 +00001507/// \param arrayType the type of the array to initialize
1508/// \param arrayBegin an arrayType*
1509/// \param zeroInitialize true if each element should be
1510/// zero-initialized before it is constructed
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001511void
John McCallc3c07662011-07-13 06:10:41 +00001512CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1513 const ConstantArrayType *arrayType,
1514 llvm::Value *arrayBegin,
1515 CallExpr::const_arg_iterator argBegin,
1516 CallExpr::const_arg_iterator argEnd,
1517 bool zeroInitialize) {
1518 QualType elementType;
1519 llvm::Value *numElements =
1520 emitArrayLength(arrayType, elementType, arrayBegin);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001521
John McCallc3c07662011-07-13 06:10:41 +00001522 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin,
1523 argBegin, argEnd, zeroInitialize);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001524}
1525
John McCallc3c07662011-07-13 06:10:41 +00001526/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1527/// constructor for each of several members of an array.
1528///
1529/// \param ctor the constructor to call for each element
1530/// \param numElements the number of elements in the array;
John McCalldd376ca2011-07-13 07:37:11 +00001531/// may be zero
John McCallc3c07662011-07-13 06:10:41 +00001532/// \param arrayBegin a T*, where T is the type constructed by ctor
1533/// \param zeroInitialize true if each element should be
1534/// zero-initialized before it is constructed
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001535void
John McCallc3c07662011-07-13 06:10:41 +00001536CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1537 llvm::Value *numElements,
1538 llvm::Value *arrayBegin,
1539 CallExpr::const_arg_iterator argBegin,
1540 CallExpr::const_arg_iterator argEnd,
1541 bool zeroInitialize) {
John McCalldd376ca2011-07-13 07:37:11 +00001542
1543 // It's legal for numElements to be zero. This can happen both
1544 // dynamically, because x can be zero in 'new A[x]', and statically,
1545 // because of GCC extensions that permit zero-length arrays. There
1546 // are probably legitimate places where we could assume that this
1547 // doesn't happen, but it's not clear that it's worth it.
1548 llvm::BranchInst *zeroCheckBranch = 0;
1549
1550 // Optimize for a constant count.
1551 llvm::ConstantInt *constantCount
1552 = dyn_cast<llvm::ConstantInt>(numElements);
1553 if (constantCount) {
1554 // Just skip out if the constant count is zero.
1555 if (constantCount->isZero()) return;
1556
1557 // Otherwise, emit the check.
1558 } else {
1559 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1560 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1561 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1562 EmitBlock(loopBB);
1563 }
1564
John McCallc3c07662011-07-13 06:10:41 +00001565 // Find the end of the array.
1566 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1567 "arrayctor.end");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001568
John McCallc3c07662011-07-13 06:10:41 +00001569 // Enter the loop, setting up a phi for the current location to initialize.
1570 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1571 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1572 EmitBlock(loopBB);
1573 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1574 "arrayctor.cur");
1575 cur->addIncoming(arrayBegin, entryBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001576
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001577 // Inside the loop body, emit the constructor call on the array element.
John McCallc3c07662011-07-13 06:10:41 +00001578
1579 QualType type = getContext().getTypeDeclType(ctor->getParent());
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001580
Douglas Gregor59174c02010-07-21 01:10:17 +00001581 // Zero initialize the storage, if requested.
John McCallc3c07662011-07-13 06:10:41 +00001582 if (zeroInitialize)
1583 EmitNullInitialization(cur, type);
Douglas Gregor59174c02010-07-21 01:10:17 +00001584
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001585 // C++ [class.temporary]p4:
1586 // There are two contexts in which temporaries are destroyed at a different
1587 // point than the end of the full-expression. The first context is when a
1588 // default constructor is called to initialize an element of an array.
1589 // If the constructor has one or more default arguments, the destruction of
1590 // every temporary created in a default argument expression is sequenced
1591 // before the construction of the next array element, if any.
1592
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001593 {
John McCallf1549f62010-07-06 01:34:17 +00001594 RunCleanupsScope Scope(*this);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001595
John McCallc3c07662011-07-13 06:10:41 +00001596 // Evaluate the constructor and its arguments in a regular
1597 // partial-destroy cleanup.
David Blaikie4e4d0842012-03-11 07:00:24 +00001598 if (getLangOpts().Exceptions &&
John McCallc3c07662011-07-13 06:10:41 +00001599 !ctor->getParent()->hasTrivialDestructor()) {
1600 Destroyer *destroyer = destroyCXXObject;
1601 pushRegularPartialArrayCleanup(arrayBegin, cur, type, *destroyer);
1602 }
1603
1604 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/ false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001605 /*Delegating=*/false, cur, argBegin, argEnd);
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001606 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001607
John McCallc3c07662011-07-13 06:10:41 +00001608 // Go to the next element.
1609 llvm::Value *next =
1610 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
1611 "arrayctor.next");
1612 cur->addIncoming(next, Builder.GetInsertBlock());
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001613
John McCallc3c07662011-07-13 06:10:41 +00001614 // Check whether that's the end of the loop.
1615 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
1616 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
1617 Builder.CreateCondBr(done, contBB, loopBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001618
John McCalldd376ca2011-07-13 07:37:11 +00001619 // Patch the earlier check to skip over the loop.
1620 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
1621
John McCallc3c07662011-07-13 06:10:41 +00001622 EmitBlock(contBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001623}
1624
John McCallbdc4d802011-07-09 01:37:26 +00001625void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
1626 llvm::Value *addr,
1627 QualType type) {
1628 const RecordType *rtype = type->castAs<RecordType>();
1629 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
1630 const CXXDestructorDecl *dtor = record->getDestructor();
1631 assert(!dtor->isTrivial());
1632 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001633 /*Delegating=*/false, addr);
John McCallbdc4d802011-07-09 01:37:26 +00001634}
1635
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001636void
1637CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
Anders Carlsson155ed4a2010-05-02 23:20:53 +00001638 CXXCtorType Type, bool ForVirtualBase,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001639 bool Delegating,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001640 llvm::Value *This,
1641 CallExpr::const_arg_iterator ArgBeg,
1642 CallExpr::const_arg_iterator ArgEnd) {
Devang Patel3ee36af2011-02-22 20:55:26 +00001643
1644 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonov3a70cd62012-04-27 07:24:20 +00001645 if (DI &&
Douglas Gregor4cdad312012-10-23 20:05:01 +00001646 CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::LimitedDebugInfo) {
Eric Christopheraf790882012-02-01 21:44:56 +00001647 // If debug info for this class has not been emitted then this is the
1648 // right time to do so.
Devang Patel3ee36af2011-02-22 20:55:26 +00001649 const CXXRecordDecl *Parent = D->getParent();
1650 DI->getOrCreateRecordType(CGM.getContext().getTypeDeclType(Parent),
1651 Parent->getLocation());
1652 }
1653
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001654 // If this is a trivial constructor, just emit what's needed.
John McCall8b6bbeb2010-02-06 00:25:16 +00001655 if (D->isTrivial()) {
1656 if (ArgBeg == ArgEnd) {
1657 // Trivial default constructor, no codegen required.
1658 assert(D->isDefaultConstructor() &&
1659 "trivial 0-arg ctor not a default ctor");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001660 return;
1661 }
John McCall8b6bbeb2010-02-06 00:25:16 +00001662
1663 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001664 assert(D->isCopyOrMoveConstructor() &&
1665 "trivial 1-arg ctor not a copy/move ctor");
John McCall8b6bbeb2010-02-06 00:25:16 +00001666
John McCall8b6bbeb2010-02-06 00:25:16 +00001667 const Expr *E = (*ArgBeg);
1668 QualType Ty = E->getType();
1669 llvm::Value *Src = EmitLValue(E).getAddress();
1670 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001671 return;
1672 }
1673
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001674 // Non-trivial constructors are handled in an ABI-specific manner.
Manman Ren63fd4082013-03-20 16:59:38 +00001675 llvm::Value *Callee = CGM.getCXXABI().EmitConstructorCall(*this, D, Type,
1676 ForVirtualBase, Delegating, This, ArgBeg, ArgEnd);
1677 if (CGM.getCXXABI().HasThisReturn(CurGD) &&
1678 CGM.getCXXABI().HasThisReturn(GlobalDecl(D, Type)))
1679 CalleeWithThisReturn = Callee;
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001680}
1681
John McCallc0bf4622010-02-23 00:48:20 +00001682void
Fariborz Jahanian34999872010-11-13 21:53:34 +00001683CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
1684 llvm::Value *This, llvm::Value *Src,
1685 CallExpr::const_arg_iterator ArgBeg,
1686 CallExpr::const_arg_iterator ArgEnd) {
1687 if (D->isTrivial()) {
1688 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001689 assert(D->isCopyOrMoveConstructor() &&
1690 "trivial 1-arg ctor not a copy/move ctor");
Fariborz Jahanian34999872010-11-13 21:53:34 +00001691 EmitAggregateCopy(This, Src, (*ArgBeg)->getType());
1692 return;
1693 }
1694 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D,
1695 clang::Ctor_Complete);
1696 assert(D->isInstance() &&
1697 "Trying to emit a member call expr on a static method!");
1698
1699 const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
1700
1701 CallArgList Args;
1702
1703 // Push the this ptr.
Eli Friedman04c9a492011-05-02 17:57:46 +00001704 Args.add(RValue::get(This), D->getThisType(getContext()));
Fariborz Jahanian34999872010-11-13 21:53:34 +00001705
1706
1707 // Push the src ptr.
1708 QualType QT = *(FPT->arg_type_begin());
Chris Lattner2acc6e32011-07-18 04:24:23 +00001709 llvm::Type *t = CGM.getTypes().ConvertType(QT);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001710 Src = Builder.CreateBitCast(Src, t);
Eli Friedman04c9a492011-05-02 17:57:46 +00001711 Args.add(RValue::get(Src), QT);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001712
1713 // Skip over first argument (Src).
1714 ++ArgBeg;
1715 CallExpr::const_arg_iterator Arg = ArgBeg;
1716 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin()+1,
1717 E = FPT->arg_type_end(); I != E; ++I, ++Arg) {
1718 assert(Arg != ArgEnd && "Running over edge of argument list!");
John McCall413ebdb2011-03-11 20:59:21 +00001719 EmitCallArg(Args, *Arg, *I);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001720 }
1721 // Either we've emitted all the call args, or we have a call to a
1722 // variadic function.
1723 assert((Arg == ArgEnd || FPT->isVariadic()) &&
1724 "Extra arguments in non-variadic function!");
1725 // If we still have any arguments, emit them using the type of the argument.
1726 for (; Arg != ArgEnd; ++Arg) {
1727 QualType ArgType = Arg->getType();
John McCall413ebdb2011-03-11 20:59:21 +00001728 EmitCallArg(Args, *Arg, ArgType);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001729 }
1730
John McCall0f3d0972012-07-07 06:41:13 +00001731 EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, RequiredArgs::All),
1732 Callee, ReturnValueSlot(), Args, D);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001733}
1734
1735void
John McCallc0bf4622010-02-23 00:48:20 +00001736CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1737 CXXCtorType CtorType,
1738 const FunctionArgList &Args) {
1739 CallArgList DelegateArgs;
1740
1741 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
1742 assert(I != E && "no parameters to constructor");
1743
1744 // this
Eli Friedman04c9a492011-05-02 17:57:46 +00001745 DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType());
John McCallc0bf4622010-02-23 00:48:20 +00001746 ++I;
1747
1748 // vtt
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001749 if (llvm::Value *VTT = GetVTTParameter(GlobalDecl(Ctor, CtorType),
Douglas Gregor378e1e72013-01-31 05:50:40 +00001750 /*ForVirtualBase=*/false,
1751 /*Delegating=*/true)) {
John McCallc0bf4622010-02-23 00:48:20 +00001752 QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
Eli Friedman04c9a492011-05-02 17:57:46 +00001753 DelegateArgs.add(RValue::get(VTT), VoidPP);
John McCallc0bf4622010-02-23 00:48:20 +00001754
Anders Carlssonaf440352010-03-23 04:11:45 +00001755 if (CodeGenVTables::needsVTTParameter(CurGD)) {
John McCallc0bf4622010-02-23 00:48:20 +00001756 assert(I != E && "cannot skip vtt parameter, already done with args");
John McCalld26bc762011-03-09 04:27:21 +00001757 assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
John McCallc0bf4622010-02-23 00:48:20 +00001758 ++I;
1759 }
1760 }
1761
1762 // Explicit arguments.
1763 for (; I != E; ++I) {
John McCall413ebdb2011-03-11 20:59:21 +00001764 const VarDecl *param = *I;
1765 EmitDelegateCallArg(DelegateArgs, param);
John McCallc0bf4622010-02-23 00:48:20 +00001766 }
1767
Manman Ren63fd4082013-03-20 16:59:38 +00001768 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(Ctor, CtorType);
John McCallde5d3c72012-02-17 03:33:10 +00001769 EmitCall(CGM.getTypes().arrangeCXXConstructorDeclaration(Ctor, CtorType),
Manman Ren63fd4082013-03-20 16:59:38 +00001770 Callee, ReturnValueSlot(), DelegateArgs, Ctor);
1771 if (CGM.getCXXABI().HasThisReturn(CurGD) &&
1772 CGM.getCXXABI().HasThisReturn(GlobalDecl(Ctor, CtorType)))
1773 CalleeWithThisReturn = Callee;
John McCallc0bf4622010-02-23 00:48:20 +00001774}
1775
Sean Huntb76af9c2011-05-03 23:05:34 +00001776namespace {
1777 struct CallDelegatingCtorDtor : EHScopeStack::Cleanup {
1778 const CXXDestructorDecl *Dtor;
1779 llvm::Value *Addr;
1780 CXXDtorType Type;
1781
1782 CallDelegatingCtorDtor(const CXXDestructorDecl *D, llvm::Value *Addr,
1783 CXXDtorType Type)
1784 : Dtor(D), Addr(Addr), Type(Type) {}
1785
John McCallad346f42011-07-12 20:27:29 +00001786 void Emit(CodeGenFunction &CGF, Flags flags) {
Sean Huntb76af9c2011-05-03 23:05:34 +00001787 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001788 /*Delegating=*/true, Addr);
Sean Huntb76af9c2011-05-03 23:05:34 +00001789 }
1790 };
1791}
1792
Sean Hunt059ce0d2011-05-01 07:04:31 +00001793void
1794CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
1795 const FunctionArgList &Args) {
1796 assert(Ctor->isDelegatingConstructor());
1797
1798 llvm::Value *ThisPtr = LoadCXXThis();
1799
Eli Friedmanf3940782011-12-03 00:54:26 +00001800 QualType Ty = getContext().getTagDeclType(Ctor->getParent());
Eli Friedmand7722d92011-12-03 02:13:40 +00001801 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
John McCallf85e1932011-06-15 23:02:42 +00001802 AggValueSlot AggSlot =
Eli Friedmanf3940782011-12-03 00:54:26 +00001803 AggValueSlot::forAddr(ThisPtr, Alignment, Qualifiers(),
John McCall7c2349b2011-08-25 20:40:09 +00001804 AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +00001805 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +00001806 AggValueSlot::IsNotAliased);
Sean Hunt059ce0d2011-05-01 07:04:31 +00001807
1808 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
Sean Hunt059ce0d2011-05-01 07:04:31 +00001809
Sean Huntb76af9c2011-05-03 23:05:34 +00001810 const CXXRecordDecl *ClassDecl = Ctor->getParent();
David Blaikie4e4d0842012-03-11 07:00:24 +00001811 if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
Sean Huntb76af9c2011-05-03 23:05:34 +00001812 CXXDtorType Type =
1813 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
1814
1815 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
1816 ClassDecl->getDestructor(),
1817 ThisPtr, Type);
1818 }
1819}
Sean Hunt059ce0d2011-05-01 07:04:31 +00001820
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001821void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
1822 CXXDtorType Type,
Anders Carlsson8e6404c2010-05-02 23:29:11 +00001823 bool ForVirtualBase,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001824 bool Delegating,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001825 llvm::Value *This) {
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001826 llvm::Value *VTT = GetVTTParameter(GlobalDecl(DD, Type),
Douglas Gregor378e1e72013-01-31 05:50:40 +00001827 ForVirtualBase, Delegating);
Fariborz Jahanianccd52592011-02-01 23:22:34 +00001828 llvm::Value *Callee = 0;
Richard Smith7edf9e32012-11-01 22:30:59 +00001829 if (getLangOpts().AppleKext)
Fariborz Jahanian771c6782011-02-03 19:27:17 +00001830 Callee = BuildAppleKextVirtualDestructorCall(DD, Type,
1831 DD->getParent());
Fariborz Jahanianccd52592011-02-01 23:22:34 +00001832
1833 if (!Callee)
1834 Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001835
Richard Smith4def70d2012-10-09 19:52:38 +00001836 // FIXME: Provide a source location here.
1837 EmitCXXMemberCall(DD, SourceLocation(), Callee, ReturnValueSlot(), This,
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +00001838 VTT, getContext().getPointerType(getContext().VoidPtrTy),
1839 0, 0);
Manman Ren63fd4082013-03-20 16:59:38 +00001840 if (CGM.getCXXABI().HasThisReturn(CurGD) &&
1841 CGM.getCXXABI().HasThisReturn(GlobalDecl(DD, Type)))
1842 CalleeWithThisReturn = Callee;
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001843}
1844
John McCall291ae942010-07-21 01:41:18 +00001845namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001846 struct CallLocalDtor : EHScopeStack::Cleanup {
John McCall291ae942010-07-21 01:41:18 +00001847 const CXXDestructorDecl *Dtor;
1848 llvm::Value *Addr;
1849
1850 CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
1851 : Dtor(D), Addr(Addr) {}
1852
John McCallad346f42011-07-12 20:27:29 +00001853 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall291ae942010-07-21 01:41:18 +00001854 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001855 /*ForVirtualBase=*/false,
1856 /*Delegating=*/false, Addr);
John McCall291ae942010-07-21 01:41:18 +00001857 }
1858 };
1859}
1860
John McCall81407d42010-07-21 06:29:51 +00001861void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
1862 llvm::Value *Addr) {
John McCall1f0fca52010-07-21 07:22:38 +00001863 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
John McCall81407d42010-07-21 06:29:51 +00001864}
1865
John McCallf1549f62010-07-06 01:34:17 +00001866void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
1867 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
1868 if (!ClassDecl) return;
1869 if (ClassDecl->hasTrivialDestructor()) return;
1870
1871 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCall642a75f2011-04-28 02:15:35 +00001872 assert(D && D->isUsed() && "destructor not marked as used!");
John McCall81407d42010-07-21 06:29:51 +00001873 PushDestructorCleanup(D, Addr);
John McCallf1549f62010-07-06 01:34:17 +00001874}
1875
Anders Carlssond103f9f2010-03-28 19:40:00 +00001876void
1877CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001878 const CXXRecordDecl *NearestVBase,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001879 CharUnits OffsetFromNearestVBase,
Anders Carlssond103f9f2010-03-28 19:40:00 +00001880 llvm::Constant *VTable,
1881 const CXXRecordDecl *VTableClass) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001882 const CXXRecordDecl *RD = Base.getBase();
1883
Anders Carlssond103f9f2010-03-28 19:40:00 +00001884 // Compute the address point.
Anders Carlssonc83f1062010-03-29 01:08:49 +00001885 llvm::Value *VTableAddressPoint;
Anders Carlsson851853d2010-03-29 02:38:51 +00001886
Anders Carlssonc83f1062010-03-29 01:08:49 +00001887 // Check if we need to use a vtable from the VTT.
Anders Carlsson851853d2010-03-29 02:38:51 +00001888 if (CodeGenVTables::needsVTTParameter(CurGD) &&
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001889 (RD->getNumVBases() || NearestVBase)) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001890 // Get the secondary vpointer index.
1891 uint64_t VirtualPointerIndex =
1892 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1893
1894 /// Load the VTT.
1895 llvm::Value *VTT = LoadCXXVTT();
1896 if (VirtualPointerIndex)
1897 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1898
1899 // And load the address point from the VTT.
1900 VTableAddressPoint = Builder.CreateLoad(VTT);
1901 } else {
Peter Collingbourne84fcc482011-09-26 01:56:41 +00001902 uint64_t AddressPoint =
Peter Collingbournee09cdf42011-09-26 01:56:50 +00001903 CGM.getVTableContext().getVTableLayout(VTableClass).getAddressPoint(Base);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001904 VTableAddressPoint =
Anders Carlssond103f9f2010-03-28 19:40:00 +00001905 Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001906 }
Anders Carlssond103f9f2010-03-28 19:40:00 +00001907
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001908 // Compute where to store the address point.
Anders Carlsson8246cc72010-05-03 00:29:58 +00001909 llvm::Value *VirtualOffset = 0;
Ken Dyck9a8ad9b2011-03-23 00:45:26 +00001910 CharUnits NonVirtualOffset = CharUnits::Zero();
Anders Carlsson3e79c302010-04-20 18:05:10 +00001911
1912 if (CodeGenVTables::needsVTTParameter(CurGD) && NearestVBase) {
1913 // We need to use the virtual base offset offset because the virtual base
1914 // might have a different offset in the most derived class.
Reid Klecknerb0f533e2013-05-29 18:02:47 +00001915 VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(*this,
1916 LoadCXXThis(),
1917 VTableClass,
1918 NearestVBase);
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001919 NonVirtualOffset = OffsetFromNearestVBase;
Anders Carlsson3e79c302010-04-20 18:05:10 +00001920 } else {
Anders Carlsson8246cc72010-05-03 00:29:58 +00001921 // We can just use the base offset in the complete class.
Ken Dyck4230d522011-03-24 01:21:01 +00001922 NonVirtualOffset = Base.getBaseOffset();
Anders Carlsson3e79c302010-04-20 18:05:10 +00001923 }
Anders Carlsson8246cc72010-05-03 00:29:58 +00001924
1925 // Apply the offsets.
1926 llvm::Value *VTableField = LoadCXXThis();
1927
Ken Dyck9a8ad9b2011-03-23 00:45:26 +00001928 if (!NonVirtualOffset.isZero() || VirtualOffset)
Anders Carlsson8246cc72010-05-03 00:29:58 +00001929 VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
1930 NonVirtualOffset,
1931 VirtualOffset);
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001932
Anders Carlssond103f9f2010-03-28 19:40:00 +00001933 // Finally, store the address point.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001934 llvm::Type *AddressPointPtrTy =
Anders Carlssond103f9f2010-03-28 19:40:00 +00001935 VTableAddressPoint->getType()->getPointerTo();
1936 VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
Kostya Serebryany8cb4a072012-03-26 17:03:51 +00001937 llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
1938 CGM.DecorateInstruction(Store, CGM.getTBAAInfoForVTablePtr());
Anders Carlssond103f9f2010-03-28 19:40:00 +00001939}
1940
Anders Carlsson603d6d12010-03-28 21:07:49 +00001941void
1942CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001943 const CXXRecordDecl *NearestVBase,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001944 CharUnits OffsetFromNearestVBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001945 bool BaseIsNonVirtualPrimaryBase,
1946 llvm::Constant *VTable,
1947 const CXXRecordDecl *VTableClass,
1948 VisitedVirtualBasesSetTy& VBases) {
1949 // If this base is a non-virtual primary base the address point has already
1950 // been set.
1951 if (!BaseIsNonVirtualPrimaryBase) {
1952 // Initialize the vtable pointer for this base.
Anders Carlsson42358402010-05-03 00:07:07 +00001953 InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
1954 VTable, VTableClass);
Anders Carlsson603d6d12010-03-28 21:07:49 +00001955 }
1956
1957 const CXXRecordDecl *RD = Base.getBase();
1958
1959 // Traverse bases.
1960 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1961 E = RD->bases_end(); I != E; ++I) {
1962 CXXRecordDecl *BaseDecl
1963 = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1964
1965 // Ignore classes without a vtable.
1966 if (!BaseDecl->isDynamicClass())
1967 continue;
1968
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001969 CharUnits BaseOffset;
1970 CharUnits BaseOffsetFromNearestVBase;
Anders Carlsson14da9de2010-03-29 01:16:41 +00001971 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001972
1973 if (I->isVirtual()) {
1974 // Check if we've visited this virtual base before.
1975 if (!VBases.insert(BaseDecl))
1976 continue;
1977
1978 const ASTRecordLayout &Layout =
1979 getContext().getASTRecordLayout(VTableClass);
1980
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001981 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
1982 BaseOffsetFromNearestVBase = CharUnits::Zero();
Anders Carlsson14da9de2010-03-29 01:16:41 +00001983 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001984 } else {
1985 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1986
Ken Dyck4230d522011-03-24 01:21:01 +00001987 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson42358402010-05-03 00:07:07 +00001988 BaseOffsetFromNearestVBase =
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001989 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson14da9de2010-03-29 01:16:41 +00001990 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001991 }
1992
Ken Dyck4230d522011-03-24 01:21:01 +00001993 InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001994 I->isVirtual() ? BaseDecl : NearestVBase,
Anders Carlsson42358402010-05-03 00:07:07 +00001995 BaseOffsetFromNearestVBase,
Anders Carlsson14da9de2010-03-29 01:16:41 +00001996 BaseDeclIsNonVirtualPrimaryBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001997 VTable, VTableClass, VBases);
1998 }
1999}
2000
2001void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
2002 // Ignore classes without a vtable.
Anders Carlsson07036902010-03-26 04:39:42 +00002003 if (!RD->isDynamicClass())
Anders Carlsson3b5ad222010-01-01 20:29:01 +00002004 return;
2005
Anders Carlsson07036902010-03-26 04:39:42 +00002006 // Get the VTable.
2007 llvm::Constant *VTable = CGM.getVTables().GetAddrOfVTable(RD);
Anders Carlsson5c6c1d92010-03-24 03:57:14 +00002008
Anders Carlsson603d6d12010-03-28 21:07:49 +00002009 // Initialize the vtable pointers for this class and all of its bases.
2010 VisitedVirtualBasesSetTy VBases;
Ken Dyck4230d522011-03-24 01:21:01 +00002011 InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()),
2012 /*NearestVBase=*/0,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00002013 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
Anders Carlsson603d6d12010-03-28 21:07:49 +00002014 /*BaseIsNonVirtualPrimaryBase=*/false,
2015 VTable, RD, VBases);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00002016}
Dan Gohman043fb9a2010-10-26 18:44:08 +00002017
2018llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
Chris Lattner2acc6e32011-07-18 04:24:23 +00002019 llvm::Type *Ty) {
Dan Gohman043fb9a2010-10-26 18:44:08 +00002020 llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
Kostya Serebryany8cb4a072012-03-26 17:03:51 +00002021 llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
2022 CGM.DecorateInstruction(VTable, CGM.getTBAAInfoForVTablePtr());
2023 return VTable;
Dan Gohman043fb9a2010-10-26 18:44:08 +00002024}
Anders Carlssona2447e02011-05-08 20:32:23 +00002025
2026static const CXXRecordDecl *getMostDerivedClassDecl(const Expr *Base) {
2027 const Expr *E = Base;
2028
2029 while (true) {
2030 E = E->IgnoreParens();
2031 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
2032 if (CE->getCastKind() == CK_DerivedToBase ||
2033 CE->getCastKind() == CK_UncheckedDerivedToBase ||
2034 CE->getCastKind() == CK_NoOp) {
2035 E = CE->getSubExpr();
2036 continue;
2037 }
2038 }
2039
2040 break;
2041 }
2042
2043 QualType DerivedType = E->getType();
2044 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
2045 DerivedType = PTy->getPointeeType();
2046
2047 return cast<CXXRecordDecl>(DerivedType->castAs<RecordType>()->getDecl());
2048}
2049
2050// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
2051// quite what we want.
2052static const Expr *skipNoOpCastsAndParens(const Expr *E) {
2053 while (true) {
2054 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
2055 E = PE->getSubExpr();
2056 continue;
2057 }
2058
2059 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
2060 if (CE->getCastKind() == CK_NoOp) {
2061 E = CE->getSubExpr();
2062 continue;
2063 }
2064 }
2065 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2066 if (UO->getOpcode() == UO_Extension) {
2067 E = UO->getSubExpr();
2068 continue;
2069 }
2070 }
2071 return E;
2072 }
2073}
2074
2075/// canDevirtualizeMemberFunctionCall - Checks whether the given virtual member
2076/// function call on the given expr can be devirtualized.
Anders Carlssona2447e02011-05-08 20:32:23 +00002077static bool canDevirtualizeMemberFunctionCall(const Expr *Base,
2078 const CXXMethodDecl *MD) {
2079 // If the most derived class is marked final, we know that no subclass can
2080 // override this member function and so we can devirtualize it. For example:
2081 //
2082 // struct A { virtual void f(); }
2083 // struct B final : A { };
2084 //
2085 // void f(B *b) {
2086 // b->f();
2087 // }
2088 //
2089 const CXXRecordDecl *MostDerivedClassDecl = getMostDerivedClassDecl(Base);
2090 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
2091 return true;
2092
2093 // If the member function is marked 'final', we know that it can't be
2094 // overridden and can therefore devirtualize it.
2095 if (MD->hasAttr<FinalAttr>())
2096 return true;
2097
2098 // Similarly, if the class itself is marked 'final' it can't be overridden
2099 // and we can therefore devirtualize the member function call.
2100 if (MD->getParent()->hasAttr<FinalAttr>())
2101 return true;
2102
2103 Base = skipNoOpCastsAndParens(Base);
2104 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
2105 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
2106 // This is a record decl. We know the type and can devirtualize it.
2107 return VD->getType()->isRecordType();
2108 }
2109
2110 return false;
2111 }
2112
2113 // We can always devirtualize calls on temporary object expressions.
2114 if (isa<CXXConstructExpr>(Base))
2115 return true;
2116
2117 // And calls on bound temporaries.
2118 if (isa<CXXBindTemporaryExpr>(Base))
2119 return true;
2120
2121 // Check if this is a call expr that returns a record type.
2122 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
2123 return CE->getCallReturnType()->isRecordType();
2124
2125 // We can't devirtualize the call.
2126 return false;
2127}
2128
2129static bool UseVirtualCall(ASTContext &Context,
2130 const CXXOperatorCallExpr *CE,
2131 const CXXMethodDecl *MD) {
2132 if (!MD->isVirtual())
2133 return false;
2134
2135 // When building with -fapple-kext, all calls must go through the vtable since
2136 // the kernel linker can do runtime patching of vtables.
David Blaikie4e4d0842012-03-11 07:00:24 +00002137 if (Context.getLangOpts().AppleKext)
Anders Carlssona2447e02011-05-08 20:32:23 +00002138 return true;
2139
2140 return !canDevirtualizeMemberFunctionCall(CE->getArg(0), MD);
2141}
2142
2143llvm::Value *
2144CodeGenFunction::EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E,
2145 const CXXMethodDecl *MD,
2146 llvm::Value *This) {
John McCallde5d3c72012-02-17 03:33:10 +00002147 llvm::FunctionType *fnType =
2148 CGM.getTypes().GetFunctionType(
2149 CGM.getTypes().arrangeCXXMethodDeclaration(MD));
Anders Carlssona2447e02011-05-08 20:32:23 +00002150
2151 if (UseVirtualCall(getContext(), E, MD))
John McCallde5d3c72012-02-17 03:33:10 +00002152 return BuildVirtualCall(MD, This, fnType);
Anders Carlssona2447e02011-05-08 20:32:23 +00002153
John McCallde5d3c72012-02-17 03:33:10 +00002154 return CGM.GetAddrOfFunction(MD, fnType);
Anders Carlssona2447e02011-05-08 20:32:23 +00002155}
Eli Friedmanbd89f8c2012-02-16 01:37:33 +00002156
John McCall0f3d0972012-07-07 06:41:13 +00002157void CodeGenFunction::EmitForwardingCallToLambda(const CXXRecordDecl *lambda,
2158 CallArgList &callArgs) {
Eli Friedman64bee652012-02-25 02:48:22 +00002159 // Lookup the call operator
John McCall0f3d0972012-07-07 06:41:13 +00002160 DeclarationName operatorName
Eli Friedman21f6ed92012-02-16 03:47:28 +00002161 = getContext().DeclarationNames.getCXXOperatorName(OO_Call);
John McCall0f3d0972012-07-07 06:41:13 +00002162 CXXMethodDecl *callOperator =
David Blaikie3bc93e32012-12-19 00:45:41 +00002163 cast<CXXMethodDecl>(lambda->lookup(operatorName).front());
Eli Friedman21f6ed92012-02-16 03:47:28 +00002164
Eli Friedman21f6ed92012-02-16 03:47:28 +00002165 // Get the address of the call operator.
John McCall0f3d0972012-07-07 06:41:13 +00002166 const CGFunctionInfo &calleeFnInfo =
2167 CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
2168 llvm::Value *callee =
2169 CGM.GetAddrOfFunction(GlobalDecl(callOperator),
2170 CGM.getTypes().GetFunctionType(calleeFnInfo));
Eli Friedman21f6ed92012-02-16 03:47:28 +00002171
John McCall0f3d0972012-07-07 06:41:13 +00002172 // Prepare the return slot.
2173 const FunctionProtoType *FPT =
2174 callOperator->getType()->castAs<FunctionProtoType>();
2175 QualType resultType = FPT->getResultType();
2176 ReturnValueSlot returnSlot;
2177 if (!resultType->isVoidType() &&
2178 calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
John McCall9d232c82013-03-07 21:37:08 +00002179 !hasScalarEvaluationKind(calleeFnInfo.getReturnType()))
John McCall0f3d0972012-07-07 06:41:13 +00002180 returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
2181
2182 // We don't need to separately arrange the call arguments because
2183 // the call can't be variadic anyway --- it's impossible to forward
2184 // variadic arguments.
Eli Friedman21f6ed92012-02-16 03:47:28 +00002185
2186 // Now emit our call.
John McCall0f3d0972012-07-07 06:41:13 +00002187 RValue RV = EmitCall(calleeFnInfo, callee, returnSlot,
2188 callArgs, callOperator);
Eli Friedman21f6ed92012-02-16 03:47:28 +00002189
John McCall0f3d0972012-07-07 06:41:13 +00002190 // If necessary, copy the returned value into the slot.
2191 if (!resultType->isVoidType() && returnSlot.isNull())
2192 EmitReturnOfRValue(RV, resultType);
Eli Friedman50f089a2012-12-13 23:37:17 +00002193 else
2194 EmitBranchThroughCleanup(ReturnBlock);
Eli Friedman21f6ed92012-02-16 03:47:28 +00002195}
2196
Eli Friedman64bee652012-02-25 02:48:22 +00002197void CodeGenFunction::EmitLambdaBlockInvokeBody() {
2198 const BlockDecl *BD = BlockInfo->getBlockDecl();
2199 const VarDecl *variable = BD->capture_begin()->getVariable();
2200 const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
2201
2202 // Start building arguments for forwarding call
2203 CallArgList CallArgs;
2204
2205 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2206 llvm::Value *ThisPtr = GetAddrOfBlockDecl(variable, false);
2207 CallArgs.add(RValue::get(ThisPtr), ThisType);
2208
2209 // Add the rest of the parameters.
2210 for (BlockDecl::param_const_iterator I = BD->param_begin(),
2211 E = BD->param_end(); I != E; ++I) {
2212 ParmVarDecl *param = *I;
2213 EmitDelegateCallArg(CallArgs, param);
2214 }
2215
2216 EmitForwardingCallToLambda(Lambda, CallArgs);
2217}
2218
2219void CodeGenFunction::EmitLambdaToBlockPointerBody(FunctionArgList &Args) {
John McCallf5ebf9b2013-05-03 07:33:41 +00002220 if (cast<CXXMethodDecl>(CurCodeDecl)->isVariadic()) {
Eli Friedman64bee652012-02-25 02:48:22 +00002221 // FIXME: Making this work correctly is nasty because it requires either
2222 // cloning the body of the call operator or making the call operator forward.
John McCallf5ebf9b2013-05-03 07:33:41 +00002223 CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function");
Eli Friedman64bee652012-02-25 02:48:22 +00002224 return;
2225 }
2226
Eli Friedman64bee652012-02-25 02:48:22 +00002227 EmitFunctionBody(Args);
Eli Friedman64bee652012-02-25 02:48:22 +00002228}
2229
2230void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
2231 const CXXRecordDecl *Lambda = MD->getParent();
2232
2233 // Start building arguments for forwarding call
2234 CallArgList CallArgs;
2235
2236 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2237 llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
2238 CallArgs.add(RValue::get(ThisPtr), ThisType);
2239
2240 // Add the rest of the parameters.
2241 for (FunctionDecl::param_const_iterator I = MD->param_begin(),
2242 E = MD->param_end(); I != E; ++I) {
2243 ParmVarDecl *param = *I;
2244 EmitDelegateCallArg(CallArgs, param);
2245 }
2246
2247 EmitForwardingCallToLambda(Lambda, CallArgs);
2248}
2249
Douglas Gregor27dd7d92012-02-17 03:02:34 +00002250void CodeGenFunction::EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD) {
2251 if (MD->isVariadic()) {
Eli Friedman21f6ed92012-02-16 03:47:28 +00002252 // FIXME: Making this work correctly is nasty because it requires either
2253 // cloning the body of the call operator or making the call operator forward.
2254 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
Eli Friedman64bee652012-02-25 02:48:22 +00002255 return;
Eli Friedman21f6ed92012-02-16 03:47:28 +00002256 }
2257
Douglas Gregor27dd7d92012-02-17 03:02:34 +00002258 EmitLambdaDelegatingInvokeBody(MD);
Eli Friedmanbd89f8c2012-02-16 01:37:33 +00002259}