blob: d31d50bb4b26c999248d1e7aa996a03d651c20cf [file] [log] [blame]
Anders Carlsson59486a22009-11-24 05:51:11 +00001//===--- CGClass.cpp - Emit LLVM Code for C++ classes ---------------------===//
Anders Carlsson9a57c5a2009-09-12 04:27:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with C++ code generation of classes
11//
12//===----------------------------------------------------------------------===//
13
Eli Friedman2495ab02012-02-25 02:48:22 +000014#include "CGBlocks.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000015#include "CGCXXABI.h"
Devang Pateld76c1db2010-08-11 21:04:37 +000016#include "CGDebugInfo.h"
Lang Hamesbf122742013-02-17 07:22:09 +000017#include "CGRecordLayout.h"
Anders Carlsson9a57c5a2009-09-12 04:27:24 +000018#include "CodeGenFunction.h"
Anders Carlssonc6d171e2009-10-06 22:43:30 +000019#include "clang/AST/CXXInheritance.h"
Faisal Vali571df122013-09-29 08:45:24 +000020#include "clang/AST/DeclTemplate.h"
John McCall769250e2010-09-17 02:31:44 +000021#include "clang/AST/EvaluatedExprVisitor.h"
Anders Carlsson9a57c5a2009-09-12 04:27:24 +000022#include "clang/AST/RecordLayout.h"
John McCallb81884d2010-02-19 09:25:03 +000023#include "clang/AST/StmtCXX.h"
Lang Hamesbf122742013-02-17 07:22:09 +000024#include "clang/Basic/TargetBuiltins.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000025#include "clang/CodeGen/CGFunctionInfo.h"
Devang Patelb6ed3692011-02-22 20:55:26 +000026#include "clang/Frontend/CodeGenOptions.h"
Anders Carlssonc6d171e2009-10-06 22:43:30 +000027
Anders Carlsson9a57c5a2009-09-12 04:27:24 +000028using namespace clang;
29using namespace CodeGen;
30
Ken Dycka1a4ae32011-03-22 00:53:26 +000031static CharUnits
Anders Carlssond829a022010-04-24 21:06:20 +000032ComputeNonVirtualBaseClassOffset(ASTContext &Context,
33 const CXXRecordDecl *DerivedClass,
John McCallcf142162010-08-07 06:22:56 +000034 CastExpr::path_const_iterator Start,
35 CastExpr::path_const_iterator End) {
Ken Dycka1a4ae32011-03-22 00:53:26 +000036 CharUnits Offset = CharUnits::Zero();
Anders Carlssond829a022010-04-24 21:06:20 +000037
38 const CXXRecordDecl *RD = DerivedClass;
39
John McCallcf142162010-08-07 06:22:56 +000040 for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
Anders Carlssond829a022010-04-24 21:06:20 +000041 const CXXBaseSpecifier *Base = *I;
42 assert(!Base->isVirtual() && "Should not see virtual bases here!");
43
44 // Get the layout.
45 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
46
47 const CXXRecordDecl *BaseDecl =
48 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
49
50 // Add the offset.
Ken Dycka1a4ae32011-03-22 00:53:26 +000051 Offset += Layout.getBaseClassOffset(BaseDecl);
Anders Carlssond829a022010-04-24 21:06:20 +000052
53 RD = BaseDecl;
54 }
55
Ken Dycka1a4ae32011-03-22 00:53:26 +000056 return Offset;
Anders Carlssond829a022010-04-24 21:06:20 +000057}
Anders Carlsson9a57c5a2009-09-12 04:27:24 +000058
Anders Carlsson9150a2a2009-09-29 03:13:20 +000059llvm::Constant *
Anders Carlsson8a64c1c2010-04-24 21:23:59 +000060CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
John McCallcf142162010-08-07 06:22:56 +000061 CastExpr::path_const_iterator PathBegin,
62 CastExpr::path_const_iterator PathEnd) {
63 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlsson8a64c1c2010-04-24 21:23:59 +000064
Ken Dycka1a4ae32011-03-22 00:53:26 +000065 CharUnits Offset =
John McCallcf142162010-08-07 06:22:56 +000066 ComputeNonVirtualBaseClassOffset(getContext(), ClassDecl,
67 PathBegin, PathEnd);
Ken Dycka1a4ae32011-03-22 00:53:26 +000068 if (Offset.isZero())
Craig Topper8a13c412014-05-21 05:09:00 +000069 return nullptr;
70
Chris Lattner2192fe52011-07-18 04:24:23 +000071 llvm::Type *PtrDiffTy =
Anders Carlsson8a64c1c2010-04-24 21:23:59 +000072 Types.ConvertType(getContext().getPointerDiffType());
73
Ken Dycka1a4ae32011-03-22 00:53:26 +000074 return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
Anders Carlsson9150a2a2009-09-29 03:13:20 +000075}
76
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +000077/// Gets the address of a direct base class within a complete object.
John McCall6ce74722010-02-16 04:15:37 +000078/// This should only be used for (1) non-virtual bases or (2) virtual bases
79/// when the type is known to be complete (e.g. in complete destructors).
80///
81/// The object pointed to by 'This' is assumed to be non-null.
82llvm::Value *
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +000083CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(llvm::Value *This,
84 const CXXRecordDecl *Derived,
85 const CXXRecordDecl *Base,
86 bool BaseIsVirtual) {
John McCall6ce74722010-02-16 04:15:37 +000087 // 'this' must be a pointer (in some address space) to Derived.
88 assert(This->getType()->isPointerTy() &&
89 cast<llvm::PointerType>(This->getType())->getElementType()
90 == ConvertType(Derived));
91
92 // Compute the offset of the virtual base.
Ken Dyck6aa767c2011-03-22 01:21:15 +000093 CharUnits Offset;
John McCall6ce74722010-02-16 04:15:37 +000094 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +000095 if (BaseIsVirtual)
Ken Dyck6aa767c2011-03-22 01:21:15 +000096 Offset = Layout.getVBaseClassOffset(Base);
John McCall6ce74722010-02-16 04:15:37 +000097 else
Ken Dyck6aa767c2011-03-22 01:21:15 +000098 Offset = Layout.getBaseClassOffset(Base);
John McCall6ce74722010-02-16 04:15:37 +000099
100 // Shift and cast down to the base type.
101 // TODO: for complete types, this should be possible with a GEP.
102 llvm::Value *V = This;
Ken Dyck6aa767c2011-03-22 01:21:15 +0000103 if (Offset.isPositive()) {
John McCall6ce74722010-02-16 04:15:37 +0000104 V = Builder.CreateBitCast(V, Int8PtrTy);
Ken Dyck6aa767c2011-03-22 01:21:15 +0000105 V = Builder.CreateConstInBoundsGEP1_64(V, Offset.getQuantity());
John McCall6ce74722010-02-16 04:15:37 +0000106 }
107 V = Builder.CreateBitCast(V, ConvertType(Base)->getPointerTo());
108
109 return V;
Anders Carlssone87fae92010-03-28 19:40:00 +0000110}
John McCall6ce74722010-02-16 04:15:37 +0000111
Anders Carlsson53cebd12010-04-20 16:03:35 +0000112static llvm::Value *
John McCall13a39c62012-08-01 05:04:58 +0000113ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, llvm::Value *ptr,
114 CharUnits nonVirtualOffset,
115 llvm::Value *virtualOffset) {
116 // Assert that we have something to do.
Craig Topper8a13c412014-05-21 05:09:00 +0000117 assert(!nonVirtualOffset.isZero() || virtualOffset != nullptr);
John McCall13a39c62012-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 Carlsson53cebd12010-04-20 16:03:35 +0000130
131 // Apply the base offset.
John McCall13a39c62012-08-01 05:04:58 +0000132 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
133 ptr = CGF.Builder.CreateInBoundsGEP(ptr, baseOffset, "add.ptr");
134 return ptr;
Anders Carlsson53cebd12010-04-20 16:03:35 +0000135}
136
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000137llvm::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 McCallcf142162010-08-07 06:22:56 +0000142 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssond829a022010-04-24 21:06:20 +0000143
John McCallcf142162010-08-07 06:22:56 +0000144 CastExpr::path_const_iterator Start = PathBegin;
Craig Topper8a13c412014-05-21 05:09:00 +0000145 const CXXRecordDecl *VBase = nullptr;
146
John McCall13a39c62012-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 Carlssond829a022010-04-24 21:06:20 +0000151 if ((*Start)->isVirtual()) {
152 VBase =
153 cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
154 ++Start;
155 }
John McCall13a39c62012-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 Dycka1a4ae32011-03-22 00:53:26 +0000160 CharUnits NonVirtualOffset =
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000161 ComputeNonVirtualBaseClassOffset(getContext(), VBase ? VBase : Derived,
John McCallcf142162010-08-07 06:22:56 +0000162 Start, PathEnd);
Anders Carlssond829a022010-04-24 21:06:20 +0000163
John McCall13a39c62012-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;
Craig Topper8a13c412014-05-21 05:09:00 +0000171 VBase = nullptr; // we no longer have a virtual step
John McCall13a39c62012-08-01 05:04:58 +0000172 }
173
Anders Carlssond829a022010-04-24 21:06:20 +0000174 // Get the base pointer type.
Chris Lattner2192fe52011-07-18 04:24:23 +0000175 llvm::Type *BasePtrTy =
John McCallcf142162010-08-07 06:22:56 +0000176 ConvertType((PathEnd[-1])->getType())->getPointerTo();
John McCall13a39c62012-08-01 05:04:58 +0000177
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000178 QualType DerivedTy = getContext().getRecordType(Derived);
179 CharUnits DerivedAlign = getContext().getTypeAlignInChars(DerivedTy);
180
John McCall13a39c62012-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 Dycka1a4ae32011-03-22 00:53:26 +0000183 if (NonVirtualOffset.isZero() && !VBase) {
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000184 if (sanitizePerformTypeCheck()) {
185 EmitTypeCheck(TCK_Upcast, Loc, Value, DerivedTy, DerivedAlign,
186 !NullCheckValue);
187 }
Anders Carlssond829a022010-04-24 21:06:20 +0000188 return Builder.CreateBitCast(Value, BasePtrTy);
Craig Topper8a13c412014-05-21 05:09:00 +0000189 }
John McCall13a39c62012-08-01 05:04:58 +0000190
Craig Topper8a13c412014-05-21 05:09:00 +0000191 llvm::BasicBlock *origBB = nullptr;
192 llvm::BasicBlock *endBB = nullptr;
193
John McCall13a39c62012-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 Carlssond829a022010-04-24 21:06:20 +0000196 if (NullCheckValue) {
John McCall13a39c62012-08-01 05:04:58 +0000197 origBB = Builder.GetInsertBlock();
198 llvm::BasicBlock *notNullBB = createBasicBlock("cast.notnull");
199 endBB = createBasicBlock("cast.end");
Anders Carlssond829a022010-04-24 21:06:20 +0000200
John McCall13a39c62012-08-01 05:04:58 +0000201 llvm::Value *isNull = Builder.CreateIsNull(Value);
202 Builder.CreateCondBr(isNull, endBB, notNullBB);
203 EmitBlock(notNullBB);
Anders Carlssond829a022010-04-24 21:06:20 +0000204 }
205
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000206 if (sanitizePerformTypeCheck()) {
207 EmitTypeCheck(VBase ? TCK_UpcastToVirtualBase : TCK_Upcast, Loc, Value,
208 DerivedTy, DerivedAlign, true);
209 }
210
John McCall13a39c62012-08-01 05:04:58 +0000211 // Compute the virtual offset.
Craig Topper8a13c412014-05-21 05:09:00 +0000212 llvm::Value *VirtualOffset = nullptr;
Anders Carlssona376b532011-01-29 03:18:56 +0000213 if (VBase) {
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000214 VirtualOffset =
215 CGM.getCXXABI().GetVirtualBaseClassOffset(*this, Value, Derived, VBase);
Anders Carlssona376b532011-01-29 03:18:56 +0000216 }
Anders Carlssond829a022010-04-24 21:06:20 +0000217
John McCall13a39c62012-08-01 05:04:58 +0000218 // Apply both offsets.
Ken Dycka1a4ae32011-03-22 00:53:26 +0000219 Value = ApplyNonVirtualAndVirtualOffset(*this, Value,
Ken Dyckcfc332c2011-03-23 00:45:26 +0000220 NonVirtualOffset,
Anders Carlssond829a022010-04-24 21:06:20 +0000221 VirtualOffset);
222
John McCall13a39c62012-08-01 05:04:58 +0000223 // Cast to the destination type.
Anders Carlssond829a022010-04-24 21:06:20 +0000224 Value = Builder.CreateBitCast(Value, BasePtrTy);
John McCall13a39c62012-08-01 05:04:58 +0000225
226 // Build a phi if we needed a null check.
Anders Carlssond829a022010-04-24 21:06:20 +0000227 if (NullCheckValue) {
John McCall13a39c62012-08-01 05:04:58 +0000228 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
229 Builder.CreateBr(endBB);
230 EmitBlock(endBB);
Anders Carlssond829a022010-04-24 21:06:20 +0000231
John McCall13a39c62012-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 Carlssond829a022010-04-24 21:06:20 +0000235 Value = PHI;
236 }
237
238 return Value;
239}
240
241llvm::Value *
Anders Carlsson8c793172009-11-23 17:57:54 +0000242CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value,
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000243 const CXXRecordDecl *Derived,
John McCallcf142162010-08-07 06:22:56 +0000244 CastExpr::path_const_iterator PathBegin,
245 CastExpr::path_const_iterator PathEnd,
Anders Carlsson8c793172009-11-23 17:57:54 +0000246 bool NullCheckValue) {
John McCallcf142162010-08-07 06:22:56 +0000247 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlsson8a64c1c2010-04-24 21:23:59 +0000248
Anders Carlsson8c793172009-11-23 17:57:54 +0000249 QualType DerivedTy =
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000250 getContext().getCanonicalType(getContext().getTagDeclType(Derived));
Chris Lattner2192fe52011-07-18 04:24:23 +0000251 llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
Richard Smith2c5868c2013-02-13 21:18:23 +0000252
Anders Carlsson600f7372010-01-31 01:43:37 +0000253 llvm::Value *NonVirtualOffset =
John McCallcf142162010-08-07 06:22:56 +0000254 CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
Anders Carlsson600f7372010-01-31 01:43:37 +0000255
256 if (!NonVirtualOffset) {
257 // No offset, we can just cast back.
258 return Builder.CreateBitCast(Value, DerivedPtrTy);
259 }
Craig Topper8a13c412014-05-21 05:09:00 +0000260
261 llvm::BasicBlock *CastNull = nullptr;
262 llvm::BasicBlock *CastNotNull = nullptr;
263 llvm::BasicBlock *CastEnd = nullptr;
264
Anders Carlsson8c793172009-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 Carlsson98981b12011-04-11 00:30:07 +0000270 llvm::Value *IsNull = Builder.CreateIsNull(Value);
Anders Carlsson8c793172009-11-23 17:57:54 +0000271 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
272 EmitBlock(CastNotNull);
273 }
274
Anders Carlsson600f7372010-01-31 01:43:37 +0000275 // Apply the offset.
Eli Friedman87549262012-02-28 22:07:56 +0000276 Value = Builder.CreateBitCast(Value, Int8PtrTy);
277 Value = Builder.CreateGEP(Value, Builder.CreateNeg(NonVirtualOffset),
278 "sub.ptr");
Anders Carlsson600f7372010-01-31 01:43:37 +0000279
280 // Just cast.
281 Value = Builder.CreateBitCast(Value, DerivedPtrTy);
Anders Carlsson8c793172009-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 Foad20c0f022011-03-30 11:28:58 +0000289 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
Anders Carlsson8c793172009-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 Carlsson9a57c5a2009-09-12 04:27:24 +0000297}
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000298
299llvm::Value *CodeGenFunction::GetVTTParameter(GlobalDecl GD,
300 bool ForVirtualBase,
301 bool Delegating) {
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000302 if (!CGM.getCXXABI().NeedsVTTParameter(GD)) {
Anders Carlssone36a6b32010-01-02 01:01:18 +0000303 // This constructor/destructor does not need a VTT parameter.
Craig Topper8a13c412014-05-21 05:09:00 +0000304 return nullptr;
Anders Carlssone36a6b32010-01-02 01:01:18 +0000305 }
306
John McCalldec348f72013-05-03 07:33:41 +0000307 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CurCodeDecl)->getParent();
Anders Carlssone36a6b32010-01-02 01:01:18 +0000308 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
John McCall5c60a6f2010-02-18 19:59:28 +0000309
Anders Carlssone36a6b32010-01-02 01:01:18 +0000310 llvm::Value *VTT;
311
John McCall5c60a6f2010-02-18 19:59:28 +0000312 uint64_t SubVTTIndex;
313
Douglas Gregor61535002013-01-31 05:50:40 +0000314 if (Delegating) {
315 // If this is a delegating constructor call, just load the VTT.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000316 return LoadCXXVTT();
Douglas Gregor61535002013-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 Collingbourne66f82e62013-06-28 20:45:28 +0000320 assert(!CGM.getCXXABI().NeedsVTTParameter(CurGD) &&
John McCall5c60a6f2010-02-18 19:59:28 +0000321 "doing no-op VTT offset in base dtor/ctor?");
Anders Carlsson4d205ba2010-05-02 23:33:10 +0000322 assert(!ForVirtualBase && "Can't have same class as virtual base!");
John McCall5c60a6f2010-02-18 19:59:28 +0000323 SubVTTIndex = 0;
324 } else {
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000325 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Ken Dyck16ffcac2011-03-24 01:21:01 +0000326 CharUnits BaseOffset = ForVirtualBase ?
327 Layout.getVBaseClassOffset(Base) :
328 Layout.getBaseClassOffset(Base);
Anders Carlsson859b3062010-05-02 23:53:25 +0000329
330 SubVTTIndex =
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000331 CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
John McCall5c60a6f2010-02-18 19:59:28 +0000332 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
333 }
Anders Carlssone36a6b32010-01-02 01:01:18 +0000334
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000335 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
Anders Carlssone36a6b32010-01-02 01:01:18 +0000336 // A VTT parameter was passed to the constructor, use it.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000337 VTT = LoadCXXVTT();
338 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
Anders Carlssone36a6b32010-01-02 01:01:18 +0000339 } else {
340 // We're the complete constructor, so get the VTT by name.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000341 VTT = CGM.getVTables().GetAddrOfVTT(RD);
342 VTT = Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
Anders Carlssone36a6b32010-01-02 01:01:18 +0000343 }
344
345 return VTT;
346}
347
John McCall1d987562010-07-21 01:23:41 +0000348namespace {
John McCallf99a6312010-07-21 05:30:47 +0000349 /// Call the destructor for a direct base class.
John McCallcda666c2010-07-21 07:22:38 +0000350 struct CallBaseDtor : EHScopeStack::Cleanup {
John McCallf99a6312010-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 McCall1d987562010-07-21 01:23:41 +0000355
Craig Topper4f12f102014-03-12 06:41:41 +0000356 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallf99a6312010-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 Gregor61535002013-01-31 05:50:40 +0000365 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual,
366 /*Delegating=*/false, Addr);
John McCall1d987562010-07-21 01:23:41 +0000367 }
368 };
John McCall769250e2010-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 McCall1d987562010-07-21 01:23:41 +0000392}
393
Anders Carlssonfb404882009-12-24 22:46:43 +0000394static void EmitBaseInitializer(CodeGenFunction &CGF,
395 const CXXRecordDecl *ClassDecl,
Alexis Hunt1d792652011-01-08 20:30:50 +0000396 CXXCtorInitializer *BaseInit,
Anders Carlssonfb404882009-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 Carlsson1c0f8bb2010-04-12 00:51:03 +0000407 bool isBaseVirtual = BaseInit->isBaseVirtual();
Anders Carlssonfb404882009-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 McCall769250e2010-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 McCall6ce74722010-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 Carlssonc4ba0cd2010-04-24 23:01:49 +0000421 llvm::Value *V =
422 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
John McCallf99a6312010-07-21 05:30:47 +0000423 BaseClassDecl,
424 isBaseVirtual);
Eli Friedman38cd36d2011-12-03 02:13:40 +0000425 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(BaseType);
John McCall8d6fc952011-08-25 20:40:09 +0000426 AggValueSlot AggSlot =
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000427 AggValueSlot::forAddr(V, Alignment, Qualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +0000428 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +0000429 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000430 AggValueSlot::IsNotAliased);
John McCall7a626f62010-09-15 10:14:12 +0000431
432 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
Anders Carlsson5ade5d32010-02-06 20:00:21 +0000433
David Blaikiebbafb8a2012-03-11 07:00:24 +0000434 if (CGF.CGM.getLangOpts().Exceptions &&
Anders Carlsson08ce5ed2011-02-20 00:20:27 +0000435 !BaseClassDecl->hasTrivialDestructor())
John McCallcda666c2010-07-21 07:22:38 +0000436 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
437 isBaseVirtual);
Anders Carlssonfb404882009-12-24 22:46:43 +0000438}
439
Douglas Gregor94f9a482010-05-05 05:51:00 +0000440static void EmitAggMemberInitializer(CodeGenFunction &CGF,
441 LValue LHS,
Eli Friedman6ae63022012-02-14 02:15:49 +0000442 Expr *Init,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000443 llvm::Value *ArrayIndexVar,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000444 QualType T,
Eli Friedman6ae63022012-02-14 02:15:49 +0000445 ArrayRef<VarDecl *> ArrayIndexes,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000446 unsigned Index) {
Eli Friedman6ae63022012-02-14 02:15:49 +0000447 if (Index == ArrayIndexes.size()) {
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000448 LValue LV = LHS;
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000449
Richard Smithcc1b96d2013-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 Redl4e04dd12012-02-19 15:41:54 +0000459
Richard Smithcc1b96d2013-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 Gregor94f9a482010-05-05 05:51:00 +0000464 }
John McCall7a626f62010-09-15 10:14:12 +0000465
Richard Smithcc1b96d2013-06-12 22:31:48 +0000466 switch (CGF.getEvaluationKind(T)) {
467 case TEK_Scalar:
Craig Topper8a13c412014-05-21 05:09:00 +0000468 CGF.EmitScalarInit(Init, /*decl*/ nullptr, LV, false);
Richard Smithcc1b96d2013-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 Redl4e04dd12012-02-19 15:41:54 +0000484
Douglas Gregor94f9a482010-05-05 05:51:00 +0000485 return;
486 }
Richard Smithcc1b96d2013-06-12 22:31:48 +0000487
Douglas Gregor94f9a482010-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 Friedman6ae63022012-02-14 02:15:49 +0000491 = CGF.GetAddrOfLocalVar(ArrayIndexes[Index]);
Douglas Gregor94f9a482010-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 Gregor94f9a482010-05-05 05:51:00 +0000510 llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
Chris Lattner44456d22010-05-06 06:35:23 +0000511 llvm::Value *NumElementsPtr =
512 llvm::ConstantInt::get(Counter->getType(), NumElements);
Douglas Gregor94f9a482010-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 Smithcc1b96d2013-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 Gregor94f9a482010-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 McCall1d987562010-07-21 01:23:41 +0000541
Anders Carlssonfb404882009-12-24 22:46:43 +0000542static void EmitMemberInitializer(CodeGenFunction &CGF,
543 const CXXRecordDecl *ClassDecl,
Alexis Hunt1d792652011-01-08 20:30:50 +0000544 CXXCtorInitializer *MemberInit,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000545 const CXXConstructorDecl *Constructor,
546 FunctionArgList &Args) {
Francois Pichetd583da02010-12-04 09:14:42 +0000547 assert(MemberInit->isAnyMemberInitializer() &&
Anders Carlssonfb404882009-12-24 22:46:43 +0000548 "Must have member initializer!");
Richard Smith938f40b2011-06-11 17:19:42 +0000549 assert(MemberInit->getInit() && "Must have initializer!");
Anders Carlssonfb404882009-12-24 22:46:43 +0000550
551 // non-static data member initializers.
Francois Pichetd583da02010-12-04 09:14:42 +0000552 FieldDecl *Field = MemberInit->getAnyMember();
Eli Friedman6ae63022012-02-14 02:15:49 +0000553 QualType FieldType = Field->getType();
Anders Carlssonfb404882009-12-24 22:46:43 +0000554
555 llvm::Value *ThisPtr = CGF.LoadCXXThis();
Eli Friedman7f1ff602012-04-16 03:54:45 +0000556 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
Eli Friedmanf6d21842012-08-08 03:51:37 +0000557 LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
Eli Friedman7f1ff602012-04-16 03:54:45 +0000558
Francois Pichetd583da02010-12-04 09:14:42 +0000559 if (MemberInit->isIndirectMemberInitializer()) {
Eli Friedmanf6d21842012-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();
Aaron Ballman29c94602014-03-07 18:36:15 +0000563 for (const auto *I : IndirectField->chain())
Aaron Ballman13916082014-03-07 18:11:58 +0000564 LHS = CGF.EmitLValueForFieldInitialization(LHS, cast<FieldDecl>(I));
Francois Pichetd583da02010-12-04 09:14:42 +0000565 FieldType = MemberInit->getIndirectMember()->getAnonField()->getType();
John McCallc4094932010-05-21 01:18:57 +0000566 } else {
Eli Friedmanf6d21842012-08-08 03:51:37 +0000567 LHS = CGF.EmitLValueForFieldInitialization(LHS, Field);
Anders Carlssonfb404882009-12-24 22:46:43 +0000568 }
569
Eli Friedman6ae63022012-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 Rose54533f72013-08-07 16:16:48 +0000577 if (Array && Constructor->isDefaulted() &&
Eli Friedman6ae63022012-02-14 02:15:49 +0000578 Constructor->isCopyOrMoveConstructor()) {
579 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
Richard Smith993f25a2012-11-07 23:56:21 +0000580 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
Eli Friedman6ae63022012-02-14 02:15:49 +0000581 if (BaseElementTy.isPODType(CGF.getContext()) ||
Richard Smith993f25a2012-11-07 23:56:21 +0000582 (CE && CE->getConstructor()->isTrivial())) {
David Majnemer1573d732014-10-15 04:54:54 +0000583 unsigned SrcArgIndex =
584 CGF.CGM.getCXXABI().getSrcArgforCopyCtor(Constructor, Args);
Eli Friedman6ae63022012-02-14 02:15:49 +0000585 llvm::Value *SrcPtr
586 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
Eli Friedman7f1ff602012-04-16 03:54:45 +0000587 LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
588 LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field);
Eli Friedman6ae63022012-02-14 02:15:49 +0000589
590 // Copy the aggregate.
591 CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000592 LHS.isVolatileQualified());
Eli Friedman6ae63022012-02-14 02:15:49 +0000593 return;
594 }
595 }
596
597 ArrayRef<VarDecl *> ArrayIndexes;
598 if (MemberInit->getNumArrayIndices())
599 ArrayIndexes = MemberInit->getArrayIndexes();
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000600 CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit(), ArrayIndexes);
Eli Friedman6ae63022012-02-14 02:15:49 +0000601}
602
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000603void CodeGenFunction::EmitInitializerForField(FieldDecl *Field,
604 LValue LHS, Expr *Init,
605 ArrayRef<VarDecl *> ArrayIndexes) {
Eli Friedman6ae63022012-02-14 02:15:49 +0000606 QualType FieldType = Field->getType();
John McCall47fb9502013-03-07 21:37:08 +0000607 switch (getEvaluationKind(FieldType)) {
608 case TEK_Scalar:
John McCall31168b02011-06-15 23:02:42 +0000609 if (LHS.isSimple()) {
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000610 EmitExprAsInit(Init, Field, LHS, false);
John McCall31168b02011-06-15 23:02:42 +0000611 } else {
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000612 RValue RHS = RValue::get(EmitScalarExpr(Init));
613 EmitStoreThroughLValue(RHS, LHS);
John McCall31168b02011-06-15 23:02:42 +0000614 }
John McCall47fb9502013-03-07 21:37:08 +0000615 break;
616 case TEK_Complex:
617 EmitComplexExprIntoLValue(Init, LHS, /*isInit*/ true);
618 break;
619 case TEK_Aggregate: {
Craig Topper8a13c412014-05-21 05:09:00 +0000620 llvm::Value *ArrayIndexVar = nullptr;
Eli Friedman6ae63022012-02-14 02:15:49 +0000621 if (ArrayIndexes.size()) {
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000622 llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Douglas Gregor94f9a482010-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 Friedman5f1a04f2012-02-14 02:31:03 +0000626 QualType BaseElementTy = getContext().getBaseElementType(FieldType);
627 llvm::Type *BasePtr = ConvertType(BaseElementTy);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000628 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000629 llvm::Value *BaseAddrPtr = Builder.CreateBitCast(LHS.getAddress(),
630 BasePtr);
631 LHS = MakeAddrLValue(BaseAddrPtr, BaseElementTy);
Douglas Gregor94f9a482010-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 Friedman5f1a04f2012-02-14 02:31:03 +0000635 ArrayIndexVar = CreateTempAlloca(SizeTy, "object.index");
Douglas Gregor94f9a482010-05-05 05:51:00 +0000636 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000637 Builder.CreateStore(Zero, ArrayIndexVar);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000638
Douglas Gregor94f9a482010-05-05 05:51:00 +0000639
640 // Emit the block variables for the array indices, if any.
Eli Friedman6ae63022012-02-14 02:15:49 +0000641 for (unsigned I = 0, N = ArrayIndexes.size(); I != N; ++I)
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000642 EmitAutoVarDecl(*ArrayIndexes[I]);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000643 }
644
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000645 EmitAggMemberInitializer(*this, LHS, Init, ArrayIndexVar, FieldType,
Eli Friedman6ae63022012-02-14 02:15:49 +0000646 ArrayIndexes, 0);
Anders Carlssonfb404882009-12-24 22:46:43 +0000647 }
John McCall47fb9502013-03-07 21:37:08 +0000648 }
John McCall12cc42a2013-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 Carlssonfb404882009-12-24 22:46:43 +0000655}
656
John McCallf8ff7b92010-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
Alexis Hunt61bc1732011-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 McCallf8ff7b92010-02-23 00:48:20 +0000702 return true;
703}
704
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000705// 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 QualType RecordTy = Context.getTypeDeclType(ClassDecl);
754 uint64_t TypeSize = Context.getTypeSizeInChars(RecordTy).getQuantity();
755
756 // For each field check if it has sufficient padding,
757 // if so (un)poison it with a call.
758 for (size_t i = 0; i < SSV.size(); i++) {
759 uint64_t AsanAlignment = 8;
760 uint64_t NextField = i == SSV.size() - 1 ? TypeSize : SSV[i + 1].Offset;
761 uint64_t PoisonSize = NextField - SSV[i].Offset - SSV[i].Size;
762 uint64_t EndOffset = SSV[i].Offset + SSV[i].Size;
763 if (PoisonSize < AsanAlignment || !SSV[i].Size ||
764 (NextField % AsanAlignment) != 0)
765 continue;
766 Builder.CreateCall2(
767 F, Builder.CreateAdd(ThisPtr, Builder.getIntN(PtrSize, EndOffset)),
768 Builder.getIntN(PtrSize, PoisonSize));
769 }
770}
771
John McCallb81884d2010-02-19 09:25:03 +0000772/// EmitConstructorBody - Emits the body of the current constructor.
773void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000774 EmitAsanPrologueOrEpilogue(true);
John McCallb81884d2010-02-19 09:25:03 +0000775 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
776 CXXCtorType CtorType = CurGD.getCtorType();
777
Reid Kleckner340ad862014-01-13 22:57:31 +0000778 assert((CGM.getTarget().getCXXABI().hasConstructorVariants() ||
779 CtorType == Ctor_Complete) &&
780 "can only generate complete ctor for this ABI");
781
John McCallf8ff7b92010-02-23 00:48:20 +0000782 // Before we go any further, try the complete->base constructor
783 // delegation optimization.
Timur Iskhodzhanovf32a3772012-04-20 08:05:00 +0000784 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
John McCallc8e01702013-04-16 22:48:15 +0000785 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
Devang Pateld76c1db2010-08-11 21:04:37 +0000786 if (CGDebugInfo *DI = getDebugInfo())
Eric Christopher7cdf9482011-10-13 21:45:18 +0000787 DI->EmitLocation(Builder, Ctor->getLocEnd());
Nick Lewycky2d84e842013-10-02 02:29:49 +0000788 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args, Ctor->getLocEnd());
John McCallf8ff7b92010-02-23 00:48:20 +0000789 return;
790 }
791
Richard Smith46bb5812014-08-01 01:56:39 +0000792 const FunctionDecl *Definition = 0;
793 Stmt *Body = Ctor->getBody(Definition);
794 assert(Definition == Ctor && "emitting wrong constructor body");
John McCallb81884d2010-02-19 09:25:03 +0000795
John McCallf8ff7b92010-02-23 00:48:20 +0000796 // Enter the function-try-block before the constructor prologue if
797 // applicable.
John McCallf8ff7b92010-02-23 00:48:20 +0000798 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallf8ff7b92010-02-23 00:48:20 +0000799 if (IsTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000800 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000801
Justin Bogner81c22c22014-01-23 02:54:27 +0000802 RegionCounter Cnt = getPGORegionCounter(Body);
803 Cnt.beginRegion(Builder);
804
Richard Smithcc1b96d2013-06-12 22:31:48 +0000805 RunCleanupsScope RunCleanups(*this);
John McCallb81884d2010-02-19 09:25:03 +0000806
John McCall88313032012-03-30 04:25:03 +0000807 // TODO: in restricted cases, we can emit the vbase initializers of
808 // a complete ctor and then delegate to the base ctor.
809
John McCallf8ff7b92010-02-23 00:48:20 +0000810 // Emit the constructor prologue, i.e. the base and member
811 // initializers.
Douglas Gregor94f9a482010-05-05 05:51:00 +0000812 EmitCtorPrologue(Ctor, CtorType, Args);
John McCallb81884d2010-02-19 09:25:03 +0000813
814 // Emit the body of the statement.
John McCallf8ff7b92010-02-23 00:48:20 +0000815 if (IsTryBody)
John McCallb81884d2010-02-19 09:25:03 +0000816 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
817 else if (Body)
818 EmitStmt(Body);
John McCallb81884d2010-02-19 09:25:03 +0000819
820 // Emit any cleanup blocks associated with the member or base
821 // initializers, which includes (along the exceptional path) the
822 // destructors for those members and bases that were fully
823 // constructed.
Richard Smithcc1b96d2013-06-12 22:31:48 +0000824 RunCleanups.ForceCleanup();
John McCallb81884d2010-02-19 09:25:03 +0000825
John McCallf8ff7b92010-02-23 00:48:20 +0000826 if (IsTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000827 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000828}
829
Lang Hamesbf122742013-02-17 07:22:09 +0000830namespace {
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000831 /// RAII object to indicate that codegen is copying the value representation
832 /// instead of the object representation. Useful when copying a struct or
833 /// class which has uninitialized members and we're only performing
834 /// lvalue-to-rvalue conversion on the object but not its members.
835 class CopyingValueRepresentation {
836 public:
837 explicit CopyingValueRepresentation(CodeGenFunction &CGF)
838 : CGF(CGF), SO(*CGF.SanOpts), OldSanOpts(CGF.SanOpts) {
839 SO.Bool = false;
840 SO.Enum = false;
841 CGF.SanOpts = &SO;
842 }
843 ~CopyingValueRepresentation() {
844 CGF.SanOpts = OldSanOpts;
845 }
846 private:
847 CodeGenFunction &CGF;
848 SanitizerOptions SO;
849 const SanitizerOptions *OldSanOpts;
850 };
851}
852
853namespace {
Lang Hamesbf122742013-02-17 07:22:09 +0000854 class FieldMemcpyizer {
855 public:
856 FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl,
857 const VarDecl *SrcRec)
858 : CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec),
859 RecLayout(CGF.getContext().getASTRecordLayout(ClassDecl)),
Craig Topper8a13c412014-05-21 05:09:00 +0000860 FirstField(nullptr), LastField(nullptr), FirstFieldOffset(0),
861 LastFieldOffset(0), LastAddedFieldIndex(0) {}
Lang Hamesbf122742013-02-17 07:22:09 +0000862
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000863 bool isMemcpyableField(FieldDecl *F) const {
864 // Never memcpy fields when we are adding poisoned paddings.
865 if (CGF.getContext().getLangOpts().Sanitize.SanitizeAddressFieldPadding)
866 return false;
Lang Hamesbf122742013-02-17 07:22:09 +0000867 Qualifiers Qual = F->getType().getQualifiers();
868 if (Qual.hasVolatile() || Qual.hasObjCLifetime())
869 return false;
870 return true;
871 }
872
873 void addMemcpyableField(FieldDecl *F) {
Craig Topper8a13c412014-05-21 05:09:00 +0000874 if (!FirstField)
Lang Hamesbf122742013-02-17 07:22:09 +0000875 addInitialField(F);
876 else
877 addNextField(F);
878 }
879
David Majnemera586eb22014-10-10 18:57:10 +0000880 CharUnits getMemcpySize(uint64_t FirstByteOffset) const {
Lang Hamesbf122742013-02-17 07:22:09 +0000881 unsigned LastFieldSize =
882 LastField->isBitField() ?
883 LastField->getBitWidthValue(CGF.getContext()) :
884 CGF.getContext().getTypeSize(LastField->getType());
885 uint64_t MemcpySizeBits =
David Majnemera586eb22014-10-10 18:57:10 +0000886 LastFieldOffset + LastFieldSize - FirstByteOffset +
Lang Hamesbf122742013-02-17 07:22:09 +0000887 CGF.getContext().getCharWidth() - 1;
888 CharUnits MemcpySize =
889 CGF.getContext().toCharUnitsFromBits(MemcpySizeBits);
890 return MemcpySize;
891 }
892
893 void emitMemcpy() {
894 // Give the subclass a chance to bail out if it feels the memcpy isn't
895 // worth it (e.g. Hasn't aggregated enough data).
Craig Topper8a13c412014-05-21 05:09:00 +0000896 if (!FirstField) {
Lang Hamesbf122742013-02-17 07:22:09 +0000897 return;
898 }
899
Lang Hames1694e0d2013-02-27 04:14:49 +0000900 CharUnits Alignment;
Lang Hamesbf122742013-02-17 07:22:09 +0000901
David Majnemera586eb22014-10-10 18:57:10 +0000902 uint64_t FirstByteOffset;
Lang Hamesbf122742013-02-17 07:22:09 +0000903 if (FirstField->isBitField()) {
904 const CGRecordLayout &RL =
905 CGF.getTypes().getCGRecordLayout(FirstField->getParent());
906 const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField);
Lang Hames1694e0d2013-02-27 04:14:49 +0000907 Alignment = CharUnits::fromQuantity(BFInfo.StorageAlignment);
David Majnemera586eb22014-10-10 18:57:10 +0000908 // FirstFieldOffset is not appropriate for bitfields,
909 // it won't tell us what the storage offset should be and thus might not
910 // be properly aligned.
911 //
912 // Instead calculate the storage offset using the offset of the field in
913 // the struct type.
914 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
915 FirstByteOffset =
916 DL.getStructLayout(RL.getLLVMType())
917 ->getElementOffsetInBits(RL.getLLVMFieldNo(FirstField));
Lang Hames1694e0d2013-02-27 04:14:49 +0000918 } else {
Lang Hames224ae882013-03-05 20:27:24 +0000919 Alignment = CGF.getContext().getDeclAlign(FirstField);
David Majnemera586eb22014-10-10 18:57:10 +0000920 FirstByteOffset = FirstFieldOffset;
Lang Hames1694e0d2013-02-27 04:14:49 +0000921 }
Lang Hamesbf122742013-02-17 07:22:09 +0000922
David Majnemera586eb22014-10-10 18:57:10 +0000923 assert((CGF.getContext().toCharUnitsFromBits(FirstByteOffset) %
Lang Hames1694e0d2013-02-27 04:14:49 +0000924 Alignment) == 0 && "Bad field alignment.");
925
David Majnemera586eb22014-10-10 18:57:10 +0000926 CharUnits MemcpySize = getMemcpySize(FirstByteOffset);
Lang Hamesbf122742013-02-17 07:22:09 +0000927 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
928 llvm::Value *ThisPtr = CGF.LoadCXXThis();
929 LValue DestLV = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
930 LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField);
931 llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec));
932 LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
933 LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField);
934
935 emitMemcpyIR(Dest.isBitField() ? Dest.getBitFieldAddr() : Dest.getAddress(),
936 Src.isBitField() ? Src.getBitFieldAddr() : Src.getAddress(),
937 MemcpySize, Alignment);
938 reset();
939 }
940
941 void reset() {
Craig Topper8a13c412014-05-21 05:09:00 +0000942 FirstField = nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +0000943 }
944
945 protected:
946 CodeGenFunction &CGF;
947 const CXXRecordDecl *ClassDecl;
948
949 private:
950
951 void emitMemcpyIR(llvm::Value *DestPtr, llvm::Value *SrcPtr,
952 CharUnits Size, CharUnits Alignment) {
953 llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
954 llvm::Type *DBP =
955 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), DPT->getAddressSpace());
956 DestPtr = CGF.Builder.CreateBitCast(DestPtr, DBP);
957
958 llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
959 llvm::Type *SBP =
960 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), SPT->getAddressSpace());
961 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, SBP);
962
963 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity(),
964 Alignment.getQuantity());
965 }
966
967 void addInitialField(FieldDecl *F) {
968 FirstField = F;
969 LastField = F;
970 FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex());
971 LastFieldOffset = FirstFieldOffset;
972 LastAddedFieldIndex = F->getFieldIndex();
973 return;
974 }
975
976 void addNextField(FieldDecl *F) {
John McCall6054d5a2013-05-07 05:20:46 +0000977 // For the most part, the following invariant will hold:
978 // F->getFieldIndex() == LastAddedFieldIndex + 1
979 // The one exception is that Sema won't add a copy-initializer for an
980 // unnamed bitfield, which will show up here as a gap in the sequence.
981 assert(F->getFieldIndex() >= LastAddedFieldIndex + 1 &&
982 "Cannot aggregate fields out of order.");
Lang Hamesbf122742013-02-17 07:22:09 +0000983 LastAddedFieldIndex = F->getFieldIndex();
984
985 // The 'first' and 'last' fields are chosen by offset, rather than field
986 // index. This allows the code to support bitfields, as well as regular
987 // fields.
988 uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex());
989 if (FOffset < FirstFieldOffset) {
990 FirstField = F;
991 FirstFieldOffset = FOffset;
992 } else if (FOffset > LastFieldOffset) {
993 LastField = F;
994 LastFieldOffset = FOffset;
995 }
996 }
997
998 const VarDecl *SrcRec;
999 const ASTRecordLayout &RecLayout;
1000 FieldDecl *FirstField;
1001 FieldDecl *LastField;
1002 uint64_t FirstFieldOffset, LastFieldOffset;
1003 unsigned LastAddedFieldIndex;
1004 };
1005
1006 class ConstructorMemcpyizer : public FieldMemcpyizer {
1007 private:
1008
1009 /// Get source argument for copy constructor. Returns null if not a copy
David Majnemer196ac332014-09-11 23:05:02 +00001010 /// constructor.
1011 static const VarDecl *getTrivialCopySource(CodeGenFunction &CGF,
1012 const CXXConstructorDecl *CD,
Lang Hamesbf122742013-02-17 07:22:09 +00001013 FunctionArgList &Args) {
Jordan Rose54533f72013-08-07 16:16:48 +00001014 if (CD->isCopyOrMoveConstructor() && CD->isDefaulted())
David Majnemer196ac332014-09-11 23:05:02 +00001015 return Args[CGF.CGM.getCXXABI().getSrcArgforCopyCtor(CD, Args)];
Craig Topper8a13c412014-05-21 05:09:00 +00001016 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001017 }
1018
1019 // Returns true if a CXXCtorInitializer represents a member initialization
1020 // that can be rolled into a memcpy.
1021 bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const {
1022 if (!MemcpyableCtor)
1023 return false;
1024 FieldDecl *Field = MemberInit->getMember();
Craig Topper8a13c412014-05-21 05:09:00 +00001025 assert(Field && "No field for member init.");
Lang Hamesbf122742013-02-17 07:22:09 +00001026 QualType FieldType = Field->getType();
1027 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
1028
1029 // Bail out on non-POD, not-trivially-constructable members.
1030 if (!(CE && CE->getConstructor()->isTrivial()) &&
1031 !(FieldType.isTriviallyCopyableType(CGF.getContext()) ||
1032 FieldType->isReferenceType()))
1033 return false;
1034
1035 // Bail out on volatile fields.
1036 if (!isMemcpyableField(Field))
1037 return false;
1038
1039 // Otherwise we're good.
1040 return true;
1041 }
1042
1043 public:
1044 ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD,
1045 FunctionArgList &Args)
David Majnemer196ac332014-09-11 23:05:02 +00001046 : FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CGF, CD, Args)),
Lang Hamesbf122742013-02-17 07:22:09 +00001047 ConstructorDecl(CD),
Jordan Rose54533f72013-08-07 16:16:48 +00001048 MemcpyableCtor(CD->isDefaulted() &&
Lang Hamesbf122742013-02-17 07:22:09 +00001049 CD->isCopyOrMoveConstructor() &&
1050 CGF.getLangOpts().getGC() == LangOptions::NonGC),
1051 Args(Args) { }
1052
1053 void addMemberInitializer(CXXCtorInitializer *MemberInit) {
1054 if (isMemberInitMemcpyable(MemberInit)) {
1055 AggregatedInits.push_back(MemberInit);
1056 addMemcpyableField(MemberInit->getMember());
1057 } else {
1058 emitAggregatedInits();
1059 EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit,
1060 ConstructorDecl, Args);
1061 }
1062 }
1063
1064 void emitAggregatedInits() {
1065 if (AggregatedInits.size() <= 1) {
1066 // This memcpy is too small to be worthwhile. Fall back on default
1067 // codegen.
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001068 if (!AggregatedInits.empty()) {
1069 CopyingValueRepresentation CVR(CGF);
Lang Hamesbf122742013-02-17 07:22:09 +00001070 EmitMemberInitializer(CGF, ConstructorDecl->getParent(),
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001071 AggregatedInits[0], ConstructorDecl, Args);
Lang Hamesbf122742013-02-17 07:22:09 +00001072 }
1073 reset();
1074 return;
1075 }
1076
1077 pushEHDestructors();
1078 emitMemcpy();
1079 AggregatedInits.clear();
1080 }
1081
1082 void pushEHDestructors() {
1083 llvm::Value *ThisPtr = CGF.LoadCXXThis();
1084 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
1085 LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
1086
1087 for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
1088 QualType FieldType = AggregatedInits[i]->getMember()->getType();
1089 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
1090 if (CGF.needsEHCleanup(dtorKind))
1091 CGF.pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
1092 }
1093 }
1094
1095 void finish() {
1096 emitAggregatedInits();
1097 }
1098
1099 private:
1100 const CXXConstructorDecl *ConstructorDecl;
1101 bool MemcpyableCtor;
1102 FunctionArgList &Args;
1103 SmallVector<CXXCtorInitializer*, 16> AggregatedInits;
1104 };
1105
1106 class AssignmentMemcpyizer : public FieldMemcpyizer {
1107 private:
1108
1109 // Returns the memcpyable field copied by the given statement, if one
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001110 // exists. Otherwise returns null.
1111 FieldDecl *getMemcpyableField(Stmt *S) {
Lang Hamesbf122742013-02-17 07:22:09 +00001112 if (!AssignmentsMemcpyable)
Craig Topper8a13c412014-05-21 05:09:00 +00001113 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001114 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
1115 // Recognise trivial assignments.
1116 if (BO->getOpcode() != BO_Assign)
Craig Topper8a13c412014-05-21 05:09:00 +00001117 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001118 MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS());
1119 if (!ME)
Craig Topper8a13c412014-05-21 05:09:00 +00001120 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001121 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1122 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001123 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001124 Stmt *RHS = BO->getRHS();
1125 if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS))
1126 RHS = EC->getSubExpr();
1127 if (!RHS)
Craig Topper8a13c412014-05-21 05:09:00 +00001128 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001129 MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS);
1130 if (dyn_cast<FieldDecl>(ME2->getMemberDecl()) != Field)
Craig Topper8a13c412014-05-21 05:09:00 +00001131 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001132 return Field;
1133 } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) {
1134 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl());
1135 if (!(MD && (MD->isCopyAssignmentOperator() ||
1136 MD->isMoveAssignmentOperator()) &&
1137 MD->isTrivial()))
Craig Topper8a13c412014-05-21 05:09:00 +00001138 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001139 MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument());
1140 if (!IOA)
Craig Topper8a13c412014-05-21 05:09:00 +00001141 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001142 FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl());
1143 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001144 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001145 MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0));
1146 if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl()))
Craig Topper8a13c412014-05-21 05:09:00 +00001147 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001148 return Field;
1149 } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1150 FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1151 if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy)
Craig Topper8a13c412014-05-21 05:09:00 +00001152 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001153 Expr *DstPtr = CE->getArg(0);
1154 if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr))
1155 DstPtr = DC->getSubExpr();
1156 UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr);
1157 if (!DUO || DUO->getOpcode() != UO_AddrOf)
Craig Topper8a13c412014-05-21 05:09:00 +00001158 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001159 MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr());
1160 if (!ME)
Craig Topper8a13c412014-05-21 05:09:00 +00001161 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001162 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1163 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001164 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001165 Expr *SrcPtr = CE->getArg(1);
1166 if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr))
1167 SrcPtr = SC->getSubExpr();
1168 UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr);
1169 if (!SUO || SUO->getOpcode() != UO_AddrOf)
Craig Topper8a13c412014-05-21 05:09:00 +00001170 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001171 MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr());
1172 if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl()))
Craig Topper8a13c412014-05-21 05:09:00 +00001173 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001174 return Field;
1175 }
1176
Craig Topper8a13c412014-05-21 05:09:00 +00001177 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001178 }
1179
1180 bool AssignmentsMemcpyable;
1181 SmallVector<Stmt*, 16> AggregatedStmts;
1182
1183 public:
1184
1185 AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD,
1186 FunctionArgList &Args)
1187 : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]),
1188 AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) {
1189 assert(Args.size() == 2);
1190 }
1191
1192 void emitAssignment(Stmt *S) {
1193 FieldDecl *F = getMemcpyableField(S);
1194 if (F) {
1195 addMemcpyableField(F);
1196 AggregatedStmts.push_back(S);
1197 } else {
1198 emitAggregatedStmts();
1199 CGF.EmitStmt(S);
1200 }
1201 }
1202
1203 void emitAggregatedStmts() {
1204 if (AggregatedStmts.size() <= 1) {
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001205 if (!AggregatedStmts.empty()) {
1206 CopyingValueRepresentation CVR(CGF);
1207 CGF.EmitStmt(AggregatedStmts[0]);
1208 }
Lang Hamesbf122742013-02-17 07:22:09 +00001209 reset();
1210 }
1211
1212 emitMemcpy();
1213 AggregatedStmts.clear();
1214 }
1215
1216 void finish() {
1217 emitAggregatedStmts();
1218 }
1219 };
1220
1221}
1222
Anders Carlssonfb404882009-12-24 22:46:43 +00001223/// EmitCtorPrologue - This routine generates necessary code to initialize
1224/// base classes and non-static data members belonging to this constructor.
Anders Carlssonfb404882009-12-24 22:46:43 +00001225void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001226 CXXCtorType CtorType,
1227 FunctionArgList &Args) {
Alexis Hunt61bc1732011-05-01 07:04:31 +00001228 if (CD->isDelegatingConstructor())
1229 return EmitDelegatingCXXConstructorCall(CD, Args);
1230
Anders Carlssonfb404882009-12-24 22:46:43 +00001231 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlsson5dc86332010-02-02 19:58:43 +00001232
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001233 CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
1234 E = CD->init_end();
1235
Craig Topper8a13c412014-05-21 05:09:00 +00001236 llvm::BasicBlock *BaseCtorContinueBB = nullptr;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001237 if (ClassDecl->getNumVBases() &&
1238 !CGM.getTarget().getCXXABI().hasConstructorVariants()) {
1239 // The ABIs that don't have constructor variants need to put a branch
1240 // before the virtual base initialization code.
Reid Kleckner7810af02013-06-19 15:20:38 +00001241 BaseCtorContinueBB =
1242 CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this, ClassDecl);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001243 assert(BaseCtorContinueBB);
1244 }
1245
1246 // Virtual base initializers first.
1247 for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
1248 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
1249 }
1250
1251 if (BaseCtorContinueBB) {
1252 // Complete object handler should continue to the remaining initializers.
1253 Builder.CreateBr(BaseCtorContinueBB);
1254 EmitBlock(BaseCtorContinueBB);
1255 }
1256
1257 // Then, non-virtual base initializers.
1258 for (; B != E && (*B)->isBaseInitializer(); B++) {
1259 assert(!(*B)->isBaseVirtual());
1260 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
Anders Carlssonfb404882009-12-24 22:46:43 +00001261 }
1262
Anders Carlssond5895932010-03-28 21:07:49 +00001263 InitializeVTablePointers(ClassDecl);
Anders Carlsson5dc86332010-02-02 19:58:43 +00001264
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001265 // And finally, initialize class members.
Richard Smith852c9db2013-04-20 22:23:05 +00001266 FieldConstructionScope FCS(*this, CXXThisValue);
Lang Hamesbf122742013-02-17 07:22:09 +00001267 ConstructorMemcpyizer CM(*this, CD, Args);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001268 for (; B != E; B++) {
1269 CXXCtorInitializer *Member = (*B);
1270 assert(!Member->isBaseInitializer());
1271 assert(Member->isAnyMemberInitializer() &&
1272 "Delegating initializer on non-delegating constructor");
1273 CM.addMemberInitializer(Member);
1274 }
Lang Hamesbf122742013-02-17 07:22:09 +00001275 CM.finish();
Anders Carlssonfb404882009-12-24 22:46:43 +00001276}
1277
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001278static bool
1279FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
1280
1281static bool
1282HasTrivialDestructorBody(ASTContext &Context,
1283 const CXXRecordDecl *BaseClassDecl,
1284 const CXXRecordDecl *MostDerivedClassDecl)
1285{
1286 // If the destructor is trivial we don't have to check anything else.
1287 if (BaseClassDecl->hasTrivialDestructor())
1288 return true;
1289
1290 if (!BaseClassDecl->getDestructor()->hasTrivialBody())
1291 return false;
1292
1293 // Check fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001294 for (const auto *Field : BaseClassDecl->fields())
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001295 if (!FieldHasTrivialDestructorBody(Context, Field))
1296 return false;
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001297
1298 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001299 for (const auto &I : BaseClassDecl->bases()) {
1300 if (I.isVirtual())
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001301 continue;
1302
1303 const CXXRecordDecl *NonVirtualBase =
Aaron Ballman574705e2014-03-13 15:41:46 +00001304 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001305 if (!HasTrivialDestructorBody(Context, NonVirtualBase,
1306 MostDerivedClassDecl))
1307 return false;
1308 }
1309
1310 if (BaseClassDecl == MostDerivedClassDecl) {
1311 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00001312 for (const auto &I : BaseClassDecl->vbases()) {
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001313 const CXXRecordDecl *VirtualBase =
Aaron Ballman445a9392014-03-13 16:15:17 +00001314 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001315 if (!HasTrivialDestructorBody(Context, VirtualBase,
1316 MostDerivedClassDecl))
1317 return false;
1318 }
1319 }
1320
1321 return true;
1322}
1323
1324static bool
1325FieldHasTrivialDestructorBody(ASTContext &Context,
1326 const FieldDecl *Field)
1327{
1328 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
1329
1330 const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
1331 if (!RT)
1332 return true;
1333
1334 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1335 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
1336}
1337
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001338/// CanSkipVTablePointerInitialization - Check whether we need to initialize
1339/// any vtable pointers before calling this destructor.
1340static bool CanSkipVTablePointerInitialization(ASTContext &Context,
Anders Carlssond6f15182011-05-16 04:08:36 +00001341 const CXXDestructorDecl *Dtor) {
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001342 if (!Dtor->hasTrivialBody())
1343 return false;
1344
1345 // Check the fields.
1346 const CXXRecordDecl *ClassDecl = Dtor->getParent();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001347 for (const auto *Field : ClassDecl->fields())
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001348 if (!FieldHasTrivialDestructorBody(Context, Field))
1349 return false;
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001350
1351 return true;
1352}
1353
John McCallb81884d2010-02-19 09:25:03 +00001354/// EmitDestructorBody - Emits the body of the current destructor.
1355void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
1356 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
1357 CXXDtorType DtorType = CurGD.getDtorType();
1358
John McCallf99a6312010-07-21 05:30:47 +00001359 // The call to operator delete in a deleting destructor happens
1360 // outside of the function-try-block, which means it's always
1361 // possible to delegate the destructor body to the complete
1362 // destructor. Do so.
1363 if (DtorType == Dtor_Deleting) {
1364 EnterDtorCleanups(Dtor, Dtor_Deleting);
1365 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
Douglas Gregor61535002013-01-31 05:50:40 +00001366 /*Delegating=*/false, LoadCXXThis());
John McCallf99a6312010-07-21 05:30:47 +00001367 PopCleanupBlock();
1368 return;
1369 }
1370
John McCallb81884d2010-02-19 09:25:03 +00001371 Stmt *Body = Dtor->getBody();
1372
1373 // If the body is a function-try-block, enter the try before
John McCallf99a6312010-07-21 05:30:47 +00001374 // anything else.
1375 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallb81884d2010-02-19 09:25:03 +00001376 if (isTryBody)
John McCallb609d3f2010-07-07 06:56:46 +00001377 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00001378 EmitAsanPrologueOrEpilogue(false);
John McCallb81884d2010-02-19 09:25:03 +00001379
John McCallf99a6312010-07-21 05:30:47 +00001380 // Enter the epilogue cleanups.
1381 RunCleanupsScope DtorEpilogue(*this);
1382
John McCallb81884d2010-02-19 09:25:03 +00001383 // If this is the complete variant, just invoke the base variant;
1384 // the epilogue will destruct the virtual bases. But we can't do
1385 // this optimization if the body is a function-try-block, because
Reid Klecknere7de47e2013-07-22 13:51:44 +00001386 // we'd introduce *two* handler blocks. In the Microsoft ABI, we
1387 // always delegate because we might not have a definition in this TU.
John McCallf99a6312010-07-21 05:30:47 +00001388 switch (DtorType) {
Rafael Espindola1e4df922014-09-16 15:18:21 +00001389 case Dtor_Comdat:
1390 llvm_unreachable("not expecting a COMDAT");
1391
John McCallf99a6312010-07-21 05:30:47 +00001392 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
1393
1394 case Dtor_Complete:
Reid Klecknere7de47e2013-07-22 13:51:44 +00001395 assert((Body || getTarget().getCXXABI().isMicrosoft()) &&
1396 "can't emit a dtor without a body for non-Microsoft ABIs");
1397
John McCallf99a6312010-07-21 05:30:47 +00001398 // Enter the cleanup scopes for virtual bases.
1399 EnterDtorCleanups(Dtor, Dtor_Complete);
1400
Reid Klecknere7de47e2013-07-22 13:51:44 +00001401 if (!isTryBody) {
John McCallf99a6312010-07-21 05:30:47 +00001402 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
Douglas Gregor61535002013-01-31 05:50:40 +00001403 /*Delegating=*/false, LoadCXXThis());
John McCallf99a6312010-07-21 05:30:47 +00001404 break;
1405 }
1406 // Fallthrough: act like we're in the base variant.
John McCallb81884d2010-02-19 09:25:03 +00001407
John McCallf99a6312010-07-21 05:30:47 +00001408 case Dtor_Base:
Reid Klecknere7de47e2013-07-22 13:51:44 +00001409 assert(Body);
1410
Justin Bogner81c22c22014-01-23 02:54:27 +00001411 RegionCounter Cnt = getPGORegionCounter(Body);
1412 Cnt.beginRegion(Builder);
1413
John McCallf99a6312010-07-21 05:30:47 +00001414 // Enter the cleanup scopes for fields and non-virtual bases.
1415 EnterDtorCleanups(Dtor, Dtor_Base);
1416
1417 // Initialize the vtable pointers before entering the body.
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001418 if (!CanSkipVTablePointerInitialization(getContext(), Dtor))
1419 InitializeVTablePointers(Dtor->getParent());
John McCallf99a6312010-07-21 05:30:47 +00001420
1421 if (isTryBody)
1422 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
1423 else if (Body)
1424 EmitStmt(Body);
1425 else {
1426 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
1427 // nothing to do besides what's in the epilogue
1428 }
Fariborz Jahanian0c12ed12011-02-02 23:12:46 +00001429 // -fapple-kext must inline any call to this dtor into
1430 // the caller's body.
Richard Smith9c6890a2012-11-01 22:30:59 +00001431 if (getLangOpts().AppleKext)
Bill Wendling207f0532012-12-20 19:27:06 +00001432 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
John McCallf99a6312010-07-21 05:30:47 +00001433 break;
John McCallb81884d2010-02-19 09:25:03 +00001434 }
1435
John McCallf99a6312010-07-21 05:30:47 +00001436 // Jump out through the epilogue cleanups.
1437 DtorEpilogue.ForceCleanup();
John McCallb81884d2010-02-19 09:25:03 +00001438
1439 // Exit the try if applicable.
1440 if (isTryBody)
John McCallb609d3f2010-07-07 06:56:46 +00001441 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +00001442}
1443
Lang Hamesbf122742013-02-17 07:22:09 +00001444void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) {
1445 const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
1446 const Stmt *RootS = AssignOp->getBody();
1447 assert(isa<CompoundStmt>(RootS) &&
1448 "Body of an implicit assignment operator should be compound stmt.");
1449 const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
1450
1451 LexicalScope Scope(*this, RootCS->getSourceRange());
1452
1453 AssignmentMemcpyizer AM(*this, AssignOp, Args);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001454 for (auto *I : RootCS->body())
1455 AM.emitAssignment(I);
Lang Hamesbf122742013-02-17 07:22:09 +00001456 AM.finish();
1457}
1458
John McCallf99a6312010-07-21 05:30:47 +00001459namespace {
1460 /// Call the operator delete associated with the current destructor.
John McCallcda666c2010-07-21 07:22:38 +00001461 struct CallDtorDelete : EHScopeStack::Cleanup {
John McCallf99a6312010-07-21 05:30:47 +00001462 CallDtorDelete() {}
1463
Craig Topper4f12f102014-03-12 06:41:41 +00001464 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallf99a6312010-07-21 05:30:47 +00001465 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1466 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1467 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1468 CGF.getContext().getTagDeclType(ClassDecl));
1469 }
1470 };
1471
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001472 struct CallDtorDeleteConditional : EHScopeStack::Cleanup {
1473 llvm::Value *ShouldDeleteCondition;
1474 public:
1475 CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
1476 : ShouldDeleteCondition(ShouldDeleteCondition) {
Craig Topper8a13c412014-05-21 05:09:00 +00001477 assert(ShouldDeleteCondition != nullptr);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001478 }
1479
Craig Topper4f12f102014-03-12 06:41:41 +00001480 void Emit(CodeGenFunction &CGF, Flags flags) override {
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001481 llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
1482 llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
1483 llvm::Value *ShouldCallDelete
1484 = CGF.Builder.CreateIsNull(ShouldDeleteCondition);
1485 CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
1486
1487 CGF.EmitBlock(callDeleteBB);
1488 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1489 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1490 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1491 CGF.getContext().getTagDeclType(ClassDecl));
1492 CGF.Builder.CreateBr(continueBB);
1493
1494 CGF.EmitBlock(continueBB);
1495 }
1496 };
1497
John McCall4bd0fb12011-07-12 16:41:08 +00001498 class DestroyField : public EHScopeStack::Cleanup {
1499 const FieldDecl *field;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001500 CodeGenFunction::Destroyer *destroyer;
John McCall4bd0fb12011-07-12 16:41:08 +00001501 bool useEHCleanupForArray;
John McCallf99a6312010-07-21 05:30:47 +00001502
John McCall4bd0fb12011-07-12 16:41:08 +00001503 public:
1504 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
1505 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +00001506 : field(field), destroyer(destroyer),
John McCall4bd0fb12011-07-12 16:41:08 +00001507 useEHCleanupForArray(useEHCleanupForArray) {}
John McCallf99a6312010-07-21 05:30:47 +00001508
Craig Topper4f12f102014-03-12 06:41:41 +00001509 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall4bd0fb12011-07-12 16:41:08 +00001510 // Find the address of the field.
1511 llvm::Value *thisValue = CGF.LoadCXXThis();
Eli Friedman7f1ff602012-04-16 03:54:45 +00001512 QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
1513 LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
1514 LValue LV = CGF.EmitLValueForField(ThisLV, field);
John McCall4bd0fb12011-07-12 16:41:08 +00001515 assert(LV.isSimple());
1516
1517 CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +00001518 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCallf99a6312010-07-21 05:30:47 +00001519 }
1520 };
1521}
1522
Hans Wennborgdeff7032013-12-18 01:39:59 +00001523/// \brief Emit all code that comes at the end of class's
Anders Carlssonfb404882009-12-24 22:46:43 +00001524/// destructor. This is to call destructors on members and base classes
1525/// in reverse order of their construction.
John McCallf99a6312010-07-21 05:30:47 +00001526void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
1527 CXXDtorType DtorType) {
Hans Wennborg853ae942014-05-30 16:59:42 +00001528 assert((!DD->isTrivial() || DD->hasAttr<DLLExportAttr>()) &&
1529 "Should not emit dtor epilogue for non-exported trivial dtor!");
Anders Carlssonfb404882009-12-24 22:46:43 +00001530
John McCallf99a6312010-07-21 05:30:47 +00001531 // The deleting-destructor phase just needs to call the appropriate
1532 // operator delete that Sema picked up.
John McCall5c60a6f2010-02-18 19:59:28 +00001533 if (DtorType == Dtor_Deleting) {
1534 assert(DD->getOperatorDelete() &&
Hans Wennborgdeff7032013-12-18 01:39:59 +00001535 "operator delete missing - EnterDtorCleanups");
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001536 if (CXXStructorImplicitParamValue) {
1537 // If there is an implicit param to the deleting dtor, it's a boolean
1538 // telling whether we should call delete at the end of the dtor.
1539 EHStack.pushCleanup<CallDtorDeleteConditional>(
1540 NormalAndEHCleanup, CXXStructorImplicitParamValue);
1541 } else {
1542 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
1543 }
John McCall5c60a6f2010-02-18 19:59:28 +00001544 return;
1545 }
1546
John McCallf99a6312010-07-21 05:30:47 +00001547 const CXXRecordDecl *ClassDecl = DD->getParent();
1548
Richard Smith20104042011-09-18 12:11:43 +00001549 // Unions have no bases and do not call field destructors.
1550 if (ClassDecl->isUnion())
1551 return;
1552
John McCallf99a6312010-07-21 05:30:47 +00001553 // The complete-destructor phase just destructs all the virtual bases.
John McCall5c60a6f2010-02-18 19:59:28 +00001554 if (DtorType == Dtor_Complete) {
John McCallf99a6312010-07-21 05:30:47 +00001555
1556 // We push them in the forward order so that they'll be popped in
1557 // the reverse order.
Aaron Ballman445a9392014-03-13 16:15:17 +00001558 for (const auto &Base : ClassDecl->vbases()) {
John McCall5c60a6f2010-02-18 19:59:28 +00001559 CXXRecordDecl *BaseClassDecl
1560 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1561
1562 // Ignore trivial destructors.
1563 if (BaseClassDecl->hasTrivialDestructor())
1564 continue;
John McCallf99a6312010-07-21 05:30:47 +00001565
John McCallcda666c2010-07-21 07:22:38 +00001566 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1567 BaseClassDecl,
1568 /*BaseIsVirtual*/ true);
John McCall5c60a6f2010-02-18 19:59:28 +00001569 }
John McCallf99a6312010-07-21 05:30:47 +00001570
John McCall5c60a6f2010-02-18 19:59:28 +00001571 return;
1572 }
1573
1574 assert(DtorType == Dtor_Base);
John McCallf99a6312010-07-21 05:30:47 +00001575
1576 // Destroy non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001577 for (const auto &Base : ClassDecl->bases()) {
John McCallf99a6312010-07-21 05:30:47 +00001578 // Ignore virtual bases.
1579 if (Base.isVirtual())
1580 continue;
1581
1582 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
1583
1584 // Ignore trivial destructors.
1585 if (BaseClassDecl->hasTrivialDestructor())
1586 continue;
John McCall5c60a6f2010-02-18 19:59:28 +00001587
John McCallcda666c2010-07-21 07:22:38 +00001588 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1589 BaseClassDecl,
1590 /*BaseIsVirtual*/ false);
John McCallf99a6312010-07-21 05:30:47 +00001591 }
1592
1593 // Destroy direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001594 for (const auto *Field : ClassDecl->fields()) {
1595 QualType type = Field->getType();
John McCall4bd0fb12011-07-12 16:41:08 +00001596 QualType::DestructionKind dtorKind = type.isDestructedType();
1597 if (!dtorKind) continue;
John McCallf99a6312010-07-21 05:30:47 +00001598
Richard Smith921bd202012-02-26 09:11:52 +00001599 // Anonymous union members do not have their destructors called.
1600 const RecordType *RT = type->getAsUnionType();
1601 if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
1602
John McCall4bd0fb12011-07-12 16:41:08 +00001603 CleanupKind cleanupKind = getCleanupKind(dtorKind);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001604 EHStack.pushCleanup<DestroyField>(cleanupKind, Field,
John McCall4bd0fb12011-07-12 16:41:08 +00001605 getDestroyer(dtorKind),
1606 cleanupKind & EHCleanup);
Anders Carlssonfb404882009-12-24 22:46:43 +00001607 }
Anders Carlssonfb404882009-12-24 22:46:43 +00001608}
1609
John McCallf677a8e2011-07-13 06:10:41 +00001610/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1611/// constructor for each of several members of an array.
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001612///
John McCallf677a8e2011-07-13 06:10:41 +00001613/// \param ctor the constructor to call for each element
John McCallf677a8e2011-07-13 06:10:41 +00001614/// \param arrayType the type of the array to initialize
1615/// \param arrayBegin an arrayType*
1616/// \param zeroInitialize true if each element should be
1617/// zero-initialized before it is constructed
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001618void CodeGenFunction::EmitCXXAggrConstructorCall(
1619 const CXXConstructorDecl *ctor, const ConstantArrayType *arrayType,
1620 llvm::Value *arrayBegin, const CXXConstructExpr *E, bool zeroInitialize) {
John McCallf677a8e2011-07-13 06:10:41 +00001621 QualType elementType;
1622 llvm::Value *numElements =
1623 emitArrayLength(arrayType, elementType, arrayBegin);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001624
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001625 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin, E, zeroInitialize);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001626}
1627
John McCallf677a8e2011-07-13 06:10:41 +00001628/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1629/// constructor for each of several members of an array.
1630///
1631/// \param ctor the constructor to call for each element
1632/// \param numElements the number of elements in the array;
John McCall6549b312011-07-13 07:37:11 +00001633/// may be zero
John McCallf677a8e2011-07-13 06:10:41 +00001634/// \param arrayBegin a T*, where T is the type constructed by ctor
1635/// \param zeroInitialize true if each element should be
1636/// zero-initialized before it is constructed
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001637void CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1638 llvm::Value *numElements,
1639 llvm::Value *arrayBegin,
1640 const CXXConstructExpr *E,
1641 bool zeroInitialize) {
John McCall6549b312011-07-13 07:37:11 +00001642
1643 // It's legal for numElements to be zero. This can happen both
1644 // dynamically, because x can be zero in 'new A[x]', and statically,
1645 // because of GCC extensions that permit zero-length arrays. There
1646 // are probably legitimate places where we could assume that this
1647 // doesn't happen, but it's not clear that it's worth it.
Craig Topper8a13c412014-05-21 05:09:00 +00001648 llvm::BranchInst *zeroCheckBranch = nullptr;
John McCall6549b312011-07-13 07:37:11 +00001649
1650 // Optimize for a constant count.
1651 llvm::ConstantInt *constantCount
1652 = dyn_cast<llvm::ConstantInt>(numElements);
1653 if (constantCount) {
1654 // Just skip out if the constant count is zero.
1655 if (constantCount->isZero()) return;
1656
1657 // Otherwise, emit the check.
1658 } else {
1659 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1660 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1661 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1662 EmitBlock(loopBB);
1663 }
1664
John McCallf677a8e2011-07-13 06:10:41 +00001665 // Find the end of the array.
1666 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1667 "arrayctor.end");
Anders Carlsson27da15b2010-01-01 20:29:01 +00001668
John McCallf677a8e2011-07-13 06:10:41 +00001669 // Enter the loop, setting up a phi for the current location to initialize.
1670 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1671 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1672 EmitBlock(loopBB);
1673 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1674 "arrayctor.cur");
1675 cur->addIncoming(arrayBegin, entryBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001676
Anders Carlsson27da15b2010-01-01 20:29:01 +00001677 // Inside the loop body, emit the constructor call on the array element.
John McCallf677a8e2011-07-13 06:10:41 +00001678
1679 QualType type = getContext().getTypeDeclType(ctor->getParent());
Anders Carlsson27da15b2010-01-01 20:29:01 +00001680
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001681 // Zero initialize the storage, if requested.
John McCallf677a8e2011-07-13 06:10:41 +00001682 if (zeroInitialize)
1683 EmitNullInitialization(cur, type);
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001684
Anders Carlsson27da15b2010-01-01 20:29:01 +00001685 // C++ [class.temporary]p4:
1686 // There are two contexts in which temporaries are destroyed at a different
1687 // point than the end of the full-expression. The first context is when a
1688 // default constructor is called to initialize an element of an array.
1689 // If the constructor has one or more default arguments, the destruction of
1690 // every temporary created in a default argument expression is sequenced
1691 // before the construction of the next array element, if any.
1692
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00001693 {
John McCallbd309292010-07-06 01:34:17 +00001694 RunCleanupsScope Scope(*this);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001695
John McCallf677a8e2011-07-13 06:10:41 +00001696 // Evaluate the constructor and its arguments in a regular
1697 // partial-destroy cleanup.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001698 if (getLangOpts().Exceptions &&
John McCallf677a8e2011-07-13 06:10:41 +00001699 !ctor->getParent()->hasTrivialDestructor()) {
1700 Destroyer *destroyer = destroyCXXObject;
1701 pushRegularPartialArrayCleanup(arrayBegin, cur, type, *destroyer);
1702 }
1703
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001704 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/false,
1705 /*Delegating=*/false, cur, E);
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00001706 }
Anders Carlsson27da15b2010-01-01 20:29:01 +00001707
John McCallf677a8e2011-07-13 06:10:41 +00001708 // Go to the next element.
1709 llvm::Value *next =
1710 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
1711 "arrayctor.next");
1712 cur->addIncoming(next, Builder.GetInsertBlock());
Anders Carlsson27da15b2010-01-01 20:29:01 +00001713
John McCallf677a8e2011-07-13 06:10:41 +00001714 // Check whether that's the end of the loop.
1715 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
1716 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
1717 Builder.CreateCondBr(done, contBB, loopBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001718
John McCall6549b312011-07-13 07:37:11 +00001719 // Patch the earlier check to skip over the loop.
1720 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
1721
John McCallf677a8e2011-07-13 06:10:41 +00001722 EmitBlock(contBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001723}
1724
John McCall82fe67b2011-07-09 01:37:26 +00001725void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
1726 llvm::Value *addr,
1727 QualType type) {
1728 const RecordType *rtype = type->castAs<RecordType>();
1729 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
1730 const CXXDestructorDecl *dtor = record->getDestructor();
1731 assert(!dtor->isTrivial());
1732 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
Douglas Gregor61535002013-01-31 05:50:40 +00001733 /*Delegating=*/false, addr);
John McCall82fe67b2011-07-09 01:37:26 +00001734}
1735
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001736void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
1737 CXXCtorType Type,
1738 bool ForVirtualBase,
1739 bool Delegating, llvm::Value *This,
1740 const CXXConstructExpr *E) {
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001741 // If this is a trivial constructor, just emit what's needed.
John McCallca972cd2010-02-06 00:25:16 +00001742 if (D->isTrivial()) {
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001743 if (E->getNumArgs() == 0) {
John McCallca972cd2010-02-06 00:25:16 +00001744 // Trivial default constructor, no codegen required.
1745 assert(D->isDefaultConstructor() &&
1746 "trivial 0-arg ctor not a default ctor");
Anders Carlsson27da15b2010-01-01 20:29:01 +00001747 return;
1748 }
John McCallca972cd2010-02-06 00:25:16 +00001749
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001750 assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
Sebastian Redl22653ba2011-08-30 19:58:05 +00001751 assert(D->isCopyOrMoveConstructor() &&
1752 "trivial 1-arg ctor not a copy/move ctor");
John McCallca972cd2010-02-06 00:25:16 +00001753
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001754 const Expr *Arg = E->getArg(0);
1755 QualType Ty = Arg->getType();
1756 llvm::Value *Src = EmitLValue(Arg).getAddress();
John McCallca972cd2010-02-06 00:25:16 +00001757 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001758 return;
1759 }
1760
Reid Kleckner89077a12013-12-17 19:46:40 +00001761 // C++11 [class.mfct.non-static]p2:
1762 // If a non-static member function of a class X is called for an object that
1763 // is not of type X, or of a type derived from X, the behavior is undefined.
1764 // FIXME: Provide a source location here.
1765 EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall, SourceLocation(), This,
1766 getContext().getRecordType(D->getParent()));
1767
1768 CallArgList Args;
1769
1770 // Push the this ptr.
1771 Args.add(RValue::get(This), D->getThisType(getContext()));
1772
1773 // Add the rest of the user-supplied arguments.
1774 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001775 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end(), E->getConstructor());
Reid Kleckner89077a12013-12-17 19:46:40 +00001776
1777 // Insert any ABI-specific implicit constructor arguments.
1778 unsigned ExtraArgs = CGM.getCXXABI().addImplicitConstructorArgs(
1779 *this, D, Type, ForVirtualBase, Delegating, Args);
1780
1781 // Emit the call.
Rafael Espindola1ac0ec82014-09-11 15:42:06 +00001782 llvm::Value *Callee = CGM.getAddrOfCXXStructor(D, getFromCtorType(Type));
Reid Kleckner89077a12013-12-17 19:46:40 +00001783 const CGFunctionInfo &Info =
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001784 CGM.getTypes().arrangeCXXConstructorCall(Args, D, Type, ExtraArgs);
Reid Kleckner89077a12013-12-17 19:46:40 +00001785 EmitCall(Info, Callee, ReturnValueSlot(), Args, D);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001786}
1787
John McCallf8ff7b92010-02-23 00:48:20 +00001788void
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001789CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
1790 llvm::Value *This, llvm::Value *Src,
Alexey Samsonov525bf652014-08-25 21:58:56 +00001791 const CXXConstructExpr *E) {
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001792 if (D->isTrivial()) {
Alexey Samsonov96fd0a42014-08-26 20:18:26 +00001793 assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
Sebastian Redl22653ba2011-08-30 19:58:05 +00001794 assert(D->isCopyOrMoveConstructor() &&
1795 "trivial 1-arg ctor not a copy/move ctor");
Alexey Samsonov525bf652014-08-25 21:58:56 +00001796 EmitAggregateCopy(This, Src, E->arg_begin()->getType());
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001797 return;
1798 }
Rafael Espindola1ac0ec82014-09-11 15:42:06 +00001799 llvm::Value *Callee = CGM.getAddrOfCXXStructor(D, StructorType::Complete);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001800 assert(D->isInstance() &&
1801 "Trying to emit a member call expr on a static method!");
1802
Reid Kleckner739756c2013-12-04 19:23:12 +00001803 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001804
1805 CallArgList Args;
1806
1807 // Push the this ptr.
Eli Friedman43dca6a2011-05-02 17:57:46 +00001808 Args.add(RValue::get(This), D->getThisType(getContext()));
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001809
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001810 // Push the src ptr.
Alp Toker9cacbab2014-01-20 20:26:09 +00001811 QualType QT = *(FPT->param_type_begin());
Chris Lattner2192fe52011-07-18 04:24:23 +00001812 llvm::Type *t = CGM.getTypes().ConvertType(QT);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001813 Src = Builder.CreateBitCast(Src, t);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001814 Args.add(RValue::get(Src), QT);
Reid Kleckner739756c2013-12-04 19:23:12 +00001815
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001816 // Skip over first argument (Src).
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001817 EmitCallArgs(Args, FPT, E->arg_begin() + 1, E->arg_end(), E->getConstructor(),
1818 /*ParamsToSkip*/ 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00001819
John McCall8dda7b22012-07-07 06:41:13 +00001820 EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, RequiredArgs::All),
1821 Callee, ReturnValueSlot(), Args, D);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001822}
1823
1824void
John McCallf8ff7b92010-02-23 00:48:20 +00001825CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1826 CXXCtorType CtorType,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001827 const FunctionArgList &Args,
1828 SourceLocation Loc) {
John McCallf8ff7b92010-02-23 00:48:20 +00001829 CallArgList DelegateArgs;
1830
1831 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
1832 assert(I != E && "no parameters to constructor");
1833
1834 // this
Eli Friedman43dca6a2011-05-02 17:57:46 +00001835 DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType());
John McCallf8ff7b92010-02-23 00:48:20 +00001836 ++I;
1837
1838 // vtt
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001839 if (llvm::Value *VTT = GetVTTParameter(GlobalDecl(Ctor, CtorType),
Douglas Gregor61535002013-01-31 05:50:40 +00001840 /*ForVirtualBase=*/false,
1841 /*Delegating=*/true)) {
John McCallf8ff7b92010-02-23 00:48:20 +00001842 QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001843 DelegateArgs.add(RValue::get(VTT), VoidPP);
John McCallf8ff7b92010-02-23 00:48:20 +00001844
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001845 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
John McCallf8ff7b92010-02-23 00:48:20 +00001846 assert(I != E && "cannot skip vtt parameter, already done with args");
John McCalla738c252011-03-09 04:27:21 +00001847 assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
John McCallf8ff7b92010-02-23 00:48:20 +00001848 ++I;
1849 }
1850 }
1851
1852 // Explicit arguments.
1853 for (; I != E; ++I) {
John McCall32ea9692011-03-11 20:59:21 +00001854 const VarDecl *param = *I;
Nick Lewycky2d84e842013-10-02 02:29:49 +00001855 // FIXME: per-argument source location
1856 EmitDelegateCallArg(DelegateArgs, param, Loc);
John McCallf8ff7b92010-02-23 00:48:20 +00001857 }
1858
Rafael Espindola1ac0ec82014-09-11 15:42:06 +00001859 llvm::Value *Callee =
1860 CGM.getAddrOfCXXStructor(Ctor, getFromCtorType(CtorType));
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001861 EmitCall(CGM.getTypes()
1862 .arrangeCXXStructorDeclaration(Ctor, getFromCtorType(CtorType)),
Manman Ren01754612013-03-20 16:59:38 +00001863 Callee, ReturnValueSlot(), DelegateArgs, Ctor);
John McCallf8ff7b92010-02-23 00:48:20 +00001864}
1865
Alexis Hunt9d47faf2011-05-03 23:05:34 +00001866namespace {
1867 struct CallDelegatingCtorDtor : EHScopeStack::Cleanup {
1868 const CXXDestructorDecl *Dtor;
1869 llvm::Value *Addr;
1870 CXXDtorType Type;
1871
1872 CallDelegatingCtorDtor(const CXXDestructorDecl *D, llvm::Value *Addr,
1873 CXXDtorType Type)
1874 : Dtor(D), Addr(Addr), Type(Type) {}
1875
Craig Topper4f12f102014-03-12 06:41:41 +00001876 void Emit(CodeGenFunction &CGF, Flags flags) override {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00001877 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
Douglas Gregor61535002013-01-31 05:50:40 +00001878 /*Delegating=*/true, Addr);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00001879 }
1880 };
1881}
1882
Alexis Hunt61bc1732011-05-01 07:04:31 +00001883void
1884CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
1885 const FunctionArgList &Args) {
1886 assert(Ctor->isDelegatingConstructor());
1887
1888 llvm::Value *ThisPtr = LoadCXXThis();
1889
Eli Friedmanc1d85b92011-12-03 00:54:26 +00001890 QualType Ty = getContext().getTagDeclType(Ctor->getParent());
Eli Friedman38cd36d2011-12-03 02:13:40 +00001891 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
John McCall31168b02011-06-15 23:02:42 +00001892 AggValueSlot AggSlot =
Eli Friedmanc1d85b92011-12-03 00:54:26 +00001893 AggValueSlot::forAddr(ThisPtr, Alignment, Qualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +00001894 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001895 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001896 AggValueSlot::IsNotAliased);
Alexis Hunt61bc1732011-05-01 07:04:31 +00001897
1898 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
Alexis Hunt61bc1732011-05-01 07:04:31 +00001899
Alexis Hunt9d47faf2011-05-03 23:05:34 +00001900 const CXXRecordDecl *ClassDecl = Ctor->getParent();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001901 if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00001902 CXXDtorType Type =
1903 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
1904
1905 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
1906 ClassDecl->getDestructor(),
1907 ThisPtr, Type);
1908 }
1909}
Alexis Hunt61bc1732011-05-01 07:04:31 +00001910
Anders Carlsson27da15b2010-01-01 20:29:01 +00001911void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
1912 CXXDtorType Type,
Anders Carlssonf8a71f02010-05-02 23:29:11 +00001913 bool ForVirtualBase,
Douglas Gregor61535002013-01-31 05:50:40 +00001914 bool Delegating,
Anders Carlsson27da15b2010-01-01 20:29:01 +00001915 llvm::Value *This) {
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001916 CGM.getCXXABI().EmitDestructorCall(*this, DD, Type, ForVirtualBase,
1917 Delegating, This);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001918}
1919
John McCall53cad2e2010-07-21 01:41:18 +00001920namespace {
John McCallcda666c2010-07-21 07:22:38 +00001921 struct CallLocalDtor : EHScopeStack::Cleanup {
John McCall53cad2e2010-07-21 01:41:18 +00001922 const CXXDestructorDecl *Dtor;
1923 llvm::Value *Addr;
1924
1925 CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
1926 : Dtor(D), Addr(Addr) {}
1927
Craig Topper4f12f102014-03-12 06:41:41 +00001928 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall53cad2e2010-07-21 01:41:18 +00001929 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +00001930 /*ForVirtualBase=*/false,
1931 /*Delegating=*/false, Addr);
John McCall53cad2e2010-07-21 01:41:18 +00001932 }
1933 };
1934}
1935
John McCall8680f872010-07-21 06:29:51 +00001936void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
1937 llvm::Value *Addr) {
John McCallcda666c2010-07-21 07:22:38 +00001938 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
John McCall8680f872010-07-21 06:29:51 +00001939}
1940
John McCallbd309292010-07-06 01:34:17 +00001941void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
1942 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
1943 if (!ClassDecl) return;
1944 if (ClassDecl->hasTrivialDestructor()) return;
1945
1946 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCalla85af562011-04-28 02:15:35 +00001947 assert(D && D->isUsed() && "destructor not marked as used!");
John McCall8680f872010-07-21 06:29:51 +00001948 PushDestructorCleanup(D, Addr);
John McCallbd309292010-07-06 01:34:17 +00001949}
1950
Anders Carlssone87fae92010-03-28 19:40:00 +00001951void
1952CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
Anders Carlsson652758c2010-04-20 05:22:15 +00001953 const CXXRecordDecl *NearestVBase,
Ken Dyck3fb4c892011-03-23 01:04:18 +00001954 CharUnits OffsetFromNearestVBase,
Anders Carlssone87fae92010-03-28 19:40:00 +00001955 const CXXRecordDecl *VTableClass) {
Anders Carlssone87fae92010-03-28 19:40:00 +00001956 // Compute the address point.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001957 bool NeedsVirtualOffset;
1958 llvm::Value *VTableAddressPoint =
1959 CGM.getCXXABI().getVTableAddressPointInStructor(
1960 *this, VTableClass, Base, NearestVBase, NeedsVirtualOffset);
1961 if (!VTableAddressPoint)
1962 return;
Anders Carlssone87fae92010-03-28 19:40:00 +00001963
Anders Carlsson6a0227d2010-04-20 16:22:16 +00001964 // Compute where to store the address point.
Craig Topper8a13c412014-05-21 05:09:00 +00001965 llvm::Value *VirtualOffset = nullptr;
Ken Dyckcfc332c2011-03-23 00:45:26 +00001966 CharUnits NonVirtualOffset = CharUnits::Zero();
Anders Carlsson91baecf2010-04-20 18:05:10 +00001967
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001968 if (NeedsVirtualOffset) {
Anders Carlsson91baecf2010-04-20 18:05:10 +00001969 // We need to use the virtual base offset offset because the virtual base
1970 // might have a different offset in the most derived class.
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001971 VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(*this,
1972 LoadCXXThis(),
1973 VTableClass,
1974 NearestVBase);
Ken Dyck3fb4c892011-03-23 01:04:18 +00001975 NonVirtualOffset = OffsetFromNearestVBase;
Anders Carlsson91baecf2010-04-20 18:05:10 +00001976 } else {
Anders Carlssonc58fb552010-05-03 00:29:58 +00001977 // We can just use the base offset in the complete class.
Ken Dyck16ffcac2011-03-24 01:21:01 +00001978 NonVirtualOffset = Base.getBaseOffset();
Anders Carlsson91baecf2010-04-20 18:05:10 +00001979 }
Anders Carlssonc58fb552010-05-03 00:29:58 +00001980
1981 // Apply the offsets.
1982 llvm::Value *VTableField = LoadCXXThis();
1983
Ken Dyckcfc332c2011-03-23 00:45:26 +00001984 if (!NonVirtualOffset.isZero() || VirtualOffset)
Anders Carlssonc58fb552010-05-03 00:29:58 +00001985 VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
1986 NonVirtualOffset,
1987 VirtualOffset);
Anders Carlsson6a0227d2010-04-20 16:22:16 +00001988
Anders Carlssone87fae92010-03-28 19:40:00 +00001989 // Finally, store the address point.
Chris Lattner2192fe52011-07-18 04:24:23 +00001990 llvm::Type *AddressPointPtrTy =
Anders Carlssone87fae92010-03-28 19:40:00 +00001991 VTableAddressPoint->getType()->getPointerTo();
1992 VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
Kostya Serebryany141e46f2012-03-26 17:03:51 +00001993 llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
1994 CGM.DecorateInstruction(Store, CGM.getTBAAInfoForVTablePtr());
Anders Carlssone87fae92010-03-28 19:40:00 +00001995}
1996
Anders Carlssond5895932010-03-28 21:07:49 +00001997void
1998CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
Anders Carlsson652758c2010-04-20 05:22:15 +00001999 const CXXRecordDecl *NearestVBase,
Ken Dyck3fb4c892011-03-23 01:04:18 +00002000 CharUnits OffsetFromNearestVBase,
Anders Carlssond5895932010-03-28 21:07:49 +00002001 bool BaseIsNonVirtualPrimaryBase,
Anders Carlssond5895932010-03-28 21:07:49 +00002002 const CXXRecordDecl *VTableClass,
2003 VisitedVirtualBasesSetTy& VBases) {
2004 // If this base is a non-virtual primary base the address point has already
2005 // been set.
2006 if (!BaseIsNonVirtualPrimaryBase) {
2007 // Initialize the vtable pointer for this base.
Anders Carlssonc4d0d0f2010-05-03 00:07:07 +00002008 InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
Timur Iskhodzhanovd8fa10d2013-08-21 17:33:16 +00002009 VTableClass);
Anders Carlssond5895932010-03-28 21:07:49 +00002010 }
2011
2012 const CXXRecordDecl *RD = Base.getBase();
2013
2014 // Traverse bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00002015 for (const auto &I : RD->bases()) {
Anders Carlssond5895932010-03-28 21:07:49 +00002016 CXXRecordDecl *BaseDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00002017 = cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Anders Carlssond5895932010-03-28 21:07:49 +00002018
2019 // Ignore classes without a vtable.
2020 if (!BaseDecl->isDynamicClass())
2021 continue;
2022
Ken Dyck3fb4c892011-03-23 01:04:18 +00002023 CharUnits BaseOffset;
2024 CharUnits BaseOffsetFromNearestVBase;
Anders Carlsson948d3f42010-03-29 01:16:41 +00002025 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlssond5895932010-03-28 21:07:49 +00002026
Aaron Ballman574705e2014-03-13 15:41:46 +00002027 if (I.isVirtual()) {
Anders Carlssond5895932010-03-28 21:07:49 +00002028 // Check if we've visited this virtual base before.
2029 if (!VBases.insert(BaseDecl))
2030 continue;
2031
2032 const ASTRecordLayout &Layout =
2033 getContext().getASTRecordLayout(VTableClass);
2034
Ken Dyck3fb4c892011-03-23 01:04:18 +00002035 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
2036 BaseOffsetFromNearestVBase = CharUnits::Zero();
Anders Carlsson948d3f42010-03-29 01:16:41 +00002037 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlssond5895932010-03-28 21:07:49 +00002038 } else {
2039 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
2040
Ken Dyck16ffcac2011-03-24 01:21:01 +00002041 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
Anders Carlssonc4d0d0f2010-05-03 00:07:07 +00002042 BaseOffsetFromNearestVBase =
Ken Dyck3fb4c892011-03-23 01:04:18 +00002043 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson948d3f42010-03-29 01:16:41 +00002044 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlssond5895932010-03-28 21:07:49 +00002045 }
2046
Ken Dyck16ffcac2011-03-24 01:21:01 +00002047 InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
Aaron Ballman574705e2014-03-13 15:41:46 +00002048 I.isVirtual() ? BaseDecl : NearestVBase,
Anders Carlssonc4d0d0f2010-05-03 00:07:07 +00002049 BaseOffsetFromNearestVBase,
Anders Carlsson948d3f42010-03-29 01:16:41 +00002050 BaseDeclIsNonVirtualPrimaryBase,
Timur Iskhodzhanovd8fa10d2013-08-21 17:33:16 +00002051 VTableClass, VBases);
Anders Carlssond5895932010-03-28 21:07:49 +00002052 }
2053}
2054
2055void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
2056 // Ignore classes without a vtable.
Anders Carlsson1f9348c2010-03-26 04:39:42 +00002057 if (!RD->isDynamicClass())
Anders Carlsson27da15b2010-01-01 20:29:01 +00002058 return;
2059
Anders Carlssond5895932010-03-28 21:07:49 +00002060 // Initialize the vtable pointers for this class and all of its bases.
2061 VisitedVirtualBasesSetTy VBases;
Ken Dyck16ffcac2011-03-24 01:21:01 +00002062 InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()),
Craig Topper8a13c412014-05-21 05:09:00 +00002063 /*NearestVBase=*/nullptr,
Ken Dyck3fb4c892011-03-23 01:04:18 +00002064 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
Timur Iskhodzhanovd8fa10d2013-08-21 17:33:16 +00002065 /*BaseIsNonVirtualPrimaryBase=*/false, RD, VBases);
Timur Iskhodzhanovb6487322013-10-09 18:16:58 +00002066
2067 if (RD->getNumVBases())
2068 CGM.getCXXABI().initializeHiddenVirtualInheritanceMembers(*this, RD);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002069}
Dan Gohman8fc50c22010-10-26 18:44:08 +00002070
2071llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
Chris Lattner2192fe52011-07-18 04:24:23 +00002072 llvm::Type *Ty) {
Dan Gohman8fc50c22010-10-26 18:44:08 +00002073 llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002074 llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
2075 CGM.DecorateInstruction(VTable, CGM.getTBAAInfoForVTablePtr());
2076 return VTable;
Dan Gohman8fc50c22010-10-26 18:44:08 +00002077}
Anders Carlssonc36783e2011-05-08 20:32:23 +00002078
Anders Carlssonc36783e2011-05-08 20:32:23 +00002079
2080// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
2081// quite what we want.
2082static const Expr *skipNoOpCastsAndParens(const Expr *E) {
2083 while (true) {
2084 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
2085 E = PE->getSubExpr();
2086 continue;
2087 }
2088
2089 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
2090 if (CE->getCastKind() == CK_NoOp) {
2091 E = CE->getSubExpr();
2092 continue;
2093 }
2094 }
2095 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2096 if (UO->getOpcode() == UO_Extension) {
2097 E = UO->getSubExpr();
2098 continue;
2099 }
2100 }
2101 return E;
2102 }
2103}
2104
Benjamin Kramer7463ed72013-08-25 22:46:27 +00002105bool
2106CodeGenFunction::CanDevirtualizeMemberFunctionCall(const Expr *Base,
2107 const CXXMethodDecl *MD) {
2108 // When building with -fapple-kext, all calls must go through the vtable since
2109 // the kernel linker can do runtime patching of vtables.
2110 if (getLangOpts().AppleKext)
2111 return false;
2112
Anders Carlssonc36783e2011-05-08 20:32:23 +00002113 // If the most derived class is marked final, we know that no subclass can
2114 // override this member function and so we can devirtualize it. For example:
2115 //
2116 // struct A { virtual void f(); }
2117 // struct B final : A { };
2118 //
2119 // void f(B *b) {
2120 // b->f();
2121 // }
2122 //
Benjamin Kramer7463ed72013-08-25 22:46:27 +00002123 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
Anders Carlssonc36783e2011-05-08 20:32:23 +00002124 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
2125 return true;
2126
2127 // If the member function is marked 'final', we know that it can't be
2128 // overridden and can therefore devirtualize it.
2129 if (MD->hasAttr<FinalAttr>())
2130 return true;
2131
2132 // Similarly, if the class itself is marked 'final' it can't be overridden
2133 // and we can therefore devirtualize the member function call.
2134 if (MD->getParent()->hasAttr<FinalAttr>())
2135 return true;
2136
2137 Base = skipNoOpCastsAndParens(Base);
2138 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
2139 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
2140 // This is a record decl. We know the type and can devirtualize it.
2141 return VD->getType()->isRecordType();
2142 }
2143
2144 return false;
2145 }
Benjamin Kramer7463ed72013-08-25 22:46:27 +00002146
2147 // We can devirtualize calls on an object accessed by a class member access
2148 // expression, since by C++11 [basic.life]p6 we know that it can't refer to
2149 // a derived class object constructed in the same location.
2150 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Base))
2151 if (const ValueDecl *VD = dyn_cast<ValueDecl>(ME->getMemberDecl()))
2152 return VD->getType()->isRecordType();
2153
Anders Carlssonc36783e2011-05-08 20:32:23 +00002154 // We can always devirtualize calls on temporary object expressions.
2155 if (isa<CXXConstructExpr>(Base))
2156 return true;
2157
2158 // And calls on bound temporaries.
2159 if (isa<CXXBindTemporaryExpr>(Base))
2160 return true;
2161
2162 // Check if this is a call expr that returns a record type.
2163 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
2164 return CE->getCallReturnType()->isRecordType();
2165
2166 // We can't devirtualize the call.
2167 return false;
2168}
2169
Anders Carlssonc36783e2011-05-08 20:32:23 +00002170llvm::Value *
2171CodeGenFunction::EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E,
2172 const CXXMethodDecl *MD,
2173 llvm::Value *This) {
John McCalla729c622012-02-17 03:33:10 +00002174 llvm::FunctionType *fnType =
2175 CGM.getTypes().GetFunctionType(
2176 CGM.getTypes().arrangeCXXMethodDeclaration(MD));
Anders Carlssonc36783e2011-05-08 20:32:23 +00002177
Benjamin Kramer7463ed72013-08-25 22:46:27 +00002178 if (MD->isVirtual() && !CanDevirtualizeMemberFunctionCall(E->getArg(0), MD))
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00002179 return CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, fnType);
Anders Carlssonc36783e2011-05-08 20:32:23 +00002180
John McCalla729c622012-02-17 03:33:10 +00002181 return CGM.GetAddrOfFunction(MD, fnType);
Anders Carlssonc36783e2011-05-08 20:32:23 +00002182}
Eli Friedman5a6d5072012-02-16 01:37:33 +00002183
Faisal Vali571df122013-09-29 08:45:24 +00002184void CodeGenFunction::EmitForwardingCallToLambda(
2185 const CXXMethodDecl *callOperator,
2186 CallArgList &callArgs) {
Eli Friedman5b446882012-02-16 03:47:28 +00002187 // Get the address of the call operator.
John McCall8dda7b22012-07-07 06:41:13 +00002188 const CGFunctionInfo &calleeFnInfo =
2189 CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
2190 llvm::Value *callee =
2191 CGM.GetAddrOfFunction(GlobalDecl(callOperator),
2192 CGM.getTypes().GetFunctionType(calleeFnInfo));
Eli Friedman5b446882012-02-16 03:47:28 +00002193
John McCall8dda7b22012-07-07 06:41:13 +00002194 // Prepare the return slot.
2195 const FunctionProtoType *FPT =
2196 callOperator->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00002197 QualType resultType = FPT->getReturnType();
John McCall8dda7b22012-07-07 06:41:13 +00002198 ReturnValueSlot returnSlot;
2199 if (!resultType->isVoidType() &&
2200 calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
John McCall47fb9502013-03-07 21:37:08 +00002201 !hasScalarEvaluationKind(calleeFnInfo.getReturnType()))
John McCall8dda7b22012-07-07 06:41:13 +00002202 returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
2203
2204 // We don't need to separately arrange the call arguments because
2205 // the call can't be variadic anyway --- it's impossible to forward
2206 // variadic arguments.
Eli Friedman5b446882012-02-16 03:47:28 +00002207
2208 // Now emit our call.
John McCall8dda7b22012-07-07 06:41:13 +00002209 RValue RV = EmitCall(calleeFnInfo, callee, returnSlot,
2210 callArgs, callOperator);
Eli Friedman5b446882012-02-16 03:47:28 +00002211
John McCall8dda7b22012-07-07 06:41:13 +00002212 // If necessary, copy the returned value into the slot.
2213 if (!resultType->isVoidType() && returnSlot.isNull())
2214 EmitReturnOfRValue(RV, resultType);
Eli Friedmanf5f4d2f2012-12-13 23:37:17 +00002215 else
2216 EmitBranchThroughCleanup(ReturnBlock);
Eli Friedman5b446882012-02-16 03:47:28 +00002217}
2218
Eli Friedman2495ab02012-02-25 02:48:22 +00002219void CodeGenFunction::EmitLambdaBlockInvokeBody() {
2220 const BlockDecl *BD = BlockInfo->getBlockDecl();
2221 const VarDecl *variable = BD->capture_begin()->getVariable();
2222 const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
2223
2224 // Start building arguments for forwarding call
2225 CallArgList CallArgs;
2226
2227 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2228 llvm::Value *ThisPtr = GetAddrOfBlockDecl(variable, false);
2229 CallArgs.add(RValue::get(ThisPtr), ThisType);
2230
2231 // Add the rest of the parameters.
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00002232 for (auto param : BD->params())
Nick Lewycky2d84e842013-10-02 02:29:49 +00002233 EmitDelegateCallArg(CallArgs, param, param->getLocStart());
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00002234
Faisal Vali571df122013-09-29 08:45:24 +00002235 assert(!Lambda->isGenericLambda() &&
2236 "generic lambda interconversion to block not implemented");
2237 EmitForwardingCallToLambda(Lambda->getLambdaCallOperator(), CallArgs);
Eli Friedman2495ab02012-02-25 02:48:22 +00002238}
2239
2240void CodeGenFunction::EmitLambdaToBlockPointerBody(FunctionArgList &Args) {
John McCalldec348f72013-05-03 07:33:41 +00002241 if (cast<CXXMethodDecl>(CurCodeDecl)->isVariadic()) {
Eli Friedman2495ab02012-02-25 02:48:22 +00002242 // FIXME: Making this work correctly is nasty because it requires either
2243 // cloning the body of the call operator or making the call operator forward.
John McCalldec348f72013-05-03 07:33:41 +00002244 CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function");
Eli Friedman2495ab02012-02-25 02:48:22 +00002245 return;
2246 }
2247
Richard Smithb47c36f2013-11-05 09:12:18 +00002248 EmitFunctionBody(Args, cast<FunctionDecl>(CurGD.getDecl())->getBody());
Eli Friedman2495ab02012-02-25 02:48:22 +00002249}
2250
2251void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
2252 const CXXRecordDecl *Lambda = MD->getParent();
2253
2254 // Start building arguments for forwarding call
2255 CallArgList CallArgs;
2256
2257 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2258 llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
2259 CallArgs.add(RValue::get(ThisPtr), ThisType);
2260
2261 // Add the rest of the parameters.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002262 for (auto Param : MD->params())
2263 EmitDelegateCallArg(CallArgs, Param, Param->getLocStart());
2264
Faisal Vali571df122013-09-29 08:45:24 +00002265 const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
2266 // For a generic lambda, find the corresponding call operator specialization
2267 // to which the call to the static-invoker shall be forwarded.
2268 if (Lambda->isGenericLambda()) {
2269 assert(MD->isFunctionTemplateSpecialization());
2270 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
2271 FunctionTemplateDecl *CallOpTemplate = CallOp->getDescribedFunctionTemplate();
Craig Topper8a13c412014-05-21 05:09:00 +00002272 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +00002273 FunctionDecl *CorrespondingCallOpSpecialization =
Craig Topper7e0daca2014-06-26 04:58:53 +00002274 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
Faisal Vali571df122013-09-29 08:45:24 +00002275 assert(CorrespondingCallOpSpecialization);
2276 CallOp = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
2277 }
2278 EmitForwardingCallToLambda(CallOp, CallArgs);
Eli Friedman2495ab02012-02-25 02:48:22 +00002279}
2280
Douglas Gregor355efbb2012-02-17 03:02:34 +00002281void CodeGenFunction::EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD) {
2282 if (MD->isVariadic()) {
Eli Friedman5b446882012-02-16 03:47:28 +00002283 // FIXME: Making this work correctly is nasty because it requires either
2284 // cloning the body of the call operator or making the call operator forward.
2285 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
Eli Friedman2495ab02012-02-25 02:48:22 +00002286 return;
Eli Friedman5b446882012-02-16 03:47:28 +00002287 }
2288
Douglas Gregor355efbb2012-02-17 03:02:34 +00002289 EmitLambdaDelegatingInvokeBody(MD);
Eli Friedman5a6d5072012-02-16 01:37:33 +00002290}