blob: 273fed52d5c0ea72d44444e719a407a567612ec8 [file] [log] [blame]
Anders Carlsson59486a22009-11-24 05:51:11 +00001//===--- CGClass.cpp - Emit LLVM Code for C++ classes ---------------------===//
Anders Carlsson9a57c5a2009-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 Friedman2495ab02012-02-25 02:48:22 +000014#include "CGBlocks.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000015#include "CGCXXABI.h"
Devang Pateld76c1db2010-08-11 21:04:37 +000016#include "CGDebugInfo.h"
Lang Hamesbf122742013-02-17 07:22:09 +000017#include "CGRecordLayout.h"
Anders Carlsson9a57c5a2009-09-12 04:27:24 +000018#include "CodeGenFunction.h"
Anders Carlssonc6d171e2009-10-06 22:43:30 +000019#include "clang/AST/CXXInheritance.h"
Faisal Vali571df122013-09-29 08:45:24 +000020#include "clang/AST/DeclTemplate.h"
John McCall769250e2010-09-17 02:31:44 +000021#include "clang/AST/EvaluatedExprVisitor.h"
Anders Carlsson9a57c5a2009-09-12 04:27:24 +000022#include "clang/AST/RecordLayout.h"
John McCallb81884d2010-02-19 09:25:03 +000023#include "clang/AST/StmtCXX.h"
Lang Hamesbf122742013-02-17 07:22:09 +000024#include "clang/Basic/TargetBuiltins.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000025#include "clang/CodeGen/CGFunctionInfo.h"
Devang Patelb6ed3692011-02-22 20:55:26 +000026#include "clang/Frontend/CodeGenOptions.h"
Anders Carlssonc6d171e2009-10-06 22:43:30 +000027
Anders Carlsson9a57c5a2009-09-12 04:27:24 +000028using namespace clang;
29using namespace CodeGen;
30
Ken Dycka1a4ae32011-03-22 00:53:26 +000031static CharUnits
Anders Carlssond829a022010-04-24 21:06:20 +000032ComputeNonVirtualBaseClassOffset(ASTContext &Context,
33 const CXXRecordDecl *DerivedClass,
John McCallcf142162010-08-07 06:22:56 +000034 CastExpr::path_const_iterator Start,
35 CastExpr::path_const_iterator End) {
Ken Dycka1a4ae32011-03-22 00:53:26 +000036 CharUnits Offset = CharUnits::Zero();
Anders Carlssond829a022010-04-24 21:06:20 +000037
38 const CXXRecordDecl *RD = DerivedClass;
39
John McCallcf142162010-08-07 06:22:56 +000040 for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
Anders Carlssond829a022010-04-24 21:06:20 +000041 const CXXBaseSpecifier *Base = *I;
42 assert(!Base->isVirtual() && "Should not see virtual bases here!");
43
44 // Get the layout.
45 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
46
47 const CXXRecordDecl *BaseDecl =
48 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
49
50 // Add the offset.
Ken Dycka1a4ae32011-03-22 00:53:26 +000051 Offset += Layout.getBaseClassOffset(BaseDecl);
Anders Carlssond829a022010-04-24 21:06:20 +000052
53 RD = BaseDecl;
54 }
55
Ken Dycka1a4ae32011-03-22 00:53:26 +000056 return Offset;
Anders Carlssond829a022010-04-24 21:06:20 +000057}
Anders Carlsson9a57c5a2009-09-12 04:27:24 +000058
Anders Carlsson9150a2a2009-09-29 03:13:20 +000059llvm::Constant *
Anders Carlsson8a64c1c2010-04-24 21:23:59 +000060CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
John McCallcf142162010-08-07 06:22:56 +000061 CastExpr::path_const_iterator PathBegin,
62 CastExpr::path_const_iterator PathEnd) {
63 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlsson8a64c1c2010-04-24 21:23:59 +000064
Ken Dycka1a4ae32011-03-22 00:53:26 +000065 CharUnits Offset =
John McCallcf142162010-08-07 06:22:56 +000066 ComputeNonVirtualBaseClassOffset(getContext(), ClassDecl,
67 PathBegin, PathEnd);
Ken Dycka1a4ae32011-03-22 00:53:26 +000068 if (Offset.isZero())
Anders Carlsson8a64c1c2010-04-24 21:23:59 +000069 return 0;
70
Chris Lattner2192fe52011-07-18 04:24:23 +000071 llvm::Type *PtrDiffTy =
Anders Carlsson8a64c1c2010-04-24 21:23:59 +000072 Types.ConvertType(getContext().getPointerDiffType());
73
Ken Dycka1a4ae32011-03-22 00:53:26 +000074 return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
Anders Carlsson9150a2a2009-09-29 03:13:20 +000075}
76
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +000077/// Gets the address of a direct base class within a complete object.
John McCall6ce74722010-02-16 04:15:37 +000078/// This should only be used for (1) non-virtual bases or (2) virtual bases
79/// when the type is known to be complete (e.g. in complete destructors).
80///
81/// The object pointed to by 'This' is assumed to be non-null.
82llvm::Value *
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +000083CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(llvm::Value *This,
84 const CXXRecordDecl *Derived,
85 const CXXRecordDecl *Base,
86 bool BaseIsVirtual) {
John McCall6ce74722010-02-16 04:15:37 +000087 // 'this' must be a pointer (in some address space) to Derived.
88 assert(This->getType()->isPointerTy() &&
89 cast<llvm::PointerType>(This->getType())->getElementType()
90 == ConvertType(Derived));
91
92 // Compute the offset of the virtual base.
Ken Dyck6aa767c2011-03-22 01:21:15 +000093 CharUnits Offset;
John McCall6ce74722010-02-16 04:15:37 +000094 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +000095 if (BaseIsVirtual)
Ken Dyck6aa767c2011-03-22 01:21:15 +000096 Offset = Layout.getVBaseClassOffset(Base);
John McCall6ce74722010-02-16 04:15:37 +000097 else
Ken Dyck6aa767c2011-03-22 01:21:15 +000098 Offset = Layout.getBaseClassOffset(Base);
John McCall6ce74722010-02-16 04:15:37 +000099
100 // Shift and cast down to the base type.
101 // TODO: for complete types, this should be possible with a GEP.
102 llvm::Value *V = This;
Ken Dyck6aa767c2011-03-22 01:21:15 +0000103 if (Offset.isPositive()) {
John McCall6ce74722010-02-16 04:15:37 +0000104 V = Builder.CreateBitCast(V, Int8PtrTy);
Ken Dyck6aa767c2011-03-22 01:21:15 +0000105 V = Builder.CreateConstInBoundsGEP1_64(V, Offset.getQuantity());
John McCall6ce74722010-02-16 04:15:37 +0000106 }
107 V = Builder.CreateBitCast(V, ConvertType(Base)->getPointerTo());
108
109 return V;
Anders Carlssone87fae92010-03-28 19:40:00 +0000110}
John McCall6ce74722010-02-16 04:15:37 +0000111
Anders Carlsson53cebd12010-04-20 16:03:35 +0000112static llvm::Value *
John McCall13a39c62012-08-01 05:04:58 +0000113ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, llvm::Value *ptr,
114 CharUnits nonVirtualOffset,
115 llvm::Value *virtualOffset) {
116 // Assert that we have something to do.
117 assert(!nonVirtualOffset.isZero() || virtualOffset != 0);
118
119 // Compute the offset from the static and dynamic components.
120 llvm::Value *baseOffset;
121 if (!nonVirtualOffset.isZero()) {
122 baseOffset = llvm::ConstantInt::get(CGF.PtrDiffTy,
123 nonVirtualOffset.getQuantity());
124 if (virtualOffset) {
125 baseOffset = CGF.Builder.CreateAdd(virtualOffset, baseOffset);
126 }
127 } else {
128 baseOffset = virtualOffset;
129 }
Anders Carlsson53cebd12010-04-20 16:03:35 +0000130
131 // Apply the base offset.
John McCall13a39c62012-08-01 05:04:58 +0000132 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
133 ptr = CGF.Builder.CreateInBoundsGEP(ptr, baseOffset, "add.ptr");
134 return ptr;
Anders Carlsson53cebd12010-04-20 16:03:35 +0000135}
136
Anders Carlsson9a57c5a2009-09-12 04:27:24 +0000137llvm::Value *
Anders Carlssond829a022010-04-24 21:06:20 +0000138CodeGenFunction::GetAddressOfBaseClass(llvm::Value *Value,
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000139 const CXXRecordDecl *Derived,
John McCallcf142162010-08-07 06:22:56 +0000140 CastExpr::path_const_iterator PathBegin,
141 CastExpr::path_const_iterator PathEnd,
Anders Carlssond829a022010-04-24 21:06:20 +0000142 bool NullCheckValue) {
John McCallcf142162010-08-07 06:22:56 +0000143 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssond829a022010-04-24 21:06:20 +0000144
John McCallcf142162010-08-07 06:22:56 +0000145 CastExpr::path_const_iterator Start = PathBegin;
Anders Carlssond829a022010-04-24 21:06:20 +0000146 const CXXRecordDecl *VBase = 0;
147
John McCall13a39c62012-08-01 05:04:58 +0000148 // Sema has done some convenient canonicalization here: if the
149 // access path involved any virtual steps, the conversion path will
150 // *start* with a step down to the correct virtual base subobject,
151 // and hence will not require any further steps.
Anders Carlssond829a022010-04-24 21:06:20 +0000152 if ((*Start)->isVirtual()) {
153 VBase =
154 cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
155 ++Start;
156 }
John McCall13a39c62012-08-01 05:04:58 +0000157
158 // Compute the static offset of the ultimate destination within its
159 // allocating subobject (the virtual base, if there is one, or else
160 // the "complete" object that we see).
Ken Dycka1a4ae32011-03-22 00:53:26 +0000161 CharUnits NonVirtualOffset =
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000162 ComputeNonVirtualBaseClassOffset(getContext(), VBase ? VBase : Derived,
John McCallcf142162010-08-07 06:22:56 +0000163 Start, PathEnd);
Anders Carlssond829a022010-04-24 21:06:20 +0000164
John McCall13a39c62012-08-01 05:04:58 +0000165 // If there's a virtual step, we can sometimes "devirtualize" it.
166 // For now, that's limited to when the derived type is final.
167 // TODO: "devirtualize" this for accesses to known-complete objects.
168 if (VBase && Derived->hasAttr<FinalAttr>()) {
169 const ASTRecordLayout &layout = getContext().getASTRecordLayout(Derived);
170 CharUnits vBaseOffset = layout.getVBaseClassOffset(VBase);
171 NonVirtualOffset += vBaseOffset;
172 VBase = 0; // we no longer have a virtual step
173 }
174
Anders Carlssond829a022010-04-24 21:06:20 +0000175 // Get the base pointer type.
Chris Lattner2192fe52011-07-18 04:24:23 +0000176 llvm::Type *BasePtrTy =
John McCallcf142162010-08-07 06:22:56 +0000177 ConvertType((PathEnd[-1])->getType())->getPointerTo();
John McCall13a39c62012-08-01 05:04:58 +0000178
179 // If the static offset is zero and we don't have a virtual step,
180 // just do a bitcast; null checks are unnecessary.
Ken Dycka1a4ae32011-03-22 00:53:26 +0000181 if (NonVirtualOffset.isZero() && !VBase) {
Anders Carlssond829a022010-04-24 21:06:20 +0000182 return Builder.CreateBitCast(Value, BasePtrTy);
183 }
John McCall13a39c62012-08-01 05:04:58 +0000184
185 llvm::BasicBlock *origBB = 0;
186 llvm::BasicBlock *endBB = 0;
Anders Carlssond829a022010-04-24 21:06:20 +0000187
John McCall13a39c62012-08-01 05:04:58 +0000188 // Skip over the offset (and the vtable load) if we're supposed to
189 // null-check the pointer.
Anders Carlssond829a022010-04-24 21:06:20 +0000190 if (NullCheckValue) {
John McCall13a39c62012-08-01 05:04:58 +0000191 origBB = Builder.GetInsertBlock();
192 llvm::BasicBlock *notNullBB = createBasicBlock("cast.notnull");
193 endBB = createBasicBlock("cast.end");
Anders Carlssond829a022010-04-24 21:06:20 +0000194
John McCall13a39c62012-08-01 05:04:58 +0000195 llvm::Value *isNull = Builder.CreateIsNull(Value);
196 Builder.CreateCondBr(isNull, endBB, notNullBB);
197 EmitBlock(notNullBB);
Anders Carlssond829a022010-04-24 21:06:20 +0000198 }
199
John McCall13a39c62012-08-01 05:04:58 +0000200 // Compute the virtual offset.
Anders Carlssond829a022010-04-24 21:06:20 +0000201 llvm::Value *VirtualOffset = 0;
Anders Carlssona376b532011-01-29 03:18:56 +0000202 if (VBase) {
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000203 VirtualOffset =
204 CGM.getCXXABI().GetVirtualBaseClassOffset(*this, Value, Derived, VBase);
Anders Carlssona376b532011-01-29 03:18:56 +0000205 }
Anders Carlssond829a022010-04-24 21:06:20 +0000206
John McCall13a39c62012-08-01 05:04:58 +0000207 // Apply both offsets.
Ken Dycka1a4ae32011-03-22 00:53:26 +0000208 Value = ApplyNonVirtualAndVirtualOffset(*this, Value,
Ken Dyckcfc332c2011-03-23 00:45:26 +0000209 NonVirtualOffset,
Anders Carlssond829a022010-04-24 21:06:20 +0000210 VirtualOffset);
211
John McCall13a39c62012-08-01 05:04:58 +0000212 // Cast to the destination type.
Anders Carlssond829a022010-04-24 21:06:20 +0000213 Value = Builder.CreateBitCast(Value, BasePtrTy);
John McCall13a39c62012-08-01 05:04:58 +0000214
215 // Build a phi if we needed a null check.
Anders Carlssond829a022010-04-24 21:06:20 +0000216 if (NullCheckValue) {
John McCall13a39c62012-08-01 05:04:58 +0000217 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
218 Builder.CreateBr(endBB);
219 EmitBlock(endBB);
Anders Carlssond829a022010-04-24 21:06:20 +0000220
John McCall13a39c62012-08-01 05:04:58 +0000221 llvm::PHINode *PHI = Builder.CreatePHI(BasePtrTy, 2, "cast.result");
222 PHI->addIncoming(Value, notNullBB);
223 PHI->addIncoming(llvm::Constant::getNullValue(BasePtrTy), origBB);
Anders Carlssond829a022010-04-24 21:06:20 +0000224 Value = PHI;
225 }
226
227 return Value;
228}
229
230llvm::Value *
Anders Carlsson8c793172009-11-23 17:57:54 +0000231CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value,
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000232 const CXXRecordDecl *Derived,
John McCallcf142162010-08-07 06:22:56 +0000233 CastExpr::path_const_iterator PathBegin,
234 CastExpr::path_const_iterator PathEnd,
Anders Carlsson8c793172009-11-23 17:57:54 +0000235 bool NullCheckValue) {
John McCallcf142162010-08-07 06:22:56 +0000236 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlsson8a64c1c2010-04-24 21:23:59 +0000237
Anders Carlsson8c793172009-11-23 17:57:54 +0000238 QualType DerivedTy =
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000239 getContext().getCanonicalType(getContext().getTagDeclType(Derived));
Chris Lattner2192fe52011-07-18 04:24:23 +0000240 llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
Richard Smith2c5868c2013-02-13 21:18:23 +0000241
Anders Carlsson600f7372010-01-31 01:43:37 +0000242 llvm::Value *NonVirtualOffset =
John McCallcf142162010-08-07 06:22:56 +0000243 CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
Anders Carlsson600f7372010-01-31 01:43:37 +0000244
245 if (!NonVirtualOffset) {
246 // No offset, we can just cast back.
247 return Builder.CreateBitCast(Value, DerivedPtrTy);
248 }
249
Anders Carlsson8c793172009-11-23 17:57:54 +0000250 llvm::BasicBlock *CastNull = 0;
251 llvm::BasicBlock *CastNotNull = 0;
252 llvm::BasicBlock *CastEnd = 0;
253
254 if (NullCheckValue) {
255 CastNull = createBasicBlock("cast.null");
256 CastNotNull = createBasicBlock("cast.notnull");
257 CastEnd = createBasicBlock("cast.end");
258
Anders Carlsson98981b12011-04-11 00:30:07 +0000259 llvm::Value *IsNull = Builder.CreateIsNull(Value);
Anders Carlsson8c793172009-11-23 17:57:54 +0000260 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
261 EmitBlock(CastNotNull);
262 }
263
Anders Carlsson600f7372010-01-31 01:43:37 +0000264 // Apply the offset.
Eli Friedman87549262012-02-28 22:07:56 +0000265 Value = Builder.CreateBitCast(Value, Int8PtrTy);
266 Value = Builder.CreateGEP(Value, Builder.CreateNeg(NonVirtualOffset),
267 "sub.ptr");
Anders Carlsson600f7372010-01-31 01:43:37 +0000268
269 // Just cast.
270 Value = Builder.CreateBitCast(Value, DerivedPtrTy);
Anders Carlsson8c793172009-11-23 17:57:54 +0000271
272 if (NullCheckValue) {
273 Builder.CreateBr(CastEnd);
274 EmitBlock(CastNull);
275 Builder.CreateBr(CastEnd);
276 EmitBlock(CastEnd);
277
Jay Foad20c0f022011-03-30 11:28:58 +0000278 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
Anders Carlsson8c793172009-11-23 17:57:54 +0000279 PHI->addIncoming(Value, CastNotNull);
280 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
281 CastNull);
282 Value = PHI;
283 }
284
285 return Value;
Anders Carlsson9a57c5a2009-09-12 04:27:24 +0000286}
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000287
288llvm::Value *CodeGenFunction::GetVTTParameter(GlobalDecl GD,
289 bool ForVirtualBase,
290 bool Delegating) {
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000291 if (!CGM.getCXXABI().NeedsVTTParameter(GD)) {
Anders Carlssone36a6b32010-01-02 01:01:18 +0000292 // This constructor/destructor does not need a VTT parameter.
293 return 0;
294 }
295
John McCalldec348f72013-05-03 07:33:41 +0000296 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CurCodeDecl)->getParent();
Anders Carlssone36a6b32010-01-02 01:01:18 +0000297 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
John McCall5c60a6f2010-02-18 19:59:28 +0000298
Anders Carlssone36a6b32010-01-02 01:01:18 +0000299 llvm::Value *VTT;
300
John McCall5c60a6f2010-02-18 19:59:28 +0000301 uint64_t SubVTTIndex;
302
Douglas Gregor61535002013-01-31 05:50:40 +0000303 if (Delegating) {
304 // If this is a delegating constructor call, just load the VTT.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000305 return LoadCXXVTT();
Douglas Gregor61535002013-01-31 05:50:40 +0000306 } else if (RD == Base) {
307 // If the record matches the base, this is the complete ctor/dtor
308 // variant calling the base variant in a class with virtual bases.
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000309 assert(!CGM.getCXXABI().NeedsVTTParameter(CurGD) &&
John McCall5c60a6f2010-02-18 19:59:28 +0000310 "doing no-op VTT offset in base dtor/ctor?");
Anders Carlsson4d205ba2010-05-02 23:33:10 +0000311 assert(!ForVirtualBase && "Can't have same class as virtual base!");
John McCall5c60a6f2010-02-18 19:59:28 +0000312 SubVTTIndex = 0;
313 } else {
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000314 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Ken Dyck16ffcac2011-03-24 01:21:01 +0000315 CharUnits BaseOffset = ForVirtualBase ?
316 Layout.getVBaseClassOffset(Base) :
317 Layout.getBaseClassOffset(Base);
Anders Carlsson859b3062010-05-02 23:53:25 +0000318
319 SubVTTIndex =
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000320 CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
John McCall5c60a6f2010-02-18 19:59:28 +0000321 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
322 }
Anders Carlssone36a6b32010-01-02 01:01:18 +0000323
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000324 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
Anders Carlssone36a6b32010-01-02 01:01:18 +0000325 // A VTT parameter was passed to the constructor, use it.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000326 VTT = LoadCXXVTT();
327 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
Anders Carlssone36a6b32010-01-02 01:01:18 +0000328 } else {
329 // We're the complete constructor, so get the VTT by name.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000330 VTT = CGM.getVTables().GetAddrOfVTT(RD);
331 VTT = Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
Anders Carlssone36a6b32010-01-02 01:01:18 +0000332 }
333
334 return VTT;
335}
336
John McCall1d987562010-07-21 01:23:41 +0000337namespace {
John McCallf99a6312010-07-21 05:30:47 +0000338 /// Call the destructor for a direct base class.
John McCallcda666c2010-07-21 07:22:38 +0000339 struct CallBaseDtor : EHScopeStack::Cleanup {
John McCallf99a6312010-07-21 05:30:47 +0000340 const CXXRecordDecl *BaseClass;
341 bool BaseIsVirtual;
342 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
343 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
John McCall1d987562010-07-21 01:23:41 +0000344
John McCall30317fd2011-07-12 20:27:29 +0000345 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf99a6312010-07-21 05:30:47 +0000346 const CXXRecordDecl *DerivedClass =
347 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
348
349 const CXXDestructorDecl *D = BaseClass->getDestructor();
350 llvm::Value *Addr =
351 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThis(),
352 DerivedClass, BaseClass,
353 BaseIsVirtual);
Douglas Gregor61535002013-01-31 05:50:40 +0000354 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual,
355 /*Delegating=*/false, Addr);
John McCall1d987562010-07-21 01:23:41 +0000356 }
357 };
John McCall769250e2010-09-17 02:31:44 +0000358
359 /// A visitor which checks whether an initializer uses 'this' in a
360 /// way which requires the vtable to be properly set.
361 struct DynamicThisUseChecker : EvaluatedExprVisitor<DynamicThisUseChecker> {
362 typedef EvaluatedExprVisitor<DynamicThisUseChecker> super;
363
364 bool UsesThis;
365
366 DynamicThisUseChecker(ASTContext &C) : super(C), UsesThis(false) {}
367
368 // Black-list all explicit and implicit references to 'this'.
369 //
370 // Do we need to worry about external references to 'this' derived
371 // from arbitrary code? If so, then anything which runs arbitrary
372 // external code might potentially access the vtable.
373 void VisitCXXThisExpr(CXXThisExpr *E) { UsesThis = true; }
374 };
375}
376
377static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
378 DynamicThisUseChecker Checker(C);
379 Checker.Visit(const_cast<Expr*>(Init));
380 return Checker.UsesThis;
John McCall1d987562010-07-21 01:23:41 +0000381}
382
Anders Carlssonfb404882009-12-24 22:46:43 +0000383static void EmitBaseInitializer(CodeGenFunction &CGF,
384 const CXXRecordDecl *ClassDecl,
Alexis Hunt1d792652011-01-08 20:30:50 +0000385 CXXCtorInitializer *BaseInit,
Anders Carlssonfb404882009-12-24 22:46:43 +0000386 CXXCtorType CtorType) {
387 assert(BaseInit->isBaseInitializer() &&
388 "Must have base initializer!");
389
390 llvm::Value *ThisPtr = CGF.LoadCXXThis();
391
392 const Type *BaseType = BaseInit->getBaseClass();
393 CXXRecordDecl *BaseClassDecl =
394 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
395
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +0000396 bool isBaseVirtual = BaseInit->isBaseVirtual();
Anders Carlssonfb404882009-12-24 22:46:43 +0000397
398 // The base constructor doesn't construct virtual bases.
399 if (CtorType == Ctor_Base && isBaseVirtual)
400 return;
401
John McCall769250e2010-09-17 02:31:44 +0000402 // If the initializer for the base (other than the constructor
403 // itself) accesses 'this' in any way, we need to initialize the
404 // vtables.
405 if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
406 CGF.InitializeVTablePointers(ClassDecl);
407
John McCall6ce74722010-02-16 04:15:37 +0000408 // We can pretend to be a complete class because it only matters for
409 // virtual bases, and we only do virtual bases for complete ctors.
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000410 llvm::Value *V =
411 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
John McCallf99a6312010-07-21 05:30:47 +0000412 BaseClassDecl,
413 isBaseVirtual);
Eli Friedman38cd36d2011-12-03 02:13:40 +0000414 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(BaseType);
John McCall8d6fc952011-08-25 20:40:09 +0000415 AggValueSlot AggSlot =
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000416 AggValueSlot::forAddr(V, Alignment, Qualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +0000417 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +0000418 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000419 AggValueSlot::IsNotAliased);
John McCall7a626f62010-09-15 10:14:12 +0000420
421 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
Anders Carlsson5ade5d32010-02-06 20:00:21 +0000422
David Blaikiebbafb8a2012-03-11 07:00:24 +0000423 if (CGF.CGM.getLangOpts().Exceptions &&
Anders Carlsson08ce5ed2011-02-20 00:20:27 +0000424 !BaseClassDecl->hasTrivialDestructor())
John McCallcda666c2010-07-21 07:22:38 +0000425 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
426 isBaseVirtual);
Anders Carlssonfb404882009-12-24 22:46:43 +0000427}
428
Douglas Gregor94f9a482010-05-05 05:51:00 +0000429static void EmitAggMemberInitializer(CodeGenFunction &CGF,
430 LValue LHS,
Eli Friedman6ae63022012-02-14 02:15:49 +0000431 Expr *Init,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000432 llvm::Value *ArrayIndexVar,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000433 QualType T,
Eli Friedman6ae63022012-02-14 02:15:49 +0000434 ArrayRef<VarDecl *> ArrayIndexes,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000435 unsigned Index) {
Eli Friedman6ae63022012-02-14 02:15:49 +0000436 if (Index == ArrayIndexes.size()) {
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000437 LValue LV = LHS;
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000438
Richard Smithcc1b96d2013-06-12 22:31:48 +0000439 if (ArrayIndexVar) {
440 // If we have an array index variable, load it and use it as an offset.
441 // Then, increment the value.
442 llvm::Value *Dest = LHS.getAddress();
443 llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar);
444 Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress");
445 llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1);
446 Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc");
447 CGF.Builder.CreateStore(Next, ArrayIndexVar);
Sebastian Redl4e04dd12012-02-19 15:41:54 +0000448
Richard Smithcc1b96d2013-06-12 22:31:48 +0000449 // Update the LValue.
450 LV.setAddress(Dest);
451 CharUnits Align = CGF.getContext().getTypeAlignInChars(T);
452 LV.setAlignment(std::min(Align, LV.getAlignment()));
Douglas Gregor94f9a482010-05-05 05:51:00 +0000453 }
John McCall7a626f62010-09-15 10:14:12 +0000454
Richard Smithcc1b96d2013-06-12 22:31:48 +0000455 switch (CGF.getEvaluationKind(T)) {
456 case TEK_Scalar:
457 CGF.EmitScalarInit(Init, /*decl*/ 0, LV, false);
458 break;
459 case TEK_Complex:
460 CGF.EmitComplexExprIntoLValue(Init, LV, /*isInit*/ true);
461 break;
462 case TEK_Aggregate: {
463 AggValueSlot Slot =
464 AggValueSlot::forLValue(LV,
465 AggValueSlot::IsDestructed,
466 AggValueSlot::DoesNotNeedGCBarriers,
467 AggValueSlot::IsNotAliased);
468
469 CGF.EmitAggExpr(Init, Slot);
470 break;
471 }
472 }
Sebastian Redl4e04dd12012-02-19 15:41:54 +0000473
Douglas Gregor94f9a482010-05-05 05:51:00 +0000474 return;
475 }
Richard Smithcc1b96d2013-06-12 22:31:48 +0000476
Douglas Gregor94f9a482010-05-05 05:51:00 +0000477 const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T);
478 assert(Array && "Array initialization without the array type?");
479 llvm::Value *IndexVar
Eli Friedman6ae63022012-02-14 02:15:49 +0000480 = CGF.GetAddrOfLocalVar(ArrayIndexes[Index]);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000481 assert(IndexVar && "Array index variable not loaded");
482
483 // Initialize this index variable to zero.
484 llvm::Value* Zero
485 = llvm::Constant::getNullValue(
486 CGF.ConvertType(CGF.getContext().getSizeType()));
487 CGF.Builder.CreateStore(Zero, IndexVar);
488
489 // Start the loop with a block that tests the condition.
490 llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond");
491 llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end");
492
493 CGF.EmitBlock(CondBlock);
494
495 llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body");
496 // Generate: if (loop-index < number-of-elements) fall to the loop body,
497 // otherwise, go to the block after the for-loop.
498 uint64_t NumElements = Array->getSize().getZExtValue();
Douglas Gregor94f9a482010-05-05 05:51:00 +0000499 llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
Chris Lattner44456d22010-05-06 06:35:23 +0000500 llvm::Value *NumElementsPtr =
501 llvm::ConstantInt::get(Counter->getType(), NumElements);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000502 llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr,
503 "isless");
504
505 // If the condition is true, execute the body.
506 CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor);
507
508 CGF.EmitBlock(ForBody);
509 llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc");
Richard Smithcc1b96d2013-06-12 22:31:48 +0000510
511 // Inside the loop body recurse to emit the inner loop or, eventually, the
512 // constructor call.
513 EmitAggMemberInitializer(CGF, LHS, Init, ArrayIndexVar,
514 Array->getElementType(), ArrayIndexes, Index + 1);
515
Douglas Gregor94f9a482010-05-05 05:51:00 +0000516 CGF.EmitBlock(ContinueBlock);
517
518 // Emit the increment of the loop counter.
519 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
520 Counter = CGF.Builder.CreateLoad(IndexVar);
521 NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc");
522 CGF.Builder.CreateStore(NextVal, IndexVar);
523
524 // Finally, branch back up to the condition for the next iteration.
525 CGF.EmitBranch(CondBlock);
526
527 // Emit the fall-through block.
528 CGF.EmitBlock(AfterFor, true);
529}
John McCall1d987562010-07-21 01:23:41 +0000530
Anders Carlssonfb404882009-12-24 22:46:43 +0000531static void EmitMemberInitializer(CodeGenFunction &CGF,
532 const CXXRecordDecl *ClassDecl,
Alexis Hunt1d792652011-01-08 20:30:50 +0000533 CXXCtorInitializer *MemberInit,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000534 const CXXConstructorDecl *Constructor,
535 FunctionArgList &Args) {
Francois Pichetd583da02010-12-04 09:14:42 +0000536 assert(MemberInit->isAnyMemberInitializer() &&
Anders Carlssonfb404882009-12-24 22:46:43 +0000537 "Must have member initializer!");
Richard Smith938f40b2011-06-11 17:19:42 +0000538 assert(MemberInit->getInit() && "Must have initializer!");
Anders Carlssonfb404882009-12-24 22:46:43 +0000539
540 // non-static data member initializers.
Francois Pichetd583da02010-12-04 09:14:42 +0000541 FieldDecl *Field = MemberInit->getAnyMember();
Eli Friedman6ae63022012-02-14 02:15:49 +0000542 QualType FieldType = Field->getType();
Anders Carlssonfb404882009-12-24 22:46:43 +0000543
544 llvm::Value *ThisPtr = CGF.LoadCXXThis();
Eli Friedman7f1ff602012-04-16 03:54:45 +0000545 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
Eli Friedmanf6d21842012-08-08 03:51:37 +0000546 LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
Eli Friedman7f1ff602012-04-16 03:54:45 +0000547
Francois Pichetd583da02010-12-04 09:14:42 +0000548 if (MemberInit->isIndirectMemberInitializer()) {
Eli Friedmanf6d21842012-08-08 03:51:37 +0000549 // If we are initializing an anonymous union field, drill down to
550 // the field.
551 IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember();
552 IndirectFieldDecl::chain_iterator I = IndirectField->chain_begin(),
553 IEnd = IndirectField->chain_end();
554 for ( ; I != IEnd; ++I)
555 LHS = CGF.EmitLValueForFieldInitialization(LHS, cast<FieldDecl>(*I));
Francois Pichetd583da02010-12-04 09:14:42 +0000556 FieldType = MemberInit->getIndirectMember()->getAnonField()->getType();
John McCallc4094932010-05-21 01:18:57 +0000557 } else {
Eli Friedmanf6d21842012-08-08 03:51:37 +0000558 LHS = CGF.EmitLValueForFieldInitialization(LHS, Field);
Anders Carlssonfb404882009-12-24 22:46:43 +0000559 }
560
Eli Friedman6ae63022012-02-14 02:15:49 +0000561 // Special case: if we are in a copy or move constructor, and we are copying
562 // an array of PODs or classes with trivial copy constructors, ignore the
563 // AST and perform the copy we know is equivalent.
564 // FIXME: This is hacky at best... if we had a bit more explicit information
565 // in the AST, we could generalize it more easily.
566 const ConstantArrayType *Array
567 = CGF.getContext().getAsConstantArrayType(FieldType);
Jordan Rose54533f72013-08-07 16:16:48 +0000568 if (Array && Constructor->isDefaulted() &&
Eli Friedman6ae63022012-02-14 02:15:49 +0000569 Constructor->isCopyOrMoveConstructor()) {
570 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
Richard Smith993f25a2012-11-07 23:56:21 +0000571 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
Eli Friedman6ae63022012-02-14 02:15:49 +0000572 if (BaseElementTy.isPODType(CGF.getContext()) ||
Richard Smith993f25a2012-11-07 23:56:21 +0000573 (CE && CE->getConstructor()->isTrivial())) {
574 // Find the source pointer. We know it's the last argument because
575 // we know we're in an implicit copy constructor.
Eli Friedman6ae63022012-02-14 02:15:49 +0000576 unsigned SrcArgIndex = Args.size() - 1;
577 llvm::Value *SrcPtr
578 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
Eli Friedman7f1ff602012-04-16 03:54:45 +0000579 LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
580 LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field);
Eli Friedman6ae63022012-02-14 02:15:49 +0000581
582 // Copy the aggregate.
583 CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000584 LHS.isVolatileQualified());
Eli Friedman6ae63022012-02-14 02:15:49 +0000585 return;
586 }
587 }
588
589 ArrayRef<VarDecl *> ArrayIndexes;
590 if (MemberInit->getNumArrayIndices())
591 ArrayIndexes = MemberInit->getArrayIndexes();
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000592 CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit(), ArrayIndexes);
Eli Friedman6ae63022012-02-14 02:15:49 +0000593}
594
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000595void CodeGenFunction::EmitInitializerForField(FieldDecl *Field,
596 LValue LHS, Expr *Init,
597 ArrayRef<VarDecl *> ArrayIndexes) {
Eli Friedman6ae63022012-02-14 02:15:49 +0000598 QualType FieldType = Field->getType();
John McCall47fb9502013-03-07 21:37:08 +0000599 switch (getEvaluationKind(FieldType)) {
600 case TEK_Scalar:
John McCall31168b02011-06-15 23:02:42 +0000601 if (LHS.isSimple()) {
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000602 EmitExprAsInit(Init, Field, LHS, false);
John McCall31168b02011-06-15 23:02:42 +0000603 } else {
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000604 RValue RHS = RValue::get(EmitScalarExpr(Init));
605 EmitStoreThroughLValue(RHS, LHS);
John McCall31168b02011-06-15 23:02:42 +0000606 }
John McCall47fb9502013-03-07 21:37:08 +0000607 break;
608 case TEK_Complex:
609 EmitComplexExprIntoLValue(Init, LHS, /*isInit*/ true);
610 break;
611 case TEK_Aggregate: {
Douglas Gregor94f9a482010-05-05 05:51:00 +0000612 llvm::Value *ArrayIndexVar = 0;
Eli Friedman6ae63022012-02-14 02:15:49 +0000613 if (ArrayIndexes.size()) {
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000614 llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Douglas Gregor94f9a482010-05-05 05:51:00 +0000615
616 // The LHS is a pointer to the first object we'll be constructing, as
617 // a flat array.
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000618 QualType BaseElementTy = getContext().getBaseElementType(FieldType);
619 llvm::Type *BasePtr = ConvertType(BaseElementTy);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000620 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000621 llvm::Value *BaseAddrPtr = Builder.CreateBitCast(LHS.getAddress(),
622 BasePtr);
623 LHS = MakeAddrLValue(BaseAddrPtr, BaseElementTy);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000624
625 // Create an array index that will be used to walk over all of the
626 // objects we're constructing.
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000627 ArrayIndexVar = CreateTempAlloca(SizeTy, "object.index");
Douglas Gregor94f9a482010-05-05 05:51:00 +0000628 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000629 Builder.CreateStore(Zero, ArrayIndexVar);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000630
Douglas Gregor94f9a482010-05-05 05:51:00 +0000631
632 // Emit the block variables for the array indices, if any.
Eli Friedman6ae63022012-02-14 02:15:49 +0000633 for (unsigned I = 0, N = ArrayIndexes.size(); I != N; ++I)
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000634 EmitAutoVarDecl(*ArrayIndexes[I]);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000635 }
636
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000637 EmitAggMemberInitializer(*this, LHS, Init, ArrayIndexVar, FieldType,
Eli Friedman6ae63022012-02-14 02:15:49 +0000638 ArrayIndexes, 0);
Anders Carlssonfb404882009-12-24 22:46:43 +0000639 }
John McCall47fb9502013-03-07 21:37:08 +0000640 }
John McCall12cc42a2013-02-01 05:11:40 +0000641
642 // Ensure that we destroy this object if an exception is thrown
643 // later in the constructor.
644 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
645 if (needsEHCleanup(dtorKind))
646 pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
Anders Carlssonfb404882009-12-24 22:46:43 +0000647}
648
John McCallf8ff7b92010-02-23 00:48:20 +0000649/// Checks whether the given constructor is a valid subject for the
650/// complete-to-base constructor delegation optimization, i.e.
651/// emitting the complete constructor as a simple call to the base
652/// constructor.
653static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
654
655 // Currently we disable the optimization for classes with virtual
656 // bases because (1) the addresses of parameter variables need to be
657 // consistent across all initializers but (2) the delegate function
658 // call necessarily creates a second copy of the parameter variable.
659 //
660 // The limiting example (purely theoretical AFAIK):
661 // struct A { A(int &c) { c++; } };
662 // struct B : virtual A {
663 // B(int count) : A(count) { printf("%d\n", count); }
664 // };
665 // ...although even this example could in principle be emitted as a
666 // delegation since the address of the parameter doesn't escape.
667 if (Ctor->getParent()->getNumVBases()) {
668 // TODO: white-list trivial vbase initializers. This case wouldn't
669 // be subject to the restrictions below.
670
671 // TODO: white-list cases where:
672 // - there are no non-reference parameters to the constructor
673 // - the initializers don't access any non-reference parameters
674 // - the initializers don't take the address of non-reference
675 // parameters
676 // - etc.
677 // If we ever add any of the above cases, remember that:
678 // - function-try-blocks will always blacklist this optimization
679 // - we need to perform the constructor prologue and cleanup in
680 // EmitConstructorBody.
681
682 return false;
683 }
684
685 // We also disable the optimization for variadic functions because
686 // it's impossible to "re-pass" varargs.
687 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
688 return false;
689
Alexis Hunt61bc1732011-05-01 07:04:31 +0000690 // FIXME: Decide if we can do a delegation of a delegating constructor.
691 if (Ctor->isDelegatingConstructor())
692 return false;
693
John McCallf8ff7b92010-02-23 00:48:20 +0000694 return true;
695}
696
John McCallb81884d2010-02-19 09:25:03 +0000697/// EmitConstructorBody - Emits the body of the current constructor.
698void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
699 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
700 CXXCtorType CtorType = CurGD.getCtorType();
701
Reid Kleckner340ad862014-01-13 22:57:31 +0000702 assert((CGM.getTarget().getCXXABI().hasConstructorVariants() ||
703 CtorType == Ctor_Complete) &&
704 "can only generate complete ctor for this ABI");
705
John McCallf8ff7b92010-02-23 00:48:20 +0000706 // Before we go any further, try the complete->base constructor
707 // delegation optimization.
Timur Iskhodzhanovf32a3772012-04-20 08:05:00 +0000708 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
John McCallc8e01702013-04-16 22:48:15 +0000709 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
Devang Pateld76c1db2010-08-11 21:04:37 +0000710 if (CGDebugInfo *DI = getDebugInfo())
Eric Christopher7cdf9482011-10-13 21:45:18 +0000711 DI->EmitLocation(Builder, Ctor->getLocEnd());
Nick Lewycky2d84e842013-10-02 02:29:49 +0000712 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args, Ctor->getLocEnd());
John McCallf8ff7b92010-02-23 00:48:20 +0000713 return;
714 }
715
John McCallb81884d2010-02-19 09:25:03 +0000716 Stmt *Body = Ctor->getBody();
717
John McCallf8ff7b92010-02-23 00:48:20 +0000718 // Enter the function-try-block before the constructor prologue if
719 // applicable.
John McCallf8ff7b92010-02-23 00:48:20 +0000720 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallf8ff7b92010-02-23 00:48:20 +0000721 if (IsTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000722 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000723
Justin Bogner81c22c22014-01-23 02:54:27 +0000724 RegionCounter Cnt = getPGORegionCounter(Body);
725 Cnt.beginRegion(Builder);
726
Richard Smithcc1b96d2013-06-12 22:31:48 +0000727 RunCleanupsScope RunCleanups(*this);
John McCallb81884d2010-02-19 09:25:03 +0000728
John McCall88313032012-03-30 04:25:03 +0000729 // TODO: in restricted cases, we can emit the vbase initializers of
730 // a complete ctor and then delegate to the base ctor.
731
John McCallf8ff7b92010-02-23 00:48:20 +0000732 // Emit the constructor prologue, i.e. the base and member
733 // initializers.
Douglas Gregor94f9a482010-05-05 05:51:00 +0000734 EmitCtorPrologue(Ctor, CtorType, Args);
John McCallb81884d2010-02-19 09:25:03 +0000735
736 // Emit the body of the statement.
John McCallf8ff7b92010-02-23 00:48:20 +0000737 if (IsTryBody)
John McCallb81884d2010-02-19 09:25:03 +0000738 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
739 else if (Body)
740 EmitStmt(Body);
John McCallb81884d2010-02-19 09:25:03 +0000741
742 // Emit any cleanup blocks associated with the member or base
743 // initializers, which includes (along the exceptional path) the
744 // destructors for those members and bases that were fully
745 // constructed.
Richard Smithcc1b96d2013-06-12 22:31:48 +0000746 RunCleanups.ForceCleanup();
John McCallb81884d2010-02-19 09:25:03 +0000747
John McCallf8ff7b92010-02-23 00:48:20 +0000748 if (IsTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000749 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000750}
751
Lang Hamesbf122742013-02-17 07:22:09 +0000752namespace {
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000753 /// RAII object to indicate that codegen is copying the value representation
754 /// instead of the object representation. Useful when copying a struct or
755 /// class which has uninitialized members and we're only performing
756 /// lvalue-to-rvalue conversion on the object but not its members.
757 class CopyingValueRepresentation {
758 public:
759 explicit CopyingValueRepresentation(CodeGenFunction &CGF)
760 : CGF(CGF), SO(*CGF.SanOpts), OldSanOpts(CGF.SanOpts) {
761 SO.Bool = false;
762 SO.Enum = false;
763 CGF.SanOpts = &SO;
764 }
765 ~CopyingValueRepresentation() {
766 CGF.SanOpts = OldSanOpts;
767 }
768 private:
769 CodeGenFunction &CGF;
770 SanitizerOptions SO;
771 const SanitizerOptions *OldSanOpts;
772 };
773}
774
775namespace {
Lang Hamesbf122742013-02-17 07:22:09 +0000776 class FieldMemcpyizer {
777 public:
778 FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl,
779 const VarDecl *SrcRec)
780 : CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec),
781 RecLayout(CGF.getContext().getASTRecordLayout(ClassDecl)),
782 FirstField(0), LastField(0), FirstFieldOffset(0), LastFieldOffset(0),
783 LastAddedFieldIndex(0) { }
784
785 static bool isMemcpyableField(FieldDecl *F) {
786 Qualifiers Qual = F->getType().getQualifiers();
787 if (Qual.hasVolatile() || Qual.hasObjCLifetime())
788 return false;
789 return true;
790 }
791
792 void addMemcpyableField(FieldDecl *F) {
793 if (FirstField == 0)
794 addInitialField(F);
795 else
796 addNextField(F);
797 }
798
799 CharUnits getMemcpySize() const {
800 unsigned LastFieldSize =
801 LastField->isBitField() ?
802 LastField->getBitWidthValue(CGF.getContext()) :
803 CGF.getContext().getTypeSize(LastField->getType());
804 uint64_t MemcpySizeBits =
805 LastFieldOffset + LastFieldSize - FirstFieldOffset +
806 CGF.getContext().getCharWidth() - 1;
807 CharUnits MemcpySize =
808 CGF.getContext().toCharUnitsFromBits(MemcpySizeBits);
809 return MemcpySize;
810 }
811
812 void emitMemcpy() {
813 // Give the subclass a chance to bail out if it feels the memcpy isn't
814 // worth it (e.g. Hasn't aggregated enough data).
815 if (FirstField == 0) {
816 return;
817 }
818
Lang Hames1694e0d2013-02-27 04:14:49 +0000819 CharUnits Alignment;
Lang Hamesbf122742013-02-17 07:22:09 +0000820
821 if (FirstField->isBitField()) {
822 const CGRecordLayout &RL =
823 CGF.getTypes().getCGRecordLayout(FirstField->getParent());
824 const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField);
Lang Hames1694e0d2013-02-27 04:14:49 +0000825 Alignment = CharUnits::fromQuantity(BFInfo.StorageAlignment);
826 } else {
Lang Hames224ae882013-03-05 20:27:24 +0000827 Alignment = CGF.getContext().getDeclAlign(FirstField);
Lang Hames1694e0d2013-02-27 04:14:49 +0000828 }
Lang Hamesbf122742013-02-17 07:22:09 +0000829
Lang Hames1694e0d2013-02-27 04:14:49 +0000830 assert((CGF.getContext().toCharUnitsFromBits(FirstFieldOffset) %
831 Alignment) == 0 && "Bad field alignment.");
832
Lang Hamesbf122742013-02-17 07:22:09 +0000833 CharUnits MemcpySize = getMemcpySize();
834 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
835 llvm::Value *ThisPtr = CGF.LoadCXXThis();
836 LValue DestLV = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
837 LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField);
838 llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec));
839 LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
840 LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField);
841
842 emitMemcpyIR(Dest.isBitField() ? Dest.getBitFieldAddr() : Dest.getAddress(),
843 Src.isBitField() ? Src.getBitFieldAddr() : Src.getAddress(),
844 MemcpySize, Alignment);
845 reset();
846 }
847
848 void reset() {
849 FirstField = 0;
850 }
851
852 protected:
853 CodeGenFunction &CGF;
854 const CXXRecordDecl *ClassDecl;
855
856 private:
857
858 void emitMemcpyIR(llvm::Value *DestPtr, llvm::Value *SrcPtr,
859 CharUnits Size, CharUnits Alignment) {
860 llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
861 llvm::Type *DBP =
862 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), DPT->getAddressSpace());
863 DestPtr = CGF.Builder.CreateBitCast(DestPtr, DBP);
864
865 llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
866 llvm::Type *SBP =
867 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), SPT->getAddressSpace());
868 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, SBP);
869
870 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity(),
871 Alignment.getQuantity());
872 }
873
874 void addInitialField(FieldDecl *F) {
875 FirstField = F;
876 LastField = F;
877 FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex());
878 LastFieldOffset = FirstFieldOffset;
879 LastAddedFieldIndex = F->getFieldIndex();
880 return;
881 }
882
883 void addNextField(FieldDecl *F) {
John McCall6054d5a2013-05-07 05:20:46 +0000884 // For the most part, the following invariant will hold:
885 // F->getFieldIndex() == LastAddedFieldIndex + 1
886 // The one exception is that Sema won't add a copy-initializer for an
887 // unnamed bitfield, which will show up here as a gap in the sequence.
888 assert(F->getFieldIndex() >= LastAddedFieldIndex + 1 &&
889 "Cannot aggregate fields out of order.");
Lang Hamesbf122742013-02-17 07:22:09 +0000890 LastAddedFieldIndex = F->getFieldIndex();
891
892 // The 'first' and 'last' fields are chosen by offset, rather than field
893 // index. This allows the code to support bitfields, as well as regular
894 // fields.
895 uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex());
896 if (FOffset < FirstFieldOffset) {
897 FirstField = F;
898 FirstFieldOffset = FOffset;
899 } else if (FOffset > LastFieldOffset) {
900 LastField = F;
901 LastFieldOffset = FOffset;
902 }
903 }
904
905 const VarDecl *SrcRec;
906 const ASTRecordLayout &RecLayout;
907 FieldDecl *FirstField;
908 FieldDecl *LastField;
909 uint64_t FirstFieldOffset, LastFieldOffset;
910 unsigned LastAddedFieldIndex;
911 };
912
913 class ConstructorMemcpyizer : public FieldMemcpyizer {
914 private:
915
916 /// Get source argument for copy constructor. Returns null if not a copy
917 /// constructor.
918 static const VarDecl* getTrivialCopySource(const CXXConstructorDecl *CD,
919 FunctionArgList &Args) {
Jordan Rose54533f72013-08-07 16:16:48 +0000920 if (CD->isCopyOrMoveConstructor() && CD->isDefaulted())
Lang Hamesbf122742013-02-17 07:22:09 +0000921 return Args[Args.size() - 1];
922 return 0;
923 }
924
925 // Returns true if a CXXCtorInitializer represents a member initialization
926 // that can be rolled into a memcpy.
927 bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const {
928 if (!MemcpyableCtor)
929 return false;
930 FieldDecl *Field = MemberInit->getMember();
931 assert(Field != 0 && "No field for member init.");
932 QualType FieldType = Field->getType();
933 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
934
935 // Bail out on non-POD, not-trivially-constructable members.
936 if (!(CE && CE->getConstructor()->isTrivial()) &&
937 !(FieldType.isTriviallyCopyableType(CGF.getContext()) ||
938 FieldType->isReferenceType()))
939 return false;
940
941 // Bail out on volatile fields.
942 if (!isMemcpyableField(Field))
943 return false;
944
945 // Otherwise we're good.
946 return true;
947 }
948
949 public:
950 ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD,
951 FunctionArgList &Args)
952 : FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CD, Args)),
953 ConstructorDecl(CD),
Jordan Rose54533f72013-08-07 16:16:48 +0000954 MemcpyableCtor(CD->isDefaulted() &&
Lang Hamesbf122742013-02-17 07:22:09 +0000955 CD->isCopyOrMoveConstructor() &&
956 CGF.getLangOpts().getGC() == LangOptions::NonGC),
957 Args(Args) { }
958
959 void addMemberInitializer(CXXCtorInitializer *MemberInit) {
960 if (isMemberInitMemcpyable(MemberInit)) {
961 AggregatedInits.push_back(MemberInit);
962 addMemcpyableField(MemberInit->getMember());
963 } else {
964 emitAggregatedInits();
965 EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit,
966 ConstructorDecl, Args);
967 }
968 }
969
970 void emitAggregatedInits() {
971 if (AggregatedInits.size() <= 1) {
972 // This memcpy is too small to be worthwhile. Fall back on default
973 // codegen.
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000974 if (!AggregatedInits.empty()) {
975 CopyingValueRepresentation CVR(CGF);
Lang Hamesbf122742013-02-17 07:22:09 +0000976 EmitMemberInitializer(CGF, ConstructorDecl->getParent(),
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000977 AggregatedInits[0], ConstructorDecl, Args);
Lang Hamesbf122742013-02-17 07:22:09 +0000978 }
979 reset();
980 return;
981 }
982
983 pushEHDestructors();
984 emitMemcpy();
985 AggregatedInits.clear();
986 }
987
988 void pushEHDestructors() {
989 llvm::Value *ThisPtr = CGF.LoadCXXThis();
990 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
991 LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
992
993 for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
994 QualType FieldType = AggregatedInits[i]->getMember()->getType();
995 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
996 if (CGF.needsEHCleanup(dtorKind))
997 CGF.pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
998 }
999 }
1000
1001 void finish() {
1002 emitAggregatedInits();
1003 }
1004
1005 private:
1006 const CXXConstructorDecl *ConstructorDecl;
1007 bool MemcpyableCtor;
1008 FunctionArgList &Args;
1009 SmallVector<CXXCtorInitializer*, 16> AggregatedInits;
1010 };
1011
1012 class AssignmentMemcpyizer : public FieldMemcpyizer {
1013 private:
1014
1015 // Returns the memcpyable field copied by the given statement, if one
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001016 // exists. Otherwise returns null.
1017 FieldDecl *getMemcpyableField(Stmt *S) {
Lang Hamesbf122742013-02-17 07:22:09 +00001018 if (!AssignmentsMemcpyable)
1019 return 0;
1020 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
1021 // Recognise trivial assignments.
1022 if (BO->getOpcode() != BO_Assign)
1023 return 0;
1024 MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS());
1025 if (!ME)
1026 return 0;
1027 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1028 if (!Field || !isMemcpyableField(Field))
1029 return 0;
1030 Stmt *RHS = BO->getRHS();
1031 if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS))
1032 RHS = EC->getSubExpr();
1033 if (!RHS)
1034 return 0;
1035 MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS);
1036 if (dyn_cast<FieldDecl>(ME2->getMemberDecl()) != Field)
1037 return 0;
1038 return Field;
1039 } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) {
1040 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl());
1041 if (!(MD && (MD->isCopyAssignmentOperator() ||
1042 MD->isMoveAssignmentOperator()) &&
1043 MD->isTrivial()))
1044 return 0;
1045 MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument());
1046 if (!IOA)
1047 return 0;
1048 FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl());
1049 if (!Field || !isMemcpyableField(Field))
1050 return 0;
1051 MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0));
1052 if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl()))
1053 return 0;
1054 return Field;
1055 } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1056 FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1057 if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy)
1058 return 0;
1059 Expr *DstPtr = CE->getArg(0);
1060 if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr))
1061 DstPtr = DC->getSubExpr();
1062 UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr);
1063 if (!DUO || DUO->getOpcode() != UO_AddrOf)
1064 return 0;
1065 MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr());
1066 if (!ME)
1067 return 0;
1068 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1069 if (!Field || !isMemcpyableField(Field))
1070 return 0;
1071 Expr *SrcPtr = CE->getArg(1);
1072 if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr))
1073 SrcPtr = SC->getSubExpr();
1074 UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr);
1075 if (!SUO || SUO->getOpcode() != UO_AddrOf)
1076 return 0;
1077 MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr());
1078 if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl()))
1079 return 0;
1080 return Field;
1081 }
1082
1083 return 0;
1084 }
1085
1086 bool AssignmentsMemcpyable;
1087 SmallVector<Stmt*, 16> AggregatedStmts;
1088
1089 public:
1090
1091 AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD,
1092 FunctionArgList &Args)
1093 : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]),
1094 AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) {
1095 assert(Args.size() == 2);
1096 }
1097
1098 void emitAssignment(Stmt *S) {
1099 FieldDecl *F = getMemcpyableField(S);
1100 if (F) {
1101 addMemcpyableField(F);
1102 AggregatedStmts.push_back(S);
1103 } else {
1104 emitAggregatedStmts();
1105 CGF.EmitStmt(S);
1106 }
1107 }
1108
1109 void emitAggregatedStmts() {
1110 if (AggregatedStmts.size() <= 1) {
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001111 if (!AggregatedStmts.empty()) {
1112 CopyingValueRepresentation CVR(CGF);
1113 CGF.EmitStmt(AggregatedStmts[0]);
1114 }
Lang Hamesbf122742013-02-17 07:22:09 +00001115 reset();
1116 }
1117
1118 emitMemcpy();
1119 AggregatedStmts.clear();
1120 }
1121
1122 void finish() {
1123 emitAggregatedStmts();
1124 }
1125 };
1126
1127}
1128
Anders Carlssonfb404882009-12-24 22:46:43 +00001129/// EmitCtorPrologue - This routine generates necessary code to initialize
1130/// base classes and non-static data members belonging to this constructor.
Anders Carlssonfb404882009-12-24 22:46:43 +00001131void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001132 CXXCtorType CtorType,
1133 FunctionArgList &Args) {
Alexis Hunt61bc1732011-05-01 07:04:31 +00001134 if (CD->isDelegatingConstructor())
1135 return EmitDelegatingCXXConstructorCall(CD, Args);
1136
Anders Carlssonfb404882009-12-24 22:46:43 +00001137 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlsson5dc86332010-02-02 19:58:43 +00001138
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001139 CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
1140 E = CD->init_end();
1141
1142 llvm::BasicBlock *BaseCtorContinueBB = 0;
1143 if (ClassDecl->getNumVBases() &&
1144 !CGM.getTarget().getCXXABI().hasConstructorVariants()) {
1145 // The ABIs that don't have constructor variants need to put a branch
1146 // before the virtual base initialization code.
Reid Kleckner7810af02013-06-19 15:20:38 +00001147 BaseCtorContinueBB =
1148 CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this, ClassDecl);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001149 assert(BaseCtorContinueBB);
1150 }
1151
1152 // Virtual base initializers first.
1153 for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
1154 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
1155 }
1156
1157 if (BaseCtorContinueBB) {
1158 // Complete object handler should continue to the remaining initializers.
1159 Builder.CreateBr(BaseCtorContinueBB);
1160 EmitBlock(BaseCtorContinueBB);
1161 }
1162
1163 // Then, non-virtual base initializers.
1164 for (; B != E && (*B)->isBaseInitializer(); B++) {
1165 assert(!(*B)->isBaseVirtual());
1166 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
Anders Carlssonfb404882009-12-24 22:46:43 +00001167 }
1168
Anders Carlssond5895932010-03-28 21:07:49 +00001169 InitializeVTablePointers(ClassDecl);
Anders Carlsson5dc86332010-02-02 19:58:43 +00001170
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001171 // And finally, initialize class members.
Richard Smith852c9db2013-04-20 22:23:05 +00001172 FieldConstructionScope FCS(*this, CXXThisValue);
Lang Hamesbf122742013-02-17 07:22:09 +00001173 ConstructorMemcpyizer CM(*this, CD, Args);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001174 for (; B != E; B++) {
1175 CXXCtorInitializer *Member = (*B);
1176 assert(!Member->isBaseInitializer());
1177 assert(Member->isAnyMemberInitializer() &&
1178 "Delegating initializer on non-delegating constructor");
1179 CM.addMemberInitializer(Member);
1180 }
Lang Hamesbf122742013-02-17 07:22:09 +00001181 CM.finish();
Anders Carlssonfb404882009-12-24 22:46:43 +00001182}
1183
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001184static bool
1185FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
1186
1187static bool
1188HasTrivialDestructorBody(ASTContext &Context,
1189 const CXXRecordDecl *BaseClassDecl,
1190 const CXXRecordDecl *MostDerivedClassDecl)
1191{
1192 // If the destructor is trivial we don't have to check anything else.
1193 if (BaseClassDecl->hasTrivialDestructor())
1194 return true;
1195
1196 if (!BaseClassDecl->getDestructor()->hasTrivialBody())
1197 return false;
1198
1199 // Check fields.
1200 for (CXXRecordDecl::field_iterator I = BaseClassDecl->field_begin(),
1201 E = BaseClassDecl->field_end(); I != E; ++I) {
David Blaikie40ed2972012-06-06 20:45:41 +00001202 const FieldDecl *Field = *I;
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001203
1204 if (!FieldHasTrivialDestructorBody(Context, Field))
1205 return false;
1206 }
1207
1208 // Check non-virtual bases.
1209 for (CXXRecordDecl::base_class_const_iterator I =
1210 BaseClassDecl->bases_begin(), E = BaseClassDecl->bases_end();
1211 I != E; ++I) {
1212 if (I->isVirtual())
1213 continue;
1214
1215 const CXXRecordDecl *NonVirtualBase =
1216 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
1217 if (!HasTrivialDestructorBody(Context, NonVirtualBase,
1218 MostDerivedClassDecl))
1219 return false;
1220 }
1221
1222 if (BaseClassDecl == MostDerivedClassDecl) {
1223 // Check virtual bases.
1224 for (CXXRecordDecl::base_class_const_iterator I =
1225 BaseClassDecl->vbases_begin(), E = BaseClassDecl->vbases_end();
1226 I != E; ++I) {
1227 const CXXRecordDecl *VirtualBase =
1228 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
1229 if (!HasTrivialDestructorBody(Context, VirtualBase,
1230 MostDerivedClassDecl))
1231 return false;
1232 }
1233 }
1234
1235 return true;
1236}
1237
1238static bool
1239FieldHasTrivialDestructorBody(ASTContext &Context,
1240 const FieldDecl *Field)
1241{
1242 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
1243
1244 const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
1245 if (!RT)
1246 return true;
1247
1248 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1249 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
1250}
1251
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001252/// CanSkipVTablePointerInitialization - Check whether we need to initialize
1253/// any vtable pointers before calling this destructor.
1254static bool CanSkipVTablePointerInitialization(ASTContext &Context,
Anders Carlssond6f15182011-05-16 04:08:36 +00001255 const CXXDestructorDecl *Dtor) {
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001256 if (!Dtor->hasTrivialBody())
1257 return false;
1258
1259 // Check the fields.
1260 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1261 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1262 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie40ed2972012-06-06 20:45:41 +00001263 const FieldDecl *Field = *I;
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001264
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001265 if (!FieldHasTrivialDestructorBody(Context, Field))
1266 return false;
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001267 }
1268
1269 return true;
1270}
1271
John McCallb81884d2010-02-19 09:25:03 +00001272/// EmitDestructorBody - Emits the body of the current destructor.
1273void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
1274 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
1275 CXXDtorType DtorType = CurGD.getDtorType();
1276
John McCallf99a6312010-07-21 05:30:47 +00001277 // The call to operator delete in a deleting destructor happens
1278 // outside of the function-try-block, which means it's always
1279 // possible to delegate the destructor body to the complete
1280 // destructor. Do so.
1281 if (DtorType == Dtor_Deleting) {
1282 EnterDtorCleanups(Dtor, Dtor_Deleting);
1283 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
Douglas Gregor61535002013-01-31 05:50:40 +00001284 /*Delegating=*/false, LoadCXXThis());
John McCallf99a6312010-07-21 05:30:47 +00001285 PopCleanupBlock();
1286 return;
1287 }
1288
John McCallb81884d2010-02-19 09:25:03 +00001289 Stmt *Body = Dtor->getBody();
1290
1291 // If the body is a function-try-block, enter the try before
John McCallf99a6312010-07-21 05:30:47 +00001292 // anything else.
1293 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallb81884d2010-02-19 09:25:03 +00001294 if (isTryBody)
John McCallb609d3f2010-07-07 06:56:46 +00001295 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +00001296
John McCallf99a6312010-07-21 05:30:47 +00001297 // Enter the epilogue cleanups.
1298 RunCleanupsScope DtorEpilogue(*this);
1299
John McCallb81884d2010-02-19 09:25:03 +00001300 // If this is the complete variant, just invoke the base variant;
1301 // the epilogue will destruct the virtual bases. But we can't do
1302 // this optimization if the body is a function-try-block, because
Reid Klecknere7de47e2013-07-22 13:51:44 +00001303 // we'd introduce *two* handler blocks. In the Microsoft ABI, we
1304 // always delegate because we might not have a definition in this TU.
John McCallf99a6312010-07-21 05:30:47 +00001305 switch (DtorType) {
1306 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
1307
1308 case Dtor_Complete:
Reid Klecknere7de47e2013-07-22 13:51:44 +00001309 assert((Body || getTarget().getCXXABI().isMicrosoft()) &&
1310 "can't emit a dtor without a body for non-Microsoft ABIs");
1311
John McCallf99a6312010-07-21 05:30:47 +00001312 // Enter the cleanup scopes for virtual bases.
1313 EnterDtorCleanups(Dtor, Dtor_Complete);
1314
Reid Klecknere7de47e2013-07-22 13:51:44 +00001315 if (!isTryBody) {
John McCallf99a6312010-07-21 05:30:47 +00001316 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
Douglas Gregor61535002013-01-31 05:50:40 +00001317 /*Delegating=*/false, LoadCXXThis());
John McCallf99a6312010-07-21 05:30:47 +00001318 break;
1319 }
1320 // Fallthrough: act like we're in the base variant.
John McCallb81884d2010-02-19 09:25:03 +00001321
John McCallf99a6312010-07-21 05:30:47 +00001322 case Dtor_Base:
Reid Klecknere7de47e2013-07-22 13:51:44 +00001323 assert(Body);
1324
Justin Bogner81c22c22014-01-23 02:54:27 +00001325 RegionCounter Cnt = getPGORegionCounter(Body);
1326 Cnt.beginRegion(Builder);
1327
John McCallf99a6312010-07-21 05:30:47 +00001328 // Enter the cleanup scopes for fields and non-virtual bases.
1329 EnterDtorCleanups(Dtor, Dtor_Base);
1330
1331 // Initialize the vtable pointers before entering the body.
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001332 if (!CanSkipVTablePointerInitialization(getContext(), Dtor))
1333 InitializeVTablePointers(Dtor->getParent());
John McCallf99a6312010-07-21 05:30:47 +00001334
1335 if (isTryBody)
1336 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
1337 else if (Body)
1338 EmitStmt(Body);
1339 else {
1340 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
1341 // nothing to do besides what's in the epilogue
1342 }
Fariborz Jahanian0c12ed12011-02-02 23:12:46 +00001343 // -fapple-kext must inline any call to this dtor into
1344 // the caller's body.
Richard Smith9c6890a2012-11-01 22:30:59 +00001345 if (getLangOpts().AppleKext)
Bill Wendling207f0532012-12-20 19:27:06 +00001346 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
John McCallf99a6312010-07-21 05:30:47 +00001347 break;
John McCallb81884d2010-02-19 09:25:03 +00001348 }
1349
John McCallf99a6312010-07-21 05:30:47 +00001350 // Jump out through the epilogue cleanups.
1351 DtorEpilogue.ForceCleanup();
John McCallb81884d2010-02-19 09:25:03 +00001352
1353 // Exit the try if applicable.
1354 if (isTryBody)
John McCallb609d3f2010-07-07 06:56:46 +00001355 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +00001356}
1357
Lang Hamesbf122742013-02-17 07:22:09 +00001358void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) {
1359 const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
1360 const Stmt *RootS = AssignOp->getBody();
1361 assert(isa<CompoundStmt>(RootS) &&
1362 "Body of an implicit assignment operator should be compound stmt.");
1363 const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
1364
1365 LexicalScope Scope(*this, RootCS->getSourceRange());
1366
1367 AssignmentMemcpyizer AM(*this, AssignOp, Args);
1368 for (CompoundStmt::const_body_iterator I = RootCS->body_begin(),
1369 E = RootCS->body_end();
1370 I != E; ++I) {
1371 AM.emitAssignment(*I);
1372 }
1373 AM.finish();
1374}
1375
John McCallf99a6312010-07-21 05:30:47 +00001376namespace {
1377 /// Call the operator delete associated with the current destructor.
John McCallcda666c2010-07-21 07:22:38 +00001378 struct CallDtorDelete : EHScopeStack::Cleanup {
John McCallf99a6312010-07-21 05:30:47 +00001379 CallDtorDelete() {}
1380
John McCall30317fd2011-07-12 20:27:29 +00001381 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf99a6312010-07-21 05:30:47 +00001382 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1383 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1384 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1385 CGF.getContext().getTagDeclType(ClassDecl));
1386 }
1387 };
1388
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001389 struct CallDtorDeleteConditional : EHScopeStack::Cleanup {
1390 llvm::Value *ShouldDeleteCondition;
1391 public:
1392 CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
1393 : ShouldDeleteCondition(ShouldDeleteCondition) {
1394 assert(ShouldDeleteCondition != NULL);
1395 }
1396
1397 void Emit(CodeGenFunction &CGF, Flags flags) {
1398 llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
1399 llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
1400 llvm::Value *ShouldCallDelete
1401 = CGF.Builder.CreateIsNull(ShouldDeleteCondition);
1402 CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
1403
1404 CGF.EmitBlock(callDeleteBB);
1405 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1406 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1407 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1408 CGF.getContext().getTagDeclType(ClassDecl));
1409 CGF.Builder.CreateBr(continueBB);
1410
1411 CGF.EmitBlock(continueBB);
1412 }
1413 };
1414
John McCall4bd0fb12011-07-12 16:41:08 +00001415 class DestroyField : public EHScopeStack::Cleanup {
1416 const FieldDecl *field;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001417 CodeGenFunction::Destroyer *destroyer;
John McCall4bd0fb12011-07-12 16:41:08 +00001418 bool useEHCleanupForArray;
John McCallf99a6312010-07-21 05:30:47 +00001419
John McCall4bd0fb12011-07-12 16:41:08 +00001420 public:
1421 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
1422 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +00001423 : field(field), destroyer(destroyer),
John McCall4bd0fb12011-07-12 16:41:08 +00001424 useEHCleanupForArray(useEHCleanupForArray) {}
John McCallf99a6312010-07-21 05:30:47 +00001425
John McCall30317fd2011-07-12 20:27:29 +00001426 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall4bd0fb12011-07-12 16:41:08 +00001427 // Find the address of the field.
1428 llvm::Value *thisValue = CGF.LoadCXXThis();
Eli Friedman7f1ff602012-04-16 03:54:45 +00001429 QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
1430 LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
1431 LValue LV = CGF.EmitLValueForField(ThisLV, field);
John McCall4bd0fb12011-07-12 16:41:08 +00001432 assert(LV.isSimple());
1433
1434 CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +00001435 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCallf99a6312010-07-21 05:30:47 +00001436 }
1437 };
1438}
1439
Hans Wennborgdeff7032013-12-18 01:39:59 +00001440/// \brief Emit all code that comes at the end of class's
Anders Carlssonfb404882009-12-24 22:46:43 +00001441/// destructor. This is to call destructors on members and base classes
1442/// in reverse order of their construction.
John McCallf99a6312010-07-21 05:30:47 +00001443void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
1444 CXXDtorType DtorType) {
Anders Carlssonfb404882009-12-24 22:46:43 +00001445 assert(!DD->isTrivial() &&
1446 "Should not emit dtor epilogue for trivial dtor!");
1447
John McCallf99a6312010-07-21 05:30:47 +00001448 // The deleting-destructor phase just needs to call the appropriate
1449 // operator delete that Sema picked up.
John McCall5c60a6f2010-02-18 19:59:28 +00001450 if (DtorType == Dtor_Deleting) {
1451 assert(DD->getOperatorDelete() &&
Hans Wennborgdeff7032013-12-18 01:39:59 +00001452 "operator delete missing - EnterDtorCleanups");
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001453 if (CXXStructorImplicitParamValue) {
1454 // If there is an implicit param to the deleting dtor, it's a boolean
1455 // telling whether we should call delete at the end of the dtor.
1456 EHStack.pushCleanup<CallDtorDeleteConditional>(
1457 NormalAndEHCleanup, CXXStructorImplicitParamValue);
1458 } else {
1459 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
1460 }
John McCall5c60a6f2010-02-18 19:59:28 +00001461 return;
1462 }
1463
John McCallf99a6312010-07-21 05:30:47 +00001464 const CXXRecordDecl *ClassDecl = DD->getParent();
1465
Richard Smith20104042011-09-18 12:11:43 +00001466 // Unions have no bases and do not call field destructors.
1467 if (ClassDecl->isUnion())
1468 return;
1469
John McCallf99a6312010-07-21 05:30:47 +00001470 // The complete-destructor phase just destructs all the virtual bases.
John McCall5c60a6f2010-02-18 19:59:28 +00001471 if (DtorType == Dtor_Complete) {
John McCallf99a6312010-07-21 05:30:47 +00001472
1473 // We push them in the forward order so that they'll be popped in
1474 // the reverse order.
1475 for (CXXRecordDecl::base_class_const_iterator I =
1476 ClassDecl->vbases_begin(), E = ClassDecl->vbases_end();
John McCall5c60a6f2010-02-18 19:59:28 +00001477 I != E; ++I) {
1478 const CXXBaseSpecifier &Base = *I;
1479 CXXRecordDecl *BaseClassDecl
1480 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1481
1482 // Ignore trivial destructors.
1483 if (BaseClassDecl->hasTrivialDestructor())
1484 continue;
John McCallf99a6312010-07-21 05:30:47 +00001485
John McCallcda666c2010-07-21 07:22:38 +00001486 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1487 BaseClassDecl,
1488 /*BaseIsVirtual*/ true);
John McCall5c60a6f2010-02-18 19:59:28 +00001489 }
John McCallf99a6312010-07-21 05:30:47 +00001490
John McCall5c60a6f2010-02-18 19:59:28 +00001491 return;
1492 }
1493
1494 assert(DtorType == Dtor_Base);
John McCallf99a6312010-07-21 05:30:47 +00001495
1496 // Destroy non-virtual bases.
1497 for (CXXRecordDecl::base_class_const_iterator I =
1498 ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) {
1499 const CXXBaseSpecifier &Base = *I;
1500
1501 // Ignore virtual bases.
1502 if (Base.isVirtual())
1503 continue;
1504
1505 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
1506
1507 // Ignore trivial destructors.
1508 if (BaseClassDecl->hasTrivialDestructor())
1509 continue;
John McCall5c60a6f2010-02-18 19:59:28 +00001510
John McCallcda666c2010-07-21 07:22:38 +00001511 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1512 BaseClassDecl,
1513 /*BaseIsVirtual*/ false);
John McCallf99a6312010-07-21 05:30:47 +00001514 }
1515
1516 // Destroy direct fields.
Anders Carlssonfb404882009-12-24 22:46:43 +00001517 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1518 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie40ed2972012-06-06 20:45:41 +00001519 const FieldDecl *field = *I;
John McCall4bd0fb12011-07-12 16:41:08 +00001520 QualType type = field->getType();
1521 QualType::DestructionKind dtorKind = type.isDestructedType();
1522 if (!dtorKind) continue;
John McCallf99a6312010-07-21 05:30:47 +00001523
Richard Smith921bd202012-02-26 09:11:52 +00001524 // Anonymous union members do not have their destructors called.
1525 const RecordType *RT = type->getAsUnionType();
1526 if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
1527
John McCall4bd0fb12011-07-12 16:41:08 +00001528 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1529 EHStack.pushCleanup<DestroyField>(cleanupKind, field,
1530 getDestroyer(dtorKind),
1531 cleanupKind & EHCleanup);
Anders Carlssonfb404882009-12-24 22:46:43 +00001532 }
Anders Carlssonfb404882009-12-24 22:46:43 +00001533}
1534
John McCallf677a8e2011-07-13 06:10:41 +00001535/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1536/// constructor for each of several members of an array.
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001537///
John McCallf677a8e2011-07-13 06:10:41 +00001538/// \param ctor the constructor to call for each element
John McCallf677a8e2011-07-13 06:10:41 +00001539/// \param arrayType the type of the array to initialize
1540/// \param arrayBegin an arrayType*
1541/// \param zeroInitialize true if each element should be
1542/// zero-initialized before it is constructed
Anders Carlsson27da15b2010-01-01 20:29:01 +00001543void
John McCallf677a8e2011-07-13 06:10:41 +00001544CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1545 const ConstantArrayType *arrayType,
1546 llvm::Value *arrayBegin,
1547 CallExpr::const_arg_iterator argBegin,
1548 CallExpr::const_arg_iterator argEnd,
1549 bool zeroInitialize) {
1550 QualType elementType;
1551 llvm::Value *numElements =
1552 emitArrayLength(arrayType, elementType, arrayBegin);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001553
John McCallf677a8e2011-07-13 06:10:41 +00001554 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin,
1555 argBegin, argEnd, zeroInitialize);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001556}
1557
John McCallf677a8e2011-07-13 06:10:41 +00001558/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1559/// constructor for each of several members of an array.
1560///
1561/// \param ctor the constructor to call for each element
1562/// \param numElements the number of elements in the array;
John McCall6549b312011-07-13 07:37:11 +00001563/// may be zero
John McCallf677a8e2011-07-13 06:10:41 +00001564/// \param arrayBegin a T*, where T is the type constructed by ctor
1565/// \param zeroInitialize true if each element should be
1566/// zero-initialized before it is constructed
Anders Carlsson27da15b2010-01-01 20:29:01 +00001567void
John McCallf677a8e2011-07-13 06:10:41 +00001568CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1569 llvm::Value *numElements,
1570 llvm::Value *arrayBegin,
1571 CallExpr::const_arg_iterator argBegin,
1572 CallExpr::const_arg_iterator argEnd,
1573 bool zeroInitialize) {
John McCall6549b312011-07-13 07:37:11 +00001574
1575 // It's legal for numElements to be zero. This can happen both
1576 // dynamically, because x can be zero in 'new A[x]', and statically,
1577 // because of GCC extensions that permit zero-length arrays. There
1578 // are probably legitimate places where we could assume that this
1579 // doesn't happen, but it's not clear that it's worth it.
1580 llvm::BranchInst *zeroCheckBranch = 0;
1581
1582 // Optimize for a constant count.
1583 llvm::ConstantInt *constantCount
1584 = dyn_cast<llvm::ConstantInt>(numElements);
1585 if (constantCount) {
1586 // Just skip out if the constant count is zero.
1587 if (constantCount->isZero()) return;
1588
1589 // Otherwise, emit the check.
1590 } else {
1591 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1592 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1593 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1594 EmitBlock(loopBB);
1595 }
1596
John McCallf677a8e2011-07-13 06:10:41 +00001597 // Find the end of the array.
1598 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1599 "arrayctor.end");
Anders Carlsson27da15b2010-01-01 20:29:01 +00001600
John McCallf677a8e2011-07-13 06:10:41 +00001601 // Enter the loop, setting up a phi for the current location to initialize.
1602 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1603 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1604 EmitBlock(loopBB);
1605 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1606 "arrayctor.cur");
1607 cur->addIncoming(arrayBegin, entryBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001608
Anders Carlsson27da15b2010-01-01 20:29:01 +00001609 // Inside the loop body, emit the constructor call on the array element.
John McCallf677a8e2011-07-13 06:10:41 +00001610
1611 QualType type = getContext().getTypeDeclType(ctor->getParent());
Anders Carlsson27da15b2010-01-01 20:29:01 +00001612
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001613 // Zero initialize the storage, if requested.
John McCallf677a8e2011-07-13 06:10:41 +00001614 if (zeroInitialize)
1615 EmitNullInitialization(cur, type);
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001616
Anders Carlsson27da15b2010-01-01 20:29:01 +00001617 // C++ [class.temporary]p4:
1618 // There are two contexts in which temporaries are destroyed at a different
1619 // point than the end of the full-expression. The first context is when a
1620 // default constructor is called to initialize an element of an array.
1621 // If the constructor has one or more default arguments, the destruction of
1622 // every temporary created in a default argument expression is sequenced
1623 // before the construction of the next array element, if any.
1624
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00001625 {
John McCallbd309292010-07-06 01:34:17 +00001626 RunCleanupsScope Scope(*this);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001627
John McCallf677a8e2011-07-13 06:10:41 +00001628 // Evaluate the constructor and its arguments in a regular
1629 // partial-destroy cleanup.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001630 if (getLangOpts().Exceptions &&
John McCallf677a8e2011-07-13 06:10:41 +00001631 !ctor->getParent()->hasTrivialDestructor()) {
1632 Destroyer *destroyer = destroyCXXObject;
1633 pushRegularPartialArrayCleanup(arrayBegin, cur, type, *destroyer);
1634 }
1635
1636 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/ false,
Douglas Gregor61535002013-01-31 05:50:40 +00001637 /*Delegating=*/false, cur, argBegin, argEnd);
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00001638 }
Anders Carlsson27da15b2010-01-01 20:29:01 +00001639
John McCallf677a8e2011-07-13 06:10:41 +00001640 // Go to the next element.
1641 llvm::Value *next =
1642 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
1643 "arrayctor.next");
1644 cur->addIncoming(next, Builder.GetInsertBlock());
Anders Carlsson27da15b2010-01-01 20:29:01 +00001645
John McCallf677a8e2011-07-13 06:10:41 +00001646 // Check whether that's the end of the loop.
1647 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
1648 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
1649 Builder.CreateCondBr(done, contBB, loopBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001650
John McCall6549b312011-07-13 07:37:11 +00001651 // Patch the earlier check to skip over the loop.
1652 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
1653
John McCallf677a8e2011-07-13 06:10:41 +00001654 EmitBlock(contBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001655}
1656
John McCall82fe67b2011-07-09 01:37:26 +00001657void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
1658 llvm::Value *addr,
1659 QualType type) {
1660 const RecordType *rtype = type->castAs<RecordType>();
1661 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
1662 const CXXDestructorDecl *dtor = record->getDestructor();
1663 assert(!dtor->isTrivial());
1664 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
Douglas Gregor61535002013-01-31 05:50:40 +00001665 /*Delegating=*/false, addr);
John McCall82fe67b2011-07-09 01:37:26 +00001666}
1667
Anders Carlsson27da15b2010-01-01 20:29:01 +00001668void
1669CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
Anders Carlssone11f9ce2010-05-02 23:20:53 +00001670 CXXCtorType Type, bool ForVirtualBase,
Douglas Gregor61535002013-01-31 05:50:40 +00001671 bool Delegating,
Anders Carlsson27da15b2010-01-01 20:29:01 +00001672 llvm::Value *This,
1673 CallExpr::const_arg_iterator ArgBeg,
1674 CallExpr::const_arg_iterator ArgEnd) {
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001675 // If this is a trivial constructor, just emit what's needed.
John McCallca972cd2010-02-06 00:25:16 +00001676 if (D->isTrivial()) {
1677 if (ArgBeg == ArgEnd) {
1678 // Trivial default constructor, no codegen required.
1679 assert(D->isDefaultConstructor() &&
1680 "trivial 0-arg ctor not a default ctor");
Anders Carlsson27da15b2010-01-01 20:29:01 +00001681 return;
1682 }
John McCallca972cd2010-02-06 00:25:16 +00001683
1684 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
Sebastian Redl22653ba2011-08-30 19:58:05 +00001685 assert(D->isCopyOrMoveConstructor() &&
1686 "trivial 1-arg ctor not a copy/move ctor");
John McCallca972cd2010-02-06 00:25:16 +00001687
John McCallca972cd2010-02-06 00:25:16 +00001688 const Expr *E = (*ArgBeg);
1689 QualType Ty = E->getType();
1690 llvm::Value *Src = EmitLValue(E).getAddress();
1691 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001692 return;
1693 }
1694
Reid Kleckner89077a12013-12-17 19:46:40 +00001695 // C++11 [class.mfct.non-static]p2:
1696 // If a non-static member function of a class X is called for an object that
1697 // is not of type X, or of a type derived from X, the behavior is undefined.
1698 // FIXME: Provide a source location here.
1699 EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall, SourceLocation(), This,
1700 getContext().getRecordType(D->getParent()));
1701
1702 CallArgList Args;
1703
1704 // Push the this ptr.
1705 Args.add(RValue::get(This), D->getThisType(getContext()));
1706
1707 // Add the rest of the user-supplied arguments.
1708 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
1709 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
1710
1711 // Insert any ABI-specific implicit constructor arguments.
1712 unsigned ExtraArgs = CGM.getCXXABI().addImplicitConstructorArgs(
1713 *this, D, Type, ForVirtualBase, Delegating, Args);
1714
1715 // Emit the call.
1716 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
1717 RequiredArgs Required = RequiredArgs::forPrototypePlus(FPT, 1 + ExtraArgs);
1718 const CGFunctionInfo &Info =
1719 CGM.getTypes().arrangeCXXMethodCall(Args, FPT, Required);
1720 EmitCall(Info, Callee, ReturnValueSlot(), Args, D);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001721}
1722
John McCallf8ff7b92010-02-23 00:48:20 +00001723void
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001724CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
1725 llvm::Value *This, llvm::Value *Src,
1726 CallExpr::const_arg_iterator ArgBeg,
1727 CallExpr::const_arg_iterator ArgEnd) {
1728 if (D->isTrivial()) {
1729 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
Sebastian Redl22653ba2011-08-30 19:58:05 +00001730 assert(D->isCopyOrMoveConstructor() &&
1731 "trivial 1-arg ctor not a copy/move ctor");
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001732 EmitAggregateCopy(This, Src, (*ArgBeg)->getType());
1733 return;
1734 }
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001735 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, clang::Ctor_Complete);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001736 assert(D->isInstance() &&
1737 "Trying to emit a member call expr on a static method!");
1738
Reid Kleckner739756c2013-12-04 19:23:12 +00001739 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001740
1741 CallArgList Args;
1742
1743 // Push the this ptr.
Eli Friedman43dca6a2011-05-02 17:57:46 +00001744 Args.add(RValue::get(This), D->getThisType(getContext()));
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001745
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001746 // Push the src ptr.
Alp Toker9cacbab2014-01-20 20:26:09 +00001747 QualType QT = *(FPT->param_type_begin());
Chris Lattner2192fe52011-07-18 04:24:23 +00001748 llvm::Type *t = CGM.getTypes().ConvertType(QT);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001749 Src = Builder.CreateBitCast(Src, t);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001750 Args.add(RValue::get(Src), QT);
Reid Kleckner739756c2013-12-04 19:23:12 +00001751
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001752 // Skip over first argument (Src).
Alp Toker9cacbab2014-01-20 20:26:09 +00001753 EmitCallArgs(Args, FPT->isVariadic(), FPT->param_type_begin() + 1,
1754 FPT->param_type_end(), ArgBeg + 1, ArgEnd);
Reid Kleckner739756c2013-12-04 19:23:12 +00001755
John McCall8dda7b22012-07-07 06:41:13 +00001756 EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, RequiredArgs::All),
1757 Callee, ReturnValueSlot(), Args, D);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001758}
1759
1760void
John McCallf8ff7b92010-02-23 00:48:20 +00001761CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1762 CXXCtorType CtorType,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001763 const FunctionArgList &Args,
1764 SourceLocation Loc) {
John McCallf8ff7b92010-02-23 00:48:20 +00001765 CallArgList DelegateArgs;
1766
1767 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
1768 assert(I != E && "no parameters to constructor");
1769
1770 // this
Eli Friedman43dca6a2011-05-02 17:57:46 +00001771 DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType());
John McCallf8ff7b92010-02-23 00:48:20 +00001772 ++I;
1773
1774 // vtt
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001775 if (llvm::Value *VTT = GetVTTParameter(GlobalDecl(Ctor, CtorType),
Douglas Gregor61535002013-01-31 05:50:40 +00001776 /*ForVirtualBase=*/false,
1777 /*Delegating=*/true)) {
John McCallf8ff7b92010-02-23 00:48:20 +00001778 QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001779 DelegateArgs.add(RValue::get(VTT), VoidPP);
John McCallf8ff7b92010-02-23 00:48:20 +00001780
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001781 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
John McCallf8ff7b92010-02-23 00:48:20 +00001782 assert(I != E && "cannot skip vtt parameter, already done with args");
John McCalla738c252011-03-09 04:27:21 +00001783 assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
John McCallf8ff7b92010-02-23 00:48:20 +00001784 ++I;
1785 }
1786 }
1787
1788 // Explicit arguments.
1789 for (; I != E; ++I) {
John McCall32ea9692011-03-11 20:59:21 +00001790 const VarDecl *param = *I;
Nick Lewycky2d84e842013-10-02 02:29:49 +00001791 // FIXME: per-argument source location
1792 EmitDelegateCallArg(DelegateArgs, param, Loc);
John McCallf8ff7b92010-02-23 00:48:20 +00001793 }
1794
Manman Ren01754612013-03-20 16:59:38 +00001795 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(Ctor, CtorType);
John McCalla729c622012-02-17 03:33:10 +00001796 EmitCall(CGM.getTypes().arrangeCXXConstructorDeclaration(Ctor, CtorType),
Manman Ren01754612013-03-20 16:59:38 +00001797 Callee, ReturnValueSlot(), DelegateArgs, Ctor);
John McCallf8ff7b92010-02-23 00:48:20 +00001798}
1799
Alexis Hunt9d47faf2011-05-03 23:05:34 +00001800namespace {
1801 struct CallDelegatingCtorDtor : EHScopeStack::Cleanup {
1802 const CXXDestructorDecl *Dtor;
1803 llvm::Value *Addr;
1804 CXXDtorType Type;
1805
1806 CallDelegatingCtorDtor(const CXXDestructorDecl *D, llvm::Value *Addr,
1807 CXXDtorType Type)
1808 : Dtor(D), Addr(Addr), Type(Type) {}
1809
John McCall30317fd2011-07-12 20:27:29 +00001810 void Emit(CodeGenFunction &CGF, Flags flags) {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00001811 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
Douglas Gregor61535002013-01-31 05:50:40 +00001812 /*Delegating=*/true, Addr);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00001813 }
1814 };
1815}
1816
Alexis Hunt61bc1732011-05-01 07:04:31 +00001817void
1818CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
1819 const FunctionArgList &Args) {
1820 assert(Ctor->isDelegatingConstructor());
1821
1822 llvm::Value *ThisPtr = LoadCXXThis();
1823
Eli Friedmanc1d85b92011-12-03 00:54:26 +00001824 QualType Ty = getContext().getTagDeclType(Ctor->getParent());
Eli Friedman38cd36d2011-12-03 02:13:40 +00001825 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
John McCall31168b02011-06-15 23:02:42 +00001826 AggValueSlot AggSlot =
Eli Friedmanc1d85b92011-12-03 00:54:26 +00001827 AggValueSlot::forAddr(ThisPtr, Alignment, Qualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +00001828 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001829 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001830 AggValueSlot::IsNotAliased);
Alexis Hunt61bc1732011-05-01 07:04:31 +00001831
1832 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
Alexis Hunt61bc1732011-05-01 07:04:31 +00001833
Alexis Hunt9d47faf2011-05-03 23:05:34 +00001834 const CXXRecordDecl *ClassDecl = Ctor->getParent();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001835 if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00001836 CXXDtorType Type =
1837 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
1838
1839 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
1840 ClassDecl->getDestructor(),
1841 ThisPtr, Type);
1842 }
1843}
Alexis Hunt61bc1732011-05-01 07:04:31 +00001844
Anders Carlsson27da15b2010-01-01 20:29:01 +00001845void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
1846 CXXDtorType Type,
Anders Carlssonf8a71f02010-05-02 23:29:11 +00001847 bool ForVirtualBase,
Douglas Gregor61535002013-01-31 05:50:40 +00001848 bool Delegating,
Anders Carlsson27da15b2010-01-01 20:29:01 +00001849 llvm::Value *This) {
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001850 CGM.getCXXABI().EmitDestructorCall(*this, DD, Type, ForVirtualBase,
1851 Delegating, This);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001852}
1853
John McCall53cad2e2010-07-21 01:41:18 +00001854namespace {
John McCallcda666c2010-07-21 07:22:38 +00001855 struct CallLocalDtor : EHScopeStack::Cleanup {
John McCall53cad2e2010-07-21 01:41:18 +00001856 const CXXDestructorDecl *Dtor;
1857 llvm::Value *Addr;
1858
1859 CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
1860 : Dtor(D), Addr(Addr) {}
1861
John McCall30317fd2011-07-12 20:27:29 +00001862 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall53cad2e2010-07-21 01:41:18 +00001863 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +00001864 /*ForVirtualBase=*/false,
1865 /*Delegating=*/false, Addr);
John McCall53cad2e2010-07-21 01:41:18 +00001866 }
1867 };
1868}
1869
John McCall8680f872010-07-21 06:29:51 +00001870void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
1871 llvm::Value *Addr) {
John McCallcda666c2010-07-21 07:22:38 +00001872 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
John McCall8680f872010-07-21 06:29:51 +00001873}
1874
John McCallbd309292010-07-06 01:34:17 +00001875void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
1876 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
1877 if (!ClassDecl) return;
1878 if (ClassDecl->hasTrivialDestructor()) return;
1879
1880 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCalla85af562011-04-28 02:15:35 +00001881 assert(D && D->isUsed() && "destructor not marked as used!");
John McCall8680f872010-07-21 06:29:51 +00001882 PushDestructorCleanup(D, Addr);
John McCallbd309292010-07-06 01:34:17 +00001883}
1884
Anders Carlssone87fae92010-03-28 19:40:00 +00001885void
1886CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
Anders Carlsson652758c2010-04-20 05:22:15 +00001887 const CXXRecordDecl *NearestVBase,
Ken Dyck3fb4c892011-03-23 01:04:18 +00001888 CharUnits OffsetFromNearestVBase,
Anders Carlssone87fae92010-03-28 19:40:00 +00001889 const CXXRecordDecl *VTableClass) {
Anders Carlssone87fae92010-03-28 19:40:00 +00001890 // Compute the address point.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001891 bool NeedsVirtualOffset;
1892 llvm::Value *VTableAddressPoint =
1893 CGM.getCXXABI().getVTableAddressPointInStructor(
1894 *this, VTableClass, Base, NearestVBase, NeedsVirtualOffset);
1895 if (!VTableAddressPoint)
1896 return;
Anders Carlssone87fae92010-03-28 19:40:00 +00001897
Anders Carlsson6a0227d2010-04-20 16:22:16 +00001898 // Compute where to store the address point.
Anders Carlssonc58fb552010-05-03 00:29:58 +00001899 llvm::Value *VirtualOffset = 0;
Ken Dyckcfc332c2011-03-23 00:45:26 +00001900 CharUnits NonVirtualOffset = CharUnits::Zero();
Anders Carlsson91baecf2010-04-20 18:05:10 +00001901
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001902 if (NeedsVirtualOffset) {
Anders Carlsson91baecf2010-04-20 18:05:10 +00001903 // We need to use the virtual base offset offset because the virtual base
1904 // might have a different offset in the most derived class.
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001905 VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(*this,
1906 LoadCXXThis(),
1907 VTableClass,
1908 NearestVBase);
Ken Dyck3fb4c892011-03-23 01:04:18 +00001909 NonVirtualOffset = OffsetFromNearestVBase;
Anders Carlsson91baecf2010-04-20 18:05:10 +00001910 } else {
Anders Carlssonc58fb552010-05-03 00:29:58 +00001911 // We can just use the base offset in the complete class.
Ken Dyck16ffcac2011-03-24 01:21:01 +00001912 NonVirtualOffset = Base.getBaseOffset();
Anders Carlsson91baecf2010-04-20 18:05:10 +00001913 }
Anders Carlssonc58fb552010-05-03 00:29:58 +00001914
1915 // Apply the offsets.
1916 llvm::Value *VTableField = LoadCXXThis();
1917
Ken Dyckcfc332c2011-03-23 00:45:26 +00001918 if (!NonVirtualOffset.isZero() || VirtualOffset)
Anders Carlssonc58fb552010-05-03 00:29:58 +00001919 VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
1920 NonVirtualOffset,
1921 VirtualOffset);
Anders Carlsson6a0227d2010-04-20 16:22:16 +00001922
Anders Carlssone87fae92010-03-28 19:40:00 +00001923 // Finally, store the address point.
Chris Lattner2192fe52011-07-18 04:24:23 +00001924 llvm::Type *AddressPointPtrTy =
Anders Carlssone87fae92010-03-28 19:40:00 +00001925 VTableAddressPoint->getType()->getPointerTo();
1926 VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
Kostya Serebryany141e46f2012-03-26 17:03:51 +00001927 llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
1928 CGM.DecorateInstruction(Store, CGM.getTBAAInfoForVTablePtr());
Anders Carlssone87fae92010-03-28 19:40:00 +00001929}
1930
Anders Carlssond5895932010-03-28 21:07:49 +00001931void
1932CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
Anders Carlsson652758c2010-04-20 05:22:15 +00001933 const CXXRecordDecl *NearestVBase,
Ken Dyck3fb4c892011-03-23 01:04:18 +00001934 CharUnits OffsetFromNearestVBase,
Anders Carlssond5895932010-03-28 21:07:49 +00001935 bool BaseIsNonVirtualPrimaryBase,
Anders Carlssond5895932010-03-28 21:07:49 +00001936 const CXXRecordDecl *VTableClass,
1937 VisitedVirtualBasesSetTy& VBases) {
1938 // If this base is a non-virtual primary base the address point has already
1939 // been set.
1940 if (!BaseIsNonVirtualPrimaryBase) {
1941 // Initialize the vtable pointer for this base.
Anders Carlssonc4d0d0f2010-05-03 00:07:07 +00001942 InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
Timur Iskhodzhanovd8fa10d2013-08-21 17:33:16 +00001943 VTableClass);
Anders Carlssond5895932010-03-28 21:07:49 +00001944 }
1945
1946 const CXXRecordDecl *RD = Base.getBase();
1947
1948 // Traverse bases.
1949 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1950 E = RD->bases_end(); I != E; ++I) {
1951 CXXRecordDecl *BaseDecl
1952 = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1953
1954 // Ignore classes without a vtable.
1955 if (!BaseDecl->isDynamicClass())
1956 continue;
1957
Ken Dyck3fb4c892011-03-23 01:04:18 +00001958 CharUnits BaseOffset;
1959 CharUnits BaseOffsetFromNearestVBase;
Anders Carlsson948d3f42010-03-29 01:16:41 +00001960 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlssond5895932010-03-28 21:07:49 +00001961
1962 if (I->isVirtual()) {
1963 // Check if we've visited this virtual base before.
1964 if (!VBases.insert(BaseDecl))
1965 continue;
1966
1967 const ASTRecordLayout &Layout =
1968 getContext().getASTRecordLayout(VTableClass);
1969
Ken Dyck3fb4c892011-03-23 01:04:18 +00001970 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
1971 BaseOffsetFromNearestVBase = CharUnits::Zero();
Anders Carlsson948d3f42010-03-29 01:16:41 +00001972 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlssond5895932010-03-28 21:07:49 +00001973 } else {
1974 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1975
Ken Dyck16ffcac2011-03-24 01:21:01 +00001976 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
Anders Carlssonc4d0d0f2010-05-03 00:07:07 +00001977 BaseOffsetFromNearestVBase =
Ken Dyck3fb4c892011-03-23 01:04:18 +00001978 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson948d3f42010-03-29 01:16:41 +00001979 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlssond5895932010-03-28 21:07:49 +00001980 }
1981
Ken Dyck16ffcac2011-03-24 01:21:01 +00001982 InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
Anders Carlsson652758c2010-04-20 05:22:15 +00001983 I->isVirtual() ? BaseDecl : NearestVBase,
Anders Carlssonc4d0d0f2010-05-03 00:07:07 +00001984 BaseOffsetFromNearestVBase,
Anders Carlsson948d3f42010-03-29 01:16:41 +00001985 BaseDeclIsNonVirtualPrimaryBase,
Timur Iskhodzhanovd8fa10d2013-08-21 17:33:16 +00001986 VTableClass, VBases);
Anders Carlssond5895932010-03-28 21:07:49 +00001987 }
1988}
1989
1990void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
1991 // Ignore classes without a vtable.
Anders Carlsson1f9348c2010-03-26 04:39:42 +00001992 if (!RD->isDynamicClass())
Anders Carlsson27da15b2010-01-01 20:29:01 +00001993 return;
1994
Anders Carlssond5895932010-03-28 21:07:49 +00001995 // Initialize the vtable pointers for this class and all of its bases.
1996 VisitedVirtualBasesSetTy VBases;
Ken Dyck16ffcac2011-03-24 01:21:01 +00001997 InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()),
1998 /*NearestVBase=*/0,
Ken Dyck3fb4c892011-03-23 01:04:18 +00001999 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
Timur Iskhodzhanovd8fa10d2013-08-21 17:33:16 +00002000 /*BaseIsNonVirtualPrimaryBase=*/false, RD, VBases);
Timur Iskhodzhanovb6487322013-10-09 18:16:58 +00002001
2002 if (RD->getNumVBases())
2003 CGM.getCXXABI().initializeHiddenVirtualInheritanceMembers(*this, RD);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002004}
Dan Gohman8fc50c22010-10-26 18:44:08 +00002005
2006llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
Chris Lattner2192fe52011-07-18 04:24:23 +00002007 llvm::Type *Ty) {
Dan Gohman8fc50c22010-10-26 18:44:08 +00002008 llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002009 llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
2010 CGM.DecorateInstruction(VTable, CGM.getTBAAInfoForVTablePtr());
2011 return VTable;
Dan Gohman8fc50c22010-10-26 18:44:08 +00002012}
Anders Carlssonc36783e2011-05-08 20:32:23 +00002013
Anders Carlssonc36783e2011-05-08 20:32:23 +00002014
2015// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
2016// quite what we want.
2017static const Expr *skipNoOpCastsAndParens(const Expr *E) {
2018 while (true) {
2019 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
2020 E = PE->getSubExpr();
2021 continue;
2022 }
2023
2024 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
2025 if (CE->getCastKind() == CK_NoOp) {
2026 E = CE->getSubExpr();
2027 continue;
2028 }
2029 }
2030 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2031 if (UO->getOpcode() == UO_Extension) {
2032 E = UO->getSubExpr();
2033 continue;
2034 }
2035 }
2036 return E;
2037 }
2038}
2039
Benjamin Kramer7463ed72013-08-25 22:46:27 +00002040bool
2041CodeGenFunction::CanDevirtualizeMemberFunctionCall(const Expr *Base,
2042 const CXXMethodDecl *MD) {
2043 // When building with -fapple-kext, all calls must go through the vtable since
2044 // the kernel linker can do runtime patching of vtables.
2045 if (getLangOpts().AppleKext)
2046 return false;
2047
Anders Carlssonc36783e2011-05-08 20:32:23 +00002048 // If the most derived class is marked final, we know that no subclass can
2049 // override this member function and so we can devirtualize it. For example:
2050 //
2051 // struct A { virtual void f(); }
2052 // struct B final : A { };
2053 //
2054 // void f(B *b) {
2055 // b->f();
2056 // }
2057 //
Benjamin Kramer7463ed72013-08-25 22:46:27 +00002058 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
Anders Carlssonc36783e2011-05-08 20:32:23 +00002059 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
2060 return true;
2061
2062 // If the member function is marked 'final', we know that it can't be
2063 // overridden and can therefore devirtualize it.
2064 if (MD->hasAttr<FinalAttr>())
2065 return true;
2066
2067 // Similarly, if the class itself is marked 'final' it can't be overridden
2068 // and we can therefore devirtualize the member function call.
2069 if (MD->getParent()->hasAttr<FinalAttr>())
2070 return true;
2071
2072 Base = skipNoOpCastsAndParens(Base);
2073 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
2074 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
2075 // This is a record decl. We know the type and can devirtualize it.
2076 return VD->getType()->isRecordType();
2077 }
2078
2079 return false;
2080 }
Benjamin Kramer7463ed72013-08-25 22:46:27 +00002081
2082 // We can devirtualize calls on an object accessed by a class member access
2083 // expression, since by C++11 [basic.life]p6 we know that it can't refer to
2084 // a derived class object constructed in the same location.
2085 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Base))
2086 if (const ValueDecl *VD = dyn_cast<ValueDecl>(ME->getMemberDecl()))
2087 return VD->getType()->isRecordType();
2088
Anders Carlssonc36783e2011-05-08 20:32:23 +00002089 // We can always devirtualize calls on temporary object expressions.
2090 if (isa<CXXConstructExpr>(Base))
2091 return true;
2092
2093 // And calls on bound temporaries.
2094 if (isa<CXXBindTemporaryExpr>(Base))
2095 return true;
2096
2097 // Check if this is a call expr that returns a record type.
2098 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
2099 return CE->getCallReturnType()->isRecordType();
2100
2101 // We can't devirtualize the call.
2102 return false;
2103}
2104
Anders Carlssonc36783e2011-05-08 20:32:23 +00002105llvm::Value *
2106CodeGenFunction::EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E,
2107 const CXXMethodDecl *MD,
2108 llvm::Value *This) {
John McCalla729c622012-02-17 03:33:10 +00002109 llvm::FunctionType *fnType =
2110 CGM.getTypes().GetFunctionType(
2111 CGM.getTypes().arrangeCXXMethodDeclaration(MD));
Anders Carlssonc36783e2011-05-08 20:32:23 +00002112
Benjamin Kramer7463ed72013-08-25 22:46:27 +00002113 if (MD->isVirtual() && !CanDevirtualizeMemberFunctionCall(E->getArg(0), MD))
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00002114 return CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, fnType);
Anders Carlssonc36783e2011-05-08 20:32:23 +00002115
John McCalla729c622012-02-17 03:33:10 +00002116 return CGM.GetAddrOfFunction(MD, fnType);
Anders Carlssonc36783e2011-05-08 20:32:23 +00002117}
Eli Friedman5a6d5072012-02-16 01:37:33 +00002118
Faisal Vali571df122013-09-29 08:45:24 +00002119void CodeGenFunction::EmitForwardingCallToLambda(
2120 const CXXMethodDecl *callOperator,
2121 CallArgList &callArgs) {
Eli Friedman5b446882012-02-16 03:47:28 +00002122 // Get the address of the call operator.
John McCall8dda7b22012-07-07 06:41:13 +00002123 const CGFunctionInfo &calleeFnInfo =
2124 CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
2125 llvm::Value *callee =
2126 CGM.GetAddrOfFunction(GlobalDecl(callOperator),
2127 CGM.getTypes().GetFunctionType(calleeFnInfo));
Eli Friedman5b446882012-02-16 03:47:28 +00002128
John McCall8dda7b22012-07-07 06:41:13 +00002129 // Prepare the return slot.
2130 const FunctionProtoType *FPT =
2131 callOperator->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00002132 QualType resultType = FPT->getReturnType();
John McCall8dda7b22012-07-07 06:41:13 +00002133 ReturnValueSlot returnSlot;
2134 if (!resultType->isVoidType() &&
2135 calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
John McCall47fb9502013-03-07 21:37:08 +00002136 !hasScalarEvaluationKind(calleeFnInfo.getReturnType()))
John McCall8dda7b22012-07-07 06:41:13 +00002137 returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
2138
2139 // We don't need to separately arrange the call arguments because
2140 // the call can't be variadic anyway --- it's impossible to forward
2141 // variadic arguments.
Eli Friedman5b446882012-02-16 03:47:28 +00002142
2143 // Now emit our call.
John McCall8dda7b22012-07-07 06:41:13 +00002144 RValue RV = EmitCall(calleeFnInfo, callee, returnSlot,
2145 callArgs, callOperator);
Eli Friedman5b446882012-02-16 03:47:28 +00002146
John McCall8dda7b22012-07-07 06:41:13 +00002147 // If necessary, copy the returned value into the slot.
2148 if (!resultType->isVoidType() && returnSlot.isNull())
2149 EmitReturnOfRValue(RV, resultType);
Eli Friedmanf5f4d2f2012-12-13 23:37:17 +00002150 else
2151 EmitBranchThroughCleanup(ReturnBlock);
Eli Friedman5b446882012-02-16 03:47:28 +00002152}
2153
Eli Friedman2495ab02012-02-25 02:48:22 +00002154void CodeGenFunction::EmitLambdaBlockInvokeBody() {
2155 const BlockDecl *BD = BlockInfo->getBlockDecl();
2156 const VarDecl *variable = BD->capture_begin()->getVariable();
2157 const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
2158
2159 // Start building arguments for forwarding call
2160 CallArgList CallArgs;
2161
2162 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2163 llvm::Value *ThisPtr = GetAddrOfBlockDecl(variable, false);
2164 CallArgs.add(RValue::get(ThisPtr), ThisType);
2165
2166 // Add the rest of the parameters.
2167 for (BlockDecl::param_const_iterator I = BD->param_begin(),
2168 E = BD->param_end(); I != E; ++I) {
2169 ParmVarDecl *param = *I;
Nick Lewycky2d84e842013-10-02 02:29:49 +00002170 EmitDelegateCallArg(CallArgs, param, param->getLocStart());
Eli Friedman2495ab02012-02-25 02:48:22 +00002171 }
Faisal Vali571df122013-09-29 08:45:24 +00002172 assert(!Lambda->isGenericLambda() &&
2173 "generic lambda interconversion to block not implemented");
2174 EmitForwardingCallToLambda(Lambda->getLambdaCallOperator(), CallArgs);
Eli Friedman2495ab02012-02-25 02:48:22 +00002175}
2176
2177void CodeGenFunction::EmitLambdaToBlockPointerBody(FunctionArgList &Args) {
John McCalldec348f72013-05-03 07:33:41 +00002178 if (cast<CXXMethodDecl>(CurCodeDecl)->isVariadic()) {
Eli Friedman2495ab02012-02-25 02:48:22 +00002179 // FIXME: Making this work correctly is nasty because it requires either
2180 // cloning the body of the call operator or making the call operator forward.
John McCalldec348f72013-05-03 07:33:41 +00002181 CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function");
Eli Friedman2495ab02012-02-25 02:48:22 +00002182 return;
2183 }
2184
Richard Smithb47c36f2013-11-05 09:12:18 +00002185 EmitFunctionBody(Args, cast<FunctionDecl>(CurGD.getDecl())->getBody());
Eli Friedman2495ab02012-02-25 02:48:22 +00002186}
2187
2188void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
2189 const CXXRecordDecl *Lambda = MD->getParent();
2190
2191 // Start building arguments for forwarding call
2192 CallArgList CallArgs;
2193
2194 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2195 llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
2196 CallArgs.add(RValue::get(ThisPtr), ThisType);
2197
2198 // Add the rest of the parameters.
2199 for (FunctionDecl::param_const_iterator I = MD->param_begin(),
2200 E = MD->param_end(); I != E; ++I) {
2201 ParmVarDecl *param = *I;
Nick Lewycky2d84e842013-10-02 02:29:49 +00002202 EmitDelegateCallArg(CallArgs, param, param->getLocStart());
Eli Friedman2495ab02012-02-25 02:48:22 +00002203 }
Faisal Vali571df122013-09-29 08:45:24 +00002204 const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
2205 // For a generic lambda, find the corresponding call operator specialization
2206 // to which the call to the static-invoker shall be forwarded.
2207 if (Lambda->isGenericLambda()) {
2208 assert(MD->isFunctionTemplateSpecialization());
2209 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
2210 FunctionTemplateDecl *CallOpTemplate = CallOp->getDescribedFunctionTemplate();
2211 void *InsertPos = 0;
2212 FunctionDecl *CorrespondingCallOpSpecialization =
2213 CallOpTemplate->findSpecialization(TAL->data(), TAL->size(), InsertPos);
2214 assert(CorrespondingCallOpSpecialization);
2215 CallOp = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
2216 }
2217 EmitForwardingCallToLambda(CallOp, CallArgs);
Eli Friedman2495ab02012-02-25 02:48:22 +00002218}
2219
Douglas Gregor355efbb2012-02-17 03:02:34 +00002220void CodeGenFunction::EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD) {
2221 if (MD->isVariadic()) {
Eli Friedman5b446882012-02-16 03:47:28 +00002222 // FIXME: Making this work correctly is nasty because it requires either
2223 // cloning the body of the call operator or making the call operator forward.
2224 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
Eli Friedman2495ab02012-02-25 02:48:22 +00002225 return;
Eli Friedman5b446882012-02-16 03:47:28 +00002226 }
2227
Douglas Gregor355efbb2012-02-17 03:02:34 +00002228 EmitLambdaDelegatingInvokeBody(MD);
Eli Friedman5a6d5072012-02-16 01:37:33 +00002229}