blob: 56bd25025f53f18a79cc4193366117ea7ce498d0 [file] [log] [blame]
Hans Wennborgdcfba332015-10-06 23:40:43 +00001//===--- CGClass.cpp - Emit LLVM Code for C++ classes -----------*- C++ -*-===//
Anders Carlsson9a57c5a2009-09-12 04:27:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with C++ code generation of classes
11//
12//===----------------------------------------------------------------------===//
13
Eli Friedman2495ab02012-02-25 02:48:22 +000014#include "CGBlocks.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000015#include "CGCXXABI.h"
Devang Pateld76c1db2010-08-11 21:04:37 +000016#include "CGDebugInfo.h"
Lang Hamesbf122742013-02-17 07:22:09 +000017#include "CGRecordLayout.h"
Anders Carlsson9a57c5a2009-09-12 04:27:24 +000018#include "CodeGenFunction.h"
Anders Carlssonc6d171e2009-10-06 22:43:30 +000019#include "clang/AST/CXXInheritance.h"
Faisal Vali571df122013-09-29 08:45:24 +000020#include "clang/AST/DeclTemplate.h"
John McCall769250e2010-09-17 02:31:44 +000021#include "clang/AST/EvaluatedExprVisitor.h"
Anders Carlsson9a57c5a2009-09-12 04:27:24 +000022#include "clang/AST/RecordLayout.h"
John McCallb81884d2010-02-19 09:25:03 +000023#include "clang/AST/StmtCXX.h"
Lang Hamesbf122742013-02-17 07:22:09 +000024#include "clang/Basic/TargetBuiltins.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000025#include "clang/CodeGen/CGFunctionInfo.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000026#include "clang/Frontend/CodeGenOptions.h"
Peter Collingbournea4ccff32015-02-20 20:30:56 +000027#include "llvm/IR/Intrinsics.h"
Piotr Padlewski4b1ac722015-09-15 21:46:55 +000028#include "llvm/IR/Metadata.h"
Peter Collingbournedc134532016-01-16 00:31:22 +000029#include "llvm/Transforms/Utils/SanitizerStats.h"
Anders Carlssonc6d171e2009-10-06 22:43:30 +000030
Anders Carlsson9a57c5a2009-09-12 04:27:24 +000031using namespace clang;
32using namespace CodeGen;
33
John McCall7f416cc2015-09-08 08:05:57 +000034/// Return the best known alignment for an unknown pointer to a
35/// particular class.
36CharUnits CodeGenModule::getClassPointerAlignment(const CXXRecordDecl *RD) {
37 if (!RD->isCompleteDefinition())
38 return CharUnits::One(); // Hopefully won't be used anywhere.
39
40 auto &layout = getContext().getASTRecordLayout(RD);
41
42 // If the class is final, then we know that the pointer points to an
43 // object of that type and can use the full alignment.
44 if (RD->hasAttr<FinalAttr>()) {
45 return layout.getAlignment();
46
47 // Otherwise, we have to assume it could be a subclass.
48 } else {
49 return layout.getNonVirtualAlignment();
50 }
51}
52
53/// Return the best known alignment for a pointer to a virtual base,
54/// given the alignment of a pointer to the derived class.
55CharUnits CodeGenModule::getVBaseAlignment(CharUnits actualDerivedAlign,
56 const CXXRecordDecl *derivedClass,
57 const CXXRecordDecl *vbaseClass) {
58 // The basic idea here is that an underaligned derived pointer might
59 // indicate an underaligned base pointer.
60
61 assert(vbaseClass->isCompleteDefinition());
62 auto &baseLayout = getContext().getASTRecordLayout(vbaseClass);
63 CharUnits expectedVBaseAlign = baseLayout.getNonVirtualAlignment();
64
65 return getDynamicOffsetAlignment(actualDerivedAlign, derivedClass,
66 expectedVBaseAlign);
67}
68
69CharUnits
70CodeGenModule::getDynamicOffsetAlignment(CharUnits actualBaseAlign,
71 const CXXRecordDecl *baseDecl,
72 CharUnits expectedTargetAlign) {
73 // If the base is an incomplete type (which is, alas, possible with
74 // member pointers), be pessimistic.
75 if (!baseDecl->isCompleteDefinition())
76 return std::min(actualBaseAlign, expectedTargetAlign);
77
78 auto &baseLayout = getContext().getASTRecordLayout(baseDecl);
79 CharUnits expectedBaseAlign = baseLayout.getNonVirtualAlignment();
80
81 // If the class is properly aligned, assume the target offset is, too.
82 //
83 // This actually isn't necessarily the right thing to do --- if the
84 // class is a complete object, but it's only properly aligned for a
85 // base subobject, then the alignments of things relative to it are
86 // probably off as well. (Note that this requires the alignment of
87 // the target to be greater than the NV alignment of the derived
88 // class.)
89 //
90 // However, our approach to this kind of under-alignment can only
91 // ever be best effort; after all, we're never going to propagate
92 // alignments through variables or parameters. Note, in particular,
93 // that constructing a polymorphic type in an address that's less
94 // than pointer-aligned will generally trap in the constructor,
95 // unless we someday add some sort of attribute to change the
96 // assumed alignment of 'this'. So our goal here is pretty much
97 // just to allow the user to explicitly say that a pointer is
Eric Christopherd160c502016-01-29 01:35:53 +000098 // under-aligned and then safely access its fields and vtables.
John McCall7f416cc2015-09-08 08:05:57 +000099 if (actualBaseAlign >= expectedBaseAlign) {
100 return expectedTargetAlign;
101 }
102
103 // Otherwise, we might be offset by an arbitrary multiple of the
104 // actual alignment. The correct adjustment is to take the min of
105 // the two alignments.
106 return std::min(actualBaseAlign, expectedTargetAlign);
107}
108
109Address CodeGenFunction::LoadCXXThisAddress() {
110 assert(CurFuncDecl && "loading 'this' without a func declaration?");
111 assert(isa<CXXMethodDecl>(CurFuncDecl));
112
113 // Lazily compute CXXThisAlignment.
114 if (CXXThisAlignment.isZero()) {
115 // Just use the best known alignment for the parent.
116 // TODO: if we're currently emitting a complete-object ctor/dtor,
117 // we can always use the complete-object alignment.
118 auto RD = cast<CXXMethodDecl>(CurFuncDecl)->getParent();
119 CXXThisAlignment = CGM.getClassPointerAlignment(RD);
120 }
121
122 return Address(LoadCXXThis(), CXXThisAlignment);
123}
124
125/// Emit the address of a field using a member data pointer.
126///
127/// \param E Only used for emergency diagnostics
128Address
129CodeGenFunction::EmitCXXMemberDataPointerAddress(const Expr *E, Address base,
130 llvm::Value *memberPtr,
131 const MemberPointerType *memberPtrType,
Ivan A. Kosarev229a6d82017-10-13 16:38:32 +0000132 LValueBaseInfo *BaseInfo,
133 TBAAAccessInfo *TBAAInfo) {
John McCall7f416cc2015-09-08 08:05:57 +0000134 // Ask the ABI to compute the actual address.
135 llvm::Value *ptr =
136 CGM.getCXXABI().EmitMemberDataPointerAddress(*this, E, base,
137 memberPtr, memberPtrType);
138
139 QualType memberType = memberPtrType->getPointeeType();
Ivan A. 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 =
John McCallcf142162010-08-07 06:22:56 +0000305 ConvertType((PathEnd[-1])->getType())->getPointerTo();
John McCall13a39c62012-08-01 05:04:58 +0000306
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000307 QualType DerivedTy = getContext().getRecordType(Derived);
John McCall7f416cc2015-09-08 08:05:57 +0000308 CharUnits DerivedAlign = CGM.getClassPointerAlignment(Derived);
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000309
John McCall13a39c62012-08-01 05:04:58 +0000310 // If the static offset is zero and we don't have a virtual step,
311 // just do a bitcast; null checks are unnecessary.
Ken Dycka1a4ae32011-03-22 00:53:26 +0000312 if (NonVirtualOffset.isZero() && !VBase) {
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000313 if (sanitizePerformTypeCheck()) {
Vedant Kumar18348ea2017-02-17 23:22:55 +0000314 SanitizerSet SkippedChecks;
315 SkippedChecks.set(SanitizerKind::Null, !NullCheckValue);
John McCall7f416cc2015-09-08 08:05:57 +0000316 EmitTypeCheck(TCK_Upcast, Loc, Value.getPointer(),
Vedant Kumar18348ea2017-02-17 23:22:55 +0000317 DerivedTy, DerivedAlign, SkippedChecks);
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000318 }
Anders Carlssond829a022010-04-24 21:06:20 +0000319 return Builder.CreateBitCast(Value, BasePtrTy);
Craig Topper8a13c412014-05-21 05:09:00 +0000320 }
John McCall13a39c62012-08-01 05:04:58 +0000321
Craig Topper8a13c412014-05-21 05:09:00 +0000322 llvm::BasicBlock *origBB = nullptr;
323 llvm::BasicBlock *endBB = nullptr;
324
John McCall13a39c62012-08-01 05:04:58 +0000325 // Skip over the offset (and the vtable load) if we're supposed to
326 // null-check the pointer.
Anders Carlssond829a022010-04-24 21:06:20 +0000327 if (NullCheckValue) {
John McCall13a39c62012-08-01 05:04:58 +0000328 origBB = Builder.GetInsertBlock();
329 llvm::BasicBlock *notNullBB = createBasicBlock("cast.notnull");
330 endBB = createBasicBlock("cast.end");
Justin Bogner1cd11f12015-05-20 15:53:59 +0000331
John McCall7f416cc2015-09-08 08:05:57 +0000332 llvm::Value *isNull = Builder.CreateIsNull(Value.getPointer());
John McCall13a39c62012-08-01 05:04:58 +0000333 Builder.CreateCondBr(isNull, endBB, notNullBB);
334 EmitBlock(notNullBB);
Anders Carlssond829a022010-04-24 21:06:20 +0000335 }
336
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000337 if (sanitizePerformTypeCheck()) {
Vedant Kumar18348ea2017-02-17 23:22:55 +0000338 SanitizerSet SkippedChecks;
339 SkippedChecks.set(SanitizerKind::Null, true);
John McCall7f416cc2015-09-08 08:05:57 +0000340 EmitTypeCheck(VBase ? TCK_UpcastToVirtualBase : TCK_Upcast, Loc,
Vedant Kumar18348ea2017-02-17 23:22:55 +0000341 Value.getPointer(), DerivedTy, DerivedAlign, SkippedChecks);
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000342 }
343
John McCall13a39c62012-08-01 05:04:58 +0000344 // Compute the virtual offset.
Craig Topper8a13c412014-05-21 05:09:00 +0000345 llvm::Value *VirtualOffset = nullptr;
Anders Carlssona376b532011-01-29 03:18:56 +0000346 if (VBase) {
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000347 VirtualOffset =
348 CGM.getCXXABI().GetVirtualBaseClassOffset(*this, Value, Derived, VBase);
Anders Carlssona376b532011-01-29 03:18:56 +0000349 }
Anders Carlssond829a022010-04-24 21:06:20 +0000350
John McCall13a39c62012-08-01 05:04:58 +0000351 // Apply both offsets.
John McCall7f416cc2015-09-08 08:05:57 +0000352 Value = ApplyNonVirtualAndVirtualOffset(*this, Value, NonVirtualOffset,
353 VirtualOffset, Derived, VBase);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000354
John McCall13a39c62012-08-01 05:04:58 +0000355 // Cast to the destination type.
Anders Carlssond829a022010-04-24 21:06:20 +0000356 Value = Builder.CreateBitCast(Value, BasePtrTy);
John McCall13a39c62012-08-01 05:04:58 +0000357
358 // Build a phi if we needed a null check.
Anders Carlssond829a022010-04-24 21:06:20 +0000359 if (NullCheckValue) {
John McCall13a39c62012-08-01 05:04:58 +0000360 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
361 Builder.CreateBr(endBB);
362 EmitBlock(endBB);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000363
John McCall13a39c62012-08-01 05:04:58 +0000364 llvm::PHINode *PHI = Builder.CreatePHI(BasePtrTy, 2, "cast.result");
John McCall7f416cc2015-09-08 08:05:57 +0000365 PHI->addIncoming(Value.getPointer(), notNullBB);
John McCall13a39c62012-08-01 05:04:58 +0000366 PHI->addIncoming(llvm::Constant::getNullValue(BasePtrTy), origBB);
John McCall7f416cc2015-09-08 08:05:57 +0000367 Value = Address(PHI, Value.getAlignment());
Anders Carlssond829a022010-04-24 21:06:20 +0000368 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000369
Anders Carlssond829a022010-04-24 21:06:20 +0000370 return Value;
371}
372
John McCall7f416cc2015-09-08 08:05:57 +0000373Address
374CodeGenFunction::GetAddressOfDerivedClass(Address BaseAddr,
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000375 const CXXRecordDecl *Derived,
John McCallcf142162010-08-07 06:22:56 +0000376 CastExpr::path_const_iterator PathBegin,
377 CastExpr::path_const_iterator PathEnd,
Anders Carlsson8c793172009-11-23 17:57:54 +0000378 bool NullCheckValue) {
John McCallcf142162010-08-07 06:22:56 +0000379 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlsson8a64c1c2010-04-24 21:23:59 +0000380
Anders Carlsson8c793172009-11-23 17:57:54 +0000381 QualType DerivedTy =
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000382 getContext().getCanonicalType(getContext().getTagDeclType(Derived));
Chris Lattner2192fe52011-07-18 04:24:23 +0000383 llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
Richard Smith2c5868c2013-02-13 21:18:23 +0000384
Anders Carlsson600f7372010-01-31 01:43:37 +0000385 llvm::Value *NonVirtualOffset =
John McCallcf142162010-08-07 06:22:56 +0000386 CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000387
Anders Carlsson600f7372010-01-31 01:43:37 +0000388 if (!NonVirtualOffset) {
389 // No offset, we can just cast back.
John McCall7f416cc2015-09-08 08:05:57 +0000390 return Builder.CreateBitCast(BaseAddr, DerivedPtrTy);
Anders Carlsson600f7372010-01-31 01:43:37 +0000391 }
Craig Topper8a13c412014-05-21 05:09:00 +0000392
393 llvm::BasicBlock *CastNull = nullptr;
394 llvm::BasicBlock *CastNotNull = nullptr;
395 llvm::BasicBlock *CastEnd = nullptr;
396
Anders Carlsson8c793172009-11-23 17:57:54 +0000397 if (NullCheckValue) {
398 CastNull = createBasicBlock("cast.null");
399 CastNotNull = createBasicBlock("cast.notnull");
400 CastEnd = createBasicBlock("cast.end");
Justin Bogner1cd11f12015-05-20 15:53:59 +0000401
John McCall7f416cc2015-09-08 08:05:57 +0000402 llvm::Value *IsNull = Builder.CreateIsNull(BaseAddr.getPointer());
Anders Carlsson8c793172009-11-23 17:57:54 +0000403 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
404 EmitBlock(CastNotNull);
405 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000406
Anders Carlsson600f7372010-01-31 01:43:37 +0000407 // Apply the offset.
John McCall7f416cc2015-09-08 08:05:57 +0000408 llvm::Value *Value = Builder.CreateBitCast(BaseAddr.getPointer(), Int8PtrTy);
Sanjay Patel372c3f12018-01-19 15:14:51 +0000409 Value = Builder.CreateInBoundsGEP(Value, Builder.CreateNeg(NonVirtualOffset),
410 "sub.ptr");
Anders Carlsson600f7372010-01-31 01:43:37 +0000411
412 // Just cast.
413 Value = Builder.CreateBitCast(Value, DerivedPtrTy);
Anders Carlsson8c793172009-11-23 17:57:54 +0000414
John McCall7f416cc2015-09-08 08:05:57 +0000415 // Produce a PHI if we had a null-check.
Anders Carlsson8c793172009-11-23 17:57:54 +0000416 if (NullCheckValue) {
417 Builder.CreateBr(CastEnd);
418 EmitBlock(CastNull);
419 Builder.CreateBr(CastEnd);
420 EmitBlock(CastEnd);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000421
Jay Foad20c0f022011-03-30 11:28:58 +0000422 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
Anders Carlsson8c793172009-11-23 17:57:54 +0000423 PHI->addIncoming(Value, CastNotNull);
John McCall7f416cc2015-09-08 08:05:57 +0000424 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
Anders Carlsson8c793172009-11-23 17:57:54 +0000425 Value = PHI;
426 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000427
John McCall7f416cc2015-09-08 08:05:57 +0000428 return Address(Value, CGM.getClassPointerAlignment(Derived));
Anders Carlsson9a57c5a2009-09-12 04:27:24 +0000429}
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000430
431llvm::Value *CodeGenFunction::GetVTTParameter(GlobalDecl GD,
432 bool ForVirtualBase,
433 bool Delegating) {
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000434 if (!CGM.getCXXABI().NeedsVTTParameter(GD)) {
Anders Carlssone36a6b32010-01-02 01:01:18 +0000435 // This constructor/destructor does not need a VTT parameter.
Craig Topper8a13c412014-05-21 05:09:00 +0000436 return nullptr;
Anders Carlssone36a6b32010-01-02 01:01:18 +0000437 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000438
John McCalldec348f72013-05-03 07:33:41 +0000439 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CurCodeDecl)->getParent();
Anders Carlssone36a6b32010-01-02 01:01:18 +0000440 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
John McCall5c60a6f2010-02-18 19:59:28 +0000441
Anders Carlssone36a6b32010-01-02 01:01:18 +0000442 llvm::Value *VTT;
443
John McCall5c60a6f2010-02-18 19:59:28 +0000444 uint64_t SubVTTIndex;
445
Douglas Gregor61535002013-01-31 05:50:40 +0000446 if (Delegating) {
447 // If this is a delegating constructor call, just load the VTT.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000448 return LoadCXXVTT();
Douglas Gregor61535002013-01-31 05:50:40 +0000449 } else if (RD == Base) {
450 // If the record matches the base, this is the complete ctor/dtor
451 // variant calling the base variant in a class with virtual bases.
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000452 assert(!CGM.getCXXABI().NeedsVTTParameter(CurGD) &&
John McCall5c60a6f2010-02-18 19:59:28 +0000453 "doing no-op VTT offset in base dtor/ctor?");
Anders Carlsson4d205ba2010-05-02 23:33:10 +0000454 assert(!ForVirtualBase && "Can't have same class as virtual base!");
John McCall5c60a6f2010-02-18 19:59:28 +0000455 SubVTTIndex = 0;
456 } else {
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000457 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000458 CharUnits BaseOffset = ForVirtualBase ?
459 Layout.getVBaseClassOffset(Base) :
Ken Dyck16ffcac2011-03-24 01:21:01 +0000460 Layout.getBaseClassOffset(Base);
Anders Carlsson859b3062010-05-02 23:53:25 +0000461
Justin Bogner1cd11f12015-05-20 15:53:59 +0000462 SubVTTIndex =
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000463 CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
John McCall5c60a6f2010-02-18 19:59:28 +0000464 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
465 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000466
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000467 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
Anders Carlssone36a6b32010-01-02 01:01:18 +0000468 // A VTT parameter was passed to the constructor, use it.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000469 VTT = LoadCXXVTT();
470 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
Anders Carlssone36a6b32010-01-02 01:01:18 +0000471 } else {
472 // We're the complete constructor, so get the VTT by name.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000473 VTT = CGM.getVTables().GetAddrOfVTT(RD);
474 VTT = Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
Anders Carlssone36a6b32010-01-02 01:01:18 +0000475 }
476
477 return VTT;
478}
479
John McCall1d987562010-07-21 01:23:41 +0000480namespace {
John McCallf99a6312010-07-21 05:30:47 +0000481 /// Call the destructor for a direct base class.
David Blaikie7e70d682015-08-18 22:40:54 +0000482 struct CallBaseDtor final : EHScopeStack::Cleanup {
John McCallf99a6312010-07-21 05:30:47 +0000483 const CXXRecordDecl *BaseClass;
484 bool BaseIsVirtual;
485 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
486 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
John McCall1d987562010-07-21 01:23:41 +0000487
Craig Topper4f12f102014-03-12 06:41:41 +0000488 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallf99a6312010-07-21 05:30:47 +0000489 const CXXRecordDecl *DerivedClass =
490 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
491
492 const CXXDestructorDecl *D = BaseClass->getDestructor();
John McCall7f416cc2015-09-08 08:05:57 +0000493 Address Addr =
494 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThisAddress(),
John McCallf99a6312010-07-21 05:30:47 +0000495 DerivedClass, BaseClass,
496 BaseIsVirtual);
Douglas Gregor61535002013-01-31 05:50:40 +0000497 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual,
498 /*Delegating=*/false, Addr);
John McCall1d987562010-07-21 01:23:41 +0000499 }
500 };
John McCall769250e2010-09-17 02:31:44 +0000501
502 /// A visitor which checks whether an initializer uses 'this' in a
503 /// way which requires the vtable to be properly set.
Scott Douglass503fc392015-06-10 13:53:15 +0000504 struct DynamicThisUseChecker : ConstEvaluatedExprVisitor<DynamicThisUseChecker> {
505 typedef ConstEvaluatedExprVisitor<DynamicThisUseChecker> super;
John McCall769250e2010-09-17 02:31:44 +0000506
507 bool UsesThis;
508
Scott Douglass503fc392015-06-10 13:53:15 +0000509 DynamicThisUseChecker(const ASTContext &C) : super(C), UsesThis(false) {}
John McCall769250e2010-09-17 02:31:44 +0000510
511 // Black-list all explicit and implicit references to 'this'.
512 //
513 // Do we need to worry about external references to 'this' derived
514 // from arbitrary code? If so, then anything which runs arbitrary
515 // external code might potentially access the vtable.
Scott Douglass503fc392015-06-10 13:53:15 +0000516 void VisitCXXThisExpr(const CXXThisExpr *E) { UsesThis = true; }
John McCall769250e2010-09-17 02:31:44 +0000517 };
Hans Wennborgdcfba332015-10-06 23:40:43 +0000518} // end anonymous namespace
John McCall769250e2010-09-17 02:31:44 +0000519
520static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
521 DynamicThisUseChecker Checker(C);
Scott Douglass503fc392015-06-10 13:53:15 +0000522 Checker.Visit(Init);
John McCall769250e2010-09-17 02:31:44 +0000523 return Checker.UsesThis;
John McCall1d987562010-07-21 01:23:41 +0000524}
525
Justin Bogner1cd11f12015-05-20 15:53:59 +0000526static void EmitBaseInitializer(CodeGenFunction &CGF,
Anders Carlssonfb404882009-12-24 22:46:43 +0000527 const CXXRecordDecl *ClassDecl,
Alexis Hunt1d792652011-01-08 20:30:50 +0000528 CXXCtorInitializer *BaseInit,
Anders Carlssonfb404882009-12-24 22:46:43 +0000529 CXXCtorType CtorType) {
530 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
541 // The base constructor doesn't construct virtual bases.
542 if (CtorType == Ctor_Base && isBaseVirtual)
543 return;
544
John McCall769250e2010-09-17 02:31:44 +0000545 // If the initializer for the base (other than the constructor
546 // itself) accesses 'this' in any way, we need to initialize the
547 // vtables.
548 if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
549 CGF.InitializeVTablePointers(ClassDecl);
550
John McCall6ce74722010-02-16 04:15:37 +0000551 // We can pretend to be a complete class because it only matters for
552 // virtual bases, and we only do virtual bases for complete ctors.
John McCall7f416cc2015-09-08 08:05:57 +0000553 Address V =
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000554 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
John McCallf99a6312010-07-21 05:30:47 +0000555 BaseClassDecl,
556 isBaseVirtual);
John McCall8d6fc952011-08-25 20:40:09 +0000557 AggValueSlot AggSlot =
John McCall7f416cc2015-09-08 08:05:57 +0000558 AggValueSlot::forAddr(V, Qualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +0000559 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +0000560 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000561 AggValueSlot::IsNotAliased);
John McCall7a626f62010-09-15 10:14:12 +0000562
563 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000564
565 if (CGF.CGM.getLangOpts().Exceptions &&
Anders Carlsson08ce5ed2011-02-20 00:20:27 +0000566 !BaseClassDecl->hasTrivialDestructor())
John McCallcda666c2010-07-21 07:22:38 +0000567 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
568 isBaseVirtual);
Anders Carlssonfb404882009-12-24 22:46:43 +0000569}
570
Richard Smith419bd092015-04-29 19:26:57 +0000571static bool isMemcpyEquivalentSpecialMember(const CXXMethodDecl *D) {
572 auto *CD = dyn_cast<CXXConstructorDecl>(D);
573 if (!(CD && CD->isCopyOrMoveConstructor()) &&
574 !D->isCopyAssignmentOperator() && !D->isMoveAssignmentOperator())
575 return false;
576
577 // We can emit a memcpy for a trivial copy or move constructor/assignment.
578 if (D->isTrivial() && !D->getParent()->mayInsertExtraPadding())
579 return true;
580
581 // We *must* emit a memcpy for a defaulted union copy or move op.
582 if (D->getParent()->isUnion() && D->isDefaulted())
583 return true;
584
585 return false;
586}
587
Alexey Bataev152c71f2015-07-14 07:55:48 +0000588static void EmitLValueForAnyFieldInitialization(CodeGenFunction &CGF,
589 CXXCtorInitializer *MemberInit,
590 LValue &LHS) {
591 FieldDecl *Field = MemberInit->getAnyMember();
592 if (MemberInit->isIndirectMemberInitializer()) {
593 // If we are initializing an anonymous union field, drill down to the field.
594 IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember();
595 for (const auto *I : IndirectField->chain())
596 LHS = CGF.EmitLValueForFieldInitialization(LHS, cast<FieldDecl>(I));
597 } else {
598 LHS = CGF.EmitLValueForFieldInitialization(LHS, Field);
599 }
600}
601
Anders Carlssonfb404882009-12-24 22:46:43 +0000602static void EmitMemberInitializer(CodeGenFunction &CGF,
603 const CXXRecordDecl *ClassDecl,
Alexis Hunt1d792652011-01-08 20:30:50 +0000604 CXXCtorInitializer *MemberInit,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000605 const CXXConstructorDecl *Constructor,
606 FunctionArgList &Args) {
David Blaikiea81d4102015-01-18 00:12:58 +0000607 ApplyDebugLocation Loc(CGF, MemberInit->getSourceLocation());
Francois Pichetd583da02010-12-04 09:14:42 +0000608 assert(MemberInit->isAnyMemberInitializer() &&
Anders Carlssonfb404882009-12-24 22:46:43 +0000609 "Must have member initializer!");
Richard Smith938f40b2011-06-11 17:19:42 +0000610 assert(MemberInit->getInit() && "Must have initializer!");
Justin Bogner1cd11f12015-05-20 15:53:59 +0000611
Anders Carlssonfb404882009-12-24 22:46:43 +0000612 // non-static data member initializers.
Francois Pichetd583da02010-12-04 09:14:42 +0000613 FieldDecl *Field = MemberInit->getAnyMember();
Eli Friedman6ae63022012-02-14 02:15:49 +0000614 QualType FieldType = Field->getType();
Anders Carlssonfb404882009-12-24 22:46:43 +0000615
616 llvm::Value *ThisPtr = CGF.LoadCXXThis();
Eli Friedman7f1ff602012-04-16 03:54:45 +0000617 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
Akira Hatanakae5dbb642018-01-27 00:34:09 +0000618 LValue LHS;
619
620 // If a base constructor is being emitted, create an LValue that has the
621 // non-virtual alignment.
622 if (CGF.CurGD.getCtorType() == Ctor_Base)
623 LHS = CGF.MakeNaturalAlignPointeeAddrLValue(ThisPtr, RecordTy);
624 else
625 LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
Eli Friedman7f1ff602012-04-16 03:54:45 +0000626
Alexey Bataev152c71f2015-07-14 07:55:48 +0000627 EmitLValueForAnyFieldInitialization(CGF, MemberInit, LHS);
Anders Carlssonfb404882009-12-24 22:46:43 +0000628
Eli Friedman6ae63022012-02-14 02:15:49 +0000629 // Special case: if we are in a copy or move constructor, and we are copying
630 // an array of PODs or classes with trivial copy constructors, ignore the
631 // AST and perform the copy we know is equivalent.
632 // FIXME: This is hacky at best... if we had a bit more explicit information
633 // in the AST, we could generalize it more easily.
634 const ConstantArrayType *Array
635 = CGF.getContext().getAsConstantArrayType(FieldType);
Jordan Rose54533f72013-08-07 16:16:48 +0000636 if (Array && Constructor->isDefaulted() &&
Eli Friedman6ae63022012-02-14 02:15:49 +0000637 Constructor->isCopyOrMoveConstructor()) {
638 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
Richard Smith993f25a2012-11-07 23:56:21 +0000639 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
Eli Friedman6ae63022012-02-14 02:15:49 +0000640 if (BaseElementTy.isPODType(CGF.getContext()) ||
Richard Smith419bd092015-04-29 19:26:57 +0000641 (CE && isMemcpyEquivalentSpecialMember(CE->getConstructor()))) {
David Majnemer1573d732014-10-15 04:54:54 +0000642 unsigned SrcArgIndex =
643 CGF.CGM.getCXXABI().getSrcArgforCopyCtor(Constructor, Args);
Eli Friedman6ae63022012-02-14 02:15:49 +0000644 llvm::Value *SrcPtr
645 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
Eli Friedman7f1ff602012-04-16 03:54:45 +0000646 LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
647 LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000648
Eli Friedman6ae63022012-02-14 02:15:49 +0000649 // Copy the aggregate.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +0000650 CGF.EmitAggregateCopy(LHS, Src, FieldType, LHS.isVolatileQualified());
Alexey Bataev5d49b832015-07-08 07:31:02 +0000651 // Ensure that we destroy the objects if an exception is thrown later in
652 // the constructor.
653 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
654 if (CGF.needsEHCleanup(dtorKind))
655 CGF.pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
Eli Friedman6ae63022012-02-14 02:15:49 +0000656 return;
657 }
658 }
659
Richard Smith30e304e2016-12-14 00:03:17 +0000660 CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit());
Eli Friedman6ae63022012-02-14 02:15:49 +0000661}
662
John McCall7f416cc2015-09-08 08:05:57 +0000663void CodeGenFunction::EmitInitializerForField(FieldDecl *Field, LValue LHS,
Richard Smith30e304e2016-12-14 00:03:17 +0000664 Expr *Init) {
Eli Friedman6ae63022012-02-14 02:15:49 +0000665 QualType FieldType = Field->getType();
John McCall47fb9502013-03-07 21:37:08 +0000666 switch (getEvaluationKind(FieldType)) {
667 case TEK_Scalar:
John McCall31168b02011-06-15 23:02:42 +0000668 if (LHS.isSimple()) {
David Blaikie66e41972015-01-14 07:38:27 +0000669 EmitExprAsInit(Init, Field, LHS, false);
John McCall31168b02011-06-15 23:02:42 +0000670 } else {
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000671 RValue RHS = RValue::get(EmitScalarExpr(Init));
672 EmitStoreThroughLValue(RHS, LHS);
John McCall31168b02011-06-15 23:02:42 +0000673 }
John McCall47fb9502013-03-07 21:37:08 +0000674 break;
675 case TEK_Complex:
David Blaikie66e41972015-01-14 07:38:27 +0000676 EmitComplexExprIntoLValue(Init, LHS, /*isInit*/ true);
John McCall47fb9502013-03-07 21:37:08 +0000677 break;
678 case TEK_Aggregate: {
Richard Smith30e304e2016-12-14 00:03:17 +0000679 AggValueSlot Slot =
680 AggValueSlot::forLValue(LHS,
681 AggValueSlot::IsDestructed,
682 AggValueSlot::DoesNotNeedGCBarriers,
683 AggValueSlot::IsNotAliased);
684 EmitAggExpr(Init, Slot);
685 break;
Anders Carlssonfb404882009-12-24 22:46:43 +0000686 }
John McCall47fb9502013-03-07 21:37:08 +0000687 }
John McCall12cc42a2013-02-01 05:11:40 +0000688
689 // Ensure that we destroy this object if an exception is thrown
690 // later in the constructor.
691 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
692 if (needsEHCleanup(dtorKind))
693 pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
Anders Carlssonfb404882009-12-24 22:46:43 +0000694}
695
John McCallf8ff7b92010-02-23 00:48:20 +0000696/// Checks whether the given constructor is a valid subject for the
697/// complete-to-base constructor delegation optimization, i.e.
698/// emitting the complete constructor as a simple call to the base
699/// constructor.
Vedant Kumar7f809b22017-02-24 01:15:19 +0000700bool CodeGenFunction::IsConstructorDelegationValid(
701 const CXXConstructorDecl *Ctor) {
John McCallf8ff7b92010-02-23 00:48:20 +0000702
703 // Currently we disable the optimization for classes with virtual
704 // bases because (1) the addresses of parameter variables need to be
705 // consistent across all initializers but (2) the delegate function
706 // call necessarily creates a second copy of the parameter variable.
707 //
708 // The limiting example (purely theoretical AFAIK):
709 // struct A { A(int &c) { c++; } };
710 // struct B : virtual A {
711 // B(int count) : A(count) { printf("%d\n", count); }
712 // };
713 // ...although even this example could in principle be emitted as a
714 // delegation since the address of the parameter doesn't escape.
715 if (Ctor->getParent()->getNumVBases()) {
716 // TODO: white-list trivial vbase initializers. This case wouldn't
717 // be subject to the restrictions below.
718
719 // TODO: white-list cases where:
720 // - there are no non-reference parameters to the constructor
721 // - the initializers don't access any non-reference parameters
722 // - the initializers don't take the address of non-reference
723 // parameters
724 // - etc.
725 // If we ever add any of the above cases, remember that:
726 // - function-try-blocks will always blacklist this optimization
727 // - we need to perform the constructor prologue and cleanup in
728 // EmitConstructorBody.
729
730 return false;
731 }
732
733 // We also disable the optimization for variadic functions because
734 // it's impossible to "re-pass" varargs.
735 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
736 return false;
737
Alexis Hunt61bc1732011-05-01 07:04:31 +0000738 // FIXME: Decide if we can do a delegation of a delegating constructor.
739 if (Ctor->isDelegatingConstructor())
740 return false;
741
John McCallf8ff7b92010-02-23 00:48:20 +0000742 return true;
743}
744
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000745// Emit code in ctor (Prologue==true) or dtor (Prologue==false)
746// to poison the extra field paddings inserted under
747// -fsanitize-address-field-padding=1|2.
748void CodeGenFunction::EmitAsanPrologueOrEpilogue(bool Prologue) {
749 ASTContext &Context = getContext();
750 const CXXRecordDecl *ClassDecl =
751 Prologue ? cast<CXXConstructorDecl>(CurGD.getDecl())->getParent()
752 : cast<CXXDestructorDecl>(CurGD.getDecl())->getParent();
753 if (!ClassDecl->mayInsertExtraPadding()) return;
754
755 struct SizeAndOffset {
756 uint64_t Size;
757 uint64_t Offset;
758 };
759
760 unsigned PtrSize = CGM.getDataLayout().getPointerSizeInBits();
761 const ASTRecordLayout &Info = Context.getASTRecordLayout(ClassDecl);
762
763 // Populate sizes and offsets of fields.
764 SmallVector<SizeAndOffset, 16> SSV(Info.getFieldCount());
765 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i)
766 SSV[i].Offset =
767 Context.toCharUnitsFromBits(Info.getFieldOffset(i)).getQuantity();
768
769 size_t NumFields = 0;
770 for (const auto *Field : ClassDecl->fields()) {
771 const FieldDecl *D = Field;
772 std::pair<CharUnits, CharUnits> FieldInfo =
773 Context.getTypeInfoInChars(D->getType());
774 CharUnits FieldSize = FieldInfo.first;
775 assert(NumFields < SSV.size());
776 SSV[NumFields].Size = D->isBitField() ? 0 : FieldSize.getQuantity();
777 NumFields++;
778 }
779 assert(NumFields == SSV.size());
780 if (SSV.size() <= 1) return;
781
782 // We will insert calls to __asan_* run-time functions.
783 // LLVM AddressSanitizer pass may decide to inline them later.
784 llvm::Type *Args[2] = {IntPtrTy, IntPtrTy};
785 llvm::FunctionType *FTy =
786 llvm::FunctionType::get(CGM.VoidTy, Args, false);
787 llvm::Constant *F = CGM.CreateRuntimeFunction(
788 FTy, Prologue ? "__asan_poison_intra_object_redzone"
789 : "__asan_unpoison_intra_object_redzone");
790
791 llvm::Value *ThisPtr = LoadCXXThis();
792 ThisPtr = Builder.CreatePtrToInt(ThisPtr, IntPtrTy);
Kostya Serebryany64449212014-10-17 21:02:13 +0000793 uint64_t TypeSize = Info.getNonVirtualSize().getQuantity();
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000794 // For each field check if it has sufficient padding,
795 // if so (un)poison it with a call.
796 for (size_t i = 0; i < SSV.size(); i++) {
797 uint64_t AsanAlignment = 8;
798 uint64_t NextField = i == SSV.size() - 1 ? TypeSize : SSV[i + 1].Offset;
799 uint64_t PoisonSize = NextField - SSV[i].Offset - SSV[i].Size;
800 uint64_t EndOffset = SSV[i].Offset + SSV[i].Size;
801 if (PoisonSize < AsanAlignment || !SSV[i].Size ||
802 (NextField % AsanAlignment) != 0)
803 continue;
David Blaikie43f9bb72015-05-18 22:14:03 +0000804 Builder.CreateCall(
805 F, {Builder.CreateAdd(ThisPtr, Builder.getIntN(PtrSize, EndOffset)),
806 Builder.getIntN(PtrSize, PoisonSize)});
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000807 }
808}
809
John McCallb81884d2010-02-19 09:25:03 +0000810/// EmitConstructorBody - Emits the body of the current constructor.
811void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000812 EmitAsanPrologueOrEpilogue(true);
John McCallb81884d2010-02-19 09:25:03 +0000813 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
814 CXXCtorType CtorType = CurGD.getCtorType();
815
Reid Kleckner340ad862014-01-13 22:57:31 +0000816 assert((CGM.getTarget().getCXXABI().hasConstructorVariants() ||
817 CtorType == Ctor_Complete) &&
818 "can only generate complete ctor for this ABI");
819
John McCallf8ff7b92010-02-23 00:48:20 +0000820 // Before we go any further, try the complete->base constructor
821 // delegation optimization.
Timur Iskhodzhanovf32a3772012-04-20 08:05:00 +0000822 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
John McCallc8e01702013-04-16 22:48:15 +0000823 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000824 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args, Ctor->getLocEnd());
John McCallf8ff7b92010-02-23 00:48:20 +0000825 return;
826 }
827
Hans Wennborgdcfba332015-10-06 23:40:43 +0000828 const FunctionDecl *Definition = nullptr;
Richard Smith46bb5812014-08-01 01:56:39 +0000829 Stmt *Body = Ctor->getBody(Definition);
830 assert(Definition == Ctor && "emitting wrong constructor body");
John McCallb81884d2010-02-19 09:25:03 +0000831
John McCallf8ff7b92010-02-23 00:48:20 +0000832 // Enter the function-try-block before the constructor prologue if
833 // applicable.
John McCallf8ff7b92010-02-23 00:48:20 +0000834 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallf8ff7b92010-02-23 00:48:20 +0000835 if (IsTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000836 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000837
Justin Bogner66242d62015-04-23 23:06:47 +0000838 incrementProfileCounter(Body);
Justin Bogner81c22c22014-01-23 02:54:27 +0000839
Richard Smithcc1b96d2013-06-12 22:31:48 +0000840 RunCleanupsScope RunCleanups(*this);
John McCallb81884d2010-02-19 09:25:03 +0000841
John McCall88313032012-03-30 04:25:03 +0000842 // TODO: in restricted cases, we can emit the vbase initializers of
843 // a complete ctor and then delegate to the base ctor.
844
John McCallf8ff7b92010-02-23 00:48:20 +0000845 // Emit the constructor prologue, i.e. the base and member
846 // initializers.
Douglas Gregor94f9a482010-05-05 05:51:00 +0000847 EmitCtorPrologue(Ctor, CtorType, Args);
John McCallb81884d2010-02-19 09:25:03 +0000848
849 // Emit the body of the statement.
John McCallf8ff7b92010-02-23 00:48:20 +0000850 if (IsTryBody)
John McCallb81884d2010-02-19 09:25:03 +0000851 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
852 else if (Body)
853 EmitStmt(Body);
John McCallb81884d2010-02-19 09:25:03 +0000854
855 // Emit any cleanup blocks associated with the member or base
856 // initializers, which includes (along the exceptional path) the
857 // destructors for those members and bases that were fully
858 // constructed.
Richard Smithcc1b96d2013-06-12 22:31:48 +0000859 RunCleanups.ForceCleanup();
John McCallb81884d2010-02-19 09:25:03 +0000860
John McCallf8ff7b92010-02-23 00:48:20 +0000861 if (IsTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000862 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000863}
864
Lang Hamesbf122742013-02-17 07:22:09 +0000865namespace {
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000866 /// RAII object to indicate that codegen is copying the value representation
867 /// instead of the object representation. Useful when copying a struct or
868 /// class which has uninitialized members and we're only performing
869 /// lvalue-to-rvalue conversion on the object but not its members.
870 class CopyingValueRepresentation {
871 public:
872 explicit CopyingValueRepresentation(CodeGenFunction &CGF)
Alexey Samsonov035462c2014-10-30 19:33:44 +0000873 : CGF(CGF), OldSanOpts(CGF.SanOpts) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000874 CGF.SanOpts.set(SanitizerKind::Bool, false);
875 CGF.SanOpts.set(SanitizerKind::Enum, false);
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000876 }
877 ~CopyingValueRepresentation() {
878 CGF.SanOpts = OldSanOpts;
879 }
880 private:
881 CodeGenFunction &CGF;
Alexey Samsonova0416102014-11-11 01:26:14 +0000882 SanitizerSet OldSanOpts;
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000883 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000884} // end anonymous namespace
Hans Wennborgdcfba332015-10-06 23:40:43 +0000885
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000886namespace {
Lang Hamesbf122742013-02-17 07:22:09 +0000887 class FieldMemcpyizer {
888 public:
889 FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl,
890 const VarDecl *SrcRec)
Justin Bogner1cd11f12015-05-20 15:53:59 +0000891 : CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec),
Lang Hamesbf122742013-02-17 07:22:09 +0000892 RecLayout(CGF.getContext().getASTRecordLayout(ClassDecl)),
Craig Topper8a13c412014-05-21 05:09:00 +0000893 FirstField(nullptr), LastField(nullptr), FirstFieldOffset(0),
894 LastFieldOffset(0), LastAddedFieldIndex(0) {}
Lang Hamesbf122742013-02-17 07:22:09 +0000895
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000896 bool isMemcpyableField(FieldDecl *F) const {
897 // Never memcpy fields when we are adding poisoned paddings.
Alexey Samsonova0416102014-11-11 01:26:14 +0000898 if (CGF.getContext().getLangOpts().SanitizeAddressFieldPadding)
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000899 return false;
Lang Hamesbf122742013-02-17 07:22:09 +0000900 Qualifiers Qual = F->getType().getQualifiers();
901 if (Qual.hasVolatile() || Qual.hasObjCLifetime())
902 return false;
903 return true;
904 }
905
906 void addMemcpyableField(FieldDecl *F) {
Craig Topper8a13c412014-05-21 05:09:00 +0000907 if (!FirstField)
Lang Hamesbf122742013-02-17 07:22:09 +0000908 addInitialField(F);
909 else
910 addNextField(F);
911 }
912
David Majnemera586eb22014-10-10 18:57:10 +0000913 CharUnits getMemcpySize(uint64_t FirstByteOffset) const {
Lang Hamesbf122742013-02-17 07:22:09 +0000914 unsigned LastFieldSize =
915 LastField->isBitField() ?
916 LastField->getBitWidthValue(CGF.getContext()) :
Justin Bogner1cd11f12015-05-20 15:53:59 +0000917 CGF.getContext().getTypeSize(LastField->getType());
Lang Hamesbf122742013-02-17 07:22:09 +0000918 uint64_t MemcpySizeBits =
David Majnemera586eb22014-10-10 18:57:10 +0000919 LastFieldOffset + LastFieldSize - FirstByteOffset +
Lang Hamesbf122742013-02-17 07:22:09 +0000920 CGF.getContext().getCharWidth() - 1;
921 CharUnits MemcpySize =
922 CGF.getContext().toCharUnitsFromBits(MemcpySizeBits);
923 return MemcpySize;
924 }
925
926 void emitMemcpy() {
927 // Give the subclass a chance to bail out if it feels the memcpy isn't
928 // worth it (e.g. Hasn't aggregated enough data).
Craig Topper8a13c412014-05-21 05:09:00 +0000929 if (!FirstField) {
Lang Hamesbf122742013-02-17 07:22:09 +0000930 return;
931 }
932
David Majnemera586eb22014-10-10 18:57:10 +0000933 uint64_t FirstByteOffset;
Lang Hamesbf122742013-02-17 07:22:09 +0000934 if (FirstField->isBitField()) {
935 const CGRecordLayout &RL =
936 CGF.getTypes().getCGRecordLayout(FirstField->getParent());
937 const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField);
David Majnemera586eb22014-10-10 18:57:10 +0000938 // FirstFieldOffset is not appropriate for bitfields,
Ulrich Weigand73263d72015-07-13 11:52:14 +0000939 // we need to use the storage offset instead.
Ulrich Weigand03ce2a12015-07-10 17:30:00 +0000940 FirstByteOffset = CGF.getContext().toBits(BFInfo.StorageOffset);
Lang Hames1694e0d2013-02-27 04:14:49 +0000941 } else {
David Majnemera586eb22014-10-10 18:57:10 +0000942 FirstByteOffset = FirstFieldOffset;
Lang Hames1694e0d2013-02-27 04:14:49 +0000943 }
Lang Hamesbf122742013-02-17 07:22:09 +0000944
David Majnemera586eb22014-10-10 18:57:10 +0000945 CharUnits MemcpySize = getMemcpySize(FirstByteOffset);
Lang Hamesbf122742013-02-17 07:22:09 +0000946 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
John McCall7f416cc2015-09-08 08:05:57 +0000947 Address ThisPtr = CGF.LoadCXXThisAddress();
948 LValue DestLV = CGF.MakeAddrLValue(ThisPtr, RecordTy);
Lang Hamesbf122742013-02-17 07:22:09 +0000949 LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField);
950 llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec));
951 LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
952 LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField);
953
John McCall7f416cc2015-09-08 08:05:57 +0000954 emitMemcpyIR(Dest.isBitField() ? Dest.getBitFieldAddress() : Dest.getAddress(),
955 Src.isBitField() ? Src.getBitFieldAddress() : Src.getAddress(),
956 MemcpySize);
Lang Hamesbf122742013-02-17 07:22:09 +0000957 reset();
958 }
959
960 void reset() {
Craig Topper8a13c412014-05-21 05:09:00 +0000961 FirstField = nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +0000962 }
963
964 protected:
965 CodeGenFunction &CGF;
966 const CXXRecordDecl *ClassDecl;
967
968 private:
John McCall7f416cc2015-09-08 08:05:57 +0000969 void emitMemcpyIR(Address DestPtr, Address SrcPtr, CharUnits Size) {
970 llvm::PointerType *DPT = DestPtr.getType();
Lang Hamesbf122742013-02-17 07:22:09 +0000971 llvm::Type *DBP =
972 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), DPT->getAddressSpace());
973 DestPtr = CGF.Builder.CreateBitCast(DestPtr, DBP);
974
John McCall7f416cc2015-09-08 08:05:57 +0000975 llvm::PointerType *SPT = SrcPtr.getType();
Lang Hamesbf122742013-02-17 07:22:09 +0000976 llvm::Type *SBP =
977 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), SPT->getAddressSpace());
978 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, SBP);
979
John McCall7f416cc2015-09-08 08:05:57 +0000980 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity());
Lang Hamesbf122742013-02-17 07:22:09 +0000981 }
982
983 void addInitialField(FieldDecl *F) {
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000984 FirstField = F;
985 LastField = F;
986 FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex());
987 LastFieldOffset = FirstFieldOffset;
988 LastAddedFieldIndex = F->getFieldIndex();
989 }
Lang Hamesbf122742013-02-17 07:22:09 +0000990
991 void addNextField(FieldDecl *F) {
John McCall6054d5a2013-05-07 05:20:46 +0000992 // For the most part, the following invariant will hold:
993 // F->getFieldIndex() == LastAddedFieldIndex + 1
994 // The one exception is that Sema won't add a copy-initializer for an
995 // unnamed bitfield, which will show up here as a gap in the sequence.
996 assert(F->getFieldIndex() >= LastAddedFieldIndex + 1 &&
997 "Cannot aggregate fields out of order.");
Lang Hamesbf122742013-02-17 07:22:09 +0000998 LastAddedFieldIndex = F->getFieldIndex();
999
1000 // The 'first' and 'last' fields are chosen by offset, rather than field
1001 // index. This allows the code to support bitfields, as well as regular
1002 // fields.
1003 uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex());
1004 if (FOffset < FirstFieldOffset) {
1005 FirstField = F;
1006 FirstFieldOffset = FOffset;
1007 } else if (FOffset > LastFieldOffset) {
1008 LastField = F;
1009 LastFieldOffset = FOffset;
1010 }
1011 }
1012
1013 const VarDecl *SrcRec;
1014 const ASTRecordLayout &RecLayout;
1015 FieldDecl *FirstField;
1016 FieldDecl *LastField;
1017 uint64_t FirstFieldOffset, LastFieldOffset;
1018 unsigned LastAddedFieldIndex;
1019 };
1020
1021 class ConstructorMemcpyizer : public FieldMemcpyizer {
1022 private:
Lang Hamesbf122742013-02-17 07:22:09 +00001023 /// Get source argument for copy constructor. Returns null if not a copy
David Majnemer196ac332014-09-11 23:05:02 +00001024 /// constructor.
1025 static const VarDecl *getTrivialCopySource(CodeGenFunction &CGF,
1026 const CXXConstructorDecl *CD,
Lang Hamesbf122742013-02-17 07:22:09 +00001027 FunctionArgList &Args) {
Jordan Rose54533f72013-08-07 16:16:48 +00001028 if (CD->isCopyOrMoveConstructor() && CD->isDefaulted())
David Majnemer196ac332014-09-11 23:05:02 +00001029 return Args[CGF.CGM.getCXXABI().getSrcArgforCopyCtor(CD, Args)];
Craig Topper8a13c412014-05-21 05:09:00 +00001030 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001031 }
1032
1033 // Returns true if a CXXCtorInitializer represents a member initialization
1034 // that can be rolled into a memcpy.
1035 bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const {
1036 if (!MemcpyableCtor)
1037 return false;
1038 FieldDecl *Field = MemberInit->getMember();
Craig Topper8a13c412014-05-21 05:09:00 +00001039 assert(Field && "No field for member init.");
Lang Hamesbf122742013-02-17 07:22:09 +00001040 QualType FieldType = Field->getType();
1041 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
1042
Richard Smith419bd092015-04-29 19:26:57 +00001043 // Bail out on non-memcpyable, not-trivially-copyable members.
1044 if (!(CE && isMemcpyEquivalentSpecialMember(CE->getConstructor())) &&
Lang Hamesbf122742013-02-17 07:22:09 +00001045 !(FieldType.isTriviallyCopyableType(CGF.getContext()) ||
1046 FieldType->isReferenceType()))
1047 return false;
1048
1049 // Bail out on volatile fields.
1050 if (!isMemcpyableField(Field))
1051 return false;
1052
1053 // Otherwise we're good.
1054 return true;
1055 }
1056
1057 public:
1058 ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD,
1059 FunctionArgList &Args)
David Majnemer196ac332014-09-11 23:05:02 +00001060 : FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CGF, CD, Args)),
Lang Hamesbf122742013-02-17 07:22:09 +00001061 ConstructorDecl(CD),
Jordan Rose54533f72013-08-07 16:16:48 +00001062 MemcpyableCtor(CD->isDefaulted() &&
Lang Hamesbf122742013-02-17 07:22:09 +00001063 CD->isCopyOrMoveConstructor() &&
1064 CGF.getLangOpts().getGC() == LangOptions::NonGC),
1065 Args(Args) { }
1066
1067 void addMemberInitializer(CXXCtorInitializer *MemberInit) {
1068 if (isMemberInitMemcpyable(MemberInit)) {
1069 AggregatedInits.push_back(MemberInit);
1070 addMemcpyableField(MemberInit->getMember());
1071 } else {
1072 emitAggregatedInits();
1073 EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit,
1074 ConstructorDecl, Args);
1075 }
1076 }
1077
1078 void emitAggregatedInits() {
1079 if (AggregatedInits.size() <= 1) {
1080 // This memcpy is too small to be worthwhile. Fall back on default
1081 // codegen.
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001082 if (!AggregatedInits.empty()) {
1083 CopyingValueRepresentation CVR(CGF);
Lang Hamesbf122742013-02-17 07:22:09 +00001084 EmitMemberInitializer(CGF, ConstructorDecl->getParent(),
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001085 AggregatedInits[0], ConstructorDecl, Args);
Alexey Bataev152c71f2015-07-14 07:55:48 +00001086 AggregatedInits.clear();
Lang Hamesbf122742013-02-17 07:22:09 +00001087 }
1088 reset();
1089 return;
1090 }
1091
1092 pushEHDestructors();
1093 emitMemcpy();
1094 AggregatedInits.clear();
1095 }
1096
1097 void pushEHDestructors() {
John McCall7f416cc2015-09-08 08:05:57 +00001098 Address ThisPtr = CGF.LoadCXXThisAddress();
Lang Hamesbf122742013-02-17 07:22:09 +00001099 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
John McCall7f416cc2015-09-08 08:05:57 +00001100 LValue LHS = CGF.MakeAddrLValue(ThisPtr, RecordTy);
Lang Hamesbf122742013-02-17 07:22:09 +00001101
1102 for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
Alexey Bataev152c71f2015-07-14 07:55:48 +00001103 CXXCtorInitializer *MemberInit = AggregatedInits[i];
1104 QualType FieldType = MemberInit->getAnyMember()->getType();
Lang Hamesbf122742013-02-17 07:22:09 +00001105 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
Alexey Bataev152c71f2015-07-14 07:55:48 +00001106 if (!CGF.needsEHCleanup(dtorKind))
1107 continue;
1108 LValue FieldLHS = LHS;
1109 EmitLValueForAnyFieldInitialization(CGF, MemberInit, FieldLHS);
1110 CGF.pushEHDestroy(dtorKind, FieldLHS.getAddress(), FieldType);
Lang Hamesbf122742013-02-17 07:22:09 +00001111 }
1112 }
1113
1114 void finish() {
1115 emitAggregatedInits();
1116 }
1117
1118 private:
1119 const CXXConstructorDecl *ConstructorDecl;
1120 bool MemcpyableCtor;
1121 FunctionArgList &Args;
1122 SmallVector<CXXCtorInitializer*, 16> AggregatedInits;
1123 };
1124
1125 class AssignmentMemcpyizer : public FieldMemcpyizer {
1126 private:
Lang Hamesbf122742013-02-17 07:22:09 +00001127 // Returns the memcpyable field copied by the given statement, if one
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001128 // exists. Otherwise returns null.
1129 FieldDecl *getMemcpyableField(Stmt *S) {
Lang Hamesbf122742013-02-17 07:22:09 +00001130 if (!AssignmentsMemcpyable)
Craig Topper8a13c412014-05-21 05:09:00 +00001131 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001132 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
1133 // Recognise trivial assignments.
1134 if (BO->getOpcode() != BO_Assign)
Craig Topper8a13c412014-05-21 05:09:00 +00001135 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001136 MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS());
1137 if (!ME)
Craig Topper8a13c412014-05-21 05:09:00 +00001138 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001139 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1140 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001141 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001142 Stmt *RHS = BO->getRHS();
1143 if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS))
1144 RHS = EC->getSubExpr();
1145 if (!RHS)
Craig Topper8a13c412014-05-21 05:09:00 +00001146 return nullptr;
Warren Ristow8d17b402017-02-02 17:53:34 +00001147 if (MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS)) {
1148 if (ME2->getMemberDecl() == Field)
1149 return Field;
1150 }
1151 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001152 } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) {
1153 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl());
Richard Smith419bd092015-04-29 19:26:57 +00001154 if (!(MD && isMemcpyEquivalentSpecialMember(MD)))
Craig Topper8a13c412014-05-21 05:09:00 +00001155 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001156 MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument());
1157 if (!IOA)
Craig Topper8a13c412014-05-21 05:09:00 +00001158 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001159 FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl());
1160 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001161 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001162 MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0));
1163 if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl()))
Craig Topper8a13c412014-05-21 05:09:00 +00001164 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001165 return Field;
1166 } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1167 FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1168 if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy)
Craig Topper8a13c412014-05-21 05:09:00 +00001169 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001170 Expr *DstPtr = CE->getArg(0);
1171 if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr))
1172 DstPtr = DC->getSubExpr();
1173 UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr);
1174 if (!DUO || DUO->getOpcode() != UO_AddrOf)
Craig Topper8a13c412014-05-21 05:09:00 +00001175 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001176 MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr());
1177 if (!ME)
Craig Topper8a13c412014-05-21 05:09:00 +00001178 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001179 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1180 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001181 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001182 Expr *SrcPtr = CE->getArg(1);
1183 if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr))
1184 SrcPtr = SC->getSubExpr();
1185 UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr);
1186 if (!SUO || SUO->getOpcode() != UO_AddrOf)
Craig Topper8a13c412014-05-21 05:09:00 +00001187 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001188 MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr());
1189 if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl()))
Craig Topper8a13c412014-05-21 05:09:00 +00001190 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001191 return Field;
1192 }
1193
Craig Topper8a13c412014-05-21 05:09:00 +00001194 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001195 }
1196
1197 bool AssignmentsMemcpyable;
1198 SmallVector<Stmt*, 16> AggregatedStmts;
1199
1200 public:
Lang Hamesbf122742013-02-17 07:22:09 +00001201 AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD,
1202 FunctionArgList &Args)
1203 : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]),
1204 AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) {
1205 assert(Args.size() == 2);
1206 }
1207
1208 void emitAssignment(Stmt *S) {
1209 FieldDecl *F = getMemcpyableField(S);
1210 if (F) {
1211 addMemcpyableField(F);
1212 AggregatedStmts.push_back(S);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001213 } else {
Lang Hamesbf122742013-02-17 07:22:09 +00001214 emitAggregatedStmts();
1215 CGF.EmitStmt(S);
1216 }
1217 }
1218
1219 void emitAggregatedStmts() {
1220 if (AggregatedStmts.size() <= 1) {
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001221 if (!AggregatedStmts.empty()) {
1222 CopyingValueRepresentation CVR(CGF);
1223 CGF.EmitStmt(AggregatedStmts[0]);
1224 }
Lang Hamesbf122742013-02-17 07:22:09 +00001225 reset();
1226 }
1227
1228 emitMemcpy();
1229 AggregatedStmts.clear();
1230 }
1231
1232 void finish() {
1233 emitAggregatedStmts();
1234 }
1235 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00001236} // end anonymous namespace
Lang Hamesbf122742013-02-17 07:22:09 +00001237
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001238static bool isInitializerOfDynamicClass(const CXXCtorInitializer *BaseInit) {
1239 const Type *BaseType = BaseInit->getBaseClass();
1240 const auto *BaseClassDecl =
1241 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
1242 return BaseClassDecl->isDynamicClass();
1243}
1244
Anders Carlssonfb404882009-12-24 22:46:43 +00001245/// EmitCtorPrologue - This routine generates necessary code to initialize
1246/// base classes and non-static data members belonging to this constructor.
Anders Carlssonfb404882009-12-24 22:46:43 +00001247void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001248 CXXCtorType CtorType,
1249 FunctionArgList &Args) {
Alexis Hunt61bc1732011-05-01 07:04:31 +00001250 if (CD->isDelegatingConstructor())
1251 return EmitDelegatingCXXConstructorCall(CD, Args);
1252
Anders Carlssonfb404882009-12-24 22:46:43 +00001253 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlsson5dc86332010-02-02 19:58:43 +00001254
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001255 CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
1256 E = CD->init_end();
1257
Craig Topper8a13c412014-05-21 05:09:00 +00001258 llvm::BasicBlock *BaseCtorContinueBB = nullptr;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001259 if (ClassDecl->getNumVBases() &&
1260 !CGM.getTarget().getCXXABI().hasConstructorVariants()) {
1261 // The ABIs that don't have constructor variants need to put a branch
1262 // before the virtual base initialization code.
Reid Kleckner7810af02013-06-19 15:20:38 +00001263 BaseCtorContinueBB =
1264 CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this, ClassDecl);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001265 assert(BaseCtorContinueBB);
1266 }
1267
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001268 llvm::Value *const OldThis = CXXThisValue;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001269 // Virtual base initializers first.
1270 for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001271 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1272 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1273 isInitializerOfDynamicClass(*B))
1274 CXXThisValue = Builder.CreateInvariantGroupBarrier(LoadCXXThis());
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001275 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
1276 }
1277
1278 if (BaseCtorContinueBB) {
1279 // Complete object handler should continue to the remaining initializers.
1280 Builder.CreateBr(BaseCtorContinueBB);
1281 EmitBlock(BaseCtorContinueBB);
1282 }
1283
1284 // Then, non-virtual base initializers.
1285 for (; B != E && (*B)->isBaseInitializer(); B++) {
1286 assert(!(*B)->isBaseVirtual());
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001287
1288 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1289 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1290 isInitializerOfDynamicClass(*B))
1291 CXXThisValue = Builder.CreateInvariantGroupBarrier(LoadCXXThis());
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001292 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
Anders Carlssonfb404882009-12-24 22:46:43 +00001293 }
1294
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001295 CXXThisValue = OldThis;
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001296
Anders Carlssond5895932010-03-28 21:07:49 +00001297 InitializeVTablePointers(ClassDecl);
Anders Carlsson5dc86332010-02-02 19:58:43 +00001298
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001299 // And finally, initialize class members.
John McCall7f416cc2015-09-08 08:05:57 +00001300 FieldConstructionScope FCS(*this, LoadCXXThisAddress());
Lang Hamesbf122742013-02-17 07:22:09 +00001301 ConstructorMemcpyizer CM(*this, CD, Args);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001302 for (; B != E; B++) {
1303 CXXCtorInitializer *Member = (*B);
1304 assert(!Member->isBaseInitializer());
1305 assert(Member->isAnyMemberInitializer() &&
1306 "Delegating initializer on non-delegating constructor");
1307 CM.addMemberInitializer(Member);
1308 }
Lang Hamesbf122742013-02-17 07:22:09 +00001309 CM.finish();
Anders Carlssonfb404882009-12-24 22:46:43 +00001310}
1311
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001312static bool
1313FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
1314
1315static bool
Justin Bogner1cd11f12015-05-20 15:53:59 +00001316HasTrivialDestructorBody(ASTContext &Context,
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001317 const CXXRecordDecl *BaseClassDecl,
1318 const CXXRecordDecl *MostDerivedClassDecl)
1319{
1320 // If the destructor is trivial we don't have to check anything else.
1321 if (BaseClassDecl->hasTrivialDestructor())
1322 return true;
1323
1324 if (!BaseClassDecl->getDestructor()->hasTrivialBody())
1325 return false;
1326
1327 // Check fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001328 for (const auto *Field : BaseClassDecl->fields())
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001329 if (!FieldHasTrivialDestructorBody(Context, Field))
1330 return false;
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001331
1332 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001333 for (const auto &I : BaseClassDecl->bases()) {
1334 if (I.isVirtual())
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001335 continue;
1336
1337 const CXXRecordDecl *NonVirtualBase =
Aaron Ballman574705e2014-03-13 15:41:46 +00001338 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001339 if (!HasTrivialDestructorBody(Context, NonVirtualBase,
1340 MostDerivedClassDecl))
1341 return false;
1342 }
1343
1344 if (BaseClassDecl == MostDerivedClassDecl) {
1345 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00001346 for (const auto &I : BaseClassDecl->vbases()) {
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001347 const CXXRecordDecl *VirtualBase =
Aaron Ballman445a9392014-03-13 16:15:17 +00001348 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001349 if (!HasTrivialDestructorBody(Context, VirtualBase,
1350 MostDerivedClassDecl))
Justin Bogner1cd11f12015-05-20 15:53:59 +00001351 return false;
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001352 }
1353 }
1354
1355 return true;
1356}
1357
1358static bool
1359FieldHasTrivialDestructorBody(ASTContext &Context,
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001360 const FieldDecl *Field)
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001361{
1362 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
1363
1364 const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
1365 if (!RT)
1366 return true;
Justin Bogner1cd11f12015-05-20 15:53:59 +00001367
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001368 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Davide Italiano982bbf42015-06-26 00:18:35 +00001369
1370 // The destructor for an implicit anonymous union member is never invoked.
1371 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
1372 return false;
1373
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001374 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
1375}
1376
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001377/// CanSkipVTablePointerInitialization - Check whether we need to initialize
1378/// any vtable pointers before calling this destructor.
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001379static bool CanSkipVTablePointerInitialization(CodeGenFunction &CGF,
Anders Carlssond6f15182011-05-16 04:08:36 +00001380 const CXXDestructorDecl *Dtor) {
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001381 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1382 if (!ClassDecl->isDynamicClass())
1383 return true;
1384
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001385 if (!Dtor->hasTrivialBody())
1386 return false;
1387
1388 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001389 for (const auto *Field : ClassDecl->fields())
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001390 if (!FieldHasTrivialDestructorBody(CGF.getContext(), Field))
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001391 return false;
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001392
1393 return true;
1394}
1395
John McCallb81884d2010-02-19 09:25:03 +00001396/// EmitDestructorBody - Emits the body of the current destructor.
1397void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
1398 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
1399 CXXDtorType DtorType = CurGD.getDtorType();
1400
Richard Smithdf054d32017-02-25 23:53:05 +00001401 // For an abstract class, non-base destructors are never used (and can't
1402 // be emitted in general, because vbase dtors may not have been validated
1403 // by Sema), but the Itanium ABI doesn't make them optional and Clang may
1404 // in fact emit references to them from other compilations, so emit them
1405 // as functions containing a trap instruction.
1406 if (DtorType != Dtor_Base && Dtor->getParent()->isAbstract()) {
1407 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
1408 TrapCall->setDoesNotReturn();
1409 TrapCall->setDoesNotThrow();
1410 Builder.CreateUnreachable();
1411 Builder.ClearInsertionPoint();
1412 return;
1413 }
1414
Justin Bognerfb298222015-05-20 16:16:23 +00001415 Stmt *Body = Dtor->getBody();
1416 if (Body)
1417 incrementProfileCounter(Body);
1418
John McCallf99a6312010-07-21 05:30:47 +00001419 // The call to operator delete in a deleting destructor happens
1420 // outside of the function-try-block, which means it's always
1421 // possible to delegate the destructor body to the complete
1422 // destructor. Do so.
1423 if (DtorType == Dtor_Deleting) {
Richard Smith5b349582017-10-13 01:55:36 +00001424 RunCleanupsScope DtorEpilogue(*this);
John McCallf99a6312010-07-21 05:30:47 +00001425 EnterDtorCleanups(Dtor, Dtor_Deleting);
Richard Smith5b349582017-10-13 01:55:36 +00001426 if (HaveInsertPoint())
1427 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
1428 /*Delegating=*/false, LoadCXXThisAddress());
John McCallf99a6312010-07-21 05:30:47 +00001429 return;
1430 }
1431
John McCallb81884d2010-02-19 09:25:03 +00001432 // If the body is a function-try-block, enter the try before
John McCallf99a6312010-07-21 05:30:47 +00001433 // anything else.
1434 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallb81884d2010-02-19 09:25:03 +00001435 if (isTryBody)
John McCallb609d3f2010-07-07 06:56:46 +00001436 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00001437 EmitAsanPrologueOrEpilogue(false);
John McCallb81884d2010-02-19 09:25:03 +00001438
John McCallf99a6312010-07-21 05:30:47 +00001439 // Enter the epilogue cleanups.
1440 RunCleanupsScope DtorEpilogue(*this);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001441
John McCallb81884d2010-02-19 09:25:03 +00001442 // If this is the complete variant, just invoke the base variant;
1443 // the epilogue will destruct the virtual bases. But we can't do
1444 // this optimization if the body is a function-try-block, because
Justin Bogner1cd11f12015-05-20 15:53:59 +00001445 // we'd introduce *two* handler blocks. In the Microsoft ABI, we
Reid Klecknere7de47e2013-07-22 13:51:44 +00001446 // always delegate because we might not have a definition in this TU.
John McCallf99a6312010-07-21 05:30:47 +00001447 switch (DtorType) {
Saleem Abdulrasool8de4e872017-02-02 05:45:43 +00001448 case Dtor_Comdat: llvm_unreachable("not expecting a COMDAT");
John McCallf99a6312010-07-21 05:30:47 +00001449 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
1450
1451 case Dtor_Complete:
Reid Klecknere7de47e2013-07-22 13:51:44 +00001452 assert((Body || getTarget().getCXXABI().isMicrosoft()) &&
1453 "can't emit a dtor without a body for non-Microsoft ABIs");
1454
John McCallf99a6312010-07-21 05:30:47 +00001455 // Enter the cleanup scopes for virtual bases.
1456 EnterDtorCleanups(Dtor, Dtor_Complete);
1457
Reid Klecknere7de47e2013-07-22 13:51:44 +00001458 if (!isTryBody) {
John McCallf99a6312010-07-21 05:30:47 +00001459 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
John McCall7f416cc2015-09-08 08:05:57 +00001460 /*Delegating=*/false, LoadCXXThisAddress());
John McCallf99a6312010-07-21 05:30:47 +00001461 break;
1462 }
Saleem Abdulrasool8de4e872017-02-02 05:45:43 +00001463
John McCallf99a6312010-07-21 05:30:47 +00001464 // Fallthrough: act like we're in the base variant.
Saleem Abdulrasool8de4e872017-02-02 05:45:43 +00001465 LLVM_FALLTHROUGH;
Justin Bogner1cd11f12015-05-20 15:53:59 +00001466
John McCallf99a6312010-07-21 05:30:47 +00001467 case Dtor_Base:
Reid Klecknere7de47e2013-07-22 13:51:44 +00001468 assert(Body);
1469
John McCallf99a6312010-07-21 05:30:47 +00001470 // Enter the cleanup scopes for fields and non-virtual bases.
1471 EnterDtorCleanups(Dtor, Dtor_Base);
1472
1473 // Initialize the vtable pointers before entering the body.
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001474 if (!CanSkipVTablePointerInitialization(*this, Dtor)) {
1475 // Insert the llvm.invariant.group.barrier intrinsic before initializing
1476 // the vptrs to cancel any previous assumptions we might have made.
1477 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1478 CGM.getCodeGenOpts().OptimizationLevel > 0)
1479 CXXThisValue = Builder.CreateInvariantGroupBarrier(LoadCXXThis());
1480 InitializeVTablePointers(Dtor->getParent());
1481 }
John McCallf99a6312010-07-21 05:30:47 +00001482
1483 if (isTryBody)
1484 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
1485 else if (Body)
1486 EmitStmt(Body);
1487 else {
1488 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
1489 // nothing to do besides what's in the epilogue
1490 }
Fariborz Jahanian0c12ed12011-02-02 23:12:46 +00001491 // -fapple-kext must inline any call to this dtor into
1492 // the caller's body.
Richard Smith9c6890a2012-11-01 22:30:59 +00001493 if (getLangOpts().AppleKext)
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00001494 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
Naomi Musgravee50cb9b2015-08-13 18:35:11 +00001495
John McCallf99a6312010-07-21 05:30:47 +00001496 break;
John McCallb81884d2010-02-19 09:25:03 +00001497 }
1498
John McCallf99a6312010-07-21 05:30:47 +00001499 // Jump out through the epilogue cleanups.
1500 DtorEpilogue.ForceCleanup();
John McCallb81884d2010-02-19 09:25:03 +00001501
1502 // Exit the try if applicable.
1503 if (isTryBody)
John McCallb609d3f2010-07-07 06:56:46 +00001504 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +00001505}
1506
Lang Hamesbf122742013-02-17 07:22:09 +00001507void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) {
1508 const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
1509 const Stmt *RootS = AssignOp->getBody();
1510 assert(isa<CompoundStmt>(RootS) &&
1511 "Body of an implicit assignment operator should be compound stmt.");
1512 const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
1513
1514 LexicalScope Scope(*this, RootCS->getSourceRange());
1515
Xinliang David Lia951e8e2016-02-09 20:02:59 +00001516 incrementProfileCounter(RootCS);
Lang Hamesbf122742013-02-17 07:22:09 +00001517 AssignmentMemcpyizer AM(*this, AssignOp, Args);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001518 for (auto *I : RootCS->body())
Justin Bogner1cd11f12015-05-20 15:53:59 +00001519 AM.emitAssignment(I);
Lang Hamesbf122742013-02-17 07:22:09 +00001520 AM.finish();
1521}
1522
John McCallf99a6312010-07-21 05:30:47 +00001523namespace {
Richard Smith5b349582017-10-13 01:55:36 +00001524 llvm::Value *LoadThisForDtorDelete(CodeGenFunction &CGF,
1525 const CXXDestructorDecl *DD) {
1526 if (Expr *ThisArg = DD->getOperatorDeleteThisArg())
Haojian Wu5b5c81f2017-10-13 15:37:53 +00001527 return CGF.EmitScalarExpr(ThisArg);
Richard Smith5b349582017-10-13 01:55:36 +00001528 return CGF.LoadCXXThis();
1529 }
1530
John McCallf99a6312010-07-21 05:30:47 +00001531 /// Call the operator delete associated with the current destructor.
David Blaikie7e70d682015-08-18 22:40:54 +00001532 struct CallDtorDelete final : EHScopeStack::Cleanup {
John McCallf99a6312010-07-21 05:30:47 +00001533 CallDtorDelete() {}
1534
Craig Topper4f12f102014-03-12 06:41:41 +00001535 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallf99a6312010-07-21 05:30:47 +00001536 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1537 const CXXRecordDecl *ClassDecl = Dtor->getParent();
Richard Smith5b349582017-10-13 01:55:36 +00001538 CGF.EmitDeleteCall(Dtor->getOperatorDelete(),
1539 LoadThisForDtorDelete(CGF, Dtor),
John McCallf99a6312010-07-21 05:30:47 +00001540 CGF.getContext().getTagDeclType(ClassDecl));
1541 }
1542 };
1543
Richard Smith5b349582017-10-13 01:55:36 +00001544 void EmitConditionalDtorDeleteCall(CodeGenFunction &CGF,
1545 llvm::Value *ShouldDeleteCondition,
1546 bool ReturnAfterDelete) {
1547 llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
1548 llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
1549 llvm::Value *ShouldCallDelete
1550 = CGF.Builder.CreateIsNull(ShouldDeleteCondition);
1551 CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
1552
1553 CGF.EmitBlock(callDeleteBB);
1554 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1555 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1556 CGF.EmitDeleteCall(Dtor->getOperatorDelete(),
1557 LoadThisForDtorDelete(CGF, Dtor),
1558 CGF.getContext().getTagDeclType(ClassDecl));
1559 assert(Dtor->getOperatorDelete()->isDestroyingOperatorDelete() ==
1560 ReturnAfterDelete &&
1561 "unexpected value for ReturnAfterDelete");
1562 if (ReturnAfterDelete)
1563 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
1564 else
1565 CGF.Builder.CreateBr(continueBB);
1566
1567 CGF.EmitBlock(continueBB);
1568 }
1569
David Blaikie7e70d682015-08-18 22:40:54 +00001570 struct CallDtorDeleteConditional final : EHScopeStack::Cleanup {
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001571 llvm::Value *ShouldDeleteCondition;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001572
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001573 public:
1574 CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001575 : ShouldDeleteCondition(ShouldDeleteCondition) {
Craig Topper8a13c412014-05-21 05:09:00 +00001576 assert(ShouldDeleteCondition != nullptr);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001577 }
1578
Craig Topper4f12f102014-03-12 06:41:41 +00001579 void Emit(CodeGenFunction &CGF, Flags flags) override {
Richard Smith5b349582017-10-13 01:55:36 +00001580 EmitConditionalDtorDeleteCall(CGF, ShouldDeleteCondition,
1581 /*ReturnAfterDelete*/false);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001582 }
1583 };
1584
David Blaikie7e70d682015-08-18 22:40:54 +00001585 class DestroyField final : public EHScopeStack::Cleanup {
John McCall4bd0fb12011-07-12 16:41:08 +00001586 const FieldDecl *field;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001587 CodeGenFunction::Destroyer *destroyer;
John McCall4bd0fb12011-07-12 16:41:08 +00001588 bool useEHCleanupForArray;
John McCallf99a6312010-07-21 05:30:47 +00001589
John McCall4bd0fb12011-07-12 16:41:08 +00001590 public:
1591 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
1592 bool useEHCleanupForArray)
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001593 : field(field), destroyer(destroyer),
1594 useEHCleanupForArray(useEHCleanupForArray) {}
John McCallf99a6312010-07-21 05:30:47 +00001595
Craig Topper4f12f102014-03-12 06:41:41 +00001596 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall4bd0fb12011-07-12 16:41:08 +00001597 // Find the address of the field.
John McCall7f416cc2015-09-08 08:05:57 +00001598 Address thisValue = CGF.LoadCXXThisAddress();
Eli Friedman7f1ff602012-04-16 03:54:45 +00001599 QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
1600 LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
1601 LValue LV = CGF.EmitLValueForField(ThisLV, field);
John McCall4bd0fb12011-07-12 16:41:08 +00001602 assert(LV.isSimple());
Justin Bogner1cd11f12015-05-20 15:53:59 +00001603
John McCall4bd0fb12011-07-12 16:41:08 +00001604 CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +00001605 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCallf99a6312010-07-21 05:30:47 +00001606 }
1607 };
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001608
Naomi Musgrave703835c2015-09-16 00:38:22 +00001609 static void EmitSanitizerDtorCallback(CodeGenFunction &CGF, llvm::Value *Ptr,
1610 CharUnits::QuantityType PoisonSize) {
Matt Morehouse4881a232017-09-20 22:53:08 +00001611 CodeGenFunction::SanitizerScope SanScope(&CGF);
Naomi Musgrave703835c2015-09-16 00:38:22 +00001612 // Pass in void pointer and size of region as arguments to runtime
1613 // function
1614 llvm::Value *Args[] = {CGF.Builder.CreateBitCast(Ptr, CGF.VoidPtrTy),
1615 llvm::ConstantInt::get(CGF.SizeTy, PoisonSize)};
1616
1617 llvm::Type *ArgTypes[] = {CGF.VoidPtrTy, CGF.SizeTy};
1618
1619 llvm::FunctionType *FnType =
1620 llvm::FunctionType::get(CGF.VoidTy, ArgTypes, false);
1621 llvm::Value *Fn =
1622 CGF.CGM.CreateRuntimeFunction(FnType, "__sanitizer_dtor_callback");
1623 CGF.EmitNounwindRuntimeCall(Fn, Args);
1624 }
1625
1626 class SanitizeDtorMembers final : public EHScopeStack::Cleanup {
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001627 const CXXDestructorDecl *Dtor;
1628
1629 public:
Naomi Musgrave703835c2015-09-16 00:38:22 +00001630 SanitizeDtorMembers(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001631
1632 // Generate function call for handling object poisoning.
1633 // Disables tail call elimination, to prevent the current stack frame
1634 // from disappearing from the stack trace.
1635 void Emit(CodeGenFunction &CGF, Flags flags) override {
1636 const ASTRecordLayout &Layout =
1637 CGF.getContext().getASTRecordLayout(Dtor->getParent());
1638
1639 // Nothing to poison.
1640 if (Layout.getFieldCount() == 0)
1641 return;
1642
1643 // Prevent the current stack frame from disappearing from the stack trace.
1644 CGF.CurFn->addFnAttr("disable-tail-calls", "true");
1645
1646 // Construct pointer to region to begin poisoning, and calculate poison
1647 // size, so that only members declared in this class are poisoned.
1648 ASTContext &Context = CGF.getContext();
1649 unsigned fieldIndex = 0;
1650 int startIndex = -1;
1651 // RecordDecl::field_iterator Field;
1652 for (const FieldDecl *Field : Dtor->getParent()->fields()) {
1653 // Poison field if it is trivial
1654 if (FieldHasTrivialDestructorBody(Context, Field)) {
1655 // Start sanitizing at this field
1656 if (startIndex < 0)
1657 startIndex = fieldIndex;
1658
1659 // Currently on the last field, and it must be poisoned with the
1660 // current block.
1661 if (fieldIndex == Layout.getFieldCount() - 1) {
Naomi Musgrave703835c2015-09-16 00:38:22 +00001662 PoisonMembers(CGF, startIndex, Layout.getFieldCount());
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001663 }
1664 } else if (startIndex >= 0) {
1665 // No longer within a block of memory to poison, so poison the block
Naomi Musgrave703835c2015-09-16 00:38:22 +00001666 PoisonMembers(CGF, startIndex, fieldIndex);
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001667 // Re-set the start index
1668 startIndex = -1;
1669 }
1670 fieldIndex += 1;
1671 }
1672 }
1673
1674 private:
NAKAMURA Takumif6cef72f2015-09-04 05:19:31 +00001675 /// \param layoutStartOffset index of the ASTRecordLayout field to
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001676 /// start poisoning (inclusive)
NAKAMURA Takumif6cef72f2015-09-04 05:19:31 +00001677 /// \param layoutEndOffset index of the ASTRecordLayout field to
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001678 /// end poisoning (exclusive)
Naomi Musgrave703835c2015-09-16 00:38:22 +00001679 void PoisonMembers(CodeGenFunction &CGF, unsigned layoutStartOffset,
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001680 unsigned layoutEndOffset) {
1681 ASTContext &Context = CGF.getContext();
1682 const ASTRecordLayout &Layout =
1683 Context.getASTRecordLayout(Dtor->getParent());
1684
1685 llvm::ConstantInt *OffsetSizePtr = llvm::ConstantInt::get(
1686 CGF.SizeTy,
1687 Context.toCharUnitsFromBits(Layout.getFieldOffset(layoutStartOffset))
1688 .getQuantity());
1689
1690 llvm::Value *OffsetPtr = CGF.Builder.CreateGEP(
1691 CGF.Builder.CreateBitCast(CGF.LoadCXXThis(), CGF.Int8PtrTy),
1692 OffsetSizePtr);
1693
1694 CharUnits::QuantityType PoisonSize;
1695 if (layoutEndOffset >= Layout.getFieldCount()) {
1696 PoisonSize = Layout.getNonVirtualSize().getQuantity() -
1697 Context.toCharUnitsFromBits(
1698 Layout.getFieldOffset(layoutStartOffset))
1699 .getQuantity();
1700 } else {
1701 PoisonSize = Context.toCharUnitsFromBits(
1702 Layout.getFieldOffset(layoutEndOffset) -
1703 Layout.getFieldOffset(layoutStartOffset))
1704 .getQuantity();
1705 }
1706
1707 if (PoisonSize == 0)
1708 return;
1709
Naomi Musgrave703835c2015-09-16 00:38:22 +00001710 EmitSanitizerDtorCallback(CGF, OffsetPtr, PoisonSize);
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001711 }
1712 };
Naomi Musgrave703835c2015-09-16 00:38:22 +00001713
1714 class SanitizeDtorVTable final : public EHScopeStack::Cleanup {
1715 const CXXDestructorDecl *Dtor;
1716
1717 public:
1718 SanitizeDtorVTable(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
1719
1720 // Generate function call for handling vtable pointer poisoning.
1721 void Emit(CodeGenFunction &CGF, Flags flags) override {
1722 assert(Dtor->getParent()->isDynamicClass());
NAKAMURA Takumiee82b492015-09-16 06:26:56 +00001723 (void)Dtor;
Naomi Musgrave703835c2015-09-16 00:38:22 +00001724 ASTContext &Context = CGF.getContext();
1725 // Poison vtable and vtable ptr if they exist for this class.
1726 llvm::Value *VTablePtr = CGF.LoadCXXThis();
1727
1728 CharUnits::QuantityType PoisonSize =
1729 Context.toCharUnitsFromBits(CGF.PointerWidthInBits).getQuantity();
1730 // Pass in void pointer and size of region as arguments to runtime
1731 // function
1732 EmitSanitizerDtorCallback(CGF, VTablePtr, PoisonSize);
1733 }
1734 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00001735} // end anonymous namespace
John McCallf99a6312010-07-21 05:30:47 +00001736
Hans Wennborgdeff7032013-12-18 01:39:59 +00001737/// \brief Emit all code that comes at the end of class's
Anders Carlssonfb404882009-12-24 22:46:43 +00001738/// destructor. This is to call destructors on members and base classes
1739/// in reverse order of their construction.
Richard Smith5b349582017-10-13 01:55:36 +00001740///
1741/// For a deleting destructor, this also handles the case where a destroying
1742/// operator delete completely overrides the definition.
John McCallf99a6312010-07-21 05:30:47 +00001743void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
1744 CXXDtorType DtorType) {
Hans Wennborg853ae942014-05-30 16:59:42 +00001745 assert((!DD->isTrivial() || DD->hasAttr<DLLExportAttr>()) &&
1746 "Should not emit dtor epilogue for non-exported trivial dtor!");
Anders Carlssonfb404882009-12-24 22:46:43 +00001747
John McCallf99a6312010-07-21 05:30:47 +00001748 // The deleting-destructor phase just needs to call the appropriate
1749 // operator delete that Sema picked up.
John McCall5c60a6f2010-02-18 19:59:28 +00001750 if (DtorType == Dtor_Deleting) {
Justin Bogner1cd11f12015-05-20 15:53:59 +00001751 assert(DD->getOperatorDelete() &&
Hans Wennborgdeff7032013-12-18 01:39:59 +00001752 "operator delete missing - EnterDtorCleanups");
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001753 if (CXXStructorImplicitParamValue) {
1754 // If there is an implicit param to the deleting dtor, it's a boolean
Richard Smith5b349582017-10-13 01:55:36 +00001755 // telling whether this is a deleting destructor.
1756 if (DD->getOperatorDelete()->isDestroyingOperatorDelete())
1757 EmitConditionalDtorDeleteCall(*this, CXXStructorImplicitParamValue,
1758 /*ReturnAfterDelete*/true);
1759 else
1760 EHStack.pushCleanup<CallDtorDeleteConditional>(
1761 NormalAndEHCleanup, CXXStructorImplicitParamValue);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001762 } else {
Richard Smith5b349582017-10-13 01:55:36 +00001763 if (DD->getOperatorDelete()->isDestroyingOperatorDelete()) {
1764 const CXXRecordDecl *ClassDecl = DD->getParent();
1765 EmitDeleteCall(DD->getOperatorDelete(),
1766 LoadThisForDtorDelete(*this, DD),
1767 getContext().getTagDeclType(ClassDecl));
1768 EmitBranchThroughCleanup(ReturnBlock);
1769 } else {
1770 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
1771 }
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001772 }
John McCall5c60a6f2010-02-18 19:59:28 +00001773 return;
1774 }
1775
John McCallf99a6312010-07-21 05:30:47 +00001776 const CXXRecordDecl *ClassDecl = DD->getParent();
1777
Richard Smith20104042011-09-18 12:11:43 +00001778 // Unions have no bases and do not call field destructors.
1779 if (ClassDecl->isUnion())
1780 return;
1781
John McCallf99a6312010-07-21 05:30:47 +00001782 // The complete-destructor phase just destructs all the virtual bases.
John McCall5c60a6f2010-02-18 19:59:28 +00001783 if (DtorType == Dtor_Complete) {
Naomi Musgrave703835c2015-09-16 00:38:22 +00001784 // Poison the vtable pointer such that access after the base
1785 // and member destructors are invoked is invalid.
1786 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1787 SanOpts.has(SanitizerKind::Memory) && ClassDecl->getNumVBases() &&
1788 ClassDecl->isPolymorphic())
1789 EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
John McCallf99a6312010-07-21 05:30:47 +00001790
1791 // We push them in the forward order so that they'll be popped in
1792 // the reverse order.
Aaron Ballman445a9392014-03-13 16:15:17 +00001793 for (const auto &Base : ClassDecl->vbases()) {
John McCall5c60a6f2010-02-18 19:59:28 +00001794 CXXRecordDecl *BaseClassDecl
1795 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Justin Bogner1cd11f12015-05-20 15:53:59 +00001796
John McCall5c60a6f2010-02-18 19:59:28 +00001797 // Ignore trivial destructors.
1798 if (BaseClassDecl->hasTrivialDestructor())
1799 continue;
John McCallf99a6312010-07-21 05:30:47 +00001800
John McCallcda666c2010-07-21 07:22:38 +00001801 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1802 BaseClassDecl,
1803 /*BaseIsVirtual*/ true);
John McCall5c60a6f2010-02-18 19:59:28 +00001804 }
John McCallf99a6312010-07-21 05:30:47 +00001805
John McCall5c60a6f2010-02-18 19:59:28 +00001806 return;
1807 }
1808
1809 assert(DtorType == Dtor_Base);
Naomi Musgrave703835c2015-09-16 00:38:22 +00001810 // Poison the vtable pointer if it has no virtual bases, but inherits
1811 // virtual functions.
1812 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1813 SanOpts.has(SanitizerKind::Memory) && !ClassDecl->getNumVBases() &&
1814 ClassDecl->isPolymorphic())
1815 EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001816
John McCallf99a6312010-07-21 05:30:47 +00001817 // Destroy non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001818 for (const auto &Base : ClassDecl->bases()) {
John McCallf99a6312010-07-21 05:30:47 +00001819 // Ignore virtual bases.
1820 if (Base.isVirtual())
1821 continue;
Justin Bogner1cd11f12015-05-20 15:53:59 +00001822
John McCallf99a6312010-07-21 05:30:47 +00001823 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
Justin Bogner1cd11f12015-05-20 15:53:59 +00001824
John McCallf99a6312010-07-21 05:30:47 +00001825 // Ignore trivial destructors.
1826 if (BaseClassDecl->hasTrivialDestructor())
1827 continue;
John McCall5c60a6f2010-02-18 19:59:28 +00001828
John McCallcda666c2010-07-21 07:22:38 +00001829 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1830 BaseClassDecl,
1831 /*BaseIsVirtual*/ false);
John McCallf99a6312010-07-21 05:30:47 +00001832 }
1833
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001834 // Poison fields such that access after their destructors are
1835 // invoked, and before the base class destructor runs, is invalid.
1836 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1837 SanOpts.has(SanitizerKind::Memory))
Naomi Musgrave703835c2015-09-16 00:38:22 +00001838 EHStack.pushCleanup<SanitizeDtorMembers>(NormalAndEHCleanup, DD);
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001839
John McCallf99a6312010-07-21 05:30:47 +00001840 // Destroy direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001841 for (const auto *Field : ClassDecl->fields()) {
1842 QualType type = Field->getType();
John McCall4bd0fb12011-07-12 16:41:08 +00001843 QualType::DestructionKind dtorKind = type.isDestructedType();
1844 if (!dtorKind) continue;
John McCallf99a6312010-07-21 05:30:47 +00001845
Richard Smith921bd202012-02-26 09:11:52 +00001846 // Anonymous union members do not have their destructors called.
1847 const RecordType *RT = type->getAsUnionType();
1848 if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
1849
John McCall4bd0fb12011-07-12 16:41:08 +00001850 CleanupKind cleanupKind = getCleanupKind(dtorKind);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001851 EHStack.pushCleanup<DestroyField>(cleanupKind, Field,
John McCall4bd0fb12011-07-12 16:41:08 +00001852 getDestroyer(dtorKind),
1853 cleanupKind & EHCleanup);
Anders Carlssonfb404882009-12-24 22:46:43 +00001854 }
Anders Carlssonfb404882009-12-24 22:46:43 +00001855}
1856
John McCallf677a8e2011-07-13 06:10:41 +00001857/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1858/// constructor for each of several members of an array.
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001859///
John McCallf677a8e2011-07-13 06:10:41 +00001860/// \param ctor the constructor to call for each element
John McCallf677a8e2011-07-13 06:10:41 +00001861/// \param arrayType the type of the array to initialize
1862/// \param arrayBegin an arrayType*
1863/// \param zeroInitialize true if each element should be
1864/// zero-initialized before it is constructed
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001865void CodeGenFunction::EmitCXXAggrConstructorCall(
Alexey Bataeve7545b32016-04-29 09:39:50 +00001866 const CXXConstructorDecl *ctor, const ArrayType *arrayType,
John McCall7f416cc2015-09-08 08:05:57 +00001867 Address arrayBegin, const CXXConstructExpr *E, bool zeroInitialize) {
John McCallf677a8e2011-07-13 06:10:41 +00001868 QualType elementType;
1869 llvm::Value *numElements =
1870 emitArrayLength(arrayType, elementType, arrayBegin);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001871
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001872 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin, E, zeroInitialize);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001873}
1874
John McCallf677a8e2011-07-13 06:10:41 +00001875/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1876/// constructor for each of several members of an array.
1877///
1878/// \param ctor the constructor to call for each element
1879/// \param numElements the number of elements in the array;
John McCall6549b312011-07-13 07:37:11 +00001880/// may be zero
NAKAMURA Takumiff7a9252015-09-08 09:42:41 +00001881/// \param arrayBase a T*, where T is the type constructed by ctor
John McCallf677a8e2011-07-13 06:10:41 +00001882/// \param zeroInitialize true if each element should be
1883/// zero-initialized before it is constructed
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001884void CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1885 llvm::Value *numElements,
John McCall7f416cc2015-09-08 08:05:57 +00001886 Address arrayBase,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001887 const CXXConstructExpr *E,
1888 bool zeroInitialize) {
John McCall6549b312011-07-13 07:37:11 +00001889 // It's legal for numElements to be zero. This can happen both
1890 // dynamically, because x can be zero in 'new A[x]', and statically,
1891 // because of GCC extensions that permit zero-length arrays. There
1892 // are probably legitimate places where we could assume that this
1893 // doesn't happen, but it's not clear that it's worth it.
Craig Topper8a13c412014-05-21 05:09:00 +00001894 llvm::BranchInst *zeroCheckBranch = nullptr;
John McCall6549b312011-07-13 07:37:11 +00001895
1896 // Optimize for a constant count.
1897 llvm::ConstantInt *constantCount
1898 = dyn_cast<llvm::ConstantInt>(numElements);
1899 if (constantCount) {
1900 // Just skip out if the constant count is zero.
1901 if (constantCount->isZero()) return;
1902
1903 // Otherwise, emit the check.
1904 } else {
1905 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1906 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1907 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1908 EmitBlock(loopBB);
1909 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00001910
John McCallf677a8e2011-07-13 06:10:41 +00001911 // Find the end of the array.
John McCall7f416cc2015-09-08 08:05:57 +00001912 llvm::Value *arrayBegin = arrayBase.getPointer();
John McCallf677a8e2011-07-13 06:10:41 +00001913 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1914 "arrayctor.end");
Anders Carlsson27da15b2010-01-01 20:29:01 +00001915
John McCallf677a8e2011-07-13 06:10:41 +00001916 // Enter the loop, setting up a phi for the current location to initialize.
1917 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1918 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1919 EmitBlock(loopBB);
1920 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1921 "arrayctor.cur");
1922 cur->addIncoming(arrayBegin, entryBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001923
Anders Carlsson27da15b2010-01-01 20:29:01 +00001924 // Inside the loop body, emit the constructor call on the array element.
John McCallf677a8e2011-07-13 06:10:41 +00001925
John McCall7f416cc2015-09-08 08:05:57 +00001926 // The alignment of the base, adjusted by the size of a single element,
1927 // provides a conservative estimate of the alignment of every element.
1928 // (This assumes we never start tracking offsetted alignments.)
1929 //
1930 // Note that these are complete objects and so we don't need to
1931 // use the non-virtual size or alignment.
John McCallf677a8e2011-07-13 06:10:41 +00001932 QualType type = getContext().getTypeDeclType(ctor->getParent());
John McCall7f416cc2015-09-08 08:05:57 +00001933 CharUnits eltAlignment =
1934 arrayBase.getAlignment()
1935 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
1936 Address curAddr = Address(cur, eltAlignment);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001937
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001938 // Zero initialize the storage, if requested.
John McCallf677a8e2011-07-13 06:10:41 +00001939 if (zeroInitialize)
John McCall7f416cc2015-09-08 08:05:57 +00001940 EmitNullInitialization(curAddr, type);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001941
1942 // C++ [class.temporary]p4:
Anders Carlsson27da15b2010-01-01 20:29:01 +00001943 // There are two contexts in which temporaries are destroyed at a different
1944 // point than the end of the full-expression. The first context is when a
Justin Bogner1cd11f12015-05-20 15:53:59 +00001945 // default constructor is called to initialize an element of an array.
1946 // If the constructor has one or more default arguments, the destruction of
1947 // every temporary created in a default argument expression is sequenced
Anders Carlsson27da15b2010-01-01 20:29:01 +00001948 // before the construction of the next array element, if any.
Justin Bogner1cd11f12015-05-20 15:53:59 +00001949
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00001950 {
John McCallbd309292010-07-06 01:34:17 +00001951 RunCleanupsScope Scope(*this);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001952
John McCallf677a8e2011-07-13 06:10:41 +00001953 // Evaluate the constructor and its arguments in a regular
1954 // partial-destroy cleanup.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001955 if (getLangOpts().Exceptions &&
John McCallf677a8e2011-07-13 06:10:41 +00001956 !ctor->getParent()->hasTrivialDestructor()) {
1957 Destroyer *destroyer = destroyCXXObject;
John McCall7f416cc2015-09-08 08:05:57 +00001958 pushRegularPartialArrayCleanup(arrayBegin, cur, type, eltAlignment,
1959 *destroyer);
John McCallf677a8e2011-07-13 06:10:41 +00001960 }
1961
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001962 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/false,
John McCall7f416cc2015-09-08 08:05:57 +00001963 /*Delegating=*/false, curAddr, E);
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00001964 }
Anders Carlsson27da15b2010-01-01 20:29:01 +00001965
John McCallf677a8e2011-07-13 06:10:41 +00001966 // Go to the next element.
1967 llvm::Value *next =
1968 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
1969 "arrayctor.next");
1970 cur->addIncoming(next, Builder.GetInsertBlock());
Anders Carlsson27da15b2010-01-01 20:29:01 +00001971
John McCallf677a8e2011-07-13 06:10:41 +00001972 // Check whether that's the end of the loop.
1973 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
1974 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
1975 Builder.CreateCondBr(done, contBB, loopBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001976
John McCall6549b312011-07-13 07:37:11 +00001977 // Patch the earlier check to skip over the loop.
1978 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
1979
John McCallf677a8e2011-07-13 06:10:41 +00001980 EmitBlock(contBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001981}
1982
John McCall82fe67b2011-07-09 01:37:26 +00001983void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001984 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00001985 QualType type) {
1986 const RecordType *rtype = type->castAs<RecordType>();
1987 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
1988 const CXXDestructorDecl *dtor = record->getDestructor();
1989 assert(!dtor->isTrivial());
1990 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
Douglas Gregor61535002013-01-31 05:50:40 +00001991 /*Delegating=*/false, addr);
John McCall82fe67b2011-07-09 01:37:26 +00001992}
1993
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001994void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
1995 CXXCtorType Type,
1996 bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +00001997 bool Delegating, Address This,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001998 const CXXConstructExpr *E) {
Richard Smith5179eb72016-06-28 19:03:57 +00001999 CallArgList Args;
2000
2001 // Push the this ptr.
2002 Args.add(RValue::get(This.getPointer()), D->getThisType(getContext()));
2003
2004 // If this is a trivial constructor, emit a memcpy now before we lose
2005 // the alignment information on the argument.
2006 // FIXME: It would be better to preserve alignment information into CallArg.
2007 if (isMemcpyEquivalentSpecialMember(D)) {
2008 assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
2009
2010 const Expr *Arg = E->getArg(0);
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00002011 LValue Src = EmitLValue(Arg);
Richard Smith5179eb72016-06-28 19:03:57 +00002012 QualType DestTy = getContext().getTypeDeclType(D->getParent());
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00002013 LValue Dest = MakeAddrLValue(This, DestTy);
2014 EmitAggregateCopyCtor(Dest, Src);
Richard Smith5179eb72016-06-28 19:03:57 +00002015 return;
2016 }
2017
2018 // Add the rest of the user-supplied arguments.
2019 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
Hans Wennborg27dcc6c2017-02-01 02:21:07 +00002020 EvaluationOrder Order = E->isListInitialization()
2021 ? EvaluationOrder::ForceLeftToRight
2022 : EvaluationOrder::Default;
2023 EmitCallArgs(Args, FPT, E->arguments(), E->getConstructor(),
2024 /*ParamsToSkip*/ 0, Order);
Richard Smith5179eb72016-06-28 19:03:57 +00002025
2026 EmitCXXConstructorCall(D, Type, ForVirtualBase, Delegating, This, Args);
2027}
2028
2029static bool canEmitDelegateCallArgs(CodeGenFunction &CGF,
2030 const CXXConstructorDecl *Ctor,
2031 CXXCtorType Type, CallArgList &Args) {
2032 // We can't forward a variadic call.
2033 if (Ctor->isVariadic())
2034 return false;
2035
2036 if (CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2037 // If the parameters are callee-cleanup, it's not safe to forward.
2038 for (auto *P : Ctor->parameters())
2039 if (P->getType().isDestructedType())
2040 return false;
2041
2042 // Likewise if they're inalloca.
2043 const CGFunctionInfo &Info =
George Burgess IVd0a9e802017-02-23 22:07:35 +00002044 CGF.CGM.getTypes().arrangeCXXConstructorCall(Args, Ctor, Type, 0, 0);
Richard Smith5179eb72016-06-28 19:03:57 +00002045 if (Info.usesInAlloca())
2046 return false;
2047 }
2048
2049 // Anything else should be OK.
2050 return true;
2051}
2052
2053void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
2054 CXXCtorType Type,
2055 bool ForVirtualBase,
2056 bool Delegating,
2057 Address This,
2058 CallArgList &Args) {
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002059 const CXXRecordDecl *ClassDecl = D->getParent();
2060
Richard Smith419bd092015-04-29 19:26:57 +00002061 // C++11 [class.mfct.non-static]p2:
2062 // If a non-static member function of a class X is called for an object that
2063 // is not of type X, or of a type derived from X, the behavior is undefined.
2064 // FIXME: Provide a source location here.
John McCall7f416cc2015-09-08 08:05:57 +00002065 EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall, SourceLocation(),
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002066 This.getPointer(), getContext().getRecordType(ClassDecl));
John McCallca972cd2010-02-06 00:25:16 +00002067
Richard Smith419bd092015-04-29 19:26:57 +00002068 if (D->isTrivial() && D->isDefaultConstructor()) {
Richard Smith5179eb72016-06-28 19:03:57 +00002069 assert(Args.size() == 1 && "trivial default ctor with args");
Richard Smith419bd092015-04-29 19:26:57 +00002070 return;
2071 }
2072
2073 // If this is a trivial constructor, just emit what's needed. If this is a
2074 // union copy constructor, we must emit a memcpy, because the AST does not
2075 // model that copy.
2076 if (isMemcpyEquivalentSpecialMember(D)) {
Richard Smith5179eb72016-06-28 19:03:57 +00002077 assert(Args.size() == 2 && "unexpected argcount for trivial ctor");
John McCallca972cd2010-02-06 00:25:16 +00002078
Richard Smith5179eb72016-06-28 19:03:57 +00002079 QualType SrcTy = D->getParamDecl(0)->getType().getNonReferenceType();
2080 Address Src(Args[1].RV.getScalarVal(), getNaturalTypeAlignment(SrcTy));
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00002081 LValue SrcLVal = MakeAddrLValue(Src, SrcTy);
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002082 QualType DestTy = getContext().getTypeDeclType(ClassDecl);
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00002083 LValue DestLVal = MakeAddrLValue(This, DestTy);
2084 EmitAggregateCopyCtor(DestLVal, SrcLVal);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002085 return;
2086 }
2087
George Burgess IVd0a9e802017-02-23 22:07:35 +00002088 bool PassPrototypeArgs = true;
Richard Smith5179eb72016-06-28 19:03:57 +00002089 // Check whether we can actually emit the constructor before trying to do so.
2090 if (auto Inherited = D->getInheritedConstructor()) {
George Burgess IVd0a9e802017-02-23 22:07:35 +00002091 PassPrototypeArgs = getTypes().inheritingCtorHasParams(Inherited, Type);
2092 if (PassPrototypeArgs && !canEmitDelegateCallArgs(*this, D, Type, Args)) {
Richard Smith5179eb72016-06-28 19:03:57 +00002093 EmitInlinedInheritingCXXConstructorCall(D, Type, ForVirtualBase,
2094 Delegating, Args);
2095 return;
2096 }
2097 }
Reid Kleckner89077a12013-12-17 19:46:40 +00002098
2099 // Insert any ABI-specific implicit constructor arguments.
George Burgess IVf203dbf2017-02-22 20:28:02 +00002100 CGCXXABI::AddedStructorArgs ExtraArgs =
2101 CGM.getCXXABI().addImplicitConstructorArgs(*this, D, Type, ForVirtualBase,
2102 Delegating, Args);
Reid Kleckner89077a12013-12-17 19:46:40 +00002103
2104 // Emit the call.
John McCallb92ab1a2016-10-26 23:46:34 +00002105 llvm::Constant *CalleePtr =
2106 CGM.getAddrOfCXXStructor(D, getFromCtorType(Type));
George Burgess IVf203dbf2017-02-22 20:28:02 +00002107 const CGFunctionInfo &Info = CGM.getTypes().arrangeCXXConstructorCall(
George Burgess IVd0a9e802017-02-23 22:07:35 +00002108 Args, D, Type, ExtraArgs.Prefix, ExtraArgs.Suffix, PassPrototypeArgs);
John McCallb92ab1a2016-10-26 23:46:34 +00002109 CGCallee Callee = CGCallee::forDirect(CalleePtr, D);
2110 EmitCall(Info, Callee, ReturnValueSlot(), Args);
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002111
2112 // Generate vtable assumptions if we're constructing a complete object
2113 // with a vtable. We don't do this for base subobjects for two reasons:
2114 // first, it's incorrect for classes with virtual bases, and second, we're
2115 // about to overwrite the vptrs anyway.
2116 // We also have to make sure if we can refer to vtable:
2117 // - Otherwise we can refer to vtable if it's safe to speculatively emit.
2118 // FIXME: If vtable is used by ctor/dtor, or if vtable is external and we are
2119 // sure that definition of vtable is not hidden,
2120 // then we are always safe to refer to it.
Piotr Padlewski69dc9712015-09-28 20:30:22 +00002121 // FIXME: It looks like InstCombine is very inefficient on dealing with
2122 // assumes. Make assumption loads require -fstrict-vtable-pointers temporarily.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002123 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2124 ClassDecl->isDynamicClass() && Type != Ctor_Base &&
Piotr Padlewski69dc9712015-09-28 20:30:22 +00002125 CGM.getCXXABI().canSpeculativelyEmitVTable(ClassDecl) &&
2126 CGM.getCodeGenOpts().StrictVTablePointers)
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002127 EmitVTableAssumptionLoads(ClassDecl, This);
2128}
2129
Richard Smith5179eb72016-06-28 19:03:57 +00002130void CodeGenFunction::EmitInheritedCXXConstructorCall(
2131 const CXXConstructorDecl *D, bool ForVirtualBase, Address This,
2132 bool InheritedFromVBase, const CXXInheritedCtorInitExpr *E) {
2133 CallArgList Args;
2134 CallArg ThisArg(RValue::get(This.getPointer()), D->getThisType(getContext()),
2135 /*NeedsCopy=*/false);
2136
2137 // Forward the parameters.
2138 if (InheritedFromVBase &&
2139 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
2140 // Nothing to do; this construction is not responsible for constructing
2141 // the base class containing the inherited constructor.
2142 // FIXME: Can we just pass undef's for the remaining arguments if we don't
2143 // have constructor variants?
2144 Args.push_back(ThisArg);
2145 } else if (!CXXInheritedCtorInitExprArgs.empty()) {
2146 // The inheriting constructor was inlined; just inject its arguments.
2147 assert(CXXInheritedCtorInitExprArgs.size() >= D->getNumParams() &&
2148 "wrong number of parameters for inherited constructor call");
2149 Args = CXXInheritedCtorInitExprArgs;
2150 Args[0] = ThisArg;
2151 } else {
2152 // The inheriting constructor was not inlined. Emit delegating arguments.
2153 Args.push_back(ThisArg);
2154 const auto *OuterCtor = cast<CXXConstructorDecl>(CurCodeDecl);
2155 assert(OuterCtor->getNumParams() == D->getNumParams());
2156 assert(!OuterCtor->isVariadic() && "should have been inlined");
2157
2158 for (const auto *Param : OuterCtor->parameters()) {
2159 assert(getContext().hasSameUnqualifiedType(
2160 OuterCtor->getParamDecl(Param->getFunctionScopeIndex())->getType(),
2161 Param->getType()));
2162 EmitDelegateCallArg(Args, Param, E->getLocation());
2163
2164 // Forward __attribute__(pass_object_size).
2165 if (Param->hasAttr<PassObjectSizeAttr>()) {
2166 auto *POSParam = SizeArguments[Param];
2167 assert(POSParam && "missing pass_object_size value for forwarding");
2168 EmitDelegateCallArg(Args, POSParam, E->getLocation());
2169 }
2170 }
2171 }
2172
2173 EmitCXXConstructorCall(D, Ctor_Base, ForVirtualBase, /*Delegating*/false,
2174 This, Args);
2175}
2176
2177void CodeGenFunction::EmitInlinedInheritingCXXConstructorCall(
2178 const CXXConstructorDecl *Ctor, CXXCtorType CtorType, bool ForVirtualBase,
2179 bool Delegating, CallArgList &Args) {
Adrian Prantlb7acfc02017-02-27 21:30:05 +00002180 GlobalDecl GD(Ctor, CtorType);
2181 InlinedInheritingConstructorScope Scope(*this, GD);
2182 ApplyInlineDebugLocation DebugScope(*this, GD);
Richard Smith5179eb72016-06-28 19:03:57 +00002183
2184 // Save the arguments to be passed to the inherited constructor.
2185 CXXInheritedCtorInitExprArgs = Args;
2186
2187 FunctionArgList Params;
2188 QualType RetType = BuildFunctionArgList(CurGD, Params);
2189 FnRetTy = RetType;
2190
2191 // Insert any ABI-specific implicit constructor arguments.
2192 CGM.getCXXABI().addImplicitConstructorArgs(*this, Ctor, CtorType,
2193 ForVirtualBase, Delegating, Args);
2194
2195 // Emit a simplified prolog. We only need to emit the implicit params.
2196 assert(Args.size() >= Params.size() && "too few arguments for call");
2197 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2198 if (I < Params.size() && isa<ImplicitParamDecl>(Params[I])) {
2199 const RValue &RV = Args[I].RV;
2200 assert(!RV.isComplex() && "complex indirect params not supported");
2201 ParamValue Val = RV.isScalar()
2202 ? ParamValue::forDirect(RV.getScalarVal())
2203 : ParamValue::forIndirect(RV.getAggregateAddress());
2204 EmitParmDecl(*Params[I], Val, I + 1);
2205 }
2206 }
2207
2208 // Create a return value slot if the ABI implementation wants one.
2209 // FIXME: This is dumb, we should ask the ABI not to try to set the return
2210 // value instead.
2211 if (!RetType->isVoidType())
2212 ReturnValue = CreateIRTemp(RetType, "retval.inhctor");
2213
2214 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
2215 CXXThisValue = CXXABIThisValue;
2216
2217 // Directly emit the constructor initializers.
2218 EmitCtorPrologue(Ctor, CtorType, Params);
2219}
2220
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002221void CodeGenFunction::EmitVTableAssumptionLoad(const VPtr &Vptr, Address This) {
2222 llvm::Value *VTableGlobal =
2223 CGM.getCXXABI().getVTableAddressPoint(Vptr.Base, Vptr.VTableClass);
2224 if (!VTableGlobal)
2225 return;
2226
2227 // We can just use the base offset in the complete class.
2228 CharUnits NonVirtualOffset = Vptr.Base.getBaseOffset();
2229
2230 if (!NonVirtualOffset.isZero())
2231 This =
2232 ApplyNonVirtualAndVirtualOffset(*this, This, NonVirtualOffset, nullptr,
2233 Vptr.VTableClass, Vptr.NearestVBase);
2234
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002235 llvm::Value *VPtrValue =
2236 GetVTablePtr(This, VTableGlobal->getType(), Vptr.VTableClass);
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002237 llvm::Value *Cmp =
2238 Builder.CreateICmpEQ(VPtrValue, VTableGlobal, "cmp.vtables");
2239 Builder.CreateAssumption(Cmp);
2240}
2241
2242void CodeGenFunction::EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl,
2243 Address This) {
2244 if (CGM.getCXXABI().doStructorsInitializeVPtrs(ClassDecl))
2245 for (const VPtr &Vptr : getVTablePointers(ClassDecl))
2246 EmitVTableAssumptionLoad(Vptr, This);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002247}
2248
John McCallf8ff7b92010-02-23 00:48:20 +00002249void
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002250CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
John McCall7f416cc2015-09-08 08:05:57 +00002251 Address This, Address Src,
2252 const CXXConstructExpr *E) {
Reid Kleckner739756c2013-12-04 19:23:12 +00002253 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
Justin Bogner1cd11f12015-05-20 15:53:59 +00002254
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002255 CallArgList Args;
Justin Bogner1cd11f12015-05-20 15:53:59 +00002256
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002257 // Push the this ptr.
John McCall7f416cc2015-09-08 08:05:57 +00002258 Args.add(RValue::get(This.getPointer()), D->getThisType(getContext()));
Justin Bogner1cd11f12015-05-20 15:53:59 +00002259
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002260 // Push the src ptr.
Alp Toker9cacbab2014-01-20 20:26:09 +00002261 QualType QT = *(FPT->param_type_begin());
Chris Lattner2192fe52011-07-18 04:24:23 +00002262 llvm::Type *t = CGM.getTypes().ConvertType(QT);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002263 Src = Builder.CreateBitCast(Src, t);
John McCall7f416cc2015-09-08 08:05:57 +00002264 Args.add(RValue::get(Src.getPointer()), QT);
Reid Kleckner739756c2013-12-04 19:23:12 +00002265
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002266 // Skip over first argument (Src).
David Blaikief05779e2015-07-21 18:37:18 +00002267 EmitCallArgs(Args, FPT, drop_begin(E->arguments(), 1), E->getConstructor(),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002268 /*ParamsToSkip*/ 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002269
Richard Smith5179eb72016-06-28 19:03:57 +00002270 EmitCXXConstructorCall(D, Ctor_Complete, false, false, This, Args);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002271}
2272
2273void
John McCallf8ff7b92010-02-23 00:48:20 +00002274CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
2275 CXXCtorType CtorType,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002276 const FunctionArgList &Args,
2277 SourceLocation Loc) {
John McCallf8ff7b92010-02-23 00:48:20 +00002278 CallArgList DelegateArgs;
2279
2280 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
2281 assert(I != E && "no parameters to constructor");
2282
2283 // this
Richard Smith5179eb72016-06-28 19:03:57 +00002284 Address This = LoadCXXThisAddress();
2285 DelegateArgs.add(RValue::get(This.getPointer()), (*I)->getType());
John McCallf8ff7b92010-02-23 00:48:20 +00002286 ++I;
2287
Richard Smith5179eb72016-06-28 19:03:57 +00002288 // FIXME: The location of the VTT parameter in the parameter list is
2289 // specific to the Itanium ABI and shouldn't be hardcoded here.
2290 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
2291 assert(I != E && "cannot skip vtt parameter, already done with args");
2292 assert((*I)->getType()->isPointerType() &&
2293 "skipping parameter not of vtt type");
2294 ++I;
John McCallf8ff7b92010-02-23 00:48:20 +00002295 }
2296
2297 // Explicit arguments.
2298 for (; I != E; ++I) {
John McCall32ea9692011-03-11 20:59:21 +00002299 const VarDecl *param = *I;
Nick Lewycky2d84e842013-10-02 02:29:49 +00002300 // FIXME: per-argument source location
2301 EmitDelegateCallArg(DelegateArgs, param, Loc);
John McCallf8ff7b92010-02-23 00:48:20 +00002302 }
2303
Richard Smith5179eb72016-06-28 19:03:57 +00002304 EmitCXXConstructorCall(Ctor, CtorType, /*ForVirtualBase=*/false,
2305 /*Delegating=*/true, This, DelegateArgs);
John McCallf8ff7b92010-02-23 00:48:20 +00002306}
2307
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002308namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002309 struct CallDelegatingCtorDtor final : EHScopeStack::Cleanup {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002310 const CXXDestructorDecl *Dtor;
John McCall7f416cc2015-09-08 08:05:57 +00002311 Address Addr;
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002312 CXXDtorType Type;
2313
John McCall7f416cc2015-09-08 08:05:57 +00002314 CallDelegatingCtorDtor(const CXXDestructorDecl *D, Address Addr,
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002315 CXXDtorType Type)
2316 : Dtor(D), Addr(Addr), Type(Type) {}
2317
Craig Topper4f12f102014-03-12 06:41:41 +00002318 void Emit(CodeGenFunction &CGF, Flags flags) override {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002319 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
Douglas Gregor61535002013-01-31 05:50:40 +00002320 /*Delegating=*/true, Addr);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002321 }
2322 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00002323} // end anonymous namespace
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002324
Alexis Hunt61bc1732011-05-01 07:04:31 +00002325void
2326CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
2327 const FunctionArgList &Args) {
2328 assert(Ctor->isDelegatingConstructor());
2329
John McCall7f416cc2015-09-08 08:05:57 +00002330 Address ThisPtr = LoadCXXThisAddress();
Alexis Hunt61bc1732011-05-01 07:04:31 +00002331
John McCall31168b02011-06-15 23:02:42 +00002332 AggValueSlot AggSlot =
John McCall7f416cc2015-09-08 08:05:57 +00002333 AggValueSlot::forAddr(ThisPtr, Qualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +00002334 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00002335 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00002336 AggValueSlot::IsNotAliased);
Alexis Hunt61bc1732011-05-01 07:04:31 +00002337
2338 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
Alexis Hunt61bc1732011-05-01 07:04:31 +00002339
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002340 const CXXRecordDecl *ClassDecl = Ctor->getParent();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002341 if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002342 CXXDtorType Type =
2343 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
2344
2345 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
2346 ClassDecl->getDestructor(),
2347 ThisPtr, Type);
2348 }
2349}
Alexis Hunt61bc1732011-05-01 07:04:31 +00002350
Anders Carlsson27da15b2010-01-01 20:29:01 +00002351void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
2352 CXXDtorType Type,
Anders Carlssonf8a71f02010-05-02 23:29:11 +00002353 bool ForVirtualBase,
Douglas Gregor61535002013-01-31 05:50:40 +00002354 bool Delegating,
John McCall7f416cc2015-09-08 08:05:57 +00002355 Address This) {
Reid Kleckner6fe771a2013-12-13 00:53:54 +00002356 CGM.getCXXABI().EmitDestructorCall(*this, DD, Type, ForVirtualBase,
2357 Delegating, This);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002358}
2359
John McCall53cad2e2010-07-21 01:41:18 +00002360namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002361 struct CallLocalDtor final : EHScopeStack::Cleanup {
John McCall53cad2e2010-07-21 01:41:18 +00002362 const CXXDestructorDecl *Dtor;
John McCall7f416cc2015-09-08 08:05:57 +00002363 Address Addr;
John McCall53cad2e2010-07-21 01:41:18 +00002364
John McCall7f416cc2015-09-08 08:05:57 +00002365 CallLocalDtor(const CXXDestructorDecl *D, Address Addr)
John McCall53cad2e2010-07-21 01:41:18 +00002366 : Dtor(D), Addr(Addr) {}
2367
Craig Topper4f12f102014-03-12 06:41:41 +00002368 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall53cad2e2010-07-21 01:41:18 +00002369 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +00002370 /*ForVirtualBase=*/false,
2371 /*Delegating=*/false, Addr);
John McCall53cad2e2010-07-21 01:41:18 +00002372 }
2373 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002374} // end anonymous namespace
John McCall53cad2e2010-07-21 01:41:18 +00002375
John McCall8680f872010-07-21 06:29:51 +00002376void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
John McCall7f416cc2015-09-08 08:05:57 +00002377 Address Addr) {
John McCallcda666c2010-07-21 07:22:38 +00002378 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
John McCall8680f872010-07-21 06:29:51 +00002379}
2380
John McCall7f416cc2015-09-08 08:05:57 +00002381void CodeGenFunction::PushDestructorCleanup(QualType T, Address Addr) {
John McCallbd309292010-07-06 01:34:17 +00002382 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
2383 if (!ClassDecl) return;
2384 if (ClassDecl->hasTrivialDestructor()) return;
2385
2386 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCalla85af562011-04-28 02:15:35 +00002387 assert(D && D->isUsed() && "destructor not marked as used!");
John McCall8680f872010-07-21 06:29:51 +00002388 PushDestructorCleanup(D, Addr);
John McCallbd309292010-07-06 01:34:17 +00002389}
2390
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002391void CodeGenFunction::InitializeVTablePointer(const VPtr &Vptr) {
Anders Carlssone87fae92010-03-28 19:40:00 +00002392 // Compute the address point.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002393 llvm::Value *VTableAddressPoint =
2394 CGM.getCXXABI().getVTableAddressPointInStructor(
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002395 *this, Vptr.VTableClass, Vptr.Base, Vptr.NearestVBase);
2396
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002397 if (!VTableAddressPoint)
2398 return;
Anders Carlssone87fae92010-03-28 19:40:00 +00002399
Anders Carlsson6a0227d2010-04-20 16:22:16 +00002400 // Compute where to store the address point.
Craig Topper8a13c412014-05-21 05:09:00 +00002401 llvm::Value *VirtualOffset = nullptr;
Ken Dyckcfc332c2011-03-23 00:45:26 +00002402 CharUnits NonVirtualOffset = CharUnits::Zero();
Justin Bogner1cd11f12015-05-20 15:53:59 +00002403
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002404 if (CGM.getCXXABI().isVirtualOffsetNeededForVTableField(*this, Vptr)) {
Anders Carlsson91baecf2010-04-20 18:05:10 +00002405 // We need to use the virtual base offset offset because the virtual base
2406 // might have a different offset in the most derived class.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002407
2408 VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(
2409 *this, LoadCXXThisAddress(), Vptr.VTableClass, Vptr.NearestVBase);
2410 NonVirtualOffset = Vptr.OffsetFromNearestVBase;
Anders Carlsson91baecf2010-04-20 18:05:10 +00002411 } else {
Anders Carlssonc58fb552010-05-03 00:29:58 +00002412 // We can just use the base offset in the complete class.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002413 NonVirtualOffset = Vptr.Base.getBaseOffset();
Anders Carlsson91baecf2010-04-20 18:05:10 +00002414 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002415
Anders Carlssonc58fb552010-05-03 00:29:58 +00002416 // Apply the offsets.
John McCall7f416cc2015-09-08 08:05:57 +00002417 Address VTableField = LoadCXXThisAddress();
Justin Bogner1cd11f12015-05-20 15:53:59 +00002418
Ken Dyckcfc332c2011-03-23 00:45:26 +00002419 if (!NonVirtualOffset.isZero() || VirtualOffset)
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002420 VTableField = ApplyNonVirtualAndVirtualOffset(
2421 *this, VTableField, NonVirtualOffset, VirtualOffset, Vptr.VTableClass,
2422 Vptr.NearestVBase);
Anders Carlsson6a0227d2010-04-20 16:22:16 +00002423
Reid Kleckner8d585132014-12-03 21:00:21 +00002424 // Finally, store the address point. Use the same LLVM types as the field to
2425 // support optimization.
2426 llvm::Type *VTablePtrTy =
2427 llvm::FunctionType::get(CGM.Int32Ty, /*isVarArg=*/true)
2428 ->getPointerTo()
2429 ->getPointerTo();
2430 VTableField = Builder.CreateBitCast(VTableField, VTablePtrTy->getPointerTo());
2431 VTableAddressPoint = Builder.CreateBitCast(VTableAddressPoint, VTablePtrTy);
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002432
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002433 llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
Ivan A. Kosarev4e50e702017-11-27 09:39:29 +00002434 TBAAAccessInfo TBAAInfo = CGM.getTBAAVTablePtrAccessInfo(VTablePtrTy);
2435 CGM.DecorateInstructionWithTBAA(Store, TBAAInfo);
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002436 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2437 CGM.getCodeGenOpts().StrictVTablePointers)
2438 CGM.DecorateInstructionWithInvariantGroup(Store, Vptr.VTableClass);
Anders Carlssone87fae92010-03-28 19:40:00 +00002439}
2440
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002441CodeGenFunction::VPtrsVector
2442CodeGenFunction::getVTablePointers(const CXXRecordDecl *VTableClass) {
2443 CodeGenFunction::VPtrsVector VPtrsResult;
2444 VisitedVirtualBasesSetTy VBases;
2445 getVTablePointers(BaseSubobject(VTableClass, CharUnits::Zero()),
2446 /*NearestVBase=*/nullptr,
2447 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
2448 /*BaseIsNonVirtualPrimaryBase=*/false, VTableClass, VBases,
2449 VPtrsResult);
2450 return VPtrsResult;
2451}
2452
2453void CodeGenFunction::getVTablePointers(BaseSubobject Base,
2454 const CXXRecordDecl *NearestVBase,
2455 CharUnits OffsetFromNearestVBase,
2456 bool BaseIsNonVirtualPrimaryBase,
2457 const CXXRecordDecl *VTableClass,
2458 VisitedVirtualBasesSetTy &VBases,
2459 VPtrsVector &Vptrs) {
Anders Carlssond5895932010-03-28 21:07:49 +00002460 // If this base is a non-virtual primary base the address point has already
2461 // been set.
2462 if (!BaseIsNonVirtualPrimaryBase) {
2463 // Initialize the vtable pointer for this base.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002464 VPtr Vptr = {Base, NearestVBase, OffsetFromNearestVBase, VTableClass};
2465 Vptrs.push_back(Vptr);
Anders Carlssond5895932010-03-28 21:07:49 +00002466 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002467
Anders Carlssond5895932010-03-28 21:07:49 +00002468 const CXXRecordDecl *RD = Base.getBase();
2469
2470 // Traverse bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00002471 for (const auto &I : RD->bases()) {
Anders Carlssond5895932010-03-28 21:07:49 +00002472 CXXRecordDecl *BaseDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00002473 = cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Anders Carlssond5895932010-03-28 21:07:49 +00002474
2475 // Ignore classes without a vtable.
2476 if (!BaseDecl->isDynamicClass())
2477 continue;
2478
Ken Dyck3fb4c892011-03-23 01:04:18 +00002479 CharUnits BaseOffset;
2480 CharUnits BaseOffsetFromNearestVBase;
Anders Carlsson948d3f42010-03-29 01:16:41 +00002481 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlssond5895932010-03-28 21:07:49 +00002482
Aaron Ballman574705e2014-03-13 15:41:46 +00002483 if (I.isVirtual()) {
Anders Carlssond5895932010-03-28 21:07:49 +00002484 // Check if we've visited this virtual base before.
David Blaikie82e95a32014-11-19 07:49:47 +00002485 if (!VBases.insert(BaseDecl).second)
Anders Carlssond5895932010-03-28 21:07:49 +00002486 continue;
2487
Justin Bogner1cd11f12015-05-20 15:53:59 +00002488 const ASTRecordLayout &Layout =
Anders Carlssond5895932010-03-28 21:07:49 +00002489 getContext().getASTRecordLayout(VTableClass);
2490
Ken Dyck3fb4c892011-03-23 01:04:18 +00002491 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
2492 BaseOffsetFromNearestVBase = CharUnits::Zero();
Anders Carlsson948d3f42010-03-29 01:16:41 +00002493 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlssond5895932010-03-28 21:07:49 +00002494 } else {
2495 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
2496
Ken Dyck16ffcac2011-03-24 01:21:01 +00002497 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
Justin Bogner1cd11f12015-05-20 15:53:59 +00002498 BaseOffsetFromNearestVBase =
Ken Dyck3fb4c892011-03-23 01:04:18 +00002499 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson948d3f42010-03-29 01:16:41 +00002500 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlssond5895932010-03-28 21:07:49 +00002501 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002502
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002503 getVTablePointers(
2504 BaseSubobject(BaseDecl, BaseOffset),
2505 I.isVirtual() ? BaseDecl : NearestVBase, BaseOffsetFromNearestVBase,
2506 BaseDeclIsNonVirtualPrimaryBase, VTableClass, VBases, Vptrs);
Anders Carlssond5895932010-03-28 21:07:49 +00002507 }
2508}
2509
2510void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
2511 // Ignore classes without a vtable.
Anders Carlsson1f9348c2010-03-26 04:39:42 +00002512 if (!RD->isDynamicClass())
Anders Carlsson27da15b2010-01-01 20:29:01 +00002513 return;
2514
Anders Carlssond5895932010-03-28 21:07:49 +00002515 // Initialize the vtable pointers for this class and all of its bases.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002516 if (CGM.getCXXABI().doStructorsInitializeVPtrs(RD))
2517 for (const VPtr &Vptr : getVTablePointers(RD))
2518 InitializeVTablePointer(Vptr);
Timur Iskhodzhanovb6487322013-10-09 18:16:58 +00002519
2520 if (RD->getNumVBases())
2521 CGM.getCXXABI().initializeHiddenVirtualInheritanceMembers(*this, RD);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002522}
Dan Gohman8fc50c22010-10-26 18:44:08 +00002523
John McCall7f416cc2015-09-08 08:05:57 +00002524llvm::Value *CodeGenFunction::GetVTablePtr(Address This,
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002525 llvm::Type *VTableTy,
2526 const CXXRecordDecl *RD) {
2527 Address VTablePtrSrc = Builder.CreateElementBitCast(This, VTableTy);
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002528 llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
Ivan A. Kosarev4e50e702017-11-27 09:39:29 +00002529 TBAAAccessInfo TBAAInfo = CGM.getTBAAVTablePtrAccessInfo(VTableTy);
2530 CGM.DecorateInstructionWithTBAA(VTable, TBAAInfo);
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002531
2532 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2533 CGM.getCodeGenOpts().StrictVTablePointers)
2534 CGM.DecorateInstructionWithInvariantGroup(VTable, RD);
2535
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002536 return VTable;
Dan Gohman8fc50c22010-10-26 18:44:08 +00002537}
Anders Carlssonc36783e2011-05-08 20:32:23 +00002538
Peter Collingbourned2926c92015-03-14 02:42:25 +00002539// If a class has a single non-virtual base and does not introduce or override
2540// virtual member functions or fields, it will have the same layout as its base.
2541// This function returns the least derived such class.
2542//
2543// Casting an instance of a base class to such a derived class is technically
2544// undefined behavior, but it is a relatively common hack for introducing member
2545// functions on class instances with specific properties (e.g. llvm::Operator)
2546// that works under most compilers and should not have security implications, so
2547// we allow it by default. It can be disabled with -fsanitize=cfi-cast-strict.
2548static const CXXRecordDecl *
2549LeastDerivedClassWithSameLayout(const CXXRecordDecl *RD) {
2550 if (!RD->field_empty())
2551 return RD;
2552
2553 if (RD->getNumVBases() != 0)
2554 return RD;
2555
2556 if (RD->getNumBases() != 1)
2557 return RD;
2558
2559 for (const CXXMethodDecl *MD : RD->methods()) {
2560 if (MD->isVirtual()) {
2561 // Virtual member functions are only ok if they are implicit destructors
2562 // because the implicit destructor will have the same semantics as the
2563 // base class's destructor if no fields are added.
2564 if (isa<CXXDestructorDecl>(MD) && MD->isImplicit())
2565 continue;
2566 return RD;
2567 }
2568 }
2569
2570 return LeastDerivedClassWithSameLayout(
2571 RD->bases_begin()->getType()->getAsCXXRecordDecl());
2572}
2573
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002574void CodeGenFunction::EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD,
2575 llvm::Value *VTable,
2576 SourceLocation Loc) {
Peter Collingbourne396943a2017-07-31 22:35:33 +00002577 if (SanOpts.has(SanitizerKind::CFIVCall))
2578 EmitVTablePtrCheckForCall(RD, VTable, CodeGenFunction::CFITCK_VCall, Loc);
2579 else if (CGM.getCodeGenOpts().WholeProgramVTables &&
2580 CGM.HasHiddenLTOVisibility(RD)) {
Peter Collingbournefb532b92016-02-24 20:46:36 +00002581 llvm::Metadata *MD =
2582 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002583 llvm::Value *TypeId =
Peter Collingbournefb532b92016-02-24 20:46:36 +00002584 llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD);
2585
2586 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002587 llvm::Value *TypeTest =
2588 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
2589 {CastedVTable, TypeId});
2590 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::assume), TypeTest);
Peter Collingbournefb532b92016-02-24 20:46:36 +00002591 }
Peter Collingbournefb532b92016-02-24 20:46:36 +00002592}
2593
2594void CodeGenFunction::EmitVTablePtrCheckForCall(const CXXRecordDecl *RD,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002595 llvm::Value *VTable,
2596 CFITypeCheckKind TCK,
2597 SourceLocation Loc) {
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002598 if (!SanOpts.has(SanitizerKind::CFICastStrict))
Peter Collingbournefb532b92016-02-24 20:46:36 +00002599 RD = LeastDerivedClassWithSameLayout(RD);
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002600
Peter Collingbournefb532b92016-02-24 20:46:36 +00002601 EmitVTablePtrCheck(RD, VTable, TCK, Loc);
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002602}
2603
Peter Collingbourned2926c92015-03-14 02:42:25 +00002604void CodeGenFunction::EmitVTablePtrCheckForCast(QualType T,
2605 llvm::Value *Derived,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002606 bool MayBeNull,
2607 CFITypeCheckKind TCK,
2608 SourceLocation Loc) {
Peter Collingbourned2926c92015-03-14 02:42:25 +00002609 if (!getLangOpts().CPlusPlus)
2610 return;
2611
2612 auto *ClassTy = T->getAs<RecordType>();
2613 if (!ClassTy)
2614 return;
2615
2616 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassTy->getDecl());
2617
2618 if (!ClassDecl->isCompleteDefinition() || !ClassDecl->isDynamicClass())
2619 return;
2620
Peter Collingbourned2926c92015-03-14 02:42:25 +00002621 if (!SanOpts.has(SanitizerKind::CFICastStrict))
2622 ClassDecl = LeastDerivedClassWithSameLayout(ClassDecl);
2623
Hans Wennborgdcfba332015-10-06 23:40:43 +00002624 llvm::BasicBlock *ContBlock = nullptr;
Peter Collingbourned2926c92015-03-14 02:42:25 +00002625
2626 if (MayBeNull) {
2627 llvm::Value *DerivedNotNull =
2628 Builder.CreateIsNotNull(Derived, "cast.nonnull");
2629
2630 llvm::BasicBlock *CheckBlock = createBasicBlock("cast.check");
2631 ContBlock = createBasicBlock("cast.cont");
2632
2633 Builder.CreateCondBr(DerivedNotNull, CheckBlock, ContBlock);
2634
2635 EmitBlock(CheckBlock);
2636 }
2637
Peter Collingbourne60108802017-12-13 21:53:04 +00002638 llvm::Value *VTable;
2639 std::tie(VTable, ClassDecl) = CGM.getCXXABI().LoadVTablePtr(
2640 *this, Address(Derived, getPointerAlign()), ClassDecl);
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002641
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002642 EmitVTablePtrCheck(ClassDecl, VTable, TCK, Loc);
Peter Collingbourned2926c92015-03-14 02:42:25 +00002643
2644 if (MayBeNull) {
2645 Builder.CreateBr(ContBlock);
2646 EmitBlock(ContBlock);
2647 }
2648}
2649
2650void CodeGenFunction::EmitVTablePtrCheck(const CXXRecordDecl *RD,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002651 llvm::Value *VTable,
2652 CFITypeCheckKind TCK,
2653 SourceLocation Loc) {
Peter Collingbourne3afb2662016-04-28 17:09:37 +00002654 if (!CGM.getCodeGenOpts().SanitizeCfiCrossDso &&
2655 !CGM.HasHiddenLTOVisibility(RD))
2656 return;
2657
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002658 SanitizerMask M;
Peter Collingbournedc134532016-01-16 00:31:22 +00002659 llvm::SanitizerStatKind SSK;
2660 switch (TCK) {
2661 case CFITCK_VCall:
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002662 M = SanitizerKind::CFIVCall;
Peter Collingbournedc134532016-01-16 00:31:22 +00002663 SSK = llvm::SanStat_CFI_VCall;
2664 break;
2665 case CFITCK_NVCall:
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002666 M = SanitizerKind::CFINVCall;
Peter Collingbournedc134532016-01-16 00:31:22 +00002667 SSK = llvm::SanStat_CFI_NVCall;
2668 break;
2669 case CFITCK_DerivedCast:
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002670 M = SanitizerKind::CFIDerivedCast;
Peter Collingbournedc134532016-01-16 00:31:22 +00002671 SSK = llvm::SanStat_CFI_DerivedCast;
2672 break;
2673 case CFITCK_UnrelatedCast:
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002674 M = SanitizerKind::CFIUnrelatedCast;
Peter Collingbournedc134532016-01-16 00:31:22 +00002675 SSK = llvm::SanStat_CFI_UnrelatedCast;
2676 break;
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002677 case CFITCK_ICall:
2678 llvm_unreachable("not expecting CFITCK_ICall");
Peter Collingbournedc134532016-01-16 00:31:22 +00002679 }
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002680
2681 std::string TypeName = RD->getQualifiedNameAsString();
2682 if (getContext().getSanitizerBlacklist().isBlacklistedType(M, TypeName))
2683 return;
2684
2685 SanitizerScope SanScope(this);
Peter Collingbournedc134532016-01-16 00:31:22 +00002686 EmitSanitizerStatReport(SSK);
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002687
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002688 llvm::Metadata *MD =
2689 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002690 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002691
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002692 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002693 llvm::Value *TypeTest = Builder.CreateCall(
2694 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, TypeId});
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002695
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002696 llvm::Constant *StaticData[] = {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002697 llvm::ConstantInt::get(Int8Ty, TCK),
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002698 EmitCheckSourceLocation(Loc),
2699 EmitCheckTypeDescriptor(QualType(RD->getTypeForDecl(), 0)),
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002700 };
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002701
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002702 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
2703 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
2704 EmitCfiSlowPathCheck(M, TypeTest, CrossDsoTypeId, CastedVTable, StaticData);
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002705 return;
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002706 }
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002707
2708 if (CGM.getCodeGenOpts().SanitizeTrap.has(M)) {
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002709 EmitTrapCheck(TypeTest);
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002710 return;
2711 }
2712
2713 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
2714 CGM.getLLVMContext(),
2715 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002716 llvm::Value *ValidVtable = Builder.CreateCall(
2717 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, AllVtables});
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002718 EmitCheck(std::make_pair(TypeTest, M), SanitizerHandler::CFICheckFail,
2719 StaticData, {CastedVTable, ValidVtable});
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002720}
Anders Carlssonc36783e2011-05-08 20:32:23 +00002721
Peter Collingbourne0ca03632016-06-25 00:24:06 +00002722bool CodeGenFunction::ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD) {
2723 if (!CGM.getCodeGenOpts().WholeProgramVTables ||
2724 !SanOpts.has(SanitizerKind::CFIVCall) ||
2725 !CGM.getCodeGenOpts().SanitizeTrap.has(SanitizerKind::CFIVCall) ||
2726 !CGM.HasHiddenLTOVisibility(RD))
2727 return false;
2728
2729 std::string TypeName = RD->getQualifiedNameAsString();
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002730 return !getContext().getSanitizerBlacklist().isBlacklistedType(
2731 SanitizerKind::CFIVCall, TypeName);
Peter Collingbourne0ca03632016-06-25 00:24:06 +00002732}
2733
2734llvm::Value *CodeGenFunction::EmitVTableTypeCheckedLoad(
2735 const CXXRecordDecl *RD, llvm::Value *VTable, uint64_t VTableByteOffset) {
2736 SanitizerScope SanScope(this);
2737
2738 EmitSanitizerStatReport(llvm::SanStat_CFI_VCall);
2739
2740 llvm::Metadata *MD =
2741 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
2742 llvm::Value *TypeId = llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD);
2743
2744 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
2745 llvm::Value *CheckedLoad = Builder.CreateCall(
2746 CGM.getIntrinsic(llvm::Intrinsic::type_checked_load),
2747 {CastedVTable, llvm::ConstantInt::get(Int32Ty, VTableByteOffset),
2748 TypeId});
2749 llvm::Value *CheckResult = Builder.CreateExtractValue(CheckedLoad, 1);
2750
2751 EmitCheck(std::make_pair(CheckResult, SanitizerKind::CFIVCall),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002752 SanitizerHandler::CFICheckFail, nullptr, nullptr);
Peter Collingbourne0ca03632016-06-25 00:24:06 +00002753
2754 return Builder.CreateBitCast(
2755 Builder.CreateExtractValue(CheckedLoad, 0),
2756 cast<llvm::PointerType>(VTable->getType())->getElementType());
2757}
2758
Faisal Vali571df122013-09-29 08:45:24 +00002759void CodeGenFunction::EmitForwardingCallToLambda(
2760 const CXXMethodDecl *callOperator,
2761 CallArgList &callArgs) {
Eli Friedman5b446882012-02-16 03:47:28 +00002762 // Get the address of the call operator.
John McCall8dda7b22012-07-07 06:41:13 +00002763 const CGFunctionInfo &calleeFnInfo =
2764 CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
John McCallb92ab1a2016-10-26 23:46:34 +00002765 llvm::Constant *calleePtr =
John McCall8dda7b22012-07-07 06:41:13 +00002766 CGM.GetAddrOfFunction(GlobalDecl(callOperator),
2767 CGM.getTypes().GetFunctionType(calleeFnInfo));
Eli Friedman5b446882012-02-16 03:47:28 +00002768
John McCall8dda7b22012-07-07 06:41:13 +00002769 // Prepare the return slot.
2770 const FunctionProtoType *FPT =
2771 callOperator->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00002772 QualType resultType = FPT->getReturnType();
John McCall8dda7b22012-07-07 06:41:13 +00002773 ReturnValueSlot returnSlot;
2774 if (!resultType->isVoidType() &&
2775 calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
John McCall47fb9502013-03-07 21:37:08 +00002776 !hasScalarEvaluationKind(calleeFnInfo.getReturnType()))
John McCall8dda7b22012-07-07 06:41:13 +00002777 returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
2778
2779 // We don't need to separately arrange the call arguments because
2780 // the call can't be variadic anyway --- it's impossible to forward
2781 // variadic arguments.
Justin Bogner1cd11f12015-05-20 15:53:59 +00002782
Eli Friedman5b446882012-02-16 03:47:28 +00002783 // Now emit our call.
John McCallb92ab1a2016-10-26 23:46:34 +00002784 auto callee = CGCallee::forDirect(calleePtr, callOperator);
2785 RValue RV = EmitCall(calleeFnInfo, callee, returnSlot, callArgs);
Eli Friedman5b446882012-02-16 03:47:28 +00002786
John McCall8dda7b22012-07-07 06:41:13 +00002787 // If necessary, copy the returned value into the slot.
John McCall95088452017-12-14 18:21:14 +00002788 if (!resultType->isVoidType() && returnSlot.isNull()) {
2789 if (getLangOpts().ObjCAutoRefCount && resultType->isObjCRetainableType()) {
2790 RV = RValue::get(EmitARCRetainAutoreleasedReturnValue(RV.getScalarVal()));
2791 }
John McCall8dda7b22012-07-07 06:41:13 +00002792 EmitReturnOfRValue(RV, resultType);
John McCall95088452017-12-14 18:21:14 +00002793 } else
Eli Friedmanf5f4d2f2012-12-13 23:37:17 +00002794 EmitBranchThroughCleanup(ReturnBlock);
Eli Friedman5b446882012-02-16 03:47:28 +00002795}
2796
Eli Friedman2495ab02012-02-25 02:48:22 +00002797void CodeGenFunction::EmitLambdaBlockInvokeBody() {
2798 const BlockDecl *BD = BlockInfo->getBlockDecl();
2799 const VarDecl *variable = BD->capture_begin()->getVariable();
2800 const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
Reid Kleckner2d3c4212017-08-04 22:38:06 +00002801 const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
2802
2803 if (CallOp->isVariadic()) {
2804 // FIXME: Making this work correctly is nasty because it requires either
2805 // cloning the body of the call operator or making the call operator
2806 // forward.
2807 CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function");
2808 return;
2809 }
Eli Friedman2495ab02012-02-25 02:48:22 +00002810
2811 // Start building arguments for forwarding call
2812 CallArgList CallArgs;
2813
2814 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
John McCall7f416cc2015-09-08 08:05:57 +00002815 Address ThisPtr = GetAddrOfBlockDecl(variable, false);
2816 CallArgs.add(RValue::get(ThisPtr.getPointer()), ThisType);
Eli Friedman2495ab02012-02-25 02:48:22 +00002817
2818 // Add the rest of the parameters.
David Majnemer59f77922016-06-24 04:05:48 +00002819 for (auto param : BD->parameters())
Nick Lewycky2d84e842013-10-02 02:29:49 +00002820 EmitDelegateCallArg(CallArgs, param, param->getLocStart());
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00002821
Justin Bogner1cd11f12015-05-20 15:53:59 +00002822 assert(!Lambda->isGenericLambda() &&
Faisal Vali571df122013-09-29 08:45:24 +00002823 "generic lambda interconversion to block not implemented");
Reid Kleckner2d3c4212017-08-04 22:38:06 +00002824 EmitForwardingCallToLambda(CallOp, CallArgs);
Eli Friedman2495ab02012-02-25 02:48:22 +00002825}
2826
2827void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
2828 const CXXRecordDecl *Lambda = MD->getParent();
2829
2830 // Start building arguments for forwarding call
2831 CallArgList CallArgs;
2832
2833 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2834 llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
2835 CallArgs.add(RValue::get(ThisPtr), ThisType);
2836
2837 // Add the rest of the parameters.
David Majnemer59f77922016-06-24 04:05:48 +00002838 for (auto Param : MD->parameters())
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002839 EmitDelegateCallArg(CallArgs, Param, Param->getLocStart());
2840
Faisal Vali571df122013-09-29 08:45:24 +00002841 const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
2842 // For a generic lambda, find the corresponding call operator specialization
2843 // to which the call to the static-invoker shall be forwarded.
2844 if (Lambda->isGenericLambda()) {
2845 assert(MD->isFunctionTemplateSpecialization());
2846 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
2847 FunctionTemplateDecl *CallOpTemplate = CallOp->getDescribedFunctionTemplate();
Craig Topper8a13c412014-05-21 05:09:00 +00002848 void *InsertPos = nullptr;
Justin Bogner1cd11f12015-05-20 15:53:59 +00002849 FunctionDecl *CorrespondingCallOpSpecialization =
Craig Topper7e0daca2014-06-26 04:58:53 +00002850 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
Faisal Vali571df122013-09-29 08:45:24 +00002851 assert(CorrespondingCallOpSpecialization);
2852 CallOp = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
2853 }
2854 EmitForwardingCallToLambda(CallOp, CallArgs);
Eli Friedman2495ab02012-02-25 02:48:22 +00002855}
2856
Reid Kleckner2d3c4212017-08-04 22:38:06 +00002857void CodeGenFunction::EmitLambdaStaticInvokeBody(const CXXMethodDecl *MD) {
Douglas Gregor355efbb2012-02-17 03:02:34 +00002858 if (MD->isVariadic()) {
Eli Friedman5b446882012-02-16 03:47:28 +00002859 // FIXME: Making this work correctly is nasty because it requires either
2860 // cloning the body of the call operator or making the call operator forward.
2861 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
Eli Friedman2495ab02012-02-25 02:48:22 +00002862 return;
Eli Friedman5b446882012-02-16 03:47:28 +00002863 }
2864
Douglas Gregor355efbb2012-02-17 03:02:34 +00002865 EmitLambdaDelegatingInvokeBody(MD);
Eli Friedman5a6d5072012-02-16 01:37:33 +00002866}