blob: 8138c6fc8d23fd7fde80daf6c681c5d7ce5e9499 [file] [log] [blame]
Anders Carlsson5b955922009-11-24 05:51:11 +00001//===--- CGClass.cpp - Emit LLVM Code for C++ classes ---------------------===//
Anders Carlsson5d58a1d2009-09-12 04:27:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with C++ code generation of classes
11//
12//===----------------------------------------------------------------------===//
13
Eli Friedman64bee652012-02-25 02:48:22 +000014#include "CGBlocks.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070015#include "CGCXXABI.h"
Devang Pateld67ef0e2010-08-11 21:04:37 +000016#include "CGDebugInfo.h"
Lang Hames56c00c42013-02-17 07:22:09 +000017#include "CGRecordLayout.h"
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000018#include "CodeGenFunction.h"
Anders Carlsson2f1986b2009-10-06 22:43:30 +000019#include "clang/AST/CXXInheritance.h"
Faisal Valid6992ab2013-09-29 08:45:24 +000020#include "clang/AST/DeclTemplate.h"
John McCall7e1dff72010-09-17 02:31:44 +000021#include "clang/AST/EvaluatedExprVisitor.h"
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000022#include "clang/AST/RecordLayout.h"
John McCall9fc6a772010-02-19 09:25:03 +000023#include "clang/AST/StmtCXX.h"
Lang Hames56c00c42013-02-17 07:22:09 +000024#include "clang/Basic/TargetBuiltins.h"
Mark Lacey8b549992013-10-30 21:53:58 +000025#include "clang/CodeGen/CGFunctionInfo.h"
Devang Patel3ee36af2011-02-22 20:55:26 +000026#include "clang/Frontend/CodeGenOptions.h"
Anders Carlsson2f1986b2009-10-06 22:43:30 +000027
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000028using namespace clang;
29using namespace CodeGen;
30
Ken Dyck55c02582011-03-22 00:53:26 +000031static CharUnits
Anders Carlsson34a2d382010-04-24 21:06:20 +000032ComputeNonVirtualBaseClassOffset(ASTContext &Context,
33 const CXXRecordDecl *DerivedClass,
John McCallf871d0c2010-08-07 06:22:56 +000034 CastExpr::path_const_iterator Start,
35 CastExpr::path_const_iterator End) {
Ken Dyck55c02582011-03-22 00:53:26 +000036 CharUnits Offset = CharUnits::Zero();
Anders Carlsson34a2d382010-04-24 21:06:20 +000037
38 const CXXRecordDecl *RD = DerivedClass;
39
John McCallf871d0c2010-08-07 06:22:56 +000040 for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
Anders Carlsson34a2d382010-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 Dyck55c02582011-03-22 00:53:26 +000051 Offset += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson34a2d382010-04-24 21:06:20 +000052
53 RD = BaseDecl;
54 }
55
Ken Dyck55c02582011-03-22 00:53:26 +000056 return Offset;
Anders Carlsson34a2d382010-04-24 21:06:20 +000057}
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000058
Anders Carlsson84080ec2009-09-29 03:13:20 +000059llvm::Constant *
Anders Carlssona04efdf2010-04-24 21:23:59 +000060CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
John McCallf871d0c2010-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 Carlssona04efdf2010-04-24 21:23:59 +000064
Ken Dyck55c02582011-03-22 00:53:26 +000065 CharUnits Offset =
John McCallf871d0c2010-08-07 06:22:56 +000066 ComputeNonVirtualBaseClassOffset(getContext(), ClassDecl,
67 PathBegin, PathEnd);
Ken Dyck55c02582011-03-22 00:53:26 +000068 if (Offset.isZero())
Stephen Hines6bcf27b2014-05-29 04:14:42 -070069 return nullptr;
70
Chris Lattner2acc6e32011-07-18 04:24:23 +000071 llvm::Type *PtrDiffTy =
Anders Carlssona04efdf2010-04-24 21:23:59 +000072 Types.ConvertType(getContext().getPointerDiffType());
73
Ken Dyck55c02582011-03-22 00:53:26 +000074 return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
Anders Carlsson84080ec2009-09-29 03:13:20 +000075}
76
Anders Carlsson8561a862010-04-24 23:01:49 +000077/// Gets the address of a direct base class within a complete object.
John McCallbff225e2010-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 Carlsson8561a862010-04-24 23:01:49 +000083CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(llvm::Value *This,
84 const CXXRecordDecl *Derived,
85 const CXXRecordDecl *Base,
86 bool BaseIsVirtual) {
John McCallbff225e2010-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 Dyck5fff46b2011-03-22 01:21:15 +000093 CharUnits Offset;
John McCallbff225e2010-02-16 04:15:37 +000094 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
Anders Carlsson8561a862010-04-24 23:01:49 +000095 if (BaseIsVirtual)
Ken Dyck5fff46b2011-03-22 01:21:15 +000096 Offset = Layout.getVBaseClassOffset(Base);
John McCallbff225e2010-02-16 04:15:37 +000097 else
Ken Dyck5fff46b2011-03-22 01:21:15 +000098 Offset = Layout.getBaseClassOffset(Base);
John McCallbff225e2010-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 Dyck5fff46b2011-03-22 01:21:15 +0000103 if (Offset.isPositive()) {
John McCallbff225e2010-02-16 04:15:37 +0000104 V = Builder.CreateBitCast(V, Int8PtrTy);
Ken Dyck5fff46b2011-03-22 01:21:15 +0000105 V = Builder.CreateConstInBoundsGEP1_64(V, Offset.getQuantity());
John McCallbff225e2010-02-16 04:15:37 +0000106 }
107 V = Builder.CreateBitCast(V, ConvertType(Base)->getPointerTo());
108
109 return V;
Anders Carlssond103f9f2010-03-28 19:40:00 +0000110}
John McCallbff225e2010-02-16 04:15:37 +0000111
Anders Carlsson9dc228a2010-04-20 16:03:35 +0000112static llvm::Value *
John McCall7916c992012-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.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700117 assert(!nonVirtualOffset.isZero() || virtualOffset != nullptr);
John McCall7916c992012-08-01 05:04:58 +0000118
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 Carlsson9dc228a2010-04-20 16:03:35 +0000130
131 // Apply the base offset.
John McCall7916c992012-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 Carlsson9dc228a2010-04-20 16:03:35 +0000135}
136
Stephen Hines176edba2014-12-01 14:53:08 -0800137llvm::Value *CodeGenFunction::GetAddressOfBaseClass(
138 llvm::Value *Value, const CXXRecordDecl *Derived,
139 CastExpr::path_const_iterator PathBegin,
140 CastExpr::path_const_iterator PathEnd, bool NullCheckValue,
141 SourceLocation Loc) {
John McCallf871d0c2010-08-07 06:22:56 +0000142 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlsson34a2d382010-04-24 21:06:20 +0000143
John McCallf871d0c2010-08-07 06:22:56 +0000144 CastExpr::path_const_iterator Start = PathBegin;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700145 const CXXRecordDecl *VBase = nullptr;
146
John McCall7916c992012-08-01 05:04:58 +0000147 // Sema has done some convenient canonicalization here: if the
148 // access path involved any virtual steps, the conversion path will
149 // *start* with a step down to the correct virtual base subobject,
150 // and hence will not require any further steps.
Anders Carlsson34a2d382010-04-24 21:06:20 +0000151 if ((*Start)->isVirtual()) {
152 VBase =
153 cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
154 ++Start;
155 }
John McCall7916c992012-08-01 05:04:58 +0000156
157 // Compute the static offset of the ultimate destination within its
158 // allocating subobject (the virtual base, if there is one, or else
159 // the "complete" object that we see).
Ken Dyck55c02582011-03-22 00:53:26 +0000160 CharUnits NonVirtualOffset =
Anders Carlsson8561a862010-04-24 23:01:49 +0000161 ComputeNonVirtualBaseClassOffset(getContext(), VBase ? VBase : Derived,
John McCallf871d0c2010-08-07 06:22:56 +0000162 Start, PathEnd);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000163
John McCall7916c992012-08-01 05:04:58 +0000164 // If there's a virtual step, we can sometimes "devirtualize" it.
165 // For now, that's limited to when the derived type is final.
166 // TODO: "devirtualize" this for accesses to known-complete objects.
167 if (VBase && Derived->hasAttr<FinalAttr>()) {
168 const ASTRecordLayout &layout = getContext().getASTRecordLayout(Derived);
169 CharUnits vBaseOffset = layout.getVBaseClassOffset(VBase);
170 NonVirtualOffset += vBaseOffset;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700171 VBase = nullptr; // we no longer have a virtual step
John McCall7916c992012-08-01 05:04:58 +0000172 }
173
Anders Carlsson34a2d382010-04-24 21:06:20 +0000174 // Get the base pointer type.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000175 llvm::Type *BasePtrTy =
John McCallf871d0c2010-08-07 06:22:56 +0000176 ConvertType((PathEnd[-1])->getType())->getPointerTo();
John McCall7916c992012-08-01 05:04:58 +0000177
Stephen Hines176edba2014-12-01 14:53:08 -0800178 QualType DerivedTy = getContext().getRecordType(Derived);
179 CharUnits DerivedAlign = getContext().getTypeAlignInChars(DerivedTy);
180
John McCall7916c992012-08-01 05:04:58 +0000181 // If the static offset is zero and we don't have a virtual step,
182 // just do a bitcast; null checks are unnecessary.
Ken Dyck55c02582011-03-22 00:53:26 +0000183 if (NonVirtualOffset.isZero() && !VBase) {
Stephen Hines176edba2014-12-01 14:53:08 -0800184 if (sanitizePerformTypeCheck()) {
185 EmitTypeCheck(TCK_Upcast, Loc, Value, DerivedTy, DerivedAlign,
186 !NullCheckValue);
187 }
Anders Carlsson34a2d382010-04-24 21:06:20 +0000188 return Builder.CreateBitCast(Value, BasePtrTy);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700189 }
John McCall7916c992012-08-01 05:04:58 +0000190
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700191 llvm::BasicBlock *origBB = nullptr;
192 llvm::BasicBlock *endBB = nullptr;
193
John McCall7916c992012-08-01 05:04:58 +0000194 // Skip over the offset (and the vtable load) if we're supposed to
195 // null-check the pointer.
Anders Carlsson34a2d382010-04-24 21:06:20 +0000196 if (NullCheckValue) {
John McCall7916c992012-08-01 05:04:58 +0000197 origBB = Builder.GetInsertBlock();
198 llvm::BasicBlock *notNullBB = createBasicBlock("cast.notnull");
199 endBB = createBasicBlock("cast.end");
Anders Carlsson34a2d382010-04-24 21:06:20 +0000200
John McCall7916c992012-08-01 05:04:58 +0000201 llvm::Value *isNull = Builder.CreateIsNull(Value);
202 Builder.CreateCondBr(isNull, endBB, notNullBB);
203 EmitBlock(notNullBB);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000204 }
205
Stephen Hines176edba2014-12-01 14:53:08 -0800206 if (sanitizePerformTypeCheck()) {
207 EmitTypeCheck(VBase ? TCK_UpcastToVirtualBase : TCK_Upcast, Loc, Value,
208 DerivedTy, DerivedAlign, true);
209 }
210
John McCall7916c992012-08-01 05:04:58 +0000211 // Compute the virtual offset.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700212 llvm::Value *VirtualOffset = nullptr;
Anders Carlsson336a7dc2011-01-29 03:18:56 +0000213 if (VBase) {
Reid Klecknerb0f533e2013-05-29 18:02:47 +0000214 VirtualOffset =
215 CGM.getCXXABI().GetVirtualBaseClassOffset(*this, Value, Derived, VBase);
Anders Carlsson336a7dc2011-01-29 03:18:56 +0000216 }
Anders Carlsson34a2d382010-04-24 21:06:20 +0000217
John McCall7916c992012-08-01 05:04:58 +0000218 // Apply both offsets.
Ken Dyck55c02582011-03-22 00:53:26 +0000219 Value = ApplyNonVirtualAndVirtualOffset(*this, Value,
Ken Dyck9a8ad9b2011-03-23 00:45:26 +0000220 NonVirtualOffset,
Anders Carlsson34a2d382010-04-24 21:06:20 +0000221 VirtualOffset);
222
John McCall7916c992012-08-01 05:04:58 +0000223 // Cast to the destination type.
Anders Carlsson34a2d382010-04-24 21:06:20 +0000224 Value = Builder.CreateBitCast(Value, BasePtrTy);
John McCall7916c992012-08-01 05:04:58 +0000225
226 // Build a phi if we needed a null check.
Anders Carlsson34a2d382010-04-24 21:06:20 +0000227 if (NullCheckValue) {
John McCall7916c992012-08-01 05:04:58 +0000228 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
229 Builder.CreateBr(endBB);
230 EmitBlock(endBB);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000231
John McCall7916c992012-08-01 05:04:58 +0000232 llvm::PHINode *PHI = Builder.CreatePHI(BasePtrTy, 2, "cast.result");
233 PHI->addIncoming(Value, notNullBB);
234 PHI->addIncoming(llvm::Constant::getNullValue(BasePtrTy), origBB);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000235 Value = PHI;
236 }
237
238 return Value;
239}
240
241llvm::Value *
Anders Carlssona3697c92009-11-23 17:57:54 +0000242CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value,
Anders Carlsson8561a862010-04-24 23:01:49 +0000243 const CXXRecordDecl *Derived,
John McCallf871d0c2010-08-07 06:22:56 +0000244 CastExpr::path_const_iterator PathBegin,
245 CastExpr::path_const_iterator PathEnd,
Anders Carlssona3697c92009-11-23 17:57:54 +0000246 bool NullCheckValue) {
John McCallf871d0c2010-08-07 06:22:56 +0000247 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssona04efdf2010-04-24 21:23:59 +0000248
Anders Carlssona3697c92009-11-23 17:57:54 +0000249 QualType DerivedTy =
Anders Carlsson8561a862010-04-24 23:01:49 +0000250 getContext().getCanonicalType(getContext().getTagDeclType(Derived));
Chris Lattner2acc6e32011-07-18 04:24:23 +0000251 llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
Richard Smithc7648302013-02-13 21:18:23 +0000252
Anders Carlssona552ea72010-01-31 01:43:37 +0000253 llvm::Value *NonVirtualOffset =
John McCallf871d0c2010-08-07 06:22:56 +0000254 CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
Anders Carlssona552ea72010-01-31 01:43:37 +0000255
256 if (!NonVirtualOffset) {
257 // No offset, we can just cast back.
258 return Builder.CreateBitCast(Value, DerivedPtrTy);
259 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700260
261 llvm::BasicBlock *CastNull = nullptr;
262 llvm::BasicBlock *CastNotNull = nullptr;
263 llvm::BasicBlock *CastEnd = nullptr;
264
Anders Carlssona3697c92009-11-23 17:57:54 +0000265 if (NullCheckValue) {
266 CastNull = createBasicBlock("cast.null");
267 CastNotNull = createBasicBlock("cast.notnull");
268 CastEnd = createBasicBlock("cast.end");
269
Anders Carlssonb9241242011-04-11 00:30:07 +0000270 llvm::Value *IsNull = Builder.CreateIsNull(Value);
Anders Carlssona3697c92009-11-23 17:57:54 +0000271 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
272 EmitBlock(CastNotNull);
273 }
274
Anders Carlssona552ea72010-01-31 01:43:37 +0000275 // Apply the offset.
Eli Friedmanc5685432012-02-28 22:07:56 +0000276 Value = Builder.CreateBitCast(Value, Int8PtrTy);
277 Value = Builder.CreateGEP(Value, Builder.CreateNeg(NonVirtualOffset),
278 "sub.ptr");
Anders Carlssona552ea72010-01-31 01:43:37 +0000279
280 // Just cast.
281 Value = Builder.CreateBitCast(Value, DerivedPtrTy);
Anders Carlssona3697c92009-11-23 17:57:54 +0000282
283 if (NullCheckValue) {
284 Builder.CreateBr(CastEnd);
285 EmitBlock(CastNull);
286 Builder.CreateBr(CastEnd);
287 EmitBlock(CastEnd);
288
Jay Foadbbf3bac2011-03-30 11:28:58 +0000289 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
Anders Carlssona3697c92009-11-23 17:57:54 +0000290 PHI->addIncoming(Value, CastNotNull);
291 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
292 CastNull);
293 Value = PHI;
294 }
295
296 return Value;
Anders Carlsson5d58a1d2009-09-12 04:27:24 +0000297}
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000298
299llvm::Value *CodeGenFunction::GetVTTParameter(GlobalDecl GD,
300 bool ForVirtualBase,
301 bool Delegating) {
Peter Collingbournee1e35f72013-06-28 20:45:28 +0000302 if (!CGM.getCXXABI().NeedsVTTParameter(GD)) {
Anders Carlssonc997d422010-01-02 01:01:18 +0000303 // This constructor/destructor does not need a VTT parameter.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700304 return nullptr;
Anders Carlssonc997d422010-01-02 01:01:18 +0000305 }
306
John McCallf5ebf9b2013-05-03 07:33:41 +0000307 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CurCodeDecl)->getParent();
Anders Carlssonc997d422010-01-02 01:01:18 +0000308 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
John McCall3b477332010-02-18 19:59:28 +0000309
Anders Carlssonc997d422010-01-02 01:01:18 +0000310 llvm::Value *VTT;
311
John McCall3b477332010-02-18 19:59:28 +0000312 uint64_t SubVTTIndex;
313
Douglas Gregor378e1e72013-01-31 05:50:40 +0000314 if (Delegating) {
315 // If this is a delegating constructor call, just load the VTT.
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000316 return LoadCXXVTT();
Douglas Gregor378e1e72013-01-31 05:50:40 +0000317 } else if (RD == Base) {
318 // If the record matches the base, this is the complete ctor/dtor
319 // variant calling the base variant in a class with virtual bases.
Peter Collingbournee1e35f72013-06-28 20:45:28 +0000320 assert(!CGM.getCXXABI().NeedsVTTParameter(CurGD) &&
John McCall3b477332010-02-18 19:59:28 +0000321 "doing no-op VTT offset in base dtor/ctor?");
Anders Carlsson314e6222010-05-02 23:33:10 +0000322 assert(!ForVirtualBase && "Can't have same class as virtual base!");
John McCall3b477332010-02-18 19:59:28 +0000323 SubVTTIndex = 0;
324 } else {
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000325 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Ken Dyck4230d522011-03-24 01:21:01 +0000326 CharUnits BaseOffset = ForVirtualBase ?
327 Layout.getVBaseClassOffset(Base) :
328 Layout.getBaseClassOffset(Base);
Anders Carlssonc11bb212010-05-02 23:53:25 +0000329
330 SubVTTIndex =
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000331 CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
John McCall3b477332010-02-18 19:59:28 +0000332 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
333 }
Anders Carlssonc997d422010-01-02 01:01:18 +0000334
Peter Collingbournee1e35f72013-06-28 20:45:28 +0000335 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
Anders Carlssonc997d422010-01-02 01:01:18 +0000336 // A VTT parameter was passed to the constructor, use it.
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000337 VTT = LoadCXXVTT();
338 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
Anders Carlssonc997d422010-01-02 01:01:18 +0000339 } else {
340 // We're the complete constructor, so get the VTT by name.
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000341 VTT = CGM.getVTables().GetAddrOfVTT(RD);
342 VTT = Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
Anders Carlssonc997d422010-01-02 01:01:18 +0000343 }
344
345 return VTT;
346}
347
John McCall182ab512010-07-21 01:23:41 +0000348namespace {
John McCall50da2ca2010-07-21 05:30:47 +0000349 /// Call the destructor for a direct base class.
John McCall1f0fca52010-07-21 07:22:38 +0000350 struct CallBaseDtor : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000351 const CXXRecordDecl *BaseClass;
352 bool BaseIsVirtual;
353 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
354 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
John McCall182ab512010-07-21 01:23:41 +0000355
Stephen Hines651f13c2014-04-23 16:59:28 -0700356 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall50da2ca2010-07-21 05:30:47 +0000357 const CXXRecordDecl *DerivedClass =
358 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
359
360 const CXXDestructorDecl *D = BaseClass->getDestructor();
361 llvm::Value *Addr =
362 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThis(),
363 DerivedClass, BaseClass,
364 BaseIsVirtual);
Douglas Gregor378e1e72013-01-31 05:50:40 +0000365 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual,
366 /*Delegating=*/false, Addr);
John McCall182ab512010-07-21 01:23:41 +0000367 }
368 };
John McCall7e1dff72010-09-17 02:31:44 +0000369
370 /// A visitor which checks whether an initializer uses 'this' in a
371 /// way which requires the vtable to be properly set.
372 struct DynamicThisUseChecker : EvaluatedExprVisitor<DynamicThisUseChecker> {
373 typedef EvaluatedExprVisitor<DynamicThisUseChecker> super;
374
375 bool UsesThis;
376
377 DynamicThisUseChecker(ASTContext &C) : super(C), UsesThis(false) {}
378
379 // Black-list all explicit and implicit references to 'this'.
380 //
381 // Do we need to worry about external references to 'this' derived
382 // from arbitrary code? If so, then anything which runs arbitrary
383 // external code might potentially access the vtable.
384 void VisitCXXThisExpr(CXXThisExpr *E) { UsesThis = true; }
385 };
386}
387
388static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
389 DynamicThisUseChecker Checker(C);
390 Checker.Visit(const_cast<Expr*>(Init));
391 return Checker.UsesThis;
John McCall182ab512010-07-21 01:23:41 +0000392}
393
Anders Carlsson607d0372009-12-24 22:46:43 +0000394static void EmitBaseInitializer(CodeGenFunction &CGF,
395 const CXXRecordDecl *ClassDecl,
Sean Huntcbb67482011-01-08 20:30:50 +0000396 CXXCtorInitializer *BaseInit,
Anders Carlsson607d0372009-12-24 22:46:43 +0000397 CXXCtorType CtorType) {
398 assert(BaseInit->isBaseInitializer() &&
399 "Must have base initializer!");
400
401 llvm::Value *ThisPtr = CGF.LoadCXXThis();
402
403 const Type *BaseType = BaseInit->getBaseClass();
404 CXXRecordDecl *BaseClassDecl =
405 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
406
Anders Carlsson80638c52010-04-12 00:51:03 +0000407 bool isBaseVirtual = BaseInit->isBaseVirtual();
Anders Carlsson607d0372009-12-24 22:46:43 +0000408
409 // The base constructor doesn't construct virtual bases.
410 if (CtorType == Ctor_Base && isBaseVirtual)
411 return;
412
John McCall7e1dff72010-09-17 02:31:44 +0000413 // If the initializer for the base (other than the constructor
414 // itself) accesses 'this' in any way, we need to initialize the
415 // vtables.
416 if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
417 CGF.InitializeVTablePointers(ClassDecl);
418
John McCallbff225e2010-02-16 04:15:37 +0000419 // We can pretend to be a complete class because it only matters for
420 // virtual bases, and we only do virtual bases for complete ctors.
Anders Carlsson8561a862010-04-24 23:01:49 +0000421 llvm::Value *V =
422 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
John McCall50da2ca2010-07-21 05:30:47 +0000423 BaseClassDecl,
424 isBaseVirtual);
Eli Friedmand7722d92011-12-03 02:13:40 +0000425 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(BaseType);
John McCall7c2349b2011-08-25 20:40:09 +0000426 AggValueSlot AggSlot =
Eli Friedmanf3940782011-12-03 00:54:26 +0000427 AggValueSlot::forAddr(V, Alignment, Qualifiers(),
John McCall7c2349b2011-08-25 20:40:09 +0000428 AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +0000429 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +0000430 AggValueSlot::IsNotAliased);
John McCall558d2ab2010-09-15 10:14:12 +0000431
432 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
Anders Carlsson594d5e82010-02-06 20:00:21 +0000433
David Blaikie4e4d0842012-03-11 07:00:24 +0000434 if (CGF.CGM.getLangOpts().Exceptions &&
Anders Carlssonc1cfdf82011-02-20 00:20:27 +0000435 !BaseClassDecl->hasTrivialDestructor())
John McCall1f0fca52010-07-21 07:22:38 +0000436 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
437 isBaseVirtual);
Anders Carlsson607d0372009-12-24 22:46:43 +0000438}
439
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000440static void EmitAggMemberInitializer(CodeGenFunction &CGF,
441 LValue LHS,
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000442 Expr *Init,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000443 llvm::Value *ArrayIndexVar,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000444 QualType T,
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000445 ArrayRef<VarDecl *> ArrayIndexes,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000446 unsigned Index) {
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000447 if (Index == ArrayIndexes.size()) {
Eli Friedmanf3940782011-12-03 00:54:26 +0000448 LValue LV = LHS;
Eli Friedmanf3940782011-12-03 00:54:26 +0000449
Richard Smith7c3e6152013-06-12 22:31:48 +0000450 if (ArrayIndexVar) {
451 // If we have an array index variable, load it and use it as an offset.
452 // Then, increment the value.
453 llvm::Value *Dest = LHS.getAddress();
454 llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar);
455 Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress");
456 llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1);
457 Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc");
458 CGF.Builder.CreateStore(Next, ArrayIndexVar);
Sebastian Redl924db712012-02-19 15:41:54 +0000459
Richard Smith7c3e6152013-06-12 22:31:48 +0000460 // Update the LValue.
461 LV.setAddress(Dest);
462 CharUnits Align = CGF.getContext().getTypeAlignInChars(T);
463 LV.setAlignment(std::min(Align, LV.getAlignment()));
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000464 }
John McCall558d2ab2010-09-15 10:14:12 +0000465
Richard Smith7c3e6152013-06-12 22:31:48 +0000466 switch (CGF.getEvaluationKind(T)) {
467 case TEK_Scalar:
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700468 CGF.EmitScalarInit(Init, /*decl*/ nullptr, LV, false);
Richard Smith7c3e6152013-06-12 22:31:48 +0000469 break;
470 case TEK_Complex:
471 CGF.EmitComplexExprIntoLValue(Init, LV, /*isInit*/ true);
472 break;
473 case TEK_Aggregate: {
474 AggValueSlot Slot =
475 AggValueSlot::forLValue(LV,
476 AggValueSlot::IsDestructed,
477 AggValueSlot::DoesNotNeedGCBarriers,
478 AggValueSlot::IsNotAliased);
479
480 CGF.EmitAggExpr(Init, Slot);
481 break;
482 }
483 }
Sebastian Redl924db712012-02-19 15:41:54 +0000484
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000485 return;
486 }
Richard Smith7c3e6152013-06-12 22:31:48 +0000487
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000488 const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T);
489 assert(Array && "Array initialization without the array type?");
490 llvm::Value *IndexVar
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000491 = CGF.GetAddrOfLocalVar(ArrayIndexes[Index]);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000492 assert(IndexVar && "Array index variable not loaded");
493
494 // Initialize this index variable to zero.
495 llvm::Value* Zero
496 = llvm::Constant::getNullValue(
497 CGF.ConvertType(CGF.getContext().getSizeType()));
498 CGF.Builder.CreateStore(Zero, IndexVar);
499
500 // Start the loop with a block that tests the condition.
501 llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond");
502 llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end");
503
504 CGF.EmitBlock(CondBlock);
505
506 llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body");
507 // Generate: if (loop-index < number-of-elements) fall to the loop body,
508 // otherwise, go to the block after the for-loop.
509 uint64_t NumElements = Array->getSize().getZExtValue();
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000510 llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
Chris Lattner985f7392010-05-06 06:35:23 +0000511 llvm::Value *NumElementsPtr =
512 llvm::ConstantInt::get(Counter->getType(), NumElements);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000513 llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr,
514 "isless");
515
516 // If the condition is true, execute the body.
517 CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor);
518
519 CGF.EmitBlock(ForBody);
520 llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc");
Richard Smith7c3e6152013-06-12 22:31:48 +0000521
522 // Inside the loop body recurse to emit the inner loop or, eventually, the
523 // constructor call.
524 EmitAggMemberInitializer(CGF, LHS, Init, ArrayIndexVar,
525 Array->getElementType(), ArrayIndexes, Index + 1);
526
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000527 CGF.EmitBlock(ContinueBlock);
528
529 // Emit the increment of the loop counter.
530 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
531 Counter = CGF.Builder.CreateLoad(IndexVar);
532 NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc");
533 CGF.Builder.CreateStore(NextVal, IndexVar);
534
535 // Finally, branch back up to the condition for the next iteration.
536 CGF.EmitBranch(CondBlock);
537
538 // Emit the fall-through block.
539 CGF.EmitBlock(AfterFor, true);
540}
John McCall182ab512010-07-21 01:23:41 +0000541
Anders Carlsson607d0372009-12-24 22:46:43 +0000542static void EmitMemberInitializer(CodeGenFunction &CGF,
543 const CXXRecordDecl *ClassDecl,
Sean Huntcbb67482011-01-08 20:30:50 +0000544 CXXCtorInitializer *MemberInit,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000545 const CXXConstructorDecl *Constructor,
546 FunctionArgList &Args) {
Francois Pichet00eb3f92010-12-04 09:14:42 +0000547 assert(MemberInit->isAnyMemberInitializer() &&
Anders Carlsson607d0372009-12-24 22:46:43 +0000548 "Must have member initializer!");
Richard Smith7a614d82011-06-11 17:19:42 +0000549 assert(MemberInit->getInit() && "Must have initializer!");
Anders Carlsson607d0372009-12-24 22:46:43 +0000550
551 // non-static data member initializers.
Francois Pichet00eb3f92010-12-04 09:14:42 +0000552 FieldDecl *Field = MemberInit->getAnyMember();
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000553 QualType FieldType = Field->getType();
Anders Carlsson607d0372009-12-24 22:46:43 +0000554
555 llvm::Value *ThisPtr = CGF.LoadCXXThis();
Eli Friedman377ecc72012-04-16 03:54:45 +0000556 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
Eli Friedman859c65c2012-08-08 03:51:37 +0000557 LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
Eli Friedman377ecc72012-04-16 03:54:45 +0000558
Francois Pichet00eb3f92010-12-04 09:14:42 +0000559 if (MemberInit->isIndirectMemberInitializer()) {
Eli Friedman859c65c2012-08-08 03:51:37 +0000560 // If we are initializing an anonymous union field, drill down to
561 // the field.
562 IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember();
Stephen Hines651f13c2014-04-23 16:59:28 -0700563 for (const auto *I : IndirectField->chain())
564 LHS = CGF.EmitLValueForFieldInitialization(LHS, cast<FieldDecl>(I));
Francois Pichet00eb3f92010-12-04 09:14:42 +0000565 FieldType = MemberInit->getIndirectMember()->getAnonField()->getType();
John McCalla9976d32010-05-21 01:18:57 +0000566 } else {
Eli Friedman859c65c2012-08-08 03:51:37 +0000567 LHS = CGF.EmitLValueForFieldInitialization(LHS, Field);
Anders Carlsson607d0372009-12-24 22:46:43 +0000568 }
569
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000570 // Special case: if we are in a copy or move constructor, and we are copying
571 // an array of PODs or classes with trivial copy constructors, ignore the
572 // AST and perform the copy we know is equivalent.
573 // FIXME: This is hacky at best... if we had a bit more explicit information
574 // in the AST, we could generalize it more easily.
575 const ConstantArrayType *Array
576 = CGF.getContext().getAsConstantArrayType(FieldType);
Jordan Rosea7b87972013-08-07 16:16:48 +0000577 if (Array && Constructor->isDefaulted() &&
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000578 Constructor->isCopyOrMoveConstructor()) {
579 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
Richard Smithe9385362012-11-07 23:56:21 +0000580 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000581 if (BaseElementTy.isPODType(CGF.getContext()) ||
Richard Smithe9385362012-11-07 23:56:21 +0000582 (CE && CE->getConstructor()->isTrivial())) {
Stephen Hines176edba2014-12-01 14:53:08 -0800583 unsigned SrcArgIndex =
584 CGF.CGM.getCXXABI().getSrcArgforCopyCtor(Constructor, Args);
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000585 llvm::Value *SrcPtr
586 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
Eli Friedman377ecc72012-04-16 03:54:45 +0000587 LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
588 LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field);
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000589
590 // Copy the aggregate.
591 CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
Chad Rosier649b4a12012-03-29 17:37:10 +0000592 LHS.isVolatileQualified());
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000593 return;
594 }
595 }
596
597 ArrayRef<VarDecl *> ArrayIndexes;
598 if (MemberInit->getNumArrayIndices())
599 ArrayIndexes = MemberInit->getArrayIndexes();
Eli Friedmanb74ed082012-02-14 02:31:03 +0000600 CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit(), ArrayIndexes);
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000601}
602
Eli Friedmanb74ed082012-02-14 02:31:03 +0000603void CodeGenFunction::EmitInitializerForField(FieldDecl *Field,
604 LValue LHS, Expr *Init,
605 ArrayRef<VarDecl *> ArrayIndexes) {
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000606 QualType FieldType = Field->getType();
John McCall9d232c82013-03-07 21:37:08 +0000607 switch (getEvaluationKind(FieldType)) {
608 case TEK_Scalar:
John McCallf85e1932011-06-15 23:02:42 +0000609 if (LHS.isSimple()) {
Eli Friedmanb74ed082012-02-14 02:31:03 +0000610 EmitExprAsInit(Init, Field, LHS, false);
John McCallf85e1932011-06-15 23:02:42 +0000611 } else {
Eli Friedmanb74ed082012-02-14 02:31:03 +0000612 RValue RHS = RValue::get(EmitScalarExpr(Init));
613 EmitStoreThroughLValue(RHS, LHS);
John McCallf85e1932011-06-15 23:02:42 +0000614 }
John McCall9d232c82013-03-07 21:37:08 +0000615 break;
616 case TEK_Complex:
617 EmitComplexExprIntoLValue(Init, LHS, /*isInit*/ true);
618 break;
619 case TEK_Aggregate: {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700620 llvm::Value *ArrayIndexVar = nullptr;
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000621 if (ArrayIndexes.size()) {
Eli Friedmanb74ed082012-02-14 02:31:03 +0000622 llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000623
624 // The LHS is a pointer to the first object we'll be constructing, as
625 // a flat array.
Eli Friedmanb74ed082012-02-14 02:31:03 +0000626 QualType BaseElementTy = getContext().getBaseElementType(FieldType);
627 llvm::Type *BasePtr = ConvertType(BaseElementTy);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000628 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Eli Friedmanb74ed082012-02-14 02:31:03 +0000629 llvm::Value *BaseAddrPtr = Builder.CreateBitCast(LHS.getAddress(),
630 BasePtr);
631 LHS = MakeAddrLValue(BaseAddrPtr, BaseElementTy);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000632
633 // Create an array index that will be used to walk over all of the
634 // objects we're constructing.
Eli Friedmanb74ed082012-02-14 02:31:03 +0000635 ArrayIndexVar = CreateTempAlloca(SizeTy, "object.index");
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000636 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
Eli Friedmanb74ed082012-02-14 02:31:03 +0000637 Builder.CreateStore(Zero, ArrayIndexVar);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000638
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000639
640 // Emit the block variables for the array indices, if any.
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000641 for (unsigned I = 0, N = ArrayIndexes.size(); I != N; ++I)
Eli Friedmanb74ed082012-02-14 02:31:03 +0000642 EmitAutoVarDecl(*ArrayIndexes[I]);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000643 }
644
Eli Friedmanb74ed082012-02-14 02:31:03 +0000645 EmitAggMemberInitializer(*this, LHS, Init, ArrayIndexVar, FieldType,
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000646 ArrayIndexes, 0);
Anders Carlsson607d0372009-12-24 22:46:43 +0000647 }
John McCall9d232c82013-03-07 21:37:08 +0000648 }
John McCall074cae02013-02-01 05:11:40 +0000649
650 // Ensure that we destroy this object if an exception is thrown
651 // later in the constructor.
652 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
653 if (needsEHCleanup(dtorKind))
654 pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
Anders Carlsson607d0372009-12-24 22:46:43 +0000655}
656
John McCallc0bf4622010-02-23 00:48:20 +0000657/// Checks whether the given constructor is a valid subject for the
658/// complete-to-base constructor delegation optimization, i.e.
659/// emitting the complete constructor as a simple call to the base
660/// constructor.
661static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
662
663 // Currently we disable the optimization for classes with virtual
664 // bases because (1) the addresses of parameter variables need to be
665 // consistent across all initializers but (2) the delegate function
666 // call necessarily creates a second copy of the parameter variable.
667 //
668 // The limiting example (purely theoretical AFAIK):
669 // struct A { A(int &c) { c++; } };
670 // struct B : virtual A {
671 // B(int count) : A(count) { printf("%d\n", count); }
672 // };
673 // ...although even this example could in principle be emitted as a
674 // delegation since the address of the parameter doesn't escape.
675 if (Ctor->getParent()->getNumVBases()) {
676 // TODO: white-list trivial vbase initializers. This case wouldn't
677 // be subject to the restrictions below.
678
679 // TODO: white-list cases where:
680 // - there are no non-reference parameters to the constructor
681 // - the initializers don't access any non-reference parameters
682 // - the initializers don't take the address of non-reference
683 // parameters
684 // - etc.
685 // If we ever add any of the above cases, remember that:
686 // - function-try-blocks will always blacklist this optimization
687 // - we need to perform the constructor prologue and cleanup in
688 // EmitConstructorBody.
689
690 return false;
691 }
692
693 // We also disable the optimization for variadic functions because
694 // it's impossible to "re-pass" varargs.
695 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
696 return false;
697
Sean Hunt059ce0d2011-05-01 07:04:31 +0000698 // FIXME: Decide if we can do a delegation of a delegating constructor.
699 if (Ctor->isDelegatingConstructor())
700 return false;
701
John McCallc0bf4622010-02-23 00:48:20 +0000702 return true;
703}
704
Stephen Hines176edba2014-12-01 14:53:08 -0800705// Emit code in ctor (Prologue==true) or dtor (Prologue==false)
706// to poison the extra field paddings inserted under
707// -fsanitize-address-field-padding=1|2.
708void CodeGenFunction::EmitAsanPrologueOrEpilogue(bool Prologue) {
709 ASTContext &Context = getContext();
710 const CXXRecordDecl *ClassDecl =
711 Prologue ? cast<CXXConstructorDecl>(CurGD.getDecl())->getParent()
712 : cast<CXXDestructorDecl>(CurGD.getDecl())->getParent();
713 if (!ClassDecl->mayInsertExtraPadding()) return;
714
715 struct SizeAndOffset {
716 uint64_t Size;
717 uint64_t Offset;
718 };
719
720 unsigned PtrSize = CGM.getDataLayout().getPointerSizeInBits();
721 const ASTRecordLayout &Info = Context.getASTRecordLayout(ClassDecl);
722
723 // Populate sizes and offsets of fields.
724 SmallVector<SizeAndOffset, 16> SSV(Info.getFieldCount());
725 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i)
726 SSV[i].Offset =
727 Context.toCharUnitsFromBits(Info.getFieldOffset(i)).getQuantity();
728
729 size_t NumFields = 0;
730 for (const auto *Field : ClassDecl->fields()) {
731 const FieldDecl *D = Field;
732 std::pair<CharUnits, CharUnits> FieldInfo =
733 Context.getTypeInfoInChars(D->getType());
734 CharUnits FieldSize = FieldInfo.first;
735 assert(NumFields < SSV.size());
736 SSV[NumFields].Size = D->isBitField() ? 0 : FieldSize.getQuantity();
737 NumFields++;
738 }
739 assert(NumFields == SSV.size());
740 if (SSV.size() <= 1) return;
741
742 // We will insert calls to __asan_* run-time functions.
743 // LLVM AddressSanitizer pass may decide to inline them later.
744 llvm::Type *Args[2] = {IntPtrTy, IntPtrTy};
745 llvm::FunctionType *FTy =
746 llvm::FunctionType::get(CGM.VoidTy, Args, false);
747 llvm::Constant *F = CGM.CreateRuntimeFunction(
748 FTy, Prologue ? "__asan_poison_intra_object_redzone"
749 : "__asan_unpoison_intra_object_redzone");
750
751 llvm::Value *ThisPtr = LoadCXXThis();
752 ThisPtr = Builder.CreatePtrToInt(ThisPtr, IntPtrTy);
753 uint64_t TypeSize = Info.getNonVirtualSize().getQuantity();
754 // For each field check if it has sufficient padding,
755 // if so (un)poison it with a call.
756 for (size_t i = 0; i < SSV.size(); i++) {
757 uint64_t AsanAlignment = 8;
758 uint64_t NextField = i == SSV.size() - 1 ? TypeSize : SSV[i + 1].Offset;
759 uint64_t PoisonSize = NextField - SSV[i].Offset - SSV[i].Size;
760 uint64_t EndOffset = SSV[i].Offset + SSV[i].Size;
761 if (PoisonSize < AsanAlignment || !SSV[i].Size ||
762 (NextField % AsanAlignment) != 0)
763 continue;
764 Builder.CreateCall2(
765 F, Builder.CreateAdd(ThisPtr, Builder.getIntN(PtrSize, EndOffset)),
766 Builder.getIntN(PtrSize, PoisonSize));
767 }
768}
769
John McCall9fc6a772010-02-19 09:25:03 +0000770/// EmitConstructorBody - Emits the body of the current constructor.
771void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
Stephen Hines176edba2014-12-01 14:53:08 -0800772 EmitAsanPrologueOrEpilogue(true);
John McCall9fc6a772010-02-19 09:25:03 +0000773 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
774 CXXCtorType CtorType = CurGD.getCtorType();
775
Stephen Hines651f13c2014-04-23 16:59:28 -0700776 assert((CGM.getTarget().getCXXABI().hasConstructorVariants() ||
777 CtorType == Ctor_Complete) &&
778 "can only generate complete ctor for this ABI");
779
John McCallc0bf4622010-02-23 00:48:20 +0000780 // Before we go any further, try the complete->base constructor
781 // delegation optimization.
Timur Iskhodzhanov85607912012-04-20 08:05:00 +0000782 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
John McCall64aa4b32013-04-16 22:48:15 +0000783 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
Devang Pateld67ef0e2010-08-11 21:04:37 +0000784 if (CGDebugInfo *DI = getDebugInfo())
Eric Christopher73fb3502011-10-13 21:45:18 +0000785 DI->EmitLocation(Builder, Ctor->getLocEnd());
Nick Lewycky4ee7dc22013-10-02 02:29:49 +0000786 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args, Ctor->getLocEnd());
John McCallc0bf4622010-02-23 00:48:20 +0000787 return;
788 }
789
Stephen Hines176edba2014-12-01 14:53:08 -0800790 const FunctionDecl *Definition = 0;
791 Stmt *Body = Ctor->getBody(Definition);
792 assert(Definition == Ctor && "emitting wrong constructor body");
John McCall9fc6a772010-02-19 09:25:03 +0000793
John McCallc0bf4622010-02-23 00:48:20 +0000794 // Enter the function-try-block before the constructor prologue if
795 // applicable.
John McCallc0bf4622010-02-23 00:48:20 +0000796 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallc0bf4622010-02-23 00:48:20 +0000797 if (IsTryBody)
John McCall59a70002010-07-07 06:56:46 +0000798 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000799
Stephen Hines651f13c2014-04-23 16:59:28 -0700800 RegionCounter Cnt = getPGORegionCounter(Body);
801 Cnt.beginRegion(Builder);
802
Richard Smith7c3e6152013-06-12 22:31:48 +0000803 RunCleanupsScope RunCleanups(*this);
John McCall9fc6a772010-02-19 09:25:03 +0000804
John McCall56ea3772012-03-30 04:25:03 +0000805 // TODO: in restricted cases, we can emit the vbase initializers of
806 // a complete ctor and then delegate to the base ctor.
807
John McCallc0bf4622010-02-23 00:48:20 +0000808 // Emit the constructor prologue, i.e. the base and member
809 // initializers.
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000810 EmitCtorPrologue(Ctor, CtorType, Args);
John McCall9fc6a772010-02-19 09:25:03 +0000811
812 // Emit the body of the statement.
John McCallc0bf4622010-02-23 00:48:20 +0000813 if (IsTryBody)
John McCall9fc6a772010-02-19 09:25:03 +0000814 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
815 else if (Body)
816 EmitStmt(Body);
John McCall9fc6a772010-02-19 09:25:03 +0000817
818 // Emit any cleanup blocks associated with the member or base
819 // initializers, which includes (along the exceptional path) the
820 // destructors for those members and bases that were fully
821 // constructed.
Richard Smith7c3e6152013-06-12 22:31:48 +0000822 RunCleanups.ForceCleanup();
John McCall9fc6a772010-02-19 09:25:03 +0000823
John McCallc0bf4622010-02-23 00:48:20 +0000824 if (IsTryBody)
John McCall59a70002010-07-07 06:56:46 +0000825 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000826}
827
Lang Hames56c00c42013-02-17 07:22:09 +0000828namespace {
Nick Lewycky62a3bba2013-09-11 02:03:20 +0000829 /// RAII object to indicate that codegen is copying the value representation
830 /// instead of the object representation. Useful when copying a struct or
831 /// class which has uninitialized members and we're only performing
832 /// lvalue-to-rvalue conversion on the object but not its members.
833 class CopyingValueRepresentation {
834 public:
835 explicit CopyingValueRepresentation(CodeGenFunction &CGF)
Stephen Hines176edba2014-12-01 14:53:08 -0800836 : CGF(CGF), OldSanOpts(CGF.SanOpts) {
837 CGF.SanOpts.set(SanitizerKind::Bool, false);
838 CGF.SanOpts.set(SanitizerKind::Enum, false);
Nick Lewycky62a3bba2013-09-11 02:03:20 +0000839 }
840 ~CopyingValueRepresentation() {
841 CGF.SanOpts = OldSanOpts;
842 }
843 private:
844 CodeGenFunction &CGF;
Stephen Hines176edba2014-12-01 14:53:08 -0800845 SanitizerSet OldSanOpts;
Nick Lewycky62a3bba2013-09-11 02:03:20 +0000846 };
847}
848
849namespace {
Lang Hames56c00c42013-02-17 07:22:09 +0000850 class FieldMemcpyizer {
851 public:
852 FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl,
853 const VarDecl *SrcRec)
854 : CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec),
855 RecLayout(CGF.getContext().getASTRecordLayout(ClassDecl)),
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700856 FirstField(nullptr), LastField(nullptr), FirstFieldOffset(0),
857 LastFieldOffset(0), LastAddedFieldIndex(0) {}
Lang Hames56c00c42013-02-17 07:22:09 +0000858
Stephen Hines176edba2014-12-01 14:53:08 -0800859 bool isMemcpyableField(FieldDecl *F) const {
860 // Never memcpy fields when we are adding poisoned paddings.
861 if (CGF.getContext().getLangOpts().SanitizeAddressFieldPadding)
862 return false;
Lang Hames56c00c42013-02-17 07:22:09 +0000863 Qualifiers Qual = F->getType().getQualifiers();
864 if (Qual.hasVolatile() || Qual.hasObjCLifetime())
865 return false;
866 return true;
867 }
868
869 void addMemcpyableField(FieldDecl *F) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700870 if (!FirstField)
Lang Hames56c00c42013-02-17 07:22:09 +0000871 addInitialField(F);
872 else
873 addNextField(F);
874 }
875
Stephen Hines176edba2014-12-01 14:53:08 -0800876 CharUnits getMemcpySize(uint64_t FirstByteOffset) const {
Lang Hames56c00c42013-02-17 07:22:09 +0000877 unsigned LastFieldSize =
878 LastField->isBitField() ?
879 LastField->getBitWidthValue(CGF.getContext()) :
880 CGF.getContext().getTypeSize(LastField->getType());
881 uint64_t MemcpySizeBits =
Stephen Hines176edba2014-12-01 14:53:08 -0800882 LastFieldOffset + LastFieldSize - FirstByteOffset +
Lang Hames56c00c42013-02-17 07:22:09 +0000883 CGF.getContext().getCharWidth() - 1;
884 CharUnits MemcpySize =
885 CGF.getContext().toCharUnitsFromBits(MemcpySizeBits);
886 return MemcpySize;
887 }
888
889 void emitMemcpy() {
890 // Give the subclass a chance to bail out if it feels the memcpy isn't
891 // worth it (e.g. Hasn't aggregated enough data).
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700892 if (!FirstField) {
Lang Hames56c00c42013-02-17 07:22:09 +0000893 return;
894 }
895
Lang Hames5e8577e2013-02-27 04:14:49 +0000896 CharUnits Alignment;
Lang Hames56c00c42013-02-17 07:22:09 +0000897
Stephen Hines176edba2014-12-01 14:53:08 -0800898 uint64_t FirstByteOffset;
Lang Hames56c00c42013-02-17 07:22:09 +0000899 if (FirstField->isBitField()) {
900 const CGRecordLayout &RL =
901 CGF.getTypes().getCGRecordLayout(FirstField->getParent());
902 const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField);
Lang Hames5e8577e2013-02-27 04:14:49 +0000903 Alignment = CharUnits::fromQuantity(BFInfo.StorageAlignment);
Stephen Hines176edba2014-12-01 14:53:08 -0800904 // FirstFieldOffset is not appropriate for bitfields,
905 // it won't tell us what the storage offset should be and thus might not
906 // be properly aligned.
907 //
908 // Instead calculate the storage offset using the offset of the field in
909 // the struct type.
910 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
911 FirstByteOffset =
912 DL.getStructLayout(RL.getLLVMType())
913 ->getElementOffsetInBits(RL.getLLVMFieldNo(FirstField));
Lang Hames5e8577e2013-02-27 04:14:49 +0000914 } else {
Lang Hames23742cd2013-03-05 20:27:24 +0000915 Alignment = CGF.getContext().getDeclAlign(FirstField);
Stephen Hines176edba2014-12-01 14:53:08 -0800916 FirstByteOffset = FirstFieldOffset;
Lang Hames5e8577e2013-02-27 04:14:49 +0000917 }
Lang Hames56c00c42013-02-17 07:22:09 +0000918
Stephen Hines176edba2014-12-01 14:53:08 -0800919 assert((CGF.getContext().toCharUnitsFromBits(FirstByteOffset) %
Lang Hames5e8577e2013-02-27 04:14:49 +0000920 Alignment) == 0 && "Bad field alignment.");
921
Stephen Hines176edba2014-12-01 14:53:08 -0800922 CharUnits MemcpySize = getMemcpySize(FirstByteOffset);
Lang Hames56c00c42013-02-17 07:22:09 +0000923 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
924 llvm::Value *ThisPtr = CGF.LoadCXXThis();
925 LValue DestLV = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
926 LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField);
927 llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec));
928 LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
929 LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField);
930
931 emitMemcpyIR(Dest.isBitField() ? Dest.getBitFieldAddr() : Dest.getAddress(),
932 Src.isBitField() ? Src.getBitFieldAddr() : Src.getAddress(),
933 MemcpySize, Alignment);
934 reset();
935 }
936
937 void reset() {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700938 FirstField = nullptr;
Lang Hames56c00c42013-02-17 07:22:09 +0000939 }
940
941 protected:
942 CodeGenFunction &CGF;
943 const CXXRecordDecl *ClassDecl;
944
945 private:
946
947 void emitMemcpyIR(llvm::Value *DestPtr, llvm::Value *SrcPtr,
948 CharUnits Size, CharUnits Alignment) {
949 llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
950 llvm::Type *DBP =
951 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), DPT->getAddressSpace());
952 DestPtr = CGF.Builder.CreateBitCast(DestPtr, DBP);
953
954 llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
955 llvm::Type *SBP =
956 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), SPT->getAddressSpace());
957 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, SBP);
958
959 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity(),
960 Alignment.getQuantity());
961 }
962
963 void addInitialField(FieldDecl *F) {
964 FirstField = F;
965 LastField = F;
966 FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex());
967 LastFieldOffset = FirstFieldOffset;
968 LastAddedFieldIndex = F->getFieldIndex();
969 return;
970 }
971
972 void addNextField(FieldDecl *F) {
John McCall402cd222013-05-07 05:20:46 +0000973 // For the most part, the following invariant will hold:
974 // F->getFieldIndex() == LastAddedFieldIndex + 1
975 // The one exception is that Sema won't add a copy-initializer for an
976 // unnamed bitfield, which will show up here as a gap in the sequence.
977 assert(F->getFieldIndex() >= LastAddedFieldIndex + 1 &&
978 "Cannot aggregate fields out of order.");
Lang Hames56c00c42013-02-17 07:22:09 +0000979 LastAddedFieldIndex = F->getFieldIndex();
980
981 // The 'first' and 'last' fields are chosen by offset, rather than field
982 // index. This allows the code to support bitfields, as well as regular
983 // fields.
984 uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex());
985 if (FOffset < FirstFieldOffset) {
986 FirstField = F;
987 FirstFieldOffset = FOffset;
988 } else if (FOffset > LastFieldOffset) {
989 LastField = F;
990 LastFieldOffset = FOffset;
991 }
992 }
993
994 const VarDecl *SrcRec;
995 const ASTRecordLayout &RecLayout;
996 FieldDecl *FirstField;
997 FieldDecl *LastField;
998 uint64_t FirstFieldOffset, LastFieldOffset;
999 unsigned LastAddedFieldIndex;
1000 };
1001
1002 class ConstructorMemcpyizer : public FieldMemcpyizer {
1003 private:
1004
1005 /// Get source argument for copy constructor. Returns null if not a copy
Stephen Hines176edba2014-12-01 14:53:08 -08001006 /// constructor.
1007 static const VarDecl *getTrivialCopySource(CodeGenFunction &CGF,
1008 const CXXConstructorDecl *CD,
Lang Hames56c00c42013-02-17 07:22:09 +00001009 FunctionArgList &Args) {
Jordan Rosea7b87972013-08-07 16:16:48 +00001010 if (CD->isCopyOrMoveConstructor() && CD->isDefaulted())
Stephen Hines176edba2014-12-01 14:53:08 -08001011 return Args[CGF.CGM.getCXXABI().getSrcArgforCopyCtor(CD, Args)];
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001012 return nullptr;
Lang Hames56c00c42013-02-17 07:22:09 +00001013 }
1014
1015 // Returns true if a CXXCtorInitializer represents a member initialization
1016 // that can be rolled into a memcpy.
1017 bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const {
1018 if (!MemcpyableCtor)
1019 return false;
1020 FieldDecl *Field = MemberInit->getMember();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001021 assert(Field && "No field for member init.");
Lang Hames56c00c42013-02-17 07:22:09 +00001022 QualType FieldType = Field->getType();
1023 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
1024
1025 // Bail out on non-POD, not-trivially-constructable members.
1026 if (!(CE && CE->getConstructor()->isTrivial()) &&
1027 !(FieldType.isTriviallyCopyableType(CGF.getContext()) ||
1028 FieldType->isReferenceType()))
1029 return false;
1030
1031 // Bail out on volatile fields.
1032 if (!isMemcpyableField(Field))
1033 return false;
1034
1035 // Otherwise we're good.
1036 return true;
1037 }
1038
1039 public:
1040 ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD,
1041 FunctionArgList &Args)
Stephen Hines176edba2014-12-01 14:53:08 -08001042 : FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CGF, CD, Args)),
Lang Hames56c00c42013-02-17 07:22:09 +00001043 ConstructorDecl(CD),
Jordan Rosea7b87972013-08-07 16:16:48 +00001044 MemcpyableCtor(CD->isDefaulted() &&
Lang Hames56c00c42013-02-17 07:22:09 +00001045 CD->isCopyOrMoveConstructor() &&
1046 CGF.getLangOpts().getGC() == LangOptions::NonGC),
1047 Args(Args) { }
1048
1049 void addMemberInitializer(CXXCtorInitializer *MemberInit) {
1050 if (isMemberInitMemcpyable(MemberInit)) {
1051 AggregatedInits.push_back(MemberInit);
1052 addMemcpyableField(MemberInit->getMember());
1053 } else {
1054 emitAggregatedInits();
1055 EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit,
1056 ConstructorDecl, Args);
1057 }
1058 }
1059
1060 void emitAggregatedInits() {
1061 if (AggregatedInits.size() <= 1) {
1062 // This memcpy is too small to be worthwhile. Fall back on default
1063 // codegen.
Nick Lewycky62a3bba2013-09-11 02:03:20 +00001064 if (!AggregatedInits.empty()) {
1065 CopyingValueRepresentation CVR(CGF);
Lang Hames56c00c42013-02-17 07:22:09 +00001066 EmitMemberInitializer(CGF, ConstructorDecl->getParent(),
Nick Lewycky62a3bba2013-09-11 02:03:20 +00001067 AggregatedInits[0], ConstructorDecl, Args);
Lang Hames56c00c42013-02-17 07:22:09 +00001068 }
1069 reset();
1070 return;
1071 }
1072
1073 pushEHDestructors();
1074 emitMemcpy();
1075 AggregatedInits.clear();
1076 }
1077
1078 void pushEHDestructors() {
1079 llvm::Value *ThisPtr = CGF.LoadCXXThis();
1080 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
1081 LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
1082
1083 for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
1084 QualType FieldType = AggregatedInits[i]->getMember()->getType();
1085 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
1086 if (CGF.needsEHCleanup(dtorKind))
1087 CGF.pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
1088 }
1089 }
1090
1091 void finish() {
1092 emitAggregatedInits();
1093 }
1094
1095 private:
1096 const CXXConstructorDecl *ConstructorDecl;
1097 bool MemcpyableCtor;
1098 FunctionArgList &Args;
1099 SmallVector<CXXCtorInitializer*, 16> AggregatedInits;
1100 };
1101
1102 class AssignmentMemcpyizer : public FieldMemcpyizer {
1103 private:
1104
1105 // Returns the memcpyable field copied by the given statement, if one
Nick Lewycky62a3bba2013-09-11 02:03:20 +00001106 // exists. Otherwise returns null.
1107 FieldDecl *getMemcpyableField(Stmt *S) {
Lang Hames56c00c42013-02-17 07:22:09 +00001108 if (!AssignmentsMemcpyable)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001109 return nullptr;
Lang Hames56c00c42013-02-17 07:22:09 +00001110 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
1111 // Recognise trivial assignments.
1112 if (BO->getOpcode() != BO_Assign)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001113 return nullptr;
Lang Hames56c00c42013-02-17 07:22:09 +00001114 MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS());
1115 if (!ME)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001116 return nullptr;
Lang Hames56c00c42013-02-17 07:22:09 +00001117 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1118 if (!Field || !isMemcpyableField(Field))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001119 return nullptr;
Lang Hames56c00c42013-02-17 07:22:09 +00001120 Stmt *RHS = BO->getRHS();
1121 if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS))
1122 RHS = EC->getSubExpr();
1123 if (!RHS)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001124 return nullptr;
Lang Hames56c00c42013-02-17 07:22:09 +00001125 MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS);
1126 if (dyn_cast<FieldDecl>(ME2->getMemberDecl()) != Field)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001127 return nullptr;
Lang Hames56c00c42013-02-17 07:22:09 +00001128 return Field;
1129 } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) {
1130 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl());
1131 if (!(MD && (MD->isCopyAssignmentOperator() ||
1132 MD->isMoveAssignmentOperator()) &&
1133 MD->isTrivial()))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001134 return nullptr;
Lang Hames56c00c42013-02-17 07:22:09 +00001135 MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument());
1136 if (!IOA)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001137 return nullptr;
Lang Hames56c00c42013-02-17 07:22:09 +00001138 FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl());
1139 if (!Field || !isMemcpyableField(Field))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001140 return nullptr;
Lang Hames56c00c42013-02-17 07:22:09 +00001141 MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0));
1142 if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl()))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001143 return nullptr;
Lang Hames56c00c42013-02-17 07:22:09 +00001144 return Field;
1145 } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1146 FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1147 if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001148 return nullptr;
Lang Hames56c00c42013-02-17 07:22:09 +00001149 Expr *DstPtr = CE->getArg(0);
1150 if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr))
1151 DstPtr = DC->getSubExpr();
1152 UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr);
1153 if (!DUO || DUO->getOpcode() != UO_AddrOf)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001154 return nullptr;
Lang Hames56c00c42013-02-17 07:22:09 +00001155 MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr());
1156 if (!ME)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001157 return nullptr;
Lang Hames56c00c42013-02-17 07:22:09 +00001158 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1159 if (!Field || !isMemcpyableField(Field))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001160 return nullptr;
Lang Hames56c00c42013-02-17 07:22:09 +00001161 Expr *SrcPtr = CE->getArg(1);
1162 if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr))
1163 SrcPtr = SC->getSubExpr();
1164 UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr);
1165 if (!SUO || SUO->getOpcode() != UO_AddrOf)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001166 return nullptr;
Lang Hames56c00c42013-02-17 07:22:09 +00001167 MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr());
1168 if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl()))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001169 return nullptr;
Lang Hames56c00c42013-02-17 07:22:09 +00001170 return Field;
1171 }
1172
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001173 return nullptr;
Lang Hames56c00c42013-02-17 07:22:09 +00001174 }
1175
1176 bool AssignmentsMemcpyable;
1177 SmallVector<Stmt*, 16> AggregatedStmts;
1178
1179 public:
1180
1181 AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD,
1182 FunctionArgList &Args)
1183 : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]),
1184 AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) {
1185 assert(Args.size() == 2);
1186 }
1187
1188 void emitAssignment(Stmt *S) {
1189 FieldDecl *F = getMemcpyableField(S);
1190 if (F) {
1191 addMemcpyableField(F);
1192 AggregatedStmts.push_back(S);
1193 } else {
1194 emitAggregatedStmts();
1195 CGF.EmitStmt(S);
1196 }
1197 }
1198
1199 void emitAggregatedStmts() {
1200 if (AggregatedStmts.size() <= 1) {
Nick Lewycky62a3bba2013-09-11 02:03:20 +00001201 if (!AggregatedStmts.empty()) {
1202 CopyingValueRepresentation CVR(CGF);
1203 CGF.EmitStmt(AggregatedStmts[0]);
1204 }
Lang Hames56c00c42013-02-17 07:22:09 +00001205 reset();
1206 }
1207
1208 emitMemcpy();
1209 AggregatedStmts.clear();
1210 }
1211
1212 void finish() {
1213 emitAggregatedStmts();
1214 }
1215 };
1216
1217}
1218
Anders Carlsson607d0372009-12-24 22:46:43 +00001219/// EmitCtorPrologue - This routine generates necessary code to initialize
1220/// base classes and non-static data members belonging to this constructor.
Anders Carlsson607d0372009-12-24 22:46:43 +00001221void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001222 CXXCtorType CtorType,
1223 FunctionArgList &Args) {
Sean Hunt059ce0d2011-05-01 07:04:31 +00001224 if (CD->isDelegatingConstructor())
1225 return EmitDelegatingCXXConstructorCall(CD, Args);
1226
Anders Carlsson607d0372009-12-24 22:46:43 +00001227 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlssona78fa2c2010-02-02 19:58:43 +00001228
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001229 CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
1230 E = CD->init_end();
1231
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001232 llvm::BasicBlock *BaseCtorContinueBB = nullptr;
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001233 if (ClassDecl->getNumVBases() &&
1234 !CGM.getTarget().getCXXABI().hasConstructorVariants()) {
1235 // The ABIs that don't have constructor variants need to put a branch
1236 // before the virtual base initialization code.
Reid Kleckner90633022013-06-19 15:20:38 +00001237 BaseCtorContinueBB =
1238 CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this, ClassDecl);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001239 assert(BaseCtorContinueBB);
1240 }
1241
1242 // Virtual base initializers first.
1243 for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
1244 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
1245 }
1246
1247 if (BaseCtorContinueBB) {
1248 // Complete object handler should continue to the remaining initializers.
1249 Builder.CreateBr(BaseCtorContinueBB);
1250 EmitBlock(BaseCtorContinueBB);
1251 }
1252
1253 // Then, non-virtual base initializers.
1254 for (; B != E && (*B)->isBaseInitializer(); B++) {
1255 assert(!(*B)->isBaseVirtual());
1256 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
Anders Carlsson607d0372009-12-24 22:46:43 +00001257 }
1258
Anders Carlsson603d6d12010-03-28 21:07:49 +00001259 InitializeVTablePointers(ClassDecl);
Anders Carlssona78fa2c2010-02-02 19:58:43 +00001260
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001261 // And finally, initialize class members.
Richard Smithc3bf52c2013-04-20 22:23:05 +00001262 FieldConstructionScope FCS(*this, CXXThisValue);
Lang Hames56c00c42013-02-17 07:22:09 +00001263 ConstructorMemcpyizer CM(*this, CD, Args);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001264 for (; B != E; B++) {
1265 CXXCtorInitializer *Member = (*B);
1266 assert(!Member->isBaseInitializer());
1267 assert(Member->isAnyMemberInitializer() &&
1268 "Delegating initializer on non-delegating constructor");
1269 CM.addMemberInitializer(Member);
1270 }
Lang Hames56c00c42013-02-17 07:22:09 +00001271 CM.finish();
Anders Carlsson607d0372009-12-24 22:46:43 +00001272}
1273
Anders Carlssonadf5dc32011-05-15 17:36:21 +00001274static bool
1275FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
1276
1277static bool
1278HasTrivialDestructorBody(ASTContext &Context,
1279 const CXXRecordDecl *BaseClassDecl,
1280 const CXXRecordDecl *MostDerivedClassDecl)
1281{
1282 // If the destructor is trivial we don't have to check anything else.
1283 if (BaseClassDecl->hasTrivialDestructor())
1284 return true;
1285
1286 if (!BaseClassDecl->getDestructor()->hasTrivialBody())
1287 return false;
1288
1289 // Check fields.
Stephen Hines651f13c2014-04-23 16:59:28 -07001290 for (const auto *Field : BaseClassDecl->fields())
Anders Carlssonadf5dc32011-05-15 17:36:21 +00001291 if (!FieldHasTrivialDestructorBody(Context, Field))
1292 return false;
Anders Carlssonadf5dc32011-05-15 17:36:21 +00001293
1294 // Check non-virtual bases.
Stephen Hines651f13c2014-04-23 16:59:28 -07001295 for (const auto &I : BaseClassDecl->bases()) {
1296 if (I.isVirtual())
Anders Carlssonadf5dc32011-05-15 17:36:21 +00001297 continue;
1298
1299 const CXXRecordDecl *NonVirtualBase =
Stephen Hines651f13c2014-04-23 16:59:28 -07001300 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
Anders Carlssonadf5dc32011-05-15 17:36:21 +00001301 if (!HasTrivialDestructorBody(Context, NonVirtualBase,
1302 MostDerivedClassDecl))
1303 return false;
1304 }
1305
1306 if (BaseClassDecl == MostDerivedClassDecl) {
1307 // Check virtual bases.
Stephen Hines651f13c2014-04-23 16:59:28 -07001308 for (const auto &I : BaseClassDecl->vbases()) {
Anders Carlssonadf5dc32011-05-15 17:36:21 +00001309 const CXXRecordDecl *VirtualBase =
Stephen Hines651f13c2014-04-23 16:59:28 -07001310 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
Anders Carlssonadf5dc32011-05-15 17:36:21 +00001311 if (!HasTrivialDestructorBody(Context, VirtualBase,
1312 MostDerivedClassDecl))
1313 return false;
1314 }
1315 }
1316
1317 return true;
1318}
1319
1320static bool
1321FieldHasTrivialDestructorBody(ASTContext &Context,
1322 const FieldDecl *Field)
1323{
1324 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
1325
1326 const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
1327 if (!RT)
1328 return true;
1329
1330 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1331 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
1332}
1333
Anders Carlssonffb945f2011-05-14 23:26:09 +00001334/// CanSkipVTablePointerInitialization - Check whether we need to initialize
1335/// any vtable pointers before calling this destructor.
1336static bool CanSkipVTablePointerInitialization(ASTContext &Context,
Anders Carlssone3d6cf22011-05-16 04:08:36 +00001337 const CXXDestructorDecl *Dtor) {
Anders Carlssonffb945f2011-05-14 23:26:09 +00001338 if (!Dtor->hasTrivialBody())
1339 return false;
1340
1341 // Check the fields.
1342 const CXXRecordDecl *ClassDecl = Dtor->getParent();
Stephen Hines651f13c2014-04-23 16:59:28 -07001343 for (const auto *Field : ClassDecl->fields())
Anders Carlssonadf5dc32011-05-15 17:36:21 +00001344 if (!FieldHasTrivialDestructorBody(Context, Field))
1345 return false;
Anders Carlssonffb945f2011-05-14 23:26:09 +00001346
1347 return true;
1348}
1349
John McCall9fc6a772010-02-19 09:25:03 +00001350/// EmitDestructorBody - Emits the body of the current destructor.
1351void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
1352 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
1353 CXXDtorType DtorType = CurGD.getDtorType();
1354
John McCall50da2ca2010-07-21 05:30:47 +00001355 // The call to operator delete in a deleting destructor happens
1356 // outside of the function-try-block, which means it's always
1357 // possible to delegate the destructor body to the complete
1358 // destructor. Do so.
1359 if (DtorType == Dtor_Deleting) {
1360 EnterDtorCleanups(Dtor, Dtor_Deleting);
1361 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001362 /*Delegating=*/false, LoadCXXThis());
John McCall50da2ca2010-07-21 05:30:47 +00001363 PopCleanupBlock();
1364 return;
1365 }
1366
John McCall9fc6a772010-02-19 09:25:03 +00001367 Stmt *Body = Dtor->getBody();
1368
1369 // If the body is a function-try-block, enter the try before
John McCall50da2ca2010-07-21 05:30:47 +00001370 // anything else.
1371 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCall9fc6a772010-02-19 09:25:03 +00001372 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +00001373 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
Stephen Hines176edba2014-12-01 14:53:08 -08001374 EmitAsanPrologueOrEpilogue(false);
John McCall9fc6a772010-02-19 09:25:03 +00001375
John McCall50da2ca2010-07-21 05:30:47 +00001376 // Enter the epilogue cleanups.
1377 RunCleanupsScope DtorEpilogue(*this);
1378
John McCall9fc6a772010-02-19 09:25:03 +00001379 // If this is the complete variant, just invoke the base variant;
1380 // the epilogue will destruct the virtual bases. But we can't do
1381 // this optimization if the body is a function-try-block, because
Reid Klecknera4130ba2013-07-22 13:51:44 +00001382 // we'd introduce *two* handler blocks. In the Microsoft ABI, we
1383 // always delegate because we might not have a definition in this TU.
John McCall50da2ca2010-07-21 05:30:47 +00001384 switch (DtorType) {
Stephen Hines176edba2014-12-01 14:53:08 -08001385 case Dtor_Comdat:
1386 llvm_unreachable("not expecting a COMDAT");
1387
John McCall50da2ca2010-07-21 05:30:47 +00001388 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
1389
1390 case Dtor_Complete:
Reid Klecknera4130ba2013-07-22 13:51:44 +00001391 assert((Body || getTarget().getCXXABI().isMicrosoft()) &&
1392 "can't emit a dtor without a body for non-Microsoft ABIs");
1393
John McCall50da2ca2010-07-21 05:30:47 +00001394 // Enter the cleanup scopes for virtual bases.
1395 EnterDtorCleanups(Dtor, Dtor_Complete);
1396
Reid Klecknera4130ba2013-07-22 13:51:44 +00001397 if (!isTryBody) {
John McCall50da2ca2010-07-21 05:30:47 +00001398 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001399 /*Delegating=*/false, LoadCXXThis());
John McCall50da2ca2010-07-21 05:30:47 +00001400 break;
1401 }
1402 // Fallthrough: act like we're in the base variant.
John McCall9fc6a772010-02-19 09:25:03 +00001403
John McCall50da2ca2010-07-21 05:30:47 +00001404 case Dtor_Base:
Reid Klecknera4130ba2013-07-22 13:51:44 +00001405 assert(Body);
1406
Stephen Hines651f13c2014-04-23 16:59:28 -07001407 RegionCounter Cnt = getPGORegionCounter(Body);
1408 Cnt.beginRegion(Builder);
1409
John McCall50da2ca2010-07-21 05:30:47 +00001410 // Enter the cleanup scopes for fields and non-virtual bases.
1411 EnterDtorCleanups(Dtor, Dtor_Base);
1412
1413 // Initialize the vtable pointers before entering the body.
Anders Carlssonffb945f2011-05-14 23:26:09 +00001414 if (!CanSkipVTablePointerInitialization(getContext(), Dtor))
1415 InitializeVTablePointers(Dtor->getParent());
John McCall50da2ca2010-07-21 05:30:47 +00001416
1417 if (isTryBody)
1418 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
1419 else if (Body)
1420 EmitStmt(Body);
1421 else {
1422 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
1423 // nothing to do besides what's in the epilogue
1424 }
Fariborz Jahanian5abec142011-02-02 23:12:46 +00001425 // -fapple-kext must inline any call to this dtor into
1426 // the caller's body.
Richard Smith7edf9e32012-11-01 22:30:59 +00001427 if (getLangOpts().AppleKext)
Bill Wendling72390b32012-12-20 19:27:06 +00001428 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
John McCall50da2ca2010-07-21 05:30:47 +00001429 break;
John McCall9fc6a772010-02-19 09:25:03 +00001430 }
1431
John McCall50da2ca2010-07-21 05:30:47 +00001432 // Jump out through the epilogue cleanups.
1433 DtorEpilogue.ForceCleanup();
John McCall9fc6a772010-02-19 09:25:03 +00001434
1435 // Exit the try if applicable.
1436 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +00001437 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +00001438}
1439
Lang Hames56c00c42013-02-17 07:22:09 +00001440void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) {
1441 const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
1442 const Stmt *RootS = AssignOp->getBody();
1443 assert(isa<CompoundStmt>(RootS) &&
1444 "Body of an implicit assignment operator should be compound stmt.");
1445 const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
1446
1447 LexicalScope Scope(*this, RootCS->getSourceRange());
1448
1449 AssignmentMemcpyizer AM(*this, AssignOp, Args);
Stephen Hines651f13c2014-04-23 16:59:28 -07001450 for (auto *I : RootCS->body())
1451 AM.emitAssignment(I);
Lang Hames56c00c42013-02-17 07:22:09 +00001452 AM.finish();
1453}
1454
John McCall50da2ca2010-07-21 05:30:47 +00001455namespace {
1456 /// Call the operator delete associated with the current destructor.
John McCall1f0fca52010-07-21 07:22:38 +00001457 struct CallDtorDelete : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +00001458 CallDtorDelete() {}
1459
Stephen Hines651f13c2014-04-23 16:59:28 -07001460 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall50da2ca2010-07-21 05:30:47 +00001461 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1462 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1463 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1464 CGF.getContext().getTagDeclType(ClassDecl));
1465 }
1466 };
1467
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +00001468 struct CallDtorDeleteConditional : EHScopeStack::Cleanup {
1469 llvm::Value *ShouldDeleteCondition;
1470 public:
1471 CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
1472 : ShouldDeleteCondition(ShouldDeleteCondition) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001473 assert(ShouldDeleteCondition != nullptr);
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +00001474 }
1475
Stephen Hines651f13c2014-04-23 16:59:28 -07001476 void Emit(CodeGenFunction &CGF, Flags flags) override {
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +00001477 llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
1478 llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
1479 llvm::Value *ShouldCallDelete
1480 = CGF.Builder.CreateIsNull(ShouldDeleteCondition);
1481 CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
1482
1483 CGF.EmitBlock(callDeleteBB);
1484 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1485 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1486 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1487 CGF.getContext().getTagDeclType(ClassDecl));
1488 CGF.Builder.CreateBr(continueBB);
1489
1490 CGF.EmitBlock(continueBB);
1491 }
1492 };
1493
John McCall9928c482011-07-12 16:41:08 +00001494 class DestroyField : public EHScopeStack::Cleanup {
1495 const FieldDecl *field;
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001496 CodeGenFunction::Destroyer *destroyer;
John McCall9928c482011-07-12 16:41:08 +00001497 bool useEHCleanupForArray;
John McCall50da2ca2010-07-21 05:30:47 +00001498
John McCall9928c482011-07-12 16:41:08 +00001499 public:
1500 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
1501 bool useEHCleanupForArray)
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001502 : field(field), destroyer(destroyer),
John McCall9928c482011-07-12 16:41:08 +00001503 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall50da2ca2010-07-21 05:30:47 +00001504
Stephen Hines651f13c2014-04-23 16:59:28 -07001505 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall9928c482011-07-12 16:41:08 +00001506 // Find the address of the field.
1507 llvm::Value *thisValue = CGF.LoadCXXThis();
Eli Friedman377ecc72012-04-16 03:54:45 +00001508 QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
1509 LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
1510 LValue LV = CGF.EmitLValueForField(ThisLV, field);
John McCall9928c482011-07-12 16:41:08 +00001511 assert(LV.isSimple());
1512
1513 CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
John McCallad346f42011-07-12 20:27:29 +00001514 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCall50da2ca2010-07-21 05:30:47 +00001515 }
1516 };
1517}
1518
Stephen Hines651f13c2014-04-23 16:59:28 -07001519/// \brief Emit all code that comes at the end of class's
Anders Carlsson607d0372009-12-24 22:46:43 +00001520/// destructor. This is to call destructors on members and base classes
1521/// in reverse order of their construction.
John McCall50da2ca2010-07-21 05:30:47 +00001522void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
1523 CXXDtorType DtorType) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001524 assert((!DD->isTrivial() || DD->hasAttr<DLLExportAttr>()) &&
1525 "Should not emit dtor epilogue for non-exported trivial dtor!");
Anders Carlsson607d0372009-12-24 22:46:43 +00001526
John McCall50da2ca2010-07-21 05:30:47 +00001527 // The deleting-destructor phase just needs to call the appropriate
1528 // operator delete that Sema picked up.
John McCall3b477332010-02-18 19:59:28 +00001529 if (DtorType == Dtor_Deleting) {
1530 assert(DD->getOperatorDelete() &&
Stephen Hines651f13c2014-04-23 16:59:28 -07001531 "operator delete missing - EnterDtorCleanups");
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +00001532 if (CXXStructorImplicitParamValue) {
1533 // If there is an implicit param to the deleting dtor, it's a boolean
1534 // telling whether we should call delete at the end of the dtor.
1535 EHStack.pushCleanup<CallDtorDeleteConditional>(
1536 NormalAndEHCleanup, CXXStructorImplicitParamValue);
1537 } else {
1538 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
1539 }
John McCall3b477332010-02-18 19:59:28 +00001540 return;
1541 }
1542
John McCall50da2ca2010-07-21 05:30:47 +00001543 const CXXRecordDecl *ClassDecl = DD->getParent();
1544
Richard Smith416f63e2011-09-18 12:11:43 +00001545 // Unions have no bases and do not call field destructors.
1546 if (ClassDecl->isUnion())
1547 return;
1548
John McCall50da2ca2010-07-21 05:30:47 +00001549 // The complete-destructor phase just destructs all the virtual bases.
John McCall3b477332010-02-18 19:59:28 +00001550 if (DtorType == Dtor_Complete) {
John McCall50da2ca2010-07-21 05:30:47 +00001551
1552 // We push them in the forward order so that they'll be popped in
1553 // the reverse order.
Stephen Hines651f13c2014-04-23 16:59:28 -07001554 for (const auto &Base : ClassDecl->vbases()) {
John McCall3b477332010-02-18 19:59:28 +00001555 CXXRecordDecl *BaseClassDecl
1556 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1557
1558 // Ignore trivial destructors.
1559 if (BaseClassDecl->hasTrivialDestructor())
1560 continue;
John McCall50da2ca2010-07-21 05:30:47 +00001561
John McCall1f0fca52010-07-21 07:22:38 +00001562 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1563 BaseClassDecl,
1564 /*BaseIsVirtual*/ true);
John McCall3b477332010-02-18 19:59:28 +00001565 }
John McCall50da2ca2010-07-21 05:30:47 +00001566
John McCall3b477332010-02-18 19:59:28 +00001567 return;
1568 }
1569
1570 assert(DtorType == Dtor_Base);
John McCall50da2ca2010-07-21 05:30:47 +00001571
1572 // Destroy non-virtual bases.
Stephen Hines651f13c2014-04-23 16:59:28 -07001573 for (const auto &Base : ClassDecl->bases()) {
John McCall50da2ca2010-07-21 05:30:47 +00001574 // Ignore virtual bases.
1575 if (Base.isVirtual())
1576 continue;
1577
1578 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
1579
1580 // Ignore trivial destructors.
1581 if (BaseClassDecl->hasTrivialDestructor())
1582 continue;
John McCall3b477332010-02-18 19:59:28 +00001583
John McCall1f0fca52010-07-21 07:22:38 +00001584 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1585 BaseClassDecl,
1586 /*BaseIsVirtual*/ false);
John McCall50da2ca2010-07-21 05:30:47 +00001587 }
1588
1589 // Destroy direct fields.
Stephen Hines651f13c2014-04-23 16:59:28 -07001590 for (const auto *Field : ClassDecl->fields()) {
1591 QualType type = Field->getType();
John McCall9928c482011-07-12 16:41:08 +00001592 QualType::DestructionKind dtorKind = type.isDestructedType();
1593 if (!dtorKind) continue;
John McCall50da2ca2010-07-21 05:30:47 +00001594
Richard Smith9a561d52012-02-26 09:11:52 +00001595 // Anonymous union members do not have their destructors called.
1596 const RecordType *RT = type->getAsUnionType();
1597 if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
1598
John McCall9928c482011-07-12 16:41:08 +00001599 CleanupKind cleanupKind = getCleanupKind(dtorKind);
Stephen Hines651f13c2014-04-23 16:59:28 -07001600 EHStack.pushCleanup<DestroyField>(cleanupKind, Field,
John McCall9928c482011-07-12 16:41:08 +00001601 getDestroyer(dtorKind),
1602 cleanupKind & EHCleanup);
Anders Carlsson607d0372009-12-24 22:46:43 +00001603 }
Anders Carlsson607d0372009-12-24 22:46:43 +00001604}
1605
John McCallc3c07662011-07-13 06:10:41 +00001606/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1607/// constructor for each of several members of an array.
Douglas Gregor59174c02010-07-21 01:10:17 +00001608///
John McCallc3c07662011-07-13 06:10:41 +00001609/// \param ctor the constructor to call for each element
John McCallc3c07662011-07-13 06:10:41 +00001610/// \param arrayType the type of the array to initialize
1611/// \param arrayBegin an arrayType*
1612/// \param zeroInitialize true if each element should be
1613/// zero-initialized before it is constructed
Stephen Hines176edba2014-12-01 14:53:08 -08001614void CodeGenFunction::EmitCXXAggrConstructorCall(
1615 const CXXConstructorDecl *ctor, const ConstantArrayType *arrayType,
1616 llvm::Value *arrayBegin, const CXXConstructExpr *E, bool zeroInitialize) {
John McCallc3c07662011-07-13 06:10:41 +00001617 QualType elementType;
1618 llvm::Value *numElements =
1619 emitArrayLength(arrayType, elementType, arrayBegin);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001620
Stephen Hines176edba2014-12-01 14:53:08 -08001621 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin, E, zeroInitialize);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001622}
1623
John McCallc3c07662011-07-13 06:10:41 +00001624/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1625/// constructor for each of several members of an array.
1626///
1627/// \param ctor the constructor to call for each element
1628/// \param numElements the number of elements in the array;
John McCalldd376ca2011-07-13 07:37:11 +00001629/// may be zero
John McCallc3c07662011-07-13 06:10:41 +00001630/// \param arrayBegin a T*, where T is the type constructed by ctor
1631/// \param zeroInitialize true if each element should be
1632/// zero-initialized before it is constructed
Stephen Hines176edba2014-12-01 14:53:08 -08001633void CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1634 llvm::Value *numElements,
1635 llvm::Value *arrayBegin,
1636 const CXXConstructExpr *E,
1637 bool zeroInitialize) {
John McCalldd376ca2011-07-13 07:37:11 +00001638
1639 // It's legal for numElements to be zero. This can happen both
1640 // dynamically, because x can be zero in 'new A[x]', and statically,
1641 // because of GCC extensions that permit zero-length arrays. There
1642 // are probably legitimate places where we could assume that this
1643 // doesn't happen, but it's not clear that it's worth it.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001644 llvm::BranchInst *zeroCheckBranch = nullptr;
John McCalldd376ca2011-07-13 07:37:11 +00001645
1646 // Optimize for a constant count.
1647 llvm::ConstantInt *constantCount
1648 = dyn_cast<llvm::ConstantInt>(numElements);
1649 if (constantCount) {
1650 // Just skip out if the constant count is zero.
1651 if (constantCount->isZero()) return;
1652
1653 // Otherwise, emit the check.
1654 } else {
1655 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1656 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1657 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1658 EmitBlock(loopBB);
1659 }
1660
John McCallc3c07662011-07-13 06:10:41 +00001661 // Find the end of the array.
1662 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1663 "arrayctor.end");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001664
John McCallc3c07662011-07-13 06:10:41 +00001665 // Enter the loop, setting up a phi for the current location to initialize.
1666 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1667 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1668 EmitBlock(loopBB);
1669 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1670 "arrayctor.cur");
1671 cur->addIncoming(arrayBegin, entryBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001672
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001673 // Inside the loop body, emit the constructor call on the array element.
John McCallc3c07662011-07-13 06:10:41 +00001674
1675 QualType type = getContext().getTypeDeclType(ctor->getParent());
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001676
Douglas Gregor59174c02010-07-21 01:10:17 +00001677 // Zero initialize the storage, if requested.
John McCallc3c07662011-07-13 06:10:41 +00001678 if (zeroInitialize)
1679 EmitNullInitialization(cur, type);
Douglas Gregor59174c02010-07-21 01:10:17 +00001680
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001681 // C++ [class.temporary]p4:
1682 // There are two contexts in which temporaries are destroyed at a different
1683 // point than the end of the full-expression. The first context is when a
1684 // default constructor is called to initialize an element of an array.
1685 // If the constructor has one or more default arguments, the destruction of
1686 // every temporary created in a default argument expression is sequenced
1687 // before the construction of the next array element, if any.
1688
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001689 {
John McCallf1549f62010-07-06 01:34:17 +00001690 RunCleanupsScope Scope(*this);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001691
John McCallc3c07662011-07-13 06:10:41 +00001692 // Evaluate the constructor and its arguments in a regular
1693 // partial-destroy cleanup.
David Blaikie4e4d0842012-03-11 07:00:24 +00001694 if (getLangOpts().Exceptions &&
John McCallc3c07662011-07-13 06:10:41 +00001695 !ctor->getParent()->hasTrivialDestructor()) {
1696 Destroyer *destroyer = destroyCXXObject;
1697 pushRegularPartialArrayCleanup(arrayBegin, cur, type, *destroyer);
1698 }
1699
Stephen Hines176edba2014-12-01 14:53:08 -08001700 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/false,
1701 /*Delegating=*/false, cur, E);
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001702 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001703
John McCallc3c07662011-07-13 06:10:41 +00001704 // Go to the next element.
1705 llvm::Value *next =
1706 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
1707 "arrayctor.next");
1708 cur->addIncoming(next, Builder.GetInsertBlock());
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001709
John McCallc3c07662011-07-13 06:10:41 +00001710 // Check whether that's the end of the loop.
1711 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
1712 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
1713 Builder.CreateCondBr(done, contBB, loopBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001714
John McCalldd376ca2011-07-13 07:37:11 +00001715 // Patch the earlier check to skip over the loop.
1716 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
1717
John McCallc3c07662011-07-13 06:10:41 +00001718 EmitBlock(contBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001719}
1720
John McCallbdc4d802011-07-09 01:37:26 +00001721void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
1722 llvm::Value *addr,
1723 QualType type) {
1724 const RecordType *rtype = type->castAs<RecordType>();
1725 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
1726 const CXXDestructorDecl *dtor = record->getDestructor();
1727 assert(!dtor->isTrivial());
1728 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001729 /*Delegating=*/false, addr);
John McCallbdc4d802011-07-09 01:37:26 +00001730}
1731
Stephen Hines176edba2014-12-01 14:53:08 -08001732void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
1733 CXXCtorType Type,
1734 bool ForVirtualBase,
1735 bool Delegating, llvm::Value *This,
1736 const CXXConstructExpr *E) {
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001737 // If this is a trivial constructor, just emit what's needed.
John McCall8b6bbeb2010-02-06 00:25:16 +00001738 if (D->isTrivial()) {
Stephen Hines176edba2014-12-01 14:53:08 -08001739 if (E->getNumArgs() == 0) {
John McCall8b6bbeb2010-02-06 00:25:16 +00001740 // Trivial default constructor, no codegen required.
1741 assert(D->isDefaultConstructor() &&
1742 "trivial 0-arg ctor not a default ctor");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001743 return;
1744 }
John McCall8b6bbeb2010-02-06 00:25:16 +00001745
Stephen Hines176edba2014-12-01 14:53:08 -08001746 assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001747 assert(D->isCopyOrMoveConstructor() &&
1748 "trivial 1-arg ctor not a copy/move ctor");
John McCall8b6bbeb2010-02-06 00:25:16 +00001749
Stephen Hines176edba2014-12-01 14:53:08 -08001750 const Expr *Arg = E->getArg(0);
1751 QualType Ty = Arg->getType();
1752 llvm::Value *Src = EmitLValue(Arg).getAddress();
John McCall8b6bbeb2010-02-06 00:25:16 +00001753 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001754 return;
1755 }
1756
Stephen Hines651f13c2014-04-23 16:59:28 -07001757 // C++11 [class.mfct.non-static]p2:
1758 // If a non-static member function of a class X is called for an object that
1759 // is not of type X, or of a type derived from X, the behavior is undefined.
1760 // FIXME: Provide a source location here.
1761 EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall, SourceLocation(), This,
1762 getContext().getRecordType(D->getParent()));
1763
1764 CallArgList Args;
1765
1766 // Push the this ptr.
1767 Args.add(RValue::get(This), D->getThisType(getContext()));
1768
1769 // Add the rest of the user-supplied arguments.
1770 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
Stephen Hines176edba2014-12-01 14:53:08 -08001771 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end(), E->getConstructor());
Stephen Hines651f13c2014-04-23 16:59:28 -07001772
1773 // Insert any ABI-specific implicit constructor arguments.
1774 unsigned ExtraArgs = CGM.getCXXABI().addImplicitConstructorArgs(
1775 *this, D, Type, ForVirtualBase, Delegating, Args);
1776
1777 // Emit the call.
Stephen Hines176edba2014-12-01 14:53:08 -08001778 llvm::Value *Callee = CGM.getAddrOfCXXStructor(D, getFromCtorType(Type));
Stephen Hines651f13c2014-04-23 16:59:28 -07001779 const CGFunctionInfo &Info =
1780 CGM.getTypes().arrangeCXXConstructorCall(Args, D, Type, ExtraArgs);
1781 EmitCall(Info, Callee, ReturnValueSlot(), Args, D);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001782}
1783
John McCallc0bf4622010-02-23 00:48:20 +00001784void
Fariborz Jahanian34999872010-11-13 21:53:34 +00001785CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
1786 llvm::Value *This, llvm::Value *Src,
Stephen Hines176edba2014-12-01 14:53:08 -08001787 const CXXConstructExpr *E) {
Fariborz Jahanian34999872010-11-13 21:53:34 +00001788 if (D->isTrivial()) {
Stephen Hines176edba2014-12-01 14:53:08 -08001789 assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001790 assert(D->isCopyOrMoveConstructor() &&
1791 "trivial 1-arg ctor not a copy/move ctor");
Stephen Hines176edba2014-12-01 14:53:08 -08001792 EmitAggregateCopy(This, Src, E->arg_begin()->getType());
Fariborz Jahanian34999872010-11-13 21:53:34 +00001793 return;
1794 }
Stephen Hines176edba2014-12-01 14:53:08 -08001795 llvm::Value *Callee = CGM.getAddrOfCXXStructor(D, StructorType::Complete);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001796 assert(D->isInstance() &&
1797 "Trying to emit a member call expr on a static method!");
1798
Stephen Hines651f13c2014-04-23 16:59:28 -07001799 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
Fariborz Jahanian34999872010-11-13 21:53:34 +00001800
1801 CallArgList Args;
1802
1803 // Push the this ptr.
Eli Friedman04c9a492011-05-02 17:57:46 +00001804 Args.add(RValue::get(This), D->getThisType(getContext()));
Fariborz Jahanian34999872010-11-13 21:53:34 +00001805
Fariborz Jahanian34999872010-11-13 21:53:34 +00001806 // Push the src ptr.
Stephen Hines651f13c2014-04-23 16:59:28 -07001807 QualType QT = *(FPT->param_type_begin());
Chris Lattner2acc6e32011-07-18 04:24:23 +00001808 llvm::Type *t = CGM.getTypes().ConvertType(QT);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001809 Src = Builder.CreateBitCast(Src, t);
Eli Friedman04c9a492011-05-02 17:57:46 +00001810 Args.add(RValue::get(Src), QT);
Stephen Hines651f13c2014-04-23 16:59:28 -07001811
Fariborz Jahanian34999872010-11-13 21:53:34 +00001812 // Skip over first argument (Src).
Stephen Hines176edba2014-12-01 14:53:08 -08001813 EmitCallArgs(Args, FPT, E->arg_begin() + 1, E->arg_end(), E->getConstructor(),
1814 /*ParamsToSkip*/ 1);
Stephen Hines651f13c2014-04-23 16:59:28 -07001815
John McCall0f3d0972012-07-07 06:41:13 +00001816 EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, RequiredArgs::All),
1817 Callee, ReturnValueSlot(), Args, D);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001818}
1819
1820void
John McCallc0bf4622010-02-23 00:48:20 +00001821CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1822 CXXCtorType CtorType,
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001823 const FunctionArgList &Args,
1824 SourceLocation Loc) {
John McCallc0bf4622010-02-23 00:48:20 +00001825 CallArgList DelegateArgs;
1826
1827 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
1828 assert(I != E && "no parameters to constructor");
1829
1830 // this
Eli Friedman04c9a492011-05-02 17:57:46 +00001831 DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType());
John McCallc0bf4622010-02-23 00:48:20 +00001832 ++I;
1833
1834 // vtt
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001835 if (llvm::Value *VTT = GetVTTParameter(GlobalDecl(Ctor, CtorType),
Douglas Gregor378e1e72013-01-31 05:50:40 +00001836 /*ForVirtualBase=*/false,
1837 /*Delegating=*/true)) {
John McCallc0bf4622010-02-23 00:48:20 +00001838 QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
Eli Friedman04c9a492011-05-02 17:57:46 +00001839 DelegateArgs.add(RValue::get(VTT), VoidPP);
John McCallc0bf4622010-02-23 00:48:20 +00001840
Peter Collingbournee1e35f72013-06-28 20:45:28 +00001841 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
John McCallc0bf4622010-02-23 00:48:20 +00001842 assert(I != E && "cannot skip vtt parameter, already done with args");
John McCalld26bc762011-03-09 04:27:21 +00001843 assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
John McCallc0bf4622010-02-23 00:48:20 +00001844 ++I;
1845 }
1846 }
1847
1848 // Explicit arguments.
1849 for (; I != E; ++I) {
John McCall413ebdb2011-03-11 20:59:21 +00001850 const VarDecl *param = *I;
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001851 // FIXME: per-argument source location
1852 EmitDelegateCallArg(DelegateArgs, param, Loc);
John McCallc0bf4622010-02-23 00:48:20 +00001853 }
1854
Stephen Hines176edba2014-12-01 14:53:08 -08001855 llvm::Value *Callee =
1856 CGM.getAddrOfCXXStructor(Ctor, getFromCtorType(CtorType));
1857 EmitCall(CGM.getTypes()
1858 .arrangeCXXStructorDeclaration(Ctor, getFromCtorType(CtorType)),
Manman Ren63fd4082013-03-20 16:59:38 +00001859 Callee, ReturnValueSlot(), DelegateArgs, Ctor);
John McCallc0bf4622010-02-23 00:48:20 +00001860}
1861
Sean Huntb76af9c2011-05-03 23:05:34 +00001862namespace {
1863 struct CallDelegatingCtorDtor : EHScopeStack::Cleanup {
1864 const CXXDestructorDecl *Dtor;
1865 llvm::Value *Addr;
1866 CXXDtorType Type;
1867
1868 CallDelegatingCtorDtor(const CXXDestructorDecl *D, llvm::Value *Addr,
1869 CXXDtorType Type)
1870 : Dtor(D), Addr(Addr), Type(Type) {}
1871
Stephen Hines651f13c2014-04-23 16:59:28 -07001872 void Emit(CodeGenFunction &CGF, Flags flags) override {
Sean Huntb76af9c2011-05-03 23:05:34 +00001873 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001874 /*Delegating=*/true, Addr);
Sean Huntb76af9c2011-05-03 23:05:34 +00001875 }
1876 };
1877}
1878
Sean Hunt059ce0d2011-05-01 07:04:31 +00001879void
1880CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
1881 const FunctionArgList &Args) {
1882 assert(Ctor->isDelegatingConstructor());
1883
1884 llvm::Value *ThisPtr = LoadCXXThis();
1885
Eli Friedmanf3940782011-12-03 00:54:26 +00001886 QualType Ty = getContext().getTagDeclType(Ctor->getParent());
Eli Friedmand7722d92011-12-03 02:13:40 +00001887 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
John McCallf85e1932011-06-15 23:02:42 +00001888 AggValueSlot AggSlot =
Eli Friedmanf3940782011-12-03 00:54:26 +00001889 AggValueSlot::forAddr(ThisPtr, Alignment, Qualifiers(),
John McCall7c2349b2011-08-25 20:40:09 +00001890 AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +00001891 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +00001892 AggValueSlot::IsNotAliased);
Sean Hunt059ce0d2011-05-01 07:04:31 +00001893
1894 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
Sean Hunt059ce0d2011-05-01 07:04:31 +00001895
Sean Huntb76af9c2011-05-03 23:05:34 +00001896 const CXXRecordDecl *ClassDecl = Ctor->getParent();
David Blaikie4e4d0842012-03-11 07:00:24 +00001897 if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
Sean Huntb76af9c2011-05-03 23:05:34 +00001898 CXXDtorType Type =
1899 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
1900
1901 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
1902 ClassDecl->getDestructor(),
1903 ThisPtr, Type);
1904 }
1905}
Sean Hunt059ce0d2011-05-01 07:04:31 +00001906
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001907void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
1908 CXXDtorType Type,
Anders Carlsson8e6404c2010-05-02 23:29:11 +00001909 bool ForVirtualBase,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001910 bool Delegating,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001911 llvm::Value *This) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001912 CGM.getCXXABI().EmitDestructorCall(*this, DD, Type, ForVirtualBase,
1913 Delegating, This);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001914}
1915
John McCall291ae942010-07-21 01:41:18 +00001916namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001917 struct CallLocalDtor : EHScopeStack::Cleanup {
John McCall291ae942010-07-21 01:41:18 +00001918 const CXXDestructorDecl *Dtor;
1919 llvm::Value *Addr;
1920
1921 CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
1922 : Dtor(D), Addr(Addr) {}
1923
Stephen Hines651f13c2014-04-23 16:59:28 -07001924 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall291ae942010-07-21 01:41:18 +00001925 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001926 /*ForVirtualBase=*/false,
1927 /*Delegating=*/false, Addr);
John McCall291ae942010-07-21 01:41:18 +00001928 }
1929 };
1930}
1931
John McCall81407d42010-07-21 06:29:51 +00001932void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
1933 llvm::Value *Addr) {
John McCall1f0fca52010-07-21 07:22:38 +00001934 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
John McCall81407d42010-07-21 06:29:51 +00001935}
1936
John McCallf1549f62010-07-06 01:34:17 +00001937void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
1938 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
1939 if (!ClassDecl) return;
1940 if (ClassDecl->hasTrivialDestructor()) return;
1941
1942 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCall642a75f2011-04-28 02:15:35 +00001943 assert(D && D->isUsed() && "destructor not marked as used!");
John McCall81407d42010-07-21 06:29:51 +00001944 PushDestructorCleanup(D, Addr);
John McCallf1549f62010-07-06 01:34:17 +00001945}
1946
Anders Carlssond103f9f2010-03-28 19:40:00 +00001947void
1948CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001949 const CXXRecordDecl *NearestVBase,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001950 CharUnits OffsetFromNearestVBase,
Anders Carlssond103f9f2010-03-28 19:40:00 +00001951 const CXXRecordDecl *VTableClass) {
Anders Carlssond103f9f2010-03-28 19:40:00 +00001952 // Compute the address point.
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +00001953 bool NeedsVirtualOffset;
1954 llvm::Value *VTableAddressPoint =
1955 CGM.getCXXABI().getVTableAddressPointInStructor(
1956 *this, VTableClass, Base, NearestVBase, NeedsVirtualOffset);
1957 if (!VTableAddressPoint)
1958 return;
Anders Carlssond103f9f2010-03-28 19:40:00 +00001959
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001960 // Compute where to store the address point.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001961 llvm::Value *VirtualOffset = nullptr;
Ken Dyck9a8ad9b2011-03-23 00:45:26 +00001962 CharUnits NonVirtualOffset = CharUnits::Zero();
Anders Carlsson3e79c302010-04-20 18:05:10 +00001963
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +00001964 if (NeedsVirtualOffset) {
Anders Carlsson3e79c302010-04-20 18:05:10 +00001965 // We need to use the virtual base offset offset because the virtual base
1966 // might have a different offset in the most derived class.
Reid Klecknerb0f533e2013-05-29 18:02:47 +00001967 VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(*this,
1968 LoadCXXThis(),
1969 VTableClass,
1970 NearestVBase);
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001971 NonVirtualOffset = OffsetFromNearestVBase;
Anders Carlsson3e79c302010-04-20 18:05:10 +00001972 } else {
Anders Carlsson8246cc72010-05-03 00:29:58 +00001973 // We can just use the base offset in the complete class.
Ken Dyck4230d522011-03-24 01:21:01 +00001974 NonVirtualOffset = Base.getBaseOffset();
Anders Carlsson3e79c302010-04-20 18:05:10 +00001975 }
Anders Carlsson8246cc72010-05-03 00:29:58 +00001976
1977 // Apply the offsets.
1978 llvm::Value *VTableField = LoadCXXThis();
1979
Ken Dyck9a8ad9b2011-03-23 00:45:26 +00001980 if (!NonVirtualOffset.isZero() || VirtualOffset)
Anders Carlsson8246cc72010-05-03 00:29:58 +00001981 VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
1982 NonVirtualOffset,
1983 VirtualOffset);
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001984
Anders Carlssond103f9f2010-03-28 19:40:00 +00001985 // Finally, store the address point.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001986 llvm::Type *AddressPointPtrTy =
Anders Carlssond103f9f2010-03-28 19:40:00 +00001987 VTableAddressPoint->getType()->getPointerTo();
1988 VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
Kostya Serebryany8cb4a072012-03-26 17:03:51 +00001989 llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
1990 CGM.DecorateInstruction(Store, CGM.getTBAAInfoForVTablePtr());
Anders Carlssond103f9f2010-03-28 19:40:00 +00001991}
1992
Anders Carlsson603d6d12010-03-28 21:07:49 +00001993void
1994CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001995 const CXXRecordDecl *NearestVBase,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001996 CharUnits OffsetFromNearestVBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001997 bool BaseIsNonVirtualPrimaryBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001998 const CXXRecordDecl *VTableClass,
1999 VisitedVirtualBasesSetTy& VBases) {
2000 // If this base is a non-virtual primary base the address point has already
2001 // been set.
2002 if (!BaseIsNonVirtualPrimaryBase) {
2003 // Initialize the vtable pointer for this base.
Anders Carlsson42358402010-05-03 00:07:07 +00002004 InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
Timur Iskhodzhanov7f918f92013-08-21 17:33:16 +00002005 VTableClass);
Anders Carlsson603d6d12010-03-28 21:07:49 +00002006 }
2007
2008 const CXXRecordDecl *RD = Base.getBase();
2009
2010 // Traverse bases.
Stephen Hines651f13c2014-04-23 16:59:28 -07002011 for (const auto &I : RD->bases()) {
Anders Carlsson603d6d12010-03-28 21:07:49 +00002012 CXXRecordDecl *BaseDecl
Stephen Hines651f13c2014-04-23 16:59:28 -07002013 = cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Anders Carlsson603d6d12010-03-28 21:07:49 +00002014
2015 // Ignore classes without a vtable.
2016 if (!BaseDecl->isDynamicClass())
2017 continue;
2018
Ken Dyckd6fb21f2011-03-23 01:04:18 +00002019 CharUnits BaseOffset;
2020 CharUnits BaseOffsetFromNearestVBase;
Anders Carlsson14da9de2010-03-29 01:16:41 +00002021 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlsson603d6d12010-03-28 21:07:49 +00002022
Stephen Hines651f13c2014-04-23 16:59:28 -07002023 if (I.isVirtual()) {
Anders Carlsson603d6d12010-03-28 21:07:49 +00002024 // Check if we've visited this virtual base before.
Stephen Hines176edba2014-12-01 14:53:08 -08002025 if (!VBases.insert(BaseDecl).second)
Anders Carlsson603d6d12010-03-28 21:07:49 +00002026 continue;
2027
2028 const ASTRecordLayout &Layout =
2029 getContext().getASTRecordLayout(VTableClass);
2030
Ken Dyckd6fb21f2011-03-23 01:04:18 +00002031 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
2032 BaseOffsetFromNearestVBase = CharUnits::Zero();
Anders Carlsson14da9de2010-03-29 01:16:41 +00002033 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlsson603d6d12010-03-28 21:07:49 +00002034 } else {
2035 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
2036
Ken Dyck4230d522011-03-24 01:21:01 +00002037 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson42358402010-05-03 00:07:07 +00002038 BaseOffsetFromNearestVBase =
Ken Dyckd6fb21f2011-03-23 01:04:18 +00002039 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson14da9de2010-03-29 01:16:41 +00002040 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlsson603d6d12010-03-28 21:07:49 +00002041 }
2042
Ken Dyck4230d522011-03-24 01:21:01 +00002043 InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
Stephen Hines651f13c2014-04-23 16:59:28 -07002044 I.isVirtual() ? BaseDecl : NearestVBase,
Anders Carlsson42358402010-05-03 00:07:07 +00002045 BaseOffsetFromNearestVBase,
Anders Carlsson14da9de2010-03-29 01:16:41 +00002046 BaseDeclIsNonVirtualPrimaryBase,
Timur Iskhodzhanov7f918f92013-08-21 17:33:16 +00002047 VTableClass, VBases);
Anders Carlsson603d6d12010-03-28 21:07:49 +00002048 }
2049}
2050
2051void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
2052 // Ignore classes without a vtable.
Anders Carlsson07036902010-03-26 04:39:42 +00002053 if (!RD->isDynamicClass())
Anders Carlsson3b5ad222010-01-01 20:29:01 +00002054 return;
2055
Anders Carlsson603d6d12010-03-28 21:07:49 +00002056 // Initialize the vtable pointers for this class and all of its bases.
2057 VisitedVirtualBasesSetTy VBases;
Ken Dyck4230d522011-03-24 01:21:01 +00002058 InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002059 /*NearestVBase=*/nullptr,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00002060 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
Timur Iskhodzhanov7f918f92013-08-21 17:33:16 +00002061 /*BaseIsNonVirtualPrimaryBase=*/false, RD, VBases);
Timur Iskhodzhanov5bd0d442013-10-09 18:16:58 +00002062
2063 if (RD->getNumVBases())
2064 CGM.getCXXABI().initializeHiddenVirtualInheritanceMembers(*this, RD);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00002065}
Dan Gohman043fb9a2010-10-26 18:44:08 +00002066
2067llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
Chris Lattner2acc6e32011-07-18 04:24:23 +00002068 llvm::Type *Ty) {
Dan Gohman043fb9a2010-10-26 18:44:08 +00002069 llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
Kostya Serebryany8cb4a072012-03-26 17:03:51 +00002070 llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
2071 CGM.DecorateInstruction(VTable, CGM.getTBAAInfoForVTablePtr());
2072 return VTable;
Dan Gohman043fb9a2010-10-26 18:44:08 +00002073}
Anders Carlssona2447e02011-05-08 20:32:23 +00002074
Anders Carlssona2447e02011-05-08 20:32:23 +00002075
2076// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
2077// quite what we want.
2078static const Expr *skipNoOpCastsAndParens(const Expr *E) {
2079 while (true) {
2080 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
2081 E = PE->getSubExpr();
2082 continue;
2083 }
2084
2085 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
2086 if (CE->getCastKind() == CK_NoOp) {
2087 E = CE->getSubExpr();
2088 continue;
2089 }
2090 }
2091 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2092 if (UO->getOpcode() == UO_Extension) {
2093 E = UO->getSubExpr();
2094 continue;
2095 }
2096 }
2097 return E;
2098 }
2099}
2100
Benjamin Kramer9581ed02013-08-25 22:46:27 +00002101bool
2102CodeGenFunction::CanDevirtualizeMemberFunctionCall(const Expr *Base,
2103 const CXXMethodDecl *MD) {
2104 // When building with -fapple-kext, all calls must go through the vtable since
2105 // the kernel linker can do runtime patching of vtables.
2106 if (getLangOpts().AppleKext)
2107 return false;
2108
Anders Carlssona2447e02011-05-08 20:32:23 +00002109 // If the most derived class is marked final, we know that no subclass can
2110 // override this member function and so we can devirtualize it. For example:
2111 //
2112 // struct A { virtual void f(); }
2113 // struct B final : A { };
2114 //
2115 // void f(B *b) {
2116 // b->f();
2117 // }
2118 //
Benjamin Kramer9581ed02013-08-25 22:46:27 +00002119 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
Anders Carlssona2447e02011-05-08 20:32:23 +00002120 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
2121 return true;
2122
2123 // If the member function is marked 'final', we know that it can't be
2124 // overridden and can therefore devirtualize it.
2125 if (MD->hasAttr<FinalAttr>())
2126 return true;
2127
2128 // Similarly, if the class itself is marked 'final' it can't be overridden
2129 // and we can therefore devirtualize the member function call.
2130 if (MD->getParent()->hasAttr<FinalAttr>())
2131 return true;
2132
2133 Base = skipNoOpCastsAndParens(Base);
2134 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
2135 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
2136 // This is a record decl. We know the type and can devirtualize it.
2137 return VD->getType()->isRecordType();
2138 }
2139
2140 return false;
2141 }
Benjamin Kramer9581ed02013-08-25 22:46:27 +00002142
2143 // We can devirtualize calls on an object accessed by a class member access
2144 // expression, since by C++11 [basic.life]p6 we know that it can't refer to
2145 // a derived class object constructed in the same location.
2146 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Base))
2147 if (const ValueDecl *VD = dyn_cast<ValueDecl>(ME->getMemberDecl()))
2148 return VD->getType()->isRecordType();
2149
Anders Carlssona2447e02011-05-08 20:32:23 +00002150 // We can always devirtualize calls on temporary object expressions.
2151 if (isa<CXXConstructExpr>(Base))
2152 return true;
2153
2154 // And calls on bound temporaries.
2155 if (isa<CXXBindTemporaryExpr>(Base))
2156 return true;
2157
2158 // Check if this is a call expr that returns a record type.
2159 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
2160 return CE->getCallReturnType()->isRecordType();
2161
2162 // We can't devirtualize the call.
2163 return false;
2164}
2165
Anders Carlssona2447e02011-05-08 20:32:23 +00002166llvm::Value *
2167CodeGenFunction::EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E,
2168 const CXXMethodDecl *MD,
2169 llvm::Value *This) {
John McCallde5d3c72012-02-17 03:33:10 +00002170 llvm::FunctionType *fnType =
2171 CGM.getTypes().GetFunctionType(
2172 CGM.getTypes().arrangeCXXMethodDeclaration(MD));
Anders Carlssona2447e02011-05-08 20:32:23 +00002173
Benjamin Kramer9581ed02013-08-25 22:46:27 +00002174 if (MD->isVirtual() && !CanDevirtualizeMemberFunctionCall(E->getArg(0), MD))
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +00002175 return CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, fnType);
Anders Carlssona2447e02011-05-08 20:32:23 +00002176
John McCallde5d3c72012-02-17 03:33:10 +00002177 return CGM.GetAddrOfFunction(MD, fnType);
Anders Carlssona2447e02011-05-08 20:32:23 +00002178}
Eli Friedmanbd89f8c2012-02-16 01:37:33 +00002179
Faisal Valid6992ab2013-09-29 08:45:24 +00002180void CodeGenFunction::EmitForwardingCallToLambda(
2181 const CXXMethodDecl *callOperator,
2182 CallArgList &callArgs) {
Eli Friedman21f6ed92012-02-16 03:47:28 +00002183 // Get the address of the call operator.
John McCall0f3d0972012-07-07 06:41:13 +00002184 const CGFunctionInfo &calleeFnInfo =
2185 CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
2186 llvm::Value *callee =
2187 CGM.GetAddrOfFunction(GlobalDecl(callOperator),
2188 CGM.getTypes().GetFunctionType(calleeFnInfo));
Eli Friedman21f6ed92012-02-16 03:47:28 +00002189
John McCall0f3d0972012-07-07 06:41:13 +00002190 // Prepare the return slot.
2191 const FunctionProtoType *FPT =
2192 callOperator->getType()->castAs<FunctionProtoType>();
Stephen Hines651f13c2014-04-23 16:59:28 -07002193 QualType resultType = FPT->getReturnType();
John McCall0f3d0972012-07-07 06:41:13 +00002194 ReturnValueSlot returnSlot;
2195 if (!resultType->isVoidType() &&
2196 calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
John McCall9d232c82013-03-07 21:37:08 +00002197 !hasScalarEvaluationKind(calleeFnInfo.getReturnType()))
John McCall0f3d0972012-07-07 06:41:13 +00002198 returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
2199
2200 // We don't need to separately arrange the call arguments because
2201 // the call can't be variadic anyway --- it's impossible to forward
2202 // variadic arguments.
Eli Friedman21f6ed92012-02-16 03:47:28 +00002203
2204 // Now emit our call.
John McCall0f3d0972012-07-07 06:41:13 +00002205 RValue RV = EmitCall(calleeFnInfo, callee, returnSlot,
2206 callArgs, callOperator);
Eli Friedman21f6ed92012-02-16 03:47:28 +00002207
John McCall0f3d0972012-07-07 06:41:13 +00002208 // If necessary, copy the returned value into the slot.
2209 if (!resultType->isVoidType() && returnSlot.isNull())
2210 EmitReturnOfRValue(RV, resultType);
Eli Friedman50f089a2012-12-13 23:37:17 +00002211 else
2212 EmitBranchThroughCleanup(ReturnBlock);
Eli Friedman21f6ed92012-02-16 03:47:28 +00002213}
2214
Eli Friedman64bee652012-02-25 02:48:22 +00002215void CodeGenFunction::EmitLambdaBlockInvokeBody() {
2216 const BlockDecl *BD = BlockInfo->getBlockDecl();
2217 const VarDecl *variable = BD->capture_begin()->getVariable();
2218 const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
2219
2220 // Start building arguments for forwarding call
2221 CallArgList CallArgs;
2222
2223 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2224 llvm::Value *ThisPtr = GetAddrOfBlockDecl(variable, false);
2225 CallArgs.add(RValue::get(ThisPtr), ThisType);
2226
2227 // Add the rest of the parameters.
Stephen Hines651f13c2014-04-23 16:59:28 -07002228 for (auto param : BD->params())
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00002229 EmitDelegateCallArg(CallArgs, param, param->getLocStart());
Stephen Hines651f13c2014-04-23 16:59:28 -07002230
Faisal Valid6992ab2013-09-29 08:45:24 +00002231 assert(!Lambda->isGenericLambda() &&
2232 "generic lambda interconversion to block not implemented");
2233 EmitForwardingCallToLambda(Lambda->getLambdaCallOperator(), CallArgs);
Eli Friedman64bee652012-02-25 02:48:22 +00002234}
2235
2236void CodeGenFunction::EmitLambdaToBlockPointerBody(FunctionArgList &Args) {
John McCallf5ebf9b2013-05-03 07:33:41 +00002237 if (cast<CXXMethodDecl>(CurCodeDecl)->isVariadic()) {
Eli Friedman64bee652012-02-25 02:48:22 +00002238 // FIXME: Making this work correctly is nasty because it requires either
2239 // cloning the body of the call operator or making the call operator forward.
John McCallf5ebf9b2013-05-03 07:33:41 +00002240 CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function");
Eli Friedman64bee652012-02-25 02:48:22 +00002241 return;
2242 }
2243
Richard Smith3cebc732013-11-05 09:12:18 +00002244 EmitFunctionBody(Args, cast<FunctionDecl>(CurGD.getDecl())->getBody());
Eli Friedman64bee652012-02-25 02:48:22 +00002245}
2246
2247void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
2248 const CXXRecordDecl *Lambda = MD->getParent();
2249
2250 // Start building arguments for forwarding call
2251 CallArgList CallArgs;
2252
2253 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2254 llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
2255 CallArgs.add(RValue::get(ThisPtr), ThisType);
2256
2257 // Add the rest of the parameters.
Stephen Hines651f13c2014-04-23 16:59:28 -07002258 for (auto Param : MD->params())
2259 EmitDelegateCallArg(CallArgs, Param, Param->getLocStart());
2260
Faisal Valid6992ab2013-09-29 08:45:24 +00002261 const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
2262 // For a generic lambda, find the corresponding call operator specialization
2263 // to which the call to the static-invoker shall be forwarded.
2264 if (Lambda->isGenericLambda()) {
2265 assert(MD->isFunctionTemplateSpecialization());
2266 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
2267 FunctionTemplateDecl *CallOpTemplate = CallOp->getDescribedFunctionTemplate();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002268 void *InsertPos = nullptr;
Faisal Valid6992ab2013-09-29 08:45:24 +00002269 FunctionDecl *CorrespondingCallOpSpecialization =
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002270 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
Faisal Valid6992ab2013-09-29 08:45:24 +00002271 assert(CorrespondingCallOpSpecialization);
2272 CallOp = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
2273 }
2274 EmitForwardingCallToLambda(CallOp, CallArgs);
Eli Friedman64bee652012-02-25 02:48:22 +00002275}
2276
Douglas Gregor27dd7d92012-02-17 03:02:34 +00002277void CodeGenFunction::EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD) {
2278 if (MD->isVariadic()) {
Eli Friedman21f6ed92012-02-16 03:47:28 +00002279 // FIXME: Making this work correctly is nasty because it requires either
2280 // cloning the body of the call operator or making the call operator forward.
2281 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
Eli Friedman64bee652012-02-25 02:48:22 +00002282 return;
Eli Friedman21f6ed92012-02-16 03:47:28 +00002283 }
2284
Douglas Gregor27dd7d92012-02-17 03:02:34 +00002285 EmitLambdaDelegatingInvokeBody(MD);
Eli Friedmanbd89f8c2012-02-16 01:37:33 +00002286}