blob: a6f350e393a2966c6e3ed0fe2ddfcd9bc2569635 [file] [log] [blame]
Hans Wennborgdcfba332015-10-06 23:40:43 +00001//===--- CGClass.cpp - Emit LLVM Code for C++ classes -----------*- C++ -*-===//
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"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000026#include "clang/Frontend/CodeGenOptions.h"
Peter Collingbournea4ccff32015-02-20 20:30:56 +000027#include "llvm/IR/Intrinsics.h"
Piotr Padlewski4b1ac722015-09-15 21:46:55 +000028#include "llvm/IR/Metadata.h"
Peter Collingbournedc134532016-01-16 00:31:22 +000029#include "llvm/Transforms/Utils/SanitizerStats.h"
Anders Carlssonc6d171e2009-10-06 22:43:30 +000030
Anders Carlsson9a57c5a2009-09-12 04:27:24 +000031using namespace clang;
32using namespace CodeGen;
33
John McCall7f416cc2015-09-08 08:05:57 +000034/// Return the best known alignment for an unknown pointer to a
35/// particular class.
36CharUnits CodeGenModule::getClassPointerAlignment(const CXXRecordDecl *RD) {
37 if (!RD->isCompleteDefinition())
38 return CharUnits::One(); // Hopefully won't be used anywhere.
39
40 auto &layout = getContext().getASTRecordLayout(RD);
41
42 // If the class is final, then we know that the pointer points to an
43 // object of that type and can use the full alignment.
44 if (RD->hasAttr<FinalAttr>()) {
45 return layout.getAlignment();
46
47 // Otherwise, we have to assume it could be a subclass.
48 } else {
49 return layout.getNonVirtualAlignment();
50 }
51}
52
53/// Return the best known alignment for a pointer to a virtual base,
54/// given the alignment of a pointer to the derived class.
55CharUnits CodeGenModule::getVBaseAlignment(CharUnits actualDerivedAlign,
56 const CXXRecordDecl *derivedClass,
57 const CXXRecordDecl *vbaseClass) {
58 // The basic idea here is that an underaligned derived pointer might
59 // indicate an underaligned base pointer.
60
61 assert(vbaseClass->isCompleteDefinition());
62 auto &baseLayout = getContext().getASTRecordLayout(vbaseClass);
63 CharUnits expectedVBaseAlign = baseLayout.getNonVirtualAlignment();
64
65 return getDynamicOffsetAlignment(actualDerivedAlign, derivedClass,
66 expectedVBaseAlign);
67}
68
69CharUnits
70CodeGenModule::getDynamicOffsetAlignment(CharUnits actualBaseAlign,
71 const CXXRecordDecl *baseDecl,
72 CharUnits expectedTargetAlign) {
73 // If the base is an incomplete type (which is, alas, possible with
74 // member pointers), be pessimistic.
75 if (!baseDecl->isCompleteDefinition())
76 return std::min(actualBaseAlign, expectedTargetAlign);
77
78 auto &baseLayout = getContext().getASTRecordLayout(baseDecl);
79 CharUnits expectedBaseAlign = baseLayout.getNonVirtualAlignment();
80
81 // If the class is properly aligned, assume the target offset is, too.
82 //
83 // This actually isn't necessarily the right thing to do --- if the
84 // class is a complete object, but it's only properly aligned for a
85 // base subobject, then the alignments of things relative to it are
86 // probably off as well. (Note that this requires the alignment of
87 // the target to be greater than the NV alignment of the derived
88 // class.)
89 //
90 // However, our approach to this kind of under-alignment can only
91 // ever be best effort; after all, we're never going to propagate
92 // alignments through variables or parameters. Note, in particular,
93 // that constructing a polymorphic type in an address that's less
94 // than pointer-aligned will generally trap in the constructor,
95 // unless we someday add some sort of attribute to change the
96 // assumed alignment of 'this'. So our goal here is pretty much
97 // just to allow the user to explicitly say that a pointer is
Eric Christopherd160c502016-01-29 01:35:53 +000098 // under-aligned and then safely access its fields and vtables.
John McCall7f416cc2015-09-08 08:05:57 +000099 if (actualBaseAlign >= expectedBaseAlign) {
100 return expectedTargetAlign;
101 }
102
103 // Otherwise, we might be offset by an arbitrary multiple of the
104 // actual alignment. The correct adjustment is to take the min of
105 // the two alignments.
106 return std::min(actualBaseAlign, expectedTargetAlign);
107}
108
109Address CodeGenFunction::LoadCXXThisAddress() {
110 assert(CurFuncDecl && "loading 'this' without a func declaration?");
111 assert(isa<CXXMethodDecl>(CurFuncDecl));
112
113 // Lazily compute CXXThisAlignment.
114 if (CXXThisAlignment.isZero()) {
115 // Just use the best known alignment for the parent.
116 // TODO: if we're currently emitting a complete-object ctor/dtor,
117 // we can always use the complete-object alignment.
118 auto RD = cast<CXXMethodDecl>(CurFuncDecl)->getParent();
119 CXXThisAlignment = CGM.getClassPointerAlignment(RD);
120 }
121
122 return Address(LoadCXXThis(), CXXThisAlignment);
123}
124
125/// Emit the address of a field using a member data pointer.
126///
127/// \param E Only used for emergency diagnostics
128Address
129CodeGenFunction::EmitCXXMemberDataPointerAddress(const Expr *E, Address base,
130 llvm::Value *memberPtr,
131 const MemberPointerType *memberPtrType,
132 AlignmentSource *alignSource) {
133 // Ask the ABI to compute the actual address.
134 llvm::Value *ptr =
135 CGM.getCXXABI().EmitMemberDataPointerAddress(*this, E, base,
136 memberPtr, memberPtrType);
137
138 QualType memberType = memberPtrType->getPointeeType();
139 CharUnits memberAlign = getNaturalTypeAlignment(memberType, alignSource);
140 memberAlign =
141 CGM.getDynamicOffsetAlignment(base.getAlignment(),
142 memberPtrType->getClass()->getAsCXXRecordDecl(),
143 memberAlign);
144 return Address(ptr, memberAlign);
145}
146
David Majnemerc1709d32015-06-23 07:31:11 +0000147CharUnits CodeGenModule::computeNonVirtualBaseClassOffset(
148 const CXXRecordDecl *DerivedClass, CastExpr::path_const_iterator Start,
149 CastExpr::path_const_iterator End) {
Ken Dycka1a4ae32011-03-22 00:53:26 +0000150 CharUnits Offset = CharUnits::Zero();
Justin Bogner1cd11f12015-05-20 15:53:59 +0000151
David Majnemerc1709d32015-06-23 07:31:11 +0000152 const ASTContext &Context = getContext();
Anders Carlssond829a022010-04-24 21:06:20 +0000153 const CXXRecordDecl *RD = DerivedClass;
Justin Bogner1cd11f12015-05-20 15:53:59 +0000154
John McCallcf142162010-08-07 06:22:56 +0000155 for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
Anders Carlssond829a022010-04-24 21:06:20 +0000156 const CXXBaseSpecifier *Base = *I;
157 assert(!Base->isVirtual() && "Should not see virtual bases here!");
158
159 // Get the layout.
160 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000161
162 const CXXRecordDecl *BaseDecl =
Anders Carlssond829a022010-04-24 21:06:20 +0000163 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Justin Bogner1cd11f12015-05-20 15:53:59 +0000164
Anders Carlssond829a022010-04-24 21:06:20 +0000165 // Add the offset.
Ken Dycka1a4ae32011-03-22 00:53:26 +0000166 Offset += Layout.getBaseClassOffset(BaseDecl);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000167
Anders Carlssond829a022010-04-24 21:06:20 +0000168 RD = BaseDecl;
169 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000170
Ken Dycka1a4ae32011-03-22 00:53:26 +0000171 return Offset;
Anders Carlssond829a022010-04-24 21:06:20 +0000172}
Anders Carlsson9a57c5a2009-09-12 04:27:24 +0000173
Anders Carlsson9150a2a2009-09-29 03:13:20 +0000174llvm::Constant *
Anders Carlsson8a64c1c2010-04-24 21:23:59 +0000175CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
John McCallcf142162010-08-07 06:22:56 +0000176 CastExpr::path_const_iterator PathBegin,
177 CastExpr::path_const_iterator PathEnd) {
178 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlsson8a64c1c2010-04-24 21:23:59 +0000179
Justin Bogner1cd11f12015-05-20 15:53:59 +0000180 CharUnits Offset =
David Majnemerc1709d32015-06-23 07:31:11 +0000181 computeNonVirtualBaseClassOffset(ClassDecl, PathBegin, PathEnd);
Ken Dycka1a4ae32011-03-22 00:53:26 +0000182 if (Offset.isZero())
Craig Topper8a13c412014-05-21 05:09:00 +0000183 return nullptr;
184
Justin Bogner1cd11f12015-05-20 15:53:59 +0000185 llvm::Type *PtrDiffTy =
Anders Carlsson8a64c1c2010-04-24 21:23:59 +0000186 Types.ConvertType(getContext().getPointerDiffType());
Justin Bogner1cd11f12015-05-20 15:53:59 +0000187
Ken Dycka1a4ae32011-03-22 00:53:26 +0000188 return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
Anders Carlsson9150a2a2009-09-29 03:13:20 +0000189}
190
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000191/// Gets the address of a direct base class within a complete object.
John McCall6ce74722010-02-16 04:15:37 +0000192/// This should only be used for (1) non-virtual bases or (2) virtual bases
193/// when the type is known to be complete (e.g. in complete destructors).
194///
195/// The object pointed to by 'This' is assumed to be non-null.
John McCall7f416cc2015-09-08 08:05:57 +0000196Address
197CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(Address This,
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000198 const CXXRecordDecl *Derived,
199 const CXXRecordDecl *Base,
200 bool BaseIsVirtual) {
John McCall6ce74722010-02-16 04:15:37 +0000201 // 'this' must be a pointer (in some address space) to Derived.
John McCall7f416cc2015-09-08 08:05:57 +0000202 assert(This.getElementType() == ConvertType(Derived));
John McCall6ce74722010-02-16 04:15:37 +0000203
204 // Compute the offset of the virtual base.
Ken Dyck6aa767c2011-03-22 01:21:15 +0000205 CharUnits Offset;
John McCall6ce74722010-02-16 04:15:37 +0000206 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000207 if (BaseIsVirtual)
Ken Dyck6aa767c2011-03-22 01:21:15 +0000208 Offset = Layout.getVBaseClassOffset(Base);
John McCall6ce74722010-02-16 04:15:37 +0000209 else
Ken Dyck6aa767c2011-03-22 01:21:15 +0000210 Offset = Layout.getBaseClassOffset(Base);
John McCall6ce74722010-02-16 04:15:37 +0000211
212 // Shift and cast down to the base type.
213 // TODO: for complete types, this should be possible with a GEP.
John McCall7f416cc2015-09-08 08:05:57 +0000214 Address V = This;
215 if (!Offset.isZero()) {
216 V = Builder.CreateElementBitCast(V, Int8Ty);
217 V = Builder.CreateConstInBoundsByteGEP(V, Offset);
John McCall6ce74722010-02-16 04:15:37 +0000218 }
John McCall7f416cc2015-09-08 08:05:57 +0000219 V = Builder.CreateElementBitCast(V, ConvertType(Base));
John McCall6ce74722010-02-16 04:15:37 +0000220
221 return V;
Anders Carlssone87fae92010-03-28 19:40:00 +0000222}
John McCall6ce74722010-02-16 04:15:37 +0000223
John McCall7f416cc2015-09-08 08:05:57 +0000224static Address
225ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, Address addr,
John McCall13a39c62012-08-01 05:04:58 +0000226 CharUnits nonVirtualOffset,
John McCall7f416cc2015-09-08 08:05:57 +0000227 llvm::Value *virtualOffset,
228 const CXXRecordDecl *derivedClass,
229 const CXXRecordDecl *nearestVBase) {
John McCall13a39c62012-08-01 05:04:58 +0000230 // Assert that we have something to do.
Craig Topper8a13c412014-05-21 05:09:00 +0000231 assert(!nonVirtualOffset.isZero() || virtualOffset != nullptr);
John McCall13a39c62012-08-01 05:04:58 +0000232
233 // Compute the offset from the static and dynamic components.
234 llvm::Value *baseOffset;
235 if (!nonVirtualOffset.isZero()) {
236 baseOffset = llvm::ConstantInt::get(CGF.PtrDiffTy,
237 nonVirtualOffset.getQuantity());
238 if (virtualOffset) {
239 baseOffset = CGF.Builder.CreateAdd(virtualOffset, baseOffset);
240 }
241 } else {
242 baseOffset = virtualOffset;
243 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000244
Anders Carlsson53cebd12010-04-20 16:03:35 +0000245 // Apply the base offset.
John McCall7f416cc2015-09-08 08:05:57 +0000246 llvm::Value *ptr = addr.getPointer();
John McCall13a39c62012-08-01 05:04:58 +0000247 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
248 ptr = CGF.Builder.CreateInBoundsGEP(ptr, baseOffset, "add.ptr");
John McCall7f416cc2015-09-08 08:05:57 +0000249
250 // If we have a virtual component, the alignment of the result will
251 // be relative only to the known alignment of that vbase.
252 CharUnits alignment;
253 if (virtualOffset) {
254 assert(nearestVBase && "virtual offset without vbase?");
255 alignment = CGF.CGM.getVBaseAlignment(addr.getAlignment(),
256 derivedClass, nearestVBase);
257 } else {
258 alignment = addr.getAlignment();
259 }
260 alignment = alignment.alignmentAtOffset(nonVirtualOffset);
261
262 return Address(ptr, alignment);
Anders Carlsson53cebd12010-04-20 16:03:35 +0000263}
264
John McCall7f416cc2015-09-08 08:05:57 +0000265Address CodeGenFunction::GetAddressOfBaseClass(
266 Address Value, const CXXRecordDecl *Derived,
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000267 CastExpr::path_const_iterator PathBegin,
268 CastExpr::path_const_iterator PathEnd, bool NullCheckValue,
269 SourceLocation Loc) {
John McCallcf142162010-08-07 06:22:56 +0000270 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssond829a022010-04-24 21:06:20 +0000271
John McCallcf142162010-08-07 06:22:56 +0000272 CastExpr::path_const_iterator Start = PathBegin;
Craig Topper8a13c412014-05-21 05:09:00 +0000273 const CXXRecordDecl *VBase = nullptr;
274
John McCall13a39c62012-08-01 05:04:58 +0000275 // Sema has done some convenient canonicalization here: if the
276 // access path involved any virtual steps, the conversion path will
277 // *start* with a step down to the correct virtual base subobject,
278 // and hence will not require any further steps.
Anders Carlssond829a022010-04-24 21:06:20 +0000279 if ((*Start)->isVirtual()) {
Justin Bogner1cd11f12015-05-20 15:53:59 +0000280 VBase =
Anders Carlssond829a022010-04-24 21:06:20 +0000281 cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
282 ++Start;
283 }
John McCall13a39c62012-08-01 05:04:58 +0000284
285 // Compute the static offset of the ultimate destination within its
286 // allocating subobject (the virtual base, if there is one, or else
287 // the "complete" object that we see).
David Majnemerc1709d32015-06-23 07:31:11 +0000288 CharUnits NonVirtualOffset = CGM.computeNonVirtualBaseClassOffset(
289 VBase ? VBase : Derived, Start, PathEnd);
Anders Carlssond829a022010-04-24 21:06:20 +0000290
John McCall13a39c62012-08-01 05:04:58 +0000291 // If there's a virtual step, we can sometimes "devirtualize" it.
292 // For now, that's limited to when the derived type is final.
293 // TODO: "devirtualize" this for accesses to known-complete objects.
294 if (VBase && Derived->hasAttr<FinalAttr>()) {
295 const ASTRecordLayout &layout = getContext().getASTRecordLayout(Derived);
296 CharUnits vBaseOffset = layout.getVBaseClassOffset(VBase);
297 NonVirtualOffset += vBaseOffset;
Craig Topper8a13c412014-05-21 05:09:00 +0000298 VBase = nullptr; // we no longer have a virtual step
John McCall13a39c62012-08-01 05:04:58 +0000299 }
300
Anders Carlssond829a022010-04-24 21:06:20 +0000301 // Get the base pointer type.
Justin Bogner1cd11f12015-05-20 15:53:59 +0000302 llvm::Type *BasePtrTy =
John McCallcf142162010-08-07 06:22:56 +0000303 ConvertType((PathEnd[-1])->getType())->getPointerTo();
John McCall13a39c62012-08-01 05:04:58 +0000304
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000305 QualType DerivedTy = getContext().getRecordType(Derived);
John McCall7f416cc2015-09-08 08:05:57 +0000306 CharUnits DerivedAlign = CGM.getClassPointerAlignment(Derived);
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000307
John McCall13a39c62012-08-01 05:04:58 +0000308 // If the static offset is zero and we don't have a virtual step,
309 // just do a bitcast; null checks are unnecessary.
Ken Dycka1a4ae32011-03-22 00:53:26 +0000310 if (NonVirtualOffset.isZero() && !VBase) {
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000311 if (sanitizePerformTypeCheck()) {
Vedant Kumar18348ea2017-02-17 23:22:55 +0000312 SanitizerSet SkippedChecks;
313 SkippedChecks.set(SanitizerKind::Null, !NullCheckValue);
John McCall7f416cc2015-09-08 08:05:57 +0000314 EmitTypeCheck(TCK_Upcast, Loc, Value.getPointer(),
Vedant Kumar18348ea2017-02-17 23:22:55 +0000315 DerivedTy, DerivedAlign, SkippedChecks);
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000316 }
Anders Carlssond829a022010-04-24 21:06:20 +0000317 return Builder.CreateBitCast(Value, BasePtrTy);
Craig Topper8a13c412014-05-21 05:09:00 +0000318 }
John McCall13a39c62012-08-01 05:04:58 +0000319
Craig Topper8a13c412014-05-21 05:09:00 +0000320 llvm::BasicBlock *origBB = nullptr;
321 llvm::BasicBlock *endBB = nullptr;
322
John McCall13a39c62012-08-01 05:04:58 +0000323 // Skip over the offset (and the vtable load) if we're supposed to
324 // null-check the pointer.
Anders Carlssond829a022010-04-24 21:06:20 +0000325 if (NullCheckValue) {
John McCall13a39c62012-08-01 05:04:58 +0000326 origBB = Builder.GetInsertBlock();
327 llvm::BasicBlock *notNullBB = createBasicBlock("cast.notnull");
328 endBB = createBasicBlock("cast.end");
Justin Bogner1cd11f12015-05-20 15:53:59 +0000329
John McCall7f416cc2015-09-08 08:05:57 +0000330 llvm::Value *isNull = Builder.CreateIsNull(Value.getPointer());
John McCall13a39c62012-08-01 05:04:58 +0000331 Builder.CreateCondBr(isNull, endBB, notNullBB);
332 EmitBlock(notNullBB);
Anders Carlssond829a022010-04-24 21:06:20 +0000333 }
334
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000335 if (sanitizePerformTypeCheck()) {
Vedant Kumar18348ea2017-02-17 23:22:55 +0000336 SanitizerSet SkippedChecks;
337 SkippedChecks.set(SanitizerKind::Null, true);
John McCall7f416cc2015-09-08 08:05:57 +0000338 EmitTypeCheck(VBase ? TCK_UpcastToVirtualBase : TCK_Upcast, Loc,
Vedant Kumar18348ea2017-02-17 23:22:55 +0000339 Value.getPointer(), DerivedTy, DerivedAlign, SkippedChecks);
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000340 }
341
John McCall13a39c62012-08-01 05:04:58 +0000342 // Compute the virtual offset.
Craig Topper8a13c412014-05-21 05:09:00 +0000343 llvm::Value *VirtualOffset = nullptr;
Anders Carlssona376b532011-01-29 03:18:56 +0000344 if (VBase) {
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000345 VirtualOffset =
346 CGM.getCXXABI().GetVirtualBaseClassOffset(*this, Value, Derived, VBase);
Anders Carlssona376b532011-01-29 03:18:56 +0000347 }
Anders Carlssond829a022010-04-24 21:06:20 +0000348
John McCall13a39c62012-08-01 05:04:58 +0000349 // Apply both offsets.
John McCall7f416cc2015-09-08 08:05:57 +0000350 Value = ApplyNonVirtualAndVirtualOffset(*this, Value, NonVirtualOffset,
351 VirtualOffset, Derived, VBase);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000352
John McCall13a39c62012-08-01 05:04:58 +0000353 // Cast to the destination type.
Anders Carlssond829a022010-04-24 21:06:20 +0000354 Value = Builder.CreateBitCast(Value, BasePtrTy);
John McCall13a39c62012-08-01 05:04:58 +0000355
356 // Build a phi if we needed a null check.
Anders Carlssond829a022010-04-24 21:06:20 +0000357 if (NullCheckValue) {
John McCall13a39c62012-08-01 05:04:58 +0000358 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
359 Builder.CreateBr(endBB);
360 EmitBlock(endBB);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000361
John McCall13a39c62012-08-01 05:04:58 +0000362 llvm::PHINode *PHI = Builder.CreatePHI(BasePtrTy, 2, "cast.result");
John McCall7f416cc2015-09-08 08:05:57 +0000363 PHI->addIncoming(Value.getPointer(), notNullBB);
John McCall13a39c62012-08-01 05:04:58 +0000364 PHI->addIncoming(llvm::Constant::getNullValue(BasePtrTy), origBB);
John McCall7f416cc2015-09-08 08:05:57 +0000365 Value = Address(PHI, Value.getAlignment());
Anders Carlssond829a022010-04-24 21:06:20 +0000366 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000367
Anders Carlssond829a022010-04-24 21:06:20 +0000368 return Value;
369}
370
John McCall7f416cc2015-09-08 08:05:57 +0000371Address
372CodeGenFunction::GetAddressOfDerivedClass(Address BaseAddr,
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000373 const CXXRecordDecl *Derived,
John McCallcf142162010-08-07 06:22:56 +0000374 CastExpr::path_const_iterator PathBegin,
375 CastExpr::path_const_iterator PathEnd,
Anders Carlsson8c793172009-11-23 17:57:54 +0000376 bool NullCheckValue) {
John McCallcf142162010-08-07 06:22:56 +0000377 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlsson8a64c1c2010-04-24 21:23:59 +0000378
Anders Carlsson8c793172009-11-23 17:57:54 +0000379 QualType DerivedTy =
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000380 getContext().getCanonicalType(getContext().getTagDeclType(Derived));
Chris Lattner2192fe52011-07-18 04:24:23 +0000381 llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
Richard Smith2c5868c2013-02-13 21:18:23 +0000382
Anders Carlsson600f7372010-01-31 01:43:37 +0000383 llvm::Value *NonVirtualOffset =
John McCallcf142162010-08-07 06:22:56 +0000384 CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000385
Anders Carlsson600f7372010-01-31 01:43:37 +0000386 if (!NonVirtualOffset) {
387 // No offset, we can just cast back.
John McCall7f416cc2015-09-08 08:05:57 +0000388 return Builder.CreateBitCast(BaseAddr, DerivedPtrTy);
Anders Carlsson600f7372010-01-31 01:43:37 +0000389 }
Craig Topper8a13c412014-05-21 05:09:00 +0000390
391 llvm::BasicBlock *CastNull = nullptr;
392 llvm::BasicBlock *CastNotNull = nullptr;
393 llvm::BasicBlock *CastEnd = nullptr;
394
Anders Carlsson8c793172009-11-23 17:57:54 +0000395 if (NullCheckValue) {
396 CastNull = createBasicBlock("cast.null");
397 CastNotNull = createBasicBlock("cast.notnull");
398 CastEnd = createBasicBlock("cast.end");
Justin Bogner1cd11f12015-05-20 15:53:59 +0000399
John McCall7f416cc2015-09-08 08:05:57 +0000400 llvm::Value *IsNull = Builder.CreateIsNull(BaseAddr.getPointer());
Anders Carlsson8c793172009-11-23 17:57:54 +0000401 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
402 EmitBlock(CastNotNull);
403 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000404
Anders Carlsson600f7372010-01-31 01:43:37 +0000405 // Apply the offset.
John McCall7f416cc2015-09-08 08:05:57 +0000406 llvm::Value *Value = Builder.CreateBitCast(BaseAddr.getPointer(), Int8PtrTy);
Eli Friedman87549262012-02-28 22:07:56 +0000407 Value = Builder.CreateGEP(Value, Builder.CreateNeg(NonVirtualOffset),
408 "sub.ptr");
Anders Carlsson600f7372010-01-31 01:43:37 +0000409
410 // Just cast.
411 Value = Builder.CreateBitCast(Value, DerivedPtrTy);
Anders Carlsson8c793172009-11-23 17:57:54 +0000412
John McCall7f416cc2015-09-08 08:05:57 +0000413 // Produce a PHI if we had a null-check.
Anders Carlsson8c793172009-11-23 17:57:54 +0000414 if (NullCheckValue) {
415 Builder.CreateBr(CastEnd);
416 EmitBlock(CastNull);
417 Builder.CreateBr(CastEnd);
418 EmitBlock(CastEnd);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000419
Jay Foad20c0f022011-03-30 11:28:58 +0000420 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
Anders Carlsson8c793172009-11-23 17:57:54 +0000421 PHI->addIncoming(Value, CastNotNull);
John McCall7f416cc2015-09-08 08:05:57 +0000422 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
Anders Carlsson8c793172009-11-23 17:57:54 +0000423 Value = PHI;
424 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000425
John McCall7f416cc2015-09-08 08:05:57 +0000426 return Address(Value, CGM.getClassPointerAlignment(Derived));
Anders Carlsson9a57c5a2009-09-12 04:27:24 +0000427}
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000428
429llvm::Value *CodeGenFunction::GetVTTParameter(GlobalDecl GD,
430 bool ForVirtualBase,
431 bool Delegating) {
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000432 if (!CGM.getCXXABI().NeedsVTTParameter(GD)) {
Anders Carlssone36a6b32010-01-02 01:01:18 +0000433 // This constructor/destructor does not need a VTT parameter.
Craig Topper8a13c412014-05-21 05:09:00 +0000434 return nullptr;
Anders Carlssone36a6b32010-01-02 01:01:18 +0000435 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000436
John McCalldec348f72013-05-03 07:33:41 +0000437 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CurCodeDecl)->getParent();
Anders Carlssone36a6b32010-01-02 01:01:18 +0000438 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
John McCall5c60a6f2010-02-18 19:59:28 +0000439
Anders Carlssone36a6b32010-01-02 01:01:18 +0000440 llvm::Value *VTT;
441
John McCall5c60a6f2010-02-18 19:59:28 +0000442 uint64_t SubVTTIndex;
443
Douglas Gregor61535002013-01-31 05:50:40 +0000444 if (Delegating) {
445 // If this is a delegating constructor call, just load the VTT.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000446 return LoadCXXVTT();
Douglas Gregor61535002013-01-31 05:50:40 +0000447 } else if (RD == Base) {
448 // If the record matches the base, this is the complete ctor/dtor
449 // variant calling the base variant in a class with virtual bases.
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000450 assert(!CGM.getCXXABI().NeedsVTTParameter(CurGD) &&
John McCall5c60a6f2010-02-18 19:59:28 +0000451 "doing no-op VTT offset in base dtor/ctor?");
Anders Carlsson4d205ba2010-05-02 23:33:10 +0000452 assert(!ForVirtualBase && "Can't have same class as virtual base!");
John McCall5c60a6f2010-02-18 19:59:28 +0000453 SubVTTIndex = 0;
454 } else {
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000455 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000456 CharUnits BaseOffset = ForVirtualBase ?
457 Layout.getVBaseClassOffset(Base) :
Ken Dyck16ffcac2011-03-24 01:21:01 +0000458 Layout.getBaseClassOffset(Base);
Anders Carlsson859b3062010-05-02 23:53:25 +0000459
Justin Bogner1cd11f12015-05-20 15:53:59 +0000460 SubVTTIndex =
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000461 CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
John McCall5c60a6f2010-02-18 19:59:28 +0000462 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
463 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000464
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000465 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
Anders Carlssone36a6b32010-01-02 01:01:18 +0000466 // A VTT parameter was passed to the constructor, use it.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000467 VTT = LoadCXXVTT();
468 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
Anders Carlssone36a6b32010-01-02 01:01:18 +0000469 } else {
470 // We're the complete constructor, so get the VTT by name.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000471 VTT = CGM.getVTables().GetAddrOfVTT(RD);
472 VTT = Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
Anders Carlssone36a6b32010-01-02 01:01:18 +0000473 }
474
475 return VTT;
476}
477
John McCall1d987562010-07-21 01:23:41 +0000478namespace {
John McCallf99a6312010-07-21 05:30:47 +0000479 /// Call the destructor for a direct base class.
David Blaikie7e70d682015-08-18 22:40:54 +0000480 struct CallBaseDtor final : EHScopeStack::Cleanup {
John McCallf99a6312010-07-21 05:30:47 +0000481 const CXXRecordDecl *BaseClass;
482 bool BaseIsVirtual;
483 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
484 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
John McCall1d987562010-07-21 01:23:41 +0000485
Craig Topper4f12f102014-03-12 06:41:41 +0000486 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallf99a6312010-07-21 05:30:47 +0000487 const CXXRecordDecl *DerivedClass =
488 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
489
490 const CXXDestructorDecl *D = BaseClass->getDestructor();
John McCall7f416cc2015-09-08 08:05:57 +0000491 Address Addr =
492 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThisAddress(),
John McCallf99a6312010-07-21 05:30:47 +0000493 DerivedClass, BaseClass,
494 BaseIsVirtual);
Douglas Gregor61535002013-01-31 05:50:40 +0000495 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual,
496 /*Delegating=*/false, Addr);
John McCall1d987562010-07-21 01:23:41 +0000497 }
498 };
John McCall769250e2010-09-17 02:31:44 +0000499
500 /// A visitor which checks whether an initializer uses 'this' in a
501 /// way which requires the vtable to be properly set.
Scott Douglass503fc392015-06-10 13:53:15 +0000502 struct DynamicThisUseChecker : ConstEvaluatedExprVisitor<DynamicThisUseChecker> {
503 typedef ConstEvaluatedExprVisitor<DynamicThisUseChecker> super;
John McCall769250e2010-09-17 02:31:44 +0000504
505 bool UsesThis;
506
Scott Douglass503fc392015-06-10 13:53:15 +0000507 DynamicThisUseChecker(const ASTContext &C) : super(C), UsesThis(false) {}
John McCall769250e2010-09-17 02:31:44 +0000508
509 // Black-list all explicit and implicit references to 'this'.
510 //
511 // Do we need to worry about external references to 'this' derived
512 // from arbitrary code? If so, then anything which runs arbitrary
513 // external code might potentially access the vtable.
Scott Douglass503fc392015-06-10 13:53:15 +0000514 void VisitCXXThisExpr(const CXXThisExpr *E) { UsesThis = true; }
John McCall769250e2010-09-17 02:31:44 +0000515 };
Hans Wennborgdcfba332015-10-06 23:40:43 +0000516} // end anonymous namespace
John McCall769250e2010-09-17 02:31:44 +0000517
518static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
519 DynamicThisUseChecker Checker(C);
Scott Douglass503fc392015-06-10 13:53:15 +0000520 Checker.Visit(Init);
John McCall769250e2010-09-17 02:31:44 +0000521 return Checker.UsesThis;
John McCall1d987562010-07-21 01:23:41 +0000522}
523
Justin Bogner1cd11f12015-05-20 15:53:59 +0000524static void EmitBaseInitializer(CodeGenFunction &CGF,
Anders Carlssonfb404882009-12-24 22:46:43 +0000525 const CXXRecordDecl *ClassDecl,
Alexis Hunt1d792652011-01-08 20:30:50 +0000526 CXXCtorInitializer *BaseInit,
Anders Carlssonfb404882009-12-24 22:46:43 +0000527 CXXCtorType CtorType) {
528 assert(BaseInit->isBaseInitializer() &&
529 "Must have base initializer!");
530
John McCall7f416cc2015-09-08 08:05:57 +0000531 Address ThisPtr = CGF.LoadCXXThisAddress();
Justin Bogner1cd11f12015-05-20 15:53:59 +0000532
Anders Carlssonfb404882009-12-24 22:46:43 +0000533 const Type *BaseType = BaseInit->getBaseClass();
534 CXXRecordDecl *BaseClassDecl =
535 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
536
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +0000537 bool isBaseVirtual = BaseInit->isBaseVirtual();
Anders Carlssonfb404882009-12-24 22:46:43 +0000538
539 // The base constructor doesn't construct virtual bases.
540 if (CtorType == Ctor_Base && isBaseVirtual)
541 return;
542
John McCall769250e2010-09-17 02:31:44 +0000543 // If the initializer for the base (other than the constructor
544 // itself) accesses 'this' in any way, we need to initialize the
545 // vtables.
546 if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
547 CGF.InitializeVTablePointers(ClassDecl);
548
John McCall6ce74722010-02-16 04:15:37 +0000549 // We can pretend to be a complete class because it only matters for
550 // virtual bases, and we only do virtual bases for complete ctors.
John McCall7f416cc2015-09-08 08:05:57 +0000551 Address V =
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000552 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
John McCallf99a6312010-07-21 05:30:47 +0000553 BaseClassDecl,
554 isBaseVirtual);
John McCall8d6fc952011-08-25 20:40:09 +0000555 AggValueSlot AggSlot =
John McCall7f416cc2015-09-08 08:05:57 +0000556 AggValueSlot::forAddr(V, Qualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +0000557 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +0000558 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000559 AggValueSlot::IsNotAliased);
John McCall7a626f62010-09-15 10:14:12 +0000560
561 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000562
563 if (CGF.CGM.getLangOpts().Exceptions &&
Anders Carlsson08ce5ed2011-02-20 00:20:27 +0000564 !BaseClassDecl->hasTrivialDestructor())
John McCallcda666c2010-07-21 07:22:38 +0000565 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
566 isBaseVirtual);
Anders Carlssonfb404882009-12-24 22:46:43 +0000567}
568
Richard Smith419bd092015-04-29 19:26:57 +0000569static bool isMemcpyEquivalentSpecialMember(const CXXMethodDecl *D) {
570 auto *CD = dyn_cast<CXXConstructorDecl>(D);
571 if (!(CD && CD->isCopyOrMoveConstructor()) &&
572 !D->isCopyAssignmentOperator() && !D->isMoveAssignmentOperator())
573 return false;
574
575 // We can emit a memcpy for a trivial copy or move constructor/assignment.
576 if (D->isTrivial() && !D->getParent()->mayInsertExtraPadding())
577 return true;
578
579 // We *must* emit a memcpy for a defaulted union copy or move op.
580 if (D->getParent()->isUnion() && D->isDefaulted())
581 return true;
582
583 return false;
584}
585
Alexey Bataev152c71f2015-07-14 07:55:48 +0000586static void EmitLValueForAnyFieldInitialization(CodeGenFunction &CGF,
587 CXXCtorInitializer *MemberInit,
588 LValue &LHS) {
589 FieldDecl *Field = MemberInit->getAnyMember();
590 if (MemberInit->isIndirectMemberInitializer()) {
591 // If we are initializing an anonymous union field, drill down to the field.
592 IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember();
593 for (const auto *I : IndirectField->chain())
594 LHS = CGF.EmitLValueForFieldInitialization(LHS, cast<FieldDecl>(I));
595 } else {
596 LHS = CGF.EmitLValueForFieldInitialization(LHS, Field);
597 }
598}
599
Anders Carlssonfb404882009-12-24 22:46:43 +0000600static void EmitMemberInitializer(CodeGenFunction &CGF,
601 const CXXRecordDecl *ClassDecl,
Alexis Hunt1d792652011-01-08 20:30:50 +0000602 CXXCtorInitializer *MemberInit,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000603 const CXXConstructorDecl *Constructor,
604 FunctionArgList &Args) {
David Blaikiea81d4102015-01-18 00:12:58 +0000605 ApplyDebugLocation Loc(CGF, MemberInit->getSourceLocation());
Francois Pichetd583da02010-12-04 09:14:42 +0000606 assert(MemberInit->isAnyMemberInitializer() &&
Anders Carlssonfb404882009-12-24 22:46:43 +0000607 "Must have member initializer!");
Richard Smith938f40b2011-06-11 17:19:42 +0000608 assert(MemberInit->getInit() && "Must have initializer!");
Justin Bogner1cd11f12015-05-20 15:53:59 +0000609
Anders Carlssonfb404882009-12-24 22:46:43 +0000610 // non-static data member initializers.
Francois Pichetd583da02010-12-04 09:14:42 +0000611 FieldDecl *Field = MemberInit->getAnyMember();
Eli Friedman6ae63022012-02-14 02:15:49 +0000612 QualType FieldType = Field->getType();
Anders Carlssonfb404882009-12-24 22:46:43 +0000613
614 llvm::Value *ThisPtr = CGF.LoadCXXThis();
Eli Friedman7f1ff602012-04-16 03:54:45 +0000615 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
Eli Friedmanf6d21842012-08-08 03:51:37 +0000616 LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
Eli Friedman7f1ff602012-04-16 03:54:45 +0000617
Alexey Bataev152c71f2015-07-14 07:55:48 +0000618 EmitLValueForAnyFieldInitialization(CGF, MemberInit, LHS);
Anders Carlssonfb404882009-12-24 22:46:43 +0000619
Eli Friedman6ae63022012-02-14 02:15:49 +0000620 // Special case: if we are in a copy or move constructor, and we are copying
621 // an array of PODs or classes with trivial copy constructors, ignore the
622 // AST and perform the copy we know is equivalent.
623 // FIXME: This is hacky at best... if we had a bit more explicit information
624 // in the AST, we could generalize it more easily.
625 const ConstantArrayType *Array
626 = CGF.getContext().getAsConstantArrayType(FieldType);
Jordan Rose54533f72013-08-07 16:16:48 +0000627 if (Array && Constructor->isDefaulted() &&
Eli Friedman6ae63022012-02-14 02:15:49 +0000628 Constructor->isCopyOrMoveConstructor()) {
629 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
Richard Smith993f25a2012-11-07 23:56:21 +0000630 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
Eli Friedman6ae63022012-02-14 02:15:49 +0000631 if (BaseElementTy.isPODType(CGF.getContext()) ||
Richard Smith419bd092015-04-29 19:26:57 +0000632 (CE && isMemcpyEquivalentSpecialMember(CE->getConstructor()))) {
David Majnemer1573d732014-10-15 04:54:54 +0000633 unsigned SrcArgIndex =
634 CGF.CGM.getCXXABI().getSrcArgforCopyCtor(Constructor, Args);
Eli Friedman6ae63022012-02-14 02:15:49 +0000635 llvm::Value *SrcPtr
636 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
Eli Friedman7f1ff602012-04-16 03:54:45 +0000637 LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
638 LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000639
Eli Friedman6ae63022012-02-14 02:15:49 +0000640 // Copy the aggregate.
641 CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000642 LHS.isVolatileQualified());
Alexey Bataev5d49b832015-07-08 07:31:02 +0000643 // Ensure that we destroy the objects if an exception is thrown later in
644 // the constructor.
645 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
646 if (CGF.needsEHCleanup(dtorKind))
647 CGF.pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
Eli Friedman6ae63022012-02-14 02:15:49 +0000648 return;
649 }
650 }
651
Richard Smith30e304e2016-12-14 00:03:17 +0000652 CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit());
Eli Friedman6ae63022012-02-14 02:15:49 +0000653}
654
John McCall7f416cc2015-09-08 08:05:57 +0000655void CodeGenFunction::EmitInitializerForField(FieldDecl *Field, LValue LHS,
Richard Smith30e304e2016-12-14 00:03:17 +0000656 Expr *Init) {
Eli Friedman6ae63022012-02-14 02:15:49 +0000657 QualType FieldType = Field->getType();
John McCall47fb9502013-03-07 21:37:08 +0000658 switch (getEvaluationKind(FieldType)) {
659 case TEK_Scalar:
John McCall31168b02011-06-15 23:02:42 +0000660 if (LHS.isSimple()) {
David Blaikie66e41972015-01-14 07:38:27 +0000661 EmitExprAsInit(Init, Field, LHS, false);
John McCall31168b02011-06-15 23:02:42 +0000662 } else {
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000663 RValue RHS = RValue::get(EmitScalarExpr(Init));
664 EmitStoreThroughLValue(RHS, LHS);
John McCall31168b02011-06-15 23:02:42 +0000665 }
John McCall47fb9502013-03-07 21:37:08 +0000666 break;
667 case TEK_Complex:
David Blaikie66e41972015-01-14 07:38:27 +0000668 EmitComplexExprIntoLValue(Init, LHS, /*isInit*/ true);
John McCall47fb9502013-03-07 21:37:08 +0000669 break;
670 case TEK_Aggregate: {
Richard Smith30e304e2016-12-14 00:03:17 +0000671 AggValueSlot Slot =
672 AggValueSlot::forLValue(LHS,
673 AggValueSlot::IsDestructed,
674 AggValueSlot::DoesNotNeedGCBarriers,
675 AggValueSlot::IsNotAliased);
676 EmitAggExpr(Init, Slot);
677 break;
Anders Carlssonfb404882009-12-24 22:46:43 +0000678 }
John McCall47fb9502013-03-07 21:37:08 +0000679 }
John McCall12cc42a2013-02-01 05:11:40 +0000680
681 // Ensure that we destroy this object if an exception is thrown
682 // later in the constructor.
683 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
684 if (needsEHCleanup(dtorKind))
685 pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
Anders Carlssonfb404882009-12-24 22:46:43 +0000686}
687
John McCallf8ff7b92010-02-23 00:48:20 +0000688/// Checks whether the given constructor is a valid subject for the
689/// complete-to-base constructor delegation optimization, i.e.
690/// emitting the complete constructor as a simple call to the base
691/// constructor.
692static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
693
694 // Currently we disable the optimization for classes with virtual
695 // bases because (1) the addresses of parameter variables need to be
696 // consistent across all initializers but (2) the delegate function
697 // call necessarily creates a second copy of the parameter variable.
698 //
699 // The limiting example (purely theoretical AFAIK):
700 // struct A { A(int &c) { c++; } };
701 // struct B : virtual A {
702 // B(int count) : A(count) { printf("%d\n", count); }
703 // };
704 // ...although even this example could in principle be emitted as a
705 // delegation since the address of the parameter doesn't escape.
706 if (Ctor->getParent()->getNumVBases()) {
707 // TODO: white-list trivial vbase initializers. This case wouldn't
708 // be subject to the restrictions below.
709
710 // TODO: white-list cases where:
711 // - there are no non-reference parameters to the constructor
712 // - the initializers don't access any non-reference parameters
713 // - the initializers don't take the address of non-reference
714 // parameters
715 // - etc.
716 // If we ever add any of the above cases, remember that:
717 // - function-try-blocks will always blacklist this optimization
718 // - we need to perform the constructor prologue and cleanup in
719 // EmitConstructorBody.
720
721 return false;
722 }
723
724 // We also disable the optimization for variadic functions because
725 // it's impossible to "re-pass" varargs.
726 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
727 return false;
728
Alexis Hunt61bc1732011-05-01 07:04:31 +0000729 // FIXME: Decide if we can do a delegation of a delegating constructor.
730 if (Ctor->isDelegatingConstructor())
731 return false;
732
John McCallf8ff7b92010-02-23 00:48:20 +0000733 return true;
734}
735
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000736// Emit code in ctor (Prologue==true) or dtor (Prologue==false)
737// to poison the extra field paddings inserted under
738// -fsanitize-address-field-padding=1|2.
739void CodeGenFunction::EmitAsanPrologueOrEpilogue(bool Prologue) {
740 ASTContext &Context = getContext();
741 const CXXRecordDecl *ClassDecl =
742 Prologue ? cast<CXXConstructorDecl>(CurGD.getDecl())->getParent()
743 : cast<CXXDestructorDecl>(CurGD.getDecl())->getParent();
744 if (!ClassDecl->mayInsertExtraPadding()) return;
745
746 struct SizeAndOffset {
747 uint64_t Size;
748 uint64_t Offset;
749 };
750
751 unsigned PtrSize = CGM.getDataLayout().getPointerSizeInBits();
752 const ASTRecordLayout &Info = Context.getASTRecordLayout(ClassDecl);
753
754 // Populate sizes and offsets of fields.
755 SmallVector<SizeAndOffset, 16> SSV(Info.getFieldCount());
756 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i)
757 SSV[i].Offset =
758 Context.toCharUnitsFromBits(Info.getFieldOffset(i)).getQuantity();
759
760 size_t NumFields = 0;
761 for (const auto *Field : ClassDecl->fields()) {
762 const FieldDecl *D = Field;
763 std::pair<CharUnits, CharUnits> FieldInfo =
764 Context.getTypeInfoInChars(D->getType());
765 CharUnits FieldSize = FieldInfo.first;
766 assert(NumFields < SSV.size());
767 SSV[NumFields].Size = D->isBitField() ? 0 : FieldSize.getQuantity();
768 NumFields++;
769 }
770 assert(NumFields == SSV.size());
771 if (SSV.size() <= 1) return;
772
773 // We will insert calls to __asan_* run-time functions.
774 // LLVM AddressSanitizer pass may decide to inline them later.
775 llvm::Type *Args[2] = {IntPtrTy, IntPtrTy};
776 llvm::FunctionType *FTy =
777 llvm::FunctionType::get(CGM.VoidTy, Args, false);
778 llvm::Constant *F = CGM.CreateRuntimeFunction(
779 FTy, Prologue ? "__asan_poison_intra_object_redzone"
780 : "__asan_unpoison_intra_object_redzone");
781
782 llvm::Value *ThisPtr = LoadCXXThis();
783 ThisPtr = Builder.CreatePtrToInt(ThisPtr, IntPtrTy);
Kostya Serebryany64449212014-10-17 21:02:13 +0000784 uint64_t TypeSize = Info.getNonVirtualSize().getQuantity();
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000785 // For each field check if it has sufficient padding,
786 // if so (un)poison it with a call.
787 for (size_t i = 0; i < SSV.size(); i++) {
788 uint64_t AsanAlignment = 8;
789 uint64_t NextField = i == SSV.size() - 1 ? TypeSize : SSV[i + 1].Offset;
790 uint64_t PoisonSize = NextField - SSV[i].Offset - SSV[i].Size;
791 uint64_t EndOffset = SSV[i].Offset + SSV[i].Size;
792 if (PoisonSize < AsanAlignment || !SSV[i].Size ||
793 (NextField % AsanAlignment) != 0)
794 continue;
David Blaikie43f9bb72015-05-18 22:14:03 +0000795 Builder.CreateCall(
796 F, {Builder.CreateAdd(ThisPtr, Builder.getIntN(PtrSize, EndOffset)),
797 Builder.getIntN(PtrSize, PoisonSize)});
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000798 }
799}
800
John McCallb81884d2010-02-19 09:25:03 +0000801/// EmitConstructorBody - Emits the body of the current constructor.
802void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000803 EmitAsanPrologueOrEpilogue(true);
John McCallb81884d2010-02-19 09:25:03 +0000804 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
805 CXXCtorType CtorType = CurGD.getCtorType();
806
Reid Kleckner340ad862014-01-13 22:57:31 +0000807 assert((CGM.getTarget().getCXXABI().hasConstructorVariants() ||
808 CtorType == Ctor_Complete) &&
809 "can only generate complete ctor for this ABI");
810
John McCallf8ff7b92010-02-23 00:48:20 +0000811 // Before we go any further, try the complete->base constructor
812 // delegation optimization.
Timur Iskhodzhanovf32a3772012-04-20 08:05:00 +0000813 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
John McCallc8e01702013-04-16 22:48:15 +0000814 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000815 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args, Ctor->getLocEnd());
John McCallf8ff7b92010-02-23 00:48:20 +0000816 return;
817 }
818
Hans Wennborgdcfba332015-10-06 23:40:43 +0000819 const FunctionDecl *Definition = nullptr;
Richard Smith46bb5812014-08-01 01:56:39 +0000820 Stmt *Body = Ctor->getBody(Definition);
821 assert(Definition == Ctor && "emitting wrong constructor body");
John McCallb81884d2010-02-19 09:25:03 +0000822
John McCallf8ff7b92010-02-23 00:48:20 +0000823 // Enter the function-try-block before the constructor prologue if
824 // applicable.
John McCallf8ff7b92010-02-23 00:48:20 +0000825 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallf8ff7b92010-02-23 00:48:20 +0000826 if (IsTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000827 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000828
Justin Bogner66242d62015-04-23 23:06:47 +0000829 incrementProfileCounter(Body);
Justin Bogner81c22c22014-01-23 02:54:27 +0000830
Richard Smithcc1b96d2013-06-12 22:31:48 +0000831 RunCleanupsScope RunCleanups(*this);
John McCallb81884d2010-02-19 09:25:03 +0000832
John McCall88313032012-03-30 04:25:03 +0000833 // TODO: in restricted cases, we can emit the vbase initializers of
834 // a complete ctor and then delegate to the base ctor.
835
John McCallf8ff7b92010-02-23 00:48:20 +0000836 // Emit the constructor prologue, i.e. the base and member
837 // initializers.
Douglas Gregor94f9a482010-05-05 05:51:00 +0000838 EmitCtorPrologue(Ctor, CtorType, Args);
John McCallb81884d2010-02-19 09:25:03 +0000839
840 // Emit the body of the statement.
John McCallf8ff7b92010-02-23 00:48:20 +0000841 if (IsTryBody)
John McCallb81884d2010-02-19 09:25:03 +0000842 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
843 else if (Body)
844 EmitStmt(Body);
John McCallb81884d2010-02-19 09:25:03 +0000845
846 // Emit any cleanup blocks associated with the member or base
847 // initializers, which includes (along the exceptional path) the
848 // destructors for those members and bases that were fully
849 // constructed.
Richard Smithcc1b96d2013-06-12 22:31:48 +0000850 RunCleanups.ForceCleanup();
John McCallb81884d2010-02-19 09:25:03 +0000851
John McCallf8ff7b92010-02-23 00:48:20 +0000852 if (IsTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000853 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000854}
855
Lang Hamesbf122742013-02-17 07:22:09 +0000856namespace {
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000857 /// RAII object to indicate that codegen is copying the value representation
858 /// instead of the object representation. Useful when copying a struct or
859 /// class which has uninitialized members and we're only performing
860 /// lvalue-to-rvalue conversion on the object but not its members.
861 class CopyingValueRepresentation {
862 public:
863 explicit CopyingValueRepresentation(CodeGenFunction &CGF)
Alexey Samsonov035462c2014-10-30 19:33:44 +0000864 : CGF(CGF), OldSanOpts(CGF.SanOpts) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000865 CGF.SanOpts.set(SanitizerKind::Bool, false);
866 CGF.SanOpts.set(SanitizerKind::Enum, false);
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000867 }
868 ~CopyingValueRepresentation() {
869 CGF.SanOpts = OldSanOpts;
870 }
871 private:
872 CodeGenFunction &CGF;
Alexey Samsonova0416102014-11-11 01:26:14 +0000873 SanitizerSet OldSanOpts;
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000874 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000875} // end anonymous namespace
Hans Wennborgdcfba332015-10-06 23:40:43 +0000876
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000877namespace {
Lang Hamesbf122742013-02-17 07:22:09 +0000878 class FieldMemcpyizer {
879 public:
880 FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl,
881 const VarDecl *SrcRec)
Justin Bogner1cd11f12015-05-20 15:53:59 +0000882 : CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec),
Lang Hamesbf122742013-02-17 07:22:09 +0000883 RecLayout(CGF.getContext().getASTRecordLayout(ClassDecl)),
Craig Topper8a13c412014-05-21 05:09:00 +0000884 FirstField(nullptr), LastField(nullptr), FirstFieldOffset(0),
885 LastFieldOffset(0), LastAddedFieldIndex(0) {}
Lang Hamesbf122742013-02-17 07:22:09 +0000886
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000887 bool isMemcpyableField(FieldDecl *F) const {
888 // Never memcpy fields when we are adding poisoned paddings.
Alexey Samsonova0416102014-11-11 01:26:14 +0000889 if (CGF.getContext().getLangOpts().SanitizeAddressFieldPadding)
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000890 return false;
Lang Hamesbf122742013-02-17 07:22:09 +0000891 Qualifiers Qual = F->getType().getQualifiers();
892 if (Qual.hasVolatile() || Qual.hasObjCLifetime())
893 return false;
894 return true;
895 }
896
897 void addMemcpyableField(FieldDecl *F) {
Craig Topper8a13c412014-05-21 05:09:00 +0000898 if (!FirstField)
Lang Hamesbf122742013-02-17 07:22:09 +0000899 addInitialField(F);
900 else
901 addNextField(F);
902 }
903
David Majnemera586eb22014-10-10 18:57:10 +0000904 CharUnits getMemcpySize(uint64_t FirstByteOffset) const {
Lang Hamesbf122742013-02-17 07:22:09 +0000905 unsigned LastFieldSize =
906 LastField->isBitField() ?
907 LastField->getBitWidthValue(CGF.getContext()) :
Justin Bogner1cd11f12015-05-20 15:53:59 +0000908 CGF.getContext().getTypeSize(LastField->getType());
Lang Hamesbf122742013-02-17 07:22:09 +0000909 uint64_t MemcpySizeBits =
David Majnemera586eb22014-10-10 18:57:10 +0000910 LastFieldOffset + LastFieldSize - FirstByteOffset +
Lang Hamesbf122742013-02-17 07:22:09 +0000911 CGF.getContext().getCharWidth() - 1;
912 CharUnits MemcpySize =
913 CGF.getContext().toCharUnitsFromBits(MemcpySizeBits);
914 return MemcpySize;
915 }
916
917 void emitMemcpy() {
918 // Give the subclass a chance to bail out if it feels the memcpy isn't
919 // worth it (e.g. Hasn't aggregated enough data).
Craig Topper8a13c412014-05-21 05:09:00 +0000920 if (!FirstField) {
Lang Hamesbf122742013-02-17 07:22:09 +0000921 return;
922 }
923
David Majnemera586eb22014-10-10 18:57:10 +0000924 uint64_t FirstByteOffset;
Lang Hamesbf122742013-02-17 07:22:09 +0000925 if (FirstField->isBitField()) {
926 const CGRecordLayout &RL =
927 CGF.getTypes().getCGRecordLayout(FirstField->getParent());
928 const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField);
David Majnemera586eb22014-10-10 18:57:10 +0000929 // FirstFieldOffset is not appropriate for bitfields,
Ulrich Weigand73263d72015-07-13 11:52:14 +0000930 // we need to use the storage offset instead.
Ulrich Weigand03ce2a12015-07-10 17:30:00 +0000931 FirstByteOffset = CGF.getContext().toBits(BFInfo.StorageOffset);
Lang Hames1694e0d2013-02-27 04:14:49 +0000932 } else {
David Majnemera586eb22014-10-10 18:57:10 +0000933 FirstByteOffset = FirstFieldOffset;
Lang Hames1694e0d2013-02-27 04:14:49 +0000934 }
Lang Hamesbf122742013-02-17 07:22:09 +0000935
David Majnemera586eb22014-10-10 18:57:10 +0000936 CharUnits MemcpySize = getMemcpySize(FirstByteOffset);
Lang Hamesbf122742013-02-17 07:22:09 +0000937 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
John McCall7f416cc2015-09-08 08:05:57 +0000938 Address ThisPtr = CGF.LoadCXXThisAddress();
939 LValue DestLV = CGF.MakeAddrLValue(ThisPtr, RecordTy);
Lang Hamesbf122742013-02-17 07:22:09 +0000940 LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField);
941 llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec));
942 LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
943 LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField);
944
John McCall7f416cc2015-09-08 08:05:57 +0000945 emitMemcpyIR(Dest.isBitField() ? Dest.getBitFieldAddress() : Dest.getAddress(),
946 Src.isBitField() ? Src.getBitFieldAddress() : Src.getAddress(),
947 MemcpySize);
Lang Hamesbf122742013-02-17 07:22:09 +0000948 reset();
949 }
950
951 void reset() {
Craig Topper8a13c412014-05-21 05:09:00 +0000952 FirstField = nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +0000953 }
954
955 protected:
956 CodeGenFunction &CGF;
957 const CXXRecordDecl *ClassDecl;
958
959 private:
John McCall7f416cc2015-09-08 08:05:57 +0000960 void emitMemcpyIR(Address DestPtr, Address SrcPtr, CharUnits Size) {
961 llvm::PointerType *DPT = DestPtr.getType();
Lang Hamesbf122742013-02-17 07:22:09 +0000962 llvm::Type *DBP =
963 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), DPT->getAddressSpace());
964 DestPtr = CGF.Builder.CreateBitCast(DestPtr, DBP);
965
John McCall7f416cc2015-09-08 08:05:57 +0000966 llvm::PointerType *SPT = SrcPtr.getType();
Lang Hamesbf122742013-02-17 07:22:09 +0000967 llvm::Type *SBP =
968 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), SPT->getAddressSpace());
969 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, SBP);
970
John McCall7f416cc2015-09-08 08:05:57 +0000971 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity());
Lang Hamesbf122742013-02-17 07:22:09 +0000972 }
973
974 void addInitialField(FieldDecl *F) {
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000975 FirstField = F;
976 LastField = F;
977 FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex());
978 LastFieldOffset = FirstFieldOffset;
979 LastAddedFieldIndex = F->getFieldIndex();
980 }
Lang Hamesbf122742013-02-17 07:22:09 +0000981
982 void addNextField(FieldDecl *F) {
John McCall6054d5a2013-05-07 05:20:46 +0000983 // For the most part, the following invariant will hold:
984 // F->getFieldIndex() == LastAddedFieldIndex + 1
985 // The one exception is that Sema won't add a copy-initializer for an
986 // unnamed bitfield, which will show up here as a gap in the sequence.
987 assert(F->getFieldIndex() >= LastAddedFieldIndex + 1 &&
988 "Cannot aggregate fields out of order.");
Lang Hamesbf122742013-02-17 07:22:09 +0000989 LastAddedFieldIndex = F->getFieldIndex();
990
991 // The 'first' and 'last' fields are chosen by offset, rather than field
992 // index. This allows the code to support bitfields, as well as regular
993 // fields.
994 uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex());
995 if (FOffset < FirstFieldOffset) {
996 FirstField = F;
997 FirstFieldOffset = FOffset;
998 } else if (FOffset > LastFieldOffset) {
999 LastField = F;
1000 LastFieldOffset = FOffset;
1001 }
1002 }
1003
1004 const VarDecl *SrcRec;
1005 const ASTRecordLayout &RecLayout;
1006 FieldDecl *FirstField;
1007 FieldDecl *LastField;
1008 uint64_t FirstFieldOffset, LastFieldOffset;
1009 unsigned LastAddedFieldIndex;
1010 };
1011
1012 class ConstructorMemcpyizer : public FieldMemcpyizer {
1013 private:
Lang Hamesbf122742013-02-17 07:22:09 +00001014 /// Get source argument for copy constructor. Returns null if not a copy
David Majnemer196ac332014-09-11 23:05:02 +00001015 /// constructor.
1016 static const VarDecl *getTrivialCopySource(CodeGenFunction &CGF,
1017 const CXXConstructorDecl *CD,
Lang Hamesbf122742013-02-17 07:22:09 +00001018 FunctionArgList &Args) {
Jordan Rose54533f72013-08-07 16:16:48 +00001019 if (CD->isCopyOrMoveConstructor() && CD->isDefaulted())
David Majnemer196ac332014-09-11 23:05:02 +00001020 return Args[CGF.CGM.getCXXABI().getSrcArgforCopyCtor(CD, Args)];
Craig Topper8a13c412014-05-21 05:09:00 +00001021 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001022 }
1023
1024 // Returns true if a CXXCtorInitializer represents a member initialization
1025 // that can be rolled into a memcpy.
1026 bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const {
1027 if (!MemcpyableCtor)
1028 return false;
1029 FieldDecl *Field = MemberInit->getMember();
Craig Topper8a13c412014-05-21 05:09:00 +00001030 assert(Field && "No field for member init.");
Lang Hamesbf122742013-02-17 07:22:09 +00001031 QualType FieldType = Field->getType();
1032 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
1033
Richard Smith419bd092015-04-29 19:26:57 +00001034 // Bail out on non-memcpyable, not-trivially-copyable members.
1035 if (!(CE && isMemcpyEquivalentSpecialMember(CE->getConstructor())) &&
Lang Hamesbf122742013-02-17 07:22:09 +00001036 !(FieldType.isTriviallyCopyableType(CGF.getContext()) ||
1037 FieldType->isReferenceType()))
1038 return false;
1039
1040 // Bail out on volatile fields.
1041 if (!isMemcpyableField(Field))
1042 return false;
1043
1044 // Otherwise we're good.
1045 return true;
1046 }
1047
1048 public:
1049 ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD,
1050 FunctionArgList &Args)
David Majnemer196ac332014-09-11 23:05:02 +00001051 : FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CGF, CD, Args)),
Lang Hamesbf122742013-02-17 07:22:09 +00001052 ConstructorDecl(CD),
Jordan Rose54533f72013-08-07 16:16:48 +00001053 MemcpyableCtor(CD->isDefaulted() &&
Lang Hamesbf122742013-02-17 07:22:09 +00001054 CD->isCopyOrMoveConstructor() &&
1055 CGF.getLangOpts().getGC() == LangOptions::NonGC),
1056 Args(Args) { }
1057
1058 void addMemberInitializer(CXXCtorInitializer *MemberInit) {
1059 if (isMemberInitMemcpyable(MemberInit)) {
1060 AggregatedInits.push_back(MemberInit);
1061 addMemcpyableField(MemberInit->getMember());
1062 } else {
1063 emitAggregatedInits();
1064 EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit,
1065 ConstructorDecl, Args);
1066 }
1067 }
1068
1069 void emitAggregatedInits() {
1070 if (AggregatedInits.size() <= 1) {
1071 // This memcpy is too small to be worthwhile. Fall back on default
1072 // codegen.
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001073 if (!AggregatedInits.empty()) {
1074 CopyingValueRepresentation CVR(CGF);
Lang Hamesbf122742013-02-17 07:22:09 +00001075 EmitMemberInitializer(CGF, ConstructorDecl->getParent(),
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001076 AggregatedInits[0], ConstructorDecl, Args);
Alexey Bataev152c71f2015-07-14 07:55:48 +00001077 AggregatedInits.clear();
Lang Hamesbf122742013-02-17 07:22:09 +00001078 }
1079 reset();
1080 return;
1081 }
1082
1083 pushEHDestructors();
1084 emitMemcpy();
1085 AggregatedInits.clear();
1086 }
1087
1088 void pushEHDestructors() {
John McCall7f416cc2015-09-08 08:05:57 +00001089 Address ThisPtr = CGF.LoadCXXThisAddress();
Lang Hamesbf122742013-02-17 07:22:09 +00001090 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
John McCall7f416cc2015-09-08 08:05:57 +00001091 LValue LHS = CGF.MakeAddrLValue(ThisPtr, RecordTy);
Lang Hamesbf122742013-02-17 07:22:09 +00001092
1093 for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
Alexey Bataev152c71f2015-07-14 07:55:48 +00001094 CXXCtorInitializer *MemberInit = AggregatedInits[i];
1095 QualType FieldType = MemberInit->getAnyMember()->getType();
Lang Hamesbf122742013-02-17 07:22:09 +00001096 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
Alexey Bataev152c71f2015-07-14 07:55:48 +00001097 if (!CGF.needsEHCleanup(dtorKind))
1098 continue;
1099 LValue FieldLHS = LHS;
1100 EmitLValueForAnyFieldInitialization(CGF, MemberInit, FieldLHS);
1101 CGF.pushEHDestroy(dtorKind, FieldLHS.getAddress(), FieldType);
Lang Hamesbf122742013-02-17 07:22:09 +00001102 }
1103 }
1104
1105 void finish() {
1106 emitAggregatedInits();
1107 }
1108
1109 private:
1110 const CXXConstructorDecl *ConstructorDecl;
1111 bool MemcpyableCtor;
1112 FunctionArgList &Args;
1113 SmallVector<CXXCtorInitializer*, 16> AggregatedInits;
1114 };
1115
1116 class AssignmentMemcpyizer : public FieldMemcpyizer {
1117 private:
Lang Hamesbf122742013-02-17 07:22:09 +00001118 // Returns the memcpyable field copied by the given statement, if one
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001119 // exists. Otherwise returns null.
1120 FieldDecl *getMemcpyableField(Stmt *S) {
Lang Hamesbf122742013-02-17 07:22:09 +00001121 if (!AssignmentsMemcpyable)
Craig Topper8a13c412014-05-21 05:09:00 +00001122 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001123 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
1124 // Recognise trivial assignments.
1125 if (BO->getOpcode() != BO_Assign)
Craig Topper8a13c412014-05-21 05:09:00 +00001126 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001127 MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS());
1128 if (!ME)
Craig Topper8a13c412014-05-21 05:09:00 +00001129 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001130 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1131 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001132 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001133 Stmt *RHS = BO->getRHS();
1134 if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS))
1135 RHS = EC->getSubExpr();
1136 if (!RHS)
Craig Topper8a13c412014-05-21 05:09:00 +00001137 return nullptr;
Warren Ristow8d17b402017-02-02 17:53:34 +00001138 if (MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS)) {
1139 if (ME2->getMemberDecl() == Field)
1140 return Field;
1141 }
1142 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001143 } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) {
1144 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl());
Richard Smith419bd092015-04-29 19:26:57 +00001145 if (!(MD && isMemcpyEquivalentSpecialMember(MD)))
Craig Topper8a13c412014-05-21 05:09:00 +00001146 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001147 MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument());
1148 if (!IOA)
Craig Topper8a13c412014-05-21 05:09:00 +00001149 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001150 FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl());
1151 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001152 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001153 MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0));
1154 if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl()))
Craig Topper8a13c412014-05-21 05:09:00 +00001155 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001156 return Field;
1157 } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1158 FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1159 if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy)
Craig Topper8a13c412014-05-21 05:09:00 +00001160 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001161 Expr *DstPtr = CE->getArg(0);
1162 if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr))
1163 DstPtr = DC->getSubExpr();
1164 UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr);
1165 if (!DUO || DUO->getOpcode() != UO_AddrOf)
Craig Topper8a13c412014-05-21 05:09:00 +00001166 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001167 MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr());
1168 if (!ME)
Craig Topper8a13c412014-05-21 05:09:00 +00001169 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001170 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1171 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001172 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001173 Expr *SrcPtr = CE->getArg(1);
1174 if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr))
1175 SrcPtr = SC->getSubExpr();
1176 UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr);
1177 if (!SUO || SUO->getOpcode() != UO_AddrOf)
Craig Topper8a13c412014-05-21 05:09:00 +00001178 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001179 MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr());
1180 if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl()))
Craig Topper8a13c412014-05-21 05:09:00 +00001181 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001182 return Field;
1183 }
1184
Craig Topper8a13c412014-05-21 05:09:00 +00001185 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001186 }
1187
1188 bool AssignmentsMemcpyable;
1189 SmallVector<Stmt*, 16> AggregatedStmts;
1190
1191 public:
Lang Hamesbf122742013-02-17 07:22:09 +00001192 AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD,
1193 FunctionArgList &Args)
1194 : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]),
1195 AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) {
1196 assert(Args.size() == 2);
1197 }
1198
1199 void emitAssignment(Stmt *S) {
1200 FieldDecl *F = getMemcpyableField(S);
1201 if (F) {
1202 addMemcpyableField(F);
1203 AggregatedStmts.push_back(S);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001204 } else {
Lang Hamesbf122742013-02-17 07:22:09 +00001205 emitAggregatedStmts();
1206 CGF.EmitStmt(S);
1207 }
1208 }
1209
1210 void emitAggregatedStmts() {
1211 if (AggregatedStmts.size() <= 1) {
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001212 if (!AggregatedStmts.empty()) {
1213 CopyingValueRepresentation CVR(CGF);
1214 CGF.EmitStmt(AggregatedStmts[0]);
1215 }
Lang Hamesbf122742013-02-17 07:22:09 +00001216 reset();
1217 }
1218
1219 emitMemcpy();
1220 AggregatedStmts.clear();
1221 }
1222
1223 void finish() {
1224 emitAggregatedStmts();
1225 }
1226 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00001227} // end anonymous namespace
Lang Hamesbf122742013-02-17 07:22:09 +00001228
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001229static bool isInitializerOfDynamicClass(const CXXCtorInitializer *BaseInit) {
1230 const Type *BaseType = BaseInit->getBaseClass();
1231 const auto *BaseClassDecl =
1232 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
1233 return BaseClassDecl->isDynamicClass();
1234}
1235
Anders Carlssonfb404882009-12-24 22:46:43 +00001236/// EmitCtorPrologue - This routine generates necessary code to initialize
1237/// base classes and non-static data members belonging to this constructor.
Anders Carlssonfb404882009-12-24 22:46:43 +00001238void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001239 CXXCtorType CtorType,
1240 FunctionArgList &Args) {
Alexis Hunt61bc1732011-05-01 07:04:31 +00001241 if (CD->isDelegatingConstructor())
1242 return EmitDelegatingCXXConstructorCall(CD, Args);
1243
Anders Carlssonfb404882009-12-24 22:46:43 +00001244 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlsson5dc86332010-02-02 19:58:43 +00001245
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001246 CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
1247 E = CD->init_end();
1248
Craig Topper8a13c412014-05-21 05:09:00 +00001249 llvm::BasicBlock *BaseCtorContinueBB = nullptr;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001250 if (ClassDecl->getNumVBases() &&
1251 !CGM.getTarget().getCXXABI().hasConstructorVariants()) {
1252 // The ABIs that don't have constructor variants need to put a branch
1253 // before the virtual base initialization code.
Reid Kleckner7810af02013-06-19 15:20:38 +00001254 BaseCtorContinueBB =
1255 CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this, ClassDecl);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001256 assert(BaseCtorContinueBB);
1257 }
1258
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001259 llvm::Value *const OldThis = CXXThisValue;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001260 // Virtual base initializers first.
1261 for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001262 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1263 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1264 isInitializerOfDynamicClass(*B))
1265 CXXThisValue = Builder.CreateInvariantGroupBarrier(LoadCXXThis());
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001266 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
1267 }
1268
1269 if (BaseCtorContinueBB) {
1270 // Complete object handler should continue to the remaining initializers.
1271 Builder.CreateBr(BaseCtorContinueBB);
1272 EmitBlock(BaseCtorContinueBB);
1273 }
1274
1275 // Then, non-virtual base initializers.
1276 for (; B != E && (*B)->isBaseInitializer(); B++) {
1277 assert(!(*B)->isBaseVirtual());
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001278
1279 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1280 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1281 isInitializerOfDynamicClass(*B))
1282 CXXThisValue = Builder.CreateInvariantGroupBarrier(LoadCXXThis());
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001283 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
Anders Carlssonfb404882009-12-24 22:46:43 +00001284 }
1285
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001286 CXXThisValue = OldThis;
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001287
Anders Carlssond5895932010-03-28 21:07:49 +00001288 InitializeVTablePointers(ClassDecl);
Anders Carlsson5dc86332010-02-02 19:58:43 +00001289
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001290 // And finally, initialize class members.
John McCall7f416cc2015-09-08 08:05:57 +00001291 FieldConstructionScope FCS(*this, LoadCXXThisAddress());
Lang Hamesbf122742013-02-17 07:22:09 +00001292 ConstructorMemcpyizer CM(*this, CD, Args);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001293 for (; B != E; B++) {
1294 CXXCtorInitializer *Member = (*B);
1295 assert(!Member->isBaseInitializer());
1296 assert(Member->isAnyMemberInitializer() &&
1297 "Delegating initializer on non-delegating constructor");
1298 CM.addMemberInitializer(Member);
1299 }
Lang Hamesbf122742013-02-17 07:22:09 +00001300 CM.finish();
Anders Carlssonfb404882009-12-24 22:46:43 +00001301}
1302
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001303static bool
1304FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
1305
1306static bool
Justin Bogner1cd11f12015-05-20 15:53:59 +00001307HasTrivialDestructorBody(ASTContext &Context,
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001308 const CXXRecordDecl *BaseClassDecl,
1309 const CXXRecordDecl *MostDerivedClassDecl)
1310{
1311 // If the destructor is trivial we don't have to check anything else.
1312 if (BaseClassDecl->hasTrivialDestructor())
1313 return true;
1314
1315 if (!BaseClassDecl->getDestructor()->hasTrivialBody())
1316 return false;
1317
1318 // Check fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001319 for (const auto *Field : BaseClassDecl->fields())
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001320 if (!FieldHasTrivialDestructorBody(Context, Field))
1321 return false;
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001322
1323 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001324 for (const auto &I : BaseClassDecl->bases()) {
1325 if (I.isVirtual())
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001326 continue;
1327
1328 const CXXRecordDecl *NonVirtualBase =
Aaron Ballman574705e2014-03-13 15:41:46 +00001329 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001330 if (!HasTrivialDestructorBody(Context, NonVirtualBase,
1331 MostDerivedClassDecl))
1332 return false;
1333 }
1334
1335 if (BaseClassDecl == MostDerivedClassDecl) {
1336 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00001337 for (const auto &I : BaseClassDecl->vbases()) {
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001338 const CXXRecordDecl *VirtualBase =
Aaron Ballman445a9392014-03-13 16:15:17 +00001339 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001340 if (!HasTrivialDestructorBody(Context, VirtualBase,
1341 MostDerivedClassDecl))
Justin Bogner1cd11f12015-05-20 15:53:59 +00001342 return false;
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001343 }
1344 }
1345
1346 return true;
1347}
1348
1349static bool
1350FieldHasTrivialDestructorBody(ASTContext &Context,
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001351 const FieldDecl *Field)
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001352{
1353 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
1354
1355 const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
1356 if (!RT)
1357 return true;
Justin Bogner1cd11f12015-05-20 15:53:59 +00001358
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001359 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Davide Italiano982bbf42015-06-26 00:18:35 +00001360
1361 // The destructor for an implicit anonymous union member is never invoked.
1362 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
1363 return false;
1364
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001365 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
1366}
1367
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001368/// CanSkipVTablePointerInitialization - Check whether we need to initialize
1369/// any vtable pointers before calling this destructor.
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001370static bool CanSkipVTablePointerInitialization(CodeGenFunction &CGF,
Anders Carlssond6f15182011-05-16 04:08:36 +00001371 const CXXDestructorDecl *Dtor) {
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001372 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1373 if (!ClassDecl->isDynamicClass())
1374 return true;
1375
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001376 if (!Dtor->hasTrivialBody())
1377 return false;
1378
1379 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001380 for (const auto *Field : ClassDecl->fields())
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001381 if (!FieldHasTrivialDestructorBody(CGF.getContext(), Field))
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001382 return false;
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001383
1384 return true;
1385}
1386
John McCallb81884d2010-02-19 09:25:03 +00001387/// EmitDestructorBody - Emits the body of the current destructor.
1388void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
1389 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
1390 CXXDtorType DtorType = CurGD.getDtorType();
1391
Justin Bognerfb298222015-05-20 16:16:23 +00001392 Stmt *Body = Dtor->getBody();
1393 if (Body)
1394 incrementProfileCounter(Body);
1395
John McCallf99a6312010-07-21 05:30:47 +00001396 // The call to operator delete in a deleting destructor happens
1397 // outside of the function-try-block, which means it's always
1398 // possible to delegate the destructor body to the complete
1399 // destructor. Do so.
1400 if (DtorType == Dtor_Deleting) {
1401 EnterDtorCleanups(Dtor, Dtor_Deleting);
1402 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
John McCall7f416cc2015-09-08 08:05:57 +00001403 /*Delegating=*/false, LoadCXXThisAddress());
John McCallf99a6312010-07-21 05:30:47 +00001404 PopCleanupBlock();
1405 return;
1406 }
1407
John McCallb81884d2010-02-19 09:25:03 +00001408 // If the body is a function-try-block, enter the try before
John McCallf99a6312010-07-21 05:30:47 +00001409 // anything else.
1410 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallb81884d2010-02-19 09:25:03 +00001411 if (isTryBody)
John McCallb609d3f2010-07-07 06:56:46 +00001412 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00001413 EmitAsanPrologueOrEpilogue(false);
John McCallb81884d2010-02-19 09:25:03 +00001414
John McCallf99a6312010-07-21 05:30:47 +00001415 // Enter the epilogue cleanups.
1416 RunCleanupsScope DtorEpilogue(*this);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001417
John McCallb81884d2010-02-19 09:25:03 +00001418 // If this is the complete variant, just invoke the base variant;
1419 // the epilogue will destruct the virtual bases. But we can't do
1420 // this optimization if the body is a function-try-block, because
Justin Bogner1cd11f12015-05-20 15:53:59 +00001421 // we'd introduce *two* handler blocks. In the Microsoft ABI, we
Reid Klecknere7de47e2013-07-22 13:51:44 +00001422 // always delegate because we might not have a definition in this TU.
John McCallf99a6312010-07-21 05:30:47 +00001423 switch (DtorType) {
Saleem Abdulrasool8de4e872017-02-02 05:45:43 +00001424 case Dtor_Comdat: llvm_unreachable("not expecting a COMDAT");
John McCallf99a6312010-07-21 05:30:47 +00001425 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
1426
1427 case Dtor_Complete:
Reid Klecknere7de47e2013-07-22 13:51:44 +00001428 assert((Body || getTarget().getCXXABI().isMicrosoft()) &&
1429 "can't emit a dtor without a body for non-Microsoft ABIs");
1430
John McCallf99a6312010-07-21 05:30:47 +00001431 // Enter the cleanup scopes for virtual bases.
1432 EnterDtorCleanups(Dtor, Dtor_Complete);
1433
Reid Klecknere7de47e2013-07-22 13:51:44 +00001434 if (!isTryBody) {
John McCallf99a6312010-07-21 05:30:47 +00001435 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
John McCall7f416cc2015-09-08 08:05:57 +00001436 /*Delegating=*/false, LoadCXXThisAddress());
John McCallf99a6312010-07-21 05:30:47 +00001437 break;
1438 }
Saleem Abdulrasool8de4e872017-02-02 05:45:43 +00001439
John McCallf99a6312010-07-21 05:30:47 +00001440 // Fallthrough: act like we're in the base variant.
Saleem Abdulrasool8de4e872017-02-02 05:45:43 +00001441 LLVM_FALLTHROUGH;
Justin Bogner1cd11f12015-05-20 15:53:59 +00001442
John McCallf99a6312010-07-21 05:30:47 +00001443 case Dtor_Base:
Reid Klecknere7de47e2013-07-22 13:51:44 +00001444 assert(Body);
1445
John McCallf99a6312010-07-21 05:30:47 +00001446 // Enter the cleanup scopes for fields and non-virtual bases.
1447 EnterDtorCleanups(Dtor, Dtor_Base);
1448
1449 // Initialize the vtable pointers before entering the body.
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001450 if (!CanSkipVTablePointerInitialization(*this, Dtor)) {
1451 // Insert the llvm.invariant.group.barrier intrinsic before initializing
1452 // the vptrs to cancel any previous assumptions we might have made.
1453 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1454 CGM.getCodeGenOpts().OptimizationLevel > 0)
1455 CXXThisValue = Builder.CreateInvariantGroupBarrier(LoadCXXThis());
1456 InitializeVTablePointers(Dtor->getParent());
1457 }
John McCallf99a6312010-07-21 05:30:47 +00001458
1459 if (isTryBody)
1460 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
1461 else if (Body)
1462 EmitStmt(Body);
1463 else {
1464 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
1465 // nothing to do besides what's in the epilogue
1466 }
Fariborz Jahanian0c12ed12011-02-02 23:12:46 +00001467 // -fapple-kext must inline any call to this dtor into
1468 // the caller's body.
Richard Smith9c6890a2012-11-01 22:30:59 +00001469 if (getLangOpts().AppleKext)
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00001470 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
Naomi Musgravee50cb9b2015-08-13 18:35:11 +00001471
John McCallf99a6312010-07-21 05:30:47 +00001472 break;
John McCallb81884d2010-02-19 09:25:03 +00001473 }
1474
John McCallf99a6312010-07-21 05:30:47 +00001475 // Jump out through the epilogue cleanups.
1476 DtorEpilogue.ForceCleanup();
John McCallb81884d2010-02-19 09:25:03 +00001477
1478 // Exit the try if applicable.
1479 if (isTryBody)
John McCallb609d3f2010-07-07 06:56:46 +00001480 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +00001481}
1482
Lang Hamesbf122742013-02-17 07:22:09 +00001483void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) {
1484 const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
1485 const Stmt *RootS = AssignOp->getBody();
1486 assert(isa<CompoundStmt>(RootS) &&
1487 "Body of an implicit assignment operator should be compound stmt.");
1488 const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
1489
1490 LexicalScope Scope(*this, RootCS->getSourceRange());
1491
Xinliang David Lia951e8e2016-02-09 20:02:59 +00001492 incrementProfileCounter(RootCS);
Lang Hamesbf122742013-02-17 07:22:09 +00001493 AssignmentMemcpyizer AM(*this, AssignOp, Args);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001494 for (auto *I : RootCS->body())
Justin Bogner1cd11f12015-05-20 15:53:59 +00001495 AM.emitAssignment(I);
Lang Hamesbf122742013-02-17 07:22:09 +00001496 AM.finish();
1497}
1498
John McCallf99a6312010-07-21 05:30:47 +00001499namespace {
1500 /// Call the operator delete associated with the current destructor.
David Blaikie7e70d682015-08-18 22:40:54 +00001501 struct CallDtorDelete final : EHScopeStack::Cleanup {
John McCallf99a6312010-07-21 05:30:47 +00001502 CallDtorDelete() {}
1503
Craig Topper4f12f102014-03-12 06:41:41 +00001504 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallf99a6312010-07-21 05:30:47 +00001505 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1506 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1507 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1508 CGF.getContext().getTagDeclType(ClassDecl));
1509 }
1510 };
1511
David Blaikie7e70d682015-08-18 22:40:54 +00001512 struct CallDtorDeleteConditional final : EHScopeStack::Cleanup {
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001513 llvm::Value *ShouldDeleteCondition;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001514
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001515 public:
1516 CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001517 : ShouldDeleteCondition(ShouldDeleteCondition) {
Craig Topper8a13c412014-05-21 05:09:00 +00001518 assert(ShouldDeleteCondition != nullptr);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001519 }
1520
Craig Topper4f12f102014-03-12 06:41:41 +00001521 void Emit(CodeGenFunction &CGF, Flags flags) override {
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001522 llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
1523 llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
1524 llvm::Value *ShouldCallDelete
1525 = CGF.Builder.CreateIsNull(ShouldDeleteCondition);
1526 CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
1527
1528 CGF.EmitBlock(callDeleteBB);
1529 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1530 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1531 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1532 CGF.getContext().getTagDeclType(ClassDecl));
1533 CGF.Builder.CreateBr(continueBB);
1534
1535 CGF.EmitBlock(continueBB);
1536 }
1537 };
1538
David Blaikie7e70d682015-08-18 22:40:54 +00001539 class DestroyField final : public EHScopeStack::Cleanup {
John McCall4bd0fb12011-07-12 16:41:08 +00001540 const FieldDecl *field;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001541 CodeGenFunction::Destroyer *destroyer;
John McCall4bd0fb12011-07-12 16:41:08 +00001542 bool useEHCleanupForArray;
John McCallf99a6312010-07-21 05:30:47 +00001543
John McCall4bd0fb12011-07-12 16:41:08 +00001544 public:
1545 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
1546 bool useEHCleanupForArray)
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001547 : field(field), destroyer(destroyer),
1548 useEHCleanupForArray(useEHCleanupForArray) {}
John McCallf99a6312010-07-21 05:30:47 +00001549
Craig Topper4f12f102014-03-12 06:41:41 +00001550 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall4bd0fb12011-07-12 16:41:08 +00001551 // Find the address of the field.
John McCall7f416cc2015-09-08 08:05:57 +00001552 Address thisValue = CGF.LoadCXXThisAddress();
Eli Friedman7f1ff602012-04-16 03:54:45 +00001553 QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
1554 LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
1555 LValue LV = CGF.EmitLValueForField(ThisLV, field);
John McCall4bd0fb12011-07-12 16:41:08 +00001556 assert(LV.isSimple());
Justin Bogner1cd11f12015-05-20 15:53:59 +00001557
John McCall4bd0fb12011-07-12 16:41:08 +00001558 CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +00001559 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCallf99a6312010-07-21 05:30:47 +00001560 }
1561 };
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001562
Naomi Musgrave703835c2015-09-16 00:38:22 +00001563 static void EmitSanitizerDtorCallback(CodeGenFunction &CGF, llvm::Value *Ptr,
1564 CharUnits::QuantityType PoisonSize) {
1565 // Pass in void pointer and size of region as arguments to runtime
1566 // function
1567 llvm::Value *Args[] = {CGF.Builder.CreateBitCast(Ptr, CGF.VoidPtrTy),
1568 llvm::ConstantInt::get(CGF.SizeTy, PoisonSize)};
1569
1570 llvm::Type *ArgTypes[] = {CGF.VoidPtrTy, CGF.SizeTy};
1571
1572 llvm::FunctionType *FnType =
1573 llvm::FunctionType::get(CGF.VoidTy, ArgTypes, false);
1574 llvm::Value *Fn =
1575 CGF.CGM.CreateRuntimeFunction(FnType, "__sanitizer_dtor_callback");
1576 CGF.EmitNounwindRuntimeCall(Fn, Args);
1577 }
1578
1579 class SanitizeDtorMembers final : public EHScopeStack::Cleanup {
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001580 const CXXDestructorDecl *Dtor;
1581
1582 public:
Naomi Musgrave703835c2015-09-16 00:38:22 +00001583 SanitizeDtorMembers(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001584
1585 // Generate function call for handling object poisoning.
1586 // Disables tail call elimination, to prevent the current stack frame
1587 // from disappearing from the stack trace.
1588 void Emit(CodeGenFunction &CGF, Flags flags) override {
1589 const ASTRecordLayout &Layout =
1590 CGF.getContext().getASTRecordLayout(Dtor->getParent());
1591
1592 // Nothing to poison.
1593 if (Layout.getFieldCount() == 0)
1594 return;
1595
1596 // Prevent the current stack frame from disappearing from the stack trace.
1597 CGF.CurFn->addFnAttr("disable-tail-calls", "true");
1598
1599 // Construct pointer to region to begin poisoning, and calculate poison
1600 // size, so that only members declared in this class are poisoned.
1601 ASTContext &Context = CGF.getContext();
1602 unsigned fieldIndex = 0;
1603 int startIndex = -1;
1604 // RecordDecl::field_iterator Field;
1605 for (const FieldDecl *Field : Dtor->getParent()->fields()) {
1606 // Poison field if it is trivial
1607 if (FieldHasTrivialDestructorBody(Context, Field)) {
1608 // Start sanitizing at this field
1609 if (startIndex < 0)
1610 startIndex = fieldIndex;
1611
1612 // Currently on the last field, and it must be poisoned with the
1613 // current block.
1614 if (fieldIndex == Layout.getFieldCount() - 1) {
Naomi Musgrave703835c2015-09-16 00:38:22 +00001615 PoisonMembers(CGF, startIndex, Layout.getFieldCount());
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001616 }
1617 } else if (startIndex >= 0) {
1618 // No longer within a block of memory to poison, so poison the block
Naomi Musgrave703835c2015-09-16 00:38:22 +00001619 PoisonMembers(CGF, startIndex, fieldIndex);
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001620 // Re-set the start index
1621 startIndex = -1;
1622 }
1623 fieldIndex += 1;
1624 }
1625 }
1626
1627 private:
NAKAMURA Takumif6cef72f2015-09-04 05:19:31 +00001628 /// \param layoutStartOffset index of the ASTRecordLayout field to
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001629 /// start poisoning (inclusive)
NAKAMURA Takumif6cef72f2015-09-04 05:19:31 +00001630 /// \param layoutEndOffset index of the ASTRecordLayout field to
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001631 /// end poisoning (exclusive)
Naomi Musgrave703835c2015-09-16 00:38:22 +00001632 void PoisonMembers(CodeGenFunction &CGF, unsigned layoutStartOffset,
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001633 unsigned layoutEndOffset) {
1634 ASTContext &Context = CGF.getContext();
1635 const ASTRecordLayout &Layout =
1636 Context.getASTRecordLayout(Dtor->getParent());
1637
1638 llvm::ConstantInt *OffsetSizePtr = llvm::ConstantInt::get(
1639 CGF.SizeTy,
1640 Context.toCharUnitsFromBits(Layout.getFieldOffset(layoutStartOffset))
1641 .getQuantity());
1642
1643 llvm::Value *OffsetPtr = CGF.Builder.CreateGEP(
1644 CGF.Builder.CreateBitCast(CGF.LoadCXXThis(), CGF.Int8PtrTy),
1645 OffsetSizePtr);
1646
1647 CharUnits::QuantityType PoisonSize;
1648 if (layoutEndOffset >= Layout.getFieldCount()) {
1649 PoisonSize = Layout.getNonVirtualSize().getQuantity() -
1650 Context.toCharUnitsFromBits(
1651 Layout.getFieldOffset(layoutStartOffset))
1652 .getQuantity();
1653 } else {
1654 PoisonSize = Context.toCharUnitsFromBits(
1655 Layout.getFieldOffset(layoutEndOffset) -
1656 Layout.getFieldOffset(layoutStartOffset))
1657 .getQuantity();
1658 }
1659
1660 if (PoisonSize == 0)
1661 return;
1662
Naomi Musgrave703835c2015-09-16 00:38:22 +00001663 EmitSanitizerDtorCallback(CGF, OffsetPtr, PoisonSize);
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001664 }
1665 };
Naomi Musgrave703835c2015-09-16 00:38:22 +00001666
1667 class SanitizeDtorVTable final : public EHScopeStack::Cleanup {
1668 const CXXDestructorDecl *Dtor;
1669
1670 public:
1671 SanitizeDtorVTable(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
1672
1673 // Generate function call for handling vtable pointer poisoning.
1674 void Emit(CodeGenFunction &CGF, Flags flags) override {
1675 assert(Dtor->getParent()->isDynamicClass());
NAKAMURA Takumiee82b492015-09-16 06:26:56 +00001676 (void)Dtor;
Naomi Musgrave703835c2015-09-16 00:38:22 +00001677 ASTContext &Context = CGF.getContext();
1678 // Poison vtable and vtable ptr if they exist for this class.
1679 llvm::Value *VTablePtr = CGF.LoadCXXThis();
1680
1681 CharUnits::QuantityType PoisonSize =
1682 Context.toCharUnitsFromBits(CGF.PointerWidthInBits).getQuantity();
1683 // Pass in void pointer and size of region as arguments to runtime
1684 // function
1685 EmitSanitizerDtorCallback(CGF, VTablePtr, PoisonSize);
1686 }
1687 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00001688} // end anonymous namespace
John McCallf99a6312010-07-21 05:30:47 +00001689
Hans Wennborgdeff7032013-12-18 01:39:59 +00001690/// \brief Emit all code that comes at the end of class's
Anders Carlssonfb404882009-12-24 22:46:43 +00001691/// destructor. This is to call destructors on members and base classes
1692/// in reverse order of their construction.
John McCallf99a6312010-07-21 05:30:47 +00001693void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
1694 CXXDtorType DtorType) {
Hans Wennborg853ae942014-05-30 16:59:42 +00001695 assert((!DD->isTrivial() || DD->hasAttr<DLLExportAttr>()) &&
1696 "Should not emit dtor epilogue for non-exported trivial dtor!");
Anders Carlssonfb404882009-12-24 22:46:43 +00001697
John McCallf99a6312010-07-21 05:30:47 +00001698 // The deleting-destructor phase just needs to call the appropriate
1699 // operator delete that Sema picked up.
John McCall5c60a6f2010-02-18 19:59:28 +00001700 if (DtorType == Dtor_Deleting) {
Justin Bogner1cd11f12015-05-20 15:53:59 +00001701 assert(DD->getOperatorDelete() &&
Hans Wennborgdeff7032013-12-18 01:39:59 +00001702 "operator delete missing - EnterDtorCleanups");
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001703 if (CXXStructorImplicitParamValue) {
1704 // If there is an implicit param to the deleting dtor, it's a boolean
1705 // telling whether we should call delete at the end of the dtor.
1706 EHStack.pushCleanup<CallDtorDeleteConditional>(
1707 NormalAndEHCleanup, CXXStructorImplicitParamValue);
1708 } else {
1709 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
1710 }
John McCall5c60a6f2010-02-18 19:59:28 +00001711 return;
1712 }
1713
John McCallf99a6312010-07-21 05:30:47 +00001714 const CXXRecordDecl *ClassDecl = DD->getParent();
1715
Richard Smith20104042011-09-18 12:11:43 +00001716 // Unions have no bases and do not call field destructors.
1717 if (ClassDecl->isUnion())
1718 return;
1719
John McCallf99a6312010-07-21 05:30:47 +00001720 // The complete-destructor phase just destructs all the virtual bases.
John McCall5c60a6f2010-02-18 19:59:28 +00001721 if (DtorType == Dtor_Complete) {
Naomi Musgrave703835c2015-09-16 00:38:22 +00001722 // Poison the vtable pointer such that access after the base
1723 // and member destructors are invoked is invalid.
1724 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1725 SanOpts.has(SanitizerKind::Memory) && ClassDecl->getNumVBases() &&
1726 ClassDecl->isPolymorphic())
1727 EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
John McCallf99a6312010-07-21 05:30:47 +00001728
1729 // We push them in the forward order so that they'll be popped in
1730 // the reverse order.
Aaron Ballman445a9392014-03-13 16:15:17 +00001731 for (const auto &Base : ClassDecl->vbases()) {
John McCall5c60a6f2010-02-18 19:59:28 +00001732 CXXRecordDecl *BaseClassDecl
1733 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Justin Bogner1cd11f12015-05-20 15:53:59 +00001734
John McCall5c60a6f2010-02-18 19:59:28 +00001735 // Ignore trivial destructors.
1736 if (BaseClassDecl->hasTrivialDestructor())
1737 continue;
John McCallf99a6312010-07-21 05:30:47 +00001738
John McCallcda666c2010-07-21 07:22:38 +00001739 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1740 BaseClassDecl,
1741 /*BaseIsVirtual*/ true);
John McCall5c60a6f2010-02-18 19:59:28 +00001742 }
John McCallf99a6312010-07-21 05:30:47 +00001743
John McCall5c60a6f2010-02-18 19:59:28 +00001744 return;
1745 }
1746
1747 assert(DtorType == Dtor_Base);
Naomi Musgrave703835c2015-09-16 00:38:22 +00001748 // Poison the vtable pointer if it has no virtual bases, but inherits
1749 // virtual functions.
1750 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1751 SanOpts.has(SanitizerKind::Memory) && !ClassDecl->getNumVBases() &&
1752 ClassDecl->isPolymorphic())
1753 EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001754
John McCallf99a6312010-07-21 05:30:47 +00001755 // Destroy non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001756 for (const auto &Base : ClassDecl->bases()) {
John McCallf99a6312010-07-21 05:30:47 +00001757 // Ignore virtual bases.
1758 if (Base.isVirtual())
1759 continue;
Justin Bogner1cd11f12015-05-20 15:53:59 +00001760
John McCallf99a6312010-07-21 05:30:47 +00001761 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
Justin Bogner1cd11f12015-05-20 15:53:59 +00001762
John McCallf99a6312010-07-21 05:30:47 +00001763 // Ignore trivial destructors.
1764 if (BaseClassDecl->hasTrivialDestructor())
1765 continue;
John McCall5c60a6f2010-02-18 19:59:28 +00001766
John McCallcda666c2010-07-21 07:22:38 +00001767 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1768 BaseClassDecl,
1769 /*BaseIsVirtual*/ false);
John McCallf99a6312010-07-21 05:30:47 +00001770 }
1771
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001772 // Poison fields such that access after their destructors are
1773 // invoked, and before the base class destructor runs, is invalid.
1774 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1775 SanOpts.has(SanitizerKind::Memory))
Naomi Musgrave703835c2015-09-16 00:38:22 +00001776 EHStack.pushCleanup<SanitizeDtorMembers>(NormalAndEHCleanup, DD);
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001777
John McCallf99a6312010-07-21 05:30:47 +00001778 // Destroy direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001779 for (const auto *Field : ClassDecl->fields()) {
1780 QualType type = Field->getType();
John McCall4bd0fb12011-07-12 16:41:08 +00001781 QualType::DestructionKind dtorKind = type.isDestructedType();
1782 if (!dtorKind) continue;
John McCallf99a6312010-07-21 05:30:47 +00001783
Richard Smith921bd202012-02-26 09:11:52 +00001784 // Anonymous union members do not have their destructors called.
1785 const RecordType *RT = type->getAsUnionType();
1786 if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
1787
John McCall4bd0fb12011-07-12 16:41:08 +00001788 CleanupKind cleanupKind = getCleanupKind(dtorKind);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001789 EHStack.pushCleanup<DestroyField>(cleanupKind, Field,
John McCall4bd0fb12011-07-12 16:41:08 +00001790 getDestroyer(dtorKind),
1791 cleanupKind & EHCleanup);
Anders Carlssonfb404882009-12-24 22:46:43 +00001792 }
Anders Carlssonfb404882009-12-24 22:46:43 +00001793}
1794
John McCallf677a8e2011-07-13 06:10:41 +00001795/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1796/// constructor for each of several members of an array.
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001797///
John McCallf677a8e2011-07-13 06:10:41 +00001798/// \param ctor the constructor to call for each element
John McCallf677a8e2011-07-13 06:10:41 +00001799/// \param arrayType the type of the array to initialize
1800/// \param arrayBegin an arrayType*
1801/// \param zeroInitialize true if each element should be
1802/// zero-initialized before it is constructed
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001803void CodeGenFunction::EmitCXXAggrConstructorCall(
Alexey Bataeve7545b32016-04-29 09:39:50 +00001804 const CXXConstructorDecl *ctor, const ArrayType *arrayType,
John McCall7f416cc2015-09-08 08:05:57 +00001805 Address arrayBegin, const CXXConstructExpr *E, bool zeroInitialize) {
John McCallf677a8e2011-07-13 06:10:41 +00001806 QualType elementType;
1807 llvm::Value *numElements =
1808 emitArrayLength(arrayType, elementType, arrayBegin);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001809
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001810 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin, E, zeroInitialize);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001811}
1812
John McCallf677a8e2011-07-13 06:10:41 +00001813/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1814/// constructor for each of several members of an array.
1815///
1816/// \param ctor the constructor to call for each element
1817/// \param numElements the number of elements in the array;
John McCall6549b312011-07-13 07:37:11 +00001818/// may be zero
NAKAMURA Takumiff7a9252015-09-08 09:42:41 +00001819/// \param arrayBase a T*, where T is the type constructed by ctor
John McCallf677a8e2011-07-13 06:10:41 +00001820/// \param zeroInitialize true if each element should be
1821/// zero-initialized before it is constructed
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001822void CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1823 llvm::Value *numElements,
John McCall7f416cc2015-09-08 08:05:57 +00001824 Address arrayBase,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001825 const CXXConstructExpr *E,
1826 bool zeroInitialize) {
John McCall6549b312011-07-13 07:37:11 +00001827 // It's legal for numElements to be zero. This can happen both
1828 // dynamically, because x can be zero in 'new A[x]', and statically,
1829 // because of GCC extensions that permit zero-length arrays. There
1830 // are probably legitimate places where we could assume that this
1831 // doesn't happen, but it's not clear that it's worth it.
Craig Topper8a13c412014-05-21 05:09:00 +00001832 llvm::BranchInst *zeroCheckBranch = nullptr;
John McCall6549b312011-07-13 07:37:11 +00001833
1834 // Optimize for a constant count.
1835 llvm::ConstantInt *constantCount
1836 = dyn_cast<llvm::ConstantInt>(numElements);
1837 if (constantCount) {
1838 // Just skip out if the constant count is zero.
1839 if (constantCount->isZero()) return;
1840
1841 // Otherwise, emit the check.
1842 } else {
1843 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1844 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1845 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1846 EmitBlock(loopBB);
1847 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00001848
John McCallf677a8e2011-07-13 06:10:41 +00001849 // Find the end of the array.
John McCall7f416cc2015-09-08 08:05:57 +00001850 llvm::Value *arrayBegin = arrayBase.getPointer();
John McCallf677a8e2011-07-13 06:10:41 +00001851 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1852 "arrayctor.end");
Anders Carlsson27da15b2010-01-01 20:29:01 +00001853
John McCallf677a8e2011-07-13 06:10:41 +00001854 // Enter the loop, setting up a phi for the current location to initialize.
1855 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1856 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1857 EmitBlock(loopBB);
1858 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1859 "arrayctor.cur");
1860 cur->addIncoming(arrayBegin, entryBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001861
Anders Carlsson27da15b2010-01-01 20:29:01 +00001862 // Inside the loop body, emit the constructor call on the array element.
John McCallf677a8e2011-07-13 06:10:41 +00001863
John McCall7f416cc2015-09-08 08:05:57 +00001864 // The alignment of the base, adjusted by the size of a single element,
1865 // provides a conservative estimate of the alignment of every element.
1866 // (This assumes we never start tracking offsetted alignments.)
1867 //
1868 // Note that these are complete objects and so we don't need to
1869 // use the non-virtual size or alignment.
John McCallf677a8e2011-07-13 06:10:41 +00001870 QualType type = getContext().getTypeDeclType(ctor->getParent());
John McCall7f416cc2015-09-08 08:05:57 +00001871 CharUnits eltAlignment =
1872 arrayBase.getAlignment()
1873 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
1874 Address curAddr = Address(cur, eltAlignment);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001875
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001876 // Zero initialize the storage, if requested.
John McCallf677a8e2011-07-13 06:10:41 +00001877 if (zeroInitialize)
John McCall7f416cc2015-09-08 08:05:57 +00001878 EmitNullInitialization(curAddr, type);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001879
1880 // C++ [class.temporary]p4:
Anders Carlsson27da15b2010-01-01 20:29:01 +00001881 // There are two contexts in which temporaries are destroyed at a different
1882 // point than the end of the full-expression. The first context is when a
Justin Bogner1cd11f12015-05-20 15:53:59 +00001883 // default constructor is called to initialize an element of an array.
1884 // If the constructor has one or more default arguments, the destruction of
1885 // every temporary created in a default argument expression is sequenced
Anders Carlsson27da15b2010-01-01 20:29:01 +00001886 // before the construction of the next array element, if any.
Justin Bogner1cd11f12015-05-20 15:53:59 +00001887
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00001888 {
John McCallbd309292010-07-06 01:34:17 +00001889 RunCleanupsScope Scope(*this);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001890
John McCallf677a8e2011-07-13 06:10:41 +00001891 // Evaluate the constructor and its arguments in a regular
1892 // partial-destroy cleanup.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001893 if (getLangOpts().Exceptions &&
John McCallf677a8e2011-07-13 06:10:41 +00001894 !ctor->getParent()->hasTrivialDestructor()) {
1895 Destroyer *destroyer = destroyCXXObject;
John McCall7f416cc2015-09-08 08:05:57 +00001896 pushRegularPartialArrayCleanup(arrayBegin, cur, type, eltAlignment,
1897 *destroyer);
John McCallf677a8e2011-07-13 06:10:41 +00001898 }
1899
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001900 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/false,
John McCall7f416cc2015-09-08 08:05:57 +00001901 /*Delegating=*/false, curAddr, E);
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00001902 }
Anders Carlsson27da15b2010-01-01 20:29:01 +00001903
John McCallf677a8e2011-07-13 06:10:41 +00001904 // Go to the next element.
1905 llvm::Value *next =
1906 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
1907 "arrayctor.next");
1908 cur->addIncoming(next, Builder.GetInsertBlock());
Anders Carlsson27da15b2010-01-01 20:29:01 +00001909
John McCallf677a8e2011-07-13 06:10:41 +00001910 // Check whether that's the end of the loop.
1911 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
1912 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
1913 Builder.CreateCondBr(done, contBB, loopBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001914
John McCall6549b312011-07-13 07:37:11 +00001915 // Patch the earlier check to skip over the loop.
1916 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
1917
John McCallf677a8e2011-07-13 06:10:41 +00001918 EmitBlock(contBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001919}
1920
John McCall82fe67b2011-07-09 01:37:26 +00001921void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001922 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00001923 QualType type) {
1924 const RecordType *rtype = type->castAs<RecordType>();
1925 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
1926 const CXXDestructorDecl *dtor = record->getDestructor();
1927 assert(!dtor->isTrivial());
1928 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
Douglas Gregor61535002013-01-31 05:50:40 +00001929 /*Delegating=*/false, addr);
John McCall82fe67b2011-07-09 01:37:26 +00001930}
1931
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001932void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
1933 CXXCtorType Type,
1934 bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +00001935 bool Delegating, Address This,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001936 const CXXConstructExpr *E) {
Richard Smith5179eb72016-06-28 19:03:57 +00001937 CallArgList Args;
1938
1939 // Push the this ptr.
1940 Args.add(RValue::get(This.getPointer()), D->getThisType(getContext()));
1941
1942 // If this is a trivial constructor, emit a memcpy now before we lose
1943 // the alignment information on the argument.
1944 // FIXME: It would be better to preserve alignment information into CallArg.
1945 if (isMemcpyEquivalentSpecialMember(D)) {
1946 assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
1947
1948 const Expr *Arg = E->getArg(0);
1949 QualType SrcTy = Arg->getType();
1950 Address Src = EmitLValue(Arg).getAddress();
1951 QualType DestTy = getContext().getTypeDeclType(D->getParent());
1952 EmitAggregateCopyCtor(This, Src, DestTy, SrcTy);
1953 return;
1954 }
1955
1956 // Add the rest of the user-supplied arguments.
1957 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
Hans Wennborg27dcc6c2017-02-01 02:21:07 +00001958 EvaluationOrder Order = E->isListInitialization()
1959 ? EvaluationOrder::ForceLeftToRight
1960 : EvaluationOrder::Default;
1961 EmitCallArgs(Args, FPT, E->arguments(), E->getConstructor(),
1962 /*ParamsToSkip*/ 0, Order);
Richard Smith5179eb72016-06-28 19:03:57 +00001963
1964 EmitCXXConstructorCall(D, Type, ForVirtualBase, Delegating, This, Args);
1965}
1966
1967static bool canEmitDelegateCallArgs(CodeGenFunction &CGF,
1968 const CXXConstructorDecl *Ctor,
1969 CXXCtorType Type, CallArgList &Args) {
1970 // We can't forward a variadic call.
1971 if (Ctor->isVariadic())
1972 return false;
1973
1974 if (CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
1975 // If the parameters are callee-cleanup, it's not safe to forward.
1976 for (auto *P : Ctor->parameters())
1977 if (P->getType().isDestructedType())
1978 return false;
1979
1980 // Likewise if they're inalloca.
1981 const CGFunctionInfo &Info =
1982 CGF.CGM.getTypes().arrangeCXXConstructorCall(Args, Ctor, Type, 0);
1983 if (Info.usesInAlloca())
1984 return false;
1985 }
1986
1987 // Anything else should be OK.
1988 return true;
1989}
1990
1991void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
1992 CXXCtorType Type,
1993 bool ForVirtualBase,
1994 bool Delegating,
1995 Address This,
1996 CallArgList &Args) {
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001997 const CXXRecordDecl *ClassDecl = D->getParent();
1998
Richard Smith419bd092015-04-29 19:26:57 +00001999 // C++11 [class.mfct.non-static]p2:
2000 // If a non-static member function of a class X is called for an object that
2001 // is not of type X, or of a type derived from X, the behavior is undefined.
2002 // FIXME: Provide a source location here.
John McCall7f416cc2015-09-08 08:05:57 +00002003 EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall, SourceLocation(),
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002004 This.getPointer(), getContext().getRecordType(ClassDecl));
John McCallca972cd2010-02-06 00:25:16 +00002005
Richard Smith419bd092015-04-29 19:26:57 +00002006 if (D->isTrivial() && D->isDefaultConstructor()) {
Richard Smith5179eb72016-06-28 19:03:57 +00002007 assert(Args.size() == 1 && "trivial default ctor with args");
Richard Smith419bd092015-04-29 19:26:57 +00002008 return;
2009 }
2010
2011 // If this is a trivial constructor, just emit what's needed. If this is a
2012 // union copy constructor, we must emit a memcpy, because the AST does not
2013 // model that copy.
2014 if (isMemcpyEquivalentSpecialMember(D)) {
Richard Smith5179eb72016-06-28 19:03:57 +00002015 assert(Args.size() == 2 && "unexpected argcount for trivial ctor");
John McCallca972cd2010-02-06 00:25:16 +00002016
Richard Smith5179eb72016-06-28 19:03:57 +00002017 QualType SrcTy = D->getParamDecl(0)->getType().getNonReferenceType();
2018 Address Src(Args[1].RV.getScalarVal(), getNaturalTypeAlignment(SrcTy));
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002019 QualType DestTy = getContext().getTypeDeclType(ClassDecl);
David Majnemerfd1e7392015-02-03 23:04:06 +00002020 EmitAggregateCopyCtor(This, Src, DestTy, SrcTy);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002021 return;
2022 }
2023
Richard Smith5179eb72016-06-28 19:03:57 +00002024 // Check whether we can actually emit the constructor before trying to do so.
2025 if (auto Inherited = D->getInheritedConstructor()) {
2026 if (getTypes().inheritingCtorHasParams(Inherited, Type) &&
2027 !canEmitDelegateCallArgs(*this, D, Type, Args)) {
2028 EmitInlinedInheritingCXXConstructorCall(D, Type, ForVirtualBase,
2029 Delegating, Args);
2030 return;
2031 }
2032 }
Reid Kleckner89077a12013-12-17 19:46:40 +00002033
2034 // Insert any ABI-specific implicit constructor arguments.
George Burgess IVf203dbf2017-02-22 20:28:02 +00002035 CGCXXABI::AddedStructorArgs ExtraArgs =
2036 CGM.getCXXABI().addImplicitConstructorArgs(*this, D, Type, ForVirtualBase,
2037 Delegating, Args);
Reid Kleckner89077a12013-12-17 19:46:40 +00002038
2039 // Emit the call.
John McCallb92ab1a2016-10-26 23:46:34 +00002040 llvm::Constant *CalleePtr =
2041 CGM.getAddrOfCXXStructor(D, getFromCtorType(Type));
George Burgess IVf203dbf2017-02-22 20:28:02 +00002042 const CGFunctionInfo &Info = CGM.getTypes().arrangeCXXConstructorCall(
2043 Args, D, Type, ExtraArgs.Prefix + ExtraArgs.Suffix);
John McCallb92ab1a2016-10-26 23:46:34 +00002044 CGCallee Callee = CGCallee::forDirect(CalleePtr, D);
2045 EmitCall(Info, Callee, ReturnValueSlot(), Args);
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002046
2047 // Generate vtable assumptions if we're constructing a complete object
2048 // with a vtable. We don't do this for base subobjects for two reasons:
2049 // first, it's incorrect for classes with virtual bases, and second, we're
2050 // about to overwrite the vptrs anyway.
2051 // We also have to make sure if we can refer to vtable:
2052 // - Otherwise we can refer to vtable if it's safe to speculatively emit.
2053 // FIXME: If vtable is used by ctor/dtor, or if vtable is external and we are
2054 // sure that definition of vtable is not hidden,
2055 // then we are always safe to refer to it.
Piotr Padlewski69dc9712015-09-28 20:30:22 +00002056 // FIXME: It looks like InstCombine is very inefficient on dealing with
2057 // assumes. Make assumption loads require -fstrict-vtable-pointers temporarily.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002058 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2059 ClassDecl->isDynamicClass() && Type != Ctor_Base &&
Piotr Padlewski69dc9712015-09-28 20:30:22 +00002060 CGM.getCXXABI().canSpeculativelyEmitVTable(ClassDecl) &&
2061 CGM.getCodeGenOpts().StrictVTablePointers)
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002062 EmitVTableAssumptionLoads(ClassDecl, This);
2063}
2064
Richard Smith5179eb72016-06-28 19:03:57 +00002065void CodeGenFunction::EmitInheritedCXXConstructorCall(
2066 const CXXConstructorDecl *D, bool ForVirtualBase, Address This,
2067 bool InheritedFromVBase, const CXXInheritedCtorInitExpr *E) {
2068 CallArgList Args;
2069 CallArg ThisArg(RValue::get(This.getPointer()), D->getThisType(getContext()),
2070 /*NeedsCopy=*/false);
2071
2072 // Forward the parameters.
2073 if (InheritedFromVBase &&
2074 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
2075 // Nothing to do; this construction is not responsible for constructing
2076 // the base class containing the inherited constructor.
2077 // FIXME: Can we just pass undef's for the remaining arguments if we don't
2078 // have constructor variants?
2079 Args.push_back(ThisArg);
2080 } else if (!CXXInheritedCtorInitExprArgs.empty()) {
2081 // The inheriting constructor was inlined; just inject its arguments.
2082 assert(CXXInheritedCtorInitExprArgs.size() >= D->getNumParams() &&
2083 "wrong number of parameters for inherited constructor call");
2084 Args = CXXInheritedCtorInitExprArgs;
2085 Args[0] = ThisArg;
2086 } else {
2087 // The inheriting constructor was not inlined. Emit delegating arguments.
2088 Args.push_back(ThisArg);
2089 const auto *OuterCtor = cast<CXXConstructorDecl>(CurCodeDecl);
2090 assert(OuterCtor->getNumParams() == D->getNumParams());
2091 assert(!OuterCtor->isVariadic() && "should have been inlined");
2092
2093 for (const auto *Param : OuterCtor->parameters()) {
2094 assert(getContext().hasSameUnqualifiedType(
2095 OuterCtor->getParamDecl(Param->getFunctionScopeIndex())->getType(),
2096 Param->getType()));
2097 EmitDelegateCallArg(Args, Param, E->getLocation());
2098
2099 // Forward __attribute__(pass_object_size).
2100 if (Param->hasAttr<PassObjectSizeAttr>()) {
2101 auto *POSParam = SizeArguments[Param];
2102 assert(POSParam && "missing pass_object_size value for forwarding");
2103 EmitDelegateCallArg(Args, POSParam, E->getLocation());
2104 }
2105 }
2106 }
2107
2108 EmitCXXConstructorCall(D, Ctor_Base, ForVirtualBase, /*Delegating*/false,
2109 This, Args);
2110}
2111
2112void CodeGenFunction::EmitInlinedInheritingCXXConstructorCall(
2113 const CXXConstructorDecl *Ctor, CXXCtorType CtorType, bool ForVirtualBase,
2114 bool Delegating, CallArgList &Args) {
2115 InlinedInheritingConstructorScope Scope(*this, GlobalDecl(Ctor, CtorType));
2116
2117 // Save the arguments to be passed to the inherited constructor.
2118 CXXInheritedCtorInitExprArgs = Args;
2119
2120 FunctionArgList Params;
2121 QualType RetType = BuildFunctionArgList(CurGD, Params);
2122 FnRetTy = RetType;
2123
2124 // Insert any ABI-specific implicit constructor arguments.
2125 CGM.getCXXABI().addImplicitConstructorArgs(*this, Ctor, CtorType,
2126 ForVirtualBase, Delegating, Args);
2127
2128 // Emit a simplified prolog. We only need to emit the implicit params.
2129 assert(Args.size() >= Params.size() && "too few arguments for call");
2130 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2131 if (I < Params.size() && isa<ImplicitParamDecl>(Params[I])) {
2132 const RValue &RV = Args[I].RV;
2133 assert(!RV.isComplex() && "complex indirect params not supported");
2134 ParamValue Val = RV.isScalar()
2135 ? ParamValue::forDirect(RV.getScalarVal())
2136 : ParamValue::forIndirect(RV.getAggregateAddress());
2137 EmitParmDecl(*Params[I], Val, I + 1);
2138 }
2139 }
2140
2141 // Create a return value slot if the ABI implementation wants one.
2142 // FIXME: This is dumb, we should ask the ABI not to try to set the return
2143 // value instead.
2144 if (!RetType->isVoidType())
2145 ReturnValue = CreateIRTemp(RetType, "retval.inhctor");
2146
2147 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
2148 CXXThisValue = CXXABIThisValue;
2149
2150 // Directly emit the constructor initializers.
2151 EmitCtorPrologue(Ctor, CtorType, Params);
2152}
2153
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002154void CodeGenFunction::EmitVTableAssumptionLoad(const VPtr &Vptr, Address This) {
2155 llvm::Value *VTableGlobal =
2156 CGM.getCXXABI().getVTableAddressPoint(Vptr.Base, Vptr.VTableClass);
2157 if (!VTableGlobal)
2158 return;
2159
2160 // We can just use the base offset in the complete class.
2161 CharUnits NonVirtualOffset = Vptr.Base.getBaseOffset();
2162
2163 if (!NonVirtualOffset.isZero())
2164 This =
2165 ApplyNonVirtualAndVirtualOffset(*this, This, NonVirtualOffset, nullptr,
2166 Vptr.VTableClass, Vptr.NearestVBase);
2167
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002168 llvm::Value *VPtrValue =
2169 GetVTablePtr(This, VTableGlobal->getType(), Vptr.VTableClass);
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002170 llvm::Value *Cmp =
2171 Builder.CreateICmpEQ(VPtrValue, VTableGlobal, "cmp.vtables");
2172 Builder.CreateAssumption(Cmp);
2173}
2174
2175void CodeGenFunction::EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl,
2176 Address This) {
2177 if (CGM.getCXXABI().doStructorsInitializeVPtrs(ClassDecl))
2178 for (const VPtr &Vptr : getVTablePointers(ClassDecl))
2179 EmitVTableAssumptionLoad(Vptr, This);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002180}
2181
John McCallf8ff7b92010-02-23 00:48:20 +00002182void
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002183CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
John McCall7f416cc2015-09-08 08:05:57 +00002184 Address This, Address Src,
2185 const CXXConstructExpr *E) {
Reid Kleckner739756c2013-12-04 19:23:12 +00002186 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
Justin Bogner1cd11f12015-05-20 15:53:59 +00002187
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002188 CallArgList Args;
Justin Bogner1cd11f12015-05-20 15:53:59 +00002189
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002190 // Push the this ptr.
John McCall7f416cc2015-09-08 08:05:57 +00002191 Args.add(RValue::get(This.getPointer()), D->getThisType(getContext()));
Justin Bogner1cd11f12015-05-20 15:53:59 +00002192
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002193 // Push the src ptr.
Alp Toker9cacbab2014-01-20 20:26:09 +00002194 QualType QT = *(FPT->param_type_begin());
Chris Lattner2192fe52011-07-18 04:24:23 +00002195 llvm::Type *t = CGM.getTypes().ConvertType(QT);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002196 Src = Builder.CreateBitCast(Src, t);
John McCall7f416cc2015-09-08 08:05:57 +00002197 Args.add(RValue::get(Src.getPointer()), QT);
Reid Kleckner739756c2013-12-04 19:23:12 +00002198
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002199 // Skip over first argument (Src).
David Blaikief05779e2015-07-21 18:37:18 +00002200 EmitCallArgs(Args, FPT, drop_begin(E->arguments(), 1), E->getConstructor(),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002201 /*ParamsToSkip*/ 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002202
Richard Smith5179eb72016-06-28 19:03:57 +00002203 EmitCXXConstructorCall(D, Ctor_Complete, false, false, This, Args);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002204}
2205
2206void
John McCallf8ff7b92010-02-23 00:48:20 +00002207CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
2208 CXXCtorType CtorType,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002209 const FunctionArgList &Args,
2210 SourceLocation Loc) {
John McCallf8ff7b92010-02-23 00:48:20 +00002211 CallArgList DelegateArgs;
2212
2213 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
2214 assert(I != E && "no parameters to constructor");
2215
2216 // this
Richard Smith5179eb72016-06-28 19:03:57 +00002217 Address This = LoadCXXThisAddress();
2218 DelegateArgs.add(RValue::get(This.getPointer()), (*I)->getType());
John McCallf8ff7b92010-02-23 00:48:20 +00002219 ++I;
2220
Richard Smith5179eb72016-06-28 19:03:57 +00002221 // FIXME: The location of the VTT parameter in the parameter list is
2222 // specific to the Itanium ABI and shouldn't be hardcoded here.
2223 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
2224 assert(I != E && "cannot skip vtt parameter, already done with args");
2225 assert((*I)->getType()->isPointerType() &&
2226 "skipping parameter not of vtt type");
2227 ++I;
John McCallf8ff7b92010-02-23 00:48:20 +00002228 }
2229
2230 // Explicit arguments.
2231 for (; I != E; ++I) {
John McCall32ea9692011-03-11 20:59:21 +00002232 const VarDecl *param = *I;
Nick Lewycky2d84e842013-10-02 02:29:49 +00002233 // FIXME: per-argument source location
2234 EmitDelegateCallArg(DelegateArgs, param, Loc);
John McCallf8ff7b92010-02-23 00:48:20 +00002235 }
2236
Richard Smith5179eb72016-06-28 19:03:57 +00002237 EmitCXXConstructorCall(Ctor, CtorType, /*ForVirtualBase=*/false,
2238 /*Delegating=*/true, This, DelegateArgs);
John McCallf8ff7b92010-02-23 00:48:20 +00002239}
2240
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002241namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002242 struct CallDelegatingCtorDtor final : EHScopeStack::Cleanup {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002243 const CXXDestructorDecl *Dtor;
John McCall7f416cc2015-09-08 08:05:57 +00002244 Address Addr;
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002245 CXXDtorType Type;
2246
John McCall7f416cc2015-09-08 08:05:57 +00002247 CallDelegatingCtorDtor(const CXXDestructorDecl *D, Address Addr,
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002248 CXXDtorType Type)
2249 : Dtor(D), Addr(Addr), Type(Type) {}
2250
Craig Topper4f12f102014-03-12 06:41:41 +00002251 void Emit(CodeGenFunction &CGF, Flags flags) override {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002252 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
Douglas Gregor61535002013-01-31 05:50:40 +00002253 /*Delegating=*/true, Addr);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002254 }
2255 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00002256} // end anonymous namespace
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002257
Alexis Hunt61bc1732011-05-01 07:04:31 +00002258void
2259CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
2260 const FunctionArgList &Args) {
2261 assert(Ctor->isDelegatingConstructor());
2262
John McCall7f416cc2015-09-08 08:05:57 +00002263 Address ThisPtr = LoadCXXThisAddress();
Alexis Hunt61bc1732011-05-01 07:04:31 +00002264
John McCall31168b02011-06-15 23:02:42 +00002265 AggValueSlot AggSlot =
John McCall7f416cc2015-09-08 08:05:57 +00002266 AggValueSlot::forAddr(ThisPtr, Qualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +00002267 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00002268 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00002269 AggValueSlot::IsNotAliased);
Alexis Hunt61bc1732011-05-01 07:04:31 +00002270
2271 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
Alexis Hunt61bc1732011-05-01 07:04:31 +00002272
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002273 const CXXRecordDecl *ClassDecl = Ctor->getParent();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002274 if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002275 CXXDtorType Type =
2276 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
2277
2278 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
2279 ClassDecl->getDestructor(),
2280 ThisPtr, Type);
2281 }
2282}
Alexis Hunt61bc1732011-05-01 07:04:31 +00002283
Anders Carlsson27da15b2010-01-01 20:29:01 +00002284void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
2285 CXXDtorType Type,
Anders Carlssonf8a71f02010-05-02 23:29:11 +00002286 bool ForVirtualBase,
Douglas Gregor61535002013-01-31 05:50:40 +00002287 bool Delegating,
John McCall7f416cc2015-09-08 08:05:57 +00002288 Address This) {
Reid Kleckner6fe771a2013-12-13 00:53:54 +00002289 CGM.getCXXABI().EmitDestructorCall(*this, DD, Type, ForVirtualBase,
2290 Delegating, This);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002291}
2292
John McCall53cad2e2010-07-21 01:41:18 +00002293namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002294 struct CallLocalDtor final : EHScopeStack::Cleanup {
John McCall53cad2e2010-07-21 01:41:18 +00002295 const CXXDestructorDecl *Dtor;
John McCall7f416cc2015-09-08 08:05:57 +00002296 Address Addr;
John McCall53cad2e2010-07-21 01:41:18 +00002297
John McCall7f416cc2015-09-08 08:05:57 +00002298 CallLocalDtor(const CXXDestructorDecl *D, Address Addr)
John McCall53cad2e2010-07-21 01:41:18 +00002299 : Dtor(D), Addr(Addr) {}
2300
Craig Topper4f12f102014-03-12 06:41:41 +00002301 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall53cad2e2010-07-21 01:41:18 +00002302 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +00002303 /*ForVirtualBase=*/false,
2304 /*Delegating=*/false, Addr);
John McCall53cad2e2010-07-21 01:41:18 +00002305 }
2306 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002307} // end anonymous namespace
John McCall53cad2e2010-07-21 01:41:18 +00002308
John McCall8680f872010-07-21 06:29:51 +00002309void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
John McCall7f416cc2015-09-08 08:05:57 +00002310 Address Addr) {
John McCallcda666c2010-07-21 07:22:38 +00002311 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
John McCall8680f872010-07-21 06:29:51 +00002312}
2313
John McCall7f416cc2015-09-08 08:05:57 +00002314void CodeGenFunction::PushDestructorCleanup(QualType T, Address Addr) {
John McCallbd309292010-07-06 01:34:17 +00002315 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
2316 if (!ClassDecl) return;
2317 if (ClassDecl->hasTrivialDestructor()) return;
2318
2319 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCalla85af562011-04-28 02:15:35 +00002320 assert(D && D->isUsed() && "destructor not marked as used!");
John McCall8680f872010-07-21 06:29:51 +00002321 PushDestructorCleanup(D, Addr);
John McCallbd309292010-07-06 01:34:17 +00002322}
2323
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002324void CodeGenFunction::InitializeVTablePointer(const VPtr &Vptr) {
Anders Carlssone87fae92010-03-28 19:40:00 +00002325 // Compute the address point.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002326 llvm::Value *VTableAddressPoint =
2327 CGM.getCXXABI().getVTableAddressPointInStructor(
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002328 *this, Vptr.VTableClass, Vptr.Base, Vptr.NearestVBase);
2329
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002330 if (!VTableAddressPoint)
2331 return;
Anders Carlssone87fae92010-03-28 19:40:00 +00002332
Anders Carlsson6a0227d2010-04-20 16:22:16 +00002333 // Compute where to store the address point.
Craig Topper8a13c412014-05-21 05:09:00 +00002334 llvm::Value *VirtualOffset = nullptr;
Ken Dyckcfc332c2011-03-23 00:45:26 +00002335 CharUnits NonVirtualOffset = CharUnits::Zero();
Justin Bogner1cd11f12015-05-20 15:53:59 +00002336
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002337 if (CGM.getCXXABI().isVirtualOffsetNeededForVTableField(*this, Vptr)) {
Anders Carlsson91baecf2010-04-20 18:05:10 +00002338 // We need to use the virtual base offset offset because the virtual base
2339 // might have a different offset in the most derived class.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002340
2341 VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(
2342 *this, LoadCXXThisAddress(), Vptr.VTableClass, Vptr.NearestVBase);
2343 NonVirtualOffset = Vptr.OffsetFromNearestVBase;
Anders Carlsson91baecf2010-04-20 18:05:10 +00002344 } else {
Anders Carlssonc58fb552010-05-03 00:29:58 +00002345 // We can just use the base offset in the complete class.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002346 NonVirtualOffset = Vptr.Base.getBaseOffset();
Anders Carlsson91baecf2010-04-20 18:05:10 +00002347 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002348
Anders Carlssonc58fb552010-05-03 00:29:58 +00002349 // Apply the offsets.
John McCall7f416cc2015-09-08 08:05:57 +00002350 Address VTableField = LoadCXXThisAddress();
Justin Bogner1cd11f12015-05-20 15:53:59 +00002351
Ken Dyckcfc332c2011-03-23 00:45:26 +00002352 if (!NonVirtualOffset.isZero() || VirtualOffset)
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002353 VTableField = ApplyNonVirtualAndVirtualOffset(
2354 *this, VTableField, NonVirtualOffset, VirtualOffset, Vptr.VTableClass,
2355 Vptr.NearestVBase);
Anders Carlsson6a0227d2010-04-20 16:22:16 +00002356
Reid Kleckner8d585132014-12-03 21:00:21 +00002357 // Finally, store the address point. Use the same LLVM types as the field to
2358 // support optimization.
2359 llvm::Type *VTablePtrTy =
2360 llvm::FunctionType::get(CGM.Int32Ty, /*isVarArg=*/true)
2361 ->getPointerTo()
2362 ->getPointerTo();
2363 VTableField = Builder.CreateBitCast(VTableField, VTablePtrTy->getPointerTo());
2364 VTableAddressPoint = Builder.CreateBitCast(VTableAddressPoint, VTablePtrTy);
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002365
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002366 llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002367 CGM.DecorateInstructionWithTBAA(Store, CGM.getTBAAInfoForVTablePtr());
2368 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2369 CGM.getCodeGenOpts().StrictVTablePointers)
2370 CGM.DecorateInstructionWithInvariantGroup(Store, Vptr.VTableClass);
Anders Carlssone87fae92010-03-28 19:40:00 +00002371}
2372
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002373CodeGenFunction::VPtrsVector
2374CodeGenFunction::getVTablePointers(const CXXRecordDecl *VTableClass) {
2375 CodeGenFunction::VPtrsVector VPtrsResult;
2376 VisitedVirtualBasesSetTy VBases;
2377 getVTablePointers(BaseSubobject(VTableClass, CharUnits::Zero()),
2378 /*NearestVBase=*/nullptr,
2379 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
2380 /*BaseIsNonVirtualPrimaryBase=*/false, VTableClass, VBases,
2381 VPtrsResult);
2382 return VPtrsResult;
2383}
2384
2385void CodeGenFunction::getVTablePointers(BaseSubobject Base,
2386 const CXXRecordDecl *NearestVBase,
2387 CharUnits OffsetFromNearestVBase,
2388 bool BaseIsNonVirtualPrimaryBase,
2389 const CXXRecordDecl *VTableClass,
2390 VisitedVirtualBasesSetTy &VBases,
2391 VPtrsVector &Vptrs) {
Anders Carlssond5895932010-03-28 21:07:49 +00002392 // If this base is a non-virtual primary base the address point has already
2393 // been set.
2394 if (!BaseIsNonVirtualPrimaryBase) {
2395 // Initialize the vtable pointer for this base.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002396 VPtr Vptr = {Base, NearestVBase, OffsetFromNearestVBase, VTableClass};
2397 Vptrs.push_back(Vptr);
Anders Carlssond5895932010-03-28 21:07:49 +00002398 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002399
Anders Carlssond5895932010-03-28 21:07:49 +00002400 const CXXRecordDecl *RD = Base.getBase();
2401
2402 // Traverse bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00002403 for (const auto &I : RD->bases()) {
Anders Carlssond5895932010-03-28 21:07:49 +00002404 CXXRecordDecl *BaseDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00002405 = cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Anders Carlssond5895932010-03-28 21:07:49 +00002406
2407 // Ignore classes without a vtable.
2408 if (!BaseDecl->isDynamicClass())
2409 continue;
2410
Ken Dyck3fb4c892011-03-23 01:04:18 +00002411 CharUnits BaseOffset;
2412 CharUnits BaseOffsetFromNearestVBase;
Anders Carlsson948d3f42010-03-29 01:16:41 +00002413 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlssond5895932010-03-28 21:07:49 +00002414
Aaron Ballman574705e2014-03-13 15:41:46 +00002415 if (I.isVirtual()) {
Anders Carlssond5895932010-03-28 21:07:49 +00002416 // Check if we've visited this virtual base before.
David Blaikie82e95a32014-11-19 07:49:47 +00002417 if (!VBases.insert(BaseDecl).second)
Anders Carlssond5895932010-03-28 21:07:49 +00002418 continue;
2419
Justin Bogner1cd11f12015-05-20 15:53:59 +00002420 const ASTRecordLayout &Layout =
Anders Carlssond5895932010-03-28 21:07:49 +00002421 getContext().getASTRecordLayout(VTableClass);
2422
Ken Dyck3fb4c892011-03-23 01:04:18 +00002423 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
2424 BaseOffsetFromNearestVBase = CharUnits::Zero();
Anders Carlsson948d3f42010-03-29 01:16:41 +00002425 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlssond5895932010-03-28 21:07:49 +00002426 } else {
2427 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
2428
Ken Dyck16ffcac2011-03-24 01:21:01 +00002429 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
Justin Bogner1cd11f12015-05-20 15:53:59 +00002430 BaseOffsetFromNearestVBase =
Ken Dyck3fb4c892011-03-23 01:04:18 +00002431 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson948d3f42010-03-29 01:16:41 +00002432 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlssond5895932010-03-28 21:07:49 +00002433 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002434
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002435 getVTablePointers(
2436 BaseSubobject(BaseDecl, BaseOffset),
2437 I.isVirtual() ? BaseDecl : NearestVBase, BaseOffsetFromNearestVBase,
2438 BaseDeclIsNonVirtualPrimaryBase, VTableClass, VBases, Vptrs);
Anders Carlssond5895932010-03-28 21:07:49 +00002439 }
2440}
2441
2442void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
2443 // Ignore classes without a vtable.
Anders Carlsson1f9348c2010-03-26 04:39:42 +00002444 if (!RD->isDynamicClass())
Anders Carlsson27da15b2010-01-01 20:29:01 +00002445 return;
2446
Anders Carlssond5895932010-03-28 21:07:49 +00002447 // Initialize the vtable pointers for this class and all of its bases.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002448 if (CGM.getCXXABI().doStructorsInitializeVPtrs(RD))
2449 for (const VPtr &Vptr : getVTablePointers(RD))
2450 InitializeVTablePointer(Vptr);
Timur Iskhodzhanovb6487322013-10-09 18:16:58 +00002451
2452 if (RD->getNumVBases())
2453 CGM.getCXXABI().initializeHiddenVirtualInheritanceMembers(*this, RD);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002454}
Dan Gohman8fc50c22010-10-26 18:44:08 +00002455
John McCall7f416cc2015-09-08 08:05:57 +00002456llvm::Value *CodeGenFunction::GetVTablePtr(Address This,
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002457 llvm::Type *VTableTy,
2458 const CXXRecordDecl *RD) {
2459 Address VTablePtrSrc = Builder.CreateElementBitCast(This, VTableTy);
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002460 llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002461 CGM.DecorateInstructionWithTBAA(VTable, CGM.getTBAAInfoForVTablePtr());
2462
2463 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2464 CGM.getCodeGenOpts().StrictVTablePointers)
2465 CGM.DecorateInstructionWithInvariantGroup(VTable, RD);
2466
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002467 return VTable;
Dan Gohman8fc50c22010-10-26 18:44:08 +00002468}
Anders Carlssonc36783e2011-05-08 20:32:23 +00002469
Peter Collingbourned2926c92015-03-14 02:42:25 +00002470// If a class has a single non-virtual base and does not introduce or override
2471// virtual member functions or fields, it will have the same layout as its base.
2472// This function returns the least derived such class.
2473//
2474// Casting an instance of a base class to such a derived class is technically
2475// undefined behavior, but it is a relatively common hack for introducing member
2476// functions on class instances with specific properties (e.g. llvm::Operator)
2477// that works under most compilers and should not have security implications, so
2478// we allow it by default. It can be disabled with -fsanitize=cfi-cast-strict.
2479static const CXXRecordDecl *
2480LeastDerivedClassWithSameLayout(const CXXRecordDecl *RD) {
2481 if (!RD->field_empty())
2482 return RD;
2483
2484 if (RD->getNumVBases() != 0)
2485 return RD;
2486
2487 if (RD->getNumBases() != 1)
2488 return RD;
2489
2490 for (const CXXMethodDecl *MD : RD->methods()) {
2491 if (MD->isVirtual()) {
2492 // Virtual member functions are only ok if they are implicit destructors
2493 // because the implicit destructor will have the same semantics as the
2494 // base class's destructor if no fields are added.
2495 if (isa<CXXDestructorDecl>(MD) && MD->isImplicit())
2496 continue;
2497 return RD;
2498 }
2499 }
2500
2501 return LeastDerivedClassWithSameLayout(
2502 RD->bases_begin()->getType()->getAsCXXRecordDecl());
2503}
2504
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002505void CodeGenFunction::EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD,
2506 llvm::Value *VTable,
2507 SourceLocation Loc) {
Peter Collingbournefb532b92016-02-24 20:46:36 +00002508 if (CGM.getCodeGenOpts().WholeProgramVTables &&
Peter Collingbourne3afb2662016-04-28 17:09:37 +00002509 CGM.HasHiddenLTOVisibility(RD)) {
Peter Collingbournefb532b92016-02-24 20:46:36 +00002510 llvm::Metadata *MD =
2511 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002512 llvm::Value *TypeId =
Peter Collingbournefb532b92016-02-24 20:46:36 +00002513 llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD);
2514
2515 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002516 llvm::Value *TypeTest =
2517 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
2518 {CastedVTable, TypeId});
2519 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::assume), TypeTest);
Peter Collingbournefb532b92016-02-24 20:46:36 +00002520 }
2521
2522 if (SanOpts.has(SanitizerKind::CFIVCall))
2523 EmitVTablePtrCheckForCall(RD, VTable, CodeGenFunction::CFITCK_VCall, Loc);
2524}
2525
2526void CodeGenFunction::EmitVTablePtrCheckForCall(const CXXRecordDecl *RD,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002527 llvm::Value *VTable,
2528 CFITypeCheckKind TCK,
2529 SourceLocation Loc) {
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002530 if (!SanOpts.has(SanitizerKind::CFICastStrict))
Peter Collingbournefb532b92016-02-24 20:46:36 +00002531 RD = LeastDerivedClassWithSameLayout(RD);
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002532
Peter Collingbournefb532b92016-02-24 20:46:36 +00002533 EmitVTablePtrCheck(RD, VTable, TCK, Loc);
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002534}
2535
Peter Collingbourned2926c92015-03-14 02:42:25 +00002536void CodeGenFunction::EmitVTablePtrCheckForCast(QualType T,
2537 llvm::Value *Derived,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002538 bool MayBeNull,
2539 CFITypeCheckKind TCK,
2540 SourceLocation Loc) {
Peter Collingbourned2926c92015-03-14 02:42:25 +00002541 if (!getLangOpts().CPlusPlus)
2542 return;
2543
2544 auto *ClassTy = T->getAs<RecordType>();
2545 if (!ClassTy)
2546 return;
2547
2548 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassTy->getDecl());
2549
2550 if (!ClassDecl->isCompleteDefinition() || !ClassDecl->isDynamicClass())
2551 return;
2552
Peter Collingbourned2926c92015-03-14 02:42:25 +00002553 if (!SanOpts.has(SanitizerKind::CFICastStrict))
2554 ClassDecl = LeastDerivedClassWithSameLayout(ClassDecl);
2555
Hans Wennborgdcfba332015-10-06 23:40:43 +00002556 llvm::BasicBlock *ContBlock = nullptr;
Peter Collingbourned2926c92015-03-14 02:42:25 +00002557
2558 if (MayBeNull) {
2559 llvm::Value *DerivedNotNull =
2560 Builder.CreateIsNotNull(Derived, "cast.nonnull");
2561
2562 llvm::BasicBlock *CheckBlock = createBasicBlock("cast.check");
2563 ContBlock = createBasicBlock("cast.cont");
2564
2565 Builder.CreateCondBr(DerivedNotNull, CheckBlock, ContBlock);
2566
2567 EmitBlock(CheckBlock);
2568 }
2569
John McCall7f416cc2015-09-08 08:05:57 +00002570 llvm::Value *VTable =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002571 GetVTablePtr(Address(Derived, getPointerAlign()), Int8PtrTy, ClassDecl);
2572
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002573 EmitVTablePtrCheck(ClassDecl, VTable, TCK, Loc);
Peter Collingbourned2926c92015-03-14 02:42:25 +00002574
2575 if (MayBeNull) {
2576 Builder.CreateBr(ContBlock);
2577 EmitBlock(ContBlock);
2578 }
2579}
2580
2581void CodeGenFunction::EmitVTablePtrCheck(const CXXRecordDecl *RD,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002582 llvm::Value *VTable,
2583 CFITypeCheckKind TCK,
2584 SourceLocation Loc) {
Peter Collingbourne3afb2662016-04-28 17:09:37 +00002585 if (!CGM.getCodeGenOpts().SanitizeCfiCrossDso &&
2586 !CGM.HasHiddenLTOVisibility(RD))
2587 return;
2588
2589 std::string TypeName = RD->getQualifiedNameAsString();
2590 if (getContext().getSanitizerBlacklist().isBlacklistedType(TypeName))
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002591 return;
2592
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002593 SanitizerScope SanScope(this);
Peter Collingbournedc134532016-01-16 00:31:22 +00002594 llvm::SanitizerStatKind SSK;
2595 switch (TCK) {
2596 case CFITCK_VCall:
2597 SSK = llvm::SanStat_CFI_VCall;
2598 break;
2599 case CFITCK_NVCall:
2600 SSK = llvm::SanStat_CFI_NVCall;
2601 break;
2602 case CFITCK_DerivedCast:
2603 SSK = llvm::SanStat_CFI_DerivedCast;
2604 break;
2605 case CFITCK_UnrelatedCast:
2606 SSK = llvm::SanStat_CFI_UnrelatedCast;
2607 break;
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002608 case CFITCK_ICall:
2609 llvm_unreachable("not expecting CFITCK_ICall");
Peter Collingbournedc134532016-01-16 00:31:22 +00002610 }
2611 EmitSanitizerStatReport(SSK);
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002612
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002613 llvm::Metadata *MD =
2614 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002615 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002616
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002617 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002618 llvm::Value *TypeTest = Builder.CreateCall(
2619 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, TypeId});
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002620
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002621 SanitizerMask M;
2622 switch (TCK) {
2623 case CFITCK_VCall:
2624 M = SanitizerKind::CFIVCall;
2625 break;
2626 case CFITCK_NVCall:
2627 M = SanitizerKind::CFINVCall;
2628 break;
2629 case CFITCK_DerivedCast:
2630 M = SanitizerKind::CFIDerivedCast;
2631 break;
2632 case CFITCK_UnrelatedCast:
2633 M = SanitizerKind::CFIUnrelatedCast;
2634 break;
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002635 case CFITCK_ICall:
2636 llvm_unreachable("not expecting CFITCK_ICall");
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002637 }
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002638
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002639 llvm::Constant *StaticData[] = {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002640 llvm::ConstantInt::get(Int8Ty, TCK),
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002641 EmitCheckSourceLocation(Loc),
2642 EmitCheckTypeDescriptor(QualType(RD->getTypeForDecl(), 0)),
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002643 };
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002644
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002645 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
2646 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
2647 EmitCfiSlowPathCheck(M, TypeTest, CrossDsoTypeId, CastedVTable, StaticData);
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002648 return;
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002649 }
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002650
2651 if (CGM.getCodeGenOpts().SanitizeTrap.has(M)) {
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002652 EmitTrapCheck(TypeTest);
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002653 return;
2654 }
2655
2656 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
2657 CGM.getLLVMContext(),
2658 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002659 llvm::Value *ValidVtable = Builder.CreateCall(
2660 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, AllVtables});
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002661 EmitCheck(std::make_pair(TypeTest, M), SanitizerHandler::CFICheckFail,
2662 StaticData, {CastedVTable, ValidVtable});
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002663}
Anders Carlssonc36783e2011-05-08 20:32:23 +00002664
Peter Collingbourne0ca03632016-06-25 00:24:06 +00002665bool CodeGenFunction::ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD) {
2666 if (!CGM.getCodeGenOpts().WholeProgramVTables ||
2667 !SanOpts.has(SanitizerKind::CFIVCall) ||
2668 !CGM.getCodeGenOpts().SanitizeTrap.has(SanitizerKind::CFIVCall) ||
2669 !CGM.HasHiddenLTOVisibility(RD))
2670 return false;
2671
2672 std::string TypeName = RD->getQualifiedNameAsString();
2673 return !getContext().getSanitizerBlacklist().isBlacklistedType(TypeName);
2674}
2675
2676llvm::Value *CodeGenFunction::EmitVTableTypeCheckedLoad(
2677 const CXXRecordDecl *RD, llvm::Value *VTable, uint64_t VTableByteOffset) {
2678 SanitizerScope SanScope(this);
2679
2680 EmitSanitizerStatReport(llvm::SanStat_CFI_VCall);
2681
2682 llvm::Metadata *MD =
2683 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
2684 llvm::Value *TypeId = llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD);
2685
2686 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
2687 llvm::Value *CheckedLoad = Builder.CreateCall(
2688 CGM.getIntrinsic(llvm::Intrinsic::type_checked_load),
2689 {CastedVTable, llvm::ConstantInt::get(Int32Ty, VTableByteOffset),
2690 TypeId});
2691 llvm::Value *CheckResult = Builder.CreateExtractValue(CheckedLoad, 1);
2692
2693 EmitCheck(std::make_pair(CheckResult, SanitizerKind::CFIVCall),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002694 SanitizerHandler::CFICheckFail, nullptr, nullptr);
Peter Collingbourne0ca03632016-06-25 00:24:06 +00002695
2696 return Builder.CreateBitCast(
2697 Builder.CreateExtractValue(CheckedLoad, 0),
2698 cast<llvm::PointerType>(VTable->getType())->getElementType());
2699}
2700
Benjamin Kramer7463ed72013-08-25 22:46:27 +00002701bool
2702CodeGenFunction::CanDevirtualizeMemberFunctionCall(const Expr *Base,
2703 const CXXMethodDecl *MD) {
2704 // When building with -fapple-kext, all calls must go through the vtable since
2705 // the kernel linker can do runtime patching of vtables.
2706 if (getLangOpts().AppleKext)
2707 return false;
2708
Vedant Kumar2d38ae62016-10-20 18:44:14 +00002709 // If the member function is marked 'final', we know that it can't be
Richard Smitha2716862016-11-11 01:01:31 +00002710 // overridden and can therefore devirtualize it unless it's pure virtual.
Vedant Kumar2d38ae62016-10-20 18:44:14 +00002711 if (MD->hasAttr<FinalAttr>())
Richard Smitha2716862016-11-11 01:01:31 +00002712 return !MD->isPure();
Vedant Kumar2d38ae62016-10-20 18:44:14 +00002713
Richard Smith018ac392016-11-03 18:55:18 +00002714 // If the base expression (after skipping derived-to-base conversions) is a
2715 // class prvalue, then we can devirtualize.
2716 Base = Base->getBestDynamicClassTypeExpr();
2717 if (Base->isRValue() && Base->getType()->isRecordType())
2718 return true;
2719
Richard Smitha2716862016-11-11 01:01:31 +00002720 // If we don't even know what we would call, we can't devirtualize.
2721 const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
2722 if (!BestDynamicDecl)
2723 return false;
Anders Carlssonc36783e2011-05-08 20:32:23 +00002724
Richard Smitha2716862016-11-11 01:01:31 +00002725 // There may be a method corresponding to MD in a derived class.
2726 const CXXMethodDecl *DevirtualizedMethod =
2727 MD->getCorrespondingMethodInClass(BestDynamicDecl);
2728
2729 // If that method is pure virtual, we can't devirtualize. If this code is
2730 // reached, the result would be UB, not a direct call to the derived class
2731 // function, and we can't assume the derived class function is defined.
2732 if (DevirtualizedMethod->isPure())
2733 return false;
2734
2735 // If that method is marked final, we can devirtualize it.
2736 if (DevirtualizedMethod->hasAttr<FinalAttr>())
2737 return true;
Anders Carlssonc36783e2011-05-08 20:32:23 +00002738
2739 // Similarly, if the class itself is marked 'final' it can't be overridden
2740 // and we can therefore devirtualize the member function call.
Richard Smitha2716862016-11-11 01:01:31 +00002741 if (BestDynamicDecl->hasAttr<FinalAttr>())
Anders Carlssonc36783e2011-05-08 20:32:23 +00002742 return true;
2743
Anders Carlssonc36783e2011-05-08 20:32:23 +00002744 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
2745 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
2746 // This is a record decl. We know the type and can devirtualize it.
2747 return VD->getType()->isRecordType();
2748 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002749
Anders Carlssonc36783e2011-05-08 20:32:23 +00002750 return false;
2751 }
Benjamin Kramer7463ed72013-08-25 22:46:27 +00002752
2753 // We can devirtualize calls on an object accessed by a class member access
2754 // expression, since by C++11 [basic.life]p6 we know that it can't refer to
2755 // a derived class object constructed in the same location.
2756 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Base))
2757 if (const ValueDecl *VD = dyn_cast<ValueDecl>(ME->getMemberDecl()))
2758 return VD->getType()->isRecordType();
2759
Richard Smith018ac392016-11-03 18:55:18 +00002760 // Likewise for calls on an object accessed by a (non-reference) pointer to
2761 // member access.
2762 if (auto *BO = dyn_cast<BinaryOperator>(Base)) {
2763 if (BO->isPtrMemOp()) {
2764 auto *MPT = BO->getRHS()->getType()->castAs<MemberPointerType>();
2765 if (MPT->getPointeeType()->isRecordType())
2766 return true;
2767 }
2768 }
Anders Carlssonc36783e2011-05-08 20:32:23 +00002769
2770 // We can't devirtualize the call.
2771 return false;
2772}
2773
Faisal Vali571df122013-09-29 08:45:24 +00002774void CodeGenFunction::EmitForwardingCallToLambda(
2775 const CXXMethodDecl *callOperator,
2776 CallArgList &callArgs) {
Eli Friedman5b446882012-02-16 03:47:28 +00002777 // Get the address of the call operator.
John McCall8dda7b22012-07-07 06:41:13 +00002778 const CGFunctionInfo &calleeFnInfo =
2779 CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
John McCallb92ab1a2016-10-26 23:46:34 +00002780 llvm::Constant *calleePtr =
John McCall8dda7b22012-07-07 06:41:13 +00002781 CGM.GetAddrOfFunction(GlobalDecl(callOperator),
2782 CGM.getTypes().GetFunctionType(calleeFnInfo));
Eli Friedman5b446882012-02-16 03:47:28 +00002783
John McCall8dda7b22012-07-07 06:41:13 +00002784 // Prepare the return slot.
2785 const FunctionProtoType *FPT =
2786 callOperator->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00002787 QualType resultType = FPT->getReturnType();
John McCall8dda7b22012-07-07 06:41:13 +00002788 ReturnValueSlot returnSlot;
2789 if (!resultType->isVoidType() &&
2790 calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
John McCall47fb9502013-03-07 21:37:08 +00002791 !hasScalarEvaluationKind(calleeFnInfo.getReturnType()))
John McCall8dda7b22012-07-07 06:41:13 +00002792 returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
2793
2794 // We don't need to separately arrange the call arguments because
2795 // the call can't be variadic anyway --- it's impossible to forward
2796 // variadic arguments.
Justin Bogner1cd11f12015-05-20 15:53:59 +00002797
Eli Friedman5b446882012-02-16 03:47:28 +00002798 // Now emit our call.
John McCallb92ab1a2016-10-26 23:46:34 +00002799 auto callee = CGCallee::forDirect(calleePtr, callOperator);
2800 RValue RV = EmitCall(calleeFnInfo, callee, returnSlot, callArgs);
Eli Friedman5b446882012-02-16 03:47:28 +00002801
John McCall8dda7b22012-07-07 06:41:13 +00002802 // If necessary, copy the returned value into the slot.
2803 if (!resultType->isVoidType() && returnSlot.isNull())
2804 EmitReturnOfRValue(RV, resultType);
Eli Friedmanf5f4d2f2012-12-13 23:37:17 +00002805 else
2806 EmitBranchThroughCleanup(ReturnBlock);
Eli Friedman5b446882012-02-16 03:47:28 +00002807}
2808
Eli Friedman2495ab02012-02-25 02:48:22 +00002809void CodeGenFunction::EmitLambdaBlockInvokeBody() {
2810 const BlockDecl *BD = BlockInfo->getBlockDecl();
2811 const VarDecl *variable = BD->capture_begin()->getVariable();
2812 const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
2813
2814 // Start building arguments for forwarding call
2815 CallArgList CallArgs;
2816
2817 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
John McCall7f416cc2015-09-08 08:05:57 +00002818 Address ThisPtr = GetAddrOfBlockDecl(variable, false);
2819 CallArgs.add(RValue::get(ThisPtr.getPointer()), ThisType);
Eli Friedman2495ab02012-02-25 02:48:22 +00002820
2821 // Add the rest of the parameters.
David Majnemer59f77922016-06-24 04:05:48 +00002822 for (auto param : BD->parameters())
Nick Lewycky2d84e842013-10-02 02:29:49 +00002823 EmitDelegateCallArg(CallArgs, param, param->getLocStart());
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00002824
Justin Bogner1cd11f12015-05-20 15:53:59 +00002825 assert(!Lambda->isGenericLambda() &&
Faisal Vali571df122013-09-29 08:45:24 +00002826 "generic lambda interconversion to block not implemented");
2827 EmitForwardingCallToLambda(Lambda->getLambdaCallOperator(), CallArgs);
Eli Friedman2495ab02012-02-25 02:48:22 +00002828}
2829
2830void CodeGenFunction::EmitLambdaToBlockPointerBody(FunctionArgList &Args) {
John McCalldec348f72013-05-03 07:33:41 +00002831 if (cast<CXXMethodDecl>(CurCodeDecl)->isVariadic()) {
Eli Friedman2495ab02012-02-25 02:48:22 +00002832 // FIXME: Making this work correctly is nasty because it requires either
2833 // cloning the body of the call operator or making the call operator forward.
John McCalldec348f72013-05-03 07:33:41 +00002834 CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function");
Eli Friedman2495ab02012-02-25 02:48:22 +00002835 return;
2836 }
2837
Richard Smithb47c36f2013-11-05 09:12:18 +00002838 EmitFunctionBody(Args, cast<FunctionDecl>(CurGD.getDecl())->getBody());
Eli Friedman2495ab02012-02-25 02:48:22 +00002839}
2840
2841void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
2842 const CXXRecordDecl *Lambda = MD->getParent();
2843
2844 // Start building arguments for forwarding call
2845 CallArgList CallArgs;
2846
2847 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2848 llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
2849 CallArgs.add(RValue::get(ThisPtr), ThisType);
2850
2851 // Add the rest of the parameters.
David Majnemer59f77922016-06-24 04:05:48 +00002852 for (auto Param : MD->parameters())
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002853 EmitDelegateCallArg(CallArgs, Param, Param->getLocStart());
2854
Faisal Vali571df122013-09-29 08:45:24 +00002855 const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
2856 // For a generic lambda, find the corresponding call operator specialization
2857 // to which the call to the static-invoker shall be forwarded.
2858 if (Lambda->isGenericLambda()) {
2859 assert(MD->isFunctionTemplateSpecialization());
2860 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
2861 FunctionTemplateDecl *CallOpTemplate = CallOp->getDescribedFunctionTemplate();
Craig Topper8a13c412014-05-21 05:09:00 +00002862 void *InsertPos = nullptr;
Justin Bogner1cd11f12015-05-20 15:53:59 +00002863 FunctionDecl *CorrespondingCallOpSpecialization =
Craig Topper7e0daca2014-06-26 04:58:53 +00002864 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
Faisal Vali571df122013-09-29 08:45:24 +00002865 assert(CorrespondingCallOpSpecialization);
2866 CallOp = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
2867 }
2868 EmitForwardingCallToLambda(CallOp, CallArgs);
Eli Friedman2495ab02012-02-25 02:48:22 +00002869}
2870
Douglas Gregor355efbb2012-02-17 03:02:34 +00002871void CodeGenFunction::EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD) {
2872 if (MD->isVariadic()) {
Eli Friedman5b446882012-02-16 03:47:28 +00002873 // FIXME: Making this work correctly is nasty because it requires either
2874 // cloning the body of the call operator or making the call operator forward.
2875 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
Eli Friedman2495ab02012-02-25 02:48:22 +00002876 return;
Eli Friedman5b446882012-02-16 03:47:28 +00002877 }
2878
Douglas Gregor355efbb2012-02-17 03:02:34 +00002879 EmitLambdaDelegatingInvokeBody(MD);
Eli Friedman5a6d5072012-02-16 01:37:33 +00002880}