blob: 9bbdc98f1f2a0159a2e5d42c6e3787743840897d [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);
Eli Friedman87549262012-02-28 22:07:56 +0000409 Value = Builder.CreateGEP(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);
Eli Friedmanf6d21842012-08-08 03:51:37 +0000618 LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
Eli Friedman7f1ff602012-04-16 03:54:45 +0000619
Alexey Bataev152c71f2015-07-14 07:55:48 +0000620 EmitLValueForAnyFieldInitialization(CGF, MemberInit, LHS);
Anders Carlssonfb404882009-12-24 22:46:43 +0000621
Eli Friedman6ae63022012-02-14 02:15:49 +0000622 // Special case: if we are in a copy or move constructor, and we are copying
623 // an array of PODs or classes with trivial copy constructors, ignore the
624 // AST and perform the copy we know is equivalent.
625 // FIXME: This is hacky at best... if we had a bit more explicit information
626 // in the AST, we could generalize it more easily.
627 const ConstantArrayType *Array
628 = CGF.getContext().getAsConstantArrayType(FieldType);
Jordan Rose54533f72013-08-07 16:16:48 +0000629 if (Array && Constructor->isDefaulted() &&
Eli Friedman6ae63022012-02-14 02:15:49 +0000630 Constructor->isCopyOrMoveConstructor()) {
631 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
Richard Smith993f25a2012-11-07 23:56:21 +0000632 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
Eli Friedman6ae63022012-02-14 02:15:49 +0000633 if (BaseElementTy.isPODType(CGF.getContext()) ||
Richard Smith419bd092015-04-29 19:26:57 +0000634 (CE && isMemcpyEquivalentSpecialMember(CE->getConstructor()))) {
David Majnemer1573d732014-10-15 04:54:54 +0000635 unsigned SrcArgIndex =
636 CGF.CGM.getCXXABI().getSrcArgforCopyCtor(Constructor, Args);
Eli Friedman6ae63022012-02-14 02:15:49 +0000637 llvm::Value *SrcPtr
638 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
Eli Friedman7f1ff602012-04-16 03:54:45 +0000639 LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
640 LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000641
Eli Friedman6ae63022012-02-14 02:15:49 +0000642 // Copy the aggregate.
643 CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000644 LHS.isVolatileQualified());
Alexey Bataev5d49b832015-07-08 07:31:02 +0000645 // Ensure that we destroy the objects if an exception is thrown later in
646 // the constructor.
647 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
648 if (CGF.needsEHCleanup(dtorKind))
649 CGF.pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
Eli Friedman6ae63022012-02-14 02:15:49 +0000650 return;
651 }
652 }
653
Richard Smith30e304e2016-12-14 00:03:17 +0000654 CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit());
Eli Friedman6ae63022012-02-14 02:15:49 +0000655}
656
John McCall7f416cc2015-09-08 08:05:57 +0000657void CodeGenFunction::EmitInitializerForField(FieldDecl *Field, LValue LHS,
Richard Smith30e304e2016-12-14 00:03:17 +0000658 Expr *Init) {
Eli Friedman6ae63022012-02-14 02:15:49 +0000659 QualType FieldType = Field->getType();
John McCall47fb9502013-03-07 21:37:08 +0000660 switch (getEvaluationKind(FieldType)) {
661 case TEK_Scalar:
John McCall31168b02011-06-15 23:02:42 +0000662 if (LHS.isSimple()) {
David Blaikie66e41972015-01-14 07:38:27 +0000663 EmitExprAsInit(Init, Field, LHS, false);
John McCall31168b02011-06-15 23:02:42 +0000664 } else {
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000665 RValue RHS = RValue::get(EmitScalarExpr(Init));
666 EmitStoreThroughLValue(RHS, LHS);
John McCall31168b02011-06-15 23:02:42 +0000667 }
John McCall47fb9502013-03-07 21:37:08 +0000668 break;
669 case TEK_Complex:
David Blaikie66e41972015-01-14 07:38:27 +0000670 EmitComplexExprIntoLValue(Init, LHS, /*isInit*/ true);
John McCall47fb9502013-03-07 21:37:08 +0000671 break;
672 case TEK_Aggregate: {
Richard Smith30e304e2016-12-14 00:03:17 +0000673 AggValueSlot Slot =
674 AggValueSlot::forLValue(LHS,
675 AggValueSlot::IsDestructed,
676 AggValueSlot::DoesNotNeedGCBarriers,
677 AggValueSlot::IsNotAliased);
678 EmitAggExpr(Init, Slot);
679 break;
Anders Carlssonfb404882009-12-24 22:46:43 +0000680 }
John McCall47fb9502013-03-07 21:37:08 +0000681 }
John McCall12cc42a2013-02-01 05:11:40 +0000682
683 // Ensure that we destroy this object if an exception is thrown
684 // later in the constructor.
685 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
686 if (needsEHCleanup(dtorKind))
687 pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
Anders Carlssonfb404882009-12-24 22:46:43 +0000688}
689
John McCallf8ff7b92010-02-23 00:48:20 +0000690/// Checks whether the given constructor is a valid subject for the
691/// complete-to-base constructor delegation optimization, i.e.
692/// emitting the complete constructor as a simple call to the base
693/// constructor.
Vedant Kumar7f809b22017-02-24 01:15:19 +0000694bool CodeGenFunction::IsConstructorDelegationValid(
695 const CXXConstructorDecl *Ctor) {
John McCallf8ff7b92010-02-23 00:48:20 +0000696
697 // Currently we disable the optimization for classes with virtual
698 // bases because (1) the addresses of parameter variables need to be
699 // consistent across all initializers but (2) the delegate function
700 // call necessarily creates a second copy of the parameter variable.
701 //
702 // The limiting example (purely theoretical AFAIK):
703 // struct A { A(int &c) { c++; } };
704 // struct B : virtual A {
705 // B(int count) : A(count) { printf("%d\n", count); }
706 // };
707 // ...although even this example could in principle be emitted as a
708 // delegation since the address of the parameter doesn't escape.
709 if (Ctor->getParent()->getNumVBases()) {
710 // TODO: white-list trivial vbase initializers. This case wouldn't
711 // be subject to the restrictions below.
712
713 // TODO: white-list cases where:
714 // - there are no non-reference parameters to the constructor
715 // - the initializers don't access any non-reference parameters
716 // - the initializers don't take the address of non-reference
717 // parameters
718 // - etc.
719 // If we ever add any of the above cases, remember that:
720 // - function-try-blocks will always blacklist this optimization
721 // - we need to perform the constructor prologue and cleanup in
722 // EmitConstructorBody.
723
724 return false;
725 }
726
727 // We also disable the optimization for variadic functions because
728 // it's impossible to "re-pass" varargs.
729 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
730 return false;
731
Alexis Hunt61bc1732011-05-01 07:04:31 +0000732 // FIXME: Decide if we can do a delegation of a delegating constructor.
733 if (Ctor->isDelegatingConstructor())
734 return false;
735
John McCallf8ff7b92010-02-23 00:48:20 +0000736 return true;
737}
738
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000739// Emit code in ctor (Prologue==true) or dtor (Prologue==false)
740// to poison the extra field paddings inserted under
741// -fsanitize-address-field-padding=1|2.
742void CodeGenFunction::EmitAsanPrologueOrEpilogue(bool Prologue) {
743 ASTContext &Context = getContext();
744 const CXXRecordDecl *ClassDecl =
745 Prologue ? cast<CXXConstructorDecl>(CurGD.getDecl())->getParent()
746 : cast<CXXDestructorDecl>(CurGD.getDecl())->getParent();
747 if (!ClassDecl->mayInsertExtraPadding()) return;
748
749 struct SizeAndOffset {
750 uint64_t Size;
751 uint64_t Offset;
752 };
753
754 unsigned PtrSize = CGM.getDataLayout().getPointerSizeInBits();
755 const ASTRecordLayout &Info = Context.getASTRecordLayout(ClassDecl);
756
757 // Populate sizes and offsets of fields.
758 SmallVector<SizeAndOffset, 16> SSV(Info.getFieldCount());
759 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i)
760 SSV[i].Offset =
761 Context.toCharUnitsFromBits(Info.getFieldOffset(i)).getQuantity();
762
763 size_t NumFields = 0;
764 for (const auto *Field : ClassDecl->fields()) {
765 const FieldDecl *D = Field;
766 std::pair<CharUnits, CharUnits> FieldInfo =
767 Context.getTypeInfoInChars(D->getType());
768 CharUnits FieldSize = FieldInfo.first;
769 assert(NumFields < SSV.size());
770 SSV[NumFields].Size = D->isBitField() ? 0 : FieldSize.getQuantity();
771 NumFields++;
772 }
773 assert(NumFields == SSV.size());
774 if (SSV.size() <= 1) return;
775
776 // We will insert calls to __asan_* run-time functions.
777 // LLVM AddressSanitizer pass may decide to inline them later.
778 llvm::Type *Args[2] = {IntPtrTy, IntPtrTy};
779 llvm::FunctionType *FTy =
780 llvm::FunctionType::get(CGM.VoidTy, Args, false);
781 llvm::Constant *F = CGM.CreateRuntimeFunction(
782 FTy, Prologue ? "__asan_poison_intra_object_redzone"
783 : "__asan_unpoison_intra_object_redzone");
784
785 llvm::Value *ThisPtr = LoadCXXThis();
786 ThisPtr = Builder.CreatePtrToInt(ThisPtr, IntPtrTy);
Kostya Serebryany64449212014-10-17 21:02:13 +0000787 uint64_t TypeSize = Info.getNonVirtualSize().getQuantity();
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000788 // For each field check if it has sufficient padding,
789 // if so (un)poison it with a call.
790 for (size_t i = 0; i < SSV.size(); i++) {
791 uint64_t AsanAlignment = 8;
792 uint64_t NextField = i == SSV.size() - 1 ? TypeSize : SSV[i + 1].Offset;
793 uint64_t PoisonSize = NextField - SSV[i].Offset - SSV[i].Size;
794 uint64_t EndOffset = SSV[i].Offset + SSV[i].Size;
795 if (PoisonSize < AsanAlignment || !SSV[i].Size ||
796 (NextField % AsanAlignment) != 0)
797 continue;
David Blaikie43f9bb72015-05-18 22:14:03 +0000798 Builder.CreateCall(
799 F, {Builder.CreateAdd(ThisPtr, Builder.getIntN(PtrSize, EndOffset)),
800 Builder.getIntN(PtrSize, PoisonSize)});
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000801 }
802}
803
John McCallb81884d2010-02-19 09:25:03 +0000804/// EmitConstructorBody - Emits the body of the current constructor.
805void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000806 EmitAsanPrologueOrEpilogue(true);
John McCallb81884d2010-02-19 09:25:03 +0000807 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
808 CXXCtorType CtorType = CurGD.getCtorType();
809
Reid Kleckner340ad862014-01-13 22:57:31 +0000810 assert((CGM.getTarget().getCXXABI().hasConstructorVariants() ||
811 CtorType == Ctor_Complete) &&
812 "can only generate complete ctor for this ABI");
813
John McCallf8ff7b92010-02-23 00:48:20 +0000814 // Before we go any further, try the complete->base constructor
815 // delegation optimization.
Timur Iskhodzhanovf32a3772012-04-20 08:05:00 +0000816 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
John McCallc8e01702013-04-16 22:48:15 +0000817 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000818 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args, Ctor->getLocEnd());
John McCallf8ff7b92010-02-23 00:48:20 +0000819 return;
820 }
821
Hans Wennborgdcfba332015-10-06 23:40:43 +0000822 const FunctionDecl *Definition = nullptr;
Richard Smith46bb5812014-08-01 01:56:39 +0000823 Stmt *Body = Ctor->getBody(Definition);
824 assert(Definition == Ctor && "emitting wrong constructor body");
John McCallb81884d2010-02-19 09:25:03 +0000825
John McCallf8ff7b92010-02-23 00:48:20 +0000826 // Enter the function-try-block before the constructor prologue if
827 // applicable.
John McCallf8ff7b92010-02-23 00:48:20 +0000828 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallf8ff7b92010-02-23 00:48:20 +0000829 if (IsTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000830 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000831
Justin Bogner66242d62015-04-23 23:06:47 +0000832 incrementProfileCounter(Body);
Justin Bogner81c22c22014-01-23 02:54:27 +0000833
Richard Smithcc1b96d2013-06-12 22:31:48 +0000834 RunCleanupsScope RunCleanups(*this);
John McCallb81884d2010-02-19 09:25:03 +0000835
John McCall88313032012-03-30 04:25:03 +0000836 // TODO: in restricted cases, we can emit the vbase initializers of
837 // a complete ctor and then delegate to the base ctor.
838
John McCallf8ff7b92010-02-23 00:48:20 +0000839 // Emit the constructor prologue, i.e. the base and member
840 // initializers.
Douglas Gregor94f9a482010-05-05 05:51:00 +0000841 EmitCtorPrologue(Ctor, CtorType, Args);
John McCallb81884d2010-02-19 09:25:03 +0000842
843 // Emit the body of the statement.
John McCallf8ff7b92010-02-23 00:48:20 +0000844 if (IsTryBody)
John McCallb81884d2010-02-19 09:25:03 +0000845 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
846 else if (Body)
847 EmitStmt(Body);
John McCallb81884d2010-02-19 09:25:03 +0000848
849 // Emit any cleanup blocks associated with the member or base
850 // initializers, which includes (along the exceptional path) the
851 // destructors for those members and bases that were fully
852 // constructed.
Richard Smithcc1b96d2013-06-12 22:31:48 +0000853 RunCleanups.ForceCleanup();
John McCallb81884d2010-02-19 09:25:03 +0000854
John McCallf8ff7b92010-02-23 00:48:20 +0000855 if (IsTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000856 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000857}
858
Lang Hamesbf122742013-02-17 07:22:09 +0000859namespace {
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000860 /// RAII object to indicate that codegen is copying the value representation
861 /// instead of the object representation. Useful when copying a struct or
862 /// class which has uninitialized members and we're only performing
863 /// lvalue-to-rvalue conversion on the object but not its members.
864 class CopyingValueRepresentation {
865 public:
866 explicit CopyingValueRepresentation(CodeGenFunction &CGF)
Alexey Samsonov035462c2014-10-30 19:33:44 +0000867 : CGF(CGF), OldSanOpts(CGF.SanOpts) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000868 CGF.SanOpts.set(SanitizerKind::Bool, false);
869 CGF.SanOpts.set(SanitizerKind::Enum, false);
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000870 }
871 ~CopyingValueRepresentation() {
872 CGF.SanOpts = OldSanOpts;
873 }
874 private:
875 CodeGenFunction &CGF;
Alexey Samsonova0416102014-11-11 01:26:14 +0000876 SanitizerSet OldSanOpts;
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000877 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000878} // end anonymous namespace
Hans Wennborgdcfba332015-10-06 23:40:43 +0000879
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000880namespace {
Lang Hamesbf122742013-02-17 07:22:09 +0000881 class FieldMemcpyizer {
882 public:
883 FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl,
884 const VarDecl *SrcRec)
Justin Bogner1cd11f12015-05-20 15:53:59 +0000885 : CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec),
Lang Hamesbf122742013-02-17 07:22:09 +0000886 RecLayout(CGF.getContext().getASTRecordLayout(ClassDecl)),
Craig Topper8a13c412014-05-21 05:09:00 +0000887 FirstField(nullptr), LastField(nullptr), FirstFieldOffset(0),
888 LastFieldOffset(0), LastAddedFieldIndex(0) {}
Lang Hamesbf122742013-02-17 07:22:09 +0000889
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000890 bool isMemcpyableField(FieldDecl *F) const {
891 // Never memcpy fields when we are adding poisoned paddings.
Alexey Samsonova0416102014-11-11 01:26:14 +0000892 if (CGF.getContext().getLangOpts().SanitizeAddressFieldPadding)
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000893 return false;
Lang Hamesbf122742013-02-17 07:22:09 +0000894 Qualifiers Qual = F->getType().getQualifiers();
895 if (Qual.hasVolatile() || Qual.hasObjCLifetime())
896 return false;
897 return true;
898 }
899
900 void addMemcpyableField(FieldDecl *F) {
Craig Topper8a13c412014-05-21 05:09:00 +0000901 if (!FirstField)
Lang Hamesbf122742013-02-17 07:22:09 +0000902 addInitialField(F);
903 else
904 addNextField(F);
905 }
906
David Majnemera586eb22014-10-10 18:57:10 +0000907 CharUnits getMemcpySize(uint64_t FirstByteOffset) const {
Lang Hamesbf122742013-02-17 07:22:09 +0000908 unsigned LastFieldSize =
909 LastField->isBitField() ?
910 LastField->getBitWidthValue(CGF.getContext()) :
Justin Bogner1cd11f12015-05-20 15:53:59 +0000911 CGF.getContext().getTypeSize(LastField->getType());
Lang Hamesbf122742013-02-17 07:22:09 +0000912 uint64_t MemcpySizeBits =
David Majnemera586eb22014-10-10 18:57:10 +0000913 LastFieldOffset + LastFieldSize - FirstByteOffset +
Lang Hamesbf122742013-02-17 07:22:09 +0000914 CGF.getContext().getCharWidth() - 1;
915 CharUnits MemcpySize =
916 CGF.getContext().toCharUnitsFromBits(MemcpySizeBits);
917 return MemcpySize;
918 }
919
920 void emitMemcpy() {
921 // Give the subclass a chance to bail out if it feels the memcpy isn't
922 // worth it (e.g. Hasn't aggregated enough data).
Craig Topper8a13c412014-05-21 05:09:00 +0000923 if (!FirstField) {
Lang Hamesbf122742013-02-17 07:22:09 +0000924 return;
925 }
926
David Majnemera586eb22014-10-10 18:57:10 +0000927 uint64_t FirstByteOffset;
Lang Hamesbf122742013-02-17 07:22:09 +0000928 if (FirstField->isBitField()) {
929 const CGRecordLayout &RL =
930 CGF.getTypes().getCGRecordLayout(FirstField->getParent());
931 const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField);
David Majnemera586eb22014-10-10 18:57:10 +0000932 // FirstFieldOffset is not appropriate for bitfields,
Ulrich Weigand73263d72015-07-13 11:52:14 +0000933 // we need to use the storage offset instead.
Ulrich Weigand03ce2a12015-07-10 17:30:00 +0000934 FirstByteOffset = CGF.getContext().toBits(BFInfo.StorageOffset);
Lang Hames1694e0d2013-02-27 04:14:49 +0000935 } else {
David Majnemera586eb22014-10-10 18:57:10 +0000936 FirstByteOffset = FirstFieldOffset;
Lang Hames1694e0d2013-02-27 04:14:49 +0000937 }
Lang Hamesbf122742013-02-17 07:22:09 +0000938
David Majnemera586eb22014-10-10 18:57:10 +0000939 CharUnits MemcpySize = getMemcpySize(FirstByteOffset);
Lang Hamesbf122742013-02-17 07:22:09 +0000940 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
John McCall7f416cc2015-09-08 08:05:57 +0000941 Address ThisPtr = CGF.LoadCXXThisAddress();
942 LValue DestLV = CGF.MakeAddrLValue(ThisPtr, RecordTy);
Lang Hamesbf122742013-02-17 07:22:09 +0000943 LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField);
944 llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec));
945 LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
946 LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField);
947
John McCall7f416cc2015-09-08 08:05:57 +0000948 emitMemcpyIR(Dest.isBitField() ? Dest.getBitFieldAddress() : Dest.getAddress(),
949 Src.isBitField() ? Src.getBitFieldAddress() : Src.getAddress(),
950 MemcpySize);
Lang Hamesbf122742013-02-17 07:22:09 +0000951 reset();
952 }
953
954 void reset() {
Craig Topper8a13c412014-05-21 05:09:00 +0000955 FirstField = nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +0000956 }
957
958 protected:
959 CodeGenFunction &CGF;
960 const CXXRecordDecl *ClassDecl;
961
962 private:
John McCall7f416cc2015-09-08 08:05:57 +0000963 void emitMemcpyIR(Address DestPtr, Address SrcPtr, CharUnits Size) {
964 llvm::PointerType *DPT = DestPtr.getType();
Lang Hamesbf122742013-02-17 07:22:09 +0000965 llvm::Type *DBP =
966 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), DPT->getAddressSpace());
967 DestPtr = CGF.Builder.CreateBitCast(DestPtr, DBP);
968
John McCall7f416cc2015-09-08 08:05:57 +0000969 llvm::PointerType *SPT = SrcPtr.getType();
Lang Hamesbf122742013-02-17 07:22:09 +0000970 llvm::Type *SBP =
971 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), SPT->getAddressSpace());
972 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, SBP);
973
John McCall7f416cc2015-09-08 08:05:57 +0000974 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity());
Lang Hamesbf122742013-02-17 07:22:09 +0000975 }
976
977 void addInitialField(FieldDecl *F) {
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000978 FirstField = F;
979 LastField = F;
980 FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex());
981 LastFieldOffset = FirstFieldOffset;
982 LastAddedFieldIndex = F->getFieldIndex();
983 }
Lang Hamesbf122742013-02-17 07:22:09 +0000984
985 void addNextField(FieldDecl *F) {
John McCall6054d5a2013-05-07 05:20:46 +0000986 // For the most part, the following invariant will hold:
987 // F->getFieldIndex() == LastAddedFieldIndex + 1
988 // The one exception is that Sema won't add a copy-initializer for an
989 // unnamed bitfield, which will show up here as a gap in the sequence.
990 assert(F->getFieldIndex() >= LastAddedFieldIndex + 1 &&
991 "Cannot aggregate fields out of order.");
Lang Hamesbf122742013-02-17 07:22:09 +0000992 LastAddedFieldIndex = F->getFieldIndex();
993
994 // The 'first' and 'last' fields are chosen by offset, rather than field
995 // index. This allows the code to support bitfields, as well as regular
996 // fields.
997 uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex());
998 if (FOffset < FirstFieldOffset) {
999 FirstField = F;
1000 FirstFieldOffset = FOffset;
1001 } else if (FOffset > LastFieldOffset) {
1002 LastField = F;
1003 LastFieldOffset = FOffset;
1004 }
1005 }
1006
1007 const VarDecl *SrcRec;
1008 const ASTRecordLayout &RecLayout;
1009 FieldDecl *FirstField;
1010 FieldDecl *LastField;
1011 uint64_t FirstFieldOffset, LastFieldOffset;
1012 unsigned LastAddedFieldIndex;
1013 };
1014
1015 class ConstructorMemcpyizer : public FieldMemcpyizer {
1016 private:
Lang Hamesbf122742013-02-17 07:22:09 +00001017 /// Get source argument for copy constructor. Returns null if not a copy
David Majnemer196ac332014-09-11 23:05:02 +00001018 /// constructor.
1019 static const VarDecl *getTrivialCopySource(CodeGenFunction &CGF,
1020 const CXXConstructorDecl *CD,
Lang Hamesbf122742013-02-17 07:22:09 +00001021 FunctionArgList &Args) {
Jordan Rose54533f72013-08-07 16:16:48 +00001022 if (CD->isCopyOrMoveConstructor() && CD->isDefaulted())
David Majnemer196ac332014-09-11 23:05:02 +00001023 return Args[CGF.CGM.getCXXABI().getSrcArgforCopyCtor(CD, Args)];
Craig Topper8a13c412014-05-21 05:09:00 +00001024 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001025 }
1026
1027 // Returns true if a CXXCtorInitializer represents a member initialization
1028 // that can be rolled into a memcpy.
1029 bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const {
1030 if (!MemcpyableCtor)
1031 return false;
1032 FieldDecl *Field = MemberInit->getMember();
Craig Topper8a13c412014-05-21 05:09:00 +00001033 assert(Field && "No field for member init.");
Lang Hamesbf122742013-02-17 07:22:09 +00001034 QualType FieldType = Field->getType();
1035 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
1036
Richard Smith419bd092015-04-29 19:26:57 +00001037 // Bail out on non-memcpyable, not-trivially-copyable members.
1038 if (!(CE && isMemcpyEquivalentSpecialMember(CE->getConstructor())) &&
Lang Hamesbf122742013-02-17 07:22:09 +00001039 !(FieldType.isTriviallyCopyableType(CGF.getContext()) ||
1040 FieldType->isReferenceType()))
1041 return false;
1042
1043 // Bail out on volatile fields.
1044 if (!isMemcpyableField(Field))
1045 return false;
1046
1047 // Otherwise we're good.
1048 return true;
1049 }
1050
1051 public:
1052 ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD,
1053 FunctionArgList &Args)
David Majnemer196ac332014-09-11 23:05:02 +00001054 : FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CGF, CD, Args)),
Lang Hamesbf122742013-02-17 07:22:09 +00001055 ConstructorDecl(CD),
Jordan Rose54533f72013-08-07 16:16:48 +00001056 MemcpyableCtor(CD->isDefaulted() &&
Lang Hamesbf122742013-02-17 07:22:09 +00001057 CD->isCopyOrMoveConstructor() &&
1058 CGF.getLangOpts().getGC() == LangOptions::NonGC),
1059 Args(Args) { }
1060
1061 void addMemberInitializer(CXXCtorInitializer *MemberInit) {
1062 if (isMemberInitMemcpyable(MemberInit)) {
1063 AggregatedInits.push_back(MemberInit);
1064 addMemcpyableField(MemberInit->getMember());
1065 } else {
1066 emitAggregatedInits();
1067 EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit,
1068 ConstructorDecl, Args);
1069 }
1070 }
1071
1072 void emitAggregatedInits() {
1073 if (AggregatedInits.size() <= 1) {
1074 // This memcpy is too small to be worthwhile. Fall back on default
1075 // codegen.
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001076 if (!AggregatedInits.empty()) {
1077 CopyingValueRepresentation CVR(CGF);
Lang Hamesbf122742013-02-17 07:22:09 +00001078 EmitMemberInitializer(CGF, ConstructorDecl->getParent(),
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001079 AggregatedInits[0], ConstructorDecl, Args);
Alexey Bataev152c71f2015-07-14 07:55:48 +00001080 AggregatedInits.clear();
Lang Hamesbf122742013-02-17 07:22:09 +00001081 }
1082 reset();
1083 return;
1084 }
1085
1086 pushEHDestructors();
1087 emitMemcpy();
1088 AggregatedInits.clear();
1089 }
1090
1091 void pushEHDestructors() {
John McCall7f416cc2015-09-08 08:05:57 +00001092 Address ThisPtr = CGF.LoadCXXThisAddress();
Lang Hamesbf122742013-02-17 07:22:09 +00001093 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
John McCall7f416cc2015-09-08 08:05:57 +00001094 LValue LHS = CGF.MakeAddrLValue(ThisPtr, RecordTy);
Lang Hamesbf122742013-02-17 07:22:09 +00001095
1096 for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
Alexey Bataev152c71f2015-07-14 07:55:48 +00001097 CXXCtorInitializer *MemberInit = AggregatedInits[i];
1098 QualType FieldType = MemberInit->getAnyMember()->getType();
Lang Hamesbf122742013-02-17 07:22:09 +00001099 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
Alexey Bataev152c71f2015-07-14 07:55:48 +00001100 if (!CGF.needsEHCleanup(dtorKind))
1101 continue;
1102 LValue FieldLHS = LHS;
1103 EmitLValueForAnyFieldInitialization(CGF, MemberInit, FieldLHS);
1104 CGF.pushEHDestroy(dtorKind, FieldLHS.getAddress(), FieldType);
Lang Hamesbf122742013-02-17 07:22:09 +00001105 }
1106 }
1107
1108 void finish() {
1109 emitAggregatedInits();
1110 }
1111
1112 private:
1113 const CXXConstructorDecl *ConstructorDecl;
1114 bool MemcpyableCtor;
1115 FunctionArgList &Args;
1116 SmallVector<CXXCtorInitializer*, 16> AggregatedInits;
1117 };
1118
1119 class AssignmentMemcpyizer : public FieldMemcpyizer {
1120 private:
Lang Hamesbf122742013-02-17 07:22:09 +00001121 // Returns the memcpyable field copied by the given statement, if one
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001122 // exists. Otherwise returns null.
1123 FieldDecl *getMemcpyableField(Stmt *S) {
Lang Hamesbf122742013-02-17 07:22:09 +00001124 if (!AssignmentsMemcpyable)
Craig Topper8a13c412014-05-21 05:09:00 +00001125 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001126 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
1127 // Recognise trivial assignments.
1128 if (BO->getOpcode() != BO_Assign)
Craig Topper8a13c412014-05-21 05:09:00 +00001129 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001130 MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS());
1131 if (!ME)
Craig Topper8a13c412014-05-21 05:09:00 +00001132 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001133 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1134 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001135 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001136 Stmt *RHS = BO->getRHS();
1137 if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS))
1138 RHS = EC->getSubExpr();
1139 if (!RHS)
Craig Topper8a13c412014-05-21 05:09:00 +00001140 return nullptr;
Warren Ristow8d17b402017-02-02 17:53:34 +00001141 if (MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS)) {
1142 if (ME2->getMemberDecl() == Field)
1143 return Field;
1144 }
1145 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001146 } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) {
1147 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl());
Richard Smith419bd092015-04-29 19:26:57 +00001148 if (!(MD && isMemcpyEquivalentSpecialMember(MD)))
Craig Topper8a13c412014-05-21 05:09:00 +00001149 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001150 MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument());
1151 if (!IOA)
Craig Topper8a13c412014-05-21 05:09:00 +00001152 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001153 FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl());
1154 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001155 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001156 MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0));
1157 if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl()))
Craig Topper8a13c412014-05-21 05:09:00 +00001158 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001159 return Field;
1160 } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1161 FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1162 if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy)
Craig Topper8a13c412014-05-21 05:09:00 +00001163 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001164 Expr *DstPtr = CE->getArg(0);
1165 if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr))
1166 DstPtr = DC->getSubExpr();
1167 UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr);
1168 if (!DUO || DUO->getOpcode() != UO_AddrOf)
Craig Topper8a13c412014-05-21 05:09:00 +00001169 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001170 MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr());
1171 if (!ME)
Craig Topper8a13c412014-05-21 05:09:00 +00001172 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001173 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1174 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001175 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001176 Expr *SrcPtr = CE->getArg(1);
1177 if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr))
1178 SrcPtr = SC->getSubExpr();
1179 UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr);
1180 if (!SUO || SUO->getOpcode() != UO_AddrOf)
Craig Topper8a13c412014-05-21 05:09:00 +00001181 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001182 MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr());
1183 if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl()))
Craig Topper8a13c412014-05-21 05:09:00 +00001184 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001185 return Field;
1186 }
1187
Craig Topper8a13c412014-05-21 05:09:00 +00001188 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001189 }
1190
1191 bool AssignmentsMemcpyable;
1192 SmallVector<Stmt*, 16> AggregatedStmts;
1193
1194 public:
Lang Hamesbf122742013-02-17 07:22:09 +00001195 AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD,
1196 FunctionArgList &Args)
1197 : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]),
1198 AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) {
1199 assert(Args.size() == 2);
1200 }
1201
1202 void emitAssignment(Stmt *S) {
1203 FieldDecl *F = getMemcpyableField(S);
1204 if (F) {
1205 addMemcpyableField(F);
1206 AggregatedStmts.push_back(S);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001207 } else {
Lang Hamesbf122742013-02-17 07:22:09 +00001208 emitAggregatedStmts();
1209 CGF.EmitStmt(S);
1210 }
1211 }
1212
1213 void emitAggregatedStmts() {
1214 if (AggregatedStmts.size() <= 1) {
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001215 if (!AggregatedStmts.empty()) {
1216 CopyingValueRepresentation CVR(CGF);
1217 CGF.EmitStmt(AggregatedStmts[0]);
1218 }
Lang Hamesbf122742013-02-17 07:22:09 +00001219 reset();
1220 }
1221
1222 emitMemcpy();
1223 AggregatedStmts.clear();
1224 }
1225
1226 void finish() {
1227 emitAggregatedStmts();
1228 }
1229 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00001230} // end anonymous namespace
Lang Hamesbf122742013-02-17 07:22:09 +00001231
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001232static bool isInitializerOfDynamicClass(const CXXCtorInitializer *BaseInit) {
1233 const Type *BaseType = BaseInit->getBaseClass();
1234 const auto *BaseClassDecl =
1235 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
1236 return BaseClassDecl->isDynamicClass();
1237}
1238
Anders Carlssonfb404882009-12-24 22:46:43 +00001239/// EmitCtorPrologue - This routine generates necessary code to initialize
1240/// base classes and non-static data members belonging to this constructor.
Anders Carlssonfb404882009-12-24 22:46:43 +00001241void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001242 CXXCtorType CtorType,
1243 FunctionArgList &Args) {
Alexis Hunt61bc1732011-05-01 07:04:31 +00001244 if (CD->isDelegatingConstructor())
1245 return EmitDelegatingCXXConstructorCall(CD, Args);
1246
Anders Carlssonfb404882009-12-24 22:46:43 +00001247 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlsson5dc86332010-02-02 19:58:43 +00001248
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001249 CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
1250 E = CD->init_end();
1251
Craig Topper8a13c412014-05-21 05:09:00 +00001252 llvm::BasicBlock *BaseCtorContinueBB = nullptr;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001253 if (ClassDecl->getNumVBases() &&
1254 !CGM.getTarget().getCXXABI().hasConstructorVariants()) {
1255 // The ABIs that don't have constructor variants need to put a branch
1256 // before the virtual base initialization code.
Reid Kleckner7810af02013-06-19 15:20:38 +00001257 BaseCtorContinueBB =
1258 CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this, ClassDecl);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001259 assert(BaseCtorContinueBB);
1260 }
1261
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001262 llvm::Value *const OldThis = CXXThisValue;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001263 // Virtual base initializers first.
1264 for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001265 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1266 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1267 isInitializerOfDynamicClass(*B))
1268 CXXThisValue = Builder.CreateInvariantGroupBarrier(LoadCXXThis());
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001269 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
1270 }
1271
1272 if (BaseCtorContinueBB) {
1273 // Complete object handler should continue to the remaining initializers.
1274 Builder.CreateBr(BaseCtorContinueBB);
1275 EmitBlock(BaseCtorContinueBB);
1276 }
1277
1278 // Then, non-virtual base initializers.
1279 for (; B != E && (*B)->isBaseInitializer(); B++) {
1280 assert(!(*B)->isBaseVirtual());
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001281
1282 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1283 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1284 isInitializerOfDynamicClass(*B))
1285 CXXThisValue = Builder.CreateInvariantGroupBarrier(LoadCXXThis());
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001286 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
Anders Carlssonfb404882009-12-24 22:46:43 +00001287 }
1288
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001289 CXXThisValue = OldThis;
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001290
Anders Carlssond5895932010-03-28 21:07:49 +00001291 InitializeVTablePointers(ClassDecl);
Anders Carlsson5dc86332010-02-02 19:58:43 +00001292
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001293 // And finally, initialize class members.
John McCall7f416cc2015-09-08 08:05:57 +00001294 FieldConstructionScope FCS(*this, LoadCXXThisAddress());
Lang Hamesbf122742013-02-17 07:22:09 +00001295 ConstructorMemcpyizer CM(*this, CD, Args);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001296 for (; B != E; B++) {
1297 CXXCtorInitializer *Member = (*B);
1298 assert(!Member->isBaseInitializer());
1299 assert(Member->isAnyMemberInitializer() &&
1300 "Delegating initializer on non-delegating constructor");
1301 CM.addMemberInitializer(Member);
1302 }
Lang Hamesbf122742013-02-17 07:22:09 +00001303 CM.finish();
Anders Carlssonfb404882009-12-24 22:46:43 +00001304}
1305
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001306static bool
1307FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
1308
1309static bool
Justin Bogner1cd11f12015-05-20 15:53:59 +00001310HasTrivialDestructorBody(ASTContext &Context,
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001311 const CXXRecordDecl *BaseClassDecl,
1312 const CXXRecordDecl *MostDerivedClassDecl)
1313{
1314 // If the destructor is trivial we don't have to check anything else.
1315 if (BaseClassDecl->hasTrivialDestructor())
1316 return true;
1317
1318 if (!BaseClassDecl->getDestructor()->hasTrivialBody())
1319 return false;
1320
1321 // Check fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001322 for (const auto *Field : BaseClassDecl->fields())
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001323 if (!FieldHasTrivialDestructorBody(Context, Field))
1324 return false;
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001325
1326 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001327 for (const auto &I : BaseClassDecl->bases()) {
1328 if (I.isVirtual())
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001329 continue;
1330
1331 const CXXRecordDecl *NonVirtualBase =
Aaron Ballman574705e2014-03-13 15:41:46 +00001332 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001333 if (!HasTrivialDestructorBody(Context, NonVirtualBase,
1334 MostDerivedClassDecl))
1335 return false;
1336 }
1337
1338 if (BaseClassDecl == MostDerivedClassDecl) {
1339 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00001340 for (const auto &I : BaseClassDecl->vbases()) {
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001341 const CXXRecordDecl *VirtualBase =
Aaron Ballman445a9392014-03-13 16:15:17 +00001342 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001343 if (!HasTrivialDestructorBody(Context, VirtualBase,
1344 MostDerivedClassDecl))
Justin Bogner1cd11f12015-05-20 15:53:59 +00001345 return false;
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001346 }
1347 }
1348
1349 return true;
1350}
1351
1352static bool
1353FieldHasTrivialDestructorBody(ASTContext &Context,
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001354 const FieldDecl *Field)
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001355{
1356 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
1357
1358 const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
1359 if (!RT)
1360 return true;
Justin Bogner1cd11f12015-05-20 15:53:59 +00001361
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001362 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Davide Italiano982bbf42015-06-26 00:18:35 +00001363
1364 // The destructor for an implicit anonymous union member is never invoked.
1365 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
1366 return false;
1367
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001368 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
1369}
1370
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001371/// CanSkipVTablePointerInitialization - Check whether we need to initialize
1372/// any vtable pointers before calling this destructor.
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001373static bool CanSkipVTablePointerInitialization(CodeGenFunction &CGF,
Anders Carlssond6f15182011-05-16 04:08:36 +00001374 const CXXDestructorDecl *Dtor) {
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001375 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1376 if (!ClassDecl->isDynamicClass())
1377 return true;
1378
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001379 if (!Dtor->hasTrivialBody())
1380 return false;
1381
1382 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001383 for (const auto *Field : ClassDecl->fields())
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001384 if (!FieldHasTrivialDestructorBody(CGF.getContext(), Field))
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001385 return false;
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001386
1387 return true;
1388}
1389
John McCallb81884d2010-02-19 09:25:03 +00001390/// EmitDestructorBody - Emits the body of the current destructor.
1391void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
1392 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
1393 CXXDtorType DtorType = CurGD.getDtorType();
1394
Richard Smithdf054d32017-02-25 23:53:05 +00001395 // For an abstract class, non-base destructors are never used (and can't
1396 // be emitted in general, because vbase dtors may not have been validated
1397 // by Sema), but the Itanium ABI doesn't make them optional and Clang may
1398 // in fact emit references to them from other compilations, so emit them
1399 // as functions containing a trap instruction.
1400 if (DtorType != Dtor_Base && Dtor->getParent()->isAbstract()) {
1401 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
1402 TrapCall->setDoesNotReturn();
1403 TrapCall->setDoesNotThrow();
1404 Builder.CreateUnreachable();
1405 Builder.ClearInsertionPoint();
1406 return;
1407 }
1408
Justin Bognerfb298222015-05-20 16:16:23 +00001409 Stmt *Body = Dtor->getBody();
1410 if (Body)
1411 incrementProfileCounter(Body);
1412
John McCallf99a6312010-07-21 05:30:47 +00001413 // The call to operator delete in a deleting destructor happens
1414 // outside of the function-try-block, which means it's always
1415 // possible to delegate the destructor body to the complete
1416 // destructor. Do so.
1417 if (DtorType == Dtor_Deleting) {
Richard Smith5b349582017-10-13 01:55:36 +00001418 RunCleanupsScope DtorEpilogue(*this);
John McCallf99a6312010-07-21 05:30:47 +00001419 EnterDtorCleanups(Dtor, Dtor_Deleting);
Richard Smith5b349582017-10-13 01:55:36 +00001420 if (HaveInsertPoint())
1421 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
1422 /*Delegating=*/false, LoadCXXThisAddress());
John McCallf99a6312010-07-21 05:30:47 +00001423 return;
1424 }
1425
John McCallb81884d2010-02-19 09:25:03 +00001426 // If the body is a function-try-block, enter the try before
John McCallf99a6312010-07-21 05:30:47 +00001427 // anything else.
1428 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallb81884d2010-02-19 09:25:03 +00001429 if (isTryBody)
John McCallb609d3f2010-07-07 06:56:46 +00001430 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00001431 EmitAsanPrologueOrEpilogue(false);
John McCallb81884d2010-02-19 09:25:03 +00001432
John McCallf99a6312010-07-21 05:30:47 +00001433 // Enter the epilogue cleanups.
1434 RunCleanupsScope DtorEpilogue(*this);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001435
John McCallb81884d2010-02-19 09:25:03 +00001436 // If this is the complete variant, just invoke the base variant;
1437 // the epilogue will destruct the virtual bases. But we can't do
1438 // this optimization if the body is a function-try-block, because
Justin Bogner1cd11f12015-05-20 15:53:59 +00001439 // we'd introduce *two* handler blocks. In the Microsoft ABI, we
Reid Klecknere7de47e2013-07-22 13:51:44 +00001440 // always delegate because we might not have a definition in this TU.
John McCallf99a6312010-07-21 05:30:47 +00001441 switch (DtorType) {
Saleem Abdulrasool8de4e872017-02-02 05:45:43 +00001442 case Dtor_Comdat: llvm_unreachable("not expecting a COMDAT");
John McCallf99a6312010-07-21 05:30:47 +00001443 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
1444
1445 case Dtor_Complete:
Reid Klecknere7de47e2013-07-22 13:51:44 +00001446 assert((Body || getTarget().getCXXABI().isMicrosoft()) &&
1447 "can't emit a dtor without a body for non-Microsoft ABIs");
1448
John McCallf99a6312010-07-21 05:30:47 +00001449 // Enter the cleanup scopes for virtual bases.
1450 EnterDtorCleanups(Dtor, Dtor_Complete);
1451
Reid Klecknere7de47e2013-07-22 13:51:44 +00001452 if (!isTryBody) {
John McCallf99a6312010-07-21 05:30:47 +00001453 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
John McCall7f416cc2015-09-08 08:05:57 +00001454 /*Delegating=*/false, LoadCXXThisAddress());
John McCallf99a6312010-07-21 05:30:47 +00001455 break;
1456 }
Saleem Abdulrasool8de4e872017-02-02 05:45:43 +00001457
John McCallf99a6312010-07-21 05:30:47 +00001458 // Fallthrough: act like we're in the base variant.
Saleem Abdulrasool8de4e872017-02-02 05:45:43 +00001459 LLVM_FALLTHROUGH;
Justin Bogner1cd11f12015-05-20 15:53:59 +00001460
John McCallf99a6312010-07-21 05:30:47 +00001461 case Dtor_Base:
Reid Klecknere7de47e2013-07-22 13:51:44 +00001462 assert(Body);
1463
John McCallf99a6312010-07-21 05:30:47 +00001464 // Enter the cleanup scopes for fields and non-virtual bases.
1465 EnterDtorCleanups(Dtor, Dtor_Base);
1466
1467 // Initialize the vtable pointers before entering the body.
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001468 if (!CanSkipVTablePointerInitialization(*this, Dtor)) {
1469 // Insert the llvm.invariant.group.barrier intrinsic before initializing
1470 // the vptrs to cancel any previous assumptions we might have made.
1471 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1472 CGM.getCodeGenOpts().OptimizationLevel > 0)
1473 CXXThisValue = Builder.CreateInvariantGroupBarrier(LoadCXXThis());
1474 InitializeVTablePointers(Dtor->getParent());
1475 }
John McCallf99a6312010-07-21 05:30:47 +00001476
1477 if (isTryBody)
1478 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
1479 else if (Body)
1480 EmitStmt(Body);
1481 else {
1482 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
1483 // nothing to do besides what's in the epilogue
1484 }
Fariborz Jahanian0c12ed12011-02-02 23:12:46 +00001485 // -fapple-kext must inline any call to this dtor into
1486 // the caller's body.
Richard Smith9c6890a2012-11-01 22:30:59 +00001487 if (getLangOpts().AppleKext)
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00001488 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
Naomi Musgravee50cb9b2015-08-13 18:35:11 +00001489
John McCallf99a6312010-07-21 05:30:47 +00001490 break;
John McCallb81884d2010-02-19 09:25:03 +00001491 }
1492
John McCallf99a6312010-07-21 05:30:47 +00001493 // Jump out through the epilogue cleanups.
1494 DtorEpilogue.ForceCleanup();
John McCallb81884d2010-02-19 09:25:03 +00001495
1496 // Exit the try if applicable.
1497 if (isTryBody)
John McCallb609d3f2010-07-07 06:56:46 +00001498 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +00001499}
1500
Lang Hamesbf122742013-02-17 07:22:09 +00001501void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) {
1502 const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
1503 const Stmt *RootS = AssignOp->getBody();
1504 assert(isa<CompoundStmt>(RootS) &&
1505 "Body of an implicit assignment operator should be compound stmt.");
1506 const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
1507
1508 LexicalScope Scope(*this, RootCS->getSourceRange());
1509
Xinliang David Lia951e8e2016-02-09 20:02:59 +00001510 incrementProfileCounter(RootCS);
Lang Hamesbf122742013-02-17 07:22:09 +00001511 AssignmentMemcpyizer AM(*this, AssignOp, Args);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001512 for (auto *I : RootCS->body())
Justin Bogner1cd11f12015-05-20 15:53:59 +00001513 AM.emitAssignment(I);
Lang Hamesbf122742013-02-17 07:22:09 +00001514 AM.finish();
1515}
1516
John McCallf99a6312010-07-21 05:30:47 +00001517namespace {
Richard Smith5b349582017-10-13 01:55:36 +00001518 llvm::Value *LoadThisForDtorDelete(CodeGenFunction &CGF,
1519 const CXXDestructorDecl *DD) {
1520 if (Expr *ThisArg = DD->getOperatorDeleteThisArg())
Haojian Wu5b5c81f2017-10-13 15:37:53 +00001521 return CGF.EmitScalarExpr(ThisArg);
Richard Smith5b349582017-10-13 01:55:36 +00001522 return CGF.LoadCXXThis();
1523 }
1524
John McCallf99a6312010-07-21 05:30:47 +00001525 /// Call the operator delete associated with the current destructor.
David Blaikie7e70d682015-08-18 22:40:54 +00001526 struct CallDtorDelete final : EHScopeStack::Cleanup {
John McCallf99a6312010-07-21 05:30:47 +00001527 CallDtorDelete() {}
1528
Craig Topper4f12f102014-03-12 06:41:41 +00001529 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallf99a6312010-07-21 05:30:47 +00001530 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1531 const CXXRecordDecl *ClassDecl = Dtor->getParent();
Richard Smith5b349582017-10-13 01:55:36 +00001532 CGF.EmitDeleteCall(Dtor->getOperatorDelete(),
1533 LoadThisForDtorDelete(CGF, Dtor),
John McCallf99a6312010-07-21 05:30:47 +00001534 CGF.getContext().getTagDeclType(ClassDecl));
1535 }
1536 };
1537
Richard Smith5b349582017-10-13 01:55:36 +00001538 void EmitConditionalDtorDeleteCall(CodeGenFunction &CGF,
1539 llvm::Value *ShouldDeleteCondition,
1540 bool ReturnAfterDelete) {
1541 llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
1542 llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
1543 llvm::Value *ShouldCallDelete
1544 = CGF.Builder.CreateIsNull(ShouldDeleteCondition);
1545 CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
1546
1547 CGF.EmitBlock(callDeleteBB);
1548 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1549 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1550 CGF.EmitDeleteCall(Dtor->getOperatorDelete(),
1551 LoadThisForDtorDelete(CGF, Dtor),
1552 CGF.getContext().getTagDeclType(ClassDecl));
1553 assert(Dtor->getOperatorDelete()->isDestroyingOperatorDelete() ==
1554 ReturnAfterDelete &&
1555 "unexpected value for ReturnAfterDelete");
1556 if (ReturnAfterDelete)
1557 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
1558 else
1559 CGF.Builder.CreateBr(continueBB);
1560
1561 CGF.EmitBlock(continueBB);
1562 }
1563
David Blaikie7e70d682015-08-18 22:40:54 +00001564 struct CallDtorDeleteConditional final : EHScopeStack::Cleanup {
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001565 llvm::Value *ShouldDeleteCondition;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001566
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001567 public:
1568 CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001569 : ShouldDeleteCondition(ShouldDeleteCondition) {
Craig Topper8a13c412014-05-21 05:09:00 +00001570 assert(ShouldDeleteCondition != nullptr);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001571 }
1572
Craig Topper4f12f102014-03-12 06:41:41 +00001573 void Emit(CodeGenFunction &CGF, Flags flags) override {
Richard Smith5b349582017-10-13 01:55:36 +00001574 EmitConditionalDtorDeleteCall(CGF, ShouldDeleteCondition,
1575 /*ReturnAfterDelete*/false);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001576 }
1577 };
1578
David Blaikie7e70d682015-08-18 22:40:54 +00001579 class DestroyField final : public EHScopeStack::Cleanup {
John McCall4bd0fb12011-07-12 16:41:08 +00001580 const FieldDecl *field;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001581 CodeGenFunction::Destroyer *destroyer;
John McCall4bd0fb12011-07-12 16:41:08 +00001582 bool useEHCleanupForArray;
John McCallf99a6312010-07-21 05:30:47 +00001583
John McCall4bd0fb12011-07-12 16:41:08 +00001584 public:
1585 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
1586 bool useEHCleanupForArray)
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001587 : field(field), destroyer(destroyer),
1588 useEHCleanupForArray(useEHCleanupForArray) {}
John McCallf99a6312010-07-21 05:30:47 +00001589
Craig Topper4f12f102014-03-12 06:41:41 +00001590 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall4bd0fb12011-07-12 16:41:08 +00001591 // Find the address of the field.
John McCall7f416cc2015-09-08 08:05:57 +00001592 Address thisValue = CGF.LoadCXXThisAddress();
Eli Friedman7f1ff602012-04-16 03:54:45 +00001593 QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
1594 LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
1595 LValue LV = CGF.EmitLValueForField(ThisLV, field);
John McCall4bd0fb12011-07-12 16:41:08 +00001596 assert(LV.isSimple());
Justin Bogner1cd11f12015-05-20 15:53:59 +00001597
John McCall4bd0fb12011-07-12 16:41:08 +00001598 CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +00001599 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCallf99a6312010-07-21 05:30:47 +00001600 }
1601 };
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001602
Naomi Musgrave703835c2015-09-16 00:38:22 +00001603 static void EmitSanitizerDtorCallback(CodeGenFunction &CGF, llvm::Value *Ptr,
1604 CharUnits::QuantityType PoisonSize) {
Matt Morehouse4881a232017-09-20 22:53:08 +00001605 CodeGenFunction::SanitizerScope SanScope(&CGF);
Naomi Musgrave703835c2015-09-16 00:38:22 +00001606 // Pass in void pointer and size of region as arguments to runtime
1607 // function
1608 llvm::Value *Args[] = {CGF.Builder.CreateBitCast(Ptr, CGF.VoidPtrTy),
1609 llvm::ConstantInt::get(CGF.SizeTy, PoisonSize)};
1610
1611 llvm::Type *ArgTypes[] = {CGF.VoidPtrTy, CGF.SizeTy};
1612
1613 llvm::FunctionType *FnType =
1614 llvm::FunctionType::get(CGF.VoidTy, ArgTypes, false);
1615 llvm::Value *Fn =
1616 CGF.CGM.CreateRuntimeFunction(FnType, "__sanitizer_dtor_callback");
1617 CGF.EmitNounwindRuntimeCall(Fn, Args);
1618 }
1619
1620 class SanitizeDtorMembers final : public EHScopeStack::Cleanup {
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001621 const CXXDestructorDecl *Dtor;
1622
1623 public:
Naomi Musgrave703835c2015-09-16 00:38:22 +00001624 SanitizeDtorMembers(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001625
1626 // Generate function call for handling object poisoning.
1627 // Disables tail call elimination, to prevent the current stack frame
1628 // from disappearing from the stack trace.
1629 void Emit(CodeGenFunction &CGF, Flags flags) override {
1630 const ASTRecordLayout &Layout =
1631 CGF.getContext().getASTRecordLayout(Dtor->getParent());
1632
1633 // Nothing to poison.
1634 if (Layout.getFieldCount() == 0)
1635 return;
1636
1637 // Prevent the current stack frame from disappearing from the stack trace.
1638 CGF.CurFn->addFnAttr("disable-tail-calls", "true");
1639
1640 // Construct pointer to region to begin poisoning, and calculate poison
1641 // size, so that only members declared in this class are poisoned.
1642 ASTContext &Context = CGF.getContext();
1643 unsigned fieldIndex = 0;
1644 int startIndex = -1;
1645 // RecordDecl::field_iterator Field;
1646 for (const FieldDecl *Field : Dtor->getParent()->fields()) {
1647 // Poison field if it is trivial
1648 if (FieldHasTrivialDestructorBody(Context, Field)) {
1649 // Start sanitizing at this field
1650 if (startIndex < 0)
1651 startIndex = fieldIndex;
1652
1653 // Currently on the last field, and it must be poisoned with the
1654 // current block.
1655 if (fieldIndex == Layout.getFieldCount() - 1) {
Naomi Musgrave703835c2015-09-16 00:38:22 +00001656 PoisonMembers(CGF, startIndex, Layout.getFieldCount());
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001657 }
1658 } else if (startIndex >= 0) {
1659 // No longer within a block of memory to poison, so poison the block
Naomi Musgrave703835c2015-09-16 00:38:22 +00001660 PoisonMembers(CGF, startIndex, fieldIndex);
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001661 // Re-set the start index
1662 startIndex = -1;
1663 }
1664 fieldIndex += 1;
1665 }
1666 }
1667
1668 private:
NAKAMURA Takumif6cef72f2015-09-04 05:19:31 +00001669 /// \param layoutStartOffset index of the ASTRecordLayout field to
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001670 /// start poisoning (inclusive)
NAKAMURA Takumif6cef72f2015-09-04 05:19:31 +00001671 /// \param layoutEndOffset index of the ASTRecordLayout field to
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001672 /// end poisoning (exclusive)
Naomi Musgrave703835c2015-09-16 00:38:22 +00001673 void PoisonMembers(CodeGenFunction &CGF, unsigned layoutStartOffset,
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001674 unsigned layoutEndOffset) {
1675 ASTContext &Context = CGF.getContext();
1676 const ASTRecordLayout &Layout =
1677 Context.getASTRecordLayout(Dtor->getParent());
1678
1679 llvm::ConstantInt *OffsetSizePtr = llvm::ConstantInt::get(
1680 CGF.SizeTy,
1681 Context.toCharUnitsFromBits(Layout.getFieldOffset(layoutStartOffset))
1682 .getQuantity());
1683
1684 llvm::Value *OffsetPtr = CGF.Builder.CreateGEP(
1685 CGF.Builder.CreateBitCast(CGF.LoadCXXThis(), CGF.Int8PtrTy),
1686 OffsetSizePtr);
1687
1688 CharUnits::QuantityType PoisonSize;
1689 if (layoutEndOffset >= Layout.getFieldCount()) {
1690 PoisonSize = Layout.getNonVirtualSize().getQuantity() -
1691 Context.toCharUnitsFromBits(
1692 Layout.getFieldOffset(layoutStartOffset))
1693 .getQuantity();
1694 } else {
1695 PoisonSize = Context.toCharUnitsFromBits(
1696 Layout.getFieldOffset(layoutEndOffset) -
1697 Layout.getFieldOffset(layoutStartOffset))
1698 .getQuantity();
1699 }
1700
1701 if (PoisonSize == 0)
1702 return;
1703
Naomi Musgrave703835c2015-09-16 00:38:22 +00001704 EmitSanitizerDtorCallback(CGF, OffsetPtr, PoisonSize);
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001705 }
1706 };
Naomi Musgrave703835c2015-09-16 00:38:22 +00001707
1708 class SanitizeDtorVTable final : public EHScopeStack::Cleanup {
1709 const CXXDestructorDecl *Dtor;
1710
1711 public:
1712 SanitizeDtorVTable(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
1713
1714 // Generate function call for handling vtable pointer poisoning.
1715 void Emit(CodeGenFunction &CGF, Flags flags) override {
1716 assert(Dtor->getParent()->isDynamicClass());
NAKAMURA Takumiee82b492015-09-16 06:26:56 +00001717 (void)Dtor;
Naomi Musgrave703835c2015-09-16 00:38:22 +00001718 ASTContext &Context = CGF.getContext();
1719 // Poison vtable and vtable ptr if they exist for this class.
1720 llvm::Value *VTablePtr = CGF.LoadCXXThis();
1721
1722 CharUnits::QuantityType PoisonSize =
1723 Context.toCharUnitsFromBits(CGF.PointerWidthInBits).getQuantity();
1724 // Pass in void pointer and size of region as arguments to runtime
1725 // function
1726 EmitSanitizerDtorCallback(CGF, VTablePtr, PoisonSize);
1727 }
1728 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00001729} // end anonymous namespace
John McCallf99a6312010-07-21 05:30:47 +00001730
Hans Wennborgdeff7032013-12-18 01:39:59 +00001731/// \brief Emit all code that comes at the end of class's
Anders Carlssonfb404882009-12-24 22:46:43 +00001732/// destructor. This is to call destructors on members and base classes
1733/// in reverse order of their construction.
Richard Smith5b349582017-10-13 01:55:36 +00001734///
1735/// For a deleting destructor, this also handles the case where a destroying
1736/// operator delete completely overrides the definition.
John McCallf99a6312010-07-21 05:30:47 +00001737void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
1738 CXXDtorType DtorType) {
Hans Wennborg853ae942014-05-30 16:59:42 +00001739 assert((!DD->isTrivial() || DD->hasAttr<DLLExportAttr>()) &&
1740 "Should not emit dtor epilogue for non-exported trivial dtor!");
Anders Carlssonfb404882009-12-24 22:46:43 +00001741
John McCallf99a6312010-07-21 05:30:47 +00001742 // The deleting-destructor phase just needs to call the appropriate
1743 // operator delete that Sema picked up.
John McCall5c60a6f2010-02-18 19:59:28 +00001744 if (DtorType == Dtor_Deleting) {
Justin Bogner1cd11f12015-05-20 15:53:59 +00001745 assert(DD->getOperatorDelete() &&
Hans Wennborgdeff7032013-12-18 01:39:59 +00001746 "operator delete missing - EnterDtorCleanups");
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001747 if (CXXStructorImplicitParamValue) {
1748 // If there is an implicit param to the deleting dtor, it's a boolean
Richard Smith5b349582017-10-13 01:55:36 +00001749 // telling whether this is a deleting destructor.
1750 if (DD->getOperatorDelete()->isDestroyingOperatorDelete())
1751 EmitConditionalDtorDeleteCall(*this, CXXStructorImplicitParamValue,
1752 /*ReturnAfterDelete*/true);
1753 else
1754 EHStack.pushCleanup<CallDtorDeleteConditional>(
1755 NormalAndEHCleanup, CXXStructorImplicitParamValue);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001756 } else {
Richard Smith5b349582017-10-13 01:55:36 +00001757 if (DD->getOperatorDelete()->isDestroyingOperatorDelete()) {
1758 const CXXRecordDecl *ClassDecl = DD->getParent();
1759 EmitDeleteCall(DD->getOperatorDelete(),
1760 LoadThisForDtorDelete(*this, DD),
1761 getContext().getTagDeclType(ClassDecl));
1762 EmitBranchThroughCleanup(ReturnBlock);
1763 } else {
1764 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
1765 }
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001766 }
John McCall5c60a6f2010-02-18 19:59:28 +00001767 return;
1768 }
1769
John McCallf99a6312010-07-21 05:30:47 +00001770 const CXXRecordDecl *ClassDecl = DD->getParent();
1771
Richard Smith20104042011-09-18 12:11:43 +00001772 // Unions have no bases and do not call field destructors.
1773 if (ClassDecl->isUnion())
1774 return;
1775
John McCallf99a6312010-07-21 05:30:47 +00001776 // The complete-destructor phase just destructs all the virtual bases.
John McCall5c60a6f2010-02-18 19:59:28 +00001777 if (DtorType == Dtor_Complete) {
Naomi Musgrave703835c2015-09-16 00:38:22 +00001778 // Poison the vtable pointer such that access after the base
1779 // and member destructors are invoked is invalid.
1780 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1781 SanOpts.has(SanitizerKind::Memory) && ClassDecl->getNumVBases() &&
1782 ClassDecl->isPolymorphic())
1783 EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
John McCallf99a6312010-07-21 05:30:47 +00001784
1785 // We push them in the forward order so that they'll be popped in
1786 // the reverse order.
Aaron Ballman445a9392014-03-13 16:15:17 +00001787 for (const auto &Base : ClassDecl->vbases()) {
John McCall5c60a6f2010-02-18 19:59:28 +00001788 CXXRecordDecl *BaseClassDecl
1789 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Justin Bogner1cd11f12015-05-20 15:53:59 +00001790
John McCall5c60a6f2010-02-18 19:59:28 +00001791 // Ignore trivial destructors.
1792 if (BaseClassDecl->hasTrivialDestructor())
1793 continue;
John McCallf99a6312010-07-21 05:30:47 +00001794
John McCallcda666c2010-07-21 07:22:38 +00001795 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1796 BaseClassDecl,
1797 /*BaseIsVirtual*/ true);
John McCall5c60a6f2010-02-18 19:59:28 +00001798 }
John McCallf99a6312010-07-21 05:30:47 +00001799
John McCall5c60a6f2010-02-18 19:59:28 +00001800 return;
1801 }
1802
1803 assert(DtorType == Dtor_Base);
Naomi Musgrave703835c2015-09-16 00:38:22 +00001804 // Poison the vtable pointer if it has no virtual bases, but inherits
1805 // virtual functions.
1806 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1807 SanOpts.has(SanitizerKind::Memory) && !ClassDecl->getNumVBases() &&
1808 ClassDecl->isPolymorphic())
1809 EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001810
John McCallf99a6312010-07-21 05:30:47 +00001811 // Destroy non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001812 for (const auto &Base : ClassDecl->bases()) {
John McCallf99a6312010-07-21 05:30:47 +00001813 // Ignore virtual bases.
1814 if (Base.isVirtual())
1815 continue;
Justin Bogner1cd11f12015-05-20 15:53:59 +00001816
John McCallf99a6312010-07-21 05:30:47 +00001817 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
Justin Bogner1cd11f12015-05-20 15:53:59 +00001818
John McCallf99a6312010-07-21 05:30:47 +00001819 // Ignore trivial destructors.
1820 if (BaseClassDecl->hasTrivialDestructor())
1821 continue;
John McCall5c60a6f2010-02-18 19:59:28 +00001822
John McCallcda666c2010-07-21 07:22:38 +00001823 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1824 BaseClassDecl,
1825 /*BaseIsVirtual*/ false);
John McCallf99a6312010-07-21 05:30:47 +00001826 }
1827
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001828 // Poison fields such that access after their destructors are
1829 // invoked, and before the base class destructor runs, is invalid.
1830 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1831 SanOpts.has(SanitizerKind::Memory))
Naomi Musgrave703835c2015-09-16 00:38:22 +00001832 EHStack.pushCleanup<SanitizeDtorMembers>(NormalAndEHCleanup, DD);
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001833
John McCallf99a6312010-07-21 05:30:47 +00001834 // Destroy direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001835 for (const auto *Field : ClassDecl->fields()) {
1836 QualType type = Field->getType();
John McCall4bd0fb12011-07-12 16:41:08 +00001837 QualType::DestructionKind dtorKind = type.isDestructedType();
1838 if (!dtorKind) continue;
John McCallf99a6312010-07-21 05:30:47 +00001839
Richard Smith921bd202012-02-26 09:11:52 +00001840 // Anonymous union members do not have their destructors called.
1841 const RecordType *RT = type->getAsUnionType();
1842 if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
1843
John McCall4bd0fb12011-07-12 16:41:08 +00001844 CleanupKind cleanupKind = getCleanupKind(dtorKind);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001845 EHStack.pushCleanup<DestroyField>(cleanupKind, Field,
John McCall4bd0fb12011-07-12 16:41:08 +00001846 getDestroyer(dtorKind),
1847 cleanupKind & EHCleanup);
Anders Carlssonfb404882009-12-24 22:46:43 +00001848 }
Anders Carlssonfb404882009-12-24 22:46:43 +00001849}
1850
John McCallf677a8e2011-07-13 06:10:41 +00001851/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1852/// constructor for each of several members of an array.
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001853///
John McCallf677a8e2011-07-13 06:10:41 +00001854/// \param ctor the constructor to call for each element
John McCallf677a8e2011-07-13 06:10:41 +00001855/// \param arrayType the type of the array to initialize
1856/// \param arrayBegin an arrayType*
1857/// \param zeroInitialize true if each element should be
1858/// zero-initialized before it is constructed
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001859void CodeGenFunction::EmitCXXAggrConstructorCall(
Alexey Bataeve7545b32016-04-29 09:39:50 +00001860 const CXXConstructorDecl *ctor, const ArrayType *arrayType,
John McCall7f416cc2015-09-08 08:05:57 +00001861 Address arrayBegin, const CXXConstructExpr *E, bool zeroInitialize) {
John McCallf677a8e2011-07-13 06:10:41 +00001862 QualType elementType;
1863 llvm::Value *numElements =
1864 emitArrayLength(arrayType, elementType, arrayBegin);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001865
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001866 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin, E, zeroInitialize);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001867}
1868
John McCallf677a8e2011-07-13 06:10:41 +00001869/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1870/// constructor for each of several members of an array.
1871///
1872/// \param ctor the constructor to call for each element
1873/// \param numElements the number of elements in the array;
John McCall6549b312011-07-13 07:37:11 +00001874/// may be zero
NAKAMURA Takumiff7a9252015-09-08 09:42:41 +00001875/// \param arrayBase a T*, where T is the type constructed by ctor
John McCallf677a8e2011-07-13 06:10:41 +00001876/// \param zeroInitialize true if each element should be
1877/// zero-initialized before it is constructed
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001878void CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1879 llvm::Value *numElements,
John McCall7f416cc2015-09-08 08:05:57 +00001880 Address arrayBase,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001881 const CXXConstructExpr *E,
1882 bool zeroInitialize) {
John McCall6549b312011-07-13 07:37:11 +00001883 // It's legal for numElements to be zero. This can happen both
1884 // dynamically, because x can be zero in 'new A[x]', and statically,
1885 // because of GCC extensions that permit zero-length arrays. There
1886 // are probably legitimate places where we could assume that this
1887 // doesn't happen, but it's not clear that it's worth it.
Craig Topper8a13c412014-05-21 05:09:00 +00001888 llvm::BranchInst *zeroCheckBranch = nullptr;
John McCall6549b312011-07-13 07:37:11 +00001889
1890 // Optimize for a constant count.
1891 llvm::ConstantInt *constantCount
1892 = dyn_cast<llvm::ConstantInt>(numElements);
1893 if (constantCount) {
1894 // Just skip out if the constant count is zero.
1895 if (constantCount->isZero()) return;
1896
1897 // Otherwise, emit the check.
1898 } else {
1899 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1900 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1901 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1902 EmitBlock(loopBB);
1903 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00001904
John McCallf677a8e2011-07-13 06:10:41 +00001905 // Find the end of the array.
John McCall7f416cc2015-09-08 08:05:57 +00001906 llvm::Value *arrayBegin = arrayBase.getPointer();
John McCallf677a8e2011-07-13 06:10:41 +00001907 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1908 "arrayctor.end");
Anders Carlsson27da15b2010-01-01 20:29:01 +00001909
John McCallf677a8e2011-07-13 06:10:41 +00001910 // Enter the loop, setting up a phi for the current location to initialize.
1911 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1912 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1913 EmitBlock(loopBB);
1914 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1915 "arrayctor.cur");
1916 cur->addIncoming(arrayBegin, entryBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001917
Anders Carlsson27da15b2010-01-01 20:29:01 +00001918 // Inside the loop body, emit the constructor call on the array element.
John McCallf677a8e2011-07-13 06:10:41 +00001919
John McCall7f416cc2015-09-08 08:05:57 +00001920 // The alignment of the base, adjusted by the size of a single element,
1921 // provides a conservative estimate of the alignment of every element.
1922 // (This assumes we never start tracking offsetted alignments.)
1923 //
1924 // Note that these are complete objects and so we don't need to
1925 // use the non-virtual size or alignment.
John McCallf677a8e2011-07-13 06:10:41 +00001926 QualType type = getContext().getTypeDeclType(ctor->getParent());
John McCall7f416cc2015-09-08 08:05:57 +00001927 CharUnits eltAlignment =
1928 arrayBase.getAlignment()
1929 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
1930 Address curAddr = Address(cur, eltAlignment);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001931
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001932 // Zero initialize the storage, if requested.
John McCallf677a8e2011-07-13 06:10:41 +00001933 if (zeroInitialize)
John McCall7f416cc2015-09-08 08:05:57 +00001934 EmitNullInitialization(curAddr, type);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001935
1936 // C++ [class.temporary]p4:
Anders Carlsson27da15b2010-01-01 20:29:01 +00001937 // There are two contexts in which temporaries are destroyed at a different
1938 // point than the end of the full-expression. The first context is when a
Justin Bogner1cd11f12015-05-20 15:53:59 +00001939 // default constructor is called to initialize an element of an array.
1940 // If the constructor has one or more default arguments, the destruction of
1941 // every temporary created in a default argument expression is sequenced
Anders Carlsson27da15b2010-01-01 20:29:01 +00001942 // before the construction of the next array element, if any.
Justin Bogner1cd11f12015-05-20 15:53:59 +00001943
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00001944 {
John McCallbd309292010-07-06 01:34:17 +00001945 RunCleanupsScope Scope(*this);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001946
John McCallf677a8e2011-07-13 06:10:41 +00001947 // Evaluate the constructor and its arguments in a regular
1948 // partial-destroy cleanup.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001949 if (getLangOpts().Exceptions &&
John McCallf677a8e2011-07-13 06:10:41 +00001950 !ctor->getParent()->hasTrivialDestructor()) {
1951 Destroyer *destroyer = destroyCXXObject;
John McCall7f416cc2015-09-08 08:05:57 +00001952 pushRegularPartialArrayCleanup(arrayBegin, cur, type, eltAlignment,
1953 *destroyer);
John McCallf677a8e2011-07-13 06:10:41 +00001954 }
1955
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001956 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/false,
John McCall7f416cc2015-09-08 08:05:57 +00001957 /*Delegating=*/false, curAddr, E);
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00001958 }
Anders Carlsson27da15b2010-01-01 20:29:01 +00001959
John McCallf677a8e2011-07-13 06:10:41 +00001960 // Go to the next element.
1961 llvm::Value *next =
1962 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
1963 "arrayctor.next");
1964 cur->addIncoming(next, Builder.GetInsertBlock());
Anders Carlsson27da15b2010-01-01 20:29:01 +00001965
John McCallf677a8e2011-07-13 06:10:41 +00001966 // Check whether that's the end of the loop.
1967 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
1968 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
1969 Builder.CreateCondBr(done, contBB, loopBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001970
John McCall6549b312011-07-13 07:37:11 +00001971 // Patch the earlier check to skip over the loop.
1972 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
1973
John McCallf677a8e2011-07-13 06:10:41 +00001974 EmitBlock(contBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001975}
1976
John McCall82fe67b2011-07-09 01:37:26 +00001977void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001978 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00001979 QualType type) {
1980 const RecordType *rtype = type->castAs<RecordType>();
1981 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
1982 const CXXDestructorDecl *dtor = record->getDestructor();
1983 assert(!dtor->isTrivial());
1984 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
Douglas Gregor61535002013-01-31 05:50:40 +00001985 /*Delegating=*/false, addr);
John McCall82fe67b2011-07-09 01:37:26 +00001986}
1987
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001988void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
1989 CXXCtorType Type,
1990 bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +00001991 bool Delegating, Address This,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001992 const CXXConstructExpr *E) {
Richard Smith5179eb72016-06-28 19:03:57 +00001993 CallArgList Args;
1994
1995 // Push the this ptr.
1996 Args.add(RValue::get(This.getPointer()), D->getThisType(getContext()));
1997
1998 // If this is a trivial constructor, emit a memcpy now before we lose
1999 // the alignment information on the argument.
2000 // FIXME: It would be better to preserve alignment information into CallArg.
2001 if (isMemcpyEquivalentSpecialMember(D)) {
2002 assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
2003
2004 const Expr *Arg = E->getArg(0);
2005 QualType SrcTy = Arg->getType();
2006 Address Src = EmitLValue(Arg).getAddress();
2007 QualType DestTy = getContext().getTypeDeclType(D->getParent());
2008 EmitAggregateCopyCtor(This, Src, DestTy, SrcTy);
2009 return;
2010 }
2011
2012 // Add the rest of the user-supplied arguments.
2013 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
Hans Wennborg27dcc6c2017-02-01 02:21:07 +00002014 EvaluationOrder Order = E->isListInitialization()
2015 ? EvaluationOrder::ForceLeftToRight
2016 : EvaluationOrder::Default;
2017 EmitCallArgs(Args, FPT, E->arguments(), E->getConstructor(),
2018 /*ParamsToSkip*/ 0, Order);
Richard Smith5179eb72016-06-28 19:03:57 +00002019
2020 EmitCXXConstructorCall(D, Type, ForVirtualBase, Delegating, This, Args);
2021}
2022
2023static bool canEmitDelegateCallArgs(CodeGenFunction &CGF,
2024 const CXXConstructorDecl *Ctor,
2025 CXXCtorType Type, CallArgList &Args) {
2026 // We can't forward a variadic call.
2027 if (Ctor->isVariadic())
2028 return false;
2029
2030 if (CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2031 // If the parameters are callee-cleanup, it's not safe to forward.
2032 for (auto *P : Ctor->parameters())
2033 if (P->getType().isDestructedType())
2034 return false;
2035
2036 // Likewise if they're inalloca.
2037 const CGFunctionInfo &Info =
George Burgess IVd0a9e802017-02-23 22:07:35 +00002038 CGF.CGM.getTypes().arrangeCXXConstructorCall(Args, Ctor, Type, 0, 0);
Richard Smith5179eb72016-06-28 19:03:57 +00002039 if (Info.usesInAlloca())
2040 return false;
2041 }
2042
2043 // Anything else should be OK.
2044 return true;
2045}
2046
2047void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
2048 CXXCtorType Type,
2049 bool ForVirtualBase,
2050 bool Delegating,
2051 Address This,
2052 CallArgList &Args) {
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002053 const CXXRecordDecl *ClassDecl = D->getParent();
2054
Richard Smith419bd092015-04-29 19:26:57 +00002055 // C++11 [class.mfct.non-static]p2:
2056 // If a non-static member function of a class X is called for an object that
2057 // is not of type X, or of a type derived from X, the behavior is undefined.
2058 // FIXME: Provide a source location here.
John McCall7f416cc2015-09-08 08:05:57 +00002059 EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall, SourceLocation(),
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002060 This.getPointer(), getContext().getRecordType(ClassDecl));
John McCallca972cd2010-02-06 00:25:16 +00002061
Richard Smith419bd092015-04-29 19:26:57 +00002062 if (D->isTrivial() && D->isDefaultConstructor()) {
Richard Smith5179eb72016-06-28 19:03:57 +00002063 assert(Args.size() == 1 && "trivial default ctor with args");
Richard Smith419bd092015-04-29 19:26:57 +00002064 return;
2065 }
2066
2067 // If this is a trivial constructor, just emit what's needed. If this is a
2068 // union copy constructor, we must emit a memcpy, because the AST does not
2069 // model that copy.
2070 if (isMemcpyEquivalentSpecialMember(D)) {
Richard Smith5179eb72016-06-28 19:03:57 +00002071 assert(Args.size() == 2 && "unexpected argcount for trivial ctor");
John McCallca972cd2010-02-06 00:25:16 +00002072
Richard Smith5179eb72016-06-28 19:03:57 +00002073 QualType SrcTy = D->getParamDecl(0)->getType().getNonReferenceType();
2074 Address Src(Args[1].RV.getScalarVal(), getNaturalTypeAlignment(SrcTy));
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002075 QualType DestTy = getContext().getTypeDeclType(ClassDecl);
David Majnemerfd1e7392015-02-03 23:04:06 +00002076 EmitAggregateCopyCtor(This, Src, DestTy, SrcTy);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002077 return;
2078 }
2079
George Burgess IVd0a9e802017-02-23 22:07:35 +00002080 bool PassPrototypeArgs = true;
Richard Smith5179eb72016-06-28 19:03:57 +00002081 // Check whether we can actually emit the constructor before trying to do so.
2082 if (auto Inherited = D->getInheritedConstructor()) {
George Burgess IVd0a9e802017-02-23 22:07:35 +00002083 PassPrototypeArgs = getTypes().inheritingCtorHasParams(Inherited, Type);
2084 if (PassPrototypeArgs && !canEmitDelegateCallArgs(*this, D, Type, Args)) {
Richard Smith5179eb72016-06-28 19:03:57 +00002085 EmitInlinedInheritingCXXConstructorCall(D, Type, ForVirtualBase,
2086 Delegating, Args);
2087 return;
2088 }
2089 }
Reid Kleckner89077a12013-12-17 19:46:40 +00002090
2091 // Insert any ABI-specific implicit constructor arguments.
George Burgess IVf203dbf2017-02-22 20:28:02 +00002092 CGCXXABI::AddedStructorArgs ExtraArgs =
2093 CGM.getCXXABI().addImplicitConstructorArgs(*this, D, Type, ForVirtualBase,
2094 Delegating, Args);
Reid Kleckner89077a12013-12-17 19:46:40 +00002095
2096 // Emit the call.
John McCallb92ab1a2016-10-26 23:46:34 +00002097 llvm::Constant *CalleePtr =
2098 CGM.getAddrOfCXXStructor(D, getFromCtorType(Type));
George Burgess IVf203dbf2017-02-22 20:28:02 +00002099 const CGFunctionInfo &Info = CGM.getTypes().arrangeCXXConstructorCall(
George Burgess IVd0a9e802017-02-23 22:07:35 +00002100 Args, D, Type, ExtraArgs.Prefix, ExtraArgs.Suffix, PassPrototypeArgs);
John McCallb92ab1a2016-10-26 23:46:34 +00002101 CGCallee Callee = CGCallee::forDirect(CalleePtr, D);
2102 EmitCall(Info, Callee, ReturnValueSlot(), Args);
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002103
2104 // Generate vtable assumptions if we're constructing a complete object
2105 // with a vtable. We don't do this for base subobjects for two reasons:
2106 // first, it's incorrect for classes with virtual bases, and second, we're
2107 // about to overwrite the vptrs anyway.
2108 // We also have to make sure if we can refer to vtable:
2109 // - Otherwise we can refer to vtable if it's safe to speculatively emit.
2110 // FIXME: If vtable is used by ctor/dtor, or if vtable is external and we are
2111 // sure that definition of vtable is not hidden,
2112 // then we are always safe to refer to it.
Piotr Padlewski69dc9712015-09-28 20:30:22 +00002113 // FIXME: It looks like InstCombine is very inefficient on dealing with
2114 // assumes. Make assumption loads require -fstrict-vtable-pointers temporarily.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002115 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2116 ClassDecl->isDynamicClass() && Type != Ctor_Base &&
Piotr Padlewski69dc9712015-09-28 20:30:22 +00002117 CGM.getCXXABI().canSpeculativelyEmitVTable(ClassDecl) &&
2118 CGM.getCodeGenOpts().StrictVTablePointers)
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002119 EmitVTableAssumptionLoads(ClassDecl, This);
2120}
2121
Richard Smith5179eb72016-06-28 19:03:57 +00002122void CodeGenFunction::EmitInheritedCXXConstructorCall(
2123 const CXXConstructorDecl *D, bool ForVirtualBase, Address This,
2124 bool InheritedFromVBase, const CXXInheritedCtorInitExpr *E) {
2125 CallArgList Args;
2126 CallArg ThisArg(RValue::get(This.getPointer()), D->getThisType(getContext()),
2127 /*NeedsCopy=*/false);
2128
2129 // Forward the parameters.
2130 if (InheritedFromVBase &&
2131 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
2132 // Nothing to do; this construction is not responsible for constructing
2133 // the base class containing the inherited constructor.
2134 // FIXME: Can we just pass undef's for the remaining arguments if we don't
2135 // have constructor variants?
2136 Args.push_back(ThisArg);
2137 } else if (!CXXInheritedCtorInitExprArgs.empty()) {
2138 // The inheriting constructor was inlined; just inject its arguments.
2139 assert(CXXInheritedCtorInitExprArgs.size() >= D->getNumParams() &&
2140 "wrong number of parameters for inherited constructor call");
2141 Args = CXXInheritedCtorInitExprArgs;
2142 Args[0] = ThisArg;
2143 } else {
2144 // The inheriting constructor was not inlined. Emit delegating arguments.
2145 Args.push_back(ThisArg);
2146 const auto *OuterCtor = cast<CXXConstructorDecl>(CurCodeDecl);
2147 assert(OuterCtor->getNumParams() == D->getNumParams());
2148 assert(!OuterCtor->isVariadic() && "should have been inlined");
2149
2150 for (const auto *Param : OuterCtor->parameters()) {
2151 assert(getContext().hasSameUnqualifiedType(
2152 OuterCtor->getParamDecl(Param->getFunctionScopeIndex())->getType(),
2153 Param->getType()));
2154 EmitDelegateCallArg(Args, Param, E->getLocation());
2155
2156 // Forward __attribute__(pass_object_size).
2157 if (Param->hasAttr<PassObjectSizeAttr>()) {
2158 auto *POSParam = SizeArguments[Param];
2159 assert(POSParam && "missing pass_object_size value for forwarding");
2160 EmitDelegateCallArg(Args, POSParam, E->getLocation());
2161 }
2162 }
2163 }
2164
2165 EmitCXXConstructorCall(D, Ctor_Base, ForVirtualBase, /*Delegating*/false,
2166 This, Args);
2167}
2168
2169void CodeGenFunction::EmitInlinedInheritingCXXConstructorCall(
2170 const CXXConstructorDecl *Ctor, CXXCtorType CtorType, bool ForVirtualBase,
2171 bool Delegating, CallArgList &Args) {
Adrian Prantlb7acfc02017-02-27 21:30:05 +00002172 GlobalDecl GD(Ctor, CtorType);
2173 InlinedInheritingConstructorScope Scope(*this, GD);
2174 ApplyInlineDebugLocation DebugScope(*this, GD);
Richard Smith5179eb72016-06-28 19:03:57 +00002175
2176 // Save the arguments to be passed to the inherited constructor.
2177 CXXInheritedCtorInitExprArgs = Args;
2178
2179 FunctionArgList Params;
2180 QualType RetType = BuildFunctionArgList(CurGD, Params);
2181 FnRetTy = RetType;
2182
2183 // Insert any ABI-specific implicit constructor arguments.
2184 CGM.getCXXABI().addImplicitConstructorArgs(*this, Ctor, CtorType,
2185 ForVirtualBase, Delegating, Args);
2186
2187 // Emit a simplified prolog. We only need to emit the implicit params.
2188 assert(Args.size() >= Params.size() && "too few arguments for call");
2189 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2190 if (I < Params.size() && isa<ImplicitParamDecl>(Params[I])) {
2191 const RValue &RV = Args[I].RV;
2192 assert(!RV.isComplex() && "complex indirect params not supported");
2193 ParamValue Val = RV.isScalar()
2194 ? ParamValue::forDirect(RV.getScalarVal())
2195 : ParamValue::forIndirect(RV.getAggregateAddress());
2196 EmitParmDecl(*Params[I], Val, I + 1);
2197 }
2198 }
2199
2200 // Create a return value slot if the ABI implementation wants one.
2201 // FIXME: This is dumb, we should ask the ABI not to try to set the return
2202 // value instead.
2203 if (!RetType->isVoidType())
2204 ReturnValue = CreateIRTemp(RetType, "retval.inhctor");
2205
2206 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
2207 CXXThisValue = CXXABIThisValue;
2208
2209 // Directly emit the constructor initializers.
2210 EmitCtorPrologue(Ctor, CtorType, Params);
2211}
2212
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002213void CodeGenFunction::EmitVTableAssumptionLoad(const VPtr &Vptr, Address This) {
2214 llvm::Value *VTableGlobal =
2215 CGM.getCXXABI().getVTableAddressPoint(Vptr.Base, Vptr.VTableClass);
2216 if (!VTableGlobal)
2217 return;
2218
2219 // We can just use the base offset in the complete class.
2220 CharUnits NonVirtualOffset = Vptr.Base.getBaseOffset();
2221
2222 if (!NonVirtualOffset.isZero())
2223 This =
2224 ApplyNonVirtualAndVirtualOffset(*this, This, NonVirtualOffset, nullptr,
2225 Vptr.VTableClass, Vptr.NearestVBase);
2226
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002227 llvm::Value *VPtrValue =
2228 GetVTablePtr(This, VTableGlobal->getType(), Vptr.VTableClass);
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002229 llvm::Value *Cmp =
2230 Builder.CreateICmpEQ(VPtrValue, VTableGlobal, "cmp.vtables");
2231 Builder.CreateAssumption(Cmp);
2232}
2233
2234void CodeGenFunction::EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl,
2235 Address This) {
2236 if (CGM.getCXXABI().doStructorsInitializeVPtrs(ClassDecl))
2237 for (const VPtr &Vptr : getVTablePointers(ClassDecl))
2238 EmitVTableAssumptionLoad(Vptr, This);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002239}
2240
John McCallf8ff7b92010-02-23 00:48:20 +00002241void
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002242CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
John McCall7f416cc2015-09-08 08:05:57 +00002243 Address This, Address Src,
2244 const CXXConstructExpr *E) {
Reid Kleckner739756c2013-12-04 19:23:12 +00002245 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
Justin Bogner1cd11f12015-05-20 15:53:59 +00002246
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002247 CallArgList Args;
Justin Bogner1cd11f12015-05-20 15:53:59 +00002248
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002249 // Push the this ptr.
John McCall7f416cc2015-09-08 08:05:57 +00002250 Args.add(RValue::get(This.getPointer()), D->getThisType(getContext()));
Justin Bogner1cd11f12015-05-20 15:53:59 +00002251
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002252 // Push the src ptr.
Alp Toker9cacbab2014-01-20 20:26:09 +00002253 QualType QT = *(FPT->param_type_begin());
Chris Lattner2192fe52011-07-18 04:24:23 +00002254 llvm::Type *t = CGM.getTypes().ConvertType(QT);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002255 Src = Builder.CreateBitCast(Src, t);
John McCall7f416cc2015-09-08 08:05:57 +00002256 Args.add(RValue::get(Src.getPointer()), QT);
Reid Kleckner739756c2013-12-04 19:23:12 +00002257
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002258 // Skip over first argument (Src).
David Blaikief05779e2015-07-21 18:37:18 +00002259 EmitCallArgs(Args, FPT, drop_begin(E->arguments(), 1), E->getConstructor(),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002260 /*ParamsToSkip*/ 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002261
Richard Smith5179eb72016-06-28 19:03:57 +00002262 EmitCXXConstructorCall(D, Ctor_Complete, false, false, This, Args);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002263}
2264
2265void
John McCallf8ff7b92010-02-23 00:48:20 +00002266CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
2267 CXXCtorType CtorType,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002268 const FunctionArgList &Args,
2269 SourceLocation Loc) {
John McCallf8ff7b92010-02-23 00:48:20 +00002270 CallArgList DelegateArgs;
2271
2272 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
2273 assert(I != E && "no parameters to constructor");
2274
2275 // this
Richard Smith5179eb72016-06-28 19:03:57 +00002276 Address This = LoadCXXThisAddress();
2277 DelegateArgs.add(RValue::get(This.getPointer()), (*I)->getType());
John McCallf8ff7b92010-02-23 00:48:20 +00002278 ++I;
2279
Richard Smith5179eb72016-06-28 19:03:57 +00002280 // FIXME: The location of the VTT parameter in the parameter list is
2281 // specific to the Itanium ABI and shouldn't be hardcoded here.
2282 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
2283 assert(I != E && "cannot skip vtt parameter, already done with args");
2284 assert((*I)->getType()->isPointerType() &&
2285 "skipping parameter not of vtt type");
2286 ++I;
John McCallf8ff7b92010-02-23 00:48:20 +00002287 }
2288
2289 // Explicit arguments.
2290 for (; I != E; ++I) {
John McCall32ea9692011-03-11 20:59:21 +00002291 const VarDecl *param = *I;
Nick Lewycky2d84e842013-10-02 02:29:49 +00002292 // FIXME: per-argument source location
2293 EmitDelegateCallArg(DelegateArgs, param, Loc);
John McCallf8ff7b92010-02-23 00:48:20 +00002294 }
2295
Richard Smith5179eb72016-06-28 19:03:57 +00002296 EmitCXXConstructorCall(Ctor, CtorType, /*ForVirtualBase=*/false,
2297 /*Delegating=*/true, This, DelegateArgs);
John McCallf8ff7b92010-02-23 00:48:20 +00002298}
2299
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002300namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002301 struct CallDelegatingCtorDtor final : EHScopeStack::Cleanup {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002302 const CXXDestructorDecl *Dtor;
John McCall7f416cc2015-09-08 08:05:57 +00002303 Address Addr;
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002304 CXXDtorType Type;
2305
John McCall7f416cc2015-09-08 08:05:57 +00002306 CallDelegatingCtorDtor(const CXXDestructorDecl *D, Address Addr,
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002307 CXXDtorType Type)
2308 : Dtor(D), Addr(Addr), Type(Type) {}
2309
Craig Topper4f12f102014-03-12 06:41:41 +00002310 void Emit(CodeGenFunction &CGF, Flags flags) override {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002311 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
Douglas Gregor61535002013-01-31 05:50:40 +00002312 /*Delegating=*/true, Addr);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002313 }
2314 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00002315} // end anonymous namespace
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002316
Alexis Hunt61bc1732011-05-01 07:04:31 +00002317void
2318CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
2319 const FunctionArgList &Args) {
2320 assert(Ctor->isDelegatingConstructor());
2321
John McCall7f416cc2015-09-08 08:05:57 +00002322 Address ThisPtr = LoadCXXThisAddress();
Alexis Hunt61bc1732011-05-01 07:04:31 +00002323
John McCall31168b02011-06-15 23:02:42 +00002324 AggValueSlot AggSlot =
John McCall7f416cc2015-09-08 08:05:57 +00002325 AggValueSlot::forAddr(ThisPtr, Qualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +00002326 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00002327 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00002328 AggValueSlot::IsNotAliased);
Alexis Hunt61bc1732011-05-01 07:04:31 +00002329
2330 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
Alexis Hunt61bc1732011-05-01 07:04:31 +00002331
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002332 const CXXRecordDecl *ClassDecl = Ctor->getParent();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002333 if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002334 CXXDtorType Type =
2335 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
2336
2337 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
2338 ClassDecl->getDestructor(),
2339 ThisPtr, Type);
2340 }
2341}
Alexis Hunt61bc1732011-05-01 07:04:31 +00002342
Anders Carlsson27da15b2010-01-01 20:29:01 +00002343void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
2344 CXXDtorType Type,
Anders Carlssonf8a71f02010-05-02 23:29:11 +00002345 bool ForVirtualBase,
Douglas Gregor61535002013-01-31 05:50:40 +00002346 bool Delegating,
John McCall7f416cc2015-09-08 08:05:57 +00002347 Address This) {
Reid Kleckner6fe771a2013-12-13 00:53:54 +00002348 CGM.getCXXABI().EmitDestructorCall(*this, DD, Type, ForVirtualBase,
2349 Delegating, This);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002350}
2351
John McCall53cad2e2010-07-21 01:41:18 +00002352namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002353 struct CallLocalDtor final : EHScopeStack::Cleanup {
John McCall53cad2e2010-07-21 01:41:18 +00002354 const CXXDestructorDecl *Dtor;
John McCall7f416cc2015-09-08 08:05:57 +00002355 Address Addr;
John McCall53cad2e2010-07-21 01:41:18 +00002356
John McCall7f416cc2015-09-08 08:05:57 +00002357 CallLocalDtor(const CXXDestructorDecl *D, Address Addr)
John McCall53cad2e2010-07-21 01:41:18 +00002358 : Dtor(D), Addr(Addr) {}
2359
Craig Topper4f12f102014-03-12 06:41:41 +00002360 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall53cad2e2010-07-21 01:41:18 +00002361 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +00002362 /*ForVirtualBase=*/false,
2363 /*Delegating=*/false, Addr);
John McCall53cad2e2010-07-21 01:41:18 +00002364 }
2365 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002366} // end anonymous namespace
John McCall53cad2e2010-07-21 01:41:18 +00002367
John McCall8680f872010-07-21 06:29:51 +00002368void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
John McCall7f416cc2015-09-08 08:05:57 +00002369 Address Addr) {
John McCallcda666c2010-07-21 07:22:38 +00002370 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
John McCall8680f872010-07-21 06:29:51 +00002371}
2372
John McCall7f416cc2015-09-08 08:05:57 +00002373void CodeGenFunction::PushDestructorCleanup(QualType T, Address Addr) {
John McCallbd309292010-07-06 01:34:17 +00002374 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
2375 if (!ClassDecl) return;
2376 if (ClassDecl->hasTrivialDestructor()) return;
2377
2378 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCalla85af562011-04-28 02:15:35 +00002379 assert(D && D->isUsed() && "destructor not marked as used!");
John McCall8680f872010-07-21 06:29:51 +00002380 PushDestructorCleanup(D, Addr);
John McCallbd309292010-07-06 01:34:17 +00002381}
2382
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002383void CodeGenFunction::InitializeVTablePointer(const VPtr &Vptr) {
Anders Carlssone87fae92010-03-28 19:40:00 +00002384 // Compute the address point.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002385 llvm::Value *VTableAddressPoint =
2386 CGM.getCXXABI().getVTableAddressPointInStructor(
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002387 *this, Vptr.VTableClass, Vptr.Base, Vptr.NearestVBase);
2388
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002389 if (!VTableAddressPoint)
2390 return;
Anders Carlssone87fae92010-03-28 19:40:00 +00002391
Anders Carlsson6a0227d2010-04-20 16:22:16 +00002392 // Compute where to store the address point.
Craig Topper8a13c412014-05-21 05:09:00 +00002393 llvm::Value *VirtualOffset = nullptr;
Ken Dyckcfc332c2011-03-23 00:45:26 +00002394 CharUnits NonVirtualOffset = CharUnits::Zero();
Justin Bogner1cd11f12015-05-20 15:53:59 +00002395
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002396 if (CGM.getCXXABI().isVirtualOffsetNeededForVTableField(*this, Vptr)) {
Anders Carlsson91baecf2010-04-20 18:05:10 +00002397 // We need to use the virtual base offset offset because the virtual base
2398 // might have a different offset in the most derived class.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002399
2400 VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(
2401 *this, LoadCXXThisAddress(), Vptr.VTableClass, Vptr.NearestVBase);
2402 NonVirtualOffset = Vptr.OffsetFromNearestVBase;
Anders Carlsson91baecf2010-04-20 18:05:10 +00002403 } else {
Anders Carlssonc58fb552010-05-03 00:29:58 +00002404 // We can just use the base offset in the complete class.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002405 NonVirtualOffset = Vptr.Base.getBaseOffset();
Anders Carlsson91baecf2010-04-20 18:05:10 +00002406 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002407
Anders Carlssonc58fb552010-05-03 00:29:58 +00002408 // Apply the offsets.
John McCall7f416cc2015-09-08 08:05:57 +00002409 Address VTableField = LoadCXXThisAddress();
Justin Bogner1cd11f12015-05-20 15:53:59 +00002410
Ken Dyckcfc332c2011-03-23 00:45:26 +00002411 if (!NonVirtualOffset.isZero() || VirtualOffset)
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002412 VTableField = ApplyNonVirtualAndVirtualOffset(
2413 *this, VTableField, NonVirtualOffset, VirtualOffset, Vptr.VTableClass,
2414 Vptr.NearestVBase);
Anders Carlsson6a0227d2010-04-20 16:22:16 +00002415
Reid Kleckner8d585132014-12-03 21:00:21 +00002416 // Finally, store the address point. Use the same LLVM types as the field to
2417 // support optimization.
2418 llvm::Type *VTablePtrTy =
2419 llvm::FunctionType::get(CGM.Int32Ty, /*isVarArg=*/true)
2420 ->getPointerTo()
2421 ->getPointerTo();
2422 VTableField = Builder.CreateBitCast(VTableField, VTablePtrTy->getPointerTo());
2423 VTableAddressPoint = Builder.CreateBitCast(VTableAddressPoint, VTablePtrTy);
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002424
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002425 llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
Ivan A. Kosarev4e50e702017-11-27 09:39:29 +00002426 TBAAAccessInfo TBAAInfo = CGM.getTBAAVTablePtrAccessInfo(VTablePtrTy);
2427 CGM.DecorateInstructionWithTBAA(Store, TBAAInfo);
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002428 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2429 CGM.getCodeGenOpts().StrictVTablePointers)
2430 CGM.DecorateInstructionWithInvariantGroup(Store, Vptr.VTableClass);
Anders Carlssone87fae92010-03-28 19:40:00 +00002431}
2432
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002433CodeGenFunction::VPtrsVector
2434CodeGenFunction::getVTablePointers(const CXXRecordDecl *VTableClass) {
2435 CodeGenFunction::VPtrsVector VPtrsResult;
2436 VisitedVirtualBasesSetTy VBases;
2437 getVTablePointers(BaseSubobject(VTableClass, CharUnits::Zero()),
2438 /*NearestVBase=*/nullptr,
2439 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
2440 /*BaseIsNonVirtualPrimaryBase=*/false, VTableClass, VBases,
2441 VPtrsResult);
2442 return VPtrsResult;
2443}
2444
2445void CodeGenFunction::getVTablePointers(BaseSubobject Base,
2446 const CXXRecordDecl *NearestVBase,
2447 CharUnits OffsetFromNearestVBase,
2448 bool BaseIsNonVirtualPrimaryBase,
2449 const CXXRecordDecl *VTableClass,
2450 VisitedVirtualBasesSetTy &VBases,
2451 VPtrsVector &Vptrs) {
Anders Carlssond5895932010-03-28 21:07:49 +00002452 // If this base is a non-virtual primary base the address point has already
2453 // been set.
2454 if (!BaseIsNonVirtualPrimaryBase) {
2455 // Initialize the vtable pointer for this base.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002456 VPtr Vptr = {Base, NearestVBase, OffsetFromNearestVBase, VTableClass};
2457 Vptrs.push_back(Vptr);
Anders Carlssond5895932010-03-28 21:07:49 +00002458 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002459
Anders Carlssond5895932010-03-28 21:07:49 +00002460 const CXXRecordDecl *RD = Base.getBase();
2461
2462 // Traverse bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00002463 for (const auto &I : RD->bases()) {
Anders Carlssond5895932010-03-28 21:07:49 +00002464 CXXRecordDecl *BaseDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00002465 = cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Anders Carlssond5895932010-03-28 21:07:49 +00002466
2467 // Ignore classes without a vtable.
2468 if (!BaseDecl->isDynamicClass())
2469 continue;
2470
Ken Dyck3fb4c892011-03-23 01:04:18 +00002471 CharUnits BaseOffset;
2472 CharUnits BaseOffsetFromNearestVBase;
Anders Carlsson948d3f42010-03-29 01:16:41 +00002473 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlssond5895932010-03-28 21:07:49 +00002474
Aaron Ballman574705e2014-03-13 15:41:46 +00002475 if (I.isVirtual()) {
Anders Carlssond5895932010-03-28 21:07:49 +00002476 // Check if we've visited this virtual base before.
David Blaikie82e95a32014-11-19 07:49:47 +00002477 if (!VBases.insert(BaseDecl).second)
Anders Carlssond5895932010-03-28 21:07:49 +00002478 continue;
2479
Justin Bogner1cd11f12015-05-20 15:53:59 +00002480 const ASTRecordLayout &Layout =
Anders Carlssond5895932010-03-28 21:07:49 +00002481 getContext().getASTRecordLayout(VTableClass);
2482
Ken Dyck3fb4c892011-03-23 01:04:18 +00002483 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
2484 BaseOffsetFromNearestVBase = CharUnits::Zero();
Anders Carlsson948d3f42010-03-29 01:16:41 +00002485 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlssond5895932010-03-28 21:07:49 +00002486 } else {
2487 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
2488
Ken Dyck16ffcac2011-03-24 01:21:01 +00002489 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
Justin Bogner1cd11f12015-05-20 15:53:59 +00002490 BaseOffsetFromNearestVBase =
Ken Dyck3fb4c892011-03-23 01:04:18 +00002491 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson948d3f42010-03-29 01:16:41 +00002492 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlssond5895932010-03-28 21:07:49 +00002493 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002494
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002495 getVTablePointers(
2496 BaseSubobject(BaseDecl, BaseOffset),
2497 I.isVirtual() ? BaseDecl : NearestVBase, BaseOffsetFromNearestVBase,
2498 BaseDeclIsNonVirtualPrimaryBase, VTableClass, VBases, Vptrs);
Anders Carlssond5895932010-03-28 21:07:49 +00002499 }
2500}
2501
2502void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
2503 // Ignore classes without a vtable.
Anders Carlsson1f9348c2010-03-26 04:39:42 +00002504 if (!RD->isDynamicClass())
Anders Carlsson27da15b2010-01-01 20:29:01 +00002505 return;
2506
Anders Carlssond5895932010-03-28 21:07:49 +00002507 // Initialize the vtable pointers for this class and all of its bases.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002508 if (CGM.getCXXABI().doStructorsInitializeVPtrs(RD))
2509 for (const VPtr &Vptr : getVTablePointers(RD))
2510 InitializeVTablePointer(Vptr);
Timur Iskhodzhanovb6487322013-10-09 18:16:58 +00002511
2512 if (RD->getNumVBases())
2513 CGM.getCXXABI().initializeHiddenVirtualInheritanceMembers(*this, RD);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002514}
Dan Gohman8fc50c22010-10-26 18:44:08 +00002515
John McCall7f416cc2015-09-08 08:05:57 +00002516llvm::Value *CodeGenFunction::GetVTablePtr(Address This,
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002517 llvm::Type *VTableTy,
2518 const CXXRecordDecl *RD) {
2519 Address VTablePtrSrc = Builder.CreateElementBitCast(This, VTableTy);
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002520 llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
Ivan A. Kosarev4e50e702017-11-27 09:39:29 +00002521 TBAAAccessInfo TBAAInfo = CGM.getTBAAVTablePtrAccessInfo(VTableTy);
2522 CGM.DecorateInstructionWithTBAA(VTable, TBAAInfo);
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002523
2524 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2525 CGM.getCodeGenOpts().StrictVTablePointers)
2526 CGM.DecorateInstructionWithInvariantGroup(VTable, RD);
2527
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002528 return VTable;
Dan Gohman8fc50c22010-10-26 18:44:08 +00002529}
Anders Carlssonc36783e2011-05-08 20:32:23 +00002530
Peter Collingbourned2926c92015-03-14 02:42:25 +00002531// If a class has a single non-virtual base and does not introduce or override
2532// virtual member functions or fields, it will have the same layout as its base.
2533// This function returns the least derived such class.
2534//
2535// Casting an instance of a base class to such a derived class is technically
2536// undefined behavior, but it is a relatively common hack for introducing member
2537// functions on class instances with specific properties (e.g. llvm::Operator)
2538// that works under most compilers and should not have security implications, so
2539// we allow it by default. It can be disabled with -fsanitize=cfi-cast-strict.
2540static const CXXRecordDecl *
2541LeastDerivedClassWithSameLayout(const CXXRecordDecl *RD) {
2542 if (!RD->field_empty())
2543 return RD;
2544
2545 if (RD->getNumVBases() != 0)
2546 return RD;
2547
2548 if (RD->getNumBases() != 1)
2549 return RD;
2550
2551 for (const CXXMethodDecl *MD : RD->methods()) {
2552 if (MD->isVirtual()) {
2553 // Virtual member functions are only ok if they are implicit destructors
2554 // because the implicit destructor will have the same semantics as the
2555 // base class's destructor if no fields are added.
2556 if (isa<CXXDestructorDecl>(MD) && MD->isImplicit())
2557 continue;
2558 return RD;
2559 }
2560 }
2561
2562 return LeastDerivedClassWithSameLayout(
2563 RD->bases_begin()->getType()->getAsCXXRecordDecl());
2564}
2565
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002566void CodeGenFunction::EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD,
2567 llvm::Value *VTable,
2568 SourceLocation Loc) {
Peter Collingbourne396943a2017-07-31 22:35:33 +00002569 if (SanOpts.has(SanitizerKind::CFIVCall))
2570 EmitVTablePtrCheckForCall(RD, VTable, CodeGenFunction::CFITCK_VCall, Loc);
2571 else if (CGM.getCodeGenOpts().WholeProgramVTables &&
2572 CGM.HasHiddenLTOVisibility(RD)) {
Peter Collingbournefb532b92016-02-24 20:46:36 +00002573 llvm::Metadata *MD =
2574 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002575 llvm::Value *TypeId =
Peter Collingbournefb532b92016-02-24 20:46:36 +00002576 llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD);
2577
2578 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002579 llvm::Value *TypeTest =
2580 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
2581 {CastedVTable, TypeId});
2582 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::assume), TypeTest);
Peter Collingbournefb532b92016-02-24 20:46:36 +00002583 }
Peter Collingbournefb532b92016-02-24 20:46:36 +00002584}
2585
2586void CodeGenFunction::EmitVTablePtrCheckForCall(const CXXRecordDecl *RD,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002587 llvm::Value *VTable,
2588 CFITypeCheckKind TCK,
2589 SourceLocation Loc) {
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002590 if (!SanOpts.has(SanitizerKind::CFICastStrict))
Peter Collingbournefb532b92016-02-24 20:46:36 +00002591 RD = LeastDerivedClassWithSameLayout(RD);
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002592
Peter Collingbournefb532b92016-02-24 20:46:36 +00002593 EmitVTablePtrCheck(RD, VTable, TCK, Loc);
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002594}
2595
Peter Collingbourned2926c92015-03-14 02:42:25 +00002596void CodeGenFunction::EmitVTablePtrCheckForCast(QualType T,
2597 llvm::Value *Derived,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002598 bool MayBeNull,
2599 CFITypeCheckKind TCK,
2600 SourceLocation Loc) {
Peter Collingbourned2926c92015-03-14 02:42:25 +00002601 if (!getLangOpts().CPlusPlus)
2602 return;
2603
2604 auto *ClassTy = T->getAs<RecordType>();
2605 if (!ClassTy)
2606 return;
2607
2608 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassTy->getDecl());
2609
2610 if (!ClassDecl->isCompleteDefinition() || !ClassDecl->isDynamicClass())
2611 return;
2612
Peter Collingbourned2926c92015-03-14 02:42:25 +00002613 if (!SanOpts.has(SanitizerKind::CFICastStrict))
2614 ClassDecl = LeastDerivedClassWithSameLayout(ClassDecl);
2615
Hans Wennborgdcfba332015-10-06 23:40:43 +00002616 llvm::BasicBlock *ContBlock = nullptr;
Peter Collingbourned2926c92015-03-14 02:42:25 +00002617
2618 if (MayBeNull) {
2619 llvm::Value *DerivedNotNull =
2620 Builder.CreateIsNotNull(Derived, "cast.nonnull");
2621
2622 llvm::BasicBlock *CheckBlock = createBasicBlock("cast.check");
2623 ContBlock = createBasicBlock("cast.cont");
2624
2625 Builder.CreateCondBr(DerivedNotNull, CheckBlock, ContBlock);
2626
2627 EmitBlock(CheckBlock);
2628 }
2629
Peter Collingbourne60108802017-12-13 21:53:04 +00002630 llvm::Value *VTable;
2631 std::tie(VTable, ClassDecl) = CGM.getCXXABI().LoadVTablePtr(
2632 *this, Address(Derived, getPointerAlign()), ClassDecl);
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002633
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002634 EmitVTablePtrCheck(ClassDecl, VTable, TCK, Loc);
Peter Collingbourned2926c92015-03-14 02:42:25 +00002635
2636 if (MayBeNull) {
2637 Builder.CreateBr(ContBlock);
2638 EmitBlock(ContBlock);
2639 }
2640}
2641
2642void CodeGenFunction::EmitVTablePtrCheck(const CXXRecordDecl *RD,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002643 llvm::Value *VTable,
2644 CFITypeCheckKind TCK,
2645 SourceLocation Loc) {
Peter Collingbourne3afb2662016-04-28 17:09:37 +00002646 if (!CGM.getCodeGenOpts().SanitizeCfiCrossDso &&
2647 !CGM.HasHiddenLTOVisibility(RD))
2648 return;
2649
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002650 SanitizerMask M;
Peter Collingbournedc134532016-01-16 00:31:22 +00002651 llvm::SanitizerStatKind SSK;
2652 switch (TCK) {
2653 case CFITCK_VCall:
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002654 M = SanitizerKind::CFIVCall;
Peter Collingbournedc134532016-01-16 00:31:22 +00002655 SSK = llvm::SanStat_CFI_VCall;
2656 break;
2657 case CFITCK_NVCall:
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002658 M = SanitizerKind::CFINVCall;
Peter Collingbournedc134532016-01-16 00:31:22 +00002659 SSK = llvm::SanStat_CFI_NVCall;
2660 break;
2661 case CFITCK_DerivedCast:
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002662 M = SanitizerKind::CFIDerivedCast;
Peter Collingbournedc134532016-01-16 00:31:22 +00002663 SSK = llvm::SanStat_CFI_DerivedCast;
2664 break;
2665 case CFITCK_UnrelatedCast:
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002666 M = SanitizerKind::CFIUnrelatedCast;
Peter Collingbournedc134532016-01-16 00:31:22 +00002667 SSK = llvm::SanStat_CFI_UnrelatedCast;
2668 break;
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002669 case CFITCK_ICall:
2670 llvm_unreachable("not expecting CFITCK_ICall");
Peter Collingbournedc134532016-01-16 00:31:22 +00002671 }
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002672
2673 std::string TypeName = RD->getQualifiedNameAsString();
2674 if (getContext().getSanitizerBlacklist().isBlacklistedType(M, TypeName))
2675 return;
2676
2677 SanitizerScope SanScope(this);
Peter Collingbournedc134532016-01-16 00:31:22 +00002678 EmitSanitizerStatReport(SSK);
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002679
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002680 llvm::Metadata *MD =
2681 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002682 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002683
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002684 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002685 llvm::Value *TypeTest = Builder.CreateCall(
2686 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, TypeId});
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002687
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002688 llvm::Constant *StaticData[] = {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002689 llvm::ConstantInt::get(Int8Ty, TCK),
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002690 EmitCheckSourceLocation(Loc),
2691 EmitCheckTypeDescriptor(QualType(RD->getTypeForDecl(), 0)),
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002692 };
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002693
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002694 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
2695 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
2696 EmitCfiSlowPathCheck(M, TypeTest, CrossDsoTypeId, CastedVTable, StaticData);
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002697 return;
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002698 }
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002699
2700 if (CGM.getCodeGenOpts().SanitizeTrap.has(M)) {
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002701 EmitTrapCheck(TypeTest);
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002702 return;
2703 }
2704
2705 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
2706 CGM.getLLVMContext(),
2707 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002708 llvm::Value *ValidVtable = Builder.CreateCall(
2709 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, AllVtables});
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002710 EmitCheck(std::make_pair(TypeTest, M), SanitizerHandler::CFICheckFail,
2711 StaticData, {CastedVTable, ValidVtable});
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002712}
Anders Carlssonc36783e2011-05-08 20:32:23 +00002713
Peter Collingbourne0ca03632016-06-25 00:24:06 +00002714bool CodeGenFunction::ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD) {
2715 if (!CGM.getCodeGenOpts().WholeProgramVTables ||
2716 !SanOpts.has(SanitizerKind::CFIVCall) ||
2717 !CGM.getCodeGenOpts().SanitizeTrap.has(SanitizerKind::CFIVCall) ||
2718 !CGM.HasHiddenLTOVisibility(RD))
2719 return false;
2720
2721 std::string TypeName = RD->getQualifiedNameAsString();
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002722 return !getContext().getSanitizerBlacklist().isBlacklistedType(
2723 SanitizerKind::CFIVCall, TypeName);
Peter Collingbourne0ca03632016-06-25 00:24:06 +00002724}
2725
2726llvm::Value *CodeGenFunction::EmitVTableTypeCheckedLoad(
2727 const CXXRecordDecl *RD, llvm::Value *VTable, uint64_t VTableByteOffset) {
2728 SanitizerScope SanScope(this);
2729
2730 EmitSanitizerStatReport(llvm::SanStat_CFI_VCall);
2731
2732 llvm::Metadata *MD =
2733 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
2734 llvm::Value *TypeId = llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD);
2735
2736 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
2737 llvm::Value *CheckedLoad = Builder.CreateCall(
2738 CGM.getIntrinsic(llvm::Intrinsic::type_checked_load),
2739 {CastedVTable, llvm::ConstantInt::get(Int32Ty, VTableByteOffset),
2740 TypeId});
2741 llvm::Value *CheckResult = Builder.CreateExtractValue(CheckedLoad, 1);
2742
2743 EmitCheck(std::make_pair(CheckResult, SanitizerKind::CFIVCall),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002744 SanitizerHandler::CFICheckFail, nullptr, nullptr);
Peter Collingbourne0ca03632016-06-25 00:24:06 +00002745
2746 return Builder.CreateBitCast(
2747 Builder.CreateExtractValue(CheckedLoad, 0),
2748 cast<llvm::PointerType>(VTable->getType())->getElementType());
2749}
2750
Faisal Vali571df122013-09-29 08:45:24 +00002751void CodeGenFunction::EmitForwardingCallToLambda(
2752 const CXXMethodDecl *callOperator,
2753 CallArgList &callArgs) {
Eli Friedman5b446882012-02-16 03:47:28 +00002754 // Get the address of the call operator.
John McCall8dda7b22012-07-07 06:41:13 +00002755 const CGFunctionInfo &calleeFnInfo =
2756 CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
John McCallb92ab1a2016-10-26 23:46:34 +00002757 llvm::Constant *calleePtr =
John McCall8dda7b22012-07-07 06:41:13 +00002758 CGM.GetAddrOfFunction(GlobalDecl(callOperator),
2759 CGM.getTypes().GetFunctionType(calleeFnInfo));
Eli Friedman5b446882012-02-16 03:47:28 +00002760
John McCall8dda7b22012-07-07 06:41:13 +00002761 // Prepare the return slot.
2762 const FunctionProtoType *FPT =
2763 callOperator->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00002764 QualType resultType = FPT->getReturnType();
John McCall8dda7b22012-07-07 06:41:13 +00002765 ReturnValueSlot returnSlot;
2766 if (!resultType->isVoidType() &&
2767 calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
John McCall47fb9502013-03-07 21:37:08 +00002768 !hasScalarEvaluationKind(calleeFnInfo.getReturnType()))
John McCall8dda7b22012-07-07 06:41:13 +00002769 returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
2770
2771 // We don't need to separately arrange the call arguments because
2772 // the call can't be variadic anyway --- it's impossible to forward
2773 // variadic arguments.
Justin Bogner1cd11f12015-05-20 15:53:59 +00002774
Eli Friedman5b446882012-02-16 03:47:28 +00002775 // Now emit our call.
John McCallb92ab1a2016-10-26 23:46:34 +00002776 auto callee = CGCallee::forDirect(calleePtr, callOperator);
2777 RValue RV = EmitCall(calleeFnInfo, callee, returnSlot, callArgs);
Eli Friedman5b446882012-02-16 03:47:28 +00002778
John McCall8dda7b22012-07-07 06:41:13 +00002779 // If necessary, copy the returned value into the slot.
2780 if (!resultType->isVoidType() && returnSlot.isNull())
2781 EmitReturnOfRValue(RV, resultType);
Eli Friedmanf5f4d2f2012-12-13 23:37:17 +00002782 else
2783 EmitBranchThroughCleanup(ReturnBlock);
Eli Friedman5b446882012-02-16 03:47:28 +00002784}
2785
Eli Friedman2495ab02012-02-25 02:48:22 +00002786void CodeGenFunction::EmitLambdaBlockInvokeBody() {
2787 const BlockDecl *BD = BlockInfo->getBlockDecl();
2788 const VarDecl *variable = BD->capture_begin()->getVariable();
2789 const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
Reid Kleckner2d3c4212017-08-04 22:38:06 +00002790 const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
2791
2792 if (CallOp->isVariadic()) {
2793 // FIXME: Making this work correctly is nasty because it requires either
2794 // cloning the body of the call operator or making the call operator
2795 // forward.
2796 CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function");
2797 return;
2798 }
Eli Friedman2495ab02012-02-25 02:48:22 +00002799
2800 // Start building arguments for forwarding call
2801 CallArgList CallArgs;
2802
2803 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
John McCall7f416cc2015-09-08 08:05:57 +00002804 Address ThisPtr = GetAddrOfBlockDecl(variable, false);
2805 CallArgs.add(RValue::get(ThisPtr.getPointer()), ThisType);
Eli Friedman2495ab02012-02-25 02:48:22 +00002806
2807 // Add the rest of the parameters.
David Majnemer59f77922016-06-24 04:05:48 +00002808 for (auto param : BD->parameters())
Nick Lewycky2d84e842013-10-02 02:29:49 +00002809 EmitDelegateCallArg(CallArgs, param, param->getLocStart());
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00002810
Justin Bogner1cd11f12015-05-20 15:53:59 +00002811 assert(!Lambda->isGenericLambda() &&
Faisal Vali571df122013-09-29 08:45:24 +00002812 "generic lambda interconversion to block not implemented");
Reid Kleckner2d3c4212017-08-04 22:38:06 +00002813 EmitForwardingCallToLambda(CallOp, CallArgs);
Eli Friedman2495ab02012-02-25 02:48:22 +00002814}
2815
2816void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
2817 const CXXRecordDecl *Lambda = MD->getParent();
2818
2819 // Start building arguments for forwarding call
2820 CallArgList CallArgs;
2821
2822 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2823 llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
2824 CallArgs.add(RValue::get(ThisPtr), ThisType);
2825
2826 // Add the rest of the parameters.
David Majnemer59f77922016-06-24 04:05:48 +00002827 for (auto Param : MD->parameters())
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002828 EmitDelegateCallArg(CallArgs, Param, Param->getLocStart());
2829
Faisal Vali571df122013-09-29 08:45:24 +00002830 const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
2831 // For a generic lambda, find the corresponding call operator specialization
2832 // to which the call to the static-invoker shall be forwarded.
2833 if (Lambda->isGenericLambda()) {
2834 assert(MD->isFunctionTemplateSpecialization());
2835 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
2836 FunctionTemplateDecl *CallOpTemplate = CallOp->getDescribedFunctionTemplate();
Craig Topper8a13c412014-05-21 05:09:00 +00002837 void *InsertPos = nullptr;
Justin Bogner1cd11f12015-05-20 15:53:59 +00002838 FunctionDecl *CorrespondingCallOpSpecialization =
Craig Topper7e0daca2014-06-26 04:58:53 +00002839 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
Faisal Vali571df122013-09-29 08:45:24 +00002840 assert(CorrespondingCallOpSpecialization);
2841 CallOp = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
2842 }
2843 EmitForwardingCallToLambda(CallOp, CallArgs);
Eli Friedman2495ab02012-02-25 02:48:22 +00002844}
2845
Reid Kleckner2d3c4212017-08-04 22:38:06 +00002846void CodeGenFunction::EmitLambdaStaticInvokeBody(const CXXMethodDecl *MD) {
Douglas Gregor355efbb2012-02-17 03:02:34 +00002847 if (MD->isVariadic()) {
Eli Friedman5b446882012-02-16 03:47:28 +00002848 // FIXME: Making this work correctly is nasty because it requires either
2849 // cloning the body of the call operator or making the call operator forward.
2850 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
Eli Friedman2495ab02012-02-25 02:48:22 +00002851 return;
Eli Friedman5b446882012-02-16 03:47:28 +00002852 }
2853
Douglas Gregor355efbb2012-02-17 03:02:34 +00002854 EmitLambdaDelegatingInvokeBody(MD);
Eli Friedman5a6d5072012-02-16 01:37:33 +00002855}