xref: /openbsd-src/gnu/llvm/clang/lib/CodeGen/CGClass.cpp (revision 12c855180aad702bbcca06e0398d774beeafb155)
1e5dd7070Spatrick //===--- CGClass.cpp - Emit LLVM Code for C++ classes -----------*- C++ -*-===//
2e5dd7070Spatrick //
3e5dd7070Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e5dd7070Spatrick // See https://llvm.org/LICENSE.txt for license information.
5e5dd7070Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e5dd7070Spatrick //
7e5dd7070Spatrick //===----------------------------------------------------------------------===//
8e5dd7070Spatrick //
9e5dd7070Spatrick // This contains code dealing with C++ code generation of classes
10e5dd7070Spatrick //
11e5dd7070Spatrick //===----------------------------------------------------------------------===//
12e5dd7070Spatrick 
13e5dd7070Spatrick #include "CGBlocks.h"
14e5dd7070Spatrick #include "CGCXXABI.h"
15e5dd7070Spatrick #include "CGDebugInfo.h"
16e5dd7070Spatrick #include "CGRecordLayout.h"
17e5dd7070Spatrick #include "CodeGenFunction.h"
18e5dd7070Spatrick #include "TargetInfo.h"
19e5dd7070Spatrick #include "clang/AST/Attr.h"
20e5dd7070Spatrick #include "clang/AST/CXXInheritance.h"
21a9ac8606Spatrick #include "clang/AST/CharUnits.h"
22e5dd7070Spatrick #include "clang/AST/DeclTemplate.h"
23e5dd7070Spatrick #include "clang/AST/EvaluatedExprVisitor.h"
24e5dd7070Spatrick #include "clang/AST/RecordLayout.h"
25e5dd7070Spatrick #include "clang/AST/StmtCXX.h"
26e5dd7070Spatrick #include "clang/Basic/CodeGenOptions.h"
27e5dd7070Spatrick #include "clang/Basic/TargetBuiltins.h"
28e5dd7070Spatrick #include "clang/CodeGen/CGFunctionInfo.h"
29e5dd7070Spatrick #include "llvm/IR/Intrinsics.h"
30e5dd7070Spatrick #include "llvm/IR/Metadata.h"
31e5dd7070Spatrick #include "llvm/Transforms/Utils/SanitizerStats.h"
32*12c85518Srobert #include <optional>
33e5dd7070Spatrick 
34e5dd7070Spatrick using namespace clang;
35e5dd7070Spatrick using namespace CodeGen;
36e5dd7070Spatrick 
37e5dd7070Spatrick /// Return the best known alignment for an unknown pointer to a
38e5dd7070Spatrick /// particular class.
getClassPointerAlignment(const CXXRecordDecl * RD)39e5dd7070Spatrick CharUnits CodeGenModule::getClassPointerAlignment(const CXXRecordDecl *RD) {
40ec727ea7Spatrick   if (!RD->hasDefinition())
41e5dd7070Spatrick     return CharUnits::One(); // Hopefully won't be used anywhere.
42e5dd7070Spatrick 
43e5dd7070Spatrick   auto &layout = getContext().getASTRecordLayout(RD);
44e5dd7070Spatrick 
45e5dd7070Spatrick   // If the class is final, then we know that the pointer points to an
46e5dd7070Spatrick   // object of that type and can use the full alignment.
47ec727ea7Spatrick   if (RD->isEffectivelyFinal())
48e5dd7070Spatrick     return layout.getAlignment();
49e5dd7070Spatrick 
50e5dd7070Spatrick   // Otherwise, we have to assume it could be a subclass.
51e5dd7070Spatrick   return layout.getNonVirtualAlignment();
52e5dd7070Spatrick }
53ec727ea7Spatrick 
54ec727ea7Spatrick /// Return the smallest possible amount of storage that might be allocated
55ec727ea7Spatrick /// starting from the beginning of an object of a particular class.
56ec727ea7Spatrick ///
57ec727ea7Spatrick /// This may be smaller than sizeof(RD) if RD has virtual base classes.
getMinimumClassObjectSize(const CXXRecordDecl * RD)58ec727ea7Spatrick CharUnits CodeGenModule::getMinimumClassObjectSize(const CXXRecordDecl *RD) {
59ec727ea7Spatrick   if (!RD->hasDefinition())
60ec727ea7Spatrick     return CharUnits::One();
61ec727ea7Spatrick 
62ec727ea7Spatrick   auto &layout = getContext().getASTRecordLayout(RD);
63ec727ea7Spatrick 
64ec727ea7Spatrick   // If the class is final, then we know that the pointer points to an
65ec727ea7Spatrick   // object of that type and can use the full alignment.
66ec727ea7Spatrick   if (RD->isEffectivelyFinal())
67ec727ea7Spatrick     return layout.getSize();
68ec727ea7Spatrick 
69ec727ea7Spatrick   // Otherwise, we have to assume it could be a subclass.
70ec727ea7Spatrick   return std::max(layout.getNonVirtualSize(), CharUnits::One());
71e5dd7070Spatrick }
72e5dd7070Spatrick 
73e5dd7070Spatrick /// Return the best known alignment for a pointer to a virtual base,
74e5dd7070Spatrick /// given the alignment of a pointer to the derived class.
getVBaseAlignment(CharUnits actualDerivedAlign,const CXXRecordDecl * derivedClass,const CXXRecordDecl * vbaseClass)75e5dd7070Spatrick CharUnits CodeGenModule::getVBaseAlignment(CharUnits actualDerivedAlign,
76e5dd7070Spatrick                                            const CXXRecordDecl *derivedClass,
77e5dd7070Spatrick                                            const CXXRecordDecl *vbaseClass) {
78e5dd7070Spatrick   // The basic idea here is that an underaligned derived pointer might
79e5dd7070Spatrick   // indicate an underaligned base pointer.
80e5dd7070Spatrick 
81e5dd7070Spatrick   assert(vbaseClass->isCompleteDefinition());
82e5dd7070Spatrick   auto &baseLayout = getContext().getASTRecordLayout(vbaseClass);
83e5dd7070Spatrick   CharUnits expectedVBaseAlign = baseLayout.getNonVirtualAlignment();
84e5dd7070Spatrick 
85e5dd7070Spatrick   return getDynamicOffsetAlignment(actualDerivedAlign, derivedClass,
86e5dd7070Spatrick                                    expectedVBaseAlign);
87e5dd7070Spatrick }
88e5dd7070Spatrick 
89e5dd7070Spatrick CharUnits
getDynamicOffsetAlignment(CharUnits actualBaseAlign,const CXXRecordDecl * baseDecl,CharUnits expectedTargetAlign)90e5dd7070Spatrick CodeGenModule::getDynamicOffsetAlignment(CharUnits actualBaseAlign,
91e5dd7070Spatrick                                          const CXXRecordDecl *baseDecl,
92e5dd7070Spatrick                                          CharUnits expectedTargetAlign) {
93e5dd7070Spatrick   // If the base is an incomplete type (which is, alas, possible with
94e5dd7070Spatrick   // member pointers), be pessimistic.
95e5dd7070Spatrick   if (!baseDecl->isCompleteDefinition())
96e5dd7070Spatrick     return std::min(actualBaseAlign, expectedTargetAlign);
97e5dd7070Spatrick 
98e5dd7070Spatrick   auto &baseLayout = getContext().getASTRecordLayout(baseDecl);
99e5dd7070Spatrick   CharUnits expectedBaseAlign = baseLayout.getNonVirtualAlignment();
100e5dd7070Spatrick 
101e5dd7070Spatrick   // If the class is properly aligned, assume the target offset is, too.
102e5dd7070Spatrick   //
103e5dd7070Spatrick   // This actually isn't necessarily the right thing to do --- if the
104e5dd7070Spatrick   // class is a complete object, but it's only properly aligned for a
105e5dd7070Spatrick   // base subobject, then the alignments of things relative to it are
106e5dd7070Spatrick   // probably off as well.  (Note that this requires the alignment of
107e5dd7070Spatrick   // the target to be greater than the NV alignment of the derived
108e5dd7070Spatrick   // class.)
109e5dd7070Spatrick   //
110e5dd7070Spatrick   // However, our approach to this kind of under-alignment can only
111e5dd7070Spatrick   // ever be best effort; after all, we're never going to propagate
112e5dd7070Spatrick   // alignments through variables or parameters.  Note, in particular,
113e5dd7070Spatrick   // that constructing a polymorphic type in an address that's less
114e5dd7070Spatrick   // than pointer-aligned will generally trap in the constructor,
115e5dd7070Spatrick   // unless we someday add some sort of attribute to change the
116e5dd7070Spatrick   // assumed alignment of 'this'.  So our goal here is pretty much
117e5dd7070Spatrick   // just to allow the user to explicitly say that a pointer is
118e5dd7070Spatrick   // under-aligned and then safely access its fields and vtables.
119e5dd7070Spatrick   if (actualBaseAlign >= expectedBaseAlign) {
120e5dd7070Spatrick     return expectedTargetAlign;
121e5dd7070Spatrick   }
122e5dd7070Spatrick 
123e5dd7070Spatrick   // Otherwise, we might be offset by an arbitrary multiple of the
124e5dd7070Spatrick   // actual alignment.  The correct adjustment is to take the min of
125e5dd7070Spatrick   // the two alignments.
126e5dd7070Spatrick   return std::min(actualBaseAlign, expectedTargetAlign);
127e5dd7070Spatrick }
128e5dd7070Spatrick 
LoadCXXThisAddress()129e5dd7070Spatrick Address CodeGenFunction::LoadCXXThisAddress() {
130e5dd7070Spatrick   assert(CurFuncDecl && "loading 'this' without a func declaration?");
131*12c85518Srobert   auto *MD = cast<CXXMethodDecl>(CurFuncDecl);
132e5dd7070Spatrick 
133e5dd7070Spatrick   // Lazily compute CXXThisAlignment.
134e5dd7070Spatrick   if (CXXThisAlignment.isZero()) {
135e5dd7070Spatrick     // Just use the best known alignment for the parent.
136e5dd7070Spatrick     // TODO: if we're currently emitting a complete-object ctor/dtor,
137e5dd7070Spatrick     // we can always use the complete-object alignment.
138*12c85518Srobert     CXXThisAlignment = CGM.getClassPointerAlignment(MD->getParent());
139e5dd7070Spatrick   }
140e5dd7070Spatrick 
141*12c85518Srobert   llvm::Type *Ty = ConvertType(MD->getThisType()->getPointeeType());
142*12c85518Srobert   return Address(LoadCXXThis(), Ty, CXXThisAlignment);
143e5dd7070Spatrick }
144e5dd7070Spatrick 
145e5dd7070Spatrick /// Emit the address of a field using a member data pointer.
146e5dd7070Spatrick ///
147e5dd7070Spatrick /// \param E Only used for emergency diagnostics
148e5dd7070Spatrick Address
EmitCXXMemberDataPointerAddress(const Expr * E,Address base,llvm::Value * memberPtr,const MemberPointerType * memberPtrType,LValueBaseInfo * BaseInfo,TBAAAccessInfo * TBAAInfo)149e5dd7070Spatrick CodeGenFunction::EmitCXXMemberDataPointerAddress(const Expr *E, Address base,
150e5dd7070Spatrick                                                  llvm::Value *memberPtr,
151e5dd7070Spatrick                                       const MemberPointerType *memberPtrType,
152e5dd7070Spatrick                                                  LValueBaseInfo *BaseInfo,
153e5dd7070Spatrick                                                  TBAAAccessInfo *TBAAInfo) {
154e5dd7070Spatrick   // Ask the ABI to compute the actual address.
155e5dd7070Spatrick   llvm::Value *ptr =
156e5dd7070Spatrick     CGM.getCXXABI().EmitMemberDataPointerAddress(*this, E, base,
157e5dd7070Spatrick                                                  memberPtr, memberPtrType);
158e5dd7070Spatrick 
159e5dd7070Spatrick   QualType memberType = memberPtrType->getPointeeType();
160ec727ea7Spatrick   CharUnits memberAlign =
161ec727ea7Spatrick       CGM.getNaturalTypeAlignment(memberType, BaseInfo, TBAAInfo);
162e5dd7070Spatrick   memberAlign =
163e5dd7070Spatrick     CGM.getDynamicOffsetAlignment(base.getAlignment(),
164e5dd7070Spatrick                             memberPtrType->getClass()->getAsCXXRecordDecl(),
165e5dd7070Spatrick                                   memberAlign);
166*12c85518Srobert   return Address(ptr, ConvertTypeForMem(memberPtrType->getPointeeType()),
167*12c85518Srobert                  memberAlign);
168e5dd7070Spatrick }
169e5dd7070Spatrick 
computeNonVirtualBaseClassOffset(const CXXRecordDecl * DerivedClass,CastExpr::path_const_iterator Start,CastExpr::path_const_iterator End)170e5dd7070Spatrick CharUnits CodeGenModule::computeNonVirtualBaseClassOffset(
171e5dd7070Spatrick     const CXXRecordDecl *DerivedClass, CastExpr::path_const_iterator Start,
172e5dd7070Spatrick     CastExpr::path_const_iterator End) {
173e5dd7070Spatrick   CharUnits Offset = CharUnits::Zero();
174e5dd7070Spatrick 
175e5dd7070Spatrick   const ASTContext &Context = getContext();
176e5dd7070Spatrick   const CXXRecordDecl *RD = DerivedClass;
177e5dd7070Spatrick 
178e5dd7070Spatrick   for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
179e5dd7070Spatrick     const CXXBaseSpecifier *Base = *I;
180e5dd7070Spatrick     assert(!Base->isVirtual() && "Should not see virtual bases here!");
181e5dd7070Spatrick 
182e5dd7070Spatrick     // Get the layout.
183e5dd7070Spatrick     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
184e5dd7070Spatrick 
185e5dd7070Spatrick     const auto *BaseDecl =
186e5dd7070Spatrick         cast<CXXRecordDecl>(Base->getType()->castAs<RecordType>()->getDecl());
187e5dd7070Spatrick 
188e5dd7070Spatrick     // Add the offset.
189e5dd7070Spatrick     Offset += Layout.getBaseClassOffset(BaseDecl);
190e5dd7070Spatrick 
191e5dd7070Spatrick     RD = BaseDecl;
192e5dd7070Spatrick   }
193e5dd7070Spatrick 
194e5dd7070Spatrick   return Offset;
195e5dd7070Spatrick }
196e5dd7070Spatrick 
197e5dd7070Spatrick llvm::Constant *
GetNonVirtualBaseClassOffset(const CXXRecordDecl * ClassDecl,CastExpr::path_const_iterator PathBegin,CastExpr::path_const_iterator PathEnd)198e5dd7070Spatrick CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
199e5dd7070Spatrick                                    CastExpr::path_const_iterator PathBegin,
200e5dd7070Spatrick                                    CastExpr::path_const_iterator PathEnd) {
201e5dd7070Spatrick   assert(PathBegin != PathEnd && "Base path should not be empty!");
202e5dd7070Spatrick 
203e5dd7070Spatrick   CharUnits Offset =
204e5dd7070Spatrick       computeNonVirtualBaseClassOffset(ClassDecl, PathBegin, PathEnd);
205e5dd7070Spatrick   if (Offset.isZero())
206e5dd7070Spatrick     return nullptr;
207e5dd7070Spatrick 
208e5dd7070Spatrick   llvm::Type *PtrDiffTy =
209e5dd7070Spatrick   Types.ConvertType(getContext().getPointerDiffType());
210e5dd7070Spatrick 
211e5dd7070Spatrick   return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
212e5dd7070Spatrick }
213e5dd7070Spatrick 
214e5dd7070Spatrick /// Gets the address of a direct base class within a complete object.
215e5dd7070Spatrick /// This should only be used for (1) non-virtual bases or (2) virtual bases
216e5dd7070Spatrick /// when the type is known to be complete (e.g. in complete destructors).
217e5dd7070Spatrick ///
218e5dd7070Spatrick /// The object pointed to by 'This' is assumed to be non-null.
219e5dd7070Spatrick Address
GetAddressOfDirectBaseInCompleteClass(Address This,const CXXRecordDecl * Derived,const CXXRecordDecl * Base,bool BaseIsVirtual)220e5dd7070Spatrick CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(Address This,
221e5dd7070Spatrick                                                    const CXXRecordDecl *Derived,
222e5dd7070Spatrick                                                    const CXXRecordDecl *Base,
223e5dd7070Spatrick                                                    bool BaseIsVirtual) {
224e5dd7070Spatrick   // 'this' must be a pointer (in some address space) to Derived.
225e5dd7070Spatrick   assert(This.getElementType() == ConvertType(Derived));
226e5dd7070Spatrick 
227e5dd7070Spatrick   // Compute the offset of the virtual base.
228e5dd7070Spatrick   CharUnits Offset;
229e5dd7070Spatrick   const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
230e5dd7070Spatrick   if (BaseIsVirtual)
231e5dd7070Spatrick     Offset = Layout.getVBaseClassOffset(Base);
232e5dd7070Spatrick   else
233e5dd7070Spatrick     Offset = Layout.getBaseClassOffset(Base);
234e5dd7070Spatrick 
235e5dd7070Spatrick   // Shift and cast down to the base type.
236e5dd7070Spatrick   // TODO: for complete types, this should be possible with a GEP.
237e5dd7070Spatrick   Address V = This;
238e5dd7070Spatrick   if (!Offset.isZero()) {
239e5dd7070Spatrick     V = Builder.CreateElementBitCast(V, Int8Ty);
240e5dd7070Spatrick     V = Builder.CreateConstInBoundsByteGEP(V, Offset);
241e5dd7070Spatrick   }
242e5dd7070Spatrick   V = Builder.CreateElementBitCast(V, ConvertType(Base));
243e5dd7070Spatrick 
244e5dd7070Spatrick   return V;
245e5dd7070Spatrick }
246e5dd7070Spatrick 
247e5dd7070Spatrick static Address
ApplyNonVirtualAndVirtualOffset(CodeGenFunction & CGF,Address addr,CharUnits nonVirtualOffset,llvm::Value * virtualOffset,const CXXRecordDecl * derivedClass,const CXXRecordDecl * nearestVBase)248e5dd7070Spatrick ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, Address addr,
249e5dd7070Spatrick                                 CharUnits nonVirtualOffset,
250e5dd7070Spatrick                                 llvm::Value *virtualOffset,
251e5dd7070Spatrick                                 const CXXRecordDecl *derivedClass,
252e5dd7070Spatrick                                 const CXXRecordDecl *nearestVBase) {
253e5dd7070Spatrick   // Assert that we have something to do.
254e5dd7070Spatrick   assert(!nonVirtualOffset.isZero() || virtualOffset != nullptr);
255e5dd7070Spatrick 
256e5dd7070Spatrick   // Compute the offset from the static and dynamic components.
257e5dd7070Spatrick   llvm::Value *baseOffset;
258e5dd7070Spatrick   if (!nonVirtualOffset.isZero()) {
259ec727ea7Spatrick     llvm::Type *OffsetType =
260ec727ea7Spatrick         (CGF.CGM.getTarget().getCXXABI().isItaniumFamily() &&
261ec727ea7Spatrick          CGF.CGM.getItaniumVTableContext().isRelativeLayout())
262ec727ea7Spatrick             ? CGF.Int32Ty
263ec727ea7Spatrick             : CGF.PtrDiffTy;
264ec727ea7Spatrick     baseOffset =
265ec727ea7Spatrick         llvm::ConstantInt::get(OffsetType, nonVirtualOffset.getQuantity());
266e5dd7070Spatrick     if (virtualOffset) {
267e5dd7070Spatrick       baseOffset = CGF.Builder.CreateAdd(virtualOffset, baseOffset);
268e5dd7070Spatrick     }
269e5dd7070Spatrick   } else {
270e5dd7070Spatrick     baseOffset = virtualOffset;
271e5dd7070Spatrick   }
272e5dd7070Spatrick 
273e5dd7070Spatrick   // Apply the base offset.
274e5dd7070Spatrick   llvm::Value *ptr = addr.getPointer();
275e5dd7070Spatrick   unsigned AddrSpace = ptr->getType()->getPointerAddressSpace();
276e5dd7070Spatrick   ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8Ty->getPointerTo(AddrSpace));
277a9ac8606Spatrick   ptr = CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, ptr, baseOffset, "add.ptr");
278e5dd7070Spatrick 
279e5dd7070Spatrick   // If we have a virtual component, the alignment of the result will
280e5dd7070Spatrick   // be relative only to the known alignment of that vbase.
281e5dd7070Spatrick   CharUnits alignment;
282e5dd7070Spatrick   if (virtualOffset) {
283e5dd7070Spatrick     assert(nearestVBase && "virtual offset without vbase?");
284e5dd7070Spatrick     alignment = CGF.CGM.getVBaseAlignment(addr.getAlignment(),
285e5dd7070Spatrick                                           derivedClass, nearestVBase);
286e5dd7070Spatrick   } else {
287e5dd7070Spatrick     alignment = addr.getAlignment();
288e5dd7070Spatrick   }
289e5dd7070Spatrick   alignment = alignment.alignmentAtOffset(nonVirtualOffset);
290e5dd7070Spatrick 
291*12c85518Srobert   return Address(ptr, CGF.Int8Ty, alignment);
292e5dd7070Spatrick }
293e5dd7070Spatrick 
GetAddressOfBaseClass(Address Value,const CXXRecordDecl * Derived,CastExpr::path_const_iterator PathBegin,CastExpr::path_const_iterator PathEnd,bool NullCheckValue,SourceLocation Loc)294e5dd7070Spatrick Address CodeGenFunction::GetAddressOfBaseClass(
295e5dd7070Spatrick     Address Value, const CXXRecordDecl *Derived,
296e5dd7070Spatrick     CastExpr::path_const_iterator PathBegin,
297e5dd7070Spatrick     CastExpr::path_const_iterator PathEnd, bool NullCheckValue,
298e5dd7070Spatrick     SourceLocation Loc) {
299e5dd7070Spatrick   assert(PathBegin != PathEnd && "Base path should not be empty!");
300e5dd7070Spatrick 
301e5dd7070Spatrick   CastExpr::path_const_iterator Start = PathBegin;
302e5dd7070Spatrick   const CXXRecordDecl *VBase = nullptr;
303e5dd7070Spatrick 
304e5dd7070Spatrick   // Sema has done some convenient canonicalization here: if the
305e5dd7070Spatrick   // access path involved any virtual steps, the conversion path will
306e5dd7070Spatrick   // *start* with a step down to the correct virtual base subobject,
307e5dd7070Spatrick   // and hence will not require any further steps.
308e5dd7070Spatrick   if ((*Start)->isVirtual()) {
309e5dd7070Spatrick     VBase = cast<CXXRecordDecl>(
310e5dd7070Spatrick         (*Start)->getType()->castAs<RecordType>()->getDecl());
311e5dd7070Spatrick     ++Start;
312e5dd7070Spatrick   }
313e5dd7070Spatrick 
314e5dd7070Spatrick   // Compute the static offset of the ultimate destination within its
315e5dd7070Spatrick   // allocating subobject (the virtual base, if there is one, or else
316e5dd7070Spatrick   // the "complete" object that we see).
317e5dd7070Spatrick   CharUnits NonVirtualOffset = CGM.computeNonVirtualBaseClassOffset(
318e5dd7070Spatrick       VBase ? VBase : Derived, Start, PathEnd);
319e5dd7070Spatrick 
320e5dd7070Spatrick   // If there's a virtual step, we can sometimes "devirtualize" it.
321e5dd7070Spatrick   // For now, that's limited to when the derived type is final.
322e5dd7070Spatrick   // TODO: "devirtualize" this for accesses to known-complete objects.
323e5dd7070Spatrick   if (VBase && Derived->hasAttr<FinalAttr>()) {
324e5dd7070Spatrick     const ASTRecordLayout &layout = getContext().getASTRecordLayout(Derived);
325e5dd7070Spatrick     CharUnits vBaseOffset = layout.getVBaseClassOffset(VBase);
326e5dd7070Spatrick     NonVirtualOffset += vBaseOffset;
327e5dd7070Spatrick     VBase = nullptr; // we no longer have a virtual step
328e5dd7070Spatrick   }
329e5dd7070Spatrick 
330e5dd7070Spatrick   // Get the base pointer type.
331*12c85518Srobert   llvm::Type *BaseValueTy = ConvertType((PathEnd[-1])->getType());
332e5dd7070Spatrick   llvm::Type *BasePtrTy =
333*12c85518Srobert       BaseValueTy->getPointerTo(Value.getType()->getPointerAddressSpace());
334e5dd7070Spatrick 
335e5dd7070Spatrick   QualType DerivedTy = getContext().getRecordType(Derived);
336e5dd7070Spatrick   CharUnits DerivedAlign = CGM.getClassPointerAlignment(Derived);
337e5dd7070Spatrick 
338e5dd7070Spatrick   // If the static offset is zero and we don't have a virtual step,
339e5dd7070Spatrick   // just do a bitcast; null checks are unnecessary.
340e5dd7070Spatrick   if (NonVirtualOffset.isZero() && !VBase) {
341e5dd7070Spatrick     if (sanitizePerformTypeCheck()) {
342e5dd7070Spatrick       SanitizerSet SkippedChecks;
343e5dd7070Spatrick       SkippedChecks.set(SanitizerKind::Null, !NullCheckValue);
344e5dd7070Spatrick       EmitTypeCheck(TCK_Upcast, Loc, Value.getPointer(),
345e5dd7070Spatrick                     DerivedTy, DerivedAlign, SkippedChecks);
346e5dd7070Spatrick     }
347*12c85518Srobert     return Builder.CreateElementBitCast(Value, BaseValueTy);
348e5dd7070Spatrick   }
349e5dd7070Spatrick 
350e5dd7070Spatrick   llvm::BasicBlock *origBB = nullptr;
351e5dd7070Spatrick   llvm::BasicBlock *endBB = nullptr;
352e5dd7070Spatrick 
353e5dd7070Spatrick   // Skip over the offset (and the vtable load) if we're supposed to
354e5dd7070Spatrick   // null-check the pointer.
355e5dd7070Spatrick   if (NullCheckValue) {
356e5dd7070Spatrick     origBB = Builder.GetInsertBlock();
357e5dd7070Spatrick     llvm::BasicBlock *notNullBB = createBasicBlock("cast.notnull");
358e5dd7070Spatrick     endBB = createBasicBlock("cast.end");
359e5dd7070Spatrick 
360e5dd7070Spatrick     llvm::Value *isNull = Builder.CreateIsNull(Value.getPointer());
361e5dd7070Spatrick     Builder.CreateCondBr(isNull, endBB, notNullBB);
362e5dd7070Spatrick     EmitBlock(notNullBB);
363e5dd7070Spatrick   }
364e5dd7070Spatrick 
365e5dd7070Spatrick   if (sanitizePerformTypeCheck()) {
366e5dd7070Spatrick     SanitizerSet SkippedChecks;
367e5dd7070Spatrick     SkippedChecks.set(SanitizerKind::Null, true);
368e5dd7070Spatrick     EmitTypeCheck(VBase ? TCK_UpcastToVirtualBase : TCK_Upcast, Loc,
369e5dd7070Spatrick                   Value.getPointer(), DerivedTy, DerivedAlign, SkippedChecks);
370e5dd7070Spatrick   }
371e5dd7070Spatrick 
372e5dd7070Spatrick   // Compute the virtual offset.
373e5dd7070Spatrick   llvm::Value *VirtualOffset = nullptr;
374e5dd7070Spatrick   if (VBase) {
375e5dd7070Spatrick     VirtualOffset =
376e5dd7070Spatrick       CGM.getCXXABI().GetVirtualBaseClassOffset(*this, Value, Derived, VBase);
377e5dd7070Spatrick   }
378e5dd7070Spatrick 
379e5dd7070Spatrick   // Apply both offsets.
380e5dd7070Spatrick   Value = ApplyNonVirtualAndVirtualOffset(*this, Value, NonVirtualOffset,
381e5dd7070Spatrick                                           VirtualOffset, Derived, VBase);
382e5dd7070Spatrick 
383e5dd7070Spatrick   // Cast to the destination type.
384*12c85518Srobert   Value = Builder.CreateElementBitCast(Value, BaseValueTy);
385e5dd7070Spatrick 
386e5dd7070Spatrick   // Build a phi if we needed a null check.
387e5dd7070Spatrick   if (NullCheckValue) {
388e5dd7070Spatrick     llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
389e5dd7070Spatrick     Builder.CreateBr(endBB);
390e5dd7070Spatrick     EmitBlock(endBB);
391e5dd7070Spatrick 
392e5dd7070Spatrick     llvm::PHINode *PHI = Builder.CreatePHI(BasePtrTy, 2, "cast.result");
393e5dd7070Spatrick     PHI->addIncoming(Value.getPointer(), notNullBB);
394e5dd7070Spatrick     PHI->addIncoming(llvm::Constant::getNullValue(BasePtrTy), origBB);
395*12c85518Srobert     Value = Value.withPointer(PHI);
396e5dd7070Spatrick   }
397e5dd7070Spatrick 
398e5dd7070Spatrick   return Value;
399e5dd7070Spatrick }
400e5dd7070Spatrick 
401e5dd7070Spatrick Address
GetAddressOfDerivedClass(Address BaseAddr,const CXXRecordDecl * Derived,CastExpr::path_const_iterator PathBegin,CastExpr::path_const_iterator PathEnd,bool NullCheckValue)402e5dd7070Spatrick CodeGenFunction::GetAddressOfDerivedClass(Address BaseAddr,
403e5dd7070Spatrick                                           const CXXRecordDecl *Derived,
404e5dd7070Spatrick                                         CastExpr::path_const_iterator PathBegin,
405e5dd7070Spatrick                                           CastExpr::path_const_iterator PathEnd,
406e5dd7070Spatrick                                           bool NullCheckValue) {
407e5dd7070Spatrick   assert(PathBegin != PathEnd && "Base path should not be empty!");
408e5dd7070Spatrick 
409e5dd7070Spatrick   QualType DerivedTy =
410e5dd7070Spatrick     getContext().getCanonicalType(getContext().getTagDeclType(Derived));
411*12c85518Srobert   unsigned AddrSpace = BaseAddr.getAddressSpace();
412*12c85518Srobert   llvm::Type *DerivedValueTy = ConvertType(DerivedTy);
413*12c85518Srobert   llvm::Type *DerivedPtrTy = DerivedValueTy->getPointerTo(AddrSpace);
414e5dd7070Spatrick 
415e5dd7070Spatrick   llvm::Value *NonVirtualOffset =
416e5dd7070Spatrick     CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
417e5dd7070Spatrick 
418e5dd7070Spatrick   if (!NonVirtualOffset) {
419e5dd7070Spatrick     // No offset, we can just cast back.
420*12c85518Srobert     return Builder.CreateElementBitCast(BaseAddr, DerivedValueTy);
421e5dd7070Spatrick   }
422e5dd7070Spatrick 
423e5dd7070Spatrick   llvm::BasicBlock *CastNull = nullptr;
424e5dd7070Spatrick   llvm::BasicBlock *CastNotNull = nullptr;
425e5dd7070Spatrick   llvm::BasicBlock *CastEnd = nullptr;
426e5dd7070Spatrick 
427e5dd7070Spatrick   if (NullCheckValue) {
428e5dd7070Spatrick     CastNull = createBasicBlock("cast.null");
429e5dd7070Spatrick     CastNotNull = createBasicBlock("cast.notnull");
430e5dd7070Spatrick     CastEnd = createBasicBlock("cast.end");
431e5dd7070Spatrick 
432e5dd7070Spatrick     llvm::Value *IsNull = Builder.CreateIsNull(BaseAddr.getPointer());
433e5dd7070Spatrick     Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
434e5dd7070Spatrick     EmitBlock(CastNotNull);
435e5dd7070Spatrick   }
436e5dd7070Spatrick 
437e5dd7070Spatrick   // Apply the offset.
438e5dd7070Spatrick   llvm::Value *Value = Builder.CreateBitCast(BaseAddr.getPointer(), Int8PtrTy);
439a9ac8606Spatrick   Value = Builder.CreateInBoundsGEP(
440a9ac8606Spatrick       Int8Ty, Value, Builder.CreateNeg(NonVirtualOffset), "sub.ptr");
441e5dd7070Spatrick 
442e5dd7070Spatrick   // Just cast.
443e5dd7070Spatrick   Value = Builder.CreateBitCast(Value, DerivedPtrTy);
444e5dd7070Spatrick 
445e5dd7070Spatrick   // Produce a PHI if we had a null-check.
446e5dd7070Spatrick   if (NullCheckValue) {
447e5dd7070Spatrick     Builder.CreateBr(CastEnd);
448e5dd7070Spatrick     EmitBlock(CastNull);
449e5dd7070Spatrick     Builder.CreateBr(CastEnd);
450e5dd7070Spatrick     EmitBlock(CastEnd);
451e5dd7070Spatrick 
452e5dd7070Spatrick     llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
453e5dd7070Spatrick     PHI->addIncoming(Value, CastNotNull);
454e5dd7070Spatrick     PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
455e5dd7070Spatrick     Value = PHI;
456e5dd7070Spatrick   }
457e5dd7070Spatrick 
458*12c85518Srobert   return Address(Value, DerivedValueTy, CGM.getClassPointerAlignment(Derived));
459e5dd7070Spatrick }
460e5dd7070Spatrick 
GetVTTParameter(GlobalDecl GD,bool ForVirtualBase,bool Delegating)461e5dd7070Spatrick llvm::Value *CodeGenFunction::GetVTTParameter(GlobalDecl GD,
462e5dd7070Spatrick                                               bool ForVirtualBase,
463e5dd7070Spatrick                                               bool Delegating) {
464e5dd7070Spatrick   if (!CGM.getCXXABI().NeedsVTTParameter(GD)) {
465e5dd7070Spatrick     // This constructor/destructor does not need a VTT parameter.
466e5dd7070Spatrick     return nullptr;
467e5dd7070Spatrick   }
468e5dd7070Spatrick 
469e5dd7070Spatrick   const CXXRecordDecl *RD = cast<CXXMethodDecl>(CurCodeDecl)->getParent();
470e5dd7070Spatrick   const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
471e5dd7070Spatrick 
472e5dd7070Spatrick   uint64_t SubVTTIndex;
473e5dd7070Spatrick 
474e5dd7070Spatrick   if (Delegating) {
475e5dd7070Spatrick     // If this is a delegating constructor call, just load the VTT.
476e5dd7070Spatrick     return LoadCXXVTT();
477e5dd7070Spatrick   } else if (RD == Base) {
478e5dd7070Spatrick     // If the record matches the base, this is the complete ctor/dtor
479e5dd7070Spatrick     // variant calling the base variant in a class with virtual bases.
480e5dd7070Spatrick     assert(!CGM.getCXXABI().NeedsVTTParameter(CurGD) &&
481e5dd7070Spatrick            "doing no-op VTT offset in base dtor/ctor?");
482e5dd7070Spatrick     assert(!ForVirtualBase && "Can't have same class as virtual base!");
483e5dd7070Spatrick     SubVTTIndex = 0;
484e5dd7070Spatrick   } else {
485e5dd7070Spatrick     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
486e5dd7070Spatrick     CharUnits BaseOffset = ForVirtualBase ?
487e5dd7070Spatrick       Layout.getVBaseClassOffset(Base) :
488e5dd7070Spatrick       Layout.getBaseClassOffset(Base);
489e5dd7070Spatrick 
490e5dd7070Spatrick     SubVTTIndex =
491e5dd7070Spatrick       CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
492e5dd7070Spatrick     assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
493e5dd7070Spatrick   }
494e5dd7070Spatrick 
495e5dd7070Spatrick   if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
496e5dd7070Spatrick     // A VTT parameter was passed to the constructor, use it.
497a9ac8606Spatrick     llvm::Value *VTT = LoadCXXVTT();
498a9ac8606Spatrick     return Builder.CreateConstInBoundsGEP1_64(VoidPtrTy, VTT, SubVTTIndex);
499e5dd7070Spatrick   } else {
500e5dd7070Spatrick     // We're the complete constructor, so get the VTT by name.
501a9ac8606Spatrick     llvm::GlobalValue *VTT = CGM.getVTables().GetAddrOfVTT(RD);
502a9ac8606Spatrick     return Builder.CreateConstInBoundsGEP2_64(
503a9ac8606Spatrick         VTT->getValueType(), VTT, 0, SubVTTIndex);
504e5dd7070Spatrick   }
505e5dd7070Spatrick }
506e5dd7070Spatrick 
507e5dd7070Spatrick namespace {
508e5dd7070Spatrick   /// Call the destructor for a direct base class.
509e5dd7070Spatrick   struct CallBaseDtor final : EHScopeStack::Cleanup {
510e5dd7070Spatrick     const CXXRecordDecl *BaseClass;
511e5dd7070Spatrick     bool BaseIsVirtual;
CallBaseDtor__anonda710d950111::CallBaseDtor512e5dd7070Spatrick     CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
513e5dd7070Spatrick       : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
514e5dd7070Spatrick 
Emit__anonda710d950111::CallBaseDtor515e5dd7070Spatrick     void Emit(CodeGenFunction &CGF, Flags flags) override {
516e5dd7070Spatrick       const CXXRecordDecl *DerivedClass =
517e5dd7070Spatrick         cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
518e5dd7070Spatrick 
519e5dd7070Spatrick       const CXXDestructorDecl *D = BaseClass->getDestructor();
520e5dd7070Spatrick       // We are already inside a destructor, so presumably the object being
521e5dd7070Spatrick       // destroyed should have the expected type.
522e5dd7070Spatrick       QualType ThisTy = D->getThisObjectType();
523e5dd7070Spatrick       Address Addr =
524e5dd7070Spatrick         CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThisAddress(),
525e5dd7070Spatrick                                                   DerivedClass, BaseClass,
526e5dd7070Spatrick                                                   BaseIsVirtual);
527e5dd7070Spatrick       CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual,
528e5dd7070Spatrick                                 /*Delegating=*/false, Addr, ThisTy);
529e5dd7070Spatrick     }
530e5dd7070Spatrick   };
531e5dd7070Spatrick 
532e5dd7070Spatrick   /// A visitor which checks whether an initializer uses 'this' in a
533e5dd7070Spatrick   /// way which requires the vtable to be properly set.
534e5dd7070Spatrick   struct DynamicThisUseChecker : ConstEvaluatedExprVisitor<DynamicThisUseChecker> {
535e5dd7070Spatrick     typedef ConstEvaluatedExprVisitor<DynamicThisUseChecker> super;
536e5dd7070Spatrick 
537e5dd7070Spatrick     bool UsesThis;
538e5dd7070Spatrick 
DynamicThisUseChecker__anonda710d950111::DynamicThisUseChecker539e5dd7070Spatrick     DynamicThisUseChecker(const ASTContext &C) : super(C), UsesThis(false) {}
540e5dd7070Spatrick 
541e5dd7070Spatrick     // Black-list all explicit and implicit references to 'this'.
542e5dd7070Spatrick     //
543e5dd7070Spatrick     // Do we need to worry about external references to 'this' derived
544e5dd7070Spatrick     // from arbitrary code?  If so, then anything which runs arbitrary
545e5dd7070Spatrick     // external code might potentially access the vtable.
VisitCXXThisExpr__anonda710d950111::DynamicThisUseChecker546e5dd7070Spatrick     void VisitCXXThisExpr(const CXXThisExpr *E) { UsesThis = true; }
547e5dd7070Spatrick   };
548e5dd7070Spatrick } // end anonymous namespace
549e5dd7070Spatrick 
BaseInitializerUsesThis(ASTContext & C,const Expr * Init)550e5dd7070Spatrick static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
551e5dd7070Spatrick   DynamicThisUseChecker Checker(C);
552e5dd7070Spatrick   Checker.Visit(Init);
553e5dd7070Spatrick   return Checker.UsesThis;
554e5dd7070Spatrick }
555e5dd7070Spatrick 
EmitBaseInitializer(CodeGenFunction & CGF,const CXXRecordDecl * ClassDecl,CXXCtorInitializer * BaseInit)556e5dd7070Spatrick static void EmitBaseInitializer(CodeGenFunction &CGF,
557e5dd7070Spatrick                                 const CXXRecordDecl *ClassDecl,
558e5dd7070Spatrick                                 CXXCtorInitializer *BaseInit) {
559e5dd7070Spatrick   assert(BaseInit->isBaseInitializer() &&
560e5dd7070Spatrick          "Must have base initializer!");
561e5dd7070Spatrick 
562e5dd7070Spatrick   Address ThisPtr = CGF.LoadCXXThisAddress();
563e5dd7070Spatrick 
564e5dd7070Spatrick   const Type *BaseType = BaseInit->getBaseClass();
565e5dd7070Spatrick   const auto *BaseClassDecl =
566e5dd7070Spatrick       cast<CXXRecordDecl>(BaseType->castAs<RecordType>()->getDecl());
567e5dd7070Spatrick 
568e5dd7070Spatrick   bool isBaseVirtual = BaseInit->isBaseVirtual();
569e5dd7070Spatrick 
570e5dd7070Spatrick   // If the initializer for the base (other than the constructor
571e5dd7070Spatrick   // itself) accesses 'this' in any way, we need to initialize the
572e5dd7070Spatrick   // vtables.
573e5dd7070Spatrick   if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
574e5dd7070Spatrick     CGF.InitializeVTablePointers(ClassDecl);
575e5dd7070Spatrick 
576e5dd7070Spatrick   // We can pretend to be a complete class because it only matters for
577e5dd7070Spatrick   // virtual bases, and we only do virtual bases for complete ctors.
578e5dd7070Spatrick   Address V =
579e5dd7070Spatrick     CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
580e5dd7070Spatrick                                               BaseClassDecl,
581e5dd7070Spatrick                                               isBaseVirtual);
582e5dd7070Spatrick   AggValueSlot AggSlot =
583e5dd7070Spatrick       AggValueSlot::forAddr(
584e5dd7070Spatrick           V, Qualifiers(),
585e5dd7070Spatrick           AggValueSlot::IsDestructed,
586e5dd7070Spatrick           AggValueSlot::DoesNotNeedGCBarriers,
587e5dd7070Spatrick           AggValueSlot::IsNotAliased,
588e5dd7070Spatrick           CGF.getOverlapForBaseInit(ClassDecl, BaseClassDecl, isBaseVirtual));
589e5dd7070Spatrick 
590e5dd7070Spatrick   CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
591e5dd7070Spatrick 
592e5dd7070Spatrick   if (CGF.CGM.getLangOpts().Exceptions &&
593e5dd7070Spatrick       !BaseClassDecl->hasTrivialDestructor())
594e5dd7070Spatrick     CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
595e5dd7070Spatrick                                           isBaseVirtual);
596e5dd7070Spatrick }
597e5dd7070Spatrick 
isMemcpyEquivalentSpecialMember(const CXXMethodDecl * D)598e5dd7070Spatrick static bool isMemcpyEquivalentSpecialMember(const CXXMethodDecl *D) {
599e5dd7070Spatrick   auto *CD = dyn_cast<CXXConstructorDecl>(D);
600e5dd7070Spatrick   if (!(CD && CD->isCopyOrMoveConstructor()) &&
601e5dd7070Spatrick       !D->isCopyAssignmentOperator() && !D->isMoveAssignmentOperator())
602e5dd7070Spatrick     return false;
603e5dd7070Spatrick 
604e5dd7070Spatrick   // We can emit a memcpy for a trivial copy or move constructor/assignment.
605e5dd7070Spatrick   if (D->isTrivial() && !D->getParent()->mayInsertExtraPadding())
606e5dd7070Spatrick     return true;
607e5dd7070Spatrick 
608e5dd7070Spatrick   // We *must* emit a memcpy for a defaulted union copy or move op.
609e5dd7070Spatrick   if (D->getParent()->isUnion() && D->isDefaulted())
610e5dd7070Spatrick     return true;
611e5dd7070Spatrick 
612e5dd7070Spatrick   return false;
613e5dd7070Spatrick }
614e5dd7070Spatrick 
EmitLValueForAnyFieldInitialization(CodeGenFunction & CGF,CXXCtorInitializer * MemberInit,LValue & LHS)615e5dd7070Spatrick static void EmitLValueForAnyFieldInitialization(CodeGenFunction &CGF,
616e5dd7070Spatrick                                                 CXXCtorInitializer *MemberInit,
617e5dd7070Spatrick                                                 LValue &LHS) {
618e5dd7070Spatrick   FieldDecl *Field = MemberInit->getAnyMember();
619e5dd7070Spatrick   if (MemberInit->isIndirectMemberInitializer()) {
620e5dd7070Spatrick     // If we are initializing an anonymous union field, drill down to the field.
621e5dd7070Spatrick     IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember();
622e5dd7070Spatrick     for (const auto *I : IndirectField->chain())
623e5dd7070Spatrick       LHS = CGF.EmitLValueForFieldInitialization(LHS, cast<FieldDecl>(I));
624e5dd7070Spatrick   } else {
625e5dd7070Spatrick     LHS = CGF.EmitLValueForFieldInitialization(LHS, Field);
626e5dd7070Spatrick   }
627e5dd7070Spatrick }
628e5dd7070Spatrick 
EmitMemberInitializer(CodeGenFunction & CGF,const CXXRecordDecl * ClassDecl,CXXCtorInitializer * MemberInit,const CXXConstructorDecl * Constructor,FunctionArgList & Args)629e5dd7070Spatrick static void EmitMemberInitializer(CodeGenFunction &CGF,
630e5dd7070Spatrick                                   const CXXRecordDecl *ClassDecl,
631e5dd7070Spatrick                                   CXXCtorInitializer *MemberInit,
632e5dd7070Spatrick                                   const CXXConstructorDecl *Constructor,
633e5dd7070Spatrick                                   FunctionArgList &Args) {
634e5dd7070Spatrick   ApplyDebugLocation Loc(CGF, MemberInit->getSourceLocation());
635e5dd7070Spatrick   assert(MemberInit->isAnyMemberInitializer() &&
636e5dd7070Spatrick          "Must have member initializer!");
637e5dd7070Spatrick   assert(MemberInit->getInit() && "Must have initializer!");
638e5dd7070Spatrick 
639e5dd7070Spatrick   // non-static data member initializers.
640e5dd7070Spatrick   FieldDecl *Field = MemberInit->getAnyMember();
641e5dd7070Spatrick   QualType FieldType = Field->getType();
642e5dd7070Spatrick 
643e5dd7070Spatrick   llvm::Value *ThisPtr = CGF.LoadCXXThis();
644e5dd7070Spatrick   QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
645e5dd7070Spatrick   LValue LHS;
646e5dd7070Spatrick 
647e5dd7070Spatrick   // If a base constructor is being emitted, create an LValue that has the
648e5dd7070Spatrick   // non-virtual alignment.
649e5dd7070Spatrick   if (CGF.CurGD.getCtorType() == Ctor_Base)
650e5dd7070Spatrick     LHS = CGF.MakeNaturalAlignPointeeAddrLValue(ThisPtr, RecordTy);
651e5dd7070Spatrick   else
652e5dd7070Spatrick     LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
653e5dd7070Spatrick 
654e5dd7070Spatrick   EmitLValueForAnyFieldInitialization(CGF, MemberInit, LHS);
655e5dd7070Spatrick 
656e5dd7070Spatrick   // Special case: if we are in a copy or move constructor, and we are copying
657e5dd7070Spatrick   // an array of PODs or classes with trivial copy constructors, ignore the
658e5dd7070Spatrick   // AST and perform the copy we know is equivalent.
659e5dd7070Spatrick   // FIXME: This is hacky at best... if we had a bit more explicit information
660e5dd7070Spatrick   // in the AST, we could generalize it more easily.
661e5dd7070Spatrick   const ConstantArrayType *Array
662e5dd7070Spatrick     = CGF.getContext().getAsConstantArrayType(FieldType);
663e5dd7070Spatrick   if (Array && Constructor->isDefaulted() &&
664e5dd7070Spatrick       Constructor->isCopyOrMoveConstructor()) {
665e5dd7070Spatrick     QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
666e5dd7070Spatrick     CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
667e5dd7070Spatrick     if (BaseElementTy.isPODType(CGF.getContext()) ||
668e5dd7070Spatrick         (CE && isMemcpyEquivalentSpecialMember(CE->getConstructor()))) {
669e5dd7070Spatrick       unsigned SrcArgIndex =
670e5dd7070Spatrick           CGF.CGM.getCXXABI().getSrcArgforCopyCtor(Constructor, Args);
671e5dd7070Spatrick       llvm::Value *SrcPtr
672e5dd7070Spatrick         = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
673e5dd7070Spatrick       LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
674e5dd7070Spatrick       LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field);
675e5dd7070Spatrick 
676e5dd7070Spatrick       // Copy the aggregate.
677e5dd7070Spatrick       CGF.EmitAggregateCopy(LHS, Src, FieldType, CGF.getOverlapForFieldInit(Field),
678e5dd7070Spatrick                             LHS.isVolatileQualified());
679e5dd7070Spatrick       // Ensure that we destroy the objects if an exception is thrown later in
680e5dd7070Spatrick       // the constructor.
681e5dd7070Spatrick       QualType::DestructionKind dtorKind = FieldType.isDestructedType();
682e5dd7070Spatrick       if (CGF.needsEHCleanup(dtorKind))
683e5dd7070Spatrick         CGF.pushEHDestroy(dtorKind, LHS.getAddress(CGF), FieldType);
684e5dd7070Spatrick       return;
685e5dd7070Spatrick     }
686e5dd7070Spatrick   }
687e5dd7070Spatrick 
688e5dd7070Spatrick   CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit());
689e5dd7070Spatrick }
690e5dd7070Spatrick 
EmitInitializerForField(FieldDecl * Field,LValue LHS,Expr * Init)691e5dd7070Spatrick void CodeGenFunction::EmitInitializerForField(FieldDecl *Field, LValue LHS,
692e5dd7070Spatrick                                               Expr *Init) {
693e5dd7070Spatrick   QualType FieldType = Field->getType();
694e5dd7070Spatrick   switch (getEvaluationKind(FieldType)) {
695e5dd7070Spatrick   case TEK_Scalar:
696e5dd7070Spatrick     if (LHS.isSimple()) {
697e5dd7070Spatrick       EmitExprAsInit(Init, Field, LHS, false);
698e5dd7070Spatrick     } else {
699e5dd7070Spatrick       RValue RHS = RValue::get(EmitScalarExpr(Init));
700e5dd7070Spatrick       EmitStoreThroughLValue(RHS, LHS);
701e5dd7070Spatrick     }
702e5dd7070Spatrick     break;
703e5dd7070Spatrick   case TEK_Complex:
704e5dd7070Spatrick     EmitComplexExprIntoLValue(Init, LHS, /*isInit*/ true);
705e5dd7070Spatrick     break;
706e5dd7070Spatrick   case TEK_Aggregate: {
707e5dd7070Spatrick     AggValueSlot Slot = AggValueSlot::forLValue(
708e5dd7070Spatrick         LHS, *this, AggValueSlot::IsDestructed,
709e5dd7070Spatrick         AggValueSlot::DoesNotNeedGCBarriers, AggValueSlot::IsNotAliased,
710e5dd7070Spatrick         getOverlapForFieldInit(Field), AggValueSlot::IsNotZeroed,
711e5dd7070Spatrick         // Checks are made by the code that calls constructor.
712e5dd7070Spatrick         AggValueSlot::IsSanitizerChecked);
713e5dd7070Spatrick     EmitAggExpr(Init, Slot);
714e5dd7070Spatrick     break;
715e5dd7070Spatrick   }
716e5dd7070Spatrick   }
717e5dd7070Spatrick 
718e5dd7070Spatrick   // Ensure that we destroy this object if an exception is thrown
719e5dd7070Spatrick   // later in the constructor.
720e5dd7070Spatrick   QualType::DestructionKind dtorKind = FieldType.isDestructedType();
721e5dd7070Spatrick   if (needsEHCleanup(dtorKind))
722e5dd7070Spatrick     pushEHDestroy(dtorKind, LHS.getAddress(*this), FieldType);
723e5dd7070Spatrick }
724e5dd7070Spatrick 
725e5dd7070Spatrick /// Checks whether the given constructor is a valid subject for the
726e5dd7070Spatrick /// complete-to-base constructor delegation optimization, i.e.
727e5dd7070Spatrick /// emitting the complete constructor as a simple call to the base
728e5dd7070Spatrick /// constructor.
IsConstructorDelegationValid(const CXXConstructorDecl * Ctor)729e5dd7070Spatrick bool CodeGenFunction::IsConstructorDelegationValid(
730e5dd7070Spatrick     const CXXConstructorDecl *Ctor) {
731e5dd7070Spatrick 
732e5dd7070Spatrick   // Currently we disable the optimization for classes with virtual
733e5dd7070Spatrick   // bases because (1) the addresses of parameter variables need to be
734e5dd7070Spatrick   // consistent across all initializers but (2) the delegate function
735e5dd7070Spatrick   // call necessarily creates a second copy of the parameter variable.
736e5dd7070Spatrick   //
737e5dd7070Spatrick   // The limiting example (purely theoretical AFAIK):
738e5dd7070Spatrick   //   struct A { A(int &c) { c++; } };
739e5dd7070Spatrick   //   struct B : virtual A {
740e5dd7070Spatrick   //     B(int count) : A(count) { printf("%d\n", count); }
741e5dd7070Spatrick   //   };
742e5dd7070Spatrick   // ...although even this example could in principle be emitted as a
743e5dd7070Spatrick   // delegation since the address of the parameter doesn't escape.
744e5dd7070Spatrick   if (Ctor->getParent()->getNumVBases()) {
745e5dd7070Spatrick     // TODO: white-list trivial vbase initializers.  This case wouldn't
746e5dd7070Spatrick     // be subject to the restrictions below.
747e5dd7070Spatrick 
748e5dd7070Spatrick     // TODO: white-list cases where:
749e5dd7070Spatrick     //  - there are no non-reference parameters to the constructor
750e5dd7070Spatrick     //  - the initializers don't access any non-reference parameters
751e5dd7070Spatrick     //  - the initializers don't take the address of non-reference
752e5dd7070Spatrick     //    parameters
753e5dd7070Spatrick     //  - etc.
754e5dd7070Spatrick     // If we ever add any of the above cases, remember that:
755ec727ea7Spatrick     //  - function-try-blocks will always exclude this optimization
756e5dd7070Spatrick     //  - we need to perform the constructor prologue and cleanup in
757e5dd7070Spatrick     //    EmitConstructorBody.
758e5dd7070Spatrick 
759e5dd7070Spatrick     return false;
760e5dd7070Spatrick   }
761e5dd7070Spatrick 
762e5dd7070Spatrick   // We also disable the optimization for variadic functions because
763e5dd7070Spatrick   // it's impossible to "re-pass" varargs.
764e5dd7070Spatrick   if (Ctor->getType()->castAs<FunctionProtoType>()->isVariadic())
765e5dd7070Spatrick     return false;
766e5dd7070Spatrick 
767e5dd7070Spatrick   // FIXME: Decide if we can do a delegation of a delegating constructor.
768e5dd7070Spatrick   if (Ctor->isDelegatingConstructor())
769e5dd7070Spatrick     return false;
770e5dd7070Spatrick 
771e5dd7070Spatrick   return true;
772e5dd7070Spatrick }
773e5dd7070Spatrick 
774e5dd7070Spatrick // Emit code in ctor (Prologue==true) or dtor (Prologue==false)
775e5dd7070Spatrick // to poison the extra field paddings inserted under
776e5dd7070Spatrick // -fsanitize-address-field-padding=1|2.
EmitAsanPrologueOrEpilogue(bool Prologue)777e5dd7070Spatrick void CodeGenFunction::EmitAsanPrologueOrEpilogue(bool Prologue) {
778e5dd7070Spatrick   ASTContext &Context = getContext();
779e5dd7070Spatrick   const CXXRecordDecl *ClassDecl =
780e5dd7070Spatrick       Prologue ? cast<CXXConstructorDecl>(CurGD.getDecl())->getParent()
781e5dd7070Spatrick                : cast<CXXDestructorDecl>(CurGD.getDecl())->getParent();
782e5dd7070Spatrick   if (!ClassDecl->mayInsertExtraPadding()) return;
783e5dd7070Spatrick 
784e5dd7070Spatrick   struct SizeAndOffset {
785e5dd7070Spatrick     uint64_t Size;
786e5dd7070Spatrick     uint64_t Offset;
787e5dd7070Spatrick   };
788e5dd7070Spatrick 
789e5dd7070Spatrick   unsigned PtrSize = CGM.getDataLayout().getPointerSizeInBits();
790e5dd7070Spatrick   const ASTRecordLayout &Info = Context.getASTRecordLayout(ClassDecl);
791e5dd7070Spatrick 
792e5dd7070Spatrick   // Populate sizes and offsets of fields.
793e5dd7070Spatrick   SmallVector<SizeAndOffset, 16> SSV(Info.getFieldCount());
794e5dd7070Spatrick   for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i)
795e5dd7070Spatrick     SSV[i].Offset =
796e5dd7070Spatrick         Context.toCharUnitsFromBits(Info.getFieldOffset(i)).getQuantity();
797e5dd7070Spatrick 
798e5dd7070Spatrick   size_t NumFields = 0;
799e5dd7070Spatrick   for (const auto *Field : ClassDecl->fields()) {
800e5dd7070Spatrick     const FieldDecl *D = Field;
801a9ac8606Spatrick     auto FieldInfo = Context.getTypeInfoInChars(D->getType());
802a9ac8606Spatrick     CharUnits FieldSize = FieldInfo.Width;
803e5dd7070Spatrick     assert(NumFields < SSV.size());
804e5dd7070Spatrick     SSV[NumFields].Size = D->isBitField() ? 0 : FieldSize.getQuantity();
805e5dd7070Spatrick     NumFields++;
806e5dd7070Spatrick   }
807e5dd7070Spatrick   assert(NumFields == SSV.size());
808e5dd7070Spatrick   if (SSV.size() <= 1) return;
809e5dd7070Spatrick 
810e5dd7070Spatrick   // We will insert calls to __asan_* run-time functions.
811e5dd7070Spatrick   // LLVM AddressSanitizer pass may decide to inline them later.
812e5dd7070Spatrick   llvm::Type *Args[2] = {IntPtrTy, IntPtrTy};
813e5dd7070Spatrick   llvm::FunctionType *FTy =
814e5dd7070Spatrick       llvm::FunctionType::get(CGM.VoidTy, Args, false);
815e5dd7070Spatrick   llvm::FunctionCallee F = CGM.CreateRuntimeFunction(
816e5dd7070Spatrick       FTy, Prologue ? "__asan_poison_intra_object_redzone"
817e5dd7070Spatrick                     : "__asan_unpoison_intra_object_redzone");
818e5dd7070Spatrick 
819e5dd7070Spatrick   llvm::Value *ThisPtr = LoadCXXThis();
820e5dd7070Spatrick   ThisPtr = Builder.CreatePtrToInt(ThisPtr, IntPtrTy);
821e5dd7070Spatrick   uint64_t TypeSize = Info.getNonVirtualSize().getQuantity();
822e5dd7070Spatrick   // For each field check if it has sufficient padding,
823e5dd7070Spatrick   // if so (un)poison it with a call.
824e5dd7070Spatrick   for (size_t i = 0; i < SSV.size(); i++) {
825e5dd7070Spatrick     uint64_t AsanAlignment = 8;
826e5dd7070Spatrick     uint64_t NextField = i == SSV.size() - 1 ? TypeSize : SSV[i + 1].Offset;
827e5dd7070Spatrick     uint64_t PoisonSize = NextField - SSV[i].Offset - SSV[i].Size;
828e5dd7070Spatrick     uint64_t EndOffset = SSV[i].Offset + SSV[i].Size;
829e5dd7070Spatrick     if (PoisonSize < AsanAlignment || !SSV[i].Size ||
830e5dd7070Spatrick         (NextField % AsanAlignment) != 0)
831e5dd7070Spatrick       continue;
832e5dd7070Spatrick     Builder.CreateCall(
833e5dd7070Spatrick         F, {Builder.CreateAdd(ThisPtr, Builder.getIntN(PtrSize, EndOffset)),
834e5dd7070Spatrick             Builder.getIntN(PtrSize, PoisonSize)});
835e5dd7070Spatrick   }
836e5dd7070Spatrick }
837e5dd7070Spatrick 
838e5dd7070Spatrick /// EmitConstructorBody - Emits the body of the current constructor.
EmitConstructorBody(FunctionArgList & Args)839e5dd7070Spatrick void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
840e5dd7070Spatrick   EmitAsanPrologueOrEpilogue(true);
841e5dd7070Spatrick   const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
842e5dd7070Spatrick   CXXCtorType CtorType = CurGD.getCtorType();
843e5dd7070Spatrick 
844e5dd7070Spatrick   assert((CGM.getTarget().getCXXABI().hasConstructorVariants() ||
845e5dd7070Spatrick           CtorType == Ctor_Complete) &&
846e5dd7070Spatrick          "can only generate complete ctor for this ABI");
847e5dd7070Spatrick 
848e5dd7070Spatrick   // Before we go any further, try the complete->base constructor
849e5dd7070Spatrick   // delegation optimization.
850e5dd7070Spatrick   if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
851e5dd7070Spatrick       CGM.getTarget().getCXXABI().hasConstructorVariants()) {
852e5dd7070Spatrick     EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args, Ctor->getEndLoc());
853e5dd7070Spatrick     return;
854e5dd7070Spatrick   }
855e5dd7070Spatrick 
856e5dd7070Spatrick   const FunctionDecl *Definition = nullptr;
857e5dd7070Spatrick   Stmt *Body = Ctor->getBody(Definition);
858e5dd7070Spatrick   assert(Definition == Ctor && "emitting wrong constructor body");
859e5dd7070Spatrick 
860e5dd7070Spatrick   // Enter the function-try-block before the constructor prologue if
861e5dd7070Spatrick   // applicable.
862e5dd7070Spatrick   bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
863e5dd7070Spatrick   if (IsTryBody)
864e5dd7070Spatrick     EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
865e5dd7070Spatrick 
866e5dd7070Spatrick   incrementProfileCounter(Body);
867e5dd7070Spatrick 
868e5dd7070Spatrick   RunCleanupsScope RunCleanups(*this);
869e5dd7070Spatrick 
870e5dd7070Spatrick   // TODO: in restricted cases, we can emit the vbase initializers of
871e5dd7070Spatrick   // a complete ctor and then delegate to the base ctor.
872e5dd7070Spatrick 
873e5dd7070Spatrick   // Emit the constructor prologue, i.e. the base and member
874e5dd7070Spatrick   // initializers.
875e5dd7070Spatrick   EmitCtorPrologue(Ctor, CtorType, Args);
876e5dd7070Spatrick 
877e5dd7070Spatrick   // Emit the body of the statement.
878e5dd7070Spatrick   if (IsTryBody)
879e5dd7070Spatrick     EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
880e5dd7070Spatrick   else if (Body)
881e5dd7070Spatrick     EmitStmt(Body);
882e5dd7070Spatrick 
883e5dd7070Spatrick   // Emit any cleanup blocks associated with the member or base
884e5dd7070Spatrick   // initializers, which includes (along the exceptional path) the
885e5dd7070Spatrick   // destructors for those members and bases that were fully
886e5dd7070Spatrick   // constructed.
887e5dd7070Spatrick   RunCleanups.ForceCleanup();
888e5dd7070Spatrick 
889e5dd7070Spatrick   if (IsTryBody)
890e5dd7070Spatrick     ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
891e5dd7070Spatrick }
892e5dd7070Spatrick 
893e5dd7070Spatrick namespace {
894e5dd7070Spatrick   /// RAII object to indicate that codegen is copying the value representation
895e5dd7070Spatrick   /// instead of the object representation. Useful when copying a struct or
896e5dd7070Spatrick   /// class which has uninitialized members and we're only performing
897e5dd7070Spatrick   /// lvalue-to-rvalue conversion on the object but not its members.
898e5dd7070Spatrick   class CopyingValueRepresentation {
899e5dd7070Spatrick   public:
CopyingValueRepresentation(CodeGenFunction & CGF)900e5dd7070Spatrick     explicit CopyingValueRepresentation(CodeGenFunction &CGF)
901e5dd7070Spatrick         : CGF(CGF), OldSanOpts(CGF.SanOpts) {
902e5dd7070Spatrick       CGF.SanOpts.set(SanitizerKind::Bool, false);
903e5dd7070Spatrick       CGF.SanOpts.set(SanitizerKind::Enum, false);
904e5dd7070Spatrick     }
~CopyingValueRepresentation()905e5dd7070Spatrick     ~CopyingValueRepresentation() {
906e5dd7070Spatrick       CGF.SanOpts = OldSanOpts;
907e5dd7070Spatrick     }
908e5dd7070Spatrick   private:
909e5dd7070Spatrick     CodeGenFunction &CGF;
910e5dd7070Spatrick     SanitizerSet OldSanOpts;
911e5dd7070Spatrick   };
912e5dd7070Spatrick } // end anonymous namespace
913e5dd7070Spatrick 
914e5dd7070Spatrick namespace {
915e5dd7070Spatrick   class FieldMemcpyizer {
916e5dd7070Spatrick   public:
FieldMemcpyizer(CodeGenFunction & CGF,const CXXRecordDecl * ClassDecl,const VarDecl * SrcRec)917e5dd7070Spatrick     FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl,
918e5dd7070Spatrick                     const VarDecl *SrcRec)
919e5dd7070Spatrick       : CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec),
920e5dd7070Spatrick         RecLayout(CGF.getContext().getASTRecordLayout(ClassDecl)),
921e5dd7070Spatrick         FirstField(nullptr), LastField(nullptr), FirstFieldOffset(0),
922e5dd7070Spatrick         LastFieldOffset(0), LastAddedFieldIndex(0) {}
923e5dd7070Spatrick 
isMemcpyableField(FieldDecl * F) const924e5dd7070Spatrick     bool isMemcpyableField(FieldDecl *F) const {
925e5dd7070Spatrick       // Never memcpy fields when we are adding poisoned paddings.
926e5dd7070Spatrick       if (CGF.getContext().getLangOpts().SanitizeAddressFieldPadding)
927e5dd7070Spatrick         return false;
928e5dd7070Spatrick       Qualifiers Qual = F->getType().getQualifiers();
929e5dd7070Spatrick       if (Qual.hasVolatile() || Qual.hasObjCLifetime())
930e5dd7070Spatrick         return false;
931e5dd7070Spatrick       return true;
932e5dd7070Spatrick     }
933e5dd7070Spatrick 
addMemcpyableField(FieldDecl * F)934e5dd7070Spatrick     void addMemcpyableField(FieldDecl *F) {
935e5dd7070Spatrick       if (F->isZeroSize(CGF.getContext()))
936e5dd7070Spatrick         return;
937e5dd7070Spatrick       if (!FirstField)
938e5dd7070Spatrick         addInitialField(F);
939e5dd7070Spatrick       else
940e5dd7070Spatrick         addNextField(F);
941e5dd7070Spatrick     }
942e5dd7070Spatrick 
getMemcpySize(uint64_t FirstByteOffset) const943e5dd7070Spatrick     CharUnits getMemcpySize(uint64_t FirstByteOffset) const {
944e5dd7070Spatrick       ASTContext &Ctx = CGF.getContext();
945e5dd7070Spatrick       unsigned LastFieldSize =
946e5dd7070Spatrick           LastField->isBitField()
947e5dd7070Spatrick               ? LastField->getBitWidthValue(Ctx)
948e5dd7070Spatrick               : Ctx.toBits(
949a9ac8606Spatrick                     Ctx.getTypeInfoDataSizeInChars(LastField->getType()).Width);
950e5dd7070Spatrick       uint64_t MemcpySizeBits = LastFieldOffset + LastFieldSize -
951e5dd7070Spatrick                                 FirstByteOffset + Ctx.getCharWidth() - 1;
952e5dd7070Spatrick       CharUnits MemcpySize = Ctx.toCharUnitsFromBits(MemcpySizeBits);
953e5dd7070Spatrick       return MemcpySize;
954e5dd7070Spatrick     }
955e5dd7070Spatrick 
emitMemcpy()956e5dd7070Spatrick     void emitMemcpy() {
957e5dd7070Spatrick       // Give the subclass a chance to bail out if it feels the memcpy isn't
958e5dd7070Spatrick       // worth it (e.g. Hasn't aggregated enough data).
959e5dd7070Spatrick       if (!FirstField) {
960e5dd7070Spatrick         return;
961e5dd7070Spatrick       }
962e5dd7070Spatrick 
963e5dd7070Spatrick       uint64_t FirstByteOffset;
964e5dd7070Spatrick       if (FirstField->isBitField()) {
965e5dd7070Spatrick         const CGRecordLayout &RL =
966e5dd7070Spatrick           CGF.getTypes().getCGRecordLayout(FirstField->getParent());
967e5dd7070Spatrick         const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField);
968e5dd7070Spatrick         // FirstFieldOffset is not appropriate for bitfields,
969e5dd7070Spatrick         // we need to use the storage offset instead.
970e5dd7070Spatrick         FirstByteOffset = CGF.getContext().toBits(BFInfo.StorageOffset);
971e5dd7070Spatrick       } else {
972e5dd7070Spatrick         FirstByteOffset = FirstFieldOffset;
973e5dd7070Spatrick       }
974e5dd7070Spatrick 
975e5dd7070Spatrick       CharUnits MemcpySize = getMemcpySize(FirstByteOffset);
976e5dd7070Spatrick       QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
977e5dd7070Spatrick       Address ThisPtr = CGF.LoadCXXThisAddress();
978e5dd7070Spatrick       LValue DestLV = CGF.MakeAddrLValue(ThisPtr, RecordTy);
979e5dd7070Spatrick       LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField);
980e5dd7070Spatrick       llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec));
981e5dd7070Spatrick       LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
982e5dd7070Spatrick       LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField);
983e5dd7070Spatrick 
984e5dd7070Spatrick       emitMemcpyIR(
985e5dd7070Spatrick           Dest.isBitField() ? Dest.getBitFieldAddress() : Dest.getAddress(CGF),
986e5dd7070Spatrick           Src.isBitField() ? Src.getBitFieldAddress() : Src.getAddress(CGF),
987e5dd7070Spatrick           MemcpySize);
988e5dd7070Spatrick       reset();
989e5dd7070Spatrick     }
990e5dd7070Spatrick 
reset()991e5dd7070Spatrick     void reset() {
992e5dd7070Spatrick       FirstField = nullptr;
993e5dd7070Spatrick     }
994e5dd7070Spatrick 
995e5dd7070Spatrick   protected:
996e5dd7070Spatrick     CodeGenFunction &CGF;
997e5dd7070Spatrick     const CXXRecordDecl *ClassDecl;
998e5dd7070Spatrick 
999e5dd7070Spatrick   private:
emitMemcpyIR(Address DestPtr,Address SrcPtr,CharUnits Size)1000e5dd7070Spatrick     void emitMemcpyIR(Address DestPtr, Address SrcPtr, CharUnits Size) {
1001*12c85518Srobert       DestPtr = CGF.Builder.CreateElementBitCast(DestPtr, CGF.Int8Ty);
1002*12c85518Srobert       SrcPtr = CGF.Builder.CreateElementBitCast(SrcPtr, CGF.Int8Ty);
1003e5dd7070Spatrick       CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity());
1004e5dd7070Spatrick     }
1005e5dd7070Spatrick 
addInitialField(FieldDecl * F)1006e5dd7070Spatrick     void addInitialField(FieldDecl *F) {
1007e5dd7070Spatrick       FirstField = F;
1008e5dd7070Spatrick       LastField = F;
1009e5dd7070Spatrick       FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex());
1010e5dd7070Spatrick       LastFieldOffset = FirstFieldOffset;
1011e5dd7070Spatrick       LastAddedFieldIndex = F->getFieldIndex();
1012e5dd7070Spatrick     }
1013e5dd7070Spatrick 
addNextField(FieldDecl * F)1014e5dd7070Spatrick     void addNextField(FieldDecl *F) {
1015e5dd7070Spatrick       // For the most part, the following invariant will hold:
1016e5dd7070Spatrick       //   F->getFieldIndex() == LastAddedFieldIndex + 1
1017e5dd7070Spatrick       // The one exception is that Sema won't add a copy-initializer for an
1018e5dd7070Spatrick       // unnamed bitfield, which will show up here as a gap in the sequence.
1019e5dd7070Spatrick       assert(F->getFieldIndex() >= LastAddedFieldIndex + 1 &&
1020e5dd7070Spatrick              "Cannot aggregate fields out of order.");
1021e5dd7070Spatrick       LastAddedFieldIndex = F->getFieldIndex();
1022e5dd7070Spatrick 
1023e5dd7070Spatrick       // The 'first' and 'last' fields are chosen by offset, rather than field
1024e5dd7070Spatrick       // index. This allows the code to support bitfields, as well as regular
1025e5dd7070Spatrick       // fields.
1026e5dd7070Spatrick       uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex());
1027e5dd7070Spatrick       if (FOffset < FirstFieldOffset) {
1028e5dd7070Spatrick         FirstField = F;
1029e5dd7070Spatrick         FirstFieldOffset = FOffset;
1030e5dd7070Spatrick       } else if (FOffset >= LastFieldOffset) {
1031e5dd7070Spatrick         LastField = F;
1032e5dd7070Spatrick         LastFieldOffset = FOffset;
1033e5dd7070Spatrick       }
1034e5dd7070Spatrick     }
1035e5dd7070Spatrick 
1036e5dd7070Spatrick     const VarDecl *SrcRec;
1037e5dd7070Spatrick     const ASTRecordLayout &RecLayout;
1038e5dd7070Spatrick     FieldDecl *FirstField;
1039e5dd7070Spatrick     FieldDecl *LastField;
1040e5dd7070Spatrick     uint64_t FirstFieldOffset, LastFieldOffset;
1041e5dd7070Spatrick     unsigned LastAddedFieldIndex;
1042e5dd7070Spatrick   };
1043e5dd7070Spatrick 
1044e5dd7070Spatrick   class ConstructorMemcpyizer : public FieldMemcpyizer {
1045e5dd7070Spatrick   private:
1046e5dd7070Spatrick     /// Get source argument for copy constructor. Returns null if not a copy
1047e5dd7070Spatrick     /// constructor.
getTrivialCopySource(CodeGenFunction & CGF,const CXXConstructorDecl * CD,FunctionArgList & Args)1048e5dd7070Spatrick     static const VarDecl *getTrivialCopySource(CodeGenFunction &CGF,
1049e5dd7070Spatrick                                                const CXXConstructorDecl *CD,
1050e5dd7070Spatrick                                                FunctionArgList &Args) {
1051e5dd7070Spatrick       if (CD->isCopyOrMoveConstructor() && CD->isDefaulted())
1052e5dd7070Spatrick         return Args[CGF.CGM.getCXXABI().getSrcArgforCopyCtor(CD, Args)];
1053e5dd7070Spatrick       return nullptr;
1054e5dd7070Spatrick     }
1055e5dd7070Spatrick 
1056e5dd7070Spatrick     // Returns true if a CXXCtorInitializer represents a member initialization
1057e5dd7070Spatrick     // that can be rolled into a memcpy.
isMemberInitMemcpyable(CXXCtorInitializer * MemberInit) const1058e5dd7070Spatrick     bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const {
1059e5dd7070Spatrick       if (!MemcpyableCtor)
1060e5dd7070Spatrick         return false;
1061e5dd7070Spatrick       FieldDecl *Field = MemberInit->getMember();
1062e5dd7070Spatrick       assert(Field && "No field for member init.");
1063e5dd7070Spatrick       QualType FieldType = Field->getType();
1064e5dd7070Spatrick       CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
1065e5dd7070Spatrick 
1066e5dd7070Spatrick       // Bail out on non-memcpyable, not-trivially-copyable members.
1067e5dd7070Spatrick       if (!(CE && isMemcpyEquivalentSpecialMember(CE->getConstructor())) &&
1068e5dd7070Spatrick           !(FieldType.isTriviallyCopyableType(CGF.getContext()) ||
1069e5dd7070Spatrick             FieldType->isReferenceType()))
1070e5dd7070Spatrick         return false;
1071e5dd7070Spatrick 
1072e5dd7070Spatrick       // Bail out on volatile fields.
1073e5dd7070Spatrick       if (!isMemcpyableField(Field))
1074e5dd7070Spatrick         return false;
1075e5dd7070Spatrick 
1076e5dd7070Spatrick       // Otherwise we're good.
1077e5dd7070Spatrick       return true;
1078e5dd7070Spatrick     }
1079e5dd7070Spatrick 
1080e5dd7070Spatrick   public:
ConstructorMemcpyizer(CodeGenFunction & CGF,const CXXConstructorDecl * CD,FunctionArgList & Args)1081e5dd7070Spatrick     ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD,
1082e5dd7070Spatrick                           FunctionArgList &Args)
1083e5dd7070Spatrick       : FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CGF, CD, Args)),
1084e5dd7070Spatrick         ConstructorDecl(CD),
1085e5dd7070Spatrick         MemcpyableCtor(CD->isDefaulted() &&
1086e5dd7070Spatrick                        CD->isCopyOrMoveConstructor() &&
1087e5dd7070Spatrick                        CGF.getLangOpts().getGC() == LangOptions::NonGC),
1088e5dd7070Spatrick         Args(Args) { }
1089e5dd7070Spatrick 
addMemberInitializer(CXXCtorInitializer * MemberInit)1090e5dd7070Spatrick     void addMemberInitializer(CXXCtorInitializer *MemberInit) {
1091e5dd7070Spatrick       if (isMemberInitMemcpyable(MemberInit)) {
1092e5dd7070Spatrick         AggregatedInits.push_back(MemberInit);
1093e5dd7070Spatrick         addMemcpyableField(MemberInit->getMember());
1094e5dd7070Spatrick       } else {
1095e5dd7070Spatrick         emitAggregatedInits();
1096e5dd7070Spatrick         EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit,
1097e5dd7070Spatrick                               ConstructorDecl, Args);
1098e5dd7070Spatrick       }
1099e5dd7070Spatrick     }
1100e5dd7070Spatrick 
emitAggregatedInits()1101e5dd7070Spatrick     void emitAggregatedInits() {
1102e5dd7070Spatrick       if (AggregatedInits.size() <= 1) {
1103e5dd7070Spatrick         // This memcpy is too small to be worthwhile. Fall back on default
1104e5dd7070Spatrick         // codegen.
1105e5dd7070Spatrick         if (!AggregatedInits.empty()) {
1106e5dd7070Spatrick           CopyingValueRepresentation CVR(CGF);
1107e5dd7070Spatrick           EmitMemberInitializer(CGF, ConstructorDecl->getParent(),
1108e5dd7070Spatrick                                 AggregatedInits[0], ConstructorDecl, Args);
1109e5dd7070Spatrick           AggregatedInits.clear();
1110e5dd7070Spatrick         }
1111e5dd7070Spatrick         reset();
1112e5dd7070Spatrick         return;
1113e5dd7070Spatrick       }
1114e5dd7070Spatrick 
1115e5dd7070Spatrick       pushEHDestructors();
1116e5dd7070Spatrick       emitMemcpy();
1117e5dd7070Spatrick       AggregatedInits.clear();
1118e5dd7070Spatrick     }
1119e5dd7070Spatrick 
pushEHDestructors()1120e5dd7070Spatrick     void pushEHDestructors() {
1121e5dd7070Spatrick       Address ThisPtr = CGF.LoadCXXThisAddress();
1122e5dd7070Spatrick       QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
1123e5dd7070Spatrick       LValue LHS = CGF.MakeAddrLValue(ThisPtr, RecordTy);
1124e5dd7070Spatrick 
1125e5dd7070Spatrick       for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
1126e5dd7070Spatrick         CXXCtorInitializer *MemberInit = AggregatedInits[i];
1127e5dd7070Spatrick         QualType FieldType = MemberInit->getAnyMember()->getType();
1128e5dd7070Spatrick         QualType::DestructionKind dtorKind = FieldType.isDestructedType();
1129e5dd7070Spatrick         if (!CGF.needsEHCleanup(dtorKind))
1130e5dd7070Spatrick           continue;
1131e5dd7070Spatrick         LValue FieldLHS = LHS;
1132e5dd7070Spatrick         EmitLValueForAnyFieldInitialization(CGF, MemberInit, FieldLHS);
1133e5dd7070Spatrick         CGF.pushEHDestroy(dtorKind, FieldLHS.getAddress(CGF), FieldType);
1134e5dd7070Spatrick       }
1135e5dd7070Spatrick     }
1136e5dd7070Spatrick 
finish()1137e5dd7070Spatrick     void finish() {
1138e5dd7070Spatrick       emitAggregatedInits();
1139e5dd7070Spatrick     }
1140e5dd7070Spatrick 
1141e5dd7070Spatrick   private:
1142e5dd7070Spatrick     const CXXConstructorDecl *ConstructorDecl;
1143e5dd7070Spatrick     bool MemcpyableCtor;
1144e5dd7070Spatrick     FunctionArgList &Args;
1145e5dd7070Spatrick     SmallVector<CXXCtorInitializer*, 16> AggregatedInits;
1146e5dd7070Spatrick   };
1147e5dd7070Spatrick 
1148e5dd7070Spatrick   class AssignmentMemcpyizer : public FieldMemcpyizer {
1149e5dd7070Spatrick   private:
1150e5dd7070Spatrick     // Returns the memcpyable field copied by the given statement, if one
1151e5dd7070Spatrick     // exists. Otherwise returns null.
getMemcpyableField(Stmt * S)1152e5dd7070Spatrick     FieldDecl *getMemcpyableField(Stmt *S) {
1153e5dd7070Spatrick       if (!AssignmentsMemcpyable)
1154e5dd7070Spatrick         return nullptr;
1155e5dd7070Spatrick       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
1156e5dd7070Spatrick         // Recognise trivial assignments.
1157e5dd7070Spatrick         if (BO->getOpcode() != BO_Assign)
1158e5dd7070Spatrick           return nullptr;
1159e5dd7070Spatrick         MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS());
1160e5dd7070Spatrick         if (!ME)
1161e5dd7070Spatrick           return nullptr;
1162e5dd7070Spatrick         FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1163e5dd7070Spatrick         if (!Field || !isMemcpyableField(Field))
1164e5dd7070Spatrick           return nullptr;
1165e5dd7070Spatrick         Stmt *RHS = BO->getRHS();
1166e5dd7070Spatrick         if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS))
1167e5dd7070Spatrick           RHS = EC->getSubExpr();
1168e5dd7070Spatrick         if (!RHS)
1169e5dd7070Spatrick           return nullptr;
1170e5dd7070Spatrick         if (MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS)) {
1171e5dd7070Spatrick           if (ME2->getMemberDecl() == Field)
1172e5dd7070Spatrick             return Field;
1173e5dd7070Spatrick         }
1174e5dd7070Spatrick         return nullptr;
1175e5dd7070Spatrick       } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) {
1176e5dd7070Spatrick         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl());
1177e5dd7070Spatrick         if (!(MD && isMemcpyEquivalentSpecialMember(MD)))
1178e5dd7070Spatrick           return nullptr;
1179e5dd7070Spatrick         MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument());
1180e5dd7070Spatrick         if (!IOA)
1181e5dd7070Spatrick           return nullptr;
1182e5dd7070Spatrick         FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl());
1183e5dd7070Spatrick         if (!Field || !isMemcpyableField(Field))
1184e5dd7070Spatrick           return nullptr;
1185e5dd7070Spatrick         MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0));
1186e5dd7070Spatrick         if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl()))
1187e5dd7070Spatrick           return nullptr;
1188e5dd7070Spatrick         return Field;
1189e5dd7070Spatrick       } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1190e5dd7070Spatrick         FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1191e5dd7070Spatrick         if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy)
1192e5dd7070Spatrick           return nullptr;
1193e5dd7070Spatrick         Expr *DstPtr = CE->getArg(0);
1194e5dd7070Spatrick         if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr))
1195e5dd7070Spatrick           DstPtr = DC->getSubExpr();
1196e5dd7070Spatrick         UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr);
1197e5dd7070Spatrick         if (!DUO || DUO->getOpcode() != UO_AddrOf)
1198e5dd7070Spatrick           return nullptr;
1199e5dd7070Spatrick         MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr());
1200e5dd7070Spatrick         if (!ME)
1201e5dd7070Spatrick           return nullptr;
1202e5dd7070Spatrick         FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1203e5dd7070Spatrick         if (!Field || !isMemcpyableField(Field))
1204e5dd7070Spatrick           return nullptr;
1205e5dd7070Spatrick         Expr *SrcPtr = CE->getArg(1);
1206e5dd7070Spatrick         if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr))
1207e5dd7070Spatrick           SrcPtr = SC->getSubExpr();
1208e5dd7070Spatrick         UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr);
1209e5dd7070Spatrick         if (!SUO || SUO->getOpcode() != UO_AddrOf)
1210e5dd7070Spatrick           return nullptr;
1211e5dd7070Spatrick         MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr());
1212e5dd7070Spatrick         if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl()))
1213e5dd7070Spatrick           return nullptr;
1214e5dd7070Spatrick         return Field;
1215e5dd7070Spatrick       }
1216e5dd7070Spatrick 
1217e5dd7070Spatrick       return nullptr;
1218e5dd7070Spatrick     }
1219e5dd7070Spatrick 
1220e5dd7070Spatrick     bool AssignmentsMemcpyable;
1221e5dd7070Spatrick     SmallVector<Stmt*, 16> AggregatedStmts;
1222e5dd7070Spatrick 
1223e5dd7070Spatrick   public:
AssignmentMemcpyizer(CodeGenFunction & CGF,const CXXMethodDecl * AD,FunctionArgList & Args)1224e5dd7070Spatrick     AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD,
1225e5dd7070Spatrick                          FunctionArgList &Args)
1226e5dd7070Spatrick       : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]),
1227e5dd7070Spatrick         AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) {
1228e5dd7070Spatrick       assert(Args.size() == 2);
1229e5dd7070Spatrick     }
1230e5dd7070Spatrick 
emitAssignment(Stmt * S)1231e5dd7070Spatrick     void emitAssignment(Stmt *S) {
1232e5dd7070Spatrick       FieldDecl *F = getMemcpyableField(S);
1233e5dd7070Spatrick       if (F) {
1234e5dd7070Spatrick         addMemcpyableField(F);
1235e5dd7070Spatrick         AggregatedStmts.push_back(S);
1236e5dd7070Spatrick       } else {
1237e5dd7070Spatrick         emitAggregatedStmts();
1238e5dd7070Spatrick         CGF.EmitStmt(S);
1239e5dd7070Spatrick       }
1240e5dd7070Spatrick     }
1241e5dd7070Spatrick 
emitAggregatedStmts()1242e5dd7070Spatrick     void emitAggregatedStmts() {
1243e5dd7070Spatrick       if (AggregatedStmts.size() <= 1) {
1244e5dd7070Spatrick         if (!AggregatedStmts.empty()) {
1245e5dd7070Spatrick           CopyingValueRepresentation CVR(CGF);
1246e5dd7070Spatrick           CGF.EmitStmt(AggregatedStmts[0]);
1247e5dd7070Spatrick         }
1248e5dd7070Spatrick         reset();
1249e5dd7070Spatrick       }
1250e5dd7070Spatrick 
1251e5dd7070Spatrick       emitMemcpy();
1252e5dd7070Spatrick       AggregatedStmts.clear();
1253e5dd7070Spatrick     }
1254e5dd7070Spatrick 
finish()1255e5dd7070Spatrick     void finish() {
1256e5dd7070Spatrick       emitAggregatedStmts();
1257e5dd7070Spatrick     }
1258e5dd7070Spatrick   };
1259e5dd7070Spatrick } // end anonymous namespace
1260e5dd7070Spatrick 
isInitializerOfDynamicClass(const CXXCtorInitializer * BaseInit)1261e5dd7070Spatrick static bool isInitializerOfDynamicClass(const CXXCtorInitializer *BaseInit) {
1262e5dd7070Spatrick   const Type *BaseType = BaseInit->getBaseClass();
1263e5dd7070Spatrick   const auto *BaseClassDecl =
1264e5dd7070Spatrick       cast<CXXRecordDecl>(BaseType->castAs<RecordType>()->getDecl());
1265e5dd7070Spatrick   return BaseClassDecl->isDynamicClass();
1266e5dd7070Spatrick }
1267e5dd7070Spatrick 
1268e5dd7070Spatrick /// EmitCtorPrologue - This routine generates necessary code to initialize
1269e5dd7070Spatrick /// base classes and non-static data members belonging to this constructor.
EmitCtorPrologue(const CXXConstructorDecl * CD,CXXCtorType CtorType,FunctionArgList & Args)1270e5dd7070Spatrick void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
1271e5dd7070Spatrick                                        CXXCtorType CtorType,
1272e5dd7070Spatrick                                        FunctionArgList &Args) {
1273e5dd7070Spatrick   if (CD->isDelegatingConstructor())
1274e5dd7070Spatrick     return EmitDelegatingCXXConstructorCall(CD, Args);
1275e5dd7070Spatrick 
1276e5dd7070Spatrick   const CXXRecordDecl *ClassDecl = CD->getParent();
1277e5dd7070Spatrick 
1278e5dd7070Spatrick   CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
1279e5dd7070Spatrick                                           E = CD->init_end();
1280e5dd7070Spatrick 
1281e5dd7070Spatrick   // Virtual base initializers first, if any. They aren't needed if:
1282e5dd7070Spatrick   // - This is a base ctor variant
1283e5dd7070Spatrick   // - There are no vbases
1284e5dd7070Spatrick   // - The class is abstract, so a complete object of it cannot be constructed
1285e5dd7070Spatrick   //
1286e5dd7070Spatrick   // The check for an abstract class is necessary because sema may not have
1287e5dd7070Spatrick   // marked virtual base destructors referenced.
1288e5dd7070Spatrick   bool ConstructVBases = CtorType != Ctor_Base &&
1289e5dd7070Spatrick                          ClassDecl->getNumVBases() != 0 &&
1290e5dd7070Spatrick                          !ClassDecl->isAbstract();
1291e5dd7070Spatrick 
1292e5dd7070Spatrick   // In the Microsoft C++ ABI, there are no constructor variants. Instead, the
1293e5dd7070Spatrick   // constructor of a class with virtual bases takes an additional parameter to
1294e5dd7070Spatrick   // conditionally construct the virtual bases. Emit that check here.
1295e5dd7070Spatrick   llvm::BasicBlock *BaseCtorContinueBB = nullptr;
1296e5dd7070Spatrick   if (ConstructVBases &&
1297e5dd7070Spatrick       !CGM.getTarget().getCXXABI().hasConstructorVariants()) {
1298e5dd7070Spatrick     BaseCtorContinueBB =
1299e5dd7070Spatrick         CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this, ClassDecl);
1300e5dd7070Spatrick     assert(BaseCtorContinueBB);
1301e5dd7070Spatrick   }
1302e5dd7070Spatrick 
1303e5dd7070Spatrick   llvm::Value *const OldThis = CXXThisValue;
1304e5dd7070Spatrick   for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
1305e5dd7070Spatrick     if (!ConstructVBases)
1306e5dd7070Spatrick       continue;
1307e5dd7070Spatrick     if (CGM.getCodeGenOpts().StrictVTablePointers &&
1308e5dd7070Spatrick         CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1309e5dd7070Spatrick         isInitializerOfDynamicClass(*B))
1310e5dd7070Spatrick       CXXThisValue = Builder.CreateLaunderInvariantGroup(LoadCXXThis());
1311e5dd7070Spatrick     EmitBaseInitializer(*this, ClassDecl, *B);
1312e5dd7070Spatrick   }
1313e5dd7070Spatrick 
1314e5dd7070Spatrick   if (BaseCtorContinueBB) {
1315e5dd7070Spatrick     // Complete object handler should continue to the remaining initializers.
1316e5dd7070Spatrick     Builder.CreateBr(BaseCtorContinueBB);
1317e5dd7070Spatrick     EmitBlock(BaseCtorContinueBB);
1318e5dd7070Spatrick   }
1319e5dd7070Spatrick 
1320e5dd7070Spatrick   // Then, non-virtual base initializers.
1321e5dd7070Spatrick   for (; B != E && (*B)->isBaseInitializer(); B++) {
1322e5dd7070Spatrick     assert(!(*B)->isBaseVirtual());
1323e5dd7070Spatrick 
1324e5dd7070Spatrick     if (CGM.getCodeGenOpts().StrictVTablePointers &&
1325e5dd7070Spatrick         CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1326e5dd7070Spatrick         isInitializerOfDynamicClass(*B))
1327e5dd7070Spatrick       CXXThisValue = Builder.CreateLaunderInvariantGroup(LoadCXXThis());
1328e5dd7070Spatrick     EmitBaseInitializer(*this, ClassDecl, *B);
1329e5dd7070Spatrick   }
1330e5dd7070Spatrick 
1331e5dd7070Spatrick   CXXThisValue = OldThis;
1332e5dd7070Spatrick 
1333e5dd7070Spatrick   InitializeVTablePointers(ClassDecl);
1334e5dd7070Spatrick 
1335e5dd7070Spatrick   // And finally, initialize class members.
1336e5dd7070Spatrick   FieldConstructionScope FCS(*this, LoadCXXThisAddress());
1337e5dd7070Spatrick   ConstructorMemcpyizer CM(*this, CD, Args);
1338e5dd7070Spatrick   for (; B != E; B++) {
1339e5dd7070Spatrick     CXXCtorInitializer *Member = (*B);
1340e5dd7070Spatrick     assert(!Member->isBaseInitializer());
1341e5dd7070Spatrick     assert(Member->isAnyMemberInitializer() &&
1342e5dd7070Spatrick            "Delegating initializer on non-delegating constructor");
1343e5dd7070Spatrick     CM.addMemberInitializer(Member);
1344e5dd7070Spatrick   }
1345e5dd7070Spatrick   CM.finish();
1346e5dd7070Spatrick }
1347e5dd7070Spatrick 
1348e5dd7070Spatrick static bool
1349e5dd7070Spatrick FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
1350e5dd7070Spatrick 
1351e5dd7070Spatrick static bool
HasTrivialDestructorBody(ASTContext & Context,const CXXRecordDecl * BaseClassDecl,const CXXRecordDecl * MostDerivedClassDecl)1352e5dd7070Spatrick HasTrivialDestructorBody(ASTContext &Context,
1353e5dd7070Spatrick                          const CXXRecordDecl *BaseClassDecl,
1354e5dd7070Spatrick                          const CXXRecordDecl *MostDerivedClassDecl)
1355e5dd7070Spatrick {
1356e5dd7070Spatrick   // If the destructor is trivial we don't have to check anything else.
1357e5dd7070Spatrick   if (BaseClassDecl->hasTrivialDestructor())
1358e5dd7070Spatrick     return true;
1359e5dd7070Spatrick 
1360e5dd7070Spatrick   if (!BaseClassDecl->getDestructor()->hasTrivialBody())
1361e5dd7070Spatrick     return false;
1362e5dd7070Spatrick 
1363e5dd7070Spatrick   // Check fields.
1364e5dd7070Spatrick   for (const auto *Field : BaseClassDecl->fields())
1365e5dd7070Spatrick     if (!FieldHasTrivialDestructorBody(Context, Field))
1366e5dd7070Spatrick       return false;
1367e5dd7070Spatrick 
1368e5dd7070Spatrick   // Check non-virtual bases.
1369e5dd7070Spatrick   for (const auto &I : BaseClassDecl->bases()) {
1370e5dd7070Spatrick     if (I.isVirtual())
1371e5dd7070Spatrick       continue;
1372e5dd7070Spatrick 
1373e5dd7070Spatrick     const CXXRecordDecl *NonVirtualBase =
1374e5dd7070Spatrick       cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
1375e5dd7070Spatrick     if (!HasTrivialDestructorBody(Context, NonVirtualBase,
1376e5dd7070Spatrick                                   MostDerivedClassDecl))
1377e5dd7070Spatrick       return false;
1378e5dd7070Spatrick   }
1379e5dd7070Spatrick 
1380e5dd7070Spatrick   if (BaseClassDecl == MostDerivedClassDecl) {
1381e5dd7070Spatrick     // Check virtual bases.
1382e5dd7070Spatrick     for (const auto &I : BaseClassDecl->vbases()) {
1383e5dd7070Spatrick       const CXXRecordDecl *VirtualBase =
1384e5dd7070Spatrick         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
1385e5dd7070Spatrick       if (!HasTrivialDestructorBody(Context, VirtualBase,
1386e5dd7070Spatrick                                     MostDerivedClassDecl))
1387e5dd7070Spatrick         return false;
1388e5dd7070Spatrick     }
1389e5dd7070Spatrick   }
1390e5dd7070Spatrick 
1391e5dd7070Spatrick   return true;
1392e5dd7070Spatrick }
1393e5dd7070Spatrick 
1394e5dd7070Spatrick static bool
FieldHasTrivialDestructorBody(ASTContext & Context,const FieldDecl * Field)1395e5dd7070Spatrick FieldHasTrivialDestructorBody(ASTContext &Context,
1396e5dd7070Spatrick                                           const FieldDecl *Field)
1397e5dd7070Spatrick {
1398e5dd7070Spatrick   QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
1399e5dd7070Spatrick 
1400e5dd7070Spatrick   const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
1401e5dd7070Spatrick   if (!RT)
1402e5dd7070Spatrick     return true;
1403e5dd7070Spatrick 
1404e5dd7070Spatrick   CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1405e5dd7070Spatrick 
1406e5dd7070Spatrick   // The destructor for an implicit anonymous union member is never invoked.
1407e5dd7070Spatrick   if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
1408e5dd7070Spatrick     return false;
1409e5dd7070Spatrick 
1410e5dd7070Spatrick   return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
1411e5dd7070Spatrick }
1412e5dd7070Spatrick 
1413e5dd7070Spatrick /// CanSkipVTablePointerInitialization - Check whether we need to initialize
1414e5dd7070Spatrick /// any vtable pointers before calling this destructor.
CanSkipVTablePointerInitialization(CodeGenFunction & CGF,const CXXDestructorDecl * Dtor)1415e5dd7070Spatrick static bool CanSkipVTablePointerInitialization(CodeGenFunction &CGF,
1416e5dd7070Spatrick                                                const CXXDestructorDecl *Dtor) {
1417e5dd7070Spatrick   const CXXRecordDecl *ClassDecl = Dtor->getParent();
1418e5dd7070Spatrick   if (!ClassDecl->isDynamicClass())
1419e5dd7070Spatrick     return true;
1420e5dd7070Spatrick 
1421*12c85518Srobert   // For a final class, the vtable pointer is known to already point to the
1422*12c85518Srobert   // class's vtable.
1423*12c85518Srobert   if (ClassDecl->isEffectivelyFinal())
1424*12c85518Srobert     return true;
1425*12c85518Srobert 
1426e5dd7070Spatrick   if (!Dtor->hasTrivialBody())
1427e5dd7070Spatrick     return false;
1428e5dd7070Spatrick 
1429e5dd7070Spatrick   // Check the fields.
1430e5dd7070Spatrick   for (const auto *Field : ClassDecl->fields())
1431e5dd7070Spatrick     if (!FieldHasTrivialDestructorBody(CGF.getContext(), Field))
1432e5dd7070Spatrick       return false;
1433e5dd7070Spatrick 
1434e5dd7070Spatrick   return true;
1435e5dd7070Spatrick }
1436e5dd7070Spatrick 
1437e5dd7070Spatrick /// EmitDestructorBody - Emits the body of the current destructor.
EmitDestructorBody(FunctionArgList & Args)1438e5dd7070Spatrick void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
1439e5dd7070Spatrick   const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
1440e5dd7070Spatrick   CXXDtorType DtorType = CurGD.getDtorType();
1441e5dd7070Spatrick 
1442e5dd7070Spatrick   // For an abstract class, non-base destructors are never used (and can't
1443e5dd7070Spatrick   // be emitted in general, because vbase dtors may not have been validated
1444e5dd7070Spatrick   // by Sema), but the Itanium ABI doesn't make them optional and Clang may
1445e5dd7070Spatrick   // in fact emit references to them from other compilations, so emit them
1446e5dd7070Spatrick   // as functions containing a trap instruction.
1447e5dd7070Spatrick   if (DtorType != Dtor_Base && Dtor->getParent()->isAbstract()) {
1448e5dd7070Spatrick     llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
1449e5dd7070Spatrick     TrapCall->setDoesNotReturn();
1450e5dd7070Spatrick     TrapCall->setDoesNotThrow();
1451e5dd7070Spatrick     Builder.CreateUnreachable();
1452e5dd7070Spatrick     Builder.ClearInsertionPoint();
1453e5dd7070Spatrick     return;
1454e5dd7070Spatrick   }
1455e5dd7070Spatrick 
1456e5dd7070Spatrick   Stmt *Body = Dtor->getBody();
1457e5dd7070Spatrick   if (Body)
1458e5dd7070Spatrick     incrementProfileCounter(Body);
1459e5dd7070Spatrick 
1460e5dd7070Spatrick   // The call to operator delete in a deleting destructor happens
1461e5dd7070Spatrick   // outside of the function-try-block, which means it's always
1462e5dd7070Spatrick   // possible to delegate the destructor body to the complete
1463e5dd7070Spatrick   // destructor.  Do so.
1464e5dd7070Spatrick   if (DtorType == Dtor_Deleting) {
1465e5dd7070Spatrick     RunCleanupsScope DtorEpilogue(*this);
1466e5dd7070Spatrick     EnterDtorCleanups(Dtor, Dtor_Deleting);
1467e5dd7070Spatrick     if (HaveInsertPoint()) {
1468e5dd7070Spatrick       QualType ThisTy = Dtor->getThisObjectType();
1469e5dd7070Spatrick       EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
1470e5dd7070Spatrick                             /*Delegating=*/false, LoadCXXThisAddress(), ThisTy);
1471e5dd7070Spatrick     }
1472e5dd7070Spatrick     return;
1473e5dd7070Spatrick   }
1474e5dd7070Spatrick 
1475e5dd7070Spatrick   // If the body is a function-try-block, enter the try before
1476e5dd7070Spatrick   // anything else.
1477e5dd7070Spatrick   bool isTryBody = (Body && isa<CXXTryStmt>(Body));
1478e5dd7070Spatrick   if (isTryBody)
1479e5dd7070Spatrick     EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
1480e5dd7070Spatrick   EmitAsanPrologueOrEpilogue(false);
1481e5dd7070Spatrick 
1482e5dd7070Spatrick   // Enter the epilogue cleanups.
1483e5dd7070Spatrick   RunCleanupsScope DtorEpilogue(*this);
1484e5dd7070Spatrick 
1485e5dd7070Spatrick   // If this is the complete variant, just invoke the base variant;
1486e5dd7070Spatrick   // the epilogue will destruct the virtual bases.  But we can't do
1487e5dd7070Spatrick   // this optimization if the body is a function-try-block, because
1488e5dd7070Spatrick   // we'd introduce *two* handler blocks.  In the Microsoft ABI, we
1489e5dd7070Spatrick   // always delegate because we might not have a definition in this TU.
1490e5dd7070Spatrick   switch (DtorType) {
1491e5dd7070Spatrick   case Dtor_Comdat: llvm_unreachable("not expecting a COMDAT");
1492e5dd7070Spatrick   case Dtor_Deleting: llvm_unreachable("already handled deleting case");
1493e5dd7070Spatrick 
1494e5dd7070Spatrick   case Dtor_Complete:
1495e5dd7070Spatrick     assert((Body || getTarget().getCXXABI().isMicrosoft()) &&
1496e5dd7070Spatrick            "can't emit a dtor without a body for non-Microsoft ABIs");
1497e5dd7070Spatrick 
1498e5dd7070Spatrick     // Enter the cleanup scopes for virtual bases.
1499e5dd7070Spatrick     EnterDtorCleanups(Dtor, Dtor_Complete);
1500e5dd7070Spatrick 
1501e5dd7070Spatrick     if (!isTryBody) {
1502e5dd7070Spatrick       QualType ThisTy = Dtor->getThisObjectType();
1503e5dd7070Spatrick       EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
1504e5dd7070Spatrick                             /*Delegating=*/false, LoadCXXThisAddress(), ThisTy);
1505e5dd7070Spatrick       break;
1506e5dd7070Spatrick     }
1507e5dd7070Spatrick 
1508e5dd7070Spatrick     // Fallthrough: act like we're in the base variant.
1509*12c85518Srobert     [[fallthrough]];
1510e5dd7070Spatrick 
1511e5dd7070Spatrick   case Dtor_Base:
1512e5dd7070Spatrick     assert(Body);
1513e5dd7070Spatrick 
1514e5dd7070Spatrick     // Enter the cleanup scopes for fields and non-virtual bases.
1515e5dd7070Spatrick     EnterDtorCleanups(Dtor, Dtor_Base);
1516e5dd7070Spatrick 
1517e5dd7070Spatrick     // Initialize the vtable pointers before entering the body.
1518e5dd7070Spatrick     if (!CanSkipVTablePointerInitialization(*this, Dtor)) {
1519e5dd7070Spatrick       // Insert the llvm.launder.invariant.group intrinsic before initializing
1520e5dd7070Spatrick       // the vptrs to cancel any previous assumptions we might have made.
1521e5dd7070Spatrick       if (CGM.getCodeGenOpts().StrictVTablePointers &&
1522e5dd7070Spatrick           CGM.getCodeGenOpts().OptimizationLevel > 0)
1523e5dd7070Spatrick         CXXThisValue = Builder.CreateLaunderInvariantGroup(LoadCXXThis());
1524e5dd7070Spatrick       InitializeVTablePointers(Dtor->getParent());
1525e5dd7070Spatrick     }
1526e5dd7070Spatrick 
1527e5dd7070Spatrick     if (isTryBody)
1528e5dd7070Spatrick       EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
1529e5dd7070Spatrick     else if (Body)
1530e5dd7070Spatrick       EmitStmt(Body);
1531e5dd7070Spatrick     else {
1532e5dd7070Spatrick       assert(Dtor->isImplicit() && "bodyless dtor not implicit");
1533e5dd7070Spatrick       // nothing to do besides what's in the epilogue
1534e5dd7070Spatrick     }
1535e5dd7070Spatrick     // -fapple-kext must inline any call to this dtor into
1536e5dd7070Spatrick     // the caller's body.
1537e5dd7070Spatrick     if (getLangOpts().AppleKext)
1538e5dd7070Spatrick       CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
1539e5dd7070Spatrick 
1540e5dd7070Spatrick     break;
1541e5dd7070Spatrick   }
1542e5dd7070Spatrick 
1543e5dd7070Spatrick   // Jump out through the epilogue cleanups.
1544e5dd7070Spatrick   DtorEpilogue.ForceCleanup();
1545e5dd7070Spatrick 
1546e5dd7070Spatrick   // Exit the try if applicable.
1547e5dd7070Spatrick   if (isTryBody)
1548e5dd7070Spatrick     ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
1549e5dd7070Spatrick }
1550e5dd7070Spatrick 
emitImplicitAssignmentOperatorBody(FunctionArgList & Args)1551e5dd7070Spatrick void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) {
1552e5dd7070Spatrick   const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
1553e5dd7070Spatrick   const Stmt *RootS = AssignOp->getBody();
1554e5dd7070Spatrick   assert(isa<CompoundStmt>(RootS) &&
1555e5dd7070Spatrick          "Body of an implicit assignment operator should be compound stmt.");
1556e5dd7070Spatrick   const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
1557e5dd7070Spatrick 
1558e5dd7070Spatrick   LexicalScope Scope(*this, RootCS->getSourceRange());
1559e5dd7070Spatrick 
1560e5dd7070Spatrick   incrementProfileCounter(RootCS);
1561e5dd7070Spatrick   AssignmentMemcpyizer AM(*this, AssignOp, Args);
1562e5dd7070Spatrick   for (auto *I : RootCS->body())
1563e5dd7070Spatrick     AM.emitAssignment(I);
1564e5dd7070Spatrick   AM.finish();
1565e5dd7070Spatrick }
1566e5dd7070Spatrick 
1567e5dd7070Spatrick namespace {
LoadThisForDtorDelete(CodeGenFunction & CGF,const CXXDestructorDecl * DD)1568e5dd7070Spatrick   llvm::Value *LoadThisForDtorDelete(CodeGenFunction &CGF,
1569e5dd7070Spatrick                                      const CXXDestructorDecl *DD) {
1570e5dd7070Spatrick     if (Expr *ThisArg = DD->getOperatorDeleteThisArg())
1571e5dd7070Spatrick       return CGF.EmitScalarExpr(ThisArg);
1572e5dd7070Spatrick     return CGF.LoadCXXThis();
1573e5dd7070Spatrick   }
1574e5dd7070Spatrick 
1575e5dd7070Spatrick   /// Call the operator delete associated with the current destructor.
1576e5dd7070Spatrick   struct CallDtorDelete final : EHScopeStack::Cleanup {
CallDtorDelete__anonda710d950411::CallDtorDelete1577e5dd7070Spatrick     CallDtorDelete() {}
1578e5dd7070Spatrick 
Emit__anonda710d950411::CallDtorDelete1579e5dd7070Spatrick     void Emit(CodeGenFunction &CGF, Flags flags) override {
1580e5dd7070Spatrick       const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1581e5dd7070Spatrick       const CXXRecordDecl *ClassDecl = Dtor->getParent();
1582e5dd7070Spatrick       CGF.EmitDeleteCall(Dtor->getOperatorDelete(),
1583e5dd7070Spatrick                          LoadThisForDtorDelete(CGF, Dtor),
1584e5dd7070Spatrick                          CGF.getContext().getTagDeclType(ClassDecl));
1585e5dd7070Spatrick     }
1586e5dd7070Spatrick   };
1587e5dd7070Spatrick 
EmitConditionalDtorDeleteCall(CodeGenFunction & CGF,llvm::Value * ShouldDeleteCondition,bool ReturnAfterDelete)1588e5dd7070Spatrick   void EmitConditionalDtorDeleteCall(CodeGenFunction &CGF,
1589e5dd7070Spatrick                                      llvm::Value *ShouldDeleteCondition,
1590e5dd7070Spatrick                                      bool ReturnAfterDelete) {
1591e5dd7070Spatrick     llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
1592e5dd7070Spatrick     llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
1593e5dd7070Spatrick     llvm::Value *ShouldCallDelete
1594e5dd7070Spatrick       = CGF.Builder.CreateIsNull(ShouldDeleteCondition);
1595e5dd7070Spatrick     CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
1596e5dd7070Spatrick 
1597e5dd7070Spatrick     CGF.EmitBlock(callDeleteBB);
1598e5dd7070Spatrick     const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1599e5dd7070Spatrick     const CXXRecordDecl *ClassDecl = Dtor->getParent();
1600e5dd7070Spatrick     CGF.EmitDeleteCall(Dtor->getOperatorDelete(),
1601e5dd7070Spatrick                        LoadThisForDtorDelete(CGF, Dtor),
1602e5dd7070Spatrick                        CGF.getContext().getTagDeclType(ClassDecl));
1603e5dd7070Spatrick     assert(Dtor->getOperatorDelete()->isDestroyingOperatorDelete() ==
1604e5dd7070Spatrick                ReturnAfterDelete &&
1605e5dd7070Spatrick            "unexpected value for ReturnAfterDelete");
1606e5dd7070Spatrick     if (ReturnAfterDelete)
1607e5dd7070Spatrick       CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
1608e5dd7070Spatrick     else
1609e5dd7070Spatrick       CGF.Builder.CreateBr(continueBB);
1610e5dd7070Spatrick 
1611e5dd7070Spatrick     CGF.EmitBlock(continueBB);
1612e5dd7070Spatrick   }
1613e5dd7070Spatrick 
1614e5dd7070Spatrick   struct CallDtorDeleteConditional final : EHScopeStack::Cleanup {
1615e5dd7070Spatrick     llvm::Value *ShouldDeleteCondition;
1616e5dd7070Spatrick 
1617e5dd7070Spatrick   public:
CallDtorDeleteConditional__anonda710d950411::CallDtorDeleteConditional1618e5dd7070Spatrick     CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
1619e5dd7070Spatrick         : ShouldDeleteCondition(ShouldDeleteCondition) {
1620e5dd7070Spatrick       assert(ShouldDeleteCondition != nullptr);
1621e5dd7070Spatrick     }
1622e5dd7070Spatrick 
Emit__anonda710d950411::CallDtorDeleteConditional1623e5dd7070Spatrick     void Emit(CodeGenFunction &CGF, Flags flags) override {
1624e5dd7070Spatrick       EmitConditionalDtorDeleteCall(CGF, ShouldDeleteCondition,
1625e5dd7070Spatrick                                     /*ReturnAfterDelete*/false);
1626e5dd7070Spatrick     }
1627e5dd7070Spatrick   };
1628e5dd7070Spatrick 
1629e5dd7070Spatrick   class DestroyField  final : public EHScopeStack::Cleanup {
1630e5dd7070Spatrick     const FieldDecl *field;
1631e5dd7070Spatrick     CodeGenFunction::Destroyer *destroyer;
1632e5dd7070Spatrick     bool useEHCleanupForArray;
1633e5dd7070Spatrick 
1634e5dd7070Spatrick   public:
DestroyField(const FieldDecl * field,CodeGenFunction::Destroyer * destroyer,bool useEHCleanupForArray)1635e5dd7070Spatrick     DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
1636e5dd7070Spatrick                  bool useEHCleanupForArray)
1637e5dd7070Spatrick         : field(field), destroyer(destroyer),
1638e5dd7070Spatrick           useEHCleanupForArray(useEHCleanupForArray) {}
1639e5dd7070Spatrick 
Emit(CodeGenFunction & CGF,Flags flags)1640e5dd7070Spatrick     void Emit(CodeGenFunction &CGF, Flags flags) override {
1641e5dd7070Spatrick       // Find the address of the field.
1642e5dd7070Spatrick       Address thisValue = CGF.LoadCXXThisAddress();
1643e5dd7070Spatrick       QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
1644e5dd7070Spatrick       LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
1645e5dd7070Spatrick       LValue LV = CGF.EmitLValueForField(ThisLV, field);
1646e5dd7070Spatrick       assert(LV.isSimple());
1647e5dd7070Spatrick 
1648e5dd7070Spatrick       CGF.emitDestroy(LV.getAddress(CGF), field->getType(), destroyer,
1649e5dd7070Spatrick                       flags.isForNormalCleanup() && useEHCleanupForArray);
1650e5dd7070Spatrick     }
1651e5dd7070Spatrick   };
1652e5dd7070Spatrick 
1653*12c85518Srobert   class DeclAsInlineDebugLocation {
1654*12c85518Srobert     CGDebugInfo *DI;
1655*12c85518Srobert     llvm::MDNode *InlinedAt;
1656*12c85518Srobert     std::optional<ApplyDebugLocation> Location;
1657*12c85518Srobert 
1658*12c85518Srobert   public:
DeclAsInlineDebugLocation(CodeGenFunction & CGF,const NamedDecl & Decl)1659*12c85518Srobert     DeclAsInlineDebugLocation(CodeGenFunction &CGF, const NamedDecl &Decl)
1660*12c85518Srobert         : DI(CGF.getDebugInfo()) {
1661*12c85518Srobert       if (!DI)
1662*12c85518Srobert         return;
1663*12c85518Srobert       InlinedAt = DI->getInlinedAt();
1664*12c85518Srobert       DI->setInlinedAt(CGF.Builder.getCurrentDebugLocation());
1665*12c85518Srobert       Location.emplace(CGF, Decl.getLocation());
1666*12c85518Srobert     }
1667*12c85518Srobert 
~DeclAsInlineDebugLocation()1668*12c85518Srobert     ~DeclAsInlineDebugLocation() {
1669*12c85518Srobert       if (!DI)
1670*12c85518Srobert         return;
1671*12c85518Srobert       Location.reset();
1672*12c85518Srobert       DI->setInlinedAt(InlinedAt);
1673*12c85518Srobert     }
1674*12c85518Srobert   };
1675*12c85518Srobert 
EmitSanitizerDtorCallback(CodeGenFunction & CGF,StringRef Name,llvm::Value * Ptr,std::optional<CharUnits::QuantityType> PoisonSize={})1676*12c85518Srobert   static void EmitSanitizerDtorCallback(
1677*12c85518Srobert       CodeGenFunction &CGF, StringRef Name, llvm::Value *Ptr,
1678*12c85518Srobert       std::optional<CharUnits::QuantityType> PoisonSize = {}) {
1679e5dd7070Spatrick     CodeGenFunction::SanitizerScope SanScope(&CGF);
1680e5dd7070Spatrick     // Pass in void pointer and size of region as arguments to runtime
1681e5dd7070Spatrick     // function
1682*12c85518Srobert     SmallVector<llvm::Value *, 2> Args = {
1683*12c85518Srobert         CGF.Builder.CreateBitCast(Ptr, CGF.VoidPtrTy)};
1684*12c85518Srobert     SmallVector<llvm::Type *, 2> ArgTypes = {CGF.VoidPtrTy};
1685e5dd7070Spatrick 
1686*12c85518Srobert     if (PoisonSize.has_value()) {
1687*12c85518Srobert       Args.emplace_back(llvm::ConstantInt::get(CGF.SizeTy, *PoisonSize));
1688*12c85518Srobert       ArgTypes.emplace_back(CGF.SizeTy);
1689*12c85518Srobert     }
1690e5dd7070Spatrick 
1691e5dd7070Spatrick     llvm::FunctionType *FnType =
1692e5dd7070Spatrick         llvm::FunctionType::get(CGF.VoidTy, ArgTypes, false);
1693*12c85518Srobert     llvm::FunctionCallee Fn = CGF.CGM.CreateRuntimeFunction(FnType, Name);
1694*12c85518Srobert 
1695e5dd7070Spatrick     CGF.EmitNounwindRuntimeCall(Fn, Args);
1696e5dd7070Spatrick   }
1697e5dd7070Spatrick 
1698*12c85518Srobert   static void
EmitSanitizerDtorFieldsCallback(CodeGenFunction & CGF,llvm::Value * Ptr,CharUnits::QuantityType PoisonSize)1699*12c85518Srobert   EmitSanitizerDtorFieldsCallback(CodeGenFunction &CGF, llvm::Value *Ptr,
1700*12c85518Srobert                                   CharUnits::QuantityType PoisonSize) {
1701*12c85518Srobert     EmitSanitizerDtorCallback(CGF, "__sanitizer_dtor_callback_fields", Ptr,
1702*12c85518Srobert                               PoisonSize);
1703*12c85518Srobert   }
1704*12c85518Srobert 
1705*12c85518Srobert   /// Poison base class with a trivial destructor.
1706*12c85518Srobert   struct SanitizeDtorTrivialBase final : EHScopeStack::Cleanup {
1707*12c85518Srobert     const CXXRecordDecl *BaseClass;
1708*12c85518Srobert     bool BaseIsVirtual;
SanitizeDtorTrivialBase__anonda710d950411::SanitizeDtorTrivialBase1709*12c85518Srobert     SanitizeDtorTrivialBase(const CXXRecordDecl *Base, bool BaseIsVirtual)
1710*12c85518Srobert         : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
1711*12c85518Srobert 
Emit__anonda710d950411::SanitizeDtorTrivialBase1712*12c85518Srobert     void Emit(CodeGenFunction &CGF, Flags flags) override {
1713*12c85518Srobert       const CXXRecordDecl *DerivedClass =
1714*12c85518Srobert           cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
1715*12c85518Srobert 
1716*12c85518Srobert       Address Addr = CGF.GetAddressOfDirectBaseInCompleteClass(
1717*12c85518Srobert           CGF.LoadCXXThisAddress(), DerivedClass, BaseClass, BaseIsVirtual);
1718*12c85518Srobert 
1719*12c85518Srobert       const ASTRecordLayout &BaseLayout =
1720*12c85518Srobert           CGF.getContext().getASTRecordLayout(BaseClass);
1721*12c85518Srobert       CharUnits BaseSize = BaseLayout.getSize();
1722*12c85518Srobert 
1723*12c85518Srobert       if (!BaseSize.isPositive())
1724*12c85518Srobert         return;
1725*12c85518Srobert 
1726*12c85518Srobert       // Use the base class declaration location as inline DebugLocation. All
1727*12c85518Srobert       // fields of the class are destroyed.
1728*12c85518Srobert       DeclAsInlineDebugLocation InlineHere(CGF, *BaseClass);
1729*12c85518Srobert       EmitSanitizerDtorFieldsCallback(CGF, Addr.getPointer(),
1730*12c85518Srobert                                       BaseSize.getQuantity());
1731*12c85518Srobert 
1732*12c85518Srobert       // Prevent the current stack frame from disappearing from the stack trace.
1733*12c85518Srobert       CGF.CurFn->addFnAttr("disable-tail-calls", "true");
1734*12c85518Srobert     }
1735*12c85518Srobert   };
1736*12c85518Srobert 
1737*12c85518Srobert   class SanitizeDtorFieldRange final : public EHScopeStack::Cleanup {
1738e5dd7070Spatrick     const CXXDestructorDecl *Dtor;
1739*12c85518Srobert     unsigned StartIndex;
1740*12c85518Srobert     unsigned EndIndex;
1741e5dd7070Spatrick 
1742e5dd7070Spatrick   public:
SanitizeDtorFieldRange(const CXXDestructorDecl * Dtor,unsigned StartIndex,unsigned EndIndex)1743*12c85518Srobert     SanitizeDtorFieldRange(const CXXDestructorDecl *Dtor, unsigned StartIndex,
1744*12c85518Srobert                            unsigned EndIndex)
1745*12c85518Srobert         : Dtor(Dtor), StartIndex(StartIndex), EndIndex(EndIndex) {}
1746e5dd7070Spatrick 
1747e5dd7070Spatrick     // Generate function call for handling object poisoning.
1748e5dd7070Spatrick     // Disables tail call elimination, to prevent the current stack frame
1749e5dd7070Spatrick     // from disappearing from the stack trace.
Emit(CodeGenFunction & CGF,Flags flags)1750e5dd7070Spatrick     void Emit(CodeGenFunction &CGF, Flags flags) override {
1751*12c85518Srobert       const ASTContext &Context = CGF.getContext();
1752e5dd7070Spatrick       const ASTRecordLayout &Layout =
1753e5dd7070Spatrick           Context.getASTRecordLayout(Dtor->getParent());
1754e5dd7070Spatrick 
1755*12c85518Srobert       // It's a first trivial field so it should be at the begining of a char,
1756a9ac8606Spatrick       // still round up start offset just in case.
1757*12c85518Srobert       CharUnits PoisonStart = Context.toCharUnitsFromBits(
1758*12c85518Srobert           Layout.getFieldOffset(StartIndex) + Context.getCharWidth() - 1);
1759a9ac8606Spatrick       llvm::ConstantInt *OffsetSizePtr =
1760a9ac8606Spatrick           llvm::ConstantInt::get(CGF.SizeTy, PoisonStart.getQuantity());
1761e5dd7070Spatrick 
1762e5dd7070Spatrick       llvm::Value *OffsetPtr = CGF.Builder.CreateGEP(
1763a9ac8606Spatrick           CGF.Int8Ty,
1764e5dd7070Spatrick           CGF.Builder.CreateBitCast(CGF.LoadCXXThis(), CGF.Int8PtrTy),
1765e5dd7070Spatrick           OffsetSizePtr);
1766e5dd7070Spatrick 
1767a9ac8606Spatrick       CharUnits PoisonEnd;
1768*12c85518Srobert       if (EndIndex >= Layout.getFieldCount()) {
1769a9ac8606Spatrick         PoisonEnd = Layout.getNonVirtualSize();
1770e5dd7070Spatrick       } else {
1771a9ac8606Spatrick         PoisonEnd =
1772*12c85518Srobert             Context.toCharUnitsFromBits(Layout.getFieldOffset(EndIndex));
1773e5dd7070Spatrick       }
1774a9ac8606Spatrick       CharUnits PoisonSize = PoisonEnd - PoisonStart;
1775a9ac8606Spatrick       if (!PoisonSize.isPositive())
1776e5dd7070Spatrick         return;
1777e5dd7070Spatrick 
1778*12c85518Srobert       // Use the top field declaration location as inline DebugLocation.
1779*12c85518Srobert       DeclAsInlineDebugLocation InlineHere(
1780*12c85518Srobert           CGF, **std::next(Dtor->getParent()->field_begin(), StartIndex));
1781*12c85518Srobert       EmitSanitizerDtorFieldsCallback(CGF, OffsetPtr, PoisonSize.getQuantity());
1782*12c85518Srobert 
1783*12c85518Srobert       // Prevent the current stack frame from disappearing from the stack trace.
1784*12c85518Srobert       CGF.CurFn->addFnAttr("disable-tail-calls", "true");
1785e5dd7070Spatrick     }
1786e5dd7070Spatrick   };
1787e5dd7070Spatrick 
1788e5dd7070Spatrick  class SanitizeDtorVTable final : public EHScopeStack::Cleanup {
1789e5dd7070Spatrick     const CXXDestructorDecl *Dtor;
1790e5dd7070Spatrick 
1791e5dd7070Spatrick   public:
SanitizeDtorVTable(const CXXDestructorDecl * Dtor)1792e5dd7070Spatrick     SanitizeDtorVTable(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
1793e5dd7070Spatrick 
1794e5dd7070Spatrick     // Generate function call for handling vtable pointer poisoning.
Emit(CodeGenFunction & CGF,Flags flags)1795e5dd7070Spatrick     void Emit(CodeGenFunction &CGF, Flags flags) override {
1796e5dd7070Spatrick       assert(Dtor->getParent()->isDynamicClass());
1797e5dd7070Spatrick       (void)Dtor;
1798e5dd7070Spatrick       // Poison vtable and vtable ptr if they exist for this class.
1799e5dd7070Spatrick       llvm::Value *VTablePtr = CGF.LoadCXXThis();
1800e5dd7070Spatrick 
1801e5dd7070Spatrick       // Pass in void pointer and size of region as arguments to runtime
1802e5dd7070Spatrick       // function
1803*12c85518Srobert       EmitSanitizerDtorCallback(CGF, "__sanitizer_dtor_callback_vptr",
1804*12c85518Srobert                                 VTablePtr);
1805*12c85518Srobert     }
1806*12c85518Srobert  };
1807*12c85518Srobert 
1808*12c85518Srobert  class SanitizeDtorCleanupBuilder {
1809*12c85518Srobert    ASTContext &Context;
1810*12c85518Srobert    EHScopeStack &EHStack;
1811*12c85518Srobert    const CXXDestructorDecl *DD;
1812*12c85518Srobert    std::optional<unsigned> StartIndex;
1813*12c85518Srobert 
1814*12c85518Srobert  public:
SanitizeDtorCleanupBuilder(ASTContext & Context,EHScopeStack & EHStack,const CXXDestructorDecl * DD)1815*12c85518Srobert    SanitizeDtorCleanupBuilder(ASTContext &Context, EHScopeStack &EHStack,
1816*12c85518Srobert                               const CXXDestructorDecl *DD)
1817*12c85518Srobert        : Context(Context), EHStack(EHStack), DD(DD), StartIndex(std::nullopt) {}
PushCleanupForField(const FieldDecl * Field)1818*12c85518Srobert    void PushCleanupForField(const FieldDecl *Field) {
1819*12c85518Srobert      if (Field->isZeroSize(Context))
1820*12c85518Srobert        return;
1821*12c85518Srobert      unsigned FieldIndex = Field->getFieldIndex();
1822*12c85518Srobert      if (FieldHasTrivialDestructorBody(Context, Field)) {
1823*12c85518Srobert        if (!StartIndex)
1824*12c85518Srobert          StartIndex = FieldIndex;
1825*12c85518Srobert      } else if (StartIndex) {
1826*12c85518Srobert        EHStack.pushCleanup<SanitizeDtorFieldRange>(NormalAndEHCleanup, DD,
1827*12c85518Srobert                                                    *StartIndex, FieldIndex);
1828*12c85518Srobert        StartIndex = std::nullopt;
1829*12c85518Srobert      }
1830*12c85518Srobert    }
End()1831*12c85518Srobert    void End() {
1832*12c85518Srobert      if (StartIndex)
1833*12c85518Srobert        EHStack.pushCleanup<SanitizeDtorFieldRange>(NormalAndEHCleanup, DD,
1834*12c85518Srobert                                                    *StartIndex, -1);
1835e5dd7070Spatrick    }
1836e5dd7070Spatrick  };
1837e5dd7070Spatrick } // end anonymous namespace
1838e5dd7070Spatrick 
1839e5dd7070Spatrick /// Emit all code that comes at the end of class's
1840e5dd7070Spatrick /// destructor. This is to call destructors on members and base classes
1841e5dd7070Spatrick /// in reverse order of their construction.
1842e5dd7070Spatrick ///
1843e5dd7070Spatrick /// For a deleting destructor, this also handles the case where a destroying
1844e5dd7070Spatrick /// operator delete completely overrides the definition.
EnterDtorCleanups(const CXXDestructorDecl * DD,CXXDtorType DtorType)1845e5dd7070Spatrick void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
1846e5dd7070Spatrick                                         CXXDtorType DtorType) {
1847e5dd7070Spatrick   assert((!DD->isTrivial() || DD->hasAttr<DLLExportAttr>()) &&
1848e5dd7070Spatrick          "Should not emit dtor epilogue for non-exported trivial dtor!");
1849e5dd7070Spatrick 
1850e5dd7070Spatrick   // The deleting-destructor phase just needs to call the appropriate
1851e5dd7070Spatrick   // operator delete that Sema picked up.
1852e5dd7070Spatrick   if (DtorType == Dtor_Deleting) {
1853e5dd7070Spatrick     assert(DD->getOperatorDelete() &&
1854e5dd7070Spatrick            "operator delete missing - EnterDtorCleanups");
1855e5dd7070Spatrick     if (CXXStructorImplicitParamValue) {
1856e5dd7070Spatrick       // If there is an implicit param to the deleting dtor, it's a boolean
1857e5dd7070Spatrick       // telling whether this is a deleting destructor.
1858e5dd7070Spatrick       if (DD->getOperatorDelete()->isDestroyingOperatorDelete())
1859e5dd7070Spatrick         EmitConditionalDtorDeleteCall(*this, CXXStructorImplicitParamValue,
1860e5dd7070Spatrick                                       /*ReturnAfterDelete*/true);
1861e5dd7070Spatrick       else
1862e5dd7070Spatrick         EHStack.pushCleanup<CallDtorDeleteConditional>(
1863e5dd7070Spatrick             NormalAndEHCleanup, CXXStructorImplicitParamValue);
1864e5dd7070Spatrick     } else {
1865e5dd7070Spatrick       if (DD->getOperatorDelete()->isDestroyingOperatorDelete()) {
1866e5dd7070Spatrick         const CXXRecordDecl *ClassDecl = DD->getParent();
1867e5dd7070Spatrick         EmitDeleteCall(DD->getOperatorDelete(),
1868e5dd7070Spatrick                        LoadThisForDtorDelete(*this, DD),
1869e5dd7070Spatrick                        getContext().getTagDeclType(ClassDecl));
1870e5dd7070Spatrick         EmitBranchThroughCleanup(ReturnBlock);
1871e5dd7070Spatrick       } else {
1872e5dd7070Spatrick         EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
1873e5dd7070Spatrick       }
1874e5dd7070Spatrick     }
1875e5dd7070Spatrick     return;
1876e5dd7070Spatrick   }
1877e5dd7070Spatrick 
1878e5dd7070Spatrick   const CXXRecordDecl *ClassDecl = DD->getParent();
1879e5dd7070Spatrick 
1880e5dd7070Spatrick   // Unions have no bases and do not call field destructors.
1881e5dd7070Spatrick   if (ClassDecl->isUnion())
1882e5dd7070Spatrick     return;
1883e5dd7070Spatrick 
1884e5dd7070Spatrick   // The complete-destructor phase just destructs all the virtual bases.
1885e5dd7070Spatrick   if (DtorType == Dtor_Complete) {
1886e5dd7070Spatrick     // Poison the vtable pointer such that access after the base
1887e5dd7070Spatrick     // and member destructors are invoked is invalid.
1888e5dd7070Spatrick     if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1889e5dd7070Spatrick         SanOpts.has(SanitizerKind::Memory) && ClassDecl->getNumVBases() &&
1890e5dd7070Spatrick         ClassDecl->isPolymorphic())
1891e5dd7070Spatrick       EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
1892e5dd7070Spatrick 
1893e5dd7070Spatrick     // We push them in the forward order so that they'll be popped in
1894e5dd7070Spatrick     // the reverse order.
1895e5dd7070Spatrick     for (const auto &Base : ClassDecl->vbases()) {
1896e5dd7070Spatrick       auto *BaseClassDecl =
1897e5dd7070Spatrick           cast<CXXRecordDecl>(Base.getType()->castAs<RecordType>()->getDecl());
1898e5dd7070Spatrick 
1899*12c85518Srobert       if (BaseClassDecl->hasTrivialDestructor()) {
1900*12c85518Srobert         // Under SanitizeMemoryUseAfterDtor, poison the trivial base class
1901*12c85518Srobert         // memory. For non-trival base classes the same is done in the class
1902*12c85518Srobert         // destructor.
1903*12c85518Srobert         if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1904*12c85518Srobert             SanOpts.has(SanitizerKind::Memory) && !BaseClassDecl->isEmpty())
1905*12c85518Srobert           EHStack.pushCleanup<SanitizeDtorTrivialBase>(NormalAndEHCleanup,
1906e5dd7070Spatrick                                                        BaseClassDecl,
1907e5dd7070Spatrick                                                        /*BaseIsVirtual*/ true);
1908*12c85518Srobert       } else {
1909*12c85518Srobert         EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup, BaseClassDecl,
1910*12c85518Srobert                                           /*BaseIsVirtual*/ true);
1911*12c85518Srobert       }
1912e5dd7070Spatrick     }
1913e5dd7070Spatrick 
1914e5dd7070Spatrick     return;
1915e5dd7070Spatrick   }
1916e5dd7070Spatrick 
1917e5dd7070Spatrick   assert(DtorType == Dtor_Base);
1918e5dd7070Spatrick   // Poison the vtable pointer if it has no virtual bases, but inherits
1919e5dd7070Spatrick   // virtual functions.
1920e5dd7070Spatrick   if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1921e5dd7070Spatrick       SanOpts.has(SanitizerKind::Memory) && !ClassDecl->getNumVBases() &&
1922e5dd7070Spatrick       ClassDecl->isPolymorphic())
1923e5dd7070Spatrick     EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
1924e5dd7070Spatrick 
1925e5dd7070Spatrick   // Destroy non-virtual bases.
1926e5dd7070Spatrick   for (const auto &Base : ClassDecl->bases()) {
1927e5dd7070Spatrick     // Ignore virtual bases.
1928e5dd7070Spatrick     if (Base.isVirtual())
1929e5dd7070Spatrick       continue;
1930e5dd7070Spatrick 
1931e5dd7070Spatrick     CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
1932e5dd7070Spatrick 
1933*12c85518Srobert     if (BaseClassDecl->hasTrivialDestructor()) {
1934*12c85518Srobert       if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1935*12c85518Srobert           SanOpts.has(SanitizerKind::Memory) && !BaseClassDecl->isEmpty())
1936*12c85518Srobert         EHStack.pushCleanup<SanitizeDtorTrivialBase>(NormalAndEHCleanup,
1937e5dd7070Spatrick                                                      BaseClassDecl,
1938e5dd7070Spatrick                                                      /*BaseIsVirtual*/ false);
1939*12c85518Srobert     } else {
1940*12c85518Srobert       EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup, BaseClassDecl,
1941*12c85518Srobert                                         /*BaseIsVirtual*/ false);
1942*12c85518Srobert     }
1943e5dd7070Spatrick   }
1944e5dd7070Spatrick 
1945e5dd7070Spatrick   // Poison fields such that access after their destructors are
1946e5dd7070Spatrick   // invoked, and before the base class destructor runs, is invalid.
1947*12c85518Srobert   bool SanitizeFields = CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1948*12c85518Srobert                         SanOpts.has(SanitizerKind::Memory);
1949*12c85518Srobert   SanitizeDtorCleanupBuilder SanitizeBuilder(getContext(), EHStack, DD);
1950e5dd7070Spatrick 
1951e5dd7070Spatrick   // Destroy direct fields.
1952e5dd7070Spatrick   for (const auto *Field : ClassDecl->fields()) {
1953*12c85518Srobert     if (SanitizeFields)
1954*12c85518Srobert       SanitizeBuilder.PushCleanupForField(Field);
1955*12c85518Srobert 
1956e5dd7070Spatrick     QualType type = Field->getType();
1957e5dd7070Spatrick     QualType::DestructionKind dtorKind = type.isDestructedType();
1958*12c85518Srobert     if (!dtorKind)
1959*12c85518Srobert       continue;
1960e5dd7070Spatrick 
1961e5dd7070Spatrick     // Anonymous union members do not have their destructors called.
1962e5dd7070Spatrick     const RecordType *RT = type->getAsUnionType();
1963*12c85518Srobert     if (RT && RT->getDecl()->isAnonymousStructOrUnion())
1964*12c85518Srobert       continue;
1965e5dd7070Spatrick 
1966e5dd7070Spatrick     CleanupKind cleanupKind = getCleanupKind(dtorKind);
1967*12c85518Srobert     EHStack.pushCleanup<DestroyField>(
1968*12c85518Srobert         cleanupKind, Field, getDestroyer(dtorKind), cleanupKind & EHCleanup);
1969e5dd7070Spatrick   }
1970*12c85518Srobert 
1971*12c85518Srobert   if (SanitizeFields)
1972*12c85518Srobert     SanitizeBuilder.End();
1973e5dd7070Spatrick }
1974e5dd7070Spatrick 
1975e5dd7070Spatrick /// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1976e5dd7070Spatrick /// constructor for each of several members of an array.
1977e5dd7070Spatrick ///
1978e5dd7070Spatrick /// \param ctor the constructor to call for each element
1979e5dd7070Spatrick /// \param arrayType the type of the array to initialize
1980e5dd7070Spatrick /// \param arrayBegin an arrayType*
1981e5dd7070Spatrick /// \param zeroInitialize true if each element should be
1982e5dd7070Spatrick ///   zero-initialized before it is constructed
EmitCXXAggrConstructorCall(const CXXConstructorDecl * ctor,const ArrayType * arrayType,Address arrayBegin,const CXXConstructExpr * E,bool NewPointerIsChecked,bool zeroInitialize)1983e5dd7070Spatrick void CodeGenFunction::EmitCXXAggrConstructorCall(
1984e5dd7070Spatrick     const CXXConstructorDecl *ctor, const ArrayType *arrayType,
1985e5dd7070Spatrick     Address arrayBegin, const CXXConstructExpr *E, bool NewPointerIsChecked,
1986e5dd7070Spatrick     bool zeroInitialize) {
1987e5dd7070Spatrick   QualType elementType;
1988e5dd7070Spatrick   llvm::Value *numElements =
1989e5dd7070Spatrick     emitArrayLength(arrayType, elementType, arrayBegin);
1990e5dd7070Spatrick 
1991e5dd7070Spatrick   EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin, E,
1992e5dd7070Spatrick                              NewPointerIsChecked, zeroInitialize);
1993e5dd7070Spatrick }
1994e5dd7070Spatrick 
1995e5dd7070Spatrick /// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1996e5dd7070Spatrick /// constructor for each of several members of an array.
1997e5dd7070Spatrick ///
1998e5dd7070Spatrick /// \param ctor the constructor to call for each element
1999e5dd7070Spatrick /// \param numElements the number of elements in the array;
2000e5dd7070Spatrick ///   may be zero
2001e5dd7070Spatrick /// \param arrayBase a T*, where T is the type constructed by ctor
2002e5dd7070Spatrick /// \param zeroInitialize true if each element should be
2003e5dd7070Spatrick ///   zero-initialized before it is constructed
EmitCXXAggrConstructorCall(const CXXConstructorDecl * ctor,llvm::Value * numElements,Address arrayBase,const CXXConstructExpr * E,bool NewPointerIsChecked,bool zeroInitialize)2004e5dd7070Spatrick void CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
2005e5dd7070Spatrick                                                  llvm::Value *numElements,
2006e5dd7070Spatrick                                                  Address arrayBase,
2007e5dd7070Spatrick                                                  const CXXConstructExpr *E,
2008e5dd7070Spatrick                                                  bool NewPointerIsChecked,
2009e5dd7070Spatrick                                                  bool zeroInitialize) {
2010e5dd7070Spatrick   // It's legal for numElements to be zero.  This can happen both
2011e5dd7070Spatrick   // dynamically, because x can be zero in 'new A[x]', and statically,
2012e5dd7070Spatrick   // because of GCC extensions that permit zero-length arrays.  There
2013e5dd7070Spatrick   // are probably legitimate places where we could assume that this
2014e5dd7070Spatrick   // doesn't happen, but it's not clear that it's worth it.
2015e5dd7070Spatrick   llvm::BranchInst *zeroCheckBranch = nullptr;
2016e5dd7070Spatrick 
2017e5dd7070Spatrick   // Optimize for a constant count.
2018e5dd7070Spatrick   llvm::ConstantInt *constantCount
2019e5dd7070Spatrick     = dyn_cast<llvm::ConstantInt>(numElements);
2020e5dd7070Spatrick   if (constantCount) {
2021e5dd7070Spatrick     // Just skip out if the constant count is zero.
2022e5dd7070Spatrick     if (constantCount->isZero()) return;
2023e5dd7070Spatrick 
2024e5dd7070Spatrick   // Otherwise, emit the check.
2025e5dd7070Spatrick   } else {
2026e5dd7070Spatrick     llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
2027e5dd7070Spatrick     llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
2028e5dd7070Spatrick     zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
2029e5dd7070Spatrick     EmitBlock(loopBB);
2030e5dd7070Spatrick   }
2031e5dd7070Spatrick 
2032e5dd7070Spatrick   // Find the end of the array.
2033a9ac8606Spatrick   llvm::Type *elementType = arrayBase.getElementType();
2034e5dd7070Spatrick   llvm::Value *arrayBegin = arrayBase.getPointer();
2035a9ac8606Spatrick   llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(
2036a9ac8606Spatrick       elementType, arrayBegin, numElements, "arrayctor.end");
2037e5dd7070Spatrick 
2038e5dd7070Spatrick   // Enter the loop, setting up a phi for the current location to initialize.
2039e5dd7070Spatrick   llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
2040e5dd7070Spatrick   llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
2041e5dd7070Spatrick   EmitBlock(loopBB);
2042e5dd7070Spatrick   llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
2043e5dd7070Spatrick                                          "arrayctor.cur");
2044e5dd7070Spatrick   cur->addIncoming(arrayBegin, entryBB);
2045e5dd7070Spatrick 
2046e5dd7070Spatrick   // Inside the loop body, emit the constructor call on the array element.
2047e5dd7070Spatrick 
2048e5dd7070Spatrick   // The alignment of the base, adjusted by the size of a single element,
2049e5dd7070Spatrick   // provides a conservative estimate of the alignment of every element.
2050e5dd7070Spatrick   // (This assumes we never start tracking offsetted alignments.)
2051e5dd7070Spatrick   //
2052e5dd7070Spatrick   // Note that these are complete objects and so we don't need to
2053e5dd7070Spatrick   // use the non-virtual size or alignment.
2054e5dd7070Spatrick   QualType type = getContext().getTypeDeclType(ctor->getParent());
2055e5dd7070Spatrick   CharUnits eltAlignment =
2056e5dd7070Spatrick     arrayBase.getAlignment()
2057e5dd7070Spatrick              .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
2058*12c85518Srobert   Address curAddr = Address(cur, elementType, eltAlignment);
2059e5dd7070Spatrick 
2060e5dd7070Spatrick   // Zero initialize the storage, if requested.
2061e5dd7070Spatrick   if (zeroInitialize)
2062e5dd7070Spatrick     EmitNullInitialization(curAddr, type);
2063e5dd7070Spatrick 
2064e5dd7070Spatrick   // C++ [class.temporary]p4:
2065e5dd7070Spatrick   // There are two contexts in which temporaries are destroyed at a different
2066e5dd7070Spatrick   // point than the end of the full-expression. The first context is when a
2067e5dd7070Spatrick   // default constructor is called to initialize an element of an array.
2068e5dd7070Spatrick   // If the constructor has one or more default arguments, the destruction of
2069e5dd7070Spatrick   // every temporary created in a default argument expression is sequenced
2070e5dd7070Spatrick   // before the construction of the next array element, if any.
2071e5dd7070Spatrick 
2072e5dd7070Spatrick   {
2073e5dd7070Spatrick     RunCleanupsScope Scope(*this);
2074e5dd7070Spatrick 
2075e5dd7070Spatrick     // Evaluate the constructor and its arguments in a regular
2076e5dd7070Spatrick     // partial-destroy cleanup.
2077e5dd7070Spatrick     if (getLangOpts().Exceptions &&
2078e5dd7070Spatrick         !ctor->getParent()->hasTrivialDestructor()) {
2079e5dd7070Spatrick       Destroyer *destroyer = destroyCXXObject;
2080e5dd7070Spatrick       pushRegularPartialArrayCleanup(arrayBegin, cur, type, eltAlignment,
2081e5dd7070Spatrick                                      *destroyer);
2082e5dd7070Spatrick     }
2083e5dd7070Spatrick     auto currAVS = AggValueSlot::forAddr(
2084e5dd7070Spatrick         curAddr, type.getQualifiers(), AggValueSlot::IsDestructed,
2085e5dd7070Spatrick         AggValueSlot::DoesNotNeedGCBarriers, AggValueSlot::IsNotAliased,
2086e5dd7070Spatrick         AggValueSlot::DoesNotOverlap, AggValueSlot::IsNotZeroed,
2087e5dd7070Spatrick         NewPointerIsChecked ? AggValueSlot::IsSanitizerChecked
2088e5dd7070Spatrick                             : AggValueSlot::IsNotSanitizerChecked);
2089e5dd7070Spatrick     EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/false,
2090e5dd7070Spatrick                            /*Delegating=*/false, currAVS, E);
2091e5dd7070Spatrick   }
2092e5dd7070Spatrick 
2093e5dd7070Spatrick   // Go to the next element.
2094a9ac8606Spatrick   llvm::Value *next = Builder.CreateInBoundsGEP(
2095a9ac8606Spatrick       elementType, cur, llvm::ConstantInt::get(SizeTy, 1), "arrayctor.next");
2096e5dd7070Spatrick   cur->addIncoming(next, Builder.GetInsertBlock());
2097e5dd7070Spatrick 
2098e5dd7070Spatrick   // Check whether that's the end of the loop.
2099e5dd7070Spatrick   llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
2100e5dd7070Spatrick   llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
2101e5dd7070Spatrick   Builder.CreateCondBr(done, contBB, loopBB);
2102e5dd7070Spatrick 
2103e5dd7070Spatrick   // Patch the earlier check to skip over the loop.
2104e5dd7070Spatrick   if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
2105e5dd7070Spatrick 
2106e5dd7070Spatrick   EmitBlock(contBB);
2107e5dd7070Spatrick }
2108e5dd7070Spatrick 
destroyCXXObject(CodeGenFunction & CGF,Address addr,QualType type)2109e5dd7070Spatrick void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
2110e5dd7070Spatrick                                        Address addr,
2111e5dd7070Spatrick                                        QualType type) {
2112e5dd7070Spatrick   const RecordType *rtype = type->castAs<RecordType>();
2113e5dd7070Spatrick   const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
2114e5dd7070Spatrick   const CXXDestructorDecl *dtor = record->getDestructor();
2115e5dd7070Spatrick   assert(!dtor->isTrivial());
2116e5dd7070Spatrick   CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
2117e5dd7070Spatrick                             /*Delegating=*/false, addr, type);
2118e5dd7070Spatrick }
2119e5dd7070Spatrick 
EmitCXXConstructorCall(const CXXConstructorDecl * D,CXXCtorType Type,bool ForVirtualBase,bool Delegating,AggValueSlot ThisAVS,const CXXConstructExpr * E)2120e5dd7070Spatrick void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
2121e5dd7070Spatrick                                              CXXCtorType Type,
2122e5dd7070Spatrick                                              bool ForVirtualBase,
2123e5dd7070Spatrick                                              bool Delegating,
2124e5dd7070Spatrick                                              AggValueSlot ThisAVS,
2125e5dd7070Spatrick                                              const CXXConstructExpr *E) {
2126e5dd7070Spatrick   CallArgList Args;
2127e5dd7070Spatrick   Address This = ThisAVS.getAddress();
2128e5dd7070Spatrick   LangAS SlotAS = ThisAVS.getQualifiers().getAddressSpace();
2129e5dd7070Spatrick   QualType ThisType = D->getThisType();
2130e5dd7070Spatrick   LangAS ThisAS = ThisType.getTypePtr()->getPointeeType().getAddressSpace();
2131e5dd7070Spatrick   llvm::Value *ThisPtr = This.getPointer();
2132e5dd7070Spatrick 
2133e5dd7070Spatrick   if (SlotAS != ThisAS) {
2134e5dd7070Spatrick     unsigned TargetThisAS = getContext().getTargetAddressSpace(ThisAS);
2135*12c85518Srobert     llvm::Type *NewType = llvm::PointerType::getWithSamePointeeType(
2136*12c85518Srobert         This.getType(), TargetThisAS);
2137e5dd7070Spatrick     ThisPtr = getTargetHooks().performAddrSpaceCast(*this, This.getPointer(),
2138e5dd7070Spatrick                                                     ThisAS, SlotAS, NewType);
2139e5dd7070Spatrick   }
2140e5dd7070Spatrick 
2141e5dd7070Spatrick   // Push the this ptr.
2142e5dd7070Spatrick   Args.add(RValue::get(ThisPtr), D->getThisType());
2143e5dd7070Spatrick 
2144e5dd7070Spatrick   // If this is a trivial constructor, emit a memcpy now before we lose
2145e5dd7070Spatrick   // the alignment information on the argument.
2146e5dd7070Spatrick   // FIXME: It would be better to preserve alignment information into CallArg.
2147e5dd7070Spatrick   if (isMemcpyEquivalentSpecialMember(D)) {
2148e5dd7070Spatrick     assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
2149e5dd7070Spatrick 
2150e5dd7070Spatrick     const Expr *Arg = E->getArg(0);
2151e5dd7070Spatrick     LValue Src = EmitLValue(Arg);
2152e5dd7070Spatrick     QualType DestTy = getContext().getTypeDeclType(D->getParent());
2153e5dd7070Spatrick     LValue Dest = MakeAddrLValue(This, DestTy);
2154e5dd7070Spatrick     EmitAggregateCopyCtor(Dest, Src, ThisAVS.mayOverlap());
2155e5dd7070Spatrick     return;
2156e5dd7070Spatrick   }
2157e5dd7070Spatrick 
2158e5dd7070Spatrick   // Add the rest of the user-supplied arguments.
2159e5dd7070Spatrick   const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
2160e5dd7070Spatrick   EvaluationOrder Order = E->isListInitialization()
2161e5dd7070Spatrick                               ? EvaluationOrder::ForceLeftToRight
2162e5dd7070Spatrick                               : EvaluationOrder::Default;
2163e5dd7070Spatrick   EmitCallArgs(Args, FPT, E->arguments(), E->getConstructor(),
2164e5dd7070Spatrick                /*ParamsToSkip*/ 0, Order);
2165e5dd7070Spatrick 
2166e5dd7070Spatrick   EmitCXXConstructorCall(D, Type, ForVirtualBase, Delegating, This, Args,
2167e5dd7070Spatrick                          ThisAVS.mayOverlap(), E->getExprLoc(),
2168e5dd7070Spatrick                          ThisAVS.isSanitizerChecked());
2169e5dd7070Spatrick }
2170e5dd7070Spatrick 
canEmitDelegateCallArgs(CodeGenFunction & CGF,const CXXConstructorDecl * Ctor,CXXCtorType Type,CallArgList & Args)2171e5dd7070Spatrick static bool canEmitDelegateCallArgs(CodeGenFunction &CGF,
2172e5dd7070Spatrick                                     const CXXConstructorDecl *Ctor,
2173e5dd7070Spatrick                                     CXXCtorType Type, CallArgList &Args) {
2174e5dd7070Spatrick   // We can't forward a variadic call.
2175e5dd7070Spatrick   if (Ctor->isVariadic())
2176e5dd7070Spatrick     return false;
2177e5dd7070Spatrick 
2178e5dd7070Spatrick   if (CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2179e5dd7070Spatrick     // If the parameters are callee-cleanup, it's not safe to forward.
2180e5dd7070Spatrick     for (auto *P : Ctor->parameters())
2181e5dd7070Spatrick       if (P->needsDestruction(CGF.getContext()))
2182e5dd7070Spatrick         return false;
2183e5dd7070Spatrick 
2184e5dd7070Spatrick     // Likewise if they're inalloca.
2185e5dd7070Spatrick     const CGFunctionInfo &Info =
2186e5dd7070Spatrick         CGF.CGM.getTypes().arrangeCXXConstructorCall(Args, Ctor, Type, 0, 0);
2187e5dd7070Spatrick     if (Info.usesInAlloca())
2188e5dd7070Spatrick       return false;
2189e5dd7070Spatrick   }
2190e5dd7070Spatrick 
2191e5dd7070Spatrick   // Anything else should be OK.
2192e5dd7070Spatrick   return true;
2193e5dd7070Spatrick }
2194e5dd7070Spatrick 
EmitCXXConstructorCall(const CXXConstructorDecl * D,CXXCtorType Type,bool ForVirtualBase,bool Delegating,Address This,CallArgList & Args,AggValueSlot::Overlap_t Overlap,SourceLocation Loc,bool NewPointerIsChecked)2195e5dd7070Spatrick void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
2196e5dd7070Spatrick                                              CXXCtorType Type,
2197e5dd7070Spatrick                                              bool ForVirtualBase,
2198e5dd7070Spatrick                                              bool Delegating,
2199e5dd7070Spatrick                                              Address This,
2200e5dd7070Spatrick                                              CallArgList &Args,
2201e5dd7070Spatrick                                              AggValueSlot::Overlap_t Overlap,
2202e5dd7070Spatrick                                              SourceLocation Loc,
2203e5dd7070Spatrick                                              bool NewPointerIsChecked) {
2204e5dd7070Spatrick   const CXXRecordDecl *ClassDecl = D->getParent();
2205e5dd7070Spatrick 
2206e5dd7070Spatrick   if (!NewPointerIsChecked)
2207e5dd7070Spatrick     EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall, Loc, This.getPointer(),
2208e5dd7070Spatrick                   getContext().getRecordType(ClassDecl), CharUnits::Zero());
2209e5dd7070Spatrick 
2210e5dd7070Spatrick   if (D->isTrivial() && D->isDefaultConstructor()) {
2211e5dd7070Spatrick     assert(Args.size() == 1 && "trivial default ctor with args");
2212e5dd7070Spatrick     return;
2213e5dd7070Spatrick   }
2214e5dd7070Spatrick 
2215e5dd7070Spatrick   // If this is a trivial constructor, just emit what's needed. If this is a
2216e5dd7070Spatrick   // union copy constructor, we must emit a memcpy, because the AST does not
2217e5dd7070Spatrick   // model that copy.
2218e5dd7070Spatrick   if (isMemcpyEquivalentSpecialMember(D)) {
2219e5dd7070Spatrick     assert(Args.size() == 2 && "unexpected argcount for trivial ctor");
2220e5dd7070Spatrick 
2221e5dd7070Spatrick     QualType SrcTy = D->getParamDecl(0)->getType().getNonReferenceType();
2222*12c85518Srobert     Address Src = Address(Args[1].getRValue(*this).getScalarVal(), ConvertTypeForMem(SrcTy),
2223ec727ea7Spatrick                                       CGM.getNaturalTypeAlignment(SrcTy));
2224e5dd7070Spatrick     LValue SrcLVal = MakeAddrLValue(Src, SrcTy);
2225e5dd7070Spatrick     QualType DestTy = getContext().getTypeDeclType(ClassDecl);
2226e5dd7070Spatrick     LValue DestLVal = MakeAddrLValue(This, DestTy);
2227e5dd7070Spatrick     EmitAggregateCopyCtor(DestLVal, SrcLVal, Overlap);
2228e5dd7070Spatrick     return;
2229e5dd7070Spatrick   }
2230e5dd7070Spatrick 
2231e5dd7070Spatrick   bool PassPrototypeArgs = true;
2232e5dd7070Spatrick   // Check whether we can actually emit the constructor before trying to do so.
2233e5dd7070Spatrick   if (auto Inherited = D->getInheritedConstructor()) {
2234e5dd7070Spatrick     PassPrototypeArgs = getTypes().inheritingCtorHasParams(Inherited, Type);
2235e5dd7070Spatrick     if (PassPrototypeArgs && !canEmitDelegateCallArgs(*this, D, Type, Args)) {
2236e5dd7070Spatrick       EmitInlinedInheritingCXXConstructorCall(D, Type, ForVirtualBase,
2237e5dd7070Spatrick                                               Delegating, Args);
2238e5dd7070Spatrick       return;
2239e5dd7070Spatrick     }
2240e5dd7070Spatrick   }
2241e5dd7070Spatrick 
2242e5dd7070Spatrick   // Insert any ABI-specific implicit constructor arguments.
2243ec727ea7Spatrick   CGCXXABI::AddedStructorArgCounts ExtraArgs =
2244e5dd7070Spatrick       CGM.getCXXABI().addImplicitConstructorArgs(*this, D, Type, ForVirtualBase,
2245e5dd7070Spatrick                                                  Delegating, Args);
2246e5dd7070Spatrick 
2247e5dd7070Spatrick   // Emit the call.
2248e5dd7070Spatrick   llvm::Constant *CalleePtr = CGM.getAddrOfCXXStructor(GlobalDecl(D, Type));
2249e5dd7070Spatrick   const CGFunctionInfo &Info = CGM.getTypes().arrangeCXXConstructorCall(
2250e5dd7070Spatrick       Args, D, Type, ExtraArgs.Prefix, ExtraArgs.Suffix, PassPrototypeArgs);
2251e5dd7070Spatrick   CGCallee Callee = CGCallee::forDirect(CalleePtr, GlobalDecl(D, Type));
2252a9ac8606Spatrick   EmitCall(Info, Callee, ReturnValueSlot(), Args, nullptr, false, Loc);
2253e5dd7070Spatrick 
2254e5dd7070Spatrick   // Generate vtable assumptions if we're constructing a complete object
2255e5dd7070Spatrick   // with a vtable.  We don't do this for base subobjects for two reasons:
2256e5dd7070Spatrick   // first, it's incorrect for classes with virtual bases, and second, we're
2257e5dd7070Spatrick   // about to overwrite the vptrs anyway.
2258e5dd7070Spatrick   // We also have to make sure if we can refer to vtable:
2259e5dd7070Spatrick   // - Otherwise we can refer to vtable if it's safe to speculatively emit.
2260e5dd7070Spatrick   // FIXME: If vtable is used by ctor/dtor, or if vtable is external and we are
2261e5dd7070Spatrick   // sure that definition of vtable is not hidden,
2262e5dd7070Spatrick   // then we are always safe to refer to it.
2263e5dd7070Spatrick   // FIXME: It looks like InstCombine is very inefficient on dealing with
2264e5dd7070Spatrick   // assumes. Make assumption loads require -fstrict-vtable-pointers temporarily.
2265e5dd7070Spatrick   if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2266e5dd7070Spatrick       ClassDecl->isDynamicClass() && Type != Ctor_Base &&
2267e5dd7070Spatrick       CGM.getCXXABI().canSpeculativelyEmitVTable(ClassDecl) &&
2268e5dd7070Spatrick       CGM.getCodeGenOpts().StrictVTablePointers)
2269e5dd7070Spatrick     EmitVTableAssumptionLoads(ClassDecl, This);
2270e5dd7070Spatrick }
2271e5dd7070Spatrick 
EmitInheritedCXXConstructorCall(const CXXConstructorDecl * D,bool ForVirtualBase,Address This,bool InheritedFromVBase,const CXXInheritedCtorInitExpr * E)2272e5dd7070Spatrick void CodeGenFunction::EmitInheritedCXXConstructorCall(
2273e5dd7070Spatrick     const CXXConstructorDecl *D, bool ForVirtualBase, Address This,
2274e5dd7070Spatrick     bool InheritedFromVBase, const CXXInheritedCtorInitExpr *E) {
2275e5dd7070Spatrick   CallArgList Args;
2276e5dd7070Spatrick   CallArg ThisArg(RValue::get(This.getPointer()), D->getThisType());
2277e5dd7070Spatrick 
2278e5dd7070Spatrick   // Forward the parameters.
2279e5dd7070Spatrick   if (InheritedFromVBase &&
2280e5dd7070Spatrick       CGM.getTarget().getCXXABI().hasConstructorVariants()) {
2281e5dd7070Spatrick     // Nothing to do; this construction is not responsible for constructing
2282e5dd7070Spatrick     // the base class containing the inherited constructor.
2283e5dd7070Spatrick     // FIXME: Can we just pass undef's for the remaining arguments if we don't
2284e5dd7070Spatrick     // have constructor variants?
2285e5dd7070Spatrick     Args.push_back(ThisArg);
2286e5dd7070Spatrick   } else if (!CXXInheritedCtorInitExprArgs.empty()) {
2287e5dd7070Spatrick     // The inheriting constructor was inlined; just inject its arguments.
2288e5dd7070Spatrick     assert(CXXInheritedCtorInitExprArgs.size() >= D->getNumParams() &&
2289e5dd7070Spatrick            "wrong number of parameters for inherited constructor call");
2290e5dd7070Spatrick     Args = CXXInheritedCtorInitExprArgs;
2291e5dd7070Spatrick     Args[0] = ThisArg;
2292e5dd7070Spatrick   } else {
2293e5dd7070Spatrick     // The inheriting constructor was not inlined. Emit delegating arguments.
2294e5dd7070Spatrick     Args.push_back(ThisArg);
2295e5dd7070Spatrick     const auto *OuterCtor = cast<CXXConstructorDecl>(CurCodeDecl);
2296e5dd7070Spatrick     assert(OuterCtor->getNumParams() == D->getNumParams());
2297e5dd7070Spatrick     assert(!OuterCtor->isVariadic() && "should have been inlined");
2298e5dd7070Spatrick 
2299e5dd7070Spatrick     for (const auto *Param : OuterCtor->parameters()) {
2300e5dd7070Spatrick       assert(getContext().hasSameUnqualifiedType(
2301e5dd7070Spatrick           OuterCtor->getParamDecl(Param->getFunctionScopeIndex())->getType(),
2302e5dd7070Spatrick           Param->getType()));
2303e5dd7070Spatrick       EmitDelegateCallArg(Args, Param, E->getLocation());
2304e5dd7070Spatrick 
2305e5dd7070Spatrick       // Forward __attribute__(pass_object_size).
2306e5dd7070Spatrick       if (Param->hasAttr<PassObjectSizeAttr>()) {
2307e5dd7070Spatrick         auto *POSParam = SizeArguments[Param];
2308e5dd7070Spatrick         assert(POSParam && "missing pass_object_size value for forwarding");
2309e5dd7070Spatrick         EmitDelegateCallArg(Args, POSParam, E->getLocation());
2310e5dd7070Spatrick       }
2311e5dd7070Spatrick     }
2312e5dd7070Spatrick   }
2313e5dd7070Spatrick 
2314e5dd7070Spatrick   EmitCXXConstructorCall(D, Ctor_Base, ForVirtualBase, /*Delegating*/false,
2315e5dd7070Spatrick                          This, Args, AggValueSlot::MayOverlap,
2316e5dd7070Spatrick                          E->getLocation(), /*NewPointerIsChecked*/true);
2317e5dd7070Spatrick }
2318e5dd7070Spatrick 
EmitInlinedInheritingCXXConstructorCall(const CXXConstructorDecl * Ctor,CXXCtorType CtorType,bool ForVirtualBase,bool Delegating,CallArgList & Args)2319e5dd7070Spatrick void CodeGenFunction::EmitInlinedInheritingCXXConstructorCall(
2320e5dd7070Spatrick     const CXXConstructorDecl *Ctor, CXXCtorType CtorType, bool ForVirtualBase,
2321e5dd7070Spatrick     bool Delegating, CallArgList &Args) {
2322e5dd7070Spatrick   GlobalDecl GD(Ctor, CtorType);
2323e5dd7070Spatrick   InlinedInheritingConstructorScope Scope(*this, GD);
2324e5dd7070Spatrick   ApplyInlineDebugLocation DebugScope(*this, GD);
2325e5dd7070Spatrick   RunCleanupsScope RunCleanups(*this);
2326e5dd7070Spatrick 
2327e5dd7070Spatrick   // Save the arguments to be passed to the inherited constructor.
2328e5dd7070Spatrick   CXXInheritedCtorInitExprArgs = Args;
2329e5dd7070Spatrick 
2330e5dd7070Spatrick   FunctionArgList Params;
2331e5dd7070Spatrick   QualType RetType = BuildFunctionArgList(CurGD, Params);
2332e5dd7070Spatrick   FnRetTy = RetType;
2333e5dd7070Spatrick 
2334e5dd7070Spatrick   // Insert any ABI-specific implicit constructor arguments.
2335e5dd7070Spatrick   CGM.getCXXABI().addImplicitConstructorArgs(*this, Ctor, CtorType,
2336e5dd7070Spatrick                                              ForVirtualBase, Delegating, Args);
2337e5dd7070Spatrick 
2338e5dd7070Spatrick   // Emit a simplified prolog. We only need to emit the implicit params.
2339e5dd7070Spatrick   assert(Args.size() >= Params.size() && "too few arguments for call");
2340e5dd7070Spatrick   for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2341e5dd7070Spatrick     if (I < Params.size() && isa<ImplicitParamDecl>(Params[I])) {
2342e5dd7070Spatrick       const RValue &RV = Args[I].getRValue(*this);
2343e5dd7070Spatrick       assert(!RV.isComplex() && "complex indirect params not supported");
2344e5dd7070Spatrick       ParamValue Val = RV.isScalar()
2345e5dd7070Spatrick                            ? ParamValue::forDirect(RV.getScalarVal())
2346e5dd7070Spatrick                            : ParamValue::forIndirect(RV.getAggregateAddress());
2347e5dd7070Spatrick       EmitParmDecl(*Params[I], Val, I + 1);
2348e5dd7070Spatrick     }
2349e5dd7070Spatrick   }
2350e5dd7070Spatrick 
2351e5dd7070Spatrick   // Create a return value slot if the ABI implementation wants one.
2352e5dd7070Spatrick   // FIXME: This is dumb, we should ask the ABI not to try to set the return
2353e5dd7070Spatrick   // value instead.
2354e5dd7070Spatrick   if (!RetType->isVoidType())
2355e5dd7070Spatrick     ReturnValue = CreateIRTemp(RetType, "retval.inhctor");
2356e5dd7070Spatrick 
2357e5dd7070Spatrick   CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
2358e5dd7070Spatrick   CXXThisValue = CXXABIThisValue;
2359e5dd7070Spatrick 
2360e5dd7070Spatrick   // Directly emit the constructor initializers.
2361e5dd7070Spatrick   EmitCtorPrologue(Ctor, CtorType, Params);
2362e5dd7070Spatrick }
2363e5dd7070Spatrick 
EmitVTableAssumptionLoad(const VPtr & Vptr,Address This)2364e5dd7070Spatrick void CodeGenFunction::EmitVTableAssumptionLoad(const VPtr &Vptr, Address This) {
2365e5dd7070Spatrick   llvm::Value *VTableGlobal =
2366e5dd7070Spatrick       CGM.getCXXABI().getVTableAddressPoint(Vptr.Base, Vptr.VTableClass);
2367e5dd7070Spatrick   if (!VTableGlobal)
2368e5dd7070Spatrick     return;
2369e5dd7070Spatrick 
2370e5dd7070Spatrick   // We can just use the base offset in the complete class.
2371e5dd7070Spatrick   CharUnits NonVirtualOffset = Vptr.Base.getBaseOffset();
2372e5dd7070Spatrick 
2373e5dd7070Spatrick   if (!NonVirtualOffset.isZero())
2374e5dd7070Spatrick     This =
2375e5dd7070Spatrick         ApplyNonVirtualAndVirtualOffset(*this, This, NonVirtualOffset, nullptr,
2376e5dd7070Spatrick                                         Vptr.VTableClass, Vptr.NearestVBase);
2377e5dd7070Spatrick 
2378e5dd7070Spatrick   llvm::Value *VPtrValue =
2379e5dd7070Spatrick       GetVTablePtr(This, VTableGlobal->getType(), Vptr.VTableClass);
2380e5dd7070Spatrick   llvm::Value *Cmp =
2381e5dd7070Spatrick       Builder.CreateICmpEQ(VPtrValue, VTableGlobal, "cmp.vtables");
2382e5dd7070Spatrick   Builder.CreateAssumption(Cmp);
2383e5dd7070Spatrick }
2384e5dd7070Spatrick 
EmitVTableAssumptionLoads(const CXXRecordDecl * ClassDecl,Address This)2385e5dd7070Spatrick void CodeGenFunction::EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl,
2386e5dd7070Spatrick                                                 Address This) {
2387e5dd7070Spatrick   if (CGM.getCXXABI().doStructorsInitializeVPtrs(ClassDecl))
2388e5dd7070Spatrick     for (const VPtr &Vptr : getVTablePointers(ClassDecl))
2389e5dd7070Spatrick       EmitVTableAssumptionLoad(Vptr, This);
2390e5dd7070Spatrick }
2391e5dd7070Spatrick 
2392e5dd7070Spatrick void
EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl * D,Address This,Address Src,const CXXConstructExpr * E)2393e5dd7070Spatrick CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
2394e5dd7070Spatrick                                                 Address This, Address Src,
2395e5dd7070Spatrick                                                 const CXXConstructExpr *E) {
2396e5dd7070Spatrick   const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
2397e5dd7070Spatrick 
2398e5dd7070Spatrick   CallArgList Args;
2399e5dd7070Spatrick 
2400e5dd7070Spatrick   // Push the this ptr.
2401e5dd7070Spatrick   Args.add(RValue::get(This.getPointer()), D->getThisType());
2402e5dd7070Spatrick 
2403e5dd7070Spatrick   // Push the src ptr.
2404e5dd7070Spatrick   QualType QT = *(FPT->param_type_begin());
2405e5dd7070Spatrick   llvm::Type *t = CGM.getTypes().ConvertType(QT);
2406*12c85518Srobert   llvm::Value *SrcVal = Builder.CreateBitCast(Src.getPointer(), t);
2407*12c85518Srobert   Args.add(RValue::get(SrcVal), QT);
2408e5dd7070Spatrick 
2409e5dd7070Spatrick   // Skip over first argument (Src).
2410e5dd7070Spatrick   EmitCallArgs(Args, FPT, drop_begin(E->arguments(), 1), E->getConstructor(),
2411e5dd7070Spatrick                /*ParamsToSkip*/ 1);
2412e5dd7070Spatrick 
2413e5dd7070Spatrick   EmitCXXConstructorCall(D, Ctor_Complete, /*ForVirtualBase*/false,
2414e5dd7070Spatrick                          /*Delegating*/false, This, Args,
2415e5dd7070Spatrick                          AggValueSlot::MayOverlap, E->getExprLoc(),
2416e5dd7070Spatrick                          /*NewPointerIsChecked*/false);
2417e5dd7070Spatrick }
2418e5dd7070Spatrick 
2419e5dd7070Spatrick void
EmitDelegateCXXConstructorCall(const CXXConstructorDecl * Ctor,CXXCtorType CtorType,const FunctionArgList & Args,SourceLocation Loc)2420e5dd7070Spatrick CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
2421e5dd7070Spatrick                                                 CXXCtorType CtorType,
2422e5dd7070Spatrick                                                 const FunctionArgList &Args,
2423e5dd7070Spatrick                                                 SourceLocation Loc) {
2424e5dd7070Spatrick   CallArgList DelegateArgs;
2425e5dd7070Spatrick 
2426e5dd7070Spatrick   FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
2427e5dd7070Spatrick   assert(I != E && "no parameters to constructor");
2428e5dd7070Spatrick 
2429e5dd7070Spatrick   // this
2430e5dd7070Spatrick   Address This = LoadCXXThisAddress();
2431e5dd7070Spatrick   DelegateArgs.add(RValue::get(This.getPointer()), (*I)->getType());
2432e5dd7070Spatrick   ++I;
2433e5dd7070Spatrick 
2434e5dd7070Spatrick   // FIXME: The location of the VTT parameter in the parameter list is
2435e5dd7070Spatrick   // specific to the Itanium ABI and shouldn't be hardcoded here.
2436e5dd7070Spatrick   if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
2437e5dd7070Spatrick     assert(I != E && "cannot skip vtt parameter, already done with args");
2438e5dd7070Spatrick     assert((*I)->getType()->isPointerType() &&
2439e5dd7070Spatrick            "skipping parameter not of vtt type");
2440e5dd7070Spatrick     ++I;
2441e5dd7070Spatrick   }
2442e5dd7070Spatrick 
2443e5dd7070Spatrick   // Explicit arguments.
2444e5dd7070Spatrick   for (; I != E; ++I) {
2445e5dd7070Spatrick     const VarDecl *param = *I;
2446e5dd7070Spatrick     // FIXME: per-argument source location
2447e5dd7070Spatrick     EmitDelegateCallArg(DelegateArgs, param, Loc);
2448e5dd7070Spatrick   }
2449e5dd7070Spatrick 
2450e5dd7070Spatrick   EmitCXXConstructorCall(Ctor, CtorType, /*ForVirtualBase=*/false,
2451e5dd7070Spatrick                          /*Delegating=*/true, This, DelegateArgs,
2452e5dd7070Spatrick                          AggValueSlot::MayOverlap, Loc,
2453e5dd7070Spatrick                          /*NewPointerIsChecked=*/true);
2454e5dd7070Spatrick }
2455e5dd7070Spatrick 
2456e5dd7070Spatrick namespace {
2457e5dd7070Spatrick   struct CallDelegatingCtorDtor final : EHScopeStack::Cleanup {
2458e5dd7070Spatrick     const CXXDestructorDecl *Dtor;
2459e5dd7070Spatrick     Address Addr;
2460e5dd7070Spatrick     CXXDtorType Type;
2461e5dd7070Spatrick 
CallDelegatingCtorDtor__anonda710d950511::CallDelegatingCtorDtor2462e5dd7070Spatrick     CallDelegatingCtorDtor(const CXXDestructorDecl *D, Address Addr,
2463e5dd7070Spatrick                            CXXDtorType Type)
2464e5dd7070Spatrick       : Dtor(D), Addr(Addr), Type(Type) {}
2465e5dd7070Spatrick 
Emit__anonda710d950511::CallDelegatingCtorDtor2466e5dd7070Spatrick     void Emit(CodeGenFunction &CGF, Flags flags) override {
2467e5dd7070Spatrick       // We are calling the destructor from within the constructor.
2468e5dd7070Spatrick       // Therefore, "this" should have the expected type.
2469e5dd7070Spatrick       QualType ThisTy = Dtor->getThisObjectType();
2470e5dd7070Spatrick       CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
2471e5dd7070Spatrick                                 /*Delegating=*/true, Addr, ThisTy);
2472e5dd7070Spatrick     }
2473e5dd7070Spatrick   };
2474e5dd7070Spatrick } // end anonymous namespace
2475e5dd7070Spatrick 
2476e5dd7070Spatrick void
EmitDelegatingCXXConstructorCall(const CXXConstructorDecl * Ctor,const FunctionArgList & Args)2477e5dd7070Spatrick CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
2478e5dd7070Spatrick                                                   const FunctionArgList &Args) {
2479e5dd7070Spatrick   assert(Ctor->isDelegatingConstructor());
2480e5dd7070Spatrick 
2481e5dd7070Spatrick   Address ThisPtr = LoadCXXThisAddress();
2482e5dd7070Spatrick 
2483e5dd7070Spatrick   AggValueSlot AggSlot =
2484e5dd7070Spatrick     AggValueSlot::forAddr(ThisPtr, Qualifiers(),
2485e5dd7070Spatrick                           AggValueSlot::IsDestructed,
2486e5dd7070Spatrick                           AggValueSlot::DoesNotNeedGCBarriers,
2487e5dd7070Spatrick                           AggValueSlot::IsNotAliased,
2488e5dd7070Spatrick                           AggValueSlot::MayOverlap,
2489e5dd7070Spatrick                           AggValueSlot::IsNotZeroed,
2490e5dd7070Spatrick                           // Checks are made by the code that calls constructor.
2491e5dd7070Spatrick                           AggValueSlot::IsSanitizerChecked);
2492e5dd7070Spatrick 
2493e5dd7070Spatrick   EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
2494e5dd7070Spatrick 
2495e5dd7070Spatrick   const CXXRecordDecl *ClassDecl = Ctor->getParent();
2496e5dd7070Spatrick   if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
2497e5dd7070Spatrick     CXXDtorType Type =
2498e5dd7070Spatrick       CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
2499e5dd7070Spatrick 
2500e5dd7070Spatrick     EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
2501e5dd7070Spatrick                                                 ClassDecl->getDestructor(),
2502e5dd7070Spatrick                                                 ThisPtr, Type);
2503e5dd7070Spatrick   }
2504e5dd7070Spatrick }
2505e5dd7070Spatrick 
EmitCXXDestructorCall(const CXXDestructorDecl * DD,CXXDtorType Type,bool ForVirtualBase,bool Delegating,Address This,QualType ThisTy)2506e5dd7070Spatrick void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
2507e5dd7070Spatrick                                             CXXDtorType Type,
2508e5dd7070Spatrick                                             bool ForVirtualBase,
2509e5dd7070Spatrick                                             bool Delegating, Address This,
2510e5dd7070Spatrick                                             QualType ThisTy) {
2511e5dd7070Spatrick   CGM.getCXXABI().EmitDestructorCall(*this, DD, Type, ForVirtualBase,
2512e5dd7070Spatrick                                      Delegating, This, ThisTy);
2513e5dd7070Spatrick }
2514e5dd7070Spatrick 
2515e5dd7070Spatrick namespace {
2516e5dd7070Spatrick   struct CallLocalDtor final : EHScopeStack::Cleanup {
2517e5dd7070Spatrick     const CXXDestructorDecl *Dtor;
2518e5dd7070Spatrick     Address Addr;
2519e5dd7070Spatrick     QualType Ty;
2520e5dd7070Spatrick 
CallLocalDtor__anonda710d950611::CallLocalDtor2521e5dd7070Spatrick     CallLocalDtor(const CXXDestructorDecl *D, Address Addr, QualType Ty)
2522e5dd7070Spatrick         : Dtor(D), Addr(Addr), Ty(Ty) {}
2523e5dd7070Spatrick 
Emit__anonda710d950611::CallLocalDtor2524e5dd7070Spatrick     void Emit(CodeGenFunction &CGF, Flags flags) override {
2525e5dd7070Spatrick       CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
2526e5dd7070Spatrick                                 /*ForVirtualBase=*/false,
2527e5dd7070Spatrick                                 /*Delegating=*/false, Addr, Ty);
2528e5dd7070Spatrick     }
2529e5dd7070Spatrick   };
2530e5dd7070Spatrick } // end anonymous namespace
2531e5dd7070Spatrick 
PushDestructorCleanup(const CXXDestructorDecl * D,QualType T,Address Addr)2532e5dd7070Spatrick void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
2533e5dd7070Spatrick                                             QualType T, Address Addr) {
2534e5dd7070Spatrick   EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr, T);
2535e5dd7070Spatrick }
2536e5dd7070Spatrick 
PushDestructorCleanup(QualType T,Address Addr)2537e5dd7070Spatrick void CodeGenFunction::PushDestructorCleanup(QualType T, Address Addr) {
2538e5dd7070Spatrick   CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
2539e5dd7070Spatrick   if (!ClassDecl) return;
2540e5dd7070Spatrick   if (ClassDecl->hasTrivialDestructor()) return;
2541e5dd7070Spatrick 
2542e5dd7070Spatrick   const CXXDestructorDecl *D = ClassDecl->getDestructor();
2543e5dd7070Spatrick   assert(D && D->isUsed() && "destructor not marked as used!");
2544e5dd7070Spatrick   PushDestructorCleanup(D, T, Addr);
2545e5dd7070Spatrick }
2546e5dd7070Spatrick 
InitializeVTablePointer(const VPtr & Vptr)2547e5dd7070Spatrick void CodeGenFunction::InitializeVTablePointer(const VPtr &Vptr) {
2548e5dd7070Spatrick   // Compute the address point.
2549e5dd7070Spatrick   llvm::Value *VTableAddressPoint =
2550e5dd7070Spatrick       CGM.getCXXABI().getVTableAddressPointInStructor(
2551e5dd7070Spatrick           *this, Vptr.VTableClass, Vptr.Base, Vptr.NearestVBase);
2552e5dd7070Spatrick 
2553e5dd7070Spatrick   if (!VTableAddressPoint)
2554e5dd7070Spatrick     return;
2555e5dd7070Spatrick 
2556e5dd7070Spatrick   // Compute where to store the address point.
2557e5dd7070Spatrick   llvm::Value *VirtualOffset = nullptr;
2558e5dd7070Spatrick   CharUnits NonVirtualOffset = CharUnits::Zero();
2559e5dd7070Spatrick 
2560e5dd7070Spatrick   if (CGM.getCXXABI().isVirtualOffsetNeededForVTableField(*this, Vptr)) {
2561e5dd7070Spatrick     // We need to use the virtual base offset offset because the virtual base
2562e5dd7070Spatrick     // might have a different offset in the most derived class.
2563e5dd7070Spatrick 
2564e5dd7070Spatrick     VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(
2565e5dd7070Spatrick         *this, LoadCXXThisAddress(), Vptr.VTableClass, Vptr.NearestVBase);
2566e5dd7070Spatrick     NonVirtualOffset = Vptr.OffsetFromNearestVBase;
2567e5dd7070Spatrick   } else {
2568e5dd7070Spatrick     // We can just use the base offset in the complete class.
2569e5dd7070Spatrick     NonVirtualOffset = Vptr.Base.getBaseOffset();
2570e5dd7070Spatrick   }
2571e5dd7070Spatrick 
2572e5dd7070Spatrick   // Apply the offsets.
2573e5dd7070Spatrick   Address VTableField = LoadCXXThisAddress();
2574e5dd7070Spatrick   if (!NonVirtualOffset.isZero() || VirtualOffset)
2575e5dd7070Spatrick     VTableField = ApplyNonVirtualAndVirtualOffset(
2576e5dd7070Spatrick         *this, VTableField, NonVirtualOffset, VirtualOffset, Vptr.VTableClass,
2577e5dd7070Spatrick         Vptr.NearestVBase);
2578e5dd7070Spatrick 
2579e5dd7070Spatrick   // Finally, store the address point. Use the same LLVM types as the field to
2580e5dd7070Spatrick   // support optimization.
2581a9ac8606Spatrick   unsigned GlobalsAS = CGM.getDataLayout().getDefaultGlobalsAddressSpace();
2582a9ac8606Spatrick   unsigned ProgAS = CGM.getDataLayout().getProgramAddressSpace();
2583e5dd7070Spatrick   llvm::Type *VTablePtrTy =
2584e5dd7070Spatrick       llvm::FunctionType::get(CGM.Int32Ty, /*isVarArg=*/true)
2585a9ac8606Spatrick           ->getPointerTo(ProgAS)
2586a9ac8606Spatrick           ->getPointerTo(GlobalsAS);
2587*12c85518Srobert   // vtable field is derived from `this` pointer, therefore they should be in
2588*12c85518Srobert   // the same addr space. Note that this might not be LLVM address space 0.
2589*12c85518Srobert   VTableField = Builder.CreateElementBitCast(VTableField, VTablePtrTy);
2590*12c85518Srobert   VTableAddressPoint = Builder.CreateBitCast(VTableAddressPoint, VTablePtrTy);
2591e5dd7070Spatrick 
2592e5dd7070Spatrick   llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
2593e5dd7070Spatrick   TBAAAccessInfo TBAAInfo = CGM.getTBAAVTablePtrAccessInfo(VTablePtrTy);
2594e5dd7070Spatrick   CGM.DecorateInstructionWithTBAA(Store, TBAAInfo);
2595e5dd7070Spatrick   if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2596e5dd7070Spatrick       CGM.getCodeGenOpts().StrictVTablePointers)
2597e5dd7070Spatrick     CGM.DecorateInstructionWithInvariantGroup(Store, Vptr.VTableClass);
2598e5dd7070Spatrick }
2599e5dd7070Spatrick 
2600e5dd7070Spatrick CodeGenFunction::VPtrsVector
getVTablePointers(const CXXRecordDecl * VTableClass)2601e5dd7070Spatrick CodeGenFunction::getVTablePointers(const CXXRecordDecl *VTableClass) {
2602e5dd7070Spatrick   CodeGenFunction::VPtrsVector VPtrsResult;
2603e5dd7070Spatrick   VisitedVirtualBasesSetTy VBases;
2604e5dd7070Spatrick   getVTablePointers(BaseSubobject(VTableClass, CharUnits::Zero()),
2605e5dd7070Spatrick                     /*NearestVBase=*/nullptr,
2606e5dd7070Spatrick                     /*OffsetFromNearestVBase=*/CharUnits::Zero(),
2607e5dd7070Spatrick                     /*BaseIsNonVirtualPrimaryBase=*/false, VTableClass, VBases,
2608e5dd7070Spatrick                     VPtrsResult);
2609e5dd7070Spatrick   return VPtrsResult;
2610e5dd7070Spatrick }
2611e5dd7070Spatrick 
getVTablePointers(BaseSubobject Base,const CXXRecordDecl * NearestVBase,CharUnits OffsetFromNearestVBase,bool BaseIsNonVirtualPrimaryBase,const CXXRecordDecl * VTableClass,VisitedVirtualBasesSetTy & VBases,VPtrsVector & Vptrs)2612e5dd7070Spatrick void CodeGenFunction::getVTablePointers(BaseSubobject Base,
2613e5dd7070Spatrick                                         const CXXRecordDecl *NearestVBase,
2614e5dd7070Spatrick                                         CharUnits OffsetFromNearestVBase,
2615e5dd7070Spatrick                                         bool BaseIsNonVirtualPrimaryBase,
2616e5dd7070Spatrick                                         const CXXRecordDecl *VTableClass,
2617e5dd7070Spatrick                                         VisitedVirtualBasesSetTy &VBases,
2618e5dd7070Spatrick                                         VPtrsVector &Vptrs) {
2619e5dd7070Spatrick   // If this base is a non-virtual primary base the address point has already
2620e5dd7070Spatrick   // been set.
2621e5dd7070Spatrick   if (!BaseIsNonVirtualPrimaryBase) {
2622e5dd7070Spatrick     // Initialize the vtable pointer for this base.
2623e5dd7070Spatrick     VPtr Vptr = {Base, NearestVBase, OffsetFromNearestVBase, VTableClass};
2624e5dd7070Spatrick     Vptrs.push_back(Vptr);
2625e5dd7070Spatrick   }
2626e5dd7070Spatrick 
2627e5dd7070Spatrick   const CXXRecordDecl *RD = Base.getBase();
2628e5dd7070Spatrick 
2629e5dd7070Spatrick   // Traverse bases.
2630e5dd7070Spatrick   for (const auto &I : RD->bases()) {
2631e5dd7070Spatrick     auto *BaseDecl =
2632e5dd7070Spatrick         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
2633e5dd7070Spatrick 
2634e5dd7070Spatrick     // Ignore classes without a vtable.
2635e5dd7070Spatrick     if (!BaseDecl->isDynamicClass())
2636e5dd7070Spatrick       continue;
2637e5dd7070Spatrick 
2638e5dd7070Spatrick     CharUnits BaseOffset;
2639e5dd7070Spatrick     CharUnits BaseOffsetFromNearestVBase;
2640e5dd7070Spatrick     bool BaseDeclIsNonVirtualPrimaryBase;
2641e5dd7070Spatrick 
2642e5dd7070Spatrick     if (I.isVirtual()) {
2643e5dd7070Spatrick       // Check if we've visited this virtual base before.
2644e5dd7070Spatrick       if (!VBases.insert(BaseDecl).second)
2645e5dd7070Spatrick         continue;
2646e5dd7070Spatrick 
2647e5dd7070Spatrick       const ASTRecordLayout &Layout =
2648e5dd7070Spatrick         getContext().getASTRecordLayout(VTableClass);
2649e5dd7070Spatrick 
2650e5dd7070Spatrick       BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
2651e5dd7070Spatrick       BaseOffsetFromNearestVBase = CharUnits::Zero();
2652e5dd7070Spatrick       BaseDeclIsNonVirtualPrimaryBase = false;
2653e5dd7070Spatrick     } else {
2654e5dd7070Spatrick       const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
2655e5dd7070Spatrick 
2656e5dd7070Spatrick       BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
2657e5dd7070Spatrick       BaseOffsetFromNearestVBase =
2658e5dd7070Spatrick         OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
2659e5dd7070Spatrick       BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
2660e5dd7070Spatrick     }
2661e5dd7070Spatrick 
2662e5dd7070Spatrick     getVTablePointers(
2663e5dd7070Spatrick         BaseSubobject(BaseDecl, BaseOffset),
2664e5dd7070Spatrick         I.isVirtual() ? BaseDecl : NearestVBase, BaseOffsetFromNearestVBase,
2665e5dd7070Spatrick         BaseDeclIsNonVirtualPrimaryBase, VTableClass, VBases, Vptrs);
2666e5dd7070Spatrick   }
2667e5dd7070Spatrick }
2668e5dd7070Spatrick 
InitializeVTablePointers(const CXXRecordDecl * RD)2669e5dd7070Spatrick void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
2670e5dd7070Spatrick   // Ignore classes without a vtable.
2671e5dd7070Spatrick   if (!RD->isDynamicClass())
2672e5dd7070Spatrick     return;
2673e5dd7070Spatrick 
2674e5dd7070Spatrick   // Initialize the vtable pointers for this class and all of its bases.
2675e5dd7070Spatrick   if (CGM.getCXXABI().doStructorsInitializeVPtrs(RD))
2676e5dd7070Spatrick     for (const VPtr &Vptr : getVTablePointers(RD))
2677e5dd7070Spatrick       InitializeVTablePointer(Vptr);
2678e5dd7070Spatrick 
2679e5dd7070Spatrick   if (RD->getNumVBases())
2680e5dd7070Spatrick     CGM.getCXXABI().initializeHiddenVirtualInheritanceMembers(*this, RD);
2681e5dd7070Spatrick }
2682e5dd7070Spatrick 
GetVTablePtr(Address This,llvm::Type * VTableTy,const CXXRecordDecl * RD)2683e5dd7070Spatrick llvm::Value *CodeGenFunction::GetVTablePtr(Address This,
2684e5dd7070Spatrick                                            llvm::Type *VTableTy,
2685e5dd7070Spatrick                                            const CXXRecordDecl *RD) {
2686e5dd7070Spatrick   Address VTablePtrSrc = Builder.CreateElementBitCast(This, VTableTy);
2687e5dd7070Spatrick   llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
2688e5dd7070Spatrick   TBAAAccessInfo TBAAInfo = CGM.getTBAAVTablePtrAccessInfo(VTableTy);
2689e5dd7070Spatrick   CGM.DecorateInstructionWithTBAA(VTable, TBAAInfo);
2690e5dd7070Spatrick 
2691e5dd7070Spatrick   if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2692e5dd7070Spatrick       CGM.getCodeGenOpts().StrictVTablePointers)
2693e5dd7070Spatrick     CGM.DecorateInstructionWithInvariantGroup(VTable, RD);
2694e5dd7070Spatrick 
2695e5dd7070Spatrick   return VTable;
2696e5dd7070Spatrick }
2697e5dd7070Spatrick 
2698e5dd7070Spatrick // If a class has a single non-virtual base and does not introduce or override
2699e5dd7070Spatrick // virtual member functions or fields, it will have the same layout as its base.
2700e5dd7070Spatrick // This function returns the least derived such class.
2701e5dd7070Spatrick //
2702e5dd7070Spatrick // Casting an instance of a base class to such a derived class is technically
2703e5dd7070Spatrick // undefined behavior, but it is a relatively common hack for introducing member
2704e5dd7070Spatrick // functions on class instances with specific properties (e.g. llvm::Operator)
2705e5dd7070Spatrick // that works under most compilers and should not have security implications, so
2706e5dd7070Spatrick // we allow it by default. It can be disabled with -fsanitize=cfi-cast-strict.
2707e5dd7070Spatrick static const CXXRecordDecl *
LeastDerivedClassWithSameLayout(const CXXRecordDecl * RD)2708e5dd7070Spatrick LeastDerivedClassWithSameLayout(const CXXRecordDecl *RD) {
2709e5dd7070Spatrick   if (!RD->field_empty())
2710e5dd7070Spatrick     return RD;
2711e5dd7070Spatrick 
2712e5dd7070Spatrick   if (RD->getNumVBases() != 0)
2713e5dd7070Spatrick     return RD;
2714e5dd7070Spatrick 
2715e5dd7070Spatrick   if (RD->getNumBases() != 1)
2716e5dd7070Spatrick     return RD;
2717e5dd7070Spatrick 
2718e5dd7070Spatrick   for (const CXXMethodDecl *MD : RD->methods()) {
2719e5dd7070Spatrick     if (MD->isVirtual()) {
2720e5dd7070Spatrick       // Virtual member functions are only ok if they are implicit destructors
2721e5dd7070Spatrick       // because the implicit destructor will have the same semantics as the
2722e5dd7070Spatrick       // base class's destructor if no fields are added.
2723e5dd7070Spatrick       if (isa<CXXDestructorDecl>(MD) && MD->isImplicit())
2724e5dd7070Spatrick         continue;
2725e5dd7070Spatrick       return RD;
2726e5dd7070Spatrick     }
2727e5dd7070Spatrick   }
2728e5dd7070Spatrick 
2729e5dd7070Spatrick   return LeastDerivedClassWithSameLayout(
2730e5dd7070Spatrick       RD->bases_begin()->getType()->getAsCXXRecordDecl());
2731e5dd7070Spatrick }
2732e5dd7070Spatrick 
EmitTypeMetadataCodeForVCall(const CXXRecordDecl * RD,llvm::Value * VTable,SourceLocation Loc)2733e5dd7070Spatrick void CodeGenFunction::EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD,
2734e5dd7070Spatrick                                                    llvm::Value *VTable,
2735e5dd7070Spatrick                                                    SourceLocation Loc) {
2736e5dd7070Spatrick   if (SanOpts.has(SanitizerKind::CFIVCall))
2737e5dd7070Spatrick     EmitVTablePtrCheckForCall(RD, VTable, CodeGenFunction::CFITCK_VCall, Loc);
2738e5dd7070Spatrick   else if (CGM.getCodeGenOpts().WholeProgramVTables &&
2739*12c85518Srobert            // Don't insert type test assumes if we are forcing public
2740ec727ea7Spatrick            // visibility.
2741*12c85518Srobert            !CGM.AlwaysHasLTOVisibilityPublic(RD)) {
2742*12c85518Srobert     QualType Ty = QualType(RD->getTypeForDecl(), 0);
2743*12c85518Srobert     llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(Ty);
2744e5dd7070Spatrick     llvm::Value *TypeId =
2745e5dd7070Spatrick         llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD);
2746e5dd7070Spatrick 
2747e5dd7070Spatrick     llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
2748*12c85518Srobert     // If we already know that the call has hidden LTO visibility, emit
2749*12c85518Srobert     // @llvm.type.test(). Otherwise emit @llvm.public.type.test(), which WPD
2750*12c85518Srobert     // will convert to @llvm.type.test() if we assert at link time that we have
2751*12c85518Srobert     // whole program visibility.
2752*12c85518Srobert     llvm::Intrinsic::ID IID = CGM.HasHiddenLTOVisibility(RD)
2753*12c85518Srobert                                   ? llvm::Intrinsic::type_test
2754*12c85518Srobert                                   : llvm::Intrinsic::public_type_test;
2755e5dd7070Spatrick     llvm::Value *TypeTest =
2756*12c85518Srobert         Builder.CreateCall(CGM.getIntrinsic(IID), {CastedVTable, TypeId});
2757e5dd7070Spatrick     Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::assume), TypeTest);
2758e5dd7070Spatrick   }
2759e5dd7070Spatrick }
2760e5dd7070Spatrick 
EmitVTablePtrCheckForCall(const CXXRecordDecl * RD,llvm::Value * VTable,CFITypeCheckKind TCK,SourceLocation Loc)2761e5dd7070Spatrick void CodeGenFunction::EmitVTablePtrCheckForCall(const CXXRecordDecl *RD,
2762e5dd7070Spatrick                                                 llvm::Value *VTable,
2763e5dd7070Spatrick                                                 CFITypeCheckKind TCK,
2764e5dd7070Spatrick                                                 SourceLocation Loc) {
2765e5dd7070Spatrick   if (!SanOpts.has(SanitizerKind::CFICastStrict))
2766e5dd7070Spatrick     RD = LeastDerivedClassWithSameLayout(RD);
2767e5dd7070Spatrick 
2768e5dd7070Spatrick   EmitVTablePtrCheck(RD, VTable, TCK, Loc);
2769e5dd7070Spatrick }
2770e5dd7070Spatrick 
EmitVTablePtrCheckForCast(QualType T,Address Derived,bool MayBeNull,CFITypeCheckKind TCK,SourceLocation Loc)2771*12c85518Srobert void CodeGenFunction::EmitVTablePtrCheckForCast(QualType T, Address Derived,
2772e5dd7070Spatrick                                                 bool MayBeNull,
2773e5dd7070Spatrick                                                 CFITypeCheckKind TCK,
2774e5dd7070Spatrick                                                 SourceLocation Loc) {
2775e5dd7070Spatrick   if (!getLangOpts().CPlusPlus)
2776e5dd7070Spatrick     return;
2777e5dd7070Spatrick 
2778e5dd7070Spatrick   auto *ClassTy = T->getAs<RecordType>();
2779e5dd7070Spatrick   if (!ClassTy)
2780e5dd7070Spatrick     return;
2781e5dd7070Spatrick 
2782e5dd7070Spatrick   const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassTy->getDecl());
2783e5dd7070Spatrick 
2784e5dd7070Spatrick   if (!ClassDecl->isCompleteDefinition() || !ClassDecl->isDynamicClass())
2785e5dd7070Spatrick     return;
2786e5dd7070Spatrick 
2787e5dd7070Spatrick   if (!SanOpts.has(SanitizerKind::CFICastStrict))
2788e5dd7070Spatrick     ClassDecl = LeastDerivedClassWithSameLayout(ClassDecl);
2789e5dd7070Spatrick 
2790e5dd7070Spatrick   llvm::BasicBlock *ContBlock = nullptr;
2791e5dd7070Spatrick 
2792e5dd7070Spatrick   if (MayBeNull) {
2793e5dd7070Spatrick     llvm::Value *DerivedNotNull =
2794*12c85518Srobert         Builder.CreateIsNotNull(Derived.getPointer(), "cast.nonnull");
2795e5dd7070Spatrick 
2796e5dd7070Spatrick     llvm::BasicBlock *CheckBlock = createBasicBlock("cast.check");
2797e5dd7070Spatrick     ContBlock = createBasicBlock("cast.cont");
2798e5dd7070Spatrick 
2799e5dd7070Spatrick     Builder.CreateCondBr(DerivedNotNull, CheckBlock, ContBlock);
2800e5dd7070Spatrick 
2801e5dd7070Spatrick     EmitBlock(CheckBlock);
2802e5dd7070Spatrick   }
2803e5dd7070Spatrick 
2804e5dd7070Spatrick   llvm::Value *VTable;
2805*12c85518Srobert   std::tie(VTable, ClassDecl) =
2806*12c85518Srobert       CGM.getCXXABI().LoadVTablePtr(*this, Derived, ClassDecl);
2807e5dd7070Spatrick 
2808e5dd7070Spatrick   EmitVTablePtrCheck(ClassDecl, VTable, TCK, Loc);
2809e5dd7070Spatrick 
2810e5dd7070Spatrick   if (MayBeNull) {
2811e5dd7070Spatrick     Builder.CreateBr(ContBlock);
2812e5dd7070Spatrick     EmitBlock(ContBlock);
2813e5dd7070Spatrick   }
2814e5dd7070Spatrick }
2815e5dd7070Spatrick 
EmitVTablePtrCheck(const CXXRecordDecl * RD,llvm::Value * VTable,CFITypeCheckKind TCK,SourceLocation Loc)2816e5dd7070Spatrick void CodeGenFunction::EmitVTablePtrCheck(const CXXRecordDecl *RD,
2817e5dd7070Spatrick                                          llvm::Value *VTable,
2818e5dd7070Spatrick                                          CFITypeCheckKind TCK,
2819e5dd7070Spatrick                                          SourceLocation Loc) {
2820e5dd7070Spatrick   if (!CGM.getCodeGenOpts().SanitizeCfiCrossDso &&
2821e5dd7070Spatrick       !CGM.HasHiddenLTOVisibility(RD))
2822e5dd7070Spatrick     return;
2823e5dd7070Spatrick 
2824e5dd7070Spatrick   SanitizerMask M;
2825e5dd7070Spatrick   llvm::SanitizerStatKind SSK;
2826e5dd7070Spatrick   switch (TCK) {
2827e5dd7070Spatrick   case CFITCK_VCall:
2828e5dd7070Spatrick     M = SanitizerKind::CFIVCall;
2829e5dd7070Spatrick     SSK = llvm::SanStat_CFI_VCall;
2830e5dd7070Spatrick     break;
2831e5dd7070Spatrick   case CFITCK_NVCall:
2832e5dd7070Spatrick     M = SanitizerKind::CFINVCall;
2833e5dd7070Spatrick     SSK = llvm::SanStat_CFI_NVCall;
2834e5dd7070Spatrick     break;
2835e5dd7070Spatrick   case CFITCK_DerivedCast:
2836e5dd7070Spatrick     M = SanitizerKind::CFIDerivedCast;
2837e5dd7070Spatrick     SSK = llvm::SanStat_CFI_DerivedCast;
2838e5dd7070Spatrick     break;
2839e5dd7070Spatrick   case CFITCK_UnrelatedCast:
2840e5dd7070Spatrick     M = SanitizerKind::CFIUnrelatedCast;
2841e5dd7070Spatrick     SSK = llvm::SanStat_CFI_UnrelatedCast;
2842e5dd7070Spatrick     break;
2843e5dd7070Spatrick   case CFITCK_ICall:
2844e5dd7070Spatrick   case CFITCK_NVMFCall:
2845e5dd7070Spatrick   case CFITCK_VMFCall:
2846e5dd7070Spatrick     llvm_unreachable("unexpected sanitizer kind");
2847e5dd7070Spatrick   }
2848e5dd7070Spatrick 
2849e5dd7070Spatrick   std::string TypeName = RD->getQualifiedNameAsString();
2850a9ac8606Spatrick   if (getContext().getNoSanitizeList().containsType(M, TypeName))
2851e5dd7070Spatrick     return;
2852e5dd7070Spatrick 
2853e5dd7070Spatrick   SanitizerScope SanScope(this);
2854e5dd7070Spatrick   EmitSanitizerStatReport(SSK);
2855e5dd7070Spatrick 
2856e5dd7070Spatrick   llvm::Metadata *MD =
2857e5dd7070Spatrick       CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
2858e5dd7070Spatrick   llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
2859e5dd7070Spatrick 
2860e5dd7070Spatrick   llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
2861e5dd7070Spatrick   llvm::Value *TypeTest = Builder.CreateCall(
2862e5dd7070Spatrick       CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, TypeId});
2863e5dd7070Spatrick 
2864e5dd7070Spatrick   llvm::Constant *StaticData[] = {
2865e5dd7070Spatrick       llvm::ConstantInt::get(Int8Ty, TCK),
2866e5dd7070Spatrick       EmitCheckSourceLocation(Loc),
2867e5dd7070Spatrick       EmitCheckTypeDescriptor(QualType(RD->getTypeForDecl(), 0)),
2868e5dd7070Spatrick   };
2869e5dd7070Spatrick 
2870e5dd7070Spatrick   auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
2871e5dd7070Spatrick   if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
2872e5dd7070Spatrick     EmitCfiSlowPathCheck(M, TypeTest, CrossDsoTypeId, CastedVTable, StaticData);
2873e5dd7070Spatrick     return;
2874e5dd7070Spatrick   }
2875e5dd7070Spatrick 
2876e5dd7070Spatrick   if (CGM.getCodeGenOpts().SanitizeTrap.has(M)) {
2877a9ac8606Spatrick     EmitTrapCheck(TypeTest, SanitizerHandler::CFICheckFail);
2878e5dd7070Spatrick     return;
2879e5dd7070Spatrick   }
2880e5dd7070Spatrick 
2881e5dd7070Spatrick   llvm::Value *AllVtables = llvm::MetadataAsValue::get(
2882e5dd7070Spatrick       CGM.getLLVMContext(),
2883e5dd7070Spatrick       llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
2884e5dd7070Spatrick   llvm::Value *ValidVtable = Builder.CreateCall(
2885e5dd7070Spatrick       CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, AllVtables});
2886e5dd7070Spatrick   EmitCheck(std::make_pair(TypeTest, M), SanitizerHandler::CFICheckFail,
2887e5dd7070Spatrick             StaticData, {CastedVTable, ValidVtable});
2888e5dd7070Spatrick }
2889e5dd7070Spatrick 
ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl * RD)2890e5dd7070Spatrick bool CodeGenFunction::ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD) {
2891e5dd7070Spatrick   if (!CGM.getCodeGenOpts().WholeProgramVTables ||
2892e5dd7070Spatrick       !CGM.HasHiddenLTOVisibility(RD))
2893e5dd7070Spatrick     return false;
2894e5dd7070Spatrick 
2895e5dd7070Spatrick   if (CGM.getCodeGenOpts().VirtualFunctionElimination)
2896e5dd7070Spatrick     return true;
2897e5dd7070Spatrick 
2898e5dd7070Spatrick   if (!SanOpts.has(SanitizerKind::CFIVCall) ||
2899e5dd7070Spatrick       !CGM.getCodeGenOpts().SanitizeTrap.has(SanitizerKind::CFIVCall))
2900e5dd7070Spatrick     return false;
2901e5dd7070Spatrick 
2902e5dd7070Spatrick   std::string TypeName = RD->getQualifiedNameAsString();
2903a9ac8606Spatrick   return !getContext().getNoSanitizeList().containsType(SanitizerKind::CFIVCall,
2904a9ac8606Spatrick                                                         TypeName);
2905e5dd7070Spatrick }
2906e5dd7070Spatrick 
EmitVTableTypeCheckedLoad(const CXXRecordDecl * RD,llvm::Value * VTable,llvm::Type * VTableTy,uint64_t VTableByteOffset)2907e5dd7070Spatrick llvm::Value *CodeGenFunction::EmitVTableTypeCheckedLoad(
2908*12c85518Srobert     const CXXRecordDecl *RD, llvm::Value *VTable, llvm::Type *VTableTy,
2909*12c85518Srobert     uint64_t VTableByteOffset) {
2910e5dd7070Spatrick   SanitizerScope SanScope(this);
2911e5dd7070Spatrick 
2912e5dd7070Spatrick   EmitSanitizerStatReport(llvm::SanStat_CFI_VCall);
2913e5dd7070Spatrick 
2914e5dd7070Spatrick   llvm::Metadata *MD =
2915e5dd7070Spatrick       CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
2916e5dd7070Spatrick   llvm::Value *TypeId = llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD);
2917e5dd7070Spatrick 
2918e5dd7070Spatrick   llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
2919e5dd7070Spatrick   llvm::Value *CheckedLoad = Builder.CreateCall(
2920e5dd7070Spatrick       CGM.getIntrinsic(llvm::Intrinsic::type_checked_load),
2921e5dd7070Spatrick       {CastedVTable, llvm::ConstantInt::get(Int32Ty, VTableByteOffset),
2922e5dd7070Spatrick        TypeId});
2923e5dd7070Spatrick   llvm::Value *CheckResult = Builder.CreateExtractValue(CheckedLoad, 1);
2924e5dd7070Spatrick 
2925e5dd7070Spatrick   std::string TypeName = RD->getQualifiedNameAsString();
2926e5dd7070Spatrick   if (SanOpts.has(SanitizerKind::CFIVCall) &&
2927a9ac8606Spatrick       !getContext().getNoSanitizeList().containsType(SanitizerKind::CFIVCall,
2928a9ac8606Spatrick                                                      TypeName)) {
2929e5dd7070Spatrick     EmitCheck(std::make_pair(CheckResult, SanitizerKind::CFIVCall),
2930e5dd7070Spatrick               SanitizerHandler::CFICheckFail, {}, {});
2931e5dd7070Spatrick   }
2932e5dd7070Spatrick 
2933*12c85518Srobert   return Builder.CreateBitCast(Builder.CreateExtractValue(CheckedLoad, 0),
2934*12c85518Srobert                                VTableTy);
2935e5dd7070Spatrick }
2936e5dd7070Spatrick 
EmitForwardingCallToLambda(const CXXMethodDecl * callOperator,CallArgList & callArgs)2937e5dd7070Spatrick void CodeGenFunction::EmitForwardingCallToLambda(
2938e5dd7070Spatrick                                       const CXXMethodDecl *callOperator,
2939e5dd7070Spatrick                                       CallArgList &callArgs) {
2940e5dd7070Spatrick   // Get the address of the call operator.
2941e5dd7070Spatrick   const CGFunctionInfo &calleeFnInfo =
2942e5dd7070Spatrick     CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
2943e5dd7070Spatrick   llvm::Constant *calleePtr =
2944e5dd7070Spatrick     CGM.GetAddrOfFunction(GlobalDecl(callOperator),
2945e5dd7070Spatrick                           CGM.getTypes().GetFunctionType(calleeFnInfo));
2946e5dd7070Spatrick 
2947e5dd7070Spatrick   // Prepare the return slot.
2948e5dd7070Spatrick   const FunctionProtoType *FPT =
2949e5dd7070Spatrick     callOperator->getType()->castAs<FunctionProtoType>();
2950e5dd7070Spatrick   QualType resultType = FPT->getReturnType();
2951e5dd7070Spatrick   ReturnValueSlot returnSlot;
2952e5dd7070Spatrick   if (!resultType->isVoidType() &&
2953e5dd7070Spatrick       calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
2954e5dd7070Spatrick       !hasScalarEvaluationKind(calleeFnInfo.getReturnType()))
2955ec727ea7Spatrick     returnSlot =
2956ec727ea7Spatrick         ReturnValueSlot(ReturnValue, resultType.isVolatileQualified(),
2957ec727ea7Spatrick                         /*IsUnused=*/false, /*IsExternallyDestructed=*/true);
2958e5dd7070Spatrick 
2959e5dd7070Spatrick   // We don't need to separately arrange the call arguments because
2960e5dd7070Spatrick   // the call can't be variadic anyway --- it's impossible to forward
2961e5dd7070Spatrick   // variadic arguments.
2962e5dd7070Spatrick 
2963e5dd7070Spatrick   // Now emit our call.
2964e5dd7070Spatrick   auto callee = CGCallee::forDirect(calleePtr, GlobalDecl(callOperator));
2965e5dd7070Spatrick   RValue RV = EmitCall(calleeFnInfo, callee, returnSlot, callArgs);
2966e5dd7070Spatrick 
2967e5dd7070Spatrick   // If necessary, copy the returned value into the slot.
2968e5dd7070Spatrick   if (!resultType->isVoidType() && returnSlot.isNull()) {
2969e5dd7070Spatrick     if (getLangOpts().ObjCAutoRefCount && resultType->isObjCRetainableType()) {
2970e5dd7070Spatrick       RV = RValue::get(EmitARCRetainAutoreleasedReturnValue(RV.getScalarVal()));
2971e5dd7070Spatrick     }
2972e5dd7070Spatrick     EmitReturnOfRValue(RV, resultType);
2973e5dd7070Spatrick   } else
2974e5dd7070Spatrick     EmitBranchThroughCleanup(ReturnBlock);
2975e5dd7070Spatrick }
2976e5dd7070Spatrick 
EmitLambdaBlockInvokeBody()2977e5dd7070Spatrick void CodeGenFunction::EmitLambdaBlockInvokeBody() {
2978e5dd7070Spatrick   const BlockDecl *BD = BlockInfo->getBlockDecl();
2979e5dd7070Spatrick   const VarDecl *variable = BD->capture_begin()->getVariable();
2980e5dd7070Spatrick   const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
2981e5dd7070Spatrick   const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
2982e5dd7070Spatrick 
2983e5dd7070Spatrick   if (CallOp->isVariadic()) {
2984e5dd7070Spatrick     // FIXME: Making this work correctly is nasty because it requires either
2985e5dd7070Spatrick     // cloning the body of the call operator or making the call operator
2986e5dd7070Spatrick     // forward.
2987e5dd7070Spatrick     CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function");
2988e5dd7070Spatrick     return;
2989e5dd7070Spatrick   }
2990e5dd7070Spatrick 
2991e5dd7070Spatrick   // Start building arguments for forwarding call
2992e5dd7070Spatrick   CallArgList CallArgs;
2993e5dd7070Spatrick 
2994e5dd7070Spatrick   QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2995e5dd7070Spatrick   Address ThisPtr = GetAddrOfBlockDecl(variable);
2996e5dd7070Spatrick   CallArgs.add(RValue::get(ThisPtr.getPointer()), ThisType);
2997e5dd7070Spatrick 
2998e5dd7070Spatrick   // Add the rest of the parameters.
2999*12c85518Srobert   for (auto *param : BD->parameters())
3000e5dd7070Spatrick     EmitDelegateCallArg(CallArgs, param, param->getBeginLoc());
3001e5dd7070Spatrick 
3002e5dd7070Spatrick   assert(!Lambda->isGenericLambda() &&
3003e5dd7070Spatrick             "generic lambda interconversion to block not implemented");
3004e5dd7070Spatrick   EmitForwardingCallToLambda(CallOp, CallArgs);
3005e5dd7070Spatrick }
3006e5dd7070Spatrick 
EmitLambdaDelegatingInvokeBody(const CXXMethodDecl * MD)3007e5dd7070Spatrick void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
3008e5dd7070Spatrick   const CXXRecordDecl *Lambda = MD->getParent();
3009e5dd7070Spatrick 
3010e5dd7070Spatrick   // Start building arguments for forwarding call
3011e5dd7070Spatrick   CallArgList CallArgs;
3012e5dd7070Spatrick 
3013*12c85518Srobert   QualType LambdaType = getContext().getRecordType(Lambda);
3014*12c85518Srobert   QualType ThisType = getContext().getPointerType(LambdaType);
3015*12c85518Srobert   Address ThisPtr = CreateMemTemp(LambdaType, "unused.capture");
3016*12c85518Srobert   CallArgs.add(RValue::get(ThisPtr.getPointer()), ThisType);
3017e5dd7070Spatrick 
3018e5dd7070Spatrick   // Add the rest of the parameters.
3019*12c85518Srobert   for (auto *Param : MD->parameters())
3020e5dd7070Spatrick     EmitDelegateCallArg(CallArgs, Param, Param->getBeginLoc());
3021e5dd7070Spatrick 
3022e5dd7070Spatrick   const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
3023e5dd7070Spatrick   // For a generic lambda, find the corresponding call operator specialization
3024e5dd7070Spatrick   // to which the call to the static-invoker shall be forwarded.
3025e5dd7070Spatrick   if (Lambda->isGenericLambda()) {
3026e5dd7070Spatrick     assert(MD->isFunctionTemplateSpecialization());
3027e5dd7070Spatrick     const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
3028e5dd7070Spatrick     FunctionTemplateDecl *CallOpTemplate = CallOp->getDescribedFunctionTemplate();
3029e5dd7070Spatrick     void *InsertPos = nullptr;
3030e5dd7070Spatrick     FunctionDecl *CorrespondingCallOpSpecialization =
3031e5dd7070Spatrick         CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
3032e5dd7070Spatrick     assert(CorrespondingCallOpSpecialization);
3033e5dd7070Spatrick     CallOp = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
3034e5dd7070Spatrick   }
3035e5dd7070Spatrick   EmitForwardingCallToLambda(CallOp, CallArgs);
3036e5dd7070Spatrick }
3037e5dd7070Spatrick 
EmitLambdaStaticInvokeBody(const CXXMethodDecl * MD)3038e5dd7070Spatrick void CodeGenFunction::EmitLambdaStaticInvokeBody(const CXXMethodDecl *MD) {
3039e5dd7070Spatrick   if (MD->isVariadic()) {
3040e5dd7070Spatrick     // FIXME: Making this work correctly is nasty because it requires either
3041e5dd7070Spatrick     // cloning the body of the call operator or making the call operator forward.
3042e5dd7070Spatrick     CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
3043e5dd7070Spatrick     return;
3044e5dd7070Spatrick   }
3045e5dd7070Spatrick 
3046e5dd7070Spatrick   EmitLambdaDelegatingInvokeBody(MD);
3047e5dd7070Spatrick }
3048