blob: c5220592d56483bde1ca1dfe81fafaf549e7d3d0 [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) {
Peter Collingbournee1e35f72013-06-28 20:45:28 +0000289 if (!CGM.getCXXABI().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.
Peter Collingbournee1e35f72013-06-28 20:45:28 +0000307 assert(!CGM.getCXXABI().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
Peter Collingbournee1e35f72013-06-28 20:45:28 +0000322 if (CGM.getCXXABI().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.
Reid Kleckner90633022013-06-19 15:20:38 +00001112 BaseCtorContinueBB =
1113 CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this, ClassDecl);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001114 assert(BaseCtorContinueBB);
1115 }
1116
1117 // Virtual base initializers first.
1118 for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
1119 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
1120 }
1121
1122 if (BaseCtorContinueBB) {
1123 // Complete object handler should continue to the remaining initializers.
1124 Builder.CreateBr(BaseCtorContinueBB);
1125 EmitBlock(BaseCtorContinueBB);
1126 }
1127
1128 // Then, non-virtual base initializers.
1129 for (; B != E && (*B)->isBaseInitializer(); B++) {
1130 assert(!(*B)->isBaseVirtual());
1131 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
Anders Carlsson607d0372009-12-24 22:46:43 +00001132 }
1133
Anders Carlsson603d6d12010-03-28 21:07:49 +00001134 InitializeVTablePointers(ClassDecl);
Anders Carlssona78fa2c2010-02-02 19:58:43 +00001135
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001136 // And finally, initialize class members.
Richard Smithc3bf52c2013-04-20 22:23:05 +00001137 FieldConstructionScope FCS(*this, CXXThisValue);
Lang Hames56c00c42013-02-17 07:22:09 +00001138 ConstructorMemcpyizer CM(*this, CD, Args);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001139 for (; B != E; B++) {
1140 CXXCtorInitializer *Member = (*B);
1141 assert(!Member->isBaseInitializer());
1142 assert(Member->isAnyMemberInitializer() &&
1143 "Delegating initializer on non-delegating constructor");
1144 CM.addMemberInitializer(Member);
1145 }
Lang Hames56c00c42013-02-17 07:22:09 +00001146 CM.finish();
Anders Carlsson607d0372009-12-24 22:46:43 +00001147}
1148
Anders Carlssonadf5dc32011-05-15 17:36:21 +00001149static bool
1150FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
1151
1152static bool
1153HasTrivialDestructorBody(ASTContext &Context,
1154 const CXXRecordDecl *BaseClassDecl,
1155 const CXXRecordDecl *MostDerivedClassDecl)
1156{
1157 // If the destructor is trivial we don't have to check anything else.
1158 if (BaseClassDecl->hasTrivialDestructor())
1159 return true;
1160
1161 if (!BaseClassDecl->getDestructor()->hasTrivialBody())
1162 return false;
1163
1164 // Check fields.
1165 for (CXXRecordDecl::field_iterator I = BaseClassDecl->field_begin(),
1166 E = BaseClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001167 const FieldDecl *Field = *I;
Anders Carlssonadf5dc32011-05-15 17:36:21 +00001168
1169 if (!FieldHasTrivialDestructorBody(Context, Field))
1170 return false;
1171 }
1172
1173 // Check non-virtual bases.
1174 for (CXXRecordDecl::base_class_const_iterator I =
1175 BaseClassDecl->bases_begin(), E = BaseClassDecl->bases_end();
1176 I != E; ++I) {
1177 if (I->isVirtual())
1178 continue;
1179
1180 const CXXRecordDecl *NonVirtualBase =
1181 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
1182 if (!HasTrivialDestructorBody(Context, NonVirtualBase,
1183 MostDerivedClassDecl))
1184 return false;
1185 }
1186
1187 if (BaseClassDecl == MostDerivedClassDecl) {
1188 // Check virtual bases.
1189 for (CXXRecordDecl::base_class_const_iterator I =
1190 BaseClassDecl->vbases_begin(), E = BaseClassDecl->vbases_end();
1191 I != E; ++I) {
1192 const CXXRecordDecl *VirtualBase =
1193 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
1194 if (!HasTrivialDestructorBody(Context, VirtualBase,
1195 MostDerivedClassDecl))
1196 return false;
1197 }
1198 }
1199
1200 return true;
1201}
1202
1203static bool
1204FieldHasTrivialDestructorBody(ASTContext &Context,
1205 const FieldDecl *Field)
1206{
1207 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
1208
1209 const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
1210 if (!RT)
1211 return true;
1212
1213 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1214 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
1215}
1216
Anders Carlssonffb945f2011-05-14 23:26:09 +00001217/// CanSkipVTablePointerInitialization - Check whether we need to initialize
1218/// any vtable pointers before calling this destructor.
1219static bool CanSkipVTablePointerInitialization(ASTContext &Context,
Anders Carlssone3d6cf22011-05-16 04:08:36 +00001220 const CXXDestructorDecl *Dtor) {
Anders Carlssonffb945f2011-05-14 23:26:09 +00001221 if (!Dtor->hasTrivialBody())
1222 return false;
1223
1224 // Check the fields.
1225 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1226 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1227 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001228 const FieldDecl *Field = *I;
Anders Carlssonffb945f2011-05-14 23:26:09 +00001229
Anders Carlssonadf5dc32011-05-15 17:36:21 +00001230 if (!FieldHasTrivialDestructorBody(Context, Field))
1231 return false;
Anders Carlssonffb945f2011-05-14 23:26:09 +00001232 }
1233
1234 return true;
1235}
1236
John McCall9fc6a772010-02-19 09:25:03 +00001237/// EmitDestructorBody - Emits the body of the current destructor.
1238void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
1239 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
1240 CXXDtorType DtorType = CurGD.getDtorType();
1241
John McCall50da2ca2010-07-21 05:30:47 +00001242 // The call to operator delete in a deleting destructor happens
1243 // outside of the function-try-block, which means it's always
1244 // possible to delegate the destructor body to the complete
1245 // destructor. Do so.
1246 if (DtorType == Dtor_Deleting) {
1247 EnterDtorCleanups(Dtor, Dtor_Deleting);
1248 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001249 /*Delegating=*/false, LoadCXXThis());
John McCall50da2ca2010-07-21 05:30:47 +00001250 PopCleanupBlock();
1251 return;
1252 }
1253
John McCall9fc6a772010-02-19 09:25:03 +00001254 Stmt *Body = Dtor->getBody();
1255
1256 // If the body is a function-try-block, enter the try before
John McCall50da2ca2010-07-21 05:30:47 +00001257 // anything else.
1258 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCall9fc6a772010-02-19 09:25:03 +00001259 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +00001260 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +00001261
John McCall50da2ca2010-07-21 05:30:47 +00001262 // Enter the epilogue cleanups.
1263 RunCleanupsScope DtorEpilogue(*this);
1264
John McCall9fc6a772010-02-19 09:25:03 +00001265 // If this is the complete variant, just invoke the base variant;
1266 // the epilogue will destruct the virtual bases. But we can't do
1267 // this optimization if the body is a function-try-block, because
1268 // we'd introduce *two* handler blocks.
John McCall50da2ca2010-07-21 05:30:47 +00001269 switch (DtorType) {
1270 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
1271
1272 case Dtor_Complete:
1273 // Enter the cleanup scopes for virtual bases.
1274 EnterDtorCleanups(Dtor, Dtor_Complete);
1275
John McCallb8b2c9d2013-01-25 22:30:49 +00001276 if (!isTryBody &&
John McCall64aa4b32013-04-16 22:48:15 +00001277 CGM.getTarget().getCXXABI().hasDestructorVariants()) {
John McCall50da2ca2010-07-21 05:30:47 +00001278 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001279 /*Delegating=*/false, LoadCXXThis());
John McCall50da2ca2010-07-21 05:30:47 +00001280 break;
1281 }
1282 // Fallthrough: act like we're in the base variant.
John McCall9fc6a772010-02-19 09:25:03 +00001283
John McCall50da2ca2010-07-21 05:30:47 +00001284 case Dtor_Base:
1285 // Enter the cleanup scopes for fields and non-virtual bases.
1286 EnterDtorCleanups(Dtor, Dtor_Base);
1287
1288 // Initialize the vtable pointers before entering the body.
Anders Carlssonffb945f2011-05-14 23:26:09 +00001289 if (!CanSkipVTablePointerInitialization(getContext(), Dtor))
1290 InitializeVTablePointers(Dtor->getParent());
John McCall50da2ca2010-07-21 05:30:47 +00001291
1292 if (isTryBody)
1293 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
1294 else if (Body)
1295 EmitStmt(Body);
1296 else {
1297 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
1298 // nothing to do besides what's in the epilogue
1299 }
Fariborz Jahanian5abec142011-02-02 23:12:46 +00001300 // -fapple-kext must inline any call to this dtor into
1301 // the caller's body.
Richard Smith7edf9e32012-11-01 22:30:59 +00001302 if (getLangOpts().AppleKext)
Bill Wendling72390b32012-12-20 19:27:06 +00001303 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
John McCall50da2ca2010-07-21 05:30:47 +00001304 break;
John McCall9fc6a772010-02-19 09:25:03 +00001305 }
1306
John McCall50da2ca2010-07-21 05:30:47 +00001307 // Jump out through the epilogue cleanups.
1308 DtorEpilogue.ForceCleanup();
John McCall9fc6a772010-02-19 09:25:03 +00001309
1310 // Exit the try if applicable.
1311 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +00001312 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +00001313}
1314
Lang Hames56c00c42013-02-17 07:22:09 +00001315void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) {
1316 const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
1317 const Stmt *RootS = AssignOp->getBody();
1318 assert(isa<CompoundStmt>(RootS) &&
1319 "Body of an implicit assignment operator should be compound stmt.");
1320 const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
1321
1322 LexicalScope Scope(*this, RootCS->getSourceRange());
1323
1324 AssignmentMemcpyizer AM(*this, AssignOp, Args);
1325 for (CompoundStmt::const_body_iterator I = RootCS->body_begin(),
1326 E = RootCS->body_end();
1327 I != E; ++I) {
1328 AM.emitAssignment(*I);
1329 }
1330 AM.finish();
1331}
1332
John McCall50da2ca2010-07-21 05:30:47 +00001333namespace {
1334 /// Call the operator delete associated with the current destructor.
John McCall1f0fca52010-07-21 07:22:38 +00001335 struct CallDtorDelete : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +00001336 CallDtorDelete() {}
1337
John McCallad346f42011-07-12 20:27:29 +00001338 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall50da2ca2010-07-21 05:30:47 +00001339 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1340 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1341 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1342 CGF.getContext().getTagDeclType(ClassDecl));
1343 }
1344 };
1345
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +00001346 struct CallDtorDeleteConditional : EHScopeStack::Cleanup {
1347 llvm::Value *ShouldDeleteCondition;
1348 public:
1349 CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
1350 : ShouldDeleteCondition(ShouldDeleteCondition) {
1351 assert(ShouldDeleteCondition != NULL);
1352 }
1353
1354 void Emit(CodeGenFunction &CGF, Flags flags) {
1355 llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
1356 llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
1357 llvm::Value *ShouldCallDelete
1358 = CGF.Builder.CreateIsNull(ShouldDeleteCondition);
1359 CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
1360
1361 CGF.EmitBlock(callDeleteBB);
1362 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1363 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1364 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1365 CGF.getContext().getTagDeclType(ClassDecl));
1366 CGF.Builder.CreateBr(continueBB);
1367
1368 CGF.EmitBlock(continueBB);
1369 }
1370 };
1371
John McCall9928c482011-07-12 16:41:08 +00001372 class DestroyField : public EHScopeStack::Cleanup {
1373 const FieldDecl *field;
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001374 CodeGenFunction::Destroyer *destroyer;
John McCall9928c482011-07-12 16:41:08 +00001375 bool useEHCleanupForArray;
John McCall50da2ca2010-07-21 05:30:47 +00001376
John McCall9928c482011-07-12 16:41:08 +00001377 public:
1378 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
1379 bool useEHCleanupForArray)
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001380 : field(field), destroyer(destroyer),
John McCall9928c482011-07-12 16:41:08 +00001381 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall50da2ca2010-07-21 05:30:47 +00001382
John McCallad346f42011-07-12 20:27:29 +00001383 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall9928c482011-07-12 16:41:08 +00001384 // Find the address of the field.
1385 llvm::Value *thisValue = CGF.LoadCXXThis();
Eli Friedman377ecc72012-04-16 03:54:45 +00001386 QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
1387 LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
1388 LValue LV = CGF.EmitLValueForField(ThisLV, field);
John McCall9928c482011-07-12 16:41:08 +00001389 assert(LV.isSimple());
1390
1391 CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
John McCallad346f42011-07-12 20:27:29 +00001392 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCall50da2ca2010-07-21 05:30:47 +00001393 }
1394 };
1395}
1396
Anders Carlsson607d0372009-12-24 22:46:43 +00001397/// EmitDtorEpilogue - Emit all code that comes at the end of class's
1398/// destructor. This is to call destructors on members and base classes
1399/// in reverse order of their construction.
John McCall50da2ca2010-07-21 05:30:47 +00001400void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
1401 CXXDtorType DtorType) {
Anders Carlsson607d0372009-12-24 22:46:43 +00001402 assert(!DD->isTrivial() &&
1403 "Should not emit dtor epilogue for trivial dtor!");
1404
John McCall50da2ca2010-07-21 05:30:47 +00001405 // The deleting-destructor phase just needs to call the appropriate
1406 // operator delete that Sema picked up.
John McCall3b477332010-02-18 19:59:28 +00001407 if (DtorType == Dtor_Deleting) {
1408 assert(DD->getOperatorDelete() &&
1409 "operator delete missing - EmitDtorEpilogue");
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +00001410 if (CXXStructorImplicitParamValue) {
1411 // If there is an implicit param to the deleting dtor, it's a boolean
1412 // telling whether we should call delete at the end of the dtor.
1413 EHStack.pushCleanup<CallDtorDeleteConditional>(
1414 NormalAndEHCleanup, CXXStructorImplicitParamValue);
1415 } else {
1416 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
1417 }
John McCall3b477332010-02-18 19:59:28 +00001418 return;
1419 }
1420
John McCall50da2ca2010-07-21 05:30:47 +00001421 const CXXRecordDecl *ClassDecl = DD->getParent();
1422
Richard Smith416f63e2011-09-18 12:11:43 +00001423 // Unions have no bases and do not call field destructors.
1424 if (ClassDecl->isUnion())
1425 return;
1426
John McCall50da2ca2010-07-21 05:30:47 +00001427 // The complete-destructor phase just destructs all the virtual bases.
John McCall3b477332010-02-18 19:59:28 +00001428 if (DtorType == Dtor_Complete) {
John McCall50da2ca2010-07-21 05:30:47 +00001429
1430 // We push them in the forward order so that they'll be popped in
1431 // the reverse order.
1432 for (CXXRecordDecl::base_class_const_iterator I =
1433 ClassDecl->vbases_begin(), E = ClassDecl->vbases_end();
John McCall3b477332010-02-18 19:59:28 +00001434 I != E; ++I) {
1435 const CXXBaseSpecifier &Base = *I;
1436 CXXRecordDecl *BaseClassDecl
1437 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1438
1439 // Ignore trivial destructors.
1440 if (BaseClassDecl->hasTrivialDestructor())
1441 continue;
John McCall50da2ca2010-07-21 05:30:47 +00001442
John McCall1f0fca52010-07-21 07:22:38 +00001443 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1444 BaseClassDecl,
1445 /*BaseIsVirtual*/ true);
John McCall3b477332010-02-18 19:59:28 +00001446 }
John McCall50da2ca2010-07-21 05:30:47 +00001447
John McCall3b477332010-02-18 19:59:28 +00001448 return;
1449 }
1450
1451 assert(DtorType == Dtor_Base);
John McCall50da2ca2010-07-21 05:30:47 +00001452
1453 // Destroy non-virtual bases.
1454 for (CXXRecordDecl::base_class_const_iterator I =
1455 ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) {
1456 const CXXBaseSpecifier &Base = *I;
1457
1458 // Ignore virtual bases.
1459 if (Base.isVirtual())
1460 continue;
1461
1462 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
1463
1464 // Ignore trivial destructors.
1465 if (BaseClassDecl->hasTrivialDestructor())
1466 continue;
John McCall3b477332010-02-18 19:59:28 +00001467
John McCall1f0fca52010-07-21 07:22:38 +00001468 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1469 BaseClassDecl,
1470 /*BaseIsVirtual*/ false);
John McCall50da2ca2010-07-21 05:30:47 +00001471 }
1472
1473 // Destroy direct fields.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001474 SmallVector<const FieldDecl *, 16> FieldDecls;
Anders Carlsson607d0372009-12-24 22:46:43 +00001475 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1476 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001477 const FieldDecl *field = *I;
John McCall9928c482011-07-12 16:41:08 +00001478 QualType type = field->getType();
1479 QualType::DestructionKind dtorKind = type.isDestructedType();
1480 if (!dtorKind) continue;
John McCall50da2ca2010-07-21 05:30:47 +00001481
Richard Smith9a561d52012-02-26 09:11:52 +00001482 // Anonymous union members do not have their destructors called.
1483 const RecordType *RT = type->getAsUnionType();
1484 if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
1485
John McCall9928c482011-07-12 16:41:08 +00001486 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1487 EHStack.pushCleanup<DestroyField>(cleanupKind, field,
1488 getDestroyer(dtorKind),
1489 cleanupKind & EHCleanup);
Anders Carlsson607d0372009-12-24 22:46:43 +00001490 }
Anders Carlsson607d0372009-12-24 22:46:43 +00001491}
1492
John McCallc3c07662011-07-13 06:10:41 +00001493/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1494/// constructor for each of several members of an array.
Douglas Gregor59174c02010-07-21 01:10:17 +00001495///
John McCallc3c07662011-07-13 06:10:41 +00001496/// \param ctor the constructor to call for each element
John McCallc3c07662011-07-13 06:10:41 +00001497/// \param arrayType the type of the array to initialize
1498/// \param arrayBegin an arrayType*
1499/// \param zeroInitialize true if each element should be
1500/// zero-initialized before it is constructed
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001501void
John McCallc3c07662011-07-13 06:10:41 +00001502CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1503 const ConstantArrayType *arrayType,
1504 llvm::Value *arrayBegin,
1505 CallExpr::const_arg_iterator argBegin,
1506 CallExpr::const_arg_iterator argEnd,
1507 bool zeroInitialize) {
1508 QualType elementType;
1509 llvm::Value *numElements =
1510 emitArrayLength(arrayType, elementType, arrayBegin);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001511
John McCallc3c07662011-07-13 06:10:41 +00001512 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin,
1513 argBegin, argEnd, zeroInitialize);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001514}
1515
John McCallc3c07662011-07-13 06:10:41 +00001516/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1517/// constructor for each of several members of an array.
1518///
1519/// \param ctor the constructor to call for each element
1520/// \param numElements the number of elements in the array;
John McCalldd376ca2011-07-13 07:37:11 +00001521/// may be zero
John McCallc3c07662011-07-13 06:10:41 +00001522/// \param arrayBegin a T*, where T is the type constructed by ctor
1523/// \param zeroInitialize true if each element should be
1524/// zero-initialized before it is constructed
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001525void
John McCallc3c07662011-07-13 06:10:41 +00001526CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1527 llvm::Value *numElements,
1528 llvm::Value *arrayBegin,
1529 CallExpr::const_arg_iterator argBegin,
1530 CallExpr::const_arg_iterator argEnd,
1531 bool zeroInitialize) {
John McCalldd376ca2011-07-13 07:37:11 +00001532
1533 // It's legal for numElements to be zero. This can happen both
1534 // dynamically, because x can be zero in 'new A[x]', and statically,
1535 // because of GCC extensions that permit zero-length arrays. There
1536 // are probably legitimate places where we could assume that this
1537 // doesn't happen, but it's not clear that it's worth it.
1538 llvm::BranchInst *zeroCheckBranch = 0;
1539
1540 // Optimize for a constant count.
1541 llvm::ConstantInt *constantCount
1542 = dyn_cast<llvm::ConstantInt>(numElements);
1543 if (constantCount) {
1544 // Just skip out if the constant count is zero.
1545 if (constantCount->isZero()) return;
1546
1547 // Otherwise, emit the check.
1548 } else {
1549 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1550 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1551 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1552 EmitBlock(loopBB);
1553 }
1554
John McCallc3c07662011-07-13 06:10:41 +00001555 // Find the end of the array.
1556 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1557 "arrayctor.end");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001558
John McCallc3c07662011-07-13 06:10:41 +00001559 // Enter the loop, setting up a phi for the current location to initialize.
1560 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1561 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1562 EmitBlock(loopBB);
1563 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1564 "arrayctor.cur");
1565 cur->addIncoming(arrayBegin, entryBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001566
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001567 // Inside the loop body, emit the constructor call on the array element.
John McCallc3c07662011-07-13 06:10:41 +00001568
1569 QualType type = getContext().getTypeDeclType(ctor->getParent());
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001570
Douglas Gregor59174c02010-07-21 01:10:17 +00001571 // Zero initialize the storage, if requested.
John McCallc3c07662011-07-13 06:10:41 +00001572 if (zeroInitialize)
1573 EmitNullInitialization(cur, type);
Douglas Gregor59174c02010-07-21 01:10:17 +00001574
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001575 // C++ [class.temporary]p4:
1576 // There are two contexts in which temporaries are destroyed at a different
1577 // point than the end of the full-expression. The first context is when a
1578 // default constructor is called to initialize an element of an array.
1579 // If the constructor has one or more default arguments, the destruction of
1580 // every temporary created in a default argument expression is sequenced
1581 // before the construction of the next array element, if any.
1582
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001583 {
John McCallf1549f62010-07-06 01:34:17 +00001584 RunCleanupsScope Scope(*this);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001585
John McCallc3c07662011-07-13 06:10:41 +00001586 // Evaluate the constructor and its arguments in a regular
1587 // partial-destroy cleanup.
David Blaikie4e4d0842012-03-11 07:00:24 +00001588 if (getLangOpts().Exceptions &&
John McCallc3c07662011-07-13 06:10:41 +00001589 !ctor->getParent()->hasTrivialDestructor()) {
1590 Destroyer *destroyer = destroyCXXObject;
1591 pushRegularPartialArrayCleanup(arrayBegin, cur, type, *destroyer);
1592 }
1593
1594 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/ false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001595 /*Delegating=*/false, cur, argBegin, argEnd);
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001596 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001597
John McCallc3c07662011-07-13 06:10:41 +00001598 // Go to the next element.
1599 llvm::Value *next =
1600 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
1601 "arrayctor.next");
1602 cur->addIncoming(next, Builder.GetInsertBlock());
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001603
John McCallc3c07662011-07-13 06:10:41 +00001604 // Check whether that's the end of the loop.
1605 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
1606 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
1607 Builder.CreateCondBr(done, contBB, loopBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001608
John McCalldd376ca2011-07-13 07:37:11 +00001609 // Patch the earlier check to skip over the loop.
1610 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
1611
John McCallc3c07662011-07-13 06:10:41 +00001612 EmitBlock(contBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001613}
1614
John McCallbdc4d802011-07-09 01:37:26 +00001615void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
1616 llvm::Value *addr,
1617 QualType type) {
1618 const RecordType *rtype = type->castAs<RecordType>();
1619 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
1620 const CXXDestructorDecl *dtor = record->getDestructor();
1621 assert(!dtor->isTrivial());
1622 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001623 /*Delegating=*/false, addr);
John McCallbdc4d802011-07-09 01:37:26 +00001624}
1625
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001626void
1627CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
Anders Carlsson155ed4a2010-05-02 23:20:53 +00001628 CXXCtorType Type, bool ForVirtualBase,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001629 bool Delegating,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001630 llvm::Value *This,
1631 CallExpr::const_arg_iterator ArgBeg,
1632 CallExpr::const_arg_iterator ArgEnd) {
Devang Patel3ee36af2011-02-22 20:55:26 +00001633
1634 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonov3a70cd62012-04-27 07:24:20 +00001635 if (DI &&
Douglas Gregor4cdad312012-10-23 20:05:01 +00001636 CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::LimitedDebugInfo) {
Eric Christopheraf790882012-02-01 21:44:56 +00001637 // If debug info for this class has not been emitted then this is the
1638 // right time to do so.
Devang Patel3ee36af2011-02-22 20:55:26 +00001639 const CXXRecordDecl *Parent = D->getParent();
1640 DI->getOrCreateRecordType(CGM.getContext().getTypeDeclType(Parent),
1641 Parent->getLocation());
1642 }
1643
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001644 // If this is a trivial constructor, just emit what's needed.
John McCall8b6bbeb2010-02-06 00:25:16 +00001645 if (D->isTrivial()) {
1646 if (ArgBeg == ArgEnd) {
1647 // Trivial default constructor, no codegen required.
1648 assert(D->isDefaultConstructor() &&
1649 "trivial 0-arg ctor not a default ctor");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001650 return;
1651 }
John McCall8b6bbeb2010-02-06 00:25:16 +00001652
1653 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001654 assert(D->isCopyOrMoveConstructor() &&
1655 "trivial 1-arg ctor not a copy/move ctor");
John McCall8b6bbeb2010-02-06 00:25:16 +00001656
John McCall8b6bbeb2010-02-06 00:25:16 +00001657 const Expr *E = (*ArgBeg);
1658 QualType Ty = E->getType();
1659 llvm::Value *Src = EmitLValue(E).getAddress();
1660 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001661 return;
1662 }
1663
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001664 // Non-trivial constructors are handled in an ABI-specific manner.
Stephen Lin3b50e8d2013-06-30 20:40:16 +00001665 CGM.getCXXABI().EmitConstructorCall(*this, D, Type, ForVirtualBase,
1666 Delegating, 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
Peter Collingbournee1e35f72013-06-28 20:45:28 +00001742 if (CGM.getCXXABI().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
Peter Collingbournee1e35f72013-06-28 20:45:28 +00001868 bool NeedsVTTParam = CGM.getCXXABI().NeedsVTTParameter(CurGD);
1869
Anders Carlssonc83f1062010-03-29 01:08:49 +00001870 // Check if we need to use a vtable from the VTT.
Peter Collingbournee1e35f72013-06-28 20:45:28 +00001871 if (NeedsVTTParam && (RD->getNumVBases() || NearestVBase)) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001872 // Get the secondary vpointer index.
1873 uint64_t VirtualPointerIndex =
1874 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1875
1876 /// Load the VTT.
1877 llvm::Value *VTT = LoadCXXVTT();
1878 if (VirtualPointerIndex)
1879 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1880
1881 // And load the address point from the VTT.
1882 VTableAddressPoint = Builder.CreateLoad(VTT);
1883 } else {
Peter Collingbourne84fcc482011-09-26 01:56:41 +00001884 uint64_t AddressPoint =
Peter Collingbournee09cdf42011-09-26 01:56:50 +00001885 CGM.getVTableContext().getVTableLayout(VTableClass).getAddressPoint(Base);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001886 VTableAddressPoint =
Anders Carlssond103f9f2010-03-28 19:40:00 +00001887 Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001888 }
Anders Carlssond103f9f2010-03-28 19:40:00 +00001889
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001890 // Compute where to store the address point.
Anders Carlsson8246cc72010-05-03 00:29:58 +00001891 llvm::Value *VirtualOffset = 0;
Ken Dyck9a8ad9b2011-03-23 00:45:26 +00001892 CharUnits NonVirtualOffset = CharUnits::Zero();
Anders Carlsson3e79c302010-04-20 18:05:10 +00001893
Peter Collingbournee1e35f72013-06-28 20:45:28 +00001894 if (NeedsVTTParam && NearestVBase) {
Anders Carlsson3e79c302010-04-20 18:05:10 +00001895 // We need to use the virtual base offset offset because the virtual base
1896 // might have a different offset in the most derived class.
Reid Klecknerb0f533e2013-05-29 18:02:47 +00001897 VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(*this,
1898 LoadCXXThis(),
1899 VTableClass,
1900 NearestVBase);
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001901 NonVirtualOffset = OffsetFromNearestVBase;
Anders Carlsson3e79c302010-04-20 18:05:10 +00001902 } else {
Anders Carlsson8246cc72010-05-03 00:29:58 +00001903 // We can just use the base offset in the complete class.
Ken Dyck4230d522011-03-24 01:21:01 +00001904 NonVirtualOffset = Base.getBaseOffset();
Anders Carlsson3e79c302010-04-20 18:05:10 +00001905 }
Anders Carlsson8246cc72010-05-03 00:29:58 +00001906
1907 // Apply the offsets.
1908 llvm::Value *VTableField = LoadCXXThis();
1909
Ken Dyck9a8ad9b2011-03-23 00:45:26 +00001910 if (!NonVirtualOffset.isZero() || VirtualOffset)
Anders Carlsson8246cc72010-05-03 00:29:58 +00001911 VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
1912 NonVirtualOffset,
1913 VirtualOffset);
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001914
Anders Carlssond103f9f2010-03-28 19:40:00 +00001915 // Finally, store the address point.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001916 llvm::Type *AddressPointPtrTy =
Anders Carlssond103f9f2010-03-28 19:40:00 +00001917 VTableAddressPoint->getType()->getPointerTo();
1918 VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
Kostya Serebryany8cb4a072012-03-26 17:03:51 +00001919 llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
1920 CGM.DecorateInstruction(Store, CGM.getTBAAInfoForVTablePtr());
Anders Carlssond103f9f2010-03-28 19:40:00 +00001921}
1922
Anders Carlsson603d6d12010-03-28 21:07:49 +00001923void
1924CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001925 const CXXRecordDecl *NearestVBase,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001926 CharUnits OffsetFromNearestVBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001927 bool BaseIsNonVirtualPrimaryBase,
1928 llvm::Constant *VTable,
1929 const CXXRecordDecl *VTableClass,
1930 VisitedVirtualBasesSetTy& VBases) {
1931 // If this base is a non-virtual primary base the address point has already
1932 // been set.
1933 if (!BaseIsNonVirtualPrimaryBase) {
1934 // Initialize the vtable pointer for this base.
Anders Carlsson42358402010-05-03 00:07:07 +00001935 InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
1936 VTable, VTableClass);
Anders Carlsson603d6d12010-03-28 21:07:49 +00001937 }
1938
1939 const CXXRecordDecl *RD = Base.getBase();
1940
1941 // Traverse bases.
1942 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1943 E = RD->bases_end(); I != E; ++I) {
1944 CXXRecordDecl *BaseDecl
1945 = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1946
1947 // Ignore classes without a vtable.
1948 if (!BaseDecl->isDynamicClass())
1949 continue;
1950
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001951 CharUnits BaseOffset;
1952 CharUnits BaseOffsetFromNearestVBase;
Anders Carlsson14da9de2010-03-29 01:16:41 +00001953 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001954
1955 if (I->isVirtual()) {
1956 // Check if we've visited this virtual base before.
1957 if (!VBases.insert(BaseDecl))
1958 continue;
1959
1960 const ASTRecordLayout &Layout =
1961 getContext().getASTRecordLayout(VTableClass);
1962
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001963 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
1964 BaseOffsetFromNearestVBase = CharUnits::Zero();
Anders Carlsson14da9de2010-03-29 01:16:41 +00001965 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001966 } else {
1967 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1968
Ken Dyck4230d522011-03-24 01:21:01 +00001969 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson42358402010-05-03 00:07:07 +00001970 BaseOffsetFromNearestVBase =
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001971 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson14da9de2010-03-29 01:16:41 +00001972 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001973 }
1974
Ken Dyck4230d522011-03-24 01:21:01 +00001975 InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001976 I->isVirtual() ? BaseDecl : NearestVBase,
Anders Carlsson42358402010-05-03 00:07:07 +00001977 BaseOffsetFromNearestVBase,
Anders Carlsson14da9de2010-03-29 01:16:41 +00001978 BaseDeclIsNonVirtualPrimaryBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001979 VTable, VTableClass, VBases);
1980 }
1981}
1982
1983void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
1984 // Ignore classes without a vtable.
Anders Carlsson07036902010-03-26 04:39:42 +00001985 if (!RD->isDynamicClass())
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001986 return;
1987
Anders Carlsson07036902010-03-26 04:39:42 +00001988 // Get the VTable.
1989 llvm::Constant *VTable = CGM.getVTables().GetAddrOfVTable(RD);
Anders Carlsson5c6c1d92010-03-24 03:57:14 +00001990
Anders Carlsson603d6d12010-03-28 21:07:49 +00001991 // Initialize the vtable pointers for this class and all of its bases.
1992 VisitedVirtualBasesSetTy VBases;
Ken Dyck4230d522011-03-24 01:21:01 +00001993 InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()),
1994 /*NearestVBase=*/0,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001995 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
Anders Carlsson603d6d12010-03-28 21:07:49 +00001996 /*BaseIsNonVirtualPrimaryBase=*/false,
1997 VTable, RD, VBases);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001998}
Dan Gohman043fb9a2010-10-26 18:44:08 +00001999
2000llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
Chris Lattner2acc6e32011-07-18 04:24:23 +00002001 llvm::Type *Ty) {
Dan Gohman043fb9a2010-10-26 18:44:08 +00002002 llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
Kostya Serebryany8cb4a072012-03-26 17:03:51 +00002003 llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
2004 CGM.DecorateInstruction(VTable, CGM.getTBAAInfoForVTablePtr());
2005 return VTable;
Dan Gohman043fb9a2010-10-26 18:44:08 +00002006}
Anders Carlssona2447e02011-05-08 20:32:23 +00002007
2008static const CXXRecordDecl *getMostDerivedClassDecl(const Expr *Base) {
2009 const Expr *E = Base;
2010
2011 while (true) {
2012 E = E->IgnoreParens();
2013 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
2014 if (CE->getCastKind() == CK_DerivedToBase ||
2015 CE->getCastKind() == CK_UncheckedDerivedToBase ||
2016 CE->getCastKind() == CK_NoOp) {
2017 E = CE->getSubExpr();
2018 continue;
2019 }
2020 }
2021
2022 break;
2023 }
2024
2025 QualType DerivedType = E->getType();
2026 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
2027 DerivedType = PTy->getPointeeType();
2028
2029 return cast<CXXRecordDecl>(DerivedType->castAs<RecordType>()->getDecl());
2030}
2031
2032// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
2033// quite what we want.
2034static const Expr *skipNoOpCastsAndParens(const Expr *E) {
2035 while (true) {
2036 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
2037 E = PE->getSubExpr();
2038 continue;
2039 }
2040
2041 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
2042 if (CE->getCastKind() == CK_NoOp) {
2043 E = CE->getSubExpr();
2044 continue;
2045 }
2046 }
2047 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2048 if (UO->getOpcode() == UO_Extension) {
2049 E = UO->getSubExpr();
2050 continue;
2051 }
2052 }
2053 return E;
2054 }
2055}
2056
2057/// canDevirtualizeMemberFunctionCall - Checks whether the given virtual member
2058/// function call on the given expr can be devirtualized.
Anders Carlssona2447e02011-05-08 20:32:23 +00002059static bool canDevirtualizeMemberFunctionCall(const Expr *Base,
2060 const CXXMethodDecl *MD) {
2061 // If the most derived class is marked final, we know that no subclass can
2062 // override this member function and so we can devirtualize it. For example:
2063 //
2064 // struct A { virtual void f(); }
2065 // struct B final : A { };
2066 //
2067 // void f(B *b) {
2068 // b->f();
2069 // }
2070 //
2071 const CXXRecordDecl *MostDerivedClassDecl = getMostDerivedClassDecl(Base);
2072 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
2073 return true;
2074
2075 // If the member function is marked 'final', we know that it can't be
2076 // overridden and can therefore devirtualize it.
2077 if (MD->hasAttr<FinalAttr>())
2078 return true;
2079
2080 // Similarly, if the class itself is marked 'final' it can't be overridden
2081 // and we can therefore devirtualize the member function call.
2082 if (MD->getParent()->hasAttr<FinalAttr>())
2083 return true;
2084
2085 Base = skipNoOpCastsAndParens(Base);
2086 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
2087 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
2088 // This is a record decl. We know the type and can devirtualize it.
2089 return VD->getType()->isRecordType();
2090 }
2091
2092 return false;
2093 }
2094
2095 // We can always devirtualize calls on temporary object expressions.
2096 if (isa<CXXConstructExpr>(Base))
2097 return true;
2098
2099 // And calls on bound temporaries.
2100 if (isa<CXXBindTemporaryExpr>(Base))
2101 return true;
2102
2103 // Check if this is a call expr that returns a record type.
2104 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
2105 return CE->getCallReturnType()->isRecordType();
2106
2107 // We can't devirtualize the call.
2108 return false;
2109}
2110
2111static bool UseVirtualCall(ASTContext &Context,
2112 const CXXOperatorCallExpr *CE,
2113 const CXXMethodDecl *MD) {
2114 if (!MD->isVirtual())
2115 return false;
2116
2117 // When building with -fapple-kext, all calls must go through the vtable since
2118 // the kernel linker can do runtime patching of vtables.
David Blaikie4e4d0842012-03-11 07:00:24 +00002119 if (Context.getLangOpts().AppleKext)
Anders Carlssona2447e02011-05-08 20:32:23 +00002120 return true;
2121
2122 return !canDevirtualizeMemberFunctionCall(CE->getArg(0), MD);
2123}
2124
2125llvm::Value *
2126CodeGenFunction::EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E,
2127 const CXXMethodDecl *MD,
2128 llvm::Value *This) {
John McCallde5d3c72012-02-17 03:33:10 +00002129 llvm::FunctionType *fnType =
2130 CGM.getTypes().GetFunctionType(
2131 CGM.getTypes().arrangeCXXMethodDeclaration(MD));
Anders Carlssona2447e02011-05-08 20:32:23 +00002132
2133 if (UseVirtualCall(getContext(), E, MD))
John McCallde5d3c72012-02-17 03:33:10 +00002134 return BuildVirtualCall(MD, This, fnType);
Anders Carlssona2447e02011-05-08 20:32:23 +00002135
John McCallde5d3c72012-02-17 03:33:10 +00002136 return CGM.GetAddrOfFunction(MD, fnType);
Anders Carlssona2447e02011-05-08 20:32:23 +00002137}
Eli Friedmanbd89f8c2012-02-16 01:37:33 +00002138
John McCall0f3d0972012-07-07 06:41:13 +00002139void CodeGenFunction::EmitForwardingCallToLambda(const CXXRecordDecl *lambda,
2140 CallArgList &callArgs) {
Eli Friedman64bee652012-02-25 02:48:22 +00002141 // Lookup the call operator
John McCall0f3d0972012-07-07 06:41:13 +00002142 DeclarationName operatorName
Eli Friedman21f6ed92012-02-16 03:47:28 +00002143 = getContext().DeclarationNames.getCXXOperatorName(OO_Call);
John McCall0f3d0972012-07-07 06:41:13 +00002144 CXXMethodDecl *callOperator =
David Blaikie3bc93e32012-12-19 00:45:41 +00002145 cast<CXXMethodDecl>(lambda->lookup(operatorName).front());
Eli Friedman21f6ed92012-02-16 03:47:28 +00002146
Eli Friedman21f6ed92012-02-16 03:47:28 +00002147 // Get the address of the call operator.
John McCall0f3d0972012-07-07 06:41:13 +00002148 const CGFunctionInfo &calleeFnInfo =
2149 CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
2150 llvm::Value *callee =
2151 CGM.GetAddrOfFunction(GlobalDecl(callOperator),
2152 CGM.getTypes().GetFunctionType(calleeFnInfo));
Eli Friedman21f6ed92012-02-16 03:47:28 +00002153
John McCall0f3d0972012-07-07 06:41:13 +00002154 // Prepare the return slot.
2155 const FunctionProtoType *FPT =
2156 callOperator->getType()->castAs<FunctionProtoType>();
2157 QualType resultType = FPT->getResultType();
2158 ReturnValueSlot returnSlot;
2159 if (!resultType->isVoidType() &&
2160 calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
John McCall9d232c82013-03-07 21:37:08 +00002161 !hasScalarEvaluationKind(calleeFnInfo.getReturnType()))
John McCall0f3d0972012-07-07 06:41:13 +00002162 returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
2163
2164 // We don't need to separately arrange the call arguments because
2165 // the call can't be variadic anyway --- it's impossible to forward
2166 // variadic arguments.
Eli Friedman21f6ed92012-02-16 03:47:28 +00002167
2168 // Now emit our call.
John McCall0f3d0972012-07-07 06:41:13 +00002169 RValue RV = EmitCall(calleeFnInfo, callee, returnSlot,
2170 callArgs, callOperator);
Eli Friedman21f6ed92012-02-16 03:47:28 +00002171
John McCall0f3d0972012-07-07 06:41:13 +00002172 // If necessary, copy the returned value into the slot.
2173 if (!resultType->isVoidType() && returnSlot.isNull())
2174 EmitReturnOfRValue(RV, resultType);
Eli Friedman50f089a2012-12-13 23:37:17 +00002175 else
2176 EmitBranchThroughCleanup(ReturnBlock);
Eli Friedman21f6ed92012-02-16 03:47:28 +00002177}
2178
Eli Friedman64bee652012-02-25 02:48:22 +00002179void CodeGenFunction::EmitLambdaBlockInvokeBody() {
2180 const BlockDecl *BD = BlockInfo->getBlockDecl();
2181 const VarDecl *variable = BD->capture_begin()->getVariable();
2182 const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
2183
2184 // Start building arguments for forwarding call
2185 CallArgList CallArgs;
2186
2187 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2188 llvm::Value *ThisPtr = GetAddrOfBlockDecl(variable, false);
2189 CallArgs.add(RValue::get(ThisPtr), ThisType);
2190
2191 // Add the rest of the parameters.
2192 for (BlockDecl::param_const_iterator I = BD->param_begin(),
2193 E = BD->param_end(); I != E; ++I) {
2194 ParmVarDecl *param = *I;
2195 EmitDelegateCallArg(CallArgs, param);
2196 }
2197
2198 EmitForwardingCallToLambda(Lambda, CallArgs);
2199}
2200
2201void CodeGenFunction::EmitLambdaToBlockPointerBody(FunctionArgList &Args) {
John McCallf5ebf9b2013-05-03 07:33:41 +00002202 if (cast<CXXMethodDecl>(CurCodeDecl)->isVariadic()) {
Eli Friedman64bee652012-02-25 02:48:22 +00002203 // FIXME: Making this work correctly is nasty because it requires either
2204 // cloning the body of the call operator or making the call operator forward.
John McCallf5ebf9b2013-05-03 07:33:41 +00002205 CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function");
Eli Friedman64bee652012-02-25 02:48:22 +00002206 return;
2207 }
2208
Eli Friedman64bee652012-02-25 02:48:22 +00002209 EmitFunctionBody(Args);
Eli Friedman64bee652012-02-25 02:48:22 +00002210}
2211
2212void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
2213 const CXXRecordDecl *Lambda = MD->getParent();
2214
2215 // Start building arguments for forwarding call
2216 CallArgList CallArgs;
2217
2218 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2219 llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
2220 CallArgs.add(RValue::get(ThisPtr), ThisType);
2221
2222 // Add the rest of the parameters.
2223 for (FunctionDecl::param_const_iterator I = MD->param_begin(),
2224 E = MD->param_end(); I != E; ++I) {
2225 ParmVarDecl *param = *I;
2226 EmitDelegateCallArg(CallArgs, param);
2227 }
2228
2229 EmitForwardingCallToLambda(Lambda, CallArgs);
2230}
2231
Douglas Gregor27dd7d92012-02-17 03:02:34 +00002232void CodeGenFunction::EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD) {
2233 if (MD->isVariadic()) {
Eli Friedman21f6ed92012-02-16 03:47:28 +00002234 // FIXME: Making this work correctly is nasty because it requires either
2235 // cloning the body of the call operator or making the call operator forward.
2236 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
Eli Friedman64bee652012-02-25 02:48:22 +00002237 return;
Eli Friedman21f6ed92012-02-16 03:47:28 +00002238 }
2239
Douglas Gregor27dd7d92012-02-17 03:02:34 +00002240 EmitLambdaDelegatingInvokeBody(MD);
Eli Friedmanbd89f8c2012-02-16 01:37:33 +00002241}