blob: 45ef0f52b016626cbf31c96fe6140dc010aa31bc [file] [log] [blame]
Anders Carlsson59486a22009-11-24 05:51:11 +00001//===--- CGClass.cpp - Emit LLVM Code for C++ classes ---------------------===//
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"
Devang Patelb6ed3692011-02-22 20:55:26 +000026#include "clang/Frontend/CodeGenOptions.h"
Peter Collingbournea4ccff32015-02-20 20:30:56 +000027#include "llvm/IR/Intrinsics.h"
Anders Carlssonc6d171e2009-10-06 22:43:30 +000028
Anders Carlsson9a57c5a2009-09-12 04:27:24 +000029using namespace clang;
30using namespace CodeGen;
31
John McCall7f416cc2015-09-08 08:05:57 +000032/// Return the best known alignment for an unknown pointer to a
33/// particular class.
34CharUnits CodeGenModule::getClassPointerAlignment(const CXXRecordDecl *RD) {
35 if (!RD->isCompleteDefinition())
36 return CharUnits::One(); // Hopefully won't be used anywhere.
37
38 auto &layout = getContext().getASTRecordLayout(RD);
39
40 // If the class is final, then we know that the pointer points to an
41 // object of that type and can use the full alignment.
42 if (RD->hasAttr<FinalAttr>()) {
43 return layout.getAlignment();
44
45 // Otherwise, we have to assume it could be a subclass.
46 } else {
47 return layout.getNonVirtualAlignment();
48 }
49}
50
51/// Return the best known alignment for a pointer to a virtual base,
52/// given the alignment of a pointer to the derived class.
53CharUnits CodeGenModule::getVBaseAlignment(CharUnits actualDerivedAlign,
54 const CXXRecordDecl *derivedClass,
55 const CXXRecordDecl *vbaseClass) {
56 // The basic idea here is that an underaligned derived pointer might
57 // indicate an underaligned base pointer.
58
59 assert(vbaseClass->isCompleteDefinition());
60 auto &baseLayout = getContext().getASTRecordLayout(vbaseClass);
61 CharUnits expectedVBaseAlign = baseLayout.getNonVirtualAlignment();
62
63 return getDynamicOffsetAlignment(actualDerivedAlign, derivedClass,
64 expectedVBaseAlign);
65}
66
67CharUnits
68CodeGenModule::getDynamicOffsetAlignment(CharUnits actualBaseAlign,
69 const CXXRecordDecl *baseDecl,
70 CharUnits expectedTargetAlign) {
71 // If the base is an incomplete type (which is, alas, possible with
72 // member pointers), be pessimistic.
73 if (!baseDecl->isCompleteDefinition())
74 return std::min(actualBaseAlign, expectedTargetAlign);
75
76 auto &baseLayout = getContext().getASTRecordLayout(baseDecl);
77 CharUnits expectedBaseAlign = baseLayout.getNonVirtualAlignment();
78
79 // If the class is properly aligned, assume the target offset is, too.
80 //
81 // This actually isn't necessarily the right thing to do --- if the
82 // class is a complete object, but it's only properly aligned for a
83 // base subobject, then the alignments of things relative to it are
84 // probably off as well. (Note that this requires the alignment of
85 // the target to be greater than the NV alignment of the derived
86 // class.)
87 //
88 // However, our approach to this kind of under-alignment can only
89 // ever be best effort; after all, we're never going to propagate
90 // alignments through variables or parameters. Note, in particular,
91 // that constructing a polymorphic type in an address that's less
92 // than pointer-aligned will generally trap in the constructor,
93 // unless we someday add some sort of attribute to change the
94 // assumed alignment of 'this'. So our goal here is pretty much
95 // just to allow the user to explicitly say that a pointer is
96 // under-aligned and then safely access its fields and v-tables.
97 if (actualBaseAlign >= expectedBaseAlign) {
98 return expectedTargetAlign;
99 }
100
101 // Otherwise, we might be offset by an arbitrary multiple of the
102 // actual alignment. The correct adjustment is to take the min of
103 // the two alignments.
104 return std::min(actualBaseAlign, expectedTargetAlign);
105}
106
107Address CodeGenFunction::LoadCXXThisAddress() {
108 assert(CurFuncDecl && "loading 'this' without a func declaration?");
109 assert(isa<CXXMethodDecl>(CurFuncDecl));
110
111 // Lazily compute CXXThisAlignment.
112 if (CXXThisAlignment.isZero()) {
113 // Just use the best known alignment for the parent.
114 // TODO: if we're currently emitting a complete-object ctor/dtor,
115 // we can always use the complete-object alignment.
116 auto RD = cast<CXXMethodDecl>(CurFuncDecl)->getParent();
117 CXXThisAlignment = CGM.getClassPointerAlignment(RD);
118 }
119
120 return Address(LoadCXXThis(), CXXThisAlignment);
121}
122
123/// Emit the address of a field using a member data pointer.
124///
125/// \param E Only used for emergency diagnostics
126Address
127CodeGenFunction::EmitCXXMemberDataPointerAddress(const Expr *E, Address base,
128 llvm::Value *memberPtr,
129 const MemberPointerType *memberPtrType,
130 AlignmentSource *alignSource) {
131 // Ask the ABI to compute the actual address.
132 llvm::Value *ptr =
133 CGM.getCXXABI().EmitMemberDataPointerAddress(*this, E, base,
134 memberPtr, memberPtrType);
135
136 QualType memberType = memberPtrType->getPointeeType();
137 CharUnits memberAlign = getNaturalTypeAlignment(memberType, alignSource);
138 memberAlign =
139 CGM.getDynamicOffsetAlignment(base.getAlignment(),
140 memberPtrType->getClass()->getAsCXXRecordDecl(),
141 memberAlign);
142 return Address(ptr, memberAlign);
143}
144
David Majnemerc1709d32015-06-23 07:31:11 +0000145CharUnits CodeGenModule::computeNonVirtualBaseClassOffset(
146 const CXXRecordDecl *DerivedClass, CastExpr::path_const_iterator Start,
147 CastExpr::path_const_iterator End) {
Ken Dycka1a4ae32011-03-22 00:53:26 +0000148 CharUnits Offset = CharUnits::Zero();
Justin Bogner1cd11f12015-05-20 15:53:59 +0000149
David Majnemerc1709d32015-06-23 07:31:11 +0000150 const ASTContext &Context = getContext();
Anders Carlssond829a022010-04-24 21:06:20 +0000151 const CXXRecordDecl *RD = DerivedClass;
Justin Bogner1cd11f12015-05-20 15:53:59 +0000152
John McCallcf142162010-08-07 06:22:56 +0000153 for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
Anders Carlssond829a022010-04-24 21:06:20 +0000154 const CXXBaseSpecifier *Base = *I;
155 assert(!Base->isVirtual() && "Should not see virtual bases here!");
156
157 // Get the layout.
158 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000159
160 const CXXRecordDecl *BaseDecl =
Anders Carlssond829a022010-04-24 21:06:20 +0000161 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Justin Bogner1cd11f12015-05-20 15:53:59 +0000162
Anders Carlssond829a022010-04-24 21:06:20 +0000163 // Add the offset.
Ken Dycka1a4ae32011-03-22 00:53:26 +0000164 Offset += Layout.getBaseClassOffset(BaseDecl);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000165
Anders Carlssond829a022010-04-24 21:06:20 +0000166 RD = BaseDecl;
167 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000168
Ken Dycka1a4ae32011-03-22 00:53:26 +0000169 return Offset;
Anders Carlssond829a022010-04-24 21:06:20 +0000170}
Anders Carlsson9a57c5a2009-09-12 04:27:24 +0000171
Anders Carlsson9150a2a2009-09-29 03:13:20 +0000172llvm::Constant *
Anders Carlsson8a64c1c2010-04-24 21:23:59 +0000173CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
John McCallcf142162010-08-07 06:22:56 +0000174 CastExpr::path_const_iterator PathBegin,
175 CastExpr::path_const_iterator PathEnd) {
176 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlsson8a64c1c2010-04-24 21:23:59 +0000177
Justin Bogner1cd11f12015-05-20 15:53:59 +0000178 CharUnits Offset =
David Majnemerc1709d32015-06-23 07:31:11 +0000179 computeNonVirtualBaseClassOffset(ClassDecl, PathBegin, PathEnd);
Ken Dycka1a4ae32011-03-22 00:53:26 +0000180 if (Offset.isZero())
Craig Topper8a13c412014-05-21 05:09:00 +0000181 return nullptr;
182
Justin Bogner1cd11f12015-05-20 15:53:59 +0000183 llvm::Type *PtrDiffTy =
Anders Carlsson8a64c1c2010-04-24 21:23:59 +0000184 Types.ConvertType(getContext().getPointerDiffType());
Justin Bogner1cd11f12015-05-20 15:53:59 +0000185
Ken Dycka1a4ae32011-03-22 00:53:26 +0000186 return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
Anders Carlsson9150a2a2009-09-29 03:13:20 +0000187}
188
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000189/// Gets the address of a direct base class within a complete object.
John McCall6ce74722010-02-16 04:15:37 +0000190/// This should only be used for (1) non-virtual bases or (2) virtual bases
191/// when the type is known to be complete (e.g. in complete destructors).
192///
193/// The object pointed to by 'This' is assumed to be non-null.
John McCall7f416cc2015-09-08 08:05:57 +0000194Address
195CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(Address This,
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000196 const CXXRecordDecl *Derived,
197 const CXXRecordDecl *Base,
198 bool BaseIsVirtual) {
John McCall6ce74722010-02-16 04:15:37 +0000199 // 'this' must be a pointer (in some address space) to Derived.
John McCall7f416cc2015-09-08 08:05:57 +0000200 assert(This.getElementType() == ConvertType(Derived));
John McCall6ce74722010-02-16 04:15:37 +0000201
202 // Compute the offset of the virtual base.
Ken Dyck6aa767c2011-03-22 01:21:15 +0000203 CharUnits Offset;
John McCall6ce74722010-02-16 04:15:37 +0000204 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000205 if (BaseIsVirtual)
Ken Dyck6aa767c2011-03-22 01:21:15 +0000206 Offset = Layout.getVBaseClassOffset(Base);
John McCall6ce74722010-02-16 04:15:37 +0000207 else
Ken Dyck6aa767c2011-03-22 01:21:15 +0000208 Offset = Layout.getBaseClassOffset(Base);
John McCall6ce74722010-02-16 04:15:37 +0000209
210 // Shift and cast down to the base type.
211 // TODO: for complete types, this should be possible with a GEP.
John McCall7f416cc2015-09-08 08:05:57 +0000212 Address V = This;
213 if (!Offset.isZero()) {
214 V = Builder.CreateElementBitCast(V, Int8Ty);
215 V = Builder.CreateConstInBoundsByteGEP(V, Offset);
John McCall6ce74722010-02-16 04:15:37 +0000216 }
John McCall7f416cc2015-09-08 08:05:57 +0000217 V = Builder.CreateElementBitCast(V, ConvertType(Base));
John McCall6ce74722010-02-16 04:15:37 +0000218
219 return V;
Anders Carlssone87fae92010-03-28 19:40:00 +0000220}
John McCall6ce74722010-02-16 04:15:37 +0000221
John McCall7f416cc2015-09-08 08:05:57 +0000222static Address
223ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, Address addr,
John McCall13a39c62012-08-01 05:04:58 +0000224 CharUnits nonVirtualOffset,
John McCall7f416cc2015-09-08 08:05:57 +0000225 llvm::Value *virtualOffset,
226 const CXXRecordDecl *derivedClass,
227 const CXXRecordDecl *nearestVBase) {
John McCall13a39c62012-08-01 05:04:58 +0000228 // Assert that we have something to do.
Craig Topper8a13c412014-05-21 05:09:00 +0000229 assert(!nonVirtualOffset.isZero() || virtualOffset != nullptr);
John McCall13a39c62012-08-01 05:04:58 +0000230
231 // Compute the offset from the static and dynamic components.
232 llvm::Value *baseOffset;
233 if (!nonVirtualOffset.isZero()) {
234 baseOffset = llvm::ConstantInt::get(CGF.PtrDiffTy,
235 nonVirtualOffset.getQuantity());
236 if (virtualOffset) {
237 baseOffset = CGF.Builder.CreateAdd(virtualOffset, baseOffset);
238 }
239 } else {
240 baseOffset = virtualOffset;
241 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000242
Anders Carlsson53cebd12010-04-20 16:03:35 +0000243 // Apply the base offset.
John McCall7f416cc2015-09-08 08:05:57 +0000244 llvm::Value *ptr = addr.getPointer();
John McCall13a39c62012-08-01 05:04:58 +0000245 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
246 ptr = CGF.Builder.CreateInBoundsGEP(ptr, baseOffset, "add.ptr");
John McCall7f416cc2015-09-08 08:05:57 +0000247
248 // If we have a virtual component, the alignment of the result will
249 // be relative only to the known alignment of that vbase.
250 CharUnits alignment;
251 if (virtualOffset) {
252 assert(nearestVBase && "virtual offset without vbase?");
253 alignment = CGF.CGM.getVBaseAlignment(addr.getAlignment(),
254 derivedClass, nearestVBase);
255 } else {
256 alignment = addr.getAlignment();
257 }
258 alignment = alignment.alignmentAtOffset(nonVirtualOffset);
259
260 return Address(ptr, alignment);
Anders Carlsson53cebd12010-04-20 16:03:35 +0000261}
262
John McCall7f416cc2015-09-08 08:05:57 +0000263Address CodeGenFunction::GetAddressOfBaseClass(
264 Address Value, const CXXRecordDecl *Derived,
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000265 CastExpr::path_const_iterator PathBegin,
266 CastExpr::path_const_iterator PathEnd, bool NullCheckValue,
267 SourceLocation Loc) {
John McCallcf142162010-08-07 06:22:56 +0000268 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssond829a022010-04-24 21:06:20 +0000269
John McCallcf142162010-08-07 06:22:56 +0000270 CastExpr::path_const_iterator Start = PathBegin;
Craig Topper8a13c412014-05-21 05:09:00 +0000271 const CXXRecordDecl *VBase = nullptr;
272
John McCall13a39c62012-08-01 05:04:58 +0000273 // Sema has done some convenient canonicalization here: if the
274 // access path involved any virtual steps, the conversion path will
275 // *start* with a step down to the correct virtual base subobject,
276 // and hence will not require any further steps.
Anders Carlssond829a022010-04-24 21:06:20 +0000277 if ((*Start)->isVirtual()) {
Justin Bogner1cd11f12015-05-20 15:53:59 +0000278 VBase =
Anders Carlssond829a022010-04-24 21:06:20 +0000279 cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
280 ++Start;
281 }
John McCall13a39c62012-08-01 05:04:58 +0000282
283 // Compute the static offset of the ultimate destination within its
284 // allocating subobject (the virtual base, if there is one, or else
285 // the "complete" object that we see).
David Majnemerc1709d32015-06-23 07:31:11 +0000286 CharUnits NonVirtualOffset = CGM.computeNonVirtualBaseClassOffset(
287 VBase ? VBase : Derived, Start, PathEnd);
Anders Carlssond829a022010-04-24 21:06:20 +0000288
John McCall13a39c62012-08-01 05:04:58 +0000289 // If there's a virtual step, we can sometimes "devirtualize" it.
290 // For now, that's limited to when the derived type is final.
291 // TODO: "devirtualize" this for accesses to known-complete objects.
292 if (VBase && Derived->hasAttr<FinalAttr>()) {
293 const ASTRecordLayout &layout = getContext().getASTRecordLayout(Derived);
294 CharUnits vBaseOffset = layout.getVBaseClassOffset(VBase);
295 NonVirtualOffset += vBaseOffset;
Craig Topper8a13c412014-05-21 05:09:00 +0000296 VBase = nullptr; // we no longer have a virtual step
John McCall13a39c62012-08-01 05:04:58 +0000297 }
298
Anders Carlssond829a022010-04-24 21:06:20 +0000299 // Get the base pointer type.
Justin Bogner1cd11f12015-05-20 15:53:59 +0000300 llvm::Type *BasePtrTy =
John McCallcf142162010-08-07 06:22:56 +0000301 ConvertType((PathEnd[-1])->getType())->getPointerTo();
John McCall13a39c62012-08-01 05:04:58 +0000302
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000303 QualType DerivedTy = getContext().getRecordType(Derived);
John McCall7f416cc2015-09-08 08:05:57 +0000304 CharUnits DerivedAlign = CGM.getClassPointerAlignment(Derived);
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000305
John McCall13a39c62012-08-01 05:04:58 +0000306 // If the static offset is zero and we don't have a virtual step,
307 // just do a bitcast; null checks are unnecessary.
Ken Dycka1a4ae32011-03-22 00:53:26 +0000308 if (NonVirtualOffset.isZero() && !VBase) {
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000309 if (sanitizePerformTypeCheck()) {
John McCall7f416cc2015-09-08 08:05:57 +0000310 EmitTypeCheck(TCK_Upcast, Loc, Value.getPointer(),
311 DerivedTy, DerivedAlign, !NullCheckValue);
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000312 }
Anders Carlssond829a022010-04-24 21:06:20 +0000313 return Builder.CreateBitCast(Value, BasePtrTy);
Craig Topper8a13c412014-05-21 05:09:00 +0000314 }
John McCall13a39c62012-08-01 05:04:58 +0000315
Craig Topper8a13c412014-05-21 05:09:00 +0000316 llvm::BasicBlock *origBB = nullptr;
317 llvm::BasicBlock *endBB = nullptr;
318
John McCall13a39c62012-08-01 05:04:58 +0000319 // Skip over the offset (and the vtable load) if we're supposed to
320 // null-check the pointer.
Anders Carlssond829a022010-04-24 21:06:20 +0000321 if (NullCheckValue) {
John McCall13a39c62012-08-01 05:04:58 +0000322 origBB = Builder.GetInsertBlock();
323 llvm::BasicBlock *notNullBB = createBasicBlock("cast.notnull");
324 endBB = createBasicBlock("cast.end");
Justin Bogner1cd11f12015-05-20 15:53:59 +0000325
John McCall7f416cc2015-09-08 08:05:57 +0000326 llvm::Value *isNull = Builder.CreateIsNull(Value.getPointer());
John McCall13a39c62012-08-01 05:04:58 +0000327 Builder.CreateCondBr(isNull, endBB, notNullBB);
328 EmitBlock(notNullBB);
Anders Carlssond829a022010-04-24 21:06:20 +0000329 }
330
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000331 if (sanitizePerformTypeCheck()) {
John McCall7f416cc2015-09-08 08:05:57 +0000332 EmitTypeCheck(VBase ? TCK_UpcastToVirtualBase : TCK_Upcast, Loc,
333 Value.getPointer(), DerivedTy, DerivedAlign, true);
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000334 }
335
John McCall13a39c62012-08-01 05:04:58 +0000336 // Compute the virtual offset.
Craig Topper8a13c412014-05-21 05:09:00 +0000337 llvm::Value *VirtualOffset = nullptr;
Anders Carlssona376b532011-01-29 03:18:56 +0000338 if (VBase) {
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000339 VirtualOffset =
340 CGM.getCXXABI().GetVirtualBaseClassOffset(*this, Value, Derived, VBase);
Anders Carlssona376b532011-01-29 03:18:56 +0000341 }
Anders Carlssond829a022010-04-24 21:06:20 +0000342
John McCall13a39c62012-08-01 05:04:58 +0000343 // Apply both offsets.
John McCall7f416cc2015-09-08 08:05:57 +0000344 Value = ApplyNonVirtualAndVirtualOffset(*this, Value, NonVirtualOffset,
345 VirtualOffset, Derived, VBase);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000346
John McCall13a39c62012-08-01 05:04:58 +0000347 // Cast to the destination type.
Anders Carlssond829a022010-04-24 21:06:20 +0000348 Value = Builder.CreateBitCast(Value, BasePtrTy);
John McCall13a39c62012-08-01 05:04:58 +0000349
350 // Build a phi if we needed a null check.
Anders Carlssond829a022010-04-24 21:06:20 +0000351 if (NullCheckValue) {
John McCall13a39c62012-08-01 05:04:58 +0000352 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
353 Builder.CreateBr(endBB);
354 EmitBlock(endBB);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000355
John McCall13a39c62012-08-01 05:04:58 +0000356 llvm::PHINode *PHI = Builder.CreatePHI(BasePtrTy, 2, "cast.result");
John McCall7f416cc2015-09-08 08:05:57 +0000357 PHI->addIncoming(Value.getPointer(), notNullBB);
John McCall13a39c62012-08-01 05:04:58 +0000358 PHI->addIncoming(llvm::Constant::getNullValue(BasePtrTy), origBB);
John McCall7f416cc2015-09-08 08:05:57 +0000359 Value = Address(PHI, Value.getAlignment());
Anders Carlssond829a022010-04-24 21:06:20 +0000360 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000361
Anders Carlssond829a022010-04-24 21:06:20 +0000362 return Value;
363}
364
John McCall7f416cc2015-09-08 08:05:57 +0000365Address
366CodeGenFunction::GetAddressOfDerivedClass(Address BaseAddr,
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000367 const CXXRecordDecl *Derived,
John McCallcf142162010-08-07 06:22:56 +0000368 CastExpr::path_const_iterator PathBegin,
369 CastExpr::path_const_iterator PathEnd,
Anders Carlsson8c793172009-11-23 17:57:54 +0000370 bool NullCheckValue) {
John McCallcf142162010-08-07 06:22:56 +0000371 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlsson8a64c1c2010-04-24 21:23:59 +0000372
Anders Carlsson8c793172009-11-23 17:57:54 +0000373 QualType DerivedTy =
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000374 getContext().getCanonicalType(getContext().getTagDeclType(Derived));
Chris Lattner2192fe52011-07-18 04:24:23 +0000375 llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
Richard Smith2c5868c2013-02-13 21:18:23 +0000376
Anders Carlsson600f7372010-01-31 01:43:37 +0000377 llvm::Value *NonVirtualOffset =
John McCallcf142162010-08-07 06:22:56 +0000378 CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000379
Anders Carlsson600f7372010-01-31 01:43:37 +0000380 if (!NonVirtualOffset) {
381 // No offset, we can just cast back.
John McCall7f416cc2015-09-08 08:05:57 +0000382 return Builder.CreateBitCast(BaseAddr, DerivedPtrTy);
Anders Carlsson600f7372010-01-31 01:43:37 +0000383 }
Craig Topper8a13c412014-05-21 05:09:00 +0000384
385 llvm::BasicBlock *CastNull = nullptr;
386 llvm::BasicBlock *CastNotNull = nullptr;
387 llvm::BasicBlock *CastEnd = nullptr;
388
Anders Carlsson8c793172009-11-23 17:57:54 +0000389 if (NullCheckValue) {
390 CastNull = createBasicBlock("cast.null");
391 CastNotNull = createBasicBlock("cast.notnull");
392 CastEnd = createBasicBlock("cast.end");
Justin Bogner1cd11f12015-05-20 15:53:59 +0000393
John McCall7f416cc2015-09-08 08:05:57 +0000394 llvm::Value *IsNull = Builder.CreateIsNull(BaseAddr.getPointer());
Anders Carlsson8c793172009-11-23 17:57:54 +0000395 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
396 EmitBlock(CastNotNull);
397 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000398
Anders Carlsson600f7372010-01-31 01:43:37 +0000399 // Apply the offset.
John McCall7f416cc2015-09-08 08:05:57 +0000400 llvm::Value *Value = Builder.CreateBitCast(BaseAddr.getPointer(), Int8PtrTy);
Eli Friedman87549262012-02-28 22:07:56 +0000401 Value = Builder.CreateGEP(Value, Builder.CreateNeg(NonVirtualOffset),
402 "sub.ptr");
Anders Carlsson600f7372010-01-31 01:43:37 +0000403
404 // Just cast.
405 Value = Builder.CreateBitCast(Value, DerivedPtrTy);
Anders Carlsson8c793172009-11-23 17:57:54 +0000406
John McCall7f416cc2015-09-08 08:05:57 +0000407 // Produce a PHI if we had a null-check.
Anders Carlsson8c793172009-11-23 17:57:54 +0000408 if (NullCheckValue) {
409 Builder.CreateBr(CastEnd);
410 EmitBlock(CastNull);
411 Builder.CreateBr(CastEnd);
412 EmitBlock(CastEnd);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000413
Jay Foad20c0f022011-03-30 11:28:58 +0000414 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
Anders Carlsson8c793172009-11-23 17:57:54 +0000415 PHI->addIncoming(Value, CastNotNull);
John McCall7f416cc2015-09-08 08:05:57 +0000416 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
Anders Carlsson8c793172009-11-23 17:57:54 +0000417 Value = PHI;
418 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000419
John McCall7f416cc2015-09-08 08:05:57 +0000420 return Address(Value, CGM.getClassPointerAlignment(Derived));
Anders Carlsson9a57c5a2009-09-12 04:27:24 +0000421}
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000422
423llvm::Value *CodeGenFunction::GetVTTParameter(GlobalDecl GD,
424 bool ForVirtualBase,
425 bool Delegating) {
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000426 if (!CGM.getCXXABI().NeedsVTTParameter(GD)) {
Anders Carlssone36a6b32010-01-02 01:01:18 +0000427 // This constructor/destructor does not need a VTT parameter.
Craig Topper8a13c412014-05-21 05:09:00 +0000428 return nullptr;
Anders Carlssone36a6b32010-01-02 01:01:18 +0000429 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000430
John McCalldec348f72013-05-03 07:33:41 +0000431 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CurCodeDecl)->getParent();
Anders Carlssone36a6b32010-01-02 01:01:18 +0000432 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
John McCall5c60a6f2010-02-18 19:59:28 +0000433
Anders Carlssone36a6b32010-01-02 01:01:18 +0000434 llvm::Value *VTT;
435
John McCall5c60a6f2010-02-18 19:59:28 +0000436 uint64_t SubVTTIndex;
437
Douglas Gregor61535002013-01-31 05:50:40 +0000438 if (Delegating) {
439 // If this is a delegating constructor call, just load the VTT.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000440 return LoadCXXVTT();
Douglas Gregor61535002013-01-31 05:50:40 +0000441 } else if (RD == Base) {
442 // If the record matches the base, this is the complete ctor/dtor
443 // variant calling the base variant in a class with virtual bases.
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000444 assert(!CGM.getCXXABI().NeedsVTTParameter(CurGD) &&
John McCall5c60a6f2010-02-18 19:59:28 +0000445 "doing no-op VTT offset in base dtor/ctor?");
Anders Carlsson4d205ba2010-05-02 23:33:10 +0000446 assert(!ForVirtualBase && "Can't have same class as virtual base!");
John McCall5c60a6f2010-02-18 19:59:28 +0000447 SubVTTIndex = 0;
448 } else {
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000449 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000450 CharUnits BaseOffset = ForVirtualBase ?
451 Layout.getVBaseClassOffset(Base) :
Ken Dyck16ffcac2011-03-24 01:21:01 +0000452 Layout.getBaseClassOffset(Base);
Anders Carlsson859b3062010-05-02 23:53:25 +0000453
Justin Bogner1cd11f12015-05-20 15:53:59 +0000454 SubVTTIndex =
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000455 CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
John McCall5c60a6f2010-02-18 19:59:28 +0000456 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
457 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000458
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000459 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
Anders Carlssone36a6b32010-01-02 01:01:18 +0000460 // A VTT parameter was passed to the constructor, use it.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000461 VTT = LoadCXXVTT();
462 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
Anders Carlssone36a6b32010-01-02 01:01:18 +0000463 } else {
464 // We're the complete constructor, so get the VTT by name.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000465 VTT = CGM.getVTables().GetAddrOfVTT(RD);
466 VTT = Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
Anders Carlssone36a6b32010-01-02 01:01:18 +0000467 }
468
469 return VTT;
470}
471
John McCall1d987562010-07-21 01:23:41 +0000472namespace {
John McCallf99a6312010-07-21 05:30:47 +0000473 /// Call the destructor for a direct base class.
David Blaikie7e70d682015-08-18 22:40:54 +0000474 struct CallBaseDtor final : EHScopeStack::Cleanup {
John McCallf99a6312010-07-21 05:30:47 +0000475 const CXXRecordDecl *BaseClass;
476 bool BaseIsVirtual;
477 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
478 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
John McCall1d987562010-07-21 01:23:41 +0000479
Craig Topper4f12f102014-03-12 06:41:41 +0000480 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallf99a6312010-07-21 05:30:47 +0000481 const CXXRecordDecl *DerivedClass =
482 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
483
484 const CXXDestructorDecl *D = BaseClass->getDestructor();
John McCall7f416cc2015-09-08 08:05:57 +0000485 Address Addr =
486 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThisAddress(),
John McCallf99a6312010-07-21 05:30:47 +0000487 DerivedClass, BaseClass,
488 BaseIsVirtual);
Douglas Gregor61535002013-01-31 05:50:40 +0000489 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual,
490 /*Delegating=*/false, Addr);
John McCall1d987562010-07-21 01:23:41 +0000491 }
492 };
John McCall769250e2010-09-17 02:31:44 +0000493
494 /// A visitor which checks whether an initializer uses 'this' in a
495 /// way which requires the vtable to be properly set.
Scott Douglass503fc392015-06-10 13:53:15 +0000496 struct DynamicThisUseChecker : ConstEvaluatedExprVisitor<DynamicThisUseChecker> {
497 typedef ConstEvaluatedExprVisitor<DynamicThisUseChecker> super;
John McCall769250e2010-09-17 02:31:44 +0000498
499 bool UsesThis;
500
Scott Douglass503fc392015-06-10 13:53:15 +0000501 DynamicThisUseChecker(const ASTContext &C) : super(C), UsesThis(false) {}
John McCall769250e2010-09-17 02:31:44 +0000502
503 // Black-list all explicit and implicit references to 'this'.
504 //
505 // Do we need to worry about external references to 'this' derived
506 // from arbitrary code? If so, then anything which runs arbitrary
507 // external code might potentially access the vtable.
Scott Douglass503fc392015-06-10 13:53:15 +0000508 void VisitCXXThisExpr(const CXXThisExpr *E) { UsesThis = true; }
John McCall769250e2010-09-17 02:31:44 +0000509 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000510}
John McCall769250e2010-09-17 02:31:44 +0000511
512static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
513 DynamicThisUseChecker Checker(C);
Scott Douglass503fc392015-06-10 13:53:15 +0000514 Checker.Visit(Init);
John McCall769250e2010-09-17 02:31:44 +0000515 return Checker.UsesThis;
John McCall1d987562010-07-21 01:23:41 +0000516}
517
Justin Bogner1cd11f12015-05-20 15:53:59 +0000518static void EmitBaseInitializer(CodeGenFunction &CGF,
Anders Carlssonfb404882009-12-24 22:46:43 +0000519 const CXXRecordDecl *ClassDecl,
Alexis Hunt1d792652011-01-08 20:30:50 +0000520 CXXCtorInitializer *BaseInit,
Anders Carlssonfb404882009-12-24 22:46:43 +0000521 CXXCtorType CtorType) {
522 assert(BaseInit->isBaseInitializer() &&
523 "Must have base initializer!");
524
John McCall7f416cc2015-09-08 08:05:57 +0000525 Address ThisPtr = CGF.LoadCXXThisAddress();
Justin Bogner1cd11f12015-05-20 15:53:59 +0000526
Anders Carlssonfb404882009-12-24 22:46:43 +0000527 const Type *BaseType = BaseInit->getBaseClass();
528 CXXRecordDecl *BaseClassDecl =
529 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
530
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +0000531 bool isBaseVirtual = BaseInit->isBaseVirtual();
Anders Carlssonfb404882009-12-24 22:46:43 +0000532
533 // The base constructor doesn't construct virtual bases.
534 if (CtorType == Ctor_Base && isBaseVirtual)
535 return;
536
John McCall769250e2010-09-17 02:31:44 +0000537 // If the initializer for the base (other than the constructor
538 // itself) accesses 'this' in any way, we need to initialize the
539 // vtables.
540 if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
541 CGF.InitializeVTablePointers(ClassDecl);
542
John McCall6ce74722010-02-16 04:15:37 +0000543 // We can pretend to be a complete class because it only matters for
544 // virtual bases, and we only do virtual bases for complete ctors.
John McCall7f416cc2015-09-08 08:05:57 +0000545 Address V =
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000546 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
John McCallf99a6312010-07-21 05:30:47 +0000547 BaseClassDecl,
548 isBaseVirtual);
John McCall8d6fc952011-08-25 20:40:09 +0000549 AggValueSlot AggSlot =
John McCall7f416cc2015-09-08 08:05:57 +0000550 AggValueSlot::forAddr(V, Qualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +0000551 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +0000552 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000553 AggValueSlot::IsNotAliased);
John McCall7a626f62010-09-15 10:14:12 +0000554
555 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000556
557 if (CGF.CGM.getLangOpts().Exceptions &&
Anders Carlsson08ce5ed2011-02-20 00:20:27 +0000558 !BaseClassDecl->hasTrivialDestructor())
John McCallcda666c2010-07-21 07:22:38 +0000559 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
560 isBaseVirtual);
Anders Carlssonfb404882009-12-24 22:46:43 +0000561}
562
Douglas Gregor94f9a482010-05-05 05:51:00 +0000563static void EmitAggMemberInitializer(CodeGenFunction &CGF,
564 LValue LHS,
Eli Friedman6ae63022012-02-14 02:15:49 +0000565 Expr *Init,
John McCall7f416cc2015-09-08 08:05:57 +0000566 Address ArrayIndexVar,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000567 QualType T,
Eli Friedman6ae63022012-02-14 02:15:49 +0000568 ArrayRef<VarDecl *> ArrayIndexes,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000569 unsigned Index) {
Eli Friedman6ae63022012-02-14 02:15:49 +0000570 if (Index == ArrayIndexes.size()) {
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000571 LValue LV = LHS;
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000572
John McCall7f416cc2015-09-08 08:05:57 +0000573 if (ArrayIndexVar.isValid()) {
Richard Smithcc1b96d2013-06-12 22:31:48 +0000574 // If we have an array index variable, load it and use it as an offset.
575 // Then, increment the value.
John McCall7f416cc2015-09-08 08:05:57 +0000576 llvm::Value *Dest = LHS.getPointer();
Richard Smithcc1b96d2013-06-12 22:31:48 +0000577 llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar);
578 Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress");
579 llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1);
580 Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc");
581 CGF.Builder.CreateStore(Next, ArrayIndexVar);
Sebastian Redl4e04dd12012-02-19 15:41:54 +0000582
Richard Smithcc1b96d2013-06-12 22:31:48 +0000583 // Update the LValue.
John McCall7f416cc2015-09-08 08:05:57 +0000584 CharUnits EltSize = CGF.getContext().getTypeSizeInChars(T);
585 CharUnits Align = LV.getAlignment().alignmentOfArrayElement(EltSize);
586 LV.setAddress(Address(Dest, Align));
Douglas Gregor94f9a482010-05-05 05:51:00 +0000587 }
John McCall7a626f62010-09-15 10:14:12 +0000588
Richard Smithcc1b96d2013-06-12 22:31:48 +0000589 switch (CGF.getEvaluationKind(T)) {
590 case TEK_Scalar:
Craig Topper8a13c412014-05-21 05:09:00 +0000591 CGF.EmitScalarInit(Init, /*decl*/ nullptr, LV, false);
Richard Smithcc1b96d2013-06-12 22:31:48 +0000592 break;
593 case TEK_Complex:
594 CGF.EmitComplexExprIntoLValue(Init, LV, /*isInit*/ true);
595 break;
596 case TEK_Aggregate: {
597 AggValueSlot Slot =
598 AggValueSlot::forLValue(LV,
599 AggValueSlot::IsDestructed,
600 AggValueSlot::DoesNotNeedGCBarriers,
601 AggValueSlot::IsNotAliased);
602
603 CGF.EmitAggExpr(Init, Slot);
604 break;
605 }
606 }
Sebastian Redl4e04dd12012-02-19 15:41:54 +0000607
Douglas Gregor94f9a482010-05-05 05:51:00 +0000608 return;
609 }
Richard Smithcc1b96d2013-06-12 22:31:48 +0000610
Douglas Gregor94f9a482010-05-05 05:51:00 +0000611 const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T);
612 assert(Array && "Array initialization without the array type?");
John McCall7f416cc2015-09-08 08:05:57 +0000613 Address IndexVar = CGF.GetAddrOfLocalVar(ArrayIndexes[Index]);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000614
Douglas Gregor94f9a482010-05-05 05:51:00 +0000615 // Initialize this index variable to zero.
616 llvm::Value* Zero
John McCall7f416cc2015-09-08 08:05:57 +0000617 = llvm::Constant::getNullValue(IndexVar.getElementType());
Douglas Gregor94f9a482010-05-05 05:51:00 +0000618 CGF.Builder.CreateStore(Zero, IndexVar);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000619
Douglas Gregor94f9a482010-05-05 05:51:00 +0000620 // Start the loop with a block that tests the condition.
621 llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond");
622 llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end");
Justin Bogner1cd11f12015-05-20 15:53:59 +0000623
Douglas Gregor94f9a482010-05-05 05:51:00 +0000624 CGF.EmitBlock(CondBlock);
625
626 llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body");
627 // Generate: if (loop-index < number-of-elements) fall to the loop body,
628 // otherwise, go to the block after the for-loop.
629 uint64_t NumElements = Array->getSize().getZExtValue();
Douglas Gregor94f9a482010-05-05 05:51:00 +0000630 llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
Chris Lattner44456d22010-05-06 06:35:23 +0000631 llvm::Value *NumElementsPtr =
632 llvm::ConstantInt::get(Counter->getType(), NumElements);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000633 llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr,
634 "isless");
Justin Bogner1cd11f12015-05-20 15:53:59 +0000635
Douglas Gregor94f9a482010-05-05 05:51:00 +0000636 // If the condition is true, execute the body.
637 CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor);
638
639 CGF.EmitBlock(ForBody);
640 llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc");
Richard Smithcc1b96d2013-06-12 22:31:48 +0000641
642 // Inside the loop body recurse to emit the inner loop or, eventually, the
643 // constructor call.
644 EmitAggMemberInitializer(CGF, LHS, Init, ArrayIndexVar,
645 Array->getElementType(), ArrayIndexes, Index + 1);
646
Douglas Gregor94f9a482010-05-05 05:51:00 +0000647 CGF.EmitBlock(ContinueBlock);
648
649 // Emit the increment of the loop counter.
650 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
651 Counter = CGF.Builder.CreateLoad(IndexVar);
652 NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc");
653 CGF.Builder.CreateStore(NextVal, IndexVar);
654
655 // Finally, branch back up to the condition for the next iteration.
656 CGF.EmitBranch(CondBlock);
657
658 // Emit the fall-through block.
659 CGF.EmitBlock(AfterFor, true);
660}
John McCall1d987562010-07-21 01:23:41 +0000661
Richard Smith419bd092015-04-29 19:26:57 +0000662static bool isMemcpyEquivalentSpecialMember(const CXXMethodDecl *D) {
663 auto *CD = dyn_cast<CXXConstructorDecl>(D);
664 if (!(CD && CD->isCopyOrMoveConstructor()) &&
665 !D->isCopyAssignmentOperator() && !D->isMoveAssignmentOperator())
666 return false;
667
668 // We can emit a memcpy for a trivial copy or move constructor/assignment.
669 if (D->isTrivial() && !D->getParent()->mayInsertExtraPadding())
670 return true;
671
672 // We *must* emit a memcpy for a defaulted union copy or move op.
673 if (D->getParent()->isUnion() && D->isDefaulted())
674 return true;
675
676 return false;
677}
678
Alexey Bataev152c71f2015-07-14 07:55:48 +0000679static void EmitLValueForAnyFieldInitialization(CodeGenFunction &CGF,
680 CXXCtorInitializer *MemberInit,
681 LValue &LHS) {
682 FieldDecl *Field = MemberInit->getAnyMember();
683 if (MemberInit->isIndirectMemberInitializer()) {
684 // If we are initializing an anonymous union field, drill down to the field.
685 IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember();
686 for (const auto *I : IndirectField->chain())
687 LHS = CGF.EmitLValueForFieldInitialization(LHS, cast<FieldDecl>(I));
688 } else {
689 LHS = CGF.EmitLValueForFieldInitialization(LHS, Field);
690 }
691}
692
Anders Carlssonfb404882009-12-24 22:46:43 +0000693static void EmitMemberInitializer(CodeGenFunction &CGF,
694 const CXXRecordDecl *ClassDecl,
Alexis Hunt1d792652011-01-08 20:30:50 +0000695 CXXCtorInitializer *MemberInit,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000696 const CXXConstructorDecl *Constructor,
697 FunctionArgList &Args) {
David Blaikiea81d4102015-01-18 00:12:58 +0000698 ApplyDebugLocation Loc(CGF, MemberInit->getSourceLocation());
Francois Pichetd583da02010-12-04 09:14:42 +0000699 assert(MemberInit->isAnyMemberInitializer() &&
Anders Carlssonfb404882009-12-24 22:46:43 +0000700 "Must have member initializer!");
Richard Smith938f40b2011-06-11 17:19:42 +0000701 assert(MemberInit->getInit() && "Must have initializer!");
Justin Bogner1cd11f12015-05-20 15:53:59 +0000702
Anders Carlssonfb404882009-12-24 22:46:43 +0000703 // non-static data member initializers.
Francois Pichetd583da02010-12-04 09:14:42 +0000704 FieldDecl *Field = MemberInit->getAnyMember();
Eli Friedman6ae63022012-02-14 02:15:49 +0000705 QualType FieldType = Field->getType();
Anders Carlssonfb404882009-12-24 22:46:43 +0000706
707 llvm::Value *ThisPtr = CGF.LoadCXXThis();
Eli Friedman7f1ff602012-04-16 03:54:45 +0000708 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
Eli Friedmanf6d21842012-08-08 03:51:37 +0000709 LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
Eli Friedman7f1ff602012-04-16 03:54:45 +0000710
Alexey Bataev152c71f2015-07-14 07:55:48 +0000711 EmitLValueForAnyFieldInitialization(CGF, MemberInit, LHS);
Anders Carlssonfb404882009-12-24 22:46:43 +0000712
Eli Friedman6ae63022012-02-14 02:15:49 +0000713 // Special case: if we are in a copy or move constructor, and we are copying
714 // an array of PODs or classes with trivial copy constructors, ignore the
715 // AST and perform the copy we know is equivalent.
716 // FIXME: This is hacky at best... if we had a bit more explicit information
717 // in the AST, we could generalize it more easily.
718 const ConstantArrayType *Array
719 = CGF.getContext().getAsConstantArrayType(FieldType);
Jordan Rose54533f72013-08-07 16:16:48 +0000720 if (Array && Constructor->isDefaulted() &&
Eli Friedman6ae63022012-02-14 02:15:49 +0000721 Constructor->isCopyOrMoveConstructor()) {
722 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
Richard Smith993f25a2012-11-07 23:56:21 +0000723 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
Eli Friedman6ae63022012-02-14 02:15:49 +0000724 if (BaseElementTy.isPODType(CGF.getContext()) ||
Richard Smith419bd092015-04-29 19:26:57 +0000725 (CE && isMemcpyEquivalentSpecialMember(CE->getConstructor()))) {
David Majnemer1573d732014-10-15 04:54:54 +0000726 unsigned SrcArgIndex =
727 CGF.CGM.getCXXABI().getSrcArgforCopyCtor(Constructor, Args);
Eli Friedman6ae63022012-02-14 02:15:49 +0000728 llvm::Value *SrcPtr
729 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
Eli Friedman7f1ff602012-04-16 03:54:45 +0000730 LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
731 LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000732
Eli Friedman6ae63022012-02-14 02:15:49 +0000733 // Copy the aggregate.
734 CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000735 LHS.isVolatileQualified());
Alexey Bataev5d49b832015-07-08 07:31:02 +0000736 // Ensure that we destroy the objects if an exception is thrown later in
737 // the constructor.
738 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
739 if (CGF.needsEHCleanup(dtorKind))
740 CGF.pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
Eli Friedman6ae63022012-02-14 02:15:49 +0000741 return;
742 }
743 }
744
745 ArrayRef<VarDecl *> ArrayIndexes;
746 if (MemberInit->getNumArrayIndices())
747 ArrayIndexes = MemberInit->getArrayIndexes();
David Blaikie66e41972015-01-14 07:38:27 +0000748 CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit(), ArrayIndexes);
Eli Friedman6ae63022012-02-14 02:15:49 +0000749}
750
John McCall7f416cc2015-09-08 08:05:57 +0000751void CodeGenFunction::EmitInitializerForField(FieldDecl *Field, LValue LHS,
752 Expr *Init, ArrayRef<VarDecl *> ArrayIndexes) {
Eli Friedman6ae63022012-02-14 02:15:49 +0000753 QualType FieldType = Field->getType();
John McCall47fb9502013-03-07 21:37:08 +0000754 switch (getEvaluationKind(FieldType)) {
755 case TEK_Scalar:
John McCall31168b02011-06-15 23:02:42 +0000756 if (LHS.isSimple()) {
David Blaikie66e41972015-01-14 07:38:27 +0000757 EmitExprAsInit(Init, Field, LHS, false);
John McCall31168b02011-06-15 23:02:42 +0000758 } else {
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000759 RValue RHS = RValue::get(EmitScalarExpr(Init));
760 EmitStoreThroughLValue(RHS, LHS);
John McCall31168b02011-06-15 23:02:42 +0000761 }
John McCall47fb9502013-03-07 21:37:08 +0000762 break;
763 case TEK_Complex:
David Blaikie66e41972015-01-14 07:38:27 +0000764 EmitComplexExprIntoLValue(Init, LHS, /*isInit*/ true);
John McCall47fb9502013-03-07 21:37:08 +0000765 break;
766 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000767 Address ArrayIndexVar = Address::invalid();
Eli Friedman6ae63022012-02-14 02:15:49 +0000768 if (ArrayIndexes.size()) {
Douglas Gregor94f9a482010-05-05 05:51:00 +0000769 // The LHS is a pointer to the first object we'll be constructing, as
770 // a flat array.
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000771 QualType BaseElementTy = getContext().getBaseElementType(FieldType);
772 llvm::Type *BasePtr = ConvertType(BaseElementTy);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000773 BasePtr = llvm::PointerType::getUnqual(BasePtr);
John McCall7f416cc2015-09-08 08:05:57 +0000774 Address BaseAddrPtr = Builder.CreateBitCast(LHS.getAddress(), BasePtr);
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000775 LHS = MakeAddrLValue(BaseAddrPtr, BaseElementTy);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000776
Douglas Gregor94f9a482010-05-05 05:51:00 +0000777 // Create an array index that will be used to walk over all of the
778 // objects we're constructing.
John McCall7f416cc2015-09-08 08:05:57 +0000779 ArrayIndexVar = CreateMemTemp(getContext().getSizeType(), "object.index");
780 llvm::Value *Zero =
781 llvm::Constant::getNullValue(ArrayIndexVar.getElementType());
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000782 Builder.CreateStore(Zero, ArrayIndexVar);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000783
Douglas Gregor94f9a482010-05-05 05:51:00 +0000784 // Emit the block variables for the array indices, if any.
Eli Friedman6ae63022012-02-14 02:15:49 +0000785 for (unsigned I = 0, N = ArrayIndexes.size(); I != N; ++I)
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000786 EmitAutoVarDecl(*ArrayIndexes[I]);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000787 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000788
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000789 EmitAggMemberInitializer(*this, LHS, Init, ArrayIndexVar, FieldType,
Eli Friedman6ae63022012-02-14 02:15:49 +0000790 ArrayIndexes, 0);
Anders Carlssonfb404882009-12-24 22:46:43 +0000791 }
John McCall47fb9502013-03-07 21:37:08 +0000792 }
John McCall12cc42a2013-02-01 05:11:40 +0000793
794 // Ensure that we destroy this object if an exception is thrown
795 // later in the constructor.
796 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
797 if (needsEHCleanup(dtorKind))
798 pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
Anders Carlssonfb404882009-12-24 22:46:43 +0000799}
800
John McCallf8ff7b92010-02-23 00:48:20 +0000801/// Checks whether the given constructor is a valid subject for the
802/// complete-to-base constructor delegation optimization, i.e.
803/// emitting the complete constructor as a simple call to the base
804/// constructor.
805static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
806
807 // Currently we disable the optimization for classes with virtual
808 // bases because (1) the addresses of parameter variables need to be
809 // consistent across all initializers but (2) the delegate function
810 // call necessarily creates a second copy of the parameter variable.
811 //
812 // The limiting example (purely theoretical AFAIK):
813 // struct A { A(int &c) { c++; } };
814 // struct B : virtual A {
815 // B(int count) : A(count) { printf("%d\n", count); }
816 // };
817 // ...although even this example could in principle be emitted as a
818 // delegation since the address of the parameter doesn't escape.
819 if (Ctor->getParent()->getNumVBases()) {
820 // TODO: white-list trivial vbase initializers. This case wouldn't
821 // be subject to the restrictions below.
822
823 // TODO: white-list cases where:
824 // - there are no non-reference parameters to the constructor
825 // - the initializers don't access any non-reference parameters
826 // - the initializers don't take the address of non-reference
827 // parameters
828 // - etc.
829 // If we ever add any of the above cases, remember that:
830 // - function-try-blocks will always blacklist this optimization
831 // - we need to perform the constructor prologue and cleanup in
832 // EmitConstructorBody.
833
834 return false;
835 }
836
837 // We also disable the optimization for variadic functions because
838 // it's impossible to "re-pass" varargs.
839 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
840 return false;
841
Alexis Hunt61bc1732011-05-01 07:04:31 +0000842 // FIXME: Decide if we can do a delegation of a delegating constructor.
843 if (Ctor->isDelegatingConstructor())
844 return false;
845
John McCallf8ff7b92010-02-23 00:48:20 +0000846 return true;
847}
848
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000849// Emit code in ctor (Prologue==true) or dtor (Prologue==false)
850// to poison the extra field paddings inserted under
851// -fsanitize-address-field-padding=1|2.
852void CodeGenFunction::EmitAsanPrologueOrEpilogue(bool Prologue) {
853 ASTContext &Context = getContext();
854 const CXXRecordDecl *ClassDecl =
855 Prologue ? cast<CXXConstructorDecl>(CurGD.getDecl())->getParent()
856 : cast<CXXDestructorDecl>(CurGD.getDecl())->getParent();
857 if (!ClassDecl->mayInsertExtraPadding()) return;
858
859 struct SizeAndOffset {
860 uint64_t Size;
861 uint64_t Offset;
862 };
863
864 unsigned PtrSize = CGM.getDataLayout().getPointerSizeInBits();
865 const ASTRecordLayout &Info = Context.getASTRecordLayout(ClassDecl);
866
867 // Populate sizes and offsets of fields.
868 SmallVector<SizeAndOffset, 16> SSV(Info.getFieldCount());
869 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i)
870 SSV[i].Offset =
871 Context.toCharUnitsFromBits(Info.getFieldOffset(i)).getQuantity();
872
873 size_t NumFields = 0;
874 for (const auto *Field : ClassDecl->fields()) {
875 const FieldDecl *D = Field;
876 std::pair<CharUnits, CharUnits> FieldInfo =
877 Context.getTypeInfoInChars(D->getType());
878 CharUnits FieldSize = FieldInfo.first;
879 assert(NumFields < SSV.size());
880 SSV[NumFields].Size = D->isBitField() ? 0 : FieldSize.getQuantity();
881 NumFields++;
882 }
883 assert(NumFields == SSV.size());
884 if (SSV.size() <= 1) return;
885
886 // We will insert calls to __asan_* run-time functions.
887 // LLVM AddressSanitizer pass may decide to inline them later.
888 llvm::Type *Args[2] = {IntPtrTy, IntPtrTy};
889 llvm::FunctionType *FTy =
890 llvm::FunctionType::get(CGM.VoidTy, Args, false);
891 llvm::Constant *F = CGM.CreateRuntimeFunction(
892 FTy, Prologue ? "__asan_poison_intra_object_redzone"
893 : "__asan_unpoison_intra_object_redzone");
894
895 llvm::Value *ThisPtr = LoadCXXThis();
896 ThisPtr = Builder.CreatePtrToInt(ThisPtr, IntPtrTy);
Kostya Serebryany64449212014-10-17 21:02:13 +0000897 uint64_t TypeSize = Info.getNonVirtualSize().getQuantity();
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000898 // For each field check if it has sufficient padding,
899 // if so (un)poison it with a call.
900 for (size_t i = 0; i < SSV.size(); i++) {
901 uint64_t AsanAlignment = 8;
902 uint64_t NextField = i == SSV.size() - 1 ? TypeSize : SSV[i + 1].Offset;
903 uint64_t PoisonSize = NextField - SSV[i].Offset - SSV[i].Size;
904 uint64_t EndOffset = SSV[i].Offset + SSV[i].Size;
905 if (PoisonSize < AsanAlignment || !SSV[i].Size ||
906 (NextField % AsanAlignment) != 0)
907 continue;
David Blaikie43f9bb72015-05-18 22:14:03 +0000908 Builder.CreateCall(
909 F, {Builder.CreateAdd(ThisPtr, Builder.getIntN(PtrSize, EndOffset)),
910 Builder.getIntN(PtrSize, PoisonSize)});
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000911 }
912}
913
John McCallb81884d2010-02-19 09:25:03 +0000914/// EmitConstructorBody - Emits the body of the current constructor.
915void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000916 EmitAsanPrologueOrEpilogue(true);
John McCallb81884d2010-02-19 09:25:03 +0000917 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
918 CXXCtorType CtorType = CurGD.getCtorType();
919
Reid Kleckner340ad862014-01-13 22:57:31 +0000920 assert((CGM.getTarget().getCXXABI().hasConstructorVariants() ||
921 CtorType == Ctor_Complete) &&
922 "can only generate complete ctor for this ABI");
923
John McCallf8ff7b92010-02-23 00:48:20 +0000924 // Before we go any further, try the complete->base constructor
925 // delegation optimization.
Timur Iskhodzhanovf32a3772012-04-20 08:05:00 +0000926 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
John McCallc8e01702013-04-16 22:48:15 +0000927 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000928 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args, Ctor->getLocEnd());
John McCallf8ff7b92010-02-23 00:48:20 +0000929 return;
930 }
931
Richard Smith46bb5812014-08-01 01:56:39 +0000932 const FunctionDecl *Definition = 0;
933 Stmt *Body = Ctor->getBody(Definition);
934 assert(Definition == Ctor && "emitting wrong constructor body");
John McCallb81884d2010-02-19 09:25:03 +0000935
John McCallf8ff7b92010-02-23 00:48:20 +0000936 // Enter the function-try-block before the constructor prologue if
937 // applicable.
John McCallf8ff7b92010-02-23 00:48:20 +0000938 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallf8ff7b92010-02-23 00:48:20 +0000939 if (IsTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000940 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000941
Justin Bogner66242d62015-04-23 23:06:47 +0000942 incrementProfileCounter(Body);
Justin Bogner81c22c22014-01-23 02:54:27 +0000943
Richard Smithcc1b96d2013-06-12 22:31:48 +0000944 RunCleanupsScope RunCleanups(*this);
John McCallb81884d2010-02-19 09:25:03 +0000945
John McCall88313032012-03-30 04:25:03 +0000946 // TODO: in restricted cases, we can emit the vbase initializers of
947 // a complete ctor and then delegate to the base ctor.
948
John McCallf8ff7b92010-02-23 00:48:20 +0000949 // Emit the constructor prologue, i.e. the base and member
950 // initializers.
Douglas Gregor94f9a482010-05-05 05:51:00 +0000951 EmitCtorPrologue(Ctor, CtorType, Args);
John McCallb81884d2010-02-19 09:25:03 +0000952
953 // Emit the body of the statement.
John McCallf8ff7b92010-02-23 00:48:20 +0000954 if (IsTryBody)
John McCallb81884d2010-02-19 09:25:03 +0000955 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
956 else if (Body)
957 EmitStmt(Body);
John McCallb81884d2010-02-19 09:25:03 +0000958
959 // Emit any cleanup blocks associated with the member or base
960 // initializers, which includes (along the exceptional path) the
961 // destructors for those members and bases that were fully
962 // constructed.
Richard Smithcc1b96d2013-06-12 22:31:48 +0000963 RunCleanups.ForceCleanup();
John McCallb81884d2010-02-19 09:25:03 +0000964
John McCallf8ff7b92010-02-23 00:48:20 +0000965 if (IsTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000966 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000967}
968
Lang Hamesbf122742013-02-17 07:22:09 +0000969namespace {
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000970 /// RAII object to indicate that codegen is copying the value representation
971 /// instead of the object representation. Useful when copying a struct or
972 /// class which has uninitialized members and we're only performing
973 /// lvalue-to-rvalue conversion on the object but not its members.
974 class CopyingValueRepresentation {
975 public:
976 explicit CopyingValueRepresentation(CodeGenFunction &CGF)
Alexey Samsonov035462c2014-10-30 19:33:44 +0000977 : CGF(CGF), OldSanOpts(CGF.SanOpts) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000978 CGF.SanOpts.set(SanitizerKind::Bool, false);
979 CGF.SanOpts.set(SanitizerKind::Enum, false);
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000980 }
981 ~CopyingValueRepresentation() {
982 CGF.SanOpts = OldSanOpts;
983 }
984 private:
985 CodeGenFunction &CGF;
Alexey Samsonova0416102014-11-11 01:26:14 +0000986 SanitizerSet OldSanOpts;
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000987 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000988}
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000989
990namespace {
Lang Hamesbf122742013-02-17 07:22:09 +0000991 class FieldMemcpyizer {
992 public:
993 FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl,
994 const VarDecl *SrcRec)
Justin Bogner1cd11f12015-05-20 15:53:59 +0000995 : CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec),
Lang Hamesbf122742013-02-17 07:22:09 +0000996 RecLayout(CGF.getContext().getASTRecordLayout(ClassDecl)),
Craig Topper8a13c412014-05-21 05:09:00 +0000997 FirstField(nullptr), LastField(nullptr), FirstFieldOffset(0),
998 LastFieldOffset(0), LastAddedFieldIndex(0) {}
Lang Hamesbf122742013-02-17 07:22:09 +0000999
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00001000 bool isMemcpyableField(FieldDecl *F) const {
1001 // Never memcpy fields when we are adding poisoned paddings.
Alexey Samsonova0416102014-11-11 01:26:14 +00001002 if (CGF.getContext().getLangOpts().SanitizeAddressFieldPadding)
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00001003 return false;
Lang Hamesbf122742013-02-17 07:22:09 +00001004 Qualifiers Qual = F->getType().getQualifiers();
1005 if (Qual.hasVolatile() || Qual.hasObjCLifetime())
1006 return false;
1007 return true;
1008 }
1009
1010 void addMemcpyableField(FieldDecl *F) {
Craig Topper8a13c412014-05-21 05:09:00 +00001011 if (!FirstField)
Lang Hamesbf122742013-02-17 07:22:09 +00001012 addInitialField(F);
1013 else
1014 addNextField(F);
1015 }
1016
David Majnemera586eb22014-10-10 18:57:10 +00001017 CharUnits getMemcpySize(uint64_t FirstByteOffset) const {
Lang Hamesbf122742013-02-17 07:22:09 +00001018 unsigned LastFieldSize =
1019 LastField->isBitField() ?
1020 LastField->getBitWidthValue(CGF.getContext()) :
Justin Bogner1cd11f12015-05-20 15:53:59 +00001021 CGF.getContext().getTypeSize(LastField->getType());
Lang Hamesbf122742013-02-17 07:22:09 +00001022 uint64_t MemcpySizeBits =
David Majnemera586eb22014-10-10 18:57:10 +00001023 LastFieldOffset + LastFieldSize - FirstByteOffset +
Lang Hamesbf122742013-02-17 07:22:09 +00001024 CGF.getContext().getCharWidth() - 1;
1025 CharUnits MemcpySize =
1026 CGF.getContext().toCharUnitsFromBits(MemcpySizeBits);
1027 return MemcpySize;
1028 }
1029
1030 void emitMemcpy() {
1031 // Give the subclass a chance to bail out if it feels the memcpy isn't
1032 // worth it (e.g. Hasn't aggregated enough data).
Craig Topper8a13c412014-05-21 05:09:00 +00001033 if (!FirstField) {
Lang Hamesbf122742013-02-17 07:22:09 +00001034 return;
1035 }
1036
David Majnemera586eb22014-10-10 18:57:10 +00001037 uint64_t FirstByteOffset;
Lang Hamesbf122742013-02-17 07:22:09 +00001038 if (FirstField->isBitField()) {
1039 const CGRecordLayout &RL =
1040 CGF.getTypes().getCGRecordLayout(FirstField->getParent());
1041 const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField);
David Majnemera586eb22014-10-10 18:57:10 +00001042 // FirstFieldOffset is not appropriate for bitfields,
Ulrich Weigand73263d72015-07-13 11:52:14 +00001043 // we need to use the storage offset instead.
Ulrich Weigand03ce2a12015-07-10 17:30:00 +00001044 FirstByteOffset = CGF.getContext().toBits(BFInfo.StorageOffset);
Lang Hames1694e0d2013-02-27 04:14:49 +00001045 } else {
David Majnemera586eb22014-10-10 18:57:10 +00001046 FirstByteOffset = FirstFieldOffset;
Lang Hames1694e0d2013-02-27 04:14:49 +00001047 }
Lang Hamesbf122742013-02-17 07:22:09 +00001048
David Majnemera586eb22014-10-10 18:57:10 +00001049 CharUnits MemcpySize = getMemcpySize(FirstByteOffset);
Lang Hamesbf122742013-02-17 07:22:09 +00001050 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
John McCall7f416cc2015-09-08 08:05:57 +00001051 Address ThisPtr = CGF.LoadCXXThisAddress();
1052 LValue DestLV = CGF.MakeAddrLValue(ThisPtr, RecordTy);
Lang Hamesbf122742013-02-17 07:22:09 +00001053 LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField);
1054 llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec));
1055 LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
1056 LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField);
1057
John McCall7f416cc2015-09-08 08:05:57 +00001058 emitMemcpyIR(Dest.isBitField() ? Dest.getBitFieldAddress() : Dest.getAddress(),
1059 Src.isBitField() ? Src.getBitFieldAddress() : Src.getAddress(),
1060 MemcpySize);
Lang Hamesbf122742013-02-17 07:22:09 +00001061 reset();
1062 }
1063
1064 void reset() {
Craig Topper8a13c412014-05-21 05:09:00 +00001065 FirstField = nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001066 }
1067
1068 protected:
1069 CodeGenFunction &CGF;
1070 const CXXRecordDecl *ClassDecl;
1071
1072 private:
1073
John McCall7f416cc2015-09-08 08:05:57 +00001074 void emitMemcpyIR(Address DestPtr, Address SrcPtr, CharUnits Size) {
1075 llvm::PointerType *DPT = DestPtr.getType();
Lang Hamesbf122742013-02-17 07:22:09 +00001076 llvm::Type *DBP =
1077 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), DPT->getAddressSpace());
1078 DestPtr = CGF.Builder.CreateBitCast(DestPtr, DBP);
1079
John McCall7f416cc2015-09-08 08:05:57 +00001080 llvm::PointerType *SPT = SrcPtr.getType();
Lang Hamesbf122742013-02-17 07:22:09 +00001081 llvm::Type *SBP =
1082 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), SPT->getAddressSpace());
1083 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, SBP);
1084
John McCall7f416cc2015-09-08 08:05:57 +00001085 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity());
Lang Hamesbf122742013-02-17 07:22:09 +00001086 }
1087
1088 void addInitialField(FieldDecl *F) {
1089 FirstField = F;
1090 LastField = F;
1091 FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex());
1092 LastFieldOffset = FirstFieldOffset;
1093 LastAddedFieldIndex = F->getFieldIndex();
1094 return;
1095 }
1096
1097 void addNextField(FieldDecl *F) {
John McCall6054d5a2013-05-07 05:20:46 +00001098 // For the most part, the following invariant will hold:
1099 // F->getFieldIndex() == LastAddedFieldIndex + 1
1100 // The one exception is that Sema won't add a copy-initializer for an
1101 // unnamed bitfield, which will show up here as a gap in the sequence.
1102 assert(F->getFieldIndex() >= LastAddedFieldIndex + 1 &&
1103 "Cannot aggregate fields out of order.");
Lang Hamesbf122742013-02-17 07:22:09 +00001104 LastAddedFieldIndex = F->getFieldIndex();
1105
1106 // The 'first' and 'last' fields are chosen by offset, rather than field
1107 // index. This allows the code to support bitfields, as well as regular
1108 // fields.
1109 uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex());
1110 if (FOffset < FirstFieldOffset) {
1111 FirstField = F;
1112 FirstFieldOffset = FOffset;
1113 } else if (FOffset > LastFieldOffset) {
1114 LastField = F;
1115 LastFieldOffset = FOffset;
1116 }
1117 }
1118
1119 const VarDecl *SrcRec;
1120 const ASTRecordLayout &RecLayout;
1121 FieldDecl *FirstField;
1122 FieldDecl *LastField;
1123 uint64_t FirstFieldOffset, LastFieldOffset;
1124 unsigned LastAddedFieldIndex;
1125 };
1126
1127 class ConstructorMemcpyizer : public FieldMemcpyizer {
1128 private:
1129
1130 /// Get source argument for copy constructor. Returns null if not a copy
David Majnemer196ac332014-09-11 23:05:02 +00001131 /// constructor.
1132 static const VarDecl *getTrivialCopySource(CodeGenFunction &CGF,
1133 const CXXConstructorDecl *CD,
Lang Hamesbf122742013-02-17 07:22:09 +00001134 FunctionArgList &Args) {
Jordan Rose54533f72013-08-07 16:16:48 +00001135 if (CD->isCopyOrMoveConstructor() && CD->isDefaulted())
David Majnemer196ac332014-09-11 23:05:02 +00001136 return Args[CGF.CGM.getCXXABI().getSrcArgforCopyCtor(CD, Args)];
Craig Topper8a13c412014-05-21 05:09:00 +00001137 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001138 }
1139
1140 // Returns true if a CXXCtorInitializer represents a member initialization
1141 // that can be rolled into a memcpy.
1142 bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const {
1143 if (!MemcpyableCtor)
1144 return false;
1145 FieldDecl *Field = MemberInit->getMember();
Craig Topper8a13c412014-05-21 05:09:00 +00001146 assert(Field && "No field for member init.");
Lang Hamesbf122742013-02-17 07:22:09 +00001147 QualType FieldType = Field->getType();
1148 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
1149
Richard Smith419bd092015-04-29 19:26:57 +00001150 // Bail out on non-memcpyable, not-trivially-copyable members.
1151 if (!(CE && isMemcpyEquivalentSpecialMember(CE->getConstructor())) &&
Lang Hamesbf122742013-02-17 07:22:09 +00001152 !(FieldType.isTriviallyCopyableType(CGF.getContext()) ||
1153 FieldType->isReferenceType()))
1154 return false;
1155
1156 // Bail out on volatile fields.
1157 if (!isMemcpyableField(Field))
1158 return false;
1159
1160 // Otherwise we're good.
1161 return true;
1162 }
1163
1164 public:
1165 ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD,
1166 FunctionArgList &Args)
David Majnemer196ac332014-09-11 23:05:02 +00001167 : FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CGF, CD, Args)),
Lang Hamesbf122742013-02-17 07:22:09 +00001168 ConstructorDecl(CD),
Jordan Rose54533f72013-08-07 16:16:48 +00001169 MemcpyableCtor(CD->isDefaulted() &&
Lang Hamesbf122742013-02-17 07:22:09 +00001170 CD->isCopyOrMoveConstructor() &&
1171 CGF.getLangOpts().getGC() == LangOptions::NonGC),
1172 Args(Args) { }
1173
1174 void addMemberInitializer(CXXCtorInitializer *MemberInit) {
1175 if (isMemberInitMemcpyable(MemberInit)) {
1176 AggregatedInits.push_back(MemberInit);
1177 addMemcpyableField(MemberInit->getMember());
1178 } else {
1179 emitAggregatedInits();
1180 EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit,
1181 ConstructorDecl, Args);
1182 }
1183 }
1184
1185 void emitAggregatedInits() {
1186 if (AggregatedInits.size() <= 1) {
1187 // This memcpy is too small to be worthwhile. Fall back on default
1188 // codegen.
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001189 if (!AggregatedInits.empty()) {
1190 CopyingValueRepresentation CVR(CGF);
Lang Hamesbf122742013-02-17 07:22:09 +00001191 EmitMemberInitializer(CGF, ConstructorDecl->getParent(),
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001192 AggregatedInits[0], ConstructorDecl, Args);
Alexey Bataev152c71f2015-07-14 07:55:48 +00001193 AggregatedInits.clear();
Lang Hamesbf122742013-02-17 07:22:09 +00001194 }
1195 reset();
1196 return;
1197 }
1198
1199 pushEHDestructors();
1200 emitMemcpy();
1201 AggregatedInits.clear();
1202 }
1203
1204 void pushEHDestructors() {
John McCall7f416cc2015-09-08 08:05:57 +00001205 Address ThisPtr = CGF.LoadCXXThisAddress();
Lang Hamesbf122742013-02-17 07:22:09 +00001206 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
John McCall7f416cc2015-09-08 08:05:57 +00001207 LValue LHS = CGF.MakeAddrLValue(ThisPtr, RecordTy);
Lang Hamesbf122742013-02-17 07:22:09 +00001208
1209 for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
Alexey Bataev152c71f2015-07-14 07:55:48 +00001210 CXXCtorInitializer *MemberInit = AggregatedInits[i];
1211 QualType FieldType = MemberInit->getAnyMember()->getType();
Lang Hamesbf122742013-02-17 07:22:09 +00001212 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
Alexey Bataev152c71f2015-07-14 07:55:48 +00001213 if (!CGF.needsEHCleanup(dtorKind))
1214 continue;
1215 LValue FieldLHS = LHS;
1216 EmitLValueForAnyFieldInitialization(CGF, MemberInit, FieldLHS);
1217 CGF.pushEHDestroy(dtorKind, FieldLHS.getAddress(), FieldType);
Lang Hamesbf122742013-02-17 07:22:09 +00001218 }
1219 }
1220
1221 void finish() {
1222 emitAggregatedInits();
1223 }
1224
1225 private:
1226 const CXXConstructorDecl *ConstructorDecl;
1227 bool MemcpyableCtor;
1228 FunctionArgList &Args;
1229 SmallVector<CXXCtorInitializer*, 16> AggregatedInits;
1230 };
1231
1232 class AssignmentMemcpyizer : public FieldMemcpyizer {
1233 private:
1234
1235 // Returns the memcpyable field copied by the given statement, if one
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001236 // exists. Otherwise returns null.
1237 FieldDecl *getMemcpyableField(Stmt *S) {
Lang Hamesbf122742013-02-17 07:22:09 +00001238 if (!AssignmentsMemcpyable)
Craig Topper8a13c412014-05-21 05:09:00 +00001239 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001240 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
1241 // Recognise trivial assignments.
1242 if (BO->getOpcode() != BO_Assign)
Craig Topper8a13c412014-05-21 05:09:00 +00001243 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001244 MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS());
1245 if (!ME)
Craig Topper8a13c412014-05-21 05:09:00 +00001246 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001247 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1248 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001249 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001250 Stmt *RHS = BO->getRHS();
1251 if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS))
1252 RHS = EC->getSubExpr();
1253 if (!RHS)
Craig Topper8a13c412014-05-21 05:09:00 +00001254 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001255 MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS);
1256 if (dyn_cast<FieldDecl>(ME2->getMemberDecl()) != Field)
Craig Topper8a13c412014-05-21 05:09:00 +00001257 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001258 return Field;
1259 } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) {
1260 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl());
Richard Smith419bd092015-04-29 19:26:57 +00001261 if (!(MD && isMemcpyEquivalentSpecialMember(MD)))
Craig Topper8a13c412014-05-21 05:09:00 +00001262 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001263 MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument());
1264 if (!IOA)
Craig Topper8a13c412014-05-21 05:09:00 +00001265 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001266 FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl());
1267 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001268 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001269 MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0));
1270 if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl()))
Craig Topper8a13c412014-05-21 05:09:00 +00001271 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001272 return Field;
1273 } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1274 FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1275 if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy)
Craig Topper8a13c412014-05-21 05:09:00 +00001276 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001277 Expr *DstPtr = CE->getArg(0);
1278 if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr))
1279 DstPtr = DC->getSubExpr();
1280 UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr);
1281 if (!DUO || DUO->getOpcode() != UO_AddrOf)
Craig Topper8a13c412014-05-21 05:09:00 +00001282 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001283 MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr());
1284 if (!ME)
Craig Topper8a13c412014-05-21 05:09:00 +00001285 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001286 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1287 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001288 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001289 Expr *SrcPtr = CE->getArg(1);
1290 if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr))
1291 SrcPtr = SC->getSubExpr();
1292 UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr);
1293 if (!SUO || SUO->getOpcode() != UO_AddrOf)
Craig Topper8a13c412014-05-21 05:09:00 +00001294 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001295 MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr());
1296 if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl()))
Craig Topper8a13c412014-05-21 05:09:00 +00001297 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001298 return Field;
1299 }
1300
Craig Topper8a13c412014-05-21 05:09:00 +00001301 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001302 }
1303
1304 bool AssignmentsMemcpyable;
1305 SmallVector<Stmt*, 16> AggregatedStmts;
1306
1307 public:
1308
1309 AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD,
1310 FunctionArgList &Args)
1311 : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]),
1312 AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) {
1313 assert(Args.size() == 2);
1314 }
1315
1316 void emitAssignment(Stmt *S) {
1317 FieldDecl *F = getMemcpyableField(S);
1318 if (F) {
1319 addMemcpyableField(F);
1320 AggregatedStmts.push_back(S);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001321 } else {
Lang Hamesbf122742013-02-17 07:22:09 +00001322 emitAggregatedStmts();
1323 CGF.EmitStmt(S);
1324 }
1325 }
1326
1327 void emitAggregatedStmts() {
1328 if (AggregatedStmts.size() <= 1) {
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001329 if (!AggregatedStmts.empty()) {
1330 CopyingValueRepresentation CVR(CGF);
1331 CGF.EmitStmt(AggregatedStmts[0]);
1332 }
Lang Hamesbf122742013-02-17 07:22:09 +00001333 reset();
1334 }
1335
1336 emitMemcpy();
1337 AggregatedStmts.clear();
1338 }
1339
1340 void finish() {
1341 emitAggregatedStmts();
1342 }
1343 };
1344
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001345}
Lang Hamesbf122742013-02-17 07:22:09 +00001346
Anders Carlssonfb404882009-12-24 22:46:43 +00001347/// EmitCtorPrologue - This routine generates necessary code to initialize
1348/// base classes and non-static data members belonging to this constructor.
Anders Carlssonfb404882009-12-24 22:46:43 +00001349void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001350 CXXCtorType CtorType,
1351 FunctionArgList &Args) {
Alexis Hunt61bc1732011-05-01 07:04:31 +00001352 if (CD->isDelegatingConstructor())
1353 return EmitDelegatingCXXConstructorCall(CD, Args);
1354
Anders Carlssonfb404882009-12-24 22:46:43 +00001355 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlsson5dc86332010-02-02 19:58:43 +00001356
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001357 CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
1358 E = CD->init_end();
1359
Craig Topper8a13c412014-05-21 05:09:00 +00001360 llvm::BasicBlock *BaseCtorContinueBB = nullptr;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001361 if (ClassDecl->getNumVBases() &&
1362 !CGM.getTarget().getCXXABI().hasConstructorVariants()) {
1363 // The ABIs that don't have constructor variants need to put a branch
1364 // before the virtual base initialization code.
Reid Kleckner7810af02013-06-19 15:20:38 +00001365 BaseCtorContinueBB =
1366 CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this, ClassDecl);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001367 assert(BaseCtorContinueBB);
1368 }
1369
1370 // Virtual base initializers first.
1371 for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
1372 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
1373 }
1374
1375 if (BaseCtorContinueBB) {
1376 // Complete object handler should continue to the remaining initializers.
1377 Builder.CreateBr(BaseCtorContinueBB);
1378 EmitBlock(BaseCtorContinueBB);
1379 }
1380
1381 // Then, non-virtual base initializers.
1382 for (; B != E && (*B)->isBaseInitializer(); B++) {
1383 assert(!(*B)->isBaseVirtual());
1384 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
Anders Carlssonfb404882009-12-24 22:46:43 +00001385 }
1386
Anders Carlssond5895932010-03-28 21:07:49 +00001387 InitializeVTablePointers(ClassDecl);
Anders Carlsson5dc86332010-02-02 19:58:43 +00001388
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001389 // And finally, initialize class members.
John McCall7f416cc2015-09-08 08:05:57 +00001390 FieldConstructionScope FCS(*this, LoadCXXThisAddress());
Lang Hamesbf122742013-02-17 07:22:09 +00001391 ConstructorMemcpyizer CM(*this, CD, Args);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001392 for (; B != E; B++) {
1393 CXXCtorInitializer *Member = (*B);
1394 assert(!Member->isBaseInitializer());
1395 assert(Member->isAnyMemberInitializer() &&
1396 "Delegating initializer on non-delegating constructor");
1397 CM.addMemberInitializer(Member);
1398 }
Lang Hamesbf122742013-02-17 07:22:09 +00001399 CM.finish();
Anders Carlssonfb404882009-12-24 22:46:43 +00001400}
1401
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001402static bool
1403FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
1404
1405static bool
Justin Bogner1cd11f12015-05-20 15:53:59 +00001406HasTrivialDestructorBody(ASTContext &Context,
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001407 const CXXRecordDecl *BaseClassDecl,
1408 const CXXRecordDecl *MostDerivedClassDecl)
1409{
1410 // If the destructor is trivial we don't have to check anything else.
1411 if (BaseClassDecl->hasTrivialDestructor())
1412 return true;
1413
1414 if (!BaseClassDecl->getDestructor()->hasTrivialBody())
1415 return false;
1416
1417 // Check fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001418 for (const auto *Field : BaseClassDecl->fields())
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001419 if (!FieldHasTrivialDestructorBody(Context, Field))
1420 return false;
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001421
1422 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001423 for (const auto &I : BaseClassDecl->bases()) {
1424 if (I.isVirtual())
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001425 continue;
1426
1427 const CXXRecordDecl *NonVirtualBase =
Aaron Ballman574705e2014-03-13 15:41:46 +00001428 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001429 if (!HasTrivialDestructorBody(Context, NonVirtualBase,
1430 MostDerivedClassDecl))
1431 return false;
1432 }
1433
1434 if (BaseClassDecl == MostDerivedClassDecl) {
1435 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00001436 for (const auto &I : BaseClassDecl->vbases()) {
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001437 const CXXRecordDecl *VirtualBase =
Aaron Ballman445a9392014-03-13 16:15:17 +00001438 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001439 if (!HasTrivialDestructorBody(Context, VirtualBase,
1440 MostDerivedClassDecl))
Justin Bogner1cd11f12015-05-20 15:53:59 +00001441 return false;
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001442 }
1443 }
1444
1445 return true;
1446}
1447
1448static bool
1449FieldHasTrivialDestructorBody(ASTContext &Context,
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001450 const FieldDecl *Field)
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001451{
1452 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
1453
1454 const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
1455 if (!RT)
1456 return true;
Justin Bogner1cd11f12015-05-20 15:53:59 +00001457
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001458 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Davide Italiano982bbf42015-06-26 00:18:35 +00001459
1460 // The destructor for an implicit anonymous union member is never invoked.
1461 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
1462 return false;
1463
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001464 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
1465}
1466
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001467/// CanSkipVTablePointerInitialization - Check whether we need to initialize
1468/// any vtable pointers before calling this destructor.
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001469static bool CanSkipVTablePointerInitialization(CodeGenFunction &CGF,
Anders Carlssond6f15182011-05-16 04:08:36 +00001470 const CXXDestructorDecl *Dtor) {
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001471 if (!Dtor->hasTrivialBody())
1472 return false;
1473
1474 // Check the fields.
1475 const CXXRecordDecl *ClassDecl = Dtor->getParent();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001476 for (const auto *Field : ClassDecl->fields())
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001477 if (!FieldHasTrivialDestructorBody(CGF.getContext(), Field))
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001478 return false;
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001479
1480 return true;
1481}
1482
John McCallb81884d2010-02-19 09:25:03 +00001483/// EmitDestructorBody - Emits the body of the current destructor.
1484void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
1485 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
1486 CXXDtorType DtorType = CurGD.getDtorType();
1487
Justin Bognerfb298222015-05-20 16:16:23 +00001488 Stmt *Body = Dtor->getBody();
1489 if (Body)
1490 incrementProfileCounter(Body);
1491
John McCallf99a6312010-07-21 05:30:47 +00001492 // The call to operator delete in a deleting destructor happens
1493 // outside of the function-try-block, which means it's always
1494 // possible to delegate the destructor body to the complete
1495 // destructor. Do so.
1496 if (DtorType == Dtor_Deleting) {
1497 EnterDtorCleanups(Dtor, Dtor_Deleting);
1498 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
John McCall7f416cc2015-09-08 08:05:57 +00001499 /*Delegating=*/false, LoadCXXThisAddress());
John McCallf99a6312010-07-21 05:30:47 +00001500 PopCleanupBlock();
1501 return;
1502 }
1503
John McCallb81884d2010-02-19 09:25:03 +00001504 // If the body is a function-try-block, enter the try before
John McCallf99a6312010-07-21 05:30:47 +00001505 // anything else.
1506 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallb81884d2010-02-19 09:25:03 +00001507 if (isTryBody)
John McCallb609d3f2010-07-07 06:56:46 +00001508 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00001509 EmitAsanPrologueOrEpilogue(false);
John McCallb81884d2010-02-19 09:25:03 +00001510
John McCallf99a6312010-07-21 05:30:47 +00001511 // Enter the epilogue cleanups.
1512 RunCleanupsScope DtorEpilogue(*this);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001513
John McCallb81884d2010-02-19 09:25:03 +00001514 // If this is the complete variant, just invoke the base variant;
1515 // the epilogue will destruct the virtual bases. But we can't do
1516 // this optimization if the body is a function-try-block, because
Justin Bogner1cd11f12015-05-20 15:53:59 +00001517 // we'd introduce *two* handler blocks. In the Microsoft ABI, we
Reid Klecknere7de47e2013-07-22 13:51:44 +00001518 // always delegate because we might not have a definition in this TU.
John McCallf99a6312010-07-21 05:30:47 +00001519 switch (DtorType) {
Rafael Espindola1e4df922014-09-16 15:18:21 +00001520 case Dtor_Comdat:
1521 llvm_unreachable("not expecting a COMDAT");
1522
John McCallf99a6312010-07-21 05:30:47 +00001523 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
1524
1525 case Dtor_Complete:
Reid Klecknere7de47e2013-07-22 13:51:44 +00001526 assert((Body || getTarget().getCXXABI().isMicrosoft()) &&
1527 "can't emit a dtor without a body for non-Microsoft ABIs");
1528
John McCallf99a6312010-07-21 05:30:47 +00001529 // Enter the cleanup scopes for virtual bases.
1530 EnterDtorCleanups(Dtor, Dtor_Complete);
1531
Reid Klecknere7de47e2013-07-22 13:51:44 +00001532 if (!isTryBody) {
John McCallf99a6312010-07-21 05:30:47 +00001533 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
John McCall7f416cc2015-09-08 08:05:57 +00001534 /*Delegating=*/false, LoadCXXThisAddress());
John McCallf99a6312010-07-21 05:30:47 +00001535 break;
1536 }
1537 // Fallthrough: act like we're in the base variant.
Justin Bogner1cd11f12015-05-20 15:53:59 +00001538
John McCallf99a6312010-07-21 05:30:47 +00001539 case Dtor_Base:
Reid Klecknere7de47e2013-07-22 13:51:44 +00001540 assert(Body);
1541
John McCallf99a6312010-07-21 05:30:47 +00001542 // Enter the cleanup scopes for fields and non-virtual bases.
1543 EnterDtorCleanups(Dtor, Dtor_Base);
1544
1545 // Initialize the vtable pointers before entering the body.
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001546 if (!CanSkipVTablePointerInitialization(*this, Dtor))
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001547 InitializeVTablePointers(Dtor->getParent());
John McCallf99a6312010-07-21 05:30:47 +00001548
1549 if (isTryBody)
1550 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
1551 else if (Body)
1552 EmitStmt(Body);
1553 else {
1554 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
1555 // nothing to do besides what's in the epilogue
1556 }
Fariborz Jahanian0c12ed12011-02-02 23:12:46 +00001557 // -fapple-kext must inline any call to this dtor into
1558 // the caller's body.
Richard Smith9c6890a2012-11-01 22:30:59 +00001559 if (getLangOpts().AppleKext)
Bill Wendling207f0532012-12-20 19:27:06 +00001560 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
Naomi Musgravee50cb9b2015-08-13 18:35:11 +00001561
John McCallf99a6312010-07-21 05:30:47 +00001562 break;
John McCallb81884d2010-02-19 09:25:03 +00001563 }
1564
John McCallf99a6312010-07-21 05:30:47 +00001565 // Jump out through the epilogue cleanups.
1566 DtorEpilogue.ForceCleanup();
John McCallb81884d2010-02-19 09:25:03 +00001567
1568 // Exit the try if applicable.
1569 if (isTryBody)
John McCallb609d3f2010-07-07 06:56:46 +00001570 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +00001571}
1572
Lang Hamesbf122742013-02-17 07:22:09 +00001573void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) {
1574 const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
1575 const Stmt *RootS = AssignOp->getBody();
1576 assert(isa<CompoundStmt>(RootS) &&
1577 "Body of an implicit assignment operator should be compound stmt.");
1578 const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
1579
1580 LexicalScope Scope(*this, RootCS->getSourceRange());
1581
1582 AssignmentMemcpyizer AM(*this, AssignOp, Args);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001583 for (auto *I : RootCS->body())
Justin Bogner1cd11f12015-05-20 15:53:59 +00001584 AM.emitAssignment(I);
Lang Hamesbf122742013-02-17 07:22:09 +00001585 AM.finish();
1586}
1587
John McCallf99a6312010-07-21 05:30:47 +00001588namespace {
1589 /// Call the operator delete associated with the current destructor.
David Blaikie7e70d682015-08-18 22:40:54 +00001590 struct CallDtorDelete final : EHScopeStack::Cleanup {
John McCallf99a6312010-07-21 05:30:47 +00001591 CallDtorDelete() {}
1592
Craig Topper4f12f102014-03-12 06:41:41 +00001593 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallf99a6312010-07-21 05:30:47 +00001594 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1595 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1596 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1597 CGF.getContext().getTagDeclType(ClassDecl));
1598 }
1599 };
1600
David Blaikie7e70d682015-08-18 22:40:54 +00001601 struct CallDtorDeleteConditional final : EHScopeStack::Cleanup {
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001602 llvm::Value *ShouldDeleteCondition;
1603 public:
1604 CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001605 : ShouldDeleteCondition(ShouldDeleteCondition) {
Craig Topper8a13c412014-05-21 05:09:00 +00001606 assert(ShouldDeleteCondition != nullptr);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001607 }
1608
Craig Topper4f12f102014-03-12 06:41:41 +00001609 void Emit(CodeGenFunction &CGF, Flags flags) override {
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001610 llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
1611 llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
1612 llvm::Value *ShouldCallDelete
1613 = CGF.Builder.CreateIsNull(ShouldDeleteCondition);
1614 CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
1615
1616 CGF.EmitBlock(callDeleteBB);
1617 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1618 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1619 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1620 CGF.getContext().getTagDeclType(ClassDecl));
1621 CGF.Builder.CreateBr(continueBB);
1622
1623 CGF.EmitBlock(continueBB);
1624 }
1625 };
1626
David Blaikie7e70d682015-08-18 22:40:54 +00001627 class DestroyField final : public EHScopeStack::Cleanup {
John McCall4bd0fb12011-07-12 16:41:08 +00001628 const FieldDecl *field;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001629 CodeGenFunction::Destroyer *destroyer;
John McCall4bd0fb12011-07-12 16:41:08 +00001630 bool useEHCleanupForArray;
John McCallf99a6312010-07-21 05:30:47 +00001631
John McCall4bd0fb12011-07-12 16:41:08 +00001632 public:
1633 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
1634 bool useEHCleanupForArray)
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001635 : field(field), destroyer(destroyer),
1636 useEHCleanupForArray(useEHCleanupForArray) {}
John McCallf99a6312010-07-21 05:30:47 +00001637
Craig Topper4f12f102014-03-12 06:41:41 +00001638 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall4bd0fb12011-07-12 16:41:08 +00001639 // Find the address of the field.
John McCall7f416cc2015-09-08 08:05:57 +00001640 Address thisValue = CGF.LoadCXXThisAddress();
Eli Friedman7f1ff602012-04-16 03:54:45 +00001641 QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
1642 LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
1643 LValue LV = CGF.EmitLValueForField(ThisLV, field);
John McCall4bd0fb12011-07-12 16:41:08 +00001644 assert(LV.isSimple());
Justin Bogner1cd11f12015-05-20 15:53:59 +00001645
John McCall4bd0fb12011-07-12 16:41:08 +00001646 CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +00001647 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCallf99a6312010-07-21 05:30:47 +00001648 }
1649 };
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001650
1651 class SanitizeDtor final : public EHScopeStack::Cleanup {
1652 const CXXDestructorDecl *Dtor;
1653
1654 public:
1655 SanitizeDtor(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
1656
1657 // Generate function call for handling object poisoning.
1658 // Disables tail call elimination, to prevent the current stack frame
1659 // from disappearing from the stack trace.
1660 void Emit(CodeGenFunction &CGF, Flags flags) override {
1661 const ASTRecordLayout &Layout =
1662 CGF.getContext().getASTRecordLayout(Dtor->getParent());
1663
1664 // Nothing to poison.
1665 if (Layout.getFieldCount() == 0)
1666 return;
1667
1668 // Prevent the current stack frame from disappearing from the stack trace.
1669 CGF.CurFn->addFnAttr("disable-tail-calls", "true");
1670
1671 // Construct pointer to region to begin poisoning, and calculate poison
1672 // size, so that only members declared in this class are poisoned.
1673 ASTContext &Context = CGF.getContext();
1674 unsigned fieldIndex = 0;
1675 int startIndex = -1;
1676 // RecordDecl::field_iterator Field;
1677 for (const FieldDecl *Field : Dtor->getParent()->fields()) {
1678 // Poison field if it is trivial
1679 if (FieldHasTrivialDestructorBody(Context, Field)) {
1680 // Start sanitizing at this field
1681 if (startIndex < 0)
1682 startIndex = fieldIndex;
1683
1684 // Currently on the last field, and it must be poisoned with the
1685 // current block.
1686 if (fieldIndex == Layout.getFieldCount() - 1) {
1687 PoisonBlock(CGF, startIndex, Layout.getFieldCount());
1688 }
1689 } else if (startIndex >= 0) {
1690 // No longer within a block of memory to poison, so poison the block
1691 PoisonBlock(CGF, startIndex, fieldIndex);
1692 // Re-set the start index
1693 startIndex = -1;
1694 }
1695 fieldIndex += 1;
1696 }
1697 }
1698
1699 private:
NAKAMURA Takumif6cef72f2015-09-04 05:19:31 +00001700 /// \param layoutStartOffset index of the ASTRecordLayout field to
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001701 /// start poisoning (inclusive)
NAKAMURA Takumif6cef72f2015-09-04 05:19:31 +00001702 /// \param layoutEndOffset index of the ASTRecordLayout field to
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001703 /// end poisoning (exclusive)
1704 void PoisonBlock(CodeGenFunction &CGF, unsigned layoutStartOffset,
1705 unsigned layoutEndOffset) {
1706 ASTContext &Context = CGF.getContext();
1707 const ASTRecordLayout &Layout =
1708 Context.getASTRecordLayout(Dtor->getParent());
1709
1710 llvm::ConstantInt *OffsetSizePtr = llvm::ConstantInt::get(
1711 CGF.SizeTy,
1712 Context.toCharUnitsFromBits(Layout.getFieldOffset(layoutStartOffset))
1713 .getQuantity());
1714
1715 llvm::Value *OffsetPtr = CGF.Builder.CreateGEP(
1716 CGF.Builder.CreateBitCast(CGF.LoadCXXThis(), CGF.Int8PtrTy),
1717 OffsetSizePtr);
1718
1719 CharUnits::QuantityType PoisonSize;
1720 if (layoutEndOffset >= Layout.getFieldCount()) {
1721 PoisonSize = Layout.getNonVirtualSize().getQuantity() -
1722 Context.toCharUnitsFromBits(
1723 Layout.getFieldOffset(layoutStartOffset))
1724 .getQuantity();
1725 } else {
1726 PoisonSize = Context.toCharUnitsFromBits(
1727 Layout.getFieldOffset(layoutEndOffset) -
1728 Layout.getFieldOffset(layoutStartOffset))
1729 .getQuantity();
1730 }
1731
1732 if (PoisonSize == 0)
1733 return;
1734
1735 // Pass in void pointer and size of region as arguments to runtime
1736 // function
1737 llvm::Value *Args[] = {CGF.Builder.CreateBitCast(OffsetPtr, CGF.VoidPtrTy),
1738 llvm::ConstantInt::get(CGF.SizeTy, PoisonSize)};
1739
1740 llvm::Type *ArgTypes[] = {CGF.VoidPtrTy, CGF.SizeTy};
1741
1742 llvm::FunctionType *FnType =
1743 llvm::FunctionType::get(CGF.VoidTy, ArgTypes, false);
1744 llvm::Value *Fn =
1745 CGF.CGM.CreateRuntimeFunction(FnType, "__sanitizer_dtor_callback");
1746 CGF.EmitNounwindRuntimeCall(Fn, Args);
1747 }
1748 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001749}
John McCallf99a6312010-07-21 05:30:47 +00001750
Hans Wennborgdeff7032013-12-18 01:39:59 +00001751/// \brief Emit all code that comes at the end of class's
Anders Carlssonfb404882009-12-24 22:46:43 +00001752/// destructor. This is to call destructors on members and base classes
1753/// in reverse order of their construction.
John McCallf99a6312010-07-21 05:30:47 +00001754void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
1755 CXXDtorType DtorType) {
Hans Wennborg853ae942014-05-30 16:59:42 +00001756 assert((!DD->isTrivial() || DD->hasAttr<DLLExportAttr>()) &&
1757 "Should not emit dtor epilogue for non-exported trivial dtor!");
Anders Carlssonfb404882009-12-24 22:46:43 +00001758
John McCallf99a6312010-07-21 05:30:47 +00001759 // The deleting-destructor phase just needs to call the appropriate
1760 // operator delete that Sema picked up.
John McCall5c60a6f2010-02-18 19:59:28 +00001761 if (DtorType == Dtor_Deleting) {
Justin Bogner1cd11f12015-05-20 15:53:59 +00001762 assert(DD->getOperatorDelete() &&
Hans Wennborgdeff7032013-12-18 01:39:59 +00001763 "operator delete missing - EnterDtorCleanups");
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001764 if (CXXStructorImplicitParamValue) {
1765 // If there is an implicit param to the deleting dtor, it's a boolean
1766 // telling whether we should call delete at the end of the dtor.
1767 EHStack.pushCleanup<CallDtorDeleteConditional>(
1768 NormalAndEHCleanup, CXXStructorImplicitParamValue);
1769 } else {
1770 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
1771 }
John McCall5c60a6f2010-02-18 19:59:28 +00001772 return;
1773 }
1774
John McCallf99a6312010-07-21 05:30:47 +00001775 const CXXRecordDecl *ClassDecl = DD->getParent();
1776
Richard Smith20104042011-09-18 12:11:43 +00001777 // Unions have no bases and do not call field destructors.
1778 if (ClassDecl->isUnion())
1779 return;
1780
John McCallf99a6312010-07-21 05:30:47 +00001781 // The complete-destructor phase just destructs all the virtual bases.
John McCall5c60a6f2010-02-18 19:59:28 +00001782 if (DtorType == Dtor_Complete) {
John McCallf99a6312010-07-21 05:30:47 +00001783
1784 // We push them in the forward order so that they'll be popped in
1785 // the reverse order.
Aaron Ballman445a9392014-03-13 16:15:17 +00001786 for (const auto &Base : ClassDecl->vbases()) {
John McCall5c60a6f2010-02-18 19:59:28 +00001787 CXXRecordDecl *BaseClassDecl
1788 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Justin Bogner1cd11f12015-05-20 15:53:59 +00001789
John McCall5c60a6f2010-02-18 19:59:28 +00001790 // Ignore trivial destructors.
1791 if (BaseClassDecl->hasTrivialDestructor())
1792 continue;
John McCallf99a6312010-07-21 05:30:47 +00001793
John McCallcda666c2010-07-21 07:22:38 +00001794 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1795 BaseClassDecl,
1796 /*BaseIsVirtual*/ true);
John McCall5c60a6f2010-02-18 19:59:28 +00001797 }
John McCallf99a6312010-07-21 05:30:47 +00001798
John McCall5c60a6f2010-02-18 19:59:28 +00001799 return;
1800 }
1801
1802 assert(DtorType == Dtor_Base);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001803
John McCallf99a6312010-07-21 05:30:47 +00001804 // Destroy non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001805 for (const auto &Base : ClassDecl->bases()) {
John McCallf99a6312010-07-21 05:30:47 +00001806 // Ignore virtual bases.
1807 if (Base.isVirtual())
1808 continue;
Justin Bogner1cd11f12015-05-20 15:53:59 +00001809
John McCallf99a6312010-07-21 05:30:47 +00001810 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
Justin Bogner1cd11f12015-05-20 15:53:59 +00001811
John McCallf99a6312010-07-21 05:30:47 +00001812 // Ignore trivial destructors.
1813 if (BaseClassDecl->hasTrivialDestructor())
1814 continue;
John McCall5c60a6f2010-02-18 19:59:28 +00001815
John McCallcda666c2010-07-21 07:22:38 +00001816 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1817 BaseClassDecl,
1818 /*BaseIsVirtual*/ false);
John McCallf99a6312010-07-21 05:30:47 +00001819 }
1820
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001821 // Poison fields such that access after their destructors are
1822 // invoked, and before the base class destructor runs, is invalid.
1823 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1824 SanOpts.has(SanitizerKind::Memory))
1825 EHStack.pushCleanup<SanitizeDtor>(NormalAndEHCleanup, DD);
1826
John McCallf99a6312010-07-21 05:30:47 +00001827 // Destroy direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001828 for (const auto *Field : ClassDecl->fields()) {
1829 QualType type = Field->getType();
John McCall4bd0fb12011-07-12 16:41:08 +00001830 QualType::DestructionKind dtorKind = type.isDestructedType();
1831 if (!dtorKind) continue;
John McCallf99a6312010-07-21 05:30:47 +00001832
Richard Smith921bd202012-02-26 09:11:52 +00001833 // Anonymous union members do not have their destructors called.
1834 const RecordType *RT = type->getAsUnionType();
1835 if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
1836
John McCall4bd0fb12011-07-12 16:41:08 +00001837 CleanupKind cleanupKind = getCleanupKind(dtorKind);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001838 EHStack.pushCleanup<DestroyField>(cleanupKind, Field,
John McCall4bd0fb12011-07-12 16:41:08 +00001839 getDestroyer(dtorKind),
1840 cleanupKind & EHCleanup);
Anders Carlssonfb404882009-12-24 22:46:43 +00001841 }
Anders Carlssonfb404882009-12-24 22:46:43 +00001842}
1843
John McCallf677a8e2011-07-13 06:10:41 +00001844/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1845/// constructor for each of several members of an array.
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001846///
John McCallf677a8e2011-07-13 06:10:41 +00001847/// \param ctor the constructor to call for each element
John McCallf677a8e2011-07-13 06:10:41 +00001848/// \param arrayType the type of the array to initialize
1849/// \param arrayBegin an arrayType*
1850/// \param zeroInitialize true if each element should be
1851/// zero-initialized before it is constructed
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001852void CodeGenFunction::EmitCXXAggrConstructorCall(
1853 const CXXConstructorDecl *ctor, const ConstantArrayType *arrayType,
John McCall7f416cc2015-09-08 08:05:57 +00001854 Address arrayBegin, const CXXConstructExpr *E, bool zeroInitialize) {
John McCallf677a8e2011-07-13 06:10:41 +00001855 QualType elementType;
1856 llvm::Value *numElements =
1857 emitArrayLength(arrayType, elementType, arrayBegin);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001858
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001859 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin, E, zeroInitialize);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001860}
1861
John McCallf677a8e2011-07-13 06:10:41 +00001862/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1863/// constructor for each of several members of an array.
1864///
1865/// \param ctor the constructor to call for each element
1866/// \param numElements the number of elements in the array;
John McCall6549b312011-07-13 07:37:11 +00001867/// may be zero
NAKAMURA Takumiff7a9252015-09-08 09:42:41 +00001868/// \param arrayBase a T*, where T is the type constructed by ctor
John McCallf677a8e2011-07-13 06:10:41 +00001869/// \param zeroInitialize true if each element should be
1870/// zero-initialized before it is constructed
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001871void CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1872 llvm::Value *numElements,
John McCall7f416cc2015-09-08 08:05:57 +00001873 Address arrayBase,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001874 const CXXConstructExpr *E,
1875 bool zeroInitialize) {
John McCall6549b312011-07-13 07:37:11 +00001876
1877 // It's legal for numElements to be zero. This can happen both
1878 // dynamically, because x can be zero in 'new A[x]', and statically,
1879 // because of GCC extensions that permit zero-length arrays. There
1880 // are probably legitimate places where we could assume that this
1881 // doesn't happen, but it's not clear that it's worth it.
Craig Topper8a13c412014-05-21 05:09:00 +00001882 llvm::BranchInst *zeroCheckBranch = nullptr;
John McCall6549b312011-07-13 07:37:11 +00001883
1884 // Optimize for a constant count.
1885 llvm::ConstantInt *constantCount
1886 = dyn_cast<llvm::ConstantInt>(numElements);
1887 if (constantCount) {
1888 // Just skip out if the constant count is zero.
1889 if (constantCount->isZero()) return;
1890
1891 // Otherwise, emit the check.
1892 } else {
1893 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1894 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1895 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1896 EmitBlock(loopBB);
1897 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00001898
John McCallf677a8e2011-07-13 06:10:41 +00001899 // Find the end of the array.
John McCall7f416cc2015-09-08 08:05:57 +00001900 llvm::Value *arrayBegin = arrayBase.getPointer();
John McCallf677a8e2011-07-13 06:10:41 +00001901 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1902 "arrayctor.end");
Anders Carlsson27da15b2010-01-01 20:29:01 +00001903
John McCallf677a8e2011-07-13 06:10:41 +00001904 // Enter the loop, setting up a phi for the current location to initialize.
1905 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1906 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1907 EmitBlock(loopBB);
1908 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1909 "arrayctor.cur");
1910 cur->addIncoming(arrayBegin, entryBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001911
Anders Carlsson27da15b2010-01-01 20:29:01 +00001912 // Inside the loop body, emit the constructor call on the array element.
John McCallf677a8e2011-07-13 06:10:41 +00001913
John McCall7f416cc2015-09-08 08:05:57 +00001914 // The alignment of the base, adjusted by the size of a single element,
1915 // provides a conservative estimate of the alignment of every element.
1916 // (This assumes we never start tracking offsetted alignments.)
1917 //
1918 // Note that these are complete objects and so we don't need to
1919 // use the non-virtual size or alignment.
John McCallf677a8e2011-07-13 06:10:41 +00001920 QualType type = getContext().getTypeDeclType(ctor->getParent());
John McCall7f416cc2015-09-08 08:05:57 +00001921 CharUnits eltAlignment =
1922 arrayBase.getAlignment()
1923 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
1924 Address curAddr = Address(cur, eltAlignment);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001925
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001926 // Zero initialize the storage, if requested.
John McCallf677a8e2011-07-13 06:10:41 +00001927 if (zeroInitialize)
John McCall7f416cc2015-09-08 08:05:57 +00001928 EmitNullInitialization(curAddr, type);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001929
1930 // C++ [class.temporary]p4:
Anders Carlsson27da15b2010-01-01 20:29:01 +00001931 // There are two contexts in which temporaries are destroyed at a different
1932 // point than the end of the full-expression. The first context is when a
Justin Bogner1cd11f12015-05-20 15:53:59 +00001933 // default constructor is called to initialize an element of an array.
1934 // If the constructor has one or more default arguments, the destruction of
1935 // every temporary created in a default argument expression is sequenced
Anders Carlsson27da15b2010-01-01 20:29:01 +00001936 // before the construction of the next array element, if any.
Justin Bogner1cd11f12015-05-20 15:53:59 +00001937
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00001938 {
John McCallbd309292010-07-06 01:34:17 +00001939 RunCleanupsScope Scope(*this);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001940
John McCallf677a8e2011-07-13 06:10:41 +00001941 // Evaluate the constructor and its arguments in a regular
1942 // partial-destroy cleanup.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001943 if (getLangOpts().Exceptions &&
John McCallf677a8e2011-07-13 06:10:41 +00001944 !ctor->getParent()->hasTrivialDestructor()) {
1945 Destroyer *destroyer = destroyCXXObject;
John McCall7f416cc2015-09-08 08:05:57 +00001946 pushRegularPartialArrayCleanup(arrayBegin, cur, type, eltAlignment,
1947 *destroyer);
John McCallf677a8e2011-07-13 06:10:41 +00001948 }
1949
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001950 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/false,
John McCall7f416cc2015-09-08 08:05:57 +00001951 /*Delegating=*/false, curAddr, E);
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00001952 }
Anders Carlsson27da15b2010-01-01 20:29:01 +00001953
John McCallf677a8e2011-07-13 06:10:41 +00001954 // Go to the next element.
1955 llvm::Value *next =
1956 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
1957 "arrayctor.next");
1958 cur->addIncoming(next, Builder.GetInsertBlock());
Anders Carlsson27da15b2010-01-01 20:29:01 +00001959
John McCallf677a8e2011-07-13 06:10:41 +00001960 // Check whether that's the end of the loop.
1961 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
1962 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
1963 Builder.CreateCondBr(done, contBB, loopBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001964
John McCall6549b312011-07-13 07:37:11 +00001965 // Patch the earlier check to skip over the loop.
1966 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
1967
John McCallf677a8e2011-07-13 06:10:41 +00001968 EmitBlock(contBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001969}
1970
John McCall82fe67b2011-07-09 01:37:26 +00001971void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001972 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00001973 QualType type) {
1974 const RecordType *rtype = type->castAs<RecordType>();
1975 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
1976 const CXXDestructorDecl *dtor = record->getDestructor();
1977 assert(!dtor->isTrivial());
1978 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
Douglas Gregor61535002013-01-31 05:50:40 +00001979 /*Delegating=*/false, addr);
John McCall82fe67b2011-07-09 01:37:26 +00001980}
1981
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001982void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
1983 CXXCtorType Type,
1984 bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +00001985 bool Delegating, Address This,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001986 const CXXConstructExpr *E) {
Richard Smith419bd092015-04-29 19:26:57 +00001987 // C++11 [class.mfct.non-static]p2:
1988 // If a non-static member function of a class X is called for an object that
1989 // is not of type X, or of a type derived from X, the behavior is undefined.
1990 // FIXME: Provide a source location here.
John McCall7f416cc2015-09-08 08:05:57 +00001991 EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall, SourceLocation(),
1992 This.getPointer(), getContext().getRecordType(D->getParent()));
John McCallca972cd2010-02-06 00:25:16 +00001993
Richard Smith419bd092015-04-29 19:26:57 +00001994 if (D->isTrivial() && D->isDefaultConstructor()) {
1995 assert(E->getNumArgs() == 0 && "trivial default ctor with args");
1996 return;
1997 }
1998
1999 // If this is a trivial constructor, just emit what's needed. If this is a
2000 // union copy constructor, we must emit a memcpy, because the AST does not
2001 // model that copy.
2002 if (isMemcpyEquivalentSpecialMember(D)) {
Alexey Samsonov70b9c012014-08-21 20:26:47 +00002003 assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
John McCallca972cd2010-02-06 00:25:16 +00002004
Alexey Samsonov70b9c012014-08-21 20:26:47 +00002005 const Expr *Arg = E->getArg(0);
David Majnemerfd1e7392015-02-03 23:04:06 +00002006 QualType SrcTy = Arg->getType();
John McCall7f416cc2015-09-08 08:05:57 +00002007 Address Src = EmitLValue(Arg).getAddress();
Steven Wu5528da72015-08-28 07:14:10 +00002008 QualType DestTy = getContext().getTypeDeclType(D->getParent());
David Majnemerfd1e7392015-02-03 23:04:06 +00002009 EmitAggregateCopyCtor(This, Src, DestTy, SrcTy);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002010 return;
2011 }
2012
Reid Kleckner89077a12013-12-17 19:46:40 +00002013 CallArgList Args;
2014
2015 // Push the this ptr.
John McCall7f416cc2015-09-08 08:05:57 +00002016 Args.add(RValue::get(This.getPointer()), D->getThisType(getContext()));
Reid Kleckner89077a12013-12-17 19:46:40 +00002017
2018 // Add the rest of the user-supplied arguments.
2019 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
David Blaikief05779e2015-07-21 18:37:18 +00002020 EmitCallArgs(Args, FPT, E->arguments(), E->getConstructor());
Reid Kleckner89077a12013-12-17 19:46:40 +00002021
2022 // Insert any ABI-specific implicit constructor arguments.
2023 unsigned ExtraArgs = CGM.getCXXABI().addImplicitConstructorArgs(
2024 *this, D, Type, ForVirtualBase, Delegating, Args);
2025
2026 // Emit the call.
Rafael Espindola1ac0ec82014-09-11 15:42:06 +00002027 llvm::Value *Callee = CGM.getAddrOfCXXStructor(D, getFromCtorType(Type));
Reid Kleckner89077a12013-12-17 19:46:40 +00002028 const CGFunctionInfo &Info =
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002029 CGM.getTypes().arrangeCXXConstructorCall(Args, D, Type, ExtraArgs);
Reid Kleckner89077a12013-12-17 19:46:40 +00002030 EmitCall(Info, Callee, ReturnValueSlot(), Args, D);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002031}
2032
John McCallf8ff7b92010-02-23 00:48:20 +00002033void
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002034CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
John McCall7f416cc2015-09-08 08:05:57 +00002035 Address This, Address Src,
2036 const CXXConstructExpr *E) {
Richard Smith419bd092015-04-29 19:26:57 +00002037 if (isMemcpyEquivalentSpecialMember(D)) {
Alexey Samsonov96fd0a42014-08-26 20:18:26 +00002038 assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
Sebastian Redl22653ba2011-08-30 19:58:05 +00002039 assert(D->isCopyOrMoveConstructor() &&
2040 "trivial 1-arg ctor not a copy/move ctor");
David Majnemerfd1e7392015-02-03 23:04:06 +00002041 EmitAggregateCopyCtor(This, Src,
2042 getContext().getTypeDeclType(D->getParent()),
Benjamin Kramerf48ee442015-07-18 14:35:53 +00002043 (*E->arg_begin())->getType());
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002044 return;
2045 }
Rafael Espindola1ac0ec82014-09-11 15:42:06 +00002046 llvm::Value *Callee = CGM.getAddrOfCXXStructor(D, StructorType::Complete);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002047 assert(D->isInstance() &&
2048 "Trying to emit a member call expr on a static method!");
Justin Bogner1cd11f12015-05-20 15:53:59 +00002049
Reid Kleckner739756c2013-12-04 19:23:12 +00002050 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
Justin Bogner1cd11f12015-05-20 15:53:59 +00002051
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002052 CallArgList Args;
Justin Bogner1cd11f12015-05-20 15:53:59 +00002053
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002054 // Push the this ptr.
John McCall7f416cc2015-09-08 08:05:57 +00002055 Args.add(RValue::get(This.getPointer()), D->getThisType(getContext()));
Justin Bogner1cd11f12015-05-20 15:53:59 +00002056
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002057 // Push the src ptr.
Alp Toker9cacbab2014-01-20 20:26:09 +00002058 QualType QT = *(FPT->param_type_begin());
Chris Lattner2192fe52011-07-18 04:24:23 +00002059 llvm::Type *t = CGM.getTypes().ConvertType(QT);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002060 Src = Builder.CreateBitCast(Src, t);
John McCall7f416cc2015-09-08 08:05:57 +00002061 Args.add(RValue::get(Src.getPointer()), QT);
Reid Kleckner739756c2013-12-04 19:23:12 +00002062
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002063 // Skip over first argument (Src).
David Blaikief05779e2015-07-21 18:37:18 +00002064 EmitCallArgs(Args, FPT, drop_begin(E->arguments(), 1), E->getConstructor(),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002065 /*ParamsToSkip*/ 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002066
John McCall8dda7b22012-07-07 06:41:13 +00002067 EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, RequiredArgs::All),
2068 Callee, ReturnValueSlot(), Args, D);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002069}
2070
2071void
John McCallf8ff7b92010-02-23 00:48:20 +00002072CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
2073 CXXCtorType CtorType,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002074 const FunctionArgList &Args,
2075 SourceLocation Loc) {
John McCallf8ff7b92010-02-23 00:48:20 +00002076 CallArgList DelegateArgs;
2077
2078 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
2079 assert(I != E && "no parameters to constructor");
2080
2081 // this
Eli Friedman43dca6a2011-05-02 17:57:46 +00002082 DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType());
John McCallf8ff7b92010-02-23 00:48:20 +00002083 ++I;
2084
2085 // vtt
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00002086 if (llvm::Value *VTT = GetVTTParameter(GlobalDecl(Ctor, CtorType),
Douglas Gregor61535002013-01-31 05:50:40 +00002087 /*ForVirtualBase=*/false,
2088 /*Delegating=*/true)) {
John McCallf8ff7b92010-02-23 00:48:20 +00002089 QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
Eli Friedman43dca6a2011-05-02 17:57:46 +00002090 DelegateArgs.add(RValue::get(VTT), VoidPP);
John McCallf8ff7b92010-02-23 00:48:20 +00002091
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002092 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
John McCallf8ff7b92010-02-23 00:48:20 +00002093 assert(I != E && "cannot skip vtt parameter, already done with args");
John McCalla738c252011-03-09 04:27:21 +00002094 assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
John McCallf8ff7b92010-02-23 00:48:20 +00002095 ++I;
2096 }
2097 }
2098
2099 // Explicit arguments.
2100 for (; I != E; ++I) {
John McCall32ea9692011-03-11 20:59:21 +00002101 const VarDecl *param = *I;
Nick Lewycky2d84e842013-10-02 02:29:49 +00002102 // FIXME: per-argument source location
2103 EmitDelegateCallArg(DelegateArgs, param, Loc);
John McCallf8ff7b92010-02-23 00:48:20 +00002104 }
2105
Rafael Espindola1ac0ec82014-09-11 15:42:06 +00002106 llvm::Value *Callee =
2107 CGM.getAddrOfCXXStructor(Ctor, getFromCtorType(CtorType));
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00002108 EmitCall(CGM.getTypes()
2109 .arrangeCXXStructorDeclaration(Ctor, getFromCtorType(CtorType)),
Manman Ren01754612013-03-20 16:59:38 +00002110 Callee, ReturnValueSlot(), DelegateArgs, Ctor);
John McCallf8ff7b92010-02-23 00:48:20 +00002111}
2112
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002113namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002114 struct CallDelegatingCtorDtor final : EHScopeStack::Cleanup {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002115 const CXXDestructorDecl *Dtor;
John McCall7f416cc2015-09-08 08:05:57 +00002116 Address Addr;
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002117 CXXDtorType Type;
2118
John McCall7f416cc2015-09-08 08:05:57 +00002119 CallDelegatingCtorDtor(const CXXDestructorDecl *D, Address Addr,
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002120 CXXDtorType Type)
2121 : Dtor(D), Addr(Addr), Type(Type) {}
2122
Craig Topper4f12f102014-03-12 06:41:41 +00002123 void Emit(CodeGenFunction &CGF, Flags flags) override {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002124 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
Douglas Gregor61535002013-01-31 05:50:40 +00002125 /*Delegating=*/true, Addr);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002126 }
2127 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002128}
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002129
Alexis Hunt61bc1732011-05-01 07:04:31 +00002130void
2131CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
2132 const FunctionArgList &Args) {
2133 assert(Ctor->isDelegatingConstructor());
2134
John McCall7f416cc2015-09-08 08:05:57 +00002135 Address ThisPtr = LoadCXXThisAddress();
Alexis Hunt61bc1732011-05-01 07:04:31 +00002136
John McCall31168b02011-06-15 23:02:42 +00002137 AggValueSlot AggSlot =
John McCall7f416cc2015-09-08 08:05:57 +00002138 AggValueSlot::forAddr(ThisPtr, Qualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +00002139 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00002140 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00002141 AggValueSlot::IsNotAliased);
Alexis Hunt61bc1732011-05-01 07:04:31 +00002142
2143 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
Alexis Hunt61bc1732011-05-01 07:04:31 +00002144
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002145 const CXXRecordDecl *ClassDecl = Ctor->getParent();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002146 if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002147 CXXDtorType Type =
2148 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
2149
2150 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
2151 ClassDecl->getDestructor(),
2152 ThisPtr, Type);
2153 }
2154}
Alexis Hunt61bc1732011-05-01 07:04:31 +00002155
Anders Carlsson27da15b2010-01-01 20:29:01 +00002156void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
2157 CXXDtorType Type,
Anders Carlssonf8a71f02010-05-02 23:29:11 +00002158 bool ForVirtualBase,
Douglas Gregor61535002013-01-31 05:50:40 +00002159 bool Delegating,
John McCall7f416cc2015-09-08 08:05:57 +00002160 Address This) {
Reid Kleckner6fe771a2013-12-13 00:53:54 +00002161 CGM.getCXXABI().EmitDestructorCall(*this, DD, Type, ForVirtualBase,
2162 Delegating, This);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002163}
2164
John McCall53cad2e2010-07-21 01:41:18 +00002165namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002166 struct CallLocalDtor final : EHScopeStack::Cleanup {
John McCall53cad2e2010-07-21 01:41:18 +00002167 const CXXDestructorDecl *Dtor;
John McCall7f416cc2015-09-08 08:05:57 +00002168 Address Addr;
John McCall53cad2e2010-07-21 01:41:18 +00002169
John McCall7f416cc2015-09-08 08:05:57 +00002170 CallLocalDtor(const CXXDestructorDecl *D, Address Addr)
John McCall53cad2e2010-07-21 01:41:18 +00002171 : Dtor(D), Addr(Addr) {}
2172
Craig Topper4f12f102014-03-12 06:41:41 +00002173 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall53cad2e2010-07-21 01:41:18 +00002174 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +00002175 /*ForVirtualBase=*/false,
2176 /*Delegating=*/false, Addr);
John McCall53cad2e2010-07-21 01:41:18 +00002177 }
2178 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002179}
John McCall53cad2e2010-07-21 01:41:18 +00002180
John McCall8680f872010-07-21 06:29:51 +00002181void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
John McCall7f416cc2015-09-08 08:05:57 +00002182 Address Addr) {
John McCallcda666c2010-07-21 07:22:38 +00002183 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
John McCall8680f872010-07-21 06:29:51 +00002184}
2185
John McCall7f416cc2015-09-08 08:05:57 +00002186void CodeGenFunction::PushDestructorCleanup(QualType T, Address Addr) {
John McCallbd309292010-07-06 01:34:17 +00002187 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
2188 if (!ClassDecl) return;
2189 if (ClassDecl->hasTrivialDestructor()) return;
2190
2191 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCalla85af562011-04-28 02:15:35 +00002192 assert(D && D->isUsed() && "destructor not marked as used!");
John McCall8680f872010-07-21 06:29:51 +00002193 PushDestructorCleanup(D, Addr);
John McCallbd309292010-07-06 01:34:17 +00002194}
2195
Steven Wu5528da72015-08-28 07:14:10 +00002196void
2197CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
2198 const CXXRecordDecl *NearestVBase,
2199 CharUnits OffsetFromNearestVBase,
2200 const CXXRecordDecl *VTableClass) {
2201 const CXXRecordDecl *RD = Base.getBase();
2202
2203 // Don't initialize the vtable pointer if the class is marked with the
2204 // 'novtable' attribute.
2205 if ((RD == VTableClass || RD == NearestVBase) &&
2206 VTableClass->hasAttr<MSNoVTableAttr>())
2207 return;
2208
Anders Carlssone87fae92010-03-28 19:40:00 +00002209 // Compute the address point.
Steven Wu5528da72015-08-28 07:14:10 +00002210 bool NeedsVirtualOffset;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002211 llvm::Value *VTableAddressPoint =
2212 CGM.getCXXABI().getVTableAddressPointInStructor(
Steven Wu5528da72015-08-28 07:14:10 +00002213 *this, VTableClass, Base, NearestVBase, NeedsVirtualOffset);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002214 if (!VTableAddressPoint)
2215 return;
Anders Carlssone87fae92010-03-28 19:40:00 +00002216
Anders Carlsson6a0227d2010-04-20 16:22:16 +00002217 // Compute where to store the address point.
Craig Topper8a13c412014-05-21 05:09:00 +00002218 llvm::Value *VirtualOffset = nullptr;
Ken Dyckcfc332c2011-03-23 00:45:26 +00002219 CharUnits NonVirtualOffset = CharUnits::Zero();
Justin Bogner1cd11f12015-05-20 15:53:59 +00002220
Steven Wu5528da72015-08-28 07:14:10 +00002221 if (NeedsVirtualOffset) {
Anders Carlsson91baecf2010-04-20 18:05:10 +00002222 // We need to use the virtual base offset offset because the virtual base
2223 // might have a different offset in the most derived class.
John McCall7f416cc2015-09-08 08:05:57 +00002224 VirtualOffset =
2225 CGM.getCXXABI().GetVirtualBaseClassOffset(*this, LoadCXXThisAddress(),
2226 VTableClass, NearestVBase);
Steven Wu5528da72015-08-28 07:14:10 +00002227 NonVirtualOffset = OffsetFromNearestVBase;
Anders Carlsson91baecf2010-04-20 18:05:10 +00002228 } else {
Anders Carlssonc58fb552010-05-03 00:29:58 +00002229 // We can just use the base offset in the complete class.
Steven Wu5528da72015-08-28 07:14:10 +00002230 NonVirtualOffset = Base.getBaseOffset();
Anders Carlsson91baecf2010-04-20 18:05:10 +00002231 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002232
Anders Carlssonc58fb552010-05-03 00:29:58 +00002233 // Apply the offsets.
John McCall7f416cc2015-09-08 08:05:57 +00002234 Address VTableField = LoadCXXThisAddress();
Justin Bogner1cd11f12015-05-20 15:53:59 +00002235
Ken Dyckcfc332c2011-03-23 00:45:26 +00002236 if (!NonVirtualOffset.isZero() || VirtualOffset)
Justin Bogner1cd11f12015-05-20 15:53:59 +00002237 VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
Anders Carlssonc58fb552010-05-03 00:29:58 +00002238 NonVirtualOffset,
John McCall7f416cc2015-09-08 08:05:57 +00002239 VirtualOffset,
2240 VTableClass,
2241 NearestVBase);
Anders Carlsson6a0227d2010-04-20 16:22:16 +00002242
Reid Kleckner8d585132014-12-03 21:00:21 +00002243 // Finally, store the address point. Use the same LLVM types as the field to
2244 // support optimization.
2245 llvm::Type *VTablePtrTy =
2246 llvm::FunctionType::get(CGM.Int32Ty, /*isVarArg=*/true)
2247 ->getPointerTo()
2248 ->getPointerTo();
2249 VTableField = Builder.CreateBitCast(VTableField, VTablePtrTy->getPointerTo());
2250 VTableAddressPoint = Builder.CreateBitCast(VTableAddressPoint, VTablePtrTy);
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002251 llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
2252 CGM.DecorateInstruction(Store, CGM.getTBAAInfoForVTablePtr());
Anders Carlssone87fae92010-03-28 19:40:00 +00002253}
2254
Steven Wu5528da72015-08-28 07:14:10 +00002255void
2256CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
2257 const CXXRecordDecl *NearestVBase,
2258 CharUnits OffsetFromNearestVBase,
2259 bool BaseIsNonVirtualPrimaryBase,
2260 const CXXRecordDecl *VTableClass,
2261 VisitedVirtualBasesSetTy& VBases) {
Anders Carlssond5895932010-03-28 21:07:49 +00002262 // If this base is a non-virtual primary base the address point has already
2263 // been set.
2264 if (!BaseIsNonVirtualPrimaryBase) {
2265 // Initialize the vtable pointer for this base.
Steven Wu5528da72015-08-28 07:14:10 +00002266 InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
2267 VTableClass);
Anders Carlssond5895932010-03-28 21:07:49 +00002268 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002269
Anders Carlssond5895932010-03-28 21:07:49 +00002270 const CXXRecordDecl *RD = Base.getBase();
2271
2272 // Traverse bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00002273 for (const auto &I : RD->bases()) {
Anders Carlssond5895932010-03-28 21:07:49 +00002274 CXXRecordDecl *BaseDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00002275 = cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Anders Carlssond5895932010-03-28 21:07:49 +00002276
2277 // Ignore classes without a vtable.
2278 if (!BaseDecl->isDynamicClass())
2279 continue;
2280
Ken Dyck3fb4c892011-03-23 01:04:18 +00002281 CharUnits BaseOffset;
2282 CharUnits BaseOffsetFromNearestVBase;
Anders Carlsson948d3f42010-03-29 01:16:41 +00002283 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlssond5895932010-03-28 21:07:49 +00002284
Aaron Ballman574705e2014-03-13 15:41:46 +00002285 if (I.isVirtual()) {
Anders Carlssond5895932010-03-28 21:07:49 +00002286 // Check if we've visited this virtual base before.
David Blaikie82e95a32014-11-19 07:49:47 +00002287 if (!VBases.insert(BaseDecl).second)
Anders Carlssond5895932010-03-28 21:07:49 +00002288 continue;
2289
Justin Bogner1cd11f12015-05-20 15:53:59 +00002290 const ASTRecordLayout &Layout =
Anders Carlssond5895932010-03-28 21:07:49 +00002291 getContext().getASTRecordLayout(VTableClass);
2292
Ken Dyck3fb4c892011-03-23 01:04:18 +00002293 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
2294 BaseOffsetFromNearestVBase = CharUnits::Zero();
Anders Carlsson948d3f42010-03-29 01:16:41 +00002295 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlssond5895932010-03-28 21:07:49 +00002296 } else {
2297 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
2298
Ken Dyck16ffcac2011-03-24 01:21:01 +00002299 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
Justin Bogner1cd11f12015-05-20 15:53:59 +00002300 BaseOffsetFromNearestVBase =
Ken Dyck3fb4c892011-03-23 01:04:18 +00002301 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson948d3f42010-03-29 01:16:41 +00002302 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlssond5895932010-03-28 21:07:49 +00002303 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002304
Steven Wu5528da72015-08-28 07:14:10 +00002305 InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
2306 I.isVirtual() ? BaseDecl : NearestVBase,
2307 BaseOffsetFromNearestVBase,
2308 BaseDeclIsNonVirtualPrimaryBase,
2309 VTableClass, VBases);
Anders Carlssond5895932010-03-28 21:07:49 +00002310 }
2311}
2312
2313void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
2314 // Ignore classes without a vtable.
Anders Carlsson1f9348c2010-03-26 04:39:42 +00002315 if (!RD->isDynamicClass())
Anders Carlsson27da15b2010-01-01 20:29:01 +00002316 return;
2317
Anders Carlssond5895932010-03-28 21:07:49 +00002318 // Initialize the vtable pointers for this class and all of its bases.
Steven Wu5528da72015-08-28 07:14:10 +00002319 VisitedVirtualBasesSetTy VBases;
2320 InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()),
2321 /*NearestVBase=*/nullptr,
2322 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
2323 /*BaseIsNonVirtualPrimaryBase=*/false, RD, VBases);
Timur Iskhodzhanovb6487322013-10-09 18:16:58 +00002324
2325 if (RD->getNumVBases())
2326 CGM.getCXXABI().initializeHiddenVirtualInheritanceMembers(*this, RD);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002327}
Dan Gohman8fc50c22010-10-26 18:44:08 +00002328
John McCall7f416cc2015-09-08 08:05:57 +00002329llvm::Value *CodeGenFunction::GetVTablePtr(Address This,
Chris Lattner2192fe52011-07-18 04:24:23 +00002330 llvm::Type *Ty) {
John McCall7f416cc2015-09-08 08:05:57 +00002331 Address VTablePtrSrc = Builder.CreateElementBitCast(This, Ty);
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002332 llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
2333 CGM.DecorateInstruction(VTable, CGM.getTBAAInfoForVTablePtr());
2334 return VTable;
Dan Gohman8fc50c22010-10-26 18:44:08 +00002335}
Anders Carlssonc36783e2011-05-08 20:32:23 +00002336
Peter Collingbourned2926c92015-03-14 02:42:25 +00002337// If a class has a single non-virtual base and does not introduce or override
2338// virtual member functions or fields, it will have the same layout as its base.
2339// This function returns the least derived such class.
2340//
2341// Casting an instance of a base class to such a derived class is technically
2342// undefined behavior, but it is a relatively common hack for introducing member
2343// functions on class instances with specific properties (e.g. llvm::Operator)
2344// that works under most compilers and should not have security implications, so
2345// we allow it by default. It can be disabled with -fsanitize=cfi-cast-strict.
2346static const CXXRecordDecl *
2347LeastDerivedClassWithSameLayout(const CXXRecordDecl *RD) {
2348 if (!RD->field_empty())
2349 return RD;
2350
2351 if (RD->getNumVBases() != 0)
2352 return RD;
2353
2354 if (RD->getNumBases() != 1)
2355 return RD;
2356
2357 for (const CXXMethodDecl *MD : RD->methods()) {
2358 if (MD->isVirtual()) {
2359 // Virtual member functions are only ok if they are implicit destructors
2360 // because the implicit destructor will have the same semantics as the
2361 // base class's destructor if no fields are added.
2362 if (isa<CXXDestructorDecl>(MD) && MD->isImplicit())
2363 continue;
2364 return RD;
2365 }
2366 }
2367
2368 return LeastDerivedClassWithSameLayout(
2369 RD->bases_begin()->getType()->getAsCXXRecordDecl());
2370}
2371
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002372void CodeGenFunction::EmitVTablePtrCheckForCall(const CXXMethodDecl *MD,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002373 llvm::Value *VTable,
2374 CFITypeCheckKind TCK,
2375 SourceLocation Loc) {
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002376 const CXXRecordDecl *ClassDecl = MD->getParent();
2377 if (!SanOpts.has(SanitizerKind::CFICastStrict))
2378 ClassDecl = LeastDerivedClassWithSameLayout(ClassDecl);
2379
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002380 EmitVTablePtrCheck(ClassDecl, VTable, TCK, Loc);
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002381}
2382
Peter Collingbourned2926c92015-03-14 02:42:25 +00002383void CodeGenFunction::EmitVTablePtrCheckForCast(QualType T,
2384 llvm::Value *Derived,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002385 bool MayBeNull,
2386 CFITypeCheckKind TCK,
2387 SourceLocation Loc) {
Peter Collingbourned2926c92015-03-14 02:42:25 +00002388 if (!getLangOpts().CPlusPlus)
2389 return;
2390
2391 auto *ClassTy = T->getAs<RecordType>();
2392 if (!ClassTy)
2393 return;
2394
2395 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassTy->getDecl());
2396
2397 if (!ClassDecl->isCompleteDefinition() || !ClassDecl->isDynamicClass())
2398 return;
2399
Peter Collingbourned2926c92015-03-14 02:42:25 +00002400 if (!SanOpts.has(SanitizerKind::CFICastStrict))
2401 ClassDecl = LeastDerivedClassWithSameLayout(ClassDecl);
2402
2403 llvm::BasicBlock *ContBlock = 0;
2404
2405 if (MayBeNull) {
2406 llvm::Value *DerivedNotNull =
2407 Builder.CreateIsNotNull(Derived, "cast.nonnull");
2408
2409 llvm::BasicBlock *CheckBlock = createBasicBlock("cast.check");
2410 ContBlock = createBasicBlock("cast.cont");
2411
2412 Builder.CreateCondBr(DerivedNotNull, CheckBlock, ContBlock);
2413
2414 EmitBlock(CheckBlock);
2415 }
2416
John McCall7f416cc2015-09-08 08:05:57 +00002417 llvm::Value *VTable =
2418 GetVTablePtr(Address(Derived, getPointerAlign()), Int8PtrTy);
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002419 EmitVTablePtrCheck(ClassDecl, VTable, TCK, Loc);
Peter Collingbourned2926c92015-03-14 02:42:25 +00002420
2421 if (MayBeNull) {
2422 Builder.CreateBr(ContBlock);
2423 EmitBlock(ContBlock);
2424 }
2425}
2426
2427void CodeGenFunction::EmitVTablePtrCheck(const CXXRecordDecl *RD,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002428 llvm::Value *VTable,
2429 CFITypeCheckKind TCK,
2430 SourceLocation Loc) {
Peter Collingbournee5706442015-07-09 19:56:14 +00002431 if (CGM.IsCFIBlacklistedRecord(RD))
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002432 return;
2433
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002434 SanitizerScope SanScope(this);
2435
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002436 std::string OutName;
2437 llvm::raw_string_ostream Out(OutName);
2438 CGM.getCXXABI().getMangleContext().mangleCXXVTableBitSet(RD, Out);
2439
2440 llvm::Value *BitSetName = llvm::MetadataAsValue::get(
2441 getLLVMContext(), llvm::MDString::get(getLLVMContext(), Out.str()));
2442
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002443 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
2444 llvm::Value *BitSetTest =
2445 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::bitset_test),
2446 {CastedVTable, BitSetName});
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002447
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002448 SanitizerMask M;
2449 switch (TCK) {
2450 case CFITCK_VCall:
2451 M = SanitizerKind::CFIVCall;
2452 break;
2453 case CFITCK_NVCall:
2454 M = SanitizerKind::CFINVCall;
2455 break;
2456 case CFITCK_DerivedCast:
2457 M = SanitizerKind::CFIDerivedCast;
2458 break;
2459 case CFITCK_UnrelatedCast:
2460 M = SanitizerKind::CFIUnrelatedCast;
2461 break;
2462 }
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002463
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002464 llvm::Constant *StaticData[] = {
2465 EmitCheckSourceLocation(Loc),
2466 EmitCheckTypeDescriptor(QualType(RD->getTypeForDecl(), 0)),
2467 llvm::ConstantInt::get(Int8Ty, TCK),
2468 };
2469 EmitCheck(std::make_pair(BitSetTest, M), "cfi_bad_type", StaticData,
2470 CastedVTable);
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002471}
Anders Carlssonc36783e2011-05-08 20:32:23 +00002472
2473// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
2474// quite what we want.
2475static const Expr *skipNoOpCastsAndParens(const Expr *E) {
2476 while (true) {
2477 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
2478 E = PE->getSubExpr();
2479 continue;
2480 }
2481
2482 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
2483 if (CE->getCastKind() == CK_NoOp) {
2484 E = CE->getSubExpr();
2485 continue;
2486 }
2487 }
2488 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2489 if (UO->getOpcode() == UO_Extension) {
2490 E = UO->getSubExpr();
2491 continue;
2492 }
2493 }
2494 return E;
2495 }
2496}
2497
Benjamin Kramer7463ed72013-08-25 22:46:27 +00002498bool
2499CodeGenFunction::CanDevirtualizeMemberFunctionCall(const Expr *Base,
2500 const CXXMethodDecl *MD) {
2501 // When building with -fapple-kext, all calls must go through the vtable since
2502 // the kernel linker can do runtime patching of vtables.
2503 if (getLangOpts().AppleKext)
2504 return false;
2505
Anders Carlssonc36783e2011-05-08 20:32:23 +00002506 // If the most derived class is marked final, we know that no subclass can
2507 // override this member function and so we can devirtualize it. For example:
2508 //
2509 // struct A { virtual void f(); }
2510 // struct B final : A { };
2511 //
2512 // void f(B *b) {
2513 // b->f();
2514 // }
2515 //
Benjamin Kramer7463ed72013-08-25 22:46:27 +00002516 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
Anders Carlssonc36783e2011-05-08 20:32:23 +00002517 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
2518 return true;
2519
2520 // If the member function is marked 'final', we know that it can't be
2521 // overridden and can therefore devirtualize it.
2522 if (MD->hasAttr<FinalAttr>())
2523 return true;
2524
2525 // Similarly, if the class itself is marked 'final' it can't be overridden
2526 // and we can therefore devirtualize the member function call.
2527 if (MD->getParent()->hasAttr<FinalAttr>())
2528 return true;
2529
2530 Base = skipNoOpCastsAndParens(Base);
2531 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
2532 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
2533 // This is a record decl. We know the type and can devirtualize it.
2534 return VD->getType()->isRecordType();
2535 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002536
Anders Carlssonc36783e2011-05-08 20:32:23 +00002537 return false;
2538 }
Benjamin Kramer7463ed72013-08-25 22:46:27 +00002539
2540 // We can devirtualize calls on an object accessed by a class member access
2541 // expression, since by C++11 [basic.life]p6 we know that it can't refer to
2542 // a derived class object constructed in the same location.
2543 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Base))
2544 if (const ValueDecl *VD = dyn_cast<ValueDecl>(ME->getMemberDecl()))
2545 return VD->getType()->isRecordType();
2546
Anders Carlssonc36783e2011-05-08 20:32:23 +00002547 // We can always devirtualize calls on temporary object expressions.
2548 if (isa<CXXConstructExpr>(Base))
2549 return true;
Justin Bogner1cd11f12015-05-20 15:53:59 +00002550
Anders Carlssonc36783e2011-05-08 20:32:23 +00002551 // And calls on bound temporaries.
2552 if (isa<CXXBindTemporaryExpr>(Base))
2553 return true;
Justin Bogner1cd11f12015-05-20 15:53:59 +00002554
Anders Carlssonc36783e2011-05-08 20:32:23 +00002555 // Check if this is a call expr that returns a record type.
2556 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
David Majnemerced8bdf2015-02-25 17:36:15 +00002557 return CE->getCallReturnType(getContext())->isRecordType();
Anders Carlssonc36783e2011-05-08 20:32:23 +00002558
2559 // We can't devirtualize the call.
2560 return false;
2561}
2562
Faisal Vali571df122013-09-29 08:45:24 +00002563void CodeGenFunction::EmitForwardingCallToLambda(
2564 const CXXMethodDecl *callOperator,
2565 CallArgList &callArgs) {
Eli Friedman5b446882012-02-16 03:47:28 +00002566 // Get the address of the call operator.
John McCall8dda7b22012-07-07 06:41:13 +00002567 const CGFunctionInfo &calleeFnInfo =
2568 CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
2569 llvm::Value *callee =
2570 CGM.GetAddrOfFunction(GlobalDecl(callOperator),
2571 CGM.getTypes().GetFunctionType(calleeFnInfo));
Eli Friedman5b446882012-02-16 03:47:28 +00002572
John McCall8dda7b22012-07-07 06:41:13 +00002573 // Prepare the return slot.
2574 const FunctionProtoType *FPT =
2575 callOperator->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00002576 QualType resultType = FPT->getReturnType();
John McCall8dda7b22012-07-07 06:41:13 +00002577 ReturnValueSlot returnSlot;
2578 if (!resultType->isVoidType() &&
2579 calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
John McCall47fb9502013-03-07 21:37:08 +00002580 !hasScalarEvaluationKind(calleeFnInfo.getReturnType()))
John McCall8dda7b22012-07-07 06:41:13 +00002581 returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
2582
2583 // We don't need to separately arrange the call arguments because
2584 // the call can't be variadic anyway --- it's impossible to forward
2585 // variadic arguments.
Justin Bogner1cd11f12015-05-20 15:53:59 +00002586
Eli Friedman5b446882012-02-16 03:47:28 +00002587 // Now emit our call.
John McCall8dda7b22012-07-07 06:41:13 +00002588 RValue RV = EmitCall(calleeFnInfo, callee, returnSlot,
2589 callArgs, callOperator);
Eli Friedman5b446882012-02-16 03:47:28 +00002590
John McCall8dda7b22012-07-07 06:41:13 +00002591 // If necessary, copy the returned value into the slot.
2592 if (!resultType->isVoidType() && returnSlot.isNull())
2593 EmitReturnOfRValue(RV, resultType);
Eli Friedmanf5f4d2f2012-12-13 23:37:17 +00002594 else
2595 EmitBranchThroughCleanup(ReturnBlock);
Eli Friedman5b446882012-02-16 03:47:28 +00002596}
2597
Eli Friedman2495ab02012-02-25 02:48:22 +00002598void CodeGenFunction::EmitLambdaBlockInvokeBody() {
2599 const BlockDecl *BD = BlockInfo->getBlockDecl();
2600 const VarDecl *variable = BD->capture_begin()->getVariable();
2601 const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
2602
2603 // Start building arguments for forwarding call
2604 CallArgList CallArgs;
2605
2606 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
John McCall7f416cc2015-09-08 08:05:57 +00002607 Address ThisPtr = GetAddrOfBlockDecl(variable, false);
2608 CallArgs.add(RValue::get(ThisPtr.getPointer()), ThisType);
Eli Friedman2495ab02012-02-25 02:48:22 +00002609
2610 // Add the rest of the parameters.
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00002611 for (auto param : BD->params())
Nick Lewycky2d84e842013-10-02 02:29:49 +00002612 EmitDelegateCallArg(CallArgs, param, param->getLocStart());
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00002613
Justin Bogner1cd11f12015-05-20 15:53:59 +00002614 assert(!Lambda->isGenericLambda() &&
Faisal Vali571df122013-09-29 08:45:24 +00002615 "generic lambda interconversion to block not implemented");
2616 EmitForwardingCallToLambda(Lambda->getLambdaCallOperator(), CallArgs);
Eli Friedman2495ab02012-02-25 02:48:22 +00002617}
2618
2619void CodeGenFunction::EmitLambdaToBlockPointerBody(FunctionArgList &Args) {
John McCalldec348f72013-05-03 07:33:41 +00002620 if (cast<CXXMethodDecl>(CurCodeDecl)->isVariadic()) {
Eli Friedman2495ab02012-02-25 02:48:22 +00002621 // FIXME: Making this work correctly is nasty because it requires either
2622 // cloning the body of the call operator or making the call operator forward.
John McCalldec348f72013-05-03 07:33:41 +00002623 CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function");
Eli Friedman2495ab02012-02-25 02:48:22 +00002624 return;
2625 }
2626
Richard Smithb47c36f2013-11-05 09:12:18 +00002627 EmitFunctionBody(Args, cast<FunctionDecl>(CurGD.getDecl())->getBody());
Eli Friedman2495ab02012-02-25 02:48:22 +00002628}
2629
2630void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
2631 const CXXRecordDecl *Lambda = MD->getParent();
2632
2633 // Start building arguments for forwarding call
2634 CallArgList CallArgs;
2635
2636 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2637 llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
2638 CallArgs.add(RValue::get(ThisPtr), ThisType);
2639
2640 // Add the rest of the parameters.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002641 for (auto Param : MD->params())
2642 EmitDelegateCallArg(CallArgs, Param, Param->getLocStart());
2643
Faisal Vali571df122013-09-29 08:45:24 +00002644 const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
2645 // For a generic lambda, find the corresponding call operator specialization
2646 // to which the call to the static-invoker shall be forwarded.
2647 if (Lambda->isGenericLambda()) {
2648 assert(MD->isFunctionTemplateSpecialization());
2649 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
2650 FunctionTemplateDecl *CallOpTemplate = CallOp->getDescribedFunctionTemplate();
Craig Topper8a13c412014-05-21 05:09:00 +00002651 void *InsertPos = nullptr;
Justin Bogner1cd11f12015-05-20 15:53:59 +00002652 FunctionDecl *CorrespondingCallOpSpecialization =
Craig Topper7e0daca2014-06-26 04:58:53 +00002653 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
Faisal Vali571df122013-09-29 08:45:24 +00002654 assert(CorrespondingCallOpSpecialization);
2655 CallOp = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
2656 }
2657 EmitForwardingCallToLambda(CallOp, CallArgs);
Eli Friedman2495ab02012-02-25 02:48:22 +00002658}
2659
Douglas Gregor355efbb2012-02-17 03:02:34 +00002660void CodeGenFunction::EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD) {
2661 if (MD->isVariadic()) {
Eli Friedman5b446882012-02-16 03:47:28 +00002662 // FIXME: Making this work correctly is nasty because it requires either
2663 // cloning the body of the call operator or making the call operator forward.
2664 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
Eli Friedman2495ab02012-02-25 02:48:22 +00002665 return;
Eli Friedman5b446882012-02-16 03:47:28 +00002666 }
2667
Douglas Gregor355efbb2012-02-17 03:02:34 +00002668 EmitLambdaDelegatingInvokeBody(MD);
Eli Friedman5a6d5072012-02-16 01:37:33 +00002669}