blob: 5c08f67d4029db8b818e50d3064f17b0a4b7c39c [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"
Piotr Padlewski4b1ac722015-09-15 21:46:55 +000028#include "llvm/IR/Metadata.h"
Anders Carlssonc6d171e2009-10-06 22:43:30 +000029
Anders Carlsson9a57c5a2009-09-12 04:27:24 +000030using namespace clang;
31using namespace CodeGen;
32
John McCall7f416cc2015-09-08 08:05:57 +000033/// Return the best known alignment for an unknown pointer to a
34/// particular class.
35CharUnits CodeGenModule::getClassPointerAlignment(const CXXRecordDecl *RD) {
36 if (!RD->isCompleteDefinition())
37 return CharUnits::One(); // Hopefully won't be used anywhere.
38
39 auto &layout = getContext().getASTRecordLayout(RD);
40
41 // If the class is final, then we know that the pointer points to an
42 // object of that type and can use the full alignment.
43 if (RD->hasAttr<FinalAttr>()) {
44 return layout.getAlignment();
45
46 // Otherwise, we have to assume it could be a subclass.
47 } else {
48 return layout.getNonVirtualAlignment();
49 }
50}
51
52/// Return the best known alignment for a pointer to a virtual base,
53/// given the alignment of a pointer to the derived class.
54CharUnits CodeGenModule::getVBaseAlignment(CharUnits actualDerivedAlign,
55 const CXXRecordDecl *derivedClass,
56 const CXXRecordDecl *vbaseClass) {
57 // The basic idea here is that an underaligned derived pointer might
58 // indicate an underaligned base pointer.
59
60 assert(vbaseClass->isCompleteDefinition());
61 auto &baseLayout = getContext().getASTRecordLayout(vbaseClass);
62 CharUnits expectedVBaseAlign = baseLayout.getNonVirtualAlignment();
63
64 return getDynamicOffsetAlignment(actualDerivedAlign, derivedClass,
65 expectedVBaseAlign);
66}
67
68CharUnits
69CodeGenModule::getDynamicOffsetAlignment(CharUnits actualBaseAlign,
70 const CXXRecordDecl *baseDecl,
71 CharUnits expectedTargetAlign) {
72 // If the base is an incomplete type (which is, alas, possible with
73 // member pointers), be pessimistic.
74 if (!baseDecl->isCompleteDefinition())
75 return std::min(actualBaseAlign, expectedTargetAlign);
76
77 auto &baseLayout = getContext().getASTRecordLayout(baseDecl);
78 CharUnits expectedBaseAlign = baseLayout.getNonVirtualAlignment();
79
80 // If the class is properly aligned, assume the target offset is, too.
81 //
82 // This actually isn't necessarily the right thing to do --- if the
83 // class is a complete object, but it's only properly aligned for a
84 // base subobject, then the alignments of things relative to it are
85 // probably off as well. (Note that this requires the alignment of
86 // the target to be greater than the NV alignment of the derived
87 // class.)
88 //
89 // However, our approach to this kind of under-alignment can only
90 // ever be best effort; after all, we're never going to propagate
91 // alignments through variables or parameters. Note, in particular,
92 // that constructing a polymorphic type in an address that's less
93 // than pointer-aligned will generally trap in the constructor,
94 // unless we someday add some sort of attribute to change the
95 // assumed alignment of 'this'. So our goal here is pretty much
96 // just to allow the user to explicitly say that a pointer is
97 // under-aligned and then safely access its fields and v-tables.
98 if (actualBaseAlign >= expectedBaseAlign) {
99 return expectedTargetAlign;
100 }
101
102 // Otherwise, we might be offset by an arbitrary multiple of the
103 // actual alignment. The correct adjustment is to take the min of
104 // the two alignments.
105 return std::min(actualBaseAlign, expectedTargetAlign);
106}
107
108Address CodeGenFunction::LoadCXXThisAddress() {
109 assert(CurFuncDecl && "loading 'this' without a func declaration?");
110 assert(isa<CXXMethodDecl>(CurFuncDecl));
111
112 // Lazily compute CXXThisAlignment.
113 if (CXXThisAlignment.isZero()) {
114 // Just use the best known alignment for the parent.
115 // TODO: if we're currently emitting a complete-object ctor/dtor,
116 // we can always use the complete-object alignment.
117 auto RD = cast<CXXMethodDecl>(CurFuncDecl)->getParent();
118 CXXThisAlignment = CGM.getClassPointerAlignment(RD);
119 }
120
121 return Address(LoadCXXThis(), CXXThisAlignment);
122}
123
124/// Emit the address of a field using a member data pointer.
125///
126/// \param E Only used for emergency diagnostics
127Address
128CodeGenFunction::EmitCXXMemberDataPointerAddress(const Expr *E, Address base,
129 llvm::Value *memberPtr,
130 const MemberPointerType *memberPtrType,
131 AlignmentSource *alignSource) {
132 // Ask the ABI to compute the actual address.
133 llvm::Value *ptr =
134 CGM.getCXXABI().EmitMemberDataPointerAddress(*this, E, base,
135 memberPtr, memberPtrType);
136
137 QualType memberType = memberPtrType->getPointeeType();
138 CharUnits memberAlign = getNaturalTypeAlignment(memberType, alignSource);
139 memberAlign =
140 CGM.getDynamicOffsetAlignment(base.getAlignment(),
141 memberPtrType->getClass()->getAsCXXRecordDecl(),
142 memberAlign);
143 return Address(ptr, memberAlign);
144}
145
David Majnemerc1709d32015-06-23 07:31:11 +0000146CharUnits CodeGenModule::computeNonVirtualBaseClassOffset(
147 const CXXRecordDecl *DerivedClass, CastExpr::path_const_iterator Start,
148 CastExpr::path_const_iterator End) {
Ken Dycka1a4ae32011-03-22 00:53:26 +0000149 CharUnits Offset = CharUnits::Zero();
Justin Bogner1cd11f12015-05-20 15:53:59 +0000150
David Majnemerc1709d32015-06-23 07:31:11 +0000151 const ASTContext &Context = getContext();
Anders Carlssond829a022010-04-24 21:06:20 +0000152 const CXXRecordDecl *RD = DerivedClass;
Justin Bogner1cd11f12015-05-20 15:53:59 +0000153
John McCallcf142162010-08-07 06:22:56 +0000154 for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
Anders Carlssond829a022010-04-24 21:06:20 +0000155 const CXXBaseSpecifier *Base = *I;
156 assert(!Base->isVirtual() && "Should not see virtual bases here!");
157
158 // Get the layout.
159 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000160
161 const CXXRecordDecl *BaseDecl =
Anders Carlssond829a022010-04-24 21:06:20 +0000162 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Justin Bogner1cd11f12015-05-20 15:53:59 +0000163
Anders Carlssond829a022010-04-24 21:06:20 +0000164 // Add the offset.
Ken Dycka1a4ae32011-03-22 00:53:26 +0000165 Offset += Layout.getBaseClassOffset(BaseDecl);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000166
Anders Carlssond829a022010-04-24 21:06:20 +0000167 RD = BaseDecl;
168 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000169
Ken Dycka1a4ae32011-03-22 00:53:26 +0000170 return Offset;
Anders Carlssond829a022010-04-24 21:06:20 +0000171}
Anders Carlsson9a57c5a2009-09-12 04:27:24 +0000172
Anders Carlsson9150a2a2009-09-29 03:13:20 +0000173llvm::Constant *
Anders Carlsson8a64c1c2010-04-24 21:23:59 +0000174CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
John McCallcf142162010-08-07 06:22:56 +0000175 CastExpr::path_const_iterator PathBegin,
176 CastExpr::path_const_iterator PathEnd) {
177 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlsson8a64c1c2010-04-24 21:23:59 +0000178
Justin Bogner1cd11f12015-05-20 15:53:59 +0000179 CharUnits Offset =
David Majnemerc1709d32015-06-23 07:31:11 +0000180 computeNonVirtualBaseClassOffset(ClassDecl, PathBegin, PathEnd);
Ken Dycka1a4ae32011-03-22 00:53:26 +0000181 if (Offset.isZero())
Craig Topper8a13c412014-05-21 05:09:00 +0000182 return nullptr;
183
Justin Bogner1cd11f12015-05-20 15:53:59 +0000184 llvm::Type *PtrDiffTy =
Anders Carlsson8a64c1c2010-04-24 21:23:59 +0000185 Types.ConvertType(getContext().getPointerDiffType());
Justin Bogner1cd11f12015-05-20 15:53:59 +0000186
Ken Dycka1a4ae32011-03-22 00:53:26 +0000187 return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
Anders Carlsson9150a2a2009-09-29 03:13:20 +0000188}
189
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000190/// Gets the address of a direct base class within a complete object.
John McCall6ce74722010-02-16 04:15:37 +0000191/// This should only be used for (1) non-virtual bases or (2) virtual bases
192/// when the type is known to be complete (e.g. in complete destructors).
193///
194/// The object pointed to by 'This' is assumed to be non-null.
John McCall7f416cc2015-09-08 08:05:57 +0000195Address
196CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(Address This,
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000197 const CXXRecordDecl *Derived,
198 const CXXRecordDecl *Base,
199 bool BaseIsVirtual) {
John McCall6ce74722010-02-16 04:15:37 +0000200 // 'this' must be a pointer (in some address space) to Derived.
John McCall7f416cc2015-09-08 08:05:57 +0000201 assert(This.getElementType() == ConvertType(Derived));
John McCall6ce74722010-02-16 04:15:37 +0000202
203 // Compute the offset of the virtual base.
Ken Dyck6aa767c2011-03-22 01:21:15 +0000204 CharUnits Offset;
John McCall6ce74722010-02-16 04:15:37 +0000205 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000206 if (BaseIsVirtual)
Ken Dyck6aa767c2011-03-22 01:21:15 +0000207 Offset = Layout.getVBaseClassOffset(Base);
John McCall6ce74722010-02-16 04:15:37 +0000208 else
Ken Dyck6aa767c2011-03-22 01:21:15 +0000209 Offset = Layout.getBaseClassOffset(Base);
John McCall6ce74722010-02-16 04:15:37 +0000210
211 // Shift and cast down to the base type.
212 // TODO: for complete types, this should be possible with a GEP.
John McCall7f416cc2015-09-08 08:05:57 +0000213 Address V = This;
214 if (!Offset.isZero()) {
215 V = Builder.CreateElementBitCast(V, Int8Ty);
216 V = Builder.CreateConstInBoundsByteGEP(V, Offset);
John McCall6ce74722010-02-16 04:15:37 +0000217 }
John McCall7f416cc2015-09-08 08:05:57 +0000218 V = Builder.CreateElementBitCast(V, ConvertType(Base));
John McCall6ce74722010-02-16 04:15:37 +0000219
220 return V;
Anders Carlssone87fae92010-03-28 19:40:00 +0000221}
John McCall6ce74722010-02-16 04:15:37 +0000222
John McCall7f416cc2015-09-08 08:05:57 +0000223static Address
224ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, Address addr,
John McCall13a39c62012-08-01 05:04:58 +0000225 CharUnits nonVirtualOffset,
John McCall7f416cc2015-09-08 08:05:57 +0000226 llvm::Value *virtualOffset,
227 const CXXRecordDecl *derivedClass,
228 const CXXRecordDecl *nearestVBase) {
John McCall13a39c62012-08-01 05:04:58 +0000229 // Assert that we have something to do.
Craig Topper8a13c412014-05-21 05:09:00 +0000230 assert(!nonVirtualOffset.isZero() || virtualOffset != nullptr);
John McCall13a39c62012-08-01 05:04:58 +0000231
232 // Compute the offset from the static and dynamic components.
233 llvm::Value *baseOffset;
234 if (!nonVirtualOffset.isZero()) {
235 baseOffset = llvm::ConstantInt::get(CGF.PtrDiffTy,
236 nonVirtualOffset.getQuantity());
237 if (virtualOffset) {
238 baseOffset = CGF.Builder.CreateAdd(virtualOffset, baseOffset);
239 }
240 } else {
241 baseOffset = virtualOffset;
242 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000243
Anders Carlsson53cebd12010-04-20 16:03:35 +0000244 // Apply the base offset.
John McCall7f416cc2015-09-08 08:05:57 +0000245 llvm::Value *ptr = addr.getPointer();
John McCall13a39c62012-08-01 05:04:58 +0000246 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
247 ptr = CGF.Builder.CreateInBoundsGEP(ptr, baseOffset, "add.ptr");
John McCall7f416cc2015-09-08 08:05:57 +0000248
249 // If we have a virtual component, the alignment of the result will
250 // be relative only to the known alignment of that vbase.
251 CharUnits alignment;
252 if (virtualOffset) {
253 assert(nearestVBase && "virtual offset without vbase?");
254 alignment = CGF.CGM.getVBaseAlignment(addr.getAlignment(),
255 derivedClass, nearestVBase);
256 } else {
257 alignment = addr.getAlignment();
258 }
259 alignment = alignment.alignmentAtOffset(nonVirtualOffset);
260
261 return Address(ptr, alignment);
Anders Carlsson53cebd12010-04-20 16:03:35 +0000262}
263
John McCall7f416cc2015-09-08 08:05:57 +0000264Address CodeGenFunction::GetAddressOfBaseClass(
265 Address Value, const CXXRecordDecl *Derived,
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000266 CastExpr::path_const_iterator PathBegin,
267 CastExpr::path_const_iterator PathEnd, bool NullCheckValue,
268 SourceLocation Loc) {
John McCallcf142162010-08-07 06:22:56 +0000269 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssond829a022010-04-24 21:06:20 +0000270
John McCallcf142162010-08-07 06:22:56 +0000271 CastExpr::path_const_iterator Start = PathBegin;
Craig Topper8a13c412014-05-21 05:09:00 +0000272 const CXXRecordDecl *VBase = nullptr;
273
John McCall13a39c62012-08-01 05:04:58 +0000274 // Sema has done some convenient canonicalization here: if the
275 // access path involved any virtual steps, the conversion path will
276 // *start* with a step down to the correct virtual base subobject,
277 // and hence will not require any further steps.
Anders Carlssond829a022010-04-24 21:06:20 +0000278 if ((*Start)->isVirtual()) {
Justin Bogner1cd11f12015-05-20 15:53:59 +0000279 VBase =
Anders Carlssond829a022010-04-24 21:06:20 +0000280 cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
281 ++Start;
282 }
John McCall13a39c62012-08-01 05:04:58 +0000283
284 // Compute the static offset of the ultimate destination within its
285 // allocating subobject (the virtual base, if there is one, or else
286 // the "complete" object that we see).
David Majnemerc1709d32015-06-23 07:31:11 +0000287 CharUnits NonVirtualOffset = CGM.computeNonVirtualBaseClassOffset(
288 VBase ? VBase : Derived, Start, PathEnd);
Anders Carlssond829a022010-04-24 21:06:20 +0000289
John McCall13a39c62012-08-01 05:04:58 +0000290 // If there's a virtual step, we can sometimes "devirtualize" it.
291 // For now, that's limited to when the derived type is final.
292 // TODO: "devirtualize" this for accesses to known-complete objects.
293 if (VBase && Derived->hasAttr<FinalAttr>()) {
294 const ASTRecordLayout &layout = getContext().getASTRecordLayout(Derived);
295 CharUnits vBaseOffset = layout.getVBaseClassOffset(VBase);
296 NonVirtualOffset += vBaseOffset;
Craig Topper8a13c412014-05-21 05:09:00 +0000297 VBase = nullptr; // we no longer have a virtual step
John McCall13a39c62012-08-01 05:04:58 +0000298 }
299
Anders Carlssond829a022010-04-24 21:06:20 +0000300 // Get the base pointer type.
Justin Bogner1cd11f12015-05-20 15:53:59 +0000301 llvm::Type *BasePtrTy =
John McCallcf142162010-08-07 06:22:56 +0000302 ConvertType((PathEnd[-1])->getType())->getPointerTo();
John McCall13a39c62012-08-01 05:04:58 +0000303
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000304 QualType DerivedTy = getContext().getRecordType(Derived);
John McCall7f416cc2015-09-08 08:05:57 +0000305 CharUnits DerivedAlign = CGM.getClassPointerAlignment(Derived);
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000306
John McCall13a39c62012-08-01 05:04:58 +0000307 // If the static offset is zero and we don't have a virtual step,
308 // just do a bitcast; null checks are unnecessary.
Ken Dycka1a4ae32011-03-22 00:53:26 +0000309 if (NonVirtualOffset.isZero() && !VBase) {
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000310 if (sanitizePerformTypeCheck()) {
John McCall7f416cc2015-09-08 08:05:57 +0000311 EmitTypeCheck(TCK_Upcast, Loc, Value.getPointer(),
312 DerivedTy, DerivedAlign, !NullCheckValue);
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000313 }
Anders Carlssond829a022010-04-24 21:06:20 +0000314 return Builder.CreateBitCast(Value, BasePtrTy);
Craig Topper8a13c412014-05-21 05:09:00 +0000315 }
John McCall13a39c62012-08-01 05:04:58 +0000316
Craig Topper8a13c412014-05-21 05:09:00 +0000317 llvm::BasicBlock *origBB = nullptr;
318 llvm::BasicBlock *endBB = nullptr;
319
John McCall13a39c62012-08-01 05:04:58 +0000320 // Skip over the offset (and the vtable load) if we're supposed to
321 // null-check the pointer.
Anders Carlssond829a022010-04-24 21:06:20 +0000322 if (NullCheckValue) {
John McCall13a39c62012-08-01 05:04:58 +0000323 origBB = Builder.GetInsertBlock();
324 llvm::BasicBlock *notNullBB = createBasicBlock("cast.notnull");
325 endBB = createBasicBlock("cast.end");
Justin Bogner1cd11f12015-05-20 15:53:59 +0000326
John McCall7f416cc2015-09-08 08:05:57 +0000327 llvm::Value *isNull = Builder.CreateIsNull(Value.getPointer());
John McCall13a39c62012-08-01 05:04:58 +0000328 Builder.CreateCondBr(isNull, endBB, notNullBB);
329 EmitBlock(notNullBB);
Anders Carlssond829a022010-04-24 21:06:20 +0000330 }
331
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000332 if (sanitizePerformTypeCheck()) {
John McCall7f416cc2015-09-08 08:05:57 +0000333 EmitTypeCheck(VBase ? TCK_UpcastToVirtualBase : TCK_Upcast, Loc,
334 Value.getPointer(), DerivedTy, DerivedAlign, true);
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000335 }
336
John McCall13a39c62012-08-01 05:04:58 +0000337 // Compute the virtual offset.
Craig Topper8a13c412014-05-21 05:09:00 +0000338 llvm::Value *VirtualOffset = nullptr;
Anders Carlssona376b532011-01-29 03:18:56 +0000339 if (VBase) {
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000340 VirtualOffset =
341 CGM.getCXXABI().GetVirtualBaseClassOffset(*this, Value, Derived, VBase);
Anders Carlssona376b532011-01-29 03:18:56 +0000342 }
Anders Carlssond829a022010-04-24 21:06:20 +0000343
John McCall13a39c62012-08-01 05:04:58 +0000344 // Apply both offsets.
John McCall7f416cc2015-09-08 08:05:57 +0000345 Value = ApplyNonVirtualAndVirtualOffset(*this, Value, NonVirtualOffset,
346 VirtualOffset, Derived, VBase);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000347
John McCall13a39c62012-08-01 05:04:58 +0000348 // Cast to the destination type.
Anders Carlssond829a022010-04-24 21:06:20 +0000349 Value = Builder.CreateBitCast(Value, BasePtrTy);
John McCall13a39c62012-08-01 05:04:58 +0000350
351 // Build a phi if we needed a null check.
Anders Carlssond829a022010-04-24 21:06:20 +0000352 if (NullCheckValue) {
John McCall13a39c62012-08-01 05:04:58 +0000353 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
354 Builder.CreateBr(endBB);
355 EmitBlock(endBB);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000356
John McCall13a39c62012-08-01 05:04:58 +0000357 llvm::PHINode *PHI = Builder.CreatePHI(BasePtrTy, 2, "cast.result");
John McCall7f416cc2015-09-08 08:05:57 +0000358 PHI->addIncoming(Value.getPointer(), notNullBB);
John McCall13a39c62012-08-01 05:04:58 +0000359 PHI->addIncoming(llvm::Constant::getNullValue(BasePtrTy), origBB);
John McCall7f416cc2015-09-08 08:05:57 +0000360 Value = Address(PHI, Value.getAlignment());
Anders Carlssond829a022010-04-24 21:06:20 +0000361 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000362
Anders Carlssond829a022010-04-24 21:06:20 +0000363 return Value;
364}
365
John McCall7f416cc2015-09-08 08:05:57 +0000366Address
367CodeGenFunction::GetAddressOfDerivedClass(Address BaseAddr,
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000368 const CXXRecordDecl *Derived,
John McCallcf142162010-08-07 06:22:56 +0000369 CastExpr::path_const_iterator PathBegin,
370 CastExpr::path_const_iterator PathEnd,
Anders Carlsson8c793172009-11-23 17:57:54 +0000371 bool NullCheckValue) {
John McCallcf142162010-08-07 06:22:56 +0000372 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlsson8a64c1c2010-04-24 21:23:59 +0000373
Anders Carlsson8c793172009-11-23 17:57:54 +0000374 QualType DerivedTy =
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000375 getContext().getCanonicalType(getContext().getTagDeclType(Derived));
Chris Lattner2192fe52011-07-18 04:24:23 +0000376 llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
Richard Smith2c5868c2013-02-13 21:18:23 +0000377
Anders Carlsson600f7372010-01-31 01:43:37 +0000378 llvm::Value *NonVirtualOffset =
John McCallcf142162010-08-07 06:22:56 +0000379 CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000380
Anders Carlsson600f7372010-01-31 01:43:37 +0000381 if (!NonVirtualOffset) {
382 // No offset, we can just cast back.
John McCall7f416cc2015-09-08 08:05:57 +0000383 return Builder.CreateBitCast(BaseAddr, DerivedPtrTy);
Anders Carlsson600f7372010-01-31 01:43:37 +0000384 }
Craig Topper8a13c412014-05-21 05:09:00 +0000385
386 llvm::BasicBlock *CastNull = nullptr;
387 llvm::BasicBlock *CastNotNull = nullptr;
388 llvm::BasicBlock *CastEnd = nullptr;
389
Anders Carlsson8c793172009-11-23 17:57:54 +0000390 if (NullCheckValue) {
391 CastNull = createBasicBlock("cast.null");
392 CastNotNull = createBasicBlock("cast.notnull");
393 CastEnd = createBasicBlock("cast.end");
Justin Bogner1cd11f12015-05-20 15:53:59 +0000394
John McCall7f416cc2015-09-08 08:05:57 +0000395 llvm::Value *IsNull = Builder.CreateIsNull(BaseAddr.getPointer());
Anders Carlsson8c793172009-11-23 17:57:54 +0000396 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
397 EmitBlock(CastNotNull);
398 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000399
Anders Carlsson600f7372010-01-31 01:43:37 +0000400 // Apply the offset.
John McCall7f416cc2015-09-08 08:05:57 +0000401 llvm::Value *Value = Builder.CreateBitCast(BaseAddr.getPointer(), Int8PtrTy);
Eli Friedman87549262012-02-28 22:07:56 +0000402 Value = Builder.CreateGEP(Value, Builder.CreateNeg(NonVirtualOffset),
403 "sub.ptr");
Anders Carlsson600f7372010-01-31 01:43:37 +0000404
405 // Just cast.
406 Value = Builder.CreateBitCast(Value, DerivedPtrTy);
Anders Carlsson8c793172009-11-23 17:57:54 +0000407
John McCall7f416cc2015-09-08 08:05:57 +0000408 // Produce a PHI if we had a null-check.
Anders Carlsson8c793172009-11-23 17:57:54 +0000409 if (NullCheckValue) {
410 Builder.CreateBr(CastEnd);
411 EmitBlock(CastNull);
412 Builder.CreateBr(CastEnd);
413 EmitBlock(CastEnd);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000414
Jay Foad20c0f022011-03-30 11:28:58 +0000415 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
Anders Carlsson8c793172009-11-23 17:57:54 +0000416 PHI->addIncoming(Value, CastNotNull);
John McCall7f416cc2015-09-08 08:05:57 +0000417 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
Anders Carlsson8c793172009-11-23 17:57:54 +0000418 Value = PHI;
419 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000420
John McCall7f416cc2015-09-08 08:05:57 +0000421 return Address(Value, CGM.getClassPointerAlignment(Derived));
Anders Carlsson9a57c5a2009-09-12 04:27:24 +0000422}
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000423
424llvm::Value *CodeGenFunction::GetVTTParameter(GlobalDecl GD,
425 bool ForVirtualBase,
426 bool Delegating) {
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000427 if (!CGM.getCXXABI().NeedsVTTParameter(GD)) {
Anders Carlssone36a6b32010-01-02 01:01:18 +0000428 // This constructor/destructor does not need a VTT parameter.
Craig Topper8a13c412014-05-21 05:09:00 +0000429 return nullptr;
Anders Carlssone36a6b32010-01-02 01:01:18 +0000430 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000431
John McCalldec348f72013-05-03 07:33:41 +0000432 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CurCodeDecl)->getParent();
Anders Carlssone36a6b32010-01-02 01:01:18 +0000433 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
John McCall5c60a6f2010-02-18 19:59:28 +0000434
Anders Carlssone36a6b32010-01-02 01:01:18 +0000435 llvm::Value *VTT;
436
John McCall5c60a6f2010-02-18 19:59:28 +0000437 uint64_t SubVTTIndex;
438
Douglas Gregor61535002013-01-31 05:50:40 +0000439 if (Delegating) {
440 // If this is a delegating constructor call, just load the VTT.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000441 return LoadCXXVTT();
Douglas Gregor61535002013-01-31 05:50:40 +0000442 } else if (RD == Base) {
443 // If the record matches the base, this is the complete ctor/dtor
444 // variant calling the base variant in a class with virtual bases.
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000445 assert(!CGM.getCXXABI().NeedsVTTParameter(CurGD) &&
John McCall5c60a6f2010-02-18 19:59:28 +0000446 "doing no-op VTT offset in base dtor/ctor?");
Anders Carlsson4d205ba2010-05-02 23:33:10 +0000447 assert(!ForVirtualBase && "Can't have same class as virtual base!");
John McCall5c60a6f2010-02-18 19:59:28 +0000448 SubVTTIndex = 0;
449 } else {
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000450 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000451 CharUnits BaseOffset = ForVirtualBase ?
452 Layout.getVBaseClassOffset(Base) :
Ken Dyck16ffcac2011-03-24 01:21:01 +0000453 Layout.getBaseClassOffset(Base);
Anders Carlsson859b3062010-05-02 23:53:25 +0000454
Justin Bogner1cd11f12015-05-20 15:53:59 +0000455 SubVTTIndex =
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000456 CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
John McCall5c60a6f2010-02-18 19:59:28 +0000457 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
458 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000459
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000460 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
Anders Carlssone36a6b32010-01-02 01:01:18 +0000461 // A VTT parameter was passed to the constructor, use it.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000462 VTT = LoadCXXVTT();
463 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
Anders Carlssone36a6b32010-01-02 01:01:18 +0000464 } else {
465 // We're the complete constructor, so get the VTT by name.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000466 VTT = CGM.getVTables().GetAddrOfVTT(RD);
467 VTT = Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
Anders Carlssone36a6b32010-01-02 01:01:18 +0000468 }
469
470 return VTT;
471}
472
John McCall1d987562010-07-21 01:23:41 +0000473namespace {
John McCallf99a6312010-07-21 05:30:47 +0000474 /// Call the destructor for a direct base class.
David Blaikie7e70d682015-08-18 22:40:54 +0000475 struct CallBaseDtor final : EHScopeStack::Cleanup {
John McCallf99a6312010-07-21 05:30:47 +0000476 const CXXRecordDecl *BaseClass;
477 bool BaseIsVirtual;
478 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
479 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
John McCall1d987562010-07-21 01:23:41 +0000480
Craig Topper4f12f102014-03-12 06:41:41 +0000481 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallf99a6312010-07-21 05:30:47 +0000482 const CXXRecordDecl *DerivedClass =
483 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
484
485 const CXXDestructorDecl *D = BaseClass->getDestructor();
John McCall7f416cc2015-09-08 08:05:57 +0000486 Address Addr =
487 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThisAddress(),
John McCallf99a6312010-07-21 05:30:47 +0000488 DerivedClass, BaseClass,
489 BaseIsVirtual);
Douglas Gregor61535002013-01-31 05:50:40 +0000490 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual,
491 /*Delegating=*/false, Addr);
John McCall1d987562010-07-21 01:23:41 +0000492 }
493 };
John McCall769250e2010-09-17 02:31:44 +0000494
495 /// A visitor which checks whether an initializer uses 'this' in a
496 /// way which requires the vtable to be properly set.
Scott Douglass503fc392015-06-10 13:53:15 +0000497 struct DynamicThisUseChecker : ConstEvaluatedExprVisitor<DynamicThisUseChecker> {
498 typedef ConstEvaluatedExprVisitor<DynamicThisUseChecker> super;
John McCall769250e2010-09-17 02:31:44 +0000499
500 bool UsesThis;
501
Scott Douglass503fc392015-06-10 13:53:15 +0000502 DynamicThisUseChecker(const ASTContext &C) : super(C), UsesThis(false) {}
John McCall769250e2010-09-17 02:31:44 +0000503
504 // Black-list all explicit and implicit references to 'this'.
505 //
506 // Do we need to worry about external references to 'this' derived
507 // from arbitrary code? If so, then anything which runs arbitrary
508 // external code might potentially access the vtable.
Scott Douglass503fc392015-06-10 13:53:15 +0000509 void VisitCXXThisExpr(const CXXThisExpr *E) { UsesThis = true; }
John McCall769250e2010-09-17 02:31:44 +0000510 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000511}
John McCall769250e2010-09-17 02:31:44 +0000512
513static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
514 DynamicThisUseChecker Checker(C);
Scott Douglass503fc392015-06-10 13:53:15 +0000515 Checker.Visit(Init);
John McCall769250e2010-09-17 02:31:44 +0000516 return Checker.UsesThis;
John McCall1d987562010-07-21 01:23:41 +0000517}
518
Justin Bogner1cd11f12015-05-20 15:53:59 +0000519static void EmitBaseInitializer(CodeGenFunction &CGF,
Anders Carlssonfb404882009-12-24 22:46:43 +0000520 const CXXRecordDecl *ClassDecl,
Alexis Hunt1d792652011-01-08 20:30:50 +0000521 CXXCtorInitializer *BaseInit,
Anders Carlssonfb404882009-12-24 22:46:43 +0000522 CXXCtorType CtorType) {
523 assert(BaseInit->isBaseInitializer() &&
524 "Must have base initializer!");
525
John McCall7f416cc2015-09-08 08:05:57 +0000526 Address ThisPtr = CGF.LoadCXXThisAddress();
Justin Bogner1cd11f12015-05-20 15:53:59 +0000527
Anders Carlssonfb404882009-12-24 22:46:43 +0000528 const Type *BaseType = BaseInit->getBaseClass();
529 CXXRecordDecl *BaseClassDecl =
530 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
531
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +0000532 bool isBaseVirtual = BaseInit->isBaseVirtual();
Anders Carlssonfb404882009-12-24 22:46:43 +0000533
534 // The base constructor doesn't construct virtual bases.
535 if (CtorType == Ctor_Base && isBaseVirtual)
536 return;
537
John McCall769250e2010-09-17 02:31:44 +0000538 // If the initializer for the base (other than the constructor
539 // itself) accesses 'this' in any way, we need to initialize the
540 // vtables.
541 if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
542 CGF.InitializeVTablePointers(ClassDecl);
543
John McCall6ce74722010-02-16 04:15:37 +0000544 // We can pretend to be a complete class because it only matters for
545 // virtual bases, and we only do virtual bases for complete ctors.
John McCall7f416cc2015-09-08 08:05:57 +0000546 Address V =
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000547 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
John McCallf99a6312010-07-21 05:30:47 +0000548 BaseClassDecl,
549 isBaseVirtual);
John McCall8d6fc952011-08-25 20:40:09 +0000550 AggValueSlot AggSlot =
John McCall7f416cc2015-09-08 08:05:57 +0000551 AggValueSlot::forAddr(V, Qualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +0000552 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +0000553 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000554 AggValueSlot::IsNotAliased);
John McCall7a626f62010-09-15 10:14:12 +0000555
556 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000557
558 if (CGF.CGM.getLangOpts().Exceptions &&
Anders Carlsson08ce5ed2011-02-20 00:20:27 +0000559 !BaseClassDecl->hasTrivialDestructor())
John McCallcda666c2010-07-21 07:22:38 +0000560 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
561 isBaseVirtual);
Anders Carlssonfb404882009-12-24 22:46:43 +0000562}
563
Douglas Gregor94f9a482010-05-05 05:51:00 +0000564static void EmitAggMemberInitializer(CodeGenFunction &CGF,
565 LValue LHS,
Eli Friedman6ae63022012-02-14 02:15:49 +0000566 Expr *Init,
John McCall7f416cc2015-09-08 08:05:57 +0000567 Address ArrayIndexVar,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000568 QualType T,
Eli Friedman6ae63022012-02-14 02:15:49 +0000569 ArrayRef<VarDecl *> ArrayIndexes,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000570 unsigned Index) {
Eli Friedman6ae63022012-02-14 02:15:49 +0000571 if (Index == ArrayIndexes.size()) {
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000572 LValue LV = LHS;
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000573
John McCall7f416cc2015-09-08 08:05:57 +0000574 if (ArrayIndexVar.isValid()) {
Richard Smithcc1b96d2013-06-12 22:31:48 +0000575 // If we have an array index variable, load it and use it as an offset.
576 // Then, increment the value.
John McCall7f416cc2015-09-08 08:05:57 +0000577 llvm::Value *Dest = LHS.getPointer();
Richard Smithcc1b96d2013-06-12 22:31:48 +0000578 llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar);
579 Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress");
580 llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1);
581 Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc");
582 CGF.Builder.CreateStore(Next, ArrayIndexVar);
Sebastian Redl4e04dd12012-02-19 15:41:54 +0000583
Richard Smithcc1b96d2013-06-12 22:31:48 +0000584 // Update the LValue.
John McCall7f416cc2015-09-08 08:05:57 +0000585 CharUnits EltSize = CGF.getContext().getTypeSizeInChars(T);
586 CharUnits Align = LV.getAlignment().alignmentOfArrayElement(EltSize);
587 LV.setAddress(Address(Dest, Align));
Douglas Gregor94f9a482010-05-05 05:51:00 +0000588 }
John McCall7a626f62010-09-15 10:14:12 +0000589
Richard Smithcc1b96d2013-06-12 22:31:48 +0000590 switch (CGF.getEvaluationKind(T)) {
591 case TEK_Scalar:
Craig Topper8a13c412014-05-21 05:09:00 +0000592 CGF.EmitScalarInit(Init, /*decl*/ nullptr, LV, false);
Richard Smithcc1b96d2013-06-12 22:31:48 +0000593 break;
594 case TEK_Complex:
595 CGF.EmitComplexExprIntoLValue(Init, LV, /*isInit*/ true);
596 break;
597 case TEK_Aggregate: {
598 AggValueSlot Slot =
599 AggValueSlot::forLValue(LV,
600 AggValueSlot::IsDestructed,
601 AggValueSlot::DoesNotNeedGCBarriers,
602 AggValueSlot::IsNotAliased);
603
604 CGF.EmitAggExpr(Init, Slot);
605 break;
606 }
607 }
Sebastian Redl4e04dd12012-02-19 15:41:54 +0000608
Douglas Gregor94f9a482010-05-05 05:51:00 +0000609 return;
610 }
Richard Smithcc1b96d2013-06-12 22:31:48 +0000611
Douglas Gregor94f9a482010-05-05 05:51:00 +0000612 const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T);
613 assert(Array && "Array initialization without the array type?");
John McCall7f416cc2015-09-08 08:05:57 +0000614 Address IndexVar = CGF.GetAddrOfLocalVar(ArrayIndexes[Index]);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000615
Douglas Gregor94f9a482010-05-05 05:51:00 +0000616 // Initialize this index variable to zero.
617 llvm::Value* Zero
John McCall7f416cc2015-09-08 08:05:57 +0000618 = llvm::Constant::getNullValue(IndexVar.getElementType());
Douglas Gregor94f9a482010-05-05 05:51:00 +0000619 CGF.Builder.CreateStore(Zero, IndexVar);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000620
Douglas Gregor94f9a482010-05-05 05:51:00 +0000621 // Start the loop with a block that tests the condition.
622 llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond");
623 llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end");
Justin Bogner1cd11f12015-05-20 15:53:59 +0000624
Douglas Gregor94f9a482010-05-05 05:51:00 +0000625 CGF.EmitBlock(CondBlock);
626
627 llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body");
628 // Generate: if (loop-index < number-of-elements) fall to the loop body,
629 // otherwise, go to the block after the for-loop.
630 uint64_t NumElements = Array->getSize().getZExtValue();
Douglas Gregor94f9a482010-05-05 05:51:00 +0000631 llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
Chris Lattner44456d22010-05-06 06:35:23 +0000632 llvm::Value *NumElementsPtr =
633 llvm::ConstantInt::get(Counter->getType(), NumElements);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000634 llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr,
635 "isless");
Justin Bogner1cd11f12015-05-20 15:53:59 +0000636
Douglas Gregor94f9a482010-05-05 05:51:00 +0000637 // If the condition is true, execute the body.
638 CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor);
639
640 CGF.EmitBlock(ForBody);
641 llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc");
Richard Smithcc1b96d2013-06-12 22:31:48 +0000642
643 // Inside the loop body recurse to emit the inner loop or, eventually, the
644 // constructor call.
645 EmitAggMemberInitializer(CGF, LHS, Init, ArrayIndexVar,
646 Array->getElementType(), ArrayIndexes, Index + 1);
647
Douglas Gregor94f9a482010-05-05 05:51:00 +0000648 CGF.EmitBlock(ContinueBlock);
649
650 // Emit the increment of the loop counter.
651 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
652 Counter = CGF.Builder.CreateLoad(IndexVar);
653 NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc");
654 CGF.Builder.CreateStore(NextVal, IndexVar);
655
656 // Finally, branch back up to the condition for the next iteration.
657 CGF.EmitBranch(CondBlock);
658
659 // Emit the fall-through block.
660 CGF.EmitBlock(AfterFor, true);
661}
John McCall1d987562010-07-21 01:23:41 +0000662
Richard Smith419bd092015-04-29 19:26:57 +0000663static bool isMemcpyEquivalentSpecialMember(const CXXMethodDecl *D) {
664 auto *CD = dyn_cast<CXXConstructorDecl>(D);
665 if (!(CD && CD->isCopyOrMoveConstructor()) &&
666 !D->isCopyAssignmentOperator() && !D->isMoveAssignmentOperator())
667 return false;
668
669 // We can emit a memcpy for a trivial copy or move constructor/assignment.
670 if (D->isTrivial() && !D->getParent()->mayInsertExtraPadding())
671 return true;
672
673 // We *must* emit a memcpy for a defaulted union copy or move op.
674 if (D->getParent()->isUnion() && D->isDefaulted())
675 return true;
676
677 return false;
678}
679
Alexey Bataev152c71f2015-07-14 07:55:48 +0000680static void EmitLValueForAnyFieldInitialization(CodeGenFunction &CGF,
681 CXXCtorInitializer *MemberInit,
682 LValue &LHS) {
683 FieldDecl *Field = MemberInit->getAnyMember();
684 if (MemberInit->isIndirectMemberInitializer()) {
685 // If we are initializing an anonymous union field, drill down to the field.
686 IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember();
687 for (const auto *I : IndirectField->chain())
688 LHS = CGF.EmitLValueForFieldInitialization(LHS, cast<FieldDecl>(I));
689 } else {
690 LHS = CGF.EmitLValueForFieldInitialization(LHS, Field);
691 }
692}
693
Anders Carlssonfb404882009-12-24 22:46:43 +0000694static void EmitMemberInitializer(CodeGenFunction &CGF,
695 const CXXRecordDecl *ClassDecl,
Alexis Hunt1d792652011-01-08 20:30:50 +0000696 CXXCtorInitializer *MemberInit,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000697 const CXXConstructorDecl *Constructor,
698 FunctionArgList &Args) {
David Blaikiea81d4102015-01-18 00:12:58 +0000699 ApplyDebugLocation Loc(CGF, MemberInit->getSourceLocation());
Francois Pichetd583da02010-12-04 09:14:42 +0000700 assert(MemberInit->isAnyMemberInitializer() &&
Anders Carlssonfb404882009-12-24 22:46:43 +0000701 "Must have member initializer!");
Richard Smith938f40b2011-06-11 17:19:42 +0000702 assert(MemberInit->getInit() && "Must have initializer!");
Justin Bogner1cd11f12015-05-20 15:53:59 +0000703
Anders Carlssonfb404882009-12-24 22:46:43 +0000704 // non-static data member initializers.
Francois Pichetd583da02010-12-04 09:14:42 +0000705 FieldDecl *Field = MemberInit->getAnyMember();
Eli Friedman6ae63022012-02-14 02:15:49 +0000706 QualType FieldType = Field->getType();
Anders Carlssonfb404882009-12-24 22:46:43 +0000707
708 llvm::Value *ThisPtr = CGF.LoadCXXThis();
Eli Friedman7f1ff602012-04-16 03:54:45 +0000709 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
Eli Friedmanf6d21842012-08-08 03:51:37 +0000710 LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
Eli Friedman7f1ff602012-04-16 03:54:45 +0000711
Alexey Bataev152c71f2015-07-14 07:55:48 +0000712 EmitLValueForAnyFieldInitialization(CGF, MemberInit, LHS);
Anders Carlssonfb404882009-12-24 22:46:43 +0000713
Eli Friedman6ae63022012-02-14 02:15:49 +0000714 // Special case: if we are in a copy or move constructor, and we are copying
715 // an array of PODs or classes with trivial copy constructors, ignore the
716 // AST and perform the copy we know is equivalent.
717 // FIXME: This is hacky at best... if we had a bit more explicit information
718 // in the AST, we could generalize it more easily.
719 const ConstantArrayType *Array
720 = CGF.getContext().getAsConstantArrayType(FieldType);
Jordan Rose54533f72013-08-07 16:16:48 +0000721 if (Array && Constructor->isDefaulted() &&
Eli Friedman6ae63022012-02-14 02:15:49 +0000722 Constructor->isCopyOrMoveConstructor()) {
723 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
Richard Smith993f25a2012-11-07 23:56:21 +0000724 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
Eli Friedman6ae63022012-02-14 02:15:49 +0000725 if (BaseElementTy.isPODType(CGF.getContext()) ||
Richard Smith419bd092015-04-29 19:26:57 +0000726 (CE && isMemcpyEquivalentSpecialMember(CE->getConstructor()))) {
David Majnemer1573d732014-10-15 04:54:54 +0000727 unsigned SrcArgIndex =
728 CGF.CGM.getCXXABI().getSrcArgforCopyCtor(Constructor, Args);
Eli Friedman6ae63022012-02-14 02:15:49 +0000729 llvm::Value *SrcPtr
730 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
Eli Friedman7f1ff602012-04-16 03:54:45 +0000731 LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
732 LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000733
Eli Friedman6ae63022012-02-14 02:15:49 +0000734 // Copy the aggregate.
735 CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000736 LHS.isVolatileQualified());
Alexey Bataev5d49b832015-07-08 07:31:02 +0000737 // Ensure that we destroy the objects if an exception is thrown later in
738 // the constructor.
739 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
740 if (CGF.needsEHCleanup(dtorKind))
741 CGF.pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
Eli Friedman6ae63022012-02-14 02:15:49 +0000742 return;
743 }
744 }
745
746 ArrayRef<VarDecl *> ArrayIndexes;
747 if (MemberInit->getNumArrayIndices())
748 ArrayIndexes = MemberInit->getArrayIndexes();
David Blaikie66e41972015-01-14 07:38:27 +0000749 CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit(), ArrayIndexes);
Eli Friedman6ae63022012-02-14 02:15:49 +0000750}
751
John McCall7f416cc2015-09-08 08:05:57 +0000752void CodeGenFunction::EmitInitializerForField(FieldDecl *Field, LValue LHS,
753 Expr *Init, ArrayRef<VarDecl *> ArrayIndexes) {
Eli Friedman6ae63022012-02-14 02:15:49 +0000754 QualType FieldType = Field->getType();
John McCall47fb9502013-03-07 21:37:08 +0000755 switch (getEvaluationKind(FieldType)) {
756 case TEK_Scalar:
John McCall31168b02011-06-15 23:02:42 +0000757 if (LHS.isSimple()) {
David Blaikie66e41972015-01-14 07:38:27 +0000758 EmitExprAsInit(Init, Field, LHS, false);
John McCall31168b02011-06-15 23:02:42 +0000759 } else {
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000760 RValue RHS = RValue::get(EmitScalarExpr(Init));
761 EmitStoreThroughLValue(RHS, LHS);
John McCall31168b02011-06-15 23:02:42 +0000762 }
John McCall47fb9502013-03-07 21:37:08 +0000763 break;
764 case TEK_Complex:
David Blaikie66e41972015-01-14 07:38:27 +0000765 EmitComplexExprIntoLValue(Init, LHS, /*isInit*/ true);
John McCall47fb9502013-03-07 21:37:08 +0000766 break;
767 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000768 Address ArrayIndexVar = Address::invalid();
Eli Friedman6ae63022012-02-14 02:15:49 +0000769 if (ArrayIndexes.size()) {
Douglas Gregor94f9a482010-05-05 05:51:00 +0000770 // The LHS is a pointer to the first object we'll be constructing, as
771 // a flat array.
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000772 QualType BaseElementTy = getContext().getBaseElementType(FieldType);
773 llvm::Type *BasePtr = ConvertType(BaseElementTy);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000774 BasePtr = llvm::PointerType::getUnqual(BasePtr);
John McCall7f416cc2015-09-08 08:05:57 +0000775 Address BaseAddrPtr = Builder.CreateBitCast(LHS.getAddress(), BasePtr);
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000776 LHS = MakeAddrLValue(BaseAddrPtr, BaseElementTy);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000777
Douglas Gregor94f9a482010-05-05 05:51:00 +0000778 // Create an array index that will be used to walk over all of the
779 // objects we're constructing.
John McCall7f416cc2015-09-08 08:05:57 +0000780 ArrayIndexVar = CreateMemTemp(getContext().getSizeType(), "object.index");
781 llvm::Value *Zero =
782 llvm::Constant::getNullValue(ArrayIndexVar.getElementType());
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000783 Builder.CreateStore(Zero, ArrayIndexVar);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000784
Douglas Gregor94f9a482010-05-05 05:51:00 +0000785 // Emit the block variables for the array indices, if any.
Eli Friedman6ae63022012-02-14 02:15:49 +0000786 for (unsigned I = 0, N = ArrayIndexes.size(); I != N; ++I)
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000787 EmitAutoVarDecl(*ArrayIndexes[I]);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000788 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000789
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000790 EmitAggMemberInitializer(*this, LHS, Init, ArrayIndexVar, FieldType,
Eli Friedman6ae63022012-02-14 02:15:49 +0000791 ArrayIndexes, 0);
Anders Carlssonfb404882009-12-24 22:46:43 +0000792 }
John McCall47fb9502013-03-07 21:37:08 +0000793 }
John McCall12cc42a2013-02-01 05:11:40 +0000794
795 // Ensure that we destroy this object if an exception is thrown
796 // later in the constructor.
797 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
798 if (needsEHCleanup(dtorKind))
799 pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
Anders Carlssonfb404882009-12-24 22:46:43 +0000800}
801
John McCallf8ff7b92010-02-23 00:48:20 +0000802/// Checks whether the given constructor is a valid subject for the
803/// complete-to-base constructor delegation optimization, i.e.
804/// emitting the complete constructor as a simple call to the base
805/// constructor.
806static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
807
808 // Currently we disable the optimization for classes with virtual
809 // bases because (1) the addresses of parameter variables need to be
810 // consistent across all initializers but (2) the delegate function
811 // call necessarily creates a second copy of the parameter variable.
812 //
813 // The limiting example (purely theoretical AFAIK):
814 // struct A { A(int &c) { c++; } };
815 // struct B : virtual A {
816 // B(int count) : A(count) { printf("%d\n", count); }
817 // };
818 // ...although even this example could in principle be emitted as a
819 // delegation since the address of the parameter doesn't escape.
820 if (Ctor->getParent()->getNumVBases()) {
821 // TODO: white-list trivial vbase initializers. This case wouldn't
822 // be subject to the restrictions below.
823
824 // TODO: white-list cases where:
825 // - there are no non-reference parameters to the constructor
826 // - the initializers don't access any non-reference parameters
827 // - the initializers don't take the address of non-reference
828 // parameters
829 // - etc.
830 // If we ever add any of the above cases, remember that:
831 // - function-try-blocks will always blacklist this optimization
832 // - we need to perform the constructor prologue and cleanup in
833 // EmitConstructorBody.
834
835 return false;
836 }
837
838 // We also disable the optimization for variadic functions because
839 // it's impossible to "re-pass" varargs.
840 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
841 return false;
842
Alexis Hunt61bc1732011-05-01 07:04:31 +0000843 // FIXME: Decide if we can do a delegation of a delegating constructor.
844 if (Ctor->isDelegatingConstructor())
845 return false;
846
John McCallf8ff7b92010-02-23 00:48:20 +0000847 return true;
848}
849
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000850// Emit code in ctor (Prologue==true) or dtor (Prologue==false)
851// to poison the extra field paddings inserted under
852// -fsanitize-address-field-padding=1|2.
853void CodeGenFunction::EmitAsanPrologueOrEpilogue(bool Prologue) {
854 ASTContext &Context = getContext();
855 const CXXRecordDecl *ClassDecl =
856 Prologue ? cast<CXXConstructorDecl>(CurGD.getDecl())->getParent()
857 : cast<CXXDestructorDecl>(CurGD.getDecl())->getParent();
858 if (!ClassDecl->mayInsertExtraPadding()) return;
859
860 struct SizeAndOffset {
861 uint64_t Size;
862 uint64_t Offset;
863 };
864
865 unsigned PtrSize = CGM.getDataLayout().getPointerSizeInBits();
866 const ASTRecordLayout &Info = Context.getASTRecordLayout(ClassDecl);
867
868 // Populate sizes and offsets of fields.
869 SmallVector<SizeAndOffset, 16> SSV(Info.getFieldCount());
870 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i)
871 SSV[i].Offset =
872 Context.toCharUnitsFromBits(Info.getFieldOffset(i)).getQuantity();
873
874 size_t NumFields = 0;
875 for (const auto *Field : ClassDecl->fields()) {
876 const FieldDecl *D = Field;
877 std::pair<CharUnits, CharUnits> FieldInfo =
878 Context.getTypeInfoInChars(D->getType());
879 CharUnits FieldSize = FieldInfo.first;
880 assert(NumFields < SSV.size());
881 SSV[NumFields].Size = D->isBitField() ? 0 : FieldSize.getQuantity();
882 NumFields++;
883 }
884 assert(NumFields == SSV.size());
885 if (SSV.size() <= 1) return;
886
887 // We will insert calls to __asan_* run-time functions.
888 // LLVM AddressSanitizer pass may decide to inline them later.
889 llvm::Type *Args[2] = {IntPtrTy, IntPtrTy};
890 llvm::FunctionType *FTy =
891 llvm::FunctionType::get(CGM.VoidTy, Args, false);
892 llvm::Constant *F = CGM.CreateRuntimeFunction(
893 FTy, Prologue ? "__asan_poison_intra_object_redzone"
894 : "__asan_unpoison_intra_object_redzone");
895
896 llvm::Value *ThisPtr = LoadCXXThis();
897 ThisPtr = Builder.CreatePtrToInt(ThisPtr, IntPtrTy);
Kostya Serebryany64449212014-10-17 21:02:13 +0000898 uint64_t TypeSize = Info.getNonVirtualSize().getQuantity();
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000899 // For each field check if it has sufficient padding,
900 // if so (un)poison it with a call.
901 for (size_t i = 0; i < SSV.size(); i++) {
902 uint64_t AsanAlignment = 8;
903 uint64_t NextField = i == SSV.size() - 1 ? TypeSize : SSV[i + 1].Offset;
904 uint64_t PoisonSize = NextField - SSV[i].Offset - SSV[i].Size;
905 uint64_t EndOffset = SSV[i].Offset + SSV[i].Size;
906 if (PoisonSize < AsanAlignment || !SSV[i].Size ||
907 (NextField % AsanAlignment) != 0)
908 continue;
David Blaikie43f9bb72015-05-18 22:14:03 +0000909 Builder.CreateCall(
910 F, {Builder.CreateAdd(ThisPtr, Builder.getIntN(PtrSize, EndOffset)),
911 Builder.getIntN(PtrSize, PoisonSize)});
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000912 }
913}
914
John McCallb81884d2010-02-19 09:25:03 +0000915/// EmitConstructorBody - Emits the body of the current constructor.
916void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000917 EmitAsanPrologueOrEpilogue(true);
John McCallb81884d2010-02-19 09:25:03 +0000918 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
919 CXXCtorType CtorType = CurGD.getCtorType();
920
Reid Kleckner340ad862014-01-13 22:57:31 +0000921 assert((CGM.getTarget().getCXXABI().hasConstructorVariants() ||
922 CtorType == Ctor_Complete) &&
923 "can only generate complete ctor for this ABI");
924
John McCallf8ff7b92010-02-23 00:48:20 +0000925 // Before we go any further, try the complete->base constructor
926 // delegation optimization.
Timur Iskhodzhanovf32a3772012-04-20 08:05:00 +0000927 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
John McCallc8e01702013-04-16 22:48:15 +0000928 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000929 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args, Ctor->getLocEnd());
John McCallf8ff7b92010-02-23 00:48:20 +0000930 return;
931 }
932
Richard Smith46bb5812014-08-01 01:56:39 +0000933 const FunctionDecl *Definition = 0;
934 Stmt *Body = Ctor->getBody(Definition);
935 assert(Definition == Ctor && "emitting wrong constructor body");
John McCallb81884d2010-02-19 09:25:03 +0000936
John McCallf8ff7b92010-02-23 00:48:20 +0000937 // Enter the function-try-block before the constructor prologue if
938 // applicable.
John McCallf8ff7b92010-02-23 00:48:20 +0000939 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallf8ff7b92010-02-23 00:48:20 +0000940 if (IsTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000941 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000942
Justin Bogner66242d62015-04-23 23:06:47 +0000943 incrementProfileCounter(Body);
Justin Bogner81c22c22014-01-23 02:54:27 +0000944
Richard Smithcc1b96d2013-06-12 22:31:48 +0000945 RunCleanupsScope RunCleanups(*this);
John McCallb81884d2010-02-19 09:25:03 +0000946
John McCall88313032012-03-30 04:25:03 +0000947 // TODO: in restricted cases, we can emit the vbase initializers of
948 // a complete ctor and then delegate to the base ctor.
949
John McCallf8ff7b92010-02-23 00:48:20 +0000950 // Emit the constructor prologue, i.e. the base and member
951 // initializers.
Douglas Gregor94f9a482010-05-05 05:51:00 +0000952 EmitCtorPrologue(Ctor, CtorType, Args);
John McCallb81884d2010-02-19 09:25:03 +0000953
954 // Emit the body of the statement.
John McCallf8ff7b92010-02-23 00:48:20 +0000955 if (IsTryBody)
John McCallb81884d2010-02-19 09:25:03 +0000956 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
957 else if (Body)
958 EmitStmt(Body);
John McCallb81884d2010-02-19 09:25:03 +0000959
960 // Emit any cleanup blocks associated with the member or base
961 // initializers, which includes (along the exceptional path) the
962 // destructors for those members and bases that were fully
963 // constructed.
Richard Smithcc1b96d2013-06-12 22:31:48 +0000964 RunCleanups.ForceCleanup();
John McCallb81884d2010-02-19 09:25:03 +0000965
John McCallf8ff7b92010-02-23 00:48:20 +0000966 if (IsTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000967 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000968}
969
Lang Hamesbf122742013-02-17 07:22:09 +0000970namespace {
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000971 /// RAII object to indicate that codegen is copying the value representation
972 /// instead of the object representation. Useful when copying a struct or
973 /// class which has uninitialized members and we're only performing
974 /// lvalue-to-rvalue conversion on the object but not its members.
975 class CopyingValueRepresentation {
976 public:
977 explicit CopyingValueRepresentation(CodeGenFunction &CGF)
Alexey Samsonov035462c2014-10-30 19:33:44 +0000978 : CGF(CGF), OldSanOpts(CGF.SanOpts) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000979 CGF.SanOpts.set(SanitizerKind::Bool, false);
980 CGF.SanOpts.set(SanitizerKind::Enum, false);
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000981 }
982 ~CopyingValueRepresentation() {
983 CGF.SanOpts = OldSanOpts;
984 }
985 private:
986 CodeGenFunction &CGF;
Alexey Samsonova0416102014-11-11 01:26:14 +0000987 SanitizerSet OldSanOpts;
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000988 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000989}
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000990
991namespace {
Lang Hamesbf122742013-02-17 07:22:09 +0000992 class FieldMemcpyizer {
993 public:
994 FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl,
995 const VarDecl *SrcRec)
Justin Bogner1cd11f12015-05-20 15:53:59 +0000996 : CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec),
Lang Hamesbf122742013-02-17 07:22:09 +0000997 RecLayout(CGF.getContext().getASTRecordLayout(ClassDecl)),
Craig Topper8a13c412014-05-21 05:09:00 +0000998 FirstField(nullptr), LastField(nullptr), FirstFieldOffset(0),
999 LastFieldOffset(0), LastAddedFieldIndex(0) {}
Lang Hamesbf122742013-02-17 07:22:09 +00001000
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00001001 bool isMemcpyableField(FieldDecl *F) const {
1002 // Never memcpy fields when we are adding poisoned paddings.
Alexey Samsonova0416102014-11-11 01:26:14 +00001003 if (CGF.getContext().getLangOpts().SanitizeAddressFieldPadding)
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00001004 return false;
Lang Hamesbf122742013-02-17 07:22:09 +00001005 Qualifiers Qual = F->getType().getQualifiers();
1006 if (Qual.hasVolatile() || Qual.hasObjCLifetime())
1007 return false;
1008 return true;
1009 }
1010
1011 void addMemcpyableField(FieldDecl *F) {
Craig Topper8a13c412014-05-21 05:09:00 +00001012 if (!FirstField)
Lang Hamesbf122742013-02-17 07:22:09 +00001013 addInitialField(F);
1014 else
1015 addNextField(F);
1016 }
1017
David Majnemera586eb22014-10-10 18:57:10 +00001018 CharUnits getMemcpySize(uint64_t FirstByteOffset) const {
Lang Hamesbf122742013-02-17 07:22:09 +00001019 unsigned LastFieldSize =
1020 LastField->isBitField() ?
1021 LastField->getBitWidthValue(CGF.getContext()) :
Justin Bogner1cd11f12015-05-20 15:53:59 +00001022 CGF.getContext().getTypeSize(LastField->getType());
Lang Hamesbf122742013-02-17 07:22:09 +00001023 uint64_t MemcpySizeBits =
David Majnemera586eb22014-10-10 18:57:10 +00001024 LastFieldOffset + LastFieldSize - FirstByteOffset +
Lang Hamesbf122742013-02-17 07:22:09 +00001025 CGF.getContext().getCharWidth() - 1;
1026 CharUnits MemcpySize =
1027 CGF.getContext().toCharUnitsFromBits(MemcpySizeBits);
1028 return MemcpySize;
1029 }
1030
1031 void emitMemcpy() {
1032 // Give the subclass a chance to bail out if it feels the memcpy isn't
1033 // worth it (e.g. Hasn't aggregated enough data).
Craig Topper8a13c412014-05-21 05:09:00 +00001034 if (!FirstField) {
Lang Hamesbf122742013-02-17 07:22:09 +00001035 return;
1036 }
1037
David Majnemera586eb22014-10-10 18:57:10 +00001038 uint64_t FirstByteOffset;
Lang Hamesbf122742013-02-17 07:22:09 +00001039 if (FirstField->isBitField()) {
1040 const CGRecordLayout &RL =
1041 CGF.getTypes().getCGRecordLayout(FirstField->getParent());
1042 const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField);
David Majnemera586eb22014-10-10 18:57:10 +00001043 // FirstFieldOffset is not appropriate for bitfields,
Ulrich Weigand73263d72015-07-13 11:52:14 +00001044 // we need to use the storage offset instead.
Ulrich Weigand03ce2a12015-07-10 17:30:00 +00001045 FirstByteOffset = CGF.getContext().toBits(BFInfo.StorageOffset);
Lang Hames1694e0d2013-02-27 04:14:49 +00001046 } else {
David Majnemera586eb22014-10-10 18:57:10 +00001047 FirstByteOffset = FirstFieldOffset;
Lang Hames1694e0d2013-02-27 04:14:49 +00001048 }
Lang Hamesbf122742013-02-17 07:22:09 +00001049
David Majnemera586eb22014-10-10 18:57:10 +00001050 CharUnits MemcpySize = getMemcpySize(FirstByteOffset);
Lang Hamesbf122742013-02-17 07:22:09 +00001051 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
John McCall7f416cc2015-09-08 08:05:57 +00001052 Address ThisPtr = CGF.LoadCXXThisAddress();
1053 LValue DestLV = CGF.MakeAddrLValue(ThisPtr, RecordTy);
Lang Hamesbf122742013-02-17 07:22:09 +00001054 LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField);
1055 llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec));
1056 LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
1057 LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField);
1058
John McCall7f416cc2015-09-08 08:05:57 +00001059 emitMemcpyIR(Dest.isBitField() ? Dest.getBitFieldAddress() : Dest.getAddress(),
1060 Src.isBitField() ? Src.getBitFieldAddress() : Src.getAddress(),
1061 MemcpySize);
Lang Hamesbf122742013-02-17 07:22:09 +00001062 reset();
1063 }
1064
1065 void reset() {
Craig Topper8a13c412014-05-21 05:09:00 +00001066 FirstField = nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001067 }
1068
1069 protected:
1070 CodeGenFunction &CGF;
1071 const CXXRecordDecl *ClassDecl;
1072
1073 private:
1074
John McCall7f416cc2015-09-08 08:05:57 +00001075 void emitMemcpyIR(Address DestPtr, Address SrcPtr, CharUnits Size) {
1076 llvm::PointerType *DPT = DestPtr.getType();
Lang Hamesbf122742013-02-17 07:22:09 +00001077 llvm::Type *DBP =
1078 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), DPT->getAddressSpace());
1079 DestPtr = CGF.Builder.CreateBitCast(DestPtr, DBP);
1080
John McCall7f416cc2015-09-08 08:05:57 +00001081 llvm::PointerType *SPT = SrcPtr.getType();
Lang Hamesbf122742013-02-17 07:22:09 +00001082 llvm::Type *SBP =
1083 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), SPT->getAddressSpace());
1084 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, SBP);
1085
John McCall7f416cc2015-09-08 08:05:57 +00001086 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity());
Lang Hamesbf122742013-02-17 07:22:09 +00001087 }
1088
1089 void addInitialField(FieldDecl *F) {
1090 FirstField = F;
1091 LastField = F;
1092 FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex());
1093 LastFieldOffset = FirstFieldOffset;
1094 LastAddedFieldIndex = F->getFieldIndex();
1095 return;
1096 }
1097
1098 void addNextField(FieldDecl *F) {
John McCall6054d5a2013-05-07 05:20:46 +00001099 // For the most part, the following invariant will hold:
1100 // F->getFieldIndex() == LastAddedFieldIndex + 1
1101 // The one exception is that Sema won't add a copy-initializer for an
1102 // unnamed bitfield, which will show up here as a gap in the sequence.
1103 assert(F->getFieldIndex() >= LastAddedFieldIndex + 1 &&
1104 "Cannot aggregate fields out of order.");
Lang Hamesbf122742013-02-17 07:22:09 +00001105 LastAddedFieldIndex = F->getFieldIndex();
1106
1107 // The 'first' and 'last' fields are chosen by offset, rather than field
1108 // index. This allows the code to support bitfields, as well as regular
1109 // fields.
1110 uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex());
1111 if (FOffset < FirstFieldOffset) {
1112 FirstField = F;
1113 FirstFieldOffset = FOffset;
1114 } else if (FOffset > LastFieldOffset) {
1115 LastField = F;
1116 LastFieldOffset = FOffset;
1117 }
1118 }
1119
1120 const VarDecl *SrcRec;
1121 const ASTRecordLayout &RecLayout;
1122 FieldDecl *FirstField;
1123 FieldDecl *LastField;
1124 uint64_t FirstFieldOffset, LastFieldOffset;
1125 unsigned LastAddedFieldIndex;
1126 };
1127
1128 class ConstructorMemcpyizer : public FieldMemcpyizer {
1129 private:
1130
1131 /// Get source argument for copy constructor. Returns null if not a copy
David Majnemer196ac332014-09-11 23:05:02 +00001132 /// constructor.
1133 static const VarDecl *getTrivialCopySource(CodeGenFunction &CGF,
1134 const CXXConstructorDecl *CD,
Lang Hamesbf122742013-02-17 07:22:09 +00001135 FunctionArgList &Args) {
Jordan Rose54533f72013-08-07 16:16:48 +00001136 if (CD->isCopyOrMoveConstructor() && CD->isDefaulted())
David Majnemer196ac332014-09-11 23:05:02 +00001137 return Args[CGF.CGM.getCXXABI().getSrcArgforCopyCtor(CD, Args)];
Craig Topper8a13c412014-05-21 05:09:00 +00001138 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001139 }
1140
1141 // Returns true if a CXXCtorInitializer represents a member initialization
1142 // that can be rolled into a memcpy.
1143 bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const {
1144 if (!MemcpyableCtor)
1145 return false;
1146 FieldDecl *Field = MemberInit->getMember();
Craig Topper8a13c412014-05-21 05:09:00 +00001147 assert(Field && "No field for member init.");
Lang Hamesbf122742013-02-17 07:22:09 +00001148 QualType FieldType = Field->getType();
1149 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
1150
Richard Smith419bd092015-04-29 19:26:57 +00001151 // Bail out on non-memcpyable, not-trivially-copyable members.
1152 if (!(CE && isMemcpyEquivalentSpecialMember(CE->getConstructor())) &&
Lang Hamesbf122742013-02-17 07:22:09 +00001153 !(FieldType.isTriviallyCopyableType(CGF.getContext()) ||
1154 FieldType->isReferenceType()))
1155 return false;
1156
1157 // Bail out on volatile fields.
1158 if (!isMemcpyableField(Field))
1159 return false;
1160
1161 // Otherwise we're good.
1162 return true;
1163 }
1164
1165 public:
1166 ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD,
1167 FunctionArgList &Args)
David Majnemer196ac332014-09-11 23:05:02 +00001168 : FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CGF, CD, Args)),
Lang Hamesbf122742013-02-17 07:22:09 +00001169 ConstructorDecl(CD),
Jordan Rose54533f72013-08-07 16:16:48 +00001170 MemcpyableCtor(CD->isDefaulted() &&
Lang Hamesbf122742013-02-17 07:22:09 +00001171 CD->isCopyOrMoveConstructor() &&
1172 CGF.getLangOpts().getGC() == LangOptions::NonGC),
1173 Args(Args) { }
1174
1175 void addMemberInitializer(CXXCtorInitializer *MemberInit) {
1176 if (isMemberInitMemcpyable(MemberInit)) {
1177 AggregatedInits.push_back(MemberInit);
1178 addMemcpyableField(MemberInit->getMember());
1179 } else {
1180 emitAggregatedInits();
1181 EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit,
1182 ConstructorDecl, Args);
1183 }
1184 }
1185
1186 void emitAggregatedInits() {
1187 if (AggregatedInits.size() <= 1) {
1188 // This memcpy is too small to be worthwhile. Fall back on default
1189 // codegen.
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001190 if (!AggregatedInits.empty()) {
1191 CopyingValueRepresentation CVR(CGF);
Lang Hamesbf122742013-02-17 07:22:09 +00001192 EmitMemberInitializer(CGF, ConstructorDecl->getParent(),
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001193 AggregatedInits[0], ConstructorDecl, Args);
Alexey Bataev152c71f2015-07-14 07:55:48 +00001194 AggregatedInits.clear();
Lang Hamesbf122742013-02-17 07:22:09 +00001195 }
1196 reset();
1197 return;
1198 }
1199
1200 pushEHDestructors();
1201 emitMemcpy();
1202 AggregatedInits.clear();
1203 }
1204
1205 void pushEHDestructors() {
John McCall7f416cc2015-09-08 08:05:57 +00001206 Address ThisPtr = CGF.LoadCXXThisAddress();
Lang Hamesbf122742013-02-17 07:22:09 +00001207 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
John McCall7f416cc2015-09-08 08:05:57 +00001208 LValue LHS = CGF.MakeAddrLValue(ThisPtr, RecordTy);
Lang Hamesbf122742013-02-17 07:22:09 +00001209
1210 for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
Alexey Bataev152c71f2015-07-14 07:55:48 +00001211 CXXCtorInitializer *MemberInit = AggregatedInits[i];
1212 QualType FieldType = MemberInit->getAnyMember()->getType();
Lang Hamesbf122742013-02-17 07:22:09 +00001213 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
Alexey Bataev152c71f2015-07-14 07:55:48 +00001214 if (!CGF.needsEHCleanup(dtorKind))
1215 continue;
1216 LValue FieldLHS = LHS;
1217 EmitLValueForAnyFieldInitialization(CGF, MemberInit, FieldLHS);
1218 CGF.pushEHDestroy(dtorKind, FieldLHS.getAddress(), FieldType);
Lang Hamesbf122742013-02-17 07:22:09 +00001219 }
1220 }
1221
1222 void finish() {
1223 emitAggregatedInits();
1224 }
1225
1226 private:
1227 const CXXConstructorDecl *ConstructorDecl;
1228 bool MemcpyableCtor;
1229 FunctionArgList &Args;
1230 SmallVector<CXXCtorInitializer*, 16> AggregatedInits;
1231 };
1232
1233 class AssignmentMemcpyizer : public FieldMemcpyizer {
1234 private:
1235
1236 // Returns the memcpyable field copied by the given statement, if one
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001237 // exists. Otherwise returns null.
1238 FieldDecl *getMemcpyableField(Stmt *S) {
Lang Hamesbf122742013-02-17 07:22:09 +00001239 if (!AssignmentsMemcpyable)
Craig Topper8a13c412014-05-21 05:09:00 +00001240 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001241 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
1242 // Recognise trivial assignments.
1243 if (BO->getOpcode() != BO_Assign)
Craig Topper8a13c412014-05-21 05:09:00 +00001244 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001245 MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS());
1246 if (!ME)
Craig Topper8a13c412014-05-21 05:09:00 +00001247 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001248 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1249 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001250 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001251 Stmt *RHS = BO->getRHS();
1252 if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS))
1253 RHS = EC->getSubExpr();
1254 if (!RHS)
Craig Topper8a13c412014-05-21 05:09:00 +00001255 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001256 MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS);
1257 if (dyn_cast<FieldDecl>(ME2->getMemberDecl()) != Field)
Craig Topper8a13c412014-05-21 05:09:00 +00001258 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001259 return Field;
1260 } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) {
1261 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl());
Richard Smith419bd092015-04-29 19:26:57 +00001262 if (!(MD && isMemcpyEquivalentSpecialMember(MD)))
Craig Topper8a13c412014-05-21 05:09:00 +00001263 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001264 MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument());
1265 if (!IOA)
Craig Topper8a13c412014-05-21 05:09:00 +00001266 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001267 FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl());
1268 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001269 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001270 MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0));
1271 if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl()))
Craig Topper8a13c412014-05-21 05:09:00 +00001272 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001273 return Field;
1274 } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1275 FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1276 if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy)
Craig Topper8a13c412014-05-21 05:09:00 +00001277 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001278 Expr *DstPtr = CE->getArg(0);
1279 if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr))
1280 DstPtr = DC->getSubExpr();
1281 UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr);
1282 if (!DUO || DUO->getOpcode() != UO_AddrOf)
Craig Topper8a13c412014-05-21 05:09:00 +00001283 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001284 MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr());
1285 if (!ME)
Craig Topper8a13c412014-05-21 05:09:00 +00001286 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001287 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1288 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001289 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001290 Expr *SrcPtr = CE->getArg(1);
1291 if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr))
1292 SrcPtr = SC->getSubExpr();
1293 UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr);
1294 if (!SUO || SUO->getOpcode() != UO_AddrOf)
Craig Topper8a13c412014-05-21 05:09:00 +00001295 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001296 MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr());
1297 if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl()))
Craig Topper8a13c412014-05-21 05:09:00 +00001298 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001299 return Field;
1300 }
1301
Craig Topper8a13c412014-05-21 05:09:00 +00001302 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001303 }
1304
1305 bool AssignmentsMemcpyable;
1306 SmallVector<Stmt*, 16> AggregatedStmts;
1307
1308 public:
1309
1310 AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD,
1311 FunctionArgList &Args)
1312 : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]),
1313 AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) {
1314 assert(Args.size() == 2);
1315 }
1316
1317 void emitAssignment(Stmt *S) {
1318 FieldDecl *F = getMemcpyableField(S);
1319 if (F) {
1320 addMemcpyableField(F);
1321 AggregatedStmts.push_back(S);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001322 } else {
Lang Hamesbf122742013-02-17 07:22:09 +00001323 emitAggregatedStmts();
1324 CGF.EmitStmt(S);
1325 }
1326 }
1327
1328 void emitAggregatedStmts() {
1329 if (AggregatedStmts.size() <= 1) {
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001330 if (!AggregatedStmts.empty()) {
1331 CopyingValueRepresentation CVR(CGF);
1332 CGF.EmitStmt(AggregatedStmts[0]);
1333 }
Lang Hamesbf122742013-02-17 07:22:09 +00001334 reset();
1335 }
1336
1337 emitMemcpy();
1338 AggregatedStmts.clear();
1339 }
1340
1341 void finish() {
1342 emitAggregatedStmts();
1343 }
1344 };
1345
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001346}
Lang Hamesbf122742013-02-17 07:22:09 +00001347
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001348static bool isInitializerOfDynamicClass(const CXXCtorInitializer *BaseInit) {
1349 const Type *BaseType = BaseInit->getBaseClass();
1350 const auto *BaseClassDecl =
1351 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
1352 return BaseClassDecl->isDynamicClass();
1353}
1354
Anders Carlssonfb404882009-12-24 22:46:43 +00001355/// EmitCtorPrologue - This routine generates necessary code to initialize
1356/// base classes and non-static data members belonging to this constructor.
Anders Carlssonfb404882009-12-24 22:46:43 +00001357void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001358 CXXCtorType CtorType,
1359 FunctionArgList &Args) {
Alexis Hunt61bc1732011-05-01 07:04:31 +00001360 if (CD->isDelegatingConstructor())
1361 return EmitDelegatingCXXConstructorCall(CD, Args);
1362
Anders Carlssonfb404882009-12-24 22:46:43 +00001363 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlsson5dc86332010-02-02 19:58:43 +00001364
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001365 CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
1366 E = CD->init_end();
1367
Craig Topper8a13c412014-05-21 05:09:00 +00001368 llvm::BasicBlock *BaseCtorContinueBB = nullptr;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001369 if (ClassDecl->getNumVBases() &&
1370 !CGM.getTarget().getCXXABI().hasConstructorVariants()) {
1371 // The ABIs that don't have constructor variants need to put a branch
1372 // before the virtual base initialization code.
Reid Kleckner7810af02013-06-19 15:20:38 +00001373 BaseCtorContinueBB =
1374 CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this, ClassDecl);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001375 assert(BaseCtorContinueBB);
1376 }
1377
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001378 llvm::Value *const OldThis = CXXThisValue;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001379 // Virtual base initializers first.
1380 for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001381 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1382 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1383 isInitializerOfDynamicClass(*B))
1384 CXXThisValue = Builder.CreateInvariantGroupBarrier(LoadCXXThis());
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001385 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
1386 }
1387
1388 if (BaseCtorContinueBB) {
1389 // Complete object handler should continue to the remaining initializers.
1390 Builder.CreateBr(BaseCtorContinueBB);
1391 EmitBlock(BaseCtorContinueBB);
1392 }
1393
1394 // Then, non-virtual base initializers.
1395 for (; B != E && (*B)->isBaseInitializer(); B++) {
1396 assert(!(*B)->isBaseVirtual());
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001397
1398 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1399 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1400 isInitializerOfDynamicClass(*B))
1401 CXXThisValue = Builder.CreateInvariantGroupBarrier(LoadCXXThis());
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001402 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
Anders Carlssonfb404882009-12-24 22:46:43 +00001403 }
1404
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001405 CXXThisValue = OldThis;
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001406
Anders Carlssond5895932010-03-28 21:07:49 +00001407 InitializeVTablePointers(ClassDecl);
Anders Carlsson5dc86332010-02-02 19:58:43 +00001408
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001409 // And finally, initialize class members.
John McCall7f416cc2015-09-08 08:05:57 +00001410 FieldConstructionScope FCS(*this, LoadCXXThisAddress());
Lang Hamesbf122742013-02-17 07:22:09 +00001411 ConstructorMemcpyizer CM(*this, CD, Args);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001412 for (; B != E; B++) {
1413 CXXCtorInitializer *Member = (*B);
1414 assert(!Member->isBaseInitializer());
1415 assert(Member->isAnyMemberInitializer() &&
1416 "Delegating initializer on non-delegating constructor");
1417 CM.addMemberInitializer(Member);
1418 }
Lang Hamesbf122742013-02-17 07:22:09 +00001419 CM.finish();
Anders Carlssonfb404882009-12-24 22:46:43 +00001420}
1421
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001422static bool
1423FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
1424
1425static bool
Justin Bogner1cd11f12015-05-20 15:53:59 +00001426HasTrivialDestructorBody(ASTContext &Context,
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001427 const CXXRecordDecl *BaseClassDecl,
1428 const CXXRecordDecl *MostDerivedClassDecl)
1429{
1430 // If the destructor is trivial we don't have to check anything else.
1431 if (BaseClassDecl->hasTrivialDestructor())
1432 return true;
1433
1434 if (!BaseClassDecl->getDestructor()->hasTrivialBody())
1435 return false;
1436
1437 // Check fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001438 for (const auto *Field : BaseClassDecl->fields())
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001439 if (!FieldHasTrivialDestructorBody(Context, Field))
1440 return false;
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001441
1442 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001443 for (const auto &I : BaseClassDecl->bases()) {
1444 if (I.isVirtual())
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001445 continue;
1446
1447 const CXXRecordDecl *NonVirtualBase =
Aaron Ballman574705e2014-03-13 15:41:46 +00001448 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001449 if (!HasTrivialDestructorBody(Context, NonVirtualBase,
1450 MostDerivedClassDecl))
1451 return false;
1452 }
1453
1454 if (BaseClassDecl == MostDerivedClassDecl) {
1455 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00001456 for (const auto &I : BaseClassDecl->vbases()) {
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001457 const CXXRecordDecl *VirtualBase =
Aaron Ballman445a9392014-03-13 16:15:17 +00001458 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001459 if (!HasTrivialDestructorBody(Context, VirtualBase,
1460 MostDerivedClassDecl))
Justin Bogner1cd11f12015-05-20 15:53:59 +00001461 return false;
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001462 }
1463 }
1464
1465 return true;
1466}
1467
1468static bool
1469FieldHasTrivialDestructorBody(ASTContext &Context,
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001470 const FieldDecl *Field)
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001471{
1472 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
1473
1474 const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
1475 if (!RT)
1476 return true;
Justin Bogner1cd11f12015-05-20 15:53:59 +00001477
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001478 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Davide Italiano982bbf42015-06-26 00:18:35 +00001479
1480 // The destructor for an implicit anonymous union member is never invoked.
1481 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
1482 return false;
1483
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001484 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
1485}
1486
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001487/// CanSkipVTablePointerInitialization - Check whether we need to initialize
1488/// any vtable pointers before calling this destructor.
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001489static bool CanSkipVTablePointerInitialization(CodeGenFunction &CGF,
Anders Carlssond6f15182011-05-16 04:08:36 +00001490 const CXXDestructorDecl *Dtor) {
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001491 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1492 if (!ClassDecl->isDynamicClass())
1493 return true;
1494
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001495 if (!Dtor->hasTrivialBody())
1496 return false;
1497
1498 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001499 for (const auto *Field : ClassDecl->fields())
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001500 if (!FieldHasTrivialDestructorBody(CGF.getContext(), Field))
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001501 return false;
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001502
1503 return true;
1504}
1505
John McCallb81884d2010-02-19 09:25:03 +00001506/// EmitDestructorBody - Emits the body of the current destructor.
1507void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
1508 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
1509 CXXDtorType DtorType = CurGD.getDtorType();
1510
Justin Bognerfb298222015-05-20 16:16:23 +00001511 Stmt *Body = Dtor->getBody();
1512 if (Body)
1513 incrementProfileCounter(Body);
1514
John McCallf99a6312010-07-21 05:30:47 +00001515 // The call to operator delete in a deleting destructor happens
1516 // outside of the function-try-block, which means it's always
1517 // possible to delegate the destructor body to the complete
1518 // destructor. Do so.
1519 if (DtorType == Dtor_Deleting) {
1520 EnterDtorCleanups(Dtor, Dtor_Deleting);
1521 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
John McCall7f416cc2015-09-08 08:05:57 +00001522 /*Delegating=*/false, LoadCXXThisAddress());
John McCallf99a6312010-07-21 05:30:47 +00001523 PopCleanupBlock();
1524 return;
1525 }
1526
John McCallb81884d2010-02-19 09:25:03 +00001527 // If the body is a function-try-block, enter the try before
John McCallf99a6312010-07-21 05:30:47 +00001528 // anything else.
1529 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallb81884d2010-02-19 09:25:03 +00001530 if (isTryBody)
John McCallb609d3f2010-07-07 06:56:46 +00001531 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00001532 EmitAsanPrologueOrEpilogue(false);
John McCallb81884d2010-02-19 09:25:03 +00001533
John McCallf99a6312010-07-21 05:30:47 +00001534 // Enter the epilogue cleanups.
1535 RunCleanupsScope DtorEpilogue(*this);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001536
John McCallb81884d2010-02-19 09:25:03 +00001537 // If this is the complete variant, just invoke the base variant;
1538 // the epilogue will destruct the virtual bases. But we can't do
1539 // this optimization if the body is a function-try-block, because
Justin Bogner1cd11f12015-05-20 15:53:59 +00001540 // we'd introduce *two* handler blocks. In the Microsoft ABI, we
Reid Klecknere7de47e2013-07-22 13:51:44 +00001541 // always delegate because we might not have a definition in this TU.
John McCallf99a6312010-07-21 05:30:47 +00001542 switch (DtorType) {
Rafael Espindola1e4df922014-09-16 15:18:21 +00001543 case Dtor_Comdat:
1544 llvm_unreachable("not expecting a COMDAT");
1545
John McCallf99a6312010-07-21 05:30:47 +00001546 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
1547
1548 case Dtor_Complete:
Reid Klecknere7de47e2013-07-22 13:51:44 +00001549 assert((Body || getTarget().getCXXABI().isMicrosoft()) &&
1550 "can't emit a dtor without a body for non-Microsoft ABIs");
1551
John McCallf99a6312010-07-21 05:30:47 +00001552 // Enter the cleanup scopes for virtual bases.
1553 EnterDtorCleanups(Dtor, Dtor_Complete);
1554
Reid Klecknere7de47e2013-07-22 13:51:44 +00001555 if (!isTryBody) {
John McCallf99a6312010-07-21 05:30:47 +00001556 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
John McCall7f416cc2015-09-08 08:05:57 +00001557 /*Delegating=*/false, LoadCXXThisAddress());
John McCallf99a6312010-07-21 05:30:47 +00001558 break;
1559 }
1560 // Fallthrough: act like we're in the base variant.
Justin Bogner1cd11f12015-05-20 15:53:59 +00001561
John McCallf99a6312010-07-21 05:30:47 +00001562 case Dtor_Base:
Reid Klecknere7de47e2013-07-22 13:51:44 +00001563 assert(Body);
1564
John McCallf99a6312010-07-21 05:30:47 +00001565 // Enter the cleanup scopes for fields and non-virtual bases.
1566 EnterDtorCleanups(Dtor, Dtor_Base);
1567
1568 // Initialize the vtable pointers before entering the body.
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001569 if (!CanSkipVTablePointerInitialization(*this, Dtor)) {
1570 // Insert the llvm.invariant.group.barrier intrinsic before initializing
1571 // the vptrs to cancel any previous assumptions we might have made.
1572 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1573 CGM.getCodeGenOpts().OptimizationLevel > 0)
1574 CXXThisValue = Builder.CreateInvariantGroupBarrier(LoadCXXThis());
1575 InitializeVTablePointers(Dtor->getParent());
1576 }
John McCallf99a6312010-07-21 05:30:47 +00001577
1578 if (isTryBody)
1579 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
1580 else if (Body)
1581 EmitStmt(Body);
1582 else {
1583 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
1584 // nothing to do besides what's in the epilogue
1585 }
Fariborz Jahanian0c12ed12011-02-02 23:12:46 +00001586 // -fapple-kext must inline any call to this dtor into
1587 // the caller's body.
Richard Smith9c6890a2012-11-01 22:30:59 +00001588 if (getLangOpts().AppleKext)
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00001589 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
Naomi Musgravee50cb9b2015-08-13 18:35:11 +00001590
John McCallf99a6312010-07-21 05:30:47 +00001591 break;
John McCallb81884d2010-02-19 09:25:03 +00001592 }
1593
John McCallf99a6312010-07-21 05:30:47 +00001594 // Jump out through the epilogue cleanups.
1595 DtorEpilogue.ForceCleanup();
John McCallb81884d2010-02-19 09:25:03 +00001596
1597 // Exit the try if applicable.
1598 if (isTryBody)
John McCallb609d3f2010-07-07 06:56:46 +00001599 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +00001600}
1601
Lang Hamesbf122742013-02-17 07:22:09 +00001602void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) {
1603 const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
1604 const Stmt *RootS = AssignOp->getBody();
1605 assert(isa<CompoundStmt>(RootS) &&
1606 "Body of an implicit assignment operator should be compound stmt.");
1607 const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
1608
1609 LexicalScope Scope(*this, RootCS->getSourceRange());
1610
1611 AssignmentMemcpyizer AM(*this, AssignOp, Args);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001612 for (auto *I : RootCS->body())
Justin Bogner1cd11f12015-05-20 15:53:59 +00001613 AM.emitAssignment(I);
Lang Hamesbf122742013-02-17 07:22:09 +00001614 AM.finish();
1615}
1616
John McCallf99a6312010-07-21 05:30:47 +00001617namespace {
1618 /// Call the operator delete associated with the current destructor.
David Blaikie7e70d682015-08-18 22:40:54 +00001619 struct CallDtorDelete final : EHScopeStack::Cleanup {
John McCallf99a6312010-07-21 05:30:47 +00001620 CallDtorDelete() {}
1621
Craig Topper4f12f102014-03-12 06:41:41 +00001622 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallf99a6312010-07-21 05:30:47 +00001623 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1624 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1625 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1626 CGF.getContext().getTagDeclType(ClassDecl));
1627 }
1628 };
1629
David Blaikie7e70d682015-08-18 22:40:54 +00001630 struct CallDtorDeleteConditional final : EHScopeStack::Cleanup {
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001631 llvm::Value *ShouldDeleteCondition;
1632 public:
1633 CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001634 : ShouldDeleteCondition(ShouldDeleteCondition) {
Craig Topper8a13c412014-05-21 05:09:00 +00001635 assert(ShouldDeleteCondition != nullptr);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001636 }
1637
Craig Topper4f12f102014-03-12 06:41:41 +00001638 void Emit(CodeGenFunction &CGF, Flags flags) override {
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001639 llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
1640 llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
1641 llvm::Value *ShouldCallDelete
1642 = CGF.Builder.CreateIsNull(ShouldDeleteCondition);
1643 CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
1644
1645 CGF.EmitBlock(callDeleteBB);
1646 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1647 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1648 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1649 CGF.getContext().getTagDeclType(ClassDecl));
1650 CGF.Builder.CreateBr(continueBB);
1651
1652 CGF.EmitBlock(continueBB);
1653 }
1654 };
1655
David Blaikie7e70d682015-08-18 22:40:54 +00001656 class DestroyField final : public EHScopeStack::Cleanup {
John McCall4bd0fb12011-07-12 16:41:08 +00001657 const FieldDecl *field;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001658 CodeGenFunction::Destroyer *destroyer;
John McCall4bd0fb12011-07-12 16:41:08 +00001659 bool useEHCleanupForArray;
John McCallf99a6312010-07-21 05:30:47 +00001660
John McCall4bd0fb12011-07-12 16:41:08 +00001661 public:
1662 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
1663 bool useEHCleanupForArray)
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001664 : field(field), destroyer(destroyer),
1665 useEHCleanupForArray(useEHCleanupForArray) {}
John McCallf99a6312010-07-21 05:30:47 +00001666
Craig Topper4f12f102014-03-12 06:41:41 +00001667 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall4bd0fb12011-07-12 16:41:08 +00001668 // Find the address of the field.
John McCall7f416cc2015-09-08 08:05:57 +00001669 Address thisValue = CGF.LoadCXXThisAddress();
Eli Friedman7f1ff602012-04-16 03:54:45 +00001670 QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
1671 LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
1672 LValue LV = CGF.EmitLValueForField(ThisLV, field);
John McCall4bd0fb12011-07-12 16:41:08 +00001673 assert(LV.isSimple());
Justin Bogner1cd11f12015-05-20 15:53:59 +00001674
John McCall4bd0fb12011-07-12 16:41:08 +00001675 CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +00001676 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCallf99a6312010-07-21 05:30:47 +00001677 }
1678 };
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001679
Naomi Musgrave703835c2015-09-16 00:38:22 +00001680 static void EmitSanitizerDtorCallback(CodeGenFunction &CGF, llvm::Value *Ptr,
1681 CharUnits::QuantityType PoisonSize) {
1682 // Pass in void pointer and size of region as arguments to runtime
1683 // function
1684 llvm::Value *Args[] = {CGF.Builder.CreateBitCast(Ptr, CGF.VoidPtrTy),
1685 llvm::ConstantInt::get(CGF.SizeTy, PoisonSize)};
1686
1687 llvm::Type *ArgTypes[] = {CGF.VoidPtrTy, CGF.SizeTy};
1688
1689 llvm::FunctionType *FnType =
1690 llvm::FunctionType::get(CGF.VoidTy, ArgTypes, false);
1691 llvm::Value *Fn =
1692 CGF.CGM.CreateRuntimeFunction(FnType, "__sanitizer_dtor_callback");
1693 CGF.EmitNounwindRuntimeCall(Fn, Args);
1694 }
1695
1696 class SanitizeDtorMembers final : public EHScopeStack::Cleanup {
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001697 const CXXDestructorDecl *Dtor;
1698
1699 public:
Naomi Musgrave703835c2015-09-16 00:38:22 +00001700 SanitizeDtorMembers(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001701
1702 // Generate function call for handling object poisoning.
1703 // Disables tail call elimination, to prevent the current stack frame
1704 // from disappearing from the stack trace.
1705 void Emit(CodeGenFunction &CGF, Flags flags) override {
1706 const ASTRecordLayout &Layout =
1707 CGF.getContext().getASTRecordLayout(Dtor->getParent());
1708
1709 // Nothing to poison.
1710 if (Layout.getFieldCount() == 0)
1711 return;
1712
1713 // Prevent the current stack frame from disappearing from the stack trace.
1714 CGF.CurFn->addFnAttr("disable-tail-calls", "true");
1715
1716 // Construct pointer to region to begin poisoning, and calculate poison
1717 // size, so that only members declared in this class are poisoned.
1718 ASTContext &Context = CGF.getContext();
1719 unsigned fieldIndex = 0;
1720 int startIndex = -1;
1721 // RecordDecl::field_iterator Field;
1722 for (const FieldDecl *Field : Dtor->getParent()->fields()) {
1723 // Poison field if it is trivial
1724 if (FieldHasTrivialDestructorBody(Context, Field)) {
1725 // Start sanitizing at this field
1726 if (startIndex < 0)
1727 startIndex = fieldIndex;
1728
1729 // Currently on the last field, and it must be poisoned with the
1730 // current block.
1731 if (fieldIndex == Layout.getFieldCount() - 1) {
Naomi Musgrave703835c2015-09-16 00:38:22 +00001732 PoisonMembers(CGF, startIndex, Layout.getFieldCount());
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001733 }
1734 } else if (startIndex >= 0) {
1735 // No longer within a block of memory to poison, so poison the block
Naomi Musgrave703835c2015-09-16 00:38:22 +00001736 PoisonMembers(CGF, startIndex, fieldIndex);
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001737 // Re-set the start index
1738 startIndex = -1;
1739 }
1740 fieldIndex += 1;
1741 }
1742 }
1743
1744 private:
NAKAMURA Takumif6cef72f2015-09-04 05:19:31 +00001745 /// \param layoutStartOffset index of the ASTRecordLayout field to
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001746 /// start poisoning (inclusive)
NAKAMURA Takumif6cef72f2015-09-04 05:19:31 +00001747 /// \param layoutEndOffset index of the ASTRecordLayout field to
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001748 /// end poisoning (exclusive)
Naomi Musgrave703835c2015-09-16 00:38:22 +00001749 void PoisonMembers(CodeGenFunction &CGF, unsigned layoutStartOffset,
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001750 unsigned layoutEndOffset) {
1751 ASTContext &Context = CGF.getContext();
1752 const ASTRecordLayout &Layout =
1753 Context.getASTRecordLayout(Dtor->getParent());
1754
1755 llvm::ConstantInt *OffsetSizePtr = llvm::ConstantInt::get(
1756 CGF.SizeTy,
1757 Context.toCharUnitsFromBits(Layout.getFieldOffset(layoutStartOffset))
1758 .getQuantity());
1759
1760 llvm::Value *OffsetPtr = CGF.Builder.CreateGEP(
1761 CGF.Builder.CreateBitCast(CGF.LoadCXXThis(), CGF.Int8PtrTy),
1762 OffsetSizePtr);
1763
1764 CharUnits::QuantityType PoisonSize;
1765 if (layoutEndOffset >= Layout.getFieldCount()) {
1766 PoisonSize = Layout.getNonVirtualSize().getQuantity() -
1767 Context.toCharUnitsFromBits(
1768 Layout.getFieldOffset(layoutStartOffset))
1769 .getQuantity();
1770 } else {
1771 PoisonSize = Context.toCharUnitsFromBits(
1772 Layout.getFieldOffset(layoutEndOffset) -
1773 Layout.getFieldOffset(layoutStartOffset))
1774 .getQuantity();
1775 }
1776
1777 if (PoisonSize == 0)
1778 return;
1779
Naomi Musgrave703835c2015-09-16 00:38:22 +00001780 EmitSanitizerDtorCallback(CGF, OffsetPtr, PoisonSize);
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001781 }
1782 };
Naomi Musgrave703835c2015-09-16 00:38:22 +00001783
1784 class SanitizeDtorVTable final : public EHScopeStack::Cleanup {
1785 const CXXDestructorDecl *Dtor;
1786
1787 public:
1788 SanitizeDtorVTable(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
1789
1790 // Generate function call for handling vtable pointer poisoning.
1791 void Emit(CodeGenFunction &CGF, Flags flags) override {
1792 assert(Dtor->getParent()->isDynamicClass());
NAKAMURA Takumiee82b492015-09-16 06:26:56 +00001793 (void)Dtor;
Naomi Musgrave703835c2015-09-16 00:38:22 +00001794 ASTContext &Context = CGF.getContext();
1795 // Poison vtable and vtable ptr if they exist for this class.
1796 llvm::Value *VTablePtr = CGF.LoadCXXThis();
1797
1798 CharUnits::QuantityType PoisonSize =
1799 Context.toCharUnitsFromBits(CGF.PointerWidthInBits).getQuantity();
1800 // Pass in void pointer and size of region as arguments to runtime
1801 // function
1802 EmitSanitizerDtorCallback(CGF, VTablePtr, PoisonSize);
1803 }
1804 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001805}
John McCallf99a6312010-07-21 05:30:47 +00001806
Hans Wennborgdeff7032013-12-18 01:39:59 +00001807/// \brief Emit all code that comes at the end of class's
Anders Carlssonfb404882009-12-24 22:46:43 +00001808/// destructor. This is to call destructors on members and base classes
1809/// in reverse order of their construction.
John McCallf99a6312010-07-21 05:30:47 +00001810void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
1811 CXXDtorType DtorType) {
Hans Wennborg853ae942014-05-30 16:59:42 +00001812 assert((!DD->isTrivial() || DD->hasAttr<DLLExportAttr>()) &&
1813 "Should not emit dtor epilogue for non-exported trivial dtor!");
Anders Carlssonfb404882009-12-24 22:46:43 +00001814
John McCallf99a6312010-07-21 05:30:47 +00001815 // The deleting-destructor phase just needs to call the appropriate
1816 // operator delete that Sema picked up.
John McCall5c60a6f2010-02-18 19:59:28 +00001817 if (DtorType == Dtor_Deleting) {
Justin Bogner1cd11f12015-05-20 15:53:59 +00001818 assert(DD->getOperatorDelete() &&
Hans Wennborgdeff7032013-12-18 01:39:59 +00001819 "operator delete missing - EnterDtorCleanups");
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001820 if (CXXStructorImplicitParamValue) {
1821 // If there is an implicit param to the deleting dtor, it's a boolean
1822 // telling whether we should call delete at the end of the dtor.
1823 EHStack.pushCleanup<CallDtorDeleteConditional>(
1824 NormalAndEHCleanup, CXXStructorImplicitParamValue);
1825 } else {
1826 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
1827 }
John McCall5c60a6f2010-02-18 19:59:28 +00001828 return;
1829 }
1830
John McCallf99a6312010-07-21 05:30:47 +00001831 const CXXRecordDecl *ClassDecl = DD->getParent();
1832
Richard Smith20104042011-09-18 12:11:43 +00001833 // Unions have no bases and do not call field destructors.
1834 if (ClassDecl->isUnion())
1835 return;
1836
John McCallf99a6312010-07-21 05:30:47 +00001837 // The complete-destructor phase just destructs all the virtual bases.
John McCall5c60a6f2010-02-18 19:59:28 +00001838 if (DtorType == Dtor_Complete) {
Naomi Musgrave703835c2015-09-16 00:38:22 +00001839 // Poison the vtable pointer such that access after the base
1840 // and member destructors are invoked is invalid.
1841 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1842 SanOpts.has(SanitizerKind::Memory) && ClassDecl->getNumVBases() &&
1843 ClassDecl->isPolymorphic())
1844 EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
John McCallf99a6312010-07-21 05:30:47 +00001845
1846 // We push them in the forward order so that they'll be popped in
1847 // the reverse order.
Aaron Ballman445a9392014-03-13 16:15:17 +00001848 for (const auto &Base : ClassDecl->vbases()) {
John McCall5c60a6f2010-02-18 19:59:28 +00001849 CXXRecordDecl *BaseClassDecl
1850 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Justin Bogner1cd11f12015-05-20 15:53:59 +00001851
John McCall5c60a6f2010-02-18 19:59:28 +00001852 // Ignore trivial destructors.
1853 if (BaseClassDecl->hasTrivialDestructor())
1854 continue;
John McCallf99a6312010-07-21 05:30:47 +00001855
John McCallcda666c2010-07-21 07:22:38 +00001856 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1857 BaseClassDecl,
1858 /*BaseIsVirtual*/ true);
John McCall5c60a6f2010-02-18 19:59:28 +00001859 }
John McCallf99a6312010-07-21 05:30:47 +00001860
John McCall5c60a6f2010-02-18 19:59:28 +00001861 return;
1862 }
1863
1864 assert(DtorType == Dtor_Base);
Naomi Musgrave703835c2015-09-16 00:38:22 +00001865 // Poison the vtable pointer if it has no virtual bases, but inherits
1866 // virtual functions.
1867 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1868 SanOpts.has(SanitizerKind::Memory) && !ClassDecl->getNumVBases() &&
1869 ClassDecl->isPolymorphic())
1870 EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001871
John McCallf99a6312010-07-21 05:30:47 +00001872 // Destroy non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001873 for (const auto &Base : ClassDecl->bases()) {
John McCallf99a6312010-07-21 05:30:47 +00001874 // Ignore virtual bases.
1875 if (Base.isVirtual())
1876 continue;
Justin Bogner1cd11f12015-05-20 15:53:59 +00001877
John McCallf99a6312010-07-21 05:30:47 +00001878 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
Justin Bogner1cd11f12015-05-20 15:53:59 +00001879
John McCallf99a6312010-07-21 05:30:47 +00001880 // Ignore trivial destructors.
1881 if (BaseClassDecl->hasTrivialDestructor())
1882 continue;
John McCall5c60a6f2010-02-18 19:59:28 +00001883
John McCallcda666c2010-07-21 07:22:38 +00001884 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1885 BaseClassDecl,
1886 /*BaseIsVirtual*/ false);
John McCallf99a6312010-07-21 05:30:47 +00001887 }
1888
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001889 // Poison fields such that access after their destructors are
1890 // invoked, and before the base class destructor runs, is invalid.
1891 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1892 SanOpts.has(SanitizerKind::Memory))
Naomi Musgrave703835c2015-09-16 00:38:22 +00001893 EHStack.pushCleanup<SanitizeDtorMembers>(NormalAndEHCleanup, DD);
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001894
John McCallf99a6312010-07-21 05:30:47 +00001895 // Destroy direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001896 for (const auto *Field : ClassDecl->fields()) {
1897 QualType type = Field->getType();
John McCall4bd0fb12011-07-12 16:41:08 +00001898 QualType::DestructionKind dtorKind = type.isDestructedType();
1899 if (!dtorKind) continue;
John McCallf99a6312010-07-21 05:30:47 +00001900
Richard Smith921bd202012-02-26 09:11:52 +00001901 // Anonymous union members do not have their destructors called.
1902 const RecordType *RT = type->getAsUnionType();
1903 if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
1904
John McCall4bd0fb12011-07-12 16:41:08 +00001905 CleanupKind cleanupKind = getCleanupKind(dtorKind);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001906 EHStack.pushCleanup<DestroyField>(cleanupKind, Field,
John McCall4bd0fb12011-07-12 16:41:08 +00001907 getDestroyer(dtorKind),
1908 cleanupKind & EHCleanup);
Anders Carlssonfb404882009-12-24 22:46:43 +00001909 }
Anders Carlssonfb404882009-12-24 22:46:43 +00001910}
1911
John McCallf677a8e2011-07-13 06:10:41 +00001912/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1913/// constructor for each of several members of an array.
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001914///
John McCallf677a8e2011-07-13 06:10:41 +00001915/// \param ctor the constructor to call for each element
John McCallf677a8e2011-07-13 06:10:41 +00001916/// \param arrayType the type of the array to initialize
1917/// \param arrayBegin an arrayType*
1918/// \param zeroInitialize true if each element should be
1919/// zero-initialized before it is constructed
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001920void CodeGenFunction::EmitCXXAggrConstructorCall(
1921 const CXXConstructorDecl *ctor, const ConstantArrayType *arrayType,
John McCall7f416cc2015-09-08 08:05:57 +00001922 Address arrayBegin, const CXXConstructExpr *E, bool zeroInitialize) {
John McCallf677a8e2011-07-13 06:10:41 +00001923 QualType elementType;
1924 llvm::Value *numElements =
1925 emitArrayLength(arrayType, elementType, arrayBegin);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001926
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001927 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin, E, zeroInitialize);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001928}
1929
John McCallf677a8e2011-07-13 06:10:41 +00001930/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1931/// constructor for each of several members of an array.
1932///
1933/// \param ctor the constructor to call for each element
1934/// \param numElements the number of elements in the array;
John McCall6549b312011-07-13 07:37:11 +00001935/// may be zero
NAKAMURA Takumiff7a9252015-09-08 09:42:41 +00001936/// \param arrayBase a T*, where T is the type constructed by ctor
John McCallf677a8e2011-07-13 06:10:41 +00001937/// \param zeroInitialize true if each element should be
1938/// zero-initialized before it is constructed
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001939void CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1940 llvm::Value *numElements,
John McCall7f416cc2015-09-08 08:05:57 +00001941 Address arrayBase,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001942 const CXXConstructExpr *E,
1943 bool zeroInitialize) {
John McCall6549b312011-07-13 07:37:11 +00001944
1945 // It's legal for numElements to be zero. This can happen both
1946 // dynamically, because x can be zero in 'new A[x]', and statically,
1947 // because of GCC extensions that permit zero-length arrays. There
1948 // are probably legitimate places where we could assume that this
1949 // doesn't happen, but it's not clear that it's worth it.
Craig Topper8a13c412014-05-21 05:09:00 +00001950 llvm::BranchInst *zeroCheckBranch = nullptr;
John McCall6549b312011-07-13 07:37:11 +00001951
1952 // Optimize for a constant count.
1953 llvm::ConstantInt *constantCount
1954 = dyn_cast<llvm::ConstantInt>(numElements);
1955 if (constantCount) {
1956 // Just skip out if the constant count is zero.
1957 if (constantCount->isZero()) return;
1958
1959 // Otherwise, emit the check.
1960 } else {
1961 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1962 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1963 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1964 EmitBlock(loopBB);
1965 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00001966
John McCallf677a8e2011-07-13 06:10:41 +00001967 // Find the end of the array.
John McCall7f416cc2015-09-08 08:05:57 +00001968 llvm::Value *arrayBegin = arrayBase.getPointer();
John McCallf677a8e2011-07-13 06:10:41 +00001969 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1970 "arrayctor.end");
Anders Carlsson27da15b2010-01-01 20:29:01 +00001971
John McCallf677a8e2011-07-13 06:10:41 +00001972 // Enter the loop, setting up a phi for the current location to initialize.
1973 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1974 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1975 EmitBlock(loopBB);
1976 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1977 "arrayctor.cur");
1978 cur->addIncoming(arrayBegin, entryBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001979
Anders Carlsson27da15b2010-01-01 20:29:01 +00001980 // Inside the loop body, emit the constructor call on the array element.
John McCallf677a8e2011-07-13 06:10:41 +00001981
John McCall7f416cc2015-09-08 08:05:57 +00001982 // The alignment of the base, adjusted by the size of a single element,
1983 // provides a conservative estimate of the alignment of every element.
1984 // (This assumes we never start tracking offsetted alignments.)
1985 //
1986 // Note that these are complete objects and so we don't need to
1987 // use the non-virtual size or alignment.
John McCallf677a8e2011-07-13 06:10:41 +00001988 QualType type = getContext().getTypeDeclType(ctor->getParent());
John McCall7f416cc2015-09-08 08:05:57 +00001989 CharUnits eltAlignment =
1990 arrayBase.getAlignment()
1991 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
1992 Address curAddr = Address(cur, eltAlignment);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001993
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001994 // Zero initialize the storage, if requested.
John McCallf677a8e2011-07-13 06:10:41 +00001995 if (zeroInitialize)
John McCall7f416cc2015-09-08 08:05:57 +00001996 EmitNullInitialization(curAddr, type);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001997
1998 // C++ [class.temporary]p4:
Anders Carlsson27da15b2010-01-01 20:29:01 +00001999 // There are two contexts in which temporaries are destroyed at a different
2000 // point than the end of the full-expression. The first context is when a
Justin Bogner1cd11f12015-05-20 15:53:59 +00002001 // default constructor is called to initialize an element of an array.
2002 // If the constructor has one or more default arguments, the destruction of
2003 // every temporary created in a default argument expression is sequenced
Anders Carlsson27da15b2010-01-01 20:29:01 +00002004 // before the construction of the next array element, if any.
Justin Bogner1cd11f12015-05-20 15:53:59 +00002005
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00002006 {
John McCallbd309292010-07-06 01:34:17 +00002007 RunCleanupsScope Scope(*this);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002008
John McCallf677a8e2011-07-13 06:10:41 +00002009 // Evaluate the constructor and its arguments in a regular
2010 // partial-destroy cleanup.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002011 if (getLangOpts().Exceptions &&
John McCallf677a8e2011-07-13 06:10:41 +00002012 !ctor->getParent()->hasTrivialDestructor()) {
2013 Destroyer *destroyer = destroyCXXObject;
John McCall7f416cc2015-09-08 08:05:57 +00002014 pushRegularPartialArrayCleanup(arrayBegin, cur, type, eltAlignment,
2015 *destroyer);
John McCallf677a8e2011-07-13 06:10:41 +00002016 }
2017
Alexey Samsonov70b9c012014-08-21 20:26:47 +00002018 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/false,
John McCall7f416cc2015-09-08 08:05:57 +00002019 /*Delegating=*/false, curAddr, E);
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00002020 }
Anders Carlsson27da15b2010-01-01 20:29:01 +00002021
John McCallf677a8e2011-07-13 06:10:41 +00002022 // Go to the next element.
2023 llvm::Value *next =
2024 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
2025 "arrayctor.next");
2026 cur->addIncoming(next, Builder.GetInsertBlock());
Anders Carlsson27da15b2010-01-01 20:29:01 +00002027
John McCallf677a8e2011-07-13 06:10:41 +00002028 // Check whether that's the end of the loop.
2029 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
2030 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
2031 Builder.CreateCondBr(done, contBB, loopBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002032
John McCall6549b312011-07-13 07:37:11 +00002033 // Patch the earlier check to skip over the loop.
2034 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
2035
John McCallf677a8e2011-07-13 06:10:41 +00002036 EmitBlock(contBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002037}
2038
John McCall82fe67b2011-07-09 01:37:26 +00002039void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002040 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002041 QualType type) {
2042 const RecordType *rtype = type->castAs<RecordType>();
2043 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
2044 const CXXDestructorDecl *dtor = record->getDestructor();
2045 assert(!dtor->isTrivial());
2046 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
Douglas Gregor61535002013-01-31 05:50:40 +00002047 /*Delegating=*/false, addr);
John McCall82fe67b2011-07-09 01:37:26 +00002048}
2049
Alexey Samsonov70b9c012014-08-21 20:26:47 +00002050void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
2051 CXXCtorType Type,
2052 bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +00002053 bool Delegating, Address This,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00002054 const CXXConstructExpr *E) {
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002055 const CXXRecordDecl *ClassDecl = D->getParent();
2056
Richard Smith419bd092015-04-29 19:26:57 +00002057 // C++11 [class.mfct.non-static]p2:
2058 // If a non-static member function of a class X is called for an object that
2059 // is not of type X, or of a type derived from X, the behavior is undefined.
2060 // FIXME: Provide a source location here.
John McCall7f416cc2015-09-08 08:05:57 +00002061 EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall, SourceLocation(),
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002062 This.getPointer(), getContext().getRecordType(ClassDecl));
John McCallca972cd2010-02-06 00:25:16 +00002063
Richard Smith419bd092015-04-29 19:26:57 +00002064 if (D->isTrivial() && D->isDefaultConstructor()) {
2065 assert(E->getNumArgs() == 0 && "trivial default ctor with args");
2066 return;
2067 }
2068
2069 // If this is a trivial constructor, just emit what's needed. If this is a
2070 // union copy constructor, we must emit a memcpy, because the AST does not
2071 // model that copy.
2072 if (isMemcpyEquivalentSpecialMember(D)) {
Alexey Samsonov70b9c012014-08-21 20:26:47 +00002073 assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
John McCallca972cd2010-02-06 00:25:16 +00002074
Alexey Samsonov70b9c012014-08-21 20:26:47 +00002075 const Expr *Arg = E->getArg(0);
David Majnemerfd1e7392015-02-03 23:04:06 +00002076 QualType SrcTy = Arg->getType();
John McCall7f416cc2015-09-08 08:05:57 +00002077 Address Src = EmitLValue(Arg).getAddress();
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002078 QualType DestTy = getContext().getTypeDeclType(ClassDecl);
David Majnemerfd1e7392015-02-03 23:04:06 +00002079 EmitAggregateCopyCtor(This, Src, DestTy, SrcTy);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002080 return;
2081 }
2082
Reid Kleckner89077a12013-12-17 19:46:40 +00002083 CallArgList Args;
2084
2085 // Push the this ptr.
John McCall7f416cc2015-09-08 08:05:57 +00002086 Args.add(RValue::get(This.getPointer()), D->getThisType(getContext()));
Reid Kleckner89077a12013-12-17 19:46:40 +00002087
2088 // Add the rest of the user-supplied arguments.
2089 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
David Blaikief05779e2015-07-21 18:37:18 +00002090 EmitCallArgs(Args, FPT, E->arguments(), E->getConstructor());
Reid Kleckner89077a12013-12-17 19:46:40 +00002091
2092 // Insert any ABI-specific implicit constructor arguments.
2093 unsigned ExtraArgs = CGM.getCXXABI().addImplicitConstructorArgs(
2094 *this, D, Type, ForVirtualBase, Delegating, Args);
2095
2096 // Emit the call.
Rafael Espindola1ac0ec82014-09-11 15:42:06 +00002097 llvm::Value *Callee = CGM.getAddrOfCXXStructor(D, getFromCtorType(Type));
Reid Kleckner89077a12013-12-17 19:46:40 +00002098 const CGFunctionInfo &Info =
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002099 CGM.getTypes().arrangeCXXConstructorCall(Args, D, Type, ExtraArgs);
Reid Kleckner89077a12013-12-17 19:46:40 +00002100 EmitCall(Info, Callee, ReturnValueSlot(), Args, D);
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002101
2102 // Generate vtable assumptions if we're constructing a complete object
2103 // with a vtable. We don't do this for base subobjects for two reasons:
2104 // first, it's incorrect for classes with virtual bases, and second, we're
2105 // about to overwrite the vptrs anyway.
2106 // We also have to make sure if we can refer to vtable:
2107 // - Otherwise we can refer to vtable if it's safe to speculatively emit.
2108 // FIXME: If vtable is used by ctor/dtor, or if vtable is external and we are
2109 // sure that definition of vtable is not hidden,
2110 // then we are always safe to refer to it.
Piotr Padlewski69dc9712015-09-28 20:30:22 +00002111 // FIXME: It looks like InstCombine is very inefficient on dealing with
2112 // assumes. Make assumption loads require -fstrict-vtable-pointers temporarily.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002113 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2114 ClassDecl->isDynamicClass() && Type != Ctor_Base &&
Piotr Padlewski69dc9712015-09-28 20:30:22 +00002115 CGM.getCXXABI().canSpeculativelyEmitVTable(ClassDecl) &&
2116 CGM.getCodeGenOpts().StrictVTablePointers)
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002117 EmitVTableAssumptionLoads(ClassDecl, This);
2118}
2119
2120void CodeGenFunction::EmitVTableAssumptionLoad(const VPtr &Vptr, Address This) {
2121 llvm::Value *VTableGlobal =
2122 CGM.getCXXABI().getVTableAddressPoint(Vptr.Base, Vptr.VTableClass);
2123 if (!VTableGlobal)
2124 return;
2125
2126 // We can just use the base offset in the complete class.
2127 CharUnits NonVirtualOffset = Vptr.Base.getBaseOffset();
2128
2129 if (!NonVirtualOffset.isZero())
2130 This =
2131 ApplyNonVirtualAndVirtualOffset(*this, This, NonVirtualOffset, nullptr,
2132 Vptr.VTableClass, Vptr.NearestVBase);
2133
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002134 llvm::Value *VPtrValue =
2135 GetVTablePtr(This, VTableGlobal->getType(), Vptr.VTableClass);
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002136 llvm::Value *Cmp =
2137 Builder.CreateICmpEQ(VPtrValue, VTableGlobal, "cmp.vtables");
2138 Builder.CreateAssumption(Cmp);
2139}
2140
2141void CodeGenFunction::EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl,
2142 Address This) {
2143 if (CGM.getCXXABI().doStructorsInitializeVPtrs(ClassDecl))
2144 for (const VPtr &Vptr : getVTablePointers(ClassDecl))
2145 EmitVTableAssumptionLoad(Vptr, This);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002146}
2147
John McCallf8ff7b92010-02-23 00:48:20 +00002148void
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002149CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
John McCall7f416cc2015-09-08 08:05:57 +00002150 Address This, Address Src,
2151 const CXXConstructExpr *E) {
Richard Smith419bd092015-04-29 19:26:57 +00002152 if (isMemcpyEquivalentSpecialMember(D)) {
Alexey Samsonov96fd0a42014-08-26 20:18:26 +00002153 assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
Sebastian Redl22653ba2011-08-30 19:58:05 +00002154 assert(D->isCopyOrMoveConstructor() &&
2155 "trivial 1-arg ctor not a copy/move ctor");
David Majnemerfd1e7392015-02-03 23:04:06 +00002156 EmitAggregateCopyCtor(This, Src,
2157 getContext().getTypeDeclType(D->getParent()),
Benjamin Kramerf48ee442015-07-18 14:35:53 +00002158 (*E->arg_begin())->getType());
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002159 return;
2160 }
Rafael Espindola1ac0ec82014-09-11 15:42:06 +00002161 llvm::Value *Callee = CGM.getAddrOfCXXStructor(D, StructorType::Complete);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002162 assert(D->isInstance() &&
2163 "Trying to emit a member call expr on a static method!");
Justin Bogner1cd11f12015-05-20 15:53:59 +00002164
Reid Kleckner739756c2013-12-04 19:23:12 +00002165 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
Justin Bogner1cd11f12015-05-20 15:53:59 +00002166
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002167 CallArgList Args;
Justin Bogner1cd11f12015-05-20 15:53:59 +00002168
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002169 // Push the this ptr.
John McCall7f416cc2015-09-08 08:05:57 +00002170 Args.add(RValue::get(This.getPointer()), D->getThisType(getContext()));
Justin Bogner1cd11f12015-05-20 15:53:59 +00002171
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002172 // Push the src ptr.
Alp Toker9cacbab2014-01-20 20:26:09 +00002173 QualType QT = *(FPT->param_type_begin());
Chris Lattner2192fe52011-07-18 04:24:23 +00002174 llvm::Type *t = CGM.getTypes().ConvertType(QT);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002175 Src = Builder.CreateBitCast(Src, t);
John McCall7f416cc2015-09-08 08:05:57 +00002176 Args.add(RValue::get(Src.getPointer()), QT);
Reid Kleckner739756c2013-12-04 19:23:12 +00002177
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002178 // Skip over first argument (Src).
David Blaikief05779e2015-07-21 18:37:18 +00002179 EmitCallArgs(Args, FPT, drop_begin(E->arguments(), 1), E->getConstructor(),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002180 /*ParamsToSkip*/ 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002181
John McCall8dda7b22012-07-07 06:41:13 +00002182 EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, RequiredArgs::All),
2183 Callee, ReturnValueSlot(), Args, D);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002184}
2185
2186void
John McCallf8ff7b92010-02-23 00:48:20 +00002187CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
2188 CXXCtorType CtorType,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002189 const FunctionArgList &Args,
2190 SourceLocation Loc) {
John McCallf8ff7b92010-02-23 00:48:20 +00002191 CallArgList DelegateArgs;
2192
2193 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
2194 assert(I != E && "no parameters to constructor");
2195
2196 // this
Eli Friedman43dca6a2011-05-02 17:57:46 +00002197 DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType());
John McCallf8ff7b92010-02-23 00:48:20 +00002198 ++I;
2199
2200 // vtt
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00002201 if (llvm::Value *VTT = GetVTTParameter(GlobalDecl(Ctor, CtorType),
Douglas Gregor61535002013-01-31 05:50:40 +00002202 /*ForVirtualBase=*/false,
2203 /*Delegating=*/true)) {
John McCallf8ff7b92010-02-23 00:48:20 +00002204 QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
Eli Friedman43dca6a2011-05-02 17:57:46 +00002205 DelegateArgs.add(RValue::get(VTT), VoidPP);
John McCallf8ff7b92010-02-23 00:48:20 +00002206
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002207 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
John McCallf8ff7b92010-02-23 00:48:20 +00002208 assert(I != E && "cannot skip vtt parameter, already done with args");
John McCalla738c252011-03-09 04:27:21 +00002209 assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
John McCallf8ff7b92010-02-23 00:48:20 +00002210 ++I;
2211 }
2212 }
2213
2214 // Explicit arguments.
2215 for (; I != E; ++I) {
John McCall32ea9692011-03-11 20:59:21 +00002216 const VarDecl *param = *I;
Nick Lewycky2d84e842013-10-02 02:29:49 +00002217 // FIXME: per-argument source location
2218 EmitDelegateCallArg(DelegateArgs, param, Loc);
John McCallf8ff7b92010-02-23 00:48:20 +00002219 }
2220
Rafael Espindola1ac0ec82014-09-11 15:42:06 +00002221 llvm::Value *Callee =
2222 CGM.getAddrOfCXXStructor(Ctor, getFromCtorType(CtorType));
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00002223 EmitCall(CGM.getTypes()
2224 .arrangeCXXStructorDeclaration(Ctor, getFromCtorType(CtorType)),
Manman Ren01754612013-03-20 16:59:38 +00002225 Callee, ReturnValueSlot(), DelegateArgs, Ctor);
John McCallf8ff7b92010-02-23 00:48:20 +00002226}
2227
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002228namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002229 struct CallDelegatingCtorDtor final : EHScopeStack::Cleanup {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002230 const CXXDestructorDecl *Dtor;
John McCall7f416cc2015-09-08 08:05:57 +00002231 Address Addr;
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002232 CXXDtorType Type;
2233
John McCall7f416cc2015-09-08 08:05:57 +00002234 CallDelegatingCtorDtor(const CXXDestructorDecl *D, Address Addr,
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002235 CXXDtorType Type)
2236 : Dtor(D), Addr(Addr), Type(Type) {}
2237
Craig Topper4f12f102014-03-12 06:41:41 +00002238 void Emit(CodeGenFunction &CGF, Flags flags) override {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002239 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
Douglas Gregor61535002013-01-31 05:50:40 +00002240 /*Delegating=*/true, Addr);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002241 }
2242 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002243}
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002244
Alexis Hunt61bc1732011-05-01 07:04:31 +00002245void
2246CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
2247 const FunctionArgList &Args) {
2248 assert(Ctor->isDelegatingConstructor());
2249
John McCall7f416cc2015-09-08 08:05:57 +00002250 Address ThisPtr = LoadCXXThisAddress();
Alexis Hunt61bc1732011-05-01 07:04:31 +00002251
John McCall31168b02011-06-15 23:02:42 +00002252 AggValueSlot AggSlot =
John McCall7f416cc2015-09-08 08:05:57 +00002253 AggValueSlot::forAddr(ThisPtr, Qualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +00002254 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00002255 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00002256 AggValueSlot::IsNotAliased);
Alexis Hunt61bc1732011-05-01 07:04:31 +00002257
2258 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
Alexis Hunt61bc1732011-05-01 07:04:31 +00002259
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002260 const CXXRecordDecl *ClassDecl = Ctor->getParent();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002261 if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002262 CXXDtorType Type =
2263 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
2264
2265 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
2266 ClassDecl->getDestructor(),
2267 ThisPtr, Type);
2268 }
2269}
Alexis Hunt61bc1732011-05-01 07:04:31 +00002270
Anders Carlsson27da15b2010-01-01 20:29:01 +00002271void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
2272 CXXDtorType Type,
Anders Carlssonf8a71f02010-05-02 23:29:11 +00002273 bool ForVirtualBase,
Douglas Gregor61535002013-01-31 05:50:40 +00002274 bool Delegating,
John McCall7f416cc2015-09-08 08:05:57 +00002275 Address This) {
Reid Kleckner6fe771a2013-12-13 00:53:54 +00002276 CGM.getCXXABI().EmitDestructorCall(*this, DD, Type, ForVirtualBase,
2277 Delegating, This);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002278}
2279
John McCall53cad2e2010-07-21 01:41:18 +00002280namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002281 struct CallLocalDtor final : EHScopeStack::Cleanup {
John McCall53cad2e2010-07-21 01:41:18 +00002282 const CXXDestructorDecl *Dtor;
John McCall7f416cc2015-09-08 08:05:57 +00002283 Address Addr;
John McCall53cad2e2010-07-21 01:41:18 +00002284
John McCall7f416cc2015-09-08 08:05:57 +00002285 CallLocalDtor(const CXXDestructorDecl *D, Address Addr)
John McCall53cad2e2010-07-21 01:41:18 +00002286 : Dtor(D), Addr(Addr) {}
2287
Craig Topper4f12f102014-03-12 06:41:41 +00002288 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall53cad2e2010-07-21 01:41:18 +00002289 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +00002290 /*ForVirtualBase=*/false,
2291 /*Delegating=*/false, Addr);
John McCall53cad2e2010-07-21 01:41:18 +00002292 }
2293 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002294}
John McCall53cad2e2010-07-21 01:41:18 +00002295
John McCall8680f872010-07-21 06:29:51 +00002296void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
John McCall7f416cc2015-09-08 08:05:57 +00002297 Address Addr) {
John McCallcda666c2010-07-21 07:22:38 +00002298 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
John McCall8680f872010-07-21 06:29:51 +00002299}
2300
John McCall7f416cc2015-09-08 08:05:57 +00002301void CodeGenFunction::PushDestructorCleanup(QualType T, Address Addr) {
John McCallbd309292010-07-06 01:34:17 +00002302 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
2303 if (!ClassDecl) return;
2304 if (ClassDecl->hasTrivialDestructor()) return;
2305
2306 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCalla85af562011-04-28 02:15:35 +00002307 assert(D && D->isUsed() && "destructor not marked as used!");
John McCall8680f872010-07-21 06:29:51 +00002308 PushDestructorCleanup(D, Addr);
John McCallbd309292010-07-06 01:34:17 +00002309}
2310
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002311void CodeGenFunction::InitializeVTablePointer(const VPtr &Vptr) {
Anders Carlssone87fae92010-03-28 19:40:00 +00002312 // Compute the address point.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002313 llvm::Value *VTableAddressPoint =
2314 CGM.getCXXABI().getVTableAddressPointInStructor(
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002315 *this, Vptr.VTableClass, Vptr.Base, Vptr.NearestVBase);
2316
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002317 if (!VTableAddressPoint)
2318 return;
Anders Carlssone87fae92010-03-28 19:40:00 +00002319
Anders Carlsson6a0227d2010-04-20 16:22:16 +00002320 // Compute where to store the address point.
Craig Topper8a13c412014-05-21 05:09:00 +00002321 llvm::Value *VirtualOffset = nullptr;
Ken Dyckcfc332c2011-03-23 00:45:26 +00002322 CharUnits NonVirtualOffset = CharUnits::Zero();
Justin Bogner1cd11f12015-05-20 15:53:59 +00002323
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002324 if (CGM.getCXXABI().isVirtualOffsetNeededForVTableField(*this, Vptr)) {
Anders Carlsson91baecf2010-04-20 18:05:10 +00002325 // We need to use the virtual base offset offset because the virtual base
2326 // might have a different offset in the most derived class.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002327
2328 VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(
2329 *this, LoadCXXThisAddress(), Vptr.VTableClass, Vptr.NearestVBase);
2330 NonVirtualOffset = Vptr.OffsetFromNearestVBase;
Anders Carlsson91baecf2010-04-20 18:05:10 +00002331 } else {
Anders Carlssonc58fb552010-05-03 00:29:58 +00002332 // We can just use the base offset in the complete class.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002333 NonVirtualOffset = Vptr.Base.getBaseOffset();
Anders Carlsson91baecf2010-04-20 18:05:10 +00002334 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002335
Anders Carlssonc58fb552010-05-03 00:29:58 +00002336 // Apply the offsets.
John McCall7f416cc2015-09-08 08:05:57 +00002337 Address VTableField = LoadCXXThisAddress();
Justin Bogner1cd11f12015-05-20 15:53:59 +00002338
Ken Dyckcfc332c2011-03-23 00:45:26 +00002339 if (!NonVirtualOffset.isZero() || VirtualOffset)
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002340 VTableField = ApplyNonVirtualAndVirtualOffset(
2341 *this, VTableField, NonVirtualOffset, VirtualOffset, Vptr.VTableClass,
2342 Vptr.NearestVBase);
Anders Carlsson6a0227d2010-04-20 16:22:16 +00002343
Reid Kleckner8d585132014-12-03 21:00:21 +00002344 // Finally, store the address point. Use the same LLVM types as the field to
2345 // support optimization.
2346 llvm::Type *VTablePtrTy =
2347 llvm::FunctionType::get(CGM.Int32Ty, /*isVarArg=*/true)
2348 ->getPointerTo()
2349 ->getPointerTo();
2350 VTableField = Builder.CreateBitCast(VTableField, VTablePtrTy->getPointerTo());
2351 VTableAddressPoint = Builder.CreateBitCast(VTableAddressPoint, VTablePtrTy);
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002352
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002353 llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002354 CGM.DecorateInstructionWithTBAA(Store, CGM.getTBAAInfoForVTablePtr());
2355 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2356 CGM.getCodeGenOpts().StrictVTablePointers)
2357 CGM.DecorateInstructionWithInvariantGroup(Store, Vptr.VTableClass);
Anders Carlssone87fae92010-03-28 19:40:00 +00002358}
2359
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002360CodeGenFunction::VPtrsVector
2361CodeGenFunction::getVTablePointers(const CXXRecordDecl *VTableClass) {
2362 CodeGenFunction::VPtrsVector VPtrsResult;
2363 VisitedVirtualBasesSetTy VBases;
2364 getVTablePointers(BaseSubobject(VTableClass, CharUnits::Zero()),
2365 /*NearestVBase=*/nullptr,
2366 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
2367 /*BaseIsNonVirtualPrimaryBase=*/false, VTableClass, VBases,
2368 VPtrsResult);
2369 return VPtrsResult;
2370}
2371
2372void CodeGenFunction::getVTablePointers(BaseSubobject Base,
2373 const CXXRecordDecl *NearestVBase,
2374 CharUnits OffsetFromNearestVBase,
2375 bool BaseIsNonVirtualPrimaryBase,
2376 const CXXRecordDecl *VTableClass,
2377 VisitedVirtualBasesSetTy &VBases,
2378 VPtrsVector &Vptrs) {
Anders Carlssond5895932010-03-28 21:07:49 +00002379 // If this base is a non-virtual primary base the address point has already
2380 // been set.
2381 if (!BaseIsNonVirtualPrimaryBase) {
2382 // Initialize the vtable pointer for this base.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002383 VPtr Vptr = {Base, NearestVBase, OffsetFromNearestVBase, VTableClass};
2384 Vptrs.push_back(Vptr);
Anders Carlssond5895932010-03-28 21:07:49 +00002385 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002386
Anders Carlssond5895932010-03-28 21:07:49 +00002387 const CXXRecordDecl *RD = Base.getBase();
2388
2389 // Traverse bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00002390 for (const auto &I : RD->bases()) {
Anders Carlssond5895932010-03-28 21:07:49 +00002391 CXXRecordDecl *BaseDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00002392 = cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Anders Carlssond5895932010-03-28 21:07:49 +00002393
2394 // Ignore classes without a vtable.
2395 if (!BaseDecl->isDynamicClass())
2396 continue;
2397
Ken Dyck3fb4c892011-03-23 01:04:18 +00002398 CharUnits BaseOffset;
2399 CharUnits BaseOffsetFromNearestVBase;
Anders Carlsson948d3f42010-03-29 01:16:41 +00002400 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlssond5895932010-03-28 21:07:49 +00002401
Aaron Ballman574705e2014-03-13 15:41:46 +00002402 if (I.isVirtual()) {
Anders Carlssond5895932010-03-28 21:07:49 +00002403 // Check if we've visited this virtual base before.
David Blaikie82e95a32014-11-19 07:49:47 +00002404 if (!VBases.insert(BaseDecl).second)
Anders Carlssond5895932010-03-28 21:07:49 +00002405 continue;
2406
Justin Bogner1cd11f12015-05-20 15:53:59 +00002407 const ASTRecordLayout &Layout =
Anders Carlssond5895932010-03-28 21:07:49 +00002408 getContext().getASTRecordLayout(VTableClass);
2409
Ken Dyck3fb4c892011-03-23 01:04:18 +00002410 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
2411 BaseOffsetFromNearestVBase = CharUnits::Zero();
Anders Carlsson948d3f42010-03-29 01:16:41 +00002412 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlssond5895932010-03-28 21:07:49 +00002413 } else {
2414 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
2415
Ken Dyck16ffcac2011-03-24 01:21:01 +00002416 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
Justin Bogner1cd11f12015-05-20 15:53:59 +00002417 BaseOffsetFromNearestVBase =
Ken Dyck3fb4c892011-03-23 01:04:18 +00002418 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson948d3f42010-03-29 01:16:41 +00002419 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlssond5895932010-03-28 21:07:49 +00002420 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002421
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002422 getVTablePointers(
2423 BaseSubobject(BaseDecl, BaseOffset),
2424 I.isVirtual() ? BaseDecl : NearestVBase, BaseOffsetFromNearestVBase,
2425 BaseDeclIsNonVirtualPrimaryBase, VTableClass, VBases, Vptrs);
Anders Carlssond5895932010-03-28 21:07:49 +00002426 }
2427}
2428
2429void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
2430 // Ignore classes without a vtable.
Anders Carlsson1f9348c2010-03-26 04:39:42 +00002431 if (!RD->isDynamicClass())
Anders Carlsson27da15b2010-01-01 20:29:01 +00002432 return;
2433
Anders Carlssond5895932010-03-28 21:07:49 +00002434 // Initialize the vtable pointers for this class and all of its bases.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002435 if (CGM.getCXXABI().doStructorsInitializeVPtrs(RD))
2436 for (const VPtr &Vptr : getVTablePointers(RD))
2437 InitializeVTablePointer(Vptr);
Timur Iskhodzhanovb6487322013-10-09 18:16:58 +00002438
2439 if (RD->getNumVBases())
2440 CGM.getCXXABI().initializeHiddenVirtualInheritanceMembers(*this, RD);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002441}
Dan Gohman8fc50c22010-10-26 18:44:08 +00002442
John McCall7f416cc2015-09-08 08:05:57 +00002443llvm::Value *CodeGenFunction::GetVTablePtr(Address This,
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002444 llvm::Type *VTableTy,
2445 const CXXRecordDecl *RD) {
2446 Address VTablePtrSrc = Builder.CreateElementBitCast(This, VTableTy);
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002447 llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002448 CGM.DecorateInstructionWithTBAA(VTable, CGM.getTBAAInfoForVTablePtr());
2449
2450 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2451 CGM.getCodeGenOpts().StrictVTablePointers)
2452 CGM.DecorateInstructionWithInvariantGroup(VTable, RD);
2453
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002454 return VTable;
Dan Gohman8fc50c22010-10-26 18:44:08 +00002455}
Anders Carlssonc36783e2011-05-08 20:32:23 +00002456
Peter Collingbourned2926c92015-03-14 02:42:25 +00002457// If a class has a single non-virtual base and does not introduce or override
2458// virtual member functions or fields, it will have the same layout as its base.
2459// This function returns the least derived such class.
2460//
2461// Casting an instance of a base class to such a derived class is technically
2462// undefined behavior, but it is a relatively common hack for introducing member
2463// functions on class instances with specific properties (e.g. llvm::Operator)
2464// that works under most compilers and should not have security implications, so
2465// we allow it by default. It can be disabled with -fsanitize=cfi-cast-strict.
2466static const CXXRecordDecl *
2467LeastDerivedClassWithSameLayout(const CXXRecordDecl *RD) {
2468 if (!RD->field_empty())
2469 return RD;
2470
2471 if (RD->getNumVBases() != 0)
2472 return RD;
2473
2474 if (RD->getNumBases() != 1)
2475 return RD;
2476
2477 for (const CXXMethodDecl *MD : RD->methods()) {
2478 if (MD->isVirtual()) {
2479 // Virtual member functions are only ok if they are implicit destructors
2480 // because the implicit destructor will have the same semantics as the
2481 // base class's destructor if no fields are added.
2482 if (isa<CXXDestructorDecl>(MD) && MD->isImplicit())
2483 continue;
2484 return RD;
2485 }
2486 }
2487
2488 return LeastDerivedClassWithSameLayout(
2489 RD->bases_begin()->getType()->getAsCXXRecordDecl());
2490}
2491
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002492void CodeGenFunction::EmitVTablePtrCheckForCall(const CXXMethodDecl *MD,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002493 llvm::Value *VTable,
2494 CFITypeCheckKind TCK,
2495 SourceLocation Loc) {
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002496 const CXXRecordDecl *ClassDecl = MD->getParent();
2497 if (!SanOpts.has(SanitizerKind::CFICastStrict))
2498 ClassDecl = LeastDerivedClassWithSameLayout(ClassDecl);
2499
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002500 EmitVTablePtrCheck(ClassDecl, VTable, TCK, Loc);
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002501}
2502
Peter Collingbourned2926c92015-03-14 02:42:25 +00002503void CodeGenFunction::EmitVTablePtrCheckForCast(QualType T,
2504 llvm::Value *Derived,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002505 bool MayBeNull,
2506 CFITypeCheckKind TCK,
2507 SourceLocation Loc) {
Peter Collingbourned2926c92015-03-14 02:42:25 +00002508 if (!getLangOpts().CPlusPlus)
2509 return;
2510
2511 auto *ClassTy = T->getAs<RecordType>();
2512 if (!ClassTy)
2513 return;
2514
2515 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassTy->getDecl());
2516
2517 if (!ClassDecl->isCompleteDefinition() || !ClassDecl->isDynamicClass())
2518 return;
2519
Peter Collingbourned2926c92015-03-14 02:42:25 +00002520 if (!SanOpts.has(SanitizerKind::CFICastStrict))
2521 ClassDecl = LeastDerivedClassWithSameLayout(ClassDecl);
2522
2523 llvm::BasicBlock *ContBlock = 0;
2524
2525 if (MayBeNull) {
2526 llvm::Value *DerivedNotNull =
2527 Builder.CreateIsNotNull(Derived, "cast.nonnull");
2528
2529 llvm::BasicBlock *CheckBlock = createBasicBlock("cast.check");
2530 ContBlock = createBasicBlock("cast.cont");
2531
2532 Builder.CreateCondBr(DerivedNotNull, CheckBlock, ContBlock);
2533
2534 EmitBlock(CheckBlock);
2535 }
2536
John McCall7f416cc2015-09-08 08:05:57 +00002537 llvm::Value *VTable =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002538 GetVTablePtr(Address(Derived, getPointerAlign()), Int8PtrTy, ClassDecl);
2539
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002540 EmitVTablePtrCheck(ClassDecl, VTable, TCK, Loc);
Peter Collingbourned2926c92015-03-14 02:42:25 +00002541
2542 if (MayBeNull) {
2543 Builder.CreateBr(ContBlock);
2544 EmitBlock(ContBlock);
2545 }
2546}
2547
2548void CodeGenFunction::EmitVTablePtrCheck(const CXXRecordDecl *RD,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002549 llvm::Value *VTable,
2550 CFITypeCheckKind TCK,
2551 SourceLocation Loc) {
Peter Collingbournee5706442015-07-09 19:56:14 +00002552 if (CGM.IsCFIBlacklistedRecord(RD))
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002553 return;
2554
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002555 SanitizerScope SanScope(this);
2556
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002557 llvm::Value *BitSetName = llvm::MetadataAsValue::get(
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00002558 getLLVMContext(),
2559 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)));
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002560
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002561 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
2562 llvm::Value *BitSetTest =
2563 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::bitset_test),
2564 {CastedVTable, BitSetName});
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002565
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002566 SanitizerMask M;
2567 switch (TCK) {
2568 case CFITCK_VCall:
2569 M = SanitizerKind::CFIVCall;
2570 break;
2571 case CFITCK_NVCall:
2572 M = SanitizerKind::CFINVCall;
2573 break;
2574 case CFITCK_DerivedCast:
2575 M = SanitizerKind::CFIDerivedCast;
2576 break;
2577 case CFITCK_UnrelatedCast:
2578 M = SanitizerKind::CFIUnrelatedCast;
2579 break;
2580 }
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002581
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002582 llvm::Constant *StaticData[] = {
2583 EmitCheckSourceLocation(Loc),
2584 EmitCheckTypeDescriptor(QualType(RD->getTypeForDecl(), 0)),
2585 llvm::ConstantInt::get(Int8Ty, TCK),
2586 };
2587 EmitCheck(std::make_pair(BitSetTest, M), "cfi_bad_type", StaticData,
2588 CastedVTable);
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002589}
Anders Carlssonc36783e2011-05-08 20:32:23 +00002590
2591// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
2592// quite what we want.
2593static const Expr *skipNoOpCastsAndParens(const Expr *E) {
2594 while (true) {
2595 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
2596 E = PE->getSubExpr();
2597 continue;
2598 }
2599
2600 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
2601 if (CE->getCastKind() == CK_NoOp) {
2602 E = CE->getSubExpr();
2603 continue;
2604 }
2605 }
2606 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2607 if (UO->getOpcode() == UO_Extension) {
2608 E = UO->getSubExpr();
2609 continue;
2610 }
2611 }
2612 return E;
2613 }
2614}
2615
Benjamin Kramer7463ed72013-08-25 22:46:27 +00002616bool
2617CodeGenFunction::CanDevirtualizeMemberFunctionCall(const Expr *Base,
2618 const CXXMethodDecl *MD) {
2619 // When building with -fapple-kext, all calls must go through the vtable since
2620 // the kernel linker can do runtime patching of vtables.
2621 if (getLangOpts().AppleKext)
2622 return false;
2623
Anders Carlssonc36783e2011-05-08 20:32:23 +00002624 // If the most derived class is marked final, we know that no subclass can
2625 // override this member function and so we can devirtualize it. For example:
2626 //
2627 // struct A { virtual void f(); }
2628 // struct B final : A { };
2629 //
2630 // void f(B *b) {
2631 // b->f();
2632 // }
2633 //
Benjamin Kramer7463ed72013-08-25 22:46:27 +00002634 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
Anders Carlssonc36783e2011-05-08 20:32:23 +00002635 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
2636 return true;
2637
2638 // If the member function is marked 'final', we know that it can't be
2639 // overridden and can therefore devirtualize it.
2640 if (MD->hasAttr<FinalAttr>())
2641 return true;
2642
2643 // Similarly, if the class itself is marked 'final' it can't be overridden
2644 // and we can therefore devirtualize the member function call.
2645 if (MD->getParent()->hasAttr<FinalAttr>())
2646 return true;
2647
2648 Base = skipNoOpCastsAndParens(Base);
2649 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
2650 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
2651 // This is a record decl. We know the type and can devirtualize it.
2652 return VD->getType()->isRecordType();
2653 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002654
Anders Carlssonc36783e2011-05-08 20:32:23 +00002655 return false;
2656 }
Benjamin Kramer7463ed72013-08-25 22:46:27 +00002657
2658 // We can devirtualize calls on an object accessed by a class member access
2659 // expression, since by C++11 [basic.life]p6 we know that it can't refer to
2660 // a derived class object constructed in the same location.
2661 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Base))
2662 if (const ValueDecl *VD = dyn_cast<ValueDecl>(ME->getMemberDecl()))
2663 return VD->getType()->isRecordType();
2664
Anders Carlssonc36783e2011-05-08 20:32:23 +00002665 // We can always devirtualize calls on temporary object expressions.
2666 if (isa<CXXConstructExpr>(Base))
2667 return true;
Justin Bogner1cd11f12015-05-20 15:53:59 +00002668
Anders Carlssonc36783e2011-05-08 20:32:23 +00002669 // And calls on bound temporaries.
2670 if (isa<CXXBindTemporaryExpr>(Base))
2671 return true;
Justin Bogner1cd11f12015-05-20 15:53:59 +00002672
Anders Carlssonc36783e2011-05-08 20:32:23 +00002673 // Check if this is a call expr that returns a record type.
2674 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
David Majnemerced8bdf2015-02-25 17:36:15 +00002675 return CE->getCallReturnType(getContext())->isRecordType();
Anders Carlssonc36783e2011-05-08 20:32:23 +00002676
2677 // We can't devirtualize the call.
2678 return false;
2679}
2680
Faisal Vali571df122013-09-29 08:45:24 +00002681void CodeGenFunction::EmitForwardingCallToLambda(
2682 const CXXMethodDecl *callOperator,
2683 CallArgList &callArgs) {
Eli Friedman5b446882012-02-16 03:47:28 +00002684 // Get the address of the call operator.
John McCall8dda7b22012-07-07 06:41:13 +00002685 const CGFunctionInfo &calleeFnInfo =
2686 CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
2687 llvm::Value *callee =
2688 CGM.GetAddrOfFunction(GlobalDecl(callOperator),
2689 CGM.getTypes().GetFunctionType(calleeFnInfo));
Eli Friedman5b446882012-02-16 03:47:28 +00002690
John McCall8dda7b22012-07-07 06:41:13 +00002691 // Prepare the return slot.
2692 const FunctionProtoType *FPT =
2693 callOperator->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00002694 QualType resultType = FPT->getReturnType();
John McCall8dda7b22012-07-07 06:41:13 +00002695 ReturnValueSlot returnSlot;
2696 if (!resultType->isVoidType() &&
2697 calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
John McCall47fb9502013-03-07 21:37:08 +00002698 !hasScalarEvaluationKind(calleeFnInfo.getReturnType()))
John McCall8dda7b22012-07-07 06:41:13 +00002699 returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
2700
2701 // We don't need to separately arrange the call arguments because
2702 // the call can't be variadic anyway --- it's impossible to forward
2703 // variadic arguments.
Justin Bogner1cd11f12015-05-20 15:53:59 +00002704
Eli Friedman5b446882012-02-16 03:47:28 +00002705 // Now emit our call.
John McCall8dda7b22012-07-07 06:41:13 +00002706 RValue RV = EmitCall(calleeFnInfo, callee, returnSlot,
2707 callArgs, callOperator);
Eli Friedman5b446882012-02-16 03:47:28 +00002708
John McCall8dda7b22012-07-07 06:41:13 +00002709 // If necessary, copy the returned value into the slot.
2710 if (!resultType->isVoidType() && returnSlot.isNull())
2711 EmitReturnOfRValue(RV, resultType);
Eli Friedmanf5f4d2f2012-12-13 23:37:17 +00002712 else
2713 EmitBranchThroughCleanup(ReturnBlock);
Eli Friedman5b446882012-02-16 03:47:28 +00002714}
2715
Eli Friedman2495ab02012-02-25 02:48:22 +00002716void CodeGenFunction::EmitLambdaBlockInvokeBody() {
2717 const BlockDecl *BD = BlockInfo->getBlockDecl();
2718 const VarDecl *variable = BD->capture_begin()->getVariable();
2719 const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
2720
2721 // Start building arguments for forwarding call
2722 CallArgList CallArgs;
2723
2724 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
John McCall7f416cc2015-09-08 08:05:57 +00002725 Address ThisPtr = GetAddrOfBlockDecl(variable, false);
2726 CallArgs.add(RValue::get(ThisPtr.getPointer()), ThisType);
Eli Friedman2495ab02012-02-25 02:48:22 +00002727
2728 // Add the rest of the parameters.
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00002729 for (auto param : BD->params())
Nick Lewycky2d84e842013-10-02 02:29:49 +00002730 EmitDelegateCallArg(CallArgs, param, param->getLocStart());
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00002731
Justin Bogner1cd11f12015-05-20 15:53:59 +00002732 assert(!Lambda->isGenericLambda() &&
Faisal Vali571df122013-09-29 08:45:24 +00002733 "generic lambda interconversion to block not implemented");
2734 EmitForwardingCallToLambda(Lambda->getLambdaCallOperator(), CallArgs);
Eli Friedman2495ab02012-02-25 02:48:22 +00002735}
2736
2737void CodeGenFunction::EmitLambdaToBlockPointerBody(FunctionArgList &Args) {
John McCalldec348f72013-05-03 07:33:41 +00002738 if (cast<CXXMethodDecl>(CurCodeDecl)->isVariadic()) {
Eli Friedman2495ab02012-02-25 02:48:22 +00002739 // FIXME: Making this work correctly is nasty because it requires either
2740 // cloning the body of the call operator or making the call operator forward.
John McCalldec348f72013-05-03 07:33:41 +00002741 CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function");
Eli Friedman2495ab02012-02-25 02:48:22 +00002742 return;
2743 }
2744
Richard Smithb47c36f2013-11-05 09:12:18 +00002745 EmitFunctionBody(Args, cast<FunctionDecl>(CurGD.getDecl())->getBody());
Eli Friedman2495ab02012-02-25 02:48:22 +00002746}
2747
2748void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
2749 const CXXRecordDecl *Lambda = MD->getParent();
2750
2751 // Start building arguments for forwarding call
2752 CallArgList CallArgs;
2753
2754 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2755 llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
2756 CallArgs.add(RValue::get(ThisPtr), ThisType);
2757
2758 // Add the rest of the parameters.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002759 for (auto Param : MD->params())
2760 EmitDelegateCallArg(CallArgs, Param, Param->getLocStart());
2761
Faisal Vali571df122013-09-29 08:45:24 +00002762 const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
2763 // For a generic lambda, find the corresponding call operator specialization
2764 // to which the call to the static-invoker shall be forwarded.
2765 if (Lambda->isGenericLambda()) {
2766 assert(MD->isFunctionTemplateSpecialization());
2767 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
2768 FunctionTemplateDecl *CallOpTemplate = CallOp->getDescribedFunctionTemplate();
Craig Topper8a13c412014-05-21 05:09:00 +00002769 void *InsertPos = nullptr;
Justin Bogner1cd11f12015-05-20 15:53:59 +00002770 FunctionDecl *CorrespondingCallOpSpecialization =
Craig Topper7e0daca2014-06-26 04:58:53 +00002771 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
Faisal Vali571df122013-09-29 08:45:24 +00002772 assert(CorrespondingCallOpSpecialization);
2773 CallOp = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
2774 }
2775 EmitForwardingCallToLambda(CallOp, CallArgs);
Eli Friedman2495ab02012-02-25 02:48:22 +00002776}
2777
Douglas Gregor355efbb2012-02-17 03:02:34 +00002778void CodeGenFunction::EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD) {
2779 if (MD->isVariadic()) {
Eli Friedman5b446882012-02-16 03:47:28 +00002780 // FIXME: Making this work correctly is nasty because it requires either
2781 // cloning the body of the call operator or making the call operator forward.
2782 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
Eli Friedman2495ab02012-02-25 02:48:22 +00002783 return;
Eli Friedman5b446882012-02-16 03:47:28 +00002784 }
2785
Douglas Gregor355efbb2012-02-17 03:02:34 +00002786 EmitLambdaDelegatingInvokeBody(MD);
Eli Friedman5a6d5072012-02-16 01:37:33 +00002787}