blob: d4df3109fe954306be44dc0f391b9731c381612c [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
164 const CXXRecordDecl *BaseDecl =
Anders Carlssond829a022010-04-24 21:06:20 +0000165 cast<CXXRecordDecl>(Base->getType()->getAs<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()) {
Justin Bogner1cd11f12015-05-20 15:53:59 +0000282 VBase =
Anders Carlssond829a022010-04-24 21:06:20 +0000283 cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
284 ++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();
John McCall7f416cc2015-09-08 08:05:57 +0000494 Address Addr =
495 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThisAddress(),
John McCallf99a6312010-07-21 05:30:47 +0000496 DerivedClass, BaseClass,
497 BaseIsVirtual);
Douglas Gregor61535002013-01-31 05:50:40 +0000498 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual,
499 /*Delegating=*/false, Addr);
John McCall1d987562010-07-21 01:23:41 +0000500 }
501 };
John McCall769250e2010-09-17 02:31:44 +0000502
503 /// A visitor which checks whether an initializer uses 'this' in a
504 /// way which requires the vtable to be properly set.
Scott Douglass503fc392015-06-10 13:53:15 +0000505 struct DynamicThisUseChecker : ConstEvaluatedExprVisitor<DynamicThisUseChecker> {
506 typedef ConstEvaluatedExprVisitor<DynamicThisUseChecker> super;
John McCall769250e2010-09-17 02:31:44 +0000507
508 bool UsesThis;
509
Scott Douglass503fc392015-06-10 13:53:15 +0000510 DynamicThisUseChecker(const ASTContext &C) : super(C), UsesThis(false) {}
John McCall769250e2010-09-17 02:31:44 +0000511
512 // Black-list all explicit and implicit references to 'this'.
513 //
514 // Do we need to worry about external references to 'this' derived
515 // from arbitrary code? If so, then anything which runs arbitrary
516 // external code might potentially access the vtable.
Scott Douglass503fc392015-06-10 13:53:15 +0000517 void VisitCXXThisExpr(const CXXThisExpr *E) { UsesThis = true; }
John McCall769250e2010-09-17 02:31:44 +0000518 };
Hans Wennborgdcfba332015-10-06 23:40:43 +0000519} // end anonymous namespace
John McCall769250e2010-09-17 02:31:44 +0000520
521static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
522 DynamicThisUseChecker Checker(C);
Scott Douglass503fc392015-06-10 13:53:15 +0000523 Checker.Visit(Init);
John McCall769250e2010-09-17 02:31:44 +0000524 return Checker.UsesThis;
John McCall1d987562010-07-21 01:23:41 +0000525}
526
Justin Bogner1cd11f12015-05-20 15:53:59 +0000527static void EmitBaseInitializer(CodeGenFunction &CGF,
Anders Carlssonfb404882009-12-24 22:46:43 +0000528 const CXXRecordDecl *ClassDecl,
Reid Kleckner61c9b7c2019-03-18 22:41:50 +0000529 CXXCtorInitializer *BaseInit) {
Anders Carlssonfb404882009-12-24 22:46:43 +0000530 assert(BaseInit->isBaseInitializer() &&
531 "Must have base initializer!");
532
John McCall7f416cc2015-09-08 08:05:57 +0000533 Address ThisPtr = CGF.LoadCXXThisAddress();
Justin Bogner1cd11f12015-05-20 15:53:59 +0000534
Anders Carlssonfb404882009-12-24 22:46:43 +0000535 const Type *BaseType = BaseInit->getBaseClass();
536 CXXRecordDecl *BaseClassDecl =
537 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
538
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +0000539 bool isBaseVirtual = BaseInit->isBaseVirtual();
Anders Carlssonfb404882009-12-24 22:46:43 +0000540
John McCall769250e2010-09-17 02:31:44 +0000541 // If the initializer for the base (other than the constructor
542 // itself) accesses 'this' in any way, we need to initialize the
543 // vtables.
544 if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
545 CGF.InitializeVTablePointers(ClassDecl);
546
John McCall6ce74722010-02-16 04:15:37 +0000547 // We can pretend to be a complete class because it only matters for
548 // virtual bases, and we only do virtual bases for complete ctors.
John McCall7f416cc2015-09-08 08:05:57 +0000549 Address V =
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000550 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
John McCallf99a6312010-07-21 05:30:47 +0000551 BaseClassDecl,
552 isBaseVirtual);
John McCall8d6fc952011-08-25 20:40:09 +0000553 AggValueSlot AggSlot =
Richard Smithe78fac52018-04-05 20:52:58 +0000554 AggValueSlot::forAddr(
555 V, Qualifiers(),
556 AggValueSlot::IsDestructed,
557 AggValueSlot::DoesNotNeedGCBarriers,
558 AggValueSlot::IsNotAliased,
559 CGF.overlapForBaseInit(ClassDecl, BaseClassDecl, isBaseVirtual));
John McCall7a626f62010-09-15 10:14:12 +0000560
561 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000562
563 if (CGF.CGM.getLangOpts().Exceptions &&
Anders Carlsson08ce5ed2011-02-20 00:20:27 +0000564 !BaseClassDecl->hasTrivialDestructor())
John McCallcda666c2010-07-21 07:22:38 +0000565 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
566 isBaseVirtual);
Anders Carlssonfb404882009-12-24 22:46:43 +0000567}
568
Richard Smith419bd092015-04-29 19:26:57 +0000569static bool isMemcpyEquivalentSpecialMember(const CXXMethodDecl *D) {
570 auto *CD = dyn_cast<CXXConstructorDecl>(D);
571 if (!(CD && CD->isCopyOrMoveConstructor()) &&
572 !D->isCopyAssignmentOperator() && !D->isMoveAssignmentOperator())
573 return false;
574
575 // We can emit a memcpy for a trivial copy or move constructor/assignment.
576 if (D->isTrivial() && !D->getParent()->mayInsertExtraPadding())
577 return true;
578
579 // We *must* emit a memcpy for a defaulted union copy or move op.
580 if (D->getParent()->isUnion() && D->isDefaulted())
581 return true;
582
583 return false;
584}
585
Alexey Bataev152c71f2015-07-14 07:55:48 +0000586static void EmitLValueForAnyFieldInitialization(CodeGenFunction &CGF,
587 CXXCtorInitializer *MemberInit,
588 LValue &LHS) {
589 FieldDecl *Field = MemberInit->getAnyMember();
590 if (MemberInit->isIndirectMemberInitializer()) {
591 // If we are initializing an anonymous union field, drill down to the field.
592 IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember();
593 for (const auto *I : IndirectField->chain())
594 LHS = CGF.EmitLValueForFieldInitialization(LHS, cast<FieldDecl>(I));
595 } else {
596 LHS = CGF.EmitLValueForFieldInitialization(LHS, Field);
597 }
598}
599
Anders Carlssonfb404882009-12-24 22:46:43 +0000600static void EmitMemberInitializer(CodeGenFunction &CGF,
601 const CXXRecordDecl *ClassDecl,
Alexis Hunt1d792652011-01-08 20:30:50 +0000602 CXXCtorInitializer *MemberInit,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000603 const CXXConstructorDecl *Constructor,
604 FunctionArgList &Args) {
David Blaikiea81d4102015-01-18 00:12:58 +0000605 ApplyDebugLocation Loc(CGF, MemberInit->getSourceLocation());
Francois Pichetd583da02010-12-04 09:14:42 +0000606 assert(MemberInit->isAnyMemberInitializer() &&
Anders Carlssonfb404882009-12-24 22:46:43 +0000607 "Must have member initializer!");
Richard Smith938f40b2011-06-11 17:19:42 +0000608 assert(MemberInit->getInit() && "Must have initializer!");
Justin Bogner1cd11f12015-05-20 15:53:59 +0000609
Anders Carlssonfb404882009-12-24 22:46:43 +0000610 // non-static data member initializers.
Francois Pichetd583da02010-12-04 09:14:42 +0000611 FieldDecl *Field = MemberInit->getAnyMember();
Eli Friedman6ae63022012-02-14 02:15:49 +0000612 QualType FieldType = Field->getType();
Anders Carlssonfb404882009-12-24 22:46:43 +0000613
614 llvm::Value *ThisPtr = CGF.LoadCXXThis();
Eli Friedman7f1ff602012-04-16 03:54:45 +0000615 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
Akira Hatanakae5dbb642018-01-27 00:34:09 +0000616 LValue LHS;
617
618 // If a base constructor is being emitted, create an LValue that has the
619 // non-virtual alignment.
620 if (CGF.CurGD.getCtorType() == Ctor_Base)
621 LHS = CGF.MakeNaturalAlignPointeeAddrLValue(ThisPtr, RecordTy);
622 else
623 LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
Eli Friedman7f1ff602012-04-16 03:54:45 +0000624
Alexey Bataev152c71f2015-07-14 07:55:48 +0000625 EmitLValueForAnyFieldInitialization(CGF, MemberInit, LHS);
Anders Carlssonfb404882009-12-24 22:46:43 +0000626
Eli Friedman6ae63022012-02-14 02:15:49 +0000627 // Special case: if we are in a copy or move constructor, and we are copying
628 // an array of PODs or classes with trivial copy constructors, ignore the
629 // AST and perform the copy we know is equivalent.
630 // FIXME: This is hacky at best... if we had a bit more explicit information
631 // in the AST, we could generalize it more easily.
632 const ConstantArrayType *Array
633 = CGF.getContext().getAsConstantArrayType(FieldType);
Jordan Rose54533f72013-08-07 16:16:48 +0000634 if (Array && Constructor->isDefaulted() &&
Eli Friedman6ae63022012-02-14 02:15:49 +0000635 Constructor->isCopyOrMoveConstructor()) {
636 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
Richard Smith993f25a2012-11-07 23:56:21 +0000637 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
Eli Friedman6ae63022012-02-14 02:15:49 +0000638 if (BaseElementTy.isPODType(CGF.getContext()) ||
Richard Smith419bd092015-04-29 19:26:57 +0000639 (CE && isMemcpyEquivalentSpecialMember(CE->getConstructor()))) {
David Majnemer1573d732014-10-15 04:54:54 +0000640 unsigned SrcArgIndex =
641 CGF.CGM.getCXXABI().getSrcArgforCopyCtor(Constructor, Args);
Eli Friedman6ae63022012-02-14 02:15:49 +0000642 llvm::Value *SrcPtr
643 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
Eli Friedman7f1ff602012-04-16 03:54:45 +0000644 LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
645 LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000646
Eli Friedman6ae63022012-02-14 02:15:49 +0000647 // Copy the aggregate.
Richard Smithe78fac52018-04-05 20:52:58 +0000648 CGF.EmitAggregateCopy(LHS, Src, FieldType, CGF.overlapForFieldInit(Field),
649 LHS.isVolatileQualified());
Alexey Bataev5d49b832015-07-08 07:31:02 +0000650 // Ensure that we destroy the objects if an exception is thrown later in
651 // the constructor.
652 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
653 if (CGF.needsEHCleanup(dtorKind))
Fangrui Song6907ce22018-07-30 19:24:48 +0000654 CGF.pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
Eli Friedman6ae63022012-02-14 02:15:49 +0000655 return;
656 }
657 }
658
Richard Smith30e304e2016-12-14 00:03:17 +0000659 CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit());
Eli Friedman6ae63022012-02-14 02:15:49 +0000660}
661
John McCall7f416cc2015-09-08 08:05:57 +0000662void CodeGenFunction::EmitInitializerForField(FieldDecl *Field, LValue LHS,
Richard Smith30e304e2016-12-14 00:03:17 +0000663 Expr *Init) {
Eli Friedman6ae63022012-02-14 02:15:49 +0000664 QualType FieldType = Field->getType();
John McCall47fb9502013-03-07 21:37:08 +0000665 switch (getEvaluationKind(FieldType)) {
666 case TEK_Scalar:
John McCall31168b02011-06-15 23:02:42 +0000667 if (LHS.isSimple()) {
David Blaikie66e41972015-01-14 07:38:27 +0000668 EmitExprAsInit(Init, Field, LHS, false);
John McCall31168b02011-06-15 23:02:42 +0000669 } else {
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000670 RValue RHS = RValue::get(EmitScalarExpr(Init));
671 EmitStoreThroughLValue(RHS, LHS);
John McCall31168b02011-06-15 23:02:42 +0000672 }
John McCall47fb9502013-03-07 21:37:08 +0000673 break;
674 case TEK_Complex:
David Blaikie66e41972015-01-14 07:38:27 +0000675 EmitComplexExprIntoLValue(Init, LHS, /*isInit*/ true);
John McCall47fb9502013-03-07 21:37:08 +0000676 break;
677 case TEK_Aggregate: {
Richard Smith30e304e2016-12-14 00:03:17 +0000678 AggValueSlot Slot =
Richard Smithe78fac52018-04-05 20:52:58 +0000679 AggValueSlot::forLValue(
680 LHS,
681 AggValueSlot::IsDestructed,
682 AggValueSlot::DoesNotNeedGCBarriers,
683 AggValueSlot::IsNotAliased,
Serge Pavlov37605182018-07-28 15:33:03 +0000684 overlapForFieldInit(Field),
685 AggValueSlot::IsNotZeroed,
686 // Checks are made by the code that calls constructor.
687 AggValueSlot::IsSanitizerChecked);
Richard Smith30e304e2016-12-14 00:03:17 +0000688 EmitAggExpr(Init, Slot);
689 break;
Anders Carlssonfb404882009-12-24 22:46:43 +0000690 }
John McCall47fb9502013-03-07 21:37:08 +0000691 }
John McCall12cc42a2013-02-01 05:11:40 +0000692
693 // Ensure that we destroy this object if an exception is thrown
694 // later in the constructor.
695 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
696 if (needsEHCleanup(dtorKind))
697 pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
Anders Carlssonfb404882009-12-24 22:46:43 +0000698}
699
John McCallf8ff7b92010-02-23 00:48:20 +0000700/// Checks whether the given constructor is a valid subject for the
701/// complete-to-base constructor delegation optimization, i.e.
702/// emitting the complete constructor as a simple call to the base
703/// constructor.
Vedant Kumar7f809b22017-02-24 01:15:19 +0000704bool CodeGenFunction::IsConstructorDelegationValid(
705 const CXXConstructorDecl *Ctor) {
John McCallf8ff7b92010-02-23 00:48:20 +0000706
707 // Currently we disable the optimization for classes with virtual
708 // bases because (1) the addresses of parameter variables need to be
709 // consistent across all initializers but (2) the delegate function
710 // call necessarily creates a second copy of the parameter variable.
711 //
712 // The limiting example (purely theoretical AFAIK):
713 // struct A { A(int &c) { c++; } };
714 // struct B : virtual A {
715 // B(int count) : A(count) { printf("%d\n", count); }
716 // };
717 // ...although even this example could in principle be emitted as a
718 // delegation since the address of the parameter doesn't escape.
719 if (Ctor->getParent()->getNumVBases()) {
720 // TODO: white-list trivial vbase initializers. This case wouldn't
721 // be subject to the restrictions below.
722
723 // TODO: white-list cases where:
724 // - there are no non-reference parameters to the constructor
725 // - the initializers don't access any non-reference parameters
726 // - the initializers don't take the address of non-reference
727 // parameters
728 // - etc.
729 // If we ever add any of the above cases, remember that:
730 // - function-try-blocks will always blacklist this optimization
731 // - we need to perform the constructor prologue and cleanup in
732 // EmitConstructorBody.
733
734 return false;
735 }
736
737 // We also disable the optimization for variadic functions because
738 // it's impossible to "re-pass" varargs.
739 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
740 return false;
741
Alexis Hunt61bc1732011-05-01 07:04:31 +0000742 // FIXME: Decide if we can do a delegation of a delegating constructor.
743 if (Ctor->isDelegatingConstructor())
744 return false;
745
John McCallf8ff7b92010-02-23 00:48:20 +0000746 return true;
747}
748
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000749// Emit code in ctor (Prologue==true) or dtor (Prologue==false)
750// to poison the extra field paddings inserted under
751// -fsanitize-address-field-padding=1|2.
752void CodeGenFunction::EmitAsanPrologueOrEpilogue(bool Prologue) {
753 ASTContext &Context = getContext();
754 const CXXRecordDecl *ClassDecl =
755 Prologue ? cast<CXXConstructorDecl>(CurGD.getDecl())->getParent()
756 : cast<CXXDestructorDecl>(CurGD.getDecl())->getParent();
757 if (!ClassDecl->mayInsertExtraPadding()) return;
758
759 struct SizeAndOffset {
760 uint64_t Size;
761 uint64_t Offset;
762 };
763
764 unsigned PtrSize = CGM.getDataLayout().getPointerSizeInBits();
765 const ASTRecordLayout &Info = Context.getASTRecordLayout(ClassDecl);
766
767 // Populate sizes and offsets of fields.
768 SmallVector<SizeAndOffset, 16> SSV(Info.getFieldCount());
769 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i)
770 SSV[i].Offset =
771 Context.toCharUnitsFromBits(Info.getFieldOffset(i)).getQuantity();
772
773 size_t NumFields = 0;
774 for (const auto *Field : ClassDecl->fields()) {
775 const FieldDecl *D = Field;
776 std::pair<CharUnits, CharUnits> FieldInfo =
777 Context.getTypeInfoInChars(D->getType());
778 CharUnits FieldSize = FieldInfo.first;
779 assert(NumFields < SSV.size());
780 SSV[NumFields].Size = D->isBitField() ? 0 : FieldSize.getQuantity();
781 NumFields++;
782 }
783 assert(NumFields == SSV.size());
784 if (SSV.size() <= 1) return;
785
786 // We will insert calls to __asan_* run-time functions.
787 // LLVM AddressSanitizer pass may decide to inline them later.
788 llvm::Type *Args[2] = {IntPtrTy, IntPtrTy};
789 llvm::FunctionType *FTy =
790 llvm::FunctionType::get(CGM.VoidTy, Args, false);
James Y Knight9871db02019-02-05 16:42:33 +0000791 llvm::FunctionCallee F = CGM.CreateRuntimeFunction(
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000792 FTy, Prologue ? "__asan_poison_intra_object_redzone"
793 : "__asan_unpoison_intra_object_redzone");
794
795 llvm::Value *ThisPtr = LoadCXXThis();
796 ThisPtr = Builder.CreatePtrToInt(ThisPtr, IntPtrTy);
Kostya Serebryany64449212014-10-17 21:02:13 +0000797 uint64_t TypeSize = Info.getNonVirtualSize().getQuantity();
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000798 // For each field check if it has sufficient padding,
799 // if so (un)poison it with a call.
800 for (size_t i = 0; i < SSV.size(); i++) {
801 uint64_t AsanAlignment = 8;
802 uint64_t NextField = i == SSV.size() - 1 ? TypeSize : SSV[i + 1].Offset;
803 uint64_t PoisonSize = NextField - SSV[i].Offset - SSV[i].Size;
804 uint64_t EndOffset = SSV[i].Offset + SSV[i].Size;
805 if (PoisonSize < AsanAlignment || !SSV[i].Size ||
806 (NextField % AsanAlignment) != 0)
807 continue;
David Blaikie43f9bb72015-05-18 22:14:03 +0000808 Builder.CreateCall(
809 F, {Builder.CreateAdd(ThisPtr, Builder.getIntN(PtrSize, EndOffset)),
810 Builder.getIntN(PtrSize, PoisonSize)});
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000811 }
812}
813
John McCallb81884d2010-02-19 09:25:03 +0000814/// EmitConstructorBody - Emits the body of the current constructor.
815void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000816 EmitAsanPrologueOrEpilogue(true);
John McCallb81884d2010-02-19 09:25:03 +0000817 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
818 CXXCtorType CtorType = CurGD.getCtorType();
819
Reid Kleckner340ad862014-01-13 22:57:31 +0000820 assert((CGM.getTarget().getCXXABI().hasConstructorVariants() ||
821 CtorType == Ctor_Complete) &&
822 "can only generate complete ctor for this ABI");
823
John McCallf8ff7b92010-02-23 00:48:20 +0000824 // Before we go any further, try the complete->base constructor
825 // delegation optimization.
Timur Iskhodzhanovf32a3772012-04-20 08:05:00 +0000826 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
John McCallc8e01702013-04-16 22:48:15 +0000827 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000828 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args, Ctor->getEndLoc());
John McCallf8ff7b92010-02-23 00:48:20 +0000829 return;
830 }
831
Hans Wennborgdcfba332015-10-06 23:40:43 +0000832 const FunctionDecl *Definition = nullptr;
Richard Smith46bb5812014-08-01 01:56:39 +0000833 Stmt *Body = Ctor->getBody(Definition);
834 assert(Definition == Ctor && "emitting wrong constructor body");
John McCallb81884d2010-02-19 09:25:03 +0000835
John McCallf8ff7b92010-02-23 00:48:20 +0000836 // Enter the function-try-block before the constructor prologue if
837 // applicable.
John McCallf8ff7b92010-02-23 00:48:20 +0000838 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallf8ff7b92010-02-23 00:48:20 +0000839 if (IsTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000840 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000841
Justin Bogner66242d62015-04-23 23:06:47 +0000842 incrementProfileCounter(Body);
Justin Bogner81c22c22014-01-23 02:54:27 +0000843
Richard Smithcc1b96d2013-06-12 22:31:48 +0000844 RunCleanupsScope RunCleanups(*this);
John McCallb81884d2010-02-19 09:25:03 +0000845
John McCall88313032012-03-30 04:25:03 +0000846 // TODO: in restricted cases, we can emit the vbase initializers of
847 // a complete ctor and then delegate to the base ctor.
848
John McCallf8ff7b92010-02-23 00:48:20 +0000849 // Emit the constructor prologue, i.e. the base and member
850 // initializers.
Douglas Gregor94f9a482010-05-05 05:51:00 +0000851 EmitCtorPrologue(Ctor, CtorType, Args);
John McCallb81884d2010-02-19 09:25:03 +0000852
853 // Emit the body of the statement.
John McCallf8ff7b92010-02-23 00:48:20 +0000854 if (IsTryBody)
John McCallb81884d2010-02-19 09:25:03 +0000855 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
856 else if (Body)
857 EmitStmt(Body);
John McCallb81884d2010-02-19 09:25:03 +0000858
859 // Emit any cleanup blocks associated with the member or base
860 // initializers, which includes (along the exceptional path) the
861 // destructors for those members and bases that were fully
862 // constructed.
Richard Smithcc1b96d2013-06-12 22:31:48 +0000863 RunCleanups.ForceCleanup();
John McCallb81884d2010-02-19 09:25:03 +0000864
John McCallf8ff7b92010-02-23 00:48:20 +0000865 if (IsTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000866 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000867}
868
Lang Hamesbf122742013-02-17 07:22:09 +0000869namespace {
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000870 /// RAII object to indicate that codegen is copying the value representation
871 /// instead of the object representation. Useful when copying a struct or
872 /// class which has uninitialized members and we're only performing
873 /// lvalue-to-rvalue conversion on the object but not its members.
874 class CopyingValueRepresentation {
875 public:
876 explicit CopyingValueRepresentation(CodeGenFunction &CGF)
Alexey Samsonov035462c2014-10-30 19:33:44 +0000877 : CGF(CGF), OldSanOpts(CGF.SanOpts) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000878 CGF.SanOpts.set(SanitizerKind::Bool, false);
879 CGF.SanOpts.set(SanitizerKind::Enum, false);
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000880 }
881 ~CopyingValueRepresentation() {
882 CGF.SanOpts = OldSanOpts;
883 }
884 private:
885 CodeGenFunction &CGF;
Alexey Samsonova0416102014-11-11 01:26:14 +0000886 SanitizerSet OldSanOpts;
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000887 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000888} // end anonymous namespace
Fangrui Song6907ce22018-07-30 19:24:48 +0000889
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000890namespace {
Lang Hamesbf122742013-02-17 07:22:09 +0000891 class FieldMemcpyizer {
892 public:
893 FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl,
894 const VarDecl *SrcRec)
Justin Bogner1cd11f12015-05-20 15:53:59 +0000895 : CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec),
Lang Hamesbf122742013-02-17 07:22:09 +0000896 RecLayout(CGF.getContext().getASTRecordLayout(ClassDecl)),
Craig Topper8a13c412014-05-21 05:09:00 +0000897 FirstField(nullptr), LastField(nullptr), FirstFieldOffset(0),
898 LastFieldOffset(0), LastAddedFieldIndex(0) {}
Lang Hamesbf122742013-02-17 07:22:09 +0000899
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000900 bool isMemcpyableField(FieldDecl *F) const {
901 // Never memcpy fields when we are adding poisoned paddings.
Alexey Samsonova0416102014-11-11 01:26:14 +0000902 if (CGF.getContext().getLangOpts().SanitizeAddressFieldPadding)
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000903 return false;
Lang Hamesbf122742013-02-17 07:22:09 +0000904 Qualifiers Qual = F->getType().getQualifiers();
905 if (Qual.hasVolatile() || Qual.hasObjCLifetime())
906 return false;
907 return true;
908 }
909
910 void addMemcpyableField(FieldDecl *F) {
Craig Topper8a13c412014-05-21 05:09:00 +0000911 if (!FirstField)
Lang Hamesbf122742013-02-17 07:22:09 +0000912 addInitialField(F);
913 else
914 addNextField(F);
915 }
916
David Majnemera586eb22014-10-10 18:57:10 +0000917 CharUnits getMemcpySize(uint64_t FirstByteOffset) const {
Richard Smithe78fac52018-04-05 20:52:58 +0000918 ASTContext &Ctx = CGF.getContext();
Lang Hamesbf122742013-02-17 07:22:09 +0000919 unsigned LastFieldSize =
Richard Smithe78fac52018-04-05 20:52:58 +0000920 LastField->isBitField()
921 ? LastField->getBitWidthValue(Ctx)
922 : Ctx.toBits(
923 Ctx.getTypeInfoDataSizeInChars(LastField->getType()).first);
924 uint64_t MemcpySizeBits = LastFieldOffset + LastFieldSize -
925 FirstByteOffset + Ctx.getCharWidth() - 1;
926 CharUnits MemcpySize = Ctx.toCharUnitsFromBits(MemcpySizeBits);
Lang Hamesbf122742013-02-17 07:22:09 +0000927 return MemcpySize;
928 }
929
930 void emitMemcpy() {
931 // Give the subclass a chance to bail out if it feels the memcpy isn't
932 // worth it (e.g. Hasn't aggregated enough data).
Craig Topper8a13c412014-05-21 05:09:00 +0000933 if (!FirstField) {
Lang Hamesbf122742013-02-17 07:22:09 +0000934 return;
935 }
936
David Majnemera586eb22014-10-10 18:57:10 +0000937 uint64_t FirstByteOffset;
Lang Hamesbf122742013-02-17 07:22:09 +0000938 if (FirstField->isBitField()) {
939 const CGRecordLayout &RL =
940 CGF.getTypes().getCGRecordLayout(FirstField->getParent());
941 const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField);
David Majnemera586eb22014-10-10 18:57:10 +0000942 // FirstFieldOffset is not appropriate for bitfields,
Ulrich Weigand73263d72015-07-13 11:52:14 +0000943 // we need to use the storage offset instead.
Ulrich Weigand03ce2a12015-07-10 17:30:00 +0000944 FirstByteOffset = CGF.getContext().toBits(BFInfo.StorageOffset);
Lang Hames1694e0d2013-02-27 04:14:49 +0000945 } else {
David Majnemera586eb22014-10-10 18:57:10 +0000946 FirstByteOffset = FirstFieldOffset;
Lang Hames1694e0d2013-02-27 04:14:49 +0000947 }
Lang Hamesbf122742013-02-17 07:22:09 +0000948
David Majnemera586eb22014-10-10 18:57:10 +0000949 CharUnits MemcpySize = getMemcpySize(FirstByteOffset);
Lang Hamesbf122742013-02-17 07:22:09 +0000950 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
John McCall7f416cc2015-09-08 08:05:57 +0000951 Address ThisPtr = CGF.LoadCXXThisAddress();
952 LValue DestLV = CGF.MakeAddrLValue(ThisPtr, RecordTy);
Lang Hamesbf122742013-02-17 07:22:09 +0000953 LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField);
954 llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec));
955 LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
956 LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField);
957
John McCall7f416cc2015-09-08 08:05:57 +0000958 emitMemcpyIR(Dest.isBitField() ? Dest.getBitFieldAddress() : Dest.getAddress(),
959 Src.isBitField() ? Src.getBitFieldAddress() : Src.getAddress(),
960 MemcpySize);
Lang Hamesbf122742013-02-17 07:22:09 +0000961 reset();
962 }
963
964 void reset() {
Craig Topper8a13c412014-05-21 05:09:00 +0000965 FirstField = nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +0000966 }
967
968 protected:
969 CodeGenFunction &CGF;
970 const CXXRecordDecl *ClassDecl;
971
972 private:
John McCall7f416cc2015-09-08 08:05:57 +0000973 void emitMemcpyIR(Address DestPtr, Address SrcPtr, CharUnits Size) {
974 llvm::PointerType *DPT = DestPtr.getType();
Lang Hamesbf122742013-02-17 07:22:09 +0000975 llvm::Type *DBP =
976 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), DPT->getAddressSpace());
977 DestPtr = CGF.Builder.CreateBitCast(DestPtr, DBP);
978
John McCall7f416cc2015-09-08 08:05:57 +0000979 llvm::PointerType *SPT = SrcPtr.getType();
Lang Hamesbf122742013-02-17 07:22:09 +0000980 llvm::Type *SBP =
981 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), SPT->getAddressSpace());
982 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, SBP);
983
John McCall7f416cc2015-09-08 08:05:57 +0000984 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity());
Lang Hamesbf122742013-02-17 07:22:09 +0000985 }
986
987 void addInitialField(FieldDecl *F) {
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000988 FirstField = F;
989 LastField = F;
990 FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex());
991 LastFieldOffset = FirstFieldOffset;
992 LastAddedFieldIndex = F->getFieldIndex();
993 }
Lang Hamesbf122742013-02-17 07:22:09 +0000994
995 void addNextField(FieldDecl *F) {
John McCall6054d5a2013-05-07 05:20:46 +0000996 // For the most part, the following invariant will hold:
997 // F->getFieldIndex() == LastAddedFieldIndex + 1
998 // The one exception is that Sema won't add a copy-initializer for an
999 // unnamed bitfield, which will show up here as a gap in the sequence.
1000 assert(F->getFieldIndex() >= LastAddedFieldIndex + 1 &&
1001 "Cannot aggregate fields out of order.");
Lang Hamesbf122742013-02-17 07:22:09 +00001002 LastAddedFieldIndex = F->getFieldIndex();
1003
1004 // The 'first' and 'last' fields are chosen by offset, rather than field
1005 // index. This allows the code to support bitfields, as well as regular
1006 // fields.
1007 uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex());
1008 if (FOffset < FirstFieldOffset) {
1009 FirstField = F;
1010 FirstFieldOffset = FOffset;
1011 } else if (FOffset > LastFieldOffset) {
1012 LastField = F;
1013 LastFieldOffset = FOffset;
1014 }
1015 }
1016
1017 const VarDecl *SrcRec;
1018 const ASTRecordLayout &RecLayout;
1019 FieldDecl *FirstField;
1020 FieldDecl *LastField;
1021 uint64_t FirstFieldOffset, LastFieldOffset;
1022 unsigned LastAddedFieldIndex;
1023 };
1024
1025 class ConstructorMemcpyizer : public FieldMemcpyizer {
1026 private:
Lang Hamesbf122742013-02-17 07:22:09 +00001027 /// Get source argument for copy constructor. Returns null if not a copy
David Majnemer196ac332014-09-11 23:05:02 +00001028 /// constructor.
1029 static const VarDecl *getTrivialCopySource(CodeGenFunction &CGF,
1030 const CXXConstructorDecl *CD,
Lang Hamesbf122742013-02-17 07:22:09 +00001031 FunctionArgList &Args) {
Jordan Rose54533f72013-08-07 16:16:48 +00001032 if (CD->isCopyOrMoveConstructor() && CD->isDefaulted())
David Majnemer196ac332014-09-11 23:05:02 +00001033 return Args[CGF.CGM.getCXXABI().getSrcArgforCopyCtor(CD, Args)];
Craig Topper8a13c412014-05-21 05:09:00 +00001034 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001035 }
1036
1037 // Returns true if a CXXCtorInitializer represents a member initialization
1038 // that can be rolled into a memcpy.
1039 bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const {
1040 if (!MemcpyableCtor)
1041 return false;
1042 FieldDecl *Field = MemberInit->getMember();
Craig Topper8a13c412014-05-21 05:09:00 +00001043 assert(Field && "No field for member init.");
Lang Hamesbf122742013-02-17 07:22:09 +00001044 QualType FieldType = Field->getType();
1045 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
1046
Richard Smith419bd092015-04-29 19:26:57 +00001047 // Bail out on non-memcpyable, not-trivially-copyable members.
1048 if (!(CE && isMemcpyEquivalentSpecialMember(CE->getConstructor())) &&
Lang Hamesbf122742013-02-17 07:22:09 +00001049 !(FieldType.isTriviallyCopyableType(CGF.getContext()) ||
1050 FieldType->isReferenceType()))
1051 return false;
1052
1053 // Bail out on volatile fields.
1054 if (!isMemcpyableField(Field))
1055 return false;
1056
1057 // Otherwise we're good.
1058 return true;
1059 }
1060
1061 public:
1062 ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD,
1063 FunctionArgList &Args)
David Majnemer196ac332014-09-11 23:05:02 +00001064 : FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CGF, CD, Args)),
Lang Hamesbf122742013-02-17 07:22:09 +00001065 ConstructorDecl(CD),
Jordan Rose54533f72013-08-07 16:16:48 +00001066 MemcpyableCtor(CD->isDefaulted() &&
Lang Hamesbf122742013-02-17 07:22:09 +00001067 CD->isCopyOrMoveConstructor() &&
1068 CGF.getLangOpts().getGC() == LangOptions::NonGC),
1069 Args(Args) { }
1070
1071 void addMemberInitializer(CXXCtorInitializer *MemberInit) {
1072 if (isMemberInitMemcpyable(MemberInit)) {
1073 AggregatedInits.push_back(MemberInit);
1074 addMemcpyableField(MemberInit->getMember());
1075 } else {
1076 emitAggregatedInits();
1077 EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit,
1078 ConstructorDecl, Args);
1079 }
1080 }
1081
1082 void emitAggregatedInits() {
1083 if (AggregatedInits.size() <= 1) {
1084 // This memcpy is too small to be worthwhile. Fall back on default
1085 // codegen.
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001086 if (!AggregatedInits.empty()) {
1087 CopyingValueRepresentation CVR(CGF);
Lang Hamesbf122742013-02-17 07:22:09 +00001088 EmitMemberInitializer(CGF, ConstructorDecl->getParent(),
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001089 AggregatedInits[0], ConstructorDecl, Args);
Alexey Bataev152c71f2015-07-14 07:55:48 +00001090 AggregatedInits.clear();
Lang Hamesbf122742013-02-17 07:22:09 +00001091 }
1092 reset();
1093 return;
1094 }
1095
1096 pushEHDestructors();
1097 emitMemcpy();
1098 AggregatedInits.clear();
1099 }
1100
1101 void pushEHDestructors() {
John McCall7f416cc2015-09-08 08:05:57 +00001102 Address ThisPtr = CGF.LoadCXXThisAddress();
Lang Hamesbf122742013-02-17 07:22:09 +00001103 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
John McCall7f416cc2015-09-08 08:05:57 +00001104 LValue LHS = CGF.MakeAddrLValue(ThisPtr, RecordTy);
Lang Hamesbf122742013-02-17 07:22:09 +00001105
1106 for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
Alexey Bataev152c71f2015-07-14 07:55:48 +00001107 CXXCtorInitializer *MemberInit = AggregatedInits[i];
1108 QualType FieldType = MemberInit->getAnyMember()->getType();
Lang Hamesbf122742013-02-17 07:22:09 +00001109 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
Alexey Bataev152c71f2015-07-14 07:55:48 +00001110 if (!CGF.needsEHCleanup(dtorKind))
1111 continue;
1112 LValue FieldLHS = LHS;
1113 EmitLValueForAnyFieldInitialization(CGF, MemberInit, FieldLHS);
1114 CGF.pushEHDestroy(dtorKind, FieldLHS.getAddress(), FieldType);
Lang Hamesbf122742013-02-17 07:22:09 +00001115 }
1116 }
1117
1118 void finish() {
1119 emitAggregatedInits();
1120 }
1121
1122 private:
1123 const CXXConstructorDecl *ConstructorDecl;
1124 bool MemcpyableCtor;
1125 FunctionArgList &Args;
1126 SmallVector<CXXCtorInitializer*, 16> AggregatedInits;
1127 };
1128
1129 class AssignmentMemcpyizer : public FieldMemcpyizer {
1130 private:
Lang Hamesbf122742013-02-17 07:22:09 +00001131 // Returns the memcpyable field copied by the given statement, if one
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001132 // exists. Otherwise returns null.
1133 FieldDecl *getMemcpyableField(Stmt *S) {
Lang Hamesbf122742013-02-17 07:22:09 +00001134 if (!AssignmentsMemcpyable)
Craig Topper8a13c412014-05-21 05:09:00 +00001135 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001136 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
1137 // Recognise trivial assignments.
1138 if (BO->getOpcode() != BO_Assign)
Craig Topper8a13c412014-05-21 05:09:00 +00001139 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001140 MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS());
1141 if (!ME)
Craig Topper8a13c412014-05-21 05:09:00 +00001142 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001143 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1144 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001145 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001146 Stmt *RHS = BO->getRHS();
1147 if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS))
1148 RHS = EC->getSubExpr();
1149 if (!RHS)
Craig Topper8a13c412014-05-21 05:09:00 +00001150 return nullptr;
Warren Ristow8d17b402017-02-02 17:53:34 +00001151 if (MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS)) {
1152 if (ME2->getMemberDecl() == Field)
1153 return Field;
1154 }
1155 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001156 } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) {
1157 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl());
Richard Smith419bd092015-04-29 19:26:57 +00001158 if (!(MD && isMemcpyEquivalentSpecialMember(MD)))
Craig Topper8a13c412014-05-21 05:09:00 +00001159 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001160 MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument());
1161 if (!IOA)
Craig Topper8a13c412014-05-21 05:09:00 +00001162 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001163 FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl());
1164 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001165 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001166 MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0));
1167 if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl()))
Craig Topper8a13c412014-05-21 05:09:00 +00001168 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001169 return Field;
1170 } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1171 FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1172 if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy)
Craig Topper8a13c412014-05-21 05:09:00 +00001173 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001174 Expr *DstPtr = CE->getArg(0);
1175 if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr))
1176 DstPtr = DC->getSubExpr();
1177 UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr);
1178 if (!DUO || DUO->getOpcode() != UO_AddrOf)
Craig Topper8a13c412014-05-21 05:09:00 +00001179 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001180 MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr());
1181 if (!ME)
Craig Topper8a13c412014-05-21 05:09:00 +00001182 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001183 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1184 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001185 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001186 Expr *SrcPtr = CE->getArg(1);
1187 if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr))
1188 SrcPtr = SC->getSubExpr();
1189 UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr);
1190 if (!SUO || SUO->getOpcode() != UO_AddrOf)
Craig Topper8a13c412014-05-21 05:09:00 +00001191 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001192 MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr());
1193 if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl()))
Craig Topper8a13c412014-05-21 05:09:00 +00001194 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001195 return Field;
1196 }
1197
Craig Topper8a13c412014-05-21 05:09:00 +00001198 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001199 }
1200
1201 bool AssignmentsMemcpyable;
1202 SmallVector<Stmt*, 16> AggregatedStmts;
1203
1204 public:
Lang Hamesbf122742013-02-17 07:22:09 +00001205 AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD,
1206 FunctionArgList &Args)
1207 : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]),
1208 AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) {
1209 assert(Args.size() == 2);
1210 }
1211
1212 void emitAssignment(Stmt *S) {
1213 FieldDecl *F = getMemcpyableField(S);
1214 if (F) {
1215 addMemcpyableField(F);
1216 AggregatedStmts.push_back(S);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001217 } else {
Lang Hamesbf122742013-02-17 07:22:09 +00001218 emitAggregatedStmts();
1219 CGF.EmitStmt(S);
1220 }
1221 }
1222
1223 void emitAggregatedStmts() {
1224 if (AggregatedStmts.size() <= 1) {
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001225 if (!AggregatedStmts.empty()) {
1226 CopyingValueRepresentation CVR(CGF);
1227 CGF.EmitStmt(AggregatedStmts[0]);
1228 }
Lang Hamesbf122742013-02-17 07:22:09 +00001229 reset();
1230 }
1231
1232 emitMemcpy();
1233 AggregatedStmts.clear();
1234 }
1235
1236 void finish() {
1237 emitAggregatedStmts();
1238 }
1239 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00001240} // end anonymous namespace
Lang Hamesbf122742013-02-17 07:22:09 +00001241
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001242static bool isInitializerOfDynamicClass(const CXXCtorInitializer *BaseInit) {
1243 const Type *BaseType = BaseInit->getBaseClass();
1244 const auto *BaseClassDecl =
1245 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
1246 return BaseClassDecl->isDynamicClass();
1247}
1248
Anders Carlssonfb404882009-12-24 22:46:43 +00001249/// EmitCtorPrologue - This routine generates necessary code to initialize
1250/// base classes and non-static data members belonging to this constructor.
Anders Carlssonfb404882009-12-24 22:46:43 +00001251void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001252 CXXCtorType CtorType,
1253 FunctionArgList &Args) {
Alexis Hunt61bc1732011-05-01 07:04:31 +00001254 if (CD->isDelegatingConstructor())
1255 return EmitDelegatingCXXConstructorCall(CD, Args);
1256
Anders Carlssonfb404882009-12-24 22:46:43 +00001257 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlsson5dc86332010-02-02 19:58:43 +00001258
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001259 CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
1260 E = CD->init_end();
1261
Reid Kleckner61c9b7c2019-03-18 22:41:50 +00001262 // Virtual base initializers first, if any. They aren't needed if:
1263 // - This is a base ctor variant
1264 // - There are no vbases
1265 // - The class is abstract, so a complete object of it cannot be constructed
1266 //
1267 // The check for an abstract class is necessary because sema may not have
1268 // marked virtual base destructors referenced.
1269 bool ConstructVBases = CtorType != Ctor_Base &&
1270 ClassDecl->getNumVBases() != 0 &&
1271 !ClassDecl->isAbstract();
1272
1273 // In the Microsoft C++ ABI, there are no constructor variants. Instead, the
1274 // constructor of a class with virtual bases takes an additional parameter to
1275 // conditionally construct the virtual bases. Emit that check here.
Craig Topper8a13c412014-05-21 05:09:00 +00001276 llvm::BasicBlock *BaseCtorContinueBB = nullptr;
Reid Kleckner61c9b7c2019-03-18 22:41:50 +00001277 if (ConstructVBases &&
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001278 !CGM.getTarget().getCXXABI().hasConstructorVariants()) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001279 BaseCtorContinueBB =
Reid Kleckner61c9b7c2019-03-18 22:41:50 +00001280 CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this, ClassDecl);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001281 assert(BaseCtorContinueBB);
1282 }
1283
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001284 llvm::Value *const OldThis = CXXThisValue;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001285 for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
Reid Kleckner61c9b7c2019-03-18 22:41:50 +00001286 if (!ConstructVBases)
1287 continue;
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001288 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1289 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1290 isInitializerOfDynamicClass(*B))
Piotr Padlewski5dde8092018-05-03 11:03:01 +00001291 CXXThisValue = Builder.CreateLaunderInvariantGroup(LoadCXXThis());
Reid Kleckner61c9b7c2019-03-18 22:41:50 +00001292 EmitBaseInitializer(*this, ClassDecl, *B);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001293 }
1294
1295 if (BaseCtorContinueBB) {
1296 // Complete object handler should continue to the remaining initializers.
1297 Builder.CreateBr(BaseCtorContinueBB);
1298 EmitBlock(BaseCtorContinueBB);
1299 }
1300
1301 // Then, non-virtual base initializers.
1302 for (; B != E && (*B)->isBaseInitializer(); B++) {
1303 assert(!(*B)->isBaseVirtual());
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001304
1305 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1306 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1307 isInitializerOfDynamicClass(*B))
Piotr Padlewski5dde8092018-05-03 11:03:01 +00001308 CXXThisValue = Builder.CreateLaunderInvariantGroup(LoadCXXThis());
Reid Kleckner61c9b7c2019-03-18 22:41:50 +00001309 EmitBaseInitializer(*this, ClassDecl, *B);
Anders Carlssonfb404882009-12-24 22:46:43 +00001310 }
1311
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001312 CXXThisValue = OldThis;
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001313
Anders Carlssond5895932010-03-28 21:07:49 +00001314 InitializeVTablePointers(ClassDecl);
Anders Carlsson5dc86332010-02-02 19:58:43 +00001315
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001316 // And finally, initialize class members.
John McCall7f416cc2015-09-08 08:05:57 +00001317 FieldConstructionScope FCS(*this, LoadCXXThisAddress());
Lang Hamesbf122742013-02-17 07:22:09 +00001318 ConstructorMemcpyizer CM(*this, CD, Args);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001319 for (; B != E; B++) {
1320 CXXCtorInitializer *Member = (*B);
1321 assert(!Member->isBaseInitializer());
1322 assert(Member->isAnyMemberInitializer() &&
1323 "Delegating initializer on non-delegating constructor");
1324 CM.addMemberInitializer(Member);
1325 }
Lang Hamesbf122742013-02-17 07:22:09 +00001326 CM.finish();
Anders Carlssonfb404882009-12-24 22:46:43 +00001327}
1328
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001329static bool
1330FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
1331
1332static bool
Justin Bogner1cd11f12015-05-20 15:53:59 +00001333HasTrivialDestructorBody(ASTContext &Context,
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001334 const CXXRecordDecl *BaseClassDecl,
1335 const CXXRecordDecl *MostDerivedClassDecl)
1336{
1337 // If the destructor is trivial we don't have to check anything else.
1338 if (BaseClassDecl->hasTrivialDestructor())
1339 return true;
1340
1341 if (!BaseClassDecl->getDestructor()->hasTrivialBody())
1342 return false;
1343
1344 // Check fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001345 for (const auto *Field : BaseClassDecl->fields())
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001346 if (!FieldHasTrivialDestructorBody(Context, Field))
1347 return false;
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001348
1349 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001350 for (const auto &I : BaseClassDecl->bases()) {
1351 if (I.isVirtual())
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001352 continue;
1353
1354 const CXXRecordDecl *NonVirtualBase =
Aaron Ballman574705e2014-03-13 15:41:46 +00001355 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001356 if (!HasTrivialDestructorBody(Context, NonVirtualBase,
1357 MostDerivedClassDecl))
1358 return false;
1359 }
1360
1361 if (BaseClassDecl == MostDerivedClassDecl) {
1362 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00001363 for (const auto &I : BaseClassDecl->vbases()) {
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001364 const CXXRecordDecl *VirtualBase =
Aaron Ballman445a9392014-03-13 16:15:17 +00001365 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001366 if (!HasTrivialDestructorBody(Context, VirtualBase,
1367 MostDerivedClassDecl))
Justin Bogner1cd11f12015-05-20 15:53:59 +00001368 return false;
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001369 }
1370 }
1371
1372 return true;
1373}
1374
1375static bool
1376FieldHasTrivialDestructorBody(ASTContext &Context,
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001377 const FieldDecl *Field)
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001378{
1379 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
1380
1381 const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
1382 if (!RT)
1383 return true;
Justin Bogner1cd11f12015-05-20 15:53:59 +00001384
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001385 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Davide Italiano982bbf42015-06-26 00:18:35 +00001386
1387 // The destructor for an implicit anonymous union member is never invoked.
1388 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
1389 return false;
1390
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001391 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
1392}
1393
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001394/// CanSkipVTablePointerInitialization - Check whether we need to initialize
1395/// any vtable pointers before calling this destructor.
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001396static bool CanSkipVTablePointerInitialization(CodeGenFunction &CGF,
Anders Carlssond6f15182011-05-16 04:08:36 +00001397 const CXXDestructorDecl *Dtor) {
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001398 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1399 if (!ClassDecl->isDynamicClass())
1400 return true;
1401
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001402 if (!Dtor->hasTrivialBody())
1403 return false;
1404
1405 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001406 for (const auto *Field : ClassDecl->fields())
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001407 if (!FieldHasTrivialDestructorBody(CGF.getContext(), Field))
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001408 return false;
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001409
1410 return true;
1411}
1412
John McCallb81884d2010-02-19 09:25:03 +00001413/// EmitDestructorBody - Emits the body of the current destructor.
1414void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
1415 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
1416 CXXDtorType DtorType = CurGD.getDtorType();
1417
Richard Smithdf054d32017-02-25 23:53:05 +00001418 // For an abstract class, non-base destructors are never used (and can't
1419 // be emitted in general, because vbase dtors may not have been validated
1420 // by Sema), but the Itanium ABI doesn't make them optional and Clang may
1421 // in fact emit references to them from other compilations, so emit them
1422 // as functions containing a trap instruction.
1423 if (DtorType != Dtor_Base && Dtor->getParent()->isAbstract()) {
1424 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
1425 TrapCall->setDoesNotReturn();
1426 TrapCall->setDoesNotThrow();
1427 Builder.CreateUnreachable();
1428 Builder.ClearInsertionPoint();
1429 return;
1430 }
1431
Justin Bognerfb298222015-05-20 16:16:23 +00001432 Stmt *Body = Dtor->getBody();
1433 if (Body)
1434 incrementProfileCounter(Body);
1435
John McCallf99a6312010-07-21 05:30:47 +00001436 // The call to operator delete in a deleting destructor happens
1437 // outside of the function-try-block, which means it's always
1438 // possible to delegate the destructor body to the complete
1439 // destructor. Do so.
1440 if (DtorType == Dtor_Deleting) {
Richard Smith5b349582017-10-13 01:55:36 +00001441 RunCleanupsScope DtorEpilogue(*this);
John McCallf99a6312010-07-21 05:30:47 +00001442 EnterDtorCleanups(Dtor, Dtor_Deleting);
Richard Smith5b349582017-10-13 01:55:36 +00001443 if (HaveInsertPoint())
1444 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
1445 /*Delegating=*/false, LoadCXXThisAddress());
John McCallf99a6312010-07-21 05:30:47 +00001446 return;
1447 }
1448
John McCallb81884d2010-02-19 09:25:03 +00001449 // If the body is a function-try-block, enter the try before
John McCallf99a6312010-07-21 05:30:47 +00001450 // anything else.
1451 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallb81884d2010-02-19 09:25:03 +00001452 if (isTryBody)
John McCallb609d3f2010-07-07 06:56:46 +00001453 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00001454 EmitAsanPrologueOrEpilogue(false);
John McCallb81884d2010-02-19 09:25:03 +00001455
John McCallf99a6312010-07-21 05:30:47 +00001456 // Enter the epilogue cleanups.
1457 RunCleanupsScope DtorEpilogue(*this);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001458
John McCallb81884d2010-02-19 09:25:03 +00001459 // If this is the complete variant, just invoke the base variant;
1460 // the epilogue will destruct the virtual bases. But we can't do
1461 // this optimization if the body is a function-try-block, because
Justin Bogner1cd11f12015-05-20 15:53:59 +00001462 // we'd introduce *two* handler blocks. In the Microsoft ABI, we
Reid Klecknere7de47e2013-07-22 13:51:44 +00001463 // always delegate because we might not have a definition in this TU.
John McCallf99a6312010-07-21 05:30:47 +00001464 switch (DtorType) {
Saleem Abdulrasool8de4e872017-02-02 05:45:43 +00001465 case Dtor_Comdat: llvm_unreachable("not expecting a COMDAT");
John McCallf99a6312010-07-21 05:30:47 +00001466 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
1467
1468 case Dtor_Complete:
Reid Klecknere7de47e2013-07-22 13:51:44 +00001469 assert((Body || getTarget().getCXXABI().isMicrosoft()) &&
1470 "can't emit a dtor without a body for non-Microsoft ABIs");
1471
John McCallf99a6312010-07-21 05:30:47 +00001472 // Enter the cleanup scopes for virtual bases.
1473 EnterDtorCleanups(Dtor, Dtor_Complete);
1474
Reid Klecknere7de47e2013-07-22 13:51:44 +00001475 if (!isTryBody) {
John McCallf99a6312010-07-21 05:30:47 +00001476 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
John McCall7f416cc2015-09-08 08:05:57 +00001477 /*Delegating=*/false, LoadCXXThisAddress());
John McCallf99a6312010-07-21 05:30:47 +00001478 break;
1479 }
Saleem Abdulrasool8de4e872017-02-02 05:45:43 +00001480
John McCallf99a6312010-07-21 05:30:47 +00001481 // Fallthrough: act like we're in the base variant.
Saleem Abdulrasool8de4e872017-02-02 05:45:43 +00001482 LLVM_FALLTHROUGH;
Justin Bogner1cd11f12015-05-20 15:53:59 +00001483
John McCallf99a6312010-07-21 05:30:47 +00001484 case Dtor_Base:
Reid Klecknere7de47e2013-07-22 13:51:44 +00001485 assert(Body);
1486
John McCallf99a6312010-07-21 05:30:47 +00001487 // Enter the cleanup scopes for fields and non-virtual bases.
1488 EnterDtorCleanups(Dtor, Dtor_Base);
1489
1490 // Initialize the vtable pointers before entering the body.
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001491 if (!CanSkipVTablePointerInitialization(*this, Dtor)) {
Piotr Padlewski5dde8092018-05-03 11:03:01 +00001492 // Insert the llvm.launder.invariant.group intrinsic before initializing
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001493 // the vptrs to cancel any previous assumptions we might have made.
1494 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1495 CGM.getCodeGenOpts().OptimizationLevel > 0)
Piotr Padlewski5dde8092018-05-03 11:03:01 +00001496 CXXThisValue = Builder.CreateLaunderInvariantGroup(LoadCXXThis());
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001497 InitializeVTablePointers(Dtor->getParent());
1498 }
John McCallf99a6312010-07-21 05:30:47 +00001499
1500 if (isTryBody)
1501 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
1502 else if (Body)
1503 EmitStmt(Body);
1504 else {
1505 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
1506 // nothing to do besides what's in the epilogue
1507 }
Fariborz Jahanian0c12ed12011-02-02 23:12:46 +00001508 // -fapple-kext must inline any call to this dtor into
1509 // the caller's body.
Richard Smith9c6890a2012-11-01 22:30:59 +00001510 if (getLangOpts().AppleKext)
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00001511 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
Naomi Musgravee50cb9b2015-08-13 18:35:11 +00001512
John McCallf99a6312010-07-21 05:30:47 +00001513 break;
John McCallb81884d2010-02-19 09:25:03 +00001514 }
1515
John McCallf99a6312010-07-21 05:30:47 +00001516 // Jump out through the epilogue cleanups.
1517 DtorEpilogue.ForceCleanup();
John McCallb81884d2010-02-19 09:25:03 +00001518
1519 // Exit the try if applicable.
1520 if (isTryBody)
John McCallb609d3f2010-07-07 06:56:46 +00001521 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +00001522}
1523
Lang Hamesbf122742013-02-17 07:22:09 +00001524void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) {
1525 const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
1526 const Stmt *RootS = AssignOp->getBody();
1527 assert(isa<CompoundStmt>(RootS) &&
1528 "Body of an implicit assignment operator should be compound stmt.");
1529 const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
1530
1531 LexicalScope Scope(*this, RootCS->getSourceRange());
1532
Xinliang David Lia951e8e2016-02-09 20:02:59 +00001533 incrementProfileCounter(RootCS);
Lang Hamesbf122742013-02-17 07:22:09 +00001534 AssignmentMemcpyizer AM(*this, AssignOp, Args);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001535 for (auto *I : RootCS->body())
Justin Bogner1cd11f12015-05-20 15:53:59 +00001536 AM.emitAssignment(I);
Lang Hamesbf122742013-02-17 07:22:09 +00001537 AM.finish();
1538}
1539
John McCallf99a6312010-07-21 05:30:47 +00001540namespace {
Richard Smith5b349582017-10-13 01:55:36 +00001541 llvm::Value *LoadThisForDtorDelete(CodeGenFunction &CGF,
1542 const CXXDestructorDecl *DD) {
1543 if (Expr *ThisArg = DD->getOperatorDeleteThisArg())
Haojian Wu5b5c81f2017-10-13 15:37:53 +00001544 return CGF.EmitScalarExpr(ThisArg);
Richard Smith5b349582017-10-13 01:55:36 +00001545 return CGF.LoadCXXThis();
1546 }
1547
John McCallf99a6312010-07-21 05:30:47 +00001548 /// Call the operator delete associated with the current destructor.
David Blaikie7e70d682015-08-18 22:40:54 +00001549 struct CallDtorDelete final : EHScopeStack::Cleanup {
John McCallf99a6312010-07-21 05:30:47 +00001550 CallDtorDelete() {}
1551
Craig Topper4f12f102014-03-12 06:41:41 +00001552 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallf99a6312010-07-21 05:30:47 +00001553 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1554 const CXXRecordDecl *ClassDecl = Dtor->getParent();
Richard Smith5b349582017-10-13 01:55:36 +00001555 CGF.EmitDeleteCall(Dtor->getOperatorDelete(),
1556 LoadThisForDtorDelete(CGF, Dtor),
John McCallf99a6312010-07-21 05:30:47 +00001557 CGF.getContext().getTagDeclType(ClassDecl));
1558 }
1559 };
1560
Richard Smith5b349582017-10-13 01:55:36 +00001561 void EmitConditionalDtorDeleteCall(CodeGenFunction &CGF,
1562 llvm::Value *ShouldDeleteCondition,
1563 bool ReturnAfterDelete) {
1564 llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
1565 llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
1566 llvm::Value *ShouldCallDelete
1567 = CGF.Builder.CreateIsNull(ShouldDeleteCondition);
1568 CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
1569
1570 CGF.EmitBlock(callDeleteBB);
1571 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1572 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1573 CGF.EmitDeleteCall(Dtor->getOperatorDelete(),
1574 LoadThisForDtorDelete(CGF, Dtor),
1575 CGF.getContext().getTagDeclType(ClassDecl));
1576 assert(Dtor->getOperatorDelete()->isDestroyingOperatorDelete() ==
1577 ReturnAfterDelete &&
1578 "unexpected value for ReturnAfterDelete");
1579 if (ReturnAfterDelete)
1580 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
1581 else
1582 CGF.Builder.CreateBr(continueBB);
1583
1584 CGF.EmitBlock(continueBB);
1585 }
1586
David Blaikie7e70d682015-08-18 22:40:54 +00001587 struct CallDtorDeleteConditional final : EHScopeStack::Cleanup {
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001588 llvm::Value *ShouldDeleteCondition;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001589
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001590 public:
1591 CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001592 : ShouldDeleteCondition(ShouldDeleteCondition) {
Craig Topper8a13c412014-05-21 05:09:00 +00001593 assert(ShouldDeleteCondition != nullptr);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001594 }
1595
Craig Topper4f12f102014-03-12 06:41:41 +00001596 void Emit(CodeGenFunction &CGF, Flags flags) override {
Richard Smith5b349582017-10-13 01:55:36 +00001597 EmitConditionalDtorDeleteCall(CGF, ShouldDeleteCondition,
1598 /*ReturnAfterDelete*/false);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001599 }
1600 };
1601
David Blaikie7e70d682015-08-18 22:40:54 +00001602 class DestroyField final : public EHScopeStack::Cleanup {
John McCall4bd0fb12011-07-12 16:41:08 +00001603 const FieldDecl *field;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001604 CodeGenFunction::Destroyer *destroyer;
John McCall4bd0fb12011-07-12 16:41:08 +00001605 bool useEHCleanupForArray;
John McCallf99a6312010-07-21 05:30:47 +00001606
John McCall4bd0fb12011-07-12 16:41:08 +00001607 public:
1608 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
1609 bool useEHCleanupForArray)
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001610 : field(field), destroyer(destroyer),
1611 useEHCleanupForArray(useEHCleanupForArray) {}
John McCallf99a6312010-07-21 05:30:47 +00001612
Craig Topper4f12f102014-03-12 06:41:41 +00001613 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall4bd0fb12011-07-12 16:41:08 +00001614 // Find the address of the field.
John McCall7f416cc2015-09-08 08:05:57 +00001615 Address thisValue = CGF.LoadCXXThisAddress();
Eli Friedman7f1ff602012-04-16 03:54:45 +00001616 QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
1617 LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
1618 LValue LV = CGF.EmitLValueForField(ThisLV, field);
John McCall4bd0fb12011-07-12 16:41:08 +00001619 assert(LV.isSimple());
Justin Bogner1cd11f12015-05-20 15:53:59 +00001620
John McCall4bd0fb12011-07-12 16:41:08 +00001621 CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +00001622 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCallf99a6312010-07-21 05:30:47 +00001623 }
1624 };
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001625
Naomi Musgrave703835c2015-09-16 00:38:22 +00001626 static void EmitSanitizerDtorCallback(CodeGenFunction &CGF, llvm::Value *Ptr,
1627 CharUnits::QuantityType PoisonSize) {
Matt Morehouse4881a232017-09-20 22:53:08 +00001628 CodeGenFunction::SanitizerScope SanScope(&CGF);
Naomi Musgrave703835c2015-09-16 00:38:22 +00001629 // Pass in void pointer and size of region as arguments to runtime
1630 // function
1631 llvm::Value *Args[] = {CGF.Builder.CreateBitCast(Ptr, CGF.VoidPtrTy),
1632 llvm::ConstantInt::get(CGF.SizeTy, PoisonSize)};
1633
1634 llvm::Type *ArgTypes[] = {CGF.VoidPtrTy, CGF.SizeTy};
1635
1636 llvm::FunctionType *FnType =
1637 llvm::FunctionType::get(CGF.VoidTy, ArgTypes, false);
James Y Knight9871db02019-02-05 16:42:33 +00001638 llvm::FunctionCallee Fn =
Naomi Musgrave703835c2015-09-16 00:38:22 +00001639 CGF.CGM.CreateRuntimeFunction(FnType, "__sanitizer_dtor_callback");
1640 CGF.EmitNounwindRuntimeCall(Fn, Args);
1641 }
1642
1643 class SanitizeDtorMembers final : public EHScopeStack::Cleanup {
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001644 const CXXDestructorDecl *Dtor;
1645
1646 public:
Naomi Musgrave703835c2015-09-16 00:38:22 +00001647 SanitizeDtorMembers(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001648
1649 // Generate function call for handling object poisoning.
1650 // Disables tail call elimination, to prevent the current stack frame
1651 // from disappearing from the stack trace.
1652 void Emit(CodeGenFunction &CGF, Flags flags) override {
1653 const ASTRecordLayout &Layout =
1654 CGF.getContext().getASTRecordLayout(Dtor->getParent());
1655
1656 // Nothing to poison.
1657 if (Layout.getFieldCount() == 0)
1658 return;
1659
1660 // Prevent the current stack frame from disappearing from the stack trace.
1661 CGF.CurFn->addFnAttr("disable-tail-calls", "true");
1662
1663 // Construct pointer to region to begin poisoning, and calculate poison
1664 // size, so that only members declared in this class are poisoned.
1665 ASTContext &Context = CGF.getContext();
1666 unsigned fieldIndex = 0;
1667 int startIndex = -1;
1668 // RecordDecl::field_iterator Field;
1669 for (const FieldDecl *Field : Dtor->getParent()->fields()) {
1670 // Poison field if it is trivial
1671 if (FieldHasTrivialDestructorBody(Context, Field)) {
1672 // Start sanitizing at this field
1673 if (startIndex < 0)
1674 startIndex = fieldIndex;
1675
1676 // Currently on the last field, and it must be poisoned with the
1677 // current block.
1678 if (fieldIndex == Layout.getFieldCount() - 1) {
Naomi Musgrave703835c2015-09-16 00:38:22 +00001679 PoisonMembers(CGF, startIndex, Layout.getFieldCount());
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001680 }
1681 } else if (startIndex >= 0) {
1682 // No longer within a block of memory to poison, so poison the block
Naomi Musgrave703835c2015-09-16 00:38:22 +00001683 PoisonMembers(CGF, startIndex, fieldIndex);
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001684 // Re-set the start index
1685 startIndex = -1;
1686 }
1687 fieldIndex += 1;
1688 }
1689 }
1690
1691 private:
NAKAMURA Takumif6cef72f2015-09-04 05:19:31 +00001692 /// \param layoutStartOffset index of the ASTRecordLayout field to
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001693 /// start poisoning (inclusive)
NAKAMURA Takumif6cef72f2015-09-04 05:19:31 +00001694 /// \param layoutEndOffset index of the ASTRecordLayout field to
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001695 /// end poisoning (exclusive)
Naomi Musgrave703835c2015-09-16 00:38:22 +00001696 void PoisonMembers(CodeGenFunction &CGF, unsigned layoutStartOffset,
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001697 unsigned layoutEndOffset) {
1698 ASTContext &Context = CGF.getContext();
1699 const ASTRecordLayout &Layout =
1700 Context.getASTRecordLayout(Dtor->getParent());
1701
1702 llvm::ConstantInt *OffsetSizePtr = llvm::ConstantInt::get(
1703 CGF.SizeTy,
1704 Context.toCharUnitsFromBits(Layout.getFieldOffset(layoutStartOffset))
1705 .getQuantity());
1706
1707 llvm::Value *OffsetPtr = CGF.Builder.CreateGEP(
1708 CGF.Builder.CreateBitCast(CGF.LoadCXXThis(), CGF.Int8PtrTy),
1709 OffsetSizePtr);
1710
1711 CharUnits::QuantityType PoisonSize;
1712 if (layoutEndOffset >= Layout.getFieldCount()) {
1713 PoisonSize = Layout.getNonVirtualSize().getQuantity() -
1714 Context.toCharUnitsFromBits(
1715 Layout.getFieldOffset(layoutStartOffset))
1716 .getQuantity();
1717 } else {
1718 PoisonSize = Context.toCharUnitsFromBits(
1719 Layout.getFieldOffset(layoutEndOffset) -
1720 Layout.getFieldOffset(layoutStartOffset))
1721 .getQuantity();
1722 }
1723
1724 if (PoisonSize == 0)
1725 return;
1726
Naomi Musgrave703835c2015-09-16 00:38:22 +00001727 EmitSanitizerDtorCallback(CGF, OffsetPtr, PoisonSize);
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001728 }
1729 };
Naomi Musgrave703835c2015-09-16 00:38:22 +00001730
1731 class SanitizeDtorVTable final : public EHScopeStack::Cleanup {
1732 const CXXDestructorDecl *Dtor;
1733
1734 public:
1735 SanitizeDtorVTable(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
1736
1737 // Generate function call for handling vtable pointer poisoning.
1738 void Emit(CodeGenFunction &CGF, Flags flags) override {
1739 assert(Dtor->getParent()->isDynamicClass());
NAKAMURA Takumiee82b492015-09-16 06:26:56 +00001740 (void)Dtor;
Naomi Musgrave703835c2015-09-16 00:38:22 +00001741 ASTContext &Context = CGF.getContext();
1742 // Poison vtable and vtable ptr if they exist for this class.
1743 llvm::Value *VTablePtr = CGF.LoadCXXThis();
1744
1745 CharUnits::QuantityType PoisonSize =
1746 Context.toCharUnitsFromBits(CGF.PointerWidthInBits).getQuantity();
1747 // Pass in void pointer and size of region as arguments to runtime
1748 // function
1749 EmitSanitizerDtorCallback(CGF, VTablePtr, PoisonSize);
1750 }
1751 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00001752} // end anonymous namespace
John McCallf99a6312010-07-21 05:30:47 +00001753
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001754/// Emit all code that comes at the end of class's
Anders Carlssonfb404882009-12-24 22:46:43 +00001755/// destructor. This is to call destructors on members and base classes
1756/// in reverse order of their construction.
Richard Smith5b349582017-10-13 01:55:36 +00001757///
1758/// For a deleting destructor, this also handles the case where a destroying
1759/// operator delete completely overrides the definition.
John McCallf99a6312010-07-21 05:30:47 +00001760void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
1761 CXXDtorType DtorType) {
Hans Wennborg853ae942014-05-30 16:59:42 +00001762 assert((!DD->isTrivial() || DD->hasAttr<DLLExportAttr>()) &&
1763 "Should not emit dtor epilogue for non-exported trivial dtor!");
Anders Carlssonfb404882009-12-24 22:46:43 +00001764
John McCallf99a6312010-07-21 05:30:47 +00001765 // The deleting-destructor phase just needs to call the appropriate
1766 // operator delete that Sema picked up.
John McCall5c60a6f2010-02-18 19:59:28 +00001767 if (DtorType == Dtor_Deleting) {
Justin Bogner1cd11f12015-05-20 15:53:59 +00001768 assert(DD->getOperatorDelete() &&
Hans Wennborgdeff7032013-12-18 01:39:59 +00001769 "operator delete missing - EnterDtorCleanups");
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001770 if (CXXStructorImplicitParamValue) {
1771 // If there is an implicit param to the deleting dtor, it's a boolean
Richard Smith5b349582017-10-13 01:55:36 +00001772 // telling whether this is a deleting destructor.
1773 if (DD->getOperatorDelete()->isDestroyingOperatorDelete())
1774 EmitConditionalDtorDeleteCall(*this, CXXStructorImplicitParamValue,
1775 /*ReturnAfterDelete*/true);
1776 else
1777 EHStack.pushCleanup<CallDtorDeleteConditional>(
1778 NormalAndEHCleanup, CXXStructorImplicitParamValue);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001779 } else {
Richard Smith5b349582017-10-13 01:55:36 +00001780 if (DD->getOperatorDelete()->isDestroyingOperatorDelete()) {
1781 const CXXRecordDecl *ClassDecl = DD->getParent();
1782 EmitDeleteCall(DD->getOperatorDelete(),
1783 LoadThisForDtorDelete(*this, DD),
1784 getContext().getTagDeclType(ClassDecl));
1785 EmitBranchThroughCleanup(ReturnBlock);
1786 } else {
1787 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
1788 }
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001789 }
John McCall5c60a6f2010-02-18 19:59:28 +00001790 return;
1791 }
1792
John McCallf99a6312010-07-21 05:30:47 +00001793 const CXXRecordDecl *ClassDecl = DD->getParent();
1794
Richard Smith20104042011-09-18 12:11:43 +00001795 // Unions have no bases and do not call field destructors.
1796 if (ClassDecl->isUnion())
1797 return;
1798
John McCallf99a6312010-07-21 05:30:47 +00001799 // The complete-destructor phase just destructs all the virtual bases.
John McCall5c60a6f2010-02-18 19:59:28 +00001800 if (DtorType == Dtor_Complete) {
Naomi Musgrave703835c2015-09-16 00:38:22 +00001801 // Poison the vtable pointer such that access after the base
1802 // and member destructors are invoked is invalid.
1803 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1804 SanOpts.has(SanitizerKind::Memory) && ClassDecl->getNumVBases() &&
1805 ClassDecl->isPolymorphic())
1806 EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
John McCallf99a6312010-07-21 05:30:47 +00001807
1808 // We push them in the forward order so that they'll be popped in
1809 // the reverse order.
Aaron Ballman445a9392014-03-13 16:15:17 +00001810 for (const auto &Base : ClassDecl->vbases()) {
John McCall5c60a6f2010-02-18 19:59:28 +00001811 CXXRecordDecl *BaseClassDecl
1812 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Justin Bogner1cd11f12015-05-20 15:53:59 +00001813
John McCall5c60a6f2010-02-18 19:59:28 +00001814 // Ignore trivial destructors.
1815 if (BaseClassDecl->hasTrivialDestructor())
1816 continue;
John McCallf99a6312010-07-21 05:30:47 +00001817
John McCallcda666c2010-07-21 07:22:38 +00001818 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1819 BaseClassDecl,
1820 /*BaseIsVirtual*/ true);
John McCall5c60a6f2010-02-18 19:59:28 +00001821 }
John McCallf99a6312010-07-21 05:30:47 +00001822
John McCall5c60a6f2010-02-18 19:59:28 +00001823 return;
1824 }
1825
1826 assert(DtorType == Dtor_Base);
Naomi Musgrave703835c2015-09-16 00:38:22 +00001827 // Poison the vtable pointer if it has no virtual bases, but inherits
1828 // virtual functions.
1829 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1830 SanOpts.has(SanitizerKind::Memory) && !ClassDecl->getNumVBases() &&
1831 ClassDecl->isPolymorphic())
1832 EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001833
John McCallf99a6312010-07-21 05:30:47 +00001834 // Destroy non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001835 for (const auto &Base : ClassDecl->bases()) {
John McCallf99a6312010-07-21 05:30:47 +00001836 // Ignore virtual bases.
1837 if (Base.isVirtual())
1838 continue;
Justin Bogner1cd11f12015-05-20 15:53:59 +00001839
John McCallf99a6312010-07-21 05:30:47 +00001840 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
Justin Bogner1cd11f12015-05-20 15:53:59 +00001841
John McCallf99a6312010-07-21 05:30:47 +00001842 // Ignore trivial destructors.
1843 if (BaseClassDecl->hasTrivialDestructor())
1844 continue;
John McCall5c60a6f2010-02-18 19:59:28 +00001845
John McCallcda666c2010-07-21 07:22:38 +00001846 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1847 BaseClassDecl,
1848 /*BaseIsVirtual*/ false);
John McCallf99a6312010-07-21 05:30:47 +00001849 }
1850
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001851 // Poison fields such that access after their destructors are
1852 // invoked, and before the base class destructor runs, is invalid.
1853 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1854 SanOpts.has(SanitizerKind::Memory))
Naomi Musgrave703835c2015-09-16 00:38:22 +00001855 EHStack.pushCleanup<SanitizeDtorMembers>(NormalAndEHCleanup, DD);
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001856
John McCallf99a6312010-07-21 05:30:47 +00001857 // Destroy direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001858 for (const auto *Field : ClassDecl->fields()) {
1859 QualType type = Field->getType();
John McCall4bd0fb12011-07-12 16:41:08 +00001860 QualType::DestructionKind dtorKind = type.isDestructedType();
1861 if (!dtorKind) continue;
John McCallf99a6312010-07-21 05:30:47 +00001862
Richard Smith921bd202012-02-26 09:11:52 +00001863 // Anonymous union members do not have their destructors called.
1864 const RecordType *RT = type->getAsUnionType();
1865 if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
1866
John McCall4bd0fb12011-07-12 16:41:08 +00001867 CleanupKind cleanupKind = getCleanupKind(dtorKind);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001868 EHStack.pushCleanup<DestroyField>(cleanupKind, Field,
John McCall4bd0fb12011-07-12 16:41:08 +00001869 getDestroyer(dtorKind),
1870 cleanupKind & EHCleanup);
Anders Carlssonfb404882009-12-24 22:46:43 +00001871 }
Anders Carlssonfb404882009-12-24 22:46:43 +00001872}
1873
John McCallf677a8e2011-07-13 06:10:41 +00001874/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1875/// constructor for each of several members of an array.
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001876///
John McCallf677a8e2011-07-13 06:10:41 +00001877/// \param ctor the constructor to call for each element
John McCallf677a8e2011-07-13 06:10:41 +00001878/// \param arrayType the type of the array to initialize
1879/// \param arrayBegin an arrayType*
1880/// \param zeroInitialize true if each element should be
1881/// zero-initialized before it is constructed
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001882void CodeGenFunction::EmitCXXAggrConstructorCall(
Alexey Bataeve7545b32016-04-29 09:39:50 +00001883 const CXXConstructorDecl *ctor, const ArrayType *arrayType,
Serge Pavlov37605182018-07-28 15:33:03 +00001884 Address arrayBegin, const CXXConstructExpr *E, bool NewPointerIsChecked,
1885 bool zeroInitialize) {
John McCallf677a8e2011-07-13 06:10:41 +00001886 QualType elementType;
1887 llvm::Value *numElements =
1888 emitArrayLength(arrayType, elementType, arrayBegin);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001889
Serge Pavlov37605182018-07-28 15:33:03 +00001890 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin, E,
1891 NewPointerIsChecked, zeroInitialize);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001892}
1893
John McCallf677a8e2011-07-13 06:10:41 +00001894/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1895/// constructor for each of several members of an array.
1896///
1897/// \param ctor the constructor to call for each element
1898/// \param numElements the number of elements in the array;
John McCall6549b312011-07-13 07:37:11 +00001899/// may be zero
NAKAMURA Takumiff7a9252015-09-08 09:42:41 +00001900/// \param arrayBase a T*, where T is the type constructed by ctor
John McCallf677a8e2011-07-13 06:10:41 +00001901/// \param zeroInitialize true if each element should be
1902/// zero-initialized before it is constructed
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001903void CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1904 llvm::Value *numElements,
John McCall7f416cc2015-09-08 08:05:57 +00001905 Address arrayBase,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001906 const CXXConstructExpr *E,
Serge Pavlov37605182018-07-28 15:33:03 +00001907 bool NewPointerIsChecked,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001908 bool zeroInitialize) {
John McCall6549b312011-07-13 07:37:11 +00001909 // It's legal for numElements to be zero. This can happen both
1910 // dynamically, because x can be zero in 'new A[x]', and statically,
1911 // because of GCC extensions that permit zero-length arrays. There
1912 // are probably legitimate places where we could assume that this
1913 // doesn't happen, but it's not clear that it's worth it.
Craig Topper8a13c412014-05-21 05:09:00 +00001914 llvm::BranchInst *zeroCheckBranch = nullptr;
John McCall6549b312011-07-13 07:37:11 +00001915
1916 // Optimize for a constant count.
1917 llvm::ConstantInt *constantCount
1918 = dyn_cast<llvm::ConstantInt>(numElements);
1919 if (constantCount) {
1920 // Just skip out if the constant count is zero.
1921 if (constantCount->isZero()) return;
1922
1923 // Otherwise, emit the check.
1924 } else {
1925 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1926 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1927 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1928 EmitBlock(loopBB);
1929 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00001930
John McCallf677a8e2011-07-13 06:10:41 +00001931 // Find the end of the array.
John McCall7f416cc2015-09-08 08:05:57 +00001932 llvm::Value *arrayBegin = arrayBase.getPointer();
John McCallf677a8e2011-07-13 06:10:41 +00001933 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1934 "arrayctor.end");
Anders Carlsson27da15b2010-01-01 20:29:01 +00001935
John McCallf677a8e2011-07-13 06:10:41 +00001936 // Enter the loop, setting up a phi for the current location to initialize.
1937 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1938 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1939 EmitBlock(loopBB);
1940 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1941 "arrayctor.cur");
1942 cur->addIncoming(arrayBegin, entryBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001943
Anders Carlsson27da15b2010-01-01 20:29:01 +00001944 // Inside the loop body, emit the constructor call on the array element.
John McCallf677a8e2011-07-13 06:10:41 +00001945
John McCall7f416cc2015-09-08 08:05:57 +00001946 // The alignment of the base, adjusted by the size of a single element,
1947 // provides a conservative estimate of the alignment of every element.
1948 // (This assumes we never start tracking offsetted alignments.)
Fangrui Song6907ce22018-07-30 19:24:48 +00001949 //
John McCall7f416cc2015-09-08 08:05:57 +00001950 // Note that these are complete objects and so we don't need to
1951 // use the non-virtual size or alignment.
John McCallf677a8e2011-07-13 06:10:41 +00001952 QualType type = getContext().getTypeDeclType(ctor->getParent());
John McCall7f416cc2015-09-08 08:05:57 +00001953 CharUnits eltAlignment =
1954 arrayBase.getAlignment()
1955 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
1956 Address curAddr = Address(cur, eltAlignment);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001957
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001958 // Zero initialize the storage, if requested.
John McCallf677a8e2011-07-13 06:10:41 +00001959 if (zeroInitialize)
John McCall7f416cc2015-09-08 08:05:57 +00001960 EmitNullInitialization(curAddr, type);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001961
1962 // C++ [class.temporary]p4:
Anders Carlsson27da15b2010-01-01 20:29:01 +00001963 // There are two contexts in which temporaries are destroyed at a different
1964 // point than the end of the full-expression. The first context is when a
Justin Bogner1cd11f12015-05-20 15:53:59 +00001965 // default constructor is called to initialize an element of an array.
1966 // If the constructor has one or more default arguments, the destruction of
1967 // every temporary created in a default argument expression is sequenced
Anders Carlsson27da15b2010-01-01 20:29:01 +00001968 // before the construction of the next array element, if any.
Justin Bogner1cd11f12015-05-20 15:53:59 +00001969
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00001970 {
John McCallbd309292010-07-06 01:34:17 +00001971 RunCleanupsScope Scope(*this);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001972
John McCallf677a8e2011-07-13 06:10:41 +00001973 // Evaluate the constructor and its arguments in a regular
1974 // partial-destroy cleanup.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001975 if (getLangOpts().Exceptions &&
John McCallf677a8e2011-07-13 06:10:41 +00001976 !ctor->getParent()->hasTrivialDestructor()) {
1977 Destroyer *destroyer = destroyCXXObject;
John McCall7f416cc2015-09-08 08:05:57 +00001978 pushRegularPartialArrayCleanup(arrayBegin, cur, type, eltAlignment,
1979 *destroyer);
John McCallf677a8e2011-07-13 06:10:41 +00001980 }
1981
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001982 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/false,
Richard Smithe78fac52018-04-05 20:52:58 +00001983 /*Delegating=*/false, curAddr, E,
Serge Pavlov37605182018-07-28 15:33:03 +00001984 AggValueSlot::DoesNotOverlap, NewPointerIsChecked);
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00001985 }
Anders Carlsson27da15b2010-01-01 20:29:01 +00001986
John McCallf677a8e2011-07-13 06:10:41 +00001987 // Go to the next element.
1988 llvm::Value *next =
1989 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
1990 "arrayctor.next");
1991 cur->addIncoming(next, Builder.GetInsertBlock());
Anders Carlsson27da15b2010-01-01 20:29:01 +00001992
John McCallf677a8e2011-07-13 06:10:41 +00001993 // Check whether that's the end of the loop.
1994 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
1995 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
1996 Builder.CreateCondBr(done, contBB, loopBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001997
John McCall6549b312011-07-13 07:37:11 +00001998 // Patch the earlier check to skip over the loop.
1999 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
2000
John McCallf677a8e2011-07-13 06:10:41 +00002001 EmitBlock(contBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002002}
2003
John McCall82fe67b2011-07-09 01:37:26 +00002004void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002005 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002006 QualType type) {
2007 const RecordType *rtype = type->castAs<RecordType>();
2008 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
2009 const CXXDestructorDecl *dtor = record->getDestructor();
2010 assert(!dtor->isTrivial());
2011 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
Douglas Gregor61535002013-01-31 05:50:40 +00002012 /*Delegating=*/false, addr);
John McCall82fe67b2011-07-09 01:37:26 +00002013}
2014
Alexey Samsonov70b9c012014-08-21 20:26:47 +00002015void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
2016 CXXCtorType Type,
2017 bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +00002018 bool Delegating, Address This,
Richard Smithe78fac52018-04-05 20:52:58 +00002019 const CXXConstructExpr *E,
Serge Pavlov37605182018-07-28 15:33:03 +00002020 AggValueSlot::Overlap_t Overlap,
2021 bool NewPointerIsChecked) {
Richard Smith5179eb72016-06-28 19:03:57 +00002022 CallArgList Args;
2023
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00002024 LangAS SlotAS = E->getType().getAddressSpace();
Brian Gesiak5488ab42019-01-11 01:54:53 +00002025 QualType ThisType = D->getThisType();
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00002026 LangAS ThisAS = ThisType.getTypePtr()->getPointeeType().getAddressSpace();
2027 llvm::Value *ThisPtr = This.getPointer();
2028 if (SlotAS != ThisAS) {
2029 unsigned TargetThisAS = getContext().getTargetAddressSpace(ThisAS);
2030 llvm::Type *NewType =
2031 ThisPtr->getType()->getPointerElementType()->getPointerTo(TargetThisAS);
2032 ThisPtr = getTargetHooks().performAddrSpaceCast(*this, This.getPointer(),
2033 ThisAS, SlotAS, NewType);
2034 }
Richard Smith5179eb72016-06-28 19:03:57 +00002035 // Push the this ptr.
Brian Gesiak5488ab42019-01-11 01:54:53 +00002036 Args.add(RValue::get(ThisPtr), D->getThisType());
Richard Smith5179eb72016-06-28 19:03:57 +00002037
2038 // If this is a trivial constructor, emit a memcpy now before we lose
2039 // the alignment information on the argument.
2040 // FIXME: It would be better to preserve alignment information into CallArg.
2041 if (isMemcpyEquivalentSpecialMember(D)) {
2042 assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
2043
2044 const Expr *Arg = E->getArg(0);
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00002045 LValue Src = EmitLValue(Arg);
Richard Smith5179eb72016-06-28 19:03:57 +00002046 QualType DestTy = getContext().getTypeDeclType(D->getParent());
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00002047 LValue Dest = MakeAddrLValue(This, DestTy);
Richard Smithe78fac52018-04-05 20:52:58 +00002048 EmitAggregateCopyCtor(Dest, Src, Overlap);
Richard Smith5179eb72016-06-28 19:03:57 +00002049 return;
2050 }
2051
2052 // Add the rest of the user-supplied arguments.
2053 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
Hans Wennborg27dcc6c2017-02-01 02:21:07 +00002054 EvaluationOrder Order = E->isListInitialization()
2055 ? EvaluationOrder::ForceLeftToRight
2056 : EvaluationOrder::Default;
2057 EmitCallArgs(Args, FPT, E->arguments(), E->getConstructor(),
2058 /*ParamsToSkip*/ 0, Order);
Richard Smith5179eb72016-06-28 19:03:57 +00002059
Richard Smithe78fac52018-04-05 20:52:58 +00002060 EmitCXXConstructorCall(D, Type, ForVirtualBase, Delegating, This, Args,
Serge Pavlov37605182018-07-28 15:33:03 +00002061 Overlap, E->getExprLoc(), NewPointerIsChecked);
Richard Smith5179eb72016-06-28 19:03:57 +00002062}
2063
2064static bool canEmitDelegateCallArgs(CodeGenFunction &CGF,
2065 const CXXConstructorDecl *Ctor,
2066 CXXCtorType Type, CallArgList &Args) {
2067 // We can't forward a variadic call.
2068 if (Ctor->isVariadic())
2069 return false;
2070
2071 if (CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2072 // If the parameters are callee-cleanup, it's not safe to forward.
2073 for (auto *P : Ctor->parameters())
2074 if (P->getType().isDestructedType())
2075 return false;
2076
2077 // Likewise if they're inalloca.
2078 const CGFunctionInfo &Info =
George Burgess IVd0a9e802017-02-23 22:07:35 +00002079 CGF.CGM.getTypes().arrangeCXXConstructorCall(Args, Ctor, Type, 0, 0);
Richard Smith5179eb72016-06-28 19:03:57 +00002080 if (Info.usesInAlloca())
2081 return false;
2082 }
2083
2084 // Anything else should be OK.
2085 return true;
2086}
2087
2088void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
2089 CXXCtorType Type,
2090 bool ForVirtualBase,
2091 bool Delegating,
2092 Address This,
Richard Smithe78fac52018-04-05 20:52:58 +00002093 CallArgList &Args,
Igor Kudrineff8f9d2018-06-25 05:48:04 +00002094 AggValueSlot::Overlap_t Overlap,
Serge Pavlov37605182018-07-28 15:33:03 +00002095 SourceLocation Loc,
2096 bool NewPointerIsChecked) {
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002097 const CXXRecordDecl *ClassDecl = D->getParent();
2098
Serge Pavlov37605182018-07-28 15:33:03 +00002099 if (!NewPointerIsChecked)
2100 EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall, Loc, This.getPointer(),
2101 getContext().getRecordType(ClassDecl), CharUnits::Zero());
John McCallca972cd2010-02-06 00:25:16 +00002102
Richard Smith419bd092015-04-29 19:26:57 +00002103 if (D->isTrivial() && D->isDefaultConstructor()) {
Richard Smith5179eb72016-06-28 19:03:57 +00002104 assert(Args.size() == 1 && "trivial default ctor with args");
Richard Smith419bd092015-04-29 19:26:57 +00002105 return;
2106 }
2107
2108 // If this is a trivial constructor, just emit what's needed. If this is a
2109 // union copy constructor, we must emit a memcpy, because the AST does not
2110 // model that copy.
2111 if (isMemcpyEquivalentSpecialMember(D)) {
Richard Smith5179eb72016-06-28 19:03:57 +00002112 assert(Args.size() == 2 && "unexpected argcount for trivial ctor");
John McCallca972cd2010-02-06 00:25:16 +00002113
Richard Smith5179eb72016-06-28 19:03:57 +00002114 QualType SrcTy = D->getParamDecl(0)->getType().getNonReferenceType();
Yaxun Liu5b330e82018-03-15 15:25:19 +00002115 Address Src(Args[1].getRValue(*this).getScalarVal(),
2116 getNaturalTypeAlignment(SrcTy));
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00002117 LValue SrcLVal = MakeAddrLValue(Src, SrcTy);
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002118 QualType DestTy = getContext().getTypeDeclType(ClassDecl);
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00002119 LValue DestLVal = MakeAddrLValue(This, DestTy);
Richard Smithe78fac52018-04-05 20:52:58 +00002120 EmitAggregateCopyCtor(DestLVal, SrcLVal, Overlap);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002121 return;
2122 }
2123
George Burgess IVd0a9e802017-02-23 22:07:35 +00002124 bool PassPrototypeArgs = true;
Richard Smith5179eb72016-06-28 19:03:57 +00002125 // Check whether we can actually emit the constructor before trying to do so.
2126 if (auto Inherited = D->getInheritedConstructor()) {
George Burgess IVd0a9e802017-02-23 22:07:35 +00002127 PassPrototypeArgs = getTypes().inheritingCtorHasParams(Inherited, Type);
2128 if (PassPrototypeArgs && !canEmitDelegateCallArgs(*this, D, Type, Args)) {
Richard Smith5179eb72016-06-28 19:03:57 +00002129 EmitInlinedInheritingCXXConstructorCall(D, Type, ForVirtualBase,
2130 Delegating, Args);
2131 return;
2132 }
2133 }
Reid Kleckner89077a12013-12-17 19:46:40 +00002134
2135 // Insert any ABI-specific implicit constructor arguments.
George Burgess IVf203dbf2017-02-22 20:28:02 +00002136 CGCXXABI::AddedStructorArgs ExtraArgs =
2137 CGM.getCXXABI().addImplicitConstructorArgs(*this, D, Type, ForVirtualBase,
2138 Delegating, Args);
Reid Kleckner89077a12013-12-17 19:46:40 +00002139
2140 // Emit the call.
Peter Collingbourned1c5b282019-03-22 23:05:10 +00002141 llvm::Constant *CalleePtr = CGM.getAddrOfCXXStructor(GlobalDecl(D, Type));
George Burgess IVf203dbf2017-02-22 20:28:02 +00002142 const CGFunctionInfo &Info = CGM.getTypes().arrangeCXXConstructorCall(
George Burgess IVd0a9e802017-02-23 22:07:35 +00002143 Args, D, Type, ExtraArgs.Prefix, ExtraArgs.Suffix, PassPrototypeArgs);
Erich Keanede6480a32018-11-13 15:48:08 +00002144 CGCallee Callee = CGCallee::forDirect(CalleePtr, GlobalDecl(D, Type));
John McCallb92ab1a2016-10-26 23:46:34 +00002145 EmitCall(Info, Callee, ReturnValueSlot(), Args);
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002146
2147 // Generate vtable assumptions if we're constructing a complete object
2148 // with a vtable. We don't do this for base subobjects for two reasons:
2149 // first, it's incorrect for classes with virtual bases, and second, we're
2150 // about to overwrite the vptrs anyway.
2151 // We also have to make sure if we can refer to vtable:
2152 // - Otherwise we can refer to vtable if it's safe to speculatively emit.
2153 // FIXME: If vtable is used by ctor/dtor, or if vtable is external and we are
2154 // sure that definition of vtable is not hidden,
2155 // then we are always safe to refer to it.
Piotr Padlewski69dc9712015-09-28 20:30:22 +00002156 // FIXME: It looks like InstCombine is very inefficient on dealing with
2157 // assumes. Make assumption loads require -fstrict-vtable-pointers temporarily.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002158 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2159 ClassDecl->isDynamicClass() && Type != Ctor_Base &&
Piotr Padlewski69dc9712015-09-28 20:30:22 +00002160 CGM.getCXXABI().canSpeculativelyEmitVTable(ClassDecl) &&
2161 CGM.getCodeGenOpts().StrictVTablePointers)
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002162 EmitVTableAssumptionLoads(ClassDecl, This);
2163}
2164
Richard Smith5179eb72016-06-28 19:03:57 +00002165void CodeGenFunction::EmitInheritedCXXConstructorCall(
2166 const CXXConstructorDecl *D, bool ForVirtualBase, Address This,
2167 bool InheritedFromVBase, const CXXInheritedCtorInitExpr *E) {
2168 CallArgList Args;
Brian Gesiak5488ab42019-01-11 01:54:53 +00002169 CallArg ThisArg(RValue::get(This.getPointer()), D->getThisType());
Richard Smith5179eb72016-06-28 19:03:57 +00002170
2171 // Forward the parameters.
2172 if (InheritedFromVBase &&
2173 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
2174 // Nothing to do; this construction is not responsible for constructing
2175 // the base class containing the inherited constructor.
2176 // FIXME: Can we just pass undef's for the remaining arguments if we don't
2177 // have constructor variants?
2178 Args.push_back(ThisArg);
2179 } else if (!CXXInheritedCtorInitExprArgs.empty()) {
2180 // The inheriting constructor was inlined; just inject its arguments.
2181 assert(CXXInheritedCtorInitExprArgs.size() >= D->getNumParams() &&
2182 "wrong number of parameters for inherited constructor call");
2183 Args = CXXInheritedCtorInitExprArgs;
2184 Args[0] = ThisArg;
2185 } else {
2186 // The inheriting constructor was not inlined. Emit delegating arguments.
2187 Args.push_back(ThisArg);
2188 const auto *OuterCtor = cast<CXXConstructorDecl>(CurCodeDecl);
2189 assert(OuterCtor->getNumParams() == D->getNumParams());
2190 assert(!OuterCtor->isVariadic() && "should have been inlined");
2191
2192 for (const auto *Param : OuterCtor->parameters()) {
2193 assert(getContext().hasSameUnqualifiedType(
2194 OuterCtor->getParamDecl(Param->getFunctionScopeIndex())->getType(),
2195 Param->getType()));
2196 EmitDelegateCallArg(Args, Param, E->getLocation());
2197
2198 // Forward __attribute__(pass_object_size).
2199 if (Param->hasAttr<PassObjectSizeAttr>()) {
2200 auto *POSParam = SizeArguments[Param];
2201 assert(POSParam && "missing pass_object_size value for forwarding");
2202 EmitDelegateCallArg(Args, POSParam, E->getLocation());
2203 }
2204 }
2205 }
2206
2207 EmitCXXConstructorCall(D, Ctor_Base, ForVirtualBase, /*Delegating*/false,
Igor Kudrineff8f9d2018-06-25 05:48:04 +00002208 This, Args, AggValueSlot::MayOverlap,
Serge Pavlov37605182018-07-28 15:33:03 +00002209 E->getLocation(), /*NewPointerIsChecked*/true);
Richard Smith5179eb72016-06-28 19:03:57 +00002210}
2211
2212void CodeGenFunction::EmitInlinedInheritingCXXConstructorCall(
2213 const CXXConstructorDecl *Ctor, CXXCtorType CtorType, bool ForVirtualBase,
2214 bool Delegating, CallArgList &Args) {
Adrian Prantlb7acfc02017-02-27 21:30:05 +00002215 GlobalDecl GD(Ctor, CtorType);
2216 InlinedInheritingConstructorScope Scope(*this, GD);
2217 ApplyInlineDebugLocation DebugScope(*this, GD);
Volodymyr Sapsai232d22f2018-12-20 22:43:26 +00002218 RunCleanupsScope RunCleanups(*this);
Richard Smith5179eb72016-06-28 19:03:57 +00002219
2220 // Save the arguments to be passed to the inherited constructor.
2221 CXXInheritedCtorInitExprArgs = Args;
2222
2223 FunctionArgList Params;
2224 QualType RetType = BuildFunctionArgList(CurGD, Params);
2225 FnRetTy = RetType;
2226
2227 // Insert any ABI-specific implicit constructor arguments.
2228 CGM.getCXXABI().addImplicitConstructorArgs(*this, Ctor, CtorType,
2229 ForVirtualBase, Delegating, Args);
2230
2231 // Emit a simplified prolog. We only need to emit the implicit params.
2232 assert(Args.size() >= Params.size() && "too few arguments for call");
2233 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2234 if (I < Params.size() && isa<ImplicitParamDecl>(Params[I])) {
Yaxun Liu5b330e82018-03-15 15:25:19 +00002235 const RValue &RV = Args[I].getRValue(*this);
Richard Smith5179eb72016-06-28 19:03:57 +00002236 assert(!RV.isComplex() && "complex indirect params not supported");
2237 ParamValue Val = RV.isScalar()
2238 ? ParamValue::forDirect(RV.getScalarVal())
2239 : ParamValue::forIndirect(RV.getAggregateAddress());
2240 EmitParmDecl(*Params[I], Val, I + 1);
2241 }
2242 }
2243
2244 // Create a return value slot if the ABI implementation wants one.
2245 // FIXME: This is dumb, we should ask the ABI not to try to set the return
2246 // value instead.
2247 if (!RetType->isVoidType())
2248 ReturnValue = CreateIRTemp(RetType, "retval.inhctor");
2249
2250 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
2251 CXXThisValue = CXXABIThisValue;
2252
2253 // Directly emit the constructor initializers.
2254 EmitCtorPrologue(Ctor, CtorType, Params);
2255}
2256
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002257void CodeGenFunction::EmitVTableAssumptionLoad(const VPtr &Vptr, Address This) {
2258 llvm::Value *VTableGlobal =
2259 CGM.getCXXABI().getVTableAddressPoint(Vptr.Base, Vptr.VTableClass);
2260 if (!VTableGlobal)
2261 return;
2262
2263 // We can just use the base offset in the complete class.
2264 CharUnits NonVirtualOffset = Vptr.Base.getBaseOffset();
2265
2266 if (!NonVirtualOffset.isZero())
2267 This =
2268 ApplyNonVirtualAndVirtualOffset(*this, This, NonVirtualOffset, nullptr,
2269 Vptr.VTableClass, Vptr.NearestVBase);
2270
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002271 llvm::Value *VPtrValue =
2272 GetVTablePtr(This, VTableGlobal->getType(), Vptr.VTableClass);
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002273 llvm::Value *Cmp =
2274 Builder.CreateICmpEQ(VPtrValue, VTableGlobal, "cmp.vtables");
2275 Builder.CreateAssumption(Cmp);
2276}
2277
2278void CodeGenFunction::EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl,
2279 Address This) {
2280 if (CGM.getCXXABI().doStructorsInitializeVPtrs(ClassDecl))
2281 for (const VPtr &Vptr : getVTablePointers(ClassDecl))
2282 EmitVTableAssumptionLoad(Vptr, This);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002283}
2284
John McCallf8ff7b92010-02-23 00:48:20 +00002285void
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002286CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
John McCall7f416cc2015-09-08 08:05:57 +00002287 Address This, Address Src,
2288 const CXXConstructExpr *E) {
Reid Kleckner739756c2013-12-04 19:23:12 +00002289 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
Justin Bogner1cd11f12015-05-20 15:53:59 +00002290
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002291 CallArgList Args;
Justin Bogner1cd11f12015-05-20 15:53:59 +00002292
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002293 // Push the this ptr.
Brian Gesiak5488ab42019-01-11 01:54:53 +00002294 Args.add(RValue::get(This.getPointer()), D->getThisType());
Justin Bogner1cd11f12015-05-20 15:53:59 +00002295
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002296 // Push the src ptr.
Alp Toker9cacbab2014-01-20 20:26:09 +00002297 QualType QT = *(FPT->param_type_begin());
Chris Lattner2192fe52011-07-18 04:24:23 +00002298 llvm::Type *t = CGM.getTypes().ConvertType(QT);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002299 Src = Builder.CreateBitCast(Src, t);
John McCall7f416cc2015-09-08 08:05:57 +00002300 Args.add(RValue::get(Src.getPointer()), QT);
Reid Kleckner739756c2013-12-04 19:23:12 +00002301
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002302 // Skip over first argument (Src).
David Blaikief05779e2015-07-21 18:37:18 +00002303 EmitCallArgs(Args, FPT, drop_begin(E->arguments(), 1), E->getConstructor(),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002304 /*ParamsToSkip*/ 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002305
Serge Pavlov37605182018-07-28 15:33:03 +00002306 EmitCXXConstructorCall(D, Ctor_Complete, /*ForVirtualBase*/false,
2307 /*Delegating*/false, This, Args,
2308 AggValueSlot::MayOverlap, E->getExprLoc(),
2309 /*NewPointerIsChecked*/false);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002310}
2311
2312void
John McCallf8ff7b92010-02-23 00:48:20 +00002313CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
2314 CXXCtorType CtorType,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002315 const FunctionArgList &Args,
2316 SourceLocation Loc) {
John McCallf8ff7b92010-02-23 00:48:20 +00002317 CallArgList DelegateArgs;
2318
2319 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
2320 assert(I != E && "no parameters to constructor");
2321
2322 // this
Richard Smith5179eb72016-06-28 19:03:57 +00002323 Address This = LoadCXXThisAddress();
2324 DelegateArgs.add(RValue::get(This.getPointer()), (*I)->getType());
John McCallf8ff7b92010-02-23 00:48:20 +00002325 ++I;
2326
Richard Smith5179eb72016-06-28 19:03:57 +00002327 // FIXME: The location of the VTT parameter in the parameter list is
2328 // specific to the Itanium ABI and shouldn't be hardcoded here.
2329 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
2330 assert(I != E && "cannot skip vtt parameter, already done with args");
2331 assert((*I)->getType()->isPointerType() &&
2332 "skipping parameter not of vtt type");
2333 ++I;
John McCallf8ff7b92010-02-23 00:48:20 +00002334 }
2335
2336 // Explicit arguments.
2337 for (; I != E; ++I) {
John McCall32ea9692011-03-11 20:59:21 +00002338 const VarDecl *param = *I;
Nick Lewycky2d84e842013-10-02 02:29:49 +00002339 // FIXME: per-argument source location
2340 EmitDelegateCallArg(DelegateArgs, param, Loc);
John McCallf8ff7b92010-02-23 00:48:20 +00002341 }
2342
Richard Smith5179eb72016-06-28 19:03:57 +00002343 EmitCXXConstructorCall(Ctor, CtorType, /*ForVirtualBase=*/false,
Richard Smithe78fac52018-04-05 20:52:58 +00002344 /*Delegating=*/true, This, DelegateArgs,
Serge Pavlov37605182018-07-28 15:33:03 +00002345 AggValueSlot::MayOverlap, Loc,
2346 /*NewPointerIsChecked=*/true);
John McCallf8ff7b92010-02-23 00:48:20 +00002347}
2348
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002349namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002350 struct CallDelegatingCtorDtor final : EHScopeStack::Cleanup {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002351 const CXXDestructorDecl *Dtor;
John McCall7f416cc2015-09-08 08:05:57 +00002352 Address Addr;
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002353 CXXDtorType Type;
2354
John McCall7f416cc2015-09-08 08:05:57 +00002355 CallDelegatingCtorDtor(const CXXDestructorDecl *D, Address Addr,
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002356 CXXDtorType Type)
2357 : Dtor(D), Addr(Addr), Type(Type) {}
2358
Craig Topper4f12f102014-03-12 06:41:41 +00002359 void Emit(CodeGenFunction &CGF, Flags flags) override {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002360 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
Douglas Gregor61535002013-01-31 05:50:40 +00002361 /*Delegating=*/true, Addr);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002362 }
2363 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00002364} // end anonymous namespace
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002365
Alexis Hunt61bc1732011-05-01 07:04:31 +00002366void
2367CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
2368 const FunctionArgList &Args) {
2369 assert(Ctor->isDelegatingConstructor());
2370
John McCall7f416cc2015-09-08 08:05:57 +00002371 Address ThisPtr = LoadCXXThisAddress();
Alexis Hunt61bc1732011-05-01 07:04:31 +00002372
John McCall31168b02011-06-15 23:02:42 +00002373 AggValueSlot AggSlot =
John McCall7f416cc2015-09-08 08:05:57 +00002374 AggValueSlot::forAddr(ThisPtr, Qualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +00002375 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00002376 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00002377 AggValueSlot::IsNotAliased,
Serge Pavlov37605182018-07-28 15:33:03 +00002378 AggValueSlot::MayOverlap,
2379 AggValueSlot::IsNotZeroed,
2380 // Checks are made by the code that calls constructor.
2381 AggValueSlot::IsSanitizerChecked);
Alexis Hunt61bc1732011-05-01 07:04:31 +00002382
2383 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
Alexis Hunt61bc1732011-05-01 07:04:31 +00002384
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002385 const CXXRecordDecl *ClassDecl = Ctor->getParent();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002386 if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002387 CXXDtorType Type =
2388 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
2389
2390 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
2391 ClassDecl->getDestructor(),
2392 ThisPtr, Type);
2393 }
2394}
Alexis Hunt61bc1732011-05-01 07:04:31 +00002395
Anders Carlsson27da15b2010-01-01 20:29:01 +00002396void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
2397 CXXDtorType Type,
Anders Carlssonf8a71f02010-05-02 23:29:11 +00002398 bool ForVirtualBase,
Douglas Gregor61535002013-01-31 05:50:40 +00002399 bool Delegating,
John McCall7f416cc2015-09-08 08:05:57 +00002400 Address This) {
Reid Kleckner6fe771a2013-12-13 00:53:54 +00002401 CGM.getCXXABI().EmitDestructorCall(*this, DD, Type, ForVirtualBase,
2402 Delegating, This);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002403}
2404
John McCall53cad2e2010-07-21 01:41:18 +00002405namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002406 struct CallLocalDtor final : EHScopeStack::Cleanup {
John McCall53cad2e2010-07-21 01:41:18 +00002407 const CXXDestructorDecl *Dtor;
John McCall7f416cc2015-09-08 08:05:57 +00002408 Address Addr;
John McCall53cad2e2010-07-21 01:41:18 +00002409
John McCall7f416cc2015-09-08 08:05:57 +00002410 CallLocalDtor(const CXXDestructorDecl *D, Address Addr)
John McCall53cad2e2010-07-21 01:41:18 +00002411 : Dtor(D), Addr(Addr) {}
2412
Craig Topper4f12f102014-03-12 06:41:41 +00002413 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall53cad2e2010-07-21 01:41:18 +00002414 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +00002415 /*ForVirtualBase=*/false,
2416 /*Delegating=*/false, Addr);
John McCall53cad2e2010-07-21 01:41:18 +00002417 }
2418 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002419} // end anonymous namespace
John McCall53cad2e2010-07-21 01:41:18 +00002420
John McCall8680f872010-07-21 06:29:51 +00002421void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
John McCall7f416cc2015-09-08 08:05:57 +00002422 Address Addr) {
John McCallcda666c2010-07-21 07:22:38 +00002423 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
John McCall8680f872010-07-21 06:29:51 +00002424}
2425
John McCall7f416cc2015-09-08 08:05:57 +00002426void CodeGenFunction::PushDestructorCleanup(QualType T, Address Addr) {
John McCallbd309292010-07-06 01:34:17 +00002427 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
2428 if (!ClassDecl) return;
2429 if (ClassDecl->hasTrivialDestructor()) return;
2430
2431 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCalla85af562011-04-28 02:15:35 +00002432 assert(D && D->isUsed() && "destructor not marked as used!");
John McCall8680f872010-07-21 06:29:51 +00002433 PushDestructorCleanup(D, Addr);
John McCallbd309292010-07-06 01:34:17 +00002434}
2435
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002436void CodeGenFunction::InitializeVTablePointer(const VPtr &Vptr) {
Anders Carlssone87fae92010-03-28 19:40:00 +00002437 // Compute the address point.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002438 llvm::Value *VTableAddressPoint =
2439 CGM.getCXXABI().getVTableAddressPointInStructor(
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002440 *this, Vptr.VTableClass, Vptr.Base, Vptr.NearestVBase);
2441
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002442 if (!VTableAddressPoint)
2443 return;
Anders Carlssone87fae92010-03-28 19:40:00 +00002444
Anders Carlsson6a0227d2010-04-20 16:22:16 +00002445 // Compute where to store the address point.
Craig Topper8a13c412014-05-21 05:09:00 +00002446 llvm::Value *VirtualOffset = nullptr;
Ken Dyckcfc332c2011-03-23 00:45:26 +00002447 CharUnits NonVirtualOffset = CharUnits::Zero();
Justin Bogner1cd11f12015-05-20 15:53:59 +00002448
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002449 if (CGM.getCXXABI().isVirtualOffsetNeededForVTableField(*this, Vptr)) {
Anders Carlsson91baecf2010-04-20 18:05:10 +00002450 // We need to use the virtual base offset offset because the virtual base
2451 // might have a different offset in the most derived class.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002452
2453 VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(
2454 *this, LoadCXXThisAddress(), Vptr.VTableClass, Vptr.NearestVBase);
2455 NonVirtualOffset = Vptr.OffsetFromNearestVBase;
Anders Carlsson91baecf2010-04-20 18:05:10 +00002456 } else {
Anders Carlssonc58fb552010-05-03 00:29:58 +00002457 // We can just use the base offset in the complete class.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002458 NonVirtualOffset = Vptr.Base.getBaseOffset();
Anders Carlsson91baecf2010-04-20 18:05:10 +00002459 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002460
Anders Carlssonc58fb552010-05-03 00:29:58 +00002461 // Apply the offsets.
John McCall7f416cc2015-09-08 08:05:57 +00002462 Address VTableField = LoadCXXThisAddress();
Justin Bogner1cd11f12015-05-20 15:53:59 +00002463
Ken Dyckcfc332c2011-03-23 00:45:26 +00002464 if (!NonVirtualOffset.isZero() || VirtualOffset)
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002465 VTableField = ApplyNonVirtualAndVirtualOffset(
2466 *this, VTableField, NonVirtualOffset, VirtualOffset, Vptr.VTableClass,
2467 Vptr.NearestVBase);
Anders Carlsson6a0227d2010-04-20 16:22:16 +00002468
Reid Kleckner8d585132014-12-03 21:00:21 +00002469 // Finally, store the address point. Use the same LLVM types as the field to
2470 // support optimization.
2471 llvm::Type *VTablePtrTy =
2472 llvm::FunctionType::get(CGM.Int32Ty, /*isVarArg=*/true)
2473 ->getPointerTo()
2474 ->getPointerTo();
2475 VTableField = Builder.CreateBitCast(VTableField, VTablePtrTy->getPointerTo());
2476 VTableAddressPoint = Builder.CreateBitCast(VTableAddressPoint, VTablePtrTy);
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002477
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002478 llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
Ivan A. Kosarev4e50e702017-11-27 09:39:29 +00002479 TBAAAccessInfo TBAAInfo = CGM.getTBAAVTablePtrAccessInfo(VTablePtrTy);
2480 CGM.DecorateInstructionWithTBAA(Store, TBAAInfo);
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002481 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2482 CGM.getCodeGenOpts().StrictVTablePointers)
2483 CGM.DecorateInstructionWithInvariantGroup(Store, Vptr.VTableClass);
Anders Carlssone87fae92010-03-28 19:40:00 +00002484}
2485
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002486CodeGenFunction::VPtrsVector
2487CodeGenFunction::getVTablePointers(const CXXRecordDecl *VTableClass) {
2488 CodeGenFunction::VPtrsVector VPtrsResult;
2489 VisitedVirtualBasesSetTy VBases;
2490 getVTablePointers(BaseSubobject(VTableClass, CharUnits::Zero()),
2491 /*NearestVBase=*/nullptr,
2492 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
2493 /*BaseIsNonVirtualPrimaryBase=*/false, VTableClass, VBases,
2494 VPtrsResult);
2495 return VPtrsResult;
2496}
2497
2498void CodeGenFunction::getVTablePointers(BaseSubobject Base,
2499 const CXXRecordDecl *NearestVBase,
2500 CharUnits OffsetFromNearestVBase,
2501 bool BaseIsNonVirtualPrimaryBase,
2502 const CXXRecordDecl *VTableClass,
2503 VisitedVirtualBasesSetTy &VBases,
2504 VPtrsVector &Vptrs) {
Anders Carlssond5895932010-03-28 21:07:49 +00002505 // If this base is a non-virtual primary base the address point has already
2506 // been set.
2507 if (!BaseIsNonVirtualPrimaryBase) {
2508 // Initialize the vtable pointer for this base.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002509 VPtr Vptr = {Base, NearestVBase, OffsetFromNearestVBase, VTableClass};
2510 Vptrs.push_back(Vptr);
Anders Carlssond5895932010-03-28 21:07:49 +00002511 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002512
Anders Carlssond5895932010-03-28 21:07:49 +00002513 const CXXRecordDecl *RD = Base.getBase();
2514
2515 // Traverse bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00002516 for (const auto &I : RD->bases()) {
Anders Carlssond5895932010-03-28 21:07:49 +00002517 CXXRecordDecl *BaseDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00002518 = cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Anders Carlssond5895932010-03-28 21:07:49 +00002519
2520 // Ignore classes without a vtable.
2521 if (!BaseDecl->isDynamicClass())
2522 continue;
2523
Ken Dyck3fb4c892011-03-23 01:04:18 +00002524 CharUnits BaseOffset;
2525 CharUnits BaseOffsetFromNearestVBase;
Anders Carlsson948d3f42010-03-29 01:16:41 +00002526 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlssond5895932010-03-28 21:07:49 +00002527
Aaron Ballman574705e2014-03-13 15:41:46 +00002528 if (I.isVirtual()) {
Anders Carlssond5895932010-03-28 21:07:49 +00002529 // Check if we've visited this virtual base before.
David Blaikie82e95a32014-11-19 07:49:47 +00002530 if (!VBases.insert(BaseDecl).second)
Anders Carlssond5895932010-03-28 21:07:49 +00002531 continue;
2532
Justin Bogner1cd11f12015-05-20 15:53:59 +00002533 const ASTRecordLayout &Layout =
Anders Carlssond5895932010-03-28 21:07:49 +00002534 getContext().getASTRecordLayout(VTableClass);
2535
Ken Dyck3fb4c892011-03-23 01:04:18 +00002536 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
2537 BaseOffsetFromNearestVBase = CharUnits::Zero();
Anders Carlsson948d3f42010-03-29 01:16:41 +00002538 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlssond5895932010-03-28 21:07:49 +00002539 } else {
2540 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
2541
Ken Dyck16ffcac2011-03-24 01:21:01 +00002542 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
Justin Bogner1cd11f12015-05-20 15:53:59 +00002543 BaseOffsetFromNearestVBase =
Ken Dyck3fb4c892011-03-23 01:04:18 +00002544 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson948d3f42010-03-29 01:16:41 +00002545 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlssond5895932010-03-28 21:07:49 +00002546 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002547
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002548 getVTablePointers(
2549 BaseSubobject(BaseDecl, BaseOffset),
2550 I.isVirtual() ? BaseDecl : NearestVBase, BaseOffsetFromNearestVBase,
2551 BaseDeclIsNonVirtualPrimaryBase, VTableClass, VBases, Vptrs);
Anders Carlssond5895932010-03-28 21:07:49 +00002552 }
2553}
2554
2555void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
2556 // Ignore classes without a vtable.
Anders Carlsson1f9348c2010-03-26 04:39:42 +00002557 if (!RD->isDynamicClass())
Anders Carlsson27da15b2010-01-01 20:29:01 +00002558 return;
2559
Anders Carlssond5895932010-03-28 21:07:49 +00002560 // Initialize the vtable pointers for this class and all of its bases.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002561 if (CGM.getCXXABI().doStructorsInitializeVPtrs(RD))
2562 for (const VPtr &Vptr : getVTablePointers(RD))
2563 InitializeVTablePointer(Vptr);
Timur Iskhodzhanovb6487322013-10-09 18:16:58 +00002564
2565 if (RD->getNumVBases())
2566 CGM.getCXXABI().initializeHiddenVirtualInheritanceMembers(*this, RD);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002567}
Dan Gohman8fc50c22010-10-26 18:44:08 +00002568
John McCall7f416cc2015-09-08 08:05:57 +00002569llvm::Value *CodeGenFunction::GetVTablePtr(Address This,
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002570 llvm::Type *VTableTy,
2571 const CXXRecordDecl *RD) {
2572 Address VTablePtrSrc = Builder.CreateElementBitCast(This, VTableTy);
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002573 llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
Ivan A. Kosarev4e50e702017-11-27 09:39:29 +00002574 TBAAAccessInfo TBAAInfo = CGM.getTBAAVTablePtrAccessInfo(VTableTy);
2575 CGM.DecorateInstructionWithTBAA(VTable, TBAAInfo);
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002576
2577 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2578 CGM.getCodeGenOpts().StrictVTablePointers)
2579 CGM.DecorateInstructionWithInvariantGroup(VTable, RD);
2580
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002581 return VTable;
Dan Gohman8fc50c22010-10-26 18:44:08 +00002582}
Anders Carlssonc36783e2011-05-08 20:32:23 +00002583
Peter Collingbourned2926c92015-03-14 02:42:25 +00002584// If a class has a single non-virtual base and does not introduce or override
2585// virtual member functions or fields, it will have the same layout as its base.
2586// This function returns the least derived such class.
2587//
2588// Casting an instance of a base class to such a derived class is technically
2589// undefined behavior, but it is a relatively common hack for introducing member
2590// functions on class instances with specific properties (e.g. llvm::Operator)
2591// that works under most compilers and should not have security implications, so
2592// we allow it by default. It can be disabled with -fsanitize=cfi-cast-strict.
2593static const CXXRecordDecl *
2594LeastDerivedClassWithSameLayout(const CXXRecordDecl *RD) {
2595 if (!RD->field_empty())
2596 return RD;
2597
2598 if (RD->getNumVBases() != 0)
2599 return RD;
2600
2601 if (RD->getNumBases() != 1)
2602 return RD;
2603
2604 for (const CXXMethodDecl *MD : RD->methods()) {
2605 if (MD->isVirtual()) {
2606 // Virtual member functions are only ok if they are implicit destructors
2607 // because the implicit destructor will have the same semantics as the
2608 // base class's destructor if no fields are added.
2609 if (isa<CXXDestructorDecl>(MD) && MD->isImplicit())
2610 continue;
2611 return RD;
2612 }
2613 }
2614
2615 return LeastDerivedClassWithSameLayout(
2616 RD->bases_begin()->getType()->getAsCXXRecordDecl());
2617}
2618
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002619void CodeGenFunction::EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD,
2620 llvm::Value *VTable,
2621 SourceLocation Loc) {
Peter Collingbourne396943a2017-07-31 22:35:33 +00002622 if (SanOpts.has(SanitizerKind::CFIVCall))
2623 EmitVTablePtrCheckForCall(RD, VTable, CodeGenFunction::CFITCK_VCall, Loc);
2624 else if (CGM.getCodeGenOpts().WholeProgramVTables &&
2625 CGM.HasHiddenLTOVisibility(RD)) {
Peter Collingbournefb532b92016-02-24 20:46:36 +00002626 llvm::Metadata *MD =
2627 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002628 llvm::Value *TypeId =
Peter Collingbournefb532b92016-02-24 20:46:36 +00002629 llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD);
2630
2631 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002632 llvm::Value *TypeTest =
2633 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
2634 {CastedVTable, TypeId});
2635 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::assume), TypeTest);
Peter Collingbournefb532b92016-02-24 20:46:36 +00002636 }
Peter Collingbournefb532b92016-02-24 20:46:36 +00002637}
2638
2639void CodeGenFunction::EmitVTablePtrCheckForCall(const CXXRecordDecl *RD,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002640 llvm::Value *VTable,
2641 CFITypeCheckKind TCK,
2642 SourceLocation Loc) {
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002643 if (!SanOpts.has(SanitizerKind::CFICastStrict))
Peter Collingbournefb532b92016-02-24 20:46:36 +00002644 RD = LeastDerivedClassWithSameLayout(RD);
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002645
Peter Collingbournefb532b92016-02-24 20:46:36 +00002646 EmitVTablePtrCheck(RD, VTable, TCK, Loc);
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002647}
2648
Peter Collingbourned2926c92015-03-14 02:42:25 +00002649void CodeGenFunction::EmitVTablePtrCheckForCast(QualType T,
2650 llvm::Value *Derived,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002651 bool MayBeNull,
2652 CFITypeCheckKind TCK,
2653 SourceLocation Loc) {
Peter Collingbourned2926c92015-03-14 02:42:25 +00002654 if (!getLangOpts().CPlusPlus)
2655 return;
2656
2657 auto *ClassTy = T->getAs<RecordType>();
2658 if (!ClassTy)
2659 return;
2660
2661 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassTy->getDecl());
2662
2663 if (!ClassDecl->isCompleteDefinition() || !ClassDecl->isDynamicClass())
2664 return;
2665
Peter Collingbourned2926c92015-03-14 02:42:25 +00002666 if (!SanOpts.has(SanitizerKind::CFICastStrict))
2667 ClassDecl = LeastDerivedClassWithSameLayout(ClassDecl);
2668
Hans Wennborgdcfba332015-10-06 23:40:43 +00002669 llvm::BasicBlock *ContBlock = nullptr;
Peter Collingbourned2926c92015-03-14 02:42:25 +00002670
2671 if (MayBeNull) {
2672 llvm::Value *DerivedNotNull =
2673 Builder.CreateIsNotNull(Derived, "cast.nonnull");
2674
2675 llvm::BasicBlock *CheckBlock = createBasicBlock("cast.check");
2676 ContBlock = createBasicBlock("cast.cont");
2677
2678 Builder.CreateCondBr(DerivedNotNull, CheckBlock, ContBlock);
2679
2680 EmitBlock(CheckBlock);
2681 }
2682
Peter Collingbourne60108802017-12-13 21:53:04 +00002683 llvm::Value *VTable;
2684 std::tie(VTable, ClassDecl) = CGM.getCXXABI().LoadVTablePtr(
2685 *this, Address(Derived, getPointerAlign()), ClassDecl);
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002686
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002687 EmitVTablePtrCheck(ClassDecl, VTable, TCK, Loc);
Peter Collingbourned2926c92015-03-14 02:42:25 +00002688
2689 if (MayBeNull) {
2690 Builder.CreateBr(ContBlock);
2691 EmitBlock(ContBlock);
2692 }
2693}
2694
2695void CodeGenFunction::EmitVTablePtrCheck(const CXXRecordDecl *RD,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002696 llvm::Value *VTable,
2697 CFITypeCheckKind TCK,
2698 SourceLocation Loc) {
Peter Collingbourne3afb2662016-04-28 17:09:37 +00002699 if (!CGM.getCodeGenOpts().SanitizeCfiCrossDso &&
2700 !CGM.HasHiddenLTOVisibility(RD))
2701 return;
2702
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002703 SanitizerMask M;
Peter Collingbournedc134532016-01-16 00:31:22 +00002704 llvm::SanitizerStatKind SSK;
2705 switch (TCK) {
2706 case CFITCK_VCall:
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002707 M = SanitizerKind::CFIVCall;
Peter Collingbournedc134532016-01-16 00:31:22 +00002708 SSK = llvm::SanStat_CFI_VCall;
2709 break;
2710 case CFITCK_NVCall:
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002711 M = SanitizerKind::CFINVCall;
Peter Collingbournedc134532016-01-16 00:31:22 +00002712 SSK = llvm::SanStat_CFI_NVCall;
2713 break;
2714 case CFITCK_DerivedCast:
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002715 M = SanitizerKind::CFIDerivedCast;
Peter Collingbournedc134532016-01-16 00:31:22 +00002716 SSK = llvm::SanStat_CFI_DerivedCast;
2717 break;
2718 case CFITCK_UnrelatedCast:
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002719 M = SanitizerKind::CFIUnrelatedCast;
Peter Collingbournedc134532016-01-16 00:31:22 +00002720 SSK = llvm::SanStat_CFI_UnrelatedCast;
2721 break;
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002722 case CFITCK_ICall:
Peter Collingbournee44acad2018-06-26 02:15:47 +00002723 case CFITCK_NVMFCall:
2724 case CFITCK_VMFCall:
2725 llvm_unreachable("unexpected sanitizer kind");
Peter Collingbournedc134532016-01-16 00:31:22 +00002726 }
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002727
2728 std::string TypeName = RD->getQualifiedNameAsString();
2729 if (getContext().getSanitizerBlacklist().isBlacklistedType(M, TypeName))
2730 return;
2731
2732 SanitizerScope SanScope(this);
Peter Collingbournedc134532016-01-16 00:31:22 +00002733 EmitSanitizerStatReport(SSK);
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002734
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002735 llvm::Metadata *MD =
2736 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002737 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002738
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002739 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002740 llvm::Value *TypeTest = Builder.CreateCall(
2741 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, TypeId});
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002742
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002743 llvm::Constant *StaticData[] = {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002744 llvm::ConstantInt::get(Int8Ty, TCK),
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002745 EmitCheckSourceLocation(Loc),
2746 EmitCheckTypeDescriptor(QualType(RD->getTypeForDecl(), 0)),
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002747 };
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002748
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002749 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
2750 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
2751 EmitCfiSlowPathCheck(M, TypeTest, CrossDsoTypeId, CastedVTable, StaticData);
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002752 return;
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002753 }
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002754
2755 if (CGM.getCodeGenOpts().SanitizeTrap.has(M)) {
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002756 EmitTrapCheck(TypeTest);
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002757 return;
2758 }
2759
2760 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
2761 CGM.getLLVMContext(),
2762 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002763 llvm::Value *ValidVtable = Builder.CreateCall(
2764 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, AllVtables});
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002765 EmitCheck(std::make_pair(TypeTest, M), SanitizerHandler::CFICheckFail,
2766 StaticData, {CastedVTable, ValidVtable});
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002767}
Anders Carlssonc36783e2011-05-08 20:32:23 +00002768
Peter Collingbourne0ca03632016-06-25 00:24:06 +00002769bool CodeGenFunction::ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD) {
2770 if (!CGM.getCodeGenOpts().WholeProgramVTables ||
2771 !SanOpts.has(SanitizerKind::CFIVCall) ||
2772 !CGM.getCodeGenOpts().SanitizeTrap.has(SanitizerKind::CFIVCall) ||
2773 !CGM.HasHiddenLTOVisibility(RD))
2774 return false;
2775
2776 std::string TypeName = RD->getQualifiedNameAsString();
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002777 return !getContext().getSanitizerBlacklist().isBlacklistedType(
2778 SanitizerKind::CFIVCall, TypeName);
Peter Collingbourne0ca03632016-06-25 00:24:06 +00002779}
2780
2781llvm::Value *CodeGenFunction::EmitVTableTypeCheckedLoad(
2782 const CXXRecordDecl *RD, llvm::Value *VTable, uint64_t VTableByteOffset) {
2783 SanitizerScope SanScope(this);
2784
2785 EmitSanitizerStatReport(llvm::SanStat_CFI_VCall);
2786
2787 llvm::Metadata *MD =
2788 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
2789 llvm::Value *TypeId = llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD);
2790
2791 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
2792 llvm::Value *CheckedLoad = Builder.CreateCall(
2793 CGM.getIntrinsic(llvm::Intrinsic::type_checked_load),
2794 {CastedVTable, llvm::ConstantInt::get(Int32Ty, VTableByteOffset),
2795 TypeId});
2796 llvm::Value *CheckResult = Builder.CreateExtractValue(CheckedLoad, 1);
2797
2798 EmitCheck(std::make_pair(CheckResult, SanitizerKind::CFIVCall),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002799 SanitizerHandler::CFICheckFail, nullptr, nullptr);
Peter Collingbourne0ca03632016-06-25 00:24:06 +00002800
2801 return Builder.CreateBitCast(
2802 Builder.CreateExtractValue(CheckedLoad, 0),
2803 cast<llvm::PointerType>(VTable->getType())->getElementType());
2804}
2805
Faisal Vali571df122013-09-29 08:45:24 +00002806void CodeGenFunction::EmitForwardingCallToLambda(
2807 const CXXMethodDecl *callOperator,
2808 CallArgList &callArgs) {
Eli Friedman5b446882012-02-16 03:47:28 +00002809 // Get the address of the call operator.
John McCall8dda7b22012-07-07 06:41:13 +00002810 const CGFunctionInfo &calleeFnInfo =
2811 CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
John McCallb92ab1a2016-10-26 23:46:34 +00002812 llvm::Constant *calleePtr =
John McCall8dda7b22012-07-07 06:41:13 +00002813 CGM.GetAddrOfFunction(GlobalDecl(callOperator),
2814 CGM.getTypes().GetFunctionType(calleeFnInfo));
Eli Friedman5b446882012-02-16 03:47:28 +00002815
John McCall8dda7b22012-07-07 06:41:13 +00002816 // Prepare the return slot.
2817 const FunctionProtoType *FPT =
2818 callOperator->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00002819 QualType resultType = FPT->getReturnType();
John McCall8dda7b22012-07-07 06:41:13 +00002820 ReturnValueSlot returnSlot;
2821 if (!resultType->isVoidType() &&
2822 calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
John McCall47fb9502013-03-07 21:37:08 +00002823 !hasScalarEvaluationKind(calleeFnInfo.getReturnType()))
John McCall8dda7b22012-07-07 06:41:13 +00002824 returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
2825
2826 // We don't need to separately arrange the call arguments because
2827 // the call can't be variadic anyway --- it's impossible to forward
2828 // variadic arguments.
Justin Bogner1cd11f12015-05-20 15:53:59 +00002829
Eli Friedman5b446882012-02-16 03:47:28 +00002830 // Now emit our call.
Erich Keanede6480a32018-11-13 15:48:08 +00002831 auto callee = CGCallee::forDirect(calleePtr, GlobalDecl(callOperator));
John McCallb92ab1a2016-10-26 23:46:34 +00002832 RValue RV = EmitCall(calleeFnInfo, callee, returnSlot, callArgs);
Eli Friedman5b446882012-02-16 03:47:28 +00002833
John McCall8dda7b22012-07-07 06:41:13 +00002834 // If necessary, copy the returned value into the slot.
John McCall95088452017-12-14 18:21:14 +00002835 if (!resultType->isVoidType() && returnSlot.isNull()) {
2836 if (getLangOpts().ObjCAutoRefCount && resultType->isObjCRetainableType()) {
2837 RV = RValue::get(EmitARCRetainAutoreleasedReturnValue(RV.getScalarVal()));
2838 }
John McCall8dda7b22012-07-07 06:41:13 +00002839 EmitReturnOfRValue(RV, resultType);
John McCall95088452017-12-14 18:21:14 +00002840 } else
Eli Friedmanf5f4d2f2012-12-13 23:37:17 +00002841 EmitBranchThroughCleanup(ReturnBlock);
Eli Friedman5b446882012-02-16 03:47:28 +00002842}
2843
Eli Friedman2495ab02012-02-25 02:48:22 +00002844void CodeGenFunction::EmitLambdaBlockInvokeBody() {
2845 const BlockDecl *BD = BlockInfo->getBlockDecl();
2846 const VarDecl *variable = BD->capture_begin()->getVariable();
2847 const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
Reid Kleckner2d3c4212017-08-04 22:38:06 +00002848 const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
2849
2850 if (CallOp->isVariadic()) {
2851 // FIXME: Making this work correctly is nasty because it requires either
2852 // cloning the body of the call operator or making the call operator
2853 // forward.
2854 CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function");
2855 return;
2856 }
Eli Friedman2495ab02012-02-25 02:48:22 +00002857
2858 // Start building arguments for forwarding call
2859 CallArgList CallArgs;
2860
2861 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
Akira Hatanaka8e57b072018-10-01 21:51:28 +00002862 Address ThisPtr = GetAddrOfBlockDecl(variable);
John McCall7f416cc2015-09-08 08:05:57 +00002863 CallArgs.add(RValue::get(ThisPtr.getPointer()), ThisType);
Eli Friedman2495ab02012-02-25 02:48:22 +00002864
2865 // Add the rest of the parameters.
David Majnemer59f77922016-06-24 04:05:48 +00002866 for (auto param : BD->parameters())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002867 EmitDelegateCallArg(CallArgs, param, param->getBeginLoc());
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00002868
Justin Bogner1cd11f12015-05-20 15:53:59 +00002869 assert(!Lambda->isGenericLambda() &&
Faisal Vali571df122013-09-29 08:45:24 +00002870 "generic lambda interconversion to block not implemented");
Reid Kleckner2d3c4212017-08-04 22:38:06 +00002871 EmitForwardingCallToLambda(CallOp, CallArgs);
Eli Friedman2495ab02012-02-25 02:48:22 +00002872}
2873
2874void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
2875 const CXXRecordDecl *Lambda = MD->getParent();
2876
2877 // Start building arguments for forwarding call
2878 CallArgList CallArgs;
2879
2880 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2881 llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
2882 CallArgs.add(RValue::get(ThisPtr), ThisType);
2883
2884 // Add the rest of the parameters.
David Majnemer59f77922016-06-24 04:05:48 +00002885 for (auto Param : MD->parameters())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002886 EmitDelegateCallArg(CallArgs, Param, Param->getBeginLoc());
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002887
Faisal Vali571df122013-09-29 08:45:24 +00002888 const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
2889 // For a generic lambda, find the corresponding call operator specialization
2890 // to which the call to the static-invoker shall be forwarded.
2891 if (Lambda->isGenericLambda()) {
2892 assert(MD->isFunctionTemplateSpecialization());
2893 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
2894 FunctionTemplateDecl *CallOpTemplate = CallOp->getDescribedFunctionTemplate();
Craig Topper8a13c412014-05-21 05:09:00 +00002895 void *InsertPos = nullptr;
Justin Bogner1cd11f12015-05-20 15:53:59 +00002896 FunctionDecl *CorrespondingCallOpSpecialization =
Craig Topper7e0daca2014-06-26 04:58:53 +00002897 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
Faisal Vali571df122013-09-29 08:45:24 +00002898 assert(CorrespondingCallOpSpecialization);
2899 CallOp = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
2900 }
2901 EmitForwardingCallToLambda(CallOp, CallArgs);
Eli Friedman2495ab02012-02-25 02:48:22 +00002902}
2903
Reid Kleckner2d3c4212017-08-04 22:38:06 +00002904void CodeGenFunction::EmitLambdaStaticInvokeBody(const CXXMethodDecl *MD) {
Douglas Gregor355efbb2012-02-17 03:02:34 +00002905 if (MD->isVariadic()) {
Eli Friedman5b446882012-02-16 03:47:28 +00002906 // FIXME: Making this work correctly is nasty because it requires either
2907 // cloning the body of the call operator or making the call operator forward.
2908 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
Eli Friedman2495ab02012-02-25 02:48:22 +00002909 return;
Eli Friedman5b446882012-02-16 03:47:28 +00002910 }
2911
Douglas Gregor355efbb2012-02-17 03:02:34 +00002912 EmitLambdaDelegatingInvokeBody(MD);
Eli Friedman5a6d5072012-02-16 01:37:33 +00002913}