blob: 88f5cf9e6b54dd725b74883212c49551d53e1b19 [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;
Eli Friedmanf3940782011-12-03 00:54:26 +0000436
Richard Smith7c3e6152013-06-12 22:31:48 +0000437 if (ArrayIndexVar) {
438 // If we have an array index variable, load it and use it as an offset.
439 // Then, increment the value.
440 llvm::Value *Dest = LHS.getAddress();
441 llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar);
442 Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress");
443 llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1);
444 Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc");
445 CGF.Builder.CreateStore(Next, ArrayIndexVar);
Sebastian Redl924db712012-02-19 15:41:54 +0000446
Richard Smith7c3e6152013-06-12 22:31:48 +0000447 // Update the LValue.
448 LV.setAddress(Dest);
449 CharUnits Align = CGF.getContext().getTypeAlignInChars(T);
450 LV.setAlignment(std::min(Align, LV.getAlignment()));
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000451 }
John McCall558d2ab2010-09-15 10:14:12 +0000452
Richard Smith7c3e6152013-06-12 22:31:48 +0000453 switch (CGF.getEvaluationKind(T)) {
454 case TEK_Scalar:
455 CGF.EmitScalarInit(Init, /*decl*/ 0, LV, false);
456 break;
457 case TEK_Complex:
458 CGF.EmitComplexExprIntoLValue(Init, LV, /*isInit*/ true);
459 break;
460 case TEK_Aggregate: {
461 AggValueSlot Slot =
462 AggValueSlot::forLValue(LV,
463 AggValueSlot::IsDestructed,
464 AggValueSlot::DoesNotNeedGCBarriers,
465 AggValueSlot::IsNotAliased);
466
467 CGF.EmitAggExpr(Init, Slot);
468 break;
469 }
470 }
Sebastian Redl924db712012-02-19 15:41:54 +0000471
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000472 return;
473 }
Richard Smith7c3e6152013-06-12 22:31:48 +0000474
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000475 const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T);
476 assert(Array && "Array initialization without the array type?");
477 llvm::Value *IndexVar
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000478 = CGF.GetAddrOfLocalVar(ArrayIndexes[Index]);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000479 assert(IndexVar && "Array index variable not loaded");
480
481 // Initialize this index variable to zero.
482 llvm::Value* Zero
483 = llvm::Constant::getNullValue(
484 CGF.ConvertType(CGF.getContext().getSizeType()));
485 CGF.Builder.CreateStore(Zero, IndexVar);
486
487 // Start the loop with a block that tests the condition.
488 llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond");
489 llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end");
490
491 CGF.EmitBlock(CondBlock);
492
493 llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body");
494 // Generate: if (loop-index < number-of-elements) fall to the loop body,
495 // otherwise, go to the block after the for-loop.
496 uint64_t NumElements = Array->getSize().getZExtValue();
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000497 llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
Chris Lattner985f7392010-05-06 06:35:23 +0000498 llvm::Value *NumElementsPtr =
499 llvm::ConstantInt::get(Counter->getType(), NumElements);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000500 llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr,
501 "isless");
502
503 // If the condition is true, execute the body.
504 CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor);
505
506 CGF.EmitBlock(ForBody);
507 llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc");
Richard Smith7c3e6152013-06-12 22:31:48 +0000508
509 // Inside the loop body recurse to emit the inner loop or, eventually, the
510 // constructor call.
511 EmitAggMemberInitializer(CGF, LHS, Init, ArrayIndexVar,
512 Array->getElementType(), ArrayIndexes, Index + 1);
513
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000514 CGF.EmitBlock(ContinueBlock);
515
516 // Emit the increment of the loop counter.
517 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
518 Counter = CGF.Builder.CreateLoad(IndexVar);
519 NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc");
520 CGF.Builder.CreateStore(NextVal, IndexVar);
521
522 // Finally, branch back up to the condition for the next iteration.
523 CGF.EmitBranch(CondBlock);
524
525 // Emit the fall-through block.
526 CGF.EmitBlock(AfterFor, true);
527}
John McCall182ab512010-07-21 01:23:41 +0000528
Anders Carlsson607d0372009-12-24 22:46:43 +0000529static void EmitMemberInitializer(CodeGenFunction &CGF,
530 const CXXRecordDecl *ClassDecl,
Sean Huntcbb67482011-01-08 20:30:50 +0000531 CXXCtorInitializer *MemberInit,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000532 const CXXConstructorDecl *Constructor,
533 FunctionArgList &Args) {
Francois Pichet00eb3f92010-12-04 09:14:42 +0000534 assert(MemberInit->isAnyMemberInitializer() &&
Anders Carlsson607d0372009-12-24 22:46:43 +0000535 "Must have member initializer!");
Richard Smith7a614d82011-06-11 17:19:42 +0000536 assert(MemberInit->getInit() && "Must have initializer!");
Anders Carlsson607d0372009-12-24 22:46:43 +0000537
538 // non-static data member initializers.
Francois Pichet00eb3f92010-12-04 09:14:42 +0000539 FieldDecl *Field = MemberInit->getAnyMember();
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000540 QualType FieldType = Field->getType();
Anders Carlsson607d0372009-12-24 22:46:43 +0000541
542 llvm::Value *ThisPtr = CGF.LoadCXXThis();
Eli Friedman377ecc72012-04-16 03:54:45 +0000543 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
Eli Friedman859c65c2012-08-08 03:51:37 +0000544 LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
Eli Friedman377ecc72012-04-16 03:54:45 +0000545
Francois Pichet00eb3f92010-12-04 09:14:42 +0000546 if (MemberInit->isIndirectMemberInitializer()) {
Eli Friedman859c65c2012-08-08 03:51:37 +0000547 // If we are initializing an anonymous union field, drill down to
548 // the field.
549 IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember();
550 IndirectFieldDecl::chain_iterator I = IndirectField->chain_begin(),
551 IEnd = IndirectField->chain_end();
552 for ( ; I != IEnd; ++I)
553 LHS = CGF.EmitLValueForFieldInitialization(LHS, cast<FieldDecl>(*I));
Francois Pichet00eb3f92010-12-04 09:14:42 +0000554 FieldType = MemberInit->getIndirectMember()->getAnonField()->getType();
John McCalla9976d32010-05-21 01:18:57 +0000555 } else {
Eli Friedman859c65c2012-08-08 03:51:37 +0000556 LHS = CGF.EmitLValueForFieldInitialization(LHS, Field);
Anders Carlsson607d0372009-12-24 22:46:43 +0000557 }
558
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000559 // Special case: if we are in a copy or move constructor, and we are copying
560 // an array of PODs or classes with trivial copy constructors, ignore the
561 // AST and perform the copy we know is equivalent.
562 // FIXME: This is hacky at best... if we had a bit more explicit information
563 // in the AST, we could generalize it more easily.
564 const ConstantArrayType *Array
565 = CGF.getContext().getAsConstantArrayType(FieldType);
566 if (Array && Constructor->isImplicitlyDefined() &&
567 Constructor->isCopyOrMoveConstructor()) {
568 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
Richard Smithe9385362012-11-07 23:56:21 +0000569 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000570 if (BaseElementTy.isPODType(CGF.getContext()) ||
Richard Smithe9385362012-11-07 23:56:21 +0000571 (CE && CE->getConstructor()->isTrivial())) {
572 // Find the source pointer. We know it's the last argument because
573 // we know we're in an implicit copy constructor.
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000574 unsigned SrcArgIndex = Args.size() - 1;
575 llvm::Value *SrcPtr
576 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
Eli Friedman377ecc72012-04-16 03:54:45 +0000577 LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
578 LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field);
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000579
580 // Copy the aggregate.
581 CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
Chad Rosier649b4a12012-03-29 17:37:10 +0000582 LHS.isVolatileQualified());
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000583 return;
584 }
585 }
586
587 ArrayRef<VarDecl *> ArrayIndexes;
588 if (MemberInit->getNumArrayIndices())
589 ArrayIndexes = MemberInit->getArrayIndexes();
Eli Friedmanb74ed082012-02-14 02:31:03 +0000590 CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit(), ArrayIndexes);
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000591}
592
Eli Friedmanb74ed082012-02-14 02:31:03 +0000593void CodeGenFunction::EmitInitializerForField(FieldDecl *Field,
594 LValue LHS, Expr *Init,
595 ArrayRef<VarDecl *> ArrayIndexes) {
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000596 QualType FieldType = Field->getType();
John McCall9d232c82013-03-07 21:37:08 +0000597 switch (getEvaluationKind(FieldType)) {
598 case TEK_Scalar:
John McCallf85e1932011-06-15 23:02:42 +0000599 if (LHS.isSimple()) {
Eli Friedmanb74ed082012-02-14 02:31:03 +0000600 EmitExprAsInit(Init, Field, LHS, false);
John McCallf85e1932011-06-15 23:02:42 +0000601 } else {
Eli Friedmanb74ed082012-02-14 02:31:03 +0000602 RValue RHS = RValue::get(EmitScalarExpr(Init));
603 EmitStoreThroughLValue(RHS, LHS);
John McCallf85e1932011-06-15 23:02:42 +0000604 }
John McCall9d232c82013-03-07 21:37:08 +0000605 break;
606 case TEK_Complex:
607 EmitComplexExprIntoLValue(Init, LHS, /*isInit*/ true);
608 break;
609 case TEK_Aggregate: {
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000610 llvm::Value *ArrayIndexVar = 0;
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000611 if (ArrayIndexes.size()) {
Eli Friedmanb74ed082012-02-14 02:31:03 +0000612 llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000613
614 // The LHS is a pointer to the first object we'll be constructing, as
615 // a flat array.
Eli Friedmanb74ed082012-02-14 02:31:03 +0000616 QualType BaseElementTy = getContext().getBaseElementType(FieldType);
617 llvm::Type *BasePtr = ConvertType(BaseElementTy);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000618 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Eli Friedmanb74ed082012-02-14 02:31:03 +0000619 llvm::Value *BaseAddrPtr = Builder.CreateBitCast(LHS.getAddress(),
620 BasePtr);
621 LHS = MakeAddrLValue(BaseAddrPtr, BaseElementTy);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000622
623 // Create an array index that will be used to walk over all of the
624 // objects we're constructing.
Eli Friedmanb74ed082012-02-14 02:31:03 +0000625 ArrayIndexVar = CreateTempAlloca(SizeTy, "object.index");
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000626 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
Eli Friedmanb74ed082012-02-14 02:31:03 +0000627 Builder.CreateStore(Zero, ArrayIndexVar);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000628
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000629
630 // Emit the block variables for the array indices, if any.
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000631 for (unsigned I = 0, N = ArrayIndexes.size(); I != N; ++I)
Eli Friedmanb74ed082012-02-14 02:31:03 +0000632 EmitAutoVarDecl(*ArrayIndexes[I]);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000633 }
634
Eli Friedmanb74ed082012-02-14 02:31:03 +0000635 EmitAggMemberInitializer(*this, LHS, Init, ArrayIndexVar, FieldType,
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000636 ArrayIndexes, 0);
Anders Carlsson607d0372009-12-24 22:46:43 +0000637 }
John McCall9d232c82013-03-07 21:37:08 +0000638 }
John McCall074cae02013-02-01 05:11:40 +0000639
640 // Ensure that we destroy this object if an exception is thrown
641 // later in the constructor.
642 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
643 if (needsEHCleanup(dtorKind))
644 pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
Anders Carlsson607d0372009-12-24 22:46:43 +0000645}
646
John McCallc0bf4622010-02-23 00:48:20 +0000647/// Checks whether the given constructor is a valid subject for the
648/// complete-to-base constructor delegation optimization, i.e.
649/// emitting the complete constructor as a simple call to the base
650/// constructor.
651static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
652
653 // Currently we disable the optimization for classes with virtual
654 // bases because (1) the addresses of parameter variables need to be
655 // consistent across all initializers but (2) the delegate function
656 // call necessarily creates a second copy of the parameter variable.
657 //
658 // The limiting example (purely theoretical AFAIK):
659 // struct A { A(int &c) { c++; } };
660 // struct B : virtual A {
661 // B(int count) : A(count) { printf("%d\n", count); }
662 // };
663 // ...although even this example could in principle be emitted as a
664 // delegation since the address of the parameter doesn't escape.
665 if (Ctor->getParent()->getNumVBases()) {
666 // TODO: white-list trivial vbase initializers. This case wouldn't
667 // be subject to the restrictions below.
668
669 // TODO: white-list cases where:
670 // - there are no non-reference parameters to the constructor
671 // - the initializers don't access any non-reference parameters
672 // - the initializers don't take the address of non-reference
673 // parameters
674 // - etc.
675 // If we ever add any of the above cases, remember that:
676 // - function-try-blocks will always blacklist this optimization
677 // - we need to perform the constructor prologue and cleanup in
678 // EmitConstructorBody.
679
680 return false;
681 }
682
683 // We also disable the optimization for variadic functions because
684 // it's impossible to "re-pass" varargs.
685 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
686 return false;
687
Sean Hunt059ce0d2011-05-01 07:04:31 +0000688 // FIXME: Decide if we can do a delegation of a delegating constructor.
689 if (Ctor->isDelegatingConstructor())
690 return false;
691
John McCallc0bf4622010-02-23 00:48:20 +0000692 return true;
693}
694
John McCall9fc6a772010-02-19 09:25:03 +0000695/// EmitConstructorBody - Emits the body of the current constructor.
696void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
697 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
698 CXXCtorType CtorType = CurGD.getCtorType();
699
John McCallc0bf4622010-02-23 00:48:20 +0000700 // Before we go any further, try the complete->base constructor
701 // delegation optimization.
Timur Iskhodzhanov85607912012-04-20 08:05:00 +0000702 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
John McCall64aa4b32013-04-16 22:48:15 +0000703 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
Devang Pateld67ef0e2010-08-11 21:04:37 +0000704 if (CGDebugInfo *DI = getDebugInfo())
Eric Christopher73fb3502011-10-13 21:45:18 +0000705 DI->EmitLocation(Builder, Ctor->getLocEnd());
John McCallc0bf4622010-02-23 00:48:20 +0000706 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args);
707 return;
708 }
709
John McCall9fc6a772010-02-19 09:25:03 +0000710 Stmt *Body = Ctor->getBody();
711
John McCallc0bf4622010-02-23 00:48:20 +0000712 // Enter the function-try-block before the constructor prologue if
713 // applicable.
John McCallc0bf4622010-02-23 00:48:20 +0000714 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallc0bf4622010-02-23 00:48:20 +0000715 if (IsTryBody)
John McCall59a70002010-07-07 06:56:46 +0000716 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000717
Richard Smith7c3e6152013-06-12 22:31:48 +0000718 RunCleanupsScope RunCleanups(*this);
John McCall9fc6a772010-02-19 09:25:03 +0000719
John McCall56ea3772012-03-30 04:25:03 +0000720 // TODO: in restricted cases, we can emit the vbase initializers of
721 // a complete ctor and then delegate to the base ctor.
722
John McCallc0bf4622010-02-23 00:48:20 +0000723 // Emit the constructor prologue, i.e. the base and member
724 // initializers.
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000725 EmitCtorPrologue(Ctor, CtorType, Args);
John McCall9fc6a772010-02-19 09:25:03 +0000726
727 // Emit the body of the statement.
John McCallc0bf4622010-02-23 00:48:20 +0000728 if (IsTryBody)
John McCall9fc6a772010-02-19 09:25:03 +0000729 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
730 else if (Body)
731 EmitStmt(Body);
John McCall9fc6a772010-02-19 09:25:03 +0000732
733 // Emit any cleanup blocks associated with the member or base
734 // initializers, which includes (along the exceptional path) the
735 // destructors for those members and bases that were fully
736 // constructed.
Richard Smith7c3e6152013-06-12 22:31:48 +0000737 RunCleanups.ForceCleanup();
John McCall9fc6a772010-02-19 09:25:03 +0000738
John McCallc0bf4622010-02-23 00:48:20 +0000739 if (IsTryBody)
John McCall59a70002010-07-07 06:56:46 +0000740 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000741}
742
Lang Hames56c00c42013-02-17 07:22:09 +0000743namespace {
744 class FieldMemcpyizer {
745 public:
746 FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl,
747 const VarDecl *SrcRec)
748 : CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec),
749 RecLayout(CGF.getContext().getASTRecordLayout(ClassDecl)),
750 FirstField(0), LastField(0), FirstFieldOffset(0), LastFieldOffset(0),
751 LastAddedFieldIndex(0) { }
752
753 static bool isMemcpyableField(FieldDecl *F) {
754 Qualifiers Qual = F->getType().getQualifiers();
755 if (Qual.hasVolatile() || Qual.hasObjCLifetime())
756 return false;
757 return true;
758 }
759
760 void addMemcpyableField(FieldDecl *F) {
761 if (FirstField == 0)
762 addInitialField(F);
763 else
764 addNextField(F);
765 }
766
767 CharUnits getMemcpySize() const {
768 unsigned LastFieldSize =
769 LastField->isBitField() ?
770 LastField->getBitWidthValue(CGF.getContext()) :
771 CGF.getContext().getTypeSize(LastField->getType());
772 uint64_t MemcpySizeBits =
773 LastFieldOffset + LastFieldSize - FirstFieldOffset +
774 CGF.getContext().getCharWidth() - 1;
775 CharUnits MemcpySize =
776 CGF.getContext().toCharUnitsFromBits(MemcpySizeBits);
777 return MemcpySize;
778 }
779
780 void emitMemcpy() {
781 // Give the subclass a chance to bail out if it feels the memcpy isn't
782 // worth it (e.g. Hasn't aggregated enough data).
783 if (FirstField == 0) {
784 return;
785 }
786
Lang Hames5e8577e2013-02-27 04:14:49 +0000787 CharUnits Alignment;
Lang Hames56c00c42013-02-17 07:22:09 +0000788
789 if (FirstField->isBitField()) {
790 const CGRecordLayout &RL =
791 CGF.getTypes().getCGRecordLayout(FirstField->getParent());
792 const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField);
Lang Hames5e8577e2013-02-27 04:14:49 +0000793 Alignment = CharUnits::fromQuantity(BFInfo.StorageAlignment);
794 } else {
Lang Hames23742cd2013-03-05 20:27:24 +0000795 Alignment = CGF.getContext().getDeclAlign(FirstField);
Lang Hames5e8577e2013-02-27 04:14:49 +0000796 }
Lang Hames56c00c42013-02-17 07:22:09 +0000797
Lang Hames5e8577e2013-02-27 04:14:49 +0000798 assert((CGF.getContext().toCharUnitsFromBits(FirstFieldOffset) %
799 Alignment) == 0 && "Bad field alignment.");
800
Lang Hames56c00c42013-02-17 07:22:09 +0000801 CharUnits MemcpySize = getMemcpySize();
802 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
803 llvm::Value *ThisPtr = CGF.LoadCXXThis();
804 LValue DestLV = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
805 LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField);
806 llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec));
807 LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
808 LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField);
809
810 emitMemcpyIR(Dest.isBitField() ? Dest.getBitFieldAddr() : Dest.getAddress(),
811 Src.isBitField() ? Src.getBitFieldAddr() : Src.getAddress(),
812 MemcpySize, Alignment);
813 reset();
814 }
815
816 void reset() {
817 FirstField = 0;
818 }
819
820 protected:
821 CodeGenFunction &CGF;
822 const CXXRecordDecl *ClassDecl;
823
824 private:
825
826 void emitMemcpyIR(llvm::Value *DestPtr, llvm::Value *SrcPtr,
827 CharUnits Size, CharUnits Alignment) {
828 llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
829 llvm::Type *DBP =
830 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), DPT->getAddressSpace());
831 DestPtr = CGF.Builder.CreateBitCast(DestPtr, DBP);
832
833 llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
834 llvm::Type *SBP =
835 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), SPT->getAddressSpace());
836 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, SBP);
837
838 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity(),
839 Alignment.getQuantity());
840 }
841
842 void addInitialField(FieldDecl *F) {
843 FirstField = F;
844 LastField = F;
845 FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex());
846 LastFieldOffset = FirstFieldOffset;
847 LastAddedFieldIndex = F->getFieldIndex();
848 return;
849 }
850
851 void addNextField(FieldDecl *F) {
John McCall402cd222013-05-07 05:20:46 +0000852 // For the most part, the following invariant will hold:
853 // F->getFieldIndex() == LastAddedFieldIndex + 1
854 // The one exception is that Sema won't add a copy-initializer for an
855 // unnamed bitfield, which will show up here as a gap in the sequence.
856 assert(F->getFieldIndex() >= LastAddedFieldIndex + 1 &&
857 "Cannot aggregate fields out of order.");
Lang Hames56c00c42013-02-17 07:22:09 +0000858 LastAddedFieldIndex = F->getFieldIndex();
859
860 // The 'first' and 'last' fields are chosen by offset, rather than field
861 // index. This allows the code to support bitfields, as well as regular
862 // fields.
863 uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex());
864 if (FOffset < FirstFieldOffset) {
865 FirstField = F;
866 FirstFieldOffset = FOffset;
867 } else if (FOffset > LastFieldOffset) {
868 LastField = F;
869 LastFieldOffset = FOffset;
870 }
871 }
872
873 const VarDecl *SrcRec;
874 const ASTRecordLayout &RecLayout;
875 FieldDecl *FirstField;
876 FieldDecl *LastField;
877 uint64_t FirstFieldOffset, LastFieldOffset;
878 unsigned LastAddedFieldIndex;
879 };
880
881 class ConstructorMemcpyizer : public FieldMemcpyizer {
882 private:
883
884 /// Get source argument for copy constructor. Returns null if not a copy
885 /// constructor.
886 static const VarDecl* getTrivialCopySource(const CXXConstructorDecl *CD,
887 FunctionArgList &Args) {
888 if (CD->isCopyOrMoveConstructor() && CD->isImplicitlyDefined())
889 return Args[Args.size() - 1];
890 return 0;
891 }
892
893 // Returns true if a CXXCtorInitializer represents a member initialization
894 // that can be rolled into a memcpy.
895 bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const {
896 if (!MemcpyableCtor)
897 return false;
898 FieldDecl *Field = MemberInit->getMember();
899 assert(Field != 0 && "No field for member init.");
900 QualType FieldType = Field->getType();
901 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
902
903 // Bail out on non-POD, not-trivially-constructable members.
904 if (!(CE && CE->getConstructor()->isTrivial()) &&
905 !(FieldType.isTriviallyCopyableType(CGF.getContext()) ||
906 FieldType->isReferenceType()))
907 return false;
908
909 // Bail out on volatile fields.
910 if (!isMemcpyableField(Field))
911 return false;
912
913 // Otherwise we're good.
914 return true;
915 }
916
917 public:
918 ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD,
919 FunctionArgList &Args)
920 : FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CD, Args)),
921 ConstructorDecl(CD),
922 MemcpyableCtor(CD->isImplicitlyDefined() &&
923 CD->isCopyOrMoveConstructor() &&
924 CGF.getLangOpts().getGC() == LangOptions::NonGC),
925 Args(Args) { }
926
927 void addMemberInitializer(CXXCtorInitializer *MemberInit) {
928 if (isMemberInitMemcpyable(MemberInit)) {
929 AggregatedInits.push_back(MemberInit);
930 addMemcpyableField(MemberInit->getMember());
931 } else {
932 emitAggregatedInits();
933 EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit,
934 ConstructorDecl, Args);
935 }
936 }
937
938 void emitAggregatedInits() {
939 if (AggregatedInits.size() <= 1) {
940 // This memcpy is too small to be worthwhile. Fall back on default
941 // codegen.
942 for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
943 EmitMemberInitializer(CGF, ConstructorDecl->getParent(),
944 AggregatedInits[i], ConstructorDecl, Args);
945 }
946 reset();
947 return;
948 }
949
950 pushEHDestructors();
951 emitMemcpy();
952 AggregatedInits.clear();
953 }
954
955 void pushEHDestructors() {
956 llvm::Value *ThisPtr = CGF.LoadCXXThis();
957 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
958 LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
959
960 for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
961 QualType FieldType = AggregatedInits[i]->getMember()->getType();
962 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
963 if (CGF.needsEHCleanup(dtorKind))
964 CGF.pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
965 }
966 }
967
968 void finish() {
969 emitAggregatedInits();
970 }
971
972 private:
973 const CXXConstructorDecl *ConstructorDecl;
974 bool MemcpyableCtor;
975 FunctionArgList &Args;
976 SmallVector<CXXCtorInitializer*, 16> AggregatedInits;
977 };
978
979 class AssignmentMemcpyizer : public FieldMemcpyizer {
980 private:
981
982 // Returns the memcpyable field copied by the given statement, if one
983 // exists. Otherwise r
984 FieldDecl* getMemcpyableField(Stmt *S) {
985 if (!AssignmentsMemcpyable)
986 return 0;
987 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
988 // Recognise trivial assignments.
989 if (BO->getOpcode() != BO_Assign)
990 return 0;
991 MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS());
992 if (!ME)
993 return 0;
994 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
995 if (!Field || !isMemcpyableField(Field))
996 return 0;
997 Stmt *RHS = BO->getRHS();
998 if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS))
999 RHS = EC->getSubExpr();
1000 if (!RHS)
1001 return 0;
1002 MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS);
1003 if (dyn_cast<FieldDecl>(ME2->getMemberDecl()) != Field)
1004 return 0;
1005 return Field;
1006 } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) {
1007 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl());
1008 if (!(MD && (MD->isCopyAssignmentOperator() ||
1009 MD->isMoveAssignmentOperator()) &&
1010 MD->isTrivial()))
1011 return 0;
1012 MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument());
1013 if (!IOA)
1014 return 0;
1015 FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl());
1016 if (!Field || !isMemcpyableField(Field))
1017 return 0;
1018 MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0));
1019 if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl()))
1020 return 0;
1021 return Field;
1022 } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1023 FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1024 if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy)
1025 return 0;
1026 Expr *DstPtr = CE->getArg(0);
1027 if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr))
1028 DstPtr = DC->getSubExpr();
1029 UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr);
1030 if (!DUO || DUO->getOpcode() != UO_AddrOf)
1031 return 0;
1032 MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr());
1033 if (!ME)
1034 return 0;
1035 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1036 if (!Field || !isMemcpyableField(Field))
1037 return 0;
1038 Expr *SrcPtr = CE->getArg(1);
1039 if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr))
1040 SrcPtr = SC->getSubExpr();
1041 UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr);
1042 if (!SUO || SUO->getOpcode() != UO_AddrOf)
1043 return 0;
1044 MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr());
1045 if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl()))
1046 return 0;
1047 return Field;
1048 }
1049
1050 return 0;
1051 }
1052
1053 bool AssignmentsMemcpyable;
1054 SmallVector<Stmt*, 16> AggregatedStmts;
1055
1056 public:
1057
1058 AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD,
1059 FunctionArgList &Args)
1060 : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]),
1061 AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) {
1062 assert(Args.size() == 2);
1063 }
1064
1065 void emitAssignment(Stmt *S) {
1066 FieldDecl *F = getMemcpyableField(S);
1067 if (F) {
1068 addMemcpyableField(F);
1069 AggregatedStmts.push_back(S);
1070 } else {
1071 emitAggregatedStmts();
1072 CGF.EmitStmt(S);
1073 }
1074 }
1075
1076 void emitAggregatedStmts() {
1077 if (AggregatedStmts.size() <= 1) {
1078 for (unsigned i = 0; i < AggregatedStmts.size(); ++i)
1079 CGF.EmitStmt(AggregatedStmts[i]);
1080 reset();
1081 }
1082
1083 emitMemcpy();
1084 AggregatedStmts.clear();
1085 }
1086
1087 void finish() {
1088 emitAggregatedStmts();
1089 }
1090 };
1091
1092}
1093
Anders Carlsson607d0372009-12-24 22:46:43 +00001094/// EmitCtorPrologue - This routine generates necessary code to initialize
1095/// base classes and non-static data members belonging to this constructor.
Anders Carlsson607d0372009-12-24 22:46:43 +00001096void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001097 CXXCtorType CtorType,
1098 FunctionArgList &Args) {
Sean Hunt059ce0d2011-05-01 07:04:31 +00001099 if (CD->isDelegatingConstructor())
1100 return EmitDelegatingCXXConstructorCall(CD, Args);
1101
Anders Carlsson607d0372009-12-24 22:46:43 +00001102 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlssona78fa2c2010-02-02 19:58:43 +00001103
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001104 CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
1105 E = CD->init_end();
1106
1107 llvm::BasicBlock *BaseCtorContinueBB = 0;
1108 if (ClassDecl->getNumVBases() &&
1109 !CGM.getTarget().getCXXABI().hasConstructorVariants()) {
1110 // The ABIs that don't have constructor variants need to put a branch
1111 // before the virtual base initialization code.
1112 BaseCtorContinueBB = CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this);
1113 assert(BaseCtorContinueBB);
1114 }
1115
1116 // Virtual base initializers first.
1117 for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
1118 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
1119 }
1120
1121 if (BaseCtorContinueBB) {
1122 // Complete object handler should continue to the remaining initializers.
1123 Builder.CreateBr(BaseCtorContinueBB);
1124 EmitBlock(BaseCtorContinueBB);
1125 }
1126
1127 // Then, non-virtual base initializers.
1128 for (; B != E && (*B)->isBaseInitializer(); B++) {
1129 assert(!(*B)->isBaseVirtual());
1130 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
Anders Carlsson607d0372009-12-24 22:46:43 +00001131 }
1132
Anders Carlsson603d6d12010-03-28 21:07:49 +00001133 InitializeVTablePointers(ClassDecl);
Anders Carlssona78fa2c2010-02-02 19:58:43 +00001134
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001135 // And finally, initialize class members.
Richard Smithc3bf52c2013-04-20 22:23:05 +00001136 FieldConstructionScope FCS(*this, CXXThisValue);
Lang Hames56c00c42013-02-17 07:22:09 +00001137 ConstructorMemcpyizer CM(*this, CD, Args);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001138 for (; B != E; B++) {
1139 CXXCtorInitializer *Member = (*B);
1140 assert(!Member->isBaseInitializer());
1141 assert(Member->isAnyMemberInitializer() &&
1142 "Delegating initializer on non-delegating constructor");
1143 CM.addMemberInitializer(Member);
1144 }
Lang Hames56c00c42013-02-17 07:22:09 +00001145 CM.finish();
Anders Carlsson607d0372009-12-24 22:46:43 +00001146}
1147
Anders Carlssonadf5dc32011-05-15 17:36:21 +00001148static bool
1149FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
1150
1151static bool
1152HasTrivialDestructorBody(ASTContext &Context,
1153 const CXXRecordDecl *BaseClassDecl,
1154 const CXXRecordDecl *MostDerivedClassDecl)
1155{
1156 // If the destructor is trivial we don't have to check anything else.
1157 if (BaseClassDecl->hasTrivialDestructor())
1158 return true;
1159
1160 if (!BaseClassDecl->getDestructor()->hasTrivialBody())
1161 return false;
1162
1163 // Check fields.
1164 for (CXXRecordDecl::field_iterator I = BaseClassDecl->field_begin(),
1165 E = BaseClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001166 const FieldDecl *Field = *I;
Anders Carlssonadf5dc32011-05-15 17:36:21 +00001167
1168 if (!FieldHasTrivialDestructorBody(Context, Field))
1169 return false;
1170 }
1171
1172 // Check non-virtual bases.
1173 for (CXXRecordDecl::base_class_const_iterator I =
1174 BaseClassDecl->bases_begin(), E = BaseClassDecl->bases_end();
1175 I != E; ++I) {
1176 if (I->isVirtual())
1177 continue;
1178
1179 const CXXRecordDecl *NonVirtualBase =
1180 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
1181 if (!HasTrivialDestructorBody(Context, NonVirtualBase,
1182 MostDerivedClassDecl))
1183 return false;
1184 }
1185
1186 if (BaseClassDecl == MostDerivedClassDecl) {
1187 // Check virtual bases.
1188 for (CXXRecordDecl::base_class_const_iterator I =
1189 BaseClassDecl->vbases_begin(), E = BaseClassDecl->vbases_end();
1190 I != E; ++I) {
1191 const CXXRecordDecl *VirtualBase =
1192 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
1193 if (!HasTrivialDestructorBody(Context, VirtualBase,
1194 MostDerivedClassDecl))
1195 return false;
1196 }
1197 }
1198
1199 return true;
1200}
1201
1202static bool
1203FieldHasTrivialDestructorBody(ASTContext &Context,
1204 const FieldDecl *Field)
1205{
1206 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
1207
1208 const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
1209 if (!RT)
1210 return true;
1211
1212 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1213 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
1214}
1215
Anders Carlssonffb945f2011-05-14 23:26:09 +00001216/// CanSkipVTablePointerInitialization - Check whether we need to initialize
1217/// any vtable pointers before calling this destructor.
1218static bool CanSkipVTablePointerInitialization(ASTContext &Context,
Anders Carlssone3d6cf22011-05-16 04:08:36 +00001219 const CXXDestructorDecl *Dtor) {
Anders Carlssonffb945f2011-05-14 23:26:09 +00001220 if (!Dtor->hasTrivialBody())
1221 return false;
1222
1223 // Check the fields.
1224 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1225 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1226 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001227 const FieldDecl *Field = *I;
Anders Carlssonffb945f2011-05-14 23:26:09 +00001228
Anders Carlssonadf5dc32011-05-15 17:36:21 +00001229 if (!FieldHasTrivialDestructorBody(Context, Field))
1230 return false;
Anders Carlssonffb945f2011-05-14 23:26:09 +00001231 }
1232
1233 return true;
1234}
1235
John McCall9fc6a772010-02-19 09:25:03 +00001236/// EmitDestructorBody - Emits the body of the current destructor.
1237void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
1238 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
1239 CXXDtorType DtorType = CurGD.getDtorType();
1240
John McCall50da2ca2010-07-21 05:30:47 +00001241 // The call to operator delete in a deleting destructor happens
1242 // outside of the function-try-block, which means it's always
1243 // possible to delegate the destructor body to the complete
1244 // destructor. Do so.
1245 if (DtorType == Dtor_Deleting) {
1246 EnterDtorCleanups(Dtor, Dtor_Deleting);
1247 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001248 /*Delegating=*/false, LoadCXXThis());
John McCall50da2ca2010-07-21 05:30:47 +00001249 PopCleanupBlock();
1250 return;
1251 }
1252
John McCall9fc6a772010-02-19 09:25:03 +00001253 Stmt *Body = Dtor->getBody();
1254
1255 // If the body is a function-try-block, enter the try before
John McCall50da2ca2010-07-21 05:30:47 +00001256 // anything else.
1257 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCall9fc6a772010-02-19 09:25:03 +00001258 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +00001259 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +00001260
John McCall50da2ca2010-07-21 05:30:47 +00001261 // Enter the epilogue cleanups.
1262 RunCleanupsScope DtorEpilogue(*this);
1263
John McCall9fc6a772010-02-19 09:25:03 +00001264 // If this is the complete variant, just invoke the base variant;
1265 // the epilogue will destruct the virtual bases. But we can't do
1266 // this optimization if the body is a function-try-block, because
1267 // we'd introduce *two* handler blocks.
John McCall50da2ca2010-07-21 05:30:47 +00001268 switch (DtorType) {
1269 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
1270
1271 case Dtor_Complete:
1272 // Enter the cleanup scopes for virtual bases.
1273 EnterDtorCleanups(Dtor, Dtor_Complete);
1274
John McCallb8b2c9d2013-01-25 22:30:49 +00001275 if (!isTryBody &&
John McCall64aa4b32013-04-16 22:48:15 +00001276 CGM.getTarget().getCXXABI().hasDestructorVariants()) {
John McCall50da2ca2010-07-21 05:30:47 +00001277 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001278 /*Delegating=*/false, LoadCXXThis());
John McCall50da2ca2010-07-21 05:30:47 +00001279 break;
1280 }
1281 // Fallthrough: act like we're in the base variant.
John McCall9fc6a772010-02-19 09:25:03 +00001282
John McCall50da2ca2010-07-21 05:30:47 +00001283 case Dtor_Base:
1284 // Enter the cleanup scopes for fields and non-virtual bases.
1285 EnterDtorCleanups(Dtor, Dtor_Base);
1286
1287 // Initialize the vtable pointers before entering the body.
Anders Carlssonffb945f2011-05-14 23:26:09 +00001288 if (!CanSkipVTablePointerInitialization(getContext(), Dtor))
1289 InitializeVTablePointers(Dtor->getParent());
John McCall50da2ca2010-07-21 05:30:47 +00001290
1291 if (isTryBody)
1292 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
1293 else if (Body)
1294 EmitStmt(Body);
1295 else {
1296 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
1297 // nothing to do besides what's in the epilogue
1298 }
Fariborz Jahanian5abec142011-02-02 23:12:46 +00001299 // -fapple-kext must inline any call to this dtor into
1300 // the caller's body.
Richard Smith7edf9e32012-11-01 22:30:59 +00001301 if (getLangOpts().AppleKext)
Bill Wendling72390b32012-12-20 19:27:06 +00001302 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
John McCall50da2ca2010-07-21 05:30:47 +00001303 break;
John McCall9fc6a772010-02-19 09:25:03 +00001304 }
1305
John McCall50da2ca2010-07-21 05:30:47 +00001306 // Jump out through the epilogue cleanups.
1307 DtorEpilogue.ForceCleanup();
John McCall9fc6a772010-02-19 09:25:03 +00001308
1309 // Exit the try if applicable.
1310 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +00001311 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +00001312}
1313
Lang Hames56c00c42013-02-17 07:22:09 +00001314void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) {
1315 const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
1316 const Stmt *RootS = AssignOp->getBody();
1317 assert(isa<CompoundStmt>(RootS) &&
1318 "Body of an implicit assignment operator should be compound stmt.");
1319 const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
1320
1321 LexicalScope Scope(*this, RootCS->getSourceRange());
1322
1323 AssignmentMemcpyizer AM(*this, AssignOp, Args);
1324 for (CompoundStmt::const_body_iterator I = RootCS->body_begin(),
1325 E = RootCS->body_end();
1326 I != E; ++I) {
1327 AM.emitAssignment(*I);
1328 }
1329 AM.finish();
1330}
1331
John McCall50da2ca2010-07-21 05:30:47 +00001332namespace {
1333 /// Call the operator delete associated with the current destructor.
John McCall1f0fca52010-07-21 07:22:38 +00001334 struct CallDtorDelete : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +00001335 CallDtorDelete() {}
1336
John McCallad346f42011-07-12 20:27:29 +00001337 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall50da2ca2010-07-21 05:30:47 +00001338 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1339 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1340 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1341 CGF.getContext().getTagDeclType(ClassDecl));
1342 }
1343 };
1344
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +00001345 struct CallDtorDeleteConditional : EHScopeStack::Cleanup {
1346 llvm::Value *ShouldDeleteCondition;
1347 public:
1348 CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
1349 : ShouldDeleteCondition(ShouldDeleteCondition) {
1350 assert(ShouldDeleteCondition != NULL);
1351 }
1352
1353 void Emit(CodeGenFunction &CGF, Flags flags) {
1354 llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
1355 llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
1356 llvm::Value *ShouldCallDelete
1357 = CGF.Builder.CreateIsNull(ShouldDeleteCondition);
1358 CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
1359
1360 CGF.EmitBlock(callDeleteBB);
1361 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1362 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1363 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1364 CGF.getContext().getTagDeclType(ClassDecl));
1365 CGF.Builder.CreateBr(continueBB);
1366
1367 CGF.EmitBlock(continueBB);
1368 }
1369 };
1370
John McCall9928c482011-07-12 16:41:08 +00001371 class DestroyField : public EHScopeStack::Cleanup {
1372 const FieldDecl *field;
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001373 CodeGenFunction::Destroyer *destroyer;
John McCall9928c482011-07-12 16:41:08 +00001374 bool useEHCleanupForArray;
John McCall50da2ca2010-07-21 05:30:47 +00001375
John McCall9928c482011-07-12 16:41:08 +00001376 public:
1377 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
1378 bool useEHCleanupForArray)
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001379 : field(field), destroyer(destroyer),
John McCall9928c482011-07-12 16:41:08 +00001380 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall50da2ca2010-07-21 05:30:47 +00001381
John McCallad346f42011-07-12 20:27:29 +00001382 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall9928c482011-07-12 16:41:08 +00001383 // Find the address of the field.
1384 llvm::Value *thisValue = CGF.LoadCXXThis();
Eli Friedman377ecc72012-04-16 03:54:45 +00001385 QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
1386 LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
1387 LValue LV = CGF.EmitLValueForField(ThisLV, field);
John McCall9928c482011-07-12 16:41:08 +00001388 assert(LV.isSimple());
1389
1390 CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
John McCallad346f42011-07-12 20:27:29 +00001391 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCall50da2ca2010-07-21 05:30:47 +00001392 }
1393 };
1394}
1395
Anders Carlsson607d0372009-12-24 22:46:43 +00001396/// EmitDtorEpilogue - Emit all code that comes at the end of class's
1397/// destructor. This is to call destructors on members and base classes
1398/// in reverse order of their construction.
John McCall50da2ca2010-07-21 05:30:47 +00001399void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
1400 CXXDtorType DtorType) {
Anders Carlsson607d0372009-12-24 22:46:43 +00001401 assert(!DD->isTrivial() &&
1402 "Should not emit dtor epilogue for trivial dtor!");
1403
John McCall50da2ca2010-07-21 05:30:47 +00001404 // The deleting-destructor phase just needs to call the appropriate
1405 // operator delete that Sema picked up.
John McCall3b477332010-02-18 19:59:28 +00001406 if (DtorType == Dtor_Deleting) {
1407 assert(DD->getOperatorDelete() &&
1408 "operator delete missing - EmitDtorEpilogue");
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +00001409 if (CXXStructorImplicitParamValue) {
1410 // If there is an implicit param to the deleting dtor, it's a boolean
1411 // telling whether we should call delete at the end of the dtor.
1412 EHStack.pushCleanup<CallDtorDeleteConditional>(
1413 NormalAndEHCleanup, CXXStructorImplicitParamValue);
1414 } else {
1415 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
1416 }
John McCall3b477332010-02-18 19:59:28 +00001417 return;
1418 }
1419
John McCall50da2ca2010-07-21 05:30:47 +00001420 const CXXRecordDecl *ClassDecl = DD->getParent();
1421
Richard Smith416f63e2011-09-18 12:11:43 +00001422 // Unions have no bases and do not call field destructors.
1423 if (ClassDecl->isUnion())
1424 return;
1425
John McCall50da2ca2010-07-21 05:30:47 +00001426 // The complete-destructor phase just destructs all the virtual bases.
John McCall3b477332010-02-18 19:59:28 +00001427 if (DtorType == Dtor_Complete) {
John McCall50da2ca2010-07-21 05:30:47 +00001428
1429 // We push them in the forward order so that they'll be popped in
1430 // the reverse order.
1431 for (CXXRecordDecl::base_class_const_iterator I =
1432 ClassDecl->vbases_begin(), E = ClassDecl->vbases_end();
John McCall3b477332010-02-18 19:59:28 +00001433 I != E; ++I) {
1434 const CXXBaseSpecifier &Base = *I;
1435 CXXRecordDecl *BaseClassDecl
1436 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1437
1438 // Ignore trivial destructors.
1439 if (BaseClassDecl->hasTrivialDestructor())
1440 continue;
John McCall50da2ca2010-07-21 05:30:47 +00001441
John McCall1f0fca52010-07-21 07:22:38 +00001442 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1443 BaseClassDecl,
1444 /*BaseIsVirtual*/ true);
John McCall3b477332010-02-18 19:59:28 +00001445 }
John McCall50da2ca2010-07-21 05:30:47 +00001446
John McCall3b477332010-02-18 19:59:28 +00001447 return;
1448 }
1449
1450 assert(DtorType == Dtor_Base);
John McCall50da2ca2010-07-21 05:30:47 +00001451
1452 // Destroy non-virtual bases.
1453 for (CXXRecordDecl::base_class_const_iterator I =
1454 ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) {
1455 const CXXBaseSpecifier &Base = *I;
1456
1457 // Ignore virtual bases.
1458 if (Base.isVirtual())
1459 continue;
1460
1461 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
1462
1463 // Ignore trivial destructors.
1464 if (BaseClassDecl->hasTrivialDestructor())
1465 continue;
John McCall3b477332010-02-18 19:59:28 +00001466
John McCall1f0fca52010-07-21 07:22:38 +00001467 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1468 BaseClassDecl,
1469 /*BaseIsVirtual*/ false);
John McCall50da2ca2010-07-21 05:30:47 +00001470 }
1471
1472 // Destroy direct fields.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001473 SmallVector<const FieldDecl *, 16> FieldDecls;
Anders Carlsson607d0372009-12-24 22:46:43 +00001474 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1475 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001476 const FieldDecl *field = *I;
John McCall9928c482011-07-12 16:41:08 +00001477 QualType type = field->getType();
1478 QualType::DestructionKind dtorKind = type.isDestructedType();
1479 if (!dtorKind) continue;
John McCall50da2ca2010-07-21 05:30:47 +00001480
Richard Smith9a561d52012-02-26 09:11:52 +00001481 // Anonymous union members do not have their destructors called.
1482 const RecordType *RT = type->getAsUnionType();
1483 if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
1484
John McCall9928c482011-07-12 16:41:08 +00001485 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1486 EHStack.pushCleanup<DestroyField>(cleanupKind, field,
1487 getDestroyer(dtorKind),
1488 cleanupKind & EHCleanup);
Anders Carlsson607d0372009-12-24 22:46:43 +00001489 }
Anders Carlsson607d0372009-12-24 22:46:43 +00001490}
1491
John McCallc3c07662011-07-13 06:10:41 +00001492/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1493/// constructor for each of several members of an array.
Douglas Gregor59174c02010-07-21 01:10:17 +00001494///
John McCallc3c07662011-07-13 06:10:41 +00001495/// \param ctor the constructor to call for each element
John McCallc3c07662011-07-13 06:10:41 +00001496/// \param arrayType the type of the array to initialize
1497/// \param arrayBegin an arrayType*
1498/// \param zeroInitialize true if each element should be
1499/// zero-initialized before it is constructed
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001500void
John McCallc3c07662011-07-13 06:10:41 +00001501CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1502 const ConstantArrayType *arrayType,
1503 llvm::Value *arrayBegin,
1504 CallExpr::const_arg_iterator argBegin,
1505 CallExpr::const_arg_iterator argEnd,
1506 bool zeroInitialize) {
1507 QualType elementType;
1508 llvm::Value *numElements =
1509 emitArrayLength(arrayType, elementType, arrayBegin);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001510
John McCallc3c07662011-07-13 06:10:41 +00001511 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin,
1512 argBegin, argEnd, zeroInitialize);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001513}
1514
John McCallc3c07662011-07-13 06:10:41 +00001515/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1516/// constructor for each of several members of an array.
1517///
1518/// \param ctor the constructor to call for each element
1519/// \param numElements the number of elements in the array;
John McCalldd376ca2011-07-13 07:37:11 +00001520/// may be zero
John McCallc3c07662011-07-13 06:10:41 +00001521/// \param arrayBegin a T*, where T is the type constructed by ctor
1522/// \param zeroInitialize true if each element should be
1523/// zero-initialized before it is constructed
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001524void
John McCallc3c07662011-07-13 06:10:41 +00001525CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1526 llvm::Value *numElements,
1527 llvm::Value *arrayBegin,
1528 CallExpr::const_arg_iterator argBegin,
1529 CallExpr::const_arg_iterator argEnd,
1530 bool zeroInitialize) {
John McCalldd376ca2011-07-13 07:37:11 +00001531
1532 // It's legal for numElements to be zero. This can happen both
1533 // dynamically, because x can be zero in 'new A[x]', and statically,
1534 // because of GCC extensions that permit zero-length arrays. There
1535 // are probably legitimate places where we could assume that this
1536 // doesn't happen, but it's not clear that it's worth it.
1537 llvm::BranchInst *zeroCheckBranch = 0;
1538
1539 // Optimize for a constant count.
1540 llvm::ConstantInt *constantCount
1541 = dyn_cast<llvm::ConstantInt>(numElements);
1542 if (constantCount) {
1543 // Just skip out if the constant count is zero.
1544 if (constantCount->isZero()) return;
1545
1546 // Otherwise, emit the check.
1547 } else {
1548 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1549 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1550 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1551 EmitBlock(loopBB);
1552 }
1553
John McCallc3c07662011-07-13 06:10:41 +00001554 // Find the end of the array.
1555 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1556 "arrayctor.end");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001557
John McCallc3c07662011-07-13 06:10:41 +00001558 // Enter the loop, setting up a phi for the current location to initialize.
1559 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1560 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1561 EmitBlock(loopBB);
1562 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1563 "arrayctor.cur");
1564 cur->addIncoming(arrayBegin, entryBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001565
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001566 // Inside the loop body, emit the constructor call on the array element.
John McCallc3c07662011-07-13 06:10:41 +00001567
1568 QualType type = getContext().getTypeDeclType(ctor->getParent());
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001569
Douglas Gregor59174c02010-07-21 01:10:17 +00001570 // Zero initialize the storage, if requested.
John McCallc3c07662011-07-13 06:10:41 +00001571 if (zeroInitialize)
1572 EmitNullInitialization(cur, type);
Douglas Gregor59174c02010-07-21 01:10:17 +00001573
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001574 // C++ [class.temporary]p4:
1575 // There are two contexts in which temporaries are destroyed at a different
1576 // point than the end of the full-expression. The first context is when a
1577 // default constructor is called to initialize an element of an array.
1578 // If the constructor has one or more default arguments, the destruction of
1579 // every temporary created in a default argument expression is sequenced
1580 // before the construction of the next array element, if any.
1581
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001582 {
John McCallf1549f62010-07-06 01:34:17 +00001583 RunCleanupsScope Scope(*this);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001584
John McCallc3c07662011-07-13 06:10:41 +00001585 // Evaluate the constructor and its arguments in a regular
1586 // partial-destroy cleanup.
David Blaikie4e4d0842012-03-11 07:00:24 +00001587 if (getLangOpts().Exceptions &&
John McCallc3c07662011-07-13 06:10:41 +00001588 !ctor->getParent()->hasTrivialDestructor()) {
1589 Destroyer *destroyer = destroyCXXObject;
1590 pushRegularPartialArrayCleanup(arrayBegin, cur, type, *destroyer);
1591 }
1592
1593 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/ false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001594 /*Delegating=*/false, cur, argBegin, argEnd);
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001595 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001596
John McCallc3c07662011-07-13 06:10:41 +00001597 // Go to the next element.
1598 llvm::Value *next =
1599 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
1600 "arrayctor.next");
1601 cur->addIncoming(next, Builder.GetInsertBlock());
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001602
John McCallc3c07662011-07-13 06:10:41 +00001603 // Check whether that's the end of the loop.
1604 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
1605 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
1606 Builder.CreateCondBr(done, contBB, loopBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001607
John McCalldd376ca2011-07-13 07:37:11 +00001608 // Patch the earlier check to skip over the loop.
1609 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
1610
John McCallc3c07662011-07-13 06:10:41 +00001611 EmitBlock(contBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001612}
1613
John McCallbdc4d802011-07-09 01:37:26 +00001614void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
1615 llvm::Value *addr,
1616 QualType type) {
1617 const RecordType *rtype = type->castAs<RecordType>();
1618 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
1619 const CXXDestructorDecl *dtor = record->getDestructor();
1620 assert(!dtor->isTrivial());
1621 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001622 /*Delegating=*/false, addr);
John McCallbdc4d802011-07-09 01:37:26 +00001623}
1624
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001625void
1626CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
Anders Carlsson155ed4a2010-05-02 23:20:53 +00001627 CXXCtorType Type, bool ForVirtualBase,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001628 bool Delegating,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001629 llvm::Value *This,
1630 CallExpr::const_arg_iterator ArgBeg,
1631 CallExpr::const_arg_iterator ArgEnd) {
Devang Patel3ee36af2011-02-22 20:55:26 +00001632
1633 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonov3a70cd62012-04-27 07:24:20 +00001634 if (DI &&
Douglas Gregor4cdad312012-10-23 20:05:01 +00001635 CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::LimitedDebugInfo) {
Eric Christopheraf790882012-02-01 21:44:56 +00001636 // If debug info for this class has not been emitted then this is the
1637 // right time to do so.
Devang Patel3ee36af2011-02-22 20:55:26 +00001638 const CXXRecordDecl *Parent = D->getParent();
1639 DI->getOrCreateRecordType(CGM.getContext().getTypeDeclType(Parent),
1640 Parent->getLocation());
1641 }
1642
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001643 // If this is a trivial constructor, just emit what's needed.
John McCall8b6bbeb2010-02-06 00:25:16 +00001644 if (D->isTrivial()) {
1645 if (ArgBeg == ArgEnd) {
1646 // Trivial default constructor, no codegen required.
1647 assert(D->isDefaultConstructor() &&
1648 "trivial 0-arg ctor not a default ctor");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001649 return;
1650 }
John McCall8b6bbeb2010-02-06 00:25:16 +00001651
1652 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001653 assert(D->isCopyOrMoveConstructor() &&
1654 "trivial 1-arg ctor not a copy/move ctor");
John McCall8b6bbeb2010-02-06 00:25:16 +00001655
John McCall8b6bbeb2010-02-06 00:25:16 +00001656 const Expr *E = (*ArgBeg);
1657 QualType Ty = E->getType();
1658 llvm::Value *Src = EmitLValue(E).getAddress();
1659 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001660 return;
1661 }
1662
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001663 // Non-trivial constructors are handled in an ABI-specific manner.
Stephen Lind4c0cd02013-06-18 17:00:49 +00001664 CGM.getCXXABI().EmitConstructorCall(*this, D, Type,
1665 ForVirtualBase, Delegating,
1666 ReturnValueSlot(), This, ArgBeg, ArgEnd);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001667}
1668
John McCallc0bf4622010-02-23 00:48:20 +00001669void
Fariborz Jahanian34999872010-11-13 21:53:34 +00001670CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
1671 llvm::Value *This, llvm::Value *Src,
1672 CallExpr::const_arg_iterator ArgBeg,
1673 CallExpr::const_arg_iterator ArgEnd) {
1674 if (D->isTrivial()) {
1675 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001676 assert(D->isCopyOrMoveConstructor() &&
1677 "trivial 1-arg ctor not a copy/move ctor");
Fariborz Jahanian34999872010-11-13 21:53:34 +00001678 EmitAggregateCopy(This, Src, (*ArgBeg)->getType());
1679 return;
1680 }
1681 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D,
1682 clang::Ctor_Complete);
1683 assert(D->isInstance() &&
1684 "Trying to emit a member call expr on a static method!");
1685
1686 const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
1687
1688 CallArgList Args;
1689
1690 // Push the this ptr.
Eli Friedman04c9a492011-05-02 17:57:46 +00001691 Args.add(RValue::get(This), D->getThisType(getContext()));
Fariborz Jahanian34999872010-11-13 21:53:34 +00001692
1693
1694 // Push the src ptr.
1695 QualType QT = *(FPT->arg_type_begin());
Chris Lattner2acc6e32011-07-18 04:24:23 +00001696 llvm::Type *t = CGM.getTypes().ConvertType(QT);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001697 Src = Builder.CreateBitCast(Src, t);
Eli Friedman04c9a492011-05-02 17:57:46 +00001698 Args.add(RValue::get(Src), QT);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001699
1700 // Skip over first argument (Src).
1701 ++ArgBeg;
1702 CallExpr::const_arg_iterator Arg = ArgBeg;
1703 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin()+1,
1704 E = FPT->arg_type_end(); I != E; ++I, ++Arg) {
1705 assert(Arg != ArgEnd && "Running over edge of argument list!");
John McCall413ebdb2011-03-11 20:59:21 +00001706 EmitCallArg(Args, *Arg, *I);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001707 }
1708 // Either we've emitted all the call args, or we have a call to a
1709 // variadic function.
1710 assert((Arg == ArgEnd || FPT->isVariadic()) &&
1711 "Extra arguments in non-variadic function!");
1712 // If we still have any arguments, emit them using the type of the argument.
1713 for (; Arg != ArgEnd; ++Arg) {
1714 QualType ArgType = Arg->getType();
John McCall413ebdb2011-03-11 20:59:21 +00001715 EmitCallArg(Args, *Arg, ArgType);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001716 }
1717
John McCall0f3d0972012-07-07 06:41:13 +00001718 EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, RequiredArgs::All),
1719 Callee, ReturnValueSlot(), Args, D);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001720}
1721
1722void
John McCallc0bf4622010-02-23 00:48:20 +00001723CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1724 CXXCtorType CtorType,
1725 const FunctionArgList &Args) {
1726 CallArgList DelegateArgs;
1727
1728 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
1729 assert(I != E && "no parameters to constructor");
1730
1731 // this
Eli Friedman04c9a492011-05-02 17:57:46 +00001732 DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType());
John McCallc0bf4622010-02-23 00:48:20 +00001733 ++I;
1734
1735 // vtt
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001736 if (llvm::Value *VTT = GetVTTParameter(GlobalDecl(Ctor, CtorType),
Douglas Gregor378e1e72013-01-31 05:50:40 +00001737 /*ForVirtualBase=*/false,
1738 /*Delegating=*/true)) {
John McCallc0bf4622010-02-23 00:48:20 +00001739 QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
Eli Friedman04c9a492011-05-02 17:57:46 +00001740 DelegateArgs.add(RValue::get(VTT), VoidPP);
John McCallc0bf4622010-02-23 00:48:20 +00001741
Anders Carlssonaf440352010-03-23 04:11:45 +00001742 if (CodeGenVTables::needsVTTParameter(CurGD)) {
John McCallc0bf4622010-02-23 00:48:20 +00001743 assert(I != E && "cannot skip vtt parameter, already done with args");
John McCalld26bc762011-03-09 04:27:21 +00001744 assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
John McCallc0bf4622010-02-23 00:48:20 +00001745 ++I;
1746 }
1747 }
1748
1749 // Explicit arguments.
1750 for (; I != E; ++I) {
John McCall413ebdb2011-03-11 20:59:21 +00001751 const VarDecl *param = *I;
1752 EmitDelegateCallArg(DelegateArgs, param);
John McCallc0bf4622010-02-23 00:48:20 +00001753 }
1754
Manman Ren63fd4082013-03-20 16:59:38 +00001755 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(Ctor, CtorType);
John McCallde5d3c72012-02-17 03:33:10 +00001756 EmitCall(CGM.getTypes().arrangeCXXConstructorDeclaration(Ctor, CtorType),
Manman Ren63fd4082013-03-20 16:59:38 +00001757 Callee, ReturnValueSlot(), DelegateArgs, Ctor);
John McCallc0bf4622010-02-23 00:48:20 +00001758}
1759
Sean Huntb76af9c2011-05-03 23:05:34 +00001760namespace {
1761 struct CallDelegatingCtorDtor : EHScopeStack::Cleanup {
1762 const CXXDestructorDecl *Dtor;
1763 llvm::Value *Addr;
1764 CXXDtorType Type;
1765
1766 CallDelegatingCtorDtor(const CXXDestructorDecl *D, llvm::Value *Addr,
1767 CXXDtorType Type)
1768 : Dtor(D), Addr(Addr), Type(Type) {}
1769
John McCallad346f42011-07-12 20:27:29 +00001770 void Emit(CodeGenFunction &CGF, Flags flags) {
Sean Huntb76af9c2011-05-03 23:05:34 +00001771 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001772 /*Delegating=*/true, Addr);
Sean Huntb76af9c2011-05-03 23:05:34 +00001773 }
1774 };
1775}
1776
Sean Hunt059ce0d2011-05-01 07:04:31 +00001777void
1778CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
1779 const FunctionArgList &Args) {
1780 assert(Ctor->isDelegatingConstructor());
1781
1782 llvm::Value *ThisPtr = LoadCXXThis();
1783
Eli Friedmanf3940782011-12-03 00:54:26 +00001784 QualType Ty = getContext().getTagDeclType(Ctor->getParent());
Eli Friedmand7722d92011-12-03 02:13:40 +00001785 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
John McCallf85e1932011-06-15 23:02:42 +00001786 AggValueSlot AggSlot =
Eli Friedmanf3940782011-12-03 00:54:26 +00001787 AggValueSlot::forAddr(ThisPtr, Alignment, Qualifiers(),
John McCall7c2349b2011-08-25 20:40:09 +00001788 AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +00001789 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +00001790 AggValueSlot::IsNotAliased);
Sean Hunt059ce0d2011-05-01 07:04:31 +00001791
1792 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
Sean Hunt059ce0d2011-05-01 07:04:31 +00001793
Sean Huntb76af9c2011-05-03 23:05:34 +00001794 const CXXRecordDecl *ClassDecl = Ctor->getParent();
David Blaikie4e4d0842012-03-11 07:00:24 +00001795 if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
Sean Huntb76af9c2011-05-03 23:05:34 +00001796 CXXDtorType Type =
1797 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
1798
1799 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
1800 ClassDecl->getDestructor(),
1801 ThisPtr, Type);
1802 }
1803}
Sean Hunt059ce0d2011-05-01 07:04:31 +00001804
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001805void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
1806 CXXDtorType Type,
Anders Carlsson8e6404c2010-05-02 23:29:11 +00001807 bool ForVirtualBase,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001808 bool Delegating,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001809 llvm::Value *This) {
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001810 llvm::Value *VTT = GetVTTParameter(GlobalDecl(DD, Type),
Douglas Gregor378e1e72013-01-31 05:50:40 +00001811 ForVirtualBase, Delegating);
Fariborz Jahanianccd52592011-02-01 23:22:34 +00001812 llvm::Value *Callee = 0;
Richard Smith7edf9e32012-11-01 22:30:59 +00001813 if (getLangOpts().AppleKext)
Fariborz Jahanian771c6782011-02-03 19:27:17 +00001814 Callee = BuildAppleKextVirtualDestructorCall(DD, Type,
1815 DD->getParent());
Fariborz Jahanianccd52592011-02-01 23:22:34 +00001816
1817 if (!Callee)
1818 Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001819
Richard Smith4def70d2012-10-09 19:52:38 +00001820 // FIXME: Provide a source location here.
1821 EmitCXXMemberCall(DD, SourceLocation(), Callee, ReturnValueSlot(), This,
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +00001822 VTT, getContext().getPointerType(getContext().VoidPtrTy),
1823 0, 0);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001824}
1825
John McCall291ae942010-07-21 01:41:18 +00001826namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001827 struct CallLocalDtor : EHScopeStack::Cleanup {
John McCall291ae942010-07-21 01:41:18 +00001828 const CXXDestructorDecl *Dtor;
1829 llvm::Value *Addr;
1830
1831 CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
1832 : Dtor(D), Addr(Addr) {}
1833
John McCallad346f42011-07-12 20:27:29 +00001834 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall291ae942010-07-21 01:41:18 +00001835 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001836 /*ForVirtualBase=*/false,
1837 /*Delegating=*/false, Addr);
John McCall291ae942010-07-21 01:41:18 +00001838 }
1839 };
1840}
1841
John McCall81407d42010-07-21 06:29:51 +00001842void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
1843 llvm::Value *Addr) {
John McCall1f0fca52010-07-21 07:22:38 +00001844 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
John McCall81407d42010-07-21 06:29:51 +00001845}
1846
John McCallf1549f62010-07-06 01:34:17 +00001847void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
1848 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
1849 if (!ClassDecl) return;
1850 if (ClassDecl->hasTrivialDestructor()) return;
1851
1852 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCall642a75f2011-04-28 02:15:35 +00001853 assert(D && D->isUsed() && "destructor not marked as used!");
John McCall81407d42010-07-21 06:29:51 +00001854 PushDestructorCleanup(D, Addr);
John McCallf1549f62010-07-06 01:34:17 +00001855}
1856
Anders Carlssond103f9f2010-03-28 19:40:00 +00001857void
1858CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001859 const CXXRecordDecl *NearestVBase,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001860 CharUnits OffsetFromNearestVBase,
Anders Carlssond103f9f2010-03-28 19:40:00 +00001861 llvm::Constant *VTable,
1862 const CXXRecordDecl *VTableClass) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001863 const CXXRecordDecl *RD = Base.getBase();
1864
Anders Carlssond103f9f2010-03-28 19:40:00 +00001865 // Compute the address point.
Anders Carlssonc83f1062010-03-29 01:08:49 +00001866 llvm::Value *VTableAddressPoint;
Anders Carlsson851853d2010-03-29 02:38:51 +00001867
Anders Carlssonc83f1062010-03-29 01:08:49 +00001868 // Check if we need to use a vtable from the VTT.
Anders Carlsson851853d2010-03-29 02:38:51 +00001869 if (CodeGenVTables::needsVTTParameter(CurGD) &&
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001870 (RD->getNumVBases() || NearestVBase)) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001871 // Get the secondary vpointer index.
1872 uint64_t VirtualPointerIndex =
1873 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1874
1875 /// Load the VTT.
1876 llvm::Value *VTT = LoadCXXVTT();
1877 if (VirtualPointerIndex)
1878 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1879
1880 // And load the address point from the VTT.
1881 VTableAddressPoint = Builder.CreateLoad(VTT);
1882 } else {
Peter Collingbourne84fcc482011-09-26 01:56:41 +00001883 uint64_t AddressPoint =
Peter Collingbournee09cdf42011-09-26 01:56:50 +00001884 CGM.getVTableContext().getVTableLayout(VTableClass).getAddressPoint(Base);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001885 VTableAddressPoint =
Anders Carlssond103f9f2010-03-28 19:40:00 +00001886 Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001887 }
Anders Carlssond103f9f2010-03-28 19:40:00 +00001888
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001889 // Compute where to store the address point.
Anders Carlsson8246cc72010-05-03 00:29:58 +00001890 llvm::Value *VirtualOffset = 0;
Ken Dyck9a8ad9b2011-03-23 00:45:26 +00001891 CharUnits NonVirtualOffset = CharUnits::Zero();
Anders Carlsson3e79c302010-04-20 18:05:10 +00001892
1893 if (CodeGenVTables::needsVTTParameter(CurGD) && NearestVBase) {
1894 // We need to use the virtual base offset offset because the virtual base
1895 // might have a different offset in the most derived class.
Reid Klecknerb0f533e2013-05-29 18:02:47 +00001896 VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(*this,
1897 LoadCXXThis(),
1898 VTableClass,
1899 NearestVBase);
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001900 NonVirtualOffset = OffsetFromNearestVBase;
Anders Carlsson3e79c302010-04-20 18:05:10 +00001901 } else {
Anders Carlsson8246cc72010-05-03 00:29:58 +00001902 // We can just use the base offset in the complete class.
Ken Dyck4230d522011-03-24 01:21:01 +00001903 NonVirtualOffset = Base.getBaseOffset();
Anders Carlsson3e79c302010-04-20 18:05:10 +00001904 }
Anders Carlsson8246cc72010-05-03 00:29:58 +00001905
1906 // Apply the offsets.
1907 llvm::Value *VTableField = LoadCXXThis();
1908
Ken Dyck9a8ad9b2011-03-23 00:45:26 +00001909 if (!NonVirtualOffset.isZero() || VirtualOffset)
Anders Carlsson8246cc72010-05-03 00:29:58 +00001910 VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
1911 NonVirtualOffset,
1912 VirtualOffset);
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001913
Anders Carlssond103f9f2010-03-28 19:40:00 +00001914 // Finally, store the address point.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001915 llvm::Type *AddressPointPtrTy =
Anders Carlssond103f9f2010-03-28 19:40:00 +00001916 VTableAddressPoint->getType()->getPointerTo();
1917 VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
Kostya Serebryany8cb4a072012-03-26 17:03:51 +00001918 llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
1919 CGM.DecorateInstruction(Store, CGM.getTBAAInfoForVTablePtr());
Anders Carlssond103f9f2010-03-28 19:40:00 +00001920}
1921
Anders Carlsson603d6d12010-03-28 21:07:49 +00001922void
1923CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001924 const CXXRecordDecl *NearestVBase,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001925 CharUnits OffsetFromNearestVBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001926 bool BaseIsNonVirtualPrimaryBase,
1927 llvm::Constant *VTable,
1928 const CXXRecordDecl *VTableClass,
1929 VisitedVirtualBasesSetTy& VBases) {
1930 // If this base is a non-virtual primary base the address point has already
1931 // been set.
1932 if (!BaseIsNonVirtualPrimaryBase) {
1933 // Initialize the vtable pointer for this base.
Anders Carlsson42358402010-05-03 00:07:07 +00001934 InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
1935 VTable, VTableClass);
Anders Carlsson603d6d12010-03-28 21:07:49 +00001936 }
1937
1938 const CXXRecordDecl *RD = Base.getBase();
1939
1940 // Traverse bases.
1941 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1942 E = RD->bases_end(); I != E; ++I) {
1943 CXXRecordDecl *BaseDecl
1944 = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1945
1946 // Ignore classes without a vtable.
1947 if (!BaseDecl->isDynamicClass())
1948 continue;
1949
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001950 CharUnits BaseOffset;
1951 CharUnits BaseOffsetFromNearestVBase;
Anders Carlsson14da9de2010-03-29 01:16:41 +00001952 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001953
1954 if (I->isVirtual()) {
1955 // Check if we've visited this virtual base before.
1956 if (!VBases.insert(BaseDecl))
1957 continue;
1958
1959 const ASTRecordLayout &Layout =
1960 getContext().getASTRecordLayout(VTableClass);
1961
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001962 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
1963 BaseOffsetFromNearestVBase = CharUnits::Zero();
Anders Carlsson14da9de2010-03-29 01:16:41 +00001964 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001965 } else {
1966 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1967
Ken Dyck4230d522011-03-24 01:21:01 +00001968 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson42358402010-05-03 00:07:07 +00001969 BaseOffsetFromNearestVBase =
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001970 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson14da9de2010-03-29 01:16:41 +00001971 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001972 }
1973
Ken Dyck4230d522011-03-24 01:21:01 +00001974 InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001975 I->isVirtual() ? BaseDecl : NearestVBase,
Anders Carlsson42358402010-05-03 00:07:07 +00001976 BaseOffsetFromNearestVBase,
Anders Carlsson14da9de2010-03-29 01:16:41 +00001977 BaseDeclIsNonVirtualPrimaryBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001978 VTable, VTableClass, VBases);
1979 }
1980}
1981
1982void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
1983 // Ignore classes without a vtable.
Anders Carlsson07036902010-03-26 04:39:42 +00001984 if (!RD->isDynamicClass())
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001985 return;
1986
Anders Carlsson07036902010-03-26 04:39:42 +00001987 // Get the VTable.
1988 llvm::Constant *VTable = CGM.getVTables().GetAddrOfVTable(RD);
Anders Carlsson5c6c1d92010-03-24 03:57:14 +00001989
Anders Carlsson603d6d12010-03-28 21:07:49 +00001990 // Initialize the vtable pointers for this class and all of its bases.
1991 VisitedVirtualBasesSetTy VBases;
Ken Dyck4230d522011-03-24 01:21:01 +00001992 InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()),
1993 /*NearestVBase=*/0,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001994 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
Anders Carlsson603d6d12010-03-28 21:07:49 +00001995 /*BaseIsNonVirtualPrimaryBase=*/false,
1996 VTable, RD, VBases);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001997}
Dan Gohman043fb9a2010-10-26 18:44:08 +00001998
1999llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
Chris Lattner2acc6e32011-07-18 04:24:23 +00002000 llvm::Type *Ty) {
Dan Gohman043fb9a2010-10-26 18:44:08 +00002001 llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
Kostya Serebryany8cb4a072012-03-26 17:03:51 +00002002 llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
2003 CGM.DecorateInstruction(VTable, CGM.getTBAAInfoForVTablePtr());
2004 return VTable;
Dan Gohman043fb9a2010-10-26 18:44:08 +00002005}
Anders Carlssona2447e02011-05-08 20:32:23 +00002006
2007static const CXXRecordDecl *getMostDerivedClassDecl(const Expr *Base) {
2008 const Expr *E = Base;
2009
2010 while (true) {
2011 E = E->IgnoreParens();
2012 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
2013 if (CE->getCastKind() == CK_DerivedToBase ||
2014 CE->getCastKind() == CK_UncheckedDerivedToBase ||
2015 CE->getCastKind() == CK_NoOp) {
2016 E = CE->getSubExpr();
2017 continue;
2018 }
2019 }
2020
2021 break;
2022 }
2023
2024 QualType DerivedType = E->getType();
2025 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
2026 DerivedType = PTy->getPointeeType();
2027
2028 return cast<CXXRecordDecl>(DerivedType->castAs<RecordType>()->getDecl());
2029}
2030
2031// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
2032// quite what we want.
2033static const Expr *skipNoOpCastsAndParens(const Expr *E) {
2034 while (true) {
2035 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
2036 E = PE->getSubExpr();
2037 continue;
2038 }
2039
2040 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
2041 if (CE->getCastKind() == CK_NoOp) {
2042 E = CE->getSubExpr();
2043 continue;
2044 }
2045 }
2046 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2047 if (UO->getOpcode() == UO_Extension) {
2048 E = UO->getSubExpr();
2049 continue;
2050 }
2051 }
2052 return E;
2053 }
2054}
2055
2056/// canDevirtualizeMemberFunctionCall - Checks whether the given virtual member
2057/// function call on the given expr can be devirtualized.
Anders Carlssona2447e02011-05-08 20:32:23 +00002058static bool canDevirtualizeMemberFunctionCall(const Expr *Base,
2059 const CXXMethodDecl *MD) {
2060 // If the most derived class is marked final, we know that no subclass can
2061 // override this member function and so we can devirtualize it. For example:
2062 //
2063 // struct A { virtual void f(); }
2064 // struct B final : A { };
2065 //
2066 // void f(B *b) {
2067 // b->f();
2068 // }
2069 //
2070 const CXXRecordDecl *MostDerivedClassDecl = getMostDerivedClassDecl(Base);
2071 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
2072 return true;
2073
2074 // If the member function is marked 'final', we know that it can't be
2075 // overridden and can therefore devirtualize it.
2076 if (MD->hasAttr<FinalAttr>())
2077 return true;
2078
2079 // Similarly, if the class itself is marked 'final' it can't be overridden
2080 // and we can therefore devirtualize the member function call.
2081 if (MD->getParent()->hasAttr<FinalAttr>())
2082 return true;
2083
2084 Base = skipNoOpCastsAndParens(Base);
2085 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
2086 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
2087 // This is a record decl. We know the type and can devirtualize it.
2088 return VD->getType()->isRecordType();
2089 }
2090
2091 return false;
2092 }
2093
2094 // We can always devirtualize calls on temporary object expressions.
2095 if (isa<CXXConstructExpr>(Base))
2096 return true;
2097
2098 // And calls on bound temporaries.
2099 if (isa<CXXBindTemporaryExpr>(Base))
2100 return true;
2101
2102 // Check if this is a call expr that returns a record type.
2103 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
2104 return CE->getCallReturnType()->isRecordType();
2105
2106 // We can't devirtualize the call.
2107 return false;
2108}
2109
2110static bool UseVirtualCall(ASTContext &Context,
2111 const CXXOperatorCallExpr *CE,
2112 const CXXMethodDecl *MD) {
2113 if (!MD->isVirtual())
2114 return false;
2115
2116 // When building with -fapple-kext, all calls must go through the vtable since
2117 // the kernel linker can do runtime patching of vtables.
David Blaikie4e4d0842012-03-11 07:00:24 +00002118 if (Context.getLangOpts().AppleKext)
Anders Carlssona2447e02011-05-08 20:32:23 +00002119 return true;
2120
2121 return !canDevirtualizeMemberFunctionCall(CE->getArg(0), MD);
2122}
2123
2124llvm::Value *
2125CodeGenFunction::EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E,
2126 const CXXMethodDecl *MD,
2127 llvm::Value *This) {
John McCallde5d3c72012-02-17 03:33:10 +00002128 llvm::FunctionType *fnType =
2129 CGM.getTypes().GetFunctionType(
2130 CGM.getTypes().arrangeCXXMethodDeclaration(MD));
Anders Carlssona2447e02011-05-08 20:32:23 +00002131
2132 if (UseVirtualCall(getContext(), E, MD))
John McCallde5d3c72012-02-17 03:33:10 +00002133 return BuildVirtualCall(MD, This, fnType);
Anders Carlssona2447e02011-05-08 20:32:23 +00002134
John McCallde5d3c72012-02-17 03:33:10 +00002135 return CGM.GetAddrOfFunction(MD, fnType);
Anders Carlssona2447e02011-05-08 20:32:23 +00002136}
Eli Friedmanbd89f8c2012-02-16 01:37:33 +00002137
John McCall0f3d0972012-07-07 06:41:13 +00002138void CodeGenFunction::EmitForwardingCallToLambda(const CXXRecordDecl *lambda,
2139 CallArgList &callArgs) {
Eli Friedman64bee652012-02-25 02:48:22 +00002140 // Lookup the call operator
John McCall0f3d0972012-07-07 06:41:13 +00002141 DeclarationName operatorName
Eli Friedman21f6ed92012-02-16 03:47:28 +00002142 = getContext().DeclarationNames.getCXXOperatorName(OO_Call);
John McCall0f3d0972012-07-07 06:41:13 +00002143 CXXMethodDecl *callOperator =
David Blaikie3bc93e32012-12-19 00:45:41 +00002144 cast<CXXMethodDecl>(lambda->lookup(operatorName).front());
Eli Friedman21f6ed92012-02-16 03:47:28 +00002145
Eli Friedman21f6ed92012-02-16 03:47:28 +00002146 // Get the address of the call operator.
John McCall0f3d0972012-07-07 06:41:13 +00002147 const CGFunctionInfo &calleeFnInfo =
2148 CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
2149 llvm::Value *callee =
2150 CGM.GetAddrOfFunction(GlobalDecl(callOperator),
2151 CGM.getTypes().GetFunctionType(calleeFnInfo));
Eli Friedman21f6ed92012-02-16 03:47:28 +00002152
John McCall0f3d0972012-07-07 06:41:13 +00002153 // Prepare the return slot.
2154 const FunctionProtoType *FPT =
2155 callOperator->getType()->castAs<FunctionProtoType>();
2156 QualType resultType = FPT->getResultType();
2157 ReturnValueSlot returnSlot;
2158 if (!resultType->isVoidType() &&
2159 calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
John McCall9d232c82013-03-07 21:37:08 +00002160 !hasScalarEvaluationKind(calleeFnInfo.getReturnType()))
John McCall0f3d0972012-07-07 06:41:13 +00002161 returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
2162
2163 // We don't need to separately arrange the call arguments because
2164 // the call can't be variadic anyway --- it's impossible to forward
2165 // variadic arguments.
Eli Friedman21f6ed92012-02-16 03:47:28 +00002166
2167 // Now emit our call.
John McCall0f3d0972012-07-07 06:41:13 +00002168 RValue RV = EmitCall(calleeFnInfo, callee, returnSlot,
2169 callArgs, callOperator);
Eli Friedman21f6ed92012-02-16 03:47:28 +00002170
John McCall0f3d0972012-07-07 06:41:13 +00002171 // If necessary, copy the returned value into the slot.
2172 if (!resultType->isVoidType() && returnSlot.isNull())
2173 EmitReturnOfRValue(RV, resultType);
Eli Friedman50f089a2012-12-13 23:37:17 +00002174 else
2175 EmitBranchThroughCleanup(ReturnBlock);
Eli Friedman21f6ed92012-02-16 03:47:28 +00002176}
2177
Eli Friedman64bee652012-02-25 02:48:22 +00002178void CodeGenFunction::EmitLambdaBlockInvokeBody() {
2179 const BlockDecl *BD = BlockInfo->getBlockDecl();
2180 const VarDecl *variable = BD->capture_begin()->getVariable();
2181 const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
2182
2183 // Start building arguments for forwarding call
2184 CallArgList CallArgs;
2185
2186 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2187 llvm::Value *ThisPtr = GetAddrOfBlockDecl(variable, false);
2188 CallArgs.add(RValue::get(ThisPtr), ThisType);
2189
2190 // Add the rest of the parameters.
2191 for (BlockDecl::param_const_iterator I = BD->param_begin(),
2192 E = BD->param_end(); I != E; ++I) {
2193 ParmVarDecl *param = *I;
2194 EmitDelegateCallArg(CallArgs, param);
2195 }
2196
2197 EmitForwardingCallToLambda(Lambda, CallArgs);
2198}
2199
2200void CodeGenFunction::EmitLambdaToBlockPointerBody(FunctionArgList &Args) {
John McCallf5ebf9b2013-05-03 07:33:41 +00002201 if (cast<CXXMethodDecl>(CurCodeDecl)->isVariadic()) {
Eli Friedman64bee652012-02-25 02:48:22 +00002202 // FIXME: Making this work correctly is nasty because it requires either
2203 // cloning the body of the call operator or making the call operator forward.
John McCallf5ebf9b2013-05-03 07:33:41 +00002204 CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function");
Eli Friedman64bee652012-02-25 02:48:22 +00002205 return;
2206 }
2207
Eli Friedman64bee652012-02-25 02:48:22 +00002208 EmitFunctionBody(Args);
Eli Friedman64bee652012-02-25 02:48:22 +00002209}
2210
2211void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
2212 const CXXRecordDecl *Lambda = MD->getParent();
2213
2214 // Start building arguments for forwarding call
2215 CallArgList CallArgs;
2216
2217 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2218 llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
2219 CallArgs.add(RValue::get(ThisPtr), ThisType);
2220
2221 // Add the rest of the parameters.
2222 for (FunctionDecl::param_const_iterator I = MD->param_begin(),
2223 E = MD->param_end(); I != E; ++I) {
2224 ParmVarDecl *param = *I;
2225 EmitDelegateCallArg(CallArgs, param);
2226 }
2227
2228 EmitForwardingCallToLambda(Lambda, CallArgs);
2229}
2230
Douglas Gregor27dd7d92012-02-17 03:02:34 +00002231void CodeGenFunction::EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD) {
2232 if (MD->isVariadic()) {
Eli Friedman21f6ed92012-02-16 03:47:28 +00002233 // FIXME: Making this work correctly is nasty because it requires either
2234 // cloning the body of the call operator or making the call operator forward.
2235 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
Eli Friedman64bee652012-02-25 02:48:22 +00002236 return;
Eli Friedman21f6ed92012-02-16 03:47:28 +00002237 }
2238
Douglas Gregor27dd7d92012-02-17 03:02:34 +00002239 EmitLambdaDelegatingInvokeBody(MD);
Eli Friedmanbd89f8c2012-02-16 01:37:33 +00002240}