blob: f228329ad9b6af7bd1fefe14b92712346039a224 [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();
John McCall13a39c62012-08-01 05:04:58 +0000249 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
250 ptr = CGF.Builder.CreateInBoundsGEP(ptr, baseOffset, "add.ptr");
John McCall7f416cc2015-09-08 08:05:57 +0000251
252 // If we have a virtual component, the alignment of the result will
253 // be relative only to the known alignment of that vbase.
254 CharUnits alignment;
255 if (virtualOffset) {
256 assert(nearestVBase && "virtual offset without vbase?");
257 alignment = CGF.CGM.getVBaseAlignment(addr.getAlignment(),
258 derivedClass, nearestVBase);
259 } else {
260 alignment = addr.getAlignment();
261 }
262 alignment = alignment.alignmentAtOffset(nonVirtualOffset);
263
264 return Address(ptr, alignment);
Anders Carlsson53cebd12010-04-20 16:03:35 +0000265}
266
John McCall7f416cc2015-09-08 08:05:57 +0000267Address CodeGenFunction::GetAddressOfBaseClass(
268 Address Value, const CXXRecordDecl *Derived,
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000269 CastExpr::path_const_iterator PathBegin,
270 CastExpr::path_const_iterator PathEnd, bool NullCheckValue,
271 SourceLocation Loc) {
John McCallcf142162010-08-07 06:22:56 +0000272 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssond829a022010-04-24 21:06:20 +0000273
John McCallcf142162010-08-07 06:22:56 +0000274 CastExpr::path_const_iterator Start = PathBegin;
Craig Topper8a13c412014-05-21 05:09:00 +0000275 const CXXRecordDecl *VBase = nullptr;
276
John McCall13a39c62012-08-01 05:04:58 +0000277 // Sema has done some convenient canonicalization here: if the
278 // access path involved any virtual steps, the conversion path will
279 // *start* with a step down to the correct virtual base subobject,
280 // and hence will not require any further steps.
Anders Carlssond829a022010-04-24 21:06:20 +0000281 if ((*Start)->isVirtual()) {
Simon Pilgrim1cd399c2019-10-03 11:22:48 +0000282 VBase = cast<CXXRecordDecl>(
283 (*Start)->getType()->castAs<RecordType>()->getDecl());
Anders Carlssond829a022010-04-24 21:06:20 +0000284 ++Start;
285 }
John McCall13a39c62012-08-01 05:04:58 +0000286
287 // Compute the static offset of the ultimate destination within its
288 // allocating subobject (the virtual base, if there is one, or else
289 // the "complete" object that we see).
David Majnemerc1709d32015-06-23 07:31:11 +0000290 CharUnits NonVirtualOffset = CGM.computeNonVirtualBaseClassOffset(
291 VBase ? VBase : Derived, Start, PathEnd);
Anders Carlssond829a022010-04-24 21:06:20 +0000292
John McCall13a39c62012-08-01 05:04:58 +0000293 // If there's a virtual step, we can sometimes "devirtualize" it.
294 // For now, that's limited to when the derived type is final.
295 // TODO: "devirtualize" this for accesses to known-complete objects.
296 if (VBase && Derived->hasAttr<FinalAttr>()) {
297 const ASTRecordLayout &layout = getContext().getASTRecordLayout(Derived);
298 CharUnits vBaseOffset = layout.getVBaseClassOffset(VBase);
299 NonVirtualOffset += vBaseOffset;
Craig Topper8a13c412014-05-21 05:09:00 +0000300 VBase = nullptr; // we no longer have a virtual step
John McCall13a39c62012-08-01 05:04:58 +0000301 }
302
Anders Carlssond829a022010-04-24 21:06:20 +0000303 // Get the base pointer type.
Justin Bogner1cd11f12015-05-20 15:53:59 +0000304 llvm::Type *BasePtrTy =
Anastasia Stulova94049552019-03-07 16:23:15 +0000305 ConvertType((PathEnd[-1])->getType())
306 ->getPointerTo(Value.getType()->getPointerAddressSpace());
John McCall13a39c62012-08-01 05:04:58 +0000307
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000308 QualType DerivedTy = getContext().getRecordType(Derived);
John McCall7f416cc2015-09-08 08:05:57 +0000309 CharUnits DerivedAlign = CGM.getClassPointerAlignment(Derived);
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000310
John McCall13a39c62012-08-01 05:04:58 +0000311 // If the static offset is zero and we don't have a virtual step,
312 // just do a bitcast; null checks are unnecessary.
Ken Dycka1a4ae32011-03-22 00:53:26 +0000313 if (NonVirtualOffset.isZero() && !VBase) {
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000314 if (sanitizePerformTypeCheck()) {
Vedant Kumar18348ea2017-02-17 23:22:55 +0000315 SanitizerSet SkippedChecks;
316 SkippedChecks.set(SanitizerKind::Null, !NullCheckValue);
John McCall7f416cc2015-09-08 08:05:57 +0000317 EmitTypeCheck(TCK_Upcast, Loc, Value.getPointer(),
Vedant Kumar18348ea2017-02-17 23:22:55 +0000318 DerivedTy, DerivedAlign, SkippedChecks);
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000319 }
Anders Carlssond829a022010-04-24 21:06:20 +0000320 return Builder.CreateBitCast(Value, BasePtrTy);
Craig Topper8a13c412014-05-21 05:09:00 +0000321 }
John McCall13a39c62012-08-01 05:04:58 +0000322
Craig Topper8a13c412014-05-21 05:09:00 +0000323 llvm::BasicBlock *origBB = nullptr;
324 llvm::BasicBlock *endBB = nullptr;
325
John McCall13a39c62012-08-01 05:04:58 +0000326 // Skip over the offset (and the vtable load) if we're supposed to
327 // null-check the pointer.
Anders Carlssond829a022010-04-24 21:06:20 +0000328 if (NullCheckValue) {
John McCall13a39c62012-08-01 05:04:58 +0000329 origBB = Builder.GetInsertBlock();
330 llvm::BasicBlock *notNullBB = createBasicBlock("cast.notnull");
331 endBB = createBasicBlock("cast.end");
Justin Bogner1cd11f12015-05-20 15:53:59 +0000332
John McCall7f416cc2015-09-08 08:05:57 +0000333 llvm::Value *isNull = Builder.CreateIsNull(Value.getPointer());
John McCall13a39c62012-08-01 05:04:58 +0000334 Builder.CreateCondBr(isNull, endBB, notNullBB);
335 EmitBlock(notNullBB);
Anders Carlssond829a022010-04-24 21:06:20 +0000336 }
337
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000338 if (sanitizePerformTypeCheck()) {
Vedant Kumar18348ea2017-02-17 23:22:55 +0000339 SanitizerSet SkippedChecks;
340 SkippedChecks.set(SanitizerKind::Null, true);
John McCall7f416cc2015-09-08 08:05:57 +0000341 EmitTypeCheck(VBase ? TCK_UpcastToVirtualBase : TCK_Upcast, Loc,
Vedant Kumar18348ea2017-02-17 23:22:55 +0000342 Value.getPointer(), DerivedTy, DerivedAlign, SkippedChecks);
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000343 }
344
John McCall13a39c62012-08-01 05:04:58 +0000345 // Compute the virtual offset.
Craig Topper8a13c412014-05-21 05:09:00 +0000346 llvm::Value *VirtualOffset = nullptr;
Anders Carlssona376b532011-01-29 03:18:56 +0000347 if (VBase) {
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000348 VirtualOffset =
349 CGM.getCXXABI().GetVirtualBaseClassOffset(*this, Value, Derived, VBase);
Anders Carlssona376b532011-01-29 03:18:56 +0000350 }
Anders Carlssond829a022010-04-24 21:06:20 +0000351
John McCall13a39c62012-08-01 05:04:58 +0000352 // Apply both offsets.
John McCall7f416cc2015-09-08 08:05:57 +0000353 Value = ApplyNonVirtualAndVirtualOffset(*this, Value, NonVirtualOffset,
354 VirtualOffset, Derived, VBase);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000355
John McCall13a39c62012-08-01 05:04:58 +0000356 // Cast to the destination type.
Anders Carlssond829a022010-04-24 21:06:20 +0000357 Value = Builder.CreateBitCast(Value, BasePtrTy);
John McCall13a39c62012-08-01 05:04:58 +0000358
359 // Build a phi if we needed a null check.
Anders Carlssond829a022010-04-24 21:06:20 +0000360 if (NullCheckValue) {
John McCall13a39c62012-08-01 05:04:58 +0000361 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
362 Builder.CreateBr(endBB);
363 EmitBlock(endBB);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000364
John McCall13a39c62012-08-01 05:04:58 +0000365 llvm::PHINode *PHI = Builder.CreatePHI(BasePtrTy, 2, "cast.result");
John McCall7f416cc2015-09-08 08:05:57 +0000366 PHI->addIncoming(Value.getPointer(), notNullBB);
John McCall13a39c62012-08-01 05:04:58 +0000367 PHI->addIncoming(llvm::Constant::getNullValue(BasePtrTy), origBB);
John McCall7f416cc2015-09-08 08:05:57 +0000368 Value = Address(PHI, Value.getAlignment());
Anders Carlssond829a022010-04-24 21:06:20 +0000369 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000370
Anders Carlssond829a022010-04-24 21:06:20 +0000371 return Value;
372}
373
John McCall7f416cc2015-09-08 08:05:57 +0000374Address
375CodeGenFunction::GetAddressOfDerivedClass(Address BaseAddr,
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000376 const CXXRecordDecl *Derived,
John McCallcf142162010-08-07 06:22:56 +0000377 CastExpr::path_const_iterator PathBegin,
378 CastExpr::path_const_iterator PathEnd,
Anders Carlsson8c793172009-11-23 17:57:54 +0000379 bool NullCheckValue) {
John McCallcf142162010-08-07 06:22:56 +0000380 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlsson8a64c1c2010-04-24 21:23:59 +0000381
Anders Carlsson8c793172009-11-23 17:57:54 +0000382 QualType DerivedTy =
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000383 getContext().getCanonicalType(getContext().getTagDeclType(Derived));
Chris Lattner2192fe52011-07-18 04:24:23 +0000384 llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
Richard Smith2c5868c2013-02-13 21:18:23 +0000385
Anders Carlsson600f7372010-01-31 01:43:37 +0000386 llvm::Value *NonVirtualOffset =
John McCallcf142162010-08-07 06:22:56 +0000387 CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000388
Anders Carlsson600f7372010-01-31 01:43:37 +0000389 if (!NonVirtualOffset) {
390 // No offset, we can just cast back.
John McCall7f416cc2015-09-08 08:05:57 +0000391 return Builder.CreateBitCast(BaseAddr, DerivedPtrTy);
Anders Carlsson600f7372010-01-31 01:43:37 +0000392 }
Craig Topper8a13c412014-05-21 05:09:00 +0000393
394 llvm::BasicBlock *CastNull = nullptr;
395 llvm::BasicBlock *CastNotNull = nullptr;
396 llvm::BasicBlock *CastEnd = nullptr;
397
Anders Carlsson8c793172009-11-23 17:57:54 +0000398 if (NullCheckValue) {
399 CastNull = createBasicBlock("cast.null");
400 CastNotNull = createBasicBlock("cast.notnull");
401 CastEnd = createBasicBlock("cast.end");
Justin Bogner1cd11f12015-05-20 15:53:59 +0000402
John McCall7f416cc2015-09-08 08:05:57 +0000403 llvm::Value *IsNull = Builder.CreateIsNull(BaseAddr.getPointer());
Anders Carlsson8c793172009-11-23 17:57:54 +0000404 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
405 EmitBlock(CastNotNull);
406 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000407
Anders Carlsson600f7372010-01-31 01:43:37 +0000408 // Apply the offset.
John McCall7f416cc2015-09-08 08:05:57 +0000409 llvm::Value *Value = Builder.CreateBitCast(BaseAddr.getPointer(), Int8PtrTy);
Sanjay Patel372c3f12018-01-19 15:14:51 +0000410 Value = Builder.CreateInBoundsGEP(Value, Builder.CreateNeg(NonVirtualOffset),
411 "sub.ptr");
Anders Carlsson600f7372010-01-31 01:43:37 +0000412
413 // Just cast.
414 Value = Builder.CreateBitCast(Value, DerivedPtrTy);
Anders Carlsson8c793172009-11-23 17:57:54 +0000415
John McCall7f416cc2015-09-08 08:05:57 +0000416 // Produce a PHI if we had a null-check.
Anders Carlsson8c793172009-11-23 17:57:54 +0000417 if (NullCheckValue) {
418 Builder.CreateBr(CastEnd);
419 EmitBlock(CastNull);
420 Builder.CreateBr(CastEnd);
421 EmitBlock(CastEnd);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000422
Jay Foad20c0f022011-03-30 11:28:58 +0000423 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
Anders Carlsson8c793172009-11-23 17:57:54 +0000424 PHI->addIncoming(Value, CastNotNull);
John McCall7f416cc2015-09-08 08:05:57 +0000425 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
Anders Carlsson8c793172009-11-23 17:57:54 +0000426 Value = PHI;
427 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000428
John McCall7f416cc2015-09-08 08:05:57 +0000429 return Address(Value, CGM.getClassPointerAlignment(Derived));
Anders Carlsson9a57c5a2009-09-12 04:27:24 +0000430}
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000431
432llvm::Value *CodeGenFunction::GetVTTParameter(GlobalDecl GD,
433 bool ForVirtualBase,
434 bool Delegating) {
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000435 if (!CGM.getCXXABI().NeedsVTTParameter(GD)) {
Anders Carlssone36a6b32010-01-02 01:01:18 +0000436 // This constructor/destructor does not need a VTT parameter.
Craig Topper8a13c412014-05-21 05:09:00 +0000437 return nullptr;
Anders Carlssone36a6b32010-01-02 01:01:18 +0000438 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000439
John McCalldec348f72013-05-03 07:33:41 +0000440 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CurCodeDecl)->getParent();
Anders Carlssone36a6b32010-01-02 01:01:18 +0000441 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
John McCall5c60a6f2010-02-18 19:59:28 +0000442
Anders Carlssone36a6b32010-01-02 01:01:18 +0000443 llvm::Value *VTT;
444
John McCall5c60a6f2010-02-18 19:59:28 +0000445 uint64_t SubVTTIndex;
446
Douglas Gregor61535002013-01-31 05:50:40 +0000447 if (Delegating) {
448 // If this is a delegating constructor call, just load the VTT.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000449 return LoadCXXVTT();
Douglas Gregor61535002013-01-31 05:50:40 +0000450 } else if (RD == Base) {
451 // If the record matches the base, this is the complete ctor/dtor
452 // variant calling the base variant in a class with virtual bases.
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000453 assert(!CGM.getCXXABI().NeedsVTTParameter(CurGD) &&
John McCall5c60a6f2010-02-18 19:59:28 +0000454 "doing no-op VTT offset in base dtor/ctor?");
Anders Carlsson4d205ba2010-05-02 23:33:10 +0000455 assert(!ForVirtualBase && "Can't have same class as virtual base!");
John McCall5c60a6f2010-02-18 19:59:28 +0000456 SubVTTIndex = 0;
457 } else {
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000458 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000459 CharUnits BaseOffset = ForVirtualBase ?
460 Layout.getVBaseClassOffset(Base) :
Ken Dyck16ffcac2011-03-24 01:21:01 +0000461 Layout.getBaseClassOffset(Base);
Anders Carlsson859b3062010-05-02 23:53:25 +0000462
Justin Bogner1cd11f12015-05-20 15:53:59 +0000463 SubVTTIndex =
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000464 CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
John McCall5c60a6f2010-02-18 19:59:28 +0000465 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
466 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000467
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000468 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
Anders Carlssone36a6b32010-01-02 01:01:18 +0000469 // A VTT parameter was passed to the constructor, use it.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000470 VTT = LoadCXXVTT();
471 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
Anders Carlssone36a6b32010-01-02 01:01:18 +0000472 } else {
473 // We're the complete constructor, so get the VTT by name.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000474 VTT = CGM.getVTables().GetAddrOfVTT(RD);
475 VTT = Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
Anders Carlssone36a6b32010-01-02 01:01:18 +0000476 }
477
478 return VTT;
479}
480
John McCall1d987562010-07-21 01:23:41 +0000481namespace {
John McCallf99a6312010-07-21 05:30:47 +0000482 /// Call the destructor for a direct base class.
David Blaikie7e70d682015-08-18 22:40:54 +0000483 struct CallBaseDtor final : EHScopeStack::Cleanup {
John McCallf99a6312010-07-21 05:30:47 +0000484 const CXXRecordDecl *BaseClass;
485 bool BaseIsVirtual;
486 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
487 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
John McCall1d987562010-07-21 01:23:41 +0000488
Craig Topper4f12f102014-03-12 06:41:41 +0000489 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallf99a6312010-07-21 05:30:47 +0000490 const CXXRecordDecl *DerivedClass =
491 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
492
493 const CXXDestructorDecl *D = BaseClass->getDestructor();
Marco Antognini88559632019-07-22 09:39:13 +0000494 // We are already inside a destructor, so presumably the object being
495 // destroyed should have the expected type.
496 QualType ThisTy = D->getThisObjectType();
John McCall7f416cc2015-09-08 08:05:57 +0000497 Address Addr =
498 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThisAddress(),
John McCallf99a6312010-07-21 05:30:47 +0000499 DerivedClass, BaseClass,
500 BaseIsVirtual);
Douglas Gregor61535002013-01-31 05:50:40 +0000501 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual,
Marco Antognini88559632019-07-22 09:39:13 +0000502 /*Delegating=*/false, Addr, ThisTy);
John McCall1d987562010-07-21 01:23:41 +0000503 }
504 };
John McCall769250e2010-09-17 02:31:44 +0000505
506 /// A visitor which checks whether an initializer uses 'this' in a
507 /// way which requires the vtable to be properly set.
Scott Douglass503fc392015-06-10 13:53:15 +0000508 struct DynamicThisUseChecker : ConstEvaluatedExprVisitor<DynamicThisUseChecker> {
509 typedef ConstEvaluatedExprVisitor<DynamicThisUseChecker> super;
John McCall769250e2010-09-17 02:31:44 +0000510
511 bool UsesThis;
512
Scott Douglass503fc392015-06-10 13:53:15 +0000513 DynamicThisUseChecker(const ASTContext &C) : super(C), UsesThis(false) {}
John McCall769250e2010-09-17 02:31:44 +0000514
515 // Black-list all explicit and implicit references to 'this'.
516 //
517 // Do we need to worry about external references to 'this' derived
518 // from arbitrary code? If so, then anything which runs arbitrary
519 // external code might potentially access the vtable.
Scott Douglass503fc392015-06-10 13:53:15 +0000520 void VisitCXXThisExpr(const CXXThisExpr *E) { UsesThis = true; }
John McCall769250e2010-09-17 02:31:44 +0000521 };
Hans Wennborgdcfba332015-10-06 23:40:43 +0000522} // end anonymous namespace
John McCall769250e2010-09-17 02:31:44 +0000523
524static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
525 DynamicThisUseChecker Checker(C);
Scott Douglass503fc392015-06-10 13:53:15 +0000526 Checker.Visit(Init);
John McCall769250e2010-09-17 02:31:44 +0000527 return Checker.UsesThis;
John McCall1d987562010-07-21 01:23:41 +0000528}
529
Justin Bogner1cd11f12015-05-20 15:53:59 +0000530static void EmitBaseInitializer(CodeGenFunction &CGF,
Anders Carlssonfb404882009-12-24 22:46:43 +0000531 const CXXRecordDecl *ClassDecl,
Reid Kleckner61c9b7c2019-03-18 22:41:50 +0000532 CXXCtorInitializer *BaseInit) {
Anders Carlssonfb404882009-12-24 22:46:43 +0000533 assert(BaseInit->isBaseInitializer() &&
534 "Must have base initializer!");
535
John McCall7f416cc2015-09-08 08:05:57 +0000536 Address ThisPtr = CGF.LoadCXXThisAddress();
Justin Bogner1cd11f12015-05-20 15:53:59 +0000537
Anders Carlssonfb404882009-12-24 22:46:43 +0000538 const Type *BaseType = BaseInit->getBaseClass();
Simon Pilgrim1cd399c2019-10-03 11:22:48 +0000539 const auto *BaseClassDecl =
540 cast<CXXRecordDecl>(BaseType->castAs<RecordType>()->getDecl());
Anders Carlssonfb404882009-12-24 22:46:43 +0000541
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +0000542 bool isBaseVirtual = BaseInit->isBaseVirtual();
Anders Carlssonfb404882009-12-24 22:46:43 +0000543
John McCall769250e2010-09-17 02:31:44 +0000544 // If the initializer for the base (other than the constructor
545 // itself) accesses 'this' in any way, we need to initialize the
546 // vtables.
547 if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
548 CGF.InitializeVTablePointers(ClassDecl);
549
John McCall6ce74722010-02-16 04:15:37 +0000550 // We can pretend to be a complete class because it only matters for
551 // virtual bases, and we only do virtual bases for complete ctors.
John McCall7f416cc2015-09-08 08:05:57 +0000552 Address V =
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000553 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
John McCallf99a6312010-07-21 05:30:47 +0000554 BaseClassDecl,
555 isBaseVirtual);
John McCall8d6fc952011-08-25 20:40:09 +0000556 AggValueSlot AggSlot =
Richard Smithe78fac52018-04-05 20:52:58 +0000557 AggValueSlot::forAddr(
558 V, Qualifiers(),
559 AggValueSlot::IsDestructed,
560 AggValueSlot::DoesNotNeedGCBarriers,
561 AggValueSlot::IsNotAliased,
Richard Smith8cca3a52019-06-20 20:56:20 +0000562 CGF.getOverlapForBaseInit(ClassDecl, BaseClassDecl, isBaseVirtual));
John McCall7a626f62010-09-15 10:14:12 +0000563
564 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000565
566 if (CGF.CGM.getLangOpts().Exceptions &&
Anders Carlsson08ce5ed2011-02-20 00:20:27 +0000567 !BaseClassDecl->hasTrivialDestructor())
John McCallcda666c2010-07-21 07:22:38 +0000568 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
569 isBaseVirtual);
Anders Carlssonfb404882009-12-24 22:46:43 +0000570}
571
Richard Smith419bd092015-04-29 19:26:57 +0000572static bool isMemcpyEquivalentSpecialMember(const CXXMethodDecl *D) {
573 auto *CD = dyn_cast<CXXConstructorDecl>(D);
574 if (!(CD && CD->isCopyOrMoveConstructor()) &&
575 !D->isCopyAssignmentOperator() && !D->isMoveAssignmentOperator())
576 return false;
577
578 // We can emit a memcpy for a trivial copy or move constructor/assignment.
579 if (D->isTrivial() && !D->getParent()->mayInsertExtraPadding())
580 return true;
581
582 // We *must* emit a memcpy for a defaulted union copy or move op.
583 if (D->getParent()->isUnion() && D->isDefaulted())
584 return true;
585
586 return false;
587}
588
Alexey Bataev152c71f2015-07-14 07:55:48 +0000589static void EmitLValueForAnyFieldInitialization(CodeGenFunction &CGF,
590 CXXCtorInitializer *MemberInit,
591 LValue &LHS) {
592 FieldDecl *Field = MemberInit->getAnyMember();
593 if (MemberInit->isIndirectMemberInitializer()) {
594 // If we are initializing an anonymous union field, drill down to the field.
595 IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember();
596 for (const auto *I : IndirectField->chain())
597 LHS = CGF.EmitLValueForFieldInitialization(LHS, cast<FieldDecl>(I));
598 } else {
599 LHS = CGF.EmitLValueForFieldInitialization(LHS, Field);
600 }
601}
602
Anders Carlssonfb404882009-12-24 22:46:43 +0000603static void EmitMemberInitializer(CodeGenFunction &CGF,
604 const CXXRecordDecl *ClassDecl,
Alexis Hunt1d792652011-01-08 20:30:50 +0000605 CXXCtorInitializer *MemberInit,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000606 const CXXConstructorDecl *Constructor,
607 FunctionArgList &Args) {
David Blaikiea81d4102015-01-18 00:12:58 +0000608 ApplyDebugLocation Loc(CGF, MemberInit->getSourceLocation());
Francois Pichetd583da02010-12-04 09:14:42 +0000609 assert(MemberInit->isAnyMemberInitializer() &&
Anders Carlssonfb404882009-12-24 22:46:43 +0000610 "Must have member initializer!");
Richard Smith938f40b2011-06-11 17:19:42 +0000611 assert(MemberInit->getInit() && "Must have initializer!");
Justin Bogner1cd11f12015-05-20 15:53:59 +0000612
Anders Carlssonfb404882009-12-24 22:46:43 +0000613 // non-static data member initializers.
Francois Pichetd583da02010-12-04 09:14:42 +0000614 FieldDecl *Field = MemberInit->getAnyMember();
Eli Friedman6ae63022012-02-14 02:15:49 +0000615 QualType FieldType = Field->getType();
Anders Carlssonfb404882009-12-24 22:46:43 +0000616
617 llvm::Value *ThisPtr = CGF.LoadCXXThis();
Eli Friedman7f1ff602012-04-16 03:54:45 +0000618 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
Akira Hatanakae5dbb642018-01-27 00:34:09 +0000619 LValue LHS;
620
621 // If a base constructor is being emitted, create an LValue that has the
622 // non-virtual alignment.
623 if (CGF.CurGD.getCtorType() == Ctor_Base)
624 LHS = CGF.MakeNaturalAlignPointeeAddrLValue(ThisPtr, RecordTy);
625 else
626 LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
Eli Friedman7f1ff602012-04-16 03:54:45 +0000627
Alexey Bataev152c71f2015-07-14 07:55:48 +0000628 EmitLValueForAnyFieldInitialization(CGF, MemberInit, LHS);
Anders Carlssonfb404882009-12-24 22:46:43 +0000629
Eli Friedman6ae63022012-02-14 02:15:49 +0000630 // Special case: if we are in a copy or move constructor, and we are copying
631 // an array of PODs or classes with trivial copy constructors, ignore the
632 // AST and perform the copy we know is equivalent.
633 // FIXME: This is hacky at best... if we had a bit more explicit information
634 // in the AST, we could generalize it more easily.
635 const ConstantArrayType *Array
636 = CGF.getContext().getAsConstantArrayType(FieldType);
Jordan Rose54533f72013-08-07 16:16:48 +0000637 if (Array && Constructor->isDefaulted() &&
Eli Friedman6ae63022012-02-14 02:15:49 +0000638 Constructor->isCopyOrMoveConstructor()) {
639 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
Richard Smith993f25a2012-11-07 23:56:21 +0000640 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
Eli Friedman6ae63022012-02-14 02:15:49 +0000641 if (BaseElementTy.isPODType(CGF.getContext()) ||
Richard Smith419bd092015-04-29 19:26:57 +0000642 (CE && isMemcpyEquivalentSpecialMember(CE->getConstructor()))) {
David Majnemer1573d732014-10-15 04:54:54 +0000643 unsigned SrcArgIndex =
644 CGF.CGM.getCXXABI().getSrcArgforCopyCtor(Constructor, Args);
Eli Friedman6ae63022012-02-14 02:15:49 +0000645 llvm::Value *SrcPtr
646 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
Eli Friedman7f1ff602012-04-16 03:54:45 +0000647 LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
648 LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000649
Eli Friedman6ae63022012-02-14 02:15:49 +0000650 // Copy the aggregate.
Richard Smith8cca3a52019-06-20 20:56:20 +0000651 CGF.EmitAggregateCopy(LHS, Src, FieldType, CGF.getOverlapForFieldInit(Field),
Richard Smithe78fac52018-04-05 20:52:58 +0000652 LHS.isVolatileQualified());
Alexey Bataev5d49b832015-07-08 07:31:02 +0000653 // Ensure that we destroy the objects if an exception is thrown later in
654 // the constructor.
655 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
656 if (CGF.needsEHCleanup(dtorKind))
Fangrui Song6907ce22018-07-30 19:24:48 +0000657 CGF.pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
Eli Friedman6ae63022012-02-14 02:15:49 +0000658 return;
659 }
660 }
661
Richard Smith30e304e2016-12-14 00:03:17 +0000662 CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit());
Eli Friedman6ae63022012-02-14 02:15:49 +0000663}
664
John McCall7f416cc2015-09-08 08:05:57 +0000665void CodeGenFunction::EmitInitializerForField(FieldDecl *Field, LValue LHS,
Richard Smith30e304e2016-12-14 00:03:17 +0000666 Expr *Init) {
Eli Friedman6ae63022012-02-14 02:15:49 +0000667 QualType FieldType = Field->getType();
John McCall47fb9502013-03-07 21:37:08 +0000668 switch (getEvaluationKind(FieldType)) {
669 case TEK_Scalar:
John McCall31168b02011-06-15 23:02:42 +0000670 if (LHS.isSimple()) {
David Blaikie66e41972015-01-14 07:38:27 +0000671 EmitExprAsInit(Init, Field, LHS, false);
John McCall31168b02011-06-15 23:02:42 +0000672 } else {
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000673 RValue RHS = RValue::get(EmitScalarExpr(Init));
674 EmitStoreThroughLValue(RHS, LHS);
John McCall31168b02011-06-15 23:02:42 +0000675 }
John McCall47fb9502013-03-07 21:37:08 +0000676 break;
677 case TEK_Complex:
David Blaikie66e41972015-01-14 07:38:27 +0000678 EmitComplexExprIntoLValue(Init, LHS, /*isInit*/ true);
John McCall47fb9502013-03-07 21:37:08 +0000679 break;
680 case TEK_Aggregate: {
Richard Smith30e304e2016-12-14 00:03:17 +0000681 AggValueSlot Slot =
Richard Smithe78fac52018-04-05 20:52:58 +0000682 AggValueSlot::forLValue(
683 LHS,
684 AggValueSlot::IsDestructed,
685 AggValueSlot::DoesNotNeedGCBarriers,
686 AggValueSlot::IsNotAliased,
Richard Smith8cca3a52019-06-20 20:56:20 +0000687 getOverlapForFieldInit(Field),
Serge Pavlov37605182018-07-28 15:33:03 +0000688 AggValueSlot::IsNotZeroed,
689 // Checks are made by the code that calls constructor.
690 AggValueSlot::IsSanitizerChecked);
Richard Smith30e304e2016-12-14 00:03:17 +0000691 EmitAggExpr(Init, Slot);
692 break;
Anders Carlssonfb404882009-12-24 22:46:43 +0000693 }
John McCall47fb9502013-03-07 21:37:08 +0000694 }
John McCall12cc42a2013-02-01 05:11:40 +0000695
696 // Ensure that we destroy this object if an exception is thrown
697 // later in the constructor.
698 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
699 if (needsEHCleanup(dtorKind))
700 pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
Anders Carlssonfb404882009-12-24 22:46:43 +0000701}
702
John McCallf8ff7b92010-02-23 00:48:20 +0000703/// Checks whether the given constructor is a valid subject for the
704/// complete-to-base constructor delegation optimization, i.e.
705/// emitting the complete constructor as a simple call to the base
706/// constructor.
Vedant Kumar7f809b22017-02-24 01:15:19 +0000707bool CodeGenFunction::IsConstructorDelegationValid(
708 const CXXConstructorDecl *Ctor) {
John McCallf8ff7b92010-02-23 00:48:20 +0000709
710 // Currently we disable the optimization for classes with virtual
711 // bases because (1) the addresses of parameter variables need to be
712 // consistent across all initializers but (2) the delegate function
713 // call necessarily creates a second copy of the parameter variable.
714 //
715 // The limiting example (purely theoretical AFAIK):
716 // struct A { A(int &c) { c++; } };
717 // struct B : virtual A {
718 // B(int count) : A(count) { printf("%d\n", count); }
719 // };
720 // ...although even this example could in principle be emitted as a
721 // delegation since the address of the parameter doesn't escape.
722 if (Ctor->getParent()->getNumVBases()) {
723 // TODO: white-list trivial vbase initializers. This case wouldn't
724 // be subject to the restrictions below.
725
726 // TODO: white-list cases where:
727 // - there are no non-reference parameters to the constructor
728 // - the initializers don't access any non-reference parameters
729 // - the initializers don't take the address of non-reference
730 // parameters
731 // - etc.
732 // If we ever add any of the above cases, remember that:
733 // - function-try-blocks will always blacklist this optimization
734 // - we need to perform the constructor prologue and cleanup in
735 // EmitConstructorBody.
736
737 return false;
738 }
739
740 // We also disable the optimization for variadic functions because
741 // it's impossible to "re-pass" varargs.
742 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
743 return false;
744
Alexis Hunt61bc1732011-05-01 07:04:31 +0000745 // FIXME: Decide if we can do a delegation of a delegating constructor.
746 if (Ctor->isDelegatingConstructor())
747 return false;
748
John McCallf8ff7b92010-02-23 00:48:20 +0000749 return true;
750}
751
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000752// Emit code in ctor (Prologue==true) or dtor (Prologue==false)
753// to poison the extra field paddings inserted under
754// -fsanitize-address-field-padding=1|2.
755void CodeGenFunction::EmitAsanPrologueOrEpilogue(bool Prologue) {
756 ASTContext &Context = getContext();
757 const CXXRecordDecl *ClassDecl =
758 Prologue ? cast<CXXConstructorDecl>(CurGD.getDecl())->getParent()
759 : cast<CXXDestructorDecl>(CurGD.getDecl())->getParent();
760 if (!ClassDecl->mayInsertExtraPadding()) return;
761
762 struct SizeAndOffset {
763 uint64_t Size;
764 uint64_t Offset;
765 };
766
767 unsigned PtrSize = CGM.getDataLayout().getPointerSizeInBits();
768 const ASTRecordLayout &Info = Context.getASTRecordLayout(ClassDecl);
769
770 // Populate sizes and offsets of fields.
771 SmallVector<SizeAndOffset, 16> SSV(Info.getFieldCount());
772 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i)
773 SSV[i].Offset =
774 Context.toCharUnitsFromBits(Info.getFieldOffset(i)).getQuantity();
775
776 size_t NumFields = 0;
777 for (const auto *Field : ClassDecl->fields()) {
778 const FieldDecl *D = Field;
779 std::pair<CharUnits, CharUnits> FieldInfo =
780 Context.getTypeInfoInChars(D->getType());
781 CharUnits FieldSize = FieldInfo.first;
782 assert(NumFields < SSV.size());
783 SSV[NumFields].Size = D->isBitField() ? 0 : FieldSize.getQuantity();
784 NumFields++;
785 }
786 assert(NumFields == SSV.size());
787 if (SSV.size() <= 1) return;
788
789 // We will insert calls to __asan_* run-time functions.
790 // LLVM AddressSanitizer pass may decide to inline them later.
791 llvm::Type *Args[2] = {IntPtrTy, IntPtrTy};
792 llvm::FunctionType *FTy =
793 llvm::FunctionType::get(CGM.VoidTy, Args, false);
James Y Knight9871db02019-02-05 16:42:33 +0000794 llvm::FunctionCallee F = CGM.CreateRuntimeFunction(
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000795 FTy, Prologue ? "__asan_poison_intra_object_redzone"
796 : "__asan_unpoison_intra_object_redzone");
797
798 llvm::Value *ThisPtr = LoadCXXThis();
799 ThisPtr = Builder.CreatePtrToInt(ThisPtr, IntPtrTy);
Kostya Serebryany64449212014-10-17 21:02:13 +0000800 uint64_t TypeSize = Info.getNonVirtualSize().getQuantity();
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000801 // For each field check if it has sufficient padding,
802 // if so (un)poison it with a call.
803 for (size_t i = 0; i < SSV.size(); i++) {
804 uint64_t AsanAlignment = 8;
805 uint64_t NextField = i == SSV.size() - 1 ? TypeSize : SSV[i + 1].Offset;
806 uint64_t PoisonSize = NextField - SSV[i].Offset - SSV[i].Size;
807 uint64_t EndOffset = SSV[i].Offset + SSV[i].Size;
808 if (PoisonSize < AsanAlignment || !SSV[i].Size ||
809 (NextField % AsanAlignment) != 0)
810 continue;
David Blaikie43f9bb72015-05-18 22:14:03 +0000811 Builder.CreateCall(
812 F, {Builder.CreateAdd(ThisPtr, Builder.getIntN(PtrSize, EndOffset)),
813 Builder.getIntN(PtrSize, PoisonSize)});
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000814 }
815}
816
John McCallb81884d2010-02-19 09:25:03 +0000817/// EmitConstructorBody - Emits the body of the current constructor.
818void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000819 EmitAsanPrologueOrEpilogue(true);
John McCallb81884d2010-02-19 09:25:03 +0000820 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
821 CXXCtorType CtorType = CurGD.getCtorType();
822
Reid Kleckner340ad862014-01-13 22:57:31 +0000823 assert((CGM.getTarget().getCXXABI().hasConstructorVariants() ||
824 CtorType == Ctor_Complete) &&
825 "can only generate complete ctor for this ABI");
826
John McCallf8ff7b92010-02-23 00:48:20 +0000827 // Before we go any further, try the complete->base constructor
828 // delegation optimization.
Timur Iskhodzhanovf32a3772012-04-20 08:05:00 +0000829 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
John McCallc8e01702013-04-16 22:48:15 +0000830 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000831 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args, Ctor->getEndLoc());
John McCallf8ff7b92010-02-23 00:48:20 +0000832 return;
833 }
834
Hans Wennborgdcfba332015-10-06 23:40:43 +0000835 const FunctionDecl *Definition = nullptr;
Richard Smith46bb5812014-08-01 01:56:39 +0000836 Stmt *Body = Ctor->getBody(Definition);
837 assert(Definition == Ctor && "emitting wrong constructor body");
John McCallb81884d2010-02-19 09:25:03 +0000838
John McCallf8ff7b92010-02-23 00:48:20 +0000839 // Enter the function-try-block before the constructor prologue if
840 // applicable.
John McCallf8ff7b92010-02-23 00:48:20 +0000841 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallf8ff7b92010-02-23 00:48:20 +0000842 if (IsTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000843 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000844
Justin Bogner66242d62015-04-23 23:06:47 +0000845 incrementProfileCounter(Body);
Justin Bogner81c22c22014-01-23 02:54:27 +0000846
Richard Smithcc1b96d2013-06-12 22:31:48 +0000847 RunCleanupsScope RunCleanups(*this);
John McCallb81884d2010-02-19 09:25:03 +0000848
John McCall88313032012-03-30 04:25:03 +0000849 // TODO: in restricted cases, we can emit the vbase initializers of
850 // a complete ctor and then delegate to the base ctor.
851
John McCallf8ff7b92010-02-23 00:48:20 +0000852 // Emit the constructor prologue, i.e. the base and member
853 // initializers.
Douglas Gregor94f9a482010-05-05 05:51:00 +0000854 EmitCtorPrologue(Ctor, CtorType, Args);
John McCallb81884d2010-02-19 09:25:03 +0000855
856 // Emit the body of the statement.
John McCallf8ff7b92010-02-23 00:48:20 +0000857 if (IsTryBody)
John McCallb81884d2010-02-19 09:25:03 +0000858 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
859 else if (Body)
860 EmitStmt(Body);
John McCallb81884d2010-02-19 09:25:03 +0000861
862 // Emit any cleanup blocks associated with the member or base
863 // initializers, which includes (along the exceptional path) the
864 // destructors for those members and bases that were fully
865 // constructed.
Richard Smithcc1b96d2013-06-12 22:31:48 +0000866 RunCleanups.ForceCleanup();
John McCallb81884d2010-02-19 09:25:03 +0000867
John McCallf8ff7b92010-02-23 00:48:20 +0000868 if (IsTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000869 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000870}
871
Lang Hamesbf122742013-02-17 07:22:09 +0000872namespace {
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000873 /// RAII object to indicate that codegen is copying the value representation
874 /// instead of the object representation. Useful when copying a struct or
875 /// class which has uninitialized members and we're only performing
876 /// lvalue-to-rvalue conversion on the object but not its members.
877 class CopyingValueRepresentation {
878 public:
879 explicit CopyingValueRepresentation(CodeGenFunction &CGF)
Alexey Samsonov035462c2014-10-30 19:33:44 +0000880 : CGF(CGF), OldSanOpts(CGF.SanOpts) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000881 CGF.SanOpts.set(SanitizerKind::Bool, false);
882 CGF.SanOpts.set(SanitizerKind::Enum, false);
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000883 }
884 ~CopyingValueRepresentation() {
885 CGF.SanOpts = OldSanOpts;
886 }
887 private:
888 CodeGenFunction &CGF;
Alexey Samsonova0416102014-11-11 01:26:14 +0000889 SanitizerSet OldSanOpts;
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000890 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000891} // end anonymous namespace
Fangrui Song6907ce22018-07-30 19:24:48 +0000892
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000893namespace {
Lang Hamesbf122742013-02-17 07:22:09 +0000894 class FieldMemcpyizer {
895 public:
896 FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl,
897 const VarDecl *SrcRec)
Justin Bogner1cd11f12015-05-20 15:53:59 +0000898 : CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec),
Lang Hamesbf122742013-02-17 07:22:09 +0000899 RecLayout(CGF.getContext().getASTRecordLayout(ClassDecl)),
Craig Topper8a13c412014-05-21 05:09:00 +0000900 FirstField(nullptr), LastField(nullptr), FirstFieldOffset(0),
901 LastFieldOffset(0), LastAddedFieldIndex(0) {}
Lang Hamesbf122742013-02-17 07:22:09 +0000902
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000903 bool isMemcpyableField(FieldDecl *F) const {
904 // Never memcpy fields when we are adding poisoned paddings.
Alexey Samsonova0416102014-11-11 01:26:14 +0000905 if (CGF.getContext().getLangOpts().SanitizeAddressFieldPadding)
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000906 return false;
Lang Hamesbf122742013-02-17 07:22:09 +0000907 Qualifiers Qual = F->getType().getQualifiers();
908 if (Qual.hasVolatile() || Qual.hasObjCLifetime())
909 return false;
910 return true;
911 }
912
913 void addMemcpyableField(FieldDecl *F) {
Craig Topper8a13c412014-05-21 05:09:00 +0000914 if (!FirstField)
Lang Hamesbf122742013-02-17 07:22:09 +0000915 addInitialField(F);
916 else
917 addNextField(F);
918 }
919
David Majnemera586eb22014-10-10 18:57:10 +0000920 CharUnits getMemcpySize(uint64_t FirstByteOffset) const {
Richard Smithe78fac52018-04-05 20:52:58 +0000921 ASTContext &Ctx = CGF.getContext();
Lang Hamesbf122742013-02-17 07:22:09 +0000922 unsigned LastFieldSize =
Richard Smithe78fac52018-04-05 20:52:58 +0000923 LastField->isBitField()
924 ? LastField->getBitWidthValue(Ctx)
925 : Ctx.toBits(
926 Ctx.getTypeInfoDataSizeInChars(LastField->getType()).first);
927 uint64_t MemcpySizeBits = LastFieldOffset + LastFieldSize -
928 FirstByteOffset + Ctx.getCharWidth() - 1;
929 CharUnits MemcpySize = Ctx.toCharUnitsFromBits(MemcpySizeBits);
Lang Hamesbf122742013-02-17 07:22:09 +0000930 return MemcpySize;
931 }
932
933 void emitMemcpy() {
934 // Give the subclass a chance to bail out if it feels the memcpy isn't
935 // worth it (e.g. Hasn't aggregated enough data).
Craig Topper8a13c412014-05-21 05:09:00 +0000936 if (!FirstField) {
Lang Hamesbf122742013-02-17 07:22:09 +0000937 return;
938 }
939
David Majnemera586eb22014-10-10 18:57:10 +0000940 uint64_t FirstByteOffset;
Lang Hamesbf122742013-02-17 07:22:09 +0000941 if (FirstField->isBitField()) {
942 const CGRecordLayout &RL =
943 CGF.getTypes().getCGRecordLayout(FirstField->getParent());
944 const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField);
David Majnemera586eb22014-10-10 18:57:10 +0000945 // FirstFieldOffset is not appropriate for bitfields,
Ulrich Weigand73263d72015-07-13 11:52:14 +0000946 // we need to use the storage offset instead.
Ulrich Weigand03ce2a12015-07-10 17:30:00 +0000947 FirstByteOffset = CGF.getContext().toBits(BFInfo.StorageOffset);
Lang Hames1694e0d2013-02-27 04:14:49 +0000948 } else {
David Majnemera586eb22014-10-10 18:57:10 +0000949 FirstByteOffset = FirstFieldOffset;
Lang Hames1694e0d2013-02-27 04:14:49 +0000950 }
Lang Hamesbf122742013-02-17 07:22:09 +0000951
David Majnemera586eb22014-10-10 18:57:10 +0000952 CharUnits MemcpySize = getMemcpySize(FirstByteOffset);
Lang Hamesbf122742013-02-17 07:22:09 +0000953 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
John McCall7f416cc2015-09-08 08:05:57 +0000954 Address ThisPtr = CGF.LoadCXXThisAddress();
955 LValue DestLV = CGF.MakeAddrLValue(ThisPtr, RecordTy);
Lang Hamesbf122742013-02-17 07:22:09 +0000956 LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField);
957 llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec));
958 LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
959 LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField);
960
John McCall7f416cc2015-09-08 08:05:57 +0000961 emitMemcpyIR(Dest.isBitField() ? Dest.getBitFieldAddress() : Dest.getAddress(),
962 Src.isBitField() ? Src.getBitFieldAddress() : Src.getAddress(),
963 MemcpySize);
Lang Hamesbf122742013-02-17 07:22:09 +0000964 reset();
965 }
966
967 void reset() {
Craig Topper8a13c412014-05-21 05:09:00 +0000968 FirstField = nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +0000969 }
970
971 protected:
972 CodeGenFunction &CGF;
973 const CXXRecordDecl *ClassDecl;
974
975 private:
John McCall7f416cc2015-09-08 08:05:57 +0000976 void emitMemcpyIR(Address DestPtr, Address SrcPtr, CharUnits Size) {
977 llvm::PointerType *DPT = DestPtr.getType();
Lang Hamesbf122742013-02-17 07:22:09 +0000978 llvm::Type *DBP =
979 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), DPT->getAddressSpace());
980 DestPtr = CGF.Builder.CreateBitCast(DestPtr, DBP);
981
John McCall7f416cc2015-09-08 08:05:57 +0000982 llvm::PointerType *SPT = SrcPtr.getType();
Lang Hamesbf122742013-02-17 07:22:09 +0000983 llvm::Type *SBP =
984 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), SPT->getAddressSpace());
985 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, SBP);
986
John McCall7f416cc2015-09-08 08:05:57 +0000987 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity());
Lang Hamesbf122742013-02-17 07:22:09 +0000988 }
989
990 void addInitialField(FieldDecl *F) {
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000991 FirstField = F;
992 LastField = F;
993 FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex());
994 LastFieldOffset = FirstFieldOffset;
995 LastAddedFieldIndex = F->getFieldIndex();
996 }
Lang Hamesbf122742013-02-17 07:22:09 +0000997
998 void addNextField(FieldDecl *F) {
John McCall6054d5a2013-05-07 05:20:46 +0000999 // For the most part, the following invariant will hold:
1000 // F->getFieldIndex() == LastAddedFieldIndex + 1
1001 // The one exception is that Sema won't add a copy-initializer for an
1002 // unnamed bitfield, which will show up here as a gap in the sequence.
1003 assert(F->getFieldIndex() >= LastAddedFieldIndex + 1 &&
1004 "Cannot aggregate fields out of order.");
Lang Hamesbf122742013-02-17 07:22:09 +00001005 LastAddedFieldIndex = F->getFieldIndex();
1006
1007 // The 'first' and 'last' fields are chosen by offset, rather than field
1008 // index. This allows the code to support bitfields, as well as regular
1009 // fields.
1010 uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex());
1011 if (FOffset < FirstFieldOffset) {
1012 FirstField = F;
1013 FirstFieldOffset = FOffset;
John McCall7ae29f52019-04-10 18:07:18 +00001014 } else if (FOffset >= LastFieldOffset) {
Lang Hamesbf122742013-02-17 07:22:09 +00001015 LastField = F;
1016 LastFieldOffset = FOffset;
1017 }
1018 }
1019
1020 const VarDecl *SrcRec;
1021 const ASTRecordLayout &RecLayout;
1022 FieldDecl *FirstField;
1023 FieldDecl *LastField;
1024 uint64_t FirstFieldOffset, LastFieldOffset;
1025 unsigned LastAddedFieldIndex;
1026 };
1027
1028 class ConstructorMemcpyizer : public FieldMemcpyizer {
1029 private:
Lang Hamesbf122742013-02-17 07:22:09 +00001030 /// Get source argument for copy constructor. Returns null if not a copy
David Majnemer196ac332014-09-11 23:05:02 +00001031 /// constructor.
1032 static const VarDecl *getTrivialCopySource(CodeGenFunction &CGF,
1033 const CXXConstructorDecl *CD,
Lang Hamesbf122742013-02-17 07:22:09 +00001034 FunctionArgList &Args) {
Jordan Rose54533f72013-08-07 16:16:48 +00001035 if (CD->isCopyOrMoveConstructor() && CD->isDefaulted())
David Majnemer196ac332014-09-11 23:05:02 +00001036 return Args[CGF.CGM.getCXXABI().getSrcArgforCopyCtor(CD, Args)];
Craig Topper8a13c412014-05-21 05:09:00 +00001037 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001038 }
1039
1040 // Returns true if a CXXCtorInitializer represents a member initialization
1041 // that can be rolled into a memcpy.
1042 bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const {
1043 if (!MemcpyableCtor)
1044 return false;
1045 FieldDecl *Field = MemberInit->getMember();
Craig Topper8a13c412014-05-21 05:09:00 +00001046 assert(Field && "No field for member init.");
Lang Hamesbf122742013-02-17 07:22:09 +00001047 QualType FieldType = Field->getType();
1048 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
1049
Richard Smith419bd092015-04-29 19:26:57 +00001050 // Bail out on non-memcpyable, not-trivially-copyable members.
1051 if (!(CE && isMemcpyEquivalentSpecialMember(CE->getConstructor())) &&
Lang Hamesbf122742013-02-17 07:22:09 +00001052 !(FieldType.isTriviallyCopyableType(CGF.getContext()) ||
1053 FieldType->isReferenceType()))
1054 return false;
1055
1056 // Bail out on volatile fields.
1057 if (!isMemcpyableField(Field))
1058 return false;
1059
1060 // Otherwise we're good.
1061 return true;
1062 }
1063
1064 public:
1065 ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD,
1066 FunctionArgList &Args)
David Majnemer196ac332014-09-11 23:05:02 +00001067 : FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CGF, CD, Args)),
Lang Hamesbf122742013-02-17 07:22:09 +00001068 ConstructorDecl(CD),
Jordan Rose54533f72013-08-07 16:16:48 +00001069 MemcpyableCtor(CD->isDefaulted() &&
Lang Hamesbf122742013-02-17 07:22:09 +00001070 CD->isCopyOrMoveConstructor() &&
1071 CGF.getLangOpts().getGC() == LangOptions::NonGC),
1072 Args(Args) { }
1073
1074 void addMemberInitializer(CXXCtorInitializer *MemberInit) {
1075 if (isMemberInitMemcpyable(MemberInit)) {
1076 AggregatedInits.push_back(MemberInit);
1077 addMemcpyableField(MemberInit->getMember());
1078 } else {
1079 emitAggregatedInits();
1080 EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit,
1081 ConstructorDecl, Args);
1082 }
1083 }
1084
1085 void emitAggregatedInits() {
1086 if (AggregatedInits.size() <= 1) {
1087 // This memcpy is too small to be worthwhile. Fall back on default
1088 // codegen.
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001089 if (!AggregatedInits.empty()) {
1090 CopyingValueRepresentation CVR(CGF);
Lang Hamesbf122742013-02-17 07:22:09 +00001091 EmitMemberInitializer(CGF, ConstructorDecl->getParent(),
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001092 AggregatedInits[0], ConstructorDecl, Args);
Alexey Bataev152c71f2015-07-14 07:55:48 +00001093 AggregatedInits.clear();
Lang Hamesbf122742013-02-17 07:22:09 +00001094 }
1095 reset();
1096 return;
1097 }
1098
1099 pushEHDestructors();
1100 emitMemcpy();
1101 AggregatedInits.clear();
1102 }
1103
1104 void pushEHDestructors() {
John McCall7f416cc2015-09-08 08:05:57 +00001105 Address ThisPtr = CGF.LoadCXXThisAddress();
Lang Hamesbf122742013-02-17 07:22:09 +00001106 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
John McCall7f416cc2015-09-08 08:05:57 +00001107 LValue LHS = CGF.MakeAddrLValue(ThisPtr, RecordTy);
Lang Hamesbf122742013-02-17 07:22:09 +00001108
1109 for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
Alexey Bataev152c71f2015-07-14 07:55:48 +00001110 CXXCtorInitializer *MemberInit = AggregatedInits[i];
1111 QualType FieldType = MemberInit->getAnyMember()->getType();
Lang Hamesbf122742013-02-17 07:22:09 +00001112 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
Alexey Bataev152c71f2015-07-14 07:55:48 +00001113 if (!CGF.needsEHCleanup(dtorKind))
1114 continue;
1115 LValue FieldLHS = LHS;
1116 EmitLValueForAnyFieldInitialization(CGF, MemberInit, FieldLHS);
1117 CGF.pushEHDestroy(dtorKind, FieldLHS.getAddress(), FieldType);
Lang Hamesbf122742013-02-17 07:22:09 +00001118 }
1119 }
1120
1121 void finish() {
1122 emitAggregatedInits();
1123 }
1124
1125 private:
1126 const CXXConstructorDecl *ConstructorDecl;
1127 bool MemcpyableCtor;
1128 FunctionArgList &Args;
1129 SmallVector<CXXCtorInitializer*, 16> AggregatedInits;
1130 };
1131
1132 class AssignmentMemcpyizer : public FieldMemcpyizer {
1133 private:
Lang Hamesbf122742013-02-17 07:22:09 +00001134 // Returns the memcpyable field copied by the given statement, if one
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001135 // exists. Otherwise returns null.
1136 FieldDecl *getMemcpyableField(Stmt *S) {
Lang Hamesbf122742013-02-17 07:22:09 +00001137 if (!AssignmentsMemcpyable)
Craig Topper8a13c412014-05-21 05:09:00 +00001138 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001139 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
1140 // Recognise trivial assignments.
1141 if (BO->getOpcode() != BO_Assign)
Craig Topper8a13c412014-05-21 05:09:00 +00001142 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001143 MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS());
1144 if (!ME)
Craig Topper8a13c412014-05-21 05:09:00 +00001145 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001146 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1147 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001148 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001149 Stmt *RHS = BO->getRHS();
1150 if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS))
1151 RHS = EC->getSubExpr();
1152 if (!RHS)
Craig Topper8a13c412014-05-21 05:09:00 +00001153 return nullptr;
Warren Ristow8d17b402017-02-02 17:53:34 +00001154 if (MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS)) {
1155 if (ME2->getMemberDecl() == Field)
1156 return Field;
1157 }
1158 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001159 } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) {
1160 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl());
Richard Smith419bd092015-04-29 19:26:57 +00001161 if (!(MD && isMemcpyEquivalentSpecialMember(MD)))
Craig Topper8a13c412014-05-21 05:09:00 +00001162 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001163 MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument());
1164 if (!IOA)
Craig Topper8a13c412014-05-21 05:09:00 +00001165 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001166 FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl());
1167 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001168 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001169 MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0));
1170 if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl()))
Craig Topper8a13c412014-05-21 05:09:00 +00001171 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001172 return Field;
1173 } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1174 FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1175 if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy)
Craig Topper8a13c412014-05-21 05:09:00 +00001176 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001177 Expr *DstPtr = CE->getArg(0);
1178 if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr))
1179 DstPtr = DC->getSubExpr();
1180 UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr);
1181 if (!DUO || DUO->getOpcode() != UO_AddrOf)
Craig Topper8a13c412014-05-21 05:09:00 +00001182 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001183 MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr());
1184 if (!ME)
Craig Topper8a13c412014-05-21 05:09:00 +00001185 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001186 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1187 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001188 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001189 Expr *SrcPtr = CE->getArg(1);
1190 if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr))
1191 SrcPtr = SC->getSubExpr();
1192 UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr);
1193 if (!SUO || SUO->getOpcode() != UO_AddrOf)
Craig Topper8a13c412014-05-21 05:09:00 +00001194 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001195 MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr());
1196 if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl()))
Craig Topper8a13c412014-05-21 05:09:00 +00001197 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001198 return Field;
1199 }
1200
Craig Topper8a13c412014-05-21 05:09:00 +00001201 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001202 }
1203
1204 bool AssignmentsMemcpyable;
1205 SmallVector<Stmt*, 16> AggregatedStmts;
1206
1207 public:
Lang Hamesbf122742013-02-17 07:22:09 +00001208 AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD,
1209 FunctionArgList &Args)
1210 : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]),
1211 AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) {
1212 assert(Args.size() == 2);
1213 }
1214
1215 void emitAssignment(Stmt *S) {
1216 FieldDecl *F = getMemcpyableField(S);
1217 if (F) {
1218 addMemcpyableField(F);
1219 AggregatedStmts.push_back(S);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001220 } else {
Lang Hamesbf122742013-02-17 07:22:09 +00001221 emitAggregatedStmts();
1222 CGF.EmitStmt(S);
1223 }
1224 }
1225
1226 void emitAggregatedStmts() {
1227 if (AggregatedStmts.size() <= 1) {
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001228 if (!AggregatedStmts.empty()) {
1229 CopyingValueRepresentation CVR(CGF);
1230 CGF.EmitStmt(AggregatedStmts[0]);
1231 }
Lang Hamesbf122742013-02-17 07:22:09 +00001232 reset();
1233 }
1234
1235 emitMemcpy();
1236 AggregatedStmts.clear();
1237 }
1238
1239 void finish() {
1240 emitAggregatedStmts();
1241 }
1242 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00001243} // end anonymous namespace
Lang Hamesbf122742013-02-17 07:22:09 +00001244
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001245static bool isInitializerOfDynamicClass(const CXXCtorInitializer *BaseInit) {
1246 const Type *BaseType = BaseInit->getBaseClass();
1247 const auto *BaseClassDecl =
Simon Pilgrim1cd399c2019-10-03 11:22:48 +00001248 cast<CXXRecordDecl>(BaseType->castAs<RecordType>()->getDecl());
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001249 return BaseClassDecl->isDynamicClass();
1250}
1251
Anders Carlssonfb404882009-12-24 22:46:43 +00001252/// EmitCtorPrologue - This routine generates necessary code to initialize
1253/// base classes and non-static data members belonging to this constructor.
Anders Carlssonfb404882009-12-24 22:46:43 +00001254void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001255 CXXCtorType CtorType,
1256 FunctionArgList &Args) {
Alexis Hunt61bc1732011-05-01 07:04:31 +00001257 if (CD->isDelegatingConstructor())
1258 return EmitDelegatingCXXConstructorCall(CD, Args);
1259
Anders Carlssonfb404882009-12-24 22:46:43 +00001260 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlsson5dc86332010-02-02 19:58:43 +00001261
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001262 CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
1263 E = CD->init_end();
1264
Reid Kleckner61c9b7c2019-03-18 22:41:50 +00001265 // Virtual base initializers first, if any. They aren't needed if:
1266 // - This is a base ctor variant
1267 // - There are no vbases
1268 // - The class is abstract, so a complete object of it cannot be constructed
1269 //
1270 // The check for an abstract class is necessary because sema may not have
1271 // marked virtual base destructors referenced.
1272 bool ConstructVBases = CtorType != Ctor_Base &&
1273 ClassDecl->getNumVBases() != 0 &&
1274 !ClassDecl->isAbstract();
1275
1276 // In the Microsoft C++ ABI, there are no constructor variants. Instead, the
1277 // constructor of a class with virtual bases takes an additional parameter to
1278 // conditionally construct the virtual bases. Emit that check here.
Craig Topper8a13c412014-05-21 05:09:00 +00001279 llvm::BasicBlock *BaseCtorContinueBB = nullptr;
Reid Kleckner61c9b7c2019-03-18 22:41:50 +00001280 if (ConstructVBases &&
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001281 !CGM.getTarget().getCXXABI().hasConstructorVariants()) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001282 BaseCtorContinueBB =
Reid Kleckner61c9b7c2019-03-18 22:41:50 +00001283 CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this, ClassDecl);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001284 assert(BaseCtorContinueBB);
1285 }
1286
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001287 llvm::Value *const OldThis = CXXThisValue;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001288 for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
Reid Kleckner61c9b7c2019-03-18 22:41:50 +00001289 if (!ConstructVBases)
1290 continue;
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001291 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1292 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1293 isInitializerOfDynamicClass(*B))
Piotr Padlewski5dde8092018-05-03 11:03:01 +00001294 CXXThisValue = Builder.CreateLaunderInvariantGroup(LoadCXXThis());
Reid Kleckner61c9b7c2019-03-18 22:41:50 +00001295 EmitBaseInitializer(*this, ClassDecl, *B);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001296 }
1297
1298 if (BaseCtorContinueBB) {
1299 // Complete object handler should continue to the remaining initializers.
1300 Builder.CreateBr(BaseCtorContinueBB);
1301 EmitBlock(BaseCtorContinueBB);
1302 }
1303
1304 // Then, non-virtual base initializers.
1305 for (; B != E && (*B)->isBaseInitializer(); B++) {
1306 assert(!(*B)->isBaseVirtual());
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001307
1308 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1309 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1310 isInitializerOfDynamicClass(*B))
Piotr Padlewski5dde8092018-05-03 11:03:01 +00001311 CXXThisValue = Builder.CreateLaunderInvariantGroup(LoadCXXThis());
Reid Kleckner61c9b7c2019-03-18 22:41:50 +00001312 EmitBaseInitializer(*this, ClassDecl, *B);
Anders Carlssonfb404882009-12-24 22:46:43 +00001313 }
1314
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001315 CXXThisValue = OldThis;
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001316
Anders Carlssond5895932010-03-28 21:07:49 +00001317 InitializeVTablePointers(ClassDecl);
Anders Carlsson5dc86332010-02-02 19:58:43 +00001318
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001319 // And finally, initialize class members.
John McCall7f416cc2015-09-08 08:05:57 +00001320 FieldConstructionScope FCS(*this, LoadCXXThisAddress());
Lang Hamesbf122742013-02-17 07:22:09 +00001321 ConstructorMemcpyizer CM(*this, CD, Args);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001322 for (; B != E; B++) {
1323 CXXCtorInitializer *Member = (*B);
1324 assert(!Member->isBaseInitializer());
1325 assert(Member->isAnyMemberInitializer() &&
1326 "Delegating initializer on non-delegating constructor");
1327 CM.addMemberInitializer(Member);
1328 }
Lang Hamesbf122742013-02-17 07:22:09 +00001329 CM.finish();
Anders Carlssonfb404882009-12-24 22:46:43 +00001330}
1331
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001332static bool
1333FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
1334
1335static bool
Justin Bogner1cd11f12015-05-20 15:53:59 +00001336HasTrivialDestructorBody(ASTContext &Context,
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001337 const CXXRecordDecl *BaseClassDecl,
1338 const CXXRecordDecl *MostDerivedClassDecl)
1339{
1340 // If the destructor is trivial we don't have to check anything else.
1341 if (BaseClassDecl->hasTrivialDestructor())
1342 return true;
1343
1344 if (!BaseClassDecl->getDestructor()->hasTrivialBody())
1345 return false;
1346
1347 // Check fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001348 for (const auto *Field : BaseClassDecl->fields())
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001349 if (!FieldHasTrivialDestructorBody(Context, Field))
1350 return false;
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001351
1352 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001353 for (const auto &I : BaseClassDecl->bases()) {
1354 if (I.isVirtual())
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001355 continue;
1356
1357 const CXXRecordDecl *NonVirtualBase =
Aaron Ballman574705e2014-03-13 15:41:46 +00001358 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001359 if (!HasTrivialDestructorBody(Context, NonVirtualBase,
1360 MostDerivedClassDecl))
1361 return false;
1362 }
1363
1364 if (BaseClassDecl == MostDerivedClassDecl) {
1365 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00001366 for (const auto &I : BaseClassDecl->vbases()) {
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001367 const CXXRecordDecl *VirtualBase =
Aaron Ballman445a9392014-03-13 16:15:17 +00001368 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001369 if (!HasTrivialDestructorBody(Context, VirtualBase,
1370 MostDerivedClassDecl))
Justin Bogner1cd11f12015-05-20 15:53:59 +00001371 return false;
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001372 }
1373 }
1374
1375 return true;
1376}
1377
1378static bool
1379FieldHasTrivialDestructorBody(ASTContext &Context,
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001380 const FieldDecl *Field)
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001381{
1382 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
1383
1384 const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
1385 if (!RT)
1386 return true;
Justin Bogner1cd11f12015-05-20 15:53:59 +00001387
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001388 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Davide Italiano982bbf42015-06-26 00:18:35 +00001389
1390 // The destructor for an implicit anonymous union member is never invoked.
1391 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
1392 return false;
1393
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001394 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
1395}
1396
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001397/// CanSkipVTablePointerInitialization - Check whether we need to initialize
1398/// any vtable pointers before calling this destructor.
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001399static bool CanSkipVTablePointerInitialization(CodeGenFunction &CGF,
Anders Carlssond6f15182011-05-16 04:08:36 +00001400 const CXXDestructorDecl *Dtor) {
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001401 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1402 if (!ClassDecl->isDynamicClass())
1403 return true;
1404
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001405 if (!Dtor->hasTrivialBody())
1406 return false;
1407
1408 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001409 for (const auto *Field : ClassDecl->fields())
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001410 if (!FieldHasTrivialDestructorBody(CGF.getContext(), Field))
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001411 return false;
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001412
1413 return true;
1414}
1415
John McCallb81884d2010-02-19 09:25:03 +00001416/// EmitDestructorBody - Emits the body of the current destructor.
1417void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
1418 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
1419 CXXDtorType DtorType = CurGD.getDtorType();
1420
Richard Smithdf054d32017-02-25 23:53:05 +00001421 // For an abstract class, non-base destructors are never used (and can't
1422 // be emitted in general, because vbase dtors may not have been validated
1423 // by Sema), but the Itanium ABI doesn't make them optional and Clang may
1424 // in fact emit references to them from other compilations, so emit them
1425 // as functions containing a trap instruction.
1426 if (DtorType != Dtor_Base && Dtor->getParent()->isAbstract()) {
1427 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
1428 TrapCall->setDoesNotReturn();
1429 TrapCall->setDoesNotThrow();
1430 Builder.CreateUnreachable();
1431 Builder.ClearInsertionPoint();
1432 return;
1433 }
1434
Justin Bognerfb298222015-05-20 16:16:23 +00001435 Stmt *Body = Dtor->getBody();
1436 if (Body)
1437 incrementProfileCounter(Body);
1438
John McCallf99a6312010-07-21 05:30:47 +00001439 // The call to operator delete in a deleting destructor happens
1440 // outside of the function-try-block, which means it's always
1441 // possible to delegate the destructor body to the complete
1442 // destructor. Do so.
1443 if (DtorType == Dtor_Deleting) {
Richard Smith5b349582017-10-13 01:55:36 +00001444 RunCleanupsScope DtorEpilogue(*this);
John McCallf99a6312010-07-21 05:30:47 +00001445 EnterDtorCleanups(Dtor, Dtor_Deleting);
Marco Antognini88559632019-07-22 09:39:13 +00001446 if (HaveInsertPoint()) {
1447 QualType ThisTy = Dtor->getThisObjectType();
Richard Smith5b349582017-10-13 01:55:36 +00001448 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
Marco Antognini88559632019-07-22 09:39:13 +00001449 /*Delegating=*/false, LoadCXXThisAddress(), ThisTy);
1450 }
John McCallf99a6312010-07-21 05:30:47 +00001451 return;
1452 }
1453
John McCallb81884d2010-02-19 09:25:03 +00001454 // If the body is a function-try-block, enter the try before
John McCallf99a6312010-07-21 05:30:47 +00001455 // anything else.
1456 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallb81884d2010-02-19 09:25:03 +00001457 if (isTryBody)
John McCallb609d3f2010-07-07 06:56:46 +00001458 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00001459 EmitAsanPrologueOrEpilogue(false);
John McCallb81884d2010-02-19 09:25:03 +00001460
John McCallf99a6312010-07-21 05:30:47 +00001461 // Enter the epilogue cleanups.
1462 RunCleanupsScope DtorEpilogue(*this);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001463
John McCallb81884d2010-02-19 09:25:03 +00001464 // If this is the complete variant, just invoke the base variant;
1465 // the epilogue will destruct the virtual bases. But we can't do
1466 // this optimization if the body is a function-try-block, because
Justin Bogner1cd11f12015-05-20 15:53:59 +00001467 // we'd introduce *two* handler blocks. In the Microsoft ABI, we
Reid Klecknere7de47e2013-07-22 13:51:44 +00001468 // always delegate because we might not have a definition in this TU.
John McCallf99a6312010-07-21 05:30:47 +00001469 switch (DtorType) {
Saleem Abdulrasool8de4e872017-02-02 05:45:43 +00001470 case Dtor_Comdat: llvm_unreachable("not expecting a COMDAT");
John McCallf99a6312010-07-21 05:30:47 +00001471 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
1472
1473 case Dtor_Complete:
Reid Klecknere7de47e2013-07-22 13:51:44 +00001474 assert((Body || getTarget().getCXXABI().isMicrosoft()) &&
1475 "can't emit a dtor without a body for non-Microsoft ABIs");
1476
John McCallf99a6312010-07-21 05:30:47 +00001477 // Enter the cleanup scopes for virtual bases.
1478 EnterDtorCleanups(Dtor, Dtor_Complete);
1479
Reid Klecknere7de47e2013-07-22 13:51:44 +00001480 if (!isTryBody) {
Marco Antognini88559632019-07-22 09:39:13 +00001481 QualType ThisTy = Dtor->getThisObjectType();
John McCallf99a6312010-07-21 05:30:47 +00001482 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
Marco Antognini88559632019-07-22 09:39:13 +00001483 /*Delegating=*/false, LoadCXXThisAddress(), ThisTy);
John McCallf99a6312010-07-21 05:30:47 +00001484 break;
1485 }
Saleem Abdulrasool8de4e872017-02-02 05:45:43 +00001486
John McCallf99a6312010-07-21 05:30:47 +00001487 // Fallthrough: act like we're in the base variant.
Saleem Abdulrasool8de4e872017-02-02 05:45:43 +00001488 LLVM_FALLTHROUGH;
Justin Bogner1cd11f12015-05-20 15:53:59 +00001489
John McCallf99a6312010-07-21 05:30:47 +00001490 case Dtor_Base:
Reid Klecknere7de47e2013-07-22 13:51:44 +00001491 assert(Body);
1492
John McCallf99a6312010-07-21 05:30:47 +00001493 // Enter the cleanup scopes for fields and non-virtual bases.
1494 EnterDtorCleanups(Dtor, Dtor_Base);
1495
1496 // Initialize the vtable pointers before entering the body.
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001497 if (!CanSkipVTablePointerInitialization(*this, Dtor)) {
Piotr Padlewski5dde8092018-05-03 11:03:01 +00001498 // Insert the llvm.launder.invariant.group intrinsic before initializing
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001499 // the vptrs to cancel any previous assumptions we might have made.
1500 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1501 CGM.getCodeGenOpts().OptimizationLevel > 0)
Piotr Padlewski5dde8092018-05-03 11:03:01 +00001502 CXXThisValue = Builder.CreateLaunderInvariantGroup(LoadCXXThis());
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001503 InitializeVTablePointers(Dtor->getParent());
1504 }
John McCallf99a6312010-07-21 05:30:47 +00001505
1506 if (isTryBody)
1507 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
1508 else if (Body)
1509 EmitStmt(Body);
1510 else {
1511 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
1512 // nothing to do besides what's in the epilogue
1513 }
Fariborz Jahanian0c12ed12011-02-02 23:12:46 +00001514 // -fapple-kext must inline any call to this dtor into
1515 // the caller's body.
Richard Smith9c6890a2012-11-01 22:30:59 +00001516 if (getLangOpts().AppleKext)
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00001517 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
Naomi Musgravee50cb9b2015-08-13 18:35:11 +00001518
John McCallf99a6312010-07-21 05:30:47 +00001519 break;
John McCallb81884d2010-02-19 09:25:03 +00001520 }
1521
John McCallf99a6312010-07-21 05:30:47 +00001522 // Jump out through the epilogue cleanups.
1523 DtorEpilogue.ForceCleanup();
John McCallb81884d2010-02-19 09:25:03 +00001524
1525 // Exit the try if applicable.
1526 if (isTryBody)
John McCallb609d3f2010-07-07 06:56:46 +00001527 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +00001528}
1529
Lang Hamesbf122742013-02-17 07:22:09 +00001530void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) {
1531 const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
1532 const Stmt *RootS = AssignOp->getBody();
1533 assert(isa<CompoundStmt>(RootS) &&
1534 "Body of an implicit assignment operator should be compound stmt.");
1535 const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
1536
1537 LexicalScope Scope(*this, RootCS->getSourceRange());
1538
Xinliang David Lia951e8e2016-02-09 20:02:59 +00001539 incrementProfileCounter(RootCS);
Lang Hamesbf122742013-02-17 07:22:09 +00001540 AssignmentMemcpyizer AM(*this, AssignOp, Args);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001541 for (auto *I : RootCS->body())
Justin Bogner1cd11f12015-05-20 15:53:59 +00001542 AM.emitAssignment(I);
Lang Hamesbf122742013-02-17 07:22:09 +00001543 AM.finish();
1544}
1545
John McCallf99a6312010-07-21 05:30:47 +00001546namespace {
Richard Smith5b349582017-10-13 01:55:36 +00001547 llvm::Value *LoadThisForDtorDelete(CodeGenFunction &CGF,
1548 const CXXDestructorDecl *DD) {
1549 if (Expr *ThisArg = DD->getOperatorDeleteThisArg())
Haojian Wu5b5c81f2017-10-13 15:37:53 +00001550 return CGF.EmitScalarExpr(ThisArg);
Richard Smith5b349582017-10-13 01:55:36 +00001551 return CGF.LoadCXXThis();
1552 }
1553
John McCallf99a6312010-07-21 05:30:47 +00001554 /// Call the operator delete associated with the current destructor.
David Blaikie7e70d682015-08-18 22:40:54 +00001555 struct CallDtorDelete final : EHScopeStack::Cleanup {
John McCallf99a6312010-07-21 05:30:47 +00001556 CallDtorDelete() {}
1557
Craig Topper4f12f102014-03-12 06:41:41 +00001558 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallf99a6312010-07-21 05:30:47 +00001559 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1560 const CXXRecordDecl *ClassDecl = Dtor->getParent();
Richard Smith5b349582017-10-13 01:55:36 +00001561 CGF.EmitDeleteCall(Dtor->getOperatorDelete(),
1562 LoadThisForDtorDelete(CGF, Dtor),
John McCallf99a6312010-07-21 05:30:47 +00001563 CGF.getContext().getTagDeclType(ClassDecl));
1564 }
1565 };
1566
Richard Smith5b349582017-10-13 01:55:36 +00001567 void EmitConditionalDtorDeleteCall(CodeGenFunction &CGF,
1568 llvm::Value *ShouldDeleteCondition,
1569 bool ReturnAfterDelete) {
1570 llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
1571 llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
1572 llvm::Value *ShouldCallDelete
1573 = CGF.Builder.CreateIsNull(ShouldDeleteCondition);
1574 CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
1575
1576 CGF.EmitBlock(callDeleteBB);
1577 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1578 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1579 CGF.EmitDeleteCall(Dtor->getOperatorDelete(),
1580 LoadThisForDtorDelete(CGF, Dtor),
1581 CGF.getContext().getTagDeclType(ClassDecl));
1582 assert(Dtor->getOperatorDelete()->isDestroyingOperatorDelete() ==
1583 ReturnAfterDelete &&
1584 "unexpected value for ReturnAfterDelete");
1585 if (ReturnAfterDelete)
1586 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
1587 else
1588 CGF.Builder.CreateBr(continueBB);
1589
1590 CGF.EmitBlock(continueBB);
1591 }
1592
David Blaikie7e70d682015-08-18 22:40:54 +00001593 struct CallDtorDeleteConditional final : EHScopeStack::Cleanup {
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001594 llvm::Value *ShouldDeleteCondition;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001595
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001596 public:
1597 CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001598 : ShouldDeleteCondition(ShouldDeleteCondition) {
Craig Topper8a13c412014-05-21 05:09:00 +00001599 assert(ShouldDeleteCondition != nullptr);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001600 }
1601
Craig Topper4f12f102014-03-12 06:41:41 +00001602 void Emit(CodeGenFunction &CGF, Flags flags) override {
Richard Smith5b349582017-10-13 01:55:36 +00001603 EmitConditionalDtorDeleteCall(CGF, ShouldDeleteCondition,
1604 /*ReturnAfterDelete*/false);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001605 }
1606 };
1607
David Blaikie7e70d682015-08-18 22:40:54 +00001608 class DestroyField final : public EHScopeStack::Cleanup {
John McCall4bd0fb12011-07-12 16:41:08 +00001609 const FieldDecl *field;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001610 CodeGenFunction::Destroyer *destroyer;
John McCall4bd0fb12011-07-12 16:41:08 +00001611 bool useEHCleanupForArray;
John McCallf99a6312010-07-21 05:30:47 +00001612
John McCall4bd0fb12011-07-12 16:41:08 +00001613 public:
1614 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
1615 bool useEHCleanupForArray)
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001616 : field(field), destroyer(destroyer),
1617 useEHCleanupForArray(useEHCleanupForArray) {}
John McCallf99a6312010-07-21 05:30:47 +00001618
Craig Topper4f12f102014-03-12 06:41:41 +00001619 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall4bd0fb12011-07-12 16:41:08 +00001620 // Find the address of the field.
John McCall7f416cc2015-09-08 08:05:57 +00001621 Address thisValue = CGF.LoadCXXThisAddress();
Eli Friedman7f1ff602012-04-16 03:54:45 +00001622 QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
1623 LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
1624 LValue LV = CGF.EmitLValueForField(ThisLV, field);
John McCall4bd0fb12011-07-12 16:41:08 +00001625 assert(LV.isSimple());
Justin Bogner1cd11f12015-05-20 15:53:59 +00001626
John McCall4bd0fb12011-07-12 16:41:08 +00001627 CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +00001628 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCallf99a6312010-07-21 05:30:47 +00001629 }
1630 };
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001631
Naomi Musgrave703835c2015-09-16 00:38:22 +00001632 static void EmitSanitizerDtorCallback(CodeGenFunction &CGF, llvm::Value *Ptr,
1633 CharUnits::QuantityType PoisonSize) {
Matt Morehouse4881a232017-09-20 22:53:08 +00001634 CodeGenFunction::SanitizerScope SanScope(&CGF);
Naomi Musgrave703835c2015-09-16 00:38:22 +00001635 // Pass in void pointer and size of region as arguments to runtime
1636 // function
1637 llvm::Value *Args[] = {CGF.Builder.CreateBitCast(Ptr, CGF.VoidPtrTy),
1638 llvm::ConstantInt::get(CGF.SizeTy, PoisonSize)};
1639
1640 llvm::Type *ArgTypes[] = {CGF.VoidPtrTy, CGF.SizeTy};
1641
1642 llvm::FunctionType *FnType =
1643 llvm::FunctionType::get(CGF.VoidTy, ArgTypes, false);
James Y Knight9871db02019-02-05 16:42:33 +00001644 llvm::FunctionCallee Fn =
Naomi Musgrave703835c2015-09-16 00:38:22 +00001645 CGF.CGM.CreateRuntimeFunction(FnType, "__sanitizer_dtor_callback");
1646 CGF.EmitNounwindRuntimeCall(Fn, Args);
1647 }
1648
1649 class SanitizeDtorMembers final : public EHScopeStack::Cleanup {
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001650 const CXXDestructorDecl *Dtor;
1651
1652 public:
Naomi Musgrave703835c2015-09-16 00:38:22 +00001653 SanitizeDtorMembers(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001654
1655 // Generate function call for handling object poisoning.
1656 // Disables tail call elimination, to prevent the current stack frame
1657 // from disappearing from the stack trace.
1658 void Emit(CodeGenFunction &CGF, Flags flags) override {
1659 const ASTRecordLayout &Layout =
1660 CGF.getContext().getASTRecordLayout(Dtor->getParent());
1661
1662 // Nothing to poison.
1663 if (Layout.getFieldCount() == 0)
1664 return;
1665
1666 // Prevent the current stack frame from disappearing from the stack trace.
1667 CGF.CurFn->addFnAttr("disable-tail-calls", "true");
1668
1669 // Construct pointer to region to begin poisoning, and calculate poison
1670 // size, so that only members declared in this class are poisoned.
1671 ASTContext &Context = CGF.getContext();
1672 unsigned fieldIndex = 0;
1673 int startIndex = -1;
1674 // RecordDecl::field_iterator Field;
1675 for (const FieldDecl *Field : Dtor->getParent()->fields()) {
1676 // Poison field if it is trivial
1677 if (FieldHasTrivialDestructorBody(Context, Field)) {
1678 // Start sanitizing at this field
1679 if (startIndex < 0)
1680 startIndex = fieldIndex;
1681
1682 // Currently on the last field, and it must be poisoned with the
1683 // current block.
1684 if (fieldIndex == Layout.getFieldCount() - 1) {
Naomi Musgrave703835c2015-09-16 00:38:22 +00001685 PoisonMembers(CGF, startIndex, Layout.getFieldCount());
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001686 }
1687 } else if (startIndex >= 0) {
1688 // No longer within a block of memory to poison, so poison the block
Naomi Musgrave703835c2015-09-16 00:38:22 +00001689 PoisonMembers(CGF, startIndex, fieldIndex);
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001690 // Re-set the start index
1691 startIndex = -1;
1692 }
1693 fieldIndex += 1;
1694 }
1695 }
1696
1697 private:
NAKAMURA Takumif6cef72f2015-09-04 05:19:31 +00001698 /// \param layoutStartOffset index of the ASTRecordLayout field to
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001699 /// start poisoning (inclusive)
NAKAMURA Takumif6cef72f2015-09-04 05:19:31 +00001700 /// \param layoutEndOffset index of the ASTRecordLayout field to
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001701 /// end poisoning (exclusive)
Naomi Musgrave703835c2015-09-16 00:38:22 +00001702 void PoisonMembers(CodeGenFunction &CGF, unsigned layoutStartOffset,
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001703 unsigned layoutEndOffset) {
1704 ASTContext &Context = CGF.getContext();
1705 const ASTRecordLayout &Layout =
1706 Context.getASTRecordLayout(Dtor->getParent());
1707
1708 llvm::ConstantInt *OffsetSizePtr = llvm::ConstantInt::get(
1709 CGF.SizeTy,
1710 Context.toCharUnitsFromBits(Layout.getFieldOffset(layoutStartOffset))
1711 .getQuantity());
1712
1713 llvm::Value *OffsetPtr = CGF.Builder.CreateGEP(
1714 CGF.Builder.CreateBitCast(CGF.LoadCXXThis(), CGF.Int8PtrTy),
1715 OffsetSizePtr);
1716
1717 CharUnits::QuantityType PoisonSize;
1718 if (layoutEndOffset >= Layout.getFieldCount()) {
1719 PoisonSize = Layout.getNonVirtualSize().getQuantity() -
1720 Context.toCharUnitsFromBits(
1721 Layout.getFieldOffset(layoutStartOffset))
1722 .getQuantity();
1723 } else {
1724 PoisonSize = Context.toCharUnitsFromBits(
1725 Layout.getFieldOffset(layoutEndOffset) -
1726 Layout.getFieldOffset(layoutStartOffset))
1727 .getQuantity();
1728 }
1729
1730 if (PoisonSize == 0)
1731 return;
1732
Naomi Musgrave703835c2015-09-16 00:38:22 +00001733 EmitSanitizerDtorCallback(CGF, OffsetPtr, PoisonSize);
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001734 }
1735 };
Naomi Musgrave703835c2015-09-16 00:38:22 +00001736
1737 class SanitizeDtorVTable final : public EHScopeStack::Cleanup {
1738 const CXXDestructorDecl *Dtor;
1739
1740 public:
1741 SanitizeDtorVTable(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
1742
1743 // Generate function call for handling vtable pointer poisoning.
1744 void Emit(CodeGenFunction &CGF, Flags flags) override {
1745 assert(Dtor->getParent()->isDynamicClass());
NAKAMURA Takumiee82b492015-09-16 06:26:56 +00001746 (void)Dtor;
Naomi Musgrave703835c2015-09-16 00:38:22 +00001747 ASTContext &Context = CGF.getContext();
1748 // Poison vtable and vtable ptr if they exist for this class.
1749 llvm::Value *VTablePtr = CGF.LoadCXXThis();
1750
1751 CharUnits::QuantityType PoisonSize =
1752 Context.toCharUnitsFromBits(CGF.PointerWidthInBits).getQuantity();
1753 // Pass in void pointer and size of region as arguments to runtime
1754 // function
1755 EmitSanitizerDtorCallback(CGF, VTablePtr, PoisonSize);
1756 }
1757 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00001758} // end anonymous namespace
John McCallf99a6312010-07-21 05:30:47 +00001759
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001760/// Emit all code that comes at the end of class's
Anders Carlssonfb404882009-12-24 22:46:43 +00001761/// destructor. This is to call destructors on members and base classes
1762/// in reverse order of their construction.
Richard Smith5b349582017-10-13 01:55:36 +00001763///
1764/// For a deleting destructor, this also handles the case where a destroying
1765/// operator delete completely overrides the definition.
John McCallf99a6312010-07-21 05:30:47 +00001766void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
1767 CXXDtorType DtorType) {
Hans Wennborg853ae942014-05-30 16:59:42 +00001768 assert((!DD->isTrivial() || DD->hasAttr<DLLExportAttr>()) &&
1769 "Should not emit dtor epilogue for non-exported trivial dtor!");
Anders Carlssonfb404882009-12-24 22:46:43 +00001770
John McCallf99a6312010-07-21 05:30:47 +00001771 // The deleting-destructor phase just needs to call the appropriate
1772 // operator delete that Sema picked up.
John McCall5c60a6f2010-02-18 19:59:28 +00001773 if (DtorType == Dtor_Deleting) {
Justin Bogner1cd11f12015-05-20 15:53:59 +00001774 assert(DD->getOperatorDelete() &&
Hans Wennborgdeff7032013-12-18 01:39:59 +00001775 "operator delete missing - EnterDtorCleanups");
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001776 if (CXXStructorImplicitParamValue) {
1777 // If there is an implicit param to the deleting dtor, it's a boolean
Richard Smith5b349582017-10-13 01:55:36 +00001778 // telling whether this is a deleting destructor.
1779 if (DD->getOperatorDelete()->isDestroyingOperatorDelete())
1780 EmitConditionalDtorDeleteCall(*this, CXXStructorImplicitParamValue,
1781 /*ReturnAfterDelete*/true);
1782 else
1783 EHStack.pushCleanup<CallDtorDeleteConditional>(
1784 NormalAndEHCleanup, CXXStructorImplicitParamValue);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001785 } else {
Richard Smith5b349582017-10-13 01:55:36 +00001786 if (DD->getOperatorDelete()->isDestroyingOperatorDelete()) {
1787 const CXXRecordDecl *ClassDecl = DD->getParent();
1788 EmitDeleteCall(DD->getOperatorDelete(),
1789 LoadThisForDtorDelete(*this, DD),
1790 getContext().getTagDeclType(ClassDecl));
1791 EmitBranchThroughCleanup(ReturnBlock);
1792 } else {
1793 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
1794 }
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001795 }
John McCall5c60a6f2010-02-18 19:59:28 +00001796 return;
1797 }
1798
John McCallf99a6312010-07-21 05:30:47 +00001799 const CXXRecordDecl *ClassDecl = DD->getParent();
1800
Richard Smith20104042011-09-18 12:11:43 +00001801 // Unions have no bases and do not call field destructors.
1802 if (ClassDecl->isUnion())
1803 return;
1804
John McCallf99a6312010-07-21 05:30:47 +00001805 // The complete-destructor phase just destructs all the virtual bases.
John McCall5c60a6f2010-02-18 19:59:28 +00001806 if (DtorType == Dtor_Complete) {
Naomi Musgrave703835c2015-09-16 00:38:22 +00001807 // Poison the vtable pointer such that access after the base
1808 // and member destructors are invoked is invalid.
1809 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1810 SanOpts.has(SanitizerKind::Memory) && ClassDecl->getNumVBases() &&
1811 ClassDecl->isPolymorphic())
1812 EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
John McCallf99a6312010-07-21 05:30:47 +00001813
1814 // We push them in the forward order so that they'll be popped in
1815 // the reverse order.
Aaron Ballman445a9392014-03-13 16:15:17 +00001816 for (const auto &Base : ClassDecl->vbases()) {
Simon Pilgrim1cd399c2019-10-03 11:22:48 +00001817 auto *BaseClassDecl =
1818 cast<CXXRecordDecl>(Base.getType()->castAs<RecordType>()->getDecl());
Justin Bogner1cd11f12015-05-20 15:53:59 +00001819
John McCall5c60a6f2010-02-18 19:59:28 +00001820 // Ignore trivial destructors.
1821 if (BaseClassDecl->hasTrivialDestructor())
1822 continue;
John McCallf99a6312010-07-21 05:30:47 +00001823
John McCallcda666c2010-07-21 07:22:38 +00001824 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1825 BaseClassDecl,
1826 /*BaseIsVirtual*/ true);
John McCall5c60a6f2010-02-18 19:59:28 +00001827 }
John McCallf99a6312010-07-21 05:30:47 +00001828
John McCall5c60a6f2010-02-18 19:59:28 +00001829 return;
1830 }
1831
1832 assert(DtorType == Dtor_Base);
Naomi Musgrave703835c2015-09-16 00:38:22 +00001833 // Poison the vtable pointer if it has no virtual bases, but inherits
1834 // virtual functions.
1835 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1836 SanOpts.has(SanitizerKind::Memory) && !ClassDecl->getNumVBases() &&
1837 ClassDecl->isPolymorphic())
1838 EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001839
John McCallf99a6312010-07-21 05:30:47 +00001840 // Destroy non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001841 for (const auto &Base : ClassDecl->bases()) {
John McCallf99a6312010-07-21 05:30:47 +00001842 // Ignore virtual bases.
1843 if (Base.isVirtual())
1844 continue;
Justin Bogner1cd11f12015-05-20 15:53:59 +00001845
John McCallf99a6312010-07-21 05:30:47 +00001846 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
Justin Bogner1cd11f12015-05-20 15:53:59 +00001847
John McCallf99a6312010-07-21 05:30:47 +00001848 // Ignore trivial destructors.
1849 if (BaseClassDecl->hasTrivialDestructor())
1850 continue;
John McCall5c60a6f2010-02-18 19:59:28 +00001851
John McCallcda666c2010-07-21 07:22:38 +00001852 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1853 BaseClassDecl,
1854 /*BaseIsVirtual*/ false);
John McCallf99a6312010-07-21 05:30:47 +00001855 }
1856
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001857 // Poison fields such that access after their destructors are
1858 // invoked, and before the base class destructor runs, is invalid.
1859 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1860 SanOpts.has(SanitizerKind::Memory))
Naomi Musgrave703835c2015-09-16 00:38:22 +00001861 EHStack.pushCleanup<SanitizeDtorMembers>(NormalAndEHCleanup, DD);
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001862
John McCallf99a6312010-07-21 05:30:47 +00001863 // Destroy direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001864 for (const auto *Field : ClassDecl->fields()) {
1865 QualType type = Field->getType();
John McCall4bd0fb12011-07-12 16:41:08 +00001866 QualType::DestructionKind dtorKind = type.isDestructedType();
1867 if (!dtorKind) continue;
John McCallf99a6312010-07-21 05:30:47 +00001868
Richard Smith921bd202012-02-26 09:11:52 +00001869 // Anonymous union members do not have their destructors called.
1870 const RecordType *RT = type->getAsUnionType();
1871 if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
1872
John McCall4bd0fb12011-07-12 16:41:08 +00001873 CleanupKind cleanupKind = getCleanupKind(dtorKind);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001874 EHStack.pushCleanup<DestroyField>(cleanupKind, Field,
John McCall4bd0fb12011-07-12 16:41:08 +00001875 getDestroyer(dtorKind),
1876 cleanupKind & EHCleanup);
Anders Carlssonfb404882009-12-24 22:46:43 +00001877 }
Anders Carlssonfb404882009-12-24 22:46:43 +00001878}
1879
John McCallf677a8e2011-07-13 06:10:41 +00001880/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1881/// constructor for each of several members of an array.
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001882///
John McCallf677a8e2011-07-13 06:10:41 +00001883/// \param ctor the constructor to call for each element
John McCallf677a8e2011-07-13 06:10:41 +00001884/// \param arrayType the type of the array to initialize
1885/// \param arrayBegin an arrayType*
1886/// \param zeroInitialize true if each element should be
1887/// zero-initialized before it is constructed
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001888void CodeGenFunction::EmitCXXAggrConstructorCall(
Alexey Bataeve7545b32016-04-29 09:39:50 +00001889 const CXXConstructorDecl *ctor, const ArrayType *arrayType,
Serge Pavlov37605182018-07-28 15:33:03 +00001890 Address arrayBegin, const CXXConstructExpr *E, bool NewPointerIsChecked,
1891 bool zeroInitialize) {
John McCallf677a8e2011-07-13 06:10:41 +00001892 QualType elementType;
1893 llvm::Value *numElements =
1894 emitArrayLength(arrayType, elementType, arrayBegin);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001895
Serge Pavlov37605182018-07-28 15:33:03 +00001896 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin, E,
1897 NewPointerIsChecked, zeroInitialize);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001898}
1899
John McCallf677a8e2011-07-13 06:10:41 +00001900/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1901/// constructor for each of several members of an array.
1902///
1903/// \param ctor the constructor to call for each element
1904/// \param numElements the number of elements in the array;
John McCall6549b312011-07-13 07:37:11 +00001905/// may be zero
NAKAMURA Takumiff7a9252015-09-08 09:42:41 +00001906/// \param arrayBase a T*, where T is the type constructed by ctor
John McCallf677a8e2011-07-13 06:10:41 +00001907/// \param zeroInitialize true if each element should be
1908/// zero-initialized before it is constructed
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001909void CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1910 llvm::Value *numElements,
John McCall7f416cc2015-09-08 08:05:57 +00001911 Address arrayBase,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001912 const CXXConstructExpr *E,
Serge Pavlov37605182018-07-28 15:33:03 +00001913 bool NewPointerIsChecked,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001914 bool zeroInitialize) {
John McCall6549b312011-07-13 07:37:11 +00001915 // It's legal for numElements to be zero. This can happen both
1916 // dynamically, because x can be zero in 'new A[x]', and statically,
1917 // because of GCC extensions that permit zero-length arrays. There
1918 // are probably legitimate places where we could assume that this
1919 // doesn't happen, but it's not clear that it's worth it.
Craig Topper8a13c412014-05-21 05:09:00 +00001920 llvm::BranchInst *zeroCheckBranch = nullptr;
John McCall6549b312011-07-13 07:37:11 +00001921
1922 // Optimize for a constant count.
1923 llvm::ConstantInt *constantCount
1924 = dyn_cast<llvm::ConstantInt>(numElements);
1925 if (constantCount) {
1926 // Just skip out if the constant count is zero.
1927 if (constantCount->isZero()) return;
1928
1929 // Otherwise, emit the check.
1930 } else {
1931 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1932 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1933 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1934 EmitBlock(loopBB);
1935 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00001936
John McCallf677a8e2011-07-13 06:10:41 +00001937 // Find the end of the array.
John McCall7f416cc2015-09-08 08:05:57 +00001938 llvm::Value *arrayBegin = arrayBase.getPointer();
John McCallf677a8e2011-07-13 06:10:41 +00001939 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1940 "arrayctor.end");
Anders Carlsson27da15b2010-01-01 20:29:01 +00001941
John McCallf677a8e2011-07-13 06:10:41 +00001942 // Enter the loop, setting up a phi for the current location to initialize.
1943 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1944 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1945 EmitBlock(loopBB);
1946 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1947 "arrayctor.cur");
1948 cur->addIncoming(arrayBegin, entryBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001949
Anders Carlsson27da15b2010-01-01 20:29:01 +00001950 // Inside the loop body, emit the constructor call on the array element.
John McCallf677a8e2011-07-13 06:10:41 +00001951
John McCall7f416cc2015-09-08 08:05:57 +00001952 // The alignment of the base, adjusted by the size of a single element,
1953 // provides a conservative estimate of the alignment of every element.
1954 // (This assumes we never start tracking offsetted alignments.)
Fangrui Song6907ce22018-07-30 19:24:48 +00001955 //
John McCall7f416cc2015-09-08 08:05:57 +00001956 // Note that these are complete objects and so we don't need to
1957 // use the non-virtual size or alignment.
John McCallf677a8e2011-07-13 06:10:41 +00001958 QualType type = getContext().getTypeDeclType(ctor->getParent());
John McCall7f416cc2015-09-08 08:05:57 +00001959 CharUnits eltAlignment =
1960 arrayBase.getAlignment()
1961 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
1962 Address curAddr = Address(cur, eltAlignment);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001963
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001964 // Zero initialize the storage, if requested.
John McCallf677a8e2011-07-13 06:10:41 +00001965 if (zeroInitialize)
John McCall7f416cc2015-09-08 08:05:57 +00001966 EmitNullInitialization(curAddr, type);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001967
1968 // C++ [class.temporary]p4:
Anders Carlsson27da15b2010-01-01 20:29:01 +00001969 // There are two contexts in which temporaries are destroyed at a different
1970 // point than the end of the full-expression. The first context is when a
Justin Bogner1cd11f12015-05-20 15:53:59 +00001971 // default constructor is called to initialize an element of an array.
1972 // If the constructor has one or more default arguments, the destruction of
1973 // every temporary created in a default argument expression is sequenced
Anders Carlsson27da15b2010-01-01 20:29:01 +00001974 // before the construction of the next array element, if any.
Justin Bogner1cd11f12015-05-20 15:53:59 +00001975
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00001976 {
John McCallbd309292010-07-06 01:34:17 +00001977 RunCleanupsScope Scope(*this);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001978
John McCallf677a8e2011-07-13 06:10:41 +00001979 // Evaluate the constructor and its arguments in a regular
1980 // partial-destroy cleanup.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001981 if (getLangOpts().Exceptions &&
John McCallf677a8e2011-07-13 06:10:41 +00001982 !ctor->getParent()->hasTrivialDestructor()) {
1983 Destroyer *destroyer = destroyCXXObject;
John McCall7f416cc2015-09-08 08:05:57 +00001984 pushRegularPartialArrayCleanup(arrayBegin, cur, type, eltAlignment,
1985 *destroyer);
John McCallf677a8e2011-07-13 06:10:41 +00001986 }
Anastasia Stulova094c7262019-04-04 10:48:36 +00001987 auto currAVS = AggValueSlot::forAddr(
1988 curAddr, type.getQualifiers(), AggValueSlot::IsDestructed,
1989 AggValueSlot::DoesNotNeedGCBarriers, AggValueSlot::IsNotAliased,
1990 AggValueSlot::DoesNotOverlap, AggValueSlot::IsNotZeroed,
1991 NewPointerIsChecked ? AggValueSlot::IsSanitizerChecked
1992 : AggValueSlot::IsNotSanitizerChecked);
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001993 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/false,
Anastasia Stulova094c7262019-04-04 10:48:36 +00001994 /*Delegating=*/false, currAVS, E);
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00001995 }
Anders Carlsson27da15b2010-01-01 20:29:01 +00001996
John McCallf677a8e2011-07-13 06:10:41 +00001997 // Go to the next element.
1998 llvm::Value *next =
1999 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
2000 "arrayctor.next");
2001 cur->addIncoming(next, Builder.GetInsertBlock());
Anders Carlsson27da15b2010-01-01 20:29:01 +00002002
John McCallf677a8e2011-07-13 06:10:41 +00002003 // Check whether that's the end of the loop.
2004 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
2005 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
2006 Builder.CreateCondBr(done, contBB, loopBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002007
John McCall6549b312011-07-13 07:37:11 +00002008 // Patch the earlier check to skip over the loop.
2009 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
2010
John McCallf677a8e2011-07-13 06:10:41 +00002011 EmitBlock(contBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002012}
2013
John McCall82fe67b2011-07-09 01:37:26 +00002014void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002015 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002016 QualType type) {
2017 const RecordType *rtype = type->castAs<RecordType>();
2018 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
2019 const CXXDestructorDecl *dtor = record->getDestructor();
2020 assert(!dtor->isTrivial());
2021 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
Marco Antognini88559632019-07-22 09:39:13 +00002022 /*Delegating=*/false, addr, type);
John McCall82fe67b2011-07-09 01:37:26 +00002023}
2024
Alexey Samsonov70b9c012014-08-21 20:26:47 +00002025void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
2026 CXXCtorType Type,
2027 bool ForVirtualBase,
Anastasia Stulova094c7262019-04-04 10:48:36 +00002028 bool Delegating,
2029 AggValueSlot ThisAVS,
2030 const CXXConstructExpr *E) {
Richard Smith5179eb72016-06-28 19:03:57 +00002031 CallArgList Args;
Anastasia Stulova094c7262019-04-04 10:48:36 +00002032 Address This = ThisAVS.getAddress();
2033 LangAS SlotAS = ThisAVS.getQualifiers().getAddressSpace();
Brian Gesiak5488ab42019-01-11 01:54:53 +00002034 QualType ThisType = D->getThisType();
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00002035 LangAS ThisAS = ThisType.getTypePtr()->getPointeeType().getAddressSpace();
2036 llvm::Value *ThisPtr = This.getPointer();
Anastasia Stulova094c7262019-04-04 10:48:36 +00002037
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00002038 if (SlotAS != ThisAS) {
2039 unsigned TargetThisAS = getContext().getTargetAddressSpace(ThisAS);
2040 llvm::Type *NewType =
2041 ThisPtr->getType()->getPointerElementType()->getPointerTo(TargetThisAS);
2042 ThisPtr = getTargetHooks().performAddrSpaceCast(*this, This.getPointer(),
2043 ThisAS, SlotAS, NewType);
2044 }
Anastasia Stulova094c7262019-04-04 10:48:36 +00002045
Richard Smith5179eb72016-06-28 19:03:57 +00002046 // Push the this ptr.
Brian Gesiak5488ab42019-01-11 01:54:53 +00002047 Args.add(RValue::get(ThisPtr), D->getThisType());
Richard Smith5179eb72016-06-28 19:03:57 +00002048
2049 // If this is a trivial constructor, emit a memcpy now before we lose
2050 // the alignment information on the argument.
2051 // FIXME: It would be better to preserve alignment information into CallArg.
2052 if (isMemcpyEquivalentSpecialMember(D)) {
2053 assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
2054
2055 const Expr *Arg = E->getArg(0);
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00002056 LValue Src = EmitLValue(Arg);
Richard Smith5179eb72016-06-28 19:03:57 +00002057 QualType DestTy = getContext().getTypeDeclType(D->getParent());
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00002058 LValue Dest = MakeAddrLValue(This, DestTy);
Anastasia Stulova094c7262019-04-04 10:48:36 +00002059 EmitAggregateCopyCtor(Dest, Src, ThisAVS.mayOverlap());
Richard Smith5179eb72016-06-28 19:03:57 +00002060 return;
2061 }
2062
2063 // Add the rest of the user-supplied arguments.
2064 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
Hans Wennborg27dcc6c2017-02-01 02:21:07 +00002065 EvaluationOrder Order = E->isListInitialization()
2066 ? EvaluationOrder::ForceLeftToRight
2067 : EvaluationOrder::Default;
2068 EmitCallArgs(Args, FPT, E->arguments(), E->getConstructor(),
2069 /*ParamsToSkip*/ 0, Order);
Richard Smith5179eb72016-06-28 19:03:57 +00002070
Richard Smithe78fac52018-04-05 20:52:58 +00002071 EmitCXXConstructorCall(D, Type, ForVirtualBase, Delegating, This, Args,
Anastasia Stulova094c7262019-04-04 10:48:36 +00002072 ThisAVS.mayOverlap(), E->getExprLoc(),
2073 ThisAVS.isSanitizerChecked());
Richard Smith5179eb72016-06-28 19:03:57 +00002074}
2075
2076static bool canEmitDelegateCallArgs(CodeGenFunction &CGF,
2077 const CXXConstructorDecl *Ctor,
2078 CXXCtorType Type, CallArgList &Args) {
2079 // We can't forward a variadic call.
2080 if (Ctor->isVariadic())
2081 return false;
2082
2083 if (CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2084 // If the parameters are callee-cleanup, it's not safe to forward.
2085 for (auto *P : Ctor->parameters())
Richard Smith2b4fa532019-09-29 05:08:46 +00002086 if (P->needsDestruction(CGF.getContext()))
Richard Smith5179eb72016-06-28 19:03:57 +00002087 return false;
2088
2089 // Likewise if they're inalloca.
2090 const CGFunctionInfo &Info =
George Burgess IVd0a9e802017-02-23 22:07:35 +00002091 CGF.CGM.getTypes().arrangeCXXConstructorCall(Args, Ctor, Type, 0, 0);
Richard Smith5179eb72016-06-28 19:03:57 +00002092 if (Info.usesInAlloca())
2093 return false;
2094 }
2095
2096 // Anything else should be OK.
2097 return true;
2098}
2099
2100void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
2101 CXXCtorType Type,
2102 bool ForVirtualBase,
2103 bool Delegating,
2104 Address This,
Richard Smithe78fac52018-04-05 20:52:58 +00002105 CallArgList &Args,
Igor Kudrineff8f9d2018-06-25 05:48:04 +00002106 AggValueSlot::Overlap_t Overlap,
Serge Pavlov37605182018-07-28 15:33:03 +00002107 SourceLocation Loc,
2108 bool NewPointerIsChecked) {
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002109 const CXXRecordDecl *ClassDecl = D->getParent();
2110
Serge Pavlov37605182018-07-28 15:33:03 +00002111 if (!NewPointerIsChecked)
2112 EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall, Loc, This.getPointer(),
2113 getContext().getRecordType(ClassDecl), CharUnits::Zero());
John McCallca972cd2010-02-06 00:25:16 +00002114
Richard Smith419bd092015-04-29 19:26:57 +00002115 if (D->isTrivial() && D->isDefaultConstructor()) {
Richard Smith5179eb72016-06-28 19:03:57 +00002116 assert(Args.size() == 1 && "trivial default ctor with args");
Richard Smith419bd092015-04-29 19:26:57 +00002117 return;
2118 }
2119
2120 // If this is a trivial constructor, just emit what's needed. If this is a
2121 // union copy constructor, we must emit a memcpy, because the AST does not
2122 // model that copy.
2123 if (isMemcpyEquivalentSpecialMember(D)) {
Richard Smith5179eb72016-06-28 19:03:57 +00002124 assert(Args.size() == 2 && "unexpected argcount for trivial ctor");
John McCallca972cd2010-02-06 00:25:16 +00002125
Richard Smith5179eb72016-06-28 19:03:57 +00002126 QualType SrcTy = D->getParamDecl(0)->getType().getNonReferenceType();
Yaxun Liu5b330e82018-03-15 15:25:19 +00002127 Address Src(Args[1].getRValue(*this).getScalarVal(),
2128 getNaturalTypeAlignment(SrcTy));
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00002129 LValue SrcLVal = MakeAddrLValue(Src, SrcTy);
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002130 QualType DestTy = getContext().getTypeDeclType(ClassDecl);
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00002131 LValue DestLVal = MakeAddrLValue(This, DestTy);
Richard Smithe78fac52018-04-05 20:52:58 +00002132 EmitAggregateCopyCtor(DestLVal, SrcLVal, Overlap);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002133 return;
2134 }
2135
George Burgess IVd0a9e802017-02-23 22:07:35 +00002136 bool PassPrototypeArgs = true;
Richard Smith5179eb72016-06-28 19:03:57 +00002137 // Check whether we can actually emit the constructor before trying to do so.
2138 if (auto Inherited = D->getInheritedConstructor()) {
George Burgess IVd0a9e802017-02-23 22:07:35 +00002139 PassPrototypeArgs = getTypes().inheritingCtorHasParams(Inherited, Type);
2140 if (PassPrototypeArgs && !canEmitDelegateCallArgs(*this, D, Type, Args)) {
Richard Smith5179eb72016-06-28 19:03:57 +00002141 EmitInlinedInheritingCXXConstructorCall(D, Type, ForVirtualBase,
2142 Delegating, Args);
2143 return;
2144 }
2145 }
Reid Kleckner89077a12013-12-17 19:46:40 +00002146
2147 // Insert any ABI-specific implicit constructor arguments.
George Burgess IVf203dbf2017-02-22 20:28:02 +00002148 CGCXXABI::AddedStructorArgs ExtraArgs =
2149 CGM.getCXXABI().addImplicitConstructorArgs(*this, D, Type, ForVirtualBase,
2150 Delegating, Args);
Reid Kleckner89077a12013-12-17 19:46:40 +00002151
2152 // Emit the call.
Peter Collingbourned1c5b282019-03-22 23:05:10 +00002153 llvm::Constant *CalleePtr = CGM.getAddrOfCXXStructor(GlobalDecl(D, Type));
George Burgess IVf203dbf2017-02-22 20:28:02 +00002154 const CGFunctionInfo &Info = CGM.getTypes().arrangeCXXConstructorCall(
George Burgess IVd0a9e802017-02-23 22:07:35 +00002155 Args, D, Type, ExtraArgs.Prefix, ExtraArgs.Suffix, PassPrototypeArgs);
Erich Keanede6480a32018-11-13 15:48:08 +00002156 CGCallee Callee = CGCallee::forDirect(CalleePtr, GlobalDecl(D, Type));
John McCallb92ab1a2016-10-26 23:46:34 +00002157 EmitCall(Info, Callee, ReturnValueSlot(), Args);
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002158
2159 // Generate vtable assumptions if we're constructing a complete object
2160 // with a vtable. We don't do this for base subobjects for two reasons:
2161 // first, it's incorrect for classes with virtual bases, and second, we're
2162 // about to overwrite the vptrs anyway.
2163 // We also have to make sure if we can refer to vtable:
2164 // - Otherwise we can refer to vtable if it's safe to speculatively emit.
2165 // FIXME: If vtable is used by ctor/dtor, or if vtable is external and we are
2166 // sure that definition of vtable is not hidden,
2167 // then we are always safe to refer to it.
Piotr Padlewski69dc9712015-09-28 20:30:22 +00002168 // FIXME: It looks like InstCombine is very inefficient on dealing with
2169 // assumes. Make assumption loads require -fstrict-vtable-pointers temporarily.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002170 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2171 ClassDecl->isDynamicClass() && Type != Ctor_Base &&
Piotr Padlewski69dc9712015-09-28 20:30:22 +00002172 CGM.getCXXABI().canSpeculativelyEmitVTable(ClassDecl) &&
2173 CGM.getCodeGenOpts().StrictVTablePointers)
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002174 EmitVTableAssumptionLoads(ClassDecl, This);
2175}
2176
Richard Smith5179eb72016-06-28 19:03:57 +00002177void CodeGenFunction::EmitInheritedCXXConstructorCall(
2178 const CXXConstructorDecl *D, bool ForVirtualBase, Address This,
2179 bool InheritedFromVBase, const CXXInheritedCtorInitExpr *E) {
2180 CallArgList Args;
Brian Gesiak5488ab42019-01-11 01:54:53 +00002181 CallArg ThisArg(RValue::get(This.getPointer()), D->getThisType());
Richard Smith5179eb72016-06-28 19:03:57 +00002182
2183 // Forward the parameters.
2184 if (InheritedFromVBase &&
2185 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
2186 // Nothing to do; this construction is not responsible for constructing
2187 // the base class containing the inherited constructor.
2188 // FIXME: Can we just pass undef's for the remaining arguments if we don't
2189 // have constructor variants?
2190 Args.push_back(ThisArg);
2191 } else if (!CXXInheritedCtorInitExprArgs.empty()) {
2192 // The inheriting constructor was inlined; just inject its arguments.
2193 assert(CXXInheritedCtorInitExprArgs.size() >= D->getNumParams() &&
2194 "wrong number of parameters for inherited constructor call");
2195 Args = CXXInheritedCtorInitExprArgs;
2196 Args[0] = ThisArg;
2197 } else {
2198 // The inheriting constructor was not inlined. Emit delegating arguments.
2199 Args.push_back(ThisArg);
2200 const auto *OuterCtor = cast<CXXConstructorDecl>(CurCodeDecl);
2201 assert(OuterCtor->getNumParams() == D->getNumParams());
2202 assert(!OuterCtor->isVariadic() && "should have been inlined");
2203
2204 for (const auto *Param : OuterCtor->parameters()) {
2205 assert(getContext().hasSameUnqualifiedType(
2206 OuterCtor->getParamDecl(Param->getFunctionScopeIndex())->getType(),
2207 Param->getType()));
2208 EmitDelegateCallArg(Args, Param, E->getLocation());
2209
2210 // Forward __attribute__(pass_object_size).
2211 if (Param->hasAttr<PassObjectSizeAttr>()) {
2212 auto *POSParam = SizeArguments[Param];
2213 assert(POSParam && "missing pass_object_size value for forwarding");
2214 EmitDelegateCallArg(Args, POSParam, E->getLocation());
2215 }
2216 }
2217 }
2218
2219 EmitCXXConstructorCall(D, Ctor_Base, ForVirtualBase, /*Delegating*/false,
Igor Kudrineff8f9d2018-06-25 05:48:04 +00002220 This, Args, AggValueSlot::MayOverlap,
Serge Pavlov37605182018-07-28 15:33:03 +00002221 E->getLocation(), /*NewPointerIsChecked*/true);
Richard Smith5179eb72016-06-28 19:03:57 +00002222}
2223
2224void CodeGenFunction::EmitInlinedInheritingCXXConstructorCall(
2225 const CXXConstructorDecl *Ctor, CXXCtorType CtorType, bool ForVirtualBase,
2226 bool Delegating, CallArgList &Args) {
Adrian Prantlb7acfc02017-02-27 21:30:05 +00002227 GlobalDecl GD(Ctor, CtorType);
2228 InlinedInheritingConstructorScope Scope(*this, GD);
2229 ApplyInlineDebugLocation DebugScope(*this, GD);
Volodymyr Sapsai232d22f2018-12-20 22:43:26 +00002230 RunCleanupsScope RunCleanups(*this);
Richard Smith5179eb72016-06-28 19:03:57 +00002231
2232 // Save the arguments to be passed to the inherited constructor.
2233 CXXInheritedCtorInitExprArgs = Args;
2234
2235 FunctionArgList Params;
2236 QualType RetType = BuildFunctionArgList(CurGD, Params);
2237 FnRetTy = RetType;
2238
2239 // Insert any ABI-specific implicit constructor arguments.
2240 CGM.getCXXABI().addImplicitConstructorArgs(*this, Ctor, CtorType,
2241 ForVirtualBase, Delegating, Args);
2242
2243 // Emit a simplified prolog. We only need to emit the implicit params.
2244 assert(Args.size() >= Params.size() && "too few arguments for call");
2245 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2246 if (I < Params.size() && isa<ImplicitParamDecl>(Params[I])) {
Yaxun Liu5b330e82018-03-15 15:25:19 +00002247 const RValue &RV = Args[I].getRValue(*this);
Richard Smith5179eb72016-06-28 19:03:57 +00002248 assert(!RV.isComplex() && "complex indirect params not supported");
2249 ParamValue Val = RV.isScalar()
2250 ? ParamValue::forDirect(RV.getScalarVal())
2251 : ParamValue::forIndirect(RV.getAggregateAddress());
2252 EmitParmDecl(*Params[I], Val, I + 1);
2253 }
2254 }
2255
2256 // Create a return value slot if the ABI implementation wants one.
2257 // FIXME: This is dumb, we should ask the ABI not to try to set the return
2258 // value instead.
2259 if (!RetType->isVoidType())
2260 ReturnValue = CreateIRTemp(RetType, "retval.inhctor");
2261
2262 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
2263 CXXThisValue = CXXABIThisValue;
2264
2265 // Directly emit the constructor initializers.
2266 EmitCtorPrologue(Ctor, CtorType, Params);
2267}
2268
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002269void CodeGenFunction::EmitVTableAssumptionLoad(const VPtr &Vptr, Address This) {
2270 llvm::Value *VTableGlobal =
2271 CGM.getCXXABI().getVTableAddressPoint(Vptr.Base, Vptr.VTableClass);
2272 if (!VTableGlobal)
2273 return;
2274
2275 // We can just use the base offset in the complete class.
2276 CharUnits NonVirtualOffset = Vptr.Base.getBaseOffset();
2277
2278 if (!NonVirtualOffset.isZero())
2279 This =
2280 ApplyNonVirtualAndVirtualOffset(*this, This, NonVirtualOffset, nullptr,
2281 Vptr.VTableClass, Vptr.NearestVBase);
2282
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002283 llvm::Value *VPtrValue =
2284 GetVTablePtr(This, VTableGlobal->getType(), Vptr.VTableClass);
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002285 llvm::Value *Cmp =
2286 Builder.CreateICmpEQ(VPtrValue, VTableGlobal, "cmp.vtables");
2287 Builder.CreateAssumption(Cmp);
2288}
2289
2290void CodeGenFunction::EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl,
2291 Address This) {
2292 if (CGM.getCXXABI().doStructorsInitializeVPtrs(ClassDecl))
2293 for (const VPtr &Vptr : getVTablePointers(ClassDecl))
2294 EmitVTableAssumptionLoad(Vptr, This);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002295}
2296
John McCallf8ff7b92010-02-23 00:48:20 +00002297void
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002298CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
John McCall7f416cc2015-09-08 08:05:57 +00002299 Address This, Address Src,
2300 const CXXConstructExpr *E) {
Reid Kleckner739756c2013-12-04 19:23:12 +00002301 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
Justin Bogner1cd11f12015-05-20 15:53:59 +00002302
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002303 CallArgList Args;
Justin Bogner1cd11f12015-05-20 15:53:59 +00002304
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002305 // Push the this ptr.
Brian Gesiak5488ab42019-01-11 01:54:53 +00002306 Args.add(RValue::get(This.getPointer()), D->getThisType());
Justin Bogner1cd11f12015-05-20 15:53:59 +00002307
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002308 // Push the src ptr.
Alp Toker9cacbab2014-01-20 20:26:09 +00002309 QualType QT = *(FPT->param_type_begin());
Chris Lattner2192fe52011-07-18 04:24:23 +00002310 llvm::Type *t = CGM.getTypes().ConvertType(QT);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002311 Src = Builder.CreateBitCast(Src, t);
John McCall7f416cc2015-09-08 08:05:57 +00002312 Args.add(RValue::get(Src.getPointer()), QT);
Reid Kleckner739756c2013-12-04 19:23:12 +00002313
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002314 // Skip over first argument (Src).
David Blaikief05779e2015-07-21 18:37:18 +00002315 EmitCallArgs(Args, FPT, drop_begin(E->arguments(), 1), E->getConstructor(),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002316 /*ParamsToSkip*/ 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002317
Serge Pavlov37605182018-07-28 15:33:03 +00002318 EmitCXXConstructorCall(D, Ctor_Complete, /*ForVirtualBase*/false,
2319 /*Delegating*/false, This, Args,
2320 AggValueSlot::MayOverlap, E->getExprLoc(),
2321 /*NewPointerIsChecked*/false);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002322}
2323
2324void
John McCallf8ff7b92010-02-23 00:48:20 +00002325CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
2326 CXXCtorType CtorType,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002327 const FunctionArgList &Args,
2328 SourceLocation Loc) {
John McCallf8ff7b92010-02-23 00:48:20 +00002329 CallArgList DelegateArgs;
2330
2331 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
2332 assert(I != E && "no parameters to constructor");
2333
2334 // this
Richard Smith5179eb72016-06-28 19:03:57 +00002335 Address This = LoadCXXThisAddress();
2336 DelegateArgs.add(RValue::get(This.getPointer()), (*I)->getType());
John McCallf8ff7b92010-02-23 00:48:20 +00002337 ++I;
2338
Richard Smith5179eb72016-06-28 19:03:57 +00002339 // FIXME: The location of the VTT parameter in the parameter list is
2340 // specific to the Itanium ABI and shouldn't be hardcoded here.
2341 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
2342 assert(I != E && "cannot skip vtt parameter, already done with args");
2343 assert((*I)->getType()->isPointerType() &&
2344 "skipping parameter not of vtt type");
2345 ++I;
John McCallf8ff7b92010-02-23 00:48:20 +00002346 }
2347
2348 // Explicit arguments.
2349 for (; I != E; ++I) {
John McCall32ea9692011-03-11 20:59:21 +00002350 const VarDecl *param = *I;
Nick Lewycky2d84e842013-10-02 02:29:49 +00002351 // FIXME: per-argument source location
2352 EmitDelegateCallArg(DelegateArgs, param, Loc);
John McCallf8ff7b92010-02-23 00:48:20 +00002353 }
2354
Richard Smith5179eb72016-06-28 19:03:57 +00002355 EmitCXXConstructorCall(Ctor, CtorType, /*ForVirtualBase=*/false,
Richard Smithe78fac52018-04-05 20:52:58 +00002356 /*Delegating=*/true, This, DelegateArgs,
Serge Pavlov37605182018-07-28 15:33:03 +00002357 AggValueSlot::MayOverlap, Loc,
2358 /*NewPointerIsChecked=*/true);
John McCallf8ff7b92010-02-23 00:48:20 +00002359}
2360
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002361namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002362 struct CallDelegatingCtorDtor final : EHScopeStack::Cleanup {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002363 const CXXDestructorDecl *Dtor;
John McCall7f416cc2015-09-08 08:05:57 +00002364 Address Addr;
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002365 CXXDtorType Type;
2366
John McCall7f416cc2015-09-08 08:05:57 +00002367 CallDelegatingCtorDtor(const CXXDestructorDecl *D, Address Addr,
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002368 CXXDtorType Type)
2369 : Dtor(D), Addr(Addr), Type(Type) {}
2370
Craig Topper4f12f102014-03-12 06:41:41 +00002371 void Emit(CodeGenFunction &CGF, Flags flags) override {
Marco Antognini88559632019-07-22 09:39:13 +00002372 // We are calling the destructor from within the constructor.
2373 // Therefore, "this" should have the expected type.
2374 QualType ThisTy = Dtor->getThisObjectType();
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002375 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
Marco Antognini88559632019-07-22 09:39:13 +00002376 /*Delegating=*/true, Addr, ThisTy);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002377 }
2378 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00002379} // end anonymous namespace
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002380
Alexis Hunt61bc1732011-05-01 07:04:31 +00002381void
2382CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
2383 const FunctionArgList &Args) {
2384 assert(Ctor->isDelegatingConstructor());
2385
John McCall7f416cc2015-09-08 08:05:57 +00002386 Address ThisPtr = LoadCXXThisAddress();
Alexis Hunt61bc1732011-05-01 07:04:31 +00002387
John McCall31168b02011-06-15 23:02:42 +00002388 AggValueSlot AggSlot =
John McCall7f416cc2015-09-08 08:05:57 +00002389 AggValueSlot::forAddr(ThisPtr, Qualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +00002390 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00002391 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00002392 AggValueSlot::IsNotAliased,
Serge Pavlov37605182018-07-28 15:33:03 +00002393 AggValueSlot::MayOverlap,
2394 AggValueSlot::IsNotZeroed,
2395 // Checks are made by the code that calls constructor.
2396 AggValueSlot::IsSanitizerChecked);
Alexis Hunt61bc1732011-05-01 07:04:31 +00002397
2398 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
Alexis Hunt61bc1732011-05-01 07:04:31 +00002399
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002400 const CXXRecordDecl *ClassDecl = Ctor->getParent();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002401 if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002402 CXXDtorType Type =
2403 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
2404
2405 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
2406 ClassDecl->getDestructor(),
2407 ThisPtr, Type);
2408 }
2409}
Alexis Hunt61bc1732011-05-01 07:04:31 +00002410
Anders Carlsson27da15b2010-01-01 20:29:01 +00002411void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
2412 CXXDtorType Type,
Anders Carlssonf8a71f02010-05-02 23:29:11 +00002413 bool ForVirtualBase,
Marco Antognini88559632019-07-22 09:39:13 +00002414 bool Delegating, Address This,
2415 QualType ThisTy) {
Reid Kleckner6fe771a2013-12-13 00:53:54 +00002416 CGM.getCXXABI().EmitDestructorCall(*this, DD, Type, ForVirtualBase,
Marco Antognini88559632019-07-22 09:39:13 +00002417 Delegating, This, ThisTy);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002418}
2419
John McCall53cad2e2010-07-21 01:41:18 +00002420namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002421 struct CallLocalDtor final : EHScopeStack::Cleanup {
John McCall53cad2e2010-07-21 01:41:18 +00002422 const CXXDestructorDecl *Dtor;
John McCall7f416cc2015-09-08 08:05:57 +00002423 Address Addr;
Marco Antognini88559632019-07-22 09:39:13 +00002424 QualType Ty;
John McCall53cad2e2010-07-21 01:41:18 +00002425
Marco Antognini88559632019-07-22 09:39:13 +00002426 CallLocalDtor(const CXXDestructorDecl *D, Address Addr, QualType Ty)
2427 : Dtor(D), Addr(Addr), Ty(Ty) {}
John McCall53cad2e2010-07-21 01:41:18 +00002428
Craig Topper4f12f102014-03-12 06:41:41 +00002429 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall53cad2e2010-07-21 01:41:18 +00002430 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +00002431 /*ForVirtualBase=*/false,
Marco Antognini88559632019-07-22 09:39:13 +00002432 /*Delegating=*/false, Addr, Ty);
John McCall53cad2e2010-07-21 01:41:18 +00002433 }
2434 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002435} // end anonymous namespace
John McCall53cad2e2010-07-21 01:41:18 +00002436
John McCall8680f872010-07-21 06:29:51 +00002437void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
Marco Antognini88559632019-07-22 09:39:13 +00002438 QualType T, Address Addr) {
2439 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr, T);
John McCall8680f872010-07-21 06:29:51 +00002440}
2441
John McCall7f416cc2015-09-08 08:05:57 +00002442void CodeGenFunction::PushDestructorCleanup(QualType T, Address Addr) {
John McCallbd309292010-07-06 01:34:17 +00002443 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
2444 if (!ClassDecl) return;
2445 if (ClassDecl->hasTrivialDestructor()) return;
2446
2447 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCalla85af562011-04-28 02:15:35 +00002448 assert(D && D->isUsed() && "destructor not marked as used!");
Marco Antognini88559632019-07-22 09:39:13 +00002449 PushDestructorCleanup(D, T, Addr);
John McCallbd309292010-07-06 01:34:17 +00002450}
2451
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002452void CodeGenFunction::InitializeVTablePointer(const VPtr &Vptr) {
Anders Carlssone87fae92010-03-28 19:40:00 +00002453 // Compute the address point.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002454 llvm::Value *VTableAddressPoint =
2455 CGM.getCXXABI().getVTableAddressPointInStructor(
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002456 *this, Vptr.VTableClass, Vptr.Base, Vptr.NearestVBase);
2457
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002458 if (!VTableAddressPoint)
2459 return;
Anders Carlssone87fae92010-03-28 19:40:00 +00002460
Anders Carlsson6a0227d2010-04-20 16:22:16 +00002461 // Compute where to store the address point.
Craig Topper8a13c412014-05-21 05:09:00 +00002462 llvm::Value *VirtualOffset = nullptr;
Ken Dyckcfc332c2011-03-23 00:45:26 +00002463 CharUnits NonVirtualOffset = CharUnits::Zero();
Justin Bogner1cd11f12015-05-20 15:53:59 +00002464
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002465 if (CGM.getCXXABI().isVirtualOffsetNeededForVTableField(*this, Vptr)) {
Anders Carlsson91baecf2010-04-20 18:05:10 +00002466 // We need to use the virtual base offset offset because the virtual base
2467 // might have a different offset in the most derived class.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002468
2469 VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(
2470 *this, LoadCXXThisAddress(), Vptr.VTableClass, Vptr.NearestVBase);
2471 NonVirtualOffset = Vptr.OffsetFromNearestVBase;
Anders Carlsson91baecf2010-04-20 18:05:10 +00002472 } else {
Anders Carlssonc58fb552010-05-03 00:29:58 +00002473 // We can just use the base offset in the complete class.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002474 NonVirtualOffset = Vptr.Base.getBaseOffset();
Anders Carlsson91baecf2010-04-20 18:05:10 +00002475 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002476
Anders Carlssonc58fb552010-05-03 00:29:58 +00002477 // Apply the offsets.
John McCall7f416cc2015-09-08 08:05:57 +00002478 Address VTableField = LoadCXXThisAddress();
Justin Bogner1cd11f12015-05-20 15:53:59 +00002479
Ken Dyckcfc332c2011-03-23 00:45:26 +00002480 if (!NonVirtualOffset.isZero() || VirtualOffset)
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002481 VTableField = ApplyNonVirtualAndVirtualOffset(
2482 *this, VTableField, NonVirtualOffset, VirtualOffset, Vptr.VTableClass,
2483 Vptr.NearestVBase);
Anders Carlsson6a0227d2010-04-20 16:22:16 +00002484
Reid Kleckner8d585132014-12-03 21:00:21 +00002485 // Finally, store the address point. Use the same LLVM types as the field to
2486 // support optimization.
2487 llvm::Type *VTablePtrTy =
2488 llvm::FunctionType::get(CGM.Int32Ty, /*isVarArg=*/true)
2489 ->getPointerTo()
2490 ->getPointerTo();
2491 VTableField = Builder.CreateBitCast(VTableField, VTablePtrTy->getPointerTo());
2492 VTableAddressPoint = Builder.CreateBitCast(VTableAddressPoint, VTablePtrTy);
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002493
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002494 llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
Ivan A. Kosarev4e50e702017-11-27 09:39:29 +00002495 TBAAAccessInfo TBAAInfo = CGM.getTBAAVTablePtrAccessInfo(VTablePtrTy);
2496 CGM.DecorateInstructionWithTBAA(Store, TBAAInfo);
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002497 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2498 CGM.getCodeGenOpts().StrictVTablePointers)
2499 CGM.DecorateInstructionWithInvariantGroup(Store, Vptr.VTableClass);
Anders Carlssone87fae92010-03-28 19:40:00 +00002500}
2501
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002502CodeGenFunction::VPtrsVector
2503CodeGenFunction::getVTablePointers(const CXXRecordDecl *VTableClass) {
2504 CodeGenFunction::VPtrsVector VPtrsResult;
2505 VisitedVirtualBasesSetTy VBases;
2506 getVTablePointers(BaseSubobject(VTableClass, CharUnits::Zero()),
2507 /*NearestVBase=*/nullptr,
2508 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
2509 /*BaseIsNonVirtualPrimaryBase=*/false, VTableClass, VBases,
2510 VPtrsResult);
2511 return VPtrsResult;
2512}
2513
2514void CodeGenFunction::getVTablePointers(BaseSubobject Base,
2515 const CXXRecordDecl *NearestVBase,
2516 CharUnits OffsetFromNearestVBase,
2517 bool BaseIsNonVirtualPrimaryBase,
2518 const CXXRecordDecl *VTableClass,
2519 VisitedVirtualBasesSetTy &VBases,
2520 VPtrsVector &Vptrs) {
Anders Carlssond5895932010-03-28 21:07:49 +00002521 // If this base is a non-virtual primary base the address point has already
2522 // been set.
2523 if (!BaseIsNonVirtualPrimaryBase) {
2524 // Initialize the vtable pointer for this base.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002525 VPtr Vptr = {Base, NearestVBase, OffsetFromNearestVBase, VTableClass};
2526 Vptrs.push_back(Vptr);
Anders Carlssond5895932010-03-28 21:07:49 +00002527 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002528
Anders Carlssond5895932010-03-28 21:07:49 +00002529 const CXXRecordDecl *RD = Base.getBase();
2530
2531 // Traverse bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00002532 for (const auto &I : RD->bases()) {
Simon Pilgrim1cd399c2019-10-03 11:22:48 +00002533 auto *BaseDecl =
2534 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
Anders Carlssond5895932010-03-28 21:07:49 +00002535
2536 // Ignore classes without a vtable.
2537 if (!BaseDecl->isDynamicClass())
2538 continue;
2539
Ken Dyck3fb4c892011-03-23 01:04:18 +00002540 CharUnits BaseOffset;
2541 CharUnits BaseOffsetFromNearestVBase;
Anders Carlsson948d3f42010-03-29 01:16:41 +00002542 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlssond5895932010-03-28 21:07:49 +00002543
Aaron Ballman574705e2014-03-13 15:41:46 +00002544 if (I.isVirtual()) {
Anders Carlssond5895932010-03-28 21:07:49 +00002545 // Check if we've visited this virtual base before.
David Blaikie82e95a32014-11-19 07:49:47 +00002546 if (!VBases.insert(BaseDecl).second)
Anders Carlssond5895932010-03-28 21:07:49 +00002547 continue;
2548
Justin Bogner1cd11f12015-05-20 15:53:59 +00002549 const ASTRecordLayout &Layout =
Anders Carlssond5895932010-03-28 21:07:49 +00002550 getContext().getASTRecordLayout(VTableClass);
2551
Ken Dyck3fb4c892011-03-23 01:04:18 +00002552 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
2553 BaseOffsetFromNearestVBase = CharUnits::Zero();
Anders Carlsson948d3f42010-03-29 01:16:41 +00002554 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlssond5895932010-03-28 21:07:49 +00002555 } else {
2556 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
2557
Ken Dyck16ffcac2011-03-24 01:21:01 +00002558 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
Justin Bogner1cd11f12015-05-20 15:53:59 +00002559 BaseOffsetFromNearestVBase =
Ken Dyck3fb4c892011-03-23 01:04:18 +00002560 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson948d3f42010-03-29 01:16:41 +00002561 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlssond5895932010-03-28 21:07:49 +00002562 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002563
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002564 getVTablePointers(
2565 BaseSubobject(BaseDecl, BaseOffset),
2566 I.isVirtual() ? BaseDecl : NearestVBase, BaseOffsetFromNearestVBase,
2567 BaseDeclIsNonVirtualPrimaryBase, VTableClass, VBases, Vptrs);
Anders Carlssond5895932010-03-28 21:07:49 +00002568 }
2569}
2570
2571void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
2572 // Ignore classes without a vtable.
Anders Carlsson1f9348c2010-03-26 04:39:42 +00002573 if (!RD->isDynamicClass())
Anders Carlsson27da15b2010-01-01 20:29:01 +00002574 return;
2575
Anders Carlssond5895932010-03-28 21:07:49 +00002576 // Initialize the vtable pointers for this class and all of its bases.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002577 if (CGM.getCXXABI().doStructorsInitializeVPtrs(RD))
2578 for (const VPtr &Vptr : getVTablePointers(RD))
2579 InitializeVTablePointer(Vptr);
Timur Iskhodzhanovb6487322013-10-09 18:16:58 +00002580
2581 if (RD->getNumVBases())
2582 CGM.getCXXABI().initializeHiddenVirtualInheritanceMembers(*this, RD);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002583}
Dan Gohman8fc50c22010-10-26 18:44:08 +00002584
John McCall7f416cc2015-09-08 08:05:57 +00002585llvm::Value *CodeGenFunction::GetVTablePtr(Address This,
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002586 llvm::Type *VTableTy,
2587 const CXXRecordDecl *RD) {
2588 Address VTablePtrSrc = Builder.CreateElementBitCast(This, VTableTy);
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002589 llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
Ivan A. Kosarev4e50e702017-11-27 09:39:29 +00002590 TBAAAccessInfo TBAAInfo = CGM.getTBAAVTablePtrAccessInfo(VTableTy);
2591 CGM.DecorateInstructionWithTBAA(VTable, TBAAInfo);
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002592
2593 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2594 CGM.getCodeGenOpts().StrictVTablePointers)
2595 CGM.DecorateInstructionWithInvariantGroup(VTable, RD);
2596
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002597 return VTable;
Dan Gohman8fc50c22010-10-26 18:44:08 +00002598}
Anders Carlssonc36783e2011-05-08 20:32:23 +00002599
Peter Collingbourned2926c92015-03-14 02:42:25 +00002600// If a class has a single non-virtual base and does not introduce or override
2601// virtual member functions or fields, it will have the same layout as its base.
2602// This function returns the least derived such class.
2603//
2604// Casting an instance of a base class to such a derived class is technically
2605// undefined behavior, but it is a relatively common hack for introducing member
2606// functions on class instances with specific properties (e.g. llvm::Operator)
2607// that works under most compilers and should not have security implications, so
2608// we allow it by default. It can be disabled with -fsanitize=cfi-cast-strict.
2609static const CXXRecordDecl *
2610LeastDerivedClassWithSameLayout(const CXXRecordDecl *RD) {
2611 if (!RD->field_empty())
2612 return RD;
2613
2614 if (RD->getNumVBases() != 0)
2615 return RD;
2616
2617 if (RD->getNumBases() != 1)
2618 return RD;
2619
2620 for (const CXXMethodDecl *MD : RD->methods()) {
2621 if (MD->isVirtual()) {
2622 // Virtual member functions are only ok if they are implicit destructors
2623 // because the implicit destructor will have the same semantics as the
2624 // base class's destructor if no fields are added.
2625 if (isa<CXXDestructorDecl>(MD) && MD->isImplicit())
2626 continue;
2627 return RD;
2628 }
2629 }
2630
2631 return LeastDerivedClassWithSameLayout(
2632 RD->bases_begin()->getType()->getAsCXXRecordDecl());
2633}
2634
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002635void CodeGenFunction::EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD,
2636 llvm::Value *VTable,
2637 SourceLocation Loc) {
Peter Collingbourne396943a2017-07-31 22:35:33 +00002638 if (SanOpts.has(SanitizerKind::CFIVCall))
2639 EmitVTablePtrCheckForCall(RD, VTable, CodeGenFunction::CFITCK_VCall, Loc);
2640 else if (CGM.getCodeGenOpts().WholeProgramVTables &&
2641 CGM.HasHiddenLTOVisibility(RD)) {
Peter Collingbournefb532b92016-02-24 20:46:36 +00002642 llvm::Metadata *MD =
2643 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002644 llvm::Value *TypeId =
Peter Collingbournefb532b92016-02-24 20:46:36 +00002645 llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD);
2646
2647 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002648 llvm::Value *TypeTest =
2649 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
2650 {CastedVTable, TypeId});
2651 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::assume), TypeTest);
Peter Collingbournefb532b92016-02-24 20:46:36 +00002652 }
Peter Collingbournefb532b92016-02-24 20:46:36 +00002653}
2654
2655void CodeGenFunction::EmitVTablePtrCheckForCall(const CXXRecordDecl *RD,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002656 llvm::Value *VTable,
2657 CFITypeCheckKind TCK,
2658 SourceLocation Loc) {
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002659 if (!SanOpts.has(SanitizerKind::CFICastStrict))
Peter Collingbournefb532b92016-02-24 20:46:36 +00002660 RD = LeastDerivedClassWithSameLayout(RD);
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002661
Peter Collingbournefb532b92016-02-24 20:46:36 +00002662 EmitVTablePtrCheck(RD, VTable, TCK, Loc);
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002663}
2664
Peter Collingbourned2926c92015-03-14 02:42:25 +00002665void CodeGenFunction::EmitVTablePtrCheckForCast(QualType T,
2666 llvm::Value *Derived,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002667 bool MayBeNull,
2668 CFITypeCheckKind TCK,
2669 SourceLocation Loc) {
Peter Collingbourned2926c92015-03-14 02:42:25 +00002670 if (!getLangOpts().CPlusPlus)
2671 return;
2672
2673 auto *ClassTy = T->getAs<RecordType>();
2674 if (!ClassTy)
2675 return;
2676
2677 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassTy->getDecl());
2678
2679 if (!ClassDecl->isCompleteDefinition() || !ClassDecl->isDynamicClass())
2680 return;
2681
Peter Collingbourned2926c92015-03-14 02:42:25 +00002682 if (!SanOpts.has(SanitizerKind::CFICastStrict))
2683 ClassDecl = LeastDerivedClassWithSameLayout(ClassDecl);
2684
Hans Wennborgdcfba332015-10-06 23:40:43 +00002685 llvm::BasicBlock *ContBlock = nullptr;
Peter Collingbourned2926c92015-03-14 02:42:25 +00002686
2687 if (MayBeNull) {
2688 llvm::Value *DerivedNotNull =
2689 Builder.CreateIsNotNull(Derived, "cast.nonnull");
2690
2691 llvm::BasicBlock *CheckBlock = createBasicBlock("cast.check");
2692 ContBlock = createBasicBlock("cast.cont");
2693
2694 Builder.CreateCondBr(DerivedNotNull, CheckBlock, ContBlock);
2695
2696 EmitBlock(CheckBlock);
2697 }
2698
Peter Collingbourne60108802017-12-13 21:53:04 +00002699 llvm::Value *VTable;
2700 std::tie(VTable, ClassDecl) = CGM.getCXXABI().LoadVTablePtr(
2701 *this, Address(Derived, getPointerAlign()), ClassDecl);
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002702
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002703 EmitVTablePtrCheck(ClassDecl, VTable, TCK, Loc);
Peter Collingbourned2926c92015-03-14 02:42:25 +00002704
2705 if (MayBeNull) {
2706 Builder.CreateBr(ContBlock);
2707 EmitBlock(ContBlock);
2708 }
2709}
2710
2711void CodeGenFunction::EmitVTablePtrCheck(const CXXRecordDecl *RD,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002712 llvm::Value *VTable,
2713 CFITypeCheckKind TCK,
2714 SourceLocation Loc) {
Peter Collingbourne3afb2662016-04-28 17:09:37 +00002715 if (!CGM.getCodeGenOpts().SanitizeCfiCrossDso &&
2716 !CGM.HasHiddenLTOVisibility(RD))
2717 return;
2718
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002719 SanitizerMask M;
Peter Collingbournedc134532016-01-16 00:31:22 +00002720 llvm::SanitizerStatKind SSK;
2721 switch (TCK) {
2722 case CFITCK_VCall:
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002723 M = SanitizerKind::CFIVCall;
Peter Collingbournedc134532016-01-16 00:31:22 +00002724 SSK = llvm::SanStat_CFI_VCall;
2725 break;
2726 case CFITCK_NVCall:
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002727 M = SanitizerKind::CFINVCall;
Peter Collingbournedc134532016-01-16 00:31:22 +00002728 SSK = llvm::SanStat_CFI_NVCall;
2729 break;
2730 case CFITCK_DerivedCast:
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002731 M = SanitizerKind::CFIDerivedCast;
Peter Collingbournedc134532016-01-16 00:31:22 +00002732 SSK = llvm::SanStat_CFI_DerivedCast;
2733 break;
2734 case CFITCK_UnrelatedCast:
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002735 M = SanitizerKind::CFIUnrelatedCast;
Peter Collingbournedc134532016-01-16 00:31:22 +00002736 SSK = llvm::SanStat_CFI_UnrelatedCast;
2737 break;
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002738 case CFITCK_ICall:
Peter Collingbournee44acad2018-06-26 02:15:47 +00002739 case CFITCK_NVMFCall:
2740 case CFITCK_VMFCall:
2741 llvm_unreachable("unexpected sanitizer kind");
Peter Collingbournedc134532016-01-16 00:31:22 +00002742 }
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002743
2744 std::string TypeName = RD->getQualifiedNameAsString();
2745 if (getContext().getSanitizerBlacklist().isBlacklistedType(M, TypeName))
2746 return;
2747
2748 SanitizerScope SanScope(this);
Peter Collingbournedc134532016-01-16 00:31:22 +00002749 EmitSanitizerStatReport(SSK);
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002750
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002751 llvm::Metadata *MD =
2752 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002753 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002754
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002755 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002756 llvm::Value *TypeTest = Builder.CreateCall(
2757 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, TypeId});
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002758
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002759 llvm::Constant *StaticData[] = {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002760 llvm::ConstantInt::get(Int8Ty, TCK),
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002761 EmitCheckSourceLocation(Loc),
2762 EmitCheckTypeDescriptor(QualType(RD->getTypeForDecl(), 0)),
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002763 };
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002764
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002765 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
2766 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
2767 EmitCfiSlowPathCheck(M, TypeTest, CrossDsoTypeId, CastedVTable, StaticData);
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002768 return;
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002769 }
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002770
2771 if (CGM.getCodeGenOpts().SanitizeTrap.has(M)) {
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002772 EmitTrapCheck(TypeTest);
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002773 return;
2774 }
2775
2776 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
2777 CGM.getLLVMContext(),
2778 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002779 llvm::Value *ValidVtable = Builder.CreateCall(
2780 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, AllVtables});
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002781 EmitCheck(std::make_pair(TypeTest, M), SanitizerHandler::CFICheckFail,
2782 StaticData, {CastedVTable, ValidVtable});
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002783}
Anders Carlssonc36783e2011-05-08 20:32:23 +00002784
Peter Collingbourne0ca03632016-06-25 00:24:06 +00002785bool CodeGenFunction::ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD) {
2786 if (!CGM.getCodeGenOpts().WholeProgramVTables ||
2787 !SanOpts.has(SanitizerKind::CFIVCall) ||
2788 !CGM.getCodeGenOpts().SanitizeTrap.has(SanitizerKind::CFIVCall) ||
2789 !CGM.HasHiddenLTOVisibility(RD))
2790 return false;
2791
2792 std::string TypeName = RD->getQualifiedNameAsString();
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002793 return !getContext().getSanitizerBlacklist().isBlacklistedType(
2794 SanitizerKind::CFIVCall, TypeName);
Peter Collingbourne0ca03632016-06-25 00:24:06 +00002795}
2796
2797llvm::Value *CodeGenFunction::EmitVTableTypeCheckedLoad(
2798 const CXXRecordDecl *RD, llvm::Value *VTable, uint64_t VTableByteOffset) {
2799 SanitizerScope SanScope(this);
2800
2801 EmitSanitizerStatReport(llvm::SanStat_CFI_VCall);
2802
2803 llvm::Metadata *MD =
2804 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
2805 llvm::Value *TypeId = llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD);
2806
2807 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
2808 llvm::Value *CheckedLoad = Builder.CreateCall(
2809 CGM.getIntrinsic(llvm::Intrinsic::type_checked_load),
2810 {CastedVTable, llvm::ConstantInt::get(Int32Ty, VTableByteOffset),
2811 TypeId});
2812 llvm::Value *CheckResult = Builder.CreateExtractValue(CheckedLoad, 1);
2813
2814 EmitCheck(std::make_pair(CheckResult, SanitizerKind::CFIVCall),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002815 SanitizerHandler::CFICheckFail, nullptr, nullptr);
Peter Collingbourne0ca03632016-06-25 00:24:06 +00002816
2817 return Builder.CreateBitCast(
2818 Builder.CreateExtractValue(CheckedLoad, 0),
2819 cast<llvm::PointerType>(VTable->getType())->getElementType());
2820}
2821
Faisal Vali571df122013-09-29 08:45:24 +00002822void CodeGenFunction::EmitForwardingCallToLambda(
2823 const CXXMethodDecl *callOperator,
2824 CallArgList &callArgs) {
Eli Friedman5b446882012-02-16 03:47:28 +00002825 // Get the address of the call operator.
John McCall8dda7b22012-07-07 06:41:13 +00002826 const CGFunctionInfo &calleeFnInfo =
2827 CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
John McCallb92ab1a2016-10-26 23:46:34 +00002828 llvm::Constant *calleePtr =
John McCall8dda7b22012-07-07 06:41:13 +00002829 CGM.GetAddrOfFunction(GlobalDecl(callOperator),
2830 CGM.getTypes().GetFunctionType(calleeFnInfo));
Eli Friedman5b446882012-02-16 03:47:28 +00002831
John McCall8dda7b22012-07-07 06:41:13 +00002832 // Prepare the return slot.
2833 const FunctionProtoType *FPT =
2834 callOperator->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00002835 QualType resultType = FPT->getReturnType();
John McCall8dda7b22012-07-07 06:41:13 +00002836 ReturnValueSlot returnSlot;
2837 if (!resultType->isVoidType() &&
2838 calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
John McCall47fb9502013-03-07 21:37:08 +00002839 !hasScalarEvaluationKind(calleeFnInfo.getReturnType()))
John McCall8dda7b22012-07-07 06:41:13 +00002840 returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
2841
2842 // We don't need to separately arrange the call arguments because
2843 // the call can't be variadic anyway --- it's impossible to forward
2844 // variadic arguments.
Justin Bogner1cd11f12015-05-20 15:53:59 +00002845
Eli Friedman5b446882012-02-16 03:47:28 +00002846 // Now emit our call.
Erich Keanede6480a32018-11-13 15:48:08 +00002847 auto callee = CGCallee::forDirect(calleePtr, GlobalDecl(callOperator));
John McCallb92ab1a2016-10-26 23:46:34 +00002848 RValue RV = EmitCall(calleeFnInfo, callee, returnSlot, callArgs);
Eli Friedman5b446882012-02-16 03:47:28 +00002849
John McCall8dda7b22012-07-07 06:41:13 +00002850 // If necessary, copy the returned value into the slot.
John McCall95088452017-12-14 18:21:14 +00002851 if (!resultType->isVoidType() && returnSlot.isNull()) {
2852 if (getLangOpts().ObjCAutoRefCount && resultType->isObjCRetainableType()) {
2853 RV = RValue::get(EmitARCRetainAutoreleasedReturnValue(RV.getScalarVal()));
2854 }
John McCall8dda7b22012-07-07 06:41:13 +00002855 EmitReturnOfRValue(RV, resultType);
John McCall95088452017-12-14 18:21:14 +00002856 } else
Eli Friedmanf5f4d2f2012-12-13 23:37:17 +00002857 EmitBranchThroughCleanup(ReturnBlock);
Eli Friedman5b446882012-02-16 03:47:28 +00002858}
2859
Eli Friedman2495ab02012-02-25 02:48:22 +00002860void CodeGenFunction::EmitLambdaBlockInvokeBody() {
2861 const BlockDecl *BD = BlockInfo->getBlockDecl();
2862 const VarDecl *variable = BD->capture_begin()->getVariable();
2863 const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
Reid Kleckner2d3c4212017-08-04 22:38:06 +00002864 const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
2865
2866 if (CallOp->isVariadic()) {
2867 // FIXME: Making this work correctly is nasty because it requires either
2868 // cloning the body of the call operator or making the call operator
2869 // forward.
2870 CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function");
2871 return;
2872 }
Eli Friedman2495ab02012-02-25 02:48:22 +00002873
2874 // Start building arguments for forwarding call
2875 CallArgList CallArgs;
2876
2877 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
Akira Hatanaka8e57b072018-10-01 21:51:28 +00002878 Address ThisPtr = GetAddrOfBlockDecl(variable);
John McCall7f416cc2015-09-08 08:05:57 +00002879 CallArgs.add(RValue::get(ThisPtr.getPointer()), ThisType);
Eli Friedman2495ab02012-02-25 02:48:22 +00002880
2881 // Add the rest of the parameters.
David Majnemer59f77922016-06-24 04:05:48 +00002882 for (auto param : BD->parameters())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002883 EmitDelegateCallArg(CallArgs, param, param->getBeginLoc());
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00002884
Justin Bogner1cd11f12015-05-20 15:53:59 +00002885 assert(!Lambda->isGenericLambda() &&
Faisal Vali571df122013-09-29 08:45:24 +00002886 "generic lambda interconversion to block not implemented");
Reid Kleckner2d3c4212017-08-04 22:38:06 +00002887 EmitForwardingCallToLambda(CallOp, CallArgs);
Eli Friedman2495ab02012-02-25 02:48:22 +00002888}
2889
2890void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
2891 const CXXRecordDecl *Lambda = MD->getParent();
2892
2893 // Start building arguments for forwarding call
2894 CallArgList CallArgs;
2895
2896 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2897 llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
2898 CallArgs.add(RValue::get(ThisPtr), ThisType);
2899
2900 // Add the rest of the parameters.
David Majnemer59f77922016-06-24 04:05:48 +00002901 for (auto Param : MD->parameters())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002902 EmitDelegateCallArg(CallArgs, Param, Param->getBeginLoc());
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002903
Faisal Vali571df122013-09-29 08:45:24 +00002904 const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
2905 // For a generic lambda, find the corresponding call operator specialization
2906 // to which the call to the static-invoker shall be forwarded.
2907 if (Lambda->isGenericLambda()) {
2908 assert(MD->isFunctionTemplateSpecialization());
2909 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
2910 FunctionTemplateDecl *CallOpTemplate = CallOp->getDescribedFunctionTemplate();
Craig Topper8a13c412014-05-21 05:09:00 +00002911 void *InsertPos = nullptr;
Justin Bogner1cd11f12015-05-20 15:53:59 +00002912 FunctionDecl *CorrespondingCallOpSpecialization =
Craig Topper7e0daca2014-06-26 04:58:53 +00002913 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
Faisal Vali571df122013-09-29 08:45:24 +00002914 assert(CorrespondingCallOpSpecialization);
2915 CallOp = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
2916 }
2917 EmitForwardingCallToLambda(CallOp, CallArgs);
Eli Friedman2495ab02012-02-25 02:48:22 +00002918}
2919
Reid Kleckner2d3c4212017-08-04 22:38:06 +00002920void CodeGenFunction::EmitLambdaStaticInvokeBody(const CXXMethodDecl *MD) {
Douglas Gregor355efbb2012-02-17 03:02:34 +00002921 if (MD->isVariadic()) {
Eli Friedman5b446882012-02-16 03:47:28 +00002922 // FIXME: Making this work correctly is nasty because it requires either
2923 // cloning the body of the call operator or making the call operator forward.
2924 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
Eli Friedman2495ab02012-02-25 02:48:22 +00002925 return;
Eli Friedman5b446882012-02-16 03:47:28 +00002926 }
2927
Douglas Gregor355efbb2012-02-17 03:02:34 +00002928 EmitLambdaDelegatingInvokeBody(MD);
Eli Friedman5a6d5072012-02-16 01:37:33 +00002929}