blob: 674a75696db5a0fc88f10b234c7a943d27c03060 [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,
Ivan A. Kosarev229a6d82017-10-13 16:38:32 +0000132 LValueBaseInfo *BaseInfo,
133 TBAAAccessInfo *TBAAInfo) {
John McCall7f416cc2015-09-08 08:05:57 +0000134 // Ask the ABI to compute the actual address.
135 llvm::Value *ptr =
136 CGM.getCXXABI().EmitMemberDataPointerAddress(*this, E, base,
137 memberPtr, memberPtrType);
138
139 QualType memberType = memberPtrType->getPointeeType();
Ivan A. Kosarev229a6d82017-10-13 16:38:32 +0000140 if (TBAAInfo)
141 *TBAAInfo = CGM.getTBAAAccessInfo(memberType);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000142 CharUnits memberAlign = getNaturalTypeAlignment(memberType, BaseInfo);
John McCall7f416cc2015-09-08 08:05:57 +0000143 memberAlign =
144 CGM.getDynamicOffsetAlignment(base.getAlignment(),
145 memberPtrType->getClass()->getAsCXXRecordDecl(),
146 memberAlign);
147 return Address(ptr, memberAlign);
148}
149
David Majnemerc1709d32015-06-23 07:31:11 +0000150CharUnits CodeGenModule::computeNonVirtualBaseClassOffset(
151 const CXXRecordDecl *DerivedClass, CastExpr::path_const_iterator Start,
152 CastExpr::path_const_iterator End) {
Ken Dycka1a4ae32011-03-22 00:53:26 +0000153 CharUnits Offset = CharUnits::Zero();
Justin Bogner1cd11f12015-05-20 15:53:59 +0000154
David Majnemerc1709d32015-06-23 07:31:11 +0000155 const ASTContext &Context = getContext();
Anders Carlssond829a022010-04-24 21:06:20 +0000156 const CXXRecordDecl *RD = DerivedClass;
Justin Bogner1cd11f12015-05-20 15:53:59 +0000157
John McCallcf142162010-08-07 06:22:56 +0000158 for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
Anders Carlssond829a022010-04-24 21:06:20 +0000159 const CXXBaseSpecifier *Base = *I;
160 assert(!Base->isVirtual() && "Should not see virtual bases here!");
161
162 // Get the layout.
163 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000164
165 const CXXRecordDecl *BaseDecl =
Anders Carlssond829a022010-04-24 21:06:20 +0000166 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Justin Bogner1cd11f12015-05-20 15:53:59 +0000167
Anders Carlssond829a022010-04-24 21:06:20 +0000168 // Add the offset.
Ken Dycka1a4ae32011-03-22 00:53:26 +0000169 Offset += Layout.getBaseClassOffset(BaseDecl);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000170
Anders Carlssond829a022010-04-24 21:06:20 +0000171 RD = BaseDecl;
172 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000173
Ken Dycka1a4ae32011-03-22 00:53:26 +0000174 return Offset;
Anders Carlssond829a022010-04-24 21:06:20 +0000175}
Anders Carlsson9a57c5a2009-09-12 04:27:24 +0000176
Anders Carlsson9150a2a2009-09-29 03:13:20 +0000177llvm::Constant *
Anders Carlsson8a64c1c2010-04-24 21:23:59 +0000178CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
John McCallcf142162010-08-07 06:22:56 +0000179 CastExpr::path_const_iterator PathBegin,
180 CastExpr::path_const_iterator PathEnd) {
181 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlsson8a64c1c2010-04-24 21:23:59 +0000182
Justin Bogner1cd11f12015-05-20 15:53:59 +0000183 CharUnits Offset =
David Majnemerc1709d32015-06-23 07:31:11 +0000184 computeNonVirtualBaseClassOffset(ClassDecl, PathBegin, PathEnd);
Ken Dycka1a4ae32011-03-22 00:53:26 +0000185 if (Offset.isZero())
Craig Topper8a13c412014-05-21 05:09:00 +0000186 return nullptr;
187
Justin Bogner1cd11f12015-05-20 15:53:59 +0000188 llvm::Type *PtrDiffTy =
Anders Carlsson8a64c1c2010-04-24 21:23:59 +0000189 Types.ConvertType(getContext().getPointerDiffType());
Justin Bogner1cd11f12015-05-20 15:53:59 +0000190
Ken Dycka1a4ae32011-03-22 00:53:26 +0000191 return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
Anders Carlsson9150a2a2009-09-29 03:13:20 +0000192}
193
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000194/// Gets the address of a direct base class within a complete object.
John McCall6ce74722010-02-16 04:15:37 +0000195/// This should only be used for (1) non-virtual bases or (2) virtual bases
196/// when the type is known to be complete (e.g. in complete destructors).
197///
198/// The object pointed to by 'This' is assumed to be non-null.
John McCall7f416cc2015-09-08 08:05:57 +0000199Address
200CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(Address This,
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000201 const CXXRecordDecl *Derived,
202 const CXXRecordDecl *Base,
203 bool BaseIsVirtual) {
John McCall6ce74722010-02-16 04:15:37 +0000204 // 'this' must be a pointer (in some address space) to Derived.
John McCall7f416cc2015-09-08 08:05:57 +0000205 assert(This.getElementType() == ConvertType(Derived));
John McCall6ce74722010-02-16 04:15:37 +0000206
207 // Compute the offset of the virtual base.
Ken Dyck6aa767c2011-03-22 01:21:15 +0000208 CharUnits Offset;
John McCall6ce74722010-02-16 04:15:37 +0000209 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000210 if (BaseIsVirtual)
Ken Dyck6aa767c2011-03-22 01:21:15 +0000211 Offset = Layout.getVBaseClassOffset(Base);
John McCall6ce74722010-02-16 04:15:37 +0000212 else
Ken Dyck6aa767c2011-03-22 01:21:15 +0000213 Offset = Layout.getBaseClassOffset(Base);
John McCall6ce74722010-02-16 04:15:37 +0000214
215 // Shift and cast down to the base type.
216 // TODO: for complete types, this should be possible with a GEP.
John McCall7f416cc2015-09-08 08:05:57 +0000217 Address V = This;
218 if (!Offset.isZero()) {
219 V = Builder.CreateElementBitCast(V, Int8Ty);
220 V = Builder.CreateConstInBoundsByteGEP(V, Offset);
John McCall6ce74722010-02-16 04:15:37 +0000221 }
John McCall7f416cc2015-09-08 08:05:57 +0000222 V = Builder.CreateElementBitCast(V, ConvertType(Base));
John McCall6ce74722010-02-16 04:15:37 +0000223
224 return V;
Anders Carlssone87fae92010-03-28 19:40:00 +0000225}
John McCall6ce74722010-02-16 04:15:37 +0000226
John McCall7f416cc2015-09-08 08:05:57 +0000227static Address
228ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, Address addr,
John McCall13a39c62012-08-01 05:04:58 +0000229 CharUnits nonVirtualOffset,
John McCall7f416cc2015-09-08 08:05:57 +0000230 llvm::Value *virtualOffset,
231 const CXXRecordDecl *derivedClass,
232 const CXXRecordDecl *nearestVBase) {
John McCall13a39c62012-08-01 05:04:58 +0000233 // Assert that we have something to do.
Craig Topper8a13c412014-05-21 05:09:00 +0000234 assert(!nonVirtualOffset.isZero() || virtualOffset != nullptr);
John McCall13a39c62012-08-01 05:04:58 +0000235
236 // Compute the offset from the static and dynamic components.
237 llvm::Value *baseOffset;
238 if (!nonVirtualOffset.isZero()) {
239 baseOffset = llvm::ConstantInt::get(CGF.PtrDiffTy,
240 nonVirtualOffset.getQuantity());
241 if (virtualOffset) {
242 baseOffset = CGF.Builder.CreateAdd(virtualOffset, baseOffset);
243 }
244 } else {
245 baseOffset = virtualOffset;
246 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000247
Anders Carlsson53cebd12010-04-20 16:03:35 +0000248 // Apply the base offset.
John McCall7f416cc2015-09-08 08:05:57 +0000249 llvm::Value *ptr = addr.getPointer();
John McCall13a39c62012-08-01 05:04:58 +0000250 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
251 ptr = CGF.Builder.CreateInBoundsGEP(ptr, baseOffset, "add.ptr");
John McCall7f416cc2015-09-08 08:05:57 +0000252
253 // If we have a virtual component, the alignment of the result will
254 // be relative only to the known alignment of that vbase.
255 CharUnits alignment;
256 if (virtualOffset) {
257 assert(nearestVBase && "virtual offset without vbase?");
258 alignment = CGF.CGM.getVBaseAlignment(addr.getAlignment(),
259 derivedClass, nearestVBase);
260 } else {
261 alignment = addr.getAlignment();
262 }
263 alignment = alignment.alignmentAtOffset(nonVirtualOffset);
264
265 return Address(ptr, alignment);
Anders Carlsson53cebd12010-04-20 16:03:35 +0000266}
267
John McCall7f416cc2015-09-08 08:05:57 +0000268Address CodeGenFunction::GetAddressOfBaseClass(
269 Address Value, const CXXRecordDecl *Derived,
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000270 CastExpr::path_const_iterator PathBegin,
271 CastExpr::path_const_iterator PathEnd, bool NullCheckValue,
272 SourceLocation Loc) {
John McCallcf142162010-08-07 06:22:56 +0000273 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssond829a022010-04-24 21:06:20 +0000274
John McCallcf142162010-08-07 06:22:56 +0000275 CastExpr::path_const_iterator Start = PathBegin;
Craig Topper8a13c412014-05-21 05:09:00 +0000276 const CXXRecordDecl *VBase = nullptr;
277
John McCall13a39c62012-08-01 05:04:58 +0000278 // Sema has done some convenient canonicalization here: if the
279 // access path involved any virtual steps, the conversion path will
280 // *start* with a step down to the correct virtual base subobject,
281 // and hence will not require any further steps.
Anders Carlssond829a022010-04-24 21:06:20 +0000282 if ((*Start)->isVirtual()) {
Justin Bogner1cd11f12015-05-20 15:53:59 +0000283 VBase =
Anders Carlssond829a022010-04-24 21:06:20 +0000284 cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
285 ++Start;
286 }
John McCall13a39c62012-08-01 05:04:58 +0000287
288 // Compute the static offset of the ultimate destination within its
289 // allocating subobject (the virtual base, if there is one, or else
290 // the "complete" object that we see).
David Majnemerc1709d32015-06-23 07:31:11 +0000291 CharUnits NonVirtualOffset = CGM.computeNonVirtualBaseClassOffset(
292 VBase ? VBase : Derived, Start, PathEnd);
Anders Carlssond829a022010-04-24 21:06:20 +0000293
John McCall13a39c62012-08-01 05:04:58 +0000294 // If there's a virtual step, we can sometimes "devirtualize" it.
295 // For now, that's limited to when the derived type is final.
296 // TODO: "devirtualize" this for accesses to known-complete objects.
297 if (VBase && Derived->hasAttr<FinalAttr>()) {
298 const ASTRecordLayout &layout = getContext().getASTRecordLayout(Derived);
299 CharUnits vBaseOffset = layout.getVBaseClassOffset(VBase);
300 NonVirtualOffset += vBaseOffset;
Craig Topper8a13c412014-05-21 05:09:00 +0000301 VBase = nullptr; // we no longer have a virtual step
John McCall13a39c62012-08-01 05:04:58 +0000302 }
303
Anders Carlssond829a022010-04-24 21:06:20 +0000304 // Get the base pointer type.
Justin Bogner1cd11f12015-05-20 15:53:59 +0000305 llvm::Type *BasePtrTy =
John McCallcf142162010-08-07 06:22:56 +0000306 ConvertType((PathEnd[-1])->getType())->getPointerTo();
John McCall13a39c62012-08-01 05:04:58 +0000307
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000308 QualType DerivedTy = getContext().getRecordType(Derived);
John McCall7f416cc2015-09-08 08:05:57 +0000309 CharUnits DerivedAlign = CGM.getClassPointerAlignment(Derived);
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000310
John McCall13a39c62012-08-01 05:04:58 +0000311 // If the static offset is zero and we don't have a virtual step,
312 // just do a bitcast; null checks are unnecessary.
Ken Dycka1a4ae32011-03-22 00:53:26 +0000313 if (NonVirtualOffset.isZero() && !VBase) {
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000314 if (sanitizePerformTypeCheck()) {
Vedant Kumar18348ea2017-02-17 23:22:55 +0000315 SanitizerSet SkippedChecks;
316 SkippedChecks.set(SanitizerKind::Null, !NullCheckValue);
John McCall7f416cc2015-09-08 08:05:57 +0000317 EmitTypeCheck(TCK_Upcast, Loc, Value.getPointer(),
Vedant Kumar18348ea2017-02-17 23:22:55 +0000318 DerivedTy, DerivedAlign, SkippedChecks);
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000319 }
Anders Carlssond829a022010-04-24 21:06:20 +0000320 return Builder.CreateBitCast(Value, BasePtrTy);
Craig Topper8a13c412014-05-21 05:09:00 +0000321 }
John McCall13a39c62012-08-01 05:04:58 +0000322
Craig Topper8a13c412014-05-21 05:09:00 +0000323 llvm::BasicBlock *origBB = nullptr;
324 llvm::BasicBlock *endBB = nullptr;
325
John McCall13a39c62012-08-01 05:04:58 +0000326 // Skip over the offset (and the vtable load) if we're supposed to
327 // null-check the pointer.
Anders Carlssond829a022010-04-24 21:06:20 +0000328 if (NullCheckValue) {
John McCall13a39c62012-08-01 05:04:58 +0000329 origBB = Builder.GetInsertBlock();
330 llvm::BasicBlock *notNullBB = createBasicBlock("cast.notnull");
331 endBB = createBasicBlock("cast.end");
Justin Bogner1cd11f12015-05-20 15:53:59 +0000332
John McCall7f416cc2015-09-08 08:05:57 +0000333 llvm::Value *isNull = Builder.CreateIsNull(Value.getPointer());
John McCall13a39c62012-08-01 05:04:58 +0000334 Builder.CreateCondBr(isNull, endBB, notNullBB);
335 EmitBlock(notNullBB);
Anders Carlssond829a022010-04-24 21:06:20 +0000336 }
337
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000338 if (sanitizePerformTypeCheck()) {
Vedant Kumar18348ea2017-02-17 23:22:55 +0000339 SanitizerSet SkippedChecks;
340 SkippedChecks.set(SanitizerKind::Null, true);
John McCall7f416cc2015-09-08 08:05:57 +0000341 EmitTypeCheck(VBase ? TCK_UpcastToVirtualBase : TCK_Upcast, Loc,
Vedant Kumar18348ea2017-02-17 23:22:55 +0000342 Value.getPointer(), DerivedTy, DerivedAlign, SkippedChecks);
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000343 }
344
John McCall13a39c62012-08-01 05:04:58 +0000345 // Compute the virtual offset.
Craig Topper8a13c412014-05-21 05:09:00 +0000346 llvm::Value *VirtualOffset = nullptr;
Anders Carlssona376b532011-01-29 03:18:56 +0000347 if (VBase) {
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000348 VirtualOffset =
349 CGM.getCXXABI().GetVirtualBaseClassOffset(*this, Value, Derived, VBase);
Anders Carlssona376b532011-01-29 03:18:56 +0000350 }
Anders Carlssond829a022010-04-24 21:06:20 +0000351
John McCall13a39c62012-08-01 05:04:58 +0000352 // Apply both offsets.
John McCall7f416cc2015-09-08 08:05:57 +0000353 Value = ApplyNonVirtualAndVirtualOffset(*this, Value, NonVirtualOffset,
354 VirtualOffset, Derived, VBase);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000355
John McCall13a39c62012-08-01 05:04:58 +0000356 // Cast to the destination type.
Anders Carlssond829a022010-04-24 21:06:20 +0000357 Value = Builder.CreateBitCast(Value, BasePtrTy);
John McCall13a39c62012-08-01 05:04:58 +0000358
359 // Build a phi if we needed a null check.
Anders Carlssond829a022010-04-24 21:06:20 +0000360 if (NullCheckValue) {
John McCall13a39c62012-08-01 05:04:58 +0000361 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
362 Builder.CreateBr(endBB);
363 EmitBlock(endBB);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000364
John McCall13a39c62012-08-01 05:04:58 +0000365 llvm::PHINode *PHI = Builder.CreatePHI(BasePtrTy, 2, "cast.result");
John McCall7f416cc2015-09-08 08:05:57 +0000366 PHI->addIncoming(Value.getPointer(), notNullBB);
John McCall13a39c62012-08-01 05:04:58 +0000367 PHI->addIncoming(llvm::Constant::getNullValue(BasePtrTy), origBB);
John McCall7f416cc2015-09-08 08:05:57 +0000368 Value = Address(PHI, Value.getAlignment());
Anders Carlssond829a022010-04-24 21:06:20 +0000369 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000370
Anders Carlssond829a022010-04-24 21:06:20 +0000371 return Value;
372}
373
John McCall7f416cc2015-09-08 08:05:57 +0000374Address
375CodeGenFunction::GetAddressOfDerivedClass(Address BaseAddr,
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000376 const CXXRecordDecl *Derived,
John McCallcf142162010-08-07 06:22:56 +0000377 CastExpr::path_const_iterator PathBegin,
378 CastExpr::path_const_iterator PathEnd,
Anders Carlsson8c793172009-11-23 17:57:54 +0000379 bool NullCheckValue) {
John McCallcf142162010-08-07 06:22:56 +0000380 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlsson8a64c1c2010-04-24 21:23:59 +0000381
Anders Carlsson8c793172009-11-23 17:57:54 +0000382 QualType DerivedTy =
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000383 getContext().getCanonicalType(getContext().getTagDeclType(Derived));
Chris Lattner2192fe52011-07-18 04:24:23 +0000384 llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
Richard Smith2c5868c2013-02-13 21:18:23 +0000385
Anders Carlsson600f7372010-01-31 01:43:37 +0000386 llvm::Value *NonVirtualOffset =
John McCallcf142162010-08-07 06:22:56 +0000387 CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000388
Anders Carlsson600f7372010-01-31 01:43:37 +0000389 if (!NonVirtualOffset) {
390 // No offset, we can just cast back.
John McCall7f416cc2015-09-08 08:05:57 +0000391 return Builder.CreateBitCast(BaseAddr, DerivedPtrTy);
Anders Carlsson600f7372010-01-31 01:43:37 +0000392 }
Craig Topper8a13c412014-05-21 05:09:00 +0000393
394 llvm::BasicBlock *CastNull = nullptr;
395 llvm::BasicBlock *CastNotNull = nullptr;
396 llvm::BasicBlock *CastEnd = nullptr;
397
Anders Carlsson8c793172009-11-23 17:57:54 +0000398 if (NullCheckValue) {
399 CastNull = createBasicBlock("cast.null");
400 CastNotNull = createBasicBlock("cast.notnull");
401 CastEnd = createBasicBlock("cast.end");
Justin Bogner1cd11f12015-05-20 15:53:59 +0000402
John McCall7f416cc2015-09-08 08:05:57 +0000403 llvm::Value *IsNull = Builder.CreateIsNull(BaseAddr.getPointer());
Anders Carlsson8c793172009-11-23 17:57:54 +0000404 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
405 EmitBlock(CastNotNull);
406 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000407
Anders Carlsson600f7372010-01-31 01:43:37 +0000408 // Apply the offset.
John McCall7f416cc2015-09-08 08:05:57 +0000409 llvm::Value *Value = Builder.CreateBitCast(BaseAddr.getPointer(), Int8PtrTy);
Eli Friedman87549262012-02-28 22:07:56 +0000410 Value = Builder.CreateGEP(Value, Builder.CreateNeg(NonVirtualOffset),
411 "sub.ptr");
Anders Carlsson600f7372010-01-31 01:43:37 +0000412
413 // Just cast.
414 Value = Builder.CreateBitCast(Value, DerivedPtrTy);
Anders Carlsson8c793172009-11-23 17:57:54 +0000415
John McCall7f416cc2015-09-08 08:05:57 +0000416 // Produce a PHI if we had a null-check.
Anders Carlsson8c793172009-11-23 17:57:54 +0000417 if (NullCheckValue) {
418 Builder.CreateBr(CastEnd);
419 EmitBlock(CastNull);
420 Builder.CreateBr(CastEnd);
421 EmitBlock(CastEnd);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000422
Jay Foad20c0f022011-03-30 11:28:58 +0000423 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
Anders Carlsson8c793172009-11-23 17:57:54 +0000424 PHI->addIncoming(Value, CastNotNull);
John McCall7f416cc2015-09-08 08:05:57 +0000425 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
Anders Carlsson8c793172009-11-23 17:57:54 +0000426 Value = PHI;
427 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000428
John McCall7f416cc2015-09-08 08:05:57 +0000429 return Address(Value, CGM.getClassPointerAlignment(Derived));
Anders Carlsson9a57c5a2009-09-12 04:27:24 +0000430}
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000431
432llvm::Value *CodeGenFunction::GetVTTParameter(GlobalDecl GD,
433 bool ForVirtualBase,
434 bool Delegating) {
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000435 if (!CGM.getCXXABI().NeedsVTTParameter(GD)) {
Anders Carlssone36a6b32010-01-02 01:01:18 +0000436 // This constructor/destructor does not need a VTT parameter.
Craig Topper8a13c412014-05-21 05:09:00 +0000437 return nullptr;
Anders Carlssone36a6b32010-01-02 01:01:18 +0000438 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000439
John McCalldec348f72013-05-03 07:33:41 +0000440 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CurCodeDecl)->getParent();
Anders Carlssone36a6b32010-01-02 01:01:18 +0000441 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
John McCall5c60a6f2010-02-18 19:59:28 +0000442
Anders Carlssone36a6b32010-01-02 01:01:18 +0000443 llvm::Value *VTT;
444
John McCall5c60a6f2010-02-18 19:59:28 +0000445 uint64_t SubVTTIndex;
446
Douglas Gregor61535002013-01-31 05:50:40 +0000447 if (Delegating) {
448 // If this is a delegating constructor call, just load the VTT.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000449 return LoadCXXVTT();
Douglas Gregor61535002013-01-31 05:50:40 +0000450 } else if (RD == Base) {
451 // If the record matches the base, this is the complete ctor/dtor
452 // variant calling the base variant in a class with virtual bases.
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000453 assert(!CGM.getCXXABI().NeedsVTTParameter(CurGD) &&
John McCall5c60a6f2010-02-18 19:59:28 +0000454 "doing no-op VTT offset in base dtor/ctor?");
Anders Carlsson4d205ba2010-05-02 23:33:10 +0000455 assert(!ForVirtualBase && "Can't have same class as virtual base!");
John McCall5c60a6f2010-02-18 19:59:28 +0000456 SubVTTIndex = 0;
457 } else {
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000458 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000459 CharUnits BaseOffset = ForVirtualBase ?
460 Layout.getVBaseClassOffset(Base) :
Ken Dyck16ffcac2011-03-24 01:21:01 +0000461 Layout.getBaseClassOffset(Base);
Anders Carlsson859b3062010-05-02 23:53:25 +0000462
Justin Bogner1cd11f12015-05-20 15:53:59 +0000463 SubVTTIndex =
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000464 CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
John McCall5c60a6f2010-02-18 19:59:28 +0000465 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
466 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000467
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000468 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
Anders Carlssone36a6b32010-01-02 01:01:18 +0000469 // A VTT parameter was passed to the constructor, use it.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000470 VTT = LoadCXXVTT();
471 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
Anders Carlssone36a6b32010-01-02 01:01:18 +0000472 } else {
473 // We're the complete constructor, so get the VTT by name.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000474 VTT = CGM.getVTables().GetAddrOfVTT(RD);
475 VTT = Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
Anders Carlssone36a6b32010-01-02 01:01:18 +0000476 }
477
478 return VTT;
479}
480
John McCall1d987562010-07-21 01:23:41 +0000481namespace {
John McCallf99a6312010-07-21 05:30:47 +0000482 /// Call the destructor for a direct base class.
David Blaikie7e70d682015-08-18 22:40:54 +0000483 struct CallBaseDtor final : EHScopeStack::Cleanup {
John McCallf99a6312010-07-21 05:30:47 +0000484 const CXXRecordDecl *BaseClass;
485 bool BaseIsVirtual;
486 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
487 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
John McCall1d987562010-07-21 01:23:41 +0000488
Craig Topper4f12f102014-03-12 06:41:41 +0000489 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallf99a6312010-07-21 05:30:47 +0000490 const CXXRecordDecl *DerivedClass =
491 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
492
493 const CXXDestructorDecl *D = BaseClass->getDestructor();
John McCall7f416cc2015-09-08 08:05:57 +0000494 Address Addr =
495 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThisAddress(),
John McCallf99a6312010-07-21 05:30:47 +0000496 DerivedClass, BaseClass,
497 BaseIsVirtual);
Douglas Gregor61535002013-01-31 05:50:40 +0000498 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual,
499 /*Delegating=*/false, Addr);
John McCall1d987562010-07-21 01:23:41 +0000500 }
501 };
John McCall769250e2010-09-17 02:31:44 +0000502
503 /// A visitor which checks whether an initializer uses 'this' in a
504 /// way which requires the vtable to be properly set.
Scott Douglass503fc392015-06-10 13:53:15 +0000505 struct DynamicThisUseChecker : ConstEvaluatedExprVisitor<DynamicThisUseChecker> {
506 typedef ConstEvaluatedExprVisitor<DynamicThisUseChecker> super;
John McCall769250e2010-09-17 02:31:44 +0000507
508 bool UsesThis;
509
Scott Douglass503fc392015-06-10 13:53:15 +0000510 DynamicThisUseChecker(const ASTContext &C) : super(C), UsesThis(false) {}
John McCall769250e2010-09-17 02:31:44 +0000511
512 // Black-list all explicit and implicit references to 'this'.
513 //
514 // Do we need to worry about external references to 'this' derived
515 // from arbitrary code? If so, then anything which runs arbitrary
516 // external code might potentially access the vtable.
Scott Douglass503fc392015-06-10 13:53:15 +0000517 void VisitCXXThisExpr(const CXXThisExpr *E) { UsesThis = true; }
John McCall769250e2010-09-17 02:31:44 +0000518 };
Hans Wennborgdcfba332015-10-06 23:40:43 +0000519} // end anonymous namespace
John McCall769250e2010-09-17 02:31:44 +0000520
521static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
522 DynamicThisUseChecker Checker(C);
Scott Douglass503fc392015-06-10 13:53:15 +0000523 Checker.Visit(Init);
John McCall769250e2010-09-17 02:31:44 +0000524 return Checker.UsesThis;
John McCall1d987562010-07-21 01:23:41 +0000525}
526
Justin Bogner1cd11f12015-05-20 15:53:59 +0000527static void EmitBaseInitializer(CodeGenFunction &CGF,
Anders Carlssonfb404882009-12-24 22:46:43 +0000528 const CXXRecordDecl *ClassDecl,
Alexis Hunt1d792652011-01-08 20:30:50 +0000529 CXXCtorInitializer *BaseInit,
Anders Carlssonfb404882009-12-24 22:46:43 +0000530 CXXCtorType CtorType) {
531 assert(BaseInit->isBaseInitializer() &&
532 "Must have base initializer!");
533
John McCall7f416cc2015-09-08 08:05:57 +0000534 Address ThisPtr = CGF.LoadCXXThisAddress();
Justin Bogner1cd11f12015-05-20 15:53:59 +0000535
Anders Carlssonfb404882009-12-24 22:46:43 +0000536 const Type *BaseType = BaseInit->getBaseClass();
537 CXXRecordDecl *BaseClassDecl =
538 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
539
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +0000540 bool isBaseVirtual = BaseInit->isBaseVirtual();
Anders Carlssonfb404882009-12-24 22:46:43 +0000541
542 // The base constructor doesn't construct virtual bases.
543 if (CtorType == Ctor_Base && isBaseVirtual)
544 return;
545
John McCall769250e2010-09-17 02:31:44 +0000546 // If the initializer for the base (other than the constructor
547 // itself) accesses 'this' in any way, we need to initialize the
548 // vtables.
549 if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
550 CGF.InitializeVTablePointers(ClassDecl);
551
John McCall6ce74722010-02-16 04:15:37 +0000552 // We can pretend to be a complete class because it only matters for
553 // virtual bases, and we only do virtual bases for complete ctors.
John McCall7f416cc2015-09-08 08:05:57 +0000554 Address V =
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000555 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
John McCallf99a6312010-07-21 05:30:47 +0000556 BaseClassDecl,
557 isBaseVirtual);
John McCall8d6fc952011-08-25 20:40:09 +0000558 AggValueSlot AggSlot =
John McCall7f416cc2015-09-08 08:05:57 +0000559 AggValueSlot::forAddr(V, Qualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +0000560 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +0000561 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000562 AggValueSlot::IsNotAliased);
John McCall7a626f62010-09-15 10:14:12 +0000563
564 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000565
566 if (CGF.CGM.getLangOpts().Exceptions &&
Anders Carlsson08ce5ed2011-02-20 00:20:27 +0000567 !BaseClassDecl->hasTrivialDestructor())
John McCallcda666c2010-07-21 07:22:38 +0000568 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
569 isBaseVirtual);
Anders Carlssonfb404882009-12-24 22:46:43 +0000570}
571
Richard Smith419bd092015-04-29 19:26:57 +0000572static bool isMemcpyEquivalentSpecialMember(const CXXMethodDecl *D) {
573 auto *CD = dyn_cast<CXXConstructorDecl>(D);
574 if (!(CD && CD->isCopyOrMoveConstructor()) &&
575 !D->isCopyAssignmentOperator() && !D->isMoveAssignmentOperator())
576 return false;
577
578 // We can emit a memcpy for a trivial copy or move constructor/assignment.
579 if (D->isTrivial() && !D->getParent()->mayInsertExtraPadding())
580 return true;
581
582 // We *must* emit a memcpy for a defaulted union copy or move op.
583 if (D->getParent()->isUnion() && D->isDefaulted())
584 return true;
585
586 return false;
587}
588
Alexey Bataev152c71f2015-07-14 07:55:48 +0000589static void EmitLValueForAnyFieldInitialization(CodeGenFunction &CGF,
590 CXXCtorInitializer *MemberInit,
591 LValue &LHS) {
592 FieldDecl *Field = MemberInit->getAnyMember();
593 if (MemberInit->isIndirectMemberInitializer()) {
594 // If we are initializing an anonymous union field, drill down to the field.
595 IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember();
596 for (const auto *I : IndirectField->chain())
597 LHS = CGF.EmitLValueForFieldInitialization(LHS, cast<FieldDecl>(I));
598 } else {
599 LHS = CGF.EmitLValueForFieldInitialization(LHS, Field);
600 }
601}
602
Anders Carlssonfb404882009-12-24 22:46:43 +0000603static void EmitMemberInitializer(CodeGenFunction &CGF,
604 const CXXRecordDecl *ClassDecl,
Alexis Hunt1d792652011-01-08 20:30:50 +0000605 CXXCtorInitializer *MemberInit,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000606 const CXXConstructorDecl *Constructor,
607 FunctionArgList &Args) {
David Blaikiea81d4102015-01-18 00:12:58 +0000608 ApplyDebugLocation Loc(CGF, MemberInit->getSourceLocation());
Francois Pichetd583da02010-12-04 09:14:42 +0000609 assert(MemberInit->isAnyMemberInitializer() &&
Anders Carlssonfb404882009-12-24 22:46:43 +0000610 "Must have member initializer!");
Richard Smith938f40b2011-06-11 17:19:42 +0000611 assert(MemberInit->getInit() && "Must have initializer!");
Justin Bogner1cd11f12015-05-20 15:53:59 +0000612
Anders Carlssonfb404882009-12-24 22:46:43 +0000613 // non-static data member initializers.
Francois Pichetd583da02010-12-04 09:14:42 +0000614 FieldDecl *Field = MemberInit->getAnyMember();
Eli Friedman6ae63022012-02-14 02:15:49 +0000615 QualType FieldType = Field->getType();
Anders Carlssonfb404882009-12-24 22:46:43 +0000616
617 llvm::Value *ThisPtr = CGF.LoadCXXThis();
Eli Friedman7f1ff602012-04-16 03:54:45 +0000618 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
Eli Friedmanf6d21842012-08-08 03:51:37 +0000619 LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
Eli Friedman7f1ff602012-04-16 03:54:45 +0000620
Alexey Bataev152c71f2015-07-14 07:55:48 +0000621 EmitLValueForAnyFieldInitialization(CGF, MemberInit, LHS);
Anders Carlssonfb404882009-12-24 22:46:43 +0000622
Eli Friedman6ae63022012-02-14 02:15:49 +0000623 // Special case: if we are in a copy or move constructor, and we are copying
624 // an array of PODs or classes with trivial copy constructors, ignore the
625 // AST and perform the copy we know is equivalent.
626 // FIXME: This is hacky at best... if we had a bit more explicit information
627 // in the AST, we could generalize it more easily.
628 const ConstantArrayType *Array
629 = CGF.getContext().getAsConstantArrayType(FieldType);
Jordan Rose54533f72013-08-07 16:16:48 +0000630 if (Array && Constructor->isDefaulted() &&
Eli Friedman6ae63022012-02-14 02:15:49 +0000631 Constructor->isCopyOrMoveConstructor()) {
632 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
Richard Smith993f25a2012-11-07 23:56:21 +0000633 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
Eli Friedman6ae63022012-02-14 02:15:49 +0000634 if (BaseElementTy.isPODType(CGF.getContext()) ||
Richard Smith419bd092015-04-29 19:26:57 +0000635 (CE && isMemcpyEquivalentSpecialMember(CE->getConstructor()))) {
David Majnemer1573d732014-10-15 04:54:54 +0000636 unsigned SrcArgIndex =
637 CGF.CGM.getCXXABI().getSrcArgforCopyCtor(Constructor, Args);
Eli Friedman6ae63022012-02-14 02:15:49 +0000638 llvm::Value *SrcPtr
639 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
Eli Friedman7f1ff602012-04-16 03:54:45 +0000640 LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
641 LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000642
Eli Friedman6ae63022012-02-14 02:15:49 +0000643 // Copy the aggregate.
644 CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000645 LHS.isVolatileQualified());
Alexey Bataev5d49b832015-07-08 07:31:02 +0000646 // Ensure that we destroy the objects if an exception is thrown later in
647 // the constructor.
648 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
649 if (CGF.needsEHCleanup(dtorKind))
650 CGF.pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
Eli Friedman6ae63022012-02-14 02:15:49 +0000651 return;
652 }
653 }
654
Richard Smith30e304e2016-12-14 00:03:17 +0000655 CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit());
Eli Friedman6ae63022012-02-14 02:15:49 +0000656}
657
John McCall7f416cc2015-09-08 08:05:57 +0000658void CodeGenFunction::EmitInitializerForField(FieldDecl *Field, LValue LHS,
Richard Smith30e304e2016-12-14 00:03:17 +0000659 Expr *Init) {
Eli Friedman6ae63022012-02-14 02:15:49 +0000660 QualType FieldType = Field->getType();
John McCall47fb9502013-03-07 21:37:08 +0000661 switch (getEvaluationKind(FieldType)) {
662 case TEK_Scalar:
John McCall31168b02011-06-15 23:02:42 +0000663 if (LHS.isSimple()) {
David Blaikie66e41972015-01-14 07:38:27 +0000664 EmitExprAsInit(Init, Field, LHS, false);
John McCall31168b02011-06-15 23:02:42 +0000665 } else {
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000666 RValue RHS = RValue::get(EmitScalarExpr(Init));
667 EmitStoreThroughLValue(RHS, LHS);
John McCall31168b02011-06-15 23:02:42 +0000668 }
John McCall47fb9502013-03-07 21:37:08 +0000669 break;
670 case TEK_Complex:
David Blaikie66e41972015-01-14 07:38:27 +0000671 EmitComplexExprIntoLValue(Init, LHS, /*isInit*/ true);
John McCall47fb9502013-03-07 21:37:08 +0000672 break;
673 case TEK_Aggregate: {
Richard Smith30e304e2016-12-14 00:03:17 +0000674 AggValueSlot Slot =
675 AggValueSlot::forLValue(LHS,
676 AggValueSlot::IsDestructed,
677 AggValueSlot::DoesNotNeedGCBarriers,
678 AggValueSlot::IsNotAliased);
679 EmitAggExpr(Init, Slot);
680 break;
Anders Carlssonfb404882009-12-24 22:46:43 +0000681 }
John McCall47fb9502013-03-07 21:37:08 +0000682 }
John McCall12cc42a2013-02-01 05:11:40 +0000683
684 // Ensure that we destroy this object if an exception is thrown
685 // later in the constructor.
686 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
687 if (needsEHCleanup(dtorKind))
688 pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
Anders Carlssonfb404882009-12-24 22:46:43 +0000689}
690
John McCallf8ff7b92010-02-23 00:48:20 +0000691/// Checks whether the given constructor is a valid subject for the
692/// complete-to-base constructor delegation optimization, i.e.
693/// emitting the complete constructor as a simple call to the base
694/// constructor.
Vedant Kumar7f809b22017-02-24 01:15:19 +0000695bool CodeGenFunction::IsConstructorDelegationValid(
696 const CXXConstructorDecl *Ctor) {
John McCallf8ff7b92010-02-23 00:48:20 +0000697
698 // Currently we disable the optimization for classes with virtual
699 // bases because (1) the addresses of parameter variables need to be
700 // consistent across all initializers but (2) the delegate function
701 // call necessarily creates a second copy of the parameter variable.
702 //
703 // The limiting example (purely theoretical AFAIK):
704 // struct A { A(int &c) { c++; } };
705 // struct B : virtual A {
706 // B(int count) : A(count) { printf("%d\n", count); }
707 // };
708 // ...although even this example could in principle be emitted as a
709 // delegation since the address of the parameter doesn't escape.
710 if (Ctor->getParent()->getNumVBases()) {
711 // TODO: white-list trivial vbase initializers. This case wouldn't
712 // be subject to the restrictions below.
713
714 // TODO: white-list cases where:
715 // - there are no non-reference parameters to the constructor
716 // - the initializers don't access any non-reference parameters
717 // - the initializers don't take the address of non-reference
718 // parameters
719 // - etc.
720 // If we ever add any of the above cases, remember that:
721 // - function-try-blocks will always blacklist this optimization
722 // - we need to perform the constructor prologue and cleanup in
723 // EmitConstructorBody.
724
725 return false;
726 }
727
728 // We also disable the optimization for variadic functions because
729 // it's impossible to "re-pass" varargs.
730 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
731 return false;
732
Alexis Hunt61bc1732011-05-01 07:04:31 +0000733 // FIXME: Decide if we can do a delegation of a delegating constructor.
734 if (Ctor->isDelegatingConstructor())
735 return false;
736
John McCallf8ff7b92010-02-23 00:48:20 +0000737 return true;
738}
739
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000740// Emit code in ctor (Prologue==true) or dtor (Prologue==false)
741// to poison the extra field paddings inserted under
742// -fsanitize-address-field-padding=1|2.
743void CodeGenFunction::EmitAsanPrologueOrEpilogue(bool Prologue) {
744 ASTContext &Context = getContext();
745 const CXXRecordDecl *ClassDecl =
746 Prologue ? cast<CXXConstructorDecl>(CurGD.getDecl())->getParent()
747 : cast<CXXDestructorDecl>(CurGD.getDecl())->getParent();
748 if (!ClassDecl->mayInsertExtraPadding()) return;
749
750 struct SizeAndOffset {
751 uint64_t Size;
752 uint64_t Offset;
753 };
754
755 unsigned PtrSize = CGM.getDataLayout().getPointerSizeInBits();
756 const ASTRecordLayout &Info = Context.getASTRecordLayout(ClassDecl);
757
758 // Populate sizes and offsets of fields.
759 SmallVector<SizeAndOffset, 16> SSV(Info.getFieldCount());
760 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i)
761 SSV[i].Offset =
762 Context.toCharUnitsFromBits(Info.getFieldOffset(i)).getQuantity();
763
764 size_t NumFields = 0;
765 for (const auto *Field : ClassDecl->fields()) {
766 const FieldDecl *D = Field;
767 std::pair<CharUnits, CharUnits> FieldInfo =
768 Context.getTypeInfoInChars(D->getType());
769 CharUnits FieldSize = FieldInfo.first;
770 assert(NumFields < SSV.size());
771 SSV[NumFields].Size = D->isBitField() ? 0 : FieldSize.getQuantity();
772 NumFields++;
773 }
774 assert(NumFields == SSV.size());
775 if (SSV.size() <= 1) return;
776
777 // We will insert calls to __asan_* run-time functions.
778 // LLVM AddressSanitizer pass may decide to inline them later.
779 llvm::Type *Args[2] = {IntPtrTy, IntPtrTy};
780 llvm::FunctionType *FTy =
781 llvm::FunctionType::get(CGM.VoidTy, Args, false);
782 llvm::Constant *F = CGM.CreateRuntimeFunction(
783 FTy, Prologue ? "__asan_poison_intra_object_redzone"
784 : "__asan_unpoison_intra_object_redzone");
785
786 llvm::Value *ThisPtr = LoadCXXThis();
787 ThisPtr = Builder.CreatePtrToInt(ThisPtr, IntPtrTy);
Kostya Serebryany64449212014-10-17 21:02:13 +0000788 uint64_t TypeSize = Info.getNonVirtualSize().getQuantity();
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000789 // For each field check if it has sufficient padding,
790 // if so (un)poison it with a call.
791 for (size_t i = 0; i < SSV.size(); i++) {
792 uint64_t AsanAlignment = 8;
793 uint64_t NextField = i == SSV.size() - 1 ? TypeSize : SSV[i + 1].Offset;
794 uint64_t PoisonSize = NextField - SSV[i].Offset - SSV[i].Size;
795 uint64_t EndOffset = SSV[i].Offset + SSV[i].Size;
796 if (PoisonSize < AsanAlignment || !SSV[i].Size ||
797 (NextField % AsanAlignment) != 0)
798 continue;
David Blaikie43f9bb72015-05-18 22:14:03 +0000799 Builder.CreateCall(
800 F, {Builder.CreateAdd(ThisPtr, Builder.getIntN(PtrSize, EndOffset)),
801 Builder.getIntN(PtrSize, PoisonSize)});
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000802 }
803}
804
John McCallb81884d2010-02-19 09:25:03 +0000805/// EmitConstructorBody - Emits the body of the current constructor.
806void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000807 EmitAsanPrologueOrEpilogue(true);
John McCallb81884d2010-02-19 09:25:03 +0000808 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
809 CXXCtorType CtorType = CurGD.getCtorType();
810
Reid Kleckner340ad862014-01-13 22:57:31 +0000811 assert((CGM.getTarget().getCXXABI().hasConstructorVariants() ||
812 CtorType == Ctor_Complete) &&
813 "can only generate complete ctor for this ABI");
814
John McCallf8ff7b92010-02-23 00:48:20 +0000815 // Before we go any further, try the complete->base constructor
816 // delegation optimization.
Timur Iskhodzhanovf32a3772012-04-20 08:05:00 +0000817 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
John McCallc8e01702013-04-16 22:48:15 +0000818 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000819 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args, Ctor->getLocEnd());
John McCallf8ff7b92010-02-23 00:48:20 +0000820 return;
821 }
822
Hans Wennborgdcfba332015-10-06 23:40:43 +0000823 const FunctionDecl *Definition = nullptr;
Richard Smith46bb5812014-08-01 01:56:39 +0000824 Stmt *Body = Ctor->getBody(Definition);
825 assert(Definition == Ctor && "emitting wrong constructor body");
John McCallb81884d2010-02-19 09:25:03 +0000826
John McCallf8ff7b92010-02-23 00:48:20 +0000827 // Enter the function-try-block before the constructor prologue if
828 // applicable.
John McCallf8ff7b92010-02-23 00:48:20 +0000829 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallf8ff7b92010-02-23 00:48:20 +0000830 if (IsTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000831 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000832
Justin Bogner66242d62015-04-23 23:06:47 +0000833 incrementProfileCounter(Body);
Justin Bogner81c22c22014-01-23 02:54:27 +0000834
Richard Smithcc1b96d2013-06-12 22:31:48 +0000835 RunCleanupsScope RunCleanups(*this);
John McCallb81884d2010-02-19 09:25:03 +0000836
John McCall88313032012-03-30 04:25:03 +0000837 // TODO: in restricted cases, we can emit the vbase initializers of
838 // a complete ctor and then delegate to the base ctor.
839
John McCallf8ff7b92010-02-23 00:48:20 +0000840 // Emit the constructor prologue, i.e. the base and member
841 // initializers.
Douglas Gregor94f9a482010-05-05 05:51:00 +0000842 EmitCtorPrologue(Ctor, CtorType, Args);
John McCallb81884d2010-02-19 09:25:03 +0000843
844 // Emit the body of the statement.
John McCallf8ff7b92010-02-23 00:48:20 +0000845 if (IsTryBody)
John McCallb81884d2010-02-19 09:25:03 +0000846 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
847 else if (Body)
848 EmitStmt(Body);
John McCallb81884d2010-02-19 09:25:03 +0000849
850 // Emit any cleanup blocks associated with the member or base
851 // initializers, which includes (along the exceptional path) the
852 // destructors for those members and bases that were fully
853 // constructed.
Richard Smithcc1b96d2013-06-12 22:31:48 +0000854 RunCleanups.ForceCleanup();
John McCallb81884d2010-02-19 09:25:03 +0000855
John McCallf8ff7b92010-02-23 00:48:20 +0000856 if (IsTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000857 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000858}
859
Lang Hamesbf122742013-02-17 07:22:09 +0000860namespace {
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000861 /// RAII object to indicate that codegen is copying the value representation
862 /// instead of the object representation. Useful when copying a struct or
863 /// class which has uninitialized members and we're only performing
864 /// lvalue-to-rvalue conversion on the object but not its members.
865 class CopyingValueRepresentation {
866 public:
867 explicit CopyingValueRepresentation(CodeGenFunction &CGF)
Alexey Samsonov035462c2014-10-30 19:33:44 +0000868 : CGF(CGF), OldSanOpts(CGF.SanOpts) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000869 CGF.SanOpts.set(SanitizerKind::Bool, false);
870 CGF.SanOpts.set(SanitizerKind::Enum, false);
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000871 }
872 ~CopyingValueRepresentation() {
873 CGF.SanOpts = OldSanOpts;
874 }
875 private:
876 CodeGenFunction &CGF;
Alexey Samsonova0416102014-11-11 01:26:14 +0000877 SanitizerSet OldSanOpts;
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000878 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000879} // end anonymous namespace
Hans Wennborgdcfba332015-10-06 23:40:43 +0000880
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000881namespace {
Lang Hamesbf122742013-02-17 07:22:09 +0000882 class FieldMemcpyizer {
883 public:
884 FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl,
885 const VarDecl *SrcRec)
Justin Bogner1cd11f12015-05-20 15:53:59 +0000886 : CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec),
Lang Hamesbf122742013-02-17 07:22:09 +0000887 RecLayout(CGF.getContext().getASTRecordLayout(ClassDecl)),
Craig Topper8a13c412014-05-21 05:09:00 +0000888 FirstField(nullptr), LastField(nullptr), FirstFieldOffset(0),
889 LastFieldOffset(0), LastAddedFieldIndex(0) {}
Lang Hamesbf122742013-02-17 07:22:09 +0000890
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000891 bool isMemcpyableField(FieldDecl *F) const {
892 // Never memcpy fields when we are adding poisoned paddings.
Alexey Samsonova0416102014-11-11 01:26:14 +0000893 if (CGF.getContext().getLangOpts().SanitizeAddressFieldPadding)
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000894 return false;
Lang Hamesbf122742013-02-17 07:22:09 +0000895 Qualifiers Qual = F->getType().getQualifiers();
896 if (Qual.hasVolatile() || Qual.hasObjCLifetime())
897 return false;
898 return true;
899 }
900
901 void addMemcpyableField(FieldDecl *F) {
Craig Topper8a13c412014-05-21 05:09:00 +0000902 if (!FirstField)
Lang Hamesbf122742013-02-17 07:22:09 +0000903 addInitialField(F);
904 else
905 addNextField(F);
906 }
907
David Majnemera586eb22014-10-10 18:57:10 +0000908 CharUnits getMemcpySize(uint64_t FirstByteOffset) const {
Lang Hamesbf122742013-02-17 07:22:09 +0000909 unsigned LastFieldSize =
910 LastField->isBitField() ?
911 LastField->getBitWidthValue(CGF.getContext()) :
Justin Bogner1cd11f12015-05-20 15:53:59 +0000912 CGF.getContext().getTypeSize(LastField->getType());
Lang Hamesbf122742013-02-17 07:22:09 +0000913 uint64_t MemcpySizeBits =
David Majnemera586eb22014-10-10 18:57:10 +0000914 LastFieldOffset + LastFieldSize - FirstByteOffset +
Lang Hamesbf122742013-02-17 07:22:09 +0000915 CGF.getContext().getCharWidth() - 1;
916 CharUnits MemcpySize =
917 CGF.getContext().toCharUnitsFromBits(MemcpySizeBits);
918 return MemcpySize;
919 }
920
921 void emitMemcpy() {
922 // Give the subclass a chance to bail out if it feels the memcpy isn't
923 // worth it (e.g. Hasn't aggregated enough data).
Craig Topper8a13c412014-05-21 05:09:00 +0000924 if (!FirstField) {
Lang Hamesbf122742013-02-17 07:22:09 +0000925 return;
926 }
927
David Majnemera586eb22014-10-10 18:57:10 +0000928 uint64_t FirstByteOffset;
Lang Hamesbf122742013-02-17 07:22:09 +0000929 if (FirstField->isBitField()) {
930 const CGRecordLayout &RL =
931 CGF.getTypes().getCGRecordLayout(FirstField->getParent());
932 const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField);
David Majnemera586eb22014-10-10 18:57:10 +0000933 // FirstFieldOffset is not appropriate for bitfields,
Ulrich Weigand73263d72015-07-13 11:52:14 +0000934 // we need to use the storage offset instead.
Ulrich Weigand03ce2a12015-07-10 17:30:00 +0000935 FirstByteOffset = CGF.getContext().toBits(BFInfo.StorageOffset);
Lang Hames1694e0d2013-02-27 04:14:49 +0000936 } else {
David Majnemera586eb22014-10-10 18:57:10 +0000937 FirstByteOffset = FirstFieldOffset;
Lang Hames1694e0d2013-02-27 04:14:49 +0000938 }
Lang Hamesbf122742013-02-17 07:22:09 +0000939
David Majnemera586eb22014-10-10 18:57:10 +0000940 CharUnits MemcpySize = getMemcpySize(FirstByteOffset);
Lang Hamesbf122742013-02-17 07:22:09 +0000941 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
John McCall7f416cc2015-09-08 08:05:57 +0000942 Address ThisPtr = CGF.LoadCXXThisAddress();
943 LValue DestLV = CGF.MakeAddrLValue(ThisPtr, RecordTy);
Lang Hamesbf122742013-02-17 07:22:09 +0000944 LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField);
945 llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec));
946 LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
947 LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField);
948
John McCall7f416cc2015-09-08 08:05:57 +0000949 emitMemcpyIR(Dest.isBitField() ? Dest.getBitFieldAddress() : Dest.getAddress(),
950 Src.isBitField() ? Src.getBitFieldAddress() : Src.getAddress(),
951 MemcpySize);
Lang Hamesbf122742013-02-17 07:22:09 +0000952 reset();
953 }
954
955 void reset() {
Craig Topper8a13c412014-05-21 05:09:00 +0000956 FirstField = nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +0000957 }
958
959 protected:
960 CodeGenFunction &CGF;
961 const CXXRecordDecl *ClassDecl;
962
963 private:
John McCall7f416cc2015-09-08 08:05:57 +0000964 void emitMemcpyIR(Address DestPtr, Address SrcPtr, CharUnits Size) {
965 llvm::PointerType *DPT = DestPtr.getType();
Lang Hamesbf122742013-02-17 07:22:09 +0000966 llvm::Type *DBP =
967 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), DPT->getAddressSpace());
968 DestPtr = CGF.Builder.CreateBitCast(DestPtr, DBP);
969
John McCall7f416cc2015-09-08 08:05:57 +0000970 llvm::PointerType *SPT = SrcPtr.getType();
Lang Hamesbf122742013-02-17 07:22:09 +0000971 llvm::Type *SBP =
972 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), SPT->getAddressSpace());
973 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, SBP);
974
John McCall7f416cc2015-09-08 08:05:57 +0000975 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity());
Lang Hamesbf122742013-02-17 07:22:09 +0000976 }
977
978 void addInitialField(FieldDecl *F) {
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000979 FirstField = F;
980 LastField = F;
981 FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex());
982 LastFieldOffset = FirstFieldOffset;
983 LastAddedFieldIndex = F->getFieldIndex();
984 }
Lang Hamesbf122742013-02-17 07:22:09 +0000985
986 void addNextField(FieldDecl *F) {
John McCall6054d5a2013-05-07 05:20:46 +0000987 // For the most part, the following invariant will hold:
988 // F->getFieldIndex() == LastAddedFieldIndex + 1
989 // The one exception is that Sema won't add a copy-initializer for an
990 // unnamed bitfield, which will show up here as a gap in the sequence.
991 assert(F->getFieldIndex() >= LastAddedFieldIndex + 1 &&
992 "Cannot aggregate fields out of order.");
Lang Hamesbf122742013-02-17 07:22:09 +0000993 LastAddedFieldIndex = F->getFieldIndex();
994
995 // The 'first' and 'last' fields are chosen by offset, rather than field
996 // index. This allows the code to support bitfields, as well as regular
997 // fields.
998 uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex());
999 if (FOffset < FirstFieldOffset) {
1000 FirstField = F;
1001 FirstFieldOffset = FOffset;
1002 } else if (FOffset > LastFieldOffset) {
1003 LastField = F;
1004 LastFieldOffset = FOffset;
1005 }
1006 }
1007
1008 const VarDecl *SrcRec;
1009 const ASTRecordLayout &RecLayout;
1010 FieldDecl *FirstField;
1011 FieldDecl *LastField;
1012 uint64_t FirstFieldOffset, LastFieldOffset;
1013 unsigned LastAddedFieldIndex;
1014 };
1015
1016 class ConstructorMemcpyizer : public FieldMemcpyizer {
1017 private:
Lang Hamesbf122742013-02-17 07:22:09 +00001018 /// Get source argument for copy constructor. Returns null if not a copy
David Majnemer196ac332014-09-11 23:05:02 +00001019 /// constructor.
1020 static const VarDecl *getTrivialCopySource(CodeGenFunction &CGF,
1021 const CXXConstructorDecl *CD,
Lang Hamesbf122742013-02-17 07:22:09 +00001022 FunctionArgList &Args) {
Jordan Rose54533f72013-08-07 16:16:48 +00001023 if (CD->isCopyOrMoveConstructor() && CD->isDefaulted())
David Majnemer196ac332014-09-11 23:05:02 +00001024 return Args[CGF.CGM.getCXXABI().getSrcArgforCopyCtor(CD, Args)];
Craig Topper8a13c412014-05-21 05:09:00 +00001025 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001026 }
1027
1028 // Returns true if a CXXCtorInitializer represents a member initialization
1029 // that can be rolled into a memcpy.
1030 bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const {
1031 if (!MemcpyableCtor)
1032 return false;
1033 FieldDecl *Field = MemberInit->getMember();
Craig Topper8a13c412014-05-21 05:09:00 +00001034 assert(Field && "No field for member init.");
Lang Hamesbf122742013-02-17 07:22:09 +00001035 QualType FieldType = Field->getType();
1036 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
1037
Richard Smith419bd092015-04-29 19:26:57 +00001038 // Bail out on non-memcpyable, not-trivially-copyable members.
1039 if (!(CE && isMemcpyEquivalentSpecialMember(CE->getConstructor())) &&
Lang Hamesbf122742013-02-17 07:22:09 +00001040 !(FieldType.isTriviallyCopyableType(CGF.getContext()) ||
1041 FieldType->isReferenceType()))
1042 return false;
1043
1044 // Bail out on volatile fields.
1045 if (!isMemcpyableField(Field))
1046 return false;
1047
1048 // Otherwise we're good.
1049 return true;
1050 }
1051
1052 public:
1053 ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD,
1054 FunctionArgList &Args)
David Majnemer196ac332014-09-11 23:05:02 +00001055 : FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CGF, CD, Args)),
Lang Hamesbf122742013-02-17 07:22:09 +00001056 ConstructorDecl(CD),
Jordan Rose54533f72013-08-07 16:16:48 +00001057 MemcpyableCtor(CD->isDefaulted() &&
Lang Hamesbf122742013-02-17 07:22:09 +00001058 CD->isCopyOrMoveConstructor() &&
1059 CGF.getLangOpts().getGC() == LangOptions::NonGC),
1060 Args(Args) { }
1061
1062 void addMemberInitializer(CXXCtorInitializer *MemberInit) {
1063 if (isMemberInitMemcpyable(MemberInit)) {
1064 AggregatedInits.push_back(MemberInit);
1065 addMemcpyableField(MemberInit->getMember());
1066 } else {
1067 emitAggregatedInits();
1068 EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit,
1069 ConstructorDecl, Args);
1070 }
1071 }
1072
1073 void emitAggregatedInits() {
1074 if (AggregatedInits.size() <= 1) {
1075 // This memcpy is too small to be worthwhile. Fall back on default
1076 // codegen.
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001077 if (!AggregatedInits.empty()) {
1078 CopyingValueRepresentation CVR(CGF);
Lang Hamesbf122742013-02-17 07:22:09 +00001079 EmitMemberInitializer(CGF, ConstructorDecl->getParent(),
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001080 AggregatedInits[0], ConstructorDecl, Args);
Alexey Bataev152c71f2015-07-14 07:55:48 +00001081 AggregatedInits.clear();
Lang Hamesbf122742013-02-17 07:22:09 +00001082 }
1083 reset();
1084 return;
1085 }
1086
1087 pushEHDestructors();
1088 emitMemcpy();
1089 AggregatedInits.clear();
1090 }
1091
1092 void pushEHDestructors() {
John McCall7f416cc2015-09-08 08:05:57 +00001093 Address ThisPtr = CGF.LoadCXXThisAddress();
Lang Hamesbf122742013-02-17 07:22:09 +00001094 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
John McCall7f416cc2015-09-08 08:05:57 +00001095 LValue LHS = CGF.MakeAddrLValue(ThisPtr, RecordTy);
Lang Hamesbf122742013-02-17 07:22:09 +00001096
1097 for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
Alexey Bataev152c71f2015-07-14 07:55:48 +00001098 CXXCtorInitializer *MemberInit = AggregatedInits[i];
1099 QualType FieldType = MemberInit->getAnyMember()->getType();
Lang Hamesbf122742013-02-17 07:22:09 +00001100 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
Alexey Bataev152c71f2015-07-14 07:55:48 +00001101 if (!CGF.needsEHCleanup(dtorKind))
1102 continue;
1103 LValue FieldLHS = LHS;
1104 EmitLValueForAnyFieldInitialization(CGF, MemberInit, FieldLHS);
1105 CGF.pushEHDestroy(dtorKind, FieldLHS.getAddress(), FieldType);
Lang Hamesbf122742013-02-17 07:22:09 +00001106 }
1107 }
1108
1109 void finish() {
1110 emitAggregatedInits();
1111 }
1112
1113 private:
1114 const CXXConstructorDecl *ConstructorDecl;
1115 bool MemcpyableCtor;
1116 FunctionArgList &Args;
1117 SmallVector<CXXCtorInitializer*, 16> AggregatedInits;
1118 };
1119
1120 class AssignmentMemcpyizer : public FieldMemcpyizer {
1121 private:
Lang Hamesbf122742013-02-17 07:22:09 +00001122 // Returns the memcpyable field copied by the given statement, if one
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001123 // exists. Otherwise returns null.
1124 FieldDecl *getMemcpyableField(Stmt *S) {
Lang Hamesbf122742013-02-17 07:22:09 +00001125 if (!AssignmentsMemcpyable)
Craig Topper8a13c412014-05-21 05:09:00 +00001126 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001127 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
1128 // Recognise trivial assignments.
1129 if (BO->getOpcode() != BO_Assign)
Craig Topper8a13c412014-05-21 05:09:00 +00001130 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001131 MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS());
1132 if (!ME)
Craig Topper8a13c412014-05-21 05:09:00 +00001133 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001134 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1135 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001136 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001137 Stmt *RHS = BO->getRHS();
1138 if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS))
1139 RHS = EC->getSubExpr();
1140 if (!RHS)
Craig Topper8a13c412014-05-21 05:09:00 +00001141 return nullptr;
Warren Ristow8d17b402017-02-02 17:53:34 +00001142 if (MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS)) {
1143 if (ME2->getMemberDecl() == Field)
1144 return Field;
1145 }
1146 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001147 } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) {
1148 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl());
Richard Smith419bd092015-04-29 19:26:57 +00001149 if (!(MD && isMemcpyEquivalentSpecialMember(MD)))
Craig Topper8a13c412014-05-21 05:09:00 +00001150 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001151 MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument());
1152 if (!IOA)
Craig Topper8a13c412014-05-21 05:09:00 +00001153 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001154 FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl());
1155 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001156 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001157 MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0));
1158 if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl()))
Craig Topper8a13c412014-05-21 05:09:00 +00001159 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001160 return Field;
1161 } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1162 FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1163 if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy)
Craig Topper8a13c412014-05-21 05:09:00 +00001164 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001165 Expr *DstPtr = CE->getArg(0);
1166 if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr))
1167 DstPtr = DC->getSubExpr();
1168 UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr);
1169 if (!DUO || DUO->getOpcode() != UO_AddrOf)
Craig Topper8a13c412014-05-21 05:09:00 +00001170 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001171 MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr());
1172 if (!ME)
Craig Topper8a13c412014-05-21 05:09:00 +00001173 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001174 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1175 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001176 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001177 Expr *SrcPtr = CE->getArg(1);
1178 if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr))
1179 SrcPtr = SC->getSubExpr();
1180 UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr);
1181 if (!SUO || SUO->getOpcode() != UO_AddrOf)
Craig Topper8a13c412014-05-21 05:09:00 +00001182 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001183 MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr());
1184 if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl()))
Craig Topper8a13c412014-05-21 05:09:00 +00001185 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001186 return Field;
1187 }
1188
Craig Topper8a13c412014-05-21 05:09:00 +00001189 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001190 }
1191
1192 bool AssignmentsMemcpyable;
1193 SmallVector<Stmt*, 16> AggregatedStmts;
1194
1195 public:
Lang Hamesbf122742013-02-17 07:22:09 +00001196 AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD,
1197 FunctionArgList &Args)
1198 : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]),
1199 AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) {
1200 assert(Args.size() == 2);
1201 }
1202
1203 void emitAssignment(Stmt *S) {
1204 FieldDecl *F = getMemcpyableField(S);
1205 if (F) {
1206 addMemcpyableField(F);
1207 AggregatedStmts.push_back(S);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001208 } else {
Lang Hamesbf122742013-02-17 07:22:09 +00001209 emitAggregatedStmts();
1210 CGF.EmitStmt(S);
1211 }
1212 }
1213
1214 void emitAggregatedStmts() {
1215 if (AggregatedStmts.size() <= 1) {
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001216 if (!AggregatedStmts.empty()) {
1217 CopyingValueRepresentation CVR(CGF);
1218 CGF.EmitStmt(AggregatedStmts[0]);
1219 }
Lang Hamesbf122742013-02-17 07:22:09 +00001220 reset();
1221 }
1222
1223 emitMemcpy();
1224 AggregatedStmts.clear();
1225 }
1226
1227 void finish() {
1228 emitAggregatedStmts();
1229 }
1230 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00001231} // end anonymous namespace
Lang Hamesbf122742013-02-17 07:22:09 +00001232
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001233static bool isInitializerOfDynamicClass(const CXXCtorInitializer *BaseInit) {
1234 const Type *BaseType = BaseInit->getBaseClass();
1235 const auto *BaseClassDecl =
1236 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
1237 return BaseClassDecl->isDynamicClass();
1238}
1239
Anders Carlssonfb404882009-12-24 22:46:43 +00001240/// EmitCtorPrologue - This routine generates necessary code to initialize
1241/// base classes and non-static data members belonging to this constructor.
Anders Carlssonfb404882009-12-24 22:46:43 +00001242void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001243 CXXCtorType CtorType,
1244 FunctionArgList &Args) {
Alexis Hunt61bc1732011-05-01 07:04:31 +00001245 if (CD->isDelegatingConstructor())
1246 return EmitDelegatingCXXConstructorCall(CD, Args);
1247
Anders Carlssonfb404882009-12-24 22:46:43 +00001248 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlsson5dc86332010-02-02 19:58:43 +00001249
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001250 CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
1251 E = CD->init_end();
1252
Craig Topper8a13c412014-05-21 05:09:00 +00001253 llvm::BasicBlock *BaseCtorContinueBB = nullptr;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001254 if (ClassDecl->getNumVBases() &&
1255 !CGM.getTarget().getCXXABI().hasConstructorVariants()) {
1256 // The ABIs that don't have constructor variants need to put a branch
1257 // before the virtual base initialization code.
Reid Kleckner7810af02013-06-19 15:20:38 +00001258 BaseCtorContinueBB =
1259 CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this, ClassDecl);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001260 assert(BaseCtorContinueBB);
1261 }
1262
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001263 llvm::Value *const OldThis = CXXThisValue;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001264 // Virtual base initializers first.
1265 for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001266 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1267 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1268 isInitializerOfDynamicClass(*B))
1269 CXXThisValue = Builder.CreateInvariantGroupBarrier(LoadCXXThis());
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001270 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
1271 }
1272
1273 if (BaseCtorContinueBB) {
1274 // Complete object handler should continue to the remaining initializers.
1275 Builder.CreateBr(BaseCtorContinueBB);
1276 EmitBlock(BaseCtorContinueBB);
1277 }
1278
1279 // Then, non-virtual base initializers.
1280 for (; B != E && (*B)->isBaseInitializer(); B++) {
1281 assert(!(*B)->isBaseVirtual());
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001282
1283 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1284 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1285 isInitializerOfDynamicClass(*B))
1286 CXXThisValue = Builder.CreateInvariantGroupBarrier(LoadCXXThis());
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001287 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
Anders Carlssonfb404882009-12-24 22:46:43 +00001288 }
1289
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001290 CXXThisValue = OldThis;
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001291
Anders Carlssond5895932010-03-28 21:07:49 +00001292 InitializeVTablePointers(ClassDecl);
Anders Carlsson5dc86332010-02-02 19:58:43 +00001293
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001294 // And finally, initialize class members.
John McCall7f416cc2015-09-08 08:05:57 +00001295 FieldConstructionScope FCS(*this, LoadCXXThisAddress());
Lang Hamesbf122742013-02-17 07:22:09 +00001296 ConstructorMemcpyizer CM(*this, CD, Args);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001297 for (; B != E; B++) {
1298 CXXCtorInitializer *Member = (*B);
1299 assert(!Member->isBaseInitializer());
1300 assert(Member->isAnyMemberInitializer() &&
1301 "Delegating initializer on non-delegating constructor");
1302 CM.addMemberInitializer(Member);
1303 }
Lang Hamesbf122742013-02-17 07:22:09 +00001304 CM.finish();
Anders Carlssonfb404882009-12-24 22:46:43 +00001305}
1306
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001307static bool
1308FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
1309
1310static bool
Justin Bogner1cd11f12015-05-20 15:53:59 +00001311HasTrivialDestructorBody(ASTContext &Context,
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001312 const CXXRecordDecl *BaseClassDecl,
1313 const CXXRecordDecl *MostDerivedClassDecl)
1314{
1315 // If the destructor is trivial we don't have to check anything else.
1316 if (BaseClassDecl->hasTrivialDestructor())
1317 return true;
1318
1319 if (!BaseClassDecl->getDestructor()->hasTrivialBody())
1320 return false;
1321
1322 // Check fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001323 for (const auto *Field : BaseClassDecl->fields())
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001324 if (!FieldHasTrivialDestructorBody(Context, Field))
1325 return false;
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001326
1327 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001328 for (const auto &I : BaseClassDecl->bases()) {
1329 if (I.isVirtual())
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001330 continue;
1331
1332 const CXXRecordDecl *NonVirtualBase =
Aaron Ballman574705e2014-03-13 15:41:46 +00001333 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001334 if (!HasTrivialDestructorBody(Context, NonVirtualBase,
1335 MostDerivedClassDecl))
1336 return false;
1337 }
1338
1339 if (BaseClassDecl == MostDerivedClassDecl) {
1340 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00001341 for (const auto &I : BaseClassDecl->vbases()) {
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001342 const CXXRecordDecl *VirtualBase =
Aaron Ballman445a9392014-03-13 16:15:17 +00001343 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001344 if (!HasTrivialDestructorBody(Context, VirtualBase,
1345 MostDerivedClassDecl))
Justin Bogner1cd11f12015-05-20 15:53:59 +00001346 return false;
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001347 }
1348 }
1349
1350 return true;
1351}
1352
1353static bool
1354FieldHasTrivialDestructorBody(ASTContext &Context,
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001355 const FieldDecl *Field)
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001356{
1357 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
1358
1359 const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
1360 if (!RT)
1361 return true;
Justin Bogner1cd11f12015-05-20 15:53:59 +00001362
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001363 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Davide Italiano982bbf42015-06-26 00:18:35 +00001364
1365 // The destructor for an implicit anonymous union member is never invoked.
1366 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
1367 return false;
1368
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001369 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
1370}
1371
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001372/// CanSkipVTablePointerInitialization - Check whether we need to initialize
1373/// any vtable pointers before calling this destructor.
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001374static bool CanSkipVTablePointerInitialization(CodeGenFunction &CGF,
Anders Carlssond6f15182011-05-16 04:08:36 +00001375 const CXXDestructorDecl *Dtor) {
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001376 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1377 if (!ClassDecl->isDynamicClass())
1378 return true;
1379
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001380 if (!Dtor->hasTrivialBody())
1381 return false;
1382
1383 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001384 for (const auto *Field : ClassDecl->fields())
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001385 if (!FieldHasTrivialDestructorBody(CGF.getContext(), Field))
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001386 return false;
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001387
1388 return true;
1389}
1390
John McCallb81884d2010-02-19 09:25:03 +00001391/// EmitDestructorBody - Emits the body of the current destructor.
1392void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
1393 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
1394 CXXDtorType DtorType = CurGD.getDtorType();
1395
Richard Smithdf054d32017-02-25 23:53:05 +00001396 // For an abstract class, non-base destructors are never used (and can't
1397 // be emitted in general, because vbase dtors may not have been validated
1398 // by Sema), but the Itanium ABI doesn't make them optional and Clang may
1399 // in fact emit references to them from other compilations, so emit them
1400 // as functions containing a trap instruction.
1401 if (DtorType != Dtor_Base && Dtor->getParent()->isAbstract()) {
1402 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
1403 TrapCall->setDoesNotReturn();
1404 TrapCall->setDoesNotThrow();
1405 Builder.CreateUnreachable();
1406 Builder.ClearInsertionPoint();
1407 return;
1408 }
1409
Justin Bognerfb298222015-05-20 16:16:23 +00001410 Stmt *Body = Dtor->getBody();
1411 if (Body)
1412 incrementProfileCounter(Body);
1413
John McCallf99a6312010-07-21 05:30:47 +00001414 // The call to operator delete in a deleting destructor happens
1415 // outside of the function-try-block, which means it's always
1416 // possible to delegate the destructor body to the complete
1417 // destructor. Do so.
1418 if (DtorType == Dtor_Deleting) {
Richard Smith5b349582017-10-13 01:55:36 +00001419 RunCleanupsScope DtorEpilogue(*this);
John McCallf99a6312010-07-21 05:30:47 +00001420 EnterDtorCleanups(Dtor, Dtor_Deleting);
Richard Smith5b349582017-10-13 01:55:36 +00001421 if (HaveInsertPoint())
1422 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
1423 /*Delegating=*/false, LoadCXXThisAddress());
John McCallf99a6312010-07-21 05:30:47 +00001424 return;
1425 }
1426
John McCallb81884d2010-02-19 09:25:03 +00001427 // If the body is a function-try-block, enter the try before
John McCallf99a6312010-07-21 05:30:47 +00001428 // anything else.
1429 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallb81884d2010-02-19 09:25:03 +00001430 if (isTryBody)
John McCallb609d3f2010-07-07 06:56:46 +00001431 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00001432 EmitAsanPrologueOrEpilogue(false);
John McCallb81884d2010-02-19 09:25:03 +00001433
John McCallf99a6312010-07-21 05:30:47 +00001434 // Enter the epilogue cleanups.
1435 RunCleanupsScope DtorEpilogue(*this);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001436
John McCallb81884d2010-02-19 09:25:03 +00001437 // If this is the complete variant, just invoke the base variant;
1438 // the epilogue will destruct the virtual bases. But we can't do
1439 // this optimization if the body is a function-try-block, because
Justin Bogner1cd11f12015-05-20 15:53:59 +00001440 // we'd introduce *two* handler blocks. In the Microsoft ABI, we
Reid Klecknere7de47e2013-07-22 13:51:44 +00001441 // always delegate because we might not have a definition in this TU.
John McCallf99a6312010-07-21 05:30:47 +00001442 switch (DtorType) {
Saleem Abdulrasool8de4e872017-02-02 05:45:43 +00001443 case Dtor_Comdat: llvm_unreachable("not expecting a COMDAT");
John McCallf99a6312010-07-21 05:30:47 +00001444 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
1445
1446 case Dtor_Complete:
Reid Klecknere7de47e2013-07-22 13:51:44 +00001447 assert((Body || getTarget().getCXXABI().isMicrosoft()) &&
1448 "can't emit a dtor without a body for non-Microsoft ABIs");
1449
John McCallf99a6312010-07-21 05:30:47 +00001450 // Enter the cleanup scopes for virtual bases.
1451 EnterDtorCleanups(Dtor, Dtor_Complete);
1452
Reid Klecknere7de47e2013-07-22 13:51:44 +00001453 if (!isTryBody) {
John McCallf99a6312010-07-21 05:30:47 +00001454 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
John McCall7f416cc2015-09-08 08:05:57 +00001455 /*Delegating=*/false, LoadCXXThisAddress());
John McCallf99a6312010-07-21 05:30:47 +00001456 break;
1457 }
Saleem Abdulrasool8de4e872017-02-02 05:45:43 +00001458
John McCallf99a6312010-07-21 05:30:47 +00001459 // Fallthrough: act like we're in the base variant.
Saleem Abdulrasool8de4e872017-02-02 05:45:43 +00001460 LLVM_FALLTHROUGH;
Justin Bogner1cd11f12015-05-20 15:53:59 +00001461
John McCallf99a6312010-07-21 05:30:47 +00001462 case Dtor_Base:
Reid Klecknere7de47e2013-07-22 13:51:44 +00001463 assert(Body);
1464
John McCallf99a6312010-07-21 05:30:47 +00001465 // Enter the cleanup scopes for fields and non-virtual bases.
1466 EnterDtorCleanups(Dtor, Dtor_Base);
1467
1468 // Initialize the vtable pointers before entering the body.
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001469 if (!CanSkipVTablePointerInitialization(*this, Dtor)) {
1470 // Insert the llvm.invariant.group.barrier intrinsic before initializing
1471 // the vptrs to cancel any previous assumptions we might have made.
1472 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1473 CGM.getCodeGenOpts().OptimizationLevel > 0)
1474 CXXThisValue = Builder.CreateInvariantGroupBarrier(LoadCXXThis());
1475 InitializeVTablePointers(Dtor->getParent());
1476 }
John McCallf99a6312010-07-21 05:30:47 +00001477
1478 if (isTryBody)
1479 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
1480 else if (Body)
1481 EmitStmt(Body);
1482 else {
1483 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
1484 // nothing to do besides what's in the epilogue
1485 }
Fariborz Jahanian0c12ed12011-02-02 23:12:46 +00001486 // -fapple-kext must inline any call to this dtor into
1487 // the caller's body.
Richard Smith9c6890a2012-11-01 22:30:59 +00001488 if (getLangOpts().AppleKext)
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00001489 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
Naomi Musgravee50cb9b2015-08-13 18:35:11 +00001490
John McCallf99a6312010-07-21 05:30:47 +00001491 break;
John McCallb81884d2010-02-19 09:25:03 +00001492 }
1493
John McCallf99a6312010-07-21 05:30:47 +00001494 // Jump out through the epilogue cleanups.
1495 DtorEpilogue.ForceCleanup();
John McCallb81884d2010-02-19 09:25:03 +00001496
1497 // Exit the try if applicable.
1498 if (isTryBody)
John McCallb609d3f2010-07-07 06:56:46 +00001499 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +00001500}
1501
Lang Hamesbf122742013-02-17 07:22:09 +00001502void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) {
1503 const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
1504 const Stmt *RootS = AssignOp->getBody();
1505 assert(isa<CompoundStmt>(RootS) &&
1506 "Body of an implicit assignment operator should be compound stmt.");
1507 const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
1508
1509 LexicalScope Scope(*this, RootCS->getSourceRange());
1510
Xinliang David Lia951e8e2016-02-09 20:02:59 +00001511 incrementProfileCounter(RootCS);
Lang Hamesbf122742013-02-17 07:22:09 +00001512 AssignmentMemcpyizer AM(*this, AssignOp, Args);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001513 for (auto *I : RootCS->body())
Justin Bogner1cd11f12015-05-20 15:53:59 +00001514 AM.emitAssignment(I);
Lang Hamesbf122742013-02-17 07:22:09 +00001515 AM.finish();
1516}
1517
John McCallf99a6312010-07-21 05:30:47 +00001518namespace {
Richard Smith5b349582017-10-13 01:55:36 +00001519 llvm::Value *LoadThisForDtorDelete(CodeGenFunction &CGF,
1520 const CXXDestructorDecl *DD) {
1521 if (Expr *ThisArg = DD->getOperatorDeleteThisArg())
Haojian Wu5b5c81f2017-10-13 15:37:53 +00001522 return CGF.EmitScalarExpr(ThisArg);
Richard Smith5b349582017-10-13 01:55:36 +00001523 return CGF.LoadCXXThis();
1524 }
1525
John McCallf99a6312010-07-21 05:30:47 +00001526 /// Call the operator delete associated with the current destructor.
David Blaikie7e70d682015-08-18 22:40:54 +00001527 struct CallDtorDelete final : EHScopeStack::Cleanup {
John McCallf99a6312010-07-21 05:30:47 +00001528 CallDtorDelete() {}
1529
Craig Topper4f12f102014-03-12 06:41:41 +00001530 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallf99a6312010-07-21 05:30:47 +00001531 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1532 const CXXRecordDecl *ClassDecl = Dtor->getParent();
Richard Smith5b349582017-10-13 01:55:36 +00001533 CGF.EmitDeleteCall(Dtor->getOperatorDelete(),
1534 LoadThisForDtorDelete(CGF, Dtor),
John McCallf99a6312010-07-21 05:30:47 +00001535 CGF.getContext().getTagDeclType(ClassDecl));
1536 }
1537 };
1538
Richard Smith5b349582017-10-13 01:55:36 +00001539 void EmitConditionalDtorDeleteCall(CodeGenFunction &CGF,
1540 llvm::Value *ShouldDeleteCondition,
1541 bool ReturnAfterDelete) {
1542 llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
1543 llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
1544 llvm::Value *ShouldCallDelete
1545 = CGF.Builder.CreateIsNull(ShouldDeleteCondition);
1546 CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
1547
1548 CGF.EmitBlock(callDeleteBB);
1549 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1550 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1551 CGF.EmitDeleteCall(Dtor->getOperatorDelete(),
1552 LoadThisForDtorDelete(CGF, Dtor),
1553 CGF.getContext().getTagDeclType(ClassDecl));
1554 assert(Dtor->getOperatorDelete()->isDestroyingOperatorDelete() ==
1555 ReturnAfterDelete &&
1556 "unexpected value for ReturnAfterDelete");
1557 if (ReturnAfterDelete)
1558 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
1559 else
1560 CGF.Builder.CreateBr(continueBB);
1561
1562 CGF.EmitBlock(continueBB);
1563 }
1564
David Blaikie7e70d682015-08-18 22:40:54 +00001565 struct CallDtorDeleteConditional final : EHScopeStack::Cleanup {
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001566 llvm::Value *ShouldDeleteCondition;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001567
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001568 public:
1569 CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001570 : ShouldDeleteCondition(ShouldDeleteCondition) {
Craig Topper8a13c412014-05-21 05:09:00 +00001571 assert(ShouldDeleteCondition != nullptr);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001572 }
1573
Craig Topper4f12f102014-03-12 06:41:41 +00001574 void Emit(CodeGenFunction &CGF, Flags flags) override {
Richard Smith5b349582017-10-13 01:55:36 +00001575 EmitConditionalDtorDeleteCall(CGF, ShouldDeleteCondition,
1576 /*ReturnAfterDelete*/false);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001577 }
1578 };
1579
David Blaikie7e70d682015-08-18 22:40:54 +00001580 class DestroyField final : public EHScopeStack::Cleanup {
John McCall4bd0fb12011-07-12 16:41:08 +00001581 const FieldDecl *field;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001582 CodeGenFunction::Destroyer *destroyer;
John McCall4bd0fb12011-07-12 16:41:08 +00001583 bool useEHCleanupForArray;
John McCallf99a6312010-07-21 05:30:47 +00001584
John McCall4bd0fb12011-07-12 16:41:08 +00001585 public:
1586 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
1587 bool useEHCleanupForArray)
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001588 : field(field), destroyer(destroyer),
1589 useEHCleanupForArray(useEHCleanupForArray) {}
John McCallf99a6312010-07-21 05:30:47 +00001590
Craig Topper4f12f102014-03-12 06:41:41 +00001591 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall4bd0fb12011-07-12 16:41:08 +00001592 // Find the address of the field.
John McCall7f416cc2015-09-08 08:05:57 +00001593 Address thisValue = CGF.LoadCXXThisAddress();
Eli Friedman7f1ff602012-04-16 03:54:45 +00001594 QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
1595 LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
1596 LValue LV = CGF.EmitLValueForField(ThisLV, field);
John McCall4bd0fb12011-07-12 16:41:08 +00001597 assert(LV.isSimple());
Justin Bogner1cd11f12015-05-20 15:53:59 +00001598
John McCall4bd0fb12011-07-12 16:41:08 +00001599 CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +00001600 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCallf99a6312010-07-21 05:30:47 +00001601 }
1602 };
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001603
Naomi Musgrave703835c2015-09-16 00:38:22 +00001604 static void EmitSanitizerDtorCallback(CodeGenFunction &CGF, llvm::Value *Ptr,
1605 CharUnits::QuantityType PoisonSize) {
Matt Morehouse4881a232017-09-20 22:53:08 +00001606 CodeGenFunction::SanitizerScope SanScope(&CGF);
Naomi Musgrave703835c2015-09-16 00:38:22 +00001607 // Pass in void pointer and size of region as arguments to runtime
1608 // function
1609 llvm::Value *Args[] = {CGF.Builder.CreateBitCast(Ptr, CGF.VoidPtrTy),
1610 llvm::ConstantInt::get(CGF.SizeTy, PoisonSize)};
1611
1612 llvm::Type *ArgTypes[] = {CGF.VoidPtrTy, CGF.SizeTy};
1613
1614 llvm::FunctionType *FnType =
1615 llvm::FunctionType::get(CGF.VoidTy, ArgTypes, false);
1616 llvm::Value *Fn =
1617 CGF.CGM.CreateRuntimeFunction(FnType, "__sanitizer_dtor_callback");
1618 CGF.EmitNounwindRuntimeCall(Fn, Args);
1619 }
1620
1621 class SanitizeDtorMembers final : public EHScopeStack::Cleanup {
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001622 const CXXDestructorDecl *Dtor;
1623
1624 public:
Naomi Musgrave703835c2015-09-16 00:38:22 +00001625 SanitizeDtorMembers(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001626
1627 // Generate function call for handling object poisoning.
1628 // Disables tail call elimination, to prevent the current stack frame
1629 // from disappearing from the stack trace.
1630 void Emit(CodeGenFunction &CGF, Flags flags) override {
1631 const ASTRecordLayout &Layout =
1632 CGF.getContext().getASTRecordLayout(Dtor->getParent());
1633
1634 // Nothing to poison.
1635 if (Layout.getFieldCount() == 0)
1636 return;
1637
1638 // Prevent the current stack frame from disappearing from the stack trace.
1639 CGF.CurFn->addFnAttr("disable-tail-calls", "true");
1640
1641 // Construct pointer to region to begin poisoning, and calculate poison
1642 // size, so that only members declared in this class are poisoned.
1643 ASTContext &Context = CGF.getContext();
1644 unsigned fieldIndex = 0;
1645 int startIndex = -1;
1646 // RecordDecl::field_iterator Field;
1647 for (const FieldDecl *Field : Dtor->getParent()->fields()) {
1648 // Poison field if it is trivial
1649 if (FieldHasTrivialDestructorBody(Context, Field)) {
1650 // Start sanitizing at this field
1651 if (startIndex < 0)
1652 startIndex = fieldIndex;
1653
1654 // Currently on the last field, and it must be poisoned with the
1655 // current block.
1656 if (fieldIndex == Layout.getFieldCount() - 1) {
Naomi Musgrave703835c2015-09-16 00:38:22 +00001657 PoisonMembers(CGF, startIndex, Layout.getFieldCount());
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001658 }
1659 } else if (startIndex >= 0) {
1660 // No longer within a block of memory to poison, so poison the block
Naomi Musgrave703835c2015-09-16 00:38:22 +00001661 PoisonMembers(CGF, startIndex, fieldIndex);
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001662 // Re-set the start index
1663 startIndex = -1;
1664 }
1665 fieldIndex += 1;
1666 }
1667 }
1668
1669 private:
NAKAMURA Takumif6cef72f2015-09-04 05:19:31 +00001670 /// \param layoutStartOffset index of the ASTRecordLayout field to
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001671 /// start poisoning (inclusive)
NAKAMURA Takumif6cef72f2015-09-04 05:19:31 +00001672 /// \param layoutEndOffset index of the ASTRecordLayout field to
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001673 /// end poisoning (exclusive)
Naomi Musgrave703835c2015-09-16 00:38:22 +00001674 void PoisonMembers(CodeGenFunction &CGF, unsigned layoutStartOffset,
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001675 unsigned layoutEndOffset) {
1676 ASTContext &Context = CGF.getContext();
1677 const ASTRecordLayout &Layout =
1678 Context.getASTRecordLayout(Dtor->getParent());
1679
1680 llvm::ConstantInt *OffsetSizePtr = llvm::ConstantInt::get(
1681 CGF.SizeTy,
1682 Context.toCharUnitsFromBits(Layout.getFieldOffset(layoutStartOffset))
1683 .getQuantity());
1684
1685 llvm::Value *OffsetPtr = CGF.Builder.CreateGEP(
1686 CGF.Builder.CreateBitCast(CGF.LoadCXXThis(), CGF.Int8PtrTy),
1687 OffsetSizePtr);
1688
1689 CharUnits::QuantityType PoisonSize;
1690 if (layoutEndOffset >= Layout.getFieldCount()) {
1691 PoisonSize = Layout.getNonVirtualSize().getQuantity() -
1692 Context.toCharUnitsFromBits(
1693 Layout.getFieldOffset(layoutStartOffset))
1694 .getQuantity();
1695 } else {
1696 PoisonSize = Context.toCharUnitsFromBits(
1697 Layout.getFieldOffset(layoutEndOffset) -
1698 Layout.getFieldOffset(layoutStartOffset))
1699 .getQuantity();
1700 }
1701
1702 if (PoisonSize == 0)
1703 return;
1704
Naomi Musgrave703835c2015-09-16 00:38:22 +00001705 EmitSanitizerDtorCallback(CGF, OffsetPtr, PoisonSize);
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001706 }
1707 };
Naomi Musgrave703835c2015-09-16 00:38:22 +00001708
1709 class SanitizeDtorVTable final : public EHScopeStack::Cleanup {
1710 const CXXDestructorDecl *Dtor;
1711
1712 public:
1713 SanitizeDtorVTable(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
1714
1715 // Generate function call for handling vtable pointer poisoning.
1716 void Emit(CodeGenFunction &CGF, Flags flags) override {
1717 assert(Dtor->getParent()->isDynamicClass());
NAKAMURA Takumiee82b492015-09-16 06:26:56 +00001718 (void)Dtor;
Naomi Musgrave703835c2015-09-16 00:38:22 +00001719 ASTContext &Context = CGF.getContext();
1720 // Poison vtable and vtable ptr if they exist for this class.
1721 llvm::Value *VTablePtr = CGF.LoadCXXThis();
1722
1723 CharUnits::QuantityType PoisonSize =
1724 Context.toCharUnitsFromBits(CGF.PointerWidthInBits).getQuantity();
1725 // Pass in void pointer and size of region as arguments to runtime
1726 // function
1727 EmitSanitizerDtorCallback(CGF, VTablePtr, PoisonSize);
1728 }
1729 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00001730} // end anonymous namespace
John McCallf99a6312010-07-21 05:30:47 +00001731
Hans Wennborgdeff7032013-12-18 01:39:59 +00001732/// \brief Emit all code that comes at the end of class's
Anders Carlssonfb404882009-12-24 22:46:43 +00001733/// destructor. This is to call destructors on members and base classes
1734/// in reverse order of their construction.
Richard Smith5b349582017-10-13 01:55:36 +00001735///
1736/// For a deleting destructor, this also handles the case where a destroying
1737/// operator delete completely overrides the definition.
John McCallf99a6312010-07-21 05:30:47 +00001738void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
1739 CXXDtorType DtorType) {
Hans Wennborg853ae942014-05-30 16:59:42 +00001740 assert((!DD->isTrivial() || DD->hasAttr<DLLExportAttr>()) &&
1741 "Should not emit dtor epilogue for non-exported trivial dtor!");
Anders Carlssonfb404882009-12-24 22:46:43 +00001742
John McCallf99a6312010-07-21 05:30:47 +00001743 // The deleting-destructor phase just needs to call the appropriate
1744 // operator delete that Sema picked up.
John McCall5c60a6f2010-02-18 19:59:28 +00001745 if (DtorType == Dtor_Deleting) {
Justin Bogner1cd11f12015-05-20 15:53:59 +00001746 assert(DD->getOperatorDelete() &&
Hans Wennborgdeff7032013-12-18 01:39:59 +00001747 "operator delete missing - EnterDtorCleanups");
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001748 if (CXXStructorImplicitParamValue) {
1749 // If there is an implicit param to the deleting dtor, it's a boolean
Richard Smith5b349582017-10-13 01:55:36 +00001750 // telling whether this is a deleting destructor.
1751 if (DD->getOperatorDelete()->isDestroyingOperatorDelete())
1752 EmitConditionalDtorDeleteCall(*this, CXXStructorImplicitParamValue,
1753 /*ReturnAfterDelete*/true);
1754 else
1755 EHStack.pushCleanup<CallDtorDeleteConditional>(
1756 NormalAndEHCleanup, CXXStructorImplicitParamValue);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001757 } else {
Richard Smith5b349582017-10-13 01:55:36 +00001758 if (DD->getOperatorDelete()->isDestroyingOperatorDelete()) {
1759 const CXXRecordDecl *ClassDecl = DD->getParent();
1760 EmitDeleteCall(DD->getOperatorDelete(),
1761 LoadThisForDtorDelete(*this, DD),
1762 getContext().getTagDeclType(ClassDecl));
1763 EmitBranchThroughCleanup(ReturnBlock);
1764 } else {
1765 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
1766 }
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001767 }
John McCall5c60a6f2010-02-18 19:59:28 +00001768 return;
1769 }
1770
John McCallf99a6312010-07-21 05:30:47 +00001771 const CXXRecordDecl *ClassDecl = DD->getParent();
1772
Richard Smith20104042011-09-18 12:11:43 +00001773 // Unions have no bases and do not call field destructors.
1774 if (ClassDecl->isUnion())
1775 return;
1776
John McCallf99a6312010-07-21 05:30:47 +00001777 // The complete-destructor phase just destructs all the virtual bases.
John McCall5c60a6f2010-02-18 19:59:28 +00001778 if (DtorType == Dtor_Complete) {
Naomi Musgrave703835c2015-09-16 00:38:22 +00001779 // Poison the vtable pointer such that access after the base
1780 // and member destructors are invoked is invalid.
1781 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1782 SanOpts.has(SanitizerKind::Memory) && ClassDecl->getNumVBases() &&
1783 ClassDecl->isPolymorphic())
1784 EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
John McCallf99a6312010-07-21 05:30:47 +00001785
1786 // We push them in the forward order so that they'll be popped in
1787 // the reverse order.
Aaron Ballman445a9392014-03-13 16:15:17 +00001788 for (const auto &Base : ClassDecl->vbases()) {
John McCall5c60a6f2010-02-18 19:59:28 +00001789 CXXRecordDecl *BaseClassDecl
1790 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Justin Bogner1cd11f12015-05-20 15:53:59 +00001791
John McCall5c60a6f2010-02-18 19:59:28 +00001792 // Ignore trivial destructors.
1793 if (BaseClassDecl->hasTrivialDestructor())
1794 continue;
John McCallf99a6312010-07-21 05:30:47 +00001795
John McCallcda666c2010-07-21 07:22:38 +00001796 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1797 BaseClassDecl,
1798 /*BaseIsVirtual*/ true);
John McCall5c60a6f2010-02-18 19:59:28 +00001799 }
John McCallf99a6312010-07-21 05:30:47 +00001800
John McCall5c60a6f2010-02-18 19:59:28 +00001801 return;
1802 }
1803
1804 assert(DtorType == Dtor_Base);
Naomi Musgrave703835c2015-09-16 00:38:22 +00001805 // Poison the vtable pointer if it has no virtual bases, but inherits
1806 // virtual functions.
1807 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1808 SanOpts.has(SanitizerKind::Memory) && !ClassDecl->getNumVBases() &&
1809 ClassDecl->isPolymorphic())
1810 EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001811
John McCallf99a6312010-07-21 05:30:47 +00001812 // Destroy non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001813 for (const auto &Base : ClassDecl->bases()) {
John McCallf99a6312010-07-21 05:30:47 +00001814 // Ignore virtual bases.
1815 if (Base.isVirtual())
1816 continue;
Justin Bogner1cd11f12015-05-20 15:53:59 +00001817
John McCallf99a6312010-07-21 05:30:47 +00001818 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
Justin Bogner1cd11f12015-05-20 15:53:59 +00001819
John McCallf99a6312010-07-21 05:30:47 +00001820 // Ignore trivial destructors.
1821 if (BaseClassDecl->hasTrivialDestructor())
1822 continue;
John McCall5c60a6f2010-02-18 19:59:28 +00001823
John McCallcda666c2010-07-21 07:22:38 +00001824 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1825 BaseClassDecl,
1826 /*BaseIsVirtual*/ false);
John McCallf99a6312010-07-21 05:30:47 +00001827 }
1828
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001829 // Poison fields such that access after their destructors are
1830 // invoked, and before the base class destructor runs, is invalid.
1831 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1832 SanOpts.has(SanitizerKind::Memory))
Naomi Musgrave703835c2015-09-16 00:38:22 +00001833 EHStack.pushCleanup<SanitizeDtorMembers>(NormalAndEHCleanup, DD);
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001834
John McCallf99a6312010-07-21 05:30:47 +00001835 // Destroy direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001836 for (const auto *Field : ClassDecl->fields()) {
1837 QualType type = Field->getType();
John McCall4bd0fb12011-07-12 16:41:08 +00001838 QualType::DestructionKind dtorKind = type.isDestructedType();
1839 if (!dtorKind) continue;
John McCallf99a6312010-07-21 05:30:47 +00001840
Richard Smith921bd202012-02-26 09:11:52 +00001841 // Anonymous union members do not have their destructors called.
1842 const RecordType *RT = type->getAsUnionType();
1843 if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
1844
John McCall4bd0fb12011-07-12 16:41:08 +00001845 CleanupKind cleanupKind = getCleanupKind(dtorKind);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001846 EHStack.pushCleanup<DestroyField>(cleanupKind, Field,
John McCall4bd0fb12011-07-12 16:41:08 +00001847 getDestroyer(dtorKind),
1848 cleanupKind & EHCleanup);
Anders Carlssonfb404882009-12-24 22:46:43 +00001849 }
Anders Carlssonfb404882009-12-24 22:46:43 +00001850}
1851
John McCallf677a8e2011-07-13 06:10:41 +00001852/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1853/// constructor for each of several members of an array.
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001854///
John McCallf677a8e2011-07-13 06:10:41 +00001855/// \param ctor the constructor to call for each element
John McCallf677a8e2011-07-13 06:10:41 +00001856/// \param arrayType the type of the array to initialize
1857/// \param arrayBegin an arrayType*
1858/// \param zeroInitialize true if each element should be
1859/// zero-initialized before it is constructed
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001860void CodeGenFunction::EmitCXXAggrConstructorCall(
Alexey Bataeve7545b32016-04-29 09:39:50 +00001861 const CXXConstructorDecl *ctor, const ArrayType *arrayType,
John McCall7f416cc2015-09-08 08:05:57 +00001862 Address arrayBegin, const CXXConstructExpr *E, bool zeroInitialize) {
John McCallf677a8e2011-07-13 06:10:41 +00001863 QualType elementType;
1864 llvm::Value *numElements =
1865 emitArrayLength(arrayType, elementType, arrayBegin);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001866
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001867 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin, E, zeroInitialize);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001868}
1869
John McCallf677a8e2011-07-13 06:10:41 +00001870/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1871/// constructor for each of several members of an array.
1872///
1873/// \param ctor the constructor to call for each element
1874/// \param numElements the number of elements in the array;
John McCall6549b312011-07-13 07:37:11 +00001875/// may be zero
NAKAMURA Takumiff7a9252015-09-08 09:42:41 +00001876/// \param arrayBase a T*, where T is the type constructed by ctor
John McCallf677a8e2011-07-13 06:10:41 +00001877/// \param zeroInitialize true if each element should be
1878/// zero-initialized before it is constructed
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001879void CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1880 llvm::Value *numElements,
John McCall7f416cc2015-09-08 08:05:57 +00001881 Address arrayBase,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001882 const CXXConstructExpr *E,
1883 bool zeroInitialize) {
John McCall6549b312011-07-13 07:37:11 +00001884 // It's legal for numElements to be zero. This can happen both
1885 // dynamically, because x can be zero in 'new A[x]', and statically,
1886 // because of GCC extensions that permit zero-length arrays. There
1887 // are probably legitimate places where we could assume that this
1888 // doesn't happen, but it's not clear that it's worth it.
Craig Topper8a13c412014-05-21 05:09:00 +00001889 llvm::BranchInst *zeroCheckBranch = nullptr;
John McCall6549b312011-07-13 07:37:11 +00001890
1891 // Optimize for a constant count.
1892 llvm::ConstantInt *constantCount
1893 = dyn_cast<llvm::ConstantInt>(numElements);
1894 if (constantCount) {
1895 // Just skip out if the constant count is zero.
1896 if (constantCount->isZero()) return;
1897
1898 // Otherwise, emit the check.
1899 } else {
1900 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1901 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1902 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1903 EmitBlock(loopBB);
1904 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00001905
John McCallf677a8e2011-07-13 06:10:41 +00001906 // Find the end of the array.
John McCall7f416cc2015-09-08 08:05:57 +00001907 llvm::Value *arrayBegin = arrayBase.getPointer();
John McCallf677a8e2011-07-13 06:10:41 +00001908 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1909 "arrayctor.end");
Anders Carlsson27da15b2010-01-01 20:29:01 +00001910
John McCallf677a8e2011-07-13 06:10:41 +00001911 // Enter the loop, setting up a phi for the current location to initialize.
1912 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1913 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1914 EmitBlock(loopBB);
1915 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1916 "arrayctor.cur");
1917 cur->addIncoming(arrayBegin, entryBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001918
Anders Carlsson27da15b2010-01-01 20:29:01 +00001919 // Inside the loop body, emit the constructor call on the array element.
John McCallf677a8e2011-07-13 06:10:41 +00001920
John McCall7f416cc2015-09-08 08:05:57 +00001921 // The alignment of the base, adjusted by the size of a single element,
1922 // provides a conservative estimate of the alignment of every element.
1923 // (This assumes we never start tracking offsetted alignments.)
1924 //
1925 // Note that these are complete objects and so we don't need to
1926 // use the non-virtual size or alignment.
John McCallf677a8e2011-07-13 06:10:41 +00001927 QualType type = getContext().getTypeDeclType(ctor->getParent());
John McCall7f416cc2015-09-08 08:05:57 +00001928 CharUnits eltAlignment =
1929 arrayBase.getAlignment()
1930 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
1931 Address curAddr = Address(cur, eltAlignment);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001932
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001933 // Zero initialize the storage, if requested.
John McCallf677a8e2011-07-13 06:10:41 +00001934 if (zeroInitialize)
John McCall7f416cc2015-09-08 08:05:57 +00001935 EmitNullInitialization(curAddr, type);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001936
1937 // C++ [class.temporary]p4:
Anders Carlsson27da15b2010-01-01 20:29:01 +00001938 // There are two contexts in which temporaries are destroyed at a different
1939 // point than the end of the full-expression. The first context is when a
Justin Bogner1cd11f12015-05-20 15:53:59 +00001940 // default constructor is called to initialize an element of an array.
1941 // If the constructor has one or more default arguments, the destruction of
1942 // every temporary created in a default argument expression is sequenced
Anders Carlsson27da15b2010-01-01 20:29:01 +00001943 // before the construction of the next array element, if any.
Justin Bogner1cd11f12015-05-20 15:53:59 +00001944
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00001945 {
John McCallbd309292010-07-06 01:34:17 +00001946 RunCleanupsScope Scope(*this);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001947
John McCallf677a8e2011-07-13 06:10:41 +00001948 // Evaluate the constructor and its arguments in a regular
1949 // partial-destroy cleanup.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001950 if (getLangOpts().Exceptions &&
John McCallf677a8e2011-07-13 06:10:41 +00001951 !ctor->getParent()->hasTrivialDestructor()) {
1952 Destroyer *destroyer = destroyCXXObject;
John McCall7f416cc2015-09-08 08:05:57 +00001953 pushRegularPartialArrayCleanup(arrayBegin, cur, type, eltAlignment,
1954 *destroyer);
John McCallf677a8e2011-07-13 06:10:41 +00001955 }
1956
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001957 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/false,
John McCall7f416cc2015-09-08 08:05:57 +00001958 /*Delegating=*/false, curAddr, E);
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00001959 }
Anders Carlsson27da15b2010-01-01 20:29:01 +00001960
John McCallf677a8e2011-07-13 06:10:41 +00001961 // Go to the next element.
1962 llvm::Value *next =
1963 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
1964 "arrayctor.next");
1965 cur->addIncoming(next, Builder.GetInsertBlock());
Anders Carlsson27da15b2010-01-01 20:29:01 +00001966
John McCallf677a8e2011-07-13 06:10:41 +00001967 // Check whether that's the end of the loop.
1968 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
1969 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
1970 Builder.CreateCondBr(done, contBB, loopBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001971
John McCall6549b312011-07-13 07:37:11 +00001972 // Patch the earlier check to skip over the loop.
1973 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
1974
John McCallf677a8e2011-07-13 06:10:41 +00001975 EmitBlock(contBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001976}
1977
John McCall82fe67b2011-07-09 01:37:26 +00001978void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001979 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00001980 QualType type) {
1981 const RecordType *rtype = type->castAs<RecordType>();
1982 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
1983 const CXXDestructorDecl *dtor = record->getDestructor();
1984 assert(!dtor->isTrivial());
1985 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
Douglas Gregor61535002013-01-31 05:50:40 +00001986 /*Delegating=*/false, addr);
John McCall82fe67b2011-07-09 01:37:26 +00001987}
1988
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001989void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
1990 CXXCtorType Type,
1991 bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +00001992 bool Delegating, Address This,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001993 const CXXConstructExpr *E) {
Richard Smith5179eb72016-06-28 19:03:57 +00001994 CallArgList Args;
1995
1996 // Push the this ptr.
1997 Args.add(RValue::get(This.getPointer()), D->getThisType(getContext()));
1998
1999 // If this is a trivial constructor, emit a memcpy now before we lose
2000 // the alignment information on the argument.
2001 // FIXME: It would be better to preserve alignment information into CallArg.
2002 if (isMemcpyEquivalentSpecialMember(D)) {
2003 assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
2004
2005 const Expr *Arg = E->getArg(0);
2006 QualType SrcTy = Arg->getType();
2007 Address Src = EmitLValue(Arg).getAddress();
2008 QualType DestTy = getContext().getTypeDeclType(D->getParent());
2009 EmitAggregateCopyCtor(This, Src, DestTy, SrcTy);
2010 return;
2011 }
2012
2013 // Add the rest of the user-supplied arguments.
2014 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
Hans Wennborg27dcc6c2017-02-01 02:21:07 +00002015 EvaluationOrder Order = E->isListInitialization()
2016 ? EvaluationOrder::ForceLeftToRight
2017 : EvaluationOrder::Default;
2018 EmitCallArgs(Args, FPT, E->arguments(), E->getConstructor(),
2019 /*ParamsToSkip*/ 0, Order);
Richard Smith5179eb72016-06-28 19:03:57 +00002020
2021 EmitCXXConstructorCall(D, Type, ForVirtualBase, Delegating, This, Args);
2022}
2023
2024static bool canEmitDelegateCallArgs(CodeGenFunction &CGF,
2025 const CXXConstructorDecl *Ctor,
2026 CXXCtorType Type, CallArgList &Args) {
2027 // We can't forward a variadic call.
2028 if (Ctor->isVariadic())
2029 return false;
2030
2031 if (CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2032 // If the parameters are callee-cleanup, it's not safe to forward.
2033 for (auto *P : Ctor->parameters())
2034 if (P->getType().isDestructedType())
2035 return false;
2036
2037 // Likewise if they're inalloca.
2038 const CGFunctionInfo &Info =
George Burgess IVd0a9e802017-02-23 22:07:35 +00002039 CGF.CGM.getTypes().arrangeCXXConstructorCall(Args, Ctor, Type, 0, 0);
Richard Smith5179eb72016-06-28 19:03:57 +00002040 if (Info.usesInAlloca())
2041 return false;
2042 }
2043
2044 // Anything else should be OK.
2045 return true;
2046}
2047
2048void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
2049 CXXCtorType Type,
2050 bool ForVirtualBase,
2051 bool Delegating,
2052 Address This,
2053 CallArgList &Args) {
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002054 const CXXRecordDecl *ClassDecl = D->getParent();
2055
Richard Smith419bd092015-04-29 19:26:57 +00002056 // C++11 [class.mfct.non-static]p2:
2057 // If a non-static member function of a class X is called for an object that
2058 // is not of type X, or of a type derived from X, the behavior is undefined.
2059 // FIXME: Provide a source location here.
John McCall7f416cc2015-09-08 08:05:57 +00002060 EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall, SourceLocation(),
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002061 This.getPointer(), getContext().getRecordType(ClassDecl));
John McCallca972cd2010-02-06 00:25:16 +00002062
Richard Smith419bd092015-04-29 19:26:57 +00002063 if (D->isTrivial() && D->isDefaultConstructor()) {
Richard Smith5179eb72016-06-28 19:03:57 +00002064 assert(Args.size() == 1 && "trivial default ctor with args");
Richard Smith419bd092015-04-29 19:26:57 +00002065 return;
2066 }
2067
2068 // If this is a trivial constructor, just emit what's needed. If this is a
2069 // union copy constructor, we must emit a memcpy, because the AST does not
2070 // model that copy.
2071 if (isMemcpyEquivalentSpecialMember(D)) {
Richard Smith5179eb72016-06-28 19:03:57 +00002072 assert(Args.size() == 2 && "unexpected argcount for trivial ctor");
John McCallca972cd2010-02-06 00:25:16 +00002073
Richard Smith5179eb72016-06-28 19:03:57 +00002074 QualType SrcTy = D->getParamDecl(0)->getType().getNonReferenceType();
2075 Address Src(Args[1].RV.getScalarVal(), getNaturalTypeAlignment(SrcTy));
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002076 QualType DestTy = getContext().getTypeDeclType(ClassDecl);
David Majnemerfd1e7392015-02-03 23:04:06 +00002077 EmitAggregateCopyCtor(This, Src, DestTy, SrcTy);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002078 return;
2079 }
2080
George Burgess IVd0a9e802017-02-23 22:07:35 +00002081 bool PassPrototypeArgs = true;
Richard Smith5179eb72016-06-28 19:03:57 +00002082 // Check whether we can actually emit the constructor before trying to do so.
2083 if (auto Inherited = D->getInheritedConstructor()) {
George Burgess IVd0a9e802017-02-23 22:07:35 +00002084 PassPrototypeArgs = getTypes().inheritingCtorHasParams(Inherited, Type);
2085 if (PassPrototypeArgs && !canEmitDelegateCallArgs(*this, D, Type, Args)) {
Richard Smith5179eb72016-06-28 19:03:57 +00002086 EmitInlinedInheritingCXXConstructorCall(D, Type, ForVirtualBase,
2087 Delegating, Args);
2088 return;
2089 }
2090 }
Reid Kleckner89077a12013-12-17 19:46:40 +00002091
2092 // Insert any ABI-specific implicit constructor arguments.
George Burgess IVf203dbf2017-02-22 20:28:02 +00002093 CGCXXABI::AddedStructorArgs ExtraArgs =
2094 CGM.getCXXABI().addImplicitConstructorArgs(*this, D, Type, ForVirtualBase,
2095 Delegating, Args);
Reid Kleckner89077a12013-12-17 19:46:40 +00002096
2097 // Emit the call.
John McCallb92ab1a2016-10-26 23:46:34 +00002098 llvm::Constant *CalleePtr =
2099 CGM.getAddrOfCXXStructor(D, getFromCtorType(Type));
George Burgess IVf203dbf2017-02-22 20:28:02 +00002100 const CGFunctionInfo &Info = CGM.getTypes().arrangeCXXConstructorCall(
George Burgess IVd0a9e802017-02-23 22:07:35 +00002101 Args, D, Type, ExtraArgs.Prefix, ExtraArgs.Suffix, PassPrototypeArgs);
John McCallb92ab1a2016-10-26 23:46:34 +00002102 CGCallee Callee = CGCallee::forDirect(CalleePtr, D);
2103 EmitCall(Info, Callee, ReturnValueSlot(), Args);
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002104
2105 // Generate vtable assumptions if we're constructing a complete object
2106 // with a vtable. We don't do this for base subobjects for two reasons:
2107 // first, it's incorrect for classes with virtual bases, and second, we're
2108 // about to overwrite the vptrs anyway.
2109 // We also have to make sure if we can refer to vtable:
2110 // - Otherwise we can refer to vtable if it's safe to speculatively emit.
2111 // FIXME: If vtable is used by ctor/dtor, or if vtable is external and we are
2112 // sure that definition of vtable is not hidden,
2113 // then we are always safe to refer to it.
Piotr Padlewski69dc9712015-09-28 20:30:22 +00002114 // FIXME: It looks like InstCombine is very inefficient on dealing with
2115 // assumes. Make assumption loads require -fstrict-vtable-pointers temporarily.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002116 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2117 ClassDecl->isDynamicClass() && Type != Ctor_Base &&
Piotr Padlewski69dc9712015-09-28 20:30:22 +00002118 CGM.getCXXABI().canSpeculativelyEmitVTable(ClassDecl) &&
2119 CGM.getCodeGenOpts().StrictVTablePointers)
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002120 EmitVTableAssumptionLoads(ClassDecl, This);
2121}
2122
Richard Smith5179eb72016-06-28 19:03:57 +00002123void CodeGenFunction::EmitInheritedCXXConstructorCall(
2124 const CXXConstructorDecl *D, bool ForVirtualBase, Address This,
2125 bool InheritedFromVBase, const CXXInheritedCtorInitExpr *E) {
2126 CallArgList Args;
2127 CallArg ThisArg(RValue::get(This.getPointer()), D->getThisType(getContext()),
2128 /*NeedsCopy=*/false);
2129
2130 // Forward the parameters.
2131 if (InheritedFromVBase &&
2132 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
2133 // Nothing to do; this construction is not responsible for constructing
2134 // the base class containing the inherited constructor.
2135 // FIXME: Can we just pass undef's for the remaining arguments if we don't
2136 // have constructor variants?
2137 Args.push_back(ThisArg);
2138 } else if (!CXXInheritedCtorInitExprArgs.empty()) {
2139 // The inheriting constructor was inlined; just inject its arguments.
2140 assert(CXXInheritedCtorInitExprArgs.size() >= D->getNumParams() &&
2141 "wrong number of parameters for inherited constructor call");
2142 Args = CXXInheritedCtorInitExprArgs;
2143 Args[0] = ThisArg;
2144 } else {
2145 // The inheriting constructor was not inlined. Emit delegating arguments.
2146 Args.push_back(ThisArg);
2147 const auto *OuterCtor = cast<CXXConstructorDecl>(CurCodeDecl);
2148 assert(OuterCtor->getNumParams() == D->getNumParams());
2149 assert(!OuterCtor->isVariadic() && "should have been inlined");
2150
2151 for (const auto *Param : OuterCtor->parameters()) {
2152 assert(getContext().hasSameUnqualifiedType(
2153 OuterCtor->getParamDecl(Param->getFunctionScopeIndex())->getType(),
2154 Param->getType()));
2155 EmitDelegateCallArg(Args, Param, E->getLocation());
2156
2157 // Forward __attribute__(pass_object_size).
2158 if (Param->hasAttr<PassObjectSizeAttr>()) {
2159 auto *POSParam = SizeArguments[Param];
2160 assert(POSParam && "missing pass_object_size value for forwarding");
2161 EmitDelegateCallArg(Args, POSParam, E->getLocation());
2162 }
2163 }
2164 }
2165
2166 EmitCXXConstructorCall(D, Ctor_Base, ForVirtualBase, /*Delegating*/false,
2167 This, Args);
2168}
2169
2170void CodeGenFunction::EmitInlinedInheritingCXXConstructorCall(
2171 const CXXConstructorDecl *Ctor, CXXCtorType CtorType, bool ForVirtualBase,
2172 bool Delegating, CallArgList &Args) {
Adrian Prantlb7acfc02017-02-27 21:30:05 +00002173 GlobalDecl GD(Ctor, CtorType);
2174 InlinedInheritingConstructorScope Scope(*this, GD);
2175 ApplyInlineDebugLocation DebugScope(*this, GD);
Richard Smith5179eb72016-06-28 19:03:57 +00002176
2177 // Save the arguments to be passed to the inherited constructor.
2178 CXXInheritedCtorInitExprArgs = Args;
2179
2180 FunctionArgList Params;
2181 QualType RetType = BuildFunctionArgList(CurGD, Params);
2182 FnRetTy = RetType;
2183
2184 // Insert any ABI-specific implicit constructor arguments.
2185 CGM.getCXXABI().addImplicitConstructorArgs(*this, Ctor, CtorType,
2186 ForVirtualBase, Delegating, Args);
2187
2188 // Emit a simplified prolog. We only need to emit the implicit params.
2189 assert(Args.size() >= Params.size() && "too few arguments for call");
2190 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2191 if (I < Params.size() && isa<ImplicitParamDecl>(Params[I])) {
2192 const RValue &RV = Args[I].RV;
2193 assert(!RV.isComplex() && "complex indirect params not supported");
2194 ParamValue Val = RV.isScalar()
2195 ? ParamValue::forDirect(RV.getScalarVal())
2196 : ParamValue::forIndirect(RV.getAggregateAddress());
2197 EmitParmDecl(*Params[I], Val, I + 1);
2198 }
2199 }
2200
2201 // Create a return value slot if the ABI implementation wants one.
2202 // FIXME: This is dumb, we should ask the ABI not to try to set the return
2203 // value instead.
2204 if (!RetType->isVoidType())
2205 ReturnValue = CreateIRTemp(RetType, "retval.inhctor");
2206
2207 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
2208 CXXThisValue = CXXABIThisValue;
2209
2210 // Directly emit the constructor initializers.
2211 EmitCtorPrologue(Ctor, CtorType, Params);
2212}
2213
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002214void CodeGenFunction::EmitVTableAssumptionLoad(const VPtr &Vptr, Address This) {
2215 llvm::Value *VTableGlobal =
2216 CGM.getCXXABI().getVTableAddressPoint(Vptr.Base, Vptr.VTableClass);
2217 if (!VTableGlobal)
2218 return;
2219
2220 // We can just use the base offset in the complete class.
2221 CharUnits NonVirtualOffset = Vptr.Base.getBaseOffset();
2222
2223 if (!NonVirtualOffset.isZero())
2224 This =
2225 ApplyNonVirtualAndVirtualOffset(*this, This, NonVirtualOffset, nullptr,
2226 Vptr.VTableClass, Vptr.NearestVBase);
2227
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002228 llvm::Value *VPtrValue =
2229 GetVTablePtr(This, VTableGlobal->getType(), Vptr.VTableClass);
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002230 llvm::Value *Cmp =
2231 Builder.CreateICmpEQ(VPtrValue, VTableGlobal, "cmp.vtables");
2232 Builder.CreateAssumption(Cmp);
2233}
2234
2235void CodeGenFunction::EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl,
2236 Address This) {
2237 if (CGM.getCXXABI().doStructorsInitializeVPtrs(ClassDecl))
2238 for (const VPtr &Vptr : getVTablePointers(ClassDecl))
2239 EmitVTableAssumptionLoad(Vptr, This);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002240}
2241
John McCallf8ff7b92010-02-23 00:48:20 +00002242void
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002243CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
John McCall7f416cc2015-09-08 08:05:57 +00002244 Address This, Address Src,
2245 const CXXConstructExpr *E) {
Reid Kleckner739756c2013-12-04 19:23:12 +00002246 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
Justin Bogner1cd11f12015-05-20 15:53:59 +00002247
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002248 CallArgList Args;
Justin Bogner1cd11f12015-05-20 15:53:59 +00002249
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002250 // Push the this ptr.
John McCall7f416cc2015-09-08 08:05:57 +00002251 Args.add(RValue::get(This.getPointer()), D->getThisType(getContext()));
Justin Bogner1cd11f12015-05-20 15:53:59 +00002252
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002253 // Push the src ptr.
Alp Toker9cacbab2014-01-20 20:26:09 +00002254 QualType QT = *(FPT->param_type_begin());
Chris Lattner2192fe52011-07-18 04:24:23 +00002255 llvm::Type *t = CGM.getTypes().ConvertType(QT);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002256 Src = Builder.CreateBitCast(Src, t);
John McCall7f416cc2015-09-08 08:05:57 +00002257 Args.add(RValue::get(Src.getPointer()), QT);
Reid Kleckner739756c2013-12-04 19:23:12 +00002258
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002259 // Skip over first argument (Src).
David Blaikief05779e2015-07-21 18:37:18 +00002260 EmitCallArgs(Args, FPT, drop_begin(E->arguments(), 1), E->getConstructor(),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002261 /*ParamsToSkip*/ 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002262
Richard Smith5179eb72016-06-28 19:03:57 +00002263 EmitCXXConstructorCall(D, Ctor_Complete, false, false, This, Args);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002264}
2265
2266void
John McCallf8ff7b92010-02-23 00:48:20 +00002267CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
2268 CXXCtorType CtorType,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002269 const FunctionArgList &Args,
2270 SourceLocation Loc) {
John McCallf8ff7b92010-02-23 00:48:20 +00002271 CallArgList DelegateArgs;
2272
2273 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
2274 assert(I != E && "no parameters to constructor");
2275
2276 // this
Richard Smith5179eb72016-06-28 19:03:57 +00002277 Address This = LoadCXXThisAddress();
2278 DelegateArgs.add(RValue::get(This.getPointer()), (*I)->getType());
John McCallf8ff7b92010-02-23 00:48:20 +00002279 ++I;
2280
Richard Smith5179eb72016-06-28 19:03:57 +00002281 // FIXME: The location of the VTT parameter in the parameter list is
2282 // specific to the Itanium ABI and shouldn't be hardcoded here.
2283 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
2284 assert(I != E && "cannot skip vtt parameter, already done with args");
2285 assert((*I)->getType()->isPointerType() &&
2286 "skipping parameter not of vtt type");
2287 ++I;
John McCallf8ff7b92010-02-23 00:48:20 +00002288 }
2289
2290 // Explicit arguments.
2291 for (; I != E; ++I) {
John McCall32ea9692011-03-11 20:59:21 +00002292 const VarDecl *param = *I;
Nick Lewycky2d84e842013-10-02 02:29:49 +00002293 // FIXME: per-argument source location
2294 EmitDelegateCallArg(DelegateArgs, param, Loc);
John McCallf8ff7b92010-02-23 00:48:20 +00002295 }
2296
Richard Smith5179eb72016-06-28 19:03:57 +00002297 EmitCXXConstructorCall(Ctor, CtorType, /*ForVirtualBase=*/false,
2298 /*Delegating=*/true, This, DelegateArgs);
John McCallf8ff7b92010-02-23 00:48:20 +00002299}
2300
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002301namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002302 struct CallDelegatingCtorDtor final : EHScopeStack::Cleanup {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002303 const CXXDestructorDecl *Dtor;
John McCall7f416cc2015-09-08 08:05:57 +00002304 Address Addr;
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002305 CXXDtorType Type;
2306
John McCall7f416cc2015-09-08 08:05:57 +00002307 CallDelegatingCtorDtor(const CXXDestructorDecl *D, Address Addr,
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002308 CXXDtorType Type)
2309 : Dtor(D), Addr(Addr), Type(Type) {}
2310
Craig Topper4f12f102014-03-12 06:41:41 +00002311 void Emit(CodeGenFunction &CGF, Flags flags) override {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002312 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
Douglas Gregor61535002013-01-31 05:50:40 +00002313 /*Delegating=*/true, Addr);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002314 }
2315 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00002316} // end anonymous namespace
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002317
Alexis Hunt61bc1732011-05-01 07:04:31 +00002318void
2319CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
2320 const FunctionArgList &Args) {
2321 assert(Ctor->isDelegatingConstructor());
2322
John McCall7f416cc2015-09-08 08:05:57 +00002323 Address ThisPtr = LoadCXXThisAddress();
Alexis Hunt61bc1732011-05-01 07:04:31 +00002324
John McCall31168b02011-06-15 23:02:42 +00002325 AggValueSlot AggSlot =
John McCall7f416cc2015-09-08 08:05:57 +00002326 AggValueSlot::forAddr(ThisPtr, Qualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +00002327 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00002328 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00002329 AggValueSlot::IsNotAliased);
Alexis Hunt61bc1732011-05-01 07:04:31 +00002330
2331 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
Alexis Hunt61bc1732011-05-01 07:04:31 +00002332
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002333 const CXXRecordDecl *ClassDecl = Ctor->getParent();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002334 if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002335 CXXDtorType Type =
2336 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
2337
2338 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
2339 ClassDecl->getDestructor(),
2340 ThisPtr, Type);
2341 }
2342}
Alexis Hunt61bc1732011-05-01 07:04:31 +00002343
Anders Carlsson27da15b2010-01-01 20:29:01 +00002344void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
2345 CXXDtorType Type,
Anders Carlssonf8a71f02010-05-02 23:29:11 +00002346 bool ForVirtualBase,
Douglas Gregor61535002013-01-31 05:50:40 +00002347 bool Delegating,
John McCall7f416cc2015-09-08 08:05:57 +00002348 Address This) {
Reid Kleckner6fe771a2013-12-13 00:53:54 +00002349 CGM.getCXXABI().EmitDestructorCall(*this, DD, Type, ForVirtualBase,
2350 Delegating, This);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002351}
2352
John McCall53cad2e2010-07-21 01:41:18 +00002353namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002354 struct CallLocalDtor final : EHScopeStack::Cleanup {
John McCall53cad2e2010-07-21 01:41:18 +00002355 const CXXDestructorDecl *Dtor;
John McCall7f416cc2015-09-08 08:05:57 +00002356 Address Addr;
John McCall53cad2e2010-07-21 01:41:18 +00002357
John McCall7f416cc2015-09-08 08:05:57 +00002358 CallLocalDtor(const CXXDestructorDecl *D, Address Addr)
John McCall53cad2e2010-07-21 01:41:18 +00002359 : Dtor(D), Addr(Addr) {}
2360
Craig Topper4f12f102014-03-12 06:41:41 +00002361 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall53cad2e2010-07-21 01:41:18 +00002362 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +00002363 /*ForVirtualBase=*/false,
2364 /*Delegating=*/false, Addr);
John McCall53cad2e2010-07-21 01:41:18 +00002365 }
2366 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002367} // end anonymous namespace
John McCall53cad2e2010-07-21 01:41:18 +00002368
John McCall8680f872010-07-21 06:29:51 +00002369void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
John McCall7f416cc2015-09-08 08:05:57 +00002370 Address Addr) {
John McCallcda666c2010-07-21 07:22:38 +00002371 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
John McCall8680f872010-07-21 06:29:51 +00002372}
2373
John McCall7f416cc2015-09-08 08:05:57 +00002374void CodeGenFunction::PushDestructorCleanup(QualType T, Address Addr) {
John McCallbd309292010-07-06 01:34:17 +00002375 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
2376 if (!ClassDecl) return;
2377 if (ClassDecl->hasTrivialDestructor()) return;
2378
2379 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCalla85af562011-04-28 02:15:35 +00002380 assert(D && D->isUsed() && "destructor not marked as used!");
John McCall8680f872010-07-21 06:29:51 +00002381 PushDestructorCleanup(D, Addr);
John McCallbd309292010-07-06 01:34:17 +00002382}
2383
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002384void CodeGenFunction::InitializeVTablePointer(const VPtr &Vptr) {
Anders Carlssone87fae92010-03-28 19:40:00 +00002385 // Compute the address point.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002386 llvm::Value *VTableAddressPoint =
2387 CGM.getCXXABI().getVTableAddressPointInStructor(
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002388 *this, Vptr.VTableClass, Vptr.Base, Vptr.NearestVBase);
2389
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002390 if (!VTableAddressPoint)
2391 return;
Anders Carlssone87fae92010-03-28 19:40:00 +00002392
Anders Carlsson6a0227d2010-04-20 16:22:16 +00002393 // Compute where to store the address point.
Craig Topper8a13c412014-05-21 05:09:00 +00002394 llvm::Value *VirtualOffset = nullptr;
Ken Dyckcfc332c2011-03-23 00:45:26 +00002395 CharUnits NonVirtualOffset = CharUnits::Zero();
Justin Bogner1cd11f12015-05-20 15:53:59 +00002396
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002397 if (CGM.getCXXABI().isVirtualOffsetNeededForVTableField(*this, Vptr)) {
Anders Carlsson91baecf2010-04-20 18:05:10 +00002398 // We need to use the virtual base offset offset because the virtual base
2399 // might have a different offset in the most derived class.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002400
2401 VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(
2402 *this, LoadCXXThisAddress(), Vptr.VTableClass, Vptr.NearestVBase);
2403 NonVirtualOffset = Vptr.OffsetFromNearestVBase;
Anders Carlsson91baecf2010-04-20 18:05:10 +00002404 } else {
Anders Carlssonc58fb552010-05-03 00:29:58 +00002405 // We can just use the base offset in the complete class.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002406 NonVirtualOffset = Vptr.Base.getBaseOffset();
Anders Carlsson91baecf2010-04-20 18:05:10 +00002407 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002408
Anders Carlssonc58fb552010-05-03 00:29:58 +00002409 // Apply the offsets.
John McCall7f416cc2015-09-08 08:05:57 +00002410 Address VTableField = LoadCXXThisAddress();
Justin Bogner1cd11f12015-05-20 15:53:59 +00002411
Ken Dyckcfc332c2011-03-23 00:45:26 +00002412 if (!NonVirtualOffset.isZero() || VirtualOffset)
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002413 VTableField = ApplyNonVirtualAndVirtualOffset(
2414 *this, VTableField, NonVirtualOffset, VirtualOffset, Vptr.VTableClass,
2415 Vptr.NearestVBase);
Anders Carlsson6a0227d2010-04-20 16:22:16 +00002416
Reid Kleckner8d585132014-12-03 21:00:21 +00002417 // Finally, store the address point. Use the same LLVM types as the field to
2418 // support optimization.
2419 llvm::Type *VTablePtrTy =
2420 llvm::FunctionType::get(CGM.Int32Ty, /*isVarArg=*/true)
2421 ->getPointerTo()
2422 ->getPointerTo();
2423 VTableField = Builder.CreateBitCast(VTableField, VTablePtrTy->getPointerTo());
2424 VTableAddressPoint = Builder.CreateBitCast(VTableAddressPoint, VTablePtrTy);
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002425
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002426 llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +00002427 CGM.DecorateInstructionWithTBAA(Store, CGM.getTBAAVTablePtrAccessInfo());
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002428 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2429 CGM.getCodeGenOpts().StrictVTablePointers)
2430 CGM.DecorateInstructionWithInvariantGroup(Store, Vptr.VTableClass);
Anders Carlssone87fae92010-03-28 19:40:00 +00002431}
2432
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002433CodeGenFunction::VPtrsVector
2434CodeGenFunction::getVTablePointers(const CXXRecordDecl *VTableClass) {
2435 CodeGenFunction::VPtrsVector VPtrsResult;
2436 VisitedVirtualBasesSetTy VBases;
2437 getVTablePointers(BaseSubobject(VTableClass, CharUnits::Zero()),
2438 /*NearestVBase=*/nullptr,
2439 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
2440 /*BaseIsNonVirtualPrimaryBase=*/false, VTableClass, VBases,
2441 VPtrsResult);
2442 return VPtrsResult;
2443}
2444
2445void CodeGenFunction::getVTablePointers(BaseSubobject Base,
2446 const CXXRecordDecl *NearestVBase,
2447 CharUnits OffsetFromNearestVBase,
2448 bool BaseIsNonVirtualPrimaryBase,
2449 const CXXRecordDecl *VTableClass,
2450 VisitedVirtualBasesSetTy &VBases,
2451 VPtrsVector &Vptrs) {
Anders Carlssond5895932010-03-28 21:07:49 +00002452 // If this base is a non-virtual primary base the address point has already
2453 // been set.
2454 if (!BaseIsNonVirtualPrimaryBase) {
2455 // Initialize the vtable pointer for this base.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002456 VPtr Vptr = {Base, NearestVBase, OffsetFromNearestVBase, VTableClass};
2457 Vptrs.push_back(Vptr);
Anders Carlssond5895932010-03-28 21:07:49 +00002458 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002459
Anders Carlssond5895932010-03-28 21:07:49 +00002460 const CXXRecordDecl *RD = Base.getBase();
2461
2462 // Traverse bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00002463 for (const auto &I : RD->bases()) {
Anders Carlssond5895932010-03-28 21:07:49 +00002464 CXXRecordDecl *BaseDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00002465 = cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Anders Carlssond5895932010-03-28 21:07:49 +00002466
2467 // Ignore classes without a vtable.
2468 if (!BaseDecl->isDynamicClass())
2469 continue;
2470
Ken Dyck3fb4c892011-03-23 01:04:18 +00002471 CharUnits BaseOffset;
2472 CharUnits BaseOffsetFromNearestVBase;
Anders Carlsson948d3f42010-03-29 01:16:41 +00002473 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlssond5895932010-03-28 21:07:49 +00002474
Aaron Ballman574705e2014-03-13 15:41:46 +00002475 if (I.isVirtual()) {
Anders Carlssond5895932010-03-28 21:07:49 +00002476 // Check if we've visited this virtual base before.
David Blaikie82e95a32014-11-19 07:49:47 +00002477 if (!VBases.insert(BaseDecl).second)
Anders Carlssond5895932010-03-28 21:07:49 +00002478 continue;
2479
Justin Bogner1cd11f12015-05-20 15:53:59 +00002480 const ASTRecordLayout &Layout =
Anders Carlssond5895932010-03-28 21:07:49 +00002481 getContext().getASTRecordLayout(VTableClass);
2482
Ken Dyck3fb4c892011-03-23 01:04:18 +00002483 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
2484 BaseOffsetFromNearestVBase = CharUnits::Zero();
Anders Carlsson948d3f42010-03-29 01:16:41 +00002485 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlssond5895932010-03-28 21:07:49 +00002486 } else {
2487 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
2488
Ken Dyck16ffcac2011-03-24 01:21:01 +00002489 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
Justin Bogner1cd11f12015-05-20 15:53:59 +00002490 BaseOffsetFromNearestVBase =
Ken Dyck3fb4c892011-03-23 01:04:18 +00002491 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson948d3f42010-03-29 01:16:41 +00002492 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlssond5895932010-03-28 21:07:49 +00002493 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002494
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002495 getVTablePointers(
2496 BaseSubobject(BaseDecl, BaseOffset),
2497 I.isVirtual() ? BaseDecl : NearestVBase, BaseOffsetFromNearestVBase,
2498 BaseDeclIsNonVirtualPrimaryBase, VTableClass, VBases, Vptrs);
Anders Carlssond5895932010-03-28 21:07:49 +00002499 }
2500}
2501
2502void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
2503 // Ignore classes without a vtable.
Anders Carlsson1f9348c2010-03-26 04:39:42 +00002504 if (!RD->isDynamicClass())
Anders Carlsson27da15b2010-01-01 20:29:01 +00002505 return;
2506
Anders Carlssond5895932010-03-28 21:07:49 +00002507 // Initialize the vtable pointers for this class and all of its bases.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002508 if (CGM.getCXXABI().doStructorsInitializeVPtrs(RD))
2509 for (const VPtr &Vptr : getVTablePointers(RD))
2510 InitializeVTablePointer(Vptr);
Timur Iskhodzhanovb6487322013-10-09 18:16:58 +00002511
2512 if (RD->getNumVBases())
2513 CGM.getCXXABI().initializeHiddenVirtualInheritanceMembers(*this, RD);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002514}
Dan Gohman8fc50c22010-10-26 18:44:08 +00002515
John McCall7f416cc2015-09-08 08:05:57 +00002516llvm::Value *CodeGenFunction::GetVTablePtr(Address This,
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002517 llvm::Type *VTableTy,
2518 const CXXRecordDecl *RD) {
2519 Address VTablePtrSrc = Builder.CreateElementBitCast(This, VTableTy);
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002520 llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +00002521 CGM.DecorateInstructionWithTBAA(VTable, CGM.getTBAAVTablePtrAccessInfo());
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002522
2523 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2524 CGM.getCodeGenOpts().StrictVTablePointers)
2525 CGM.DecorateInstructionWithInvariantGroup(VTable, RD);
2526
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002527 return VTable;
Dan Gohman8fc50c22010-10-26 18:44:08 +00002528}
Anders Carlssonc36783e2011-05-08 20:32:23 +00002529
Peter Collingbourned2926c92015-03-14 02:42:25 +00002530// If a class has a single non-virtual base and does not introduce or override
2531// virtual member functions or fields, it will have the same layout as its base.
2532// This function returns the least derived such class.
2533//
2534// Casting an instance of a base class to such a derived class is technically
2535// undefined behavior, but it is a relatively common hack for introducing member
2536// functions on class instances with specific properties (e.g. llvm::Operator)
2537// that works under most compilers and should not have security implications, so
2538// we allow it by default. It can be disabled with -fsanitize=cfi-cast-strict.
2539static const CXXRecordDecl *
2540LeastDerivedClassWithSameLayout(const CXXRecordDecl *RD) {
2541 if (!RD->field_empty())
2542 return RD;
2543
2544 if (RD->getNumVBases() != 0)
2545 return RD;
2546
2547 if (RD->getNumBases() != 1)
2548 return RD;
2549
2550 for (const CXXMethodDecl *MD : RD->methods()) {
2551 if (MD->isVirtual()) {
2552 // Virtual member functions are only ok if they are implicit destructors
2553 // because the implicit destructor will have the same semantics as the
2554 // base class's destructor if no fields are added.
2555 if (isa<CXXDestructorDecl>(MD) && MD->isImplicit())
2556 continue;
2557 return RD;
2558 }
2559 }
2560
2561 return LeastDerivedClassWithSameLayout(
2562 RD->bases_begin()->getType()->getAsCXXRecordDecl());
2563}
2564
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002565void CodeGenFunction::EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD,
2566 llvm::Value *VTable,
2567 SourceLocation Loc) {
Peter Collingbourne396943a2017-07-31 22:35:33 +00002568 if (SanOpts.has(SanitizerKind::CFIVCall))
2569 EmitVTablePtrCheckForCall(RD, VTable, CodeGenFunction::CFITCK_VCall, Loc);
2570 else if (CGM.getCodeGenOpts().WholeProgramVTables &&
2571 CGM.HasHiddenLTOVisibility(RD)) {
Peter Collingbournefb532b92016-02-24 20:46:36 +00002572 llvm::Metadata *MD =
2573 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002574 llvm::Value *TypeId =
Peter Collingbournefb532b92016-02-24 20:46:36 +00002575 llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD);
2576
2577 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002578 llvm::Value *TypeTest =
2579 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
2580 {CastedVTable, TypeId});
2581 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::assume), TypeTest);
Peter Collingbournefb532b92016-02-24 20:46:36 +00002582 }
Peter Collingbournefb532b92016-02-24 20:46:36 +00002583}
2584
2585void CodeGenFunction::EmitVTablePtrCheckForCall(const CXXRecordDecl *RD,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002586 llvm::Value *VTable,
2587 CFITypeCheckKind TCK,
2588 SourceLocation Loc) {
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002589 if (!SanOpts.has(SanitizerKind::CFICastStrict))
Peter Collingbournefb532b92016-02-24 20:46:36 +00002590 RD = LeastDerivedClassWithSameLayout(RD);
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002591
Peter Collingbournefb532b92016-02-24 20:46:36 +00002592 EmitVTablePtrCheck(RD, VTable, TCK, Loc);
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002593}
2594
Peter Collingbourned2926c92015-03-14 02:42:25 +00002595void CodeGenFunction::EmitVTablePtrCheckForCast(QualType T,
2596 llvm::Value *Derived,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002597 bool MayBeNull,
2598 CFITypeCheckKind TCK,
2599 SourceLocation Loc) {
Peter Collingbourned2926c92015-03-14 02:42:25 +00002600 if (!getLangOpts().CPlusPlus)
2601 return;
2602
2603 auto *ClassTy = T->getAs<RecordType>();
2604 if (!ClassTy)
2605 return;
2606
2607 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassTy->getDecl());
2608
2609 if (!ClassDecl->isCompleteDefinition() || !ClassDecl->isDynamicClass())
2610 return;
2611
Peter Collingbourned2926c92015-03-14 02:42:25 +00002612 if (!SanOpts.has(SanitizerKind::CFICastStrict))
2613 ClassDecl = LeastDerivedClassWithSameLayout(ClassDecl);
2614
Hans Wennborgdcfba332015-10-06 23:40:43 +00002615 llvm::BasicBlock *ContBlock = nullptr;
Peter Collingbourned2926c92015-03-14 02:42:25 +00002616
2617 if (MayBeNull) {
2618 llvm::Value *DerivedNotNull =
2619 Builder.CreateIsNotNull(Derived, "cast.nonnull");
2620
2621 llvm::BasicBlock *CheckBlock = createBasicBlock("cast.check");
2622 ContBlock = createBasicBlock("cast.cont");
2623
2624 Builder.CreateCondBr(DerivedNotNull, CheckBlock, ContBlock);
2625
2626 EmitBlock(CheckBlock);
2627 }
2628
John McCall7f416cc2015-09-08 08:05:57 +00002629 llvm::Value *VTable =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002630 GetVTablePtr(Address(Derived, getPointerAlign()), Int8PtrTy, ClassDecl);
2631
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002632 EmitVTablePtrCheck(ClassDecl, VTable, TCK, Loc);
Peter Collingbourned2926c92015-03-14 02:42:25 +00002633
2634 if (MayBeNull) {
2635 Builder.CreateBr(ContBlock);
2636 EmitBlock(ContBlock);
2637 }
2638}
2639
2640void CodeGenFunction::EmitVTablePtrCheck(const CXXRecordDecl *RD,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002641 llvm::Value *VTable,
2642 CFITypeCheckKind TCK,
2643 SourceLocation Loc) {
Peter Collingbourne3afb2662016-04-28 17:09:37 +00002644 if (!CGM.getCodeGenOpts().SanitizeCfiCrossDso &&
2645 !CGM.HasHiddenLTOVisibility(RD))
2646 return;
2647
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002648 SanitizerMask M;
Peter Collingbournedc134532016-01-16 00:31:22 +00002649 llvm::SanitizerStatKind SSK;
2650 switch (TCK) {
2651 case CFITCK_VCall:
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002652 M = SanitizerKind::CFIVCall;
Peter Collingbournedc134532016-01-16 00:31:22 +00002653 SSK = llvm::SanStat_CFI_VCall;
2654 break;
2655 case CFITCK_NVCall:
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002656 M = SanitizerKind::CFINVCall;
Peter Collingbournedc134532016-01-16 00:31:22 +00002657 SSK = llvm::SanStat_CFI_NVCall;
2658 break;
2659 case CFITCK_DerivedCast:
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002660 M = SanitizerKind::CFIDerivedCast;
Peter Collingbournedc134532016-01-16 00:31:22 +00002661 SSK = llvm::SanStat_CFI_DerivedCast;
2662 break;
2663 case CFITCK_UnrelatedCast:
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002664 M = SanitizerKind::CFIUnrelatedCast;
Peter Collingbournedc134532016-01-16 00:31:22 +00002665 SSK = llvm::SanStat_CFI_UnrelatedCast;
2666 break;
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002667 case CFITCK_ICall:
2668 llvm_unreachable("not expecting CFITCK_ICall");
Peter Collingbournedc134532016-01-16 00:31:22 +00002669 }
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002670
2671 std::string TypeName = RD->getQualifiedNameAsString();
2672 if (getContext().getSanitizerBlacklist().isBlacklistedType(M, TypeName))
2673 return;
2674
2675 SanitizerScope SanScope(this);
Peter Collingbournedc134532016-01-16 00:31:22 +00002676 EmitSanitizerStatReport(SSK);
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002677
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002678 llvm::Metadata *MD =
2679 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002680 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002681
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002682 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002683 llvm::Value *TypeTest = Builder.CreateCall(
2684 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, TypeId});
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002685
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002686 llvm::Constant *StaticData[] = {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002687 llvm::ConstantInt::get(Int8Ty, TCK),
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002688 EmitCheckSourceLocation(Loc),
2689 EmitCheckTypeDescriptor(QualType(RD->getTypeForDecl(), 0)),
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002690 };
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002691
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002692 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
2693 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
2694 EmitCfiSlowPathCheck(M, TypeTest, CrossDsoTypeId, CastedVTable, StaticData);
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002695 return;
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002696 }
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002697
2698 if (CGM.getCodeGenOpts().SanitizeTrap.has(M)) {
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002699 EmitTrapCheck(TypeTest);
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002700 return;
2701 }
2702
2703 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
2704 CGM.getLLVMContext(),
2705 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002706 llvm::Value *ValidVtable = Builder.CreateCall(
2707 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, AllVtables});
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002708 EmitCheck(std::make_pair(TypeTest, M), SanitizerHandler::CFICheckFail,
2709 StaticData, {CastedVTable, ValidVtable});
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002710}
Anders Carlssonc36783e2011-05-08 20:32:23 +00002711
Peter Collingbourne0ca03632016-06-25 00:24:06 +00002712bool CodeGenFunction::ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD) {
2713 if (!CGM.getCodeGenOpts().WholeProgramVTables ||
2714 !SanOpts.has(SanitizerKind::CFIVCall) ||
2715 !CGM.getCodeGenOpts().SanitizeTrap.has(SanitizerKind::CFIVCall) ||
2716 !CGM.HasHiddenLTOVisibility(RD))
2717 return false;
2718
2719 std::string TypeName = RD->getQualifiedNameAsString();
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002720 return !getContext().getSanitizerBlacklist().isBlacklistedType(
2721 SanitizerKind::CFIVCall, TypeName);
Peter Collingbourne0ca03632016-06-25 00:24:06 +00002722}
2723
2724llvm::Value *CodeGenFunction::EmitVTableTypeCheckedLoad(
2725 const CXXRecordDecl *RD, llvm::Value *VTable, uint64_t VTableByteOffset) {
2726 SanitizerScope SanScope(this);
2727
2728 EmitSanitizerStatReport(llvm::SanStat_CFI_VCall);
2729
2730 llvm::Metadata *MD =
2731 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
2732 llvm::Value *TypeId = llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD);
2733
2734 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
2735 llvm::Value *CheckedLoad = Builder.CreateCall(
2736 CGM.getIntrinsic(llvm::Intrinsic::type_checked_load),
2737 {CastedVTable, llvm::ConstantInt::get(Int32Ty, VTableByteOffset),
2738 TypeId});
2739 llvm::Value *CheckResult = Builder.CreateExtractValue(CheckedLoad, 1);
2740
2741 EmitCheck(std::make_pair(CheckResult, SanitizerKind::CFIVCall),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002742 SanitizerHandler::CFICheckFail, nullptr, nullptr);
Peter Collingbourne0ca03632016-06-25 00:24:06 +00002743
2744 return Builder.CreateBitCast(
2745 Builder.CreateExtractValue(CheckedLoad, 0),
2746 cast<llvm::PointerType>(VTable->getType())->getElementType());
2747}
2748
Faisal Vali571df122013-09-29 08:45:24 +00002749void CodeGenFunction::EmitForwardingCallToLambda(
2750 const CXXMethodDecl *callOperator,
2751 CallArgList &callArgs) {
Eli Friedman5b446882012-02-16 03:47:28 +00002752 // Get the address of the call operator.
John McCall8dda7b22012-07-07 06:41:13 +00002753 const CGFunctionInfo &calleeFnInfo =
2754 CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
John McCallb92ab1a2016-10-26 23:46:34 +00002755 llvm::Constant *calleePtr =
John McCall8dda7b22012-07-07 06:41:13 +00002756 CGM.GetAddrOfFunction(GlobalDecl(callOperator),
2757 CGM.getTypes().GetFunctionType(calleeFnInfo));
Eli Friedman5b446882012-02-16 03:47:28 +00002758
John McCall8dda7b22012-07-07 06:41:13 +00002759 // Prepare the return slot.
2760 const FunctionProtoType *FPT =
2761 callOperator->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00002762 QualType resultType = FPT->getReturnType();
John McCall8dda7b22012-07-07 06:41:13 +00002763 ReturnValueSlot returnSlot;
2764 if (!resultType->isVoidType() &&
2765 calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
John McCall47fb9502013-03-07 21:37:08 +00002766 !hasScalarEvaluationKind(calleeFnInfo.getReturnType()))
John McCall8dda7b22012-07-07 06:41:13 +00002767 returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
2768
2769 // We don't need to separately arrange the call arguments because
2770 // the call can't be variadic anyway --- it's impossible to forward
2771 // variadic arguments.
Justin Bogner1cd11f12015-05-20 15:53:59 +00002772
Eli Friedman5b446882012-02-16 03:47:28 +00002773 // Now emit our call.
John McCallb92ab1a2016-10-26 23:46:34 +00002774 auto callee = CGCallee::forDirect(calleePtr, callOperator);
2775 RValue RV = EmitCall(calleeFnInfo, callee, returnSlot, callArgs);
Eli Friedman5b446882012-02-16 03:47:28 +00002776
John McCall8dda7b22012-07-07 06:41:13 +00002777 // If necessary, copy the returned value into the slot.
2778 if (!resultType->isVoidType() && returnSlot.isNull())
2779 EmitReturnOfRValue(RV, resultType);
Eli Friedmanf5f4d2f2012-12-13 23:37:17 +00002780 else
2781 EmitBranchThroughCleanup(ReturnBlock);
Eli Friedman5b446882012-02-16 03:47:28 +00002782}
2783
Eli Friedman2495ab02012-02-25 02:48:22 +00002784void CodeGenFunction::EmitLambdaBlockInvokeBody() {
2785 const BlockDecl *BD = BlockInfo->getBlockDecl();
2786 const VarDecl *variable = BD->capture_begin()->getVariable();
2787 const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
Reid Kleckner2d3c4212017-08-04 22:38:06 +00002788 const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
2789
2790 if (CallOp->isVariadic()) {
2791 // FIXME: Making this work correctly is nasty because it requires either
2792 // cloning the body of the call operator or making the call operator
2793 // forward.
2794 CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function");
2795 return;
2796 }
Eli Friedman2495ab02012-02-25 02:48:22 +00002797
2798 // Start building arguments for forwarding call
2799 CallArgList CallArgs;
2800
2801 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
John McCall7f416cc2015-09-08 08:05:57 +00002802 Address ThisPtr = GetAddrOfBlockDecl(variable, false);
2803 CallArgs.add(RValue::get(ThisPtr.getPointer()), ThisType);
Eli Friedman2495ab02012-02-25 02:48:22 +00002804
2805 // Add the rest of the parameters.
David Majnemer59f77922016-06-24 04:05:48 +00002806 for (auto param : BD->parameters())
Nick Lewycky2d84e842013-10-02 02:29:49 +00002807 EmitDelegateCallArg(CallArgs, param, param->getLocStart());
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00002808
Justin Bogner1cd11f12015-05-20 15:53:59 +00002809 assert(!Lambda->isGenericLambda() &&
Faisal Vali571df122013-09-29 08:45:24 +00002810 "generic lambda interconversion to block not implemented");
Reid Kleckner2d3c4212017-08-04 22:38:06 +00002811 EmitForwardingCallToLambda(CallOp, CallArgs);
Eli Friedman2495ab02012-02-25 02:48:22 +00002812}
2813
2814void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
2815 const CXXRecordDecl *Lambda = MD->getParent();
2816
2817 // Start building arguments for forwarding call
2818 CallArgList CallArgs;
2819
2820 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2821 llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
2822 CallArgs.add(RValue::get(ThisPtr), ThisType);
2823
2824 // Add the rest of the parameters.
David Majnemer59f77922016-06-24 04:05:48 +00002825 for (auto Param : MD->parameters())
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002826 EmitDelegateCallArg(CallArgs, Param, Param->getLocStart());
2827
Faisal Vali571df122013-09-29 08:45:24 +00002828 const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
2829 // For a generic lambda, find the corresponding call operator specialization
2830 // to which the call to the static-invoker shall be forwarded.
2831 if (Lambda->isGenericLambda()) {
2832 assert(MD->isFunctionTemplateSpecialization());
2833 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
2834 FunctionTemplateDecl *CallOpTemplate = CallOp->getDescribedFunctionTemplate();
Craig Topper8a13c412014-05-21 05:09:00 +00002835 void *InsertPos = nullptr;
Justin Bogner1cd11f12015-05-20 15:53:59 +00002836 FunctionDecl *CorrespondingCallOpSpecialization =
Craig Topper7e0daca2014-06-26 04:58:53 +00002837 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
Faisal Vali571df122013-09-29 08:45:24 +00002838 assert(CorrespondingCallOpSpecialization);
2839 CallOp = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
2840 }
2841 EmitForwardingCallToLambda(CallOp, CallArgs);
Eli Friedman2495ab02012-02-25 02:48:22 +00002842}
2843
Reid Kleckner2d3c4212017-08-04 22:38:06 +00002844void CodeGenFunction::EmitLambdaStaticInvokeBody(const CXXMethodDecl *MD) {
Douglas Gregor355efbb2012-02-17 03:02:34 +00002845 if (MD->isVariadic()) {
Eli Friedman5b446882012-02-16 03:47:28 +00002846 // FIXME: Making this work correctly is nasty because it requires either
2847 // cloning the body of the call operator or making the call operator forward.
2848 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
Eli Friedman2495ab02012-02-25 02:48:22 +00002849 return;
Eli Friedman5b446882012-02-16 03:47:28 +00002850 }
2851
Douglas Gregor355efbb2012-02-17 03:02:34 +00002852 EmitLambdaDelegatingInvokeBody(MD);
Eli Friedman5a6d5072012-02-16 01:37:33 +00002853}