blob: 64c4d3e423fdd2acd68166a8858b1cc423ec37ff [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"
Anders Carlssonc6d171e2009-10-06 22:43:30 +000019#include "clang/AST/CXXInheritance.h"
Faisal Vali571df122013-09-29 08:45:24 +000020#include "clang/AST/DeclTemplate.h"
John McCall769250e2010-09-17 02:31:44 +000021#include "clang/AST/EvaluatedExprVisitor.h"
Anders Carlsson9a57c5a2009-09-12 04:27:24 +000022#include "clang/AST/RecordLayout.h"
John McCallb81884d2010-02-19 09:25:03 +000023#include "clang/AST/StmtCXX.h"
Richard Trieu63688182018-12-11 03:18:39 +000024#include "clang/Basic/CodeGenOptions.h"
Lang Hamesbf122742013-02-17 07:22:09 +000025#include "clang/Basic/TargetBuiltins.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000026#include "clang/CodeGen/CGFunctionInfo.h"
Peter Collingbournea4ccff32015-02-20 20:30:56 +000027#include "llvm/IR/Intrinsics.h"
Piotr Padlewski4b1ac722015-09-15 21:46:55 +000028#include "llvm/IR/Metadata.h"
Peter Collingbournedc134532016-01-16 00:31:22 +000029#include "llvm/Transforms/Utils/SanitizerStats.h"
Anders Carlssonc6d171e2009-10-06 22:43:30 +000030
Anders Carlsson9a57c5a2009-09-12 04:27:24 +000031using namespace clang;
32using namespace CodeGen;
33
John McCall7f416cc2015-09-08 08:05:57 +000034/// Return the best known alignment for an unknown pointer to a
35/// particular class.
36CharUnits CodeGenModule::getClassPointerAlignment(const CXXRecordDecl *RD) {
37 if (!RD->isCompleteDefinition())
38 return CharUnits::One(); // Hopefully won't be used anywhere.
39
40 auto &layout = getContext().getASTRecordLayout(RD);
41
42 // If the class is final, then we know that the pointer points to an
43 // object of that type and can use the full alignment.
44 if (RD->hasAttr<FinalAttr>()) {
45 return layout.getAlignment();
46
47 // Otherwise, we have to assume it could be a subclass.
48 } else {
49 return layout.getNonVirtualAlignment();
50 }
51}
52
53/// Return the best known alignment for a pointer to a virtual base,
54/// given the alignment of a pointer to the derived class.
55CharUnits CodeGenModule::getVBaseAlignment(CharUnits actualDerivedAlign,
56 const CXXRecordDecl *derivedClass,
57 const CXXRecordDecl *vbaseClass) {
58 // The basic idea here is that an underaligned derived pointer might
59 // indicate an underaligned base pointer.
60
61 assert(vbaseClass->isCompleteDefinition());
62 auto &baseLayout = getContext().getASTRecordLayout(vbaseClass);
63 CharUnits expectedVBaseAlign = baseLayout.getNonVirtualAlignment();
64
65 return getDynamicOffsetAlignment(actualDerivedAlign, derivedClass,
66 expectedVBaseAlign);
67}
68
69CharUnits
70CodeGenModule::getDynamicOffsetAlignment(CharUnits actualBaseAlign,
71 const CXXRecordDecl *baseDecl,
72 CharUnits expectedTargetAlign) {
73 // If the base is an incomplete type (which is, alas, possible with
74 // member pointers), be pessimistic.
75 if (!baseDecl->isCompleteDefinition())
76 return std::min(actualBaseAlign, expectedTargetAlign);
77
78 auto &baseLayout = getContext().getASTRecordLayout(baseDecl);
79 CharUnits expectedBaseAlign = baseLayout.getNonVirtualAlignment();
80
81 // If the class is properly aligned, assume the target offset is, too.
82 //
83 // This actually isn't necessarily the right thing to do --- if the
84 // class is a complete object, but it's only properly aligned for a
85 // base subobject, then the alignments of things relative to it are
86 // probably off as well. (Note that this requires the alignment of
87 // the target to be greater than the NV alignment of the derived
88 // class.)
89 //
90 // However, our approach to this kind of under-alignment can only
91 // ever be best effort; after all, we're never going to propagate
92 // alignments through variables or parameters. Note, in particular,
93 // that constructing a polymorphic type in an address that's less
94 // than pointer-aligned will generally trap in the constructor,
95 // unless we someday add some sort of attribute to change the
96 // assumed alignment of 'this'. So our goal here is pretty much
97 // just to allow the user to explicitly say that a pointer is
Eric Christopherd160c502016-01-29 01:35:53 +000098 // under-aligned and then safely access its fields and vtables.
John McCall7f416cc2015-09-08 08:05:57 +000099 if (actualBaseAlign >= expectedBaseAlign) {
100 return expectedTargetAlign;
101 }
102
103 // Otherwise, we might be offset by an arbitrary multiple of the
104 // actual alignment. The correct adjustment is to take the min of
105 // the two alignments.
106 return std::min(actualBaseAlign, expectedTargetAlign);
107}
108
109Address CodeGenFunction::LoadCXXThisAddress() {
110 assert(CurFuncDecl && "loading 'this' without a func declaration?");
111 assert(isa<CXXMethodDecl>(CurFuncDecl));
112
113 // Lazily compute CXXThisAlignment.
114 if (CXXThisAlignment.isZero()) {
115 // Just use the best known alignment for the parent.
116 // TODO: if we're currently emitting a complete-object ctor/dtor,
117 // we can always use the complete-object alignment.
118 auto RD = cast<CXXMethodDecl>(CurFuncDecl)->getParent();
119 CXXThisAlignment = CGM.getClassPointerAlignment(RD);
120 }
121
122 return Address(LoadCXXThis(), CXXThisAlignment);
123}
124
125/// Emit the address of a field using a member data pointer.
126///
127/// \param E Only used for emergency diagnostics
128Address
129CodeGenFunction::EmitCXXMemberDataPointerAddress(const Expr *E, Address base,
130 llvm::Value *memberPtr,
131 const MemberPointerType *memberPtrType,
Ivan A. Kosarev229a6d82017-10-13 16:38:32 +0000132 LValueBaseInfo *BaseInfo,
133 TBAAAccessInfo *TBAAInfo) {
John McCall7f416cc2015-09-08 08:05:57 +0000134 // Ask the ABI to compute the actual address.
135 llvm::Value *ptr =
136 CGM.getCXXABI().EmitMemberDataPointerAddress(*this, E, base,
137 memberPtr, memberPtrType);
138
139 QualType memberType = memberPtrType->getPointeeType();
Ivan A. Kosarev78f486d2017-10-13 16:58:30 +0000140 CharUnits memberAlign = getNaturalTypeAlignment(memberType, BaseInfo,
141 TBAAInfo);
John McCall7f416cc2015-09-08 08:05:57 +0000142 memberAlign =
143 CGM.getDynamicOffsetAlignment(base.getAlignment(),
144 memberPtrType->getClass()->getAsCXXRecordDecl(),
145 memberAlign);
146 return Address(ptr, memberAlign);
147}
148
David Majnemerc1709d32015-06-23 07:31:11 +0000149CharUnits CodeGenModule::computeNonVirtualBaseClassOffset(
150 const CXXRecordDecl *DerivedClass, CastExpr::path_const_iterator Start,
151 CastExpr::path_const_iterator End) {
Ken Dycka1a4ae32011-03-22 00:53:26 +0000152 CharUnits Offset = CharUnits::Zero();
Justin Bogner1cd11f12015-05-20 15:53:59 +0000153
David Majnemerc1709d32015-06-23 07:31:11 +0000154 const ASTContext &Context = getContext();
Anders Carlssond829a022010-04-24 21:06:20 +0000155 const CXXRecordDecl *RD = DerivedClass;
Justin Bogner1cd11f12015-05-20 15:53:59 +0000156
John McCallcf142162010-08-07 06:22:56 +0000157 for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
Anders Carlssond829a022010-04-24 21:06:20 +0000158 const CXXBaseSpecifier *Base = *I;
159 assert(!Base->isVirtual() && "Should not see virtual bases here!");
160
161 // Get the layout.
162 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000163
Simon Pilgrim1cd399c2019-10-03 11:22:48 +0000164 const auto *BaseDecl =
165 cast<CXXRecordDecl>(Base->getType()->castAs<RecordType>()->getDecl());
Justin Bogner1cd11f12015-05-20 15:53:59 +0000166
Anders Carlssond829a022010-04-24 21:06:20 +0000167 // Add the offset.
Ken Dycka1a4ae32011-03-22 00:53:26 +0000168 Offset += Layout.getBaseClassOffset(BaseDecl);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000169
Anders Carlssond829a022010-04-24 21:06:20 +0000170 RD = BaseDecl;
171 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000172
Ken Dycka1a4ae32011-03-22 00:53:26 +0000173 return Offset;
Anders Carlssond829a022010-04-24 21:06:20 +0000174}
Anders Carlsson9a57c5a2009-09-12 04:27:24 +0000175
Anders Carlsson9150a2a2009-09-29 03:13:20 +0000176llvm::Constant *
Anders Carlsson8a64c1c2010-04-24 21:23:59 +0000177CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
John McCallcf142162010-08-07 06:22:56 +0000178 CastExpr::path_const_iterator PathBegin,
179 CastExpr::path_const_iterator PathEnd) {
180 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlsson8a64c1c2010-04-24 21:23:59 +0000181
Justin Bogner1cd11f12015-05-20 15:53:59 +0000182 CharUnits Offset =
David Majnemerc1709d32015-06-23 07:31:11 +0000183 computeNonVirtualBaseClassOffset(ClassDecl, PathBegin, PathEnd);
Ken Dycka1a4ae32011-03-22 00:53:26 +0000184 if (Offset.isZero())
Craig Topper8a13c412014-05-21 05:09:00 +0000185 return nullptr;
186
Justin Bogner1cd11f12015-05-20 15:53:59 +0000187 llvm::Type *PtrDiffTy =
Anders Carlsson8a64c1c2010-04-24 21:23:59 +0000188 Types.ConvertType(getContext().getPointerDiffType());
Justin Bogner1cd11f12015-05-20 15:53:59 +0000189
Ken Dycka1a4ae32011-03-22 00:53:26 +0000190 return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
Anders Carlsson9150a2a2009-09-29 03:13:20 +0000191}
192
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000193/// Gets the address of a direct base class within a complete object.
John McCall6ce74722010-02-16 04:15:37 +0000194/// This should only be used for (1) non-virtual bases or (2) virtual bases
195/// when the type is known to be complete (e.g. in complete destructors).
196///
197/// The object pointed to by 'This' is assumed to be non-null.
John McCall7f416cc2015-09-08 08:05:57 +0000198Address
199CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(Address This,
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000200 const CXXRecordDecl *Derived,
201 const CXXRecordDecl *Base,
202 bool BaseIsVirtual) {
John McCall6ce74722010-02-16 04:15:37 +0000203 // 'this' must be a pointer (in some address space) to Derived.
John McCall7f416cc2015-09-08 08:05:57 +0000204 assert(This.getElementType() == ConvertType(Derived));
John McCall6ce74722010-02-16 04:15:37 +0000205
206 // Compute the offset of the virtual base.
Ken Dyck6aa767c2011-03-22 01:21:15 +0000207 CharUnits Offset;
John McCall6ce74722010-02-16 04:15:37 +0000208 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000209 if (BaseIsVirtual)
Ken Dyck6aa767c2011-03-22 01:21:15 +0000210 Offset = Layout.getVBaseClassOffset(Base);
John McCall6ce74722010-02-16 04:15:37 +0000211 else
Ken Dyck6aa767c2011-03-22 01:21:15 +0000212 Offset = Layout.getBaseClassOffset(Base);
John McCall6ce74722010-02-16 04:15:37 +0000213
214 // Shift and cast down to the base type.
215 // TODO: for complete types, this should be possible with a GEP.
John McCall7f416cc2015-09-08 08:05:57 +0000216 Address V = This;
217 if (!Offset.isZero()) {
218 V = Builder.CreateElementBitCast(V, Int8Ty);
219 V = Builder.CreateConstInBoundsByteGEP(V, Offset);
John McCall6ce74722010-02-16 04:15:37 +0000220 }
John McCall7f416cc2015-09-08 08:05:57 +0000221 V = Builder.CreateElementBitCast(V, ConvertType(Base));
John McCall6ce74722010-02-16 04:15:37 +0000222
223 return V;
Anders Carlssone87fae92010-03-28 19:40:00 +0000224}
John McCall6ce74722010-02-16 04:15:37 +0000225
John McCall7f416cc2015-09-08 08:05:57 +0000226static Address
227ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, Address addr,
John McCall13a39c62012-08-01 05:04:58 +0000228 CharUnits nonVirtualOffset,
John McCall7f416cc2015-09-08 08:05:57 +0000229 llvm::Value *virtualOffset,
230 const CXXRecordDecl *derivedClass,
231 const CXXRecordDecl *nearestVBase) {
John McCall13a39c62012-08-01 05:04:58 +0000232 // Assert that we have something to do.
Craig Topper8a13c412014-05-21 05:09:00 +0000233 assert(!nonVirtualOffset.isZero() || virtualOffset != nullptr);
John McCall13a39c62012-08-01 05:04:58 +0000234
235 // Compute the offset from the static and dynamic components.
236 llvm::Value *baseOffset;
237 if (!nonVirtualOffset.isZero()) {
238 baseOffset = llvm::ConstantInt::get(CGF.PtrDiffTy,
239 nonVirtualOffset.getQuantity());
240 if (virtualOffset) {
241 baseOffset = CGF.Builder.CreateAdd(virtualOffset, baseOffset);
242 }
243 } else {
244 baseOffset = virtualOffset;
245 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000246
Anders Carlsson53cebd12010-04-20 16:03:35 +0000247 // Apply the base offset.
John McCall7f416cc2015-09-08 08:05:57 +0000248 llvm::Value *ptr = addr.getPointer();
Sven van Haastregtaf6248c2019-10-17 14:12:51 +0000249 unsigned AddrSpace = ptr->getType()->getPointerAddressSpace();
250 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8Ty->getPointerTo(AddrSpace));
John McCall13a39c62012-08-01 05:04:58 +0000251 ptr = CGF.Builder.CreateInBoundsGEP(ptr, baseOffset, "add.ptr");
John McCall7f416cc2015-09-08 08:05:57 +0000252
253 // If we have a virtual component, the alignment of the result will
254 // be relative only to the known alignment of that vbase.
255 CharUnits alignment;
256 if (virtualOffset) {
257 assert(nearestVBase && "virtual offset without vbase?");
258 alignment = CGF.CGM.getVBaseAlignment(addr.getAlignment(),
259 derivedClass, nearestVBase);
260 } else {
261 alignment = addr.getAlignment();
262 }
263 alignment = alignment.alignmentAtOffset(nonVirtualOffset);
264
265 return Address(ptr, alignment);
Anders Carlsson53cebd12010-04-20 16:03:35 +0000266}
267
John McCall7f416cc2015-09-08 08:05:57 +0000268Address CodeGenFunction::GetAddressOfBaseClass(
269 Address Value, const CXXRecordDecl *Derived,
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000270 CastExpr::path_const_iterator PathBegin,
271 CastExpr::path_const_iterator PathEnd, bool NullCheckValue,
272 SourceLocation Loc) {
John McCallcf142162010-08-07 06:22:56 +0000273 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssond829a022010-04-24 21:06:20 +0000274
John McCallcf142162010-08-07 06:22:56 +0000275 CastExpr::path_const_iterator Start = PathBegin;
Craig Topper8a13c412014-05-21 05:09:00 +0000276 const CXXRecordDecl *VBase = nullptr;
277
John McCall13a39c62012-08-01 05:04:58 +0000278 // Sema has done some convenient canonicalization here: if the
279 // access path involved any virtual steps, the conversion path will
280 // *start* with a step down to the correct virtual base subobject,
281 // and hence will not require any further steps.
Anders Carlssond829a022010-04-24 21:06:20 +0000282 if ((*Start)->isVirtual()) {
Simon Pilgrim1cd399c2019-10-03 11:22:48 +0000283 VBase = cast<CXXRecordDecl>(
284 (*Start)->getType()->castAs<RecordType>()->getDecl());
Anders Carlssond829a022010-04-24 21:06:20 +0000285 ++Start;
286 }
John McCall13a39c62012-08-01 05:04:58 +0000287
288 // Compute the static offset of the ultimate destination within its
289 // allocating subobject (the virtual base, if there is one, or else
290 // the "complete" object that we see).
David Majnemerc1709d32015-06-23 07:31:11 +0000291 CharUnits NonVirtualOffset = CGM.computeNonVirtualBaseClassOffset(
292 VBase ? VBase : Derived, Start, PathEnd);
Anders Carlssond829a022010-04-24 21:06:20 +0000293
John McCall13a39c62012-08-01 05:04:58 +0000294 // If there's a virtual step, we can sometimes "devirtualize" it.
295 // For now, that's limited to when the derived type is final.
296 // TODO: "devirtualize" this for accesses to known-complete objects.
297 if (VBase && Derived->hasAttr<FinalAttr>()) {
298 const ASTRecordLayout &layout = getContext().getASTRecordLayout(Derived);
299 CharUnits vBaseOffset = layout.getVBaseClassOffset(VBase);
300 NonVirtualOffset += vBaseOffset;
Craig Topper8a13c412014-05-21 05:09:00 +0000301 VBase = nullptr; // we no longer have a virtual step
John McCall13a39c62012-08-01 05:04:58 +0000302 }
303
Anders Carlssond829a022010-04-24 21:06:20 +0000304 // Get the base pointer type.
Justin Bogner1cd11f12015-05-20 15:53:59 +0000305 llvm::Type *BasePtrTy =
Anastasia Stulova94049552019-03-07 16:23:15 +0000306 ConvertType((PathEnd[-1])->getType())
307 ->getPointerTo(Value.getType()->getPointerAddressSpace());
John McCall13a39c62012-08-01 05:04:58 +0000308
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000309 QualType DerivedTy = getContext().getRecordType(Derived);
John McCall7f416cc2015-09-08 08:05:57 +0000310 CharUnits DerivedAlign = CGM.getClassPointerAlignment(Derived);
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000311
John McCall13a39c62012-08-01 05:04:58 +0000312 // If the static offset is zero and we don't have a virtual step,
313 // just do a bitcast; null checks are unnecessary.
Ken Dycka1a4ae32011-03-22 00:53:26 +0000314 if (NonVirtualOffset.isZero() && !VBase) {
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000315 if (sanitizePerformTypeCheck()) {
Vedant Kumar18348ea2017-02-17 23:22:55 +0000316 SanitizerSet SkippedChecks;
317 SkippedChecks.set(SanitizerKind::Null, !NullCheckValue);
John McCall7f416cc2015-09-08 08:05:57 +0000318 EmitTypeCheck(TCK_Upcast, Loc, Value.getPointer(),
Vedant Kumar18348ea2017-02-17 23:22:55 +0000319 DerivedTy, DerivedAlign, SkippedChecks);
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000320 }
Anders Carlssond829a022010-04-24 21:06:20 +0000321 return Builder.CreateBitCast(Value, BasePtrTy);
Craig Topper8a13c412014-05-21 05:09:00 +0000322 }
John McCall13a39c62012-08-01 05:04:58 +0000323
Craig Topper8a13c412014-05-21 05:09:00 +0000324 llvm::BasicBlock *origBB = nullptr;
325 llvm::BasicBlock *endBB = nullptr;
326
John McCall13a39c62012-08-01 05:04:58 +0000327 // Skip over the offset (and the vtable load) if we're supposed to
328 // null-check the pointer.
Anders Carlssond829a022010-04-24 21:06:20 +0000329 if (NullCheckValue) {
John McCall13a39c62012-08-01 05:04:58 +0000330 origBB = Builder.GetInsertBlock();
331 llvm::BasicBlock *notNullBB = createBasicBlock("cast.notnull");
332 endBB = createBasicBlock("cast.end");
Justin Bogner1cd11f12015-05-20 15:53:59 +0000333
John McCall7f416cc2015-09-08 08:05:57 +0000334 llvm::Value *isNull = Builder.CreateIsNull(Value.getPointer());
John McCall13a39c62012-08-01 05:04:58 +0000335 Builder.CreateCondBr(isNull, endBB, notNullBB);
336 EmitBlock(notNullBB);
Anders Carlssond829a022010-04-24 21:06:20 +0000337 }
338
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000339 if (sanitizePerformTypeCheck()) {
Vedant Kumar18348ea2017-02-17 23:22:55 +0000340 SanitizerSet SkippedChecks;
341 SkippedChecks.set(SanitizerKind::Null, true);
John McCall7f416cc2015-09-08 08:05:57 +0000342 EmitTypeCheck(VBase ? TCK_UpcastToVirtualBase : TCK_Upcast, Loc,
Vedant Kumar18348ea2017-02-17 23:22:55 +0000343 Value.getPointer(), DerivedTy, DerivedAlign, SkippedChecks);
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000344 }
345
John McCall13a39c62012-08-01 05:04:58 +0000346 // Compute the virtual offset.
Craig Topper8a13c412014-05-21 05:09:00 +0000347 llvm::Value *VirtualOffset = nullptr;
Anders Carlssona376b532011-01-29 03:18:56 +0000348 if (VBase) {
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000349 VirtualOffset =
350 CGM.getCXXABI().GetVirtualBaseClassOffset(*this, Value, Derived, VBase);
Anders Carlssona376b532011-01-29 03:18:56 +0000351 }
Anders Carlssond829a022010-04-24 21:06:20 +0000352
John McCall13a39c62012-08-01 05:04:58 +0000353 // Apply both offsets.
John McCall7f416cc2015-09-08 08:05:57 +0000354 Value = ApplyNonVirtualAndVirtualOffset(*this, Value, NonVirtualOffset,
355 VirtualOffset, Derived, VBase);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000356
John McCall13a39c62012-08-01 05:04:58 +0000357 // Cast to the destination type.
Anders Carlssond829a022010-04-24 21:06:20 +0000358 Value = Builder.CreateBitCast(Value, BasePtrTy);
John McCall13a39c62012-08-01 05:04:58 +0000359
360 // Build a phi if we needed a null check.
Anders Carlssond829a022010-04-24 21:06:20 +0000361 if (NullCheckValue) {
John McCall13a39c62012-08-01 05:04:58 +0000362 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
363 Builder.CreateBr(endBB);
364 EmitBlock(endBB);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000365
John McCall13a39c62012-08-01 05:04:58 +0000366 llvm::PHINode *PHI = Builder.CreatePHI(BasePtrTy, 2, "cast.result");
John McCall7f416cc2015-09-08 08:05:57 +0000367 PHI->addIncoming(Value.getPointer(), notNullBB);
John McCall13a39c62012-08-01 05:04:58 +0000368 PHI->addIncoming(llvm::Constant::getNullValue(BasePtrTy), origBB);
John McCall7f416cc2015-09-08 08:05:57 +0000369 Value = Address(PHI, Value.getAlignment());
Anders Carlssond829a022010-04-24 21:06:20 +0000370 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000371
Anders Carlssond829a022010-04-24 21:06:20 +0000372 return Value;
373}
374
John McCall7f416cc2015-09-08 08:05:57 +0000375Address
376CodeGenFunction::GetAddressOfDerivedClass(Address BaseAddr,
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000377 const CXXRecordDecl *Derived,
John McCallcf142162010-08-07 06:22:56 +0000378 CastExpr::path_const_iterator PathBegin,
379 CastExpr::path_const_iterator PathEnd,
Anders Carlsson8c793172009-11-23 17:57:54 +0000380 bool NullCheckValue) {
John McCallcf142162010-08-07 06:22:56 +0000381 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlsson8a64c1c2010-04-24 21:23:59 +0000382
Anders Carlsson8c793172009-11-23 17:57:54 +0000383 QualType DerivedTy =
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000384 getContext().getCanonicalType(getContext().getTagDeclType(Derived));
Sven van Haastregtaf6248c2019-10-17 14:12:51 +0000385 unsigned AddrSpace =
386 BaseAddr.getPointer()->getType()->getPointerAddressSpace();
387 llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo(AddrSpace);
Richard Smith2c5868c2013-02-13 21:18:23 +0000388
Anders Carlsson600f7372010-01-31 01:43:37 +0000389 llvm::Value *NonVirtualOffset =
John McCallcf142162010-08-07 06:22:56 +0000390 CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000391
Anders Carlsson600f7372010-01-31 01:43:37 +0000392 if (!NonVirtualOffset) {
393 // No offset, we can just cast back.
John McCall7f416cc2015-09-08 08:05:57 +0000394 return Builder.CreateBitCast(BaseAddr, DerivedPtrTy);
Anders Carlsson600f7372010-01-31 01:43:37 +0000395 }
Craig Topper8a13c412014-05-21 05:09:00 +0000396
397 llvm::BasicBlock *CastNull = nullptr;
398 llvm::BasicBlock *CastNotNull = nullptr;
399 llvm::BasicBlock *CastEnd = nullptr;
400
Anders Carlsson8c793172009-11-23 17:57:54 +0000401 if (NullCheckValue) {
402 CastNull = createBasicBlock("cast.null");
403 CastNotNull = createBasicBlock("cast.notnull");
404 CastEnd = createBasicBlock("cast.end");
Justin Bogner1cd11f12015-05-20 15:53:59 +0000405
John McCall7f416cc2015-09-08 08:05:57 +0000406 llvm::Value *IsNull = Builder.CreateIsNull(BaseAddr.getPointer());
Anders Carlsson8c793172009-11-23 17:57:54 +0000407 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
408 EmitBlock(CastNotNull);
409 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000410
Anders Carlsson600f7372010-01-31 01:43:37 +0000411 // Apply the offset.
John McCall7f416cc2015-09-08 08:05:57 +0000412 llvm::Value *Value = Builder.CreateBitCast(BaseAddr.getPointer(), Int8PtrTy);
Sanjay Patel372c3f12018-01-19 15:14:51 +0000413 Value = Builder.CreateInBoundsGEP(Value, Builder.CreateNeg(NonVirtualOffset),
414 "sub.ptr");
Anders Carlsson600f7372010-01-31 01:43:37 +0000415
416 // Just cast.
417 Value = Builder.CreateBitCast(Value, DerivedPtrTy);
Anders Carlsson8c793172009-11-23 17:57:54 +0000418
John McCall7f416cc2015-09-08 08:05:57 +0000419 // Produce a PHI if we had a null-check.
Anders Carlsson8c793172009-11-23 17:57:54 +0000420 if (NullCheckValue) {
421 Builder.CreateBr(CastEnd);
422 EmitBlock(CastNull);
423 Builder.CreateBr(CastEnd);
424 EmitBlock(CastEnd);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000425
Jay Foad20c0f022011-03-30 11:28:58 +0000426 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
Anders Carlsson8c793172009-11-23 17:57:54 +0000427 PHI->addIncoming(Value, CastNotNull);
John McCall7f416cc2015-09-08 08:05:57 +0000428 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
Anders Carlsson8c793172009-11-23 17:57:54 +0000429 Value = PHI;
430 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000431
John McCall7f416cc2015-09-08 08:05:57 +0000432 return Address(Value, CGM.getClassPointerAlignment(Derived));
Anders Carlsson9a57c5a2009-09-12 04:27:24 +0000433}
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000434
435llvm::Value *CodeGenFunction::GetVTTParameter(GlobalDecl GD,
436 bool ForVirtualBase,
437 bool Delegating) {
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000438 if (!CGM.getCXXABI().NeedsVTTParameter(GD)) {
Anders Carlssone36a6b32010-01-02 01:01:18 +0000439 // This constructor/destructor does not need a VTT parameter.
Craig Topper8a13c412014-05-21 05:09:00 +0000440 return nullptr;
Anders Carlssone36a6b32010-01-02 01:01:18 +0000441 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000442
John McCalldec348f72013-05-03 07:33:41 +0000443 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CurCodeDecl)->getParent();
Anders Carlssone36a6b32010-01-02 01:01:18 +0000444 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
John McCall5c60a6f2010-02-18 19:59:28 +0000445
Anders Carlssone36a6b32010-01-02 01:01:18 +0000446 llvm::Value *VTT;
447
John McCall5c60a6f2010-02-18 19:59:28 +0000448 uint64_t SubVTTIndex;
449
Douglas Gregor61535002013-01-31 05:50:40 +0000450 if (Delegating) {
451 // If this is a delegating constructor call, just load the VTT.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000452 return LoadCXXVTT();
Douglas Gregor61535002013-01-31 05:50:40 +0000453 } else if (RD == Base) {
454 // If the record matches the base, this is the complete ctor/dtor
455 // variant calling the base variant in a class with virtual bases.
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000456 assert(!CGM.getCXXABI().NeedsVTTParameter(CurGD) &&
John McCall5c60a6f2010-02-18 19:59:28 +0000457 "doing no-op VTT offset in base dtor/ctor?");
Anders Carlsson4d205ba2010-05-02 23:33:10 +0000458 assert(!ForVirtualBase && "Can't have same class as virtual base!");
John McCall5c60a6f2010-02-18 19:59:28 +0000459 SubVTTIndex = 0;
460 } else {
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000461 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000462 CharUnits BaseOffset = ForVirtualBase ?
463 Layout.getVBaseClassOffset(Base) :
Ken Dyck16ffcac2011-03-24 01:21:01 +0000464 Layout.getBaseClassOffset(Base);
Anders Carlsson859b3062010-05-02 23:53:25 +0000465
Justin Bogner1cd11f12015-05-20 15:53:59 +0000466 SubVTTIndex =
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000467 CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
John McCall5c60a6f2010-02-18 19:59:28 +0000468 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
469 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000470
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000471 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
Anders Carlssone36a6b32010-01-02 01:01:18 +0000472 // A VTT parameter was passed to the constructor, use it.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000473 VTT = LoadCXXVTT();
474 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
Anders Carlssone36a6b32010-01-02 01:01:18 +0000475 } else {
476 // We're the complete constructor, so get the VTT by name.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000477 VTT = CGM.getVTables().GetAddrOfVTT(RD);
478 VTT = Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
Anders Carlssone36a6b32010-01-02 01:01:18 +0000479 }
480
481 return VTT;
482}
483
John McCall1d987562010-07-21 01:23:41 +0000484namespace {
John McCallf99a6312010-07-21 05:30:47 +0000485 /// Call the destructor for a direct base class.
David Blaikie7e70d682015-08-18 22:40:54 +0000486 struct CallBaseDtor final : EHScopeStack::Cleanup {
John McCallf99a6312010-07-21 05:30:47 +0000487 const CXXRecordDecl *BaseClass;
488 bool BaseIsVirtual;
489 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
490 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
John McCall1d987562010-07-21 01:23:41 +0000491
Craig Topper4f12f102014-03-12 06:41:41 +0000492 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallf99a6312010-07-21 05:30:47 +0000493 const CXXRecordDecl *DerivedClass =
494 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
495
496 const CXXDestructorDecl *D = BaseClass->getDestructor();
Marco Antognini88559632019-07-22 09:39:13 +0000497 // We are already inside a destructor, so presumably the object being
498 // destroyed should have the expected type.
499 QualType ThisTy = D->getThisObjectType();
John McCall7f416cc2015-09-08 08:05:57 +0000500 Address Addr =
501 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThisAddress(),
John McCallf99a6312010-07-21 05:30:47 +0000502 DerivedClass, BaseClass,
503 BaseIsVirtual);
Douglas Gregor61535002013-01-31 05:50:40 +0000504 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual,
Marco Antognini88559632019-07-22 09:39:13 +0000505 /*Delegating=*/false, Addr, ThisTy);
John McCall1d987562010-07-21 01:23:41 +0000506 }
507 };
John McCall769250e2010-09-17 02:31:44 +0000508
509 /// A visitor which checks whether an initializer uses 'this' in a
510 /// way which requires the vtable to be properly set.
Scott Douglass503fc392015-06-10 13:53:15 +0000511 struct DynamicThisUseChecker : ConstEvaluatedExprVisitor<DynamicThisUseChecker> {
512 typedef ConstEvaluatedExprVisitor<DynamicThisUseChecker> super;
John McCall769250e2010-09-17 02:31:44 +0000513
514 bool UsesThis;
515
Scott Douglass503fc392015-06-10 13:53:15 +0000516 DynamicThisUseChecker(const ASTContext &C) : super(C), UsesThis(false) {}
John McCall769250e2010-09-17 02:31:44 +0000517
518 // Black-list all explicit and implicit references to 'this'.
519 //
520 // Do we need to worry about external references to 'this' derived
521 // from arbitrary code? If so, then anything which runs arbitrary
522 // external code might potentially access the vtable.
Scott Douglass503fc392015-06-10 13:53:15 +0000523 void VisitCXXThisExpr(const CXXThisExpr *E) { UsesThis = true; }
John McCall769250e2010-09-17 02:31:44 +0000524 };
Hans Wennborgdcfba332015-10-06 23:40:43 +0000525} // end anonymous namespace
John McCall769250e2010-09-17 02:31:44 +0000526
527static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
528 DynamicThisUseChecker Checker(C);
Scott Douglass503fc392015-06-10 13:53:15 +0000529 Checker.Visit(Init);
John McCall769250e2010-09-17 02:31:44 +0000530 return Checker.UsesThis;
John McCall1d987562010-07-21 01:23:41 +0000531}
532
Justin Bogner1cd11f12015-05-20 15:53:59 +0000533static void EmitBaseInitializer(CodeGenFunction &CGF,
Anders Carlssonfb404882009-12-24 22:46:43 +0000534 const CXXRecordDecl *ClassDecl,
Reid Kleckner61c9b7c2019-03-18 22:41:50 +0000535 CXXCtorInitializer *BaseInit) {
Anders Carlssonfb404882009-12-24 22:46:43 +0000536 assert(BaseInit->isBaseInitializer() &&
537 "Must have base initializer!");
538
John McCall7f416cc2015-09-08 08:05:57 +0000539 Address ThisPtr = CGF.LoadCXXThisAddress();
Justin Bogner1cd11f12015-05-20 15:53:59 +0000540
Anders Carlssonfb404882009-12-24 22:46:43 +0000541 const Type *BaseType = BaseInit->getBaseClass();
Simon Pilgrim1cd399c2019-10-03 11:22:48 +0000542 const auto *BaseClassDecl =
543 cast<CXXRecordDecl>(BaseType->castAs<RecordType>()->getDecl());
Anders Carlssonfb404882009-12-24 22:46:43 +0000544
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +0000545 bool isBaseVirtual = BaseInit->isBaseVirtual();
Anders Carlssonfb404882009-12-24 22:46:43 +0000546
John McCall769250e2010-09-17 02:31:44 +0000547 // If the initializer for the base (other than the constructor
548 // itself) accesses 'this' in any way, we need to initialize the
549 // vtables.
550 if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
551 CGF.InitializeVTablePointers(ClassDecl);
552
John McCall6ce74722010-02-16 04:15:37 +0000553 // We can pretend to be a complete class because it only matters for
554 // virtual bases, and we only do virtual bases for complete ctors.
John McCall7f416cc2015-09-08 08:05:57 +0000555 Address V =
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000556 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
John McCallf99a6312010-07-21 05:30:47 +0000557 BaseClassDecl,
558 isBaseVirtual);
John McCall8d6fc952011-08-25 20:40:09 +0000559 AggValueSlot AggSlot =
Richard Smithe78fac52018-04-05 20:52:58 +0000560 AggValueSlot::forAddr(
561 V, Qualifiers(),
562 AggValueSlot::IsDestructed,
563 AggValueSlot::DoesNotNeedGCBarriers,
564 AggValueSlot::IsNotAliased,
Richard Smith8cca3a52019-06-20 20:56:20 +0000565 CGF.getOverlapForBaseInit(ClassDecl, BaseClassDecl, isBaseVirtual));
John McCall7a626f62010-09-15 10:14:12 +0000566
567 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000568
569 if (CGF.CGM.getLangOpts().Exceptions &&
Anders Carlsson08ce5ed2011-02-20 00:20:27 +0000570 !BaseClassDecl->hasTrivialDestructor())
John McCallcda666c2010-07-21 07:22:38 +0000571 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
572 isBaseVirtual);
Anders Carlssonfb404882009-12-24 22:46:43 +0000573}
574
Richard Smith419bd092015-04-29 19:26:57 +0000575static bool isMemcpyEquivalentSpecialMember(const CXXMethodDecl *D) {
576 auto *CD = dyn_cast<CXXConstructorDecl>(D);
577 if (!(CD && CD->isCopyOrMoveConstructor()) &&
578 !D->isCopyAssignmentOperator() && !D->isMoveAssignmentOperator())
579 return false;
580
581 // We can emit a memcpy for a trivial copy or move constructor/assignment.
582 if (D->isTrivial() && !D->getParent()->mayInsertExtraPadding())
583 return true;
584
585 // We *must* emit a memcpy for a defaulted union copy or move op.
586 if (D->getParent()->isUnion() && D->isDefaulted())
587 return true;
588
589 return false;
590}
591
Alexey Bataev152c71f2015-07-14 07:55:48 +0000592static void EmitLValueForAnyFieldInitialization(CodeGenFunction &CGF,
593 CXXCtorInitializer *MemberInit,
594 LValue &LHS) {
595 FieldDecl *Field = MemberInit->getAnyMember();
596 if (MemberInit->isIndirectMemberInitializer()) {
597 // If we are initializing an anonymous union field, drill down to the field.
598 IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember();
599 for (const auto *I : IndirectField->chain())
600 LHS = CGF.EmitLValueForFieldInitialization(LHS, cast<FieldDecl>(I));
601 } else {
602 LHS = CGF.EmitLValueForFieldInitialization(LHS, Field);
603 }
604}
605
Anders Carlssonfb404882009-12-24 22:46:43 +0000606static void EmitMemberInitializer(CodeGenFunction &CGF,
607 const CXXRecordDecl *ClassDecl,
Alexis Hunt1d792652011-01-08 20:30:50 +0000608 CXXCtorInitializer *MemberInit,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000609 const CXXConstructorDecl *Constructor,
610 FunctionArgList &Args) {
David Blaikiea81d4102015-01-18 00:12:58 +0000611 ApplyDebugLocation Loc(CGF, MemberInit->getSourceLocation());
Francois Pichetd583da02010-12-04 09:14:42 +0000612 assert(MemberInit->isAnyMemberInitializer() &&
Anders Carlssonfb404882009-12-24 22:46:43 +0000613 "Must have member initializer!");
Richard Smith938f40b2011-06-11 17:19:42 +0000614 assert(MemberInit->getInit() && "Must have initializer!");
Justin Bogner1cd11f12015-05-20 15:53:59 +0000615
Anders Carlssonfb404882009-12-24 22:46:43 +0000616 // non-static data member initializers.
Francois Pichetd583da02010-12-04 09:14:42 +0000617 FieldDecl *Field = MemberInit->getAnyMember();
Eli Friedman6ae63022012-02-14 02:15:49 +0000618 QualType FieldType = Field->getType();
Anders Carlssonfb404882009-12-24 22:46:43 +0000619
620 llvm::Value *ThisPtr = CGF.LoadCXXThis();
Eli Friedman7f1ff602012-04-16 03:54:45 +0000621 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
Akira Hatanakae5dbb642018-01-27 00:34:09 +0000622 LValue LHS;
623
624 // If a base constructor is being emitted, create an LValue that has the
625 // non-virtual alignment.
626 if (CGF.CurGD.getCtorType() == Ctor_Base)
627 LHS = CGF.MakeNaturalAlignPointeeAddrLValue(ThisPtr, RecordTy);
628 else
629 LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
Eli Friedman7f1ff602012-04-16 03:54:45 +0000630
Alexey Bataev152c71f2015-07-14 07:55:48 +0000631 EmitLValueForAnyFieldInitialization(CGF, MemberInit, LHS);
Anders Carlssonfb404882009-12-24 22:46:43 +0000632
Eli Friedman6ae63022012-02-14 02:15:49 +0000633 // Special case: if we are in a copy or move constructor, and we are copying
634 // an array of PODs or classes with trivial copy constructors, ignore the
635 // AST and perform the copy we know is equivalent.
636 // FIXME: This is hacky at best... if we had a bit more explicit information
637 // in the AST, we could generalize it more easily.
638 const ConstantArrayType *Array
639 = CGF.getContext().getAsConstantArrayType(FieldType);
Jordan Rose54533f72013-08-07 16:16:48 +0000640 if (Array && Constructor->isDefaulted() &&
Eli Friedman6ae63022012-02-14 02:15:49 +0000641 Constructor->isCopyOrMoveConstructor()) {
642 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
Richard Smith993f25a2012-11-07 23:56:21 +0000643 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
Eli Friedman6ae63022012-02-14 02:15:49 +0000644 if (BaseElementTy.isPODType(CGF.getContext()) ||
Richard Smith419bd092015-04-29 19:26:57 +0000645 (CE && isMemcpyEquivalentSpecialMember(CE->getConstructor()))) {
David Majnemer1573d732014-10-15 04:54:54 +0000646 unsigned SrcArgIndex =
647 CGF.CGM.getCXXABI().getSrcArgforCopyCtor(Constructor, Args);
Eli Friedman6ae63022012-02-14 02:15:49 +0000648 llvm::Value *SrcPtr
649 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
Eli Friedman7f1ff602012-04-16 03:54:45 +0000650 LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
651 LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000652
Eli Friedman6ae63022012-02-14 02:15:49 +0000653 // Copy the aggregate.
Richard Smith8cca3a52019-06-20 20:56:20 +0000654 CGF.EmitAggregateCopy(LHS, Src, FieldType, CGF.getOverlapForFieldInit(Field),
Richard Smithe78fac52018-04-05 20:52:58 +0000655 LHS.isVolatileQualified());
Alexey Bataev5d49b832015-07-08 07:31:02 +0000656 // Ensure that we destroy the objects if an exception is thrown later in
657 // the constructor.
658 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
659 if (CGF.needsEHCleanup(dtorKind))
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800660 CGF.pushEHDestroy(dtorKind, LHS.getAddress(CGF), FieldType);
Eli Friedman6ae63022012-02-14 02:15:49 +0000661 return;
662 }
663 }
664
Richard Smith30e304e2016-12-14 00:03:17 +0000665 CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit());
Eli Friedman6ae63022012-02-14 02:15:49 +0000666}
667
John McCall7f416cc2015-09-08 08:05:57 +0000668void CodeGenFunction::EmitInitializerForField(FieldDecl *Field, LValue LHS,
Richard Smith30e304e2016-12-14 00:03:17 +0000669 Expr *Init) {
Eli Friedman6ae63022012-02-14 02:15:49 +0000670 QualType FieldType = Field->getType();
John McCall47fb9502013-03-07 21:37:08 +0000671 switch (getEvaluationKind(FieldType)) {
672 case TEK_Scalar:
John McCall31168b02011-06-15 23:02:42 +0000673 if (LHS.isSimple()) {
David Blaikie66e41972015-01-14 07:38:27 +0000674 EmitExprAsInit(Init, Field, LHS, false);
John McCall31168b02011-06-15 23:02:42 +0000675 } else {
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000676 RValue RHS = RValue::get(EmitScalarExpr(Init));
677 EmitStoreThroughLValue(RHS, LHS);
John McCall31168b02011-06-15 23:02:42 +0000678 }
John McCall47fb9502013-03-07 21:37:08 +0000679 break;
680 case TEK_Complex:
David Blaikie66e41972015-01-14 07:38:27 +0000681 EmitComplexExprIntoLValue(Init, LHS, /*isInit*/ true);
John McCall47fb9502013-03-07 21:37:08 +0000682 break;
683 case TEK_Aggregate: {
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800684 AggValueSlot Slot = AggValueSlot::forLValue(
685 LHS, *this, AggValueSlot::IsDestructed,
686 AggValueSlot::DoesNotNeedGCBarriers, AggValueSlot::IsNotAliased,
687 getOverlapForFieldInit(Field), AggValueSlot::IsNotZeroed,
688 // Checks are made by the code that calls constructor.
689 AggValueSlot::IsSanitizerChecked);
Richard Smith30e304e2016-12-14 00:03:17 +0000690 EmitAggExpr(Init, Slot);
691 break;
Anders Carlssonfb404882009-12-24 22:46:43 +0000692 }
John McCall47fb9502013-03-07 21:37:08 +0000693 }
John McCall12cc42a2013-02-01 05:11:40 +0000694
695 // Ensure that we destroy this object if an exception is thrown
696 // later in the constructor.
697 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
698 if (needsEHCleanup(dtorKind))
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800699 pushEHDestroy(dtorKind, LHS.getAddress(*this), FieldType);
Anders Carlssonfb404882009-12-24 22:46:43 +0000700}
701
John McCallf8ff7b92010-02-23 00:48:20 +0000702/// Checks whether the given constructor is a valid subject for the
703/// complete-to-base constructor delegation optimization, i.e.
704/// emitting the complete constructor as a simple call to the base
705/// constructor.
Vedant Kumar7f809b22017-02-24 01:15:19 +0000706bool CodeGenFunction::IsConstructorDelegationValid(
707 const CXXConstructorDecl *Ctor) {
John McCallf8ff7b92010-02-23 00:48:20 +0000708
709 // Currently we disable the optimization for classes with virtual
710 // bases because (1) the addresses of parameter variables need to be
711 // consistent across all initializers but (2) the delegate function
712 // call necessarily creates a second copy of the parameter variable.
713 //
714 // The limiting example (purely theoretical AFAIK):
715 // struct A { A(int &c) { c++; } };
716 // struct B : virtual A {
717 // B(int count) : A(count) { printf("%d\n", count); }
718 // };
719 // ...although even this example could in principle be emitted as a
720 // delegation since the address of the parameter doesn't escape.
721 if (Ctor->getParent()->getNumVBases()) {
722 // TODO: white-list trivial vbase initializers. This case wouldn't
723 // be subject to the restrictions below.
724
725 // TODO: white-list cases where:
726 // - there are no non-reference parameters to the constructor
727 // - the initializers don't access any non-reference parameters
728 // - the initializers don't take the address of non-reference
729 // parameters
730 // - etc.
731 // If we ever add any of the above cases, remember that:
732 // - function-try-blocks will always blacklist this optimization
733 // - we need to perform the constructor prologue and cleanup in
734 // EmitConstructorBody.
735
736 return false;
737 }
738
739 // We also disable the optimization for variadic functions because
740 // it's impossible to "re-pass" varargs.
Simon Pilgrim7e38f0c2019-10-07 16:42:25 +0000741 if (Ctor->getType()->castAs<FunctionProtoType>()->isVariadic())
John McCallf8ff7b92010-02-23 00:48:20 +0000742 return false;
743
Alexis Hunt61bc1732011-05-01 07:04:31 +0000744 // FIXME: Decide if we can do a delegation of a delegating constructor.
745 if (Ctor->isDelegatingConstructor())
746 return false;
747
John McCallf8ff7b92010-02-23 00:48:20 +0000748 return true;
749}
750
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000751// Emit code in ctor (Prologue==true) or dtor (Prologue==false)
752// to poison the extra field paddings inserted under
753// -fsanitize-address-field-padding=1|2.
754void CodeGenFunction::EmitAsanPrologueOrEpilogue(bool Prologue) {
755 ASTContext &Context = getContext();
756 const CXXRecordDecl *ClassDecl =
757 Prologue ? cast<CXXConstructorDecl>(CurGD.getDecl())->getParent()
758 : cast<CXXDestructorDecl>(CurGD.getDecl())->getParent();
759 if (!ClassDecl->mayInsertExtraPadding()) return;
760
761 struct SizeAndOffset {
762 uint64_t Size;
763 uint64_t Offset;
764 };
765
766 unsigned PtrSize = CGM.getDataLayout().getPointerSizeInBits();
767 const ASTRecordLayout &Info = Context.getASTRecordLayout(ClassDecl);
768
769 // Populate sizes and offsets of fields.
770 SmallVector<SizeAndOffset, 16> SSV(Info.getFieldCount());
771 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i)
772 SSV[i].Offset =
773 Context.toCharUnitsFromBits(Info.getFieldOffset(i)).getQuantity();
774
775 size_t NumFields = 0;
776 for (const auto *Field : ClassDecl->fields()) {
777 const FieldDecl *D = Field;
778 std::pair<CharUnits, CharUnits> FieldInfo =
779 Context.getTypeInfoInChars(D->getType());
780 CharUnits FieldSize = FieldInfo.first;
781 assert(NumFields < SSV.size());
782 SSV[NumFields].Size = D->isBitField() ? 0 : FieldSize.getQuantity();
783 NumFields++;
784 }
785 assert(NumFields == SSV.size());
786 if (SSV.size() <= 1) return;
787
788 // We will insert calls to __asan_* run-time functions.
789 // LLVM AddressSanitizer pass may decide to inline them later.
790 llvm::Type *Args[2] = {IntPtrTy, IntPtrTy};
791 llvm::FunctionType *FTy =
792 llvm::FunctionType::get(CGM.VoidTy, Args, false);
James Y Knight9871db02019-02-05 16:42:33 +0000793 llvm::FunctionCallee F = CGM.CreateRuntimeFunction(
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000794 FTy, Prologue ? "__asan_poison_intra_object_redzone"
795 : "__asan_unpoison_intra_object_redzone");
796
797 llvm::Value *ThisPtr = LoadCXXThis();
798 ThisPtr = Builder.CreatePtrToInt(ThisPtr, IntPtrTy);
Kostya Serebryany64449212014-10-17 21:02:13 +0000799 uint64_t TypeSize = Info.getNonVirtualSize().getQuantity();
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000800 // For each field check if it has sufficient padding,
801 // if so (un)poison it with a call.
802 for (size_t i = 0; i < SSV.size(); i++) {
803 uint64_t AsanAlignment = 8;
804 uint64_t NextField = i == SSV.size() - 1 ? TypeSize : SSV[i + 1].Offset;
805 uint64_t PoisonSize = NextField - SSV[i].Offset - SSV[i].Size;
806 uint64_t EndOffset = SSV[i].Offset + SSV[i].Size;
807 if (PoisonSize < AsanAlignment || !SSV[i].Size ||
808 (NextField % AsanAlignment) != 0)
809 continue;
David Blaikie43f9bb72015-05-18 22:14:03 +0000810 Builder.CreateCall(
811 F, {Builder.CreateAdd(ThisPtr, Builder.getIntN(PtrSize, EndOffset)),
812 Builder.getIntN(PtrSize, PoisonSize)});
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000813 }
814}
815
John McCallb81884d2010-02-19 09:25:03 +0000816/// EmitConstructorBody - Emits the body of the current constructor.
817void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000818 EmitAsanPrologueOrEpilogue(true);
John McCallb81884d2010-02-19 09:25:03 +0000819 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
820 CXXCtorType CtorType = CurGD.getCtorType();
821
Reid Kleckner340ad862014-01-13 22:57:31 +0000822 assert((CGM.getTarget().getCXXABI().hasConstructorVariants() ||
823 CtorType == Ctor_Complete) &&
824 "can only generate complete ctor for this ABI");
825
John McCallf8ff7b92010-02-23 00:48:20 +0000826 // Before we go any further, try the complete->base constructor
827 // delegation optimization.
Timur Iskhodzhanovf32a3772012-04-20 08:05:00 +0000828 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
John McCallc8e01702013-04-16 22:48:15 +0000829 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000830 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args, Ctor->getEndLoc());
John McCallf8ff7b92010-02-23 00:48:20 +0000831 return;
832 }
833
Hans Wennborgdcfba332015-10-06 23:40:43 +0000834 const FunctionDecl *Definition = nullptr;
Richard Smith46bb5812014-08-01 01:56:39 +0000835 Stmt *Body = Ctor->getBody(Definition);
836 assert(Definition == Ctor && "emitting wrong constructor body");
John McCallb81884d2010-02-19 09:25:03 +0000837
John McCallf8ff7b92010-02-23 00:48:20 +0000838 // Enter the function-try-block before the constructor prologue if
839 // applicable.
John McCallf8ff7b92010-02-23 00:48:20 +0000840 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallf8ff7b92010-02-23 00:48:20 +0000841 if (IsTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000842 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000843
Justin Bogner66242d62015-04-23 23:06:47 +0000844 incrementProfileCounter(Body);
Justin Bogner81c22c22014-01-23 02:54:27 +0000845
Richard Smithcc1b96d2013-06-12 22:31:48 +0000846 RunCleanupsScope RunCleanups(*this);
John McCallb81884d2010-02-19 09:25:03 +0000847
John McCall88313032012-03-30 04:25:03 +0000848 // TODO: in restricted cases, we can emit the vbase initializers of
849 // a complete ctor and then delegate to the base ctor.
850
John McCallf8ff7b92010-02-23 00:48:20 +0000851 // Emit the constructor prologue, i.e. the base and member
852 // initializers.
Douglas Gregor94f9a482010-05-05 05:51:00 +0000853 EmitCtorPrologue(Ctor, CtorType, Args);
John McCallb81884d2010-02-19 09:25:03 +0000854
855 // Emit the body of the statement.
John McCallf8ff7b92010-02-23 00:48:20 +0000856 if (IsTryBody)
John McCallb81884d2010-02-19 09:25:03 +0000857 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
858 else if (Body)
859 EmitStmt(Body);
John McCallb81884d2010-02-19 09:25:03 +0000860
861 // Emit any cleanup blocks associated with the member or base
862 // initializers, which includes (along the exceptional path) the
863 // destructors for those members and bases that were fully
864 // constructed.
Richard Smithcc1b96d2013-06-12 22:31:48 +0000865 RunCleanups.ForceCleanup();
John McCallb81884d2010-02-19 09:25:03 +0000866
John McCallf8ff7b92010-02-23 00:48:20 +0000867 if (IsTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000868 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000869}
870
Lang Hamesbf122742013-02-17 07:22:09 +0000871namespace {
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000872 /// RAII object to indicate that codegen is copying the value representation
873 /// instead of the object representation. Useful when copying a struct or
874 /// class which has uninitialized members and we're only performing
875 /// lvalue-to-rvalue conversion on the object but not its members.
876 class CopyingValueRepresentation {
877 public:
878 explicit CopyingValueRepresentation(CodeGenFunction &CGF)
Alexey Samsonov035462c2014-10-30 19:33:44 +0000879 : CGF(CGF), OldSanOpts(CGF.SanOpts) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000880 CGF.SanOpts.set(SanitizerKind::Bool, false);
881 CGF.SanOpts.set(SanitizerKind::Enum, false);
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000882 }
883 ~CopyingValueRepresentation() {
884 CGF.SanOpts = OldSanOpts;
885 }
886 private:
887 CodeGenFunction &CGF;
Alexey Samsonova0416102014-11-11 01:26:14 +0000888 SanitizerSet OldSanOpts;
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000889 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000890} // end anonymous namespace
Fangrui Song6907ce22018-07-30 19:24:48 +0000891
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000892namespace {
Lang Hamesbf122742013-02-17 07:22:09 +0000893 class FieldMemcpyizer {
894 public:
895 FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl,
896 const VarDecl *SrcRec)
Justin Bogner1cd11f12015-05-20 15:53:59 +0000897 : CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec),
Lang Hamesbf122742013-02-17 07:22:09 +0000898 RecLayout(CGF.getContext().getASTRecordLayout(ClassDecl)),
Craig Topper8a13c412014-05-21 05:09:00 +0000899 FirstField(nullptr), LastField(nullptr), FirstFieldOffset(0),
900 LastFieldOffset(0), LastAddedFieldIndex(0) {}
Lang Hamesbf122742013-02-17 07:22:09 +0000901
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000902 bool isMemcpyableField(FieldDecl *F) const {
903 // Never memcpy fields when we are adding poisoned paddings.
Alexey Samsonova0416102014-11-11 01:26:14 +0000904 if (CGF.getContext().getLangOpts().SanitizeAddressFieldPadding)
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000905 return false;
Lang Hamesbf122742013-02-17 07:22:09 +0000906 Qualifiers Qual = F->getType().getQualifiers();
907 if (Qual.hasVolatile() || Qual.hasObjCLifetime())
908 return false;
909 return true;
910 }
911
912 void addMemcpyableField(FieldDecl *F) {
Senran Zhang01d8e092019-11-26 10:15:14 +0800913 if (F->isZeroSize(CGF.getContext()))
914 return;
Craig Topper8a13c412014-05-21 05:09:00 +0000915 if (!FirstField)
Lang Hamesbf122742013-02-17 07:22:09 +0000916 addInitialField(F);
917 else
918 addNextField(F);
919 }
920
David Majnemera586eb22014-10-10 18:57:10 +0000921 CharUnits getMemcpySize(uint64_t FirstByteOffset) const {
Richard Smithe78fac52018-04-05 20:52:58 +0000922 ASTContext &Ctx = CGF.getContext();
Lang Hamesbf122742013-02-17 07:22:09 +0000923 unsigned LastFieldSize =
Richard Smithe78fac52018-04-05 20:52:58 +0000924 LastField->isBitField()
925 ? LastField->getBitWidthValue(Ctx)
926 : Ctx.toBits(
927 Ctx.getTypeInfoDataSizeInChars(LastField->getType()).first);
928 uint64_t MemcpySizeBits = LastFieldOffset + LastFieldSize -
929 FirstByteOffset + Ctx.getCharWidth() - 1;
930 CharUnits MemcpySize = Ctx.toCharUnitsFromBits(MemcpySizeBits);
Lang Hamesbf122742013-02-17 07:22:09 +0000931 return MemcpySize;
932 }
933
934 void emitMemcpy() {
935 // Give the subclass a chance to bail out if it feels the memcpy isn't
936 // worth it (e.g. Hasn't aggregated enough data).
Craig Topper8a13c412014-05-21 05:09:00 +0000937 if (!FirstField) {
Lang Hamesbf122742013-02-17 07:22:09 +0000938 return;
939 }
940
David Majnemera586eb22014-10-10 18:57:10 +0000941 uint64_t FirstByteOffset;
Lang Hamesbf122742013-02-17 07:22:09 +0000942 if (FirstField->isBitField()) {
943 const CGRecordLayout &RL =
944 CGF.getTypes().getCGRecordLayout(FirstField->getParent());
945 const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField);
David Majnemera586eb22014-10-10 18:57:10 +0000946 // FirstFieldOffset is not appropriate for bitfields,
Ulrich Weigand73263d72015-07-13 11:52:14 +0000947 // we need to use the storage offset instead.
Ulrich Weigand03ce2a12015-07-10 17:30:00 +0000948 FirstByteOffset = CGF.getContext().toBits(BFInfo.StorageOffset);
Lang Hames1694e0d2013-02-27 04:14:49 +0000949 } else {
David Majnemera586eb22014-10-10 18:57:10 +0000950 FirstByteOffset = FirstFieldOffset;
Lang Hames1694e0d2013-02-27 04:14:49 +0000951 }
Lang Hamesbf122742013-02-17 07:22:09 +0000952
David Majnemera586eb22014-10-10 18:57:10 +0000953 CharUnits MemcpySize = getMemcpySize(FirstByteOffset);
Lang Hamesbf122742013-02-17 07:22:09 +0000954 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
John McCall7f416cc2015-09-08 08:05:57 +0000955 Address ThisPtr = CGF.LoadCXXThisAddress();
956 LValue DestLV = CGF.MakeAddrLValue(ThisPtr, RecordTy);
Lang Hamesbf122742013-02-17 07:22:09 +0000957 LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField);
958 llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec));
959 LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
960 LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField);
961
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800962 emitMemcpyIR(
963 Dest.isBitField() ? Dest.getBitFieldAddress() : Dest.getAddress(CGF),
964 Src.isBitField() ? Src.getBitFieldAddress() : Src.getAddress(CGF),
965 MemcpySize);
Lang Hamesbf122742013-02-17 07:22:09 +0000966 reset();
967 }
968
969 void reset() {
Craig Topper8a13c412014-05-21 05:09:00 +0000970 FirstField = nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +0000971 }
972
973 protected:
974 CodeGenFunction &CGF;
975 const CXXRecordDecl *ClassDecl;
976
977 private:
John McCall7f416cc2015-09-08 08:05:57 +0000978 void emitMemcpyIR(Address DestPtr, Address SrcPtr, CharUnits Size) {
979 llvm::PointerType *DPT = DestPtr.getType();
Lang Hamesbf122742013-02-17 07:22:09 +0000980 llvm::Type *DBP =
981 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), DPT->getAddressSpace());
982 DestPtr = CGF.Builder.CreateBitCast(DestPtr, DBP);
983
John McCall7f416cc2015-09-08 08:05:57 +0000984 llvm::PointerType *SPT = SrcPtr.getType();
Lang Hamesbf122742013-02-17 07:22:09 +0000985 llvm::Type *SBP =
986 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), SPT->getAddressSpace());
987 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, SBP);
988
John McCall7f416cc2015-09-08 08:05:57 +0000989 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity());
Lang Hamesbf122742013-02-17 07:22:09 +0000990 }
991
992 void addInitialField(FieldDecl *F) {
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000993 FirstField = F;
994 LastField = F;
995 FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex());
996 LastFieldOffset = FirstFieldOffset;
997 LastAddedFieldIndex = F->getFieldIndex();
998 }
Lang Hamesbf122742013-02-17 07:22:09 +0000999
1000 void addNextField(FieldDecl *F) {
John McCall6054d5a2013-05-07 05:20:46 +00001001 // For the most part, the following invariant will hold:
1002 // F->getFieldIndex() == LastAddedFieldIndex + 1
1003 // The one exception is that Sema won't add a copy-initializer for an
1004 // unnamed bitfield, which will show up here as a gap in the sequence.
1005 assert(F->getFieldIndex() >= LastAddedFieldIndex + 1 &&
1006 "Cannot aggregate fields out of order.");
Lang Hamesbf122742013-02-17 07:22:09 +00001007 LastAddedFieldIndex = F->getFieldIndex();
1008
1009 // The 'first' and 'last' fields are chosen by offset, rather than field
1010 // index. This allows the code to support bitfields, as well as regular
1011 // fields.
1012 uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex());
1013 if (FOffset < FirstFieldOffset) {
1014 FirstField = F;
1015 FirstFieldOffset = FOffset;
John McCall7ae29f52019-04-10 18:07:18 +00001016 } else if (FOffset >= LastFieldOffset) {
Lang Hamesbf122742013-02-17 07:22:09 +00001017 LastField = F;
1018 LastFieldOffset = FOffset;
1019 }
1020 }
1021
1022 const VarDecl *SrcRec;
1023 const ASTRecordLayout &RecLayout;
1024 FieldDecl *FirstField;
1025 FieldDecl *LastField;
1026 uint64_t FirstFieldOffset, LastFieldOffset;
1027 unsigned LastAddedFieldIndex;
1028 };
1029
1030 class ConstructorMemcpyizer : public FieldMemcpyizer {
1031 private:
Lang Hamesbf122742013-02-17 07:22:09 +00001032 /// Get source argument for copy constructor. Returns null if not a copy
David Majnemer196ac332014-09-11 23:05:02 +00001033 /// constructor.
1034 static const VarDecl *getTrivialCopySource(CodeGenFunction &CGF,
1035 const CXXConstructorDecl *CD,
Lang Hamesbf122742013-02-17 07:22:09 +00001036 FunctionArgList &Args) {
Jordan Rose54533f72013-08-07 16:16:48 +00001037 if (CD->isCopyOrMoveConstructor() && CD->isDefaulted())
David Majnemer196ac332014-09-11 23:05:02 +00001038 return Args[CGF.CGM.getCXXABI().getSrcArgforCopyCtor(CD, Args)];
Craig Topper8a13c412014-05-21 05:09:00 +00001039 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001040 }
1041
1042 // Returns true if a CXXCtorInitializer represents a member initialization
1043 // that can be rolled into a memcpy.
1044 bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const {
1045 if (!MemcpyableCtor)
1046 return false;
1047 FieldDecl *Field = MemberInit->getMember();
Craig Topper8a13c412014-05-21 05:09:00 +00001048 assert(Field && "No field for member init.");
Lang Hamesbf122742013-02-17 07:22:09 +00001049 QualType FieldType = Field->getType();
1050 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
1051
Richard Smith419bd092015-04-29 19:26:57 +00001052 // Bail out on non-memcpyable, not-trivially-copyable members.
1053 if (!(CE && isMemcpyEquivalentSpecialMember(CE->getConstructor())) &&
Lang Hamesbf122742013-02-17 07:22:09 +00001054 !(FieldType.isTriviallyCopyableType(CGF.getContext()) ||
1055 FieldType->isReferenceType()))
1056 return false;
1057
1058 // Bail out on volatile fields.
1059 if (!isMemcpyableField(Field))
1060 return false;
1061
1062 // Otherwise we're good.
1063 return true;
1064 }
1065
1066 public:
1067 ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD,
1068 FunctionArgList &Args)
David Majnemer196ac332014-09-11 23:05:02 +00001069 : FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CGF, CD, Args)),
Lang Hamesbf122742013-02-17 07:22:09 +00001070 ConstructorDecl(CD),
Jordan Rose54533f72013-08-07 16:16:48 +00001071 MemcpyableCtor(CD->isDefaulted() &&
Lang Hamesbf122742013-02-17 07:22:09 +00001072 CD->isCopyOrMoveConstructor() &&
1073 CGF.getLangOpts().getGC() == LangOptions::NonGC),
1074 Args(Args) { }
1075
1076 void addMemberInitializer(CXXCtorInitializer *MemberInit) {
1077 if (isMemberInitMemcpyable(MemberInit)) {
1078 AggregatedInits.push_back(MemberInit);
1079 addMemcpyableField(MemberInit->getMember());
1080 } else {
1081 emitAggregatedInits();
1082 EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit,
1083 ConstructorDecl, Args);
1084 }
1085 }
1086
1087 void emitAggregatedInits() {
1088 if (AggregatedInits.size() <= 1) {
1089 // This memcpy is too small to be worthwhile. Fall back on default
1090 // codegen.
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001091 if (!AggregatedInits.empty()) {
1092 CopyingValueRepresentation CVR(CGF);
Lang Hamesbf122742013-02-17 07:22:09 +00001093 EmitMemberInitializer(CGF, ConstructorDecl->getParent(),
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001094 AggregatedInits[0], ConstructorDecl, Args);
Alexey Bataev152c71f2015-07-14 07:55:48 +00001095 AggregatedInits.clear();
Lang Hamesbf122742013-02-17 07:22:09 +00001096 }
1097 reset();
1098 return;
1099 }
1100
1101 pushEHDestructors();
1102 emitMemcpy();
1103 AggregatedInits.clear();
1104 }
1105
1106 void pushEHDestructors() {
John McCall7f416cc2015-09-08 08:05:57 +00001107 Address ThisPtr = CGF.LoadCXXThisAddress();
Lang Hamesbf122742013-02-17 07:22:09 +00001108 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
John McCall7f416cc2015-09-08 08:05:57 +00001109 LValue LHS = CGF.MakeAddrLValue(ThisPtr, RecordTy);
Lang Hamesbf122742013-02-17 07:22:09 +00001110
1111 for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
Alexey Bataev152c71f2015-07-14 07:55:48 +00001112 CXXCtorInitializer *MemberInit = AggregatedInits[i];
1113 QualType FieldType = MemberInit->getAnyMember()->getType();
Lang Hamesbf122742013-02-17 07:22:09 +00001114 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
Alexey Bataev152c71f2015-07-14 07:55:48 +00001115 if (!CGF.needsEHCleanup(dtorKind))
1116 continue;
1117 LValue FieldLHS = LHS;
1118 EmitLValueForAnyFieldInitialization(CGF, MemberInit, FieldLHS);
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001119 CGF.pushEHDestroy(dtorKind, FieldLHS.getAddress(CGF), FieldType);
Lang Hamesbf122742013-02-17 07:22:09 +00001120 }
1121 }
1122
1123 void finish() {
1124 emitAggregatedInits();
1125 }
1126
1127 private:
1128 const CXXConstructorDecl *ConstructorDecl;
1129 bool MemcpyableCtor;
1130 FunctionArgList &Args;
1131 SmallVector<CXXCtorInitializer*, 16> AggregatedInits;
1132 };
1133
1134 class AssignmentMemcpyizer : public FieldMemcpyizer {
1135 private:
Lang Hamesbf122742013-02-17 07:22:09 +00001136 // Returns the memcpyable field copied by the given statement, if one
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001137 // exists. Otherwise returns null.
1138 FieldDecl *getMemcpyableField(Stmt *S) {
Lang Hamesbf122742013-02-17 07:22:09 +00001139 if (!AssignmentsMemcpyable)
Craig Topper8a13c412014-05-21 05:09:00 +00001140 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001141 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
1142 // Recognise trivial assignments.
1143 if (BO->getOpcode() != BO_Assign)
Craig Topper8a13c412014-05-21 05:09:00 +00001144 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001145 MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS());
1146 if (!ME)
Craig Topper8a13c412014-05-21 05:09:00 +00001147 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001148 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1149 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001150 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001151 Stmt *RHS = BO->getRHS();
1152 if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS))
1153 RHS = EC->getSubExpr();
1154 if (!RHS)
Craig Topper8a13c412014-05-21 05:09:00 +00001155 return nullptr;
Warren Ristow8d17b402017-02-02 17:53:34 +00001156 if (MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS)) {
1157 if (ME2->getMemberDecl() == Field)
1158 return Field;
1159 }
1160 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001161 } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) {
1162 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl());
Richard Smith419bd092015-04-29 19:26:57 +00001163 if (!(MD && isMemcpyEquivalentSpecialMember(MD)))
Craig Topper8a13c412014-05-21 05:09:00 +00001164 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001165 MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument());
1166 if (!IOA)
Craig Topper8a13c412014-05-21 05:09:00 +00001167 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001168 FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl());
1169 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001170 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001171 MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0));
1172 if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl()))
Craig Topper8a13c412014-05-21 05:09:00 +00001173 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001174 return Field;
1175 } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1176 FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1177 if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy)
Craig Topper8a13c412014-05-21 05:09:00 +00001178 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001179 Expr *DstPtr = CE->getArg(0);
1180 if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr))
1181 DstPtr = DC->getSubExpr();
1182 UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr);
1183 if (!DUO || DUO->getOpcode() != UO_AddrOf)
Craig Topper8a13c412014-05-21 05:09:00 +00001184 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001185 MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr());
1186 if (!ME)
Craig Topper8a13c412014-05-21 05:09:00 +00001187 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001188 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1189 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001190 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001191 Expr *SrcPtr = CE->getArg(1);
1192 if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr))
1193 SrcPtr = SC->getSubExpr();
1194 UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr);
1195 if (!SUO || SUO->getOpcode() != UO_AddrOf)
Craig Topper8a13c412014-05-21 05:09:00 +00001196 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001197 MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr());
1198 if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl()))
Craig Topper8a13c412014-05-21 05:09:00 +00001199 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001200 return Field;
1201 }
1202
Craig Topper8a13c412014-05-21 05:09:00 +00001203 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001204 }
1205
1206 bool AssignmentsMemcpyable;
1207 SmallVector<Stmt*, 16> AggregatedStmts;
1208
1209 public:
Lang Hamesbf122742013-02-17 07:22:09 +00001210 AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD,
1211 FunctionArgList &Args)
1212 : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]),
1213 AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) {
1214 assert(Args.size() == 2);
1215 }
1216
1217 void emitAssignment(Stmt *S) {
1218 FieldDecl *F = getMemcpyableField(S);
1219 if (F) {
1220 addMemcpyableField(F);
1221 AggregatedStmts.push_back(S);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001222 } else {
Lang Hamesbf122742013-02-17 07:22:09 +00001223 emitAggregatedStmts();
1224 CGF.EmitStmt(S);
1225 }
1226 }
1227
1228 void emitAggregatedStmts() {
1229 if (AggregatedStmts.size() <= 1) {
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001230 if (!AggregatedStmts.empty()) {
1231 CopyingValueRepresentation CVR(CGF);
1232 CGF.EmitStmt(AggregatedStmts[0]);
1233 }
Lang Hamesbf122742013-02-17 07:22:09 +00001234 reset();
1235 }
1236
1237 emitMemcpy();
1238 AggregatedStmts.clear();
1239 }
1240
1241 void finish() {
1242 emitAggregatedStmts();
1243 }
1244 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00001245} // end anonymous namespace
Lang Hamesbf122742013-02-17 07:22:09 +00001246
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001247static bool isInitializerOfDynamicClass(const CXXCtorInitializer *BaseInit) {
1248 const Type *BaseType = BaseInit->getBaseClass();
1249 const auto *BaseClassDecl =
Simon Pilgrim1cd399c2019-10-03 11:22:48 +00001250 cast<CXXRecordDecl>(BaseType->castAs<RecordType>()->getDecl());
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001251 return BaseClassDecl->isDynamicClass();
1252}
1253
Anders Carlssonfb404882009-12-24 22:46:43 +00001254/// EmitCtorPrologue - This routine generates necessary code to initialize
1255/// base classes and non-static data members belonging to this constructor.
Anders Carlssonfb404882009-12-24 22:46:43 +00001256void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001257 CXXCtorType CtorType,
1258 FunctionArgList &Args) {
Alexis Hunt61bc1732011-05-01 07:04:31 +00001259 if (CD->isDelegatingConstructor())
1260 return EmitDelegatingCXXConstructorCall(CD, Args);
1261
Anders Carlssonfb404882009-12-24 22:46:43 +00001262 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlsson5dc86332010-02-02 19:58:43 +00001263
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001264 CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
1265 E = CD->init_end();
1266
Reid Kleckner61c9b7c2019-03-18 22:41:50 +00001267 // Virtual base initializers first, if any. They aren't needed if:
1268 // - This is a base ctor variant
1269 // - There are no vbases
1270 // - The class is abstract, so a complete object of it cannot be constructed
1271 //
1272 // The check for an abstract class is necessary because sema may not have
1273 // marked virtual base destructors referenced.
1274 bool ConstructVBases = CtorType != Ctor_Base &&
1275 ClassDecl->getNumVBases() != 0 &&
1276 !ClassDecl->isAbstract();
1277
1278 // In the Microsoft C++ ABI, there are no constructor variants. Instead, the
1279 // constructor of a class with virtual bases takes an additional parameter to
1280 // conditionally construct the virtual bases. Emit that check here.
Craig Topper8a13c412014-05-21 05:09:00 +00001281 llvm::BasicBlock *BaseCtorContinueBB = nullptr;
Reid Kleckner61c9b7c2019-03-18 22:41:50 +00001282 if (ConstructVBases &&
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001283 !CGM.getTarget().getCXXABI().hasConstructorVariants()) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001284 BaseCtorContinueBB =
Reid Kleckner61c9b7c2019-03-18 22:41:50 +00001285 CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this, ClassDecl);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001286 assert(BaseCtorContinueBB);
1287 }
1288
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001289 llvm::Value *const OldThis = CXXThisValue;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001290 for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
Reid Kleckner61c9b7c2019-03-18 22:41:50 +00001291 if (!ConstructVBases)
1292 continue;
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001293 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1294 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1295 isInitializerOfDynamicClass(*B))
Piotr Padlewski5dde8092018-05-03 11:03:01 +00001296 CXXThisValue = Builder.CreateLaunderInvariantGroup(LoadCXXThis());
Reid Kleckner61c9b7c2019-03-18 22:41:50 +00001297 EmitBaseInitializer(*this, ClassDecl, *B);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001298 }
1299
1300 if (BaseCtorContinueBB) {
1301 // Complete object handler should continue to the remaining initializers.
1302 Builder.CreateBr(BaseCtorContinueBB);
1303 EmitBlock(BaseCtorContinueBB);
1304 }
1305
1306 // Then, non-virtual base initializers.
1307 for (; B != E && (*B)->isBaseInitializer(); B++) {
1308 assert(!(*B)->isBaseVirtual());
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001309
1310 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1311 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1312 isInitializerOfDynamicClass(*B))
Piotr Padlewski5dde8092018-05-03 11:03:01 +00001313 CXXThisValue = Builder.CreateLaunderInvariantGroup(LoadCXXThis());
Reid Kleckner61c9b7c2019-03-18 22:41:50 +00001314 EmitBaseInitializer(*this, ClassDecl, *B);
Anders Carlssonfb404882009-12-24 22:46:43 +00001315 }
1316
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001317 CXXThisValue = OldThis;
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001318
Anders Carlssond5895932010-03-28 21:07:49 +00001319 InitializeVTablePointers(ClassDecl);
Anders Carlsson5dc86332010-02-02 19:58:43 +00001320
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001321 // And finally, initialize class members.
John McCall7f416cc2015-09-08 08:05:57 +00001322 FieldConstructionScope FCS(*this, LoadCXXThisAddress());
Lang Hamesbf122742013-02-17 07:22:09 +00001323 ConstructorMemcpyizer CM(*this, CD, Args);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001324 for (; B != E; B++) {
1325 CXXCtorInitializer *Member = (*B);
1326 assert(!Member->isBaseInitializer());
1327 assert(Member->isAnyMemberInitializer() &&
1328 "Delegating initializer on non-delegating constructor");
1329 CM.addMemberInitializer(Member);
1330 }
Lang Hamesbf122742013-02-17 07:22:09 +00001331 CM.finish();
Anders Carlssonfb404882009-12-24 22:46:43 +00001332}
1333
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001334static bool
1335FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
1336
1337static bool
Justin Bogner1cd11f12015-05-20 15:53:59 +00001338HasTrivialDestructorBody(ASTContext &Context,
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001339 const CXXRecordDecl *BaseClassDecl,
1340 const CXXRecordDecl *MostDerivedClassDecl)
1341{
1342 // If the destructor is trivial we don't have to check anything else.
1343 if (BaseClassDecl->hasTrivialDestructor())
1344 return true;
1345
1346 if (!BaseClassDecl->getDestructor()->hasTrivialBody())
1347 return false;
1348
1349 // Check fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001350 for (const auto *Field : BaseClassDecl->fields())
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001351 if (!FieldHasTrivialDestructorBody(Context, Field))
1352 return false;
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001353
1354 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001355 for (const auto &I : BaseClassDecl->bases()) {
1356 if (I.isVirtual())
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001357 continue;
1358
1359 const CXXRecordDecl *NonVirtualBase =
Aaron Ballman574705e2014-03-13 15:41:46 +00001360 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001361 if (!HasTrivialDestructorBody(Context, NonVirtualBase,
1362 MostDerivedClassDecl))
1363 return false;
1364 }
1365
1366 if (BaseClassDecl == MostDerivedClassDecl) {
1367 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00001368 for (const auto &I : BaseClassDecl->vbases()) {
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001369 const CXXRecordDecl *VirtualBase =
Aaron Ballman445a9392014-03-13 16:15:17 +00001370 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001371 if (!HasTrivialDestructorBody(Context, VirtualBase,
1372 MostDerivedClassDecl))
Justin Bogner1cd11f12015-05-20 15:53:59 +00001373 return false;
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001374 }
1375 }
1376
1377 return true;
1378}
1379
1380static bool
1381FieldHasTrivialDestructorBody(ASTContext &Context,
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001382 const FieldDecl *Field)
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001383{
1384 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
1385
1386 const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
1387 if (!RT)
1388 return true;
Justin Bogner1cd11f12015-05-20 15:53:59 +00001389
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001390 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Davide Italiano982bbf42015-06-26 00:18:35 +00001391
1392 // The destructor for an implicit anonymous union member is never invoked.
1393 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
1394 return false;
1395
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001396 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
1397}
1398
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001399/// CanSkipVTablePointerInitialization - Check whether we need to initialize
1400/// any vtable pointers before calling this destructor.
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001401static bool CanSkipVTablePointerInitialization(CodeGenFunction &CGF,
Anders Carlssond6f15182011-05-16 04:08:36 +00001402 const CXXDestructorDecl *Dtor) {
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001403 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1404 if (!ClassDecl->isDynamicClass())
1405 return true;
1406
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001407 if (!Dtor->hasTrivialBody())
1408 return false;
1409
1410 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001411 for (const auto *Field : ClassDecl->fields())
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001412 if (!FieldHasTrivialDestructorBody(CGF.getContext(), Field))
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001413 return false;
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001414
1415 return true;
1416}
1417
John McCallb81884d2010-02-19 09:25:03 +00001418/// EmitDestructorBody - Emits the body of the current destructor.
1419void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
1420 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
1421 CXXDtorType DtorType = CurGD.getDtorType();
1422
Richard Smithdf054d32017-02-25 23:53:05 +00001423 // For an abstract class, non-base destructors are never used (and can't
1424 // be emitted in general, because vbase dtors may not have been validated
1425 // by Sema), but the Itanium ABI doesn't make them optional and Clang may
1426 // in fact emit references to them from other compilations, so emit them
1427 // as functions containing a trap instruction.
1428 if (DtorType != Dtor_Base && Dtor->getParent()->isAbstract()) {
1429 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
1430 TrapCall->setDoesNotReturn();
1431 TrapCall->setDoesNotThrow();
1432 Builder.CreateUnreachable();
1433 Builder.ClearInsertionPoint();
1434 return;
1435 }
1436
Justin Bognerfb298222015-05-20 16:16:23 +00001437 Stmt *Body = Dtor->getBody();
1438 if (Body)
1439 incrementProfileCounter(Body);
1440
John McCallf99a6312010-07-21 05:30:47 +00001441 // The call to operator delete in a deleting destructor happens
1442 // outside of the function-try-block, which means it's always
1443 // possible to delegate the destructor body to the complete
1444 // destructor. Do so.
1445 if (DtorType == Dtor_Deleting) {
Richard Smith5b349582017-10-13 01:55:36 +00001446 RunCleanupsScope DtorEpilogue(*this);
John McCallf99a6312010-07-21 05:30:47 +00001447 EnterDtorCleanups(Dtor, Dtor_Deleting);
Marco Antognini88559632019-07-22 09:39:13 +00001448 if (HaveInsertPoint()) {
1449 QualType ThisTy = Dtor->getThisObjectType();
Richard Smith5b349582017-10-13 01:55:36 +00001450 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
Marco Antognini88559632019-07-22 09:39:13 +00001451 /*Delegating=*/false, LoadCXXThisAddress(), ThisTy);
1452 }
John McCallf99a6312010-07-21 05:30:47 +00001453 return;
1454 }
1455
John McCallb81884d2010-02-19 09:25:03 +00001456 // If the body is a function-try-block, enter the try before
John McCallf99a6312010-07-21 05:30:47 +00001457 // anything else.
1458 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallb81884d2010-02-19 09:25:03 +00001459 if (isTryBody)
John McCallb609d3f2010-07-07 06:56:46 +00001460 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00001461 EmitAsanPrologueOrEpilogue(false);
John McCallb81884d2010-02-19 09:25:03 +00001462
John McCallf99a6312010-07-21 05:30:47 +00001463 // Enter the epilogue cleanups.
1464 RunCleanupsScope DtorEpilogue(*this);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001465
John McCallb81884d2010-02-19 09:25:03 +00001466 // If this is the complete variant, just invoke the base variant;
1467 // the epilogue will destruct the virtual bases. But we can't do
1468 // this optimization if the body is a function-try-block, because
Justin Bogner1cd11f12015-05-20 15:53:59 +00001469 // we'd introduce *two* handler blocks. In the Microsoft ABI, we
Reid Klecknere7de47e2013-07-22 13:51:44 +00001470 // always delegate because we might not have a definition in this TU.
John McCallf99a6312010-07-21 05:30:47 +00001471 switch (DtorType) {
Saleem Abdulrasool8de4e872017-02-02 05:45:43 +00001472 case Dtor_Comdat: llvm_unreachable("not expecting a COMDAT");
John McCallf99a6312010-07-21 05:30:47 +00001473 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
1474
1475 case Dtor_Complete:
Reid Klecknere7de47e2013-07-22 13:51:44 +00001476 assert((Body || getTarget().getCXXABI().isMicrosoft()) &&
1477 "can't emit a dtor without a body for non-Microsoft ABIs");
1478
John McCallf99a6312010-07-21 05:30:47 +00001479 // Enter the cleanup scopes for virtual bases.
1480 EnterDtorCleanups(Dtor, Dtor_Complete);
1481
Reid Klecknere7de47e2013-07-22 13:51:44 +00001482 if (!isTryBody) {
Marco Antognini88559632019-07-22 09:39:13 +00001483 QualType ThisTy = Dtor->getThisObjectType();
John McCallf99a6312010-07-21 05:30:47 +00001484 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
Marco Antognini88559632019-07-22 09:39:13 +00001485 /*Delegating=*/false, LoadCXXThisAddress(), ThisTy);
John McCallf99a6312010-07-21 05:30:47 +00001486 break;
1487 }
Saleem Abdulrasool8de4e872017-02-02 05:45:43 +00001488
John McCallf99a6312010-07-21 05:30:47 +00001489 // Fallthrough: act like we're in the base variant.
Saleem Abdulrasool8de4e872017-02-02 05:45:43 +00001490 LLVM_FALLTHROUGH;
Justin Bogner1cd11f12015-05-20 15:53:59 +00001491
John McCallf99a6312010-07-21 05:30:47 +00001492 case Dtor_Base:
Reid Klecknere7de47e2013-07-22 13:51:44 +00001493 assert(Body);
1494
John McCallf99a6312010-07-21 05:30:47 +00001495 // Enter the cleanup scopes for fields and non-virtual bases.
1496 EnterDtorCleanups(Dtor, Dtor_Base);
1497
1498 // Initialize the vtable pointers before entering the body.
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001499 if (!CanSkipVTablePointerInitialization(*this, Dtor)) {
Piotr Padlewski5dde8092018-05-03 11:03:01 +00001500 // Insert the llvm.launder.invariant.group intrinsic before initializing
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001501 // the vptrs to cancel any previous assumptions we might have made.
1502 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1503 CGM.getCodeGenOpts().OptimizationLevel > 0)
Piotr Padlewski5dde8092018-05-03 11:03:01 +00001504 CXXThisValue = Builder.CreateLaunderInvariantGroup(LoadCXXThis());
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001505 InitializeVTablePointers(Dtor->getParent());
1506 }
John McCallf99a6312010-07-21 05:30:47 +00001507
1508 if (isTryBody)
1509 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
1510 else if (Body)
1511 EmitStmt(Body);
1512 else {
1513 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
1514 // nothing to do besides what's in the epilogue
1515 }
Fariborz Jahanian0c12ed12011-02-02 23:12:46 +00001516 // -fapple-kext must inline any call to this dtor into
1517 // the caller's body.
Richard Smith9c6890a2012-11-01 22:30:59 +00001518 if (getLangOpts().AppleKext)
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00001519 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
Naomi Musgravee50cb9b2015-08-13 18:35:11 +00001520
John McCallf99a6312010-07-21 05:30:47 +00001521 break;
John McCallb81884d2010-02-19 09:25:03 +00001522 }
1523
John McCallf99a6312010-07-21 05:30:47 +00001524 // Jump out through the epilogue cleanups.
1525 DtorEpilogue.ForceCleanup();
John McCallb81884d2010-02-19 09:25:03 +00001526
1527 // Exit the try if applicable.
1528 if (isTryBody)
John McCallb609d3f2010-07-07 06:56:46 +00001529 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +00001530}
1531
Lang Hamesbf122742013-02-17 07:22:09 +00001532void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) {
1533 const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
1534 const Stmt *RootS = AssignOp->getBody();
1535 assert(isa<CompoundStmt>(RootS) &&
1536 "Body of an implicit assignment operator should be compound stmt.");
1537 const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
1538
1539 LexicalScope Scope(*this, RootCS->getSourceRange());
1540
Xinliang David Lia951e8e2016-02-09 20:02:59 +00001541 incrementProfileCounter(RootCS);
Lang Hamesbf122742013-02-17 07:22:09 +00001542 AssignmentMemcpyizer AM(*this, AssignOp, Args);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001543 for (auto *I : RootCS->body())
Justin Bogner1cd11f12015-05-20 15:53:59 +00001544 AM.emitAssignment(I);
Lang Hamesbf122742013-02-17 07:22:09 +00001545 AM.finish();
1546}
1547
John McCallf99a6312010-07-21 05:30:47 +00001548namespace {
Richard Smith5b349582017-10-13 01:55:36 +00001549 llvm::Value *LoadThisForDtorDelete(CodeGenFunction &CGF,
1550 const CXXDestructorDecl *DD) {
1551 if (Expr *ThisArg = DD->getOperatorDeleteThisArg())
Haojian Wu5b5c81f2017-10-13 15:37:53 +00001552 return CGF.EmitScalarExpr(ThisArg);
Richard Smith5b349582017-10-13 01:55:36 +00001553 return CGF.LoadCXXThis();
1554 }
1555
John McCallf99a6312010-07-21 05:30:47 +00001556 /// Call the operator delete associated with the current destructor.
David Blaikie7e70d682015-08-18 22:40:54 +00001557 struct CallDtorDelete final : EHScopeStack::Cleanup {
John McCallf99a6312010-07-21 05:30:47 +00001558 CallDtorDelete() {}
1559
Craig Topper4f12f102014-03-12 06:41:41 +00001560 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallf99a6312010-07-21 05:30:47 +00001561 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1562 const CXXRecordDecl *ClassDecl = Dtor->getParent();
Richard Smith5b349582017-10-13 01:55:36 +00001563 CGF.EmitDeleteCall(Dtor->getOperatorDelete(),
1564 LoadThisForDtorDelete(CGF, Dtor),
John McCallf99a6312010-07-21 05:30:47 +00001565 CGF.getContext().getTagDeclType(ClassDecl));
1566 }
1567 };
1568
Richard Smith5b349582017-10-13 01:55:36 +00001569 void EmitConditionalDtorDeleteCall(CodeGenFunction &CGF,
1570 llvm::Value *ShouldDeleteCondition,
1571 bool ReturnAfterDelete) {
1572 llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
1573 llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
1574 llvm::Value *ShouldCallDelete
1575 = CGF.Builder.CreateIsNull(ShouldDeleteCondition);
1576 CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
1577
1578 CGF.EmitBlock(callDeleteBB);
1579 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1580 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1581 CGF.EmitDeleteCall(Dtor->getOperatorDelete(),
1582 LoadThisForDtorDelete(CGF, Dtor),
1583 CGF.getContext().getTagDeclType(ClassDecl));
1584 assert(Dtor->getOperatorDelete()->isDestroyingOperatorDelete() ==
1585 ReturnAfterDelete &&
1586 "unexpected value for ReturnAfterDelete");
1587 if (ReturnAfterDelete)
1588 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
1589 else
1590 CGF.Builder.CreateBr(continueBB);
1591
1592 CGF.EmitBlock(continueBB);
1593 }
1594
David Blaikie7e70d682015-08-18 22:40:54 +00001595 struct CallDtorDeleteConditional final : EHScopeStack::Cleanup {
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001596 llvm::Value *ShouldDeleteCondition;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001597
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001598 public:
1599 CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001600 : ShouldDeleteCondition(ShouldDeleteCondition) {
Craig Topper8a13c412014-05-21 05:09:00 +00001601 assert(ShouldDeleteCondition != nullptr);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001602 }
1603
Craig Topper4f12f102014-03-12 06:41:41 +00001604 void Emit(CodeGenFunction &CGF, Flags flags) override {
Richard Smith5b349582017-10-13 01:55:36 +00001605 EmitConditionalDtorDeleteCall(CGF, ShouldDeleteCondition,
1606 /*ReturnAfterDelete*/false);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001607 }
1608 };
1609
David Blaikie7e70d682015-08-18 22:40:54 +00001610 class DestroyField final : public EHScopeStack::Cleanup {
John McCall4bd0fb12011-07-12 16:41:08 +00001611 const FieldDecl *field;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001612 CodeGenFunction::Destroyer *destroyer;
John McCall4bd0fb12011-07-12 16:41:08 +00001613 bool useEHCleanupForArray;
John McCallf99a6312010-07-21 05:30:47 +00001614
John McCall4bd0fb12011-07-12 16:41:08 +00001615 public:
1616 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
1617 bool useEHCleanupForArray)
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001618 : field(field), destroyer(destroyer),
1619 useEHCleanupForArray(useEHCleanupForArray) {}
John McCallf99a6312010-07-21 05:30:47 +00001620
Craig Topper4f12f102014-03-12 06:41:41 +00001621 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall4bd0fb12011-07-12 16:41:08 +00001622 // Find the address of the field.
John McCall7f416cc2015-09-08 08:05:57 +00001623 Address thisValue = CGF.LoadCXXThisAddress();
Eli Friedman7f1ff602012-04-16 03:54:45 +00001624 QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
1625 LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
1626 LValue LV = CGF.EmitLValueForField(ThisLV, field);
John McCall4bd0fb12011-07-12 16:41:08 +00001627 assert(LV.isSimple());
Justin Bogner1cd11f12015-05-20 15:53:59 +00001628
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001629 CGF.emitDestroy(LV.getAddress(CGF), field->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +00001630 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCallf99a6312010-07-21 05:30:47 +00001631 }
1632 };
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001633
Naomi Musgrave703835c2015-09-16 00:38:22 +00001634 static void EmitSanitizerDtorCallback(CodeGenFunction &CGF, llvm::Value *Ptr,
1635 CharUnits::QuantityType PoisonSize) {
Matt Morehouse4881a232017-09-20 22:53:08 +00001636 CodeGenFunction::SanitizerScope SanScope(&CGF);
Naomi Musgrave703835c2015-09-16 00:38:22 +00001637 // Pass in void pointer and size of region as arguments to runtime
1638 // function
1639 llvm::Value *Args[] = {CGF.Builder.CreateBitCast(Ptr, CGF.VoidPtrTy),
1640 llvm::ConstantInt::get(CGF.SizeTy, PoisonSize)};
1641
1642 llvm::Type *ArgTypes[] = {CGF.VoidPtrTy, CGF.SizeTy};
1643
1644 llvm::FunctionType *FnType =
1645 llvm::FunctionType::get(CGF.VoidTy, ArgTypes, false);
James Y Knight9871db02019-02-05 16:42:33 +00001646 llvm::FunctionCallee Fn =
Naomi Musgrave703835c2015-09-16 00:38:22 +00001647 CGF.CGM.CreateRuntimeFunction(FnType, "__sanitizer_dtor_callback");
1648 CGF.EmitNounwindRuntimeCall(Fn, Args);
1649 }
1650
1651 class SanitizeDtorMembers final : public EHScopeStack::Cleanup {
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001652 const CXXDestructorDecl *Dtor;
1653
1654 public:
Naomi Musgrave703835c2015-09-16 00:38:22 +00001655 SanitizeDtorMembers(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001656
1657 // Generate function call for handling object poisoning.
1658 // Disables tail call elimination, to prevent the current stack frame
1659 // from disappearing from the stack trace.
1660 void Emit(CodeGenFunction &CGF, Flags flags) override {
1661 const ASTRecordLayout &Layout =
1662 CGF.getContext().getASTRecordLayout(Dtor->getParent());
1663
1664 // Nothing to poison.
1665 if (Layout.getFieldCount() == 0)
1666 return;
1667
1668 // Prevent the current stack frame from disappearing from the stack trace.
1669 CGF.CurFn->addFnAttr("disable-tail-calls", "true");
1670
1671 // Construct pointer to region to begin poisoning, and calculate poison
1672 // size, so that only members declared in this class are poisoned.
1673 ASTContext &Context = CGF.getContext();
1674 unsigned fieldIndex = 0;
1675 int startIndex = -1;
1676 // RecordDecl::field_iterator Field;
1677 for (const FieldDecl *Field : Dtor->getParent()->fields()) {
1678 // Poison field if it is trivial
1679 if (FieldHasTrivialDestructorBody(Context, Field)) {
1680 // Start sanitizing at this field
1681 if (startIndex < 0)
1682 startIndex = fieldIndex;
1683
1684 // Currently on the last field, and it must be poisoned with the
1685 // current block.
1686 if (fieldIndex == Layout.getFieldCount() - 1) {
Naomi Musgrave703835c2015-09-16 00:38:22 +00001687 PoisonMembers(CGF, startIndex, Layout.getFieldCount());
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001688 }
1689 } else if (startIndex >= 0) {
1690 // No longer within a block of memory to poison, so poison the block
Naomi Musgrave703835c2015-09-16 00:38:22 +00001691 PoisonMembers(CGF, startIndex, fieldIndex);
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001692 // Re-set the start index
1693 startIndex = -1;
1694 }
1695 fieldIndex += 1;
1696 }
1697 }
1698
1699 private:
NAKAMURA Takumif6cef72f2015-09-04 05:19:31 +00001700 /// \param layoutStartOffset index of the ASTRecordLayout field to
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001701 /// start poisoning (inclusive)
NAKAMURA Takumif6cef72f2015-09-04 05:19:31 +00001702 /// \param layoutEndOffset index of the ASTRecordLayout field to
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001703 /// end poisoning (exclusive)
Naomi Musgrave703835c2015-09-16 00:38:22 +00001704 void PoisonMembers(CodeGenFunction &CGF, unsigned layoutStartOffset,
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001705 unsigned layoutEndOffset) {
1706 ASTContext &Context = CGF.getContext();
1707 const ASTRecordLayout &Layout =
1708 Context.getASTRecordLayout(Dtor->getParent());
1709
1710 llvm::ConstantInt *OffsetSizePtr = llvm::ConstantInt::get(
1711 CGF.SizeTy,
1712 Context.toCharUnitsFromBits(Layout.getFieldOffset(layoutStartOffset))
1713 .getQuantity());
1714
1715 llvm::Value *OffsetPtr = CGF.Builder.CreateGEP(
1716 CGF.Builder.CreateBitCast(CGF.LoadCXXThis(), CGF.Int8PtrTy),
1717 OffsetSizePtr);
1718
1719 CharUnits::QuantityType PoisonSize;
1720 if (layoutEndOffset >= Layout.getFieldCount()) {
1721 PoisonSize = Layout.getNonVirtualSize().getQuantity() -
1722 Context.toCharUnitsFromBits(
1723 Layout.getFieldOffset(layoutStartOffset))
1724 .getQuantity();
1725 } else {
1726 PoisonSize = Context.toCharUnitsFromBits(
1727 Layout.getFieldOffset(layoutEndOffset) -
1728 Layout.getFieldOffset(layoutStartOffset))
1729 .getQuantity();
1730 }
1731
1732 if (PoisonSize == 0)
1733 return;
1734
Naomi Musgrave703835c2015-09-16 00:38:22 +00001735 EmitSanitizerDtorCallback(CGF, OffsetPtr, PoisonSize);
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001736 }
1737 };
Naomi Musgrave703835c2015-09-16 00:38:22 +00001738
1739 class SanitizeDtorVTable final : public EHScopeStack::Cleanup {
1740 const CXXDestructorDecl *Dtor;
1741
1742 public:
1743 SanitizeDtorVTable(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
1744
1745 // Generate function call for handling vtable pointer poisoning.
1746 void Emit(CodeGenFunction &CGF, Flags flags) override {
1747 assert(Dtor->getParent()->isDynamicClass());
NAKAMURA Takumiee82b492015-09-16 06:26:56 +00001748 (void)Dtor;
Naomi Musgrave703835c2015-09-16 00:38:22 +00001749 ASTContext &Context = CGF.getContext();
1750 // Poison vtable and vtable ptr if they exist for this class.
1751 llvm::Value *VTablePtr = CGF.LoadCXXThis();
1752
1753 CharUnits::QuantityType PoisonSize =
1754 Context.toCharUnitsFromBits(CGF.PointerWidthInBits).getQuantity();
1755 // Pass in void pointer and size of region as arguments to runtime
1756 // function
1757 EmitSanitizerDtorCallback(CGF, VTablePtr, PoisonSize);
1758 }
1759 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00001760} // end anonymous namespace
John McCallf99a6312010-07-21 05:30:47 +00001761
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001762/// Emit all code that comes at the end of class's
Anders Carlssonfb404882009-12-24 22:46:43 +00001763/// destructor. This is to call destructors on members and base classes
1764/// in reverse order of their construction.
Richard Smith5b349582017-10-13 01:55:36 +00001765///
1766/// For a deleting destructor, this also handles the case where a destroying
1767/// operator delete completely overrides the definition.
John McCallf99a6312010-07-21 05:30:47 +00001768void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
1769 CXXDtorType DtorType) {
Hans Wennborg853ae942014-05-30 16:59:42 +00001770 assert((!DD->isTrivial() || DD->hasAttr<DLLExportAttr>()) &&
1771 "Should not emit dtor epilogue for non-exported trivial dtor!");
Anders Carlssonfb404882009-12-24 22:46:43 +00001772
John McCallf99a6312010-07-21 05:30:47 +00001773 // The deleting-destructor phase just needs to call the appropriate
1774 // operator delete that Sema picked up.
John McCall5c60a6f2010-02-18 19:59:28 +00001775 if (DtorType == Dtor_Deleting) {
Justin Bogner1cd11f12015-05-20 15:53:59 +00001776 assert(DD->getOperatorDelete() &&
Hans Wennborgdeff7032013-12-18 01:39:59 +00001777 "operator delete missing - EnterDtorCleanups");
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001778 if (CXXStructorImplicitParamValue) {
1779 // If there is an implicit param to the deleting dtor, it's a boolean
Richard Smith5b349582017-10-13 01:55:36 +00001780 // telling whether this is a deleting destructor.
1781 if (DD->getOperatorDelete()->isDestroyingOperatorDelete())
1782 EmitConditionalDtorDeleteCall(*this, CXXStructorImplicitParamValue,
1783 /*ReturnAfterDelete*/true);
1784 else
1785 EHStack.pushCleanup<CallDtorDeleteConditional>(
1786 NormalAndEHCleanup, CXXStructorImplicitParamValue);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001787 } else {
Richard Smith5b349582017-10-13 01:55:36 +00001788 if (DD->getOperatorDelete()->isDestroyingOperatorDelete()) {
1789 const CXXRecordDecl *ClassDecl = DD->getParent();
1790 EmitDeleteCall(DD->getOperatorDelete(),
1791 LoadThisForDtorDelete(*this, DD),
1792 getContext().getTagDeclType(ClassDecl));
1793 EmitBranchThroughCleanup(ReturnBlock);
1794 } else {
1795 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
1796 }
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001797 }
John McCall5c60a6f2010-02-18 19:59:28 +00001798 return;
1799 }
1800
John McCallf99a6312010-07-21 05:30:47 +00001801 const CXXRecordDecl *ClassDecl = DD->getParent();
1802
Richard Smith20104042011-09-18 12:11:43 +00001803 // Unions have no bases and do not call field destructors.
1804 if (ClassDecl->isUnion())
1805 return;
1806
John McCallf99a6312010-07-21 05:30:47 +00001807 // The complete-destructor phase just destructs all the virtual bases.
John McCall5c60a6f2010-02-18 19:59:28 +00001808 if (DtorType == Dtor_Complete) {
Naomi Musgrave703835c2015-09-16 00:38:22 +00001809 // Poison the vtable pointer such that access after the base
1810 // and member destructors are invoked is invalid.
1811 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1812 SanOpts.has(SanitizerKind::Memory) && ClassDecl->getNumVBases() &&
1813 ClassDecl->isPolymorphic())
1814 EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
John McCallf99a6312010-07-21 05:30:47 +00001815
1816 // We push them in the forward order so that they'll be popped in
1817 // the reverse order.
Aaron Ballman445a9392014-03-13 16:15:17 +00001818 for (const auto &Base : ClassDecl->vbases()) {
Simon Pilgrim1cd399c2019-10-03 11:22:48 +00001819 auto *BaseClassDecl =
1820 cast<CXXRecordDecl>(Base.getType()->castAs<RecordType>()->getDecl());
Justin Bogner1cd11f12015-05-20 15:53:59 +00001821
John McCall5c60a6f2010-02-18 19:59:28 +00001822 // Ignore trivial destructors.
1823 if (BaseClassDecl->hasTrivialDestructor())
1824 continue;
John McCallf99a6312010-07-21 05:30:47 +00001825
John McCallcda666c2010-07-21 07:22:38 +00001826 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1827 BaseClassDecl,
1828 /*BaseIsVirtual*/ true);
John McCall5c60a6f2010-02-18 19:59:28 +00001829 }
John McCallf99a6312010-07-21 05:30:47 +00001830
John McCall5c60a6f2010-02-18 19:59:28 +00001831 return;
1832 }
1833
1834 assert(DtorType == Dtor_Base);
Naomi Musgrave703835c2015-09-16 00:38:22 +00001835 // Poison the vtable pointer if it has no virtual bases, but inherits
1836 // virtual functions.
1837 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1838 SanOpts.has(SanitizerKind::Memory) && !ClassDecl->getNumVBases() &&
1839 ClassDecl->isPolymorphic())
1840 EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001841
John McCallf99a6312010-07-21 05:30:47 +00001842 // Destroy non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001843 for (const auto &Base : ClassDecl->bases()) {
John McCallf99a6312010-07-21 05:30:47 +00001844 // Ignore virtual bases.
1845 if (Base.isVirtual())
1846 continue;
Justin Bogner1cd11f12015-05-20 15:53:59 +00001847
John McCallf99a6312010-07-21 05:30:47 +00001848 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
Justin Bogner1cd11f12015-05-20 15:53:59 +00001849
John McCallf99a6312010-07-21 05:30:47 +00001850 // Ignore trivial destructors.
1851 if (BaseClassDecl->hasTrivialDestructor())
1852 continue;
John McCall5c60a6f2010-02-18 19:59:28 +00001853
John McCallcda666c2010-07-21 07:22:38 +00001854 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1855 BaseClassDecl,
1856 /*BaseIsVirtual*/ false);
John McCallf99a6312010-07-21 05:30:47 +00001857 }
1858
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001859 // Poison fields such that access after their destructors are
1860 // invoked, and before the base class destructor runs, is invalid.
1861 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1862 SanOpts.has(SanitizerKind::Memory))
Naomi Musgrave703835c2015-09-16 00:38:22 +00001863 EHStack.pushCleanup<SanitizeDtorMembers>(NormalAndEHCleanup, DD);
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001864
John McCallf99a6312010-07-21 05:30:47 +00001865 // Destroy direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001866 for (const auto *Field : ClassDecl->fields()) {
1867 QualType type = Field->getType();
John McCall4bd0fb12011-07-12 16:41:08 +00001868 QualType::DestructionKind dtorKind = type.isDestructedType();
1869 if (!dtorKind) continue;
John McCallf99a6312010-07-21 05:30:47 +00001870
Richard Smith921bd202012-02-26 09:11:52 +00001871 // Anonymous union members do not have their destructors called.
1872 const RecordType *RT = type->getAsUnionType();
1873 if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
1874
John McCall4bd0fb12011-07-12 16:41:08 +00001875 CleanupKind cleanupKind = getCleanupKind(dtorKind);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001876 EHStack.pushCleanup<DestroyField>(cleanupKind, Field,
John McCall4bd0fb12011-07-12 16:41:08 +00001877 getDestroyer(dtorKind),
1878 cleanupKind & EHCleanup);
Anders Carlssonfb404882009-12-24 22:46:43 +00001879 }
Anders Carlssonfb404882009-12-24 22:46:43 +00001880}
1881
John McCallf677a8e2011-07-13 06:10:41 +00001882/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1883/// constructor for each of several members of an array.
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001884///
John McCallf677a8e2011-07-13 06:10:41 +00001885/// \param ctor the constructor to call for each element
John McCallf677a8e2011-07-13 06:10:41 +00001886/// \param arrayType the type of the array to initialize
1887/// \param arrayBegin an arrayType*
1888/// \param zeroInitialize true if each element should be
1889/// zero-initialized before it is constructed
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001890void CodeGenFunction::EmitCXXAggrConstructorCall(
Alexey Bataeve7545b32016-04-29 09:39:50 +00001891 const CXXConstructorDecl *ctor, const ArrayType *arrayType,
Serge Pavlov37605182018-07-28 15:33:03 +00001892 Address arrayBegin, const CXXConstructExpr *E, bool NewPointerIsChecked,
1893 bool zeroInitialize) {
John McCallf677a8e2011-07-13 06:10:41 +00001894 QualType elementType;
1895 llvm::Value *numElements =
1896 emitArrayLength(arrayType, elementType, arrayBegin);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001897
Serge Pavlov37605182018-07-28 15:33:03 +00001898 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin, E,
1899 NewPointerIsChecked, zeroInitialize);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001900}
1901
John McCallf677a8e2011-07-13 06:10:41 +00001902/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1903/// constructor for each of several members of an array.
1904///
1905/// \param ctor the constructor to call for each element
1906/// \param numElements the number of elements in the array;
John McCall6549b312011-07-13 07:37:11 +00001907/// may be zero
NAKAMURA Takumiff7a9252015-09-08 09:42:41 +00001908/// \param arrayBase a T*, where T is the type constructed by ctor
John McCallf677a8e2011-07-13 06:10:41 +00001909/// \param zeroInitialize true if each element should be
1910/// zero-initialized before it is constructed
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001911void CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1912 llvm::Value *numElements,
John McCall7f416cc2015-09-08 08:05:57 +00001913 Address arrayBase,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001914 const CXXConstructExpr *E,
Serge Pavlov37605182018-07-28 15:33:03 +00001915 bool NewPointerIsChecked,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001916 bool zeroInitialize) {
John McCall6549b312011-07-13 07:37:11 +00001917 // It's legal for numElements to be zero. This can happen both
1918 // dynamically, because x can be zero in 'new A[x]', and statically,
1919 // because of GCC extensions that permit zero-length arrays. There
1920 // are probably legitimate places where we could assume that this
1921 // doesn't happen, but it's not clear that it's worth it.
Craig Topper8a13c412014-05-21 05:09:00 +00001922 llvm::BranchInst *zeroCheckBranch = nullptr;
John McCall6549b312011-07-13 07:37:11 +00001923
1924 // Optimize for a constant count.
1925 llvm::ConstantInt *constantCount
1926 = dyn_cast<llvm::ConstantInt>(numElements);
1927 if (constantCount) {
1928 // Just skip out if the constant count is zero.
1929 if (constantCount->isZero()) return;
1930
1931 // Otherwise, emit the check.
1932 } else {
1933 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1934 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1935 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1936 EmitBlock(loopBB);
1937 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00001938
John McCallf677a8e2011-07-13 06:10:41 +00001939 // Find the end of the array.
John McCall7f416cc2015-09-08 08:05:57 +00001940 llvm::Value *arrayBegin = arrayBase.getPointer();
John McCallf677a8e2011-07-13 06:10:41 +00001941 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1942 "arrayctor.end");
Anders Carlsson27da15b2010-01-01 20:29:01 +00001943
John McCallf677a8e2011-07-13 06:10:41 +00001944 // Enter the loop, setting up a phi for the current location to initialize.
1945 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1946 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1947 EmitBlock(loopBB);
1948 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1949 "arrayctor.cur");
1950 cur->addIncoming(arrayBegin, entryBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001951
Anders Carlsson27da15b2010-01-01 20:29:01 +00001952 // Inside the loop body, emit the constructor call on the array element.
John McCallf677a8e2011-07-13 06:10:41 +00001953
John McCall7f416cc2015-09-08 08:05:57 +00001954 // The alignment of the base, adjusted by the size of a single element,
1955 // provides a conservative estimate of the alignment of every element.
1956 // (This assumes we never start tracking offsetted alignments.)
Fangrui Song6907ce22018-07-30 19:24:48 +00001957 //
John McCall7f416cc2015-09-08 08:05:57 +00001958 // Note that these are complete objects and so we don't need to
1959 // use the non-virtual size or alignment.
John McCallf677a8e2011-07-13 06:10:41 +00001960 QualType type = getContext().getTypeDeclType(ctor->getParent());
John McCall7f416cc2015-09-08 08:05:57 +00001961 CharUnits eltAlignment =
1962 arrayBase.getAlignment()
1963 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
1964 Address curAddr = Address(cur, eltAlignment);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001965
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001966 // Zero initialize the storage, if requested.
John McCallf677a8e2011-07-13 06:10:41 +00001967 if (zeroInitialize)
John McCall7f416cc2015-09-08 08:05:57 +00001968 EmitNullInitialization(curAddr, type);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001969
1970 // C++ [class.temporary]p4:
Anders Carlsson27da15b2010-01-01 20:29:01 +00001971 // There are two contexts in which temporaries are destroyed at a different
1972 // point than the end of the full-expression. The first context is when a
Justin Bogner1cd11f12015-05-20 15:53:59 +00001973 // default constructor is called to initialize an element of an array.
1974 // If the constructor has one or more default arguments, the destruction of
1975 // every temporary created in a default argument expression is sequenced
Anders Carlsson27da15b2010-01-01 20:29:01 +00001976 // before the construction of the next array element, if any.
Justin Bogner1cd11f12015-05-20 15:53:59 +00001977
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00001978 {
John McCallbd309292010-07-06 01:34:17 +00001979 RunCleanupsScope Scope(*this);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001980
John McCallf677a8e2011-07-13 06:10:41 +00001981 // Evaluate the constructor and its arguments in a regular
1982 // partial-destroy cleanup.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001983 if (getLangOpts().Exceptions &&
John McCallf677a8e2011-07-13 06:10:41 +00001984 !ctor->getParent()->hasTrivialDestructor()) {
1985 Destroyer *destroyer = destroyCXXObject;
John McCall7f416cc2015-09-08 08:05:57 +00001986 pushRegularPartialArrayCleanup(arrayBegin, cur, type, eltAlignment,
1987 *destroyer);
John McCallf677a8e2011-07-13 06:10:41 +00001988 }
Anastasia Stulova094c7262019-04-04 10:48:36 +00001989 auto currAVS = AggValueSlot::forAddr(
1990 curAddr, type.getQualifiers(), AggValueSlot::IsDestructed,
1991 AggValueSlot::DoesNotNeedGCBarriers, AggValueSlot::IsNotAliased,
1992 AggValueSlot::DoesNotOverlap, AggValueSlot::IsNotZeroed,
1993 NewPointerIsChecked ? AggValueSlot::IsSanitizerChecked
1994 : AggValueSlot::IsNotSanitizerChecked);
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001995 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/false,
Anastasia Stulova094c7262019-04-04 10:48:36 +00001996 /*Delegating=*/false, currAVS, E);
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00001997 }
Anders Carlsson27da15b2010-01-01 20:29:01 +00001998
John McCallf677a8e2011-07-13 06:10:41 +00001999 // Go to the next element.
2000 llvm::Value *next =
2001 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
2002 "arrayctor.next");
2003 cur->addIncoming(next, Builder.GetInsertBlock());
Anders Carlsson27da15b2010-01-01 20:29:01 +00002004
John McCallf677a8e2011-07-13 06:10:41 +00002005 // Check whether that's the end of the loop.
2006 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
2007 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
2008 Builder.CreateCondBr(done, contBB, loopBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002009
John McCall6549b312011-07-13 07:37:11 +00002010 // Patch the earlier check to skip over the loop.
2011 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
2012
John McCallf677a8e2011-07-13 06:10:41 +00002013 EmitBlock(contBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002014}
2015
John McCall82fe67b2011-07-09 01:37:26 +00002016void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002017 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002018 QualType type) {
2019 const RecordType *rtype = type->castAs<RecordType>();
2020 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
2021 const CXXDestructorDecl *dtor = record->getDestructor();
2022 assert(!dtor->isTrivial());
2023 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
Marco Antognini88559632019-07-22 09:39:13 +00002024 /*Delegating=*/false, addr, type);
John McCall82fe67b2011-07-09 01:37:26 +00002025}
2026
Alexey Samsonov70b9c012014-08-21 20:26:47 +00002027void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
2028 CXXCtorType Type,
2029 bool ForVirtualBase,
Anastasia Stulova094c7262019-04-04 10:48:36 +00002030 bool Delegating,
2031 AggValueSlot ThisAVS,
2032 const CXXConstructExpr *E) {
Richard Smith5179eb72016-06-28 19:03:57 +00002033 CallArgList Args;
Anastasia Stulova094c7262019-04-04 10:48:36 +00002034 Address This = ThisAVS.getAddress();
2035 LangAS SlotAS = ThisAVS.getQualifiers().getAddressSpace();
Brian Gesiak5488ab42019-01-11 01:54:53 +00002036 QualType ThisType = D->getThisType();
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00002037 LangAS ThisAS = ThisType.getTypePtr()->getPointeeType().getAddressSpace();
2038 llvm::Value *ThisPtr = This.getPointer();
Anastasia Stulova094c7262019-04-04 10:48:36 +00002039
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00002040 if (SlotAS != ThisAS) {
2041 unsigned TargetThisAS = getContext().getTargetAddressSpace(ThisAS);
2042 llvm::Type *NewType =
2043 ThisPtr->getType()->getPointerElementType()->getPointerTo(TargetThisAS);
2044 ThisPtr = getTargetHooks().performAddrSpaceCast(*this, This.getPointer(),
2045 ThisAS, SlotAS, NewType);
2046 }
Anastasia Stulova094c7262019-04-04 10:48:36 +00002047
Richard Smith5179eb72016-06-28 19:03:57 +00002048 // Push the this ptr.
Brian Gesiak5488ab42019-01-11 01:54:53 +00002049 Args.add(RValue::get(ThisPtr), D->getThisType());
Richard Smith5179eb72016-06-28 19:03:57 +00002050
2051 // If this is a trivial constructor, emit a memcpy now before we lose
2052 // the alignment information on the argument.
2053 // FIXME: It would be better to preserve alignment information into CallArg.
2054 if (isMemcpyEquivalentSpecialMember(D)) {
2055 assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
2056
2057 const Expr *Arg = E->getArg(0);
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00002058 LValue Src = EmitLValue(Arg);
Richard Smith5179eb72016-06-28 19:03:57 +00002059 QualType DestTy = getContext().getTypeDeclType(D->getParent());
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00002060 LValue Dest = MakeAddrLValue(This, DestTy);
Anastasia Stulova094c7262019-04-04 10:48:36 +00002061 EmitAggregateCopyCtor(Dest, Src, ThisAVS.mayOverlap());
Richard Smith5179eb72016-06-28 19:03:57 +00002062 return;
2063 }
2064
2065 // Add the rest of the user-supplied arguments.
2066 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
Hans Wennborg27dcc6c2017-02-01 02:21:07 +00002067 EvaluationOrder Order = E->isListInitialization()
2068 ? EvaluationOrder::ForceLeftToRight
2069 : EvaluationOrder::Default;
2070 EmitCallArgs(Args, FPT, E->arguments(), E->getConstructor(),
2071 /*ParamsToSkip*/ 0, Order);
Richard Smith5179eb72016-06-28 19:03:57 +00002072
Richard Smithe78fac52018-04-05 20:52:58 +00002073 EmitCXXConstructorCall(D, Type, ForVirtualBase, Delegating, This, Args,
Anastasia Stulova094c7262019-04-04 10:48:36 +00002074 ThisAVS.mayOverlap(), E->getExprLoc(),
2075 ThisAVS.isSanitizerChecked());
Richard Smith5179eb72016-06-28 19:03:57 +00002076}
2077
2078static bool canEmitDelegateCallArgs(CodeGenFunction &CGF,
2079 const CXXConstructorDecl *Ctor,
2080 CXXCtorType Type, CallArgList &Args) {
2081 // We can't forward a variadic call.
2082 if (Ctor->isVariadic())
2083 return false;
2084
2085 if (CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2086 // If the parameters are callee-cleanup, it's not safe to forward.
2087 for (auto *P : Ctor->parameters())
Richard Smith2b4fa532019-09-29 05:08:46 +00002088 if (P->needsDestruction(CGF.getContext()))
Richard Smith5179eb72016-06-28 19:03:57 +00002089 return false;
2090
2091 // Likewise if they're inalloca.
2092 const CGFunctionInfo &Info =
George Burgess IVd0a9e802017-02-23 22:07:35 +00002093 CGF.CGM.getTypes().arrangeCXXConstructorCall(Args, Ctor, Type, 0, 0);
Richard Smith5179eb72016-06-28 19:03:57 +00002094 if (Info.usesInAlloca())
2095 return false;
2096 }
2097
2098 // Anything else should be OK.
2099 return true;
2100}
2101
2102void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
2103 CXXCtorType Type,
2104 bool ForVirtualBase,
2105 bool Delegating,
2106 Address This,
Richard Smithe78fac52018-04-05 20:52:58 +00002107 CallArgList &Args,
Igor Kudrineff8f9d2018-06-25 05:48:04 +00002108 AggValueSlot::Overlap_t Overlap,
Serge Pavlov37605182018-07-28 15:33:03 +00002109 SourceLocation Loc,
2110 bool NewPointerIsChecked) {
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002111 const CXXRecordDecl *ClassDecl = D->getParent();
2112
Serge Pavlov37605182018-07-28 15:33:03 +00002113 if (!NewPointerIsChecked)
2114 EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall, Loc, This.getPointer(),
2115 getContext().getRecordType(ClassDecl), CharUnits::Zero());
John McCallca972cd2010-02-06 00:25:16 +00002116
Richard Smith419bd092015-04-29 19:26:57 +00002117 if (D->isTrivial() && D->isDefaultConstructor()) {
Richard Smith5179eb72016-06-28 19:03:57 +00002118 assert(Args.size() == 1 && "trivial default ctor with args");
Richard Smith419bd092015-04-29 19:26:57 +00002119 return;
2120 }
2121
2122 // If this is a trivial constructor, just emit what's needed. If this is a
2123 // union copy constructor, we must emit a memcpy, because the AST does not
2124 // model that copy.
2125 if (isMemcpyEquivalentSpecialMember(D)) {
Richard Smith5179eb72016-06-28 19:03:57 +00002126 assert(Args.size() == 2 && "unexpected argcount for trivial ctor");
John McCallca972cd2010-02-06 00:25:16 +00002127
Richard Smith5179eb72016-06-28 19:03:57 +00002128 QualType SrcTy = D->getParamDecl(0)->getType().getNonReferenceType();
Yaxun Liu5b330e82018-03-15 15:25:19 +00002129 Address Src(Args[1].getRValue(*this).getScalarVal(),
2130 getNaturalTypeAlignment(SrcTy));
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00002131 LValue SrcLVal = MakeAddrLValue(Src, SrcTy);
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002132 QualType DestTy = getContext().getTypeDeclType(ClassDecl);
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00002133 LValue DestLVal = MakeAddrLValue(This, DestTy);
Richard Smithe78fac52018-04-05 20:52:58 +00002134 EmitAggregateCopyCtor(DestLVal, SrcLVal, Overlap);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002135 return;
2136 }
2137
George Burgess IVd0a9e802017-02-23 22:07:35 +00002138 bool PassPrototypeArgs = true;
Richard Smith5179eb72016-06-28 19:03:57 +00002139 // Check whether we can actually emit the constructor before trying to do so.
2140 if (auto Inherited = D->getInheritedConstructor()) {
George Burgess IVd0a9e802017-02-23 22:07:35 +00002141 PassPrototypeArgs = getTypes().inheritingCtorHasParams(Inherited, Type);
2142 if (PassPrototypeArgs && !canEmitDelegateCallArgs(*this, D, Type, Args)) {
Richard Smith5179eb72016-06-28 19:03:57 +00002143 EmitInlinedInheritingCXXConstructorCall(D, Type, ForVirtualBase,
2144 Delegating, Args);
2145 return;
2146 }
2147 }
Reid Kleckner89077a12013-12-17 19:46:40 +00002148
2149 // Insert any ABI-specific implicit constructor arguments.
George Burgess IVf203dbf2017-02-22 20:28:02 +00002150 CGCXXABI::AddedStructorArgs ExtraArgs =
2151 CGM.getCXXABI().addImplicitConstructorArgs(*this, D, Type, ForVirtualBase,
2152 Delegating, Args);
Reid Kleckner89077a12013-12-17 19:46:40 +00002153
2154 // Emit the call.
Peter Collingbourned1c5b282019-03-22 23:05:10 +00002155 llvm::Constant *CalleePtr = CGM.getAddrOfCXXStructor(GlobalDecl(D, Type));
George Burgess IVf203dbf2017-02-22 20:28:02 +00002156 const CGFunctionInfo &Info = CGM.getTypes().arrangeCXXConstructorCall(
George Burgess IVd0a9e802017-02-23 22:07:35 +00002157 Args, D, Type, ExtraArgs.Prefix, ExtraArgs.Suffix, PassPrototypeArgs);
Erich Keanede6480a32018-11-13 15:48:08 +00002158 CGCallee Callee = CGCallee::forDirect(CalleePtr, GlobalDecl(D, Type));
John McCallb92ab1a2016-10-26 23:46:34 +00002159 EmitCall(Info, Callee, ReturnValueSlot(), Args);
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002160
2161 // Generate vtable assumptions if we're constructing a complete object
2162 // with a vtable. We don't do this for base subobjects for two reasons:
2163 // first, it's incorrect for classes with virtual bases, and second, we're
2164 // about to overwrite the vptrs anyway.
2165 // We also have to make sure if we can refer to vtable:
2166 // - Otherwise we can refer to vtable if it's safe to speculatively emit.
2167 // FIXME: If vtable is used by ctor/dtor, or if vtable is external and we are
2168 // sure that definition of vtable is not hidden,
2169 // then we are always safe to refer to it.
Piotr Padlewski69dc9712015-09-28 20:30:22 +00002170 // FIXME: It looks like InstCombine is very inefficient on dealing with
2171 // assumes. Make assumption loads require -fstrict-vtable-pointers temporarily.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002172 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2173 ClassDecl->isDynamicClass() && Type != Ctor_Base &&
Piotr Padlewski69dc9712015-09-28 20:30:22 +00002174 CGM.getCXXABI().canSpeculativelyEmitVTable(ClassDecl) &&
2175 CGM.getCodeGenOpts().StrictVTablePointers)
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002176 EmitVTableAssumptionLoads(ClassDecl, This);
2177}
2178
Richard Smith5179eb72016-06-28 19:03:57 +00002179void CodeGenFunction::EmitInheritedCXXConstructorCall(
2180 const CXXConstructorDecl *D, bool ForVirtualBase, Address This,
2181 bool InheritedFromVBase, const CXXInheritedCtorInitExpr *E) {
2182 CallArgList Args;
Brian Gesiak5488ab42019-01-11 01:54:53 +00002183 CallArg ThisArg(RValue::get(This.getPointer()), D->getThisType());
Richard Smith5179eb72016-06-28 19:03:57 +00002184
2185 // Forward the parameters.
2186 if (InheritedFromVBase &&
2187 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
2188 // Nothing to do; this construction is not responsible for constructing
2189 // the base class containing the inherited constructor.
2190 // FIXME: Can we just pass undef's for the remaining arguments if we don't
2191 // have constructor variants?
2192 Args.push_back(ThisArg);
2193 } else if (!CXXInheritedCtorInitExprArgs.empty()) {
2194 // The inheriting constructor was inlined; just inject its arguments.
2195 assert(CXXInheritedCtorInitExprArgs.size() >= D->getNumParams() &&
2196 "wrong number of parameters for inherited constructor call");
2197 Args = CXXInheritedCtorInitExprArgs;
2198 Args[0] = ThisArg;
2199 } else {
2200 // The inheriting constructor was not inlined. Emit delegating arguments.
2201 Args.push_back(ThisArg);
2202 const auto *OuterCtor = cast<CXXConstructorDecl>(CurCodeDecl);
2203 assert(OuterCtor->getNumParams() == D->getNumParams());
2204 assert(!OuterCtor->isVariadic() && "should have been inlined");
2205
2206 for (const auto *Param : OuterCtor->parameters()) {
2207 assert(getContext().hasSameUnqualifiedType(
2208 OuterCtor->getParamDecl(Param->getFunctionScopeIndex())->getType(),
2209 Param->getType()));
2210 EmitDelegateCallArg(Args, Param, E->getLocation());
2211
2212 // Forward __attribute__(pass_object_size).
2213 if (Param->hasAttr<PassObjectSizeAttr>()) {
2214 auto *POSParam = SizeArguments[Param];
2215 assert(POSParam && "missing pass_object_size value for forwarding");
2216 EmitDelegateCallArg(Args, POSParam, E->getLocation());
2217 }
2218 }
2219 }
2220
2221 EmitCXXConstructorCall(D, Ctor_Base, ForVirtualBase, /*Delegating*/false,
Igor Kudrineff8f9d2018-06-25 05:48:04 +00002222 This, Args, AggValueSlot::MayOverlap,
Serge Pavlov37605182018-07-28 15:33:03 +00002223 E->getLocation(), /*NewPointerIsChecked*/true);
Richard Smith5179eb72016-06-28 19:03:57 +00002224}
2225
2226void CodeGenFunction::EmitInlinedInheritingCXXConstructorCall(
2227 const CXXConstructorDecl *Ctor, CXXCtorType CtorType, bool ForVirtualBase,
2228 bool Delegating, CallArgList &Args) {
Adrian Prantlb7acfc02017-02-27 21:30:05 +00002229 GlobalDecl GD(Ctor, CtorType);
2230 InlinedInheritingConstructorScope Scope(*this, GD);
2231 ApplyInlineDebugLocation DebugScope(*this, GD);
Volodymyr Sapsai232d22f2018-12-20 22:43:26 +00002232 RunCleanupsScope RunCleanups(*this);
Richard Smith5179eb72016-06-28 19:03:57 +00002233
2234 // Save the arguments to be passed to the inherited constructor.
2235 CXXInheritedCtorInitExprArgs = Args;
2236
2237 FunctionArgList Params;
2238 QualType RetType = BuildFunctionArgList(CurGD, Params);
2239 FnRetTy = RetType;
2240
2241 // Insert any ABI-specific implicit constructor arguments.
2242 CGM.getCXXABI().addImplicitConstructorArgs(*this, Ctor, CtorType,
2243 ForVirtualBase, Delegating, Args);
2244
2245 // Emit a simplified prolog. We only need to emit the implicit params.
2246 assert(Args.size() >= Params.size() && "too few arguments for call");
2247 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2248 if (I < Params.size() && isa<ImplicitParamDecl>(Params[I])) {
Yaxun Liu5b330e82018-03-15 15:25:19 +00002249 const RValue &RV = Args[I].getRValue(*this);
Richard Smith5179eb72016-06-28 19:03:57 +00002250 assert(!RV.isComplex() && "complex indirect params not supported");
2251 ParamValue Val = RV.isScalar()
2252 ? ParamValue::forDirect(RV.getScalarVal())
2253 : ParamValue::forIndirect(RV.getAggregateAddress());
2254 EmitParmDecl(*Params[I], Val, I + 1);
2255 }
2256 }
2257
2258 // Create a return value slot if the ABI implementation wants one.
2259 // FIXME: This is dumb, we should ask the ABI not to try to set the return
2260 // value instead.
2261 if (!RetType->isVoidType())
2262 ReturnValue = CreateIRTemp(RetType, "retval.inhctor");
2263
2264 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
2265 CXXThisValue = CXXABIThisValue;
2266
2267 // Directly emit the constructor initializers.
2268 EmitCtorPrologue(Ctor, CtorType, Params);
2269}
2270
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002271void CodeGenFunction::EmitVTableAssumptionLoad(const VPtr &Vptr, Address This) {
2272 llvm::Value *VTableGlobal =
2273 CGM.getCXXABI().getVTableAddressPoint(Vptr.Base, Vptr.VTableClass);
2274 if (!VTableGlobal)
2275 return;
2276
2277 // We can just use the base offset in the complete class.
2278 CharUnits NonVirtualOffset = Vptr.Base.getBaseOffset();
2279
2280 if (!NonVirtualOffset.isZero())
2281 This =
2282 ApplyNonVirtualAndVirtualOffset(*this, This, NonVirtualOffset, nullptr,
2283 Vptr.VTableClass, Vptr.NearestVBase);
2284
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002285 llvm::Value *VPtrValue =
2286 GetVTablePtr(This, VTableGlobal->getType(), Vptr.VTableClass);
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002287 llvm::Value *Cmp =
2288 Builder.CreateICmpEQ(VPtrValue, VTableGlobal, "cmp.vtables");
2289 Builder.CreateAssumption(Cmp);
2290}
2291
2292void CodeGenFunction::EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl,
2293 Address This) {
2294 if (CGM.getCXXABI().doStructorsInitializeVPtrs(ClassDecl))
2295 for (const VPtr &Vptr : getVTablePointers(ClassDecl))
2296 EmitVTableAssumptionLoad(Vptr, This);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002297}
2298
John McCallf8ff7b92010-02-23 00:48:20 +00002299void
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002300CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
John McCall7f416cc2015-09-08 08:05:57 +00002301 Address This, Address Src,
2302 const CXXConstructExpr *E) {
Reid Kleckner739756c2013-12-04 19:23:12 +00002303 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
Justin Bogner1cd11f12015-05-20 15:53:59 +00002304
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002305 CallArgList Args;
Justin Bogner1cd11f12015-05-20 15:53:59 +00002306
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002307 // Push the this ptr.
Brian Gesiak5488ab42019-01-11 01:54:53 +00002308 Args.add(RValue::get(This.getPointer()), D->getThisType());
Justin Bogner1cd11f12015-05-20 15:53:59 +00002309
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002310 // Push the src ptr.
Alp Toker9cacbab2014-01-20 20:26:09 +00002311 QualType QT = *(FPT->param_type_begin());
Chris Lattner2192fe52011-07-18 04:24:23 +00002312 llvm::Type *t = CGM.getTypes().ConvertType(QT);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002313 Src = Builder.CreateBitCast(Src, t);
John McCall7f416cc2015-09-08 08:05:57 +00002314 Args.add(RValue::get(Src.getPointer()), QT);
Reid Kleckner739756c2013-12-04 19:23:12 +00002315
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002316 // Skip over first argument (Src).
David Blaikief05779e2015-07-21 18:37:18 +00002317 EmitCallArgs(Args, FPT, drop_begin(E->arguments(), 1), E->getConstructor(),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002318 /*ParamsToSkip*/ 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002319
Serge Pavlov37605182018-07-28 15:33:03 +00002320 EmitCXXConstructorCall(D, Ctor_Complete, /*ForVirtualBase*/false,
2321 /*Delegating*/false, This, Args,
2322 AggValueSlot::MayOverlap, E->getExprLoc(),
2323 /*NewPointerIsChecked*/false);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002324}
2325
2326void
John McCallf8ff7b92010-02-23 00:48:20 +00002327CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
2328 CXXCtorType CtorType,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002329 const FunctionArgList &Args,
2330 SourceLocation Loc) {
John McCallf8ff7b92010-02-23 00:48:20 +00002331 CallArgList DelegateArgs;
2332
2333 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
2334 assert(I != E && "no parameters to constructor");
2335
2336 // this
Richard Smith5179eb72016-06-28 19:03:57 +00002337 Address This = LoadCXXThisAddress();
2338 DelegateArgs.add(RValue::get(This.getPointer()), (*I)->getType());
John McCallf8ff7b92010-02-23 00:48:20 +00002339 ++I;
2340
Richard Smith5179eb72016-06-28 19:03:57 +00002341 // FIXME: The location of the VTT parameter in the parameter list is
2342 // specific to the Itanium ABI and shouldn't be hardcoded here.
2343 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
2344 assert(I != E && "cannot skip vtt parameter, already done with args");
2345 assert((*I)->getType()->isPointerType() &&
2346 "skipping parameter not of vtt type");
2347 ++I;
John McCallf8ff7b92010-02-23 00:48:20 +00002348 }
2349
2350 // Explicit arguments.
2351 for (; I != E; ++I) {
John McCall32ea9692011-03-11 20:59:21 +00002352 const VarDecl *param = *I;
Nick Lewycky2d84e842013-10-02 02:29:49 +00002353 // FIXME: per-argument source location
2354 EmitDelegateCallArg(DelegateArgs, param, Loc);
John McCallf8ff7b92010-02-23 00:48:20 +00002355 }
2356
Richard Smith5179eb72016-06-28 19:03:57 +00002357 EmitCXXConstructorCall(Ctor, CtorType, /*ForVirtualBase=*/false,
Richard Smithe78fac52018-04-05 20:52:58 +00002358 /*Delegating=*/true, This, DelegateArgs,
Serge Pavlov37605182018-07-28 15:33:03 +00002359 AggValueSlot::MayOverlap, Loc,
2360 /*NewPointerIsChecked=*/true);
John McCallf8ff7b92010-02-23 00:48:20 +00002361}
2362
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002363namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002364 struct CallDelegatingCtorDtor final : EHScopeStack::Cleanup {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002365 const CXXDestructorDecl *Dtor;
John McCall7f416cc2015-09-08 08:05:57 +00002366 Address Addr;
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002367 CXXDtorType Type;
2368
John McCall7f416cc2015-09-08 08:05:57 +00002369 CallDelegatingCtorDtor(const CXXDestructorDecl *D, Address Addr,
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002370 CXXDtorType Type)
2371 : Dtor(D), Addr(Addr), Type(Type) {}
2372
Craig Topper4f12f102014-03-12 06:41:41 +00002373 void Emit(CodeGenFunction &CGF, Flags flags) override {
Marco Antognini88559632019-07-22 09:39:13 +00002374 // We are calling the destructor from within the constructor.
2375 // Therefore, "this" should have the expected type.
2376 QualType ThisTy = Dtor->getThisObjectType();
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002377 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
Marco Antognini88559632019-07-22 09:39:13 +00002378 /*Delegating=*/true, Addr, ThisTy);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002379 }
2380 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00002381} // end anonymous namespace
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002382
Alexis Hunt61bc1732011-05-01 07:04:31 +00002383void
2384CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
2385 const FunctionArgList &Args) {
2386 assert(Ctor->isDelegatingConstructor());
2387
John McCall7f416cc2015-09-08 08:05:57 +00002388 Address ThisPtr = LoadCXXThisAddress();
Alexis Hunt61bc1732011-05-01 07:04:31 +00002389
John McCall31168b02011-06-15 23:02:42 +00002390 AggValueSlot AggSlot =
John McCall7f416cc2015-09-08 08:05:57 +00002391 AggValueSlot::forAddr(ThisPtr, Qualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +00002392 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00002393 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00002394 AggValueSlot::IsNotAliased,
Serge Pavlov37605182018-07-28 15:33:03 +00002395 AggValueSlot::MayOverlap,
2396 AggValueSlot::IsNotZeroed,
2397 // Checks are made by the code that calls constructor.
2398 AggValueSlot::IsSanitizerChecked);
Alexis Hunt61bc1732011-05-01 07:04:31 +00002399
2400 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
Alexis Hunt61bc1732011-05-01 07:04:31 +00002401
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002402 const CXXRecordDecl *ClassDecl = Ctor->getParent();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002403 if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002404 CXXDtorType Type =
2405 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
2406
2407 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
2408 ClassDecl->getDestructor(),
2409 ThisPtr, Type);
2410 }
2411}
Alexis Hunt61bc1732011-05-01 07:04:31 +00002412
Anders Carlsson27da15b2010-01-01 20:29:01 +00002413void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
2414 CXXDtorType Type,
Anders Carlssonf8a71f02010-05-02 23:29:11 +00002415 bool ForVirtualBase,
Marco Antognini88559632019-07-22 09:39:13 +00002416 bool Delegating, Address This,
2417 QualType ThisTy) {
Reid Kleckner6fe771a2013-12-13 00:53:54 +00002418 CGM.getCXXABI().EmitDestructorCall(*this, DD, Type, ForVirtualBase,
Marco Antognini88559632019-07-22 09:39:13 +00002419 Delegating, This, ThisTy);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002420}
2421
John McCall53cad2e2010-07-21 01:41:18 +00002422namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002423 struct CallLocalDtor final : EHScopeStack::Cleanup {
John McCall53cad2e2010-07-21 01:41:18 +00002424 const CXXDestructorDecl *Dtor;
John McCall7f416cc2015-09-08 08:05:57 +00002425 Address Addr;
Marco Antognini88559632019-07-22 09:39:13 +00002426 QualType Ty;
John McCall53cad2e2010-07-21 01:41:18 +00002427
Marco Antognini88559632019-07-22 09:39:13 +00002428 CallLocalDtor(const CXXDestructorDecl *D, Address Addr, QualType Ty)
2429 : Dtor(D), Addr(Addr), Ty(Ty) {}
John McCall53cad2e2010-07-21 01:41:18 +00002430
Craig Topper4f12f102014-03-12 06:41:41 +00002431 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall53cad2e2010-07-21 01:41:18 +00002432 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +00002433 /*ForVirtualBase=*/false,
Marco Antognini88559632019-07-22 09:39:13 +00002434 /*Delegating=*/false, Addr, Ty);
John McCall53cad2e2010-07-21 01:41:18 +00002435 }
2436 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002437} // end anonymous namespace
John McCall53cad2e2010-07-21 01:41:18 +00002438
John McCall8680f872010-07-21 06:29:51 +00002439void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
Marco Antognini88559632019-07-22 09:39:13 +00002440 QualType T, Address Addr) {
2441 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr, T);
John McCall8680f872010-07-21 06:29:51 +00002442}
2443
John McCall7f416cc2015-09-08 08:05:57 +00002444void CodeGenFunction::PushDestructorCleanup(QualType T, Address Addr) {
John McCallbd309292010-07-06 01:34:17 +00002445 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
2446 if (!ClassDecl) return;
2447 if (ClassDecl->hasTrivialDestructor()) return;
2448
2449 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCalla85af562011-04-28 02:15:35 +00002450 assert(D && D->isUsed() && "destructor not marked as used!");
Marco Antognini88559632019-07-22 09:39:13 +00002451 PushDestructorCleanup(D, T, Addr);
John McCallbd309292010-07-06 01:34:17 +00002452}
2453
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002454void CodeGenFunction::InitializeVTablePointer(const VPtr &Vptr) {
Anders Carlssone87fae92010-03-28 19:40:00 +00002455 // Compute the address point.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002456 llvm::Value *VTableAddressPoint =
2457 CGM.getCXXABI().getVTableAddressPointInStructor(
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002458 *this, Vptr.VTableClass, Vptr.Base, Vptr.NearestVBase);
2459
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002460 if (!VTableAddressPoint)
2461 return;
Anders Carlssone87fae92010-03-28 19:40:00 +00002462
Anders Carlsson6a0227d2010-04-20 16:22:16 +00002463 // Compute where to store the address point.
Craig Topper8a13c412014-05-21 05:09:00 +00002464 llvm::Value *VirtualOffset = nullptr;
Ken Dyckcfc332c2011-03-23 00:45:26 +00002465 CharUnits NonVirtualOffset = CharUnits::Zero();
Justin Bogner1cd11f12015-05-20 15:53:59 +00002466
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002467 if (CGM.getCXXABI().isVirtualOffsetNeededForVTableField(*this, Vptr)) {
Anders Carlsson91baecf2010-04-20 18:05:10 +00002468 // We need to use the virtual base offset offset because the virtual base
2469 // might have a different offset in the most derived class.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002470
2471 VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(
2472 *this, LoadCXXThisAddress(), Vptr.VTableClass, Vptr.NearestVBase);
2473 NonVirtualOffset = Vptr.OffsetFromNearestVBase;
Anders Carlsson91baecf2010-04-20 18:05:10 +00002474 } else {
Anders Carlssonc58fb552010-05-03 00:29:58 +00002475 // We can just use the base offset in the complete class.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002476 NonVirtualOffset = Vptr.Base.getBaseOffset();
Anders Carlsson91baecf2010-04-20 18:05:10 +00002477 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002478
Anders Carlssonc58fb552010-05-03 00:29:58 +00002479 // Apply the offsets.
John McCall7f416cc2015-09-08 08:05:57 +00002480 Address VTableField = LoadCXXThisAddress();
Justin Bogner1cd11f12015-05-20 15:53:59 +00002481
Ken Dyckcfc332c2011-03-23 00:45:26 +00002482 if (!NonVirtualOffset.isZero() || VirtualOffset)
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002483 VTableField = ApplyNonVirtualAndVirtualOffset(
2484 *this, VTableField, NonVirtualOffset, VirtualOffset, Vptr.VTableClass,
2485 Vptr.NearestVBase);
Anders Carlsson6a0227d2010-04-20 16:22:16 +00002486
Reid Kleckner8d585132014-12-03 21:00:21 +00002487 // Finally, store the address point. Use the same LLVM types as the field to
2488 // support optimization.
2489 llvm::Type *VTablePtrTy =
2490 llvm::FunctionType::get(CGM.Int32Ty, /*isVarArg=*/true)
2491 ->getPointerTo()
2492 ->getPointerTo();
2493 VTableField = Builder.CreateBitCast(VTableField, VTablePtrTy->getPointerTo());
2494 VTableAddressPoint = Builder.CreateBitCast(VTableAddressPoint, VTablePtrTy);
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002495
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002496 llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
Ivan A. Kosarev4e50e702017-11-27 09:39:29 +00002497 TBAAAccessInfo TBAAInfo = CGM.getTBAAVTablePtrAccessInfo(VTablePtrTy);
2498 CGM.DecorateInstructionWithTBAA(Store, TBAAInfo);
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002499 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2500 CGM.getCodeGenOpts().StrictVTablePointers)
2501 CGM.DecorateInstructionWithInvariantGroup(Store, Vptr.VTableClass);
Anders Carlssone87fae92010-03-28 19:40:00 +00002502}
2503
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002504CodeGenFunction::VPtrsVector
2505CodeGenFunction::getVTablePointers(const CXXRecordDecl *VTableClass) {
2506 CodeGenFunction::VPtrsVector VPtrsResult;
2507 VisitedVirtualBasesSetTy VBases;
2508 getVTablePointers(BaseSubobject(VTableClass, CharUnits::Zero()),
2509 /*NearestVBase=*/nullptr,
2510 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
2511 /*BaseIsNonVirtualPrimaryBase=*/false, VTableClass, VBases,
2512 VPtrsResult);
2513 return VPtrsResult;
2514}
2515
2516void CodeGenFunction::getVTablePointers(BaseSubobject Base,
2517 const CXXRecordDecl *NearestVBase,
2518 CharUnits OffsetFromNearestVBase,
2519 bool BaseIsNonVirtualPrimaryBase,
2520 const CXXRecordDecl *VTableClass,
2521 VisitedVirtualBasesSetTy &VBases,
2522 VPtrsVector &Vptrs) {
Anders Carlssond5895932010-03-28 21:07:49 +00002523 // If this base is a non-virtual primary base the address point has already
2524 // been set.
2525 if (!BaseIsNonVirtualPrimaryBase) {
2526 // Initialize the vtable pointer for this base.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002527 VPtr Vptr = {Base, NearestVBase, OffsetFromNearestVBase, VTableClass};
2528 Vptrs.push_back(Vptr);
Anders Carlssond5895932010-03-28 21:07:49 +00002529 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002530
Anders Carlssond5895932010-03-28 21:07:49 +00002531 const CXXRecordDecl *RD = Base.getBase();
2532
2533 // Traverse bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00002534 for (const auto &I : RD->bases()) {
Simon Pilgrim1cd399c2019-10-03 11:22:48 +00002535 auto *BaseDecl =
2536 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
Anders Carlssond5895932010-03-28 21:07:49 +00002537
2538 // Ignore classes without a vtable.
2539 if (!BaseDecl->isDynamicClass())
2540 continue;
2541
Ken Dyck3fb4c892011-03-23 01:04:18 +00002542 CharUnits BaseOffset;
2543 CharUnits BaseOffsetFromNearestVBase;
Anders Carlsson948d3f42010-03-29 01:16:41 +00002544 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlssond5895932010-03-28 21:07:49 +00002545
Aaron Ballman574705e2014-03-13 15:41:46 +00002546 if (I.isVirtual()) {
Anders Carlssond5895932010-03-28 21:07:49 +00002547 // Check if we've visited this virtual base before.
David Blaikie82e95a32014-11-19 07:49:47 +00002548 if (!VBases.insert(BaseDecl).second)
Anders Carlssond5895932010-03-28 21:07:49 +00002549 continue;
2550
Justin Bogner1cd11f12015-05-20 15:53:59 +00002551 const ASTRecordLayout &Layout =
Anders Carlssond5895932010-03-28 21:07:49 +00002552 getContext().getASTRecordLayout(VTableClass);
2553
Ken Dyck3fb4c892011-03-23 01:04:18 +00002554 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
2555 BaseOffsetFromNearestVBase = CharUnits::Zero();
Anders Carlsson948d3f42010-03-29 01:16:41 +00002556 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlssond5895932010-03-28 21:07:49 +00002557 } else {
2558 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
2559
Ken Dyck16ffcac2011-03-24 01:21:01 +00002560 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
Justin Bogner1cd11f12015-05-20 15:53:59 +00002561 BaseOffsetFromNearestVBase =
Ken Dyck3fb4c892011-03-23 01:04:18 +00002562 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson948d3f42010-03-29 01:16:41 +00002563 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlssond5895932010-03-28 21:07:49 +00002564 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002565
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002566 getVTablePointers(
2567 BaseSubobject(BaseDecl, BaseOffset),
2568 I.isVirtual() ? BaseDecl : NearestVBase, BaseOffsetFromNearestVBase,
2569 BaseDeclIsNonVirtualPrimaryBase, VTableClass, VBases, Vptrs);
Anders Carlssond5895932010-03-28 21:07:49 +00002570 }
2571}
2572
2573void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
2574 // Ignore classes without a vtable.
Anders Carlsson1f9348c2010-03-26 04:39:42 +00002575 if (!RD->isDynamicClass())
Anders Carlsson27da15b2010-01-01 20:29:01 +00002576 return;
2577
Anders Carlssond5895932010-03-28 21:07:49 +00002578 // Initialize the vtable pointers for this class and all of its bases.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002579 if (CGM.getCXXABI().doStructorsInitializeVPtrs(RD))
2580 for (const VPtr &Vptr : getVTablePointers(RD))
2581 InitializeVTablePointer(Vptr);
Timur Iskhodzhanovb6487322013-10-09 18:16:58 +00002582
2583 if (RD->getNumVBases())
2584 CGM.getCXXABI().initializeHiddenVirtualInheritanceMembers(*this, RD);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002585}
Dan Gohman8fc50c22010-10-26 18:44:08 +00002586
John McCall7f416cc2015-09-08 08:05:57 +00002587llvm::Value *CodeGenFunction::GetVTablePtr(Address This,
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002588 llvm::Type *VTableTy,
2589 const CXXRecordDecl *RD) {
2590 Address VTablePtrSrc = Builder.CreateElementBitCast(This, VTableTy);
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002591 llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
Ivan A. Kosarev4e50e702017-11-27 09:39:29 +00002592 TBAAAccessInfo TBAAInfo = CGM.getTBAAVTablePtrAccessInfo(VTableTy);
2593 CGM.DecorateInstructionWithTBAA(VTable, TBAAInfo);
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002594
2595 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2596 CGM.getCodeGenOpts().StrictVTablePointers)
2597 CGM.DecorateInstructionWithInvariantGroup(VTable, RD);
2598
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002599 return VTable;
Dan Gohman8fc50c22010-10-26 18:44:08 +00002600}
Anders Carlssonc36783e2011-05-08 20:32:23 +00002601
Peter Collingbourned2926c92015-03-14 02:42:25 +00002602// If a class has a single non-virtual base and does not introduce or override
2603// virtual member functions or fields, it will have the same layout as its base.
2604// This function returns the least derived such class.
2605//
2606// Casting an instance of a base class to such a derived class is technically
2607// undefined behavior, but it is a relatively common hack for introducing member
2608// functions on class instances with specific properties (e.g. llvm::Operator)
2609// that works under most compilers and should not have security implications, so
2610// we allow it by default. It can be disabled with -fsanitize=cfi-cast-strict.
2611static const CXXRecordDecl *
2612LeastDerivedClassWithSameLayout(const CXXRecordDecl *RD) {
2613 if (!RD->field_empty())
2614 return RD;
2615
2616 if (RD->getNumVBases() != 0)
2617 return RD;
2618
2619 if (RD->getNumBases() != 1)
2620 return RD;
2621
2622 for (const CXXMethodDecl *MD : RD->methods()) {
2623 if (MD->isVirtual()) {
2624 // Virtual member functions are only ok if they are implicit destructors
2625 // because the implicit destructor will have the same semantics as the
2626 // base class's destructor if no fields are added.
2627 if (isa<CXXDestructorDecl>(MD) && MD->isImplicit())
2628 continue;
2629 return RD;
2630 }
2631 }
2632
2633 return LeastDerivedClassWithSameLayout(
2634 RD->bases_begin()->getType()->getAsCXXRecordDecl());
2635}
2636
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002637void CodeGenFunction::EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD,
2638 llvm::Value *VTable,
2639 SourceLocation Loc) {
Peter Collingbourne396943a2017-07-31 22:35:33 +00002640 if (SanOpts.has(SanitizerKind::CFIVCall))
2641 EmitVTablePtrCheckForCall(RD, VTable, CodeGenFunction::CFITCK_VCall, Loc);
2642 else if (CGM.getCodeGenOpts().WholeProgramVTables &&
2643 CGM.HasHiddenLTOVisibility(RD)) {
Peter Collingbournefb532b92016-02-24 20:46:36 +00002644 llvm::Metadata *MD =
2645 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002646 llvm::Value *TypeId =
Peter Collingbournefb532b92016-02-24 20:46:36 +00002647 llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD);
2648
2649 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002650 llvm::Value *TypeTest =
2651 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
2652 {CastedVTable, TypeId});
2653 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::assume), TypeTest);
Peter Collingbournefb532b92016-02-24 20:46:36 +00002654 }
Peter Collingbournefb532b92016-02-24 20:46:36 +00002655}
2656
2657void CodeGenFunction::EmitVTablePtrCheckForCall(const CXXRecordDecl *RD,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002658 llvm::Value *VTable,
2659 CFITypeCheckKind TCK,
2660 SourceLocation Loc) {
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002661 if (!SanOpts.has(SanitizerKind::CFICastStrict))
Peter Collingbournefb532b92016-02-24 20:46:36 +00002662 RD = LeastDerivedClassWithSameLayout(RD);
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002663
Peter Collingbournefb532b92016-02-24 20:46:36 +00002664 EmitVTablePtrCheck(RD, VTable, TCK, Loc);
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002665}
2666
Peter Collingbourned2926c92015-03-14 02:42:25 +00002667void CodeGenFunction::EmitVTablePtrCheckForCast(QualType T,
2668 llvm::Value *Derived,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002669 bool MayBeNull,
2670 CFITypeCheckKind TCK,
2671 SourceLocation Loc) {
Peter Collingbourned2926c92015-03-14 02:42:25 +00002672 if (!getLangOpts().CPlusPlus)
2673 return;
2674
2675 auto *ClassTy = T->getAs<RecordType>();
2676 if (!ClassTy)
2677 return;
2678
2679 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassTy->getDecl());
2680
2681 if (!ClassDecl->isCompleteDefinition() || !ClassDecl->isDynamicClass())
2682 return;
2683
Peter Collingbourned2926c92015-03-14 02:42:25 +00002684 if (!SanOpts.has(SanitizerKind::CFICastStrict))
2685 ClassDecl = LeastDerivedClassWithSameLayout(ClassDecl);
2686
Hans Wennborgdcfba332015-10-06 23:40:43 +00002687 llvm::BasicBlock *ContBlock = nullptr;
Peter Collingbourned2926c92015-03-14 02:42:25 +00002688
2689 if (MayBeNull) {
2690 llvm::Value *DerivedNotNull =
2691 Builder.CreateIsNotNull(Derived, "cast.nonnull");
2692
2693 llvm::BasicBlock *CheckBlock = createBasicBlock("cast.check");
2694 ContBlock = createBasicBlock("cast.cont");
2695
2696 Builder.CreateCondBr(DerivedNotNull, CheckBlock, ContBlock);
2697
2698 EmitBlock(CheckBlock);
2699 }
2700
Peter Collingbourne60108802017-12-13 21:53:04 +00002701 llvm::Value *VTable;
2702 std::tie(VTable, ClassDecl) = CGM.getCXXABI().LoadVTablePtr(
2703 *this, Address(Derived, getPointerAlign()), ClassDecl);
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002704
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002705 EmitVTablePtrCheck(ClassDecl, VTable, TCK, Loc);
Peter Collingbourned2926c92015-03-14 02:42:25 +00002706
2707 if (MayBeNull) {
2708 Builder.CreateBr(ContBlock);
2709 EmitBlock(ContBlock);
2710 }
2711}
2712
2713void CodeGenFunction::EmitVTablePtrCheck(const CXXRecordDecl *RD,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002714 llvm::Value *VTable,
2715 CFITypeCheckKind TCK,
2716 SourceLocation Loc) {
Peter Collingbourne3afb2662016-04-28 17:09:37 +00002717 if (!CGM.getCodeGenOpts().SanitizeCfiCrossDso &&
2718 !CGM.HasHiddenLTOVisibility(RD))
2719 return;
2720
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002721 SanitizerMask M;
Peter Collingbournedc134532016-01-16 00:31:22 +00002722 llvm::SanitizerStatKind SSK;
2723 switch (TCK) {
2724 case CFITCK_VCall:
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002725 M = SanitizerKind::CFIVCall;
Peter Collingbournedc134532016-01-16 00:31:22 +00002726 SSK = llvm::SanStat_CFI_VCall;
2727 break;
2728 case CFITCK_NVCall:
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002729 M = SanitizerKind::CFINVCall;
Peter Collingbournedc134532016-01-16 00:31:22 +00002730 SSK = llvm::SanStat_CFI_NVCall;
2731 break;
2732 case CFITCK_DerivedCast:
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002733 M = SanitizerKind::CFIDerivedCast;
Peter Collingbournedc134532016-01-16 00:31:22 +00002734 SSK = llvm::SanStat_CFI_DerivedCast;
2735 break;
2736 case CFITCK_UnrelatedCast:
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002737 M = SanitizerKind::CFIUnrelatedCast;
Peter Collingbournedc134532016-01-16 00:31:22 +00002738 SSK = llvm::SanStat_CFI_UnrelatedCast;
2739 break;
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002740 case CFITCK_ICall:
Peter Collingbournee44acad2018-06-26 02:15:47 +00002741 case CFITCK_NVMFCall:
2742 case CFITCK_VMFCall:
2743 llvm_unreachable("unexpected sanitizer kind");
Peter Collingbournedc134532016-01-16 00:31:22 +00002744 }
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002745
2746 std::string TypeName = RD->getQualifiedNameAsString();
2747 if (getContext().getSanitizerBlacklist().isBlacklistedType(M, TypeName))
2748 return;
2749
2750 SanitizerScope SanScope(this);
Peter Collingbournedc134532016-01-16 00:31:22 +00002751 EmitSanitizerStatReport(SSK);
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002752
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002753 llvm::Metadata *MD =
2754 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002755 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002756
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002757 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002758 llvm::Value *TypeTest = Builder.CreateCall(
2759 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, TypeId});
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002760
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002761 llvm::Constant *StaticData[] = {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002762 llvm::ConstantInt::get(Int8Ty, TCK),
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002763 EmitCheckSourceLocation(Loc),
2764 EmitCheckTypeDescriptor(QualType(RD->getTypeForDecl(), 0)),
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002765 };
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002766
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002767 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
2768 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
2769 EmitCfiSlowPathCheck(M, TypeTest, CrossDsoTypeId, CastedVTable, StaticData);
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002770 return;
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002771 }
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002772
2773 if (CGM.getCodeGenOpts().SanitizeTrap.has(M)) {
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002774 EmitTrapCheck(TypeTest);
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002775 return;
2776 }
2777
2778 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
2779 CGM.getLLVMContext(),
2780 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002781 llvm::Value *ValidVtable = Builder.CreateCall(
2782 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, AllVtables});
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002783 EmitCheck(std::make_pair(TypeTest, M), SanitizerHandler::CFICheckFail,
2784 StaticData, {CastedVTable, ValidVtable});
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002785}
Anders Carlssonc36783e2011-05-08 20:32:23 +00002786
Peter Collingbourne0ca03632016-06-25 00:24:06 +00002787bool CodeGenFunction::ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD) {
2788 if (!CGM.getCodeGenOpts().WholeProgramVTables ||
Peter Collingbourne0ca03632016-06-25 00:24:06 +00002789 !CGM.HasHiddenLTOVisibility(RD))
2790 return false;
2791
Oliver Stannard3b598b92019-10-17 09:58:57 +00002792 if (CGM.getCodeGenOpts().VirtualFunctionElimination)
2793 return true;
2794
2795 if (!SanOpts.has(SanitizerKind::CFIVCall) ||
2796 !CGM.getCodeGenOpts().SanitizeTrap.has(SanitizerKind::CFIVCall))
2797 return false;
2798
Peter Collingbourne0ca03632016-06-25 00:24:06 +00002799 std::string TypeName = RD->getQualifiedNameAsString();
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002800 return !getContext().getSanitizerBlacklist().isBlacklistedType(
2801 SanitizerKind::CFIVCall, TypeName);
Peter Collingbourne0ca03632016-06-25 00:24:06 +00002802}
2803
2804llvm::Value *CodeGenFunction::EmitVTableTypeCheckedLoad(
2805 const CXXRecordDecl *RD, llvm::Value *VTable, uint64_t VTableByteOffset) {
2806 SanitizerScope SanScope(this);
2807
2808 EmitSanitizerStatReport(llvm::SanStat_CFI_VCall);
2809
2810 llvm::Metadata *MD =
2811 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
2812 llvm::Value *TypeId = llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD);
2813
2814 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
2815 llvm::Value *CheckedLoad = Builder.CreateCall(
2816 CGM.getIntrinsic(llvm::Intrinsic::type_checked_load),
2817 {CastedVTable, llvm::ConstantInt::get(Int32Ty, VTableByteOffset),
2818 TypeId});
2819 llvm::Value *CheckResult = Builder.CreateExtractValue(CheckedLoad, 1);
2820
Oliver Stannard3b598b92019-10-17 09:58:57 +00002821 std::string TypeName = RD->getQualifiedNameAsString();
2822 if (SanOpts.has(SanitizerKind::CFIVCall) &&
2823 !getContext().getSanitizerBlacklist().isBlacklistedType(
2824 SanitizerKind::CFIVCall, TypeName)) {
2825 EmitCheck(std::make_pair(CheckResult, SanitizerKind::CFIVCall),
2826 SanitizerHandler::CFICheckFail, {}, {});
2827 }
Peter Collingbourne0ca03632016-06-25 00:24:06 +00002828
2829 return Builder.CreateBitCast(
2830 Builder.CreateExtractValue(CheckedLoad, 0),
2831 cast<llvm::PointerType>(VTable->getType())->getElementType());
2832}
2833
Faisal Vali571df122013-09-29 08:45:24 +00002834void CodeGenFunction::EmitForwardingCallToLambda(
2835 const CXXMethodDecl *callOperator,
2836 CallArgList &callArgs) {
Eli Friedman5b446882012-02-16 03:47:28 +00002837 // Get the address of the call operator.
John McCall8dda7b22012-07-07 06:41:13 +00002838 const CGFunctionInfo &calleeFnInfo =
2839 CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
John McCallb92ab1a2016-10-26 23:46:34 +00002840 llvm::Constant *calleePtr =
John McCall8dda7b22012-07-07 06:41:13 +00002841 CGM.GetAddrOfFunction(GlobalDecl(callOperator),
2842 CGM.getTypes().GetFunctionType(calleeFnInfo));
Eli Friedman5b446882012-02-16 03:47:28 +00002843
John McCall8dda7b22012-07-07 06:41:13 +00002844 // Prepare the return slot.
2845 const FunctionProtoType *FPT =
2846 callOperator->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00002847 QualType resultType = FPT->getReturnType();
John McCall8dda7b22012-07-07 06:41:13 +00002848 ReturnValueSlot returnSlot;
2849 if (!resultType->isVoidType() &&
2850 calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
John McCall47fb9502013-03-07 21:37:08 +00002851 !hasScalarEvaluationKind(calleeFnInfo.getReturnType()))
John McCall8dda7b22012-07-07 06:41:13 +00002852 returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
2853
2854 // We don't need to separately arrange the call arguments because
2855 // the call can't be variadic anyway --- it's impossible to forward
2856 // variadic arguments.
Justin Bogner1cd11f12015-05-20 15:53:59 +00002857
Eli Friedman5b446882012-02-16 03:47:28 +00002858 // Now emit our call.
Erich Keanede6480a32018-11-13 15:48:08 +00002859 auto callee = CGCallee::forDirect(calleePtr, GlobalDecl(callOperator));
John McCallb92ab1a2016-10-26 23:46:34 +00002860 RValue RV = EmitCall(calleeFnInfo, callee, returnSlot, callArgs);
Eli Friedman5b446882012-02-16 03:47:28 +00002861
John McCall8dda7b22012-07-07 06:41:13 +00002862 // If necessary, copy the returned value into the slot.
John McCall95088452017-12-14 18:21:14 +00002863 if (!resultType->isVoidType() && returnSlot.isNull()) {
2864 if (getLangOpts().ObjCAutoRefCount && resultType->isObjCRetainableType()) {
2865 RV = RValue::get(EmitARCRetainAutoreleasedReturnValue(RV.getScalarVal()));
2866 }
John McCall8dda7b22012-07-07 06:41:13 +00002867 EmitReturnOfRValue(RV, resultType);
John McCall95088452017-12-14 18:21:14 +00002868 } else
Eli Friedmanf5f4d2f2012-12-13 23:37:17 +00002869 EmitBranchThroughCleanup(ReturnBlock);
Eli Friedman5b446882012-02-16 03:47:28 +00002870}
2871
Eli Friedman2495ab02012-02-25 02:48:22 +00002872void CodeGenFunction::EmitLambdaBlockInvokeBody() {
2873 const BlockDecl *BD = BlockInfo->getBlockDecl();
2874 const VarDecl *variable = BD->capture_begin()->getVariable();
2875 const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
Reid Kleckner2d3c4212017-08-04 22:38:06 +00002876 const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
2877
2878 if (CallOp->isVariadic()) {
2879 // FIXME: Making this work correctly is nasty because it requires either
2880 // cloning the body of the call operator or making the call operator
2881 // forward.
2882 CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function");
2883 return;
2884 }
Eli Friedman2495ab02012-02-25 02:48:22 +00002885
2886 // Start building arguments for forwarding call
2887 CallArgList CallArgs;
2888
2889 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
Akira Hatanaka8e57b072018-10-01 21:51:28 +00002890 Address ThisPtr = GetAddrOfBlockDecl(variable);
John McCall7f416cc2015-09-08 08:05:57 +00002891 CallArgs.add(RValue::get(ThisPtr.getPointer()), ThisType);
Eli Friedman2495ab02012-02-25 02:48:22 +00002892
2893 // Add the rest of the parameters.
David Majnemer59f77922016-06-24 04:05:48 +00002894 for (auto param : BD->parameters())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002895 EmitDelegateCallArg(CallArgs, param, param->getBeginLoc());
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00002896
Justin Bogner1cd11f12015-05-20 15:53:59 +00002897 assert(!Lambda->isGenericLambda() &&
Faisal Vali571df122013-09-29 08:45:24 +00002898 "generic lambda interconversion to block not implemented");
Reid Kleckner2d3c4212017-08-04 22:38:06 +00002899 EmitForwardingCallToLambda(CallOp, CallArgs);
Eli Friedman2495ab02012-02-25 02:48:22 +00002900}
2901
2902void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
2903 const CXXRecordDecl *Lambda = MD->getParent();
2904
2905 // Start building arguments for forwarding call
2906 CallArgList CallArgs;
2907
2908 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2909 llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
2910 CallArgs.add(RValue::get(ThisPtr), ThisType);
2911
2912 // Add the rest of the parameters.
David Majnemer59f77922016-06-24 04:05:48 +00002913 for (auto Param : MD->parameters())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002914 EmitDelegateCallArg(CallArgs, Param, Param->getBeginLoc());
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002915
Faisal Vali571df122013-09-29 08:45:24 +00002916 const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
2917 // For a generic lambda, find the corresponding call operator specialization
2918 // to which the call to the static-invoker shall be forwarded.
2919 if (Lambda->isGenericLambda()) {
2920 assert(MD->isFunctionTemplateSpecialization());
2921 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
2922 FunctionTemplateDecl *CallOpTemplate = CallOp->getDescribedFunctionTemplate();
Craig Topper8a13c412014-05-21 05:09:00 +00002923 void *InsertPos = nullptr;
Justin Bogner1cd11f12015-05-20 15:53:59 +00002924 FunctionDecl *CorrespondingCallOpSpecialization =
Craig Topper7e0daca2014-06-26 04:58:53 +00002925 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
Faisal Vali571df122013-09-29 08:45:24 +00002926 assert(CorrespondingCallOpSpecialization);
2927 CallOp = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
2928 }
2929 EmitForwardingCallToLambda(CallOp, CallArgs);
Eli Friedman2495ab02012-02-25 02:48:22 +00002930}
2931
Reid Kleckner2d3c4212017-08-04 22:38:06 +00002932void CodeGenFunction::EmitLambdaStaticInvokeBody(const CXXMethodDecl *MD) {
Douglas Gregor355efbb2012-02-17 03:02:34 +00002933 if (MD->isVariadic()) {
Eli Friedman5b446882012-02-16 03:47:28 +00002934 // FIXME: Making this work correctly is nasty because it requires either
2935 // cloning the body of the call operator or making the call operator forward.
2936 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
Eli Friedman2495ab02012-02-25 02:48:22 +00002937 return;
Eli Friedman5b446882012-02-16 03:47:28 +00002938 }
2939
Douglas Gregor355efbb2012-02-17 03:02:34 +00002940 EmitLambdaDelegatingInvokeBody(MD);
Eli Friedman5a6d5072012-02-16 01:37:33 +00002941}