blob: d6907840c94e692dd6db81d2778af4416d6ddd07 [file] [log] [blame]
Anders Carlsson5b955922009-11-24 05:51:11 +00001//===--- CGClass.cpp - Emit LLVM Code for C++ classes ---------------------===//
Anders Carlsson5d58a1d2009-09-12 04:27:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with C++ code generation of classes
11//
12//===----------------------------------------------------------------------===//
13
Eli Friedman64bee652012-02-25 02:48:22 +000014#include "CGBlocks.h"
Devang Pateld67ef0e2010-08-11 21:04:37 +000015#include "CGDebugInfo.h"
Lang Hames56c00c42013-02-17 07:22:09 +000016#include "CGRecordLayout.h"
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000017#include "CodeGenFunction.h"
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +000018#include "CGCXXABI.h"
Anders Carlsson2f1986b2009-10-06 22:43:30 +000019#include "clang/AST/CXXInheritance.h"
Faisal Valid6992ab2013-09-29 08:45:24 +000020#include "clang/AST/DeclTemplate.h"
John McCall7e1dff72010-09-17 02:31:44 +000021#include "clang/AST/EvaluatedExprVisitor.h"
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000022#include "clang/AST/RecordLayout.h"
John McCall9fc6a772010-02-19 09:25:03 +000023#include "clang/AST/StmtCXX.h"
Lang Hames56c00c42013-02-17 07:22:09 +000024#include "clang/Basic/TargetBuiltins.h"
Devang Patel3ee36af2011-02-22 20:55:26 +000025#include "clang/Frontend/CodeGenOptions.h"
Anders Carlsson2f1986b2009-10-06 22:43:30 +000026
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000027using namespace clang;
28using namespace CodeGen;
29
Ken Dyck55c02582011-03-22 00:53:26 +000030static CharUnits
Anders Carlsson34a2d382010-04-24 21:06:20 +000031ComputeNonVirtualBaseClassOffset(ASTContext &Context,
32 const CXXRecordDecl *DerivedClass,
John McCallf871d0c2010-08-07 06:22:56 +000033 CastExpr::path_const_iterator Start,
34 CastExpr::path_const_iterator End) {
Ken Dyck55c02582011-03-22 00:53:26 +000035 CharUnits Offset = CharUnits::Zero();
Anders Carlsson34a2d382010-04-24 21:06:20 +000036
37 const CXXRecordDecl *RD = DerivedClass;
38
John McCallf871d0c2010-08-07 06:22:56 +000039 for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
Anders Carlsson34a2d382010-04-24 21:06:20 +000040 const CXXBaseSpecifier *Base = *I;
41 assert(!Base->isVirtual() && "Should not see virtual bases here!");
42
43 // Get the layout.
44 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
45
46 const CXXRecordDecl *BaseDecl =
47 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
48
49 // Add the offset.
Ken Dyck55c02582011-03-22 00:53:26 +000050 Offset += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson34a2d382010-04-24 21:06:20 +000051
52 RD = BaseDecl;
53 }
54
Ken Dyck55c02582011-03-22 00:53:26 +000055 return Offset;
Anders Carlsson34a2d382010-04-24 21:06:20 +000056}
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000057
Anders Carlsson84080ec2009-09-29 03:13:20 +000058llvm::Constant *
Anders Carlssona04efdf2010-04-24 21:23:59 +000059CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +000060 CastExpr::path_const_iterator PathBegin,
61 CastExpr::path_const_iterator PathEnd) {
62 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssona04efdf2010-04-24 21:23:59 +000063
Ken Dyck55c02582011-03-22 00:53:26 +000064 CharUnits Offset =
John McCallf871d0c2010-08-07 06:22:56 +000065 ComputeNonVirtualBaseClassOffset(getContext(), ClassDecl,
66 PathBegin, PathEnd);
Ken Dyck55c02582011-03-22 00:53:26 +000067 if (Offset.isZero())
Anders Carlssona04efdf2010-04-24 21:23:59 +000068 return 0;
69
Chris Lattner2acc6e32011-07-18 04:24:23 +000070 llvm::Type *PtrDiffTy =
Anders Carlssona04efdf2010-04-24 21:23:59 +000071 Types.ConvertType(getContext().getPointerDiffType());
72
Ken Dyck55c02582011-03-22 00:53:26 +000073 return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
Anders Carlsson84080ec2009-09-29 03:13:20 +000074}
75
Anders Carlsson8561a862010-04-24 23:01:49 +000076/// Gets the address of a direct base class within a complete object.
John McCallbff225e2010-02-16 04:15:37 +000077/// This should only be used for (1) non-virtual bases or (2) virtual bases
78/// when the type is known to be complete (e.g. in complete destructors).
79///
80/// The object pointed to by 'This' is assumed to be non-null.
81llvm::Value *
Anders Carlsson8561a862010-04-24 23:01:49 +000082CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(llvm::Value *This,
83 const CXXRecordDecl *Derived,
84 const CXXRecordDecl *Base,
85 bool BaseIsVirtual) {
John McCallbff225e2010-02-16 04:15:37 +000086 // 'this' must be a pointer (in some address space) to Derived.
87 assert(This->getType()->isPointerTy() &&
88 cast<llvm::PointerType>(This->getType())->getElementType()
89 == ConvertType(Derived));
90
91 // Compute the offset of the virtual base.
Ken Dyck5fff46b2011-03-22 01:21:15 +000092 CharUnits Offset;
John McCallbff225e2010-02-16 04:15:37 +000093 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
Anders Carlsson8561a862010-04-24 23:01:49 +000094 if (BaseIsVirtual)
Ken Dyck5fff46b2011-03-22 01:21:15 +000095 Offset = Layout.getVBaseClassOffset(Base);
John McCallbff225e2010-02-16 04:15:37 +000096 else
Ken Dyck5fff46b2011-03-22 01:21:15 +000097 Offset = Layout.getBaseClassOffset(Base);
John McCallbff225e2010-02-16 04:15:37 +000098
99 // Shift and cast down to the base type.
100 // TODO: for complete types, this should be possible with a GEP.
101 llvm::Value *V = This;
Ken Dyck5fff46b2011-03-22 01:21:15 +0000102 if (Offset.isPositive()) {
John McCallbff225e2010-02-16 04:15:37 +0000103 V = Builder.CreateBitCast(V, Int8PtrTy);
Ken Dyck5fff46b2011-03-22 01:21:15 +0000104 V = Builder.CreateConstInBoundsGEP1_64(V, Offset.getQuantity());
John McCallbff225e2010-02-16 04:15:37 +0000105 }
106 V = Builder.CreateBitCast(V, ConvertType(Base)->getPointerTo());
107
108 return V;
Anders Carlssond103f9f2010-03-28 19:40:00 +0000109}
John McCallbff225e2010-02-16 04:15:37 +0000110
Anders Carlsson9dc228a2010-04-20 16:03:35 +0000111static llvm::Value *
John McCall7916c992012-08-01 05:04:58 +0000112ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, llvm::Value *ptr,
113 CharUnits nonVirtualOffset,
114 llvm::Value *virtualOffset) {
115 // Assert that we have something to do.
116 assert(!nonVirtualOffset.isZero() || virtualOffset != 0);
117
118 // Compute the offset from the static and dynamic components.
119 llvm::Value *baseOffset;
120 if (!nonVirtualOffset.isZero()) {
121 baseOffset = llvm::ConstantInt::get(CGF.PtrDiffTy,
122 nonVirtualOffset.getQuantity());
123 if (virtualOffset) {
124 baseOffset = CGF.Builder.CreateAdd(virtualOffset, baseOffset);
125 }
126 } else {
127 baseOffset = virtualOffset;
128 }
Anders Carlsson9dc228a2010-04-20 16:03:35 +0000129
130 // Apply the base offset.
John McCall7916c992012-08-01 05:04:58 +0000131 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
132 ptr = CGF.Builder.CreateInBoundsGEP(ptr, baseOffset, "add.ptr");
133 return ptr;
Anders Carlsson9dc228a2010-04-20 16:03:35 +0000134}
135
Anders Carlsson5d58a1d2009-09-12 04:27:24 +0000136llvm::Value *
Anders Carlsson34a2d382010-04-24 21:06:20 +0000137CodeGenFunction::GetAddressOfBaseClass(llvm::Value *Value,
Anders Carlsson8561a862010-04-24 23:01:49 +0000138 const CXXRecordDecl *Derived,
John McCallf871d0c2010-08-07 06:22:56 +0000139 CastExpr::path_const_iterator PathBegin,
140 CastExpr::path_const_iterator PathEnd,
Anders Carlsson34a2d382010-04-24 21:06:20 +0000141 bool NullCheckValue) {
John McCallf871d0c2010-08-07 06:22:56 +0000142 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlsson34a2d382010-04-24 21:06:20 +0000143
John McCallf871d0c2010-08-07 06:22:56 +0000144 CastExpr::path_const_iterator Start = PathBegin;
Anders Carlsson34a2d382010-04-24 21:06:20 +0000145 const CXXRecordDecl *VBase = 0;
146
John McCall7916c992012-08-01 05:04:58 +0000147 // Sema has done some convenient canonicalization here: if the
148 // access path involved any virtual steps, the conversion path will
149 // *start* with a step down to the correct virtual base subobject,
150 // and hence will not require any further steps.
Anders Carlsson34a2d382010-04-24 21:06:20 +0000151 if ((*Start)->isVirtual()) {
152 VBase =
153 cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
154 ++Start;
155 }
John McCall7916c992012-08-01 05:04:58 +0000156
157 // Compute the static offset of the ultimate destination within its
158 // allocating subobject (the virtual base, if there is one, or else
159 // the "complete" object that we see).
Ken Dyck55c02582011-03-22 00:53:26 +0000160 CharUnits NonVirtualOffset =
Anders Carlsson8561a862010-04-24 23:01:49 +0000161 ComputeNonVirtualBaseClassOffset(getContext(), VBase ? VBase : Derived,
John McCallf871d0c2010-08-07 06:22:56 +0000162 Start, PathEnd);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000163
John McCall7916c992012-08-01 05:04:58 +0000164 // If there's a virtual step, we can sometimes "devirtualize" it.
165 // For now, that's limited to when the derived type is final.
166 // TODO: "devirtualize" this for accesses to known-complete objects.
167 if (VBase && Derived->hasAttr<FinalAttr>()) {
168 const ASTRecordLayout &layout = getContext().getASTRecordLayout(Derived);
169 CharUnits vBaseOffset = layout.getVBaseClassOffset(VBase);
170 NonVirtualOffset += vBaseOffset;
171 VBase = 0; // we no longer have a virtual step
172 }
173
Anders Carlsson34a2d382010-04-24 21:06:20 +0000174 // Get the base pointer type.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000175 llvm::Type *BasePtrTy =
John McCallf871d0c2010-08-07 06:22:56 +0000176 ConvertType((PathEnd[-1])->getType())->getPointerTo();
John McCall7916c992012-08-01 05:04:58 +0000177
178 // If the static offset is zero and we don't have a virtual step,
179 // just do a bitcast; null checks are unnecessary.
Ken Dyck55c02582011-03-22 00:53:26 +0000180 if (NonVirtualOffset.isZero() && !VBase) {
Anders Carlsson34a2d382010-04-24 21:06:20 +0000181 return Builder.CreateBitCast(Value, BasePtrTy);
182 }
John McCall7916c992012-08-01 05:04:58 +0000183
184 llvm::BasicBlock *origBB = 0;
185 llvm::BasicBlock *endBB = 0;
Anders Carlsson34a2d382010-04-24 21:06:20 +0000186
John McCall7916c992012-08-01 05:04:58 +0000187 // Skip over the offset (and the vtable load) if we're supposed to
188 // null-check the pointer.
Anders Carlsson34a2d382010-04-24 21:06:20 +0000189 if (NullCheckValue) {
John McCall7916c992012-08-01 05:04:58 +0000190 origBB = Builder.GetInsertBlock();
191 llvm::BasicBlock *notNullBB = createBasicBlock("cast.notnull");
192 endBB = createBasicBlock("cast.end");
Anders Carlsson34a2d382010-04-24 21:06:20 +0000193
John McCall7916c992012-08-01 05:04:58 +0000194 llvm::Value *isNull = Builder.CreateIsNull(Value);
195 Builder.CreateCondBr(isNull, endBB, notNullBB);
196 EmitBlock(notNullBB);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000197 }
198
John McCall7916c992012-08-01 05:04:58 +0000199 // Compute the virtual offset.
Anders Carlsson34a2d382010-04-24 21:06:20 +0000200 llvm::Value *VirtualOffset = 0;
Anders Carlsson336a7dc2011-01-29 03:18:56 +0000201 if (VBase) {
Reid Klecknerb0f533e2013-05-29 18:02:47 +0000202 VirtualOffset =
203 CGM.getCXXABI().GetVirtualBaseClassOffset(*this, Value, Derived, VBase);
Anders Carlsson336a7dc2011-01-29 03:18:56 +0000204 }
Anders Carlsson34a2d382010-04-24 21:06:20 +0000205
John McCall7916c992012-08-01 05:04:58 +0000206 // Apply both offsets.
Ken Dyck55c02582011-03-22 00:53:26 +0000207 Value = ApplyNonVirtualAndVirtualOffset(*this, Value,
Ken Dyck9a8ad9b2011-03-23 00:45:26 +0000208 NonVirtualOffset,
Anders Carlsson34a2d382010-04-24 21:06:20 +0000209 VirtualOffset);
210
John McCall7916c992012-08-01 05:04:58 +0000211 // Cast to the destination type.
Anders Carlsson34a2d382010-04-24 21:06:20 +0000212 Value = Builder.CreateBitCast(Value, BasePtrTy);
John McCall7916c992012-08-01 05:04:58 +0000213
214 // Build a phi if we needed a null check.
Anders Carlsson34a2d382010-04-24 21:06:20 +0000215 if (NullCheckValue) {
John McCall7916c992012-08-01 05:04:58 +0000216 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
217 Builder.CreateBr(endBB);
218 EmitBlock(endBB);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000219
John McCall7916c992012-08-01 05:04:58 +0000220 llvm::PHINode *PHI = Builder.CreatePHI(BasePtrTy, 2, "cast.result");
221 PHI->addIncoming(Value, notNullBB);
222 PHI->addIncoming(llvm::Constant::getNullValue(BasePtrTy), origBB);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000223 Value = PHI;
224 }
225
226 return Value;
227}
228
229llvm::Value *
Anders Carlssona3697c92009-11-23 17:57:54 +0000230CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value,
Anders Carlsson8561a862010-04-24 23:01:49 +0000231 const CXXRecordDecl *Derived,
John McCallf871d0c2010-08-07 06:22:56 +0000232 CastExpr::path_const_iterator PathBegin,
233 CastExpr::path_const_iterator PathEnd,
Anders Carlssona3697c92009-11-23 17:57:54 +0000234 bool NullCheckValue) {
John McCallf871d0c2010-08-07 06:22:56 +0000235 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssona04efdf2010-04-24 21:23:59 +0000236
Anders Carlssona3697c92009-11-23 17:57:54 +0000237 QualType DerivedTy =
Anders Carlsson8561a862010-04-24 23:01:49 +0000238 getContext().getCanonicalType(getContext().getTagDeclType(Derived));
Chris Lattner2acc6e32011-07-18 04:24:23 +0000239 llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
Richard Smithc7648302013-02-13 21:18:23 +0000240
Anders Carlssona552ea72010-01-31 01:43:37 +0000241 llvm::Value *NonVirtualOffset =
John McCallf871d0c2010-08-07 06:22:56 +0000242 CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
Anders Carlssona552ea72010-01-31 01:43:37 +0000243
244 if (!NonVirtualOffset) {
245 // No offset, we can just cast back.
246 return Builder.CreateBitCast(Value, DerivedPtrTy);
247 }
248
Anders Carlssona3697c92009-11-23 17:57:54 +0000249 llvm::BasicBlock *CastNull = 0;
250 llvm::BasicBlock *CastNotNull = 0;
251 llvm::BasicBlock *CastEnd = 0;
252
253 if (NullCheckValue) {
254 CastNull = createBasicBlock("cast.null");
255 CastNotNull = createBasicBlock("cast.notnull");
256 CastEnd = createBasicBlock("cast.end");
257
Anders Carlssonb9241242011-04-11 00:30:07 +0000258 llvm::Value *IsNull = Builder.CreateIsNull(Value);
Anders Carlssona3697c92009-11-23 17:57:54 +0000259 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
260 EmitBlock(CastNotNull);
261 }
262
Anders Carlssona552ea72010-01-31 01:43:37 +0000263 // Apply the offset.
Eli Friedmanc5685432012-02-28 22:07:56 +0000264 Value = Builder.CreateBitCast(Value, Int8PtrTy);
265 Value = Builder.CreateGEP(Value, Builder.CreateNeg(NonVirtualOffset),
266 "sub.ptr");
Anders Carlssona552ea72010-01-31 01:43:37 +0000267
268 // Just cast.
269 Value = Builder.CreateBitCast(Value, DerivedPtrTy);
Anders Carlssona3697c92009-11-23 17:57:54 +0000270
271 if (NullCheckValue) {
272 Builder.CreateBr(CastEnd);
273 EmitBlock(CastNull);
274 Builder.CreateBr(CastEnd);
275 EmitBlock(CastEnd);
276
Jay Foadbbf3bac2011-03-30 11:28:58 +0000277 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
Anders Carlssona3697c92009-11-23 17:57:54 +0000278 PHI->addIncoming(Value, CastNotNull);
279 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
280 CastNull);
281 Value = PHI;
282 }
283
284 return Value;
Anders Carlsson5d58a1d2009-09-12 04:27:24 +0000285}
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000286
287llvm::Value *CodeGenFunction::GetVTTParameter(GlobalDecl GD,
288 bool ForVirtualBase,
289 bool Delegating) {
Peter Collingbournee1e35f72013-06-28 20:45:28 +0000290 if (!CGM.getCXXABI().NeedsVTTParameter(GD)) {
Anders Carlssonc997d422010-01-02 01:01:18 +0000291 // This constructor/destructor does not need a VTT parameter.
292 return 0;
293 }
294
John McCallf5ebf9b2013-05-03 07:33:41 +0000295 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CurCodeDecl)->getParent();
Anders Carlssonc997d422010-01-02 01:01:18 +0000296 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
John McCall3b477332010-02-18 19:59:28 +0000297
Anders Carlssonc997d422010-01-02 01:01:18 +0000298 llvm::Value *VTT;
299
John McCall3b477332010-02-18 19:59:28 +0000300 uint64_t SubVTTIndex;
301
Douglas Gregor378e1e72013-01-31 05:50:40 +0000302 if (Delegating) {
303 // If this is a delegating constructor call, just load the VTT.
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000304 return LoadCXXVTT();
Douglas Gregor378e1e72013-01-31 05:50:40 +0000305 } else if (RD == Base) {
306 // If the record matches the base, this is the complete ctor/dtor
307 // variant calling the base variant in a class with virtual bases.
Peter Collingbournee1e35f72013-06-28 20:45:28 +0000308 assert(!CGM.getCXXABI().NeedsVTTParameter(CurGD) &&
John McCall3b477332010-02-18 19:59:28 +0000309 "doing no-op VTT offset in base dtor/ctor?");
Anders Carlsson314e6222010-05-02 23:33:10 +0000310 assert(!ForVirtualBase && "Can't have same class as virtual base!");
John McCall3b477332010-02-18 19:59:28 +0000311 SubVTTIndex = 0;
312 } else {
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000313 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Ken Dyck4230d522011-03-24 01:21:01 +0000314 CharUnits BaseOffset = ForVirtualBase ?
315 Layout.getVBaseClassOffset(Base) :
316 Layout.getBaseClassOffset(Base);
Anders Carlssonc11bb212010-05-02 23:53:25 +0000317
318 SubVTTIndex =
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000319 CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
John McCall3b477332010-02-18 19:59:28 +0000320 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
321 }
Anders Carlssonc997d422010-01-02 01:01:18 +0000322
Peter Collingbournee1e35f72013-06-28 20:45:28 +0000323 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
Anders Carlssonc997d422010-01-02 01:01:18 +0000324 // A VTT parameter was passed to the constructor, use it.
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000325 VTT = LoadCXXVTT();
326 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
Anders Carlssonc997d422010-01-02 01:01:18 +0000327 } else {
328 // We're the complete constructor, so get the VTT by name.
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000329 VTT = CGM.getVTables().GetAddrOfVTT(RD);
330 VTT = Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
Anders Carlssonc997d422010-01-02 01:01:18 +0000331 }
332
333 return VTT;
334}
335
John McCall182ab512010-07-21 01:23:41 +0000336namespace {
John McCall50da2ca2010-07-21 05:30:47 +0000337 /// Call the destructor for a direct base class.
John McCall1f0fca52010-07-21 07:22:38 +0000338 struct CallBaseDtor : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000339 const CXXRecordDecl *BaseClass;
340 bool BaseIsVirtual;
341 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
342 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
John McCall182ab512010-07-21 01:23:41 +0000343
John McCallad346f42011-07-12 20:27:29 +0000344 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall50da2ca2010-07-21 05:30:47 +0000345 const CXXRecordDecl *DerivedClass =
346 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
347
348 const CXXDestructorDecl *D = BaseClass->getDestructor();
349 llvm::Value *Addr =
350 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThis(),
351 DerivedClass, BaseClass,
352 BaseIsVirtual);
Douglas Gregor378e1e72013-01-31 05:50:40 +0000353 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual,
354 /*Delegating=*/false, Addr);
John McCall182ab512010-07-21 01:23:41 +0000355 }
356 };
John McCall7e1dff72010-09-17 02:31:44 +0000357
358 /// A visitor which checks whether an initializer uses 'this' in a
359 /// way which requires the vtable to be properly set.
360 struct DynamicThisUseChecker : EvaluatedExprVisitor<DynamicThisUseChecker> {
361 typedef EvaluatedExprVisitor<DynamicThisUseChecker> super;
362
363 bool UsesThis;
364
365 DynamicThisUseChecker(ASTContext &C) : super(C), UsesThis(false) {}
366
367 // Black-list all explicit and implicit references to 'this'.
368 //
369 // Do we need to worry about external references to 'this' derived
370 // from arbitrary code? If so, then anything which runs arbitrary
371 // external code might potentially access the vtable.
372 void VisitCXXThisExpr(CXXThisExpr *E) { UsesThis = true; }
373 };
374}
375
376static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
377 DynamicThisUseChecker Checker(C);
378 Checker.Visit(const_cast<Expr*>(Init));
379 return Checker.UsesThis;
John McCall182ab512010-07-21 01:23:41 +0000380}
381
Anders Carlsson607d0372009-12-24 22:46:43 +0000382static void EmitBaseInitializer(CodeGenFunction &CGF,
383 const CXXRecordDecl *ClassDecl,
Sean Huntcbb67482011-01-08 20:30:50 +0000384 CXXCtorInitializer *BaseInit,
Anders Carlsson607d0372009-12-24 22:46:43 +0000385 CXXCtorType CtorType) {
386 assert(BaseInit->isBaseInitializer() &&
387 "Must have base initializer!");
388
389 llvm::Value *ThisPtr = CGF.LoadCXXThis();
390
391 const Type *BaseType = BaseInit->getBaseClass();
392 CXXRecordDecl *BaseClassDecl =
393 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
394
Anders Carlsson80638c52010-04-12 00:51:03 +0000395 bool isBaseVirtual = BaseInit->isBaseVirtual();
Anders Carlsson607d0372009-12-24 22:46:43 +0000396
397 // The base constructor doesn't construct virtual bases.
398 if (CtorType == Ctor_Base && isBaseVirtual)
399 return;
400
John McCall7e1dff72010-09-17 02:31:44 +0000401 // If the initializer for the base (other than the constructor
402 // itself) accesses 'this' in any way, we need to initialize the
403 // vtables.
404 if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
405 CGF.InitializeVTablePointers(ClassDecl);
406
John McCallbff225e2010-02-16 04:15:37 +0000407 // We can pretend to be a complete class because it only matters for
408 // virtual bases, and we only do virtual bases for complete ctors.
Anders Carlsson8561a862010-04-24 23:01:49 +0000409 llvm::Value *V =
410 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
John McCall50da2ca2010-07-21 05:30:47 +0000411 BaseClassDecl,
412 isBaseVirtual);
Eli Friedmand7722d92011-12-03 02:13:40 +0000413 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(BaseType);
John McCall7c2349b2011-08-25 20:40:09 +0000414 AggValueSlot AggSlot =
Eli Friedmanf3940782011-12-03 00:54:26 +0000415 AggValueSlot::forAddr(V, Alignment, Qualifiers(),
John McCall7c2349b2011-08-25 20:40:09 +0000416 AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +0000417 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +0000418 AggValueSlot::IsNotAliased);
John McCall558d2ab2010-09-15 10:14:12 +0000419
420 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
Anders Carlsson594d5e82010-02-06 20:00:21 +0000421
David Blaikie4e4d0842012-03-11 07:00:24 +0000422 if (CGF.CGM.getLangOpts().Exceptions &&
Anders Carlssonc1cfdf82011-02-20 00:20:27 +0000423 !BaseClassDecl->hasTrivialDestructor())
John McCall1f0fca52010-07-21 07:22:38 +0000424 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
425 isBaseVirtual);
Anders Carlsson607d0372009-12-24 22:46:43 +0000426}
427
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000428static void EmitAggMemberInitializer(CodeGenFunction &CGF,
429 LValue LHS,
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000430 Expr *Init,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000431 llvm::Value *ArrayIndexVar,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000432 QualType T,
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000433 ArrayRef<VarDecl *> ArrayIndexes,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000434 unsigned Index) {
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000435 if (Index == ArrayIndexes.size()) {
Eli Friedmanf3940782011-12-03 00:54:26 +0000436 LValue LV = LHS;
Eli Friedmanf3940782011-12-03 00:54:26 +0000437
Richard Smith7c3e6152013-06-12 22:31:48 +0000438 if (ArrayIndexVar) {
439 // If we have an array index variable, load it and use it as an offset.
440 // Then, increment the value.
441 llvm::Value *Dest = LHS.getAddress();
442 llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar);
443 Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress");
444 llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1);
445 Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc");
446 CGF.Builder.CreateStore(Next, ArrayIndexVar);
Sebastian Redl924db712012-02-19 15:41:54 +0000447
Richard Smith7c3e6152013-06-12 22:31:48 +0000448 // Update the LValue.
449 LV.setAddress(Dest);
450 CharUnits Align = CGF.getContext().getTypeAlignInChars(T);
451 LV.setAlignment(std::min(Align, LV.getAlignment()));
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000452 }
John McCall558d2ab2010-09-15 10:14:12 +0000453
Richard Smith7c3e6152013-06-12 22:31:48 +0000454 switch (CGF.getEvaluationKind(T)) {
455 case TEK_Scalar:
456 CGF.EmitScalarInit(Init, /*decl*/ 0, LV, false);
457 break;
458 case TEK_Complex:
459 CGF.EmitComplexExprIntoLValue(Init, LV, /*isInit*/ true);
460 break;
461 case TEK_Aggregate: {
462 AggValueSlot Slot =
463 AggValueSlot::forLValue(LV,
464 AggValueSlot::IsDestructed,
465 AggValueSlot::DoesNotNeedGCBarriers,
466 AggValueSlot::IsNotAliased);
467
468 CGF.EmitAggExpr(Init, Slot);
469 break;
470 }
471 }
Sebastian Redl924db712012-02-19 15:41:54 +0000472
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000473 return;
474 }
Richard Smith7c3e6152013-06-12 22:31:48 +0000475
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000476 const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T);
477 assert(Array && "Array initialization without the array type?");
478 llvm::Value *IndexVar
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000479 = CGF.GetAddrOfLocalVar(ArrayIndexes[Index]);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000480 assert(IndexVar && "Array index variable not loaded");
481
482 // Initialize this index variable to zero.
483 llvm::Value* Zero
484 = llvm::Constant::getNullValue(
485 CGF.ConvertType(CGF.getContext().getSizeType()));
486 CGF.Builder.CreateStore(Zero, IndexVar);
487
488 // Start the loop with a block that tests the condition.
489 llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond");
490 llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end");
491
492 CGF.EmitBlock(CondBlock);
493
494 llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body");
495 // Generate: if (loop-index < number-of-elements) fall to the loop body,
496 // otherwise, go to the block after the for-loop.
497 uint64_t NumElements = Array->getSize().getZExtValue();
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000498 llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
Chris Lattner985f7392010-05-06 06:35:23 +0000499 llvm::Value *NumElementsPtr =
500 llvm::ConstantInt::get(Counter->getType(), NumElements);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000501 llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr,
502 "isless");
503
504 // If the condition is true, execute the body.
505 CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor);
506
507 CGF.EmitBlock(ForBody);
508 llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc");
Richard Smith7c3e6152013-06-12 22:31:48 +0000509
510 // Inside the loop body recurse to emit the inner loop or, eventually, the
511 // constructor call.
512 EmitAggMemberInitializer(CGF, LHS, Init, ArrayIndexVar,
513 Array->getElementType(), ArrayIndexes, Index + 1);
514
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000515 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
Anders Carlsson607d0372009-12-24 22:46:43 +0000530static void EmitMemberInitializer(CodeGenFunction &CGF,
531 const CXXRecordDecl *ClassDecl,
Sean Huntcbb67482011-01-08 20:30:50 +0000532 CXXCtorInitializer *MemberInit,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000533 const CXXConstructorDecl *Constructor,
534 FunctionArgList &Args) {
Francois Pichet00eb3f92010-12-04 09:14:42 +0000535 assert(MemberInit->isAnyMemberInitializer() &&
Anders Carlsson607d0372009-12-24 22:46:43 +0000536 "Must have member initializer!");
Richard Smith7a614d82011-06-11 17:19:42 +0000537 assert(MemberInit->getInit() && "Must have initializer!");
Anders Carlsson607d0372009-12-24 22:46:43 +0000538
539 // non-static data member initializers.
Francois Pichet00eb3f92010-12-04 09:14:42 +0000540 FieldDecl *Field = MemberInit->getAnyMember();
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000541 QualType FieldType = Field->getType();
Anders Carlsson607d0372009-12-24 22:46:43 +0000542
543 llvm::Value *ThisPtr = CGF.LoadCXXThis();
Eli Friedman377ecc72012-04-16 03:54:45 +0000544 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
Eli Friedman859c65c2012-08-08 03:51:37 +0000545 LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
Eli Friedman377ecc72012-04-16 03:54:45 +0000546
Francois Pichet00eb3f92010-12-04 09:14:42 +0000547 if (MemberInit->isIndirectMemberInitializer()) {
Eli Friedman859c65c2012-08-08 03:51:37 +0000548 // If we are initializing an anonymous union field, drill down to
549 // the field.
550 IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember();
551 IndirectFieldDecl::chain_iterator I = IndirectField->chain_begin(),
552 IEnd = IndirectField->chain_end();
553 for ( ; I != IEnd; ++I)
554 LHS = CGF.EmitLValueForFieldInitialization(LHS, cast<FieldDecl>(*I));
Francois Pichet00eb3f92010-12-04 09:14:42 +0000555 FieldType = MemberInit->getIndirectMember()->getAnonField()->getType();
John McCalla9976d32010-05-21 01:18:57 +0000556 } else {
Eli Friedman859c65c2012-08-08 03:51:37 +0000557 LHS = CGF.EmitLValueForFieldInitialization(LHS, Field);
Anders Carlsson607d0372009-12-24 22:46:43 +0000558 }
559
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000560 // Special case: if we are in a copy or move constructor, and we are copying
561 // an array of PODs or classes with trivial copy constructors, ignore the
562 // AST and perform the copy we know is equivalent.
563 // FIXME: This is hacky at best... if we had a bit more explicit information
564 // in the AST, we could generalize it more easily.
565 const ConstantArrayType *Array
566 = CGF.getContext().getAsConstantArrayType(FieldType);
Jordan Rosea7b87972013-08-07 16:16:48 +0000567 if (Array && Constructor->isDefaulted() &&
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000568 Constructor->isCopyOrMoveConstructor()) {
569 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
Richard Smithe9385362012-11-07 23:56:21 +0000570 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000571 if (BaseElementTy.isPODType(CGF.getContext()) ||
Richard Smithe9385362012-11-07 23:56:21 +0000572 (CE && CE->getConstructor()->isTrivial())) {
573 // Find the source pointer. We know it's the last argument because
574 // we know we're in an implicit copy constructor.
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000575 unsigned SrcArgIndex = Args.size() - 1;
576 llvm::Value *SrcPtr
577 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
Eli Friedman377ecc72012-04-16 03:54:45 +0000578 LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
579 LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field);
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000580
581 // Copy the aggregate.
582 CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
Chad Rosier649b4a12012-03-29 17:37:10 +0000583 LHS.isVolatileQualified());
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000584 return;
585 }
586 }
587
588 ArrayRef<VarDecl *> ArrayIndexes;
589 if (MemberInit->getNumArrayIndices())
590 ArrayIndexes = MemberInit->getArrayIndexes();
Eli Friedmanb74ed082012-02-14 02:31:03 +0000591 CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit(), ArrayIndexes);
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000592}
593
Eli Friedmanb74ed082012-02-14 02:31:03 +0000594void CodeGenFunction::EmitInitializerForField(FieldDecl *Field,
595 LValue LHS, Expr *Init,
596 ArrayRef<VarDecl *> ArrayIndexes) {
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000597 QualType FieldType = Field->getType();
John McCall9d232c82013-03-07 21:37:08 +0000598 switch (getEvaluationKind(FieldType)) {
599 case TEK_Scalar:
John McCallf85e1932011-06-15 23:02:42 +0000600 if (LHS.isSimple()) {
Eli Friedmanb74ed082012-02-14 02:31:03 +0000601 EmitExprAsInit(Init, Field, LHS, false);
John McCallf85e1932011-06-15 23:02:42 +0000602 } else {
Eli Friedmanb74ed082012-02-14 02:31:03 +0000603 RValue RHS = RValue::get(EmitScalarExpr(Init));
604 EmitStoreThroughLValue(RHS, LHS);
John McCallf85e1932011-06-15 23:02:42 +0000605 }
John McCall9d232c82013-03-07 21:37:08 +0000606 break;
607 case TEK_Complex:
608 EmitComplexExprIntoLValue(Init, LHS, /*isInit*/ true);
609 break;
610 case TEK_Aggregate: {
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000611 llvm::Value *ArrayIndexVar = 0;
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000612 if (ArrayIndexes.size()) {
Eli Friedmanb74ed082012-02-14 02:31:03 +0000613 llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000614
615 // The LHS is a pointer to the first object we'll be constructing, as
616 // a flat array.
Eli Friedmanb74ed082012-02-14 02:31:03 +0000617 QualType BaseElementTy = getContext().getBaseElementType(FieldType);
618 llvm::Type *BasePtr = ConvertType(BaseElementTy);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000619 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Eli Friedmanb74ed082012-02-14 02:31:03 +0000620 llvm::Value *BaseAddrPtr = Builder.CreateBitCast(LHS.getAddress(),
621 BasePtr);
622 LHS = MakeAddrLValue(BaseAddrPtr, BaseElementTy);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000623
624 // Create an array index that will be used to walk over all of the
625 // objects we're constructing.
Eli Friedmanb74ed082012-02-14 02:31:03 +0000626 ArrayIndexVar = CreateTempAlloca(SizeTy, "object.index");
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000627 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
Eli Friedmanb74ed082012-02-14 02:31:03 +0000628 Builder.CreateStore(Zero, ArrayIndexVar);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000629
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000630
631 // Emit the block variables for the array indices, if any.
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000632 for (unsigned I = 0, N = ArrayIndexes.size(); I != N; ++I)
Eli Friedmanb74ed082012-02-14 02:31:03 +0000633 EmitAutoVarDecl(*ArrayIndexes[I]);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000634 }
635
Eli Friedmanb74ed082012-02-14 02:31:03 +0000636 EmitAggMemberInitializer(*this, LHS, Init, ArrayIndexVar, FieldType,
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000637 ArrayIndexes, 0);
Anders Carlsson607d0372009-12-24 22:46:43 +0000638 }
John McCall9d232c82013-03-07 21:37:08 +0000639 }
John McCall074cae02013-02-01 05:11:40 +0000640
641 // Ensure that we destroy this object if an exception is thrown
642 // later in the constructor.
643 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
644 if (needsEHCleanup(dtorKind))
645 pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
Anders Carlsson607d0372009-12-24 22:46:43 +0000646}
647
John McCallc0bf4622010-02-23 00:48:20 +0000648/// Checks whether the given constructor is a valid subject for the
649/// complete-to-base constructor delegation optimization, i.e.
650/// emitting the complete constructor as a simple call to the base
651/// constructor.
652static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
653
654 // Currently we disable the optimization for classes with virtual
655 // bases because (1) the addresses of parameter variables need to be
656 // consistent across all initializers but (2) the delegate function
657 // call necessarily creates a second copy of the parameter variable.
658 //
659 // The limiting example (purely theoretical AFAIK):
660 // struct A { A(int &c) { c++; } };
661 // struct B : virtual A {
662 // B(int count) : A(count) { printf("%d\n", count); }
663 // };
664 // ...although even this example could in principle be emitted as a
665 // delegation since the address of the parameter doesn't escape.
666 if (Ctor->getParent()->getNumVBases()) {
667 // TODO: white-list trivial vbase initializers. This case wouldn't
668 // be subject to the restrictions below.
669
670 // TODO: white-list cases where:
671 // - there are no non-reference parameters to the constructor
672 // - the initializers don't access any non-reference parameters
673 // - the initializers don't take the address of non-reference
674 // parameters
675 // - etc.
676 // If we ever add any of the above cases, remember that:
677 // - function-try-blocks will always blacklist this optimization
678 // - we need to perform the constructor prologue and cleanup in
679 // EmitConstructorBody.
680
681 return false;
682 }
683
684 // We also disable the optimization for variadic functions because
685 // it's impossible to "re-pass" varargs.
686 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
687 return false;
688
Sean Hunt059ce0d2011-05-01 07:04:31 +0000689 // FIXME: Decide if we can do a delegation of a delegating constructor.
690 if (Ctor->isDelegatingConstructor())
691 return false;
692
John McCallc0bf4622010-02-23 00:48:20 +0000693 return true;
694}
695
John McCall9fc6a772010-02-19 09:25:03 +0000696/// EmitConstructorBody - Emits the body of the current constructor.
697void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
698 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
699 CXXCtorType CtorType = CurGD.getCtorType();
700
John McCallc0bf4622010-02-23 00:48:20 +0000701 // Before we go any further, try the complete->base constructor
702 // delegation optimization.
Timur Iskhodzhanov85607912012-04-20 08:05:00 +0000703 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
John McCall64aa4b32013-04-16 22:48:15 +0000704 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
Devang Pateld67ef0e2010-08-11 21:04:37 +0000705 if (CGDebugInfo *DI = getDebugInfo())
Eric Christopher73fb3502011-10-13 21:45:18 +0000706 DI->EmitLocation(Builder, Ctor->getLocEnd());
Nick Lewycky4ee7dc22013-10-02 02:29:49 +0000707 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args, Ctor->getLocEnd());
John McCallc0bf4622010-02-23 00:48:20 +0000708 return;
709 }
710
John McCall9fc6a772010-02-19 09:25:03 +0000711 Stmt *Body = Ctor->getBody();
712
John McCallc0bf4622010-02-23 00:48:20 +0000713 // Enter the function-try-block before the constructor prologue if
714 // applicable.
John McCallc0bf4622010-02-23 00:48:20 +0000715 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallc0bf4622010-02-23 00:48:20 +0000716 if (IsTryBody)
John McCall59a70002010-07-07 06:56:46 +0000717 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000718
Richard Smith7c3e6152013-06-12 22:31:48 +0000719 RunCleanupsScope RunCleanups(*this);
John McCall9fc6a772010-02-19 09:25:03 +0000720
John McCall56ea3772012-03-30 04:25:03 +0000721 // TODO: in restricted cases, we can emit the vbase initializers of
722 // a complete ctor and then delegate to the base ctor.
723
John McCallc0bf4622010-02-23 00:48:20 +0000724 // Emit the constructor prologue, i.e. the base and member
725 // initializers.
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000726 EmitCtorPrologue(Ctor, CtorType, Args);
John McCall9fc6a772010-02-19 09:25:03 +0000727
728 // Emit the body of the statement.
John McCallc0bf4622010-02-23 00:48:20 +0000729 if (IsTryBody)
John McCall9fc6a772010-02-19 09:25:03 +0000730 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
731 else if (Body)
732 EmitStmt(Body);
John McCall9fc6a772010-02-19 09:25:03 +0000733
734 // Emit any cleanup blocks associated with the member or base
735 // initializers, which includes (along the exceptional path) the
736 // destructors for those members and bases that were fully
737 // constructed.
Richard Smith7c3e6152013-06-12 22:31:48 +0000738 RunCleanups.ForceCleanup();
John McCall9fc6a772010-02-19 09:25:03 +0000739
John McCallc0bf4622010-02-23 00:48:20 +0000740 if (IsTryBody)
John McCall59a70002010-07-07 06:56:46 +0000741 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000742}
743
Lang Hames56c00c42013-02-17 07:22:09 +0000744namespace {
Nick Lewycky62a3bba2013-09-11 02:03:20 +0000745 /// RAII object to indicate that codegen is copying the value representation
746 /// instead of the object representation. Useful when copying a struct or
747 /// class which has uninitialized members and we're only performing
748 /// lvalue-to-rvalue conversion on the object but not its members.
749 class CopyingValueRepresentation {
750 public:
751 explicit CopyingValueRepresentation(CodeGenFunction &CGF)
752 : CGF(CGF), SO(*CGF.SanOpts), OldSanOpts(CGF.SanOpts) {
753 SO.Bool = false;
754 SO.Enum = false;
755 CGF.SanOpts = &SO;
756 }
757 ~CopyingValueRepresentation() {
758 CGF.SanOpts = OldSanOpts;
759 }
760 private:
761 CodeGenFunction &CGF;
762 SanitizerOptions SO;
763 const SanitizerOptions *OldSanOpts;
764 };
765}
766
767namespace {
Lang Hames56c00c42013-02-17 07:22:09 +0000768 class FieldMemcpyizer {
769 public:
770 FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl,
771 const VarDecl *SrcRec)
772 : CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec),
773 RecLayout(CGF.getContext().getASTRecordLayout(ClassDecl)),
774 FirstField(0), LastField(0), FirstFieldOffset(0), LastFieldOffset(0),
775 LastAddedFieldIndex(0) { }
776
777 static bool isMemcpyableField(FieldDecl *F) {
778 Qualifiers Qual = F->getType().getQualifiers();
779 if (Qual.hasVolatile() || Qual.hasObjCLifetime())
780 return false;
781 return true;
782 }
783
784 void addMemcpyableField(FieldDecl *F) {
785 if (FirstField == 0)
786 addInitialField(F);
787 else
788 addNextField(F);
789 }
790
791 CharUnits getMemcpySize() const {
792 unsigned LastFieldSize =
793 LastField->isBitField() ?
794 LastField->getBitWidthValue(CGF.getContext()) :
795 CGF.getContext().getTypeSize(LastField->getType());
796 uint64_t MemcpySizeBits =
797 LastFieldOffset + LastFieldSize - FirstFieldOffset +
798 CGF.getContext().getCharWidth() - 1;
799 CharUnits MemcpySize =
800 CGF.getContext().toCharUnitsFromBits(MemcpySizeBits);
801 return MemcpySize;
802 }
803
804 void emitMemcpy() {
805 // Give the subclass a chance to bail out if it feels the memcpy isn't
806 // worth it (e.g. Hasn't aggregated enough data).
807 if (FirstField == 0) {
808 return;
809 }
810
Lang Hames5e8577e2013-02-27 04:14:49 +0000811 CharUnits Alignment;
Lang Hames56c00c42013-02-17 07:22:09 +0000812
813 if (FirstField->isBitField()) {
814 const CGRecordLayout &RL =
815 CGF.getTypes().getCGRecordLayout(FirstField->getParent());
816 const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField);
Lang Hames5e8577e2013-02-27 04:14:49 +0000817 Alignment = CharUnits::fromQuantity(BFInfo.StorageAlignment);
818 } else {
Lang Hames23742cd2013-03-05 20:27:24 +0000819 Alignment = CGF.getContext().getDeclAlign(FirstField);
Lang Hames5e8577e2013-02-27 04:14:49 +0000820 }
Lang Hames56c00c42013-02-17 07:22:09 +0000821
Lang Hames5e8577e2013-02-27 04:14:49 +0000822 assert((CGF.getContext().toCharUnitsFromBits(FirstFieldOffset) %
823 Alignment) == 0 && "Bad field alignment.");
824
Lang Hames56c00c42013-02-17 07:22:09 +0000825 CharUnits MemcpySize = getMemcpySize();
826 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
827 llvm::Value *ThisPtr = CGF.LoadCXXThis();
828 LValue DestLV = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
829 LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField);
830 llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec));
831 LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
832 LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField);
833
834 emitMemcpyIR(Dest.isBitField() ? Dest.getBitFieldAddr() : Dest.getAddress(),
835 Src.isBitField() ? Src.getBitFieldAddr() : Src.getAddress(),
836 MemcpySize, Alignment);
837 reset();
838 }
839
840 void reset() {
841 FirstField = 0;
842 }
843
844 protected:
845 CodeGenFunction &CGF;
846 const CXXRecordDecl *ClassDecl;
847
848 private:
849
850 void emitMemcpyIR(llvm::Value *DestPtr, llvm::Value *SrcPtr,
851 CharUnits Size, CharUnits Alignment) {
852 llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
853 llvm::Type *DBP =
854 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), DPT->getAddressSpace());
855 DestPtr = CGF.Builder.CreateBitCast(DestPtr, DBP);
856
857 llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
858 llvm::Type *SBP =
859 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), SPT->getAddressSpace());
860 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, SBP);
861
862 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity(),
863 Alignment.getQuantity());
864 }
865
866 void addInitialField(FieldDecl *F) {
867 FirstField = F;
868 LastField = F;
869 FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex());
870 LastFieldOffset = FirstFieldOffset;
871 LastAddedFieldIndex = F->getFieldIndex();
872 return;
873 }
874
875 void addNextField(FieldDecl *F) {
John McCall402cd222013-05-07 05:20:46 +0000876 // For the most part, the following invariant will hold:
877 // F->getFieldIndex() == LastAddedFieldIndex + 1
878 // The one exception is that Sema won't add a copy-initializer for an
879 // unnamed bitfield, which will show up here as a gap in the sequence.
880 assert(F->getFieldIndex() >= LastAddedFieldIndex + 1 &&
881 "Cannot aggregate fields out of order.");
Lang Hames56c00c42013-02-17 07:22:09 +0000882 LastAddedFieldIndex = F->getFieldIndex();
883
884 // The 'first' and 'last' fields are chosen by offset, rather than field
885 // index. This allows the code to support bitfields, as well as regular
886 // fields.
887 uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex());
888 if (FOffset < FirstFieldOffset) {
889 FirstField = F;
890 FirstFieldOffset = FOffset;
891 } else if (FOffset > LastFieldOffset) {
892 LastField = F;
893 LastFieldOffset = FOffset;
894 }
895 }
896
897 const VarDecl *SrcRec;
898 const ASTRecordLayout &RecLayout;
899 FieldDecl *FirstField;
900 FieldDecl *LastField;
901 uint64_t FirstFieldOffset, LastFieldOffset;
902 unsigned LastAddedFieldIndex;
903 };
904
905 class ConstructorMemcpyizer : public FieldMemcpyizer {
906 private:
907
908 /// Get source argument for copy constructor. Returns null if not a copy
909 /// constructor.
910 static const VarDecl* getTrivialCopySource(const CXXConstructorDecl *CD,
911 FunctionArgList &Args) {
Jordan Rosea7b87972013-08-07 16:16:48 +0000912 if (CD->isCopyOrMoveConstructor() && CD->isDefaulted())
Lang Hames56c00c42013-02-17 07:22:09 +0000913 return Args[Args.size() - 1];
914 return 0;
915 }
916
917 // Returns true if a CXXCtorInitializer represents a member initialization
918 // that can be rolled into a memcpy.
919 bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const {
920 if (!MemcpyableCtor)
921 return false;
922 FieldDecl *Field = MemberInit->getMember();
923 assert(Field != 0 && "No field for member init.");
924 QualType FieldType = Field->getType();
925 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
926
927 // Bail out on non-POD, not-trivially-constructable members.
928 if (!(CE && CE->getConstructor()->isTrivial()) &&
929 !(FieldType.isTriviallyCopyableType(CGF.getContext()) ||
930 FieldType->isReferenceType()))
931 return false;
932
933 // Bail out on volatile fields.
934 if (!isMemcpyableField(Field))
935 return false;
936
937 // Otherwise we're good.
938 return true;
939 }
940
941 public:
942 ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD,
943 FunctionArgList &Args)
944 : FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CD, Args)),
945 ConstructorDecl(CD),
Jordan Rosea7b87972013-08-07 16:16:48 +0000946 MemcpyableCtor(CD->isDefaulted() &&
Lang Hames56c00c42013-02-17 07:22:09 +0000947 CD->isCopyOrMoveConstructor() &&
948 CGF.getLangOpts().getGC() == LangOptions::NonGC),
949 Args(Args) { }
950
951 void addMemberInitializer(CXXCtorInitializer *MemberInit) {
952 if (isMemberInitMemcpyable(MemberInit)) {
953 AggregatedInits.push_back(MemberInit);
954 addMemcpyableField(MemberInit->getMember());
955 } else {
956 emitAggregatedInits();
957 EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit,
958 ConstructorDecl, Args);
959 }
960 }
961
962 void emitAggregatedInits() {
963 if (AggregatedInits.size() <= 1) {
964 // This memcpy is too small to be worthwhile. Fall back on default
965 // codegen.
Nick Lewycky62a3bba2013-09-11 02:03:20 +0000966 if (!AggregatedInits.empty()) {
967 CopyingValueRepresentation CVR(CGF);
Lang Hames56c00c42013-02-17 07:22:09 +0000968 EmitMemberInitializer(CGF, ConstructorDecl->getParent(),
Nick Lewycky62a3bba2013-09-11 02:03:20 +0000969 AggregatedInits[0], ConstructorDecl, Args);
Lang Hames56c00c42013-02-17 07:22:09 +0000970 }
971 reset();
972 return;
973 }
974
975 pushEHDestructors();
976 emitMemcpy();
977 AggregatedInits.clear();
978 }
979
980 void pushEHDestructors() {
981 llvm::Value *ThisPtr = CGF.LoadCXXThis();
982 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
983 LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
984
985 for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
986 QualType FieldType = AggregatedInits[i]->getMember()->getType();
987 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
988 if (CGF.needsEHCleanup(dtorKind))
989 CGF.pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
990 }
991 }
992
993 void finish() {
994 emitAggregatedInits();
995 }
996
997 private:
998 const CXXConstructorDecl *ConstructorDecl;
999 bool MemcpyableCtor;
1000 FunctionArgList &Args;
1001 SmallVector<CXXCtorInitializer*, 16> AggregatedInits;
1002 };
1003
1004 class AssignmentMemcpyizer : public FieldMemcpyizer {
1005 private:
1006
1007 // Returns the memcpyable field copied by the given statement, if one
Nick Lewycky62a3bba2013-09-11 02:03:20 +00001008 // exists. Otherwise returns null.
1009 FieldDecl *getMemcpyableField(Stmt *S) {
Lang Hames56c00c42013-02-17 07:22:09 +00001010 if (!AssignmentsMemcpyable)
1011 return 0;
1012 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
1013 // Recognise trivial assignments.
1014 if (BO->getOpcode() != BO_Assign)
1015 return 0;
1016 MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS());
1017 if (!ME)
1018 return 0;
1019 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1020 if (!Field || !isMemcpyableField(Field))
1021 return 0;
1022 Stmt *RHS = BO->getRHS();
1023 if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS))
1024 RHS = EC->getSubExpr();
1025 if (!RHS)
1026 return 0;
1027 MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS);
1028 if (dyn_cast<FieldDecl>(ME2->getMemberDecl()) != Field)
1029 return 0;
1030 return Field;
1031 } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) {
1032 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl());
1033 if (!(MD && (MD->isCopyAssignmentOperator() ||
1034 MD->isMoveAssignmentOperator()) &&
1035 MD->isTrivial()))
1036 return 0;
1037 MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument());
1038 if (!IOA)
1039 return 0;
1040 FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl());
1041 if (!Field || !isMemcpyableField(Field))
1042 return 0;
1043 MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0));
1044 if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl()))
1045 return 0;
1046 return Field;
1047 } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1048 FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1049 if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy)
1050 return 0;
1051 Expr *DstPtr = CE->getArg(0);
1052 if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr))
1053 DstPtr = DC->getSubExpr();
1054 UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr);
1055 if (!DUO || DUO->getOpcode() != UO_AddrOf)
1056 return 0;
1057 MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr());
1058 if (!ME)
1059 return 0;
1060 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1061 if (!Field || !isMemcpyableField(Field))
1062 return 0;
1063 Expr *SrcPtr = CE->getArg(1);
1064 if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr))
1065 SrcPtr = SC->getSubExpr();
1066 UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr);
1067 if (!SUO || SUO->getOpcode() != UO_AddrOf)
1068 return 0;
1069 MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr());
1070 if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl()))
1071 return 0;
1072 return Field;
1073 }
1074
1075 return 0;
1076 }
1077
1078 bool AssignmentsMemcpyable;
1079 SmallVector<Stmt*, 16> AggregatedStmts;
1080
1081 public:
1082
1083 AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD,
1084 FunctionArgList &Args)
1085 : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]),
1086 AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) {
1087 assert(Args.size() == 2);
1088 }
1089
1090 void emitAssignment(Stmt *S) {
1091 FieldDecl *F = getMemcpyableField(S);
1092 if (F) {
1093 addMemcpyableField(F);
1094 AggregatedStmts.push_back(S);
1095 } else {
1096 emitAggregatedStmts();
1097 CGF.EmitStmt(S);
1098 }
1099 }
1100
1101 void emitAggregatedStmts() {
1102 if (AggregatedStmts.size() <= 1) {
Nick Lewycky62a3bba2013-09-11 02:03:20 +00001103 if (!AggregatedStmts.empty()) {
1104 CopyingValueRepresentation CVR(CGF);
1105 CGF.EmitStmt(AggregatedStmts[0]);
1106 }
Lang Hames56c00c42013-02-17 07:22:09 +00001107 reset();
1108 }
1109
1110 emitMemcpy();
1111 AggregatedStmts.clear();
1112 }
1113
1114 void finish() {
1115 emitAggregatedStmts();
1116 }
1117 };
1118
1119}
1120
Anders Carlsson607d0372009-12-24 22:46:43 +00001121/// EmitCtorPrologue - This routine generates necessary code to initialize
1122/// base classes and non-static data members belonging to this constructor.
Anders Carlsson607d0372009-12-24 22:46:43 +00001123void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001124 CXXCtorType CtorType,
1125 FunctionArgList &Args) {
Sean Hunt059ce0d2011-05-01 07:04:31 +00001126 if (CD->isDelegatingConstructor())
1127 return EmitDelegatingCXXConstructorCall(CD, Args);
1128
Anders Carlsson607d0372009-12-24 22:46:43 +00001129 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlssona78fa2c2010-02-02 19:58:43 +00001130
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001131 CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
1132 E = CD->init_end();
1133
1134 llvm::BasicBlock *BaseCtorContinueBB = 0;
1135 if (ClassDecl->getNumVBases() &&
1136 !CGM.getTarget().getCXXABI().hasConstructorVariants()) {
1137 // The ABIs that don't have constructor variants need to put a branch
1138 // before the virtual base initialization code.
Reid Kleckner90633022013-06-19 15:20:38 +00001139 BaseCtorContinueBB =
1140 CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this, ClassDecl);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001141 assert(BaseCtorContinueBB);
1142 }
1143
1144 // Virtual base initializers first.
1145 for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
1146 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
1147 }
1148
1149 if (BaseCtorContinueBB) {
1150 // Complete object handler should continue to the remaining initializers.
1151 Builder.CreateBr(BaseCtorContinueBB);
1152 EmitBlock(BaseCtorContinueBB);
1153 }
1154
1155 // Then, non-virtual base initializers.
1156 for (; B != E && (*B)->isBaseInitializer(); B++) {
1157 assert(!(*B)->isBaseVirtual());
1158 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
Anders Carlsson607d0372009-12-24 22:46:43 +00001159 }
1160
Anders Carlsson603d6d12010-03-28 21:07:49 +00001161 InitializeVTablePointers(ClassDecl);
Anders Carlssona78fa2c2010-02-02 19:58:43 +00001162
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001163 // And finally, initialize class members.
Richard Smithc3bf52c2013-04-20 22:23:05 +00001164 FieldConstructionScope FCS(*this, CXXThisValue);
Lang Hames56c00c42013-02-17 07:22:09 +00001165 ConstructorMemcpyizer CM(*this, CD, Args);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001166 for (; B != E; B++) {
1167 CXXCtorInitializer *Member = (*B);
1168 assert(!Member->isBaseInitializer());
1169 assert(Member->isAnyMemberInitializer() &&
1170 "Delegating initializer on non-delegating constructor");
1171 CM.addMemberInitializer(Member);
1172 }
Lang Hames56c00c42013-02-17 07:22:09 +00001173 CM.finish();
Anders Carlsson607d0372009-12-24 22:46:43 +00001174}
1175
Anders Carlssonadf5dc32011-05-15 17:36:21 +00001176static bool
1177FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
1178
1179static bool
1180HasTrivialDestructorBody(ASTContext &Context,
1181 const CXXRecordDecl *BaseClassDecl,
1182 const CXXRecordDecl *MostDerivedClassDecl)
1183{
1184 // If the destructor is trivial we don't have to check anything else.
1185 if (BaseClassDecl->hasTrivialDestructor())
1186 return true;
1187
1188 if (!BaseClassDecl->getDestructor()->hasTrivialBody())
1189 return false;
1190
1191 // Check fields.
1192 for (CXXRecordDecl::field_iterator I = BaseClassDecl->field_begin(),
1193 E = BaseClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001194 const FieldDecl *Field = *I;
Anders Carlssonadf5dc32011-05-15 17:36:21 +00001195
1196 if (!FieldHasTrivialDestructorBody(Context, Field))
1197 return false;
1198 }
1199
1200 // Check non-virtual bases.
1201 for (CXXRecordDecl::base_class_const_iterator I =
1202 BaseClassDecl->bases_begin(), E = BaseClassDecl->bases_end();
1203 I != E; ++I) {
1204 if (I->isVirtual())
1205 continue;
1206
1207 const CXXRecordDecl *NonVirtualBase =
1208 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
1209 if (!HasTrivialDestructorBody(Context, NonVirtualBase,
1210 MostDerivedClassDecl))
1211 return false;
1212 }
1213
1214 if (BaseClassDecl == MostDerivedClassDecl) {
1215 // Check virtual bases.
1216 for (CXXRecordDecl::base_class_const_iterator I =
1217 BaseClassDecl->vbases_begin(), E = BaseClassDecl->vbases_end();
1218 I != E; ++I) {
1219 const CXXRecordDecl *VirtualBase =
1220 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
1221 if (!HasTrivialDestructorBody(Context, VirtualBase,
1222 MostDerivedClassDecl))
1223 return false;
1224 }
1225 }
1226
1227 return true;
1228}
1229
1230static bool
1231FieldHasTrivialDestructorBody(ASTContext &Context,
1232 const FieldDecl *Field)
1233{
1234 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
1235
1236 const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
1237 if (!RT)
1238 return true;
1239
1240 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1241 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
1242}
1243
Anders Carlssonffb945f2011-05-14 23:26:09 +00001244/// CanSkipVTablePointerInitialization - Check whether we need to initialize
1245/// any vtable pointers before calling this destructor.
1246static bool CanSkipVTablePointerInitialization(ASTContext &Context,
Anders Carlssone3d6cf22011-05-16 04:08:36 +00001247 const CXXDestructorDecl *Dtor) {
Anders Carlssonffb945f2011-05-14 23:26:09 +00001248 if (!Dtor->hasTrivialBody())
1249 return false;
1250
1251 // Check the fields.
1252 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1253 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1254 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001255 const FieldDecl *Field = *I;
Anders Carlssonffb945f2011-05-14 23:26:09 +00001256
Anders Carlssonadf5dc32011-05-15 17:36:21 +00001257 if (!FieldHasTrivialDestructorBody(Context, Field))
1258 return false;
Anders Carlssonffb945f2011-05-14 23:26:09 +00001259 }
1260
1261 return true;
1262}
1263
John McCall9fc6a772010-02-19 09:25:03 +00001264/// EmitDestructorBody - Emits the body of the current destructor.
1265void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
1266 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
1267 CXXDtorType DtorType = CurGD.getDtorType();
1268
John McCall50da2ca2010-07-21 05:30:47 +00001269 // The call to operator delete in a deleting destructor happens
1270 // outside of the function-try-block, which means it's always
1271 // possible to delegate the destructor body to the complete
1272 // destructor. Do so.
1273 if (DtorType == Dtor_Deleting) {
1274 EnterDtorCleanups(Dtor, Dtor_Deleting);
1275 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001276 /*Delegating=*/false, LoadCXXThis());
John McCall50da2ca2010-07-21 05:30:47 +00001277 PopCleanupBlock();
1278 return;
1279 }
1280
John McCall9fc6a772010-02-19 09:25:03 +00001281 Stmt *Body = Dtor->getBody();
1282
1283 // If the body is a function-try-block, enter the try before
John McCall50da2ca2010-07-21 05:30:47 +00001284 // anything else.
1285 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCall9fc6a772010-02-19 09:25:03 +00001286 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +00001287 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +00001288
John McCall50da2ca2010-07-21 05:30:47 +00001289 // Enter the epilogue cleanups.
1290 RunCleanupsScope DtorEpilogue(*this);
1291
John McCall9fc6a772010-02-19 09:25:03 +00001292 // If this is the complete variant, just invoke the base variant;
1293 // the epilogue will destruct the virtual bases. But we can't do
1294 // this optimization if the body is a function-try-block, because
Reid Klecknera4130ba2013-07-22 13:51:44 +00001295 // we'd introduce *two* handler blocks. In the Microsoft ABI, we
1296 // always delegate because we might not have a definition in this TU.
John McCall50da2ca2010-07-21 05:30:47 +00001297 switch (DtorType) {
1298 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
1299
1300 case Dtor_Complete:
Reid Klecknera4130ba2013-07-22 13:51:44 +00001301 assert((Body || getTarget().getCXXABI().isMicrosoft()) &&
1302 "can't emit a dtor without a body for non-Microsoft ABIs");
1303
John McCall50da2ca2010-07-21 05:30:47 +00001304 // Enter the cleanup scopes for virtual bases.
1305 EnterDtorCleanups(Dtor, Dtor_Complete);
1306
Reid Klecknera4130ba2013-07-22 13:51:44 +00001307 if (!isTryBody) {
John McCall50da2ca2010-07-21 05:30:47 +00001308 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001309 /*Delegating=*/false, LoadCXXThis());
John McCall50da2ca2010-07-21 05:30:47 +00001310 break;
1311 }
1312 // Fallthrough: act like we're in the base variant.
John McCall9fc6a772010-02-19 09:25:03 +00001313
John McCall50da2ca2010-07-21 05:30:47 +00001314 case Dtor_Base:
Reid Klecknera4130ba2013-07-22 13:51:44 +00001315 assert(Body);
1316
John McCall50da2ca2010-07-21 05:30:47 +00001317 // Enter the cleanup scopes for fields and non-virtual bases.
1318 EnterDtorCleanups(Dtor, Dtor_Base);
1319
1320 // Initialize the vtable pointers before entering the body.
Anders Carlssonffb945f2011-05-14 23:26:09 +00001321 if (!CanSkipVTablePointerInitialization(getContext(), Dtor))
1322 InitializeVTablePointers(Dtor->getParent());
John McCall50da2ca2010-07-21 05:30:47 +00001323
1324 if (isTryBody)
1325 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
1326 else if (Body)
1327 EmitStmt(Body);
1328 else {
1329 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
1330 // nothing to do besides what's in the epilogue
1331 }
Fariborz Jahanian5abec142011-02-02 23:12:46 +00001332 // -fapple-kext must inline any call to this dtor into
1333 // the caller's body.
Richard Smith7edf9e32012-11-01 22:30:59 +00001334 if (getLangOpts().AppleKext)
Bill Wendling72390b32012-12-20 19:27:06 +00001335 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
John McCall50da2ca2010-07-21 05:30:47 +00001336 break;
John McCall9fc6a772010-02-19 09:25:03 +00001337 }
1338
John McCall50da2ca2010-07-21 05:30:47 +00001339 // Jump out through the epilogue cleanups.
1340 DtorEpilogue.ForceCleanup();
John McCall9fc6a772010-02-19 09:25:03 +00001341
1342 // Exit the try if applicable.
1343 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +00001344 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +00001345}
1346
Lang Hames56c00c42013-02-17 07:22:09 +00001347void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) {
1348 const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
1349 const Stmt *RootS = AssignOp->getBody();
1350 assert(isa<CompoundStmt>(RootS) &&
1351 "Body of an implicit assignment operator should be compound stmt.");
1352 const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
1353
1354 LexicalScope Scope(*this, RootCS->getSourceRange());
1355
1356 AssignmentMemcpyizer AM(*this, AssignOp, Args);
1357 for (CompoundStmt::const_body_iterator I = RootCS->body_begin(),
1358 E = RootCS->body_end();
1359 I != E; ++I) {
1360 AM.emitAssignment(*I);
1361 }
1362 AM.finish();
1363}
1364
John McCall50da2ca2010-07-21 05:30:47 +00001365namespace {
1366 /// Call the operator delete associated with the current destructor.
John McCall1f0fca52010-07-21 07:22:38 +00001367 struct CallDtorDelete : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +00001368 CallDtorDelete() {}
1369
John McCallad346f42011-07-12 20:27:29 +00001370 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall50da2ca2010-07-21 05:30:47 +00001371 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1372 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1373 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1374 CGF.getContext().getTagDeclType(ClassDecl));
1375 }
1376 };
1377
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +00001378 struct CallDtorDeleteConditional : EHScopeStack::Cleanup {
1379 llvm::Value *ShouldDeleteCondition;
1380 public:
1381 CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
1382 : ShouldDeleteCondition(ShouldDeleteCondition) {
1383 assert(ShouldDeleteCondition != NULL);
1384 }
1385
1386 void Emit(CodeGenFunction &CGF, Flags flags) {
1387 llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
1388 llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
1389 llvm::Value *ShouldCallDelete
1390 = CGF.Builder.CreateIsNull(ShouldDeleteCondition);
1391 CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
1392
1393 CGF.EmitBlock(callDeleteBB);
1394 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1395 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1396 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1397 CGF.getContext().getTagDeclType(ClassDecl));
1398 CGF.Builder.CreateBr(continueBB);
1399
1400 CGF.EmitBlock(continueBB);
1401 }
1402 };
1403
John McCall9928c482011-07-12 16:41:08 +00001404 class DestroyField : public EHScopeStack::Cleanup {
1405 const FieldDecl *field;
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001406 CodeGenFunction::Destroyer *destroyer;
John McCall9928c482011-07-12 16:41:08 +00001407 bool useEHCleanupForArray;
John McCall50da2ca2010-07-21 05:30:47 +00001408
John McCall9928c482011-07-12 16:41:08 +00001409 public:
1410 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
1411 bool useEHCleanupForArray)
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001412 : field(field), destroyer(destroyer),
John McCall9928c482011-07-12 16:41:08 +00001413 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall50da2ca2010-07-21 05:30:47 +00001414
John McCallad346f42011-07-12 20:27:29 +00001415 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall9928c482011-07-12 16:41:08 +00001416 // Find the address of the field.
1417 llvm::Value *thisValue = CGF.LoadCXXThis();
Eli Friedman377ecc72012-04-16 03:54:45 +00001418 QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
1419 LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
1420 LValue LV = CGF.EmitLValueForField(ThisLV, field);
John McCall9928c482011-07-12 16:41:08 +00001421 assert(LV.isSimple());
1422
1423 CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
John McCallad346f42011-07-12 20:27:29 +00001424 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCall50da2ca2010-07-21 05:30:47 +00001425 }
1426 };
1427}
1428
Anders Carlsson607d0372009-12-24 22:46:43 +00001429/// EmitDtorEpilogue - Emit all code that comes at the end of class's
1430/// destructor. This is to call destructors on members and base classes
1431/// in reverse order of their construction.
John McCall50da2ca2010-07-21 05:30:47 +00001432void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
1433 CXXDtorType DtorType) {
Anders Carlsson607d0372009-12-24 22:46:43 +00001434 assert(!DD->isTrivial() &&
1435 "Should not emit dtor epilogue for trivial dtor!");
1436
John McCall50da2ca2010-07-21 05:30:47 +00001437 // The deleting-destructor phase just needs to call the appropriate
1438 // operator delete that Sema picked up.
John McCall3b477332010-02-18 19:59:28 +00001439 if (DtorType == Dtor_Deleting) {
1440 assert(DD->getOperatorDelete() &&
1441 "operator delete missing - EmitDtorEpilogue");
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +00001442 if (CXXStructorImplicitParamValue) {
1443 // If there is an implicit param to the deleting dtor, it's a boolean
1444 // telling whether we should call delete at the end of the dtor.
1445 EHStack.pushCleanup<CallDtorDeleteConditional>(
1446 NormalAndEHCleanup, CXXStructorImplicitParamValue);
1447 } else {
1448 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
1449 }
John McCall3b477332010-02-18 19:59:28 +00001450 return;
1451 }
1452
John McCall50da2ca2010-07-21 05:30:47 +00001453 const CXXRecordDecl *ClassDecl = DD->getParent();
1454
Richard Smith416f63e2011-09-18 12:11:43 +00001455 // Unions have no bases and do not call field destructors.
1456 if (ClassDecl->isUnion())
1457 return;
1458
John McCall50da2ca2010-07-21 05:30:47 +00001459 // The complete-destructor phase just destructs all the virtual bases.
John McCall3b477332010-02-18 19:59:28 +00001460 if (DtorType == Dtor_Complete) {
John McCall50da2ca2010-07-21 05:30:47 +00001461
1462 // We push them in the forward order so that they'll be popped in
1463 // the reverse order.
1464 for (CXXRecordDecl::base_class_const_iterator I =
1465 ClassDecl->vbases_begin(), E = ClassDecl->vbases_end();
John McCall3b477332010-02-18 19:59:28 +00001466 I != E; ++I) {
1467 const CXXBaseSpecifier &Base = *I;
1468 CXXRecordDecl *BaseClassDecl
1469 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1470
1471 // Ignore trivial destructors.
1472 if (BaseClassDecl->hasTrivialDestructor())
1473 continue;
John McCall50da2ca2010-07-21 05:30:47 +00001474
John McCall1f0fca52010-07-21 07:22:38 +00001475 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1476 BaseClassDecl,
1477 /*BaseIsVirtual*/ true);
John McCall3b477332010-02-18 19:59:28 +00001478 }
John McCall50da2ca2010-07-21 05:30:47 +00001479
John McCall3b477332010-02-18 19:59:28 +00001480 return;
1481 }
1482
1483 assert(DtorType == Dtor_Base);
John McCall50da2ca2010-07-21 05:30:47 +00001484
1485 // Destroy non-virtual bases.
1486 for (CXXRecordDecl::base_class_const_iterator I =
1487 ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) {
1488 const CXXBaseSpecifier &Base = *I;
1489
1490 // Ignore virtual bases.
1491 if (Base.isVirtual())
1492 continue;
1493
1494 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
1495
1496 // Ignore trivial destructors.
1497 if (BaseClassDecl->hasTrivialDestructor())
1498 continue;
John McCall3b477332010-02-18 19:59:28 +00001499
John McCall1f0fca52010-07-21 07:22:38 +00001500 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1501 BaseClassDecl,
1502 /*BaseIsVirtual*/ false);
John McCall50da2ca2010-07-21 05:30:47 +00001503 }
1504
1505 // Destroy direct fields.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001506 SmallVector<const FieldDecl *, 16> FieldDecls;
Anders Carlsson607d0372009-12-24 22:46:43 +00001507 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1508 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001509 const FieldDecl *field = *I;
John McCall9928c482011-07-12 16:41:08 +00001510 QualType type = field->getType();
1511 QualType::DestructionKind dtorKind = type.isDestructedType();
1512 if (!dtorKind) continue;
John McCall50da2ca2010-07-21 05:30:47 +00001513
Richard Smith9a561d52012-02-26 09:11:52 +00001514 // Anonymous union members do not have their destructors called.
1515 const RecordType *RT = type->getAsUnionType();
1516 if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
1517
John McCall9928c482011-07-12 16:41:08 +00001518 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1519 EHStack.pushCleanup<DestroyField>(cleanupKind, field,
1520 getDestroyer(dtorKind),
1521 cleanupKind & EHCleanup);
Anders Carlsson607d0372009-12-24 22:46:43 +00001522 }
Anders Carlsson607d0372009-12-24 22:46:43 +00001523}
1524
John McCallc3c07662011-07-13 06:10:41 +00001525/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1526/// constructor for each of several members of an array.
Douglas Gregor59174c02010-07-21 01:10:17 +00001527///
John McCallc3c07662011-07-13 06:10:41 +00001528/// \param ctor the constructor to call for each element
John McCallc3c07662011-07-13 06:10:41 +00001529/// \param arrayType the type of the array to initialize
1530/// \param arrayBegin an arrayType*
1531/// \param zeroInitialize true if each element should be
1532/// zero-initialized before it is constructed
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001533void
John McCallc3c07662011-07-13 06:10:41 +00001534CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1535 const ConstantArrayType *arrayType,
1536 llvm::Value *arrayBegin,
1537 CallExpr::const_arg_iterator argBegin,
1538 CallExpr::const_arg_iterator argEnd,
1539 bool zeroInitialize) {
1540 QualType elementType;
1541 llvm::Value *numElements =
1542 emitArrayLength(arrayType, elementType, arrayBegin);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001543
John McCallc3c07662011-07-13 06:10:41 +00001544 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin,
1545 argBegin, argEnd, zeroInitialize);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001546}
1547
John McCallc3c07662011-07-13 06:10:41 +00001548/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1549/// constructor for each of several members of an array.
1550///
1551/// \param ctor the constructor to call for each element
1552/// \param numElements the number of elements in the array;
John McCalldd376ca2011-07-13 07:37:11 +00001553/// may be zero
John McCallc3c07662011-07-13 06:10:41 +00001554/// \param arrayBegin a T*, where T is the type constructed by ctor
1555/// \param zeroInitialize true if each element should be
1556/// zero-initialized before it is constructed
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001557void
John McCallc3c07662011-07-13 06:10:41 +00001558CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1559 llvm::Value *numElements,
1560 llvm::Value *arrayBegin,
1561 CallExpr::const_arg_iterator argBegin,
1562 CallExpr::const_arg_iterator argEnd,
1563 bool zeroInitialize) {
John McCalldd376ca2011-07-13 07:37:11 +00001564
1565 // It's legal for numElements to be zero. This can happen both
1566 // dynamically, because x can be zero in 'new A[x]', and statically,
1567 // because of GCC extensions that permit zero-length arrays. There
1568 // are probably legitimate places where we could assume that this
1569 // doesn't happen, but it's not clear that it's worth it.
1570 llvm::BranchInst *zeroCheckBranch = 0;
1571
1572 // Optimize for a constant count.
1573 llvm::ConstantInt *constantCount
1574 = dyn_cast<llvm::ConstantInt>(numElements);
1575 if (constantCount) {
1576 // Just skip out if the constant count is zero.
1577 if (constantCount->isZero()) return;
1578
1579 // Otherwise, emit the check.
1580 } else {
1581 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1582 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1583 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1584 EmitBlock(loopBB);
1585 }
1586
John McCallc3c07662011-07-13 06:10:41 +00001587 // Find the end of the array.
1588 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1589 "arrayctor.end");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001590
John McCallc3c07662011-07-13 06:10:41 +00001591 // Enter the loop, setting up a phi for the current location to initialize.
1592 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1593 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1594 EmitBlock(loopBB);
1595 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1596 "arrayctor.cur");
1597 cur->addIncoming(arrayBegin, entryBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001598
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001599 // Inside the loop body, emit the constructor call on the array element.
John McCallc3c07662011-07-13 06:10:41 +00001600
1601 QualType type = getContext().getTypeDeclType(ctor->getParent());
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001602
Douglas Gregor59174c02010-07-21 01:10:17 +00001603 // Zero initialize the storage, if requested.
John McCallc3c07662011-07-13 06:10:41 +00001604 if (zeroInitialize)
1605 EmitNullInitialization(cur, type);
Douglas Gregor59174c02010-07-21 01:10:17 +00001606
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001607 // C++ [class.temporary]p4:
1608 // There are two contexts in which temporaries are destroyed at a different
1609 // point than the end of the full-expression. The first context is when a
1610 // default constructor is called to initialize an element of an array.
1611 // If the constructor has one or more default arguments, the destruction of
1612 // every temporary created in a default argument expression is sequenced
1613 // before the construction of the next array element, if any.
1614
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001615 {
John McCallf1549f62010-07-06 01:34:17 +00001616 RunCleanupsScope Scope(*this);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001617
John McCallc3c07662011-07-13 06:10:41 +00001618 // Evaluate the constructor and its arguments in a regular
1619 // partial-destroy cleanup.
David Blaikie4e4d0842012-03-11 07:00:24 +00001620 if (getLangOpts().Exceptions &&
John McCallc3c07662011-07-13 06:10:41 +00001621 !ctor->getParent()->hasTrivialDestructor()) {
1622 Destroyer *destroyer = destroyCXXObject;
1623 pushRegularPartialArrayCleanup(arrayBegin, cur, type, *destroyer);
1624 }
1625
1626 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/ false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001627 /*Delegating=*/false, cur, argBegin, argEnd);
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001628 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001629
John McCallc3c07662011-07-13 06:10:41 +00001630 // Go to the next element.
1631 llvm::Value *next =
1632 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
1633 "arrayctor.next");
1634 cur->addIncoming(next, Builder.GetInsertBlock());
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001635
John McCallc3c07662011-07-13 06:10:41 +00001636 // Check whether that's the end of the loop.
1637 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
1638 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
1639 Builder.CreateCondBr(done, contBB, loopBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001640
John McCalldd376ca2011-07-13 07:37:11 +00001641 // Patch the earlier check to skip over the loop.
1642 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
1643
John McCallc3c07662011-07-13 06:10:41 +00001644 EmitBlock(contBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001645}
1646
John McCallbdc4d802011-07-09 01:37:26 +00001647void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
1648 llvm::Value *addr,
1649 QualType type) {
1650 const RecordType *rtype = type->castAs<RecordType>();
1651 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
1652 const CXXDestructorDecl *dtor = record->getDestructor();
1653 assert(!dtor->isTrivial());
1654 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001655 /*Delegating=*/false, addr);
John McCallbdc4d802011-07-09 01:37:26 +00001656}
1657
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001658void
1659CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
Anders Carlsson155ed4a2010-05-02 23:20:53 +00001660 CXXCtorType Type, bool ForVirtualBase,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001661 bool Delegating,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001662 llvm::Value *This,
1663 CallExpr::const_arg_iterator ArgBeg,
1664 CallExpr::const_arg_iterator ArgEnd) {
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001665 // If this is a trivial constructor, just emit what's needed.
John McCall8b6bbeb2010-02-06 00:25:16 +00001666 if (D->isTrivial()) {
1667 if (ArgBeg == ArgEnd) {
1668 // Trivial default constructor, no codegen required.
1669 assert(D->isDefaultConstructor() &&
1670 "trivial 0-arg ctor not a default ctor");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001671 return;
1672 }
John McCall8b6bbeb2010-02-06 00:25:16 +00001673
1674 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001675 assert(D->isCopyOrMoveConstructor() &&
1676 "trivial 1-arg ctor not a copy/move ctor");
John McCall8b6bbeb2010-02-06 00:25:16 +00001677
John McCall8b6bbeb2010-02-06 00:25:16 +00001678 const Expr *E = (*ArgBeg);
1679 QualType Ty = E->getType();
1680 llvm::Value *Src = EmitLValue(E).getAddress();
1681 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001682 return;
1683 }
1684
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001685 // Non-trivial constructors are handled in an ABI-specific manner.
Stephen Lin3b50e8d2013-06-30 20:40:16 +00001686 CGM.getCXXABI().EmitConstructorCall(*this, D, Type, ForVirtualBase,
1687 Delegating, This, ArgBeg, ArgEnd);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001688}
1689
John McCallc0bf4622010-02-23 00:48:20 +00001690void
Fariborz Jahanian34999872010-11-13 21:53:34 +00001691CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
1692 llvm::Value *This, llvm::Value *Src,
1693 CallExpr::const_arg_iterator ArgBeg,
1694 CallExpr::const_arg_iterator ArgEnd) {
1695 if (D->isTrivial()) {
1696 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001697 assert(D->isCopyOrMoveConstructor() &&
1698 "trivial 1-arg ctor not a copy/move ctor");
Fariborz Jahanian34999872010-11-13 21:53:34 +00001699 EmitAggregateCopy(This, Src, (*ArgBeg)->getType());
1700 return;
1701 }
Nick Lewycky62a3bba2013-09-11 02:03:20 +00001702 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, clang::Ctor_Complete);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001703 assert(D->isInstance() &&
1704 "Trying to emit a member call expr on a static method!");
1705
1706 const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
1707
1708 CallArgList Args;
1709
1710 // Push the this ptr.
Eli Friedman04c9a492011-05-02 17:57:46 +00001711 Args.add(RValue::get(This), D->getThisType(getContext()));
Fariborz Jahanian34999872010-11-13 21:53:34 +00001712
1713
1714 // Push the src ptr.
1715 QualType QT = *(FPT->arg_type_begin());
Chris Lattner2acc6e32011-07-18 04:24:23 +00001716 llvm::Type *t = CGM.getTypes().ConvertType(QT);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001717 Src = Builder.CreateBitCast(Src, t);
Eli Friedman04c9a492011-05-02 17:57:46 +00001718 Args.add(RValue::get(Src), QT);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001719
1720 // Skip over first argument (Src).
1721 ++ArgBeg;
1722 CallExpr::const_arg_iterator Arg = ArgBeg;
1723 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin()+1,
1724 E = FPT->arg_type_end(); I != E; ++I, ++Arg) {
1725 assert(Arg != ArgEnd && "Running over edge of argument list!");
John McCall413ebdb2011-03-11 20:59:21 +00001726 EmitCallArg(Args, *Arg, *I);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001727 }
1728 // Either we've emitted all the call args, or we have a call to a
1729 // variadic function.
1730 assert((Arg == ArgEnd || FPT->isVariadic()) &&
1731 "Extra arguments in non-variadic function!");
1732 // If we still have any arguments, emit them using the type of the argument.
1733 for (; Arg != ArgEnd; ++Arg) {
1734 QualType ArgType = Arg->getType();
John McCall413ebdb2011-03-11 20:59:21 +00001735 EmitCallArg(Args, *Arg, ArgType);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001736 }
1737
John McCall0f3d0972012-07-07 06:41:13 +00001738 EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, RequiredArgs::All),
1739 Callee, ReturnValueSlot(), Args, D);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001740}
1741
1742void
John McCallc0bf4622010-02-23 00:48:20 +00001743CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1744 CXXCtorType CtorType,
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001745 const FunctionArgList &Args,
1746 SourceLocation Loc) {
John McCallc0bf4622010-02-23 00:48:20 +00001747 CallArgList DelegateArgs;
1748
1749 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
1750 assert(I != E && "no parameters to constructor");
1751
1752 // this
Eli Friedman04c9a492011-05-02 17:57:46 +00001753 DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType());
John McCallc0bf4622010-02-23 00:48:20 +00001754 ++I;
1755
1756 // vtt
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001757 if (llvm::Value *VTT = GetVTTParameter(GlobalDecl(Ctor, CtorType),
Douglas Gregor378e1e72013-01-31 05:50:40 +00001758 /*ForVirtualBase=*/false,
1759 /*Delegating=*/true)) {
John McCallc0bf4622010-02-23 00:48:20 +00001760 QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
Eli Friedman04c9a492011-05-02 17:57:46 +00001761 DelegateArgs.add(RValue::get(VTT), VoidPP);
John McCallc0bf4622010-02-23 00:48:20 +00001762
Peter Collingbournee1e35f72013-06-28 20:45:28 +00001763 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
John McCallc0bf4622010-02-23 00:48:20 +00001764 assert(I != E && "cannot skip vtt parameter, already done with args");
John McCalld26bc762011-03-09 04:27:21 +00001765 assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
John McCallc0bf4622010-02-23 00:48:20 +00001766 ++I;
1767 }
1768 }
1769
1770 // Explicit arguments.
1771 for (; I != E; ++I) {
John McCall413ebdb2011-03-11 20:59:21 +00001772 const VarDecl *param = *I;
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001773 // FIXME: per-argument source location
1774 EmitDelegateCallArg(DelegateArgs, param, Loc);
John McCallc0bf4622010-02-23 00:48:20 +00001775 }
1776
Manman Ren63fd4082013-03-20 16:59:38 +00001777 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(Ctor, CtorType);
John McCallde5d3c72012-02-17 03:33:10 +00001778 EmitCall(CGM.getTypes().arrangeCXXConstructorDeclaration(Ctor, CtorType),
Manman Ren63fd4082013-03-20 16:59:38 +00001779 Callee, ReturnValueSlot(), DelegateArgs, Ctor);
John McCallc0bf4622010-02-23 00:48:20 +00001780}
1781
Sean Huntb76af9c2011-05-03 23:05:34 +00001782namespace {
1783 struct CallDelegatingCtorDtor : EHScopeStack::Cleanup {
1784 const CXXDestructorDecl *Dtor;
1785 llvm::Value *Addr;
1786 CXXDtorType Type;
1787
1788 CallDelegatingCtorDtor(const CXXDestructorDecl *D, llvm::Value *Addr,
1789 CXXDtorType Type)
1790 : Dtor(D), Addr(Addr), Type(Type) {}
1791
John McCallad346f42011-07-12 20:27:29 +00001792 void Emit(CodeGenFunction &CGF, Flags flags) {
Sean Huntb76af9c2011-05-03 23:05:34 +00001793 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001794 /*Delegating=*/true, Addr);
Sean Huntb76af9c2011-05-03 23:05:34 +00001795 }
1796 };
1797}
1798
Sean Hunt059ce0d2011-05-01 07:04:31 +00001799void
1800CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
1801 const FunctionArgList &Args) {
1802 assert(Ctor->isDelegatingConstructor());
1803
1804 llvm::Value *ThisPtr = LoadCXXThis();
1805
Eli Friedmanf3940782011-12-03 00:54:26 +00001806 QualType Ty = getContext().getTagDeclType(Ctor->getParent());
Eli Friedmand7722d92011-12-03 02:13:40 +00001807 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
John McCallf85e1932011-06-15 23:02:42 +00001808 AggValueSlot AggSlot =
Eli Friedmanf3940782011-12-03 00:54:26 +00001809 AggValueSlot::forAddr(ThisPtr, Alignment, Qualifiers(),
John McCall7c2349b2011-08-25 20:40:09 +00001810 AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +00001811 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +00001812 AggValueSlot::IsNotAliased);
Sean Hunt059ce0d2011-05-01 07:04:31 +00001813
1814 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
Sean Hunt059ce0d2011-05-01 07:04:31 +00001815
Sean Huntb76af9c2011-05-03 23:05:34 +00001816 const CXXRecordDecl *ClassDecl = Ctor->getParent();
David Blaikie4e4d0842012-03-11 07:00:24 +00001817 if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
Sean Huntb76af9c2011-05-03 23:05:34 +00001818 CXXDtorType Type =
1819 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
1820
1821 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
1822 ClassDecl->getDestructor(),
1823 ThisPtr, Type);
1824 }
1825}
Sean Hunt059ce0d2011-05-01 07:04:31 +00001826
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001827void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
1828 CXXDtorType Type,
Anders Carlsson8e6404c2010-05-02 23:29:11 +00001829 bool ForVirtualBase,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001830 bool Delegating,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001831 llvm::Value *This) {
Timur Iskhodzhanov82552742013-10-16 18:24:06 +00001832 GlobalDecl GD(DD, Type);
1833 llvm::Value *VTT = GetVTTParameter(GD, ForVirtualBase, Delegating);
Fariborz Jahanianccd52592011-02-01 23:22:34 +00001834 llvm::Value *Callee = 0;
Richard Smith7edf9e32012-11-01 22:30:59 +00001835 if (getLangOpts().AppleKext)
Fariborz Jahanian771c6782011-02-03 19:27:17 +00001836 Callee = BuildAppleKextVirtualDestructorCall(DD, Type,
1837 DD->getParent());
Fariborz Jahanianccd52592011-02-01 23:22:34 +00001838
1839 if (!Callee)
1840 Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
Timur Iskhodzhanov82552742013-10-16 18:24:06 +00001841
1842 if (DD->isVirtual())
1843 This = CGM.getCXXABI().adjustThisArgumentForVirtualCall(*this, GD, This);
1844
Richard Smith4def70d2012-10-09 19:52:38 +00001845 // FIXME: Provide a source location here.
1846 EmitCXXMemberCall(DD, SourceLocation(), Callee, ReturnValueSlot(), This,
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +00001847 VTT, getContext().getPointerType(getContext().VoidPtrTy),
1848 0, 0);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001849}
1850
John McCall291ae942010-07-21 01:41:18 +00001851namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001852 struct CallLocalDtor : EHScopeStack::Cleanup {
John McCall291ae942010-07-21 01:41:18 +00001853 const CXXDestructorDecl *Dtor;
1854 llvm::Value *Addr;
1855
1856 CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
1857 : Dtor(D), Addr(Addr) {}
1858
John McCallad346f42011-07-12 20:27:29 +00001859 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall291ae942010-07-21 01:41:18 +00001860 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001861 /*ForVirtualBase=*/false,
1862 /*Delegating=*/false, Addr);
John McCall291ae942010-07-21 01:41:18 +00001863 }
1864 };
1865}
1866
John McCall81407d42010-07-21 06:29:51 +00001867void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
1868 llvm::Value *Addr) {
John McCall1f0fca52010-07-21 07:22:38 +00001869 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
John McCall81407d42010-07-21 06:29:51 +00001870}
1871
John McCallf1549f62010-07-06 01:34:17 +00001872void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
1873 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
1874 if (!ClassDecl) return;
1875 if (ClassDecl->hasTrivialDestructor()) return;
1876
1877 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCall642a75f2011-04-28 02:15:35 +00001878 assert(D && D->isUsed() && "destructor not marked as used!");
John McCall81407d42010-07-21 06:29:51 +00001879 PushDestructorCleanup(D, Addr);
John McCallf1549f62010-07-06 01:34:17 +00001880}
1881
Anders Carlssond103f9f2010-03-28 19:40:00 +00001882void
1883CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001884 const CXXRecordDecl *NearestVBase,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001885 CharUnits OffsetFromNearestVBase,
Anders Carlssond103f9f2010-03-28 19:40:00 +00001886 const CXXRecordDecl *VTableClass) {
Anders Carlssond103f9f2010-03-28 19:40:00 +00001887 // Compute the address point.
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +00001888 bool NeedsVirtualOffset;
1889 llvm::Value *VTableAddressPoint =
1890 CGM.getCXXABI().getVTableAddressPointInStructor(
1891 *this, VTableClass, Base, NearestVBase, NeedsVirtualOffset);
1892 if (!VTableAddressPoint)
1893 return;
Anders Carlssond103f9f2010-03-28 19:40:00 +00001894
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001895 // Compute where to store the address point.
Anders Carlsson8246cc72010-05-03 00:29:58 +00001896 llvm::Value *VirtualOffset = 0;
Ken Dyck9a8ad9b2011-03-23 00:45:26 +00001897 CharUnits NonVirtualOffset = CharUnits::Zero();
Anders Carlsson3e79c302010-04-20 18:05:10 +00001898
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +00001899 if (NeedsVirtualOffset) {
Anders Carlsson3e79c302010-04-20 18:05:10 +00001900 // We need to use the virtual base offset offset because the virtual base
1901 // might have a different offset in the most derived class.
Reid Klecknerb0f533e2013-05-29 18:02:47 +00001902 VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(*this,
1903 LoadCXXThis(),
1904 VTableClass,
1905 NearestVBase);
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001906 NonVirtualOffset = OffsetFromNearestVBase;
Anders Carlsson3e79c302010-04-20 18:05:10 +00001907 } else {
Anders Carlsson8246cc72010-05-03 00:29:58 +00001908 // We can just use the base offset in the complete class.
Ken Dyck4230d522011-03-24 01:21:01 +00001909 NonVirtualOffset = Base.getBaseOffset();
Anders Carlsson3e79c302010-04-20 18:05:10 +00001910 }
Anders Carlsson8246cc72010-05-03 00:29:58 +00001911
1912 // Apply the offsets.
1913 llvm::Value *VTableField = LoadCXXThis();
1914
Ken Dyck9a8ad9b2011-03-23 00:45:26 +00001915 if (!NonVirtualOffset.isZero() || VirtualOffset)
Anders Carlsson8246cc72010-05-03 00:29:58 +00001916 VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
1917 NonVirtualOffset,
1918 VirtualOffset);
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001919
Anders Carlssond103f9f2010-03-28 19:40:00 +00001920 // Finally, store the address point.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001921 llvm::Type *AddressPointPtrTy =
Anders Carlssond103f9f2010-03-28 19:40:00 +00001922 VTableAddressPoint->getType()->getPointerTo();
1923 VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
Kostya Serebryany8cb4a072012-03-26 17:03:51 +00001924 llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
1925 CGM.DecorateInstruction(Store, CGM.getTBAAInfoForVTablePtr());
Anders Carlssond103f9f2010-03-28 19:40:00 +00001926}
1927
Anders Carlsson603d6d12010-03-28 21:07:49 +00001928void
1929CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001930 const CXXRecordDecl *NearestVBase,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001931 CharUnits OffsetFromNearestVBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001932 bool BaseIsNonVirtualPrimaryBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001933 const CXXRecordDecl *VTableClass,
1934 VisitedVirtualBasesSetTy& VBases) {
1935 // If this base is a non-virtual primary base the address point has already
1936 // been set.
1937 if (!BaseIsNonVirtualPrimaryBase) {
1938 // Initialize the vtable pointer for this base.
Anders Carlsson42358402010-05-03 00:07:07 +00001939 InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
Timur Iskhodzhanov7f918f92013-08-21 17:33:16 +00001940 VTableClass);
Anders Carlsson603d6d12010-03-28 21:07:49 +00001941 }
1942
1943 const CXXRecordDecl *RD = Base.getBase();
1944
1945 // Traverse bases.
1946 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1947 E = RD->bases_end(); I != E; ++I) {
1948 CXXRecordDecl *BaseDecl
1949 = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1950
1951 // Ignore classes without a vtable.
1952 if (!BaseDecl->isDynamicClass())
1953 continue;
1954
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001955 CharUnits BaseOffset;
1956 CharUnits BaseOffsetFromNearestVBase;
Anders Carlsson14da9de2010-03-29 01:16:41 +00001957 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001958
1959 if (I->isVirtual()) {
1960 // Check if we've visited this virtual base before.
1961 if (!VBases.insert(BaseDecl))
1962 continue;
1963
1964 const ASTRecordLayout &Layout =
1965 getContext().getASTRecordLayout(VTableClass);
1966
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001967 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
1968 BaseOffsetFromNearestVBase = CharUnits::Zero();
Anders Carlsson14da9de2010-03-29 01:16:41 +00001969 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001970 } else {
1971 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1972
Ken Dyck4230d522011-03-24 01:21:01 +00001973 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson42358402010-05-03 00:07:07 +00001974 BaseOffsetFromNearestVBase =
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001975 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson14da9de2010-03-29 01:16:41 +00001976 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001977 }
1978
Ken Dyck4230d522011-03-24 01:21:01 +00001979 InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001980 I->isVirtual() ? BaseDecl : NearestVBase,
Anders Carlsson42358402010-05-03 00:07:07 +00001981 BaseOffsetFromNearestVBase,
Anders Carlsson14da9de2010-03-29 01:16:41 +00001982 BaseDeclIsNonVirtualPrimaryBase,
Timur Iskhodzhanov7f918f92013-08-21 17:33:16 +00001983 VTableClass, VBases);
Anders Carlsson603d6d12010-03-28 21:07:49 +00001984 }
1985}
1986
1987void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
1988 // Ignore classes without a vtable.
Anders Carlsson07036902010-03-26 04:39:42 +00001989 if (!RD->isDynamicClass())
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001990 return;
1991
Anders Carlsson603d6d12010-03-28 21:07:49 +00001992 // Initialize the vtable pointers for this class and all of its bases.
1993 VisitedVirtualBasesSetTy VBases;
Ken Dyck4230d522011-03-24 01:21:01 +00001994 InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()),
1995 /*NearestVBase=*/0,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001996 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
Timur Iskhodzhanov7f918f92013-08-21 17:33:16 +00001997 /*BaseIsNonVirtualPrimaryBase=*/false, RD, VBases);
Timur Iskhodzhanov5bd0d442013-10-09 18:16:58 +00001998
1999 if (RD->getNumVBases())
2000 CGM.getCXXABI().initializeHiddenVirtualInheritanceMembers(*this, RD);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00002001}
Dan Gohman043fb9a2010-10-26 18:44:08 +00002002
2003llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
Chris Lattner2acc6e32011-07-18 04:24:23 +00002004 llvm::Type *Ty) {
Dan Gohman043fb9a2010-10-26 18:44:08 +00002005 llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
Kostya Serebryany8cb4a072012-03-26 17:03:51 +00002006 llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
2007 CGM.DecorateInstruction(VTable, CGM.getTBAAInfoForVTablePtr());
2008 return VTable;
Dan Gohman043fb9a2010-10-26 18:44:08 +00002009}
Anders Carlssona2447e02011-05-08 20:32:23 +00002010
Anders Carlssona2447e02011-05-08 20:32:23 +00002011
2012// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
2013// quite what we want.
2014static const Expr *skipNoOpCastsAndParens(const Expr *E) {
2015 while (true) {
2016 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
2017 E = PE->getSubExpr();
2018 continue;
2019 }
2020
2021 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
2022 if (CE->getCastKind() == CK_NoOp) {
2023 E = CE->getSubExpr();
2024 continue;
2025 }
2026 }
2027 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2028 if (UO->getOpcode() == UO_Extension) {
2029 E = UO->getSubExpr();
2030 continue;
2031 }
2032 }
2033 return E;
2034 }
2035}
2036
Benjamin Kramer9581ed02013-08-25 22:46:27 +00002037bool
2038CodeGenFunction::CanDevirtualizeMemberFunctionCall(const Expr *Base,
2039 const CXXMethodDecl *MD) {
2040 // When building with -fapple-kext, all calls must go through the vtable since
2041 // the kernel linker can do runtime patching of vtables.
2042 if (getLangOpts().AppleKext)
2043 return false;
2044
Anders Carlssona2447e02011-05-08 20:32:23 +00002045 // If the most derived class is marked final, we know that no subclass can
2046 // override this member function and so we can devirtualize it. For example:
2047 //
2048 // struct A { virtual void f(); }
2049 // struct B final : A { };
2050 //
2051 // void f(B *b) {
2052 // b->f();
2053 // }
2054 //
Benjamin Kramer9581ed02013-08-25 22:46:27 +00002055 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
Anders Carlssona2447e02011-05-08 20:32:23 +00002056 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
2057 return true;
2058
2059 // If the member function is marked 'final', we know that it can't be
2060 // overridden and can therefore devirtualize it.
2061 if (MD->hasAttr<FinalAttr>())
2062 return true;
2063
2064 // Similarly, if the class itself is marked 'final' it can't be overridden
2065 // and we can therefore devirtualize the member function call.
2066 if (MD->getParent()->hasAttr<FinalAttr>())
2067 return true;
2068
2069 Base = skipNoOpCastsAndParens(Base);
2070 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
2071 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
2072 // This is a record decl. We know the type and can devirtualize it.
2073 return VD->getType()->isRecordType();
2074 }
2075
2076 return false;
2077 }
Benjamin Kramer9581ed02013-08-25 22:46:27 +00002078
2079 // We can devirtualize calls on an object accessed by a class member access
2080 // expression, since by C++11 [basic.life]p6 we know that it can't refer to
2081 // a derived class object constructed in the same location.
2082 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Base))
2083 if (const ValueDecl *VD = dyn_cast<ValueDecl>(ME->getMemberDecl()))
2084 return VD->getType()->isRecordType();
2085
Anders Carlssona2447e02011-05-08 20:32:23 +00002086 // We can always devirtualize calls on temporary object expressions.
2087 if (isa<CXXConstructExpr>(Base))
2088 return true;
2089
2090 // And calls on bound temporaries.
2091 if (isa<CXXBindTemporaryExpr>(Base))
2092 return true;
2093
2094 // Check if this is a call expr that returns a record type.
2095 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
2096 return CE->getCallReturnType()->isRecordType();
2097
2098 // We can't devirtualize the call.
2099 return false;
2100}
2101
Anders Carlssona2447e02011-05-08 20:32:23 +00002102llvm::Value *
2103CodeGenFunction::EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E,
2104 const CXXMethodDecl *MD,
2105 llvm::Value *This) {
John McCallde5d3c72012-02-17 03:33:10 +00002106 llvm::FunctionType *fnType =
2107 CGM.getTypes().GetFunctionType(
2108 CGM.getTypes().arrangeCXXMethodDeclaration(MD));
Anders Carlssona2447e02011-05-08 20:32:23 +00002109
Benjamin Kramer9581ed02013-08-25 22:46:27 +00002110 if (MD->isVirtual() && !CanDevirtualizeMemberFunctionCall(E->getArg(0), MD))
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +00002111 return CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, fnType);
Anders Carlssona2447e02011-05-08 20:32:23 +00002112
John McCallde5d3c72012-02-17 03:33:10 +00002113 return CGM.GetAddrOfFunction(MD, fnType);
Anders Carlssona2447e02011-05-08 20:32:23 +00002114}
Eli Friedmanbd89f8c2012-02-16 01:37:33 +00002115
Faisal Valid6992ab2013-09-29 08:45:24 +00002116void CodeGenFunction::EmitForwardingCallToLambda(
2117 const CXXMethodDecl *callOperator,
2118 CallArgList &callArgs) {
Eli Friedman21f6ed92012-02-16 03:47:28 +00002119 // Get the address of the call operator.
John McCall0f3d0972012-07-07 06:41:13 +00002120 const CGFunctionInfo &calleeFnInfo =
2121 CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
2122 llvm::Value *callee =
2123 CGM.GetAddrOfFunction(GlobalDecl(callOperator),
2124 CGM.getTypes().GetFunctionType(calleeFnInfo));
Eli Friedman21f6ed92012-02-16 03:47:28 +00002125
John McCall0f3d0972012-07-07 06:41:13 +00002126 // Prepare the return slot.
2127 const FunctionProtoType *FPT =
2128 callOperator->getType()->castAs<FunctionProtoType>();
2129 QualType resultType = FPT->getResultType();
2130 ReturnValueSlot returnSlot;
2131 if (!resultType->isVoidType() &&
2132 calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
John McCall9d232c82013-03-07 21:37:08 +00002133 !hasScalarEvaluationKind(calleeFnInfo.getReturnType()))
John McCall0f3d0972012-07-07 06:41:13 +00002134 returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
2135
2136 // We don't need to separately arrange the call arguments because
2137 // the call can't be variadic anyway --- it's impossible to forward
2138 // variadic arguments.
Eli Friedman21f6ed92012-02-16 03:47:28 +00002139
2140 // Now emit our call.
John McCall0f3d0972012-07-07 06:41:13 +00002141 RValue RV = EmitCall(calleeFnInfo, callee, returnSlot,
2142 callArgs, callOperator);
Eli Friedman21f6ed92012-02-16 03:47:28 +00002143
John McCall0f3d0972012-07-07 06:41:13 +00002144 // If necessary, copy the returned value into the slot.
2145 if (!resultType->isVoidType() && returnSlot.isNull())
2146 EmitReturnOfRValue(RV, resultType);
Eli Friedman50f089a2012-12-13 23:37:17 +00002147 else
2148 EmitBranchThroughCleanup(ReturnBlock);
Eli Friedman21f6ed92012-02-16 03:47:28 +00002149}
2150
Eli Friedman64bee652012-02-25 02:48:22 +00002151void CodeGenFunction::EmitLambdaBlockInvokeBody() {
2152 const BlockDecl *BD = BlockInfo->getBlockDecl();
2153 const VarDecl *variable = BD->capture_begin()->getVariable();
2154 const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
2155
2156 // Start building arguments for forwarding call
2157 CallArgList CallArgs;
2158
2159 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2160 llvm::Value *ThisPtr = GetAddrOfBlockDecl(variable, false);
2161 CallArgs.add(RValue::get(ThisPtr), ThisType);
2162
2163 // Add the rest of the parameters.
2164 for (BlockDecl::param_const_iterator I = BD->param_begin(),
2165 E = BD->param_end(); I != E; ++I) {
2166 ParmVarDecl *param = *I;
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00002167 EmitDelegateCallArg(CallArgs, param, param->getLocStart());
Eli Friedman64bee652012-02-25 02:48:22 +00002168 }
Faisal Valid6992ab2013-09-29 08:45:24 +00002169 assert(!Lambda->isGenericLambda() &&
2170 "generic lambda interconversion to block not implemented");
2171 EmitForwardingCallToLambda(Lambda->getLambdaCallOperator(), CallArgs);
Eli Friedman64bee652012-02-25 02:48:22 +00002172}
2173
2174void CodeGenFunction::EmitLambdaToBlockPointerBody(FunctionArgList &Args) {
John McCallf5ebf9b2013-05-03 07:33:41 +00002175 if (cast<CXXMethodDecl>(CurCodeDecl)->isVariadic()) {
Eli Friedman64bee652012-02-25 02:48:22 +00002176 // FIXME: Making this work correctly is nasty because it requires either
2177 // cloning the body of the call operator or making the call operator forward.
John McCallf5ebf9b2013-05-03 07:33:41 +00002178 CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function");
Eli Friedman64bee652012-02-25 02:48:22 +00002179 return;
2180 }
2181
Eli Friedman64bee652012-02-25 02:48:22 +00002182 EmitFunctionBody(Args);
Eli Friedman64bee652012-02-25 02:48:22 +00002183}
2184
2185void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
2186 const CXXRecordDecl *Lambda = MD->getParent();
2187
2188 // Start building arguments for forwarding call
2189 CallArgList CallArgs;
2190
2191 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2192 llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
2193 CallArgs.add(RValue::get(ThisPtr), ThisType);
2194
2195 // Add the rest of the parameters.
2196 for (FunctionDecl::param_const_iterator I = MD->param_begin(),
2197 E = MD->param_end(); I != E; ++I) {
2198 ParmVarDecl *param = *I;
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00002199 EmitDelegateCallArg(CallArgs, param, param->getLocStart());
Eli Friedman64bee652012-02-25 02:48:22 +00002200 }
Faisal Valid6992ab2013-09-29 08:45:24 +00002201 const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
2202 // For a generic lambda, find the corresponding call operator specialization
2203 // to which the call to the static-invoker shall be forwarded.
2204 if (Lambda->isGenericLambda()) {
2205 assert(MD->isFunctionTemplateSpecialization());
2206 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
2207 FunctionTemplateDecl *CallOpTemplate = CallOp->getDescribedFunctionTemplate();
2208 void *InsertPos = 0;
2209 FunctionDecl *CorrespondingCallOpSpecialization =
2210 CallOpTemplate->findSpecialization(TAL->data(), TAL->size(), InsertPos);
2211 assert(CorrespondingCallOpSpecialization);
2212 CallOp = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
2213 }
2214 EmitForwardingCallToLambda(CallOp, CallArgs);
Eli Friedman64bee652012-02-25 02:48:22 +00002215}
2216
Douglas Gregor27dd7d92012-02-17 03:02:34 +00002217void CodeGenFunction::EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD) {
2218 if (MD->isVariadic()) {
Eli Friedman21f6ed92012-02-16 03:47:28 +00002219 // FIXME: Making this work correctly is nasty because it requires either
2220 // cloning the body of the call operator or making the call operator forward.
2221 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
Eli Friedman64bee652012-02-25 02:48:22 +00002222 return;
Eli Friedman21f6ed92012-02-16 03:47:28 +00002223 }
2224
Douglas Gregor27dd7d92012-02-17 03:02:34 +00002225 EmitLambdaDelegatingInvokeBody(MD);
Eli Friedmanbd89f8c2012-02-16 01:37:33 +00002226}