blob: 0611ed7834fcf4cb75cf02f898abfcf7d0605d83 [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"
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000016#include "CodeGenFunction.h"
Anders Carlsson2f1986b2009-10-06 22:43:30 +000017#include "clang/AST/CXXInheritance.h"
John McCall7e1dff72010-09-17 02:31:44 +000018#include "clang/AST/EvaluatedExprVisitor.h"
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000019#include "clang/AST/RecordLayout.h"
John McCall9fc6a772010-02-19 09:25:03 +000020#include "clang/AST/StmtCXX.h"
Devang Patel3ee36af2011-02-22 20:55:26 +000021#include "clang/Frontend/CodeGenOptions.h"
Anders Carlsson2f1986b2009-10-06 22:43:30 +000022
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000023using namespace clang;
24using namespace CodeGen;
25
Ken Dyck55c02582011-03-22 00:53:26 +000026static CharUnits
Anders Carlsson34a2d382010-04-24 21:06:20 +000027ComputeNonVirtualBaseClassOffset(ASTContext &Context,
28 const CXXRecordDecl *DerivedClass,
John McCallf871d0c2010-08-07 06:22:56 +000029 CastExpr::path_const_iterator Start,
30 CastExpr::path_const_iterator End) {
Ken Dyck55c02582011-03-22 00:53:26 +000031 CharUnits Offset = CharUnits::Zero();
Anders Carlsson34a2d382010-04-24 21:06:20 +000032
33 const CXXRecordDecl *RD = DerivedClass;
34
John McCallf871d0c2010-08-07 06:22:56 +000035 for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
Anders Carlsson34a2d382010-04-24 21:06:20 +000036 const CXXBaseSpecifier *Base = *I;
37 assert(!Base->isVirtual() && "Should not see virtual bases here!");
38
39 // Get the layout.
40 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
41
42 const CXXRecordDecl *BaseDecl =
43 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
44
45 // Add the offset.
Ken Dyck55c02582011-03-22 00:53:26 +000046 Offset += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson34a2d382010-04-24 21:06:20 +000047
48 RD = BaseDecl;
49 }
50
Ken Dyck55c02582011-03-22 00:53:26 +000051 return Offset;
Anders Carlsson34a2d382010-04-24 21:06:20 +000052}
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000053
Anders Carlsson84080ec2009-09-29 03:13:20 +000054llvm::Constant *
Anders Carlssona04efdf2010-04-24 21:23:59 +000055CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +000056 CastExpr::path_const_iterator PathBegin,
57 CastExpr::path_const_iterator PathEnd) {
58 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssona04efdf2010-04-24 21:23:59 +000059
Ken Dyck55c02582011-03-22 00:53:26 +000060 CharUnits Offset =
John McCallf871d0c2010-08-07 06:22:56 +000061 ComputeNonVirtualBaseClassOffset(getContext(), ClassDecl,
62 PathBegin, PathEnd);
Ken Dyck55c02582011-03-22 00:53:26 +000063 if (Offset.isZero())
Anders Carlssona04efdf2010-04-24 21:23:59 +000064 return 0;
65
Chris Lattner2acc6e32011-07-18 04:24:23 +000066 llvm::Type *PtrDiffTy =
Anders Carlssona04efdf2010-04-24 21:23:59 +000067 Types.ConvertType(getContext().getPointerDiffType());
68
Ken Dyck55c02582011-03-22 00:53:26 +000069 return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
Anders Carlsson84080ec2009-09-29 03:13:20 +000070}
71
Anders Carlsson8561a862010-04-24 23:01:49 +000072/// Gets the address of a direct base class within a complete object.
John McCallbff225e2010-02-16 04:15:37 +000073/// This should only be used for (1) non-virtual bases or (2) virtual bases
74/// when the type is known to be complete (e.g. in complete destructors).
75///
76/// The object pointed to by 'This' is assumed to be non-null.
77llvm::Value *
Anders Carlsson8561a862010-04-24 23:01:49 +000078CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(llvm::Value *This,
79 const CXXRecordDecl *Derived,
80 const CXXRecordDecl *Base,
81 bool BaseIsVirtual) {
John McCallbff225e2010-02-16 04:15:37 +000082 // 'this' must be a pointer (in some address space) to Derived.
83 assert(This->getType()->isPointerTy() &&
84 cast<llvm::PointerType>(This->getType())->getElementType()
85 == ConvertType(Derived));
86
87 // Compute the offset of the virtual base.
Ken Dyck5fff46b2011-03-22 01:21:15 +000088 CharUnits Offset;
John McCallbff225e2010-02-16 04:15:37 +000089 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
Anders Carlsson8561a862010-04-24 23:01:49 +000090 if (BaseIsVirtual)
Ken Dyck5fff46b2011-03-22 01:21:15 +000091 Offset = Layout.getVBaseClassOffset(Base);
John McCallbff225e2010-02-16 04:15:37 +000092 else
Ken Dyck5fff46b2011-03-22 01:21:15 +000093 Offset = Layout.getBaseClassOffset(Base);
John McCallbff225e2010-02-16 04:15:37 +000094
95 // Shift and cast down to the base type.
96 // TODO: for complete types, this should be possible with a GEP.
97 llvm::Value *V = This;
Ken Dyck5fff46b2011-03-22 01:21:15 +000098 if (Offset.isPositive()) {
John McCallbff225e2010-02-16 04:15:37 +000099 V = Builder.CreateBitCast(V, Int8PtrTy);
Ken Dyck5fff46b2011-03-22 01:21:15 +0000100 V = Builder.CreateConstInBoundsGEP1_64(V, Offset.getQuantity());
John McCallbff225e2010-02-16 04:15:37 +0000101 }
102 V = Builder.CreateBitCast(V, ConvertType(Base)->getPointerTo());
103
104 return V;
Anders Carlssond103f9f2010-03-28 19:40:00 +0000105}
John McCallbff225e2010-02-16 04:15:37 +0000106
Anders Carlsson9dc228a2010-04-20 16:03:35 +0000107static llvm::Value *
John McCall7916c992012-08-01 05:04:58 +0000108ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, llvm::Value *ptr,
109 CharUnits nonVirtualOffset,
110 llvm::Value *virtualOffset) {
111 // Assert that we have something to do.
112 assert(!nonVirtualOffset.isZero() || virtualOffset != 0);
113
114 // Compute the offset from the static and dynamic components.
115 llvm::Value *baseOffset;
116 if (!nonVirtualOffset.isZero()) {
117 baseOffset = llvm::ConstantInt::get(CGF.PtrDiffTy,
118 nonVirtualOffset.getQuantity());
119 if (virtualOffset) {
120 baseOffset = CGF.Builder.CreateAdd(virtualOffset, baseOffset);
121 }
122 } else {
123 baseOffset = virtualOffset;
124 }
Anders Carlsson9dc228a2010-04-20 16:03:35 +0000125
126 // Apply the base offset.
John McCall7916c992012-08-01 05:04:58 +0000127 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
128 ptr = CGF.Builder.CreateInBoundsGEP(ptr, baseOffset, "add.ptr");
129 return ptr;
Anders Carlsson9dc228a2010-04-20 16:03:35 +0000130}
131
Anders Carlsson5d58a1d2009-09-12 04:27:24 +0000132llvm::Value *
Anders Carlsson34a2d382010-04-24 21:06:20 +0000133CodeGenFunction::GetAddressOfBaseClass(llvm::Value *Value,
Anders Carlsson8561a862010-04-24 23:01:49 +0000134 const CXXRecordDecl *Derived,
John McCallf871d0c2010-08-07 06:22:56 +0000135 CastExpr::path_const_iterator PathBegin,
136 CastExpr::path_const_iterator PathEnd,
Anders Carlsson34a2d382010-04-24 21:06:20 +0000137 bool NullCheckValue) {
John McCallf871d0c2010-08-07 06:22:56 +0000138 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlsson34a2d382010-04-24 21:06:20 +0000139
John McCallf871d0c2010-08-07 06:22:56 +0000140 CastExpr::path_const_iterator Start = PathBegin;
Anders Carlsson34a2d382010-04-24 21:06:20 +0000141 const CXXRecordDecl *VBase = 0;
142
John McCall7916c992012-08-01 05:04:58 +0000143 // Sema has done some convenient canonicalization here: if the
144 // access path involved any virtual steps, the conversion path will
145 // *start* with a step down to the correct virtual base subobject,
146 // and hence will not require any further steps.
Anders Carlsson34a2d382010-04-24 21:06:20 +0000147 if ((*Start)->isVirtual()) {
148 VBase =
149 cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
150 ++Start;
151 }
John McCall7916c992012-08-01 05:04:58 +0000152
153 // Compute the static offset of the ultimate destination within its
154 // allocating subobject (the virtual base, if there is one, or else
155 // the "complete" object that we see).
Ken Dyck55c02582011-03-22 00:53:26 +0000156 CharUnits NonVirtualOffset =
Anders Carlsson8561a862010-04-24 23:01:49 +0000157 ComputeNonVirtualBaseClassOffset(getContext(), VBase ? VBase : Derived,
John McCallf871d0c2010-08-07 06:22:56 +0000158 Start, PathEnd);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000159
John McCall7916c992012-08-01 05:04:58 +0000160 // If there's a virtual step, we can sometimes "devirtualize" it.
161 // For now, that's limited to when the derived type is final.
162 // TODO: "devirtualize" this for accesses to known-complete objects.
163 if (VBase && Derived->hasAttr<FinalAttr>()) {
164 const ASTRecordLayout &layout = getContext().getASTRecordLayout(Derived);
165 CharUnits vBaseOffset = layout.getVBaseClassOffset(VBase);
166 NonVirtualOffset += vBaseOffset;
167 VBase = 0; // we no longer have a virtual step
168 }
169
Anders Carlsson34a2d382010-04-24 21:06:20 +0000170 // Get the base pointer type.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000171 llvm::Type *BasePtrTy =
John McCallf871d0c2010-08-07 06:22:56 +0000172 ConvertType((PathEnd[-1])->getType())->getPointerTo();
John McCall7916c992012-08-01 05:04:58 +0000173
174 // If the static offset is zero and we don't have a virtual step,
175 // just do a bitcast; null checks are unnecessary.
Ken Dyck55c02582011-03-22 00:53:26 +0000176 if (NonVirtualOffset.isZero() && !VBase) {
Anders Carlsson34a2d382010-04-24 21:06:20 +0000177 return Builder.CreateBitCast(Value, BasePtrTy);
178 }
John McCall7916c992012-08-01 05:04:58 +0000179
180 llvm::BasicBlock *origBB = 0;
181 llvm::BasicBlock *endBB = 0;
Anders Carlsson34a2d382010-04-24 21:06:20 +0000182
John McCall7916c992012-08-01 05:04:58 +0000183 // Skip over the offset (and the vtable load) if we're supposed to
184 // null-check the pointer.
Anders Carlsson34a2d382010-04-24 21:06:20 +0000185 if (NullCheckValue) {
John McCall7916c992012-08-01 05:04:58 +0000186 origBB = Builder.GetInsertBlock();
187 llvm::BasicBlock *notNullBB = createBasicBlock("cast.notnull");
188 endBB = createBasicBlock("cast.end");
Anders Carlsson34a2d382010-04-24 21:06:20 +0000189
John McCall7916c992012-08-01 05:04:58 +0000190 llvm::Value *isNull = Builder.CreateIsNull(Value);
191 Builder.CreateCondBr(isNull, endBB, notNullBB);
192 EmitBlock(notNullBB);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000193 }
194
John McCall7916c992012-08-01 05:04:58 +0000195 // Compute the virtual offset.
Anders Carlsson34a2d382010-04-24 21:06:20 +0000196 llvm::Value *VirtualOffset = 0;
Anders Carlsson336a7dc2011-01-29 03:18:56 +0000197 if (VBase) {
John McCall7916c992012-08-01 05:04:58 +0000198 VirtualOffset = GetVirtualBaseClassOffset(Value, Derived, VBase);
Anders Carlsson336a7dc2011-01-29 03:18:56 +0000199 }
Anders Carlsson34a2d382010-04-24 21:06:20 +0000200
John McCall7916c992012-08-01 05:04:58 +0000201 // Apply both offsets.
Ken Dyck55c02582011-03-22 00:53:26 +0000202 Value = ApplyNonVirtualAndVirtualOffset(*this, Value,
Ken Dyck9a8ad9b2011-03-23 00:45:26 +0000203 NonVirtualOffset,
Anders Carlsson34a2d382010-04-24 21:06:20 +0000204 VirtualOffset);
205
John McCall7916c992012-08-01 05:04:58 +0000206 // Cast to the destination type.
Anders Carlsson34a2d382010-04-24 21:06:20 +0000207 Value = Builder.CreateBitCast(Value, BasePtrTy);
John McCall7916c992012-08-01 05:04:58 +0000208
209 // Build a phi if we needed a null check.
Anders Carlsson34a2d382010-04-24 21:06:20 +0000210 if (NullCheckValue) {
John McCall7916c992012-08-01 05:04:58 +0000211 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
212 Builder.CreateBr(endBB);
213 EmitBlock(endBB);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000214
John McCall7916c992012-08-01 05:04:58 +0000215 llvm::PHINode *PHI = Builder.CreatePHI(BasePtrTy, 2, "cast.result");
216 PHI->addIncoming(Value, notNullBB);
217 PHI->addIncoming(llvm::Constant::getNullValue(BasePtrTy), origBB);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000218 Value = PHI;
219 }
220
221 return Value;
222}
223
224llvm::Value *
Anders Carlssona3697c92009-11-23 17:57:54 +0000225CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value,
Anders Carlsson8561a862010-04-24 23:01:49 +0000226 const CXXRecordDecl *Derived,
John McCallf871d0c2010-08-07 06:22:56 +0000227 CastExpr::path_const_iterator PathBegin,
228 CastExpr::path_const_iterator PathEnd,
Anders Carlssona3697c92009-11-23 17:57:54 +0000229 bool NullCheckValue) {
John McCallf871d0c2010-08-07 06:22:56 +0000230 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssona04efdf2010-04-24 21:23:59 +0000231
Anders Carlssona3697c92009-11-23 17:57:54 +0000232 QualType DerivedTy =
Anders Carlsson8561a862010-04-24 23:01:49 +0000233 getContext().getCanonicalType(getContext().getTagDeclType(Derived));
Chris Lattner2acc6e32011-07-18 04:24:23 +0000234 llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
Anders Carlssona3697c92009-11-23 17:57:54 +0000235
Anders Carlssona552ea72010-01-31 01:43:37 +0000236 llvm::Value *NonVirtualOffset =
John McCallf871d0c2010-08-07 06:22:56 +0000237 CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
Anders Carlssona552ea72010-01-31 01:43:37 +0000238
239 if (!NonVirtualOffset) {
240 // No offset, we can just cast back.
241 return Builder.CreateBitCast(Value, DerivedPtrTy);
242 }
243
Anders Carlssona3697c92009-11-23 17:57:54 +0000244 llvm::BasicBlock *CastNull = 0;
245 llvm::BasicBlock *CastNotNull = 0;
246 llvm::BasicBlock *CastEnd = 0;
247
248 if (NullCheckValue) {
249 CastNull = createBasicBlock("cast.null");
250 CastNotNull = createBasicBlock("cast.notnull");
251 CastEnd = createBasicBlock("cast.end");
252
Anders Carlssonb9241242011-04-11 00:30:07 +0000253 llvm::Value *IsNull = Builder.CreateIsNull(Value);
Anders Carlssona3697c92009-11-23 17:57:54 +0000254 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
255 EmitBlock(CastNotNull);
256 }
257
Anders Carlssona552ea72010-01-31 01:43:37 +0000258 // Apply the offset.
Eli Friedmanc5685432012-02-28 22:07:56 +0000259 Value = Builder.CreateBitCast(Value, Int8PtrTy);
260 Value = Builder.CreateGEP(Value, Builder.CreateNeg(NonVirtualOffset),
261 "sub.ptr");
Anders Carlssona552ea72010-01-31 01:43:37 +0000262
263 // Just cast.
264 Value = Builder.CreateBitCast(Value, DerivedPtrTy);
Anders Carlssona3697c92009-11-23 17:57:54 +0000265
266 if (NullCheckValue) {
267 Builder.CreateBr(CastEnd);
268 EmitBlock(CastNull);
269 Builder.CreateBr(CastEnd);
270 EmitBlock(CastEnd);
271
Jay Foadbbf3bac2011-03-30 11:28:58 +0000272 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
Anders Carlssona3697c92009-11-23 17:57:54 +0000273 PHI->addIncoming(Value, CastNotNull);
274 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
275 CastNull);
276 Value = PHI;
277 }
278
279 return Value;
Anders Carlsson5d58a1d2009-09-12 04:27:24 +0000280}
Anders Carlsson21c9ad92010-03-30 03:27:09 +0000281
Anders Carlssonc997d422010-01-02 01:01:18 +0000282/// GetVTTParameter - Return the VTT parameter that should be passed to a
283/// base constructor/destructor with virtual bases.
Anders Carlsson314e6222010-05-02 23:33:10 +0000284static llvm::Value *GetVTTParameter(CodeGenFunction &CGF, GlobalDecl GD,
Douglas Gregor378e1e72013-01-31 05:50:40 +0000285 bool ForVirtualBase,
286 bool Delegating) {
Anders Carlssonaf440352010-03-23 04:11:45 +0000287 if (!CodeGenVTables::needsVTTParameter(GD)) {
Anders Carlssonc997d422010-01-02 01:01:18 +0000288 // This constructor/destructor does not need a VTT parameter.
289 return 0;
290 }
291
292 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CGF.CurFuncDecl)->getParent();
293 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
John McCall3b477332010-02-18 19:59:28 +0000294
Anders Carlssonc997d422010-01-02 01:01:18 +0000295 llvm::Value *VTT;
296
John McCall3b477332010-02-18 19:59:28 +0000297 uint64_t SubVTTIndex;
298
Douglas Gregor378e1e72013-01-31 05:50:40 +0000299 if (Delegating) {
300 // If this is a delegating constructor call, just load the VTT.
301 return CGF.LoadCXXVTT();
302 } else if (RD == Base) {
303 // If the record matches the base, this is the complete ctor/dtor
304 // variant calling the base variant in a class with virtual bases.
Anders Carlssonaf440352010-03-23 04:11:45 +0000305 assert(!CodeGenVTables::needsVTTParameter(CGF.CurGD) &&
John McCall3b477332010-02-18 19:59:28 +0000306 "doing no-op VTT offset in base dtor/ctor?");
Anders Carlsson314e6222010-05-02 23:33:10 +0000307 assert(!ForVirtualBase && "Can't have same class as virtual base!");
John McCall3b477332010-02-18 19:59:28 +0000308 SubVTTIndex = 0;
309 } else {
Anders Carlssonc11bb212010-05-02 23:53:25 +0000310 const ASTRecordLayout &Layout =
311 CGF.getContext().getASTRecordLayout(RD);
Ken Dyck4230d522011-03-24 01:21:01 +0000312 CharUnits BaseOffset = ForVirtualBase ?
313 Layout.getVBaseClassOffset(Base) :
314 Layout.getBaseClassOffset(Base);
Anders Carlssonc11bb212010-05-02 23:53:25 +0000315
316 SubVTTIndex =
317 CGF.CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
John McCall3b477332010-02-18 19:59:28 +0000318 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
319 }
Anders Carlssonc997d422010-01-02 01:01:18 +0000320
Anders Carlssonaf440352010-03-23 04:11:45 +0000321 if (CodeGenVTables::needsVTTParameter(CGF.CurGD)) {
Anders Carlssonc997d422010-01-02 01:01:18 +0000322 // A VTT parameter was passed to the constructor, use it.
323 VTT = CGF.LoadCXXVTT();
324 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
325 } else {
326 // We're the complete constructor, so get the VTT by name.
Anders Carlsson1cbce122011-01-29 19:16:51 +0000327 VTT = CGF.CGM.getVTables().GetAddrOfVTT(RD);
Anders Carlssonc997d422010-01-02 01:01:18 +0000328 VTT = CGF.Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
329 }
330
331 return VTT;
332}
333
John McCall182ab512010-07-21 01:23:41 +0000334namespace {
John McCall50da2ca2010-07-21 05:30:47 +0000335 /// Call the destructor for a direct base class.
John McCall1f0fca52010-07-21 07:22:38 +0000336 struct CallBaseDtor : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000337 const CXXRecordDecl *BaseClass;
338 bool BaseIsVirtual;
339 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
340 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
John McCall182ab512010-07-21 01:23:41 +0000341
John McCallad346f42011-07-12 20:27:29 +0000342 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall50da2ca2010-07-21 05:30:47 +0000343 const CXXRecordDecl *DerivedClass =
344 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
345
346 const CXXDestructorDecl *D = BaseClass->getDestructor();
347 llvm::Value *Addr =
348 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThis(),
349 DerivedClass, BaseClass,
350 BaseIsVirtual);
Douglas Gregor378e1e72013-01-31 05:50:40 +0000351 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual,
352 /*Delegating=*/false, Addr);
John McCall182ab512010-07-21 01:23:41 +0000353 }
354 };
John McCall7e1dff72010-09-17 02:31:44 +0000355
356 /// A visitor which checks whether an initializer uses 'this' in a
357 /// way which requires the vtable to be properly set.
358 struct DynamicThisUseChecker : EvaluatedExprVisitor<DynamicThisUseChecker> {
359 typedef EvaluatedExprVisitor<DynamicThisUseChecker> super;
360
361 bool UsesThis;
362
363 DynamicThisUseChecker(ASTContext &C) : super(C), UsesThis(false) {}
364
365 // Black-list all explicit and implicit references to 'this'.
366 //
367 // Do we need to worry about external references to 'this' derived
368 // from arbitrary code? If so, then anything which runs arbitrary
369 // external code might potentially access the vtable.
370 void VisitCXXThisExpr(CXXThisExpr *E) { UsesThis = true; }
371 };
372}
373
374static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
375 DynamicThisUseChecker Checker(C);
376 Checker.Visit(const_cast<Expr*>(Init));
377 return Checker.UsesThis;
John McCall182ab512010-07-21 01:23:41 +0000378}
379
Anders Carlsson607d0372009-12-24 22:46:43 +0000380static void EmitBaseInitializer(CodeGenFunction &CGF,
381 const CXXRecordDecl *ClassDecl,
Sean Huntcbb67482011-01-08 20:30:50 +0000382 CXXCtorInitializer *BaseInit,
Anders Carlsson607d0372009-12-24 22:46:43 +0000383 CXXCtorType CtorType) {
384 assert(BaseInit->isBaseInitializer() &&
385 "Must have base initializer!");
386
387 llvm::Value *ThisPtr = CGF.LoadCXXThis();
388
389 const Type *BaseType = BaseInit->getBaseClass();
390 CXXRecordDecl *BaseClassDecl =
391 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
392
Anders Carlsson80638c52010-04-12 00:51:03 +0000393 bool isBaseVirtual = BaseInit->isBaseVirtual();
Anders Carlsson607d0372009-12-24 22:46:43 +0000394
395 // The base constructor doesn't construct virtual bases.
396 if (CtorType == Ctor_Base && isBaseVirtual)
397 return;
398
John McCall7e1dff72010-09-17 02:31:44 +0000399 // If the initializer for the base (other than the constructor
400 // itself) accesses 'this' in any way, we need to initialize the
401 // vtables.
402 if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
403 CGF.InitializeVTablePointers(ClassDecl);
404
John McCallbff225e2010-02-16 04:15:37 +0000405 // We can pretend to be a complete class because it only matters for
406 // virtual bases, and we only do virtual bases for complete ctors.
Anders Carlsson8561a862010-04-24 23:01:49 +0000407 llvm::Value *V =
408 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
John McCall50da2ca2010-07-21 05:30:47 +0000409 BaseClassDecl,
410 isBaseVirtual);
Eli Friedmand7722d92011-12-03 02:13:40 +0000411 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(BaseType);
John McCall7c2349b2011-08-25 20:40:09 +0000412 AggValueSlot AggSlot =
Eli Friedmanf3940782011-12-03 00:54:26 +0000413 AggValueSlot::forAddr(V, Alignment, Qualifiers(),
John McCall7c2349b2011-08-25 20:40:09 +0000414 AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +0000415 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +0000416 AggValueSlot::IsNotAliased);
John McCall558d2ab2010-09-15 10:14:12 +0000417
418 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
Anders Carlsson594d5e82010-02-06 20:00:21 +0000419
David Blaikie4e4d0842012-03-11 07:00:24 +0000420 if (CGF.CGM.getLangOpts().Exceptions &&
Anders Carlssonc1cfdf82011-02-20 00:20:27 +0000421 !BaseClassDecl->hasTrivialDestructor())
John McCall1f0fca52010-07-21 07:22:38 +0000422 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
423 isBaseVirtual);
Anders Carlsson607d0372009-12-24 22:46:43 +0000424}
425
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000426static void EmitAggMemberInitializer(CodeGenFunction &CGF,
427 LValue LHS,
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000428 Expr *Init,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000429 llvm::Value *ArrayIndexVar,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000430 QualType T,
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000431 ArrayRef<VarDecl *> ArrayIndexes,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000432 unsigned Index) {
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000433 if (Index == ArrayIndexes.size()) {
Eli Friedmanf3940782011-12-03 00:54:26 +0000434 LValue LV = LHS;
Sebastian Redl924db712012-02-19 15:41:54 +0000435 { // Scope for Cleanups.
436 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
Eli Friedmanf3940782011-12-03 00:54:26 +0000437
Sebastian Redl924db712012-02-19 15:41:54 +0000438 if (ArrayIndexVar) {
439 // If we have an array index variable, load it and use it as an offset.
440 // Then, increment the value.
441 llvm::Value *Dest = LHS.getAddress();
442 llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar);
443 Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress");
444 llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1);
445 Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc");
446 CGF.Builder.CreateStore(Next, ArrayIndexVar);
447
448 // Update the LValue.
449 LV.setAddress(Dest);
450 CharUnits Align = CGF.getContext().getTypeAlignInChars(T);
451 LV.setAlignment(std::min(Align, LV.getAlignment()));
452 }
453
454 if (!CGF.hasAggregateLLVMType(T)) {
455 CGF.EmitScalarInit(Init, /*decl*/ 0, LV, false);
456 } else if (T->isAnyComplexType()) {
457 CGF.EmitComplexExprIntoAddr(Init, LV.getAddress(),
458 LV.isVolatileQualified());
459 } else {
460 AggValueSlot Slot =
461 AggValueSlot::forLValue(LV,
462 AggValueSlot::IsDestructed,
463 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +0000464 AggValueSlot::IsNotAliased);
Sebastian Redl924db712012-02-19 15:41:54 +0000465
466 CGF.EmitAggExpr(Init, Slot);
467 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000468 }
John McCall558d2ab2010-09-15 10:14:12 +0000469
Sebastian Redl924db712012-02-19 15:41:54 +0000470 // Now, outside of the initializer cleanup scope, destroy the backing array
471 // for a std::initializer_list member.
Sebastian Redl972edf02012-02-19 16:03:09 +0000472 CGF.MaybeEmitStdInitializerListCleanup(LV.getAddress(), Init);
Sebastian Redl924db712012-02-19 15:41:54 +0000473
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000474 return;
475 }
476
477 const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T);
478 assert(Array && "Array initialization without the array type?");
479 llvm::Value *IndexVar
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000480 = CGF.GetAddrOfLocalVar(ArrayIndexes[Index]);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000481 assert(IndexVar && "Array index variable not loaded");
482
483 // Initialize this index variable to zero.
484 llvm::Value* Zero
485 = llvm::Constant::getNullValue(
486 CGF.ConvertType(CGF.getContext().getSizeType()));
487 CGF.Builder.CreateStore(Zero, IndexVar);
488
489 // Start the loop with a block that tests the condition.
490 llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond");
491 llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end");
492
493 CGF.EmitBlock(CondBlock);
494
495 llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body");
496 // Generate: if (loop-index < number-of-elements) fall to the loop body,
497 // otherwise, go to the block after the for-loop.
498 uint64_t NumElements = Array->getSize().getZExtValue();
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000499 llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
Chris Lattner985f7392010-05-06 06:35:23 +0000500 llvm::Value *NumElementsPtr =
501 llvm::ConstantInt::get(Counter->getType(), NumElements);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000502 llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr,
503 "isless");
504
505 // If the condition is true, execute the body.
506 CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor);
507
508 CGF.EmitBlock(ForBody);
509 llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc");
510
511 {
John McCallf1549f62010-07-06 01:34:17 +0000512 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000513
514 // Inside the loop body recurse to emit the inner loop or, eventually, the
515 // constructor call.
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000516 EmitAggMemberInitializer(CGF, LHS, Init, ArrayIndexVar,
517 Array->getElementType(), ArrayIndexes, Index + 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000518 }
519
520 CGF.EmitBlock(ContinueBlock);
521
522 // Emit the increment of the loop counter.
523 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
524 Counter = CGF.Builder.CreateLoad(IndexVar);
525 NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc");
526 CGF.Builder.CreateStore(NextVal, IndexVar);
527
528 // Finally, branch back up to the condition for the next iteration.
529 CGF.EmitBranch(CondBlock);
530
531 // Emit the fall-through block.
532 CGF.EmitBlock(AfterFor, true);
533}
John McCall182ab512010-07-21 01:23:41 +0000534
535namespace {
John McCall1f0fca52010-07-21 07:22:38 +0000536 struct CallMemberDtor : EHScopeStack::Cleanup {
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000537 llvm::Value *V;
John McCall182ab512010-07-21 01:23:41 +0000538 CXXDestructorDecl *Dtor;
539
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000540 CallMemberDtor(llvm::Value *V, CXXDestructorDecl *Dtor)
541 : V(V), Dtor(Dtor) {}
John McCall182ab512010-07-21 01:23:41 +0000542
John McCallad346f42011-07-12 20:27:29 +0000543 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall182ab512010-07-21 01:23:41 +0000544 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
Douglas Gregor378e1e72013-01-31 05:50:40 +0000545 /*Delegating=*/false, V);
John McCall182ab512010-07-21 01:23:41 +0000546 }
547 };
548}
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000549
Anders Carlsson607d0372009-12-24 22:46:43 +0000550static void EmitMemberInitializer(CodeGenFunction &CGF,
551 const CXXRecordDecl *ClassDecl,
Sean Huntcbb67482011-01-08 20:30:50 +0000552 CXXCtorInitializer *MemberInit,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000553 const CXXConstructorDecl *Constructor,
554 FunctionArgList &Args) {
Francois Pichet00eb3f92010-12-04 09:14:42 +0000555 assert(MemberInit->isAnyMemberInitializer() &&
Anders Carlsson607d0372009-12-24 22:46:43 +0000556 "Must have member initializer!");
Richard Smith7a614d82011-06-11 17:19:42 +0000557 assert(MemberInit->getInit() && "Must have initializer!");
Anders Carlsson607d0372009-12-24 22:46:43 +0000558
559 // non-static data member initializers.
Francois Pichet00eb3f92010-12-04 09:14:42 +0000560 FieldDecl *Field = MemberInit->getAnyMember();
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000561 QualType FieldType = Field->getType();
Anders Carlsson607d0372009-12-24 22:46:43 +0000562
563 llvm::Value *ThisPtr = CGF.LoadCXXThis();
Eli Friedman377ecc72012-04-16 03:54:45 +0000564 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
Eli Friedman859c65c2012-08-08 03:51:37 +0000565 LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
Eli Friedman377ecc72012-04-16 03:54:45 +0000566
Francois Pichet00eb3f92010-12-04 09:14:42 +0000567 if (MemberInit->isIndirectMemberInitializer()) {
Eli Friedman859c65c2012-08-08 03:51:37 +0000568 // If we are initializing an anonymous union field, drill down to
569 // the field.
570 IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember();
571 IndirectFieldDecl::chain_iterator I = IndirectField->chain_begin(),
572 IEnd = IndirectField->chain_end();
573 for ( ; I != IEnd; ++I)
574 LHS = CGF.EmitLValueForFieldInitialization(LHS, cast<FieldDecl>(*I));
Francois Pichet00eb3f92010-12-04 09:14:42 +0000575 FieldType = MemberInit->getIndirectMember()->getAnonField()->getType();
John McCalla9976d32010-05-21 01:18:57 +0000576 } else {
Eli Friedman859c65c2012-08-08 03:51:37 +0000577 LHS = CGF.EmitLValueForFieldInitialization(LHS, Field);
Anders Carlsson607d0372009-12-24 22:46:43 +0000578 }
579
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000580 // Special case: if we are in a copy or move constructor, and we are copying
581 // an array of PODs or classes with trivial copy constructors, ignore the
582 // AST and perform the copy we know is equivalent.
583 // FIXME: This is hacky at best... if we had a bit more explicit information
584 // in the AST, we could generalize it more easily.
585 const ConstantArrayType *Array
586 = CGF.getContext().getAsConstantArrayType(FieldType);
587 if (Array && Constructor->isImplicitlyDefined() &&
588 Constructor->isCopyOrMoveConstructor()) {
589 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
Richard Smithe9385362012-11-07 23:56:21 +0000590 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000591 if (BaseElementTy.isPODType(CGF.getContext()) ||
Richard Smithe9385362012-11-07 23:56:21 +0000592 (CE && CE->getConstructor()->isTrivial())) {
593 // Find the source pointer. We know it's the last argument because
594 // we know we're in an implicit copy constructor.
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000595 unsigned SrcArgIndex = Args.size() - 1;
596 llvm::Value *SrcPtr
597 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
Eli Friedman377ecc72012-04-16 03:54:45 +0000598 LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
599 LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field);
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000600
601 // Copy the aggregate.
602 CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
Chad Rosier649b4a12012-03-29 17:37:10 +0000603 LHS.isVolatileQualified());
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000604 return;
605 }
606 }
607
608 ArrayRef<VarDecl *> ArrayIndexes;
609 if (MemberInit->getNumArrayIndices())
610 ArrayIndexes = MemberInit->getArrayIndexes();
Eli Friedmanb74ed082012-02-14 02:31:03 +0000611 CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit(), ArrayIndexes);
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000612}
613
Eli Friedmanb74ed082012-02-14 02:31:03 +0000614void CodeGenFunction::EmitInitializerForField(FieldDecl *Field,
615 LValue LHS, Expr *Init,
616 ArrayRef<VarDecl *> ArrayIndexes) {
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000617 QualType FieldType = Field->getType();
Eli Friedmanb74ed082012-02-14 02:31:03 +0000618 if (!hasAggregateLLVMType(FieldType)) {
John McCallf85e1932011-06-15 23:02:42 +0000619 if (LHS.isSimple()) {
Eli Friedmanb74ed082012-02-14 02:31:03 +0000620 EmitExprAsInit(Init, Field, LHS, false);
John McCallf85e1932011-06-15 23:02:42 +0000621 } else {
Eli Friedmanb74ed082012-02-14 02:31:03 +0000622 RValue RHS = RValue::get(EmitScalarExpr(Init));
623 EmitStoreThroughLValue(RHS, LHS);
John McCallf85e1932011-06-15 23:02:42 +0000624 }
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000625 } else if (FieldType->isAnyComplexType()) {
Eli Friedmanb74ed082012-02-14 02:31:03 +0000626 EmitComplexExprIntoAddr(Init, LHS.getAddress(), LHS.isVolatileQualified());
Anders Carlsson607d0372009-12-24 22:46:43 +0000627 } else {
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000628 llvm::Value *ArrayIndexVar = 0;
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000629 if (ArrayIndexes.size()) {
Eli Friedmanb74ed082012-02-14 02:31:03 +0000630 llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000631
632 // The LHS is a pointer to the first object we'll be constructing, as
633 // a flat array.
Eli Friedmanb74ed082012-02-14 02:31:03 +0000634 QualType BaseElementTy = getContext().getBaseElementType(FieldType);
635 llvm::Type *BasePtr = ConvertType(BaseElementTy);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000636 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Eli Friedmanb74ed082012-02-14 02:31:03 +0000637 llvm::Value *BaseAddrPtr = Builder.CreateBitCast(LHS.getAddress(),
638 BasePtr);
639 LHS = MakeAddrLValue(BaseAddrPtr, BaseElementTy);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000640
641 // Create an array index that will be used to walk over all of the
642 // objects we're constructing.
Eli Friedmanb74ed082012-02-14 02:31:03 +0000643 ArrayIndexVar = CreateTempAlloca(SizeTy, "object.index");
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000644 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
Eli Friedmanb74ed082012-02-14 02:31:03 +0000645 Builder.CreateStore(Zero, ArrayIndexVar);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000646
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000647
648 // Emit the block variables for the array indices, if any.
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000649 for (unsigned I = 0, N = ArrayIndexes.size(); I != N; ++I)
Eli Friedmanb74ed082012-02-14 02:31:03 +0000650 EmitAutoVarDecl(*ArrayIndexes[I]);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000651 }
652
Eli Friedmanb74ed082012-02-14 02:31:03 +0000653 EmitAggMemberInitializer(*this, LHS, Init, ArrayIndexVar, FieldType,
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000654 ArrayIndexes, 0);
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000655
David Blaikie4e4d0842012-03-11 07:00:24 +0000656 if (!CGM.getLangOpts().Exceptions)
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000657 return;
658
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000659 // FIXME: If we have an array of classes w/ non-trivial destructors,
660 // we need to destroy in reverse order of construction along the exception
661 // path.
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000662 const RecordType *RT = FieldType->getAs<RecordType>();
663 if (!RT)
664 return;
665
666 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall182ab512010-07-21 01:23:41 +0000667 if (!RD->hasTrivialDestructor())
Eli Friedmanb74ed082012-02-14 02:31:03 +0000668 EHStack.pushCleanup<CallMemberDtor>(EHCleanup, LHS.getAddress(),
669 RD->getDestructor());
Anders Carlsson607d0372009-12-24 22:46:43 +0000670 }
671}
672
John McCallc0bf4622010-02-23 00:48:20 +0000673/// Checks whether the given constructor is a valid subject for the
674/// complete-to-base constructor delegation optimization, i.e.
675/// emitting the complete constructor as a simple call to the base
676/// constructor.
677static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
678
679 // Currently we disable the optimization for classes with virtual
680 // bases because (1) the addresses of parameter variables need to be
681 // consistent across all initializers but (2) the delegate function
682 // call necessarily creates a second copy of the parameter variable.
683 //
684 // The limiting example (purely theoretical AFAIK):
685 // struct A { A(int &c) { c++; } };
686 // struct B : virtual A {
687 // B(int count) : A(count) { printf("%d\n", count); }
688 // };
689 // ...although even this example could in principle be emitted as a
690 // delegation since the address of the parameter doesn't escape.
691 if (Ctor->getParent()->getNumVBases()) {
692 // TODO: white-list trivial vbase initializers. This case wouldn't
693 // be subject to the restrictions below.
694
695 // TODO: white-list cases where:
696 // - there are no non-reference parameters to the constructor
697 // - the initializers don't access any non-reference parameters
698 // - the initializers don't take the address of non-reference
699 // parameters
700 // - etc.
701 // If we ever add any of the above cases, remember that:
702 // - function-try-blocks will always blacklist this optimization
703 // - we need to perform the constructor prologue and cleanup in
704 // EmitConstructorBody.
705
706 return false;
707 }
708
709 // We also disable the optimization for variadic functions because
710 // it's impossible to "re-pass" varargs.
711 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
712 return false;
713
Sean Hunt059ce0d2011-05-01 07:04:31 +0000714 // FIXME: Decide if we can do a delegation of a delegating constructor.
715 if (Ctor->isDelegatingConstructor())
716 return false;
717
John McCallc0bf4622010-02-23 00:48:20 +0000718 return true;
719}
720
John McCall9fc6a772010-02-19 09:25:03 +0000721/// EmitConstructorBody - Emits the body of the current constructor.
722void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
723 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
724 CXXCtorType CtorType = CurGD.getCtorType();
725
John McCallc0bf4622010-02-23 00:48:20 +0000726 // Before we go any further, try the complete->base constructor
727 // delegation optimization.
Timur Iskhodzhanov85607912012-04-20 08:05:00 +0000728 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
John McCallb8b2c9d2013-01-25 22:30:49 +0000729 CGM.getContext().getTargetInfo().getCXXABI().hasConstructorVariants()) {
Devang Pateld67ef0e2010-08-11 21:04:37 +0000730 if (CGDebugInfo *DI = getDebugInfo())
Eric Christopher73fb3502011-10-13 21:45:18 +0000731 DI->EmitLocation(Builder, Ctor->getLocEnd());
John McCallc0bf4622010-02-23 00:48:20 +0000732 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args);
733 return;
734 }
735
John McCall9fc6a772010-02-19 09:25:03 +0000736 Stmt *Body = Ctor->getBody();
737
John McCallc0bf4622010-02-23 00:48:20 +0000738 // Enter the function-try-block before the constructor prologue if
739 // applicable.
John McCallc0bf4622010-02-23 00:48:20 +0000740 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallc0bf4622010-02-23 00:48:20 +0000741 if (IsTryBody)
John McCall59a70002010-07-07 06:56:46 +0000742 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000743
John McCallf1549f62010-07-06 01:34:17 +0000744 EHScopeStack::stable_iterator CleanupDepth = EHStack.stable_begin();
John McCall9fc6a772010-02-19 09:25:03 +0000745
John McCall56ea3772012-03-30 04:25:03 +0000746 // TODO: in restricted cases, we can emit the vbase initializers of
747 // a complete ctor and then delegate to the base ctor.
748
John McCallc0bf4622010-02-23 00:48:20 +0000749 // Emit the constructor prologue, i.e. the base and member
750 // initializers.
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000751 EmitCtorPrologue(Ctor, CtorType, Args);
John McCall9fc6a772010-02-19 09:25:03 +0000752
753 // Emit the body of the statement.
John McCallc0bf4622010-02-23 00:48:20 +0000754 if (IsTryBody)
John McCall9fc6a772010-02-19 09:25:03 +0000755 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
756 else if (Body)
757 EmitStmt(Body);
John McCall9fc6a772010-02-19 09:25:03 +0000758
759 // Emit any cleanup blocks associated with the member or base
760 // initializers, which includes (along the exceptional path) the
761 // destructors for those members and bases that were fully
762 // constructed.
John McCallf1549f62010-07-06 01:34:17 +0000763 PopCleanupBlocks(CleanupDepth);
John McCall9fc6a772010-02-19 09:25:03 +0000764
John McCallc0bf4622010-02-23 00:48:20 +0000765 if (IsTryBody)
John McCall59a70002010-07-07 06:56:46 +0000766 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000767}
768
Anders Carlsson607d0372009-12-24 22:46:43 +0000769/// EmitCtorPrologue - This routine generates necessary code to initialize
770/// base classes and non-static data members belonging to this constructor.
Anders Carlsson607d0372009-12-24 22:46:43 +0000771void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000772 CXXCtorType CtorType,
773 FunctionArgList &Args) {
Sean Hunt059ce0d2011-05-01 07:04:31 +0000774 if (CD->isDelegatingConstructor())
775 return EmitDelegatingCXXConstructorCall(CD, Args);
776
Anders Carlsson607d0372009-12-24 22:46:43 +0000777 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000778
Chris Lattner5f9e2722011-07-23 10:55:15 +0000779 SmallVector<CXXCtorInitializer *, 8> MemberInitializers;
Anders Carlsson607d0372009-12-24 22:46:43 +0000780
Anders Carlsson607d0372009-12-24 22:46:43 +0000781 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
782 E = CD->init_end();
783 B != E; ++B) {
Sean Huntcbb67482011-01-08 20:30:50 +0000784 CXXCtorInitializer *Member = (*B);
Anders Carlsson607d0372009-12-24 22:46:43 +0000785
Sean Huntd49bd552011-05-03 20:19:28 +0000786 if (Member->isBaseInitializer()) {
Anders Carlsson607d0372009-12-24 22:46:43 +0000787 EmitBaseInitializer(*this, ClassDecl, Member, CtorType);
Sean Huntd49bd552011-05-03 20:19:28 +0000788 } else {
789 assert(Member->isAnyMemberInitializer() &&
790 "Delegating initializer on non-delegating constructor");
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000791 MemberInitializers.push_back(Member);
Sean Huntd49bd552011-05-03 20:19:28 +0000792 }
Anders Carlsson607d0372009-12-24 22:46:43 +0000793 }
794
Anders Carlsson603d6d12010-03-28 21:07:49 +0000795 InitializeVTablePointers(ClassDecl);
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000796
John McCallf1549f62010-07-06 01:34:17 +0000797 for (unsigned I = 0, E = MemberInitializers.size(); I != E; ++I)
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000798 EmitMemberInitializer(*this, ClassDecl, MemberInitializers[I], CD, Args);
Anders Carlsson607d0372009-12-24 22:46:43 +0000799}
800
Anders Carlssonadf5dc32011-05-15 17:36:21 +0000801static bool
802FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
803
804static bool
805HasTrivialDestructorBody(ASTContext &Context,
806 const CXXRecordDecl *BaseClassDecl,
807 const CXXRecordDecl *MostDerivedClassDecl)
808{
809 // If the destructor is trivial we don't have to check anything else.
810 if (BaseClassDecl->hasTrivialDestructor())
811 return true;
812
813 if (!BaseClassDecl->getDestructor()->hasTrivialBody())
814 return false;
815
816 // Check fields.
817 for (CXXRecordDecl::field_iterator I = BaseClassDecl->field_begin(),
818 E = BaseClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +0000819 const FieldDecl *Field = *I;
Anders Carlssonadf5dc32011-05-15 17:36:21 +0000820
821 if (!FieldHasTrivialDestructorBody(Context, Field))
822 return false;
823 }
824
825 // Check non-virtual bases.
826 for (CXXRecordDecl::base_class_const_iterator I =
827 BaseClassDecl->bases_begin(), E = BaseClassDecl->bases_end();
828 I != E; ++I) {
829 if (I->isVirtual())
830 continue;
831
832 const CXXRecordDecl *NonVirtualBase =
833 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
834 if (!HasTrivialDestructorBody(Context, NonVirtualBase,
835 MostDerivedClassDecl))
836 return false;
837 }
838
839 if (BaseClassDecl == MostDerivedClassDecl) {
840 // Check virtual bases.
841 for (CXXRecordDecl::base_class_const_iterator I =
842 BaseClassDecl->vbases_begin(), E = BaseClassDecl->vbases_end();
843 I != E; ++I) {
844 const CXXRecordDecl *VirtualBase =
845 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
846 if (!HasTrivialDestructorBody(Context, VirtualBase,
847 MostDerivedClassDecl))
848 return false;
849 }
850 }
851
852 return true;
853}
854
855static bool
856FieldHasTrivialDestructorBody(ASTContext &Context,
857 const FieldDecl *Field)
858{
859 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
860
861 const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
862 if (!RT)
863 return true;
864
865 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
866 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
867}
868
Anders Carlssonffb945f2011-05-14 23:26:09 +0000869/// CanSkipVTablePointerInitialization - Check whether we need to initialize
870/// any vtable pointers before calling this destructor.
871static bool CanSkipVTablePointerInitialization(ASTContext &Context,
Anders Carlssone3d6cf22011-05-16 04:08:36 +0000872 const CXXDestructorDecl *Dtor) {
Anders Carlssonffb945f2011-05-14 23:26:09 +0000873 if (!Dtor->hasTrivialBody())
874 return false;
875
876 // Check the fields.
877 const CXXRecordDecl *ClassDecl = Dtor->getParent();
878 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
879 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +0000880 const FieldDecl *Field = *I;
Anders Carlssonffb945f2011-05-14 23:26:09 +0000881
Anders Carlssonadf5dc32011-05-15 17:36:21 +0000882 if (!FieldHasTrivialDestructorBody(Context, Field))
883 return false;
Anders Carlssonffb945f2011-05-14 23:26:09 +0000884 }
885
886 return true;
887}
888
John McCall9fc6a772010-02-19 09:25:03 +0000889/// EmitDestructorBody - Emits the body of the current destructor.
890void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
891 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
892 CXXDtorType DtorType = CurGD.getDtorType();
893
John McCall50da2ca2010-07-21 05:30:47 +0000894 // The call to operator delete in a deleting destructor happens
895 // outside of the function-try-block, which means it's always
896 // possible to delegate the destructor body to the complete
897 // destructor. Do so.
898 if (DtorType == Dtor_Deleting) {
899 EnterDtorCleanups(Dtor, Dtor_Deleting);
900 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
Douglas Gregor378e1e72013-01-31 05:50:40 +0000901 /*Delegating=*/false, LoadCXXThis());
John McCall50da2ca2010-07-21 05:30:47 +0000902 PopCleanupBlock();
903 return;
904 }
905
John McCall9fc6a772010-02-19 09:25:03 +0000906 Stmt *Body = Dtor->getBody();
907
908 // If the body is a function-try-block, enter the try before
John McCall50da2ca2010-07-21 05:30:47 +0000909 // anything else.
910 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCall9fc6a772010-02-19 09:25:03 +0000911 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +0000912 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000913
John McCall50da2ca2010-07-21 05:30:47 +0000914 // Enter the epilogue cleanups.
915 RunCleanupsScope DtorEpilogue(*this);
916
John McCall9fc6a772010-02-19 09:25:03 +0000917 // If this is the complete variant, just invoke the base variant;
918 // the epilogue will destruct the virtual bases. But we can't do
919 // this optimization if the body is a function-try-block, because
920 // we'd introduce *two* handler blocks.
John McCall50da2ca2010-07-21 05:30:47 +0000921 switch (DtorType) {
922 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
923
924 case Dtor_Complete:
925 // Enter the cleanup scopes for virtual bases.
926 EnterDtorCleanups(Dtor, Dtor_Complete);
927
John McCallb8b2c9d2013-01-25 22:30:49 +0000928 if (!isTryBody &&
929 CGM.getContext().getTargetInfo().getCXXABI().hasDestructorVariants()) {
John McCall50da2ca2010-07-21 05:30:47 +0000930 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
Douglas Gregor378e1e72013-01-31 05:50:40 +0000931 /*Delegating=*/false, LoadCXXThis());
John McCall50da2ca2010-07-21 05:30:47 +0000932 break;
933 }
934 // Fallthrough: act like we're in the base variant.
John McCall9fc6a772010-02-19 09:25:03 +0000935
John McCall50da2ca2010-07-21 05:30:47 +0000936 case Dtor_Base:
937 // Enter the cleanup scopes for fields and non-virtual bases.
938 EnterDtorCleanups(Dtor, Dtor_Base);
939
940 // Initialize the vtable pointers before entering the body.
Anders Carlssonffb945f2011-05-14 23:26:09 +0000941 if (!CanSkipVTablePointerInitialization(getContext(), Dtor))
942 InitializeVTablePointers(Dtor->getParent());
John McCall50da2ca2010-07-21 05:30:47 +0000943
944 if (isTryBody)
945 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
946 else if (Body)
947 EmitStmt(Body);
948 else {
949 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
950 // nothing to do besides what's in the epilogue
951 }
Fariborz Jahanian5abec142011-02-02 23:12:46 +0000952 // -fapple-kext must inline any call to this dtor into
953 // the caller's body.
Richard Smith7edf9e32012-11-01 22:30:59 +0000954 if (getLangOpts().AppleKext)
Bill Wendling72390b32012-12-20 19:27:06 +0000955 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
John McCall50da2ca2010-07-21 05:30:47 +0000956 break;
John McCall9fc6a772010-02-19 09:25:03 +0000957 }
958
John McCall50da2ca2010-07-21 05:30:47 +0000959 // Jump out through the epilogue cleanups.
960 DtorEpilogue.ForceCleanup();
John McCall9fc6a772010-02-19 09:25:03 +0000961
962 // Exit the try if applicable.
963 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +0000964 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000965}
966
John McCall50da2ca2010-07-21 05:30:47 +0000967namespace {
968 /// Call the operator delete associated with the current destructor.
John McCall1f0fca52010-07-21 07:22:38 +0000969 struct CallDtorDelete : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000970 CallDtorDelete() {}
971
John McCallad346f42011-07-12 20:27:29 +0000972 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall50da2ca2010-07-21 05:30:47 +0000973 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
974 const CXXRecordDecl *ClassDecl = Dtor->getParent();
975 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
976 CGF.getContext().getTagDeclType(ClassDecl));
977 }
978 };
979
John McCall9928c482011-07-12 16:41:08 +0000980 class DestroyField : public EHScopeStack::Cleanup {
981 const FieldDecl *field;
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000982 CodeGenFunction::Destroyer *destroyer;
John McCall9928c482011-07-12 16:41:08 +0000983 bool useEHCleanupForArray;
John McCall50da2ca2010-07-21 05:30:47 +0000984
John McCall9928c482011-07-12 16:41:08 +0000985 public:
986 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
987 bool useEHCleanupForArray)
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000988 : field(field), destroyer(destroyer),
John McCall9928c482011-07-12 16:41:08 +0000989 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall50da2ca2010-07-21 05:30:47 +0000990
John McCallad346f42011-07-12 20:27:29 +0000991 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall9928c482011-07-12 16:41:08 +0000992 // Find the address of the field.
993 llvm::Value *thisValue = CGF.LoadCXXThis();
Eli Friedman377ecc72012-04-16 03:54:45 +0000994 QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
995 LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
996 LValue LV = CGF.EmitLValueForField(ThisLV, field);
John McCall9928c482011-07-12 16:41:08 +0000997 assert(LV.isSimple());
998
999 CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
John McCallad346f42011-07-12 20:27:29 +00001000 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCall50da2ca2010-07-21 05:30:47 +00001001 }
1002 };
1003}
1004
Anders Carlsson607d0372009-12-24 22:46:43 +00001005/// EmitDtorEpilogue - Emit all code that comes at the end of class's
1006/// destructor. This is to call destructors on members and base classes
1007/// in reverse order of their construction.
John McCall50da2ca2010-07-21 05:30:47 +00001008void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
1009 CXXDtorType DtorType) {
Anders Carlsson607d0372009-12-24 22:46:43 +00001010 assert(!DD->isTrivial() &&
1011 "Should not emit dtor epilogue for trivial dtor!");
1012
John McCall50da2ca2010-07-21 05:30:47 +00001013 // The deleting-destructor phase just needs to call the appropriate
1014 // operator delete that Sema picked up.
John McCall3b477332010-02-18 19:59:28 +00001015 if (DtorType == Dtor_Deleting) {
1016 assert(DD->getOperatorDelete() &&
1017 "operator delete missing - EmitDtorEpilogue");
John McCall1f0fca52010-07-21 07:22:38 +00001018 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
John McCall3b477332010-02-18 19:59:28 +00001019 return;
1020 }
1021
John McCall50da2ca2010-07-21 05:30:47 +00001022 const CXXRecordDecl *ClassDecl = DD->getParent();
1023
Richard Smith416f63e2011-09-18 12:11:43 +00001024 // Unions have no bases and do not call field destructors.
1025 if (ClassDecl->isUnion())
1026 return;
1027
John McCall50da2ca2010-07-21 05:30:47 +00001028 // The complete-destructor phase just destructs all the virtual bases.
John McCall3b477332010-02-18 19:59:28 +00001029 if (DtorType == Dtor_Complete) {
John McCall50da2ca2010-07-21 05:30:47 +00001030
1031 // We push them in the forward order so that they'll be popped in
1032 // the reverse order.
1033 for (CXXRecordDecl::base_class_const_iterator I =
1034 ClassDecl->vbases_begin(), E = ClassDecl->vbases_end();
John McCall3b477332010-02-18 19:59:28 +00001035 I != E; ++I) {
1036 const CXXBaseSpecifier &Base = *I;
1037 CXXRecordDecl *BaseClassDecl
1038 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1039
1040 // Ignore trivial destructors.
1041 if (BaseClassDecl->hasTrivialDestructor())
1042 continue;
John McCall50da2ca2010-07-21 05:30:47 +00001043
John McCall1f0fca52010-07-21 07:22:38 +00001044 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1045 BaseClassDecl,
1046 /*BaseIsVirtual*/ true);
John McCall3b477332010-02-18 19:59:28 +00001047 }
John McCall50da2ca2010-07-21 05:30:47 +00001048
John McCall3b477332010-02-18 19:59:28 +00001049 return;
1050 }
1051
1052 assert(DtorType == Dtor_Base);
John McCall50da2ca2010-07-21 05:30:47 +00001053
1054 // Destroy non-virtual bases.
1055 for (CXXRecordDecl::base_class_const_iterator I =
1056 ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) {
1057 const CXXBaseSpecifier &Base = *I;
1058
1059 // Ignore virtual bases.
1060 if (Base.isVirtual())
1061 continue;
1062
1063 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
1064
1065 // Ignore trivial destructors.
1066 if (BaseClassDecl->hasTrivialDestructor())
1067 continue;
John McCall3b477332010-02-18 19:59:28 +00001068
John McCall1f0fca52010-07-21 07:22:38 +00001069 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1070 BaseClassDecl,
1071 /*BaseIsVirtual*/ false);
John McCall50da2ca2010-07-21 05:30:47 +00001072 }
1073
1074 // Destroy direct fields.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001075 SmallVector<const FieldDecl *, 16> FieldDecls;
Anders Carlsson607d0372009-12-24 22:46:43 +00001076 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1077 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001078 const FieldDecl *field = *I;
John McCall9928c482011-07-12 16:41:08 +00001079 QualType type = field->getType();
1080 QualType::DestructionKind dtorKind = type.isDestructedType();
1081 if (!dtorKind) continue;
John McCall50da2ca2010-07-21 05:30:47 +00001082
Richard Smith9a561d52012-02-26 09:11:52 +00001083 // Anonymous union members do not have their destructors called.
1084 const RecordType *RT = type->getAsUnionType();
1085 if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
1086
John McCall9928c482011-07-12 16:41:08 +00001087 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1088 EHStack.pushCleanup<DestroyField>(cleanupKind, field,
1089 getDestroyer(dtorKind),
1090 cleanupKind & EHCleanup);
Anders Carlsson607d0372009-12-24 22:46:43 +00001091 }
Anders Carlsson607d0372009-12-24 22:46:43 +00001092}
1093
John McCallc3c07662011-07-13 06:10:41 +00001094/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1095/// constructor for each of several members of an array.
Douglas Gregor59174c02010-07-21 01:10:17 +00001096///
John McCallc3c07662011-07-13 06:10:41 +00001097/// \param ctor the constructor to call for each element
John McCallc3c07662011-07-13 06:10:41 +00001098/// \param arrayType the type of the array to initialize
1099/// \param arrayBegin an arrayType*
1100/// \param zeroInitialize true if each element should be
1101/// zero-initialized before it is constructed
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001102void
John McCallc3c07662011-07-13 06:10:41 +00001103CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1104 const ConstantArrayType *arrayType,
1105 llvm::Value *arrayBegin,
1106 CallExpr::const_arg_iterator argBegin,
1107 CallExpr::const_arg_iterator argEnd,
1108 bool zeroInitialize) {
1109 QualType elementType;
1110 llvm::Value *numElements =
1111 emitArrayLength(arrayType, elementType, arrayBegin);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001112
John McCallc3c07662011-07-13 06:10:41 +00001113 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin,
1114 argBegin, argEnd, zeroInitialize);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001115}
1116
John McCallc3c07662011-07-13 06:10:41 +00001117/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1118/// constructor for each of several members of an array.
1119///
1120/// \param ctor the constructor to call for each element
1121/// \param numElements the number of elements in the array;
John McCalldd376ca2011-07-13 07:37:11 +00001122/// may be zero
John McCallc3c07662011-07-13 06:10:41 +00001123/// \param arrayBegin a T*, where T is the type constructed by ctor
1124/// \param zeroInitialize true if each element should be
1125/// zero-initialized before it is constructed
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001126void
John McCallc3c07662011-07-13 06:10:41 +00001127CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1128 llvm::Value *numElements,
1129 llvm::Value *arrayBegin,
1130 CallExpr::const_arg_iterator argBegin,
1131 CallExpr::const_arg_iterator argEnd,
1132 bool zeroInitialize) {
John McCalldd376ca2011-07-13 07:37:11 +00001133
1134 // It's legal for numElements to be zero. This can happen both
1135 // dynamically, because x can be zero in 'new A[x]', and statically,
1136 // because of GCC extensions that permit zero-length arrays. There
1137 // are probably legitimate places where we could assume that this
1138 // doesn't happen, but it's not clear that it's worth it.
1139 llvm::BranchInst *zeroCheckBranch = 0;
1140
1141 // Optimize for a constant count.
1142 llvm::ConstantInt *constantCount
1143 = dyn_cast<llvm::ConstantInt>(numElements);
1144 if (constantCount) {
1145 // Just skip out if the constant count is zero.
1146 if (constantCount->isZero()) return;
1147
1148 // Otherwise, emit the check.
1149 } else {
1150 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1151 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1152 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1153 EmitBlock(loopBB);
1154 }
1155
John McCallc3c07662011-07-13 06:10:41 +00001156 // Find the end of the array.
1157 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1158 "arrayctor.end");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001159
John McCallc3c07662011-07-13 06:10:41 +00001160 // Enter the loop, setting up a phi for the current location to initialize.
1161 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1162 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1163 EmitBlock(loopBB);
1164 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1165 "arrayctor.cur");
1166 cur->addIncoming(arrayBegin, entryBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001167
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001168 // Inside the loop body, emit the constructor call on the array element.
John McCallc3c07662011-07-13 06:10:41 +00001169
1170 QualType type = getContext().getTypeDeclType(ctor->getParent());
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001171
Douglas Gregor59174c02010-07-21 01:10:17 +00001172 // Zero initialize the storage, if requested.
John McCallc3c07662011-07-13 06:10:41 +00001173 if (zeroInitialize)
1174 EmitNullInitialization(cur, type);
Douglas Gregor59174c02010-07-21 01:10:17 +00001175
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001176 // C++ [class.temporary]p4:
1177 // There are two contexts in which temporaries are destroyed at a different
1178 // point than the end of the full-expression. The first context is when a
1179 // default constructor is called to initialize an element of an array.
1180 // If the constructor has one or more default arguments, the destruction of
1181 // every temporary created in a default argument expression is sequenced
1182 // before the construction of the next array element, if any.
1183
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001184 {
John McCallf1549f62010-07-06 01:34:17 +00001185 RunCleanupsScope Scope(*this);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001186
John McCallc3c07662011-07-13 06:10:41 +00001187 // Evaluate the constructor and its arguments in a regular
1188 // partial-destroy cleanup.
David Blaikie4e4d0842012-03-11 07:00:24 +00001189 if (getLangOpts().Exceptions &&
John McCallc3c07662011-07-13 06:10:41 +00001190 !ctor->getParent()->hasTrivialDestructor()) {
1191 Destroyer *destroyer = destroyCXXObject;
1192 pushRegularPartialArrayCleanup(arrayBegin, cur, type, *destroyer);
1193 }
1194
1195 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/ false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001196 /*Delegating=*/false, cur, argBegin, argEnd);
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001197 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001198
John McCallc3c07662011-07-13 06:10:41 +00001199 // Go to the next element.
1200 llvm::Value *next =
1201 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
1202 "arrayctor.next");
1203 cur->addIncoming(next, Builder.GetInsertBlock());
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001204
John McCallc3c07662011-07-13 06:10:41 +00001205 // Check whether that's the end of the loop.
1206 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
1207 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
1208 Builder.CreateCondBr(done, contBB, loopBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001209
John McCalldd376ca2011-07-13 07:37:11 +00001210 // Patch the earlier check to skip over the loop.
1211 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
1212
John McCallc3c07662011-07-13 06:10:41 +00001213 EmitBlock(contBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001214}
1215
John McCallbdc4d802011-07-09 01:37:26 +00001216void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
1217 llvm::Value *addr,
1218 QualType type) {
1219 const RecordType *rtype = type->castAs<RecordType>();
1220 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
1221 const CXXDestructorDecl *dtor = record->getDestructor();
1222 assert(!dtor->isTrivial());
1223 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001224 /*Delegating=*/false, addr);
John McCallbdc4d802011-07-09 01:37:26 +00001225}
1226
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001227void
1228CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
Anders Carlsson155ed4a2010-05-02 23:20:53 +00001229 CXXCtorType Type, bool ForVirtualBase,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001230 bool Delegating,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001231 llvm::Value *This,
1232 CallExpr::const_arg_iterator ArgBeg,
1233 CallExpr::const_arg_iterator ArgEnd) {
Devang Patel3ee36af2011-02-22 20:55:26 +00001234
1235 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonov3a70cd62012-04-27 07:24:20 +00001236 if (DI &&
Douglas Gregor4cdad312012-10-23 20:05:01 +00001237 CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::LimitedDebugInfo) {
Eric Christopheraf790882012-02-01 21:44:56 +00001238 // If debug info for this class has not been emitted then this is the
1239 // right time to do so.
Devang Patel3ee36af2011-02-22 20:55:26 +00001240 const CXXRecordDecl *Parent = D->getParent();
1241 DI->getOrCreateRecordType(CGM.getContext().getTypeDeclType(Parent),
1242 Parent->getLocation());
1243 }
1244
John McCall8b6bbeb2010-02-06 00:25:16 +00001245 if (D->isTrivial()) {
1246 if (ArgBeg == ArgEnd) {
1247 // Trivial default constructor, no codegen required.
1248 assert(D->isDefaultConstructor() &&
1249 "trivial 0-arg ctor not a default ctor");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001250 return;
1251 }
John McCall8b6bbeb2010-02-06 00:25:16 +00001252
1253 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001254 assert(D->isCopyOrMoveConstructor() &&
1255 "trivial 1-arg ctor not a copy/move ctor");
John McCall8b6bbeb2010-02-06 00:25:16 +00001256
John McCall8b6bbeb2010-02-06 00:25:16 +00001257 const Expr *E = (*ArgBeg);
1258 QualType Ty = E->getType();
1259 llvm::Value *Src = EmitLValue(E).getAddress();
1260 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001261 return;
1262 }
1263
Douglas Gregor378e1e72013-01-31 05:50:40 +00001264 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(D, Type), ForVirtualBase,
1265 Delegating);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001266 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
1267
Richard Smith4def70d2012-10-09 19:52:38 +00001268 // FIXME: Provide a source location here.
1269 EmitCXXMemberCall(D, SourceLocation(), Callee, ReturnValueSlot(), This,
1270 VTT, ArgBeg, ArgEnd);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001271}
1272
John McCallc0bf4622010-02-23 00:48:20 +00001273void
Fariborz Jahanian34999872010-11-13 21:53:34 +00001274CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
1275 llvm::Value *This, llvm::Value *Src,
1276 CallExpr::const_arg_iterator ArgBeg,
1277 CallExpr::const_arg_iterator ArgEnd) {
1278 if (D->isTrivial()) {
1279 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001280 assert(D->isCopyOrMoveConstructor() &&
1281 "trivial 1-arg ctor not a copy/move ctor");
Fariborz Jahanian34999872010-11-13 21:53:34 +00001282 EmitAggregateCopy(This, Src, (*ArgBeg)->getType());
1283 return;
1284 }
1285 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D,
1286 clang::Ctor_Complete);
1287 assert(D->isInstance() &&
1288 "Trying to emit a member call expr on a static method!");
1289
1290 const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
1291
1292 CallArgList Args;
1293
1294 // Push the this ptr.
Eli Friedman04c9a492011-05-02 17:57:46 +00001295 Args.add(RValue::get(This), D->getThisType(getContext()));
Fariborz Jahanian34999872010-11-13 21:53:34 +00001296
1297
1298 // Push the src ptr.
1299 QualType QT = *(FPT->arg_type_begin());
Chris Lattner2acc6e32011-07-18 04:24:23 +00001300 llvm::Type *t = CGM.getTypes().ConvertType(QT);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001301 Src = Builder.CreateBitCast(Src, t);
Eli Friedman04c9a492011-05-02 17:57:46 +00001302 Args.add(RValue::get(Src), QT);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001303
1304 // Skip over first argument (Src).
1305 ++ArgBeg;
1306 CallExpr::const_arg_iterator Arg = ArgBeg;
1307 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin()+1,
1308 E = FPT->arg_type_end(); I != E; ++I, ++Arg) {
1309 assert(Arg != ArgEnd && "Running over edge of argument list!");
John McCall413ebdb2011-03-11 20:59:21 +00001310 EmitCallArg(Args, *Arg, *I);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001311 }
1312 // Either we've emitted all the call args, or we have a call to a
1313 // variadic function.
1314 assert((Arg == ArgEnd || FPT->isVariadic()) &&
1315 "Extra arguments in non-variadic function!");
1316 // If we still have any arguments, emit them using the type of the argument.
1317 for (; Arg != ArgEnd; ++Arg) {
1318 QualType ArgType = Arg->getType();
John McCall413ebdb2011-03-11 20:59:21 +00001319 EmitCallArg(Args, *Arg, ArgType);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001320 }
1321
John McCall0f3d0972012-07-07 06:41:13 +00001322 EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, RequiredArgs::All),
1323 Callee, ReturnValueSlot(), Args, D);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001324}
1325
1326void
John McCallc0bf4622010-02-23 00:48:20 +00001327CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1328 CXXCtorType CtorType,
1329 const FunctionArgList &Args) {
1330 CallArgList DelegateArgs;
1331
1332 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
1333 assert(I != E && "no parameters to constructor");
1334
1335 // this
Eli Friedman04c9a492011-05-02 17:57:46 +00001336 DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType());
John McCallc0bf4622010-02-23 00:48:20 +00001337 ++I;
1338
1339 // vtt
Anders Carlsson314e6222010-05-02 23:33:10 +00001340 if (llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(Ctor, CtorType),
Douglas Gregor378e1e72013-01-31 05:50:40 +00001341 /*ForVirtualBase=*/false,
1342 /*Delegating=*/true)) {
John McCallc0bf4622010-02-23 00:48:20 +00001343 QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
Eli Friedman04c9a492011-05-02 17:57:46 +00001344 DelegateArgs.add(RValue::get(VTT), VoidPP);
John McCallc0bf4622010-02-23 00:48:20 +00001345
Anders Carlssonaf440352010-03-23 04:11:45 +00001346 if (CodeGenVTables::needsVTTParameter(CurGD)) {
John McCallc0bf4622010-02-23 00:48:20 +00001347 assert(I != E && "cannot skip vtt parameter, already done with args");
John McCalld26bc762011-03-09 04:27:21 +00001348 assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
John McCallc0bf4622010-02-23 00:48:20 +00001349 ++I;
1350 }
1351 }
1352
1353 // Explicit arguments.
1354 for (; I != E; ++I) {
John McCall413ebdb2011-03-11 20:59:21 +00001355 const VarDecl *param = *I;
1356 EmitDelegateCallArg(DelegateArgs, param);
John McCallc0bf4622010-02-23 00:48:20 +00001357 }
1358
John McCallde5d3c72012-02-17 03:33:10 +00001359 EmitCall(CGM.getTypes().arrangeCXXConstructorDeclaration(Ctor, CtorType),
John McCallc0bf4622010-02-23 00:48:20 +00001360 CGM.GetAddrOfCXXConstructor(Ctor, CtorType),
1361 ReturnValueSlot(), DelegateArgs, Ctor);
1362}
1363
Sean Huntb76af9c2011-05-03 23:05:34 +00001364namespace {
1365 struct CallDelegatingCtorDtor : EHScopeStack::Cleanup {
1366 const CXXDestructorDecl *Dtor;
1367 llvm::Value *Addr;
1368 CXXDtorType Type;
1369
1370 CallDelegatingCtorDtor(const CXXDestructorDecl *D, llvm::Value *Addr,
1371 CXXDtorType Type)
1372 : Dtor(D), Addr(Addr), Type(Type) {}
1373
John McCallad346f42011-07-12 20:27:29 +00001374 void Emit(CodeGenFunction &CGF, Flags flags) {
Sean Huntb76af9c2011-05-03 23:05:34 +00001375 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001376 /*Delegating=*/true, Addr);
Sean Huntb76af9c2011-05-03 23:05:34 +00001377 }
1378 };
1379}
1380
Sean Hunt059ce0d2011-05-01 07:04:31 +00001381void
1382CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
1383 const FunctionArgList &Args) {
1384 assert(Ctor->isDelegatingConstructor());
1385
1386 llvm::Value *ThisPtr = LoadCXXThis();
1387
Eli Friedmanf3940782011-12-03 00:54:26 +00001388 QualType Ty = getContext().getTagDeclType(Ctor->getParent());
Eli Friedmand7722d92011-12-03 02:13:40 +00001389 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
John McCallf85e1932011-06-15 23:02:42 +00001390 AggValueSlot AggSlot =
Eli Friedmanf3940782011-12-03 00:54:26 +00001391 AggValueSlot::forAddr(ThisPtr, Alignment, Qualifiers(),
John McCall7c2349b2011-08-25 20:40:09 +00001392 AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +00001393 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +00001394 AggValueSlot::IsNotAliased);
Sean Hunt059ce0d2011-05-01 07:04:31 +00001395
1396 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
Sean Hunt059ce0d2011-05-01 07:04:31 +00001397
Sean Huntb76af9c2011-05-03 23:05:34 +00001398 const CXXRecordDecl *ClassDecl = Ctor->getParent();
David Blaikie4e4d0842012-03-11 07:00:24 +00001399 if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
Sean Huntb76af9c2011-05-03 23:05:34 +00001400 CXXDtorType Type =
1401 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
1402
1403 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
1404 ClassDecl->getDestructor(),
1405 ThisPtr, Type);
1406 }
1407}
Sean Hunt059ce0d2011-05-01 07:04:31 +00001408
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001409void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
1410 CXXDtorType Type,
Anders Carlsson8e6404c2010-05-02 23:29:11 +00001411 bool ForVirtualBase,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001412 bool Delegating,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001413 llvm::Value *This) {
Anders Carlsson314e6222010-05-02 23:33:10 +00001414 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(DD, Type),
Douglas Gregor378e1e72013-01-31 05:50:40 +00001415 ForVirtualBase, Delegating);
Fariborz Jahanianccd52592011-02-01 23:22:34 +00001416 llvm::Value *Callee = 0;
Richard Smith7edf9e32012-11-01 22:30:59 +00001417 if (getLangOpts().AppleKext)
Fariborz Jahanian771c6782011-02-03 19:27:17 +00001418 Callee = BuildAppleKextVirtualDestructorCall(DD, Type,
1419 DD->getParent());
Fariborz Jahanianccd52592011-02-01 23:22:34 +00001420
1421 if (!Callee)
1422 Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001423
Richard Smith4def70d2012-10-09 19:52:38 +00001424 // FIXME: Provide a source location here.
1425 EmitCXXMemberCall(DD, SourceLocation(), Callee, ReturnValueSlot(), This,
1426 VTT, 0, 0);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001427}
1428
John McCall291ae942010-07-21 01:41:18 +00001429namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001430 struct CallLocalDtor : EHScopeStack::Cleanup {
John McCall291ae942010-07-21 01:41:18 +00001431 const CXXDestructorDecl *Dtor;
1432 llvm::Value *Addr;
1433
1434 CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
1435 : Dtor(D), Addr(Addr) {}
1436
John McCallad346f42011-07-12 20:27:29 +00001437 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall291ae942010-07-21 01:41:18 +00001438 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001439 /*ForVirtualBase=*/false,
1440 /*Delegating=*/false, Addr);
John McCall291ae942010-07-21 01:41:18 +00001441 }
1442 };
1443}
1444
John McCall81407d42010-07-21 06:29:51 +00001445void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
1446 llvm::Value *Addr) {
John McCall1f0fca52010-07-21 07:22:38 +00001447 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
John McCall81407d42010-07-21 06:29:51 +00001448}
1449
John McCallf1549f62010-07-06 01:34:17 +00001450void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
1451 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
1452 if (!ClassDecl) return;
1453 if (ClassDecl->hasTrivialDestructor()) return;
1454
1455 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCall642a75f2011-04-28 02:15:35 +00001456 assert(D && D->isUsed() && "destructor not marked as used!");
John McCall81407d42010-07-21 06:29:51 +00001457 PushDestructorCleanup(D, Addr);
John McCallf1549f62010-07-06 01:34:17 +00001458}
1459
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001460llvm::Value *
Anders Carlssonbb7e17b2010-01-31 01:36:53 +00001461CodeGenFunction::GetVirtualBaseClassOffset(llvm::Value *This,
1462 const CXXRecordDecl *ClassDecl,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001463 const CXXRecordDecl *BaseClassDecl) {
Dan Gohman043fb9a2010-10-26 18:44:08 +00001464 llvm::Value *VTablePtr = GetVTablePtr(This, Int8PtrTy);
Ken Dyck14c65ca2011-04-07 12:37:09 +00001465 CharUnits VBaseOffsetOffset =
Peter Collingbourne1d2b3172011-09-26 01:56:30 +00001466 CGM.getVTableContext().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001467
1468 llvm::Value *VBaseOffsetPtr =
Ken Dyck14c65ca2011-04-07 12:37:09 +00001469 Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1470 "vbase.offset.ptr");
Chris Lattner2acc6e32011-07-18 04:24:23 +00001471 llvm::Type *PtrDiffTy =
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001472 ConvertType(getContext().getPointerDiffType());
1473
1474 VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr,
1475 PtrDiffTy->getPointerTo());
1476
1477 llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1478
1479 return VBaseOffset;
1480}
1481
Anders Carlssond103f9f2010-03-28 19:40:00 +00001482void
1483CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001484 const CXXRecordDecl *NearestVBase,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001485 CharUnits OffsetFromNearestVBase,
Anders Carlssond103f9f2010-03-28 19:40:00 +00001486 llvm::Constant *VTable,
1487 const CXXRecordDecl *VTableClass) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001488 const CXXRecordDecl *RD = Base.getBase();
1489
Anders Carlssond103f9f2010-03-28 19:40:00 +00001490 // Compute the address point.
Anders Carlssonc83f1062010-03-29 01:08:49 +00001491 llvm::Value *VTableAddressPoint;
Anders Carlsson851853d2010-03-29 02:38:51 +00001492
Anders Carlssonc83f1062010-03-29 01:08:49 +00001493 // Check if we need to use a vtable from the VTT.
Anders Carlsson851853d2010-03-29 02:38:51 +00001494 if (CodeGenVTables::needsVTTParameter(CurGD) &&
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001495 (RD->getNumVBases() || NearestVBase)) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001496 // Get the secondary vpointer index.
1497 uint64_t VirtualPointerIndex =
1498 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1499
1500 /// Load the VTT.
1501 llvm::Value *VTT = LoadCXXVTT();
1502 if (VirtualPointerIndex)
1503 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1504
1505 // And load the address point from the VTT.
1506 VTableAddressPoint = Builder.CreateLoad(VTT);
1507 } else {
Peter Collingbourne84fcc482011-09-26 01:56:41 +00001508 uint64_t AddressPoint =
Peter Collingbournee09cdf42011-09-26 01:56:50 +00001509 CGM.getVTableContext().getVTableLayout(VTableClass).getAddressPoint(Base);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001510 VTableAddressPoint =
Anders Carlssond103f9f2010-03-28 19:40:00 +00001511 Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001512 }
Anders Carlssond103f9f2010-03-28 19:40:00 +00001513
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001514 // Compute where to store the address point.
Anders Carlsson8246cc72010-05-03 00:29:58 +00001515 llvm::Value *VirtualOffset = 0;
Ken Dyck9a8ad9b2011-03-23 00:45:26 +00001516 CharUnits NonVirtualOffset = CharUnits::Zero();
Anders Carlsson3e79c302010-04-20 18:05:10 +00001517
1518 if (CodeGenVTables::needsVTTParameter(CurGD) && NearestVBase) {
1519 // We need to use the virtual base offset offset because the virtual base
1520 // might have a different offset in the most derived class.
Anders Carlsson8246cc72010-05-03 00:29:58 +00001521 VirtualOffset = GetVirtualBaseClassOffset(LoadCXXThis(), VTableClass,
1522 NearestVBase);
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001523 NonVirtualOffset = OffsetFromNearestVBase;
Anders Carlsson3e79c302010-04-20 18:05:10 +00001524 } else {
Anders Carlsson8246cc72010-05-03 00:29:58 +00001525 // We can just use the base offset in the complete class.
Ken Dyck4230d522011-03-24 01:21:01 +00001526 NonVirtualOffset = Base.getBaseOffset();
Anders Carlsson3e79c302010-04-20 18:05:10 +00001527 }
Anders Carlsson8246cc72010-05-03 00:29:58 +00001528
1529 // Apply the offsets.
1530 llvm::Value *VTableField = LoadCXXThis();
1531
Ken Dyck9a8ad9b2011-03-23 00:45:26 +00001532 if (!NonVirtualOffset.isZero() || VirtualOffset)
Anders Carlsson8246cc72010-05-03 00:29:58 +00001533 VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
1534 NonVirtualOffset,
1535 VirtualOffset);
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001536
Anders Carlssond103f9f2010-03-28 19:40:00 +00001537 // Finally, store the address point.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001538 llvm::Type *AddressPointPtrTy =
Anders Carlssond103f9f2010-03-28 19:40:00 +00001539 VTableAddressPoint->getType()->getPointerTo();
1540 VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
Kostya Serebryany8cb4a072012-03-26 17:03:51 +00001541 llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
1542 CGM.DecorateInstruction(Store, CGM.getTBAAInfoForVTablePtr());
Anders Carlssond103f9f2010-03-28 19:40:00 +00001543}
1544
Anders Carlsson603d6d12010-03-28 21:07:49 +00001545void
1546CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001547 const CXXRecordDecl *NearestVBase,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001548 CharUnits OffsetFromNearestVBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001549 bool BaseIsNonVirtualPrimaryBase,
1550 llvm::Constant *VTable,
1551 const CXXRecordDecl *VTableClass,
1552 VisitedVirtualBasesSetTy& VBases) {
1553 // If this base is a non-virtual primary base the address point has already
1554 // been set.
1555 if (!BaseIsNonVirtualPrimaryBase) {
1556 // Initialize the vtable pointer for this base.
Anders Carlsson42358402010-05-03 00:07:07 +00001557 InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
1558 VTable, VTableClass);
Anders Carlsson603d6d12010-03-28 21:07:49 +00001559 }
1560
1561 const CXXRecordDecl *RD = Base.getBase();
1562
1563 // Traverse bases.
1564 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1565 E = RD->bases_end(); I != E; ++I) {
1566 CXXRecordDecl *BaseDecl
1567 = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1568
1569 // Ignore classes without a vtable.
1570 if (!BaseDecl->isDynamicClass())
1571 continue;
1572
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001573 CharUnits BaseOffset;
1574 CharUnits BaseOffsetFromNearestVBase;
Anders Carlsson14da9de2010-03-29 01:16:41 +00001575 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001576
1577 if (I->isVirtual()) {
1578 // Check if we've visited this virtual base before.
1579 if (!VBases.insert(BaseDecl))
1580 continue;
1581
1582 const ASTRecordLayout &Layout =
1583 getContext().getASTRecordLayout(VTableClass);
1584
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001585 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
1586 BaseOffsetFromNearestVBase = CharUnits::Zero();
Anders Carlsson14da9de2010-03-29 01:16:41 +00001587 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001588 } else {
1589 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1590
Ken Dyck4230d522011-03-24 01:21:01 +00001591 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson42358402010-05-03 00:07:07 +00001592 BaseOffsetFromNearestVBase =
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001593 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson14da9de2010-03-29 01:16:41 +00001594 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001595 }
1596
Ken Dyck4230d522011-03-24 01:21:01 +00001597 InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001598 I->isVirtual() ? BaseDecl : NearestVBase,
Anders Carlsson42358402010-05-03 00:07:07 +00001599 BaseOffsetFromNearestVBase,
Anders Carlsson14da9de2010-03-29 01:16:41 +00001600 BaseDeclIsNonVirtualPrimaryBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001601 VTable, VTableClass, VBases);
1602 }
1603}
1604
1605void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
1606 // Ignore classes without a vtable.
Anders Carlsson07036902010-03-26 04:39:42 +00001607 if (!RD->isDynamicClass())
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001608 return;
1609
Anders Carlsson07036902010-03-26 04:39:42 +00001610 // Get the VTable.
1611 llvm::Constant *VTable = CGM.getVTables().GetAddrOfVTable(RD);
Anders Carlsson5c6c1d92010-03-24 03:57:14 +00001612
Anders Carlsson603d6d12010-03-28 21:07:49 +00001613 // Initialize the vtable pointers for this class and all of its bases.
1614 VisitedVirtualBasesSetTy VBases;
Ken Dyck4230d522011-03-24 01:21:01 +00001615 InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()),
1616 /*NearestVBase=*/0,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001617 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
Anders Carlsson603d6d12010-03-28 21:07:49 +00001618 /*BaseIsNonVirtualPrimaryBase=*/false,
1619 VTable, RD, VBases);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001620}
Dan Gohman043fb9a2010-10-26 18:44:08 +00001621
1622llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001623 llvm::Type *Ty) {
Dan Gohman043fb9a2010-10-26 18:44:08 +00001624 llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
Kostya Serebryany8cb4a072012-03-26 17:03:51 +00001625 llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
1626 CGM.DecorateInstruction(VTable, CGM.getTBAAInfoForVTablePtr());
1627 return VTable;
Dan Gohman043fb9a2010-10-26 18:44:08 +00001628}
Anders Carlssona2447e02011-05-08 20:32:23 +00001629
1630static const CXXRecordDecl *getMostDerivedClassDecl(const Expr *Base) {
1631 const Expr *E = Base;
1632
1633 while (true) {
1634 E = E->IgnoreParens();
1635 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
1636 if (CE->getCastKind() == CK_DerivedToBase ||
1637 CE->getCastKind() == CK_UncheckedDerivedToBase ||
1638 CE->getCastKind() == CK_NoOp) {
1639 E = CE->getSubExpr();
1640 continue;
1641 }
1642 }
1643
1644 break;
1645 }
1646
1647 QualType DerivedType = E->getType();
1648 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
1649 DerivedType = PTy->getPointeeType();
1650
1651 return cast<CXXRecordDecl>(DerivedType->castAs<RecordType>()->getDecl());
1652}
1653
1654// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
1655// quite what we want.
1656static const Expr *skipNoOpCastsAndParens(const Expr *E) {
1657 while (true) {
1658 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
1659 E = PE->getSubExpr();
1660 continue;
1661 }
1662
1663 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
1664 if (CE->getCastKind() == CK_NoOp) {
1665 E = CE->getSubExpr();
1666 continue;
1667 }
1668 }
1669 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1670 if (UO->getOpcode() == UO_Extension) {
1671 E = UO->getSubExpr();
1672 continue;
1673 }
1674 }
1675 return E;
1676 }
1677}
1678
1679/// canDevirtualizeMemberFunctionCall - Checks whether the given virtual member
1680/// function call on the given expr can be devirtualized.
Anders Carlssona2447e02011-05-08 20:32:23 +00001681static bool canDevirtualizeMemberFunctionCall(const Expr *Base,
1682 const CXXMethodDecl *MD) {
1683 // If the most derived class is marked final, we know that no subclass can
1684 // override this member function and so we can devirtualize it. For example:
1685 //
1686 // struct A { virtual void f(); }
1687 // struct B final : A { };
1688 //
1689 // void f(B *b) {
1690 // b->f();
1691 // }
1692 //
1693 const CXXRecordDecl *MostDerivedClassDecl = getMostDerivedClassDecl(Base);
1694 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
1695 return true;
1696
1697 // If the member function is marked 'final', we know that it can't be
1698 // overridden and can therefore devirtualize it.
1699 if (MD->hasAttr<FinalAttr>())
1700 return true;
1701
1702 // Similarly, if the class itself is marked 'final' it can't be overridden
1703 // and we can therefore devirtualize the member function call.
1704 if (MD->getParent()->hasAttr<FinalAttr>())
1705 return true;
1706
1707 Base = skipNoOpCastsAndParens(Base);
1708 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
1709 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
1710 // This is a record decl. We know the type and can devirtualize it.
1711 return VD->getType()->isRecordType();
1712 }
1713
1714 return false;
1715 }
1716
1717 // We can always devirtualize calls on temporary object expressions.
1718 if (isa<CXXConstructExpr>(Base))
1719 return true;
1720
1721 // And calls on bound temporaries.
1722 if (isa<CXXBindTemporaryExpr>(Base))
1723 return true;
1724
1725 // Check if this is a call expr that returns a record type.
1726 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
1727 return CE->getCallReturnType()->isRecordType();
1728
1729 // We can't devirtualize the call.
1730 return false;
1731}
1732
1733static bool UseVirtualCall(ASTContext &Context,
1734 const CXXOperatorCallExpr *CE,
1735 const CXXMethodDecl *MD) {
1736 if (!MD->isVirtual())
1737 return false;
1738
1739 // When building with -fapple-kext, all calls must go through the vtable since
1740 // the kernel linker can do runtime patching of vtables.
David Blaikie4e4d0842012-03-11 07:00:24 +00001741 if (Context.getLangOpts().AppleKext)
Anders Carlssona2447e02011-05-08 20:32:23 +00001742 return true;
1743
1744 return !canDevirtualizeMemberFunctionCall(CE->getArg(0), MD);
1745}
1746
1747llvm::Value *
1748CodeGenFunction::EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E,
1749 const CXXMethodDecl *MD,
1750 llvm::Value *This) {
John McCallde5d3c72012-02-17 03:33:10 +00001751 llvm::FunctionType *fnType =
1752 CGM.getTypes().GetFunctionType(
1753 CGM.getTypes().arrangeCXXMethodDeclaration(MD));
Anders Carlssona2447e02011-05-08 20:32:23 +00001754
1755 if (UseVirtualCall(getContext(), E, MD))
John McCallde5d3c72012-02-17 03:33:10 +00001756 return BuildVirtualCall(MD, This, fnType);
Anders Carlssona2447e02011-05-08 20:32:23 +00001757
John McCallde5d3c72012-02-17 03:33:10 +00001758 return CGM.GetAddrOfFunction(MD, fnType);
Anders Carlssona2447e02011-05-08 20:32:23 +00001759}
Eli Friedmanbd89f8c2012-02-16 01:37:33 +00001760
John McCall0f3d0972012-07-07 06:41:13 +00001761void CodeGenFunction::EmitForwardingCallToLambda(const CXXRecordDecl *lambda,
1762 CallArgList &callArgs) {
Eli Friedman64bee652012-02-25 02:48:22 +00001763 // Lookup the call operator
John McCall0f3d0972012-07-07 06:41:13 +00001764 DeclarationName operatorName
Eli Friedman21f6ed92012-02-16 03:47:28 +00001765 = getContext().DeclarationNames.getCXXOperatorName(OO_Call);
John McCall0f3d0972012-07-07 06:41:13 +00001766 CXXMethodDecl *callOperator =
David Blaikie3bc93e32012-12-19 00:45:41 +00001767 cast<CXXMethodDecl>(lambda->lookup(operatorName).front());
Eli Friedman21f6ed92012-02-16 03:47:28 +00001768
Eli Friedman21f6ed92012-02-16 03:47:28 +00001769 // Get the address of the call operator.
John McCall0f3d0972012-07-07 06:41:13 +00001770 const CGFunctionInfo &calleeFnInfo =
1771 CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
1772 llvm::Value *callee =
1773 CGM.GetAddrOfFunction(GlobalDecl(callOperator),
1774 CGM.getTypes().GetFunctionType(calleeFnInfo));
Eli Friedman21f6ed92012-02-16 03:47:28 +00001775
John McCall0f3d0972012-07-07 06:41:13 +00001776 // Prepare the return slot.
1777 const FunctionProtoType *FPT =
1778 callOperator->getType()->castAs<FunctionProtoType>();
1779 QualType resultType = FPT->getResultType();
1780 ReturnValueSlot returnSlot;
1781 if (!resultType->isVoidType() &&
1782 calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
1783 hasAggregateLLVMType(calleeFnInfo.getReturnType()))
1784 returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
1785
1786 // We don't need to separately arrange the call arguments because
1787 // the call can't be variadic anyway --- it's impossible to forward
1788 // variadic arguments.
Eli Friedman21f6ed92012-02-16 03:47:28 +00001789
1790 // Now emit our call.
John McCall0f3d0972012-07-07 06:41:13 +00001791 RValue RV = EmitCall(calleeFnInfo, callee, returnSlot,
1792 callArgs, callOperator);
Eli Friedman21f6ed92012-02-16 03:47:28 +00001793
John McCall0f3d0972012-07-07 06:41:13 +00001794 // If necessary, copy the returned value into the slot.
1795 if (!resultType->isVoidType() && returnSlot.isNull())
1796 EmitReturnOfRValue(RV, resultType);
Eli Friedman50f089a2012-12-13 23:37:17 +00001797 else
1798 EmitBranchThroughCleanup(ReturnBlock);
Eli Friedman21f6ed92012-02-16 03:47:28 +00001799}
1800
Eli Friedman64bee652012-02-25 02:48:22 +00001801void CodeGenFunction::EmitLambdaBlockInvokeBody() {
1802 const BlockDecl *BD = BlockInfo->getBlockDecl();
1803 const VarDecl *variable = BD->capture_begin()->getVariable();
1804 const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
1805
1806 // Start building arguments for forwarding call
1807 CallArgList CallArgs;
1808
1809 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
1810 llvm::Value *ThisPtr = GetAddrOfBlockDecl(variable, false);
1811 CallArgs.add(RValue::get(ThisPtr), ThisType);
1812
1813 // Add the rest of the parameters.
1814 for (BlockDecl::param_const_iterator I = BD->param_begin(),
1815 E = BD->param_end(); I != E; ++I) {
1816 ParmVarDecl *param = *I;
1817 EmitDelegateCallArg(CallArgs, param);
1818 }
1819
1820 EmitForwardingCallToLambda(Lambda, CallArgs);
1821}
1822
1823void CodeGenFunction::EmitLambdaToBlockPointerBody(FunctionArgList &Args) {
1824 if (cast<CXXMethodDecl>(CurFuncDecl)->isVariadic()) {
1825 // FIXME: Making this work correctly is nasty because it requires either
1826 // cloning the body of the call operator or making the call operator forward.
1827 CGM.ErrorUnsupported(CurFuncDecl, "lambda conversion to variadic function");
1828 return;
1829 }
1830
Eli Friedman64bee652012-02-25 02:48:22 +00001831 EmitFunctionBody(Args);
Eli Friedman64bee652012-02-25 02:48:22 +00001832}
1833
1834void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
1835 const CXXRecordDecl *Lambda = MD->getParent();
1836
1837 // Start building arguments for forwarding call
1838 CallArgList CallArgs;
1839
1840 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
1841 llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
1842 CallArgs.add(RValue::get(ThisPtr), ThisType);
1843
1844 // Add the rest of the parameters.
1845 for (FunctionDecl::param_const_iterator I = MD->param_begin(),
1846 E = MD->param_end(); I != E; ++I) {
1847 ParmVarDecl *param = *I;
1848 EmitDelegateCallArg(CallArgs, param);
1849 }
1850
1851 EmitForwardingCallToLambda(Lambda, CallArgs);
1852}
1853
Douglas Gregor27dd7d92012-02-17 03:02:34 +00001854void CodeGenFunction::EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD) {
1855 if (MD->isVariadic()) {
Eli Friedman21f6ed92012-02-16 03:47:28 +00001856 // FIXME: Making this work correctly is nasty because it requires either
1857 // cloning the body of the call operator or making the call operator forward.
1858 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
Eli Friedman64bee652012-02-25 02:48:22 +00001859 return;
Eli Friedman21f6ed92012-02-16 03:47:28 +00001860 }
1861
Douglas Gregor27dd7d92012-02-17 03:02:34 +00001862 EmitLambdaDelegatingInvokeBody(MD);
Eli Friedmanbd89f8c2012-02-16 01:37:33 +00001863}