blob: 585d3ba54e7fcf3ddd595807e8cb6988bfe87084 [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,
285 bool ForVirtualBase) {
Anders Carlssonaf440352010-03-23 04:11:45 +0000286 if (!CodeGenVTables::needsVTTParameter(GD)) {
Anders Carlssonc997d422010-01-02 01:01:18 +0000287 // This constructor/destructor does not need a VTT parameter.
288 return 0;
289 }
290
291 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CGF.CurFuncDecl)->getParent();
292 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
John McCall3b477332010-02-18 19:59:28 +0000293
Anders Carlssonc997d422010-01-02 01:01:18 +0000294 llvm::Value *VTT;
295
John McCall3b477332010-02-18 19:59:28 +0000296 uint64_t SubVTTIndex;
297
298 // If the record matches the base, this is the complete ctor/dtor
299 // variant calling the base variant in a class with virtual bases.
300 if (RD == Base) {
Anders Carlssonaf440352010-03-23 04:11:45 +0000301 assert(!CodeGenVTables::needsVTTParameter(CGF.CurGD) &&
John McCall3b477332010-02-18 19:59:28 +0000302 "doing no-op VTT offset in base dtor/ctor?");
Anders Carlsson314e6222010-05-02 23:33:10 +0000303 assert(!ForVirtualBase && "Can't have same class as virtual base!");
John McCall3b477332010-02-18 19:59:28 +0000304 SubVTTIndex = 0;
305 } else {
Anders Carlssonc11bb212010-05-02 23:53:25 +0000306 const ASTRecordLayout &Layout =
307 CGF.getContext().getASTRecordLayout(RD);
Ken Dyck4230d522011-03-24 01:21:01 +0000308 CharUnits BaseOffset = ForVirtualBase ?
309 Layout.getVBaseClassOffset(Base) :
310 Layout.getBaseClassOffset(Base);
Anders Carlssonc11bb212010-05-02 23:53:25 +0000311
312 SubVTTIndex =
313 CGF.CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
John McCall3b477332010-02-18 19:59:28 +0000314 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
315 }
Anders Carlssonc997d422010-01-02 01:01:18 +0000316
Anders Carlssonaf440352010-03-23 04:11:45 +0000317 if (CodeGenVTables::needsVTTParameter(CGF.CurGD)) {
Anders Carlssonc997d422010-01-02 01:01:18 +0000318 // A VTT parameter was passed to the constructor, use it.
319 VTT = CGF.LoadCXXVTT();
320 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
321 } else {
322 // We're the complete constructor, so get the VTT by name.
Anders Carlsson1cbce122011-01-29 19:16:51 +0000323 VTT = CGF.CGM.getVTables().GetAddrOfVTT(RD);
Anders Carlssonc997d422010-01-02 01:01:18 +0000324 VTT = CGF.Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
325 }
326
327 return VTT;
328}
329
John McCall182ab512010-07-21 01:23:41 +0000330namespace {
John McCall50da2ca2010-07-21 05:30:47 +0000331 /// Call the destructor for a direct base class.
John McCall1f0fca52010-07-21 07:22:38 +0000332 struct CallBaseDtor : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000333 const CXXRecordDecl *BaseClass;
334 bool BaseIsVirtual;
335 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
336 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
John McCall182ab512010-07-21 01:23:41 +0000337
John McCallad346f42011-07-12 20:27:29 +0000338 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall50da2ca2010-07-21 05:30:47 +0000339 const CXXRecordDecl *DerivedClass =
340 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
341
342 const CXXDestructorDecl *D = BaseClass->getDestructor();
343 llvm::Value *Addr =
344 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThis(),
345 DerivedClass, BaseClass,
346 BaseIsVirtual);
347 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual, Addr);
John McCall182ab512010-07-21 01:23:41 +0000348 }
349 };
John McCall7e1dff72010-09-17 02:31:44 +0000350
351 /// A visitor which checks whether an initializer uses 'this' in a
352 /// way which requires the vtable to be properly set.
353 struct DynamicThisUseChecker : EvaluatedExprVisitor<DynamicThisUseChecker> {
354 typedef EvaluatedExprVisitor<DynamicThisUseChecker> super;
355
356 bool UsesThis;
357
358 DynamicThisUseChecker(ASTContext &C) : super(C), UsesThis(false) {}
359
360 // Black-list all explicit and implicit references to 'this'.
361 //
362 // Do we need to worry about external references to 'this' derived
363 // from arbitrary code? If so, then anything which runs arbitrary
364 // external code might potentially access the vtable.
365 void VisitCXXThisExpr(CXXThisExpr *E) { UsesThis = true; }
366 };
367}
368
369static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
370 DynamicThisUseChecker Checker(C);
371 Checker.Visit(const_cast<Expr*>(Init));
372 return Checker.UsesThis;
John McCall182ab512010-07-21 01:23:41 +0000373}
374
Anders Carlsson607d0372009-12-24 22:46:43 +0000375static void EmitBaseInitializer(CodeGenFunction &CGF,
376 const CXXRecordDecl *ClassDecl,
Sean Huntcbb67482011-01-08 20:30:50 +0000377 CXXCtorInitializer *BaseInit,
Anders Carlsson607d0372009-12-24 22:46:43 +0000378 CXXCtorType CtorType) {
379 assert(BaseInit->isBaseInitializer() &&
380 "Must have base initializer!");
381
382 llvm::Value *ThisPtr = CGF.LoadCXXThis();
383
384 const Type *BaseType = BaseInit->getBaseClass();
385 CXXRecordDecl *BaseClassDecl =
386 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
387
Anders Carlsson80638c52010-04-12 00:51:03 +0000388 bool isBaseVirtual = BaseInit->isBaseVirtual();
Anders Carlsson607d0372009-12-24 22:46:43 +0000389
390 // The base constructor doesn't construct virtual bases.
391 if (CtorType == Ctor_Base && isBaseVirtual)
392 return;
393
John McCall7e1dff72010-09-17 02:31:44 +0000394 // If the initializer for the base (other than the constructor
395 // itself) accesses 'this' in any way, we need to initialize the
396 // vtables.
397 if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
398 CGF.InitializeVTablePointers(ClassDecl);
399
John McCallbff225e2010-02-16 04:15:37 +0000400 // We can pretend to be a complete class because it only matters for
401 // virtual bases, and we only do virtual bases for complete ctors.
Anders Carlsson8561a862010-04-24 23:01:49 +0000402 llvm::Value *V =
403 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
John McCall50da2ca2010-07-21 05:30:47 +0000404 BaseClassDecl,
405 isBaseVirtual);
Eli Friedmand7722d92011-12-03 02:13:40 +0000406 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(BaseType);
John McCall7c2349b2011-08-25 20:40:09 +0000407 AggValueSlot AggSlot =
Eli Friedmanf3940782011-12-03 00:54:26 +0000408 AggValueSlot::forAddr(V, Alignment, Qualifiers(),
John McCall7c2349b2011-08-25 20:40:09 +0000409 AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +0000410 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +0000411 AggValueSlot::IsNotAliased);
John McCall558d2ab2010-09-15 10:14:12 +0000412
413 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
Anders Carlsson594d5e82010-02-06 20:00:21 +0000414
David Blaikie4e4d0842012-03-11 07:00:24 +0000415 if (CGF.CGM.getLangOpts().Exceptions &&
Anders Carlssonc1cfdf82011-02-20 00:20:27 +0000416 !BaseClassDecl->hasTrivialDestructor())
John McCall1f0fca52010-07-21 07:22:38 +0000417 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
418 isBaseVirtual);
Anders Carlsson607d0372009-12-24 22:46:43 +0000419}
420
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000421static void EmitAggMemberInitializer(CodeGenFunction &CGF,
422 LValue LHS,
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000423 Expr *Init,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000424 llvm::Value *ArrayIndexVar,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000425 QualType T,
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000426 ArrayRef<VarDecl *> ArrayIndexes,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000427 unsigned Index) {
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000428 if (Index == ArrayIndexes.size()) {
Eli Friedmanf3940782011-12-03 00:54:26 +0000429 LValue LV = LHS;
Sebastian Redl924db712012-02-19 15:41:54 +0000430 { // Scope for Cleanups.
431 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
Eli Friedmanf3940782011-12-03 00:54:26 +0000432
Sebastian Redl924db712012-02-19 15:41:54 +0000433 if (ArrayIndexVar) {
434 // If we have an array index variable, load it and use it as an offset.
435 // Then, increment the value.
436 llvm::Value *Dest = LHS.getAddress();
437 llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar);
438 Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress");
439 llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1);
440 Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc");
441 CGF.Builder.CreateStore(Next, ArrayIndexVar);
442
443 // Update the LValue.
444 LV.setAddress(Dest);
445 CharUnits Align = CGF.getContext().getTypeAlignInChars(T);
446 LV.setAlignment(std::min(Align, LV.getAlignment()));
447 }
448
449 if (!CGF.hasAggregateLLVMType(T)) {
450 CGF.EmitScalarInit(Init, /*decl*/ 0, LV, false);
451 } else if (T->isAnyComplexType()) {
452 CGF.EmitComplexExprIntoAddr(Init, LV.getAddress(),
453 LV.isVolatileQualified());
454 } else {
455 AggValueSlot Slot =
456 AggValueSlot::forLValue(LV,
457 AggValueSlot::IsDestructed,
458 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +0000459 AggValueSlot::IsNotAliased);
Sebastian Redl924db712012-02-19 15:41:54 +0000460
461 CGF.EmitAggExpr(Init, Slot);
462 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000463 }
John McCall558d2ab2010-09-15 10:14:12 +0000464
Sebastian Redl924db712012-02-19 15:41:54 +0000465 // Now, outside of the initializer cleanup scope, destroy the backing array
466 // for a std::initializer_list member.
Sebastian Redl972edf02012-02-19 16:03:09 +0000467 CGF.MaybeEmitStdInitializerListCleanup(LV.getAddress(), Init);
Sebastian Redl924db712012-02-19 15:41:54 +0000468
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000469 return;
470 }
471
472 const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T);
473 assert(Array && "Array initialization without the array type?");
474 llvm::Value *IndexVar
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000475 = CGF.GetAddrOfLocalVar(ArrayIndexes[Index]);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000476 assert(IndexVar && "Array index variable not loaded");
477
478 // Initialize this index variable to zero.
479 llvm::Value* Zero
480 = llvm::Constant::getNullValue(
481 CGF.ConvertType(CGF.getContext().getSizeType()));
482 CGF.Builder.CreateStore(Zero, IndexVar);
483
484 // Start the loop with a block that tests the condition.
485 llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond");
486 llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end");
487
488 CGF.EmitBlock(CondBlock);
489
490 llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body");
491 // Generate: if (loop-index < number-of-elements) fall to the loop body,
492 // otherwise, go to the block after the for-loop.
493 uint64_t NumElements = Array->getSize().getZExtValue();
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000494 llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
Chris Lattner985f7392010-05-06 06:35:23 +0000495 llvm::Value *NumElementsPtr =
496 llvm::ConstantInt::get(Counter->getType(), NumElements);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000497 llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr,
498 "isless");
499
500 // If the condition is true, execute the body.
501 CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor);
502
503 CGF.EmitBlock(ForBody);
504 llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc");
505
506 {
John McCallf1549f62010-07-06 01:34:17 +0000507 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000508
509 // Inside the loop body recurse to emit the inner loop or, eventually, the
510 // constructor call.
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000511 EmitAggMemberInitializer(CGF, LHS, Init, ArrayIndexVar,
512 Array->getElementType(), ArrayIndexes, Index + 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000513 }
514
515 CGF.EmitBlock(ContinueBlock);
516
517 // Emit the increment of the loop counter.
518 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
519 Counter = CGF.Builder.CreateLoad(IndexVar);
520 NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc");
521 CGF.Builder.CreateStore(NextVal, IndexVar);
522
523 // Finally, branch back up to the condition for the next iteration.
524 CGF.EmitBranch(CondBlock);
525
526 // Emit the fall-through block.
527 CGF.EmitBlock(AfterFor, true);
528}
John McCall182ab512010-07-21 01:23:41 +0000529
530namespace {
John McCall1f0fca52010-07-21 07:22:38 +0000531 struct CallMemberDtor : EHScopeStack::Cleanup {
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000532 llvm::Value *V;
John McCall182ab512010-07-21 01:23:41 +0000533 CXXDestructorDecl *Dtor;
534
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000535 CallMemberDtor(llvm::Value *V, CXXDestructorDecl *Dtor)
536 : V(V), Dtor(Dtor) {}
John McCall182ab512010-07-21 01:23:41 +0000537
John McCallad346f42011-07-12 20:27:29 +0000538 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall182ab512010-07-21 01:23:41 +0000539 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000540 V);
John McCall182ab512010-07-21 01:23:41 +0000541 }
542 };
543}
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000544
Anders Carlsson607d0372009-12-24 22:46:43 +0000545static void EmitMemberInitializer(CodeGenFunction &CGF,
546 const CXXRecordDecl *ClassDecl,
Sean Huntcbb67482011-01-08 20:30:50 +0000547 CXXCtorInitializer *MemberInit,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000548 const CXXConstructorDecl *Constructor,
549 FunctionArgList &Args) {
Francois Pichet00eb3f92010-12-04 09:14:42 +0000550 assert(MemberInit->isAnyMemberInitializer() &&
Anders Carlsson607d0372009-12-24 22:46:43 +0000551 "Must have member initializer!");
Richard Smith7a614d82011-06-11 17:19:42 +0000552 assert(MemberInit->getInit() && "Must have initializer!");
Anders Carlsson607d0372009-12-24 22:46:43 +0000553
554 // non-static data member initializers.
Francois Pichet00eb3f92010-12-04 09:14:42 +0000555 FieldDecl *Field = MemberInit->getAnyMember();
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000556 QualType FieldType = Field->getType();
Anders Carlsson607d0372009-12-24 22:46:43 +0000557
558 llvm::Value *ThisPtr = CGF.LoadCXXThis();
Eli Friedman377ecc72012-04-16 03:54:45 +0000559 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
Eli Friedman859c65c2012-08-08 03:51:37 +0000560 LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
Eli Friedman377ecc72012-04-16 03:54:45 +0000561
Francois Pichet00eb3f92010-12-04 09:14:42 +0000562 if (MemberInit->isIndirectMemberInitializer()) {
Eli Friedman859c65c2012-08-08 03:51:37 +0000563 // If we are initializing an anonymous union field, drill down to
564 // the field.
565 IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember();
566 IndirectFieldDecl::chain_iterator I = IndirectField->chain_begin(),
567 IEnd = IndirectField->chain_end();
568 for ( ; I != IEnd; ++I)
569 LHS = CGF.EmitLValueForFieldInitialization(LHS, cast<FieldDecl>(*I));
Francois Pichet00eb3f92010-12-04 09:14:42 +0000570 FieldType = MemberInit->getIndirectMember()->getAnonField()->getType();
John McCalla9976d32010-05-21 01:18:57 +0000571 } else {
Eli Friedman859c65c2012-08-08 03:51:37 +0000572 LHS = CGF.EmitLValueForFieldInitialization(LHS, Field);
Anders Carlsson607d0372009-12-24 22:46:43 +0000573 }
574
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000575 // Special case: if we are in a copy or move constructor, and we are copying
576 // an array of PODs or classes with trivial copy constructors, ignore the
577 // AST and perform the copy we know is equivalent.
578 // FIXME: This is hacky at best... if we had a bit more explicit information
579 // in the AST, we could generalize it more easily.
580 const ConstantArrayType *Array
581 = CGF.getContext().getAsConstantArrayType(FieldType);
582 if (Array && Constructor->isImplicitlyDefined() &&
583 Constructor->isCopyOrMoveConstructor()) {
584 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
Richard Smithe9385362012-11-07 23:56:21 +0000585 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000586 if (BaseElementTy.isPODType(CGF.getContext()) ||
Richard Smithe9385362012-11-07 23:56:21 +0000587 (CE && CE->getConstructor()->isTrivial())) {
588 // Find the source pointer. We know it's the last argument because
589 // we know we're in an implicit copy constructor.
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000590 unsigned SrcArgIndex = Args.size() - 1;
591 llvm::Value *SrcPtr
592 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
Eli Friedman377ecc72012-04-16 03:54:45 +0000593 LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
594 LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field);
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000595
596 // Copy the aggregate.
597 CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
Chad Rosier649b4a12012-03-29 17:37:10 +0000598 LHS.isVolatileQualified());
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000599 return;
600 }
601 }
602
603 ArrayRef<VarDecl *> ArrayIndexes;
604 if (MemberInit->getNumArrayIndices())
605 ArrayIndexes = MemberInit->getArrayIndexes();
Eli Friedmanb74ed082012-02-14 02:31:03 +0000606 CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit(), ArrayIndexes);
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000607}
608
Eli Friedmanb74ed082012-02-14 02:31:03 +0000609void CodeGenFunction::EmitInitializerForField(FieldDecl *Field,
610 LValue LHS, Expr *Init,
611 ArrayRef<VarDecl *> ArrayIndexes) {
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000612 QualType FieldType = Field->getType();
Eli Friedmanb74ed082012-02-14 02:31:03 +0000613 if (!hasAggregateLLVMType(FieldType)) {
John McCallf85e1932011-06-15 23:02:42 +0000614 if (LHS.isSimple()) {
Eli Friedmanb74ed082012-02-14 02:31:03 +0000615 EmitExprAsInit(Init, Field, LHS, false);
John McCallf85e1932011-06-15 23:02:42 +0000616 } else {
Eli Friedmanb74ed082012-02-14 02:31:03 +0000617 RValue RHS = RValue::get(EmitScalarExpr(Init));
618 EmitStoreThroughLValue(RHS, LHS);
John McCallf85e1932011-06-15 23:02:42 +0000619 }
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000620 } else if (FieldType->isAnyComplexType()) {
Eli Friedmanb74ed082012-02-14 02:31:03 +0000621 EmitComplexExprIntoAddr(Init, LHS.getAddress(), LHS.isVolatileQualified());
Anders Carlsson607d0372009-12-24 22:46:43 +0000622 } else {
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000623 llvm::Value *ArrayIndexVar = 0;
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000624 if (ArrayIndexes.size()) {
Eli Friedmanb74ed082012-02-14 02:31:03 +0000625 llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000626
627 // The LHS is a pointer to the first object we'll be constructing, as
628 // a flat array.
Eli Friedmanb74ed082012-02-14 02:31:03 +0000629 QualType BaseElementTy = getContext().getBaseElementType(FieldType);
630 llvm::Type *BasePtr = ConvertType(BaseElementTy);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000631 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Eli Friedmanb74ed082012-02-14 02:31:03 +0000632 llvm::Value *BaseAddrPtr = Builder.CreateBitCast(LHS.getAddress(),
633 BasePtr);
634 LHS = MakeAddrLValue(BaseAddrPtr, BaseElementTy);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000635
636 // Create an array index that will be used to walk over all of the
637 // objects we're constructing.
Eli Friedmanb74ed082012-02-14 02:31:03 +0000638 ArrayIndexVar = CreateTempAlloca(SizeTy, "object.index");
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000639 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
Eli Friedmanb74ed082012-02-14 02:31:03 +0000640 Builder.CreateStore(Zero, ArrayIndexVar);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000641
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000642
643 // Emit the block variables for the array indices, if any.
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000644 for (unsigned I = 0, N = ArrayIndexes.size(); I != N; ++I)
Eli Friedmanb74ed082012-02-14 02:31:03 +0000645 EmitAutoVarDecl(*ArrayIndexes[I]);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000646 }
647
Eli Friedmanb74ed082012-02-14 02:31:03 +0000648 EmitAggMemberInitializer(*this, LHS, Init, ArrayIndexVar, FieldType,
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000649 ArrayIndexes, 0);
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000650
David Blaikie4e4d0842012-03-11 07:00:24 +0000651 if (!CGM.getLangOpts().Exceptions)
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000652 return;
653
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000654 // FIXME: If we have an array of classes w/ non-trivial destructors,
655 // we need to destroy in reverse order of construction along the exception
656 // path.
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000657 const RecordType *RT = FieldType->getAs<RecordType>();
658 if (!RT)
659 return;
660
661 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall182ab512010-07-21 01:23:41 +0000662 if (!RD->hasTrivialDestructor())
Eli Friedmanb74ed082012-02-14 02:31:03 +0000663 EHStack.pushCleanup<CallMemberDtor>(EHCleanup, LHS.getAddress(),
664 RD->getDestructor());
Anders Carlsson607d0372009-12-24 22:46:43 +0000665 }
666}
667
John McCallc0bf4622010-02-23 00:48:20 +0000668/// Checks whether the given constructor is a valid subject for the
669/// complete-to-base constructor delegation optimization, i.e.
670/// emitting the complete constructor as a simple call to the base
671/// constructor.
672static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
673
674 // Currently we disable the optimization for classes with virtual
675 // bases because (1) the addresses of parameter variables need to be
676 // consistent across all initializers but (2) the delegate function
677 // call necessarily creates a second copy of the parameter variable.
678 //
679 // The limiting example (purely theoretical AFAIK):
680 // struct A { A(int &c) { c++; } };
681 // struct B : virtual A {
682 // B(int count) : A(count) { printf("%d\n", count); }
683 // };
684 // ...although even this example could in principle be emitted as a
685 // delegation since the address of the parameter doesn't escape.
686 if (Ctor->getParent()->getNumVBases()) {
687 // TODO: white-list trivial vbase initializers. This case wouldn't
688 // be subject to the restrictions below.
689
690 // TODO: white-list cases where:
691 // - there are no non-reference parameters to the constructor
692 // - the initializers don't access any non-reference parameters
693 // - the initializers don't take the address of non-reference
694 // parameters
695 // - etc.
696 // If we ever add any of the above cases, remember that:
697 // - function-try-blocks will always blacklist this optimization
698 // - we need to perform the constructor prologue and cleanup in
699 // EmitConstructorBody.
700
701 return false;
702 }
703
704 // We also disable the optimization for variadic functions because
705 // it's impossible to "re-pass" varargs.
706 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
707 return false;
708
Sean Hunt059ce0d2011-05-01 07:04:31 +0000709 // FIXME: Decide if we can do a delegation of a delegating constructor.
710 if (Ctor->isDelegatingConstructor())
711 return false;
712
John McCallc0bf4622010-02-23 00:48:20 +0000713 return true;
714}
715
John McCall9fc6a772010-02-19 09:25:03 +0000716/// EmitConstructorBody - Emits the body of the current constructor.
717void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
718 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
719 CXXCtorType CtorType = CurGD.getCtorType();
720
John McCallc0bf4622010-02-23 00:48:20 +0000721 // Before we go any further, try the complete->base constructor
722 // delegation optimization.
Timur Iskhodzhanov85607912012-04-20 08:05:00 +0000723 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
724 CGM.getContext().getTargetInfo().getCXXABI() != CXXABI_Microsoft) {
Devang Pateld67ef0e2010-08-11 21:04:37 +0000725 if (CGDebugInfo *DI = getDebugInfo())
Eric Christopher73fb3502011-10-13 21:45:18 +0000726 DI->EmitLocation(Builder, Ctor->getLocEnd());
John McCallc0bf4622010-02-23 00:48:20 +0000727 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args);
728 return;
729 }
730
John McCall9fc6a772010-02-19 09:25:03 +0000731 Stmt *Body = Ctor->getBody();
732
John McCallc0bf4622010-02-23 00:48:20 +0000733 // Enter the function-try-block before the constructor prologue if
734 // applicable.
John McCallc0bf4622010-02-23 00:48:20 +0000735 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallc0bf4622010-02-23 00:48:20 +0000736 if (IsTryBody)
John McCall59a70002010-07-07 06:56:46 +0000737 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000738
John McCallf1549f62010-07-06 01:34:17 +0000739 EHScopeStack::stable_iterator CleanupDepth = EHStack.stable_begin();
John McCall9fc6a772010-02-19 09:25:03 +0000740
John McCall56ea3772012-03-30 04:25:03 +0000741 // TODO: in restricted cases, we can emit the vbase initializers of
742 // a complete ctor and then delegate to the base ctor.
743
John McCallc0bf4622010-02-23 00:48:20 +0000744 // Emit the constructor prologue, i.e. the base and member
745 // initializers.
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000746 EmitCtorPrologue(Ctor, CtorType, Args);
John McCall9fc6a772010-02-19 09:25:03 +0000747
748 // Emit the body of the statement.
John McCallc0bf4622010-02-23 00:48:20 +0000749 if (IsTryBody)
John McCall9fc6a772010-02-19 09:25:03 +0000750 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
751 else if (Body)
752 EmitStmt(Body);
John McCall9fc6a772010-02-19 09:25:03 +0000753
754 // Emit any cleanup blocks associated with the member or base
755 // initializers, which includes (along the exceptional path) the
756 // destructors for those members and bases that were fully
757 // constructed.
John McCallf1549f62010-07-06 01:34:17 +0000758 PopCleanupBlocks(CleanupDepth);
John McCall9fc6a772010-02-19 09:25:03 +0000759
John McCallc0bf4622010-02-23 00:48:20 +0000760 if (IsTryBody)
John McCall59a70002010-07-07 06:56:46 +0000761 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000762}
763
Anders Carlsson607d0372009-12-24 22:46:43 +0000764/// EmitCtorPrologue - This routine generates necessary code to initialize
765/// base classes and non-static data members belonging to this constructor.
Anders Carlsson607d0372009-12-24 22:46:43 +0000766void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000767 CXXCtorType CtorType,
768 FunctionArgList &Args) {
Sean Hunt059ce0d2011-05-01 07:04:31 +0000769 if (CD->isDelegatingConstructor())
770 return EmitDelegatingCXXConstructorCall(CD, Args);
771
Anders Carlsson607d0372009-12-24 22:46:43 +0000772 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000773
Chris Lattner5f9e2722011-07-23 10:55:15 +0000774 SmallVector<CXXCtorInitializer *, 8> MemberInitializers;
Anders Carlsson607d0372009-12-24 22:46:43 +0000775
Anders Carlsson607d0372009-12-24 22:46:43 +0000776 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
777 E = CD->init_end();
778 B != E; ++B) {
Sean Huntcbb67482011-01-08 20:30:50 +0000779 CXXCtorInitializer *Member = (*B);
Anders Carlsson607d0372009-12-24 22:46:43 +0000780
Sean Huntd49bd552011-05-03 20:19:28 +0000781 if (Member->isBaseInitializer()) {
Anders Carlsson607d0372009-12-24 22:46:43 +0000782 EmitBaseInitializer(*this, ClassDecl, Member, CtorType);
Sean Huntd49bd552011-05-03 20:19:28 +0000783 } else {
784 assert(Member->isAnyMemberInitializer() &&
785 "Delegating initializer on non-delegating constructor");
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000786 MemberInitializers.push_back(Member);
Sean Huntd49bd552011-05-03 20:19:28 +0000787 }
Anders Carlsson607d0372009-12-24 22:46:43 +0000788 }
789
Anders Carlsson603d6d12010-03-28 21:07:49 +0000790 InitializeVTablePointers(ClassDecl);
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000791
John McCallf1549f62010-07-06 01:34:17 +0000792 for (unsigned I = 0, E = MemberInitializers.size(); I != E; ++I)
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000793 EmitMemberInitializer(*this, ClassDecl, MemberInitializers[I], CD, Args);
Anders Carlsson607d0372009-12-24 22:46:43 +0000794}
795
Anders Carlssonadf5dc32011-05-15 17:36:21 +0000796static bool
797FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
798
799static bool
800HasTrivialDestructorBody(ASTContext &Context,
801 const CXXRecordDecl *BaseClassDecl,
802 const CXXRecordDecl *MostDerivedClassDecl)
803{
804 // If the destructor is trivial we don't have to check anything else.
805 if (BaseClassDecl->hasTrivialDestructor())
806 return true;
807
808 if (!BaseClassDecl->getDestructor()->hasTrivialBody())
809 return false;
810
811 // Check fields.
812 for (CXXRecordDecl::field_iterator I = BaseClassDecl->field_begin(),
813 E = BaseClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +0000814 const FieldDecl *Field = *I;
Anders Carlssonadf5dc32011-05-15 17:36:21 +0000815
816 if (!FieldHasTrivialDestructorBody(Context, Field))
817 return false;
818 }
819
820 // Check non-virtual bases.
821 for (CXXRecordDecl::base_class_const_iterator I =
822 BaseClassDecl->bases_begin(), E = BaseClassDecl->bases_end();
823 I != E; ++I) {
824 if (I->isVirtual())
825 continue;
826
827 const CXXRecordDecl *NonVirtualBase =
828 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
829 if (!HasTrivialDestructorBody(Context, NonVirtualBase,
830 MostDerivedClassDecl))
831 return false;
832 }
833
834 if (BaseClassDecl == MostDerivedClassDecl) {
835 // Check virtual bases.
836 for (CXXRecordDecl::base_class_const_iterator I =
837 BaseClassDecl->vbases_begin(), E = BaseClassDecl->vbases_end();
838 I != E; ++I) {
839 const CXXRecordDecl *VirtualBase =
840 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
841 if (!HasTrivialDestructorBody(Context, VirtualBase,
842 MostDerivedClassDecl))
843 return false;
844 }
845 }
846
847 return true;
848}
849
850static bool
851FieldHasTrivialDestructorBody(ASTContext &Context,
852 const FieldDecl *Field)
853{
854 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
855
856 const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
857 if (!RT)
858 return true;
859
860 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
861 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
862}
863
Anders Carlssonffb945f2011-05-14 23:26:09 +0000864/// CanSkipVTablePointerInitialization - Check whether we need to initialize
865/// any vtable pointers before calling this destructor.
866static bool CanSkipVTablePointerInitialization(ASTContext &Context,
Anders Carlssone3d6cf22011-05-16 04:08:36 +0000867 const CXXDestructorDecl *Dtor) {
Anders Carlssonffb945f2011-05-14 23:26:09 +0000868 if (!Dtor->hasTrivialBody())
869 return false;
870
871 // Check the fields.
872 const CXXRecordDecl *ClassDecl = Dtor->getParent();
873 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
874 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +0000875 const FieldDecl *Field = *I;
Anders Carlssonffb945f2011-05-14 23:26:09 +0000876
Anders Carlssonadf5dc32011-05-15 17:36:21 +0000877 if (!FieldHasTrivialDestructorBody(Context, Field))
878 return false;
Anders Carlssonffb945f2011-05-14 23:26:09 +0000879 }
880
881 return true;
882}
883
John McCall9fc6a772010-02-19 09:25:03 +0000884/// EmitDestructorBody - Emits the body of the current destructor.
885void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
886 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
887 CXXDtorType DtorType = CurGD.getDtorType();
888
John McCall50da2ca2010-07-21 05:30:47 +0000889 // The call to operator delete in a deleting destructor happens
890 // outside of the function-try-block, which means it's always
891 // possible to delegate the destructor body to the complete
892 // destructor. Do so.
893 if (DtorType == Dtor_Deleting) {
894 EnterDtorCleanups(Dtor, Dtor_Deleting);
895 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
896 LoadCXXThis());
897 PopCleanupBlock();
898 return;
899 }
900
John McCall9fc6a772010-02-19 09:25:03 +0000901 Stmt *Body = Dtor->getBody();
902
903 // If the body is a function-try-block, enter the try before
John McCall50da2ca2010-07-21 05:30:47 +0000904 // anything else.
905 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCall9fc6a772010-02-19 09:25:03 +0000906 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +0000907 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000908
John McCall50da2ca2010-07-21 05:30:47 +0000909 // Enter the epilogue cleanups.
910 RunCleanupsScope DtorEpilogue(*this);
911
John McCall9fc6a772010-02-19 09:25:03 +0000912 // If this is the complete variant, just invoke the base variant;
913 // the epilogue will destruct the virtual bases. But we can't do
914 // this optimization if the body is a function-try-block, because
915 // we'd introduce *two* handler blocks.
John McCall50da2ca2010-07-21 05:30:47 +0000916 switch (DtorType) {
917 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
918
919 case Dtor_Complete:
920 // Enter the cleanup scopes for virtual bases.
921 EnterDtorCleanups(Dtor, Dtor_Complete);
922
Timur Iskhodzhanov85607912012-04-20 08:05:00 +0000923 if (!isTryBody && CGM.getContext().getTargetInfo().getCXXABI() != CXXABI_Microsoft) {
John McCall50da2ca2010-07-21 05:30:47 +0000924 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
925 LoadCXXThis());
926 break;
927 }
928 // Fallthrough: act like we're in the base variant.
John McCall9fc6a772010-02-19 09:25:03 +0000929
John McCall50da2ca2010-07-21 05:30:47 +0000930 case Dtor_Base:
931 // Enter the cleanup scopes for fields and non-virtual bases.
932 EnterDtorCleanups(Dtor, Dtor_Base);
933
934 // Initialize the vtable pointers before entering the body.
Anders Carlssonffb945f2011-05-14 23:26:09 +0000935 if (!CanSkipVTablePointerInitialization(getContext(), Dtor))
936 InitializeVTablePointers(Dtor->getParent());
John McCall50da2ca2010-07-21 05:30:47 +0000937
938 if (isTryBody)
939 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
940 else if (Body)
941 EmitStmt(Body);
942 else {
943 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
944 // nothing to do besides what's in the epilogue
945 }
Fariborz Jahanian5abec142011-02-02 23:12:46 +0000946 // -fapple-kext must inline any call to this dtor into
947 // the caller's body.
Richard Smith7edf9e32012-11-01 22:30:59 +0000948 if (getLangOpts().AppleKext)
Bill Wendling72390b32012-12-20 19:27:06 +0000949 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
John McCall50da2ca2010-07-21 05:30:47 +0000950 break;
John McCall9fc6a772010-02-19 09:25:03 +0000951 }
952
John McCall50da2ca2010-07-21 05:30:47 +0000953 // Jump out through the epilogue cleanups.
954 DtorEpilogue.ForceCleanup();
John McCall9fc6a772010-02-19 09:25:03 +0000955
956 // Exit the try if applicable.
957 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +0000958 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000959}
960
John McCall50da2ca2010-07-21 05:30:47 +0000961namespace {
962 /// Call the operator delete associated with the current destructor.
John McCall1f0fca52010-07-21 07:22:38 +0000963 struct CallDtorDelete : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000964 CallDtorDelete() {}
965
John McCallad346f42011-07-12 20:27:29 +0000966 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall50da2ca2010-07-21 05:30:47 +0000967 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
968 const CXXRecordDecl *ClassDecl = Dtor->getParent();
969 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
970 CGF.getContext().getTagDeclType(ClassDecl));
971 }
972 };
973
John McCall9928c482011-07-12 16:41:08 +0000974 class DestroyField : public EHScopeStack::Cleanup {
975 const FieldDecl *field;
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000976 CodeGenFunction::Destroyer *destroyer;
John McCall9928c482011-07-12 16:41:08 +0000977 bool useEHCleanupForArray;
John McCall50da2ca2010-07-21 05:30:47 +0000978
John McCall9928c482011-07-12 16:41:08 +0000979 public:
980 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
981 bool useEHCleanupForArray)
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000982 : field(field), destroyer(destroyer),
John McCall9928c482011-07-12 16:41:08 +0000983 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall50da2ca2010-07-21 05:30:47 +0000984
John McCallad346f42011-07-12 20:27:29 +0000985 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall9928c482011-07-12 16:41:08 +0000986 // Find the address of the field.
987 llvm::Value *thisValue = CGF.LoadCXXThis();
Eli Friedman377ecc72012-04-16 03:54:45 +0000988 QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
989 LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
990 LValue LV = CGF.EmitLValueForField(ThisLV, field);
John McCall9928c482011-07-12 16:41:08 +0000991 assert(LV.isSimple());
992
993 CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
John McCallad346f42011-07-12 20:27:29 +0000994 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCall50da2ca2010-07-21 05:30:47 +0000995 }
996 };
997}
998
Anders Carlsson607d0372009-12-24 22:46:43 +0000999/// EmitDtorEpilogue - Emit all code that comes at the end of class's
1000/// destructor. This is to call destructors on members and base classes
1001/// in reverse order of their construction.
John McCall50da2ca2010-07-21 05:30:47 +00001002void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
1003 CXXDtorType DtorType) {
Anders Carlsson607d0372009-12-24 22:46:43 +00001004 assert(!DD->isTrivial() &&
1005 "Should not emit dtor epilogue for trivial dtor!");
1006
John McCall50da2ca2010-07-21 05:30:47 +00001007 // The deleting-destructor phase just needs to call the appropriate
1008 // operator delete that Sema picked up.
John McCall3b477332010-02-18 19:59:28 +00001009 if (DtorType == Dtor_Deleting) {
1010 assert(DD->getOperatorDelete() &&
1011 "operator delete missing - EmitDtorEpilogue");
John McCall1f0fca52010-07-21 07:22:38 +00001012 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
John McCall3b477332010-02-18 19:59:28 +00001013 return;
1014 }
1015
John McCall50da2ca2010-07-21 05:30:47 +00001016 const CXXRecordDecl *ClassDecl = DD->getParent();
1017
Richard Smith416f63e2011-09-18 12:11:43 +00001018 // Unions have no bases and do not call field destructors.
1019 if (ClassDecl->isUnion())
1020 return;
1021
John McCall50da2ca2010-07-21 05:30:47 +00001022 // The complete-destructor phase just destructs all the virtual bases.
John McCall3b477332010-02-18 19:59:28 +00001023 if (DtorType == Dtor_Complete) {
John McCall50da2ca2010-07-21 05:30:47 +00001024
1025 // We push them in the forward order so that they'll be popped in
1026 // the reverse order.
1027 for (CXXRecordDecl::base_class_const_iterator I =
1028 ClassDecl->vbases_begin(), E = ClassDecl->vbases_end();
John McCall3b477332010-02-18 19:59:28 +00001029 I != E; ++I) {
1030 const CXXBaseSpecifier &Base = *I;
1031 CXXRecordDecl *BaseClassDecl
1032 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1033
1034 // Ignore trivial destructors.
1035 if (BaseClassDecl->hasTrivialDestructor())
1036 continue;
John McCall50da2ca2010-07-21 05:30:47 +00001037
John McCall1f0fca52010-07-21 07:22:38 +00001038 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1039 BaseClassDecl,
1040 /*BaseIsVirtual*/ true);
John McCall3b477332010-02-18 19:59:28 +00001041 }
John McCall50da2ca2010-07-21 05:30:47 +00001042
John McCall3b477332010-02-18 19:59:28 +00001043 return;
1044 }
1045
1046 assert(DtorType == Dtor_Base);
John McCall50da2ca2010-07-21 05:30:47 +00001047
1048 // Destroy non-virtual bases.
1049 for (CXXRecordDecl::base_class_const_iterator I =
1050 ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) {
1051 const CXXBaseSpecifier &Base = *I;
1052
1053 // Ignore virtual bases.
1054 if (Base.isVirtual())
1055 continue;
1056
1057 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
1058
1059 // Ignore trivial destructors.
1060 if (BaseClassDecl->hasTrivialDestructor())
1061 continue;
John McCall3b477332010-02-18 19:59:28 +00001062
John McCall1f0fca52010-07-21 07:22:38 +00001063 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1064 BaseClassDecl,
1065 /*BaseIsVirtual*/ false);
John McCall50da2ca2010-07-21 05:30:47 +00001066 }
1067
1068 // Destroy direct fields.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001069 SmallVector<const FieldDecl *, 16> FieldDecls;
Anders Carlsson607d0372009-12-24 22:46:43 +00001070 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1071 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001072 const FieldDecl *field = *I;
John McCall9928c482011-07-12 16:41:08 +00001073 QualType type = field->getType();
1074 QualType::DestructionKind dtorKind = type.isDestructedType();
1075 if (!dtorKind) continue;
John McCall50da2ca2010-07-21 05:30:47 +00001076
Richard Smith9a561d52012-02-26 09:11:52 +00001077 // Anonymous union members do not have their destructors called.
1078 const RecordType *RT = type->getAsUnionType();
1079 if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
1080
John McCall9928c482011-07-12 16:41:08 +00001081 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1082 EHStack.pushCleanup<DestroyField>(cleanupKind, field,
1083 getDestroyer(dtorKind),
1084 cleanupKind & EHCleanup);
Anders Carlsson607d0372009-12-24 22:46:43 +00001085 }
Anders Carlsson607d0372009-12-24 22:46:43 +00001086}
1087
John McCallc3c07662011-07-13 06:10:41 +00001088/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1089/// constructor for each of several members of an array.
Douglas Gregor59174c02010-07-21 01:10:17 +00001090///
John McCallc3c07662011-07-13 06:10:41 +00001091/// \param ctor the constructor to call for each element
John McCallc3c07662011-07-13 06:10:41 +00001092/// \param arrayType the type of the array to initialize
1093/// \param arrayBegin an arrayType*
1094/// \param zeroInitialize true if each element should be
1095/// zero-initialized before it is constructed
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001096void
John McCallc3c07662011-07-13 06:10:41 +00001097CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1098 const ConstantArrayType *arrayType,
1099 llvm::Value *arrayBegin,
1100 CallExpr::const_arg_iterator argBegin,
1101 CallExpr::const_arg_iterator argEnd,
1102 bool zeroInitialize) {
1103 QualType elementType;
1104 llvm::Value *numElements =
1105 emitArrayLength(arrayType, elementType, arrayBegin);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001106
John McCallc3c07662011-07-13 06:10:41 +00001107 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin,
1108 argBegin, argEnd, zeroInitialize);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001109}
1110
John McCallc3c07662011-07-13 06:10:41 +00001111/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1112/// constructor for each of several members of an array.
1113///
1114/// \param ctor the constructor to call for each element
1115/// \param numElements the number of elements in the array;
John McCalldd376ca2011-07-13 07:37:11 +00001116/// may be zero
John McCallc3c07662011-07-13 06:10:41 +00001117/// \param arrayBegin a T*, where T is the type constructed by ctor
1118/// \param zeroInitialize true if each element should be
1119/// zero-initialized before it is constructed
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001120void
John McCallc3c07662011-07-13 06:10:41 +00001121CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1122 llvm::Value *numElements,
1123 llvm::Value *arrayBegin,
1124 CallExpr::const_arg_iterator argBegin,
1125 CallExpr::const_arg_iterator argEnd,
1126 bool zeroInitialize) {
John McCalldd376ca2011-07-13 07:37:11 +00001127
1128 // It's legal for numElements to be zero. This can happen both
1129 // dynamically, because x can be zero in 'new A[x]', and statically,
1130 // because of GCC extensions that permit zero-length arrays. There
1131 // are probably legitimate places where we could assume that this
1132 // doesn't happen, but it's not clear that it's worth it.
1133 llvm::BranchInst *zeroCheckBranch = 0;
1134
1135 // Optimize for a constant count.
1136 llvm::ConstantInt *constantCount
1137 = dyn_cast<llvm::ConstantInt>(numElements);
1138 if (constantCount) {
1139 // Just skip out if the constant count is zero.
1140 if (constantCount->isZero()) return;
1141
1142 // Otherwise, emit the check.
1143 } else {
1144 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1145 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1146 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1147 EmitBlock(loopBB);
1148 }
1149
John McCallc3c07662011-07-13 06:10:41 +00001150 // Find the end of the array.
1151 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1152 "arrayctor.end");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001153
John McCallc3c07662011-07-13 06:10:41 +00001154 // Enter the loop, setting up a phi for the current location to initialize.
1155 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1156 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1157 EmitBlock(loopBB);
1158 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1159 "arrayctor.cur");
1160 cur->addIncoming(arrayBegin, entryBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001161
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001162 // Inside the loop body, emit the constructor call on the array element.
John McCallc3c07662011-07-13 06:10:41 +00001163
1164 QualType type = getContext().getTypeDeclType(ctor->getParent());
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001165
Douglas Gregor59174c02010-07-21 01:10:17 +00001166 // Zero initialize the storage, if requested.
John McCallc3c07662011-07-13 06:10:41 +00001167 if (zeroInitialize)
1168 EmitNullInitialization(cur, type);
Douglas Gregor59174c02010-07-21 01:10:17 +00001169
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001170 // C++ [class.temporary]p4:
1171 // There are two contexts in which temporaries are destroyed at a different
1172 // point than the end of the full-expression. The first context is when a
1173 // default constructor is called to initialize an element of an array.
1174 // If the constructor has one or more default arguments, the destruction of
1175 // every temporary created in a default argument expression is sequenced
1176 // before the construction of the next array element, if any.
1177
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001178 {
John McCallf1549f62010-07-06 01:34:17 +00001179 RunCleanupsScope Scope(*this);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001180
John McCallc3c07662011-07-13 06:10:41 +00001181 // Evaluate the constructor and its arguments in a regular
1182 // partial-destroy cleanup.
David Blaikie4e4d0842012-03-11 07:00:24 +00001183 if (getLangOpts().Exceptions &&
John McCallc3c07662011-07-13 06:10:41 +00001184 !ctor->getParent()->hasTrivialDestructor()) {
1185 Destroyer *destroyer = destroyCXXObject;
1186 pushRegularPartialArrayCleanup(arrayBegin, cur, type, *destroyer);
1187 }
1188
1189 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/ false,
1190 cur, argBegin, argEnd);
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001191 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001192
John McCallc3c07662011-07-13 06:10:41 +00001193 // Go to the next element.
1194 llvm::Value *next =
1195 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
1196 "arrayctor.next");
1197 cur->addIncoming(next, Builder.GetInsertBlock());
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001198
John McCallc3c07662011-07-13 06:10:41 +00001199 // Check whether that's the end of the loop.
1200 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
1201 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
1202 Builder.CreateCondBr(done, contBB, loopBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001203
John McCalldd376ca2011-07-13 07:37:11 +00001204 // Patch the earlier check to skip over the loop.
1205 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
1206
John McCallc3c07662011-07-13 06:10:41 +00001207 EmitBlock(contBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001208}
1209
John McCallbdc4d802011-07-09 01:37:26 +00001210void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
1211 llvm::Value *addr,
1212 QualType type) {
1213 const RecordType *rtype = type->castAs<RecordType>();
1214 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
1215 const CXXDestructorDecl *dtor = record->getDestructor();
1216 assert(!dtor->isTrivial());
1217 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
1218 addr);
1219}
1220
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001221void
1222CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
Anders Carlsson155ed4a2010-05-02 23:20:53 +00001223 CXXCtorType Type, bool ForVirtualBase,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001224 llvm::Value *This,
1225 CallExpr::const_arg_iterator ArgBeg,
1226 CallExpr::const_arg_iterator ArgEnd) {
Devang Patel3ee36af2011-02-22 20:55:26 +00001227
1228 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonov3a70cd62012-04-27 07:24:20 +00001229 if (DI &&
Douglas Gregor4cdad312012-10-23 20:05:01 +00001230 CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::LimitedDebugInfo) {
Eric Christopheraf790882012-02-01 21:44:56 +00001231 // If debug info for this class has not been emitted then this is the
1232 // right time to do so.
Devang Patel3ee36af2011-02-22 20:55:26 +00001233 const CXXRecordDecl *Parent = D->getParent();
1234 DI->getOrCreateRecordType(CGM.getContext().getTypeDeclType(Parent),
1235 Parent->getLocation());
1236 }
1237
John McCall8b6bbeb2010-02-06 00:25:16 +00001238 if (D->isTrivial()) {
1239 if (ArgBeg == ArgEnd) {
1240 // Trivial default constructor, no codegen required.
1241 assert(D->isDefaultConstructor() &&
1242 "trivial 0-arg ctor not a default ctor");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001243 return;
1244 }
John McCall8b6bbeb2010-02-06 00:25:16 +00001245
1246 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001247 assert(D->isCopyOrMoveConstructor() &&
1248 "trivial 1-arg ctor not a copy/move ctor");
John McCall8b6bbeb2010-02-06 00:25:16 +00001249
John McCall8b6bbeb2010-02-06 00:25:16 +00001250 const Expr *E = (*ArgBeg);
1251 QualType Ty = E->getType();
1252 llvm::Value *Src = EmitLValue(E).getAddress();
1253 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001254 return;
1255 }
1256
Anders Carlsson314e6222010-05-02 23:33:10 +00001257 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(D, Type), ForVirtualBase);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001258 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
1259
Richard Smith4def70d2012-10-09 19:52:38 +00001260 // FIXME: Provide a source location here.
1261 EmitCXXMemberCall(D, SourceLocation(), Callee, ReturnValueSlot(), This,
1262 VTT, ArgBeg, ArgEnd);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001263}
1264
John McCallc0bf4622010-02-23 00:48:20 +00001265void
Fariborz Jahanian34999872010-11-13 21:53:34 +00001266CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
1267 llvm::Value *This, llvm::Value *Src,
1268 CallExpr::const_arg_iterator ArgBeg,
1269 CallExpr::const_arg_iterator ArgEnd) {
1270 if (D->isTrivial()) {
1271 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001272 assert(D->isCopyOrMoveConstructor() &&
1273 "trivial 1-arg ctor not a copy/move ctor");
Fariborz Jahanian34999872010-11-13 21:53:34 +00001274 EmitAggregateCopy(This, Src, (*ArgBeg)->getType());
1275 return;
1276 }
1277 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D,
1278 clang::Ctor_Complete);
1279 assert(D->isInstance() &&
1280 "Trying to emit a member call expr on a static method!");
1281
1282 const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
1283
1284 CallArgList Args;
1285
1286 // Push the this ptr.
Eli Friedman04c9a492011-05-02 17:57:46 +00001287 Args.add(RValue::get(This), D->getThisType(getContext()));
Fariborz Jahanian34999872010-11-13 21:53:34 +00001288
1289
1290 // Push the src ptr.
1291 QualType QT = *(FPT->arg_type_begin());
Chris Lattner2acc6e32011-07-18 04:24:23 +00001292 llvm::Type *t = CGM.getTypes().ConvertType(QT);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001293 Src = Builder.CreateBitCast(Src, t);
Eli Friedman04c9a492011-05-02 17:57:46 +00001294 Args.add(RValue::get(Src), QT);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001295
1296 // Skip over first argument (Src).
1297 ++ArgBeg;
1298 CallExpr::const_arg_iterator Arg = ArgBeg;
1299 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin()+1,
1300 E = FPT->arg_type_end(); I != E; ++I, ++Arg) {
1301 assert(Arg != ArgEnd && "Running over edge of argument list!");
John McCall413ebdb2011-03-11 20:59:21 +00001302 EmitCallArg(Args, *Arg, *I);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001303 }
1304 // Either we've emitted all the call args, or we have a call to a
1305 // variadic function.
1306 assert((Arg == ArgEnd || FPT->isVariadic()) &&
1307 "Extra arguments in non-variadic function!");
1308 // If we still have any arguments, emit them using the type of the argument.
1309 for (; Arg != ArgEnd; ++Arg) {
1310 QualType ArgType = Arg->getType();
John McCall413ebdb2011-03-11 20:59:21 +00001311 EmitCallArg(Args, *Arg, ArgType);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001312 }
1313
John McCall0f3d0972012-07-07 06:41:13 +00001314 EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, RequiredArgs::All),
1315 Callee, ReturnValueSlot(), Args, D);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001316}
1317
1318void
John McCallc0bf4622010-02-23 00:48:20 +00001319CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1320 CXXCtorType CtorType,
1321 const FunctionArgList &Args) {
1322 CallArgList DelegateArgs;
1323
1324 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
1325 assert(I != E && "no parameters to constructor");
1326
1327 // this
Eli Friedman04c9a492011-05-02 17:57:46 +00001328 DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType());
John McCallc0bf4622010-02-23 00:48:20 +00001329 ++I;
1330
1331 // vtt
Anders Carlsson314e6222010-05-02 23:33:10 +00001332 if (llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(Ctor, CtorType),
1333 /*ForVirtualBase=*/false)) {
John McCallc0bf4622010-02-23 00:48:20 +00001334 QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
Eli Friedman04c9a492011-05-02 17:57:46 +00001335 DelegateArgs.add(RValue::get(VTT), VoidPP);
John McCallc0bf4622010-02-23 00:48:20 +00001336
Anders Carlssonaf440352010-03-23 04:11:45 +00001337 if (CodeGenVTables::needsVTTParameter(CurGD)) {
John McCallc0bf4622010-02-23 00:48:20 +00001338 assert(I != E && "cannot skip vtt parameter, already done with args");
John McCalld26bc762011-03-09 04:27:21 +00001339 assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
John McCallc0bf4622010-02-23 00:48:20 +00001340 ++I;
1341 }
1342 }
1343
1344 // Explicit arguments.
1345 for (; I != E; ++I) {
John McCall413ebdb2011-03-11 20:59:21 +00001346 const VarDecl *param = *I;
1347 EmitDelegateCallArg(DelegateArgs, param);
John McCallc0bf4622010-02-23 00:48:20 +00001348 }
1349
John McCallde5d3c72012-02-17 03:33:10 +00001350 EmitCall(CGM.getTypes().arrangeCXXConstructorDeclaration(Ctor, CtorType),
John McCallc0bf4622010-02-23 00:48:20 +00001351 CGM.GetAddrOfCXXConstructor(Ctor, CtorType),
1352 ReturnValueSlot(), DelegateArgs, Ctor);
1353}
1354
Sean Huntb76af9c2011-05-03 23:05:34 +00001355namespace {
1356 struct CallDelegatingCtorDtor : EHScopeStack::Cleanup {
1357 const CXXDestructorDecl *Dtor;
1358 llvm::Value *Addr;
1359 CXXDtorType Type;
1360
1361 CallDelegatingCtorDtor(const CXXDestructorDecl *D, llvm::Value *Addr,
1362 CXXDtorType Type)
1363 : Dtor(D), Addr(Addr), Type(Type) {}
1364
John McCallad346f42011-07-12 20:27:29 +00001365 void Emit(CodeGenFunction &CGF, Flags flags) {
Sean Huntb76af9c2011-05-03 23:05:34 +00001366 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
1367 Addr);
1368 }
1369 };
1370}
1371
Sean Hunt059ce0d2011-05-01 07:04:31 +00001372void
1373CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
1374 const FunctionArgList &Args) {
1375 assert(Ctor->isDelegatingConstructor());
1376
1377 llvm::Value *ThisPtr = LoadCXXThis();
1378
Eli Friedmanf3940782011-12-03 00:54:26 +00001379 QualType Ty = getContext().getTagDeclType(Ctor->getParent());
Eli Friedmand7722d92011-12-03 02:13:40 +00001380 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
John McCallf85e1932011-06-15 23:02:42 +00001381 AggValueSlot AggSlot =
Eli Friedmanf3940782011-12-03 00:54:26 +00001382 AggValueSlot::forAddr(ThisPtr, Alignment, Qualifiers(),
John McCall7c2349b2011-08-25 20:40:09 +00001383 AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +00001384 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +00001385 AggValueSlot::IsNotAliased);
Sean Hunt059ce0d2011-05-01 07:04:31 +00001386
1387 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
Sean Hunt059ce0d2011-05-01 07:04:31 +00001388
Sean Huntb76af9c2011-05-03 23:05:34 +00001389 const CXXRecordDecl *ClassDecl = Ctor->getParent();
David Blaikie4e4d0842012-03-11 07:00:24 +00001390 if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
Sean Huntb76af9c2011-05-03 23:05:34 +00001391 CXXDtorType Type =
1392 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
1393
1394 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
1395 ClassDecl->getDestructor(),
1396 ThisPtr, Type);
1397 }
1398}
Sean Hunt059ce0d2011-05-01 07:04:31 +00001399
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001400void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
1401 CXXDtorType Type,
Anders Carlsson8e6404c2010-05-02 23:29:11 +00001402 bool ForVirtualBase,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001403 llvm::Value *This) {
Anders Carlsson314e6222010-05-02 23:33:10 +00001404 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(DD, Type),
1405 ForVirtualBase);
Fariborz Jahanianccd52592011-02-01 23:22:34 +00001406 llvm::Value *Callee = 0;
Richard Smith7edf9e32012-11-01 22:30:59 +00001407 if (getLangOpts().AppleKext)
Fariborz Jahanian771c6782011-02-03 19:27:17 +00001408 Callee = BuildAppleKextVirtualDestructorCall(DD, Type,
1409 DD->getParent());
Fariborz Jahanianccd52592011-02-01 23:22:34 +00001410
1411 if (!Callee)
1412 Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001413
Richard Smith4def70d2012-10-09 19:52:38 +00001414 // FIXME: Provide a source location here.
1415 EmitCXXMemberCall(DD, SourceLocation(), Callee, ReturnValueSlot(), This,
1416 VTT, 0, 0);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001417}
1418
John McCall291ae942010-07-21 01:41:18 +00001419namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001420 struct CallLocalDtor : EHScopeStack::Cleanup {
John McCall291ae942010-07-21 01:41:18 +00001421 const CXXDestructorDecl *Dtor;
1422 llvm::Value *Addr;
1423
1424 CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
1425 : Dtor(D), Addr(Addr) {}
1426
John McCallad346f42011-07-12 20:27:29 +00001427 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall291ae942010-07-21 01:41:18 +00001428 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1429 /*ForVirtualBase=*/false, Addr);
1430 }
1431 };
1432}
1433
John McCall81407d42010-07-21 06:29:51 +00001434void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
1435 llvm::Value *Addr) {
John McCall1f0fca52010-07-21 07:22:38 +00001436 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
John McCall81407d42010-07-21 06:29:51 +00001437}
1438
John McCallf1549f62010-07-06 01:34:17 +00001439void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
1440 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
1441 if (!ClassDecl) return;
1442 if (ClassDecl->hasTrivialDestructor()) return;
1443
1444 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCall642a75f2011-04-28 02:15:35 +00001445 assert(D && D->isUsed() && "destructor not marked as used!");
John McCall81407d42010-07-21 06:29:51 +00001446 PushDestructorCleanup(D, Addr);
John McCallf1549f62010-07-06 01:34:17 +00001447}
1448
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001449llvm::Value *
Anders Carlssonbb7e17b2010-01-31 01:36:53 +00001450CodeGenFunction::GetVirtualBaseClassOffset(llvm::Value *This,
1451 const CXXRecordDecl *ClassDecl,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001452 const CXXRecordDecl *BaseClassDecl) {
Dan Gohman043fb9a2010-10-26 18:44:08 +00001453 llvm::Value *VTablePtr = GetVTablePtr(This, Int8PtrTy);
Ken Dyck14c65ca2011-04-07 12:37:09 +00001454 CharUnits VBaseOffsetOffset =
Peter Collingbourne1d2b3172011-09-26 01:56:30 +00001455 CGM.getVTableContext().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001456
1457 llvm::Value *VBaseOffsetPtr =
Ken Dyck14c65ca2011-04-07 12:37:09 +00001458 Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1459 "vbase.offset.ptr");
Chris Lattner2acc6e32011-07-18 04:24:23 +00001460 llvm::Type *PtrDiffTy =
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001461 ConvertType(getContext().getPointerDiffType());
1462
1463 VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr,
1464 PtrDiffTy->getPointerTo());
1465
1466 llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1467
1468 return VBaseOffset;
1469}
1470
Anders Carlssond103f9f2010-03-28 19:40:00 +00001471void
1472CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001473 const CXXRecordDecl *NearestVBase,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001474 CharUnits OffsetFromNearestVBase,
Anders Carlssond103f9f2010-03-28 19:40:00 +00001475 llvm::Constant *VTable,
1476 const CXXRecordDecl *VTableClass) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001477 const CXXRecordDecl *RD = Base.getBase();
1478
Anders Carlssond103f9f2010-03-28 19:40:00 +00001479 // Compute the address point.
Anders Carlssonc83f1062010-03-29 01:08:49 +00001480 llvm::Value *VTableAddressPoint;
Anders Carlsson851853d2010-03-29 02:38:51 +00001481
Anders Carlssonc83f1062010-03-29 01:08:49 +00001482 // Check if we need to use a vtable from the VTT.
Anders Carlsson851853d2010-03-29 02:38:51 +00001483 if (CodeGenVTables::needsVTTParameter(CurGD) &&
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001484 (RD->getNumVBases() || NearestVBase)) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001485 // Get the secondary vpointer index.
1486 uint64_t VirtualPointerIndex =
1487 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1488
1489 /// Load the VTT.
1490 llvm::Value *VTT = LoadCXXVTT();
1491 if (VirtualPointerIndex)
1492 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1493
1494 // And load the address point from the VTT.
1495 VTableAddressPoint = Builder.CreateLoad(VTT);
1496 } else {
Peter Collingbourne84fcc482011-09-26 01:56:41 +00001497 uint64_t AddressPoint =
Peter Collingbournee09cdf42011-09-26 01:56:50 +00001498 CGM.getVTableContext().getVTableLayout(VTableClass).getAddressPoint(Base);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001499 VTableAddressPoint =
Anders Carlssond103f9f2010-03-28 19:40:00 +00001500 Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001501 }
Anders Carlssond103f9f2010-03-28 19:40:00 +00001502
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001503 // Compute where to store the address point.
Anders Carlsson8246cc72010-05-03 00:29:58 +00001504 llvm::Value *VirtualOffset = 0;
Ken Dyck9a8ad9b2011-03-23 00:45:26 +00001505 CharUnits NonVirtualOffset = CharUnits::Zero();
Anders Carlsson3e79c302010-04-20 18:05:10 +00001506
1507 if (CodeGenVTables::needsVTTParameter(CurGD) && NearestVBase) {
1508 // We need to use the virtual base offset offset because the virtual base
1509 // might have a different offset in the most derived class.
Anders Carlsson8246cc72010-05-03 00:29:58 +00001510 VirtualOffset = GetVirtualBaseClassOffset(LoadCXXThis(), VTableClass,
1511 NearestVBase);
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001512 NonVirtualOffset = OffsetFromNearestVBase;
Anders Carlsson3e79c302010-04-20 18:05:10 +00001513 } else {
Anders Carlsson8246cc72010-05-03 00:29:58 +00001514 // We can just use the base offset in the complete class.
Ken Dyck4230d522011-03-24 01:21:01 +00001515 NonVirtualOffset = Base.getBaseOffset();
Anders Carlsson3e79c302010-04-20 18:05:10 +00001516 }
Anders Carlsson8246cc72010-05-03 00:29:58 +00001517
1518 // Apply the offsets.
1519 llvm::Value *VTableField = LoadCXXThis();
1520
Ken Dyck9a8ad9b2011-03-23 00:45:26 +00001521 if (!NonVirtualOffset.isZero() || VirtualOffset)
Anders Carlsson8246cc72010-05-03 00:29:58 +00001522 VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
1523 NonVirtualOffset,
1524 VirtualOffset);
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001525
Anders Carlssond103f9f2010-03-28 19:40:00 +00001526 // Finally, store the address point.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001527 llvm::Type *AddressPointPtrTy =
Anders Carlssond103f9f2010-03-28 19:40:00 +00001528 VTableAddressPoint->getType()->getPointerTo();
1529 VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
Kostya Serebryany8cb4a072012-03-26 17:03:51 +00001530 llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
1531 CGM.DecorateInstruction(Store, CGM.getTBAAInfoForVTablePtr());
Anders Carlssond103f9f2010-03-28 19:40:00 +00001532}
1533
Anders Carlsson603d6d12010-03-28 21:07:49 +00001534void
1535CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001536 const CXXRecordDecl *NearestVBase,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001537 CharUnits OffsetFromNearestVBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001538 bool BaseIsNonVirtualPrimaryBase,
1539 llvm::Constant *VTable,
1540 const CXXRecordDecl *VTableClass,
1541 VisitedVirtualBasesSetTy& VBases) {
1542 // If this base is a non-virtual primary base the address point has already
1543 // been set.
1544 if (!BaseIsNonVirtualPrimaryBase) {
1545 // Initialize the vtable pointer for this base.
Anders Carlsson42358402010-05-03 00:07:07 +00001546 InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
1547 VTable, VTableClass);
Anders Carlsson603d6d12010-03-28 21:07:49 +00001548 }
1549
1550 const CXXRecordDecl *RD = Base.getBase();
1551
1552 // Traverse bases.
1553 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1554 E = RD->bases_end(); I != E; ++I) {
1555 CXXRecordDecl *BaseDecl
1556 = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1557
1558 // Ignore classes without a vtable.
1559 if (!BaseDecl->isDynamicClass())
1560 continue;
1561
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001562 CharUnits BaseOffset;
1563 CharUnits BaseOffsetFromNearestVBase;
Anders Carlsson14da9de2010-03-29 01:16:41 +00001564 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001565
1566 if (I->isVirtual()) {
1567 // Check if we've visited this virtual base before.
1568 if (!VBases.insert(BaseDecl))
1569 continue;
1570
1571 const ASTRecordLayout &Layout =
1572 getContext().getASTRecordLayout(VTableClass);
1573
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001574 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
1575 BaseOffsetFromNearestVBase = CharUnits::Zero();
Anders Carlsson14da9de2010-03-29 01:16:41 +00001576 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001577 } else {
1578 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1579
Ken Dyck4230d522011-03-24 01:21:01 +00001580 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson42358402010-05-03 00:07:07 +00001581 BaseOffsetFromNearestVBase =
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001582 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson14da9de2010-03-29 01:16:41 +00001583 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001584 }
1585
Ken Dyck4230d522011-03-24 01:21:01 +00001586 InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001587 I->isVirtual() ? BaseDecl : NearestVBase,
Anders Carlsson42358402010-05-03 00:07:07 +00001588 BaseOffsetFromNearestVBase,
Anders Carlsson14da9de2010-03-29 01:16:41 +00001589 BaseDeclIsNonVirtualPrimaryBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001590 VTable, VTableClass, VBases);
1591 }
1592}
1593
1594void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
1595 // Ignore classes without a vtable.
Anders Carlsson07036902010-03-26 04:39:42 +00001596 if (!RD->isDynamicClass())
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001597 return;
1598
Anders Carlsson07036902010-03-26 04:39:42 +00001599 // Get the VTable.
1600 llvm::Constant *VTable = CGM.getVTables().GetAddrOfVTable(RD);
Anders Carlsson5c6c1d92010-03-24 03:57:14 +00001601
Anders Carlsson603d6d12010-03-28 21:07:49 +00001602 // Initialize the vtable pointers for this class and all of its bases.
1603 VisitedVirtualBasesSetTy VBases;
Ken Dyck4230d522011-03-24 01:21:01 +00001604 InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()),
1605 /*NearestVBase=*/0,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001606 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
Anders Carlsson603d6d12010-03-28 21:07:49 +00001607 /*BaseIsNonVirtualPrimaryBase=*/false,
1608 VTable, RD, VBases);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001609}
Dan Gohman043fb9a2010-10-26 18:44:08 +00001610
1611llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001612 llvm::Type *Ty) {
Dan Gohman043fb9a2010-10-26 18:44:08 +00001613 llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
Kostya Serebryany8cb4a072012-03-26 17:03:51 +00001614 llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
1615 CGM.DecorateInstruction(VTable, CGM.getTBAAInfoForVTablePtr());
1616 return VTable;
Dan Gohman043fb9a2010-10-26 18:44:08 +00001617}
Anders Carlssona2447e02011-05-08 20:32:23 +00001618
1619static const CXXRecordDecl *getMostDerivedClassDecl(const Expr *Base) {
1620 const Expr *E = Base;
1621
1622 while (true) {
1623 E = E->IgnoreParens();
1624 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
1625 if (CE->getCastKind() == CK_DerivedToBase ||
1626 CE->getCastKind() == CK_UncheckedDerivedToBase ||
1627 CE->getCastKind() == CK_NoOp) {
1628 E = CE->getSubExpr();
1629 continue;
1630 }
1631 }
1632
1633 break;
1634 }
1635
1636 QualType DerivedType = E->getType();
1637 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
1638 DerivedType = PTy->getPointeeType();
1639
1640 return cast<CXXRecordDecl>(DerivedType->castAs<RecordType>()->getDecl());
1641}
1642
1643// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
1644// quite what we want.
1645static const Expr *skipNoOpCastsAndParens(const Expr *E) {
1646 while (true) {
1647 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
1648 E = PE->getSubExpr();
1649 continue;
1650 }
1651
1652 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
1653 if (CE->getCastKind() == CK_NoOp) {
1654 E = CE->getSubExpr();
1655 continue;
1656 }
1657 }
1658 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1659 if (UO->getOpcode() == UO_Extension) {
1660 E = UO->getSubExpr();
1661 continue;
1662 }
1663 }
1664 return E;
1665 }
1666}
1667
1668/// canDevirtualizeMemberFunctionCall - Checks whether the given virtual member
1669/// function call on the given expr can be devirtualized.
Anders Carlssona2447e02011-05-08 20:32:23 +00001670static bool canDevirtualizeMemberFunctionCall(const Expr *Base,
1671 const CXXMethodDecl *MD) {
1672 // If the most derived class is marked final, we know that no subclass can
1673 // override this member function and so we can devirtualize it. For example:
1674 //
1675 // struct A { virtual void f(); }
1676 // struct B final : A { };
1677 //
1678 // void f(B *b) {
1679 // b->f();
1680 // }
1681 //
1682 const CXXRecordDecl *MostDerivedClassDecl = getMostDerivedClassDecl(Base);
1683 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
1684 return true;
1685
1686 // If the member function is marked 'final', we know that it can't be
1687 // overridden and can therefore devirtualize it.
1688 if (MD->hasAttr<FinalAttr>())
1689 return true;
1690
1691 // Similarly, if the class itself is marked 'final' it can't be overridden
1692 // and we can therefore devirtualize the member function call.
1693 if (MD->getParent()->hasAttr<FinalAttr>())
1694 return true;
1695
1696 Base = skipNoOpCastsAndParens(Base);
1697 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
1698 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
1699 // This is a record decl. We know the type and can devirtualize it.
1700 return VD->getType()->isRecordType();
1701 }
1702
1703 return false;
1704 }
1705
1706 // We can always devirtualize calls on temporary object expressions.
1707 if (isa<CXXConstructExpr>(Base))
1708 return true;
1709
1710 // And calls on bound temporaries.
1711 if (isa<CXXBindTemporaryExpr>(Base))
1712 return true;
1713
1714 // Check if this is a call expr that returns a record type.
1715 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
1716 return CE->getCallReturnType()->isRecordType();
1717
1718 // We can't devirtualize the call.
1719 return false;
1720}
1721
1722static bool UseVirtualCall(ASTContext &Context,
1723 const CXXOperatorCallExpr *CE,
1724 const CXXMethodDecl *MD) {
1725 if (!MD->isVirtual())
1726 return false;
1727
1728 // When building with -fapple-kext, all calls must go through the vtable since
1729 // the kernel linker can do runtime patching of vtables.
David Blaikie4e4d0842012-03-11 07:00:24 +00001730 if (Context.getLangOpts().AppleKext)
Anders Carlssona2447e02011-05-08 20:32:23 +00001731 return true;
1732
1733 return !canDevirtualizeMemberFunctionCall(CE->getArg(0), MD);
1734}
1735
1736llvm::Value *
1737CodeGenFunction::EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E,
1738 const CXXMethodDecl *MD,
1739 llvm::Value *This) {
John McCallde5d3c72012-02-17 03:33:10 +00001740 llvm::FunctionType *fnType =
1741 CGM.getTypes().GetFunctionType(
1742 CGM.getTypes().arrangeCXXMethodDeclaration(MD));
Anders Carlssona2447e02011-05-08 20:32:23 +00001743
1744 if (UseVirtualCall(getContext(), E, MD))
John McCallde5d3c72012-02-17 03:33:10 +00001745 return BuildVirtualCall(MD, This, fnType);
Anders Carlssona2447e02011-05-08 20:32:23 +00001746
John McCallde5d3c72012-02-17 03:33:10 +00001747 return CGM.GetAddrOfFunction(MD, fnType);
Anders Carlssona2447e02011-05-08 20:32:23 +00001748}
Eli Friedmanbd89f8c2012-02-16 01:37:33 +00001749
John McCall0f3d0972012-07-07 06:41:13 +00001750void CodeGenFunction::EmitForwardingCallToLambda(const CXXRecordDecl *lambda,
1751 CallArgList &callArgs) {
Eli Friedman64bee652012-02-25 02:48:22 +00001752 // Lookup the call operator
John McCall0f3d0972012-07-07 06:41:13 +00001753 DeclarationName operatorName
Eli Friedman21f6ed92012-02-16 03:47:28 +00001754 = getContext().DeclarationNames.getCXXOperatorName(OO_Call);
John McCall0f3d0972012-07-07 06:41:13 +00001755 CXXMethodDecl *callOperator =
David Blaikie3bc93e32012-12-19 00:45:41 +00001756 cast<CXXMethodDecl>(lambda->lookup(operatorName).front());
Eli Friedman21f6ed92012-02-16 03:47:28 +00001757
Eli Friedman21f6ed92012-02-16 03:47:28 +00001758 // Get the address of the call operator.
John McCall0f3d0972012-07-07 06:41:13 +00001759 const CGFunctionInfo &calleeFnInfo =
1760 CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
1761 llvm::Value *callee =
1762 CGM.GetAddrOfFunction(GlobalDecl(callOperator),
1763 CGM.getTypes().GetFunctionType(calleeFnInfo));
Eli Friedman21f6ed92012-02-16 03:47:28 +00001764
John McCall0f3d0972012-07-07 06:41:13 +00001765 // Prepare the return slot.
1766 const FunctionProtoType *FPT =
1767 callOperator->getType()->castAs<FunctionProtoType>();
1768 QualType resultType = FPT->getResultType();
1769 ReturnValueSlot returnSlot;
1770 if (!resultType->isVoidType() &&
1771 calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
1772 hasAggregateLLVMType(calleeFnInfo.getReturnType()))
1773 returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
1774
1775 // We don't need to separately arrange the call arguments because
1776 // the call can't be variadic anyway --- it's impossible to forward
1777 // variadic arguments.
Eli Friedman21f6ed92012-02-16 03:47:28 +00001778
1779 // Now emit our call.
John McCall0f3d0972012-07-07 06:41:13 +00001780 RValue RV = EmitCall(calleeFnInfo, callee, returnSlot,
1781 callArgs, callOperator);
Eli Friedman21f6ed92012-02-16 03:47:28 +00001782
John McCall0f3d0972012-07-07 06:41:13 +00001783 // If necessary, copy the returned value into the slot.
1784 if (!resultType->isVoidType() && returnSlot.isNull())
1785 EmitReturnOfRValue(RV, resultType);
Eli Friedman50f089a2012-12-13 23:37:17 +00001786 else
1787 EmitBranchThroughCleanup(ReturnBlock);
Eli Friedman21f6ed92012-02-16 03:47:28 +00001788}
1789
Eli Friedman64bee652012-02-25 02:48:22 +00001790void CodeGenFunction::EmitLambdaBlockInvokeBody() {
1791 const BlockDecl *BD = BlockInfo->getBlockDecl();
1792 const VarDecl *variable = BD->capture_begin()->getVariable();
1793 const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
1794
1795 // Start building arguments for forwarding call
1796 CallArgList CallArgs;
1797
1798 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
1799 llvm::Value *ThisPtr = GetAddrOfBlockDecl(variable, false);
1800 CallArgs.add(RValue::get(ThisPtr), ThisType);
1801
1802 // Add the rest of the parameters.
1803 for (BlockDecl::param_const_iterator I = BD->param_begin(),
1804 E = BD->param_end(); I != E; ++I) {
1805 ParmVarDecl *param = *I;
1806 EmitDelegateCallArg(CallArgs, param);
1807 }
1808
1809 EmitForwardingCallToLambda(Lambda, CallArgs);
1810}
1811
1812void CodeGenFunction::EmitLambdaToBlockPointerBody(FunctionArgList &Args) {
1813 if (cast<CXXMethodDecl>(CurFuncDecl)->isVariadic()) {
1814 // FIXME: Making this work correctly is nasty because it requires either
1815 // cloning the body of the call operator or making the call operator forward.
1816 CGM.ErrorUnsupported(CurFuncDecl, "lambda conversion to variadic function");
1817 return;
1818 }
1819
Eli Friedman64bee652012-02-25 02:48:22 +00001820 EmitFunctionBody(Args);
Eli Friedman64bee652012-02-25 02:48:22 +00001821}
1822
1823void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
1824 const CXXRecordDecl *Lambda = MD->getParent();
1825
1826 // Start building arguments for forwarding call
1827 CallArgList CallArgs;
1828
1829 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
1830 llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
1831 CallArgs.add(RValue::get(ThisPtr), ThisType);
1832
1833 // Add the rest of the parameters.
1834 for (FunctionDecl::param_const_iterator I = MD->param_begin(),
1835 E = MD->param_end(); I != E; ++I) {
1836 ParmVarDecl *param = *I;
1837 EmitDelegateCallArg(CallArgs, param);
1838 }
1839
1840 EmitForwardingCallToLambda(Lambda, CallArgs);
1841}
1842
Douglas Gregor27dd7d92012-02-17 03:02:34 +00001843void CodeGenFunction::EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD) {
1844 if (MD->isVariadic()) {
Eli Friedman21f6ed92012-02-16 03:47:28 +00001845 // FIXME: Making this work correctly is nasty because it requires either
1846 // cloning the body of the call operator or making the call operator forward.
1847 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
Eli Friedman64bee652012-02-25 02:48:22 +00001848 return;
Eli Friedman21f6ed92012-02-16 03:47:28 +00001849 }
1850
Douglas Gregor27dd7d92012-02-17 03:02:34 +00001851 EmitLambdaDelegatingInvokeBody(MD);
Eli Friedmanbd89f8c2012-02-16 01:37:33 +00001852}