blob: 3f3825b7627597c8114cfde78ae2b307072d4488 [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Anders Carlsson9a57c5a2009-09-12 04:27:24 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This contains code dealing with C++ code generation of classes
10//
11//===----------------------------------------------------------------------===//
12
Eli Friedman2495ab02012-02-25 02:48:22 +000013#include "CGBlocks.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000014#include "CGCXXABI.h"
Devang Pateld76c1db2010-08-11 21:04:37 +000015#include "CGDebugInfo.h"
Lang Hamesbf122742013-02-17 07:22:09 +000016#include "CGRecordLayout.h"
Anders Carlsson9a57c5a2009-09-12 04:27:24 +000017#include "CodeGenFunction.h"
Mikael Nilsson9d2872d2018-12-13 10:15:27 +000018#include "TargetInfo.h"
Reid Kleckner98031782019-12-09 16:11:56 -080019#include "clang/AST/Attr.h"
Anders Carlssonc6d171e2009-10-06 22:43:30 +000020#include "clang/AST/CXXInheritance.h"
Faisal Vali571df122013-09-29 08:45:24 +000021#include "clang/AST/DeclTemplate.h"
John McCall769250e2010-09-17 02:31:44 +000022#include "clang/AST/EvaluatedExprVisitor.h"
Anders Carlsson9a57c5a2009-09-12 04:27:24 +000023#include "clang/AST/RecordLayout.h"
John McCallb81884d2010-02-19 09:25:03 +000024#include "clang/AST/StmtCXX.h"
Richard Trieu63688182018-12-11 03:18:39 +000025#include "clang/Basic/CodeGenOptions.h"
Lang Hamesbf122742013-02-17 07:22:09 +000026#include "clang/Basic/TargetBuiltins.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000027#include "clang/CodeGen/CGFunctionInfo.h"
Peter Collingbournea4ccff32015-02-20 20:30:56 +000028#include "llvm/IR/Intrinsics.h"
Piotr Padlewski4b1ac722015-09-15 21:46:55 +000029#include "llvm/IR/Metadata.h"
Peter Collingbournedc134532016-01-16 00:31:22 +000030#include "llvm/Transforms/Utils/SanitizerStats.h"
Anders Carlssonc6d171e2009-10-06 22:43:30 +000031
Anders Carlsson9a57c5a2009-09-12 04:27:24 +000032using namespace clang;
33using namespace CodeGen;
34
John McCall7f416cc2015-09-08 08:05:57 +000035/// Return the best known alignment for an unknown pointer to a
36/// particular class.
37CharUnits CodeGenModule::getClassPointerAlignment(const CXXRecordDecl *RD) {
38 if (!RD->isCompleteDefinition())
39 return CharUnits::One(); // Hopefully won't be used anywhere.
40
41 auto &layout = getContext().getASTRecordLayout(RD);
42
43 // If the class is final, then we know that the pointer points to an
44 // object of that type and can use the full alignment.
45 if (RD->hasAttr<FinalAttr>()) {
46 return layout.getAlignment();
47
48 // Otherwise, we have to assume it could be a subclass.
49 } else {
50 return layout.getNonVirtualAlignment();
51 }
52}
53
54/// Return the best known alignment for a pointer to a virtual base,
55/// given the alignment of a pointer to the derived class.
56CharUnits CodeGenModule::getVBaseAlignment(CharUnits actualDerivedAlign,
57 const CXXRecordDecl *derivedClass,
58 const CXXRecordDecl *vbaseClass) {
59 // The basic idea here is that an underaligned derived pointer might
60 // indicate an underaligned base pointer.
61
62 assert(vbaseClass->isCompleteDefinition());
63 auto &baseLayout = getContext().getASTRecordLayout(vbaseClass);
64 CharUnits expectedVBaseAlign = baseLayout.getNonVirtualAlignment();
65
66 return getDynamicOffsetAlignment(actualDerivedAlign, derivedClass,
67 expectedVBaseAlign);
68}
69
70CharUnits
71CodeGenModule::getDynamicOffsetAlignment(CharUnits actualBaseAlign,
72 const CXXRecordDecl *baseDecl,
73 CharUnits expectedTargetAlign) {
74 // If the base is an incomplete type (which is, alas, possible with
75 // member pointers), be pessimistic.
76 if (!baseDecl->isCompleteDefinition())
77 return std::min(actualBaseAlign, expectedTargetAlign);
78
79 auto &baseLayout = getContext().getASTRecordLayout(baseDecl);
80 CharUnits expectedBaseAlign = baseLayout.getNonVirtualAlignment();
81
82 // If the class is properly aligned, assume the target offset is, too.
83 //
84 // This actually isn't necessarily the right thing to do --- if the
85 // class is a complete object, but it's only properly aligned for a
86 // base subobject, then the alignments of things relative to it are
87 // probably off as well. (Note that this requires the alignment of
88 // the target to be greater than the NV alignment of the derived
89 // class.)
90 //
91 // However, our approach to this kind of under-alignment can only
92 // ever be best effort; after all, we're never going to propagate
93 // alignments through variables or parameters. Note, in particular,
94 // that constructing a polymorphic type in an address that's less
95 // than pointer-aligned will generally trap in the constructor,
96 // unless we someday add some sort of attribute to change the
97 // assumed alignment of 'this'. So our goal here is pretty much
98 // just to allow the user to explicitly say that a pointer is
Eric Christopherd160c502016-01-29 01:35:53 +000099 // under-aligned and then safely access its fields and vtables.
John McCall7f416cc2015-09-08 08:05:57 +0000100 if (actualBaseAlign >= expectedBaseAlign) {
101 return expectedTargetAlign;
102 }
103
104 // Otherwise, we might be offset by an arbitrary multiple of the
105 // actual alignment. The correct adjustment is to take the min of
106 // the two alignments.
107 return std::min(actualBaseAlign, expectedTargetAlign);
108}
109
110Address CodeGenFunction::LoadCXXThisAddress() {
111 assert(CurFuncDecl && "loading 'this' without a func declaration?");
112 assert(isa<CXXMethodDecl>(CurFuncDecl));
113
114 // Lazily compute CXXThisAlignment.
115 if (CXXThisAlignment.isZero()) {
116 // Just use the best known alignment for the parent.
117 // TODO: if we're currently emitting a complete-object ctor/dtor,
118 // we can always use the complete-object alignment.
119 auto RD = cast<CXXMethodDecl>(CurFuncDecl)->getParent();
120 CXXThisAlignment = CGM.getClassPointerAlignment(RD);
121 }
122
123 return Address(LoadCXXThis(), CXXThisAlignment);
124}
125
126/// Emit the address of a field using a member data pointer.
127///
128/// \param E Only used for emergency diagnostics
129Address
130CodeGenFunction::EmitCXXMemberDataPointerAddress(const Expr *E, Address base,
131 llvm::Value *memberPtr,
132 const MemberPointerType *memberPtrType,
Ivan A. Kosarev229a6d82017-10-13 16:38:32 +0000133 LValueBaseInfo *BaseInfo,
134 TBAAAccessInfo *TBAAInfo) {
John McCall7f416cc2015-09-08 08:05:57 +0000135 // Ask the ABI to compute the actual address.
136 llvm::Value *ptr =
137 CGM.getCXXABI().EmitMemberDataPointerAddress(*this, E, base,
138 memberPtr, memberPtrType);
139
140 QualType memberType = memberPtrType->getPointeeType();
Ivan A. Kosarev78f486d2017-10-13 16:58:30 +0000141 CharUnits memberAlign = getNaturalTypeAlignment(memberType, BaseInfo,
142 TBAAInfo);
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
Simon Pilgrim1cd399c2019-10-03 11:22:48 +0000165 const auto *BaseDecl =
166 cast<CXXRecordDecl>(Base->getType()->castAs<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();
Sven van Haastregtaf6248c2019-10-17 14:12:51 +0000250 unsigned AddrSpace = ptr->getType()->getPointerAddressSpace();
251 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8Ty->getPointerTo(AddrSpace));
John McCall13a39c62012-08-01 05:04:58 +0000252 ptr = CGF.Builder.CreateInBoundsGEP(ptr, baseOffset, "add.ptr");
John McCall7f416cc2015-09-08 08:05:57 +0000253
254 // If we have a virtual component, the alignment of the result will
255 // be relative only to the known alignment of that vbase.
256 CharUnits alignment;
257 if (virtualOffset) {
258 assert(nearestVBase && "virtual offset without vbase?");
259 alignment = CGF.CGM.getVBaseAlignment(addr.getAlignment(),
260 derivedClass, nearestVBase);
261 } else {
262 alignment = addr.getAlignment();
263 }
264 alignment = alignment.alignmentAtOffset(nonVirtualOffset);
265
266 return Address(ptr, alignment);
Anders Carlsson53cebd12010-04-20 16:03:35 +0000267}
268
John McCall7f416cc2015-09-08 08:05:57 +0000269Address CodeGenFunction::GetAddressOfBaseClass(
270 Address Value, const CXXRecordDecl *Derived,
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000271 CastExpr::path_const_iterator PathBegin,
272 CastExpr::path_const_iterator PathEnd, bool NullCheckValue,
273 SourceLocation Loc) {
John McCallcf142162010-08-07 06:22:56 +0000274 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssond829a022010-04-24 21:06:20 +0000275
John McCallcf142162010-08-07 06:22:56 +0000276 CastExpr::path_const_iterator Start = PathBegin;
Craig Topper8a13c412014-05-21 05:09:00 +0000277 const CXXRecordDecl *VBase = nullptr;
278
John McCall13a39c62012-08-01 05:04:58 +0000279 // Sema has done some convenient canonicalization here: if the
280 // access path involved any virtual steps, the conversion path will
281 // *start* with a step down to the correct virtual base subobject,
282 // and hence will not require any further steps.
Anders Carlssond829a022010-04-24 21:06:20 +0000283 if ((*Start)->isVirtual()) {
Simon Pilgrim1cd399c2019-10-03 11:22:48 +0000284 VBase = cast<CXXRecordDecl>(
285 (*Start)->getType()->castAs<RecordType>()->getDecl());
Anders Carlssond829a022010-04-24 21:06:20 +0000286 ++Start;
287 }
John McCall13a39c62012-08-01 05:04:58 +0000288
289 // Compute the static offset of the ultimate destination within its
290 // allocating subobject (the virtual base, if there is one, or else
291 // the "complete" object that we see).
David Majnemerc1709d32015-06-23 07:31:11 +0000292 CharUnits NonVirtualOffset = CGM.computeNonVirtualBaseClassOffset(
293 VBase ? VBase : Derived, Start, PathEnd);
Anders Carlssond829a022010-04-24 21:06:20 +0000294
John McCall13a39c62012-08-01 05:04:58 +0000295 // If there's a virtual step, we can sometimes "devirtualize" it.
296 // For now, that's limited to when the derived type is final.
297 // TODO: "devirtualize" this for accesses to known-complete objects.
298 if (VBase && Derived->hasAttr<FinalAttr>()) {
299 const ASTRecordLayout &layout = getContext().getASTRecordLayout(Derived);
300 CharUnits vBaseOffset = layout.getVBaseClassOffset(VBase);
301 NonVirtualOffset += vBaseOffset;
Craig Topper8a13c412014-05-21 05:09:00 +0000302 VBase = nullptr; // we no longer have a virtual step
John McCall13a39c62012-08-01 05:04:58 +0000303 }
304
Anders Carlssond829a022010-04-24 21:06:20 +0000305 // Get the base pointer type.
Justin Bogner1cd11f12015-05-20 15:53:59 +0000306 llvm::Type *BasePtrTy =
Anastasia Stulova94049552019-03-07 16:23:15 +0000307 ConvertType((PathEnd[-1])->getType())
308 ->getPointerTo(Value.getType()->getPointerAddressSpace());
John McCall13a39c62012-08-01 05:04:58 +0000309
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000310 QualType DerivedTy = getContext().getRecordType(Derived);
John McCall7f416cc2015-09-08 08:05:57 +0000311 CharUnits DerivedAlign = CGM.getClassPointerAlignment(Derived);
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000312
John McCall13a39c62012-08-01 05:04:58 +0000313 // If the static offset is zero and we don't have a virtual step,
314 // just do a bitcast; null checks are unnecessary.
Ken Dycka1a4ae32011-03-22 00:53:26 +0000315 if (NonVirtualOffset.isZero() && !VBase) {
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000316 if (sanitizePerformTypeCheck()) {
Vedant Kumar18348ea2017-02-17 23:22:55 +0000317 SanitizerSet SkippedChecks;
318 SkippedChecks.set(SanitizerKind::Null, !NullCheckValue);
John McCall7f416cc2015-09-08 08:05:57 +0000319 EmitTypeCheck(TCK_Upcast, Loc, Value.getPointer(),
Vedant Kumar18348ea2017-02-17 23:22:55 +0000320 DerivedTy, DerivedAlign, SkippedChecks);
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000321 }
Anders Carlssond829a022010-04-24 21:06:20 +0000322 return Builder.CreateBitCast(Value, BasePtrTy);
Craig Topper8a13c412014-05-21 05:09:00 +0000323 }
John McCall13a39c62012-08-01 05:04:58 +0000324
Craig Topper8a13c412014-05-21 05:09:00 +0000325 llvm::BasicBlock *origBB = nullptr;
326 llvm::BasicBlock *endBB = nullptr;
327
John McCall13a39c62012-08-01 05:04:58 +0000328 // Skip over the offset (and the vtable load) if we're supposed to
329 // null-check the pointer.
Anders Carlssond829a022010-04-24 21:06:20 +0000330 if (NullCheckValue) {
John McCall13a39c62012-08-01 05:04:58 +0000331 origBB = Builder.GetInsertBlock();
332 llvm::BasicBlock *notNullBB = createBasicBlock("cast.notnull");
333 endBB = createBasicBlock("cast.end");
Justin Bogner1cd11f12015-05-20 15:53:59 +0000334
John McCall7f416cc2015-09-08 08:05:57 +0000335 llvm::Value *isNull = Builder.CreateIsNull(Value.getPointer());
John McCall13a39c62012-08-01 05:04:58 +0000336 Builder.CreateCondBr(isNull, endBB, notNullBB);
337 EmitBlock(notNullBB);
Anders Carlssond829a022010-04-24 21:06:20 +0000338 }
339
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000340 if (sanitizePerformTypeCheck()) {
Vedant Kumar18348ea2017-02-17 23:22:55 +0000341 SanitizerSet SkippedChecks;
342 SkippedChecks.set(SanitizerKind::Null, true);
John McCall7f416cc2015-09-08 08:05:57 +0000343 EmitTypeCheck(VBase ? TCK_UpcastToVirtualBase : TCK_Upcast, Loc,
Vedant Kumar18348ea2017-02-17 23:22:55 +0000344 Value.getPointer(), DerivedTy, DerivedAlign, SkippedChecks);
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000345 }
346
John McCall13a39c62012-08-01 05:04:58 +0000347 // Compute the virtual offset.
Craig Topper8a13c412014-05-21 05:09:00 +0000348 llvm::Value *VirtualOffset = nullptr;
Anders Carlssona376b532011-01-29 03:18:56 +0000349 if (VBase) {
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000350 VirtualOffset =
351 CGM.getCXXABI().GetVirtualBaseClassOffset(*this, Value, Derived, VBase);
Anders Carlssona376b532011-01-29 03:18:56 +0000352 }
Anders Carlssond829a022010-04-24 21:06:20 +0000353
John McCall13a39c62012-08-01 05:04:58 +0000354 // Apply both offsets.
John McCall7f416cc2015-09-08 08:05:57 +0000355 Value = ApplyNonVirtualAndVirtualOffset(*this, Value, NonVirtualOffset,
356 VirtualOffset, Derived, VBase);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000357
John McCall13a39c62012-08-01 05:04:58 +0000358 // Cast to the destination type.
Anders Carlssond829a022010-04-24 21:06:20 +0000359 Value = Builder.CreateBitCast(Value, BasePtrTy);
John McCall13a39c62012-08-01 05:04:58 +0000360
361 // Build a phi if we needed a null check.
Anders Carlssond829a022010-04-24 21:06:20 +0000362 if (NullCheckValue) {
John McCall13a39c62012-08-01 05:04:58 +0000363 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
364 Builder.CreateBr(endBB);
365 EmitBlock(endBB);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000366
John McCall13a39c62012-08-01 05:04:58 +0000367 llvm::PHINode *PHI = Builder.CreatePHI(BasePtrTy, 2, "cast.result");
John McCall7f416cc2015-09-08 08:05:57 +0000368 PHI->addIncoming(Value.getPointer(), notNullBB);
John McCall13a39c62012-08-01 05:04:58 +0000369 PHI->addIncoming(llvm::Constant::getNullValue(BasePtrTy), origBB);
John McCall7f416cc2015-09-08 08:05:57 +0000370 Value = Address(PHI, Value.getAlignment());
Anders Carlssond829a022010-04-24 21:06:20 +0000371 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000372
Anders Carlssond829a022010-04-24 21:06:20 +0000373 return Value;
374}
375
John McCall7f416cc2015-09-08 08:05:57 +0000376Address
377CodeGenFunction::GetAddressOfDerivedClass(Address BaseAddr,
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000378 const CXXRecordDecl *Derived,
John McCallcf142162010-08-07 06:22:56 +0000379 CastExpr::path_const_iterator PathBegin,
380 CastExpr::path_const_iterator PathEnd,
Anders Carlsson8c793172009-11-23 17:57:54 +0000381 bool NullCheckValue) {
John McCallcf142162010-08-07 06:22:56 +0000382 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlsson8a64c1c2010-04-24 21:23:59 +0000383
Anders Carlsson8c793172009-11-23 17:57:54 +0000384 QualType DerivedTy =
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000385 getContext().getCanonicalType(getContext().getTagDeclType(Derived));
Sven van Haastregtaf6248c2019-10-17 14:12:51 +0000386 unsigned AddrSpace =
387 BaseAddr.getPointer()->getType()->getPointerAddressSpace();
388 llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo(AddrSpace);
Richard Smith2c5868c2013-02-13 21:18:23 +0000389
Anders Carlsson600f7372010-01-31 01:43:37 +0000390 llvm::Value *NonVirtualOffset =
John McCallcf142162010-08-07 06:22:56 +0000391 CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000392
Anders Carlsson600f7372010-01-31 01:43:37 +0000393 if (!NonVirtualOffset) {
394 // No offset, we can just cast back.
John McCall7f416cc2015-09-08 08:05:57 +0000395 return Builder.CreateBitCast(BaseAddr, DerivedPtrTy);
Anders Carlsson600f7372010-01-31 01:43:37 +0000396 }
Craig Topper8a13c412014-05-21 05:09:00 +0000397
398 llvm::BasicBlock *CastNull = nullptr;
399 llvm::BasicBlock *CastNotNull = nullptr;
400 llvm::BasicBlock *CastEnd = nullptr;
401
Anders Carlsson8c793172009-11-23 17:57:54 +0000402 if (NullCheckValue) {
403 CastNull = createBasicBlock("cast.null");
404 CastNotNull = createBasicBlock("cast.notnull");
405 CastEnd = createBasicBlock("cast.end");
Justin Bogner1cd11f12015-05-20 15:53:59 +0000406
John McCall7f416cc2015-09-08 08:05:57 +0000407 llvm::Value *IsNull = Builder.CreateIsNull(BaseAddr.getPointer());
Anders Carlsson8c793172009-11-23 17:57:54 +0000408 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
409 EmitBlock(CastNotNull);
410 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000411
Anders Carlsson600f7372010-01-31 01:43:37 +0000412 // Apply the offset.
John McCall7f416cc2015-09-08 08:05:57 +0000413 llvm::Value *Value = Builder.CreateBitCast(BaseAddr.getPointer(), Int8PtrTy);
Sanjay Patel372c3f12018-01-19 15:14:51 +0000414 Value = Builder.CreateInBoundsGEP(Value, Builder.CreateNeg(NonVirtualOffset),
415 "sub.ptr");
Anders Carlsson600f7372010-01-31 01:43:37 +0000416
417 // Just cast.
418 Value = Builder.CreateBitCast(Value, DerivedPtrTy);
Anders Carlsson8c793172009-11-23 17:57:54 +0000419
John McCall7f416cc2015-09-08 08:05:57 +0000420 // Produce a PHI if we had a null-check.
Anders Carlsson8c793172009-11-23 17:57:54 +0000421 if (NullCheckValue) {
422 Builder.CreateBr(CastEnd);
423 EmitBlock(CastNull);
424 Builder.CreateBr(CastEnd);
425 EmitBlock(CastEnd);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000426
Jay Foad20c0f022011-03-30 11:28:58 +0000427 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
Anders Carlsson8c793172009-11-23 17:57:54 +0000428 PHI->addIncoming(Value, CastNotNull);
John McCall7f416cc2015-09-08 08:05:57 +0000429 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
Anders Carlsson8c793172009-11-23 17:57:54 +0000430 Value = PHI;
431 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000432
John McCall7f416cc2015-09-08 08:05:57 +0000433 return Address(Value, CGM.getClassPointerAlignment(Derived));
Anders Carlsson9a57c5a2009-09-12 04:27:24 +0000434}
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000435
436llvm::Value *CodeGenFunction::GetVTTParameter(GlobalDecl GD,
437 bool ForVirtualBase,
438 bool Delegating) {
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000439 if (!CGM.getCXXABI().NeedsVTTParameter(GD)) {
Anders Carlssone36a6b32010-01-02 01:01:18 +0000440 // This constructor/destructor does not need a VTT parameter.
Craig Topper8a13c412014-05-21 05:09:00 +0000441 return nullptr;
Anders Carlssone36a6b32010-01-02 01:01:18 +0000442 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000443
John McCalldec348f72013-05-03 07:33:41 +0000444 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CurCodeDecl)->getParent();
Anders Carlssone36a6b32010-01-02 01:01:18 +0000445 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
John McCall5c60a6f2010-02-18 19:59:28 +0000446
Anders Carlssone36a6b32010-01-02 01:01:18 +0000447 llvm::Value *VTT;
448
John McCall5c60a6f2010-02-18 19:59:28 +0000449 uint64_t SubVTTIndex;
450
Douglas Gregor61535002013-01-31 05:50:40 +0000451 if (Delegating) {
452 // If this is a delegating constructor call, just load the VTT.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000453 return LoadCXXVTT();
Douglas Gregor61535002013-01-31 05:50:40 +0000454 } else if (RD == Base) {
455 // If the record matches the base, this is the complete ctor/dtor
456 // variant calling the base variant in a class with virtual bases.
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000457 assert(!CGM.getCXXABI().NeedsVTTParameter(CurGD) &&
John McCall5c60a6f2010-02-18 19:59:28 +0000458 "doing no-op VTT offset in base dtor/ctor?");
Anders Carlsson4d205ba2010-05-02 23:33:10 +0000459 assert(!ForVirtualBase && "Can't have same class as virtual base!");
John McCall5c60a6f2010-02-18 19:59:28 +0000460 SubVTTIndex = 0;
461 } else {
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000462 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000463 CharUnits BaseOffset = ForVirtualBase ?
464 Layout.getVBaseClassOffset(Base) :
Ken Dyck16ffcac2011-03-24 01:21:01 +0000465 Layout.getBaseClassOffset(Base);
Anders Carlsson859b3062010-05-02 23:53:25 +0000466
Justin Bogner1cd11f12015-05-20 15:53:59 +0000467 SubVTTIndex =
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000468 CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
John McCall5c60a6f2010-02-18 19:59:28 +0000469 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
470 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000471
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000472 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
Anders Carlssone36a6b32010-01-02 01:01:18 +0000473 // A VTT parameter was passed to the constructor, use it.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000474 VTT = LoadCXXVTT();
475 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
Anders Carlssone36a6b32010-01-02 01:01:18 +0000476 } else {
477 // We're the complete constructor, so get the VTT by name.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000478 VTT = CGM.getVTables().GetAddrOfVTT(RD);
479 VTT = Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
Anders Carlssone36a6b32010-01-02 01:01:18 +0000480 }
481
482 return VTT;
483}
484
John McCall1d987562010-07-21 01:23:41 +0000485namespace {
John McCallf99a6312010-07-21 05:30:47 +0000486 /// Call the destructor for a direct base class.
David Blaikie7e70d682015-08-18 22:40:54 +0000487 struct CallBaseDtor final : EHScopeStack::Cleanup {
John McCallf99a6312010-07-21 05:30:47 +0000488 const CXXRecordDecl *BaseClass;
489 bool BaseIsVirtual;
490 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
491 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
John McCall1d987562010-07-21 01:23:41 +0000492
Craig Topper4f12f102014-03-12 06:41:41 +0000493 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallf99a6312010-07-21 05:30:47 +0000494 const CXXRecordDecl *DerivedClass =
495 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
496
497 const CXXDestructorDecl *D = BaseClass->getDestructor();
Marco Antognini88559632019-07-22 09:39:13 +0000498 // We are already inside a destructor, so presumably the object being
499 // destroyed should have the expected type.
500 QualType ThisTy = D->getThisObjectType();
John McCall7f416cc2015-09-08 08:05:57 +0000501 Address Addr =
502 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThisAddress(),
John McCallf99a6312010-07-21 05:30:47 +0000503 DerivedClass, BaseClass,
504 BaseIsVirtual);
Douglas Gregor61535002013-01-31 05:50:40 +0000505 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual,
Marco Antognini88559632019-07-22 09:39:13 +0000506 /*Delegating=*/false, Addr, ThisTy);
John McCall1d987562010-07-21 01:23:41 +0000507 }
508 };
John McCall769250e2010-09-17 02:31:44 +0000509
510 /// A visitor which checks whether an initializer uses 'this' in a
511 /// way which requires the vtable to be properly set.
Scott Douglass503fc392015-06-10 13:53:15 +0000512 struct DynamicThisUseChecker : ConstEvaluatedExprVisitor<DynamicThisUseChecker> {
513 typedef ConstEvaluatedExprVisitor<DynamicThisUseChecker> super;
John McCall769250e2010-09-17 02:31:44 +0000514
515 bool UsesThis;
516
Scott Douglass503fc392015-06-10 13:53:15 +0000517 DynamicThisUseChecker(const ASTContext &C) : super(C), UsesThis(false) {}
John McCall769250e2010-09-17 02:31:44 +0000518
519 // Black-list all explicit and implicit references to 'this'.
520 //
521 // Do we need to worry about external references to 'this' derived
522 // from arbitrary code? If so, then anything which runs arbitrary
523 // external code might potentially access the vtable.
Scott Douglass503fc392015-06-10 13:53:15 +0000524 void VisitCXXThisExpr(const CXXThisExpr *E) { UsesThis = true; }
John McCall769250e2010-09-17 02:31:44 +0000525 };
Hans Wennborgdcfba332015-10-06 23:40:43 +0000526} // end anonymous namespace
John McCall769250e2010-09-17 02:31:44 +0000527
528static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
529 DynamicThisUseChecker Checker(C);
Scott Douglass503fc392015-06-10 13:53:15 +0000530 Checker.Visit(Init);
John McCall769250e2010-09-17 02:31:44 +0000531 return Checker.UsesThis;
John McCall1d987562010-07-21 01:23:41 +0000532}
533
Justin Bogner1cd11f12015-05-20 15:53:59 +0000534static void EmitBaseInitializer(CodeGenFunction &CGF,
Anders Carlssonfb404882009-12-24 22:46:43 +0000535 const CXXRecordDecl *ClassDecl,
Reid Kleckner61c9b7c2019-03-18 22:41:50 +0000536 CXXCtorInitializer *BaseInit) {
Anders Carlssonfb404882009-12-24 22:46:43 +0000537 assert(BaseInit->isBaseInitializer() &&
538 "Must have base initializer!");
539
John McCall7f416cc2015-09-08 08:05:57 +0000540 Address ThisPtr = CGF.LoadCXXThisAddress();
Justin Bogner1cd11f12015-05-20 15:53:59 +0000541
Anders Carlssonfb404882009-12-24 22:46:43 +0000542 const Type *BaseType = BaseInit->getBaseClass();
Simon Pilgrim1cd399c2019-10-03 11:22:48 +0000543 const auto *BaseClassDecl =
544 cast<CXXRecordDecl>(BaseType->castAs<RecordType>()->getDecl());
Anders Carlssonfb404882009-12-24 22:46:43 +0000545
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +0000546 bool isBaseVirtual = BaseInit->isBaseVirtual();
Anders Carlssonfb404882009-12-24 22:46:43 +0000547
John McCall769250e2010-09-17 02:31:44 +0000548 // If the initializer for the base (other than the constructor
549 // itself) accesses 'this' in any way, we need to initialize the
550 // vtables.
551 if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
552 CGF.InitializeVTablePointers(ClassDecl);
553
John McCall6ce74722010-02-16 04:15:37 +0000554 // We can pretend to be a complete class because it only matters for
555 // virtual bases, and we only do virtual bases for complete ctors.
John McCall7f416cc2015-09-08 08:05:57 +0000556 Address V =
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000557 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
John McCallf99a6312010-07-21 05:30:47 +0000558 BaseClassDecl,
559 isBaseVirtual);
John McCall8d6fc952011-08-25 20:40:09 +0000560 AggValueSlot AggSlot =
Richard Smithe78fac52018-04-05 20:52:58 +0000561 AggValueSlot::forAddr(
562 V, Qualifiers(),
563 AggValueSlot::IsDestructed,
564 AggValueSlot::DoesNotNeedGCBarriers,
565 AggValueSlot::IsNotAliased,
Richard Smith8cca3a52019-06-20 20:56:20 +0000566 CGF.getOverlapForBaseInit(ClassDecl, BaseClassDecl, isBaseVirtual));
John McCall7a626f62010-09-15 10:14:12 +0000567
568 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000569
570 if (CGF.CGM.getLangOpts().Exceptions &&
Anders Carlsson08ce5ed2011-02-20 00:20:27 +0000571 !BaseClassDecl->hasTrivialDestructor())
John McCallcda666c2010-07-21 07:22:38 +0000572 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
573 isBaseVirtual);
Anders Carlssonfb404882009-12-24 22:46:43 +0000574}
575
Richard Smith419bd092015-04-29 19:26:57 +0000576static bool isMemcpyEquivalentSpecialMember(const CXXMethodDecl *D) {
577 auto *CD = dyn_cast<CXXConstructorDecl>(D);
578 if (!(CD && CD->isCopyOrMoveConstructor()) &&
579 !D->isCopyAssignmentOperator() && !D->isMoveAssignmentOperator())
580 return false;
581
582 // We can emit a memcpy for a trivial copy or move constructor/assignment.
583 if (D->isTrivial() && !D->getParent()->mayInsertExtraPadding())
584 return true;
585
586 // We *must* emit a memcpy for a defaulted union copy or move op.
587 if (D->getParent()->isUnion() && D->isDefaulted())
588 return true;
589
590 return false;
591}
592
Alexey Bataev152c71f2015-07-14 07:55:48 +0000593static void EmitLValueForAnyFieldInitialization(CodeGenFunction &CGF,
594 CXXCtorInitializer *MemberInit,
595 LValue &LHS) {
596 FieldDecl *Field = MemberInit->getAnyMember();
597 if (MemberInit->isIndirectMemberInitializer()) {
598 // If we are initializing an anonymous union field, drill down to the field.
599 IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember();
600 for (const auto *I : IndirectField->chain())
601 LHS = CGF.EmitLValueForFieldInitialization(LHS, cast<FieldDecl>(I));
602 } else {
603 LHS = CGF.EmitLValueForFieldInitialization(LHS, Field);
604 }
605}
606
Anders Carlssonfb404882009-12-24 22:46:43 +0000607static void EmitMemberInitializer(CodeGenFunction &CGF,
608 const CXXRecordDecl *ClassDecl,
Alexis Hunt1d792652011-01-08 20:30:50 +0000609 CXXCtorInitializer *MemberInit,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000610 const CXXConstructorDecl *Constructor,
611 FunctionArgList &Args) {
David Blaikiea81d4102015-01-18 00:12:58 +0000612 ApplyDebugLocation Loc(CGF, MemberInit->getSourceLocation());
Francois Pichetd583da02010-12-04 09:14:42 +0000613 assert(MemberInit->isAnyMemberInitializer() &&
Anders Carlssonfb404882009-12-24 22:46:43 +0000614 "Must have member initializer!");
Richard Smith938f40b2011-06-11 17:19:42 +0000615 assert(MemberInit->getInit() && "Must have initializer!");
Justin Bogner1cd11f12015-05-20 15:53:59 +0000616
Anders Carlssonfb404882009-12-24 22:46:43 +0000617 // non-static data member initializers.
Francois Pichetd583da02010-12-04 09:14:42 +0000618 FieldDecl *Field = MemberInit->getAnyMember();
Eli Friedman6ae63022012-02-14 02:15:49 +0000619 QualType FieldType = Field->getType();
Anders Carlssonfb404882009-12-24 22:46:43 +0000620
621 llvm::Value *ThisPtr = CGF.LoadCXXThis();
Eli Friedman7f1ff602012-04-16 03:54:45 +0000622 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
Akira Hatanakae5dbb642018-01-27 00:34:09 +0000623 LValue LHS;
624
625 // If a base constructor is being emitted, create an LValue that has the
626 // non-virtual alignment.
627 if (CGF.CurGD.getCtorType() == Ctor_Base)
628 LHS = CGF.MakeNaturalAlignPointeeAddrLValue(ThisPtr, RecordTy);
629 else
630 LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
Eli Friedman7f1ff602012-04-16 03:54:45 +0000631
Alexey Bataev152c71f2015-07-14 07:55:48 +0000632 EmitLValueForAnyFieldInitialization(CGF, MemberInit, LHS);
Anders Carlssonfb404882009-12-24 22:46:43 +0000633
Eli Friedman6ae63022012-02-14 02:15:49 +0000634 // Special case: if we are in a copy or move constructor, and we are copying
635 // an array of PODs or classes with trivial copy constructors, ignore the
636 // AST and perform the copy we know is equivalent.
637 // FIXME: This is hacky at best... if we had a bit more explicit information
638 // in the AST, we could generalize it more easily.
639 const ConstantArrayType *Array
640 = CGF.getContext().getAsConstantArrayType(FieldType);
Jordan Rose54533f72013-08-07 16:16:48 +0000641 if (Array && Constructor->isDefaulted() &&
Eli Friedman6ae63022012-02-14 02:15:49 +0000642 Constructor->isCopyOrMoveConstructor()) {
643 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
Richard Smith993f25a2012-11-07 23:56:21 +0000644 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
Eli Friedman6ae63022012-02-14 02:15:49 +0000645 if (BaseElementTy.isPODType(CGF.getContext()) ||
Richard Smith419bd092015-04-29 19:26:57 +0000646 (CE && isMemcpyEquivalentSpecialMember(CE->getConstructor()))) {
David Majnemer1573d732014-10-15 04:54:54 +0000647 unsigned SrcArgIndex =
648 CGF.CGM.getCXXABI().getSrcArgforCopyCtor(Constructor, Args);
Eli Friedman6ae63022012-02-14 02:15:49 +0000649 llvm::Value *SrcPtr
650 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
Eli Friedman7f1ff602012-04-16 03:54:45 +0000651 LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
652 LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000653
Eli Friedman6ae63022012-02-14 02:15:49 +0000654 // Copy the aggregate.
Richard Smith8cca3a52019-06-20 20:56:20 +0000655 CGF.EmitAggregateCopy(LHS, Src, FieldType, CGF.getOverlapForFieldInit(Field),
Richard Smithe78fac52018-04-05 20:52:58 +0000656 LHS.isVolatileQualified());
Alexey Bataev5d49b832015-07-08 07:31:02 +0000657 // Ensure that we destroy the objects if an exception is thrown later in
658 // the constructor.
659 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
660 if (CGF.needsEHCleanup(dtorKind))
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800661 CGF.pushEHDestroy(dtorKind, LHS.getAddress(CGF), FieldType);
Eli Friedman6ae63022012-02-14 02:15:49 +0000662 return;
663 }
664 }
665
Richard Smith30e304e2016-12-14 00:03:17 +0000666 CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit());
Eli Friedman6ae63022012-02-14 02:15:49 +0000667}
668
John McCall7f416cc2015-09-08 08:05:57 +0000669void CodeGenFunction::EmitInitializerForField(FieldDecl *Field, LValue LHS,
Richard Smith30e304e2016-12-14 00:03:17 +0000670 Expr *Init) {
Eli Friedman6ae63022012-02-14 02:15:49 +0000671 QualType FieldType = Field->getType();
John McCall47fb9502013-03-07 21:37:08 +0000672 switch (getEvaluationKind(FieldType)) {
673 case TEK_Scalar:
John McCall31168b02011-06-15 23:02:42 +0000674 if (LHS.isSimple()) {
David Blaikie66e41972015-01-14 07:38:27 +0000675 EmitExprAsInit(Init, Field, LHS, false);
John McCall31168b02011-06-15 23:02:42 +0000676 } else {
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000677 RValue RHS = RValue::get(EmitScalarExpr(Init));
678 EmitStoreThroughLValue(RHS, LHS);
John McCall31168b02011-06-15 23:02:42 +0000679 }
John McCall47fb9502013-03-07 21:37:08 +0000680 break;
681 case TEK_Complex:
David Blaikie66e41972015-01-14 07:38:27 +0000682 EmitComplexExprIntoLValue(Init, LHS, /*isInit*/ true);
John McCall47fb9502013-03-07 21:37:08 +0000683 break;
684 case TEK_Aggregate: {
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800685 AggValueSlot Slot = AggValueSlot::forLValue(
686 LHS, *this, AggValueSlot::IsDestructed,
687 AggValueSlot::DoesNotNeedGCBarriers, AggValueSlot::IsNotAliased,
688 getOverlapForFieldInit(Field), AggValueSlot::IsNotZeroed,
689 // Checks are made by the code that calls constructor.
690 AggValueSlot::IsSanitizerChecked);
Richard Smith30e304e2016-12-14 00:03:17 +0000691 EmitAggExpr(Init, Slot);
692 break;
Anders Carlssonfb404882009-12-24 22:46:43 +0000693 }
John McCall47fb9502013-03-07 21:37:08 +0000694 }
John McCall12cc42a2013-02-01 05:11:40 +0000695
696 // Ensure that we destroy this object if an exception is thrown
697 // later in the constructor.
698 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
699 if (needsEHCleanup(dtorKind))
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800700 pushEHDestroy(dtorKind, LHS.getAddress(*this), FieldType);
Anders Carlssonfb404882009-12-24 22:46:43 +0000701}
702
John McCallf8ff7b92010-02-23 00:48:20 +0000703/// Checks whether the given constructor is a valid subject for the
704/// complete-to-base constructor delegation optimization, i.e.
705/// emitting the complete constructor as a simple call to the base
706/// constructor.
Vedant Kumar7f809b22017-02-24 01:15:19 +0000707bool CodeGenFunction::IsConstructorDelegationValid(
708 const CXXConstructorDecl *Ctor) {
John McCallf8ff7b92010-02-23 00:48:20 +0000709
710 // Currently we disable the optimization for classes with virtual
711 // bases because (1) the addresses of parameter variables need to be
712 // consistent across all initializers but (2) the delegate function
713 // call necessarily creates a second copy of the parameter variable.
714 //
715 // The limiting example (purely theoretical AFAIK):
716 // struct A { A(int &c) { c++; } };
717 // struct B : virtual A {
718 // B(int count) : A(count) { printf("%d\n", count); }
719 // };
720 // ...although even this example could in principle be emitted as a
721 // delegation since the address of the parameter doesn't escape.
722 if (Ctor->getParent()->getNumVBases()) {
723 // TODO: white-list trivial vbase initializers. This case wouldn't
724 // be subject to the restrictions below.
725
726 // TODO: white-list cases where:
727 // - there are no non-reference parameters to the constructor
728 // - the initializers don't access any non-reference parameters
729 // - the initializers don't take the address of non-reference
730 // parameters
731 // - etc.
732 // If we ever add any of the above cases, remember that:
733 // - function-try-blocks will always blacklist this optimization
734 // - we need to perform the constructor prologue and cleanup in
735 // EmitConstructorBody.
736
737 return false;
738 }
739
740 // We also disable the optimization for variadic functions because
741 // it's impossible to "re-pass" varargs.
Simon Pilgrim7e38f0c2019-10-07 16:42:25 +0000742 if (Ctor->getType()->castAs<FunctionProtoType>()->isVariadic())
John McCallf8ff7b92010-02-23 00:48:20 +0000743 return false;
744
Alexis Hunt61bc1732011-05-01 07:04:31 +0000745 // FIXME: Decide if we can do a delegation of a delegating constructor.
746 if (Ctor->isDelegatingConstructor())
747 return false;
748
John McCallf8ff7b92010-02-23 00:48:20 +0000749 return true;
750}
751
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000752// Emit code in ctor (Prologue==true) or dtor (Prologue==false)
753// to poison the extra field paddings inserted under
754// -fsanitize-address-field-padding=1|2.
755void CodeGenFunction::EmitAsanPrologueOrEpilogue(bool Prologue) {
756 ASTContext &Context = getContext();
757 const CXXRecordDecl *ClassDecl =
758 Prologue ? cast<CXXConstructorDecl>(CurGD.getDecl())->getParent()
759 : cast<CXXDestructorDecl>(CurGD.getDecl())->getParent();
760 if (!ClassDecl->mayInsertExtraPadding()) return;
761
762 struct SizeAndOffset {
763 uint64_t Size;
764 uint64_t Offset;
765 };
766
767 unsigned PtrSize = CGM.getDataLayout().getPointerSizeInBits();
768 const ASTRecordLayout &Info = Context.getASTRecordLayout(ClassDecl);
769
770 // Populate sizes and offsets of fields.
771 SmallVector<SizeAndOffset, 16> SSV(Info.getFieldCount());
772 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i)
773 SSV[i].Offset =
774 Context.toCharUnitsFromBits(Info.getFieldOffset(i)).getQuantity();
775
776 size_t NumFields = 0;
777 for (const auto *Field : ClassDecl->fields()) {
778 const FieldDecl *D = Field;
779 std::pair<CharUnits, CharUnits> FieldInfo =
780 Context.getTypeInfoInChars(D->getType());
781 CharUnits FieldSize = FieldInfo.first;
782 assert(NumFields < SSV.size());
783 SSV[NumFields].Size = D->isBitField() ? 0 : FieldSize.getQuantity();
784 NumFields++;
785 }
786 assert(NumFields == SSV.size());
787 if (SSV.size() <= 1) return;
788
789 // We will insert calls to __asan_* run-time functions.
790 // LLVM AddressSanitizer pass may decide to inline them later.
791 llvm::Type *Args[2] = {IntPtrTy, IntPtrTy};
792 llvm::FunctionType *FTy =
793 llvm::FunctionType::get(CGM.VoidTy, Args, false);
James Y Knight9871db02019-02-05 16:42:33 +0000794 llvm::FunctionCallee F = CGM.CreateRuntimeFunction(
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000795 FTy, Prologue ? "__asan_poison_intra_object_redzone"
796 : "__asan_unpoison_intra_object_redzone");
797
798 llvm::Value *ThisPtr = LoadCXXThis();
799 ThisPtr = Builder.CreatePtrToInt(ThisPtr, IntPtrTy);
Kostya Serebryany64449212014-10-17 21:02:13 +0000800 uint64_t TypeSize = Info.getNonVirtualSize().getQuantity();
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000801 // For each field check if it has sufficient padding,
802 // if so (un)poison it with a call.
803 for (size_t i = 0; i < SSV.size(); i++) {
804 uint64_t AsanAlignment = 8;
805 uint64_t NextField = i == SSV.size() - 1 ? TypeSize : SSV[i + 1].Offset;
806 uint64_t PoisonSize = NextField - SSV[i].Offset - SSV[i].Size;
807 uint64_t EndOffset = SSV[i].Offset + SSV[i].Size;
808 if (PoisonSize < AsanAlignment || !SSV[i].Size ||
809 (NextField % AsanAlignment) != 0)
810 continue;
David Blaikie43f9bb72015-05-18 22:14:03 +0000811 Builder.CreateCall(
812 F, {Builder.CreateAdd(ThisPtr, Builder.getIntN(PtrSize, EndOffset)),
813 Builder.getIntN(PtrSize, PoisonSize)});
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000814 }
815}
816
John McCallb81884d2010-02-19 09:25:03 +0000817/// EmitConstructorBody - Emits the body of the current constructor.
818void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000819 EmitAsanPrologueOrEpilogue(true);
John McCallb81884d2010-02-19 09:25:03 +0000820 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
821 CXXCtorType CtorType = CurGD.getCtorType();
822
Reid Kleckner340ad862014-01-13 22:57:31 +0000823 assert((CGM.getTarget().getCXXABI().hasConstructorVariants() ||
824 CtorType == Ctor_Complete) &&
825 "can only generate complete ctor for this ABI");
826
John McCallf8ff7b92010-02-23 00:48:20 +0000827 // Before we go any further, try the complete->base constructor
828 // delegation optimization.
Timur Iskhodzhanovf32a3772012-04-20 08:05:00 +0000829 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
John McCallc8e01702013-04-16 22:48:15 +0000830 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000831 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args, Ctor->getEndLoc());
John McCallf8ff7b92010-02-23 00:48:20 +0000832 return;
833 }
834
Hans Wennborgdcfba332015-10-06 23:40:43 +0000835 const FunctionDecl *Definition = nullptr;
Richard Smith46bb5812014-08-01 01:56:39 +0000836 Stmt *Body = Ctor->getBody(Definition);
837 assert(Definition == Ctor && "emitting wrong constructor body");
John McCallb81884d2010-02-19 09:25:03 +0000838
John McCallf8ff7b92010-02-23 00:48:20 +0000839 // Enter the function-try-block before the constructor prologue if
840 // applicable.
John McCallf8ff7b92010-02-23 00:48:20 +0000841 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallf8ff7b92010-02-23 00:48:20 +0000842 if (IsTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000843 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000844
Justin Bogner66242d62015-04-23 23:06:47 +0000845 incrementProfileCounter(Body);
Justin Bogner81c22c22014-01-23 02:54:27 +0000846
Richard Smithcc1b96d2013-06-12 22:31:48 +0000847 RunCleanupsScope RunCleanups(*this);
John McCallb81884d2010-02-19 09:25:03 +0000848
John McCall88313032012-03-30 04:25:03 +0000849 // TODO: in restricted cases, we can emit the vbase initializers of
850 // a complete ctor and then delegate to the base ctor.
851
John McCallf8ff7b92010-02-23 00:48:20 +0000852 // Emit the constructor prologue, i.e. the base and member
853 // initializers.
Douglas Gregor94f9a482010-05-05 05:51:00 +0000854 EmitCtorPrologue(Ctor, CtorType, Args);
John McCallb81884d2010-02-19 09:25:03 +0000855
856 // Emit the body of the statement.
John McCallf8ff7b92010-02-23 00:48:20 +0000857 if (IsTryBody)
John McCallb81884d2010-02-19 09:25:03 +0000858 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
859 else if (Body)
860 EmitStmt(Body);
John McCallb81884d2010-02-19 09:25:03 +0000861
862 // Emit any cleanup blocks associated with the member or base
863 // initializers, which includes (along the exceptional path) the
864 // destructors for those members and bases that were fully
865 // constructed.
Richard Smithcc1b96d2013-06-12 22:31:48 +0000866 RunCleanups.ForceCleanup();
John McCallb81884d2010-02-19 09:25:03 +0000867
John McCallf8ff7b92010-02-23 00:48:20 +0000868 if (IsTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000869 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000870}
871
Lang Hamesbf122742013-02-17 07:22:09 +0000872namespace {
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000873 /// RAII object to indicate that codegen is copying the value representation
874 /// instead of the object representation. Useful when copying a struct or
875 /// class which has uninitialized members and we're only performing
876 /// lvalue-to-rvalue conversion on the object but not its members.
877 class CopyingValueRepresentation {
878 public:
879 explicit CopyingValueRepresentation(CodeGenFunction &CGF)
Alexey Samsonov035462c2014-10-30 19:33:44 +0000880 : CGF(CGF), OldSanOpts(CGF.SanOpts) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000881 CGF.SanOpts.set(SanitizerKind::Bool, false);
882 CGF.SanOpts.set(SanitizerKind::Enum, false);
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000883 }
884 ~CopyingValueRepresentation() {
885 CGF.SanOpts = OldSanOpts;
886 }
887 private:
888 CodeGenFunction &CGF;
Alexey Samsonova0416102014-11-11 01:26:14 +0000889 SanitizerSet OldSanOpts;
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000890 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000891} // end anonymous namespace
Fangrui Song6907ce22018-07-30 19:24:48 +0000892
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000893namespace {
Lang Hamesbf122742013-02-17 07:22:09 +0000894 class FieldMemcpyizer {
895 public:
896 FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl,
897 const VarDecl *SrcRec)
Justin Bogner1cd11f12015-05-20 15:53:59 +0000898 : CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec),
Lang Hamesbf122742013-02-17 07:22:09 +0000899 RecLayout(CGF.getContext().getASTRecordLayout(ClassDecl)),
Craig Topper8a13c412014-05-21 05:09:00 +0000900 FirstField(nullptr), LastField(nullptr), FirstFieldOffset(0),
901 LastFieldOffset(0), LastAddedFieldIndex(0) {}
Lang Hamesbf122742013-02-17 07:22:09 +0000902
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000903 bool isMemcpyableField(FieldDecl *F) const {
904 // Never memcpy fields when we are adding poisoned paddings.
Alexey Samsonova0416102014-11-11 01:26:14 +0000905 if (CGF.getContext().getLangOpts().SanitizeAddressFieldPadding)
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000906 return false;
Lang Hamesbf122742013-02-17 07:22:09 +0000907 Qualifiers Qual = F->getType().getQualifiers();
908 if (Qual.hasVolatile() || Qual.hasObjCLifetime())
909 return false;
910 return true;
911 }
912
913 void addMemcpyableField(FieldDecl *F) {
Senran Zhang01d8e092019-11-26 10:15:14 +0800914 if (F->isZeroSize(CGF.getContext()))
915 return;
Craig Topper8a13c412014-05-21 05:09:00 +0000916 if (!FirstField)
Lang Hamesbf122742013-02-17 07:22:09 +0000917 addInitialField(F);
918 else
919 addNextField(F);
920 }
921
David Majnemera586eb22014-10-10 18:57:10 +0000922 CharUnits getMemcpySize(uint64_t FirstByteOffset) const {
Richard Smithe78fac52018-04-05 20:52:58 +0000923 ASTContext &Ctx = CGF.getContext();
Lang Hamesbf122742013-02-17 07:22:09 +0000924 unsigned LastFieldSize =
Richard Smithe78fac52018-04-05 20:52:58 +0000925 LastField->isBitField()
926 ? LastField->getBitWidthValue(Ctx)
927 : Ctx.toBits(
928 Ctx.getTypeInfoDataSizeInChars(LastField->getType()).first);
929 uint64_t MemcpySizeBits = LastFieldOffset + LastFieldSize -
930 FirstByteOffset + Ctx.getCharWidth() - 1;
931 CharUnits MemcpySize = Ctx.toCharUnitsFromBits(MemcpySizeBits);
Lang Hamesbf122742013-02-17 07:22:09 +0000932 return MemcpySize;
933 }
934
935 void emitMemcpy() {
936 // Give the subclass a chance to bail out if it feels the memcpy isn't
937 // worth it (e.g. Hasn't aggregated enough data).
Craig Topper8a13c412014-05-21 05:09:00 +0000938 if (!FirstField) {
Lang Hamesbf122742013-02-17 07:22:09 +0000939 return;
940 }
941
David Majnemera586eb22014-10-10 18:57:10 +0000942 uint64_t FirstByteOffset;
Lang Hamesbf122742013-02-17 07:22:09 +0000943 if (FirstField->isBitField()) {
944 const CGRecordLayout &RL =
945 CGF.getTypes().getCGRecordLayout(FirstField->getParent());
946 const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField);
David Majnemera586eb22014-10-10 18:57:10 +0000947 // FirstFieldOffset is not appropriate for bitfields,
Ulrich Weigand73263d72015-07-13 11:52:14 +0000948 // we need to use the storage offset instead.
Ulrich Weigand03ce2a12015-07-10 17:30:00 +0000949 FirstByteOffset = CGF.getContext().toBits(BFInfo.StorageOffset);
Lang Hames1694e0d2013-02-27 04:14:49 +0000950 } else {
David Majnemera586eb22014-10-10 18:57:10 +0000951 FirstByteOffset = FirstFieldOffset;
Lang Hames1694e0d2013-02-27 04:14:49 +0000952 }
Lang Hamesbf122742013-02-17 07:22:09 +0000953
David Majnemera586eb22014-10-10 18:57:10 +0000954 CharUnits MemcpySize = getMemcpySize(FirstByteOffset);
Lang Hamesbf122742013-02-17 07:22:09 +0000955 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
John McCall7f416cc2015-09-08 08:05:57 +0000956 Address ThisPtr = CGF.LoadCXXThisAddress();
957 LValue DestLV = CGF.MakeAddrLValue(ThisPtr, RecordTy);
Lang Hamesbf122742013-02-17 07:22:09 +0000958 LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField);
959 llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec));
960 LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
961 LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField);
962
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800963 emitMemcpyIR(
964 Dest.isBitField() ? Dest.getBitFieldAddress() : Dest.getAddress(CGF),
965 Src.isBitField() ? Src.getBitFieldAddress() : Src.getAddress(CGF),
966 MemcpySize);
Lang Hamesbf122742013-02-17 07:22:09 +0000967 reset();
968 }
969
970 void reset() {
Craig Topper8a13c412014-05-21 05:09:00 +0000971 FirstField = nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +0000972 }
973
974 protected:
975 CodeGenFunction &CGF;
976 const CXXRecordDecl *ClassDecl;
977
978 private:
John McCall7f416cc2015-09-08 08:05:57 +0000979 void emitMemcpyIR(Address DestPtr, Address SrcPtr, CharUnits Size) {
980 llvm::PointerType *DPT = DestPtr.getType();
Lang Hamesbf122742013-02-17 07:22:09 +0000981 llvm::Type *DBP =
982 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), DPT->getAddressSpace());
983 DestPtr = CGF.Builder.CreateBitCast(DestPtr, DBP);
984
John McCall7f416cc2015-09-08 08:05:57 +0000985 llvm::PointerType *SPT = SrcPtr.getType();
Lang Hamesbf122742013-02-17 07:22:09 +0000986 llvm::Type *SBP =
987 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), SPT->getAddressSpace());
988 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, SBP);
989
John McCall7f416cc2015-09-08 08:05:57 +0000990 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity());
Lang Hamesbf122742013-02-17 07:22:09 +0000991 }
992
993 void addInitialField(FieldDecl *F) {
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000994 FirstField = F;
995 LastField = F;
996 FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex());
997 LastFieldOffset = FirstFieldOffset;
998 LastAddedFieldIndex = F->getFieldIndex();
999 }
Lang Hamesbf122742013-02-17 07:22:09 +00001000
1001 void addNextField(FieldDecl *F) {
John McCall6054d5a2013-05-07 05:20:46 +00001002 // For the most part, the following invariant will hold:
1003 // F->getFieldIndex() == LastAddedFieldIndex + 1
1004 // The one exception is that Sema won't add a copy-initializer for an
1005 // unnamed bitfield, which will show up here as a gap in the sequence.
1006 assert(F->getFieldIndex() >= LastAddedFieldIndex + 1 &&
1007 "Cannot aggregate fields out of order.");
Lang Hamesbf122742013-02-17 07:22:09 +00001008 LastAddedFieldIndex = F->getFieldIndex();
1009
1010 // The 'first' and 'last' fields are chosen by offset, rather than field
1011 // index. This allows the code to support bitfields, as well as regular
1012 // fields.
1013 uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex());
1014 if (FOffset < FirstFieldOffset) {
1015 FirstField = F;
1016 FirstFieldOffset = FOffset;
John McCall7ae29f52019-04-10 18:07:18 +00001017 } else if (FOffset >= LastFieldOffset) {
Lang Hamesbf122742013-02-17 07:22:09 +00001018 LastField = F;
1019 LastFieldOffset = FOffset;
1020 }
1021 }
1022
1023 const VarDecl *SrcRec;
1024 const ASTRecordLayout &RecLayout;
1025 FieldDecl *FirstField;
1026 FieldDecl *LastField;
1027 uint64_t FirstFieldOffset, LastFieldOffset;
1028 unsigned LastAddedFieldIndex;
1029 };
1030
1031 class ConstructorMemcpyizer : public FieldMemcpyizer {
1032 private:
Lang Hamesbf122742013-02-17 07:22:09 +00001033 /// Get source argument for copy constructor. Returns null if not a copy
David Majnemer196ac332014-09-11 23:05:02 +00001034 /// constructor.
1035 static const VarDecl *getTrivialCopySource(CodeGenFunction &CGF,
1036 const CXXConstructorDecl *CD,
Lang Hamesbf122742013-02-17 07:22:09 +00001037 FunctionArgList &Args) {
Jordan Rose54533f72013-08-07 16:16:48 +00001038 if (CD->isCopyOrMoveConstructor() && CD->isDefaulted())
David Majnemer196ac332014-09-11 23:05:02 +00001039 return Args[CGF.CGM.getCXXABI().getSrcArgforCopyCtor(CD, Args)];
Craig Topper8a13c412014-05-21 05:09:00 +00001040 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001041 }
1042
1043 // Returns true if a CXXCtorInitializer represents a member initialization
1044 // that can be rolled into a memcpy.
1045 bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const {
1046 if (!MemcpyableCtor)
1047 return false;
1048 FieldDecl *Field = MemberInit->getMember();
Craig Topper8a13c412014-05-21 05:09:00 +00001049 assert(Field && "No field for member init.");
Lang Hamesbf122742013-02-17 07:22:09 +00001050 QualType FieldType = Field->getType();
1051 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
1052
Richard Smith419bd092015-04-29 19:26:57 +00001053 // Bail out on non-memcpyable, not-trivially-copyable members.
1054 if (!(CE && isMemcpyEquivalentSpecialMember(CE->getConstructor())) &&
Lang Hamesbf122742013-02-17 07:22:09 +00001055 !(FieldType.isTriviallyCopyableType(CGF.getContext()) ||
1056 FieldType->isReferenceType()))
1057 return false;
1058
1059 // Bail out on volatile fields.
1060 if (!isMemcpyableField(Field))
1061 return false;
1062
1063 // Otherwise we're good.
1064 return true;
1065 }
1066
1067 public:
1068 ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD,
1069 FunctionArgList &Args)
David Majnemer196ac332014-09-11 23:05:02 +00001070 : FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CGF, CD, Args)),
Lang Hamesbf122742013-02-17 07:22:09 +00001071 ConstructorDecl(CD),
Jordan Rose54533f72013-08-07 16:16:48 +00001072 MemcpyableCtor(CD->isDefaulted() &&
Lang Hamesbf122742013-02-17 07:22:09 +00001073 CD->isCopyOrMoveConstructor() &&
1074 CGF.getLangOpts().getGC() == LangOptions::NonGC),
1075 Args(Args) { }
1076
1077 void addMemberInitializer(CXXCtorInitializer *MemberInit) {
1078 if (isMemberInitMemcpyable(MemberInit)) {
1079 AggregatedInits.push_back(MemberInit);
1080 addMemcpyableField(MemberInit->getMember());
1081 } else {
1082 emitAggregatedInits();
1083 EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit,
1084 ConstructorDecl, Args);
1085 }
1086 }
1087
1088 void emitAggregatedInits() {
1089 if (AggregatedInits.size() <= 1) {
1090 // This memcpy is too small to be worthwhile. Fall back on default
1091 // codegen.
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001092 if (!AggregatedInits.empty()) {
1093 CopyingValueRepresentation CVR(CGF);
Lang Hamesbf122742013-02-17 07:22:09 +00001094 EmitMemberInitializer(CGF, ConstructorDecl->getParent(),
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001095 AggregatedInits[0], ConstructorDecl, Args);
Alexey Bataev152c71f2015-07-14 07:55:48 +00001096 AggregatedInits.clear();
Lang Hamesbf122742013-02-17 07:22:09 +00001097 }
1098 reset();
1099 return;
1100 }
1101
1102 pushEHDestructors();
1103 emitMemcpy();
1104 AggregatedInits.clear();
1105 }
1106
1107 void pushEHDestructors() {
John McCall7f416cc2015-09-08 08:05:57 +00001108 Address ThisPtr = CGF.LoadCXXThisAddress();
Lang Hamesbf122742013-02-17 07:22:09 +00001109 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
John McCall7f416cc2015-09-08 08:05:57 +00001110 LValue LHS = CGF.MakeAddrLValue(ThisPtr, RecordTy);
Lang Hamesbf122742013-02-17 07:22:09 +00001111
1112 for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
Alexey Bataev152c71f2015-07-14 07:55:48 +00001113 CXXCtorInitializer *MemberInit = AggregatedInits[i];
1114 QualType FieldType = MemberInit->getAnyMember()->getType();
Lang Hamesbf122742013-02-17 07:22:09 +00001115 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
Alexey Bataev152c71f2015-07-14 07:55:48 +00001116 if (!CGF.needsEHCleanup(dtorKind))
1117 continue;
1118 LValue FieldLHS = LHS;
1119 EmitLValueForAnyFieldInitialization(CGF, MemberInit, FieldLHS);
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001120 CGF.pushEHDestroy(dtorKind, FieldLHS.getAddress(CGF), FieldType);
Lang Hamesbf122742013-02-17 07:22:09 +00001121 }
1122 }
1123
1124 void finish() {
1125 emitAggregatedInits();
1126 }
1127
1128 private:
1129 const CXXConstructorDecl *ConstructorDecl;
1130 bool MemcpyableCtor;
1131 FunctionArgList &Args;
1132 SmallVector<CXXCtorInitializer*, 16> AggregatedInits;
1133 };
1134
1135 class AssignmentMemcpyizer : public FieldMemcpyizer {
1136 private:
Lang Hamesbf122742013-02-17 07:22:09 +00001137 // Returns the memcpyable field copied by the given statement, if one
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001138 // exists. Otherwise returns null.
1139 FieldDecl *getMemcpyableField(Stmt *S) {
Lang Hamesbf122742013-02-17 07:22:09 +00001140 if (!AssignmentsMemcpyable)
Craig Topper8a13c412014-05-21 05:09:00 +00001141 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001142 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
1143 // Recognise trivial assignments.
1144 if (BO->getOpcode() != BO_Assign)
Craig Topper8a13c412014-05-21 05:09:00 +00001145 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001146 MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS());
1147 if (!ME)
Craig Topper8a13c412014-05-21 05:09:00 +00001148 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001149 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1150 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001151 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001152 Stmt *RHS = BO->getRHS();
1153 if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS))
1154 RHS = EC->getSubExpr();
1155 if (!RHS)
Craig Topper8a13c412014-05-21 05:09:00 +00001156 return nullptr;
Warren Ristow8d17b402017-02-02 17:53:34 +00001157 if (MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS)) {
1158 if (ME2->getMemberDecl() == Field)
1159 return Field;
1160 }
1161 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001162 } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) {
1163 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl());
Richard Smith419bd092015-04-29 19:26:57 +00001164 if (!(MD && isMemcpyEquivalentSpecialMember(MD)))
Craig Topper8a13c412014-05-21 05:09:00 +00001165 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001166 MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument());
1167 if (!IOA)
Craig Topper8a13c412014-05-21 05:09:00 +00001168 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001169 FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl());
1170 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001171 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001172 MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0));
1173 if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl()))
Craig Topper8a13c412014-05-21 05:09:00 +00001174 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001175 return Field;
1176 } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1177 FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1178 if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy)
Craig Topper8a13c412014-05-21 05:09:00 +00001179 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001180 Expr *DstPtr = CE->getArg(0);
1181 if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr))
1182 DstPtr = DC->getSubExpr();
1183 UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr);
1184 if (!DUO || DUO->getOpcode() != UO_AddrOf)
Craig Topper8a13c412014-05-21 05:09:00 +00001185 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001186 MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr());
1187 if (!ME)
Craig Topper8a13c412014-05-21 05:09:00 +00001188 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001189 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1190 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001191 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001192 Expr *SrcPtr = CE->getArg(1);
1193 if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr))
1194 SrcPtr = SC->getSubExpr();
1195 UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr);
1196 if (!SUO || SUO->getOpcode() != UO_AddrOf)
Craig Topper8a13c412014-05-21 05:09:00 +00001197 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001198 MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr());
1199 if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl()))
Craig Topper8a13c412014-05-21 05:09:00 +00001200 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001201 return Field;
1202 }
1203
Craig Topper8a13c412014-05-21 05:09:00 +00001204 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001205 }
1206
1207 bool AssignmentsMemcpyable;
1208 SmallVector<Stmt*, 16> AggregatedStmts;
1209
1210 public:
Lang Hamesbf122742013-02-17 07:22:09 +00001211 AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD,
1212 FunctionArgList &Args)
1213 : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]),
1214 AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) {
1215 assert(Args.size() == 2);
1216 }
1217
1218 void emitAssignment(Stmt *S) {
1219 FieldDecl *F = getMemcpyableField(S);
1220 if (F) {
1221 addMemcpyableField(F);
1222 AggregatedStmts.push_back(S);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001223 } else {
Lang Hamesbf122742013-02-17 07:22:09 +00001224 emitAggregatedStmts();
1225 CGF.EmitStmt(S);
1226 }
1227 }
1228
1229 void emitAggregatedStmts() {
1230 if (AggregatedStmts.size() <= 1) {
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001231 if (!AggregatedStmts.empty()) {
1232 CopyingValueRepresentation CVR(CGF);
1233 CGF.EmitStmt(AggregatedStmts[0]);
1234 }
Lang Hamesbf122742013-02-17 07:22:09 +00001235 reset();
1236 }
1237
1238 emitMemcpy();
1239 AggregatedStmts.clear();
1240 }
1241
1242 void finish() {
1243 emitAggregatedStmts();
1244 }
1245 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00001246} // end anonymous namespace
Lang Hamesbf122742013-02-17 07:22:09 +00001247
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001248static bool isInitializerOfDynamicClass(const CXXCtorInitializer *BaseInit) {
1249 const Type *BaseType = BaseInit->getBaseClass();
1250 const auto *BaseClassDecl =
Simon Pilgrim1cd399c2019-10-03 11:22:48 +00001251 cast<CXXRecordDecl>(BaseType->castAs<RecordType>()->getDecl());
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001252 return BaseClassDecl->isDynamicClass();
1253}
1254
Anders Carlssonfb404882009-12-24 22:46:43 +00001255/// EmitCtorPrologue - This routine generates necessary code to initialize
1256/// base classes and non-static data members belonging to this constructor.
Anders Carlssonfb404882009-12-24 22:46:43 +00001257void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001258 CXXCtorType CtorType,
1259 FunctionArgList &Args) {
Alexis Hunt61bc1732011-05-01 07:04:31 +00001260 if (CD->isDelegatingConstructor())
1261 return EmitDelegatingCXXConstructorCall(CD, Args);
1262
Anders Carlssonfb404882009-12-24 22:46:43 +00001263 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlsson5dc86332010-02-02 19:58:43 +00001264
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001265 CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
1266 E = CD->init_end();
1267
Reid Kleckner61c9b7c2019-03-18 22:41:50 +00001268 // Virtual base initializers first, if any. They aren't needed if:
1269 // - This is a base ctor variant
1270 // - There are no vbases
1271 // - The class is abstract, so a complete object of it cannot be constructed
1272 //
1273 // The check for an abstract class is necessary because sema may not have
1274 // marked virtual base destructors referenced.
1275 bool ConstructVBases = CtorType != Ctor_Base &&
1276 ClassDecl->getNumVBases() != 0 &&
1277 !ClassDecl->isAbstract();
1278
1279 // In the Microsoft C++ ABI, there are no constructor variants. Instead, the
1280 // constructor of a class with virtual bases takes an additional parameter to
1281 // conditionally construct the virtual bases. Emit that check here.
Craig Topper8a13c412014-05-21 05:09:00 +00001282 llvm::BasicBlock *BaseCtorContinueBB = nullptr;
Reid Kleckner61c9b7c2019-03-18 22:41:50 +00001283 if (ConstructVBases &&
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001284 !CGM.getTarget().getCXXABI().hasConstructorVariants()) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001285 BaseCtorContinueBB =
Reid Kleckner61c9b7c2019-03-18 22:41:50 +00001286 CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this, ClassDecl);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001287 assert(BaseCtorContinueBB);
1288 }
1289
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001290 llvm::Value *const OldThis = CXXThisValue;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001291 for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
Reid Kleckner61c9b7c2019-03-18 22:41:50 +00001292 if (!ConstructVBases)
1293 continue;
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001294 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1295 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1296 isInitializerOfDynamicClass(*B))
Piotr Padlewski5dde8092018-05-03 11:03:01 +00001297 CXXThisValue = Builder.CreateLaunderInvariantGroup(LoadCXXThis());
Reid Kleckner61c9b7c2019-03-18 22:41:50 +00001298 EmitBaseInitializer(*this, ClassDecl, *B);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001299 }
1300
1301 if (BaseCtorContinueBB) {
1302 // Complete object handler should continue to the remaining initializers.
1303 Builder.CreateBr(BaseCtorContinueBB);
1304 EmitBlock(BaseCtorContinueBB);
1305 }
1306
1307 // Then, non-virtual base initializers.
1308 for (; B != E && (*B)->isBaseInitializer(); B++) {
1309 assert(!(*B)->isBaseVirtual());
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001310
1311 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1312 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1313 isInitializerOfDynamicClass(*B))
Piotr Padlewski5dde8092018-05-03 11:03:01 +00001314 CXXThisValue = Builder.CreateLaunderInvariantGroup(LoadCXXThis());
Reid Kleckner61c9b7c2019-03-18 22:41:50 +00001315 EmitBaseInitializer(*this, ClassDecl, *B);
Anders Carlssonfb404882009-12-24 22:46:43 +00001316 }
1317
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001318 CXXThisValue = OldThis;
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001319
Anders Carlssond5895932010-03-28 21:07:49 +00001320 InitializeVTablePointers(ClassDecl);
Anders Carlsson5dc86332010-02-02 19:58:43 +00001321
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001322 // And finally, initialize class members.
John McCall7f416cc2015-09-08 08:05:57 +00001323 FieldConstructionScope FCS(*this, LoadCXXThisAddress());
Lang Hamesbf122742013-02-17 07:22:09 +00001324 ConstructorMemcpyizer CM(*this, CD, Args);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001325 for (; B != E; B++) {
1326 CXXCtorInitializer *Member = (*B);
1327 assert(!Member->isBaseInitializer());
1328 assert(Member->isAnyMemberInitializer() &&
1329 "Delegating initializer on non-delegating constructor");
1330 CM.addMemberInitializer(Member);
1331 }
Lang Hamesbf122742013-02-17 07:22:09 +00001332 CM.finish();
Anders Carlssonfb404882009-12-24 22:46:43 +00001333}
1334
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001335static bool
1336FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
1337
1338static bool
Justin Bogner1cd11f12015-05-20 15:53:59 +00001339HasTrivialDestructorBody(ASTContext &Context,
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001340 const CXXRecordDecl *BaseClassDecl,
1341 const CXXRecordDecl *MostDerivedClassDecl)
1342{
1343 // If the destructor is trivial we don't have to check anything else.
1344 if (BaseClassDecl->hasTrivialDestructor())
1345 return true;
1346
1347 if (!BaseClassDecl->getDestructor()->hasTrivialBody())
1348 return false;
1349
1350 // Check fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001351 for (const auto *Field : BaseClassDecl->fields())
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001352 if (!FieldHasTrivialDestructorBody(Context, Field))
1353 return false;
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001354
1355 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001356 for (const auto &I : BaseClassDecl->bases()) {
1357 if (I.isVirtual())
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001358 continue;
1359
1360 const CXXRecordDecl *NonVirtualBase =
Aaron Ballman574705e2014-03-13 15:41:46 +00001361 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001362 if (!HasTrivialDestructorBody(Context, NonVirtualBase,
1363 MostDerivedClassDecl))
1364 return false;
1365 }
1366
1367 if (BaseClassDecl == MostDerivedClassDecl) {
1368 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00001369 for (const auto &I : BaseClassDecl->vbases()) {
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001370 const CXXRecordDecl *VirtualBase =
Aaron Ballman445a9392014-03-13 16:15:17 +00001371 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001372 if (!HasTrivialDestructorBody(Context, VirtualBase,
1373 MostDerivedClassDecl))
Justin Bogner1cd11f12015-05-20 15:53:59 +00001374 return false;
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001375 }
1376 }
1377
1378 return true;
1379}
1380
1381static bool
1382FieldHasTrivialDestructorBody(ASTContext &Context,
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001383 const FieldDecl *Field)
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001384{
1385 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
1386
1387 const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
1388 if (!RT)
1389 return true;
Justin Bogner1cd11f12015-05-20 15:53:59 +00001390
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001391 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Davide Italiano982bbf42015-06-26 00:18:35 +00001392
1393 // The destructor for an implicit anonymous union member is never invoked.
1394 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
1395 return false;
1396
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001397 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
1398}
1399
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001400/// CanSkipVTablePointerInitialization - Check whether we need to initialize
1401/// any vtable pointers before calling this destructor.
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001402static bool CanSkipVTablePointerInitialization(CodeGenFunction &CGF,
Anders Carlssond6f15182011-05-16 04:08:36 +00001403 const CXXDestructorDecl *Dtor) {
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001404 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1405 if (!ClassDecl->isDynamicClass())
1406 return true;
1407
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001408 if (!Dtor->hasTrivialBody())
1409 return false;
1410
1411 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001412 for (const auto *Field : ClassDecl->fields())
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001413 if (!FieldHasTrivialDestructorBody(CGF.getContext(), Field))
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001414 return false;
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001415
1416 return true;
1417}
1418
John McCallb81884d2010-02-19 09:25:03 +00001419/// EmitDestructorBody - Emits the body of the current destructor.
1420void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
1421 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
1422 CXXDtorType DtorType = CurGD.getDtorType();
1423
Richard Smithdf054d32017-02-25 23:53:05 +00001424 // For an abstract class, non-base destructors are never used (and can't
1425 // be emitted in general, because vbase dtors may not have been validated
1426 // by Sema), but the Itanium ABI doesn't make them optional and Clang may
1427 // in fact emit references to them from other compilations, so emit them
1428 // as functions containing a trap instruction.
1429 if (DtorType != Dtor_Base && Dtor->getParent()->isAbstract()) {
1430 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
1431 TrapCall->setDoesNotReturn();
1432 TrapCall->setDoesNotThrow();
1433 Builder.CreateUnreachable();
1434 Builder.ClearInsertionPoint();
1435 return;
1436 }
1437
Justin Bognerfb298222015-05-20 16:16:23 +00001438 Stmt *Body = Dtor->getBody();
1439 if (Body)
1440 incrementProfileCounter(Body);
1441
John McCallf99a6312010-07-21 05:30:47 +00001442 // The call to operator delete in a deleting destructor happens
1443 // outside of the function-try-block, which means it's always
1444 // possible to delegate the destructor body to the complete
1445 // destructor. Do so.
1446 if (DtorType == Dtor_Deleting) {
Richard Smith5b349582017-10-13 01:55:36 +00001447 RunCleanupsScope DtorEpilogue(*this);
John McCallf99a6312010-07-21 05:30:47 +00001448 EnterDtorCleanups(Dtor, Dtor_Deleting);
Marco Antognini88559632019-07-22 09:39:13 +00001449 if (HaveInsertPoint()) {
1450 QualType ThisTy = Dtor->getThisObjectType();
Richard Smith5b349582017-10-13 01:55:36 +00001451 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
Marco Antognini88559632019-07-22 09:39:13 +00001452 /*Delegating=*/false, LoadCXXThisAddress(), ThisTy);
1453 }
John McCallf99a6312010-07-21 05:30:47 +00001454 return;
1455 }
1456
John McCallb81884d2010-02-19 09:25:03 +00001457 // If the body is a function-try-block, enter the try before
John McCallf99a6312010-07-21 05:30:47 +00001458 // anything else.
1459 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallb81884d2010-02-19 09:25:03 +00001460 if (isTryBody)
John McCallb609d3f2010-07-07 06:56:46 +00001461 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00001462 EmitAsanPrologueOrEpilogue(false);
John McCallb81884d2010-02-19 09:25:03 +00001463
John McCallf99a6312010-07-21 05:30:47 +00001464 // Enter the epilogue cleanups.
1465 RunCleanupsScope DtorEpilogue(*this);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001466
John McCallb81884d2010-02-19 09:25:03 +00001467 // If this is the complete variant, just invoke the base variant;
1468 // the epilogue will destruct the virtual bases. But we can't do
1469 // this optimization if the body is a function-try-block, because
Justin Bogner1cd11f12015-05-20 15:53:59 +00001470 // we'd introduce *two* handler blocks. In the Microsoft ABI, we
Reid Klecknere7de47e2013-07-22 13:51:44 +00001471 // always delegate because we might not have a definition in this TU.
John McCallf99a6312010-07-21 05:30:47 +00001472 switch (DtorType) {
Saleem Abdulrasool8de4e872017-02-02 05:45:43 +00001473 case Dtor_Comdat: llvm_unreachable("not expecting a COMDAT");
John McCallf99a6312010-07-21 05:30:47 +00001474 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
1475
1476 case Dtor_Complete:
Reid Klecknere7de47e2013-07-22 13:51:44 +00001477 assert((Body || getTarget().getCXXABI().isMicrosoft()) &&
1478 "can't emit a dtor without a body for non-Microsoft ABIs");
1479
John McCallf99a6312010-07-21 05:30:47 +00001480 // Enter the cleanup scopes for virtual bases.
1481 EnterDtorCleanups(Dtor, Dtor_Complete);
1482
Reid Klecknere7de47e2013-07-22 13:51:44 +00001483 if (!isTryBody) {
Marco Antognini88559632019-07-22 09:39:13 +00001484 QualType ThisTy = Dtor->getThisObjectType();
John McCallf99a6312010-07-21 05:30:47 +00001485 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
Marco Antognini88559632019-07-22 09:39:13 +00001486 /*Delegating=*/false, LoadCXXThisAddress(), ThisTy);
John McCallf99a6312010-07-21 05:30:47 +00001487 break;
1488 }
Saleem Abdulrasool8de4e872017-02-02 05:45:43 +00001489
John McCallf99a6312010-07-21 05:30:47 +00001490 // Fallthrough: act like we're in the base variant.
Saleem Abdulrasool8de4e872017-02-02 05:45:43 +00001491 LLVM_FALLTHROUGH;
Justin Bogner1cd11f12015-05-20 15:53:59 +00001492
John McCallf99a6312010-07-21 05:30:47 +00001493 case Dtor_Base:
Reid Klecknere7de47e2013-07-22 13:51:44 +00001494 assert(Body);
1495
John McCallf99a6312010-07-21 05:30:47 +00001496 // Enter the cleanup scopes for fields and non-virtual bases.
1497 EnterDtorCleanups(Dtor, Dtor_Base);
1498
1499 // Initialize the vtable pointers before entering the body.
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001500 if (!CanSkipVTablePointerInitialization(*this, Dtor)) {
Piotr Padlewski5dde8092018-05-03 11:03:01 +00001501 // Insert the llvm.launder.invariant.group intrinsic before initializing
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001502 // the vptrs to cancel any previous assumptions we might have made.
1503 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1504 CGM.getCodeGenOpts().OptimizationLevel > 0)
Piotr Padlewski5dde8092018-05-03 11:03:01 +00001505 CXXThisValue = Builder.CreateLaunderInvariantGroup(LoadCXXThis());
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001506 InitializeVTablePointers(Dtor->getParent());
1507 }
John McCallf99a6312010-07-21 05:30:47 +00001508
1509 if (isTryBody)
1510 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
1511 else if (Body)
1512 EmitStmt(Body);
1513 else {
1514 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
1515 // nothing to do besides what's in the epilogue
1516 }
Fariborz Jahanian0c12ed12011-02-02 23:12:46 +00001517 // -fapple-kext must inline any call to this dtor into
1518 // the caller's body.
Richard Smith9c6890a2012-11-01 22:30:59 +00001519 if (getLangOpts().AppleKext)
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00001520 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
Naomi Musgravee50cb9b2015-08-13 18:35:11 +00001521
John McCallf99a6312010-07-21 05:30:47 +00001522 break;
John McCallb81884d2010-02-19 09:25:03 +00001523 }
1524
John McCallf99a6312010-07-21 05:30:47 +00001525 // Jump out through the epilogue cleanups.
1526 DtorEpilogue.ForceCleanup();
John McCallb81884d2010-02-19 09:25:03 +00001527
1528 // Exit the try if applicable.
1529 if (isTryBody)
John McCallb609d3f2010-07-07 06:56:46 +00001530 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +00001531}
1532
Lang Hamesbf122742013-02-17 07:22:09 +00001533void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) {
1534 const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
1535 const Stmt *RootS = AssignOp->getBody();
1536 assert(isa<CompoundStmt>(RootS) &&
1537 "Body of an implicit assignment operator should be compound stmt.");
1538 const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
1539
1540 LexicalScope Scope(*this, RootCS->getSourceRange());
1541
Xinliang David Lia951e8e2016-02-09 20:02:59 +00001542 incrementProfileCounter(RootCS);
Lang Hamesbf122742013-02-17 07:22:09 +00001543 AssignmentMemcpyizer AM(*this, AssignOp, Args);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001544 for (auto *I : RootCS->body())
Justin Bogner1cd11f12015-05-20 15:53:59 +00001545 AM.emitAssignment(I);
Lang Hamesbf122742013-02-17 07:22:09 +00001546 AM.finish();
1547}
1548
John McCallf99a6312010-07-21 05:30:47 +00001549namespace {
Richard Smith5b349582017-10-13 01:55:36 +00001550 llvm::Value *LoadThisForDtorDelete(CodeGenFunction &CGF,
1551 const CXXDestructorDecl *DD) {
1552 if (Expr *ThisArg = DD->getOperatorDeleteThisArg())
Haojian Wu5b5c81f2017-10-13 15:37:53 +00001553 return CGF.EmitScalarExpr(ThisArg);
Richard Smith5b349582017-10-13 01:55:36 +00001554 return CGF.LoadCXXThis();
1555 }
1556
John McCallf99a6312010-07-21 05:30:47 +00001557 /// Call the operator delete associated with the current destructor.
David Blaikie7e70d682015-08-18 22:40:54 +00001558 struct CallDtorDelete final : EHScopeStack::Cleanup {
John McCallf99a6312010-07-21 05:30:47 +00001559 CallDtorDelete() {}
1560
Craig Topper4f12f102014-03-12 06:41:41 +00001561 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallf99a6312010-07-21 05:30:47 +00001562 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1563 const CXXRecordDecl *ClassDecl = Dtor->getParent();
Richard Smith5b349582017-10-13 01:55:36 +00001564 CGF.EmitDeleteCall(Dtor->getOperatorDelete(),
1565 LoadThisForDtorDelete(CGF, Dtor),
John McCallf99a6312010-07-21 05:30:47 +00001566 CGF.getContext().getTagDeclType(ClassDecl));
1567 }
1568 };
1569
Richard Smith5b349582017-10-13 01:55:36 +00001570 void EmitConditionalDtorDeleteCall(CodeGenFunction &CGF,
1571 llvm::Value *ShouldDeleteCondition,
1572 bool ReturnAfterDelete) {
1573 llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
1574 llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
1575 llvm::Value *ShouldCallDelete
1576 = CGF.Builder.CreateIsNull(ShouldDeleteCondition);
1577 CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
1578
1579 CGF.EmitBlock(callDeleteBB);
1580 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1581 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1582 CGF.EmitDeleteCall(Dtor->getOperatorDelete(),
1583 LoadThisForDtorDelete(CGF, Dtor),
1584 CGF.getContext().getTagDeclType(ClassDecl));
1585 assert(Dtor->getOperatorDelete()->isDestroyingOperatorDelete() ==
1586 ReturnAfterDelete &&
1587 "unexpected value for ReturnAfterDelete");
1588 if (ReturnAfterDelete)
1589 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
1590 else
1591 CGF.Builder.CreateBr(continueBB);
1592
1593 CGF.EmitBlock(continueBB);
1594 }
1595
David Blaikie7e70d682015-08-18 22:40:54 +00001596 struct CallDtorDeleteConditional final : EHScopeStack::Cleanup {
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001597 llvm::Value *ShouldDeleteCondition;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001598
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001599 public:
1600 CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001601 : ShouldDeleteCondition(ShouldDeleteCondition) {
Craig Topper8a13c412014-05-21 05:09:00 +00001602 assert(ShouldDeleteCondition != nullptr);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001603 }
1604
Craig Topper4f12f102014-03-12 06:41:41 +00001605 void Emit(CodeGenFunction &CGF, Flags flags) override {
Richard Smith5b349582017-10-13 01:55:36 +00001606 EmitConditionalDtorDeleteCall(CGF, ShouldDeleteCondition,
1607 /*ReturnAfterDelete*/false);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001608 }
1609 };
1610
David Blaikie7e70d682015-08-18 22:40:54 +00001611 class DestroyField final : public EHScopeStack::Cleanup {
John McCall4bd0fb12011-07-12 16:41:08 +00001612 const FieldDecl *field;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001613 CodeGenFunction::Destroyer *destroyer;
John McCall4bd0fb12011-07-12 16:41:08 +00001614 bool useEHCleanupForArray;
John McCallf99a6312010-07-21 05:30:47 +00001615
John McCall4bd0fb12011-07-12 16:41:08 +00001616 public:
1617 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
1618 bool useEHCleanupForArray)
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001619 : field(field), destroyer(destroyer),
1620 useEHCleanupForArray(useEHCleanupForArray) {}
John McCallf99a6312010-07-21 05:30:47 +00001621
Craig Topper4f12f102014-03-12 06:41:41 +00001622 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall4bd0fb12011-07-12 16:41:08 +00001623 // Find the address of the field.
John McCall7f416cc2015-09-08 08:05:57 +00001624 Address thisValue = CGF.LoadCXXThisAddress();
Eli Friedman7f1ff602012-04-16 03:54:45 +00001625 QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
1626 LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
1627 LValue LV = CGF.EmitLValueForField(ThisLV, field);
John McCall4bd0fb12011-07-12 16:41:08 +00001628 assert(LV.isSimple());
Justin Bogner1cd11f12015-05-20 15:53:59 +00001629
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001630 CGF.emitDestroy(LV.getAddress(CGF), field->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +00001631 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCallf99a6312010-07-21 05:30:47 +00001632 }
1633 };
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001634
Naomi Musgrave703835c2015-09-16 00:38:22 +00001635 static void EmitSanitizerDtorCallback(CodeGenFunction &CGF, llvm::Value *Ptr,
1636 CharUnits::QuantityType PoisonSize) {
Matt Morehouse4881a232017-09-20 22:53:08 +00001637 CodeGenFunction::SanitizerScope SanScope(&CGF);
Naomi Musgrave703835c2015-09-16 00:38:22 +00001638 // Pass in void pointer and size of region as arguments to runtime
1639 // function
1640 llvm::Value *Args[] = {CGF.Builder.CreateBitCast(Ptr, CGF.VoidPtrTy),
1641 llvm::ConstantInt::get(CGF.SizeTy, PoisonSize)};
1642
1643 llvm::Type *ArgTypes[] = {CGF.VoidPtrTy, CGF.SizeTy};
1644
1645 llvm::FunctionType *FnType =
1646 llvm::FunctionType::get(CGF.VoidTy, ArgTypes, false);
James Y Knight9871db02019-02-05 16:42:33 +00001647 llvm::FunctionCallee Fn =
Naomi Musgrave703835c2015-09-16 00:38:22 +00001648 CGF.CGM.CreateRuntimeFunction(FnType, "__sanitizer_dtor_callback");
1649 CGF.EmitNounwindRuntimeCall(Fn, Args);
1650 }
1651
1652 class SanitizeDtorMembers final : public EHScopeStack::Cleanup {
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001653 const CXXDestructorDecl *Dtor;
1654
1655 public:
Naomi Musgrave703835c2015-09-16 00:38:22 +00001656 SanitizeDtorMembers(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001657
1658 // Generate function call for handling object poisoning.
1659 // Disables tail call elimination, to prevent the current stack frame
1660 // from disappearing from the stack trace.
1661 void Emit(CodeGenFunction &CGF, Flags flags) override {
1662 const ASTRecordLayout &Layout =
1663 CGF.getContext().getASTRecordLayout(Dtor->getParent());
1664
1665 // Nothing to poison.
1666 if (Layout.getFieldCount() == 0)
1667 return;
1668
1669 // Prevent the current stack frame from disappearing from the stack trace.
1670 CGF.CurFn->addFnAttr("disable-tail-calls", "true");
1671
1672 // Construct pointer to region to begin poisoning, and calculate poison
1673 // size, so that only members declared in this class are poisoned.
1674 ASTContext &Context = CGF.getContext();
1675 unsigned fieldIndex = 0;
1676 int startIndex = -1;
1677 // RecordDecl::field_iterator Field;
1678 for (const FieldDecl *Field : Dtor->getParent()->fields()) {
1679 // Poison field if it is trivial
1680 if (FieldHasTrivialDestructorBody(Context, Field)) {
1681 // Start sanitizing at this field
1682 if (startIndex < 0)
1683 startIndex = fieldIndex;
1684
1685 // Currently on the last field, and it must be poisoned with the
1686 // current block.
1687 if (fieldIndex == Layout.getFieldCount() - 1) {
Naomi Musgrave703835c2015-09-16 00:38:22 +00001688 PoisonMembers(CGF, startIndex, Layout.getFieldCount());
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001689 }
1690 } else if (startIndex >= 0) {
1691 // No longer within a block of memory to poison, so poison the block
Naomi Musgrave703835c2015-09-16 00:38:22 +00001692 PoisonMembers(CGF, startIndex, fieldIndex);
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001693 // Re-set the start index
1694 startIndex = -1;
1695 }
1696 fieldIndex += 1;
1697 }
1698 }
1699
1700 private:
NAKAMURA Takumif6cef72f2015-09-04 05:19:31 +00001701 /// \param layoutStartOffset index of the ASTRecordLayout field to
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001702 /// start poisoning (inclusive)
NAKAMURA Takumif6cef72f2015-09-04 05:19:31 +00001703 /// \param layoutEndOffset index of the ASTRecordLayout field to
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001704 /// end poisoning (exclusive)
Naomi Musgrave703835c2015-09-16 00:38:22 +00001705 void PoisonMembers(CodeGenFunction &CGF, unsigned layoutStartOffset,
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001706 unsigned layoutEndOffset) {
1707 ASTContext &Context = CGF.getContext();
1708 const ASTRecordLayout &Layout =
1709 Context.getASTRecordLayout(Dtor->getParent());
1710
1711 llvm::ConstantInt *OffsetSizePtr = llvm::ConstantInt::get(
1712 CGF.SizeTy,
1713 Context.toCharUnitsFromBits(Layout.getFieldOffset(layoutStartOffset))
1714 .getQuantity());
1715
1716 llvm::Value *OffsetPtr = CGF.Builder.CreateGEP(
1717 CGF.Builder.CreateBitCast(CGF.LoadCXXThis(), CGF.Int8PtrTy),
1718 OffsetSizePtr);
1719
1720 CharUnits::QuantityType PoisonSize;
1721 if (layoutEndOffset >= Layout.getFieldCount()) {
1722 PoisonSize = Layout.getNonVirtualSize().getQuantity() -
1723 Context.toCharUnitsFromBits(
1724 Layout.getFieldOffset(layoutStartOffset))
1725 .getQuantity();
1726 } else {
1727 PoisonSize = Context.toCharUnitsFromBits(
1728 Layout.getFieldOffset(layoutEndOffset) -
1729 Layout.getFieldOffset(layoutStartOffset))
1730 .getQuantity();
1731 }
1732
1733 if (PoisonSize == 0)
1734 return;
1735
Naomi Musgrave703835c2015-09-16 00:38:22 +00001736 EmitSanitizerDtorCallback(CGF, OffsetPtr, PoisonSize);
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001737 }
1738 };
Naomi Musgrave703835c2015-09-16 00:38:22 +00001739
1740 class SanitizeDtorVTable final : public EHScopeStack::Cleanup {
1741 const CXXDestructorDecl *Dtor;
1742
1743 public:
1744 SanitizeDtorVTable(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
1745
1746 // Generate function call for handling vtable pointer poisoning.
1747 void Emit(CodeGenFunction &CGF, Flags flags) override {
1748 assert(Dtor->getParent()->isDynamicClass());
NAKAMURA Takumiee82b492015-09-16 06:26:56 +00001749 (void)Dtor;
Naomi Musgrave703835c2015-09-16 00:38:22 +00001750 ASTContext &Context = CGF.getContext();
1751 // Poison vtable and vtable ptr if they exist for this class.
1752 llvm::Value *VTablePtr = CGF.LoadCXXThis();
1753
1754 CharUnits::QuantityType PoisonSize =
1755 Context.toCharUnitsFromBits(CGF.PointerWidthInBits).getQuantity();
1756 // Pass in void pointer and size of region as arguments to runtime
1757 // function
1758 EmitSanitizerDtorCallback(CGF, VTablePtr, PoisonSize);
1759 }
1760 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00001761} // end anonymous namespace
John McCallf99a6312010-07-21 05:30:47 +00001762
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001763/// Emit all code that comes at the end of class's
Anders Carlssonfb404882009-12-24 22:46:43 +00001764/// destructor. This is to call destructors on members and base classes
1765/// in reverse order of their construction.
Richard Smith5b349582017-10-13 01:55:36 +00001766///
1767/// For a deleting destructor, this also handles the case where a destroying
1768/// operator delete completely overrides the definition.
John McCallf99a6312010-07-21 05:30:47 +00001769void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
1770 CXXDtorType DtorType) {
Hans Wennborg853ae942014-05-30 16:59:42 +00001771 assert((!DD->isTrivial() || DD->hasAttr<DLLExportAttr>()) &&
1772 "Should not emit dtor epilogue for non-exported trivial dtor!");
Anders Carlssonfb404882009-12-24 22:46:43 +00001773
John McCallf99a6312010-07-21 05:30:47 +00001774 // The deleting-destructor phase just needs to call the appropriate
1775 // operator delete that Sema picked up.
John McCall5c60a6f2010-02-18 19:59:28 +00001776 if (DtorType == Dtor_Deleting) {
Justin Bogner1cd11f12015-05-20 15:53:59 +00001777 assert(DD->getOperatorDelete() &&
Hans Wennborgdeff7032013-12-18 01:39:59 +00001778 "operator delete missing - EnterDtorCleanups");
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001779 if (CXXStructorImplicitParamValue) {
1780 // If there is an implicit param to the deleting dtor, it's a boolean
Richard Smith5b349582017-10-13 01:55:36 +00001781 // telling whether this is a deleting destructor.
1782 if (DD->getOperatorDelete()->isDestroyingOperatorDelete())
1783 EmitConditionalDtorDeleteCall(*this, CXXStructorImplicitParamValue,
1784 /*ReturnAfterDelete*/true);
1785 else
1786 EHStack.pushCleanup<CallDtorDeleteConditional>(
1787 NormalAndEHCleanup, CXXStructorImplicitParamValue);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001788 } else {
Richard Smith5b349582017-10-13 01:55:36 +00001789 if (DD->getOperatorDelete()->isDestroyingOperatorDelete()) {
1790 const CXXRecordDecl *ClassDecl = DD->getParent();
1791 EmitDeleteCall(DD->getOperatorDelete(),
1792 LoadThisForDtorDelete(*this, DD),
1793 getContext().getTagDeclType(ClassDecl));
1794 EmitBranchThroughCleanup(ReturnBlock);
1795 } else {
1796 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
1797 }
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001798 }
John McCall5c60a6f2010-02-18 19:59:28 +00001799 return;
1800 }
1801
John McCallf99a6312010-07-21 05:30:47 +00001802 const CXXRecordDecl *ClassDecl = DD->getParent();
1803
Richard Smith20104042011-09-18 12:11:43 +00001804 // Unions have no bases and do not call field destructors.
1805 if (ClassDecl->isUnion())
1806 return;
1807
John McCallf99a6312010-07-21 05:30:47 +00001808 // The complete-destructor phase just destructs all the virtual bases.
John McCall5c60a6f2010-02-18 19:59:28 +00001809 if (DtorType == Dtor_Complete) {
Naomi Musgrave703835c2015-09-16 00:38:22 +00001810 // Poison the vtable pointer such that access after the base
1811 // and member destructors are invoked is invalid.
1812 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1813 SanOpts.has(SanitizerKind::Memory) && ClassDecl->getNumVBases() &&
1814 ClassDecl->isPolymorphic())
1815 EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
John McCallf99a6312010-07-21 05:30:47 +00001816
1817 // We push them in the forward order so that they'll be popped in
1818 // the reverse order.
Aaron Ballman445a9392014-03-13 16:15:17 +00001819 for (const auto &Base : ClassDecl->vbases()) {
Simon Pilgrim1cd399c2019-10-03 11:22:48 +00001820 auto *BaseClassDecl =
1821 cast<CXXRecordDecl>(Base.getType()->castAs<RecordType>()->getDecl());
Justin Bogner1cd11f12015-05-20 15:53:59 +00001822
John McCall5c60a6f2010-02-18 19:59:28 +00001823 // Ignore trivial destructors.
1824 if (BaseClassDecl->hasTrivialDestructor())
1825 continue;
John McCallf99a6312010-07-21 05:30:47 +00001826
John McCallcda666c2010-07-21 07:22:38 +00001827 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1828 BaseClassDecl,
1829 /*BaseIsVirtual*/ true);
John McCall5c60a6f2010-02-18 19:59:28 +00001830 }
John McCallf99a6312010-07-21 05:30:47 +00001831
John McCall5c60a6f2010-02-18 19:59:28 +00001832 return;
1833 }
1834
1835 assert(DtorType == Dtor_Base);
Naomi Musgrave703835c2015-09-16 00:38:22 +00001836 // Poison the vtable pointer if it has no virtual bases, but inherits
1837 // virtual functions.
1838 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1839 SanOpts.has(SanitizerKind::Memory) && !ClassDecl->getNumVBases() &&
1840 ClassDecl->isPolymorphic())
1841 EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001842
John McCallf99a6312010-07-21 05:30:47 +00001843 // Destroy non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001844 for (const auto &Base : ClassDecl->bases()) {
John McCallf99a6312010-07-21 05:30:47 +00001845 // Ignore virtual bases.
1846 if (Base.isVirtual())
1847 continue;
Justin Bogner1cd11f12015-05-20 15:53:59 +00001848
John McCallf99a6312010-07-21 05:30:47 +00001849 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
Justin Bogner1cd11f12015-05-20 15:53:59 +00001850
John McCallf99a6312010-07-21 05:30:47 +00001851 // Ignore trivial destructors.
1852 if (BaseClassDecl->hasTrivialDestructor())
1853 continue;
John McCall5c60a6f2010-02-18 19:59:28 +00001854
John McCallcda666c2010-07-21 07:22:38 +00001855 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1856 BaseClassDecl,
1857 /*BaseIsVirtual*/ false);
John McCallf99a6312010-07-21 05:30:47 +00001858 }
1859
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001860 // Poison fields such that access after their destructors are
1861 // invoked, and before the base class destructor runs, is invalid.
1862 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1863 SanOpts.has(SanitizerKind::Memory))
Naomi Musgrave703835c2015-09-16 00:38:22 +00001864 EHStack.pushCleanup<SanitizeDtorMembers>(NormalAndEHCleanup, DD);
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001865
John McCallf99a6312010-07-21 05:30:47 +00001866 // Destroy direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001867 for (const auto *Field : ClassDecl->fields()) {
1868 QualType type = Field->getType();
John McCall4bd0fb12011-07-12 16:41:08 +00001869 QualType::DestructionKind dtorKind = type.isDestructedType();
1870 if (!dtorKind) continue;
John McCallf99a6312010-07-21 05:30:47 +00001871
Richard Smith921bd202012-02-26 09:11:52 +00001872 // Anonymous union members do not have their destructors called.
1873 const RecordType *RT = type->getAsUnionType();
1874 if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
1875
John McCall4bd0fb12011-07-12 16:41:08 +00001876 CleanupKind cleanupKind = getCleanupKind(dtorKind);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001877 EHStack.pushCleanup<DestroyField>(cleanupKind, Field,
John McCall4bd0fb12011-07-12 16:41:08 +00001878 getDestroyer(dtorKind),
1879 cleanupKind & EHCleanup);
Anders Carlssonfb404882009-12-24 22:46:43 +00001880 }
Anders Carlssonfb404882009-12-24 22:46:43 +00001881}
1882
John McCallf677a8e2011-07-13 06:10:41 +00001883/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1884/// constructor for each of several members of an array.
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001885///
John McCallf677a8e2011-07-13 06:10:41 +00001886/// \param ctor the constructor to call for each element
John McCallf677a8e2011-07-13 06:10:41 +00001887/// \param arrayType the type of the array to initialize
1888/// \param arrayBegin an arrayType*
1889/// \param zeroInitialize true if each element should be
1890/// zero-initialized before it is constructed
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001891void CodeGenFunction::EmitCXXAggrConstructorCall(
Alexey Bataeve7545b32016-04-29 09:39:50 +00001892 const CXXConstructorDecl *ctor, const ArrayType *arrayType,
Serge Pavlov37605182018-07-28 15:33:03 +00001893 Address arrayBegin, const CXXConstructExpr *E, bool NewPointerIsChecked,
1894 bool zeroInitialize) {
John McCallf677a8e2011-07-13 06:10:41 +00001895 QualType elementType;
1896 llvm::Value *numElements =
1897 emitArrayLength(arrayType, elementType, arrayBegin);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001898
Serge Pavlov37605182018-07-28 15:33:03 +00001899 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin, E,
1900 NewPointerIsChecked, zeroInitialize);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001901}
1902
John McCallf677a8e2011-07-13 06:10:41 +00001903/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1904/// constructor for each of several members of an array.
1905///
1906/// \param ctor the constructor to call for each element
1907/// \param numElements the number of elements in the array;
John McCall6549b312011-07-13 07:37:11 +00001908/// may be zero
NAKAMURA Takumiff7a9252015-09-08 09:42:41 +00001909/// \param arrayBase a T*, where T is the type constructed by ctor
John McCallf677a8e2011-07-13 06:10:41 +00001910/// \param zeroInitialize true if each element should be
1911/// zero-initialized before it is constructed
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001912void CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1913 llvm::Value *numElements,
John McCall7f416cc2015-09-08 08:05:57 +00001914 Address arrayBase,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001915 const CXXConstructExpr *E,
Serge Pavlov37605182018-07-28 15:33:03 +00001916 bool NewPointerIsChecked,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001917 bool zeroInitialize) {
John McCall6549b312011-07-13 07:37:11 +00001918 // It's legal for numElements to be zero. This can happen both
1919 // dynamically, because x can be zero in 'new A[x]', and statically,
1920 // because of GCC extensions that permit zero-length arrays. There
1921 // are probably legitimate places where we could assume that this
1922 // doesn't happen, but it's not clear that it's worth it.
Craig Topper8a13c412014-05-21 05:09:00 +00001923 llvm::BranchInst *zeroCheckBranch = nullptr;
John McCall6549b312011-07-13 07:37:11 +00001924
1925 // Optimize for a constant count.
1926 llvm::ConstantInt *constantCount
1927 = dyn_cast<llvm::ConstantInt>(numElements);
1928 if (constantCount) {
1929 // Just skip out if the constant count is zero.
1930 if (constantCount->isZero()) return;
1931
1932 // Otherwise, emit the check.
1933 } else {
1934 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1935 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1936 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1937 EmitBlock(loopBB);
1938 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00001939
John McCallf677a8e2011-07-13 06:10:41 +00001940 // Find the end of the array.
John McCall7f416cc2015-09-08 08:05:57 +00001941 llvm::Value *arrayBegin = arrayBase.getPointer();
John McCallf677a8e2011-07-13 06:10:41 +00001942 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1943 "arrayctor.end");
Anders Carlsson27da15b2010-01-01 20:29:01 +00001944
John McCallf677a8e2011-07-13 06:10:41 +00001945 // Enter the loop, setting up a phi for the current location to initialize.
1946 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1947 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1948 EmitBlock(loopBB);
1949 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1950 "arrayctor.cur");
1951 cur->addIncoming(arrayBegin, entryBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001952
Anders Carlsson27da15b2010-01-01 20:29:01 +00001953 // Inside the loop body, emit the constructor call on the array element.
John McCallf677a8e2011-07-13 06:10:41 +00001954
John McCall7f416cc2015-09-08 08:05:57 +00001955 // The alignment of the base, adjusted by the size of a single element,
1956 // provides a conservative estimate of the alignment of every element.
1957 // (This assumes we never start tracking offsetted alignments.)
Fangrui Song6907ce22018-07-30 19:24:48 +00001958 //
John McCall7f416cc2015-09-08 08:05:57 +00001959 // Note that these are complete objects and so we don't need to
1960 // use the non-virtual size or alignment.
John McCallf677a8e2011-07-13 06:10:41 +00001961 QualType type = getContext().getTypeDeclType(ctor->getParent());
John McCall7f416cc2015-09-08 08:05:57 +00001962 CharUnits eltAlignment =
1963 arrayBase.getAlignment()
1964 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
1965 Address curAddr = Address(cur, eltAlignment);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001966
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001967 // Zero initialize the storage, if requested.
John McCallf677a8e2011-07-13 06:10:41 +00001968 if (zeroInitialize)
John McCall7f416cc2015-09-08 08:05:57 +00001969 EmitNullInitialization(curAddr, type);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001970
1971 // C++ [class.temporary]p4:
Anders Carlsson27da15b2010-01-01 20:29:01 +00001972 // There are two contexts in which temporaries are destroyed at a different
1973 // point than the end of the full-expression. The first context is when a
Justin Bogner1cd11f12015-05-20 15:53:59 +00001974 // default constructor is called to initialize an element of an array.
1975 // If the constructor has one or more default arguments, the destruction of
1976 // every temporary created in a default argument expression is sequenced
Anders Carlsson27da15b2010-01-01 20:29:01 +00001977 // before the construction of the next array element, if any.
Justin Bogner1cd11f12015-05-20 15:53:59 +00001978
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00001979 {
John McCallbd309292010-07-06 01:34:17 +00001980 RunCleanupsScope Scope(*this);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001981
John McCallf677a8e2011-07-13 06:10:41 +00001982 // Evaluate the constructor and its arguments in a regular
1983 // partial-destroy cleanup.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001984 if (getLangOpts().Exceptions &&
John McCallf677a8e2011-07-13 06:10:41 +00001985 !ctor->getParent()->hasTrivialDestructor()) {
1986 Destroyer *destroyer = destroyCXXObject;
John McCall7f416cc2015-09-08 08:05:57 +00001987 pushRegularPartialArrayCleanup(arrayBegin, cur, type, eltAlignment,
1988 *destroyer);
John McCallf677a8e2011-07-13 06:10:41 +00001989 }
Anastasia Stulova094c7262019-04-04 10:48:36 +00001990 auto currAVS = AggValueSlot::forAddr(
1991 curAddr, type.getQualifiers(), AggValueSlot::IsDestructed,
1992 AggValueSlot::DoesNotNeedGCBarriers, AggValueSlot::IsNotAliased,
1993 AggValueSlot::DoesNotOverlap, AggValueSlot::IsNotZeroed,
1994 NewPointerIsChecked ? AggValueSlot::IsSanitizerChecked
1995 : AggValueSlot::IsNotSanitizerChecked);
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001996 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/false,
Anastasia Stulova094c7262019-04-04 10:48:36 +00001997 /*Delegating=*/false, currAVS, E);
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00001998 }
Anders Carlsson27da15b2010-01-01 20:29:01 +00001999
John McCallf677a8e2011-07-13 06:10:41 +00002000 // Go to the next element.
2001 llvm::Value *next =
2002 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
2003 "arrayctor.next");
2004 cur->addIncoming(next, Builder.GetInsertBlock());
Anders Carlsson27da15b2010-01-01 20:29:01 +00002005
John McCallf677a8e2011-07-13 06:10:41 +00002006 // Check whether that's the end of the loop.
2007 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
2008 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
2009 Builder.CreateCondBr(done, contBB, loopBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002010
John McCall6549b312011-07-13 07:37:11 +00002011 // Patch the earlier check to skip over the loop.
2012 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
2013
John McCallf677a8e2011-07-13 06:10:41 +00002014 EmitBlock(contBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002015}
2016
John McCall82fe67b2011-07-09 01:37:26 +00002017void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002018 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002019 QualType type) {
2020 const RecordType *rtype = type->castAs<RecordType>();
2021 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
2022 const CXXDestructorDecl *dtor = record->getDestructor();
2023 assert(!dtor->isTrivial());
2024 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
Marco Antognini88559632019-07-22 09:39:13 +00002025 /*Delegating=*/false, addr, type);
John McCall82fe67b2011-07-09 01:37:26 +00002026}
2027
Alexey Samsonov70b9c012014-08-21 20:26:47 +00002028void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
2029 CXXCtorType Type,
2030 bool ForVirtualBase,
Anastasia Stulova094c7262019-04-04 10:48:36 +00002031 bool Delegating,
2032 AggValueSlot ThisAVS,
2033 const CXXConstructExpr *E) {
Richard Smith5179eb72016-06-28 19:03:57 +00002034 CallArgList Args;
Anastasia Stulova094c7262019-04-04 10:48:36 +00002035 Address This = ThisAVS.getAddress();
2036 LangAS SlotAS = ThisAVS.getQualifiers().getAddressSpace();
Brian Gesiak5488ab42019-01-11 01:54:53 +00002037 QualType ThisType = D->getThisType();
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00002038 LangAS ThisAS = ThisType.getTypePtr()->getPointeeType().getAddressSpace();
2039 llvm::Value *ThisPtr = This.getPointer();
Anastasia Stulova094c7262019-04-04 10:48:36 +00002040
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00002041 if (SlotAS != ThisAS) {
2042 unsigned TargetThisAS = getContext().getTargetAddressSpace(ThisAS);
2043 llvm::Type *NewType =
2044 ThisPtr->getType()->getPointerElementType()->getPointerTo(TargetThisAS);
2045 ThisPtr = getTargetHooks().performAddrSpaceCast(*this, This.getPointer(),
2046 ThisAS, SlotAS, NewType);
2047 }
Anastasia Stulova094c7262019-04-04 10:48:36 +00002048
Richard Smith5179eb72016-06-28 19:03:57 +00002049 // Push the this ptr.
Brian Gesiak5488ab42019-01-11 01:54:53 +00002050 Args.add(RValue::get(ThisPtr), D->getThisType());
Richard Smith5179eb72016-06-28 19:03:57 +00002051
2052 // If this is a trivial constructor, emit a memcpy now before we lose
2053 // the alignment information on the argument.
2054 // FIXME: It would be better to preserve alignment information into CallArg.
2055 if (isMemcpyEquivalentSpecialMember(D)) {
2056 assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
2057
2058 const Expr *Arg = E->getArg(0);
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00002059 LValue Src = EmitLValue(Arg);
Richard Smith5179eb72016-06-28 19:03:57 +00002060 QualType DestTy = getContext().getTypeDeclType(D->getParent());
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00002061 LValue Dest = MakeAddrLValue(This, DestTy);
Anastasia Stulova094c7262019-04-04 10:48:36 +00002062 EmitAggregateCopyCtor(Dest, Src, ThisAVS.mayOverlap());
Richard Smith5179eb72016-06-28 19:03:57 +00002063 return;
2064 }
2065
2066 // Add the rest of the user-supplied arguments.
2067 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
Hans Wennborg27dcc6c2017-02-01 02:21:07 +00002068 EvaluationOrder Order = E->isListInitialization()
2069 ? EvaluationOrder::ForceLeftToRight
2070 : EvaluationOrder::Default;
2071 EmitCallArgs(Args, FPT, E->arguments(), E->getConstructor(),
2072 /*ParamsToSkip*/ 0, Order);
Richard Smith5179eb72016-06-28 19:03:57 +00002073
Richard Smithe78fac52018-04-05 20:52:58 +00002074 EmitCXXConstructorCall(D, Type, ForVirtualBase, Delegating, This, Args,
Anastasia Stulova094c7262019-04-04 10:48:36 +00002075 ThisAVS.mayOverlap(), E->getExprLoc(),
2076 ThisAVS.isSanitizerChecked());
Richard Smith5179eb72016-06-28 19:03:57 +00002077}
2078
2079static bool canEmitDelegateCallArgs(CodeGenFunction &CGF,
2080 const CXXConstructorDecl *Ctor,
2081 CXXCtorType Type, CallArgList &Args) {
2082 // We can't forward a variadic call.
2083 if (Ctor->isVariadic())
2084 return false;
2085
2086 if (CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2087 // If the parameters are callee-cleanup, it's not safe to forward.
2088 for (auto *P : Ctor->parameters())
Richard Smith2b4fa532019-09-29 05:08:46 +00002089 if (P->needsDestruction(CGF.getContext()))
Richard Smith5179eb72016-06-28 19:03:57 +00002090 return false;
2091
2092 // Likewise if they're inalloca.
2093 const CGFunctionInfo &Info =
George Burgess IVd0a9e802017-02-23 22:07:35 +00002094 CGF.CGM.getTypes().arrangeCXXConstructorCall(Args, Ctor, Type, 0, 0);
Richard Smith5179eb72016-06-28 19:03:57 +00002095 if (Info.usesInAlloca())
2096 return false;
2097 }
2098
2099 // Anything else should be OK.
2100 return true;
2101}
2102
2103void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
2104 CXXCtorType Type,
2105 bool ForVirtualBase,
2106 bool Delegating,
2107 Address This,
Richard Smithe78fac52018-04-05 20:52:58 +00002108 CallArgList &Args,
Igor Kudrineff8f9d2018-06-25 05:48:04 +00002109 AggValueSlot::Overlap_t Overlap,
Serge Pavlov37605182018-07-28 15:33:03 +00002110 SourceLocation Loc,
2111 bool NewPointerIsChecked) {
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002112 const CXXRecordDecl *ClassDecl = D->getParent();
2113
Serge Pavlov37605182018-07-28 15:33:03 +00002114 if (!NewPointerIsChecked)
2115 EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall, Loc, This.getPointer(),
2116 getContext().getRecordType(ClassDecl), CharUnits::Zero());
John McCallca972cd2010-02-06 00:25:16 +00002117
Richard Smith419bd092015-04-29 19:26:57 +00002118 if (D->isTrivial() && D->isDefaultConstructor()) {
Richard Smith5179eb72016-06-28 19:03:57 +00002119 assert(Args.size() == 1 && "trivial default ctor with args");
Richard Smith419bd092015-04-29 19:26:57 +00002120 return;
2121 }
2122
2123 // If this is a trivial constructor, just emit what's needed. If this is a
2124 // union copy constructor, we must emit a memcpy, because the AST does not
2125 // model that copy.
2126 if (isMemcpyEquivalentSpecialMember(D)) {
Richard Smith5179eb72016-06-28 19:03:57 +00002127 assert(Args.size() == 2 && "unexpected argcount for trivial ctor");
John McCallca972cd2010-02-06 00:25:16 +00002128
Richard Smith5179eb72016-06-28 19:03:57 +00002129 QualType SrcTy = D->getParamDecl(0)->getType().getNonReferenceType();
Yaxun Liu5b330e82018-03-15 15:25:19 +00002130 Address Src(Args[1].getRValue(*this).getScalarVal(),
2131 getNaturalTypeAlignment(SrcTy));
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00002132 LValue SrcLVal = MakeAddrLValue(Src, SrcTy);
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002133 QualType DestTy = getContext().getTypeDeclType(ClassDecl);
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00002134 LValue DestLVal = MakeAddrLValue(This, DestTy);
Richard Smithe78fac52018-04-05 20:52:58 +00002135 EmitAggregateCopyCtor(DestLVal, SrcLVal, Overlap);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002136 return;
2137 }
2138
George Burgess IVd0a9e802017-02-23 22:07:35 +00002139 bool PassPrototypeArgs = true;
Richard Smith5179eb72016-06-28 19:03:57 +00002140 // Check whether we can actually emit the constructor before trying to do so.
2141 if (auto Inherited = D->getInheritedConstructor()) {
George Burgess IVd0a9e802017-02-23 22:07:35 +00002142 PassPrototypeArgs = getTypes().inheritingCtorHasParams(Inherited, Type);
2143 if (PassPrototypeArgs && !canEmitDelegateCallArgs(*this, D, Type, Args)) {
Richard Smith5179eb72016-06-28 19:03:57 +00002144 EmitInlinedInheritingCXXConstructorCall(D, Type, ForVirtualBase,
2145 Delegating, Args);
2146 return;
2147 }
2148 }
Reid Kleckner89077a12013-12-17 19:46:40 +00002149
2150 // Insert any ABI-specific implicit constructor arguments.
George Burgess IVf203dbf2017-02-22 20:28:02 +00002151 CGCXXABI::AddedStructorArgs ExtraArgs =
2152 CGM.getCXXABI().addImplicitConstructorArgs(*this, D, Type, ForVirtualBase,
2153 Delegating, Args);
Reid Kleckner89077a12013-12-17 19:46:40 +00002154
2155 // Emit the call.
Peter Collingbourned1c5b282019-03-22 23:05:10 +00002156 llvm::Constant *CalleePtr = CGM.getAddrOfCXXStructor(GlobalDecl(D, Type));
George Burgess IVf203dbf2017-02-22 20:28:02 +00002157 const CGFunctionInfo &Info = CGM.getTypes().arrangeCXXConstructorCall(
George Burgess IVd0a9e802017-02-23 22:07:35 +00002158 Args, D, Type, ExtraArgs.Prefix, ExtraArgs.Suffix, PassPrototypeArgs);
Erich Keanede6480a32018-11-13 15:48:08 +00002159 CGCallee Callee = CGCallee::forDirect(CalleePtr, GlobalDecl(D, Type));
John McCallb92ab1a2016-10-26 23:46:34 +00002160 EmitCall(Info, Callee, ReturnValueSlot(), Args);
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002161
2162 // Generate vtable assumptions if we're constructing a complete object
2163 // with a vtable. We don't do this for base subobjects for two reasons:
2164 // first, it's incorrect for classes with virtual bases, and second, we're
2165 // about to overwrite the vptrs anyway.
2166 // We also have to make sure if we can refer to vtable:
2167 // - Otherwise we can refer to vtable if it's safe to speculatively emit.
2168 // FIXME: If vtable is used by ctor/dtor, or if vtable is external and we are
2169 // sure that definition of vtable is not hidden,
2170 // then we are always safe to refer to it.
Piotr Padlewski69dc9712015-09-28 20:30:22 +00002171 // FIXME: It looks like InstCombine is very inefficient on dealing with
2172 // assumes. Make assumption loads require -fstrict-vtable-pointers temporarily.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002173 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2174 ClassDecl->isDynamicClass() && Type != Ctor_Base &&
Piotr Padlewski69dc9712015-09-28 20:30:22 +00002175 CGM.getCXXABI().canSpeculativelyEmitVTable(ClassDecl) &&
2176 CGM.getCodeGenOpts().StrictVTablePointers)
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002177 EmitVTableAssumptionLoads(ClassDecl, This);
2178}
2179
Richard Smith5179eb72016-06-28 19:03:57 +00002180void CodeGenFunction::EmitInheritedCXXConstructorCall(
2181 const CXXConstructorDecl *D, bool ForVirtualBase, Address This,
2182 bool InheritedFromVBase, const CXXInheritedCtorInitExpr *E) {
2183 CallArgList Args;
Brian Gesiak5488ab42019-01-11 01:54:53 +00002184 CallArg ThisArg(RValue::get(This.getPointer()), D->getThisType());
Richard Smith5179eb72016-06-28 19:03:57 +00002185
2186 // Forward the parameters.
2187 if (InheritedFromVBase &&
2188 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
2189 // Nothing to do; this construction is not responsible for constructing
2190 // the base class containing the inherited constructor.
2191 // FIXME: Can we just pass undef's for the remaining arguments if we don't
2192 // have constructor variants?
2193 Args.push_back(ThisArg);
2194 } else if (!CXXInheritedCtorInitExprArgs.empty()) {
2195 // The inheriting constructor was inlined; just inject its arguments.
2196 assert(CXXInheritedCtorInitExprArgs.size() >= D->getNumParams() &&
2197 "wrong number of parameters for inherited constructor call");
2198 Args = CXXInheritedCtorInitExprArgs;
2199 Args[0] = ThisArg;
2200 } else {
2201 // The inheriting constructor was not inlined. Emit delegating arguments.
2202 Args.push_back(ThisArg);
2203 const auto *OuterCtor = cast<CXXConstructorDecl>(CurCodeDecl);
2204 assert(OuterCtor->getNumParams() == D->getNumParams());
2205 assert(!OuterCtor->isVariadic() && "should have been inlined");
2206
2207 for (const auto *Param : OuterCtor->parameters()) {
2208 assert(getContext().hasSameUnqualifiedType(
2209 OuterCtor->getParamDecl(Param->getFunctionScopeIndex())->getType(),
2210 Param->getType()));
2211 EmitDelegateCallArg(Args, Param, E->getLocation());
2212
2213 // Forward __attribute__(pass_object_size).
2214 if (Param->hasAttr<PassObjectSizeAttr>()) {
2215 auto *POSParam = SizeArguments[Param];
2216 assert(POSParam && "missing pass_object_size value for forwarding");
2217 EmitDelegateCallArg(Args, POSParam, E->getLocation());
2218 }
2219 }
2220 }
2221
2222 EmitCXXConstructorCall(D, Ctor_Base, ForVirtualBase, /*Delegating*/false,
Igor Kudrineff8f9d2018-06-25 05:48:04 +00002223 This, Args, AggValueSlot::MayOverlap,
Serge Pavlov37605182018-07-28 15:33:03 +00002224 E->getLocation(), /*NewPointerIsChecked*/true);
Richard Smith5179eb72016-06-28 19:03:57 +00002225}
2226
2227void CodeGenFunction::EmitInlinedInheritingCXXConstructorCall(
2228 const CXXConstructorDecl *Ctor, CXXCtorType CtorType, bool ForVirtualBase,
2229 bool Delegating, CallArgList &Args) {
Adrian Prantlb7acfc02017-02-27 21:30:05 +00002230 GlobalDecl GD(Ctor, CtorType);
2231 InlinedInheritingConstructorScope Scope(*this, GD);
2232 ApplyInlineDebugLocation DebugScope(*this, GD);
Volodymyr Sapsai232d22f2018-12-20 22:43:26 +00002233 RunCleanupsScope RunCleanups(*this);
Richard Smith5179eb72016-06-28 19:03:57 +00002234
2235 // Save the arguments to be passed to the inherited constructor.
2236 CXXInheritedCtorInitExprArgs = Args;
2237
2238 FunctionArgList Params;
2239 QualType RetType = BuildFunctionArgList(CurGD, Params);
2240 FnRetTy = RetType;
2241
2242 // Insert any ABI-specific implicit constructor arguments.
2243 CGM.getCXXABI().addImplicitConstructorArgs(*this, Ctor, CtorType,
2244 ForVirtualBase, Delegating, Args);
2245
2246 // Emit a simplified prolog. We only need to emit the implicit params.
2247 assert(Args.size() >= Params.size() && "too few arguments for call");
2248 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2249 if (I < Params.size() && isa<ImplicitParamDecl>(Params[I])) {
Yaxun Liu5b330e82018-03-15 15:25:19 +00002250 const RValue &RV = Args[I].getRValue(*this);
Richard Smith5179eb72016-06-28 19:03:57 +00002251 assert(!RV.isComplex() && "complex indirect params not supported");
2252 ParamValue Val = RV.isScalar()
2253 ? ParamValue::forDirect(RV.getScalarVal())
2254 : ParamValue::forIndirect(RV.getAggregateAddress());
2255 EmitParmDecl(*Params[I], Val, I + 1);
2256 }
2257 }
2258
2259 // Create a return value slot if the ABI implementation wants one.
2260 // FIXME: This is dumb, we should ask the ABI not to try to set the return
2261 // value instead.
2262 if (!RetType->isVoidType())
2263 ReturnValue = CreateIRTemp(RetType, "retval.inhctor");
2264
2265 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
2266 CXXThisValue = CXXABIThisValue;
2267
2268 // Directly emit the constructor initializers.
2269 EmitCtorPrologue(Ctor, CtorType, Params);
2270}
2271
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002272void CodeGenFunction::EmitVTableAssumptionLoad(const VPtr &Vptr, Address This) {
2273 llvm::Value *VTableGlobal =
2274 CGM.getCXXABI().getVTableAddressPoint(Vptr.Base, Vptr.VTableClass);
2275 if (!VTableGlobal)
2276 return;
2277
2278 // We can just use the base offset in the complete class.
2279 CharUnits NonVirtualOffset = Vptr.Base.getBaseOffset();
2280
2281 if (!NonVirtualOffset.isZero())
2282 This =
2283 ApplyNonVirtualAndVirtualOffset(*this, This, NonVirtualOffset, nullptr,
2284 Vptr.VTableClass, Vptr.NearestVBase);
2285
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002286 llvm::Value *VPtrValue =
2287 GetVTablePtr(This, VTableGlobal->getType(), Vptr.VTableClass);
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002288 llvm::Value *Cmp =
2289 Builder.CreateICmpEQ(VPtrValue, VTableGlobal, "cmp.vtables");
2290 Builder.CreateAssumption(Cmp);
2291}
2292
2293void CodeGenFunction::EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl,
2294 Address This) {
2295 if (CGM.getCXXABI().doStructorsInitializeVPtrs(ClassDecl))
2296 for (const VPtr &Vptr : getVTablePointers(ClassDecl))
2297 EmitVTableAssumptionLoad(Vptr, This);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002298}
2299
John McCallf8ff7b92010-02-23 00:48:20 +00002300void
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002301CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
John McCall7f416cc2015-09-08 08:05:57 +00002302 Address This, Address Src,
2303 const CXXConstructExpr *E) {
Reid Kleckner739756c2013-12-04 19:23:12 +00002304 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
Justin Bogner1cd11f12015-05-20 15:53:59 +00002305
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002306 CallArgList Args;
Justin Bogner1cd11f12015-05-20 15:53:59 +00002307
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002308 // Push the this ptr.
Brian Gesiak5488ab42019-01-11 01:54:53 +00002309 Args.add(RValue::get(This.getPointer()), D->getThisType());
Justin Bogner1cd11f12015-05-20 15:53:59 +00002310
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002311 // Push the src ptr.
Alp Toker9cacbab2014-01-20 20:26:09 +00002312 QualType QT = *(FPT->param_type_begin());
Chris Lattner2192fe52011-07-18 04:24:23 +00002313 llvm::Type *t = CGM.getTypes().ConvertType(QT);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002314 Src = Builder.CreateBitCast(Src, t);
John McCall7f416cc2015-09-08 08:05:57 +00002315 Args.add(RValue::get(Src.getPointer()), QT);
Reid Kleckner739756c2013-12-04 19:23:12 +00002316
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002317 // Skip over first argument (Src).
David Blaikief05779e2015-07-21 18:37:18 +00002318 EmitCallArgs(Args, FPT, drop_begin(E->arguments(), 1), E->getConstructor(),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002319 /*ParamsToSkip*/ 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002320
Serge Pavlov37605182018-07-28 15:33:03 +00002321 EmitCXXConstructorCall(D, Ctor_Complete, /*ForVirtualBase*/false,
2322 /*Delegating*/false, This, Args,
2323 AggValueSlot::MayOverlap, E->getExprLoc(),
2324 /*NewPointerIsChecked*/false);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002325}
2326
2327void
John McCallf8ff7b92010-02-23 00:48:20 +00002328CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
2329 CXXCtorType CtorType,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002330 const FunctionArgList &Args,
2331 SourceLocation Loc) {
John McCallf8ff7b92010-02-23 00:48:20 +00002332 CallArgList DelegateArgs;
2333
2334 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
2335 assert(I != E && "no parameters to constructor");
2336
2337 // this
Richard Smith5179eb72016-06-28 19:03:57 +00002338 Address This = LoadCXXThisAddress();
2339 DelegateArgs.add(RValue::get(This.getPointer()), (*I)->getType());
John McCallf8ff7b92010-02-23 00:48:20 +00002340 ++I;
2341
Richard Smith5179eb72016-06-28 19:03:57 +00002342 // FIXME: The location of the VTT parameter in the parameter list is
2343 // specific to the Itanium ABI and shouldn't be hardcoded here.
2344 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
2345 assert(I != E && "cannot skip vtt parameter, already done with args");
2346 assert((*I)->getType()->isPointerType() &&
2347 "skipping parameter not of vtt type");
2348 ++I;
John McCallf8ff7b92010-02-23 00:48:20 +00002349 }
2350
2351 // Explicit arguments.
2352 for (; I != E; ++I) {
John McCall32ea9692011-03-11 20:59:21 +00002353 const VarDecl *param = *I;
Nick Lewycky2d84e842013-10-02 02:29:49 +00002354 // FIXME: per-argument source location
2355 EmitDelegateCallArg(DelegateArgs, param, Loc);
John McCallf8ff7b92010-02-23 00:48:20 +00002356 }
2357
Richard Smith5179eb72016-06-28 19:03:57 +00002358 EmitCXXConstructorCall(Ctor, CtorType, /*ForVirtualBase=*/false,
Richard Smithe78fac52018-04-05 20:52:58 +00002359 /*Delegating=*/true, This, DelegateArgs,
Serge Pavlov37605182018-07-28 15:33:03 +00002360 AggValueSlot::MayOverlap, Loc,
2361 /*NewPointerIsChecked=*/true);
John McCallf8ff7b92010-02-23 00:48:20 +00002362}
2363
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002364namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002365 struct CallDelegatingCtorDtor final : EHScopeStack::Cleanup {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002366 const CXXDestructorDecl *Dtor;
John McCall7f416cc2015-09-08 08:05:57 +00002367 Address Addr;
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002368 CXXDtorType Type;
2369
John McCall7f416cc2015-09-08 08:05:57 +00002370 CallDelegatingCtorDtor(const CXXDestructorDecl *D, Address Addr,
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002371 CXXDtorType Type)
2372 : Dtor(D), Addr(Addr), Type(Type) {}
2373
Craig Topper4f12f102014-03-12 06:41:41 +00002374 void Emit(CodeGenFunction &CGF, Flags flags) override {
Marco Antognini88559632019-07-22 09:39:13 +00002375 // We are calling the destructor from within the constructor.
2376 // Therefore, "this" should have the expected type.
2377 QualType ThisTy = Dtor->getThisObjectType();
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002378 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
Marco Antognini88559632019-07-22 09:39:13 +00002379 /*Delegating=*/true, Addr, ThisTy);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002380 }
2381 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00002382} // end anonymous namespace
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002383
Alexis Hunt61bc1732011-05-01 07:04:31 +00002384void
2385CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
2386 const FunctionArgList &Args) {
2387 assert(Ctor->isDelegatingConstructor());
2388
John McCall7f416cc2015-09-08 08:05:57 +00002389 Address ThisPtr = LoadCXXThisAddress();
Alexis Hunt61bc1732011-05-01 07:04:31 +00002390
John McCall31168b02011-06-15 23:02:42 +00002391 AggValueSlot AggSlot =
John McCall7f416cc2015-09-08 08:05:57 +00002392 AggValueSlot::forAddr(ThisPtr, Qualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +00002393 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00002394 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00002395 AggValueSlot::IsNotAliased,
Serge Pavlov37605182018-07-28 15:33:03 +00002396 AggValueSlot::MayOverlap,
2397 AggValueSlot::IsNotZeroed,
2398 // Checks are made by the code that calls constructor.
2399 AggValueSlot::IsSanitizerChecked);
Alexis Hunt61bc1732011-05-01 07:04:31 +00002400
2401 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
Alexis Hunt61bc1732011-05-01 07:04:31 +00002402
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002403 const CXXRecordDecl *ClassDecl = Ctor->getParent();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002404 if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002405 CXXDtorType Type =
2406 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
2407
2408 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
2409 ClassDecl->getDestructor(),
2410 ThisPtr, Type);
2411 }
2412}
Alexis Hunt61bc1732011-05-01 07:04:31 +00002413
Anders Carlsson27da15b2010-01-01 20:29:01 +00002414void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
2415 CXXDtorType Type,
Anders Carlssonf8a71f02010-05-02 23:29:11 +00002416 bool ForVirtualBase,
Marco Antognini88559632019-07-22 09:39:13 +00002417 bool Delegating, Address This,
2418 QualType ThisTy) {
Reid Kleckner6fe771a2013-12-13 00:53:54 +00002419 CGM.getCXXABI().EmitDestructorCall(*this, DD, Type, ForVirtualBase,
Marco Antognini88559632019-07-22 09:39:13 +00002420 Delegating, This, ThisTy);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002421}
2422
John McCall53cad2e2010-07-21 01:41:18 +00002423namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002424 struct CallLocalDtor final : EHScopeStack::Cleanup {
John McCall53cad2e2010-07-21 01:41:18 +00002425 const CXXDestructorDecl *Dtor;
John McCall7f416cc2015-09-08 08:05:57 +00002426 Address Addr;
Marco Antognini88559632019-07-22 09:39:13 +00002427 QualType Ty;
John McCall53cad2e2010-07-21 01:41:18 +00002428
Marco Antognini88559632019-07-22 09:39:13 +00002429 CallLocalDtor(const CXXDestructorDecl *D, Address Addr, QualType Ty)
2430 : Dtor(D), Addr(Addr), Ty(Ty) {}
John McCall53cad2e2010-07-21 01:41:18 +00002431
Craig Topper4f12f102014-03-12 06:41:41 +00002432 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall53cad2e2010-07-21 01:41:18 +00002433 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +00002434 /*ForVirtualBase=*/false,
Marco Antognini88559632019-07-22 09:39:13 +00002435 /*Delegating=*/false, Addr, Ty);
John McCall53cad2e2010-07-21 01:41:18 +00002436 }
2437 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002438} // end anonymous namespace
John McCall53cad2e2010-07-21 01:41:18 +00002439
John McCall8680f872010-07-21 06:29:51 +00002440void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
Marco Antognini88559632019-07-22 09:39:13 +00002441 QualType T, Address Addr) {
2442 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr, T);
John McCall8680f872010-07-21 06:29:51 +00002443}
2444
John McCall7f416cc2015-09-08 08:05:57 +00002445void CodeGenFunction::PushDestructorCleanup(QualType T, Address Addr) {
John McCallbd309292010-07-06 01:34:17 +00002446 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
2447 if (!ClassDecl) return;
2448 if (ClassDecl->hasTrivialDestructor()) return;
2449
2450 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCalla85af562011-04-28 02:15:35 +00002451 assert(D && D->isUsed() && "destructor not marked as used!");
Marco Antognini88559632019-07-22 09:39:13 +00002452 PushDestructorCleanup(D, T, Addr);
John McCallbd309292010-07-06 01:34:17 +00002453}
2454
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002455void CodeGenFunction::InitializeVTablePointer(const VPtr &Vptr) {
Anders Carlssone87fae92010-03-28 19:40:00 +00002456 // Compute the address point.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002457 llvm::Value *VTableAddressPoint =
2458 CGM.getCXXABI().getVTableAddressPointInStructor(
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002459 *this, Vptr.VTableClass, Vptr.Base, Vptr.NearestVBase);
2460
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002461 if (!VTableAddressPoint)
2462 return;
Anders Carlssone87fae92010-03-28 19:40:00 +00002463
Anders Carlsson6a0227d2010-04-20 16:22:16 +00002464 // Compute where to store the address point.
Craig Topper8a13c412014-05-21 05:09:00 +00002465 llvm::Value *VirtualOffset = nullptr;
Ken Dyckcfc332c2011-03-23 00:45:26 +00002466 CharUnits NonVirtualOffset = CharUnits::Zero();
Justin Bogner1cd11f12015-05-20 15:53:59 +00002467
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002468 if (CGM.getCXXABI().isVirtualOffsetNeededForVTableField(*this, Vptr)) {
Anders Carlsson91baecf2010-04-20 18:05:10 +00002469 // We need to use the virtual base offset offset because the virtual base
2470 // might have a different offset in the most derived class.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002471
2472 VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(
2473 *this, LoadCXXThisAddress(), Vptr.VTableClass, Vptr.NearestVBase);
2474 NonVirtualOffset = Vptr.OffsetFromNearestVBase;
Anders Carlsson91baecf2010-04-20 18:05:10 +00002475 } else {
Anders Carlssonc58fb552010-05-03 00:29:58 +00002476 // We can just use the base offset in the complete class.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002477 NonVirtualOffset = Vptr.Base.getBaseOffset();
Anders Carlsson91baecf2010-04-20 18:05:10 +00002478 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002479
Anders Carlssonc58fb552010-05-03 00:29:58 +00002480 // Apply the offsets.
John McCall7f416cc2015-09-08 08:05:57 +00002481 Address VTableField = LoadCXXThisAddress();
Justin Bogner1cd11f12015-05-20 15:53:59 +00002482
Ken Dyckcfc332c2011-03-23 00:45:26 +00002483 if (!NonVirtualOffset.isZero() || VirtualOffset)
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002484 VTableField = ApplyNonVirtualAndVirtualOffset(
2485 *this, VTableField, NonVirtualOffset, VirtualOffset, Vptr.VTableClass,
2486 Vptr.NearestVBase);
Anders Carlsson6a0227d2010-04-20 16:22:16 +00002487
Reid Kleckner8d585132014-12-03 21:00:21 +00002488 // Finally, store the address point. Use the same LLVM types as the field to
2489 // support optimization.
2490 llvm::Type *VTablePtrTy =
2491 llvm::FunctionType::get(CGM.Int32Ty, /*isVarArg=*/true)
2492 ->getPointerTo()
2493 ->getPointerTo();
2494 VTableField = Builder.CreateBitCast(VTableField, VTablePtrTy->getPointerTo());
2495 VTableAddressPoint = Builder.CreateBitCast(VTableAddressPoint, VTablePtrTy);
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002496
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002497 llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
Ivan A. Kosarev4e50e702017-11-27 09:39:29 +00002498 TBAAAccessInfo TBAAInfo = CGM.getTBAAVTablePtrAccessInfo(VTablePtrTy);
2499 CGM.DecorateInstructionWithTBAA(Store, TBAAInfo);
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002500 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2501 CGM.getCodeGenOpts().StrictVTablePointers)
2502 CGM.DecorateInstructionWithInvariantGroup(Store, Vptr.VTableClass);
Anders Carlssone87fae92010-03-28 19:40:00 +00002503}
2504
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002505CodeGenFunction::VPtrsVector
2506CodeGenFunction::getVTablePointers(const CXXRecordDecl *VTableClass) {
2507 CodeGenFunction::VPtrsVector VPtrsResult;
2508 VisitedVirtualBasesSetTy VBases;
2509 getVTablePointers(BaseSubobject(VTableClass, CharUnits::Zero()),
2510 /*NearestVBase=*/nullptr,
2511 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
2512 /*BaseIsNonVirtualPrimaryBase=*/false, VTableClass, VBases,
2513 VPtrsResult);
2514 return VPtrsResult;
2515}
2516
2517void CodeGenFunction::getVTablePointers(BaseSubobject Base,
2518 const CXXRecordDecl *NearestVBase,
2519 CharUnits OffsetFromNearestVBase,
2520 bool BaseIsNonVirtualPrimaryBase,
2521 const CXXRecordDecl *VTableClass,
2522 VisitedVirtualBasesSetTy &VBases,
2523 VPtrsVector &Vptrs) {
Anders Carlssond5895932010-03-28 21:07:49 +00002524 // If this base is a non-virtual primary base the address point has already
2525 // been set.
2526 if (!BaseIsNonVirtualPrimaryBase) {
2527 // Initialize the vtable pointer for this base.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002528 VPtr Vptr = {Base, NearestVBase, OffsetFromNearestVBase, VTableClass};
2529 Vptrs.push_back(Vptr);
Anders Carlssond5895932010-03-28 21:07:49 +00002530 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002531
Anders Carlssond5895932010-03-28 21:07:49 +00002532 const CXXRecordDecl *RD = Base.getBase();
2533
2534 // Traverse bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00002535 for (const auto &I : RD->bases()) {
Simon Pilgrim1cd399c2019-10-03 11:22:48 +00002536 auto *BaseDecl =
2537 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
Anders Carlssond5895932010-03-28 21:07:49 +00002538
2539 // Ignore classes without a vtable.
2540 if (!BaseDecl->isDynamicClass())
2541 continue;
2542
Ken Dyck3fb4c892011-03-23 01:04:18 +00002543 CharUnits BaseOffset;
2544 CharUnits BaseOffsetFromNearestVBase;
Anders Carlsson948d3f42010-03-29 01:16:41 +00002545 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlssond5895932010-03-28 21:07:49 +00002546
Aaron Ballman574705e2014-03-13 15:41:46 +00002547 if (I.isVirtual()) {
Anders Carlssond5895932010-03-28 21:07:49 +00002548 // Check if we've visited this virtual base before.
David Blaikie82e95a32014-11-19 07:49:47 +00002549 if (!VBases.insert(BaseDecl).second)
Anders Carlssond5895932010-03-28 21:07:49 +00002550 continue;
2551
Justin Bogner1cd11f12015-05-20 15:53:59 +00002552 const ASTRecordLayout &Layout =
Anders Carlssond5895932010-03-28 21:07:49 +00002553 getContext().getASTRecordLayout(VTableClass);
2554
Ken Dyck3fb4c892011-03-23 01:04:18 +00002555 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
2556 BaseOffsetFromNearestVBase = CharUnits::Zero();
Anders Carlsson948d3f42010-03-29 01:16:41 +00002557 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlssond5895932010-03-28 21:07:49 +00002558 } else {
2559 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
2560
Ken Dyck16ffcac2011-03-24 01:21:01 +00002561 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
Justin Bogner1cd11f12015-05-20 15:53:59 +00002562 BaseOffsetFromNearestVBase =
Ken Dyck3fb4c892011-03-23 01:04:18 +00002563 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson948d3f42010-03-29 01:16:41 +00002564 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlssond5895932010-03-28 21:07:49 +00002565 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002566
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002567 getVTablePointers(
2568 BaseSubobject(BaseDecl, BaseOffset),
2569 I.isVirtual() ? BaseDecl : NearestVBase, BaseOffsetFromNearestVBase,
2570 BaseDeclIsNonVirtualPrimaryBase, VTableClass, VBases, Vptrs);
Anders Carlssond5895932010-03-28 21:07:49 +00002571 }
2572}
2573
2574void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
2575 // Ignore classes without a vtable.
Anders Carlsson1f9348c2010-03-26 04:39:42 +00002576 if (!RD->isDynamicClass())
Anders Carlsson27da15b2010-01-01 20:29:01 +00002577 return;
2578
Anders Carlssond5895932010-03-28 21:07:49 +00002579 // Initialize the vtable pointers for this class and all of its bases.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002580 if (CGM.getCXXABI().doStructorsInitializeVPtrs(RD))
2581 for (const VPtr &Vptr : getVTablePointers(RD))
2582 InitializeVTablePointer(Vptr);
Timur Iskhodzhanovb6487322013-10-09 18:16:58 +00002583
2584 if (RD->getNumVBases())
2585 CGM.getCXXABI().initializeHiddenVirtualInheritanceMembers(*this, RD);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002586}
Dan Gohman8fc50c22010-10-26 18:44:08 +00002587
John McCall7f416cc2015-09-08 08:05:57 +00002588llvm::Value *CodeGenFunction::GetVTablePtr(Address This,
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002589 llvm::Type *VTableTy,
2590 const CXXRecordDecl *RD) {
2591 Address VTablePtrSrc = Builder.CreateElementBitCast(This, VTableTy);
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002592 llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
Ivan A. Kosarev4e50e702017-11-27 09:39:29 +00002593 TBAAAccessInfo TBAAInfo = CGM.getTBAAVTablePtrAccessInfo(VTableTy);
2594 CGM.DecorateInstructionWithTBAA(VTable, TBAAInfo);
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002595
2596 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2597 CGM.getCodeGenOpts().StrictVTablePointers)
2598 CGM.DecorateInstructionWithInvariantGroup(VTable, RD);
2599
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002600 return VTable;
Dan Gohman8fc50c22010-10-26 18:44:08 +00002601}
Anders Carlssonc36783e2011-05-08 20:32:23 +00002602
Peter Collingbourned2926c92015-03-14 02:42:25 +00002603// If a class has a single non-virtual base and does not introduce or override
2604// virtual member functions or fields, it will have the same layout as its base.
2605// This function returns the least derived such class.
2606//
2607// Casting an instance of a base class to such a derived class is technically
2608// undefined behavior, but it is a relatively common hack for introducing member
2609// functions on class instances with specific properties (e.g. llvm::Operator)
2610// that works under most compilers and should not have security implications, so
2611// we allow it by default. It can be disabled with -fsanitize=cfi-cast-strict.
2612static const CXXRecordDecl *
2613LeastDerivedClassWithSameLayout(const CXXRecordDecl *RD) {
2614 if (!RD->field_empty())
2615 return RD;
2616
2617 if (RD->getNumVBases() != 0)
2618 return RD;
2619
2620 if (RD->getNumBases() != 1)
2621 return RD;
2622
2623 for (const CXXMethodDecl *MD : RD->methods()) {
2624 if (MD->isVirtual()) {
2625 // Virtual member functions are only ok if they are implicit destructors
2626 // because the implicit destructor will have the same semantics as the
2627 // base class's destructor if no fields are added.
2628 if (isa<CXXDestructorDecl>(MD) && MD->isImplicit())
2629 continue;
2630 return RD;
2631 }
2632 }
2633
2634 return LeastDerivedClassWithSameLayout(
2635 RD->bases_begin()->getType()->getAsCXXRecordDecl());
2636}
2637
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002638void CodeGenFunction::EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD,
2639 llvm::Value *VTable,
2640 SourceLocation Loc) {
Peter Collingbourne396943a2017-07-31 22:35:33 +00002641 if (SanOpts.has(SanitizerKind::CFIVCall))
2642 EmitVTablePtrCheckForCall(RD, VTable, CodeGenFunction::CFITCK_VCall, Loc);
2643 else if (CGM.getCodeGenOpts().WholeProgramVTables &&
2644 CGM.HasHiddenLTOVisibility(RD)) {
Peter Collingbournefb532b92016-02-24 20:46:36 +00002645 llvm::Metadata *MD =
2646 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002647 llvm::Value *TypeId =
Peter Collingbournefb532b92016-02-24 20:46:36 +00002648 llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD);
2649
2650 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002651 llvm::Value *TypeTest =
2652 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
2653 {CastedVTable, TypeId});
2654 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::assume), TypeTest);
Peter Collingbournefb532b92016-02-24 20:46:36 +00002655 }
Peter Collingbournefb532b92016-02-24 20:46:36 +00002656}
2657
2658void CodeGenFunction::EmitVTablePtrCheckForCall(const CXXRecordDecl *RD,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002659 llvm::Value *VTable,
2660 CFITypeCheckKind TCK,
2661 SourceLocation Loc) {
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002662 if (!SanOpts.has(SanitizerKind::CFICastStrict))
Peter Collingbournefb532b92016-02-24 20:46:36 +00002663 RD = LeastDerivedClassWithSameLayout(RD);
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002664
Peter Collingbournefb532b92016-02-24 20:46:36 +00002665 EmitVTablePtrCheck(RD, VTable, TCK, Loc);
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002666}
2667
Peter Collingbourned2926c92015-03-14 02:42:25 +00002668void CodeGenFunction::EmitVTablePtrCheckForCast(QualType T,
2669 llvm::Value *Derived,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002670 bool MayBeNull,
2671 CFITypeCheckKind TCK,
2672 SourceLocation Loc) {
Peter Collingbourned2926c92015-03-14 02:42:25 +00002673 if (!getLangOpts().CPlusPlus)
2674 return;
2675
2676 auto *ClassTy = T->getAs<RecordType>();
2677 if (!ClassTy)
2678 return;
2679
2680 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassTy->getDecl());
2681
2682 if (!ClassDecl->isCompleteDefinition() || !ClassDecl->isDynamicClass())
2683 return;
2684
Peter Collingbourned2926c92015-03-14 02:42:25 +00002685 if (!SanOpts.has(SanitizerKind::CFICastStrict))
2686 ClassDecl = LeastDerivedClassWithSameLayout(ClassDecl);
2687
Hans Wennborgdcfba332015-10-06 23:40:43 +00002688 llvm::BasicBlock *ContBlock = nullptr;
Peter Collingbourned2926c92015-03-14 02:42:25 +00002689
2690 if (MayBeNull) {
2691 llvm::Value *DerivedNotNull =
2692 Builder.CreateIsNotNull(Derived, "cast.nonnull");
2693
2694 llvm::BasicBlock *CheckBlock = createBasicBlock("cast.check");
2695 ContBlock = createBasicBlock("cast.cont");
2696
2697 Builder.CreateCondBr(DerivedNotNull, CheckBlock, ContBlock);
2698
2699 EmitBlock(CheckBlock);
2700 }
2701
Peter Collingbourne60108802017-12-13 21:53:04 +00002702 llvm::Value *VTable;
2703 std::tie(VTable, ClassDecl) = CGM.getCXXABI().LoadVTablePtr(
2704 *this, Address(Derived, getPointerAlign()), ClassDecl);
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002705
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002706 EmitVTablePtrCheck(ClassDecl, VTable, TCK, Loc);
Peter Collingbourned2926c92015-03-14 02:42:25 +00002707
2708 if (MayBeNull) {
2709 Builder.CreateBr(ContBlock);
2710 EmitBlock(ContBlock);
2711 }
2712}
2713
2714void CodeGenFunction::EmitVTablePtrCheck(const CXXRecordDecl *RD,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002715 llvm::Value *VTable,
2716 CFITypeCheckKind TCK,
2717 SourceLocation Loc) {
Peter Collingbourne3afb2662016-04-28 17:09:37 +00002718 if (!CGM.getCodeGenOpts().SanitizeCfiCrossDso &&
2719 !CGM.HasHiddenLTOVisibility(RD))
2720 return;
2721
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002722 SanitizerMask M;
Peter Collingbournedc134532016-01-16 00:31:22 +00002723 llvm::SanitizerStatKind SSK;
2724 switch (TCK) {
2725 case CFITCK_VCall:
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002726 M = SanitizerKind::CFIVCall;
Peter Collingbournedc134532016-01-16 00:31:22 +00002727 SSK = llvm::SanStat_CFI_VCall;
2728 break;
2729 case CFITCK_NVCall:
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002730 M = SanitizerKind::CFINVCall;
Peter Collingbournedc134532016-01-16 00:31:22 +00002731 SSK = llvm::SanStat_CFI_NVCall;
2732 break;
2733 case CFITCK_DerivedCast:
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002734 M = SanitizerKind::CFIDerivedCast;
Peter Collingbournedc134532016-01-16 00:31:22 +00002735 SSK = llvm::SanStat_CFI_DerivedCast;
2736 break;
2737 case CFITCK_UnrelatedCast:
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002738 M = SanitizerKind::CFIUnrelatedCast;
Peter Collingbournedc134532016-01-16 00:31:22 +00002739 SSK = llvm::SanStat_CFI_UnrelatedCast;
2740 break;
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002741 case CFITCK_ICall:
Peter Collingbournee44acad2018-06-26 02:15:47 +00002742 case CFITCK_NVMFCall:
2743 case CFITCK_VMFCall:
2744 llvm_unreachable("unexpected sanitizer kind");
Peter Collingbournedc134532016-01-16 00:31:22 +00002745 }
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002746
2747 std::string TypeName = RD->getQualifiedNameAsString();
2748 if (getContext().getSanitizerBlacklist().isBlacklistedType(M, TypeName))
2749 return;
2750
2751 SanitizerScope SanScope(this);
Peter Collingbournedc134532016-01-16 00:31:22 +00002752 EmitSanitizerStatReport(SSK);
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002753
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002754 llvm::Metadata *MD =
2755 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002756 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002757
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002758 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002759 llvm::Value *TypeTest = Builder.CreateCall(
2760 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, TypeId});
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002761
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002762 llvm::Constant *StaticData[] = {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002763 llvm::ConstantInt::get(Int8Ty, TCK),
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002764 EmitCheckSourceLocation(Loc),
2765 EmitCheckTypeDescriptor(QualType(RD->getTypeForDecl(), 0)),
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002766 };
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002767
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002768 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
2769 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
2770 EmitCfiSlowPathCheck(M, TypeTest, CrossDsoTypeId, CastedVTable, StaticData);
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002771 return;
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002772 }
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002773
2774 if (CGM.getCodeGenOpts().SanitizeTrap.has(M)) {
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002775 EmitTrapCheck(TypeTest);
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002776 return;
2777 }
2778
2779 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
2780 CGM.getLLVMContext(),
2781 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002782 llvm::Value *ValidVtable = Builder.CreateCall(
2783 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, AllVtables});
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002784 EmitCheck(std::make_pair(TypeTest, M), SanitizerHandler::CFICheckFail,
2785 StaticData, {CastedVTable, ValidVtable});
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002786}
Anders Carlssonc36783e2011-05-08 20:32:23 +00002787
Peter Collingbourne0ca03632016-06-25 00:24:06 +00002788bool CodeGenFunction::ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD) {
2789 if (!CGM.getCodeGenOpts().WholeProgramVTables ||
Peter Collingbourne0ca03632016-06-25 00:24:06 +00002790 !CGM.HasHiddenLTOVisibility(RD))
2791 return false;
2792
Oliver Stannard3b598b92019-10-17 09:58:57 +00002793 if (CGM.getCodeGenOpts().VirtualFunctionElimination)
2794 return true;
2795
2796 if (!SanOpts.has(SanitizerKind::CFIVCall) ||
2797 !CGM.getCodeGenOpts().SanitizeTrap.has(SanitizerKind::CFIVCall))
2798 return false;
2799
Peter Collingbourne0ca03632016-06-25 00:24:06 +00002800 std::string TypeName = RD->getQualifiedNameAsString();
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002801 return !getContext().getSanitizerBlacklist().isBlacklistedType(
2802 SanitizerKind::CFIVCall, TypeName);
Peter Collingbourne0ca03632016-06-25 00:24:06 +00002803}
2804
2805llvm::Value *CodeGenFunction::EmitVTableTypeCheckedLoad(
2806 const CXXRecordDecl *RD, llvm::Value *VTable, uint64_t VTableByteOffset) {
2807 SanitizerScope SanScope(this);
2808
2809 EmitSanitizerStatReport(llvm::SanStat_CFI_VCall);
2810
2811 llvm::Metadata *MD =
2812 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
2813 llvm::Value *TypeId = llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD);
2814
2815 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
2816 llvm::Value *CheckedLoad = Builder.CreateCall(
2817 CGM.getIntrinsic(llvm::Intrinsic::type_checked_load),
2818 {CastedVTable, llvm::ConstantInt::get(Int32Ty, VTableByteOffset),
2819 TypeId});
2820 llvm::Value *CheckResult = Builder.CreateExtractValue(CheckedLoad, 1);
2821
Oliver Stannard3b598b92019-10-17 09:58:57 +00002822 std::string TypeName = RD->getQualifiedNameAsString();
2823 if (SanOpts.has(SanitizerKind::CFIVCall) &&
2824 !getContext().getSanitizerBlacklist().isBlacklistedType(
2825 SanitizerKind::CFIVCall, TypeName)) {
2826 EmitCheck(std::make_pair(CheckResult, SanitizerKind::CFIVCall),
2827 SanitizerHandler::CFICheckFail, {}, {});
2828 }
Peter Collingbourne0ca03632016-06-25 00:24:06 +00002829
2830 return Builder.CreateBitCast(
2831 Builder.CreateExtractValue(CheckedLoad, 0),
2832 cast<llvm::PointerType>(VTable->getType())->getElementType());
2833}
2834
Faisal Vali571df122013-09-29 08:45:24 +00002835void CodeGenFunction::EmitForwardingCallToLambda(
2836 const CXXMethodDecl *callOperator,
2837 CallArgList &callArgs) {
Eli Friedman5b446882012-02-16 03:47:28 +00002838 // Get the address of the call operator.
John McCall8dda7b22012-07-07 06:41:13 +00002839 const CGFunctionInfo &calleeFnInfo =
2840 CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
John McCallb92ab1a2016-10-26 23:46:34 +00002841 llvm::Constant *calleePtr =
John McCall8dda7b22012-07-07 06:41:13 +00002842 CGM.GetAddrOfFunction(GlobalDecl(callOperator),
2843 CGM.getTypes().GetFunctionType(calleeFnInfo));
Eli Friedman5b446882012-02-16 03:47:28 +00002844
John McCall8dda7b22012-07-07 06:41:13 +00002845 // Prepare the return slot.
2846 const FunctionProtoType *FPT =
2847 callOperator->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00002848 QualType resultType = FPT->getReturnType();
John McCall8dda7b22012-07-07 06:41:13 +00002849 ReturnValueSlot returnSlot;
2850 if (!resultType->isVoidType() &&
2851 calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
John McCall47fb9502013-03-07 21:37:08 +00002852 !hasScalarEvaluationKind(calleeFnInfo.getReturnType()))
John McCall8dda7b22012-07-07 06:41:13 +00002853 returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
2854
2855 // We don't need to separately arrange the call arguments because
2856 // the call can't be variadic anyway --- it's impossible to forward
2857 // variadic arguments.
Justin Bogner1cd11f12015-05-20 15:53:59 +00002858
Eli Friedman5b446882012-02-16 03:47:28 +00002859 // Now emit our call.
Erich Keanede6480a32018-11-13 15:48:08 +00002860 auto callee = CGCallee::forDirect(calleePtr, GlobalDecl(callOperator));
John McCallb92ab1a2016-10-26 23:46:34 +00002861 RValue RV = EmitCall(calleeFnInfo, callee, returnSlot, callArgs);
Eli Friedman5b446882012-02-16 03:47:28 +00002862
John McCall8dda7b22012-07-07 06:41:13 +00002863 // If necessary, copy the returned value into the slot.
John McCall95088452017-12-14 18:21:14 +00002864 if (!resultType->isVoidType() && returnSlot.isNull()) {
2865 if (getLangOpts().ObjCAutoRefCount && resultType->isObjCRetainableType()) {
2866 RV = RValue::get(EmitARCRetainAutoreleasedReturnValue(RV.getScalarVal()));
2867 }
John McCall8dda7b22012-07-07 06:41:13 +00002868 EmitReturnOfRValue(RV, resultType);
John McCall95088452017-12-14 18:21:14 +00002869 } else
Eli Friedmanf5f4d2f2012-12-13 23:37:17 +00002870 EmitBranchThroughCleanup(ReturnBlock);
Eli Friedman5b446882012-02-16 03:47:28 +00002871}
2872
Eli Friedman2495ab02012-02-25 02:48:22 +00002873void CodeGenFunction::EmitLambdaBlockInvokeBody() {
2874 const BlockDecl *BD = BlockInfo->getBlockDecl();
2875 const VarDecl *variable = BD->capture_begin()->getVariable();
2876 const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
Reid Kleckner2d3c4212017-08-04 22:38:06 +00002877 const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
2878
2879 if (CallOp->isVariadic()) {
2880 // FIXME: Making this work correctly is nasty because it requires either
2881 // cloning the body of the call operator or making the call operator
2882 // forward.
2883 CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function");
2884 return;
2885 }
Eli Friedman2495ab02012-02-25 02:48:22 +00002886
2887 // Start building arguments for forwarding call
2888 CallArgList CallArgs;
2889
2890 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
Akira Hatanaka8e57b072018-10-01 21:51:28 +00002891 Address ThisPtr = GetAddrOfBlockDecl(variable);
John McCall7f416cc2015-09-08 08:05:57 +00002892 CallArgs.add(RValue::get(ThisPtr.getPointer()), ThisType);
Eli Friedman2495ab02012-02-25 02:48:22 +00002893
2894 // Add the rest of the parameters.
David Majnemer59f77922016-06-24 04:05:48 +00002895 for (auto param : BD->parameters())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002896 EmitDelegateCallArg(CallArgs, param, param->getBeginLoc());
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00002897
Justin Bogner1cd11f12015-05-20 15:53:59 +00002898 assert(!Lambda->isGenericLambda() &&
Faisal Vali571df122013-09-29 08:45:24 +00002899 "generic lambda interconversion to block not implemented");
Reid Kleckner2d3c4212017-08-04 22:38:06 +00002900 EmitForwardingCallToLambda(CallOp, CallArgs);
Eli Friedman2495ab02012-02-25 02:48:22 +00002901}
2902
2903void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
2904 const CXXRecordDecl *Lambda = MD->getParent();
2905
2906 // Start building arguments for forwarding call
2907 CallArgList CallArgs;
2908
2909 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2910 llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
2911 CallArgs.add(RValue::get(ThisPtr), ThisType);
2912
2913 // Add the rest of the parameters.
David Majnemer59f77922016-06-24 04:05:48 +00002914 for (auto Param : MD->parameters())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002915 EmitDelegateCallArg(CallArgs, Param, Param->getBeginLoc());
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002916
Faisal Vali571df122013-09-29 08:45:24 +00002917 const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
2918 // For a generic lambda, find the corresponding call operator specialization
2919 // to which the call to the static-invoker shall be forwarded.
2920 if (Lambda->isGenericLambda()) {
2921 assert(MD->isFunctionTemplateSpecialization());
2922 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
2923 FunctionTemplateDecl *CallOpTemplate = CallOp->getDescribedFunctionTemplate();
Craig Topper8a13c412014-05-21 05:09:00 +00002924 void *InsertPos = nullptr;
Justin Bogner1cd11f12015-05-20 15:53:59 +00002925 FunctionDecl *CorrespondingCallOpSpecialization =
Craig Topper7e0daca2014-06-26 04:58:53 +00002926 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
Faisal Vali571df122013-09-29 08:45:24 +00002927 assert(CorrespondingCallOpSpecialization);
2928 CallOp = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
2929 }
2930 EmitForwardingCallToLambda(CallOp, CallArgs);
Eli Friedman2495ab02012-02-25 02:48:22 +00002931}
2932
Reid Kleckner2d3c4212017-08-04 22:38:06 +00002933void CodeGenFunction::EmitLambdaStaticInvokeBody(const CXXMethodDecl *MD) {
Douglas Gregor355efbb2012-02-17 03:02:34 +00002934 if (MD->isVariadic()) {
Eli Friedman5b446882012-02-16 03:47:28 +00002935 // FIXME: Making this work correctly is nasty because it requires either
2936 // cloning the body of the call operator or making the call operator forward.
2937 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
Eli Friedman2495ab02012-02-25 02:48:22 +00002938 return;
Eli Friedman5b446882012-02-16 03:47:28 +00002939 }
2940
Douglas Gregor355efbb2012-02-17 03:02:34 +00002941 EmitLambdaDelegatingInvokeBody(MD);
Eli Friedman5a6d5072012-02-16 01:37:33 +00002942}