xref: /minix3/external/bsd/llvm/dist/clang/lib/CodeGen/CGClass.cpp (revision 0a6a1f1d05b60e214de2f05a7310ddd1f0e590e7)
1f4a2713aSLionel Sambuc //===--- CGClass.cpp - Emit LLVM Code for C++ classes ---------------------===//
2f4a2713aSLionel Sambuc //
3f4a2713aSLionel Sambuc //                     The LLVM Compiler Infrastructure
4f4a2713aSLionel Sambuc //
5f4a2713aSLionel Sambuc // This file is distributed under the University of Illinois Open Source
6f4a2713aSLionel Sambuc // License. See LICENSE.TXT for details.
7f4a2713aSLionel Sambuc //
8f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
9f4a2713aSLionel Sambuc //
10f4a2713aSLionel Sambuc // This contains code dealing with C++ code generation of classes
11f4a2713aSLionel Sambuc //
12f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
13f4a2713aSLionel Sambuc 
14f4a2713aSLionel Sambuc #include "CGBlocks.h"
15*0a6a1f1dSLionel Sambuc #include "CGCXXABI.h"
16f4a2713aSLionel Sambuc #include "CGDebugInfo.h"
17f4a2713aSLionel Sambuc #include "CGRecordLayout.h"
18f4a2713aSLionel Sambuc #include "CodeGenFunction.h"
19f4a2713aSLionel Sambuc #include "clang/AST/CXXInheritance.h"
20f4a2713aSLionel Sambuc #include "clang/AST/DeclTemplate.h"
21f4a2713aSLionel Sambuc #include "clang/AST/EvaluatedExprVisitor.h"
22f4a2713aSLionel Sambuc #include "clang/AST/RecordLayout.h"
23f4a2713aSLionel Sambuc #include "clang/AST/StmtCXX.h"
24f4a2713aSLionel Sambuc #include "clang/Basic/TargetBuiltins.h"
25f4a2713aSLionel Sambuc #include "clang/CodeGen/CGFunctionInfo.h"
26f4a2713aSLionel Sambuc #include "clang/Frontend/CodeGenOptions.h"
27f4a2713aSLionel Sambuc 
28f4a2713aSLionel Sambuc using namespace clang;
29f4a2713aSLionel Sambuc using namespace CodeGen;
30f4a2713aSLionel Sambuc 
31f4a2713aSLionel Sambuc static CharUnits
ComputeNonVirtualBaseClassOffset(ASTContext & Context,const CXXRecordDecl * DerivedClass,CastExpr::path_const_iterator Start,CastExpr::path_const_iterator End)32f4a2713aSLionel Sambuc ComputeNonVirtualBaseClassOffset(ASTContext &Context,
33f4a2713aSLionel Sambuc                                  const CXXRecordDecl *DerivedClass,
34f4a2713aSLionel Sambuc                                  CastExpr::path_const_iterator Start,
35f4a2713aSLionel Sambuc                                  CastExpr::path_const_iterator End) {
36f4a2713aSLionel Sambuc   CharUnits Offset = CharUnits::Zero();
37f4a2713aSLionel Sambuc 
38f4a2713aSLionel Sambuc   const CXXRecordDecl *RD = DerivedClass;
39f4a2713aSLionel Sambuc 
40f4a2713aSLionel Sambuc   for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
41f4a2713aSLionel Sambuc     const CXXBaseSpecifier *Base = *I;
42f4a2713aSLionel Sambuc     assert(!Base->isVirtual() && "Should not see virtual bases here!");
43f4a2713aSLionel Sambuc 
44f4a2713aSLionel Sambuc     // Get the layout.
45f4a2713aSLionel Sambuc     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
46f4a2713aSLionel Sambuc 
47f4a2713aSLionel Sambuc     const CXXRecordDecl *BaseDecl =
48f4a2713aSLionel Sambuc       cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
49f4a2713aSLionel Sambuc 
50f4a2713aSLionel Sambuc     // Add the offset.
51f4a2713aSLionel Sambuc     Offset += Layout.getBaseClassOffset(BaseDecl);
52f4a2713aSLionel Sambuc 
53f4a2713aSLionel Sambuc     RD = BaseDecl;
54f4a2713aSLionel Sambuc   }
55f4a2713aSLionel Sambuc 
56f4a2713aSLionel Sambuc   return Offset;
57f4a2713aSLionel Sambuc }
58f4a2713aSLionel Sambuc 
59f4a2713aSLionel Sambuc llvm::Constant *
GetNonVirtualBaseClassOffset(const CXXRecordDecl * ClassDecl,CastExpr::path_const_iterator PathBegin,CastExpr::path_const_iterator PathEnd)60f4a2713aSLionel Sambuc CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
61f4a2713aSLionel Sambuc                                    CastExpr::path_const_iterator PathBegin,
62f4a2713aSLionel Sambuc                                    CastExpr::path_const_iterator PathEnd) {
63f4a2713aSLionel Sambuc   assert(PathBegin != PathEnd && "Base path should not be empty!");
64f4a2713aSLionel Sambuc 
65f4a2713aSLionel Sambuc   CharUnits Offset =
66f4a2713aSLionel Sambuc     ComputeNonVirtualBaseClassOffset(getContext(), ClassDecl,
67f4a2713aSLionel Sambuc                                      PathBegin, PathEnd);
68f4a2713aSLionel Sambuc   if (Offset.isZero())
69*0a6a1f1dSLionel Sambuc     return nullptr;
70f4a2713aSLionel Sambuc 
71f4a2713aSLionel Sambuc   llvm::Type *PtrDiffTy =
72f4a2713aSLionel Sambuc   Types.ConvertType(getContext().getPointerDiffType());
73f4a2713aSLionel Sambuc 
74f4a2713aSLionel Sambuc   return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
75f4a2713aSLionel Sambuc }
76f4a2713aSLionel Sambuc 
77f4a2713aSLionel Sambuc /// Gets the address of a direct base class within a complete object.
78f4a2713aSLionel Sambuc /// This should only be used for (1) non-virtual bases or (2) virtual bases
79f4a2713aSLionel Sambuc /// when the type is known to be complete (e.g. in complete destructors).
80f4a2713aSLionel Sambuc ///
81f4a2713aSLionel Sambuc /// The object pointed to by 'This' is assumed to be non-null.
82f4a2713aSLionel Sambuc llvm::Value *
GetAddressOfDirectBaseInCompleteClass(llvm::Value * This,const CXXRecordDecl * Derived,const CXXRecordDecl * Base,bool BaseIsVirtual)83f4a2713aSLionel Sambuc CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(llvm::Value *This,
84f4a2713aSLionel Sambuc                                                    const CXXRecordDecl *Derived,
85f4a2713aSLionel Sambuc                                                    const CXXRecordDecl *Base,
86f4a2713aSLionel Sambuc                                                    bool BaseIsVirtual) {
87f4a2713aSLionel Sambuc   // 'this' must be a pointer (in some address space) to Derived.
88f4a2713aSLionel Sambuc   assert(This->getType()->isPointerTy() &&
89f4a2713aSLionel Sambuc          cast<llvm::PointerType>(This->getType())->getElementType()
90f4a2713aSLionel Sambuc            == ConvertType(Derived));
91f4a2713aSLionel Sambuc 
92f4a2713aSLionel Sambuc   // Compute the offset of the virtual base.
93f4a2713aSLionel Sambuc   CharUnits Offset;
94f4a2713aSLionel Sambuc   const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
95f4a2713aSLionel Sambuc   if (BaseIsVirtual)
96f4a2713aSLionel Sambuc     Offset = Layout.getVBaseClassOffset(Base);
97f4a2713aSLionel Sambuc   else
98f4a2713aSLionel Sambuc     Offset = Layout.getBaseClassOffset(Base);
99f4a2713aSLionel Sambuc 
100f4a2713aSLionel Sambuc   // Shift and cast down to the base type.
101f4a2713aSLionel Sambuc   // TODO: for complete types, this should be possible with a GEP.
102f4a2713aSLionel Sambuc   llvm::Value *V = This;
103f4a2713aSLionel Sambuc   if (Offset.isPositive()) {
104f4a2713aSLionel Sambuc     V = Builder.CreateBitCast(V, Int8PtrTy);
105f4a2713aSLionel Sambuc     V = Builder.CreateConstInBoundsGEP1_64(V, Offset.getQuantity());
106f4a2713aSLionel Sambuc   }
107f4a2713aSLionel Sambuc   V = Builder.CreateBitCast(V, ConvertType(Base)->getPointerTo());
108f4a2713aSLionel Sambuc 
109f4a2713aSLionel Sambuc   return V;
110f4a2713aSLionel Sambuc }
111f4a2713aSLionel Sambuc 
112f4a2713aSLionel Sambuc static llvm::Value *
ApplyNonVirtualAndVirtualOffset(CodeGenFunction & CGF,llvm::Value * ptr,CharUnits nonVirtualOffset,llvm::Value * virtualOffset)113f4a2713aSLionel Sambuc ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, llvm::Value *ptr,
114f4a2713aSLionel Sambuc                                 CharUnits nonVirtualOffset,
115f4a2713aSLionel Sambuc                                 llvm::Value *virtualOffset) {
116f4a2713aSLionel Sambuc   // Assert that we have something to do.
117*0a6a1f1dSLionel Sambuc   assert(!nonVirtualOffset.isZero() || virtualOffset != nullptr);
118f4a2713aSLionel Sambuc 
119f4a2713aSLionel Sambuc   // Compute the offset from the static and dynamic components.
120f4a2713aSLionel Sambuc   llvm::Value *baseOffset;
121f4a2713aSLionel Sambuc   if (!nonVirtualOffset.isZero()) {
122f4a2713aSLionel Sambuc     baseOffset = llvm::ConstantInt::get(CGF.PtrDiffTy,
123f4a2713aSLionel Sambuc                                         nonVirtualOffset.getQuantity());
124f4a2713aSLionel Sambuc     if (virtualOffset) {
125f4a2713aSLionel Sambuc       baseOffset = CGF.Builder.CreateAdd(virtualOffset, baseOffset);
126f4a2713aSLionel Sambuc     }
127f4a2713aSLionel Sambuc   } else {
128f4a2713aSLionel Sambuc     baseOffset = virtualOffset;
129f4a2713aSLionel Sambuc   }
130f4a2713aSLionel Sambuc 
131f4a2713aSLionel Sambuc   // Apply the base offset.
132f4a2713aSLionel Sambuc   ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
133f4a2713aSLionel Sambuc   ptr = CGF.Builder.CreateInBoundsGEP(ptr, baseOffset, "add.ptr");
134f4a2713aSLionel Sambuc   return ptr;
135f4a2713aSLionel Sambuc }
136f4a2713aSLionel Sambuc 
GetAddressOfBaseClass(llvm::Value * Value,const CXXRecordDecl * Derived,CastExpr::path_const_iterator PathBegin,CastExpr::path_const_iterator PathEnd,bool NullCheckValue,SourceLocation Loc)137*0a6a1f1dSLionel Sambuc llvm::Value *CodeGenFunction::GetAddressOfBaseClass(
138*0a6a1f1dSLionel Sambuc     llvm::Value *Value, const CXXRecordDecl *Derived,
139f4a2713aSLionel Sambuc     CastExpr::path_const_iterator PathBegin,
140*0a6a1f1dSLionel Sambuc     CastExpr::path_const_iterator PathEnd, bool NullCheckValue,
141*0a6a1f1dSLionel Sambuc     SourceLocation Loc) {
142f4a2713aSLionel Sambuc   assert(PathBegin != PathEnd && "Base path should not be empty!");
143f4a2713aSLionel Sambuc 
144f4a2713aSLionel Sambuc   CastExpr::path_const_iterator Start = PathBegin;
145*0a6a1f1dSLionel Sambuc   const CXXRecordDecl *VBase = nullptr;
146f4a2713aSLionel Sambuc 
147f4a2713aSLionel Sambuc   // Sema has done some convenient canonicalization here: if the
148f4a2713aSLionel Sambuc   // access path involved any virtual steps, the conversion path will
149f4a2713aSLionel Sambuc   // *start* with a step down to the correct virtual base subobject,
150f4a2713aSLionel Sambuc   // and hence will not require any further steps.
151f4a2713aSLionel Sambuc   if ((*Start)->isVirtual()) {
152f4a2713aSLionel Sambuc     VBase =
153f4a2713aSLionel Sambuc       cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
154f4a2713aSLionel Sambuc     ++Start;
155f4a2713aSLionel Sambuc   }
156f4a2713aSLionel Sambuc 
157f4a2713aSLionel Sambuc   // Compute the static offset of the ultimate destination within its
158f4a2713aSLionel Sambuc   // allocating subobject (the virtual base, if there is one, or else
159f4a2713aSLionel Sambuc   // the "complete" object that we see).
160f4a2713aSLionel Sambuc   CharUnits NonVirtualOffset =
161f4a2713aSLionel Sambuc     ComputeNonVirtualBaseClassOffset(getContext(), VBase ? VBase : Derived,
162f4a2713aSLionel Sambuc                                      Start, PathEnd);
163f4a2713aSLionel Sambuc 
164f4a2713aSLionel Sambuc   // If there's a virtual step, we can sometimes "devirtualize" it.
165f4a2713aSLionel Sambuc   // For now, that's limited to when the derived type is final.
166f4a2713aSLionel Sambuc   // TODO: "devirtualize" this for accesses to known-complete objects.
167f4a2713aSLionel Sambuc   if (VBase && Derived->hasAttr<FinalAttr>()) {
168f4a2713aSLionel Sambuc     const ASTRecordLayout &layout = getContext().getASTRecordLayout(Derived);
169f4a2713aSLionel Sambuc     CharUnits vBaseOffset = layout.getVBaseClassOffset(VBase);
170f4a2713aSLionel Sambuc     NonVirtualOffset += vBaseOffset;
171*0a6a1f1dSLionel Sambuc     VBase = nullptr; // we no longer have a virtual step
172f4a2713aSLionel Sambuc   }
173f4a2713aSLionel Sambuc 
174f4a2713aSLionel Sambuc   // Get the base pointer type.
175f4a2713aSLionel Sambuc   llvm::Type *BasePtrTy =
176f4a2713aSLionel Sambuc     ConvertType((PathEnd[-1])->getType())->getPointerTo();
177f4a2713aSLionel Sambuc 
178*0a6a1f1dSLionel Sambuc   QualType DerivedTy = getContext().getRecordType(Derived);
179*0a6a1f1dSLionel Sambuc   CharUnits DerivedAlign = getContext().getTypeAlignInChars(DerivedTy);
180*0a6a1f1dSLionel Sambuc 
181f4a2713aSLionel Sambuc   // If the static offset is zero and we don't have a virtual step,
182f4a2713aSLionel Sambuc   // just do a bitcast; null checks are unnecessary.
183f4a2713aSLionel Sambuc   if (NonVirtualOffset.isZero() && !VBase) {
184*0a6a1f1dSLionel Sambuc     if (sanitizePerformTypeCheck()) {
185*0a6a1f1dSLionel Sambuc       EmitTypeCheck(TCK_Upcast, Loc, Value, DerivedTy, DerivedAlign,
186*0a6a1f1dSLionel Sambuc                     !NullCheckValue);
187*0a6a1f1dSLionel Sambuc     }
188f4a2713aSLionel Sambuc     return Builder.CreateBitCast(Value, BasePtrTy);
189f4a2713aSLionel Sambuc   }
190f4a2713aSLionel Sambuc 
191*0a6a1f1dSLionel Sambuc   llvm::BasicBlock *origBB = nullptr;
192*0a6a1f1dSLionel Sambuc   llvm::BasicBlock *endBB = nullptr;
193f4a2713aSLionel Sambuc 
194f4a2713aSLionel Sambuc   // Skip over the offset (and the vtable load) if we're supposed to
195f4a2713aSLionel Sambuc   // null-check the pointer.
196f4a2713aSLionel Sambuc   if (NullCheckValue) {
197f4a2713aSLionel Sambuc     origBB = Builder.GetInsertBlock();
198f4a2713aSLionel Sambuc     llvm::BasicBlock *notNullBB = createBasicBlock("cast.notnull");
199f4a2713aSLionel Sambuc     endBB = createBasicBlock("cast.end");
200f4a2713aSLionel Sambuc 
201f4a2713aSLionel Sambuc     llvm::Value *isNull = Builder.CreateIsNull(Value);
202f4a2713aSLionel Sambuc     Builder.CreateCondBr(isNull, endBB, notNullBB);
203f4a2713aSLionel Sambuc     EmitBlock(notNullBB);
204f4a2713aSLionel Sambuc   }
205f4a2713aSLionel Sambuc 
206*0a6a1f1dSLionel Sambuc   if (sanitizePerformTypeCheck()) {
207*0a6a1f1dSLionel Sambuc     EmitTypeCheck(VBase ? TCK_UpcastToVirtualBase : TCK_Upcast, Loc, Value,
208*0a6a1f1dSLionel Sambuc                   DerivedTy, DerivedAlign, true);
209*0a6a1f1dSLionel Sambuc   }
210*0a6a1f1dSLionel Sambuc 
211f4a2713aSLionel Sambuc   // Compute the virtual offset.
212*0a6a1f1dSLionel Sambuc   llvm::Value *VirtualOffset = nullptr;
213f4a2713aSLionel Sambuc   if (VBase) {
214f4a2713aSLionel Sambuc     VirtualOffset =
215f4a2713aSLionel Sambuc       CGM.getCXXABI().GetVirtualBaseClassOffset(*this, Value, Derived, VBase);
216f4a2713aSLionel Sambuc   }
217f4a2713aSLionel Sambuc 
218f4a2713aSLionel Sambuc   // Apply both offsets.
219f4a2713aSLionel Sambuc   Value = ApplyNonVirtualAndVirtualOffset(*this, Value,
220f4a2713aSLionel Sambuc                                           NonVirtualOffset,
221f4a2713aSLionel Sambuc                                           VirtualOffset);
222f4a2713aSLionel Sambuc 
223f4a2713aSLionel Sambuc   // Cast to the destination type.
224f4a2713aSLionel Sambuc   Value = Builder.CreateBitCast(Value, BasePtrTy);
225f4a2713aSLionel Sambuc 
226f4a2713aSLionel Sambuc   // Build a phi if we needed a null check.
227f4a2713aSLionel Sambuc   if (NullCheckValue) {
228f4a2713aSLionel Sambuc     llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
229f4a2713aSLionel Sambuc     Builder.CreateBr(endBB);
230f4a2713aSLionel Sambuc     EmitBlock(endBB);
231f4a2713aSLionel Sambuc 
232f4a2713aSLionel Sambuc     llvm::PHINode *PHI = Builder.CreatePHI(BasePtrTy, 2, "cast.result");
233f4a2713aSLionel Sambuc     PHI->addIncoming(Value, notNullBB);
234f4a2713aSLionel Sambuc     PHI->addIncoming(llvm::Constant::getNullValue(BasePtrTy), origBB);
235f4a2713aSLionel Sambuc     Value = PHI;
236f4a2713aSLionel Sambuc   }
237f4a2713aSLionel Sambuc 
238f4a2713aSLionel Sambuc   return Value;
239f4a2713aSLionel Sambuc }
240f4a2713aSLionel Sambuc 
241f4a2713aSLionel Sambuc llvm::Value *
GetAddressOfDerivedClass(llvm::Value * Value,const CXXRecordDecl * Derived,CastExpr::path_const_iterator PathBegin,CastExpr::path_const_iterator PathEnd,bool NullCheckValue)242f4a2713aSLionel Sambuc CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value,
243f4a2713aSLionel Sambuc                                           const CXXRecordDecl *Derived,
244f4a2713aSLionel Sambuc                                         CastExpr::path_const_iterator PathBegin,
245f4a2713aSLionel Sambuc                                           CastExpr::path_const_iterator PathEnd,
246f4a2713aSLionel Sambuc                                           bool NullCheckValue) {
247f4a2713aSLionel Sambuc   assert(PathBegin != PathEnd && "Base path should not be empty!");
248f4a2713aSLionel Sambuc 
249f4a2713aSLionel Sambuc   QualType DerivedTy =
250f4a2713aSLionel Sambuc     getContext().getCanonicalType(getContext().getTagDeclType(Derived));
251f4a2713aSLionel Sambuc   llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
252f4a2713aSLionel Sambuc 
253f4a2713aSLionel Sambuc   llvm::Value *NonVirtualOffset =
254f4a2713aSLionel Sambuc     CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
255f4a2713aSLionel Sambuc 
256f4a2713aSLionel Sambuc   if (!NonVirtualOffset) {
257f4a2713aSLionel Sambuc     // No offset, we can just cast back.
258f4a2713aSLionel Sambuc     return Builder.CreateBitCast(Value, DerivedPtrTy);
259f4a2713aSLionel Sambuc   }
260f4a2713aSLionel Sambuc 
261*0a6a1f1dSLionel Sambuc   llvm::BasicBlock *CastNull = nullptr;
262*0a6a1f1dSLionel Sambuc   llvm::BasicBlock *CastNotNull = nullptr;
263*0a6a1f1dSLionel Sambuc   llvm::BasicBlock *CastEnd = nullptr;
264f4a2713aSLionel Sambuc 
265f4a2713aSLionel Sambuc   if (NullCheckValue) {
266f4a2713aSLionel Sambuc     CastNull = createBasicBlock("cast.null");
267f4a2713aSLionel Sambuc     CastNotNull = createBasicBlock("cast.notnull");
268f4a2713aSLionel Sambuc     CastEnd = createBasicBlock("cast.end");
269f4a2713aSLionel Sambuc 
270f4a2713aSLionel Sambuc     llvm::Value *IsNull = Builder.CreateIsNull(Value);
271f4a2713aSLionel Sambuc     Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
272f4a2713aSLionel Sambuc     EmitBlock(CastNotNull);
273f4a2713aSLionel Sambuc   }
274f4a2713aSLionel Sambuc 
275f4a2713aSLionel Sambuc   // Apply the offset.
276f4a2713aSLionel Sambuc   Value = Builder.CreateBitCast(Value, Int8PtrTy);
277f4a2713aSLionel Sambuc   Value = Builder.CreateGEP(Value, Builder.CreateNeg(NonVirtualOffset),
278f4a2713aSLionel Sambuc                             "sub.ptr");
279f4a2713aSLionel Sambuc 
280f4a2713aSLionel Sambuc   // Just cast.
281f4a2713aSLionel Sambuc   Value = Builder.CreateBitCast(Value, DerivedPtrTy);
282f4a2713aSLionel Sambuc 
283f4a2713aSLionel Sambuc   if (NullCheckValue) {
284f4a2713aSLionel Sambuc     Builder.CreateBr(CastEnd);
285f4a2713aSLionel Sambuc     EmitBlock(CastNull);
286f4a2713aSLionel Sambuc     Builder.CreateBr(CastEnd);
287f4a2713aSLionel Sambuc     EmitBlock(CastEnd);
288f4a2713aSLionel Sambuc 
289f4a2713aSLionel Sambuc     llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
290f4a2713aSLionel Sambuc     PHI->addIncoming(Value, CastNotNull);
291f4a2713aSLionel Sambuc     PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
292f4a2713aSLionel Sambuc                      CastNull);
293f4a2713aSLionel Sambuc     Value = PHI;
294f4a2713aSLionel Sambuc   }
295f4a2713aSLionel Sambuc 
296f4a2713aSLionel Sambuc   return Value;
297f4a2713aSLionel Sambuc }
298f4a2713aSLionel Sambuc 
GetVTTParameter(GlobalDecl GD,bool ForVirtualBase,bool Delegating)299f4a2713aSLionel Sambuc llvm::Value *CodeGenFunction::GetVTTParameter(GlobalDecl GD,
300f4a2713aSLionel Sambuc                                               bool ForVirtualBase,
301f4a2713aSLionel Sambuc                                               bool Delegating) {
302f4a2713aSLionel Sambuc   if (!CGM.getCXXABI().NeedsVTTParameter(GD)) {
303f4a2713aSLionel Sambuc     // This constructor/destructor does not need a VTT parameter.
304*0a6a1f1dSLionel Sambuc     return nullptr;
305f4a2713aSLionel Sambuc   }
306f4a2713aSLionel Sambuc 
307f4a2713aSLionel Sambuc   const CXXRecordDecl *RD = cast<CXXMethodDecl>(CurCodeDecl)->getParent();
308f4a2713aSLionel Sambuc   const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
309f4a2713aSLionel Sambuc 
310f4a2713aSLionel Sambuc   llvm::Value *VTT;
311f4a2713aSLionel Sambuc 
312f4a2713aSLionel Sambuc   uint64_t SubVTTIndex;
313f4a2713aSLionel Sambuc 
314f4a2713aSLionel Sambuc   if (Delegating) {
315f4a2713aSLionel Sambuc     // If this is a delegating constructor call, just load the VTT.
316f4a2713aSLionel Sambuc     return LoadCXXVTT();
317f4a2713aSLionel Sambuc   } else if (RD == Base) {
318f4a2713aSLionel Sambuc     // If the record matches the base, this is the complete ctor/dtor
319f4a2713aSLionel Sambuc     // variant calling the base variant in a class with virtual bases.
320f4a2713aSLionel Sambuc     assert(!CGM.getCXXABI().NeedsVTTParameter(CurGD) &&
321f4a2713aSLionel Sambuc            "doing no-op VTT offset in base dtor/ctor?");
322f4a2713aSLionel Sambuc     assert(!ForVirtualBase && "Can't have same class as virtual base!");
323f4a2713aSLionel Sambuc     SubVTTIndex = 0;
324f4a2713aSLionel Sambuc   } else {
325f4a2713aSLionel Sambuc     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
326f4a2713aSLionel Sambuc     CharUnits BaseOffset = ForVirtualBase ?
327f4a2713aSLionel Sambuc       Layout.getVBaseClassOffset(Base) :
328f4a2713aSLionel Sambuc       Layout.getBaseClassOffset(Base);
329f4a2713aSLionel Sambuc 
330f4a2713aSLionel Sambuc     SubVTTIndex =
331f4a2713aSLionel Sambuc       CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
332f4a2713aSLionel Sambuc     assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
333f4a2713aSLionel Sambuc   }
334f4a2713aSLionel Sambuc 
335f4a2713aSLionel Sambuc   if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
336f4a2713aSLionel Sambuc     // A VTT parameter was passed to the constructor, use it.
337f4a2713aSLionel Sambuc     VTT = LoadCXXVTT();
338f4a2713aSLionel Sambuc     VTT = Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
339f4a2713aSLionel Sambuc   } else {
340f4a2713aSLionel Sambuc     // We're the complete constructor, so get the VTT by name.
341f4a2713aSLionel Sambuc     VTT = CGM.getVTables().GetAddrOfVTT(RD);
342f4a2713aSLionel Sambuc     VTT = Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
343f4a2713aSLionel Sambuc   }
344f4a2713aSLionel Sambuc 
345f4a2713aSLionel Sambuc   return VTT;
346f4a2713aSLionel Sambuc }
347f4a2713aSLionel Sambuc 
348f4a2713aSLionel Sambuc namespace {
349f4a2713aSLionel Sambuc   /// Call the destructor for a direct base class.
350f4a2713aSLionel Sambuc   struct CallBaseDtor : EHScopeStack::Cleanup {
351f4a2713aSLionel Sambuc     const CXXRecordDecl *BaseClass;
352f4a2713aSLionel Sambuc     bool BaseIsVirtual;
CallBaseDtor__anone7009f310111::CallBaseDtor353f4a2713aSLionel Sambuc     CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
354f4a2713aSLionel Sambuc       : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
355f4a2713aSLionel Sambuc 
Emit__anone7009f310111::CallBaseDtor356*0a6a1f1dSLionel Sambuc     void Emit(CodeGenFunction &CGF, Flags flags) override {
357f4a2713aSLionel Sambuc       const CXXRecordDecl *DerivedClass =
358f4a2713aSLionel Sambuc         cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
359f4a2713aSLionel Sambuc 
360f4a2713aSLionel Sambuc       const CXXDestructorDecl *D = BaseClass->getDestructor();
361f4a2713aSLionel Sambuc       llvm::Value *Addr =
362f4a2713aSLionel Sambuc         CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThis(),
363f4a2713aSLionel Sambuc                                                   DerivedClass, BaseClass,
364f4a2713aSLionel Sambuc                                                   BaseIsVirtual);
365f4a2713aSLionel Sambuc       CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual,
366f4a2713aSLionel Sambuc                                 /*Delegating=*/false, Addr);
367f4a2713aSLionel Sambuc     }
368f4a2713aSLionel Sambuc   };
369f4a2713aSLionel Sambuc 
370f4a2713aSLionel Sambuc   /// A visitor which checks whether an initializer uses 'this' in a
371f4a2713aSLionel Sambuc   /// way which requires the vtable to be properly set.
372f4a2713aSLionel Sambuc   struct DynamicThisUseChecker : EvaluatedExprVisitor<DynamicThisUseChecker> {
373f4a2713aSLionel Sambuc     typedef EvaluatedExprVisitor<DynamicThisUseChecker> super;
374f4a2713aSLionel Sambuc 
375f4a2713aSLionel Sambuc     bool UsesThis;
376f4a2713aSLionel Sambuc 
DynamicThisUseChecker__anone7009f310111::DynamicThisUseChecker377f4a2713aSLionel Sambuc     DynamicThisUseChecker(ASTContext &C) : super(C), UsesThis(false) {}
378f4a2713aSLionel Sambuc 
379f4a2713aSLionel Sambuc     // Black-list all explicit and implicit references to 'this'.
380f4a2713aSLionel Sambuc     //
381f4a2713aSLionel Sambuc     // Do we need to worry about external references to 'this' derived
382f4a2713aSLionel Sambuc     // from arbitrary code?  If so, then anything which runs arbitrary
383f4a2713aSLionel Sambuc     // external code might potentially access the vtable.
VisitCXXThisExpr__anone7009f310111::DynamicThisUseChecker384f4a2713aSLionel Sambuc     void VisitCXXThisExpr(CXXThisExpr *E) { UsesThis = true; }
385f4a2713aSLionel Sambuc   };
386f4a2713aSLionel Sambuc }
387f4a2713aSLionel Sambuc 
BaseInitializerUsesThis(ASTContext & C,const Expr * Init)388f4a2713aSLionel Sambuc static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
389f4a2713aSLionel Sambuc   DynamicThisUseChecker Checker(C);
390f4a2713aSLionel Sambuc   Checker.Visit(const_cast<Expr*>(Init));
391f4a2713aSLionel Sambuc   return Checker.UsesThis;
392f4a2713aSLionel Sambuc }
393f4a2713aSLionel Sambuc 
EmitBaseInitializer(CodeGenFunction & CGF,const CXXRecordDecl * ClassDecl,CXXCtorInitializer * BaseInit,CXXCtorType CtorType)394f4a2713aSLionel Sambuc static void EmitBaseInitializer(CodeGenFunction &CGF,
395f4a2713aSLionel Sambuc                                 const CXXRecordDecl *ClassDecl,
396f4a2713aSLionel Sambuc                                 CXXCtorInitializer *BaseInit,
397f4a2713aSLionel Sambuc                                 CXXCtorType CtorType) {
398f4a2713aSLionel Sambuc   assert(BaseInit->isBaseInitializer() &&
399f4a2713aSLionel Sambuc          "Must have base initializer!");
400f4a2713aSLionel Sambuc 
401f4a2713aSLionel Sambuc   llvm::Value *ThisPtr = CGF.LoadCXXThis();
402f4a2713aSLionel Sambuc 
403f4a2713aSLionel Sambuc   const Type *BaseType = BaseInit->getBaseClass();
404f4a2713aSLionel Sambuc   CXXRecordDecl *BaseClassDecl =
405f4a2713aSLionel Sambuc     cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
406f4a2713aSLionel Sambuc 
407f4a2713aSLionel Sambuc   bool isBaseVirtual = BaseInit->isBaseVirtual();
408f4a2713aSLionel Sambuc 
409f4a2713aSLionel Sambuc   // The base constructor doesn't construct virtual bases.
410f4a2713aSLionel Sambuc   if (CtorType == Ctor_Base && isBaseVirtual)
411f4a2713aSLionel Sambuc     return;
412f4a2713aSLionel Sambuc 
413f4a2713aSLionel Sambuc   // If the initializer for the base (other than the constructor
414f4a2713aSLionel Sambuc   // itself) accesses 'this' in any way, we need to initialize the
415f4a2713aSLionel Sambuc   // vtables.
416f4a2713aSLionel Sambuc   if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
417f4a2713aSLionel Sambuc     CGF.InitializeVTablePointers(ClassDecl);
418f4a2713aSLionel Sambuc 
419f4a2713aSLionel Sambuc   // We can pretend to be a complete class because it only matters for
420f4a2713aSLionel Sambuc   // virtual bases, and we only do virtual bases for complete ctors.
421f4a2713aSLionel Sambuc   llvm::Value *V =
422f4a2713aSLionel Sambuc     CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
423f4a2713aSLionel Sambuc                                               BaseClassDecl,
424f4a2713aSLionel Sambuc                                               isBaseVirtual);
425f4a2713aSLionel Sambuc   CharUnits Alignment = CGF.getContext().getTypeAlignInChars(BaseType);
426f4a2713aSLionel Sambuc   AggValueSlot AggSlot =
427f4a2713aSLionel Sambuc     AggValueSlot::forAddr(V, Alignment, Qualifiers(),
428f4a2713aSLionel Sambuc                           AggValueSlot::IsDestructed,
429f4a2713aSLionel Sambuc                           AggValueSlot::DoesNotNeedGCBarriers,
430f4a2713aSLionel Sambuc                           AggValueSlot::IsNotAliased);
431f4a2713aSLionel Sambuc 
432f4a2713aSLionel Sambuc   CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
433f4a2713aSLionel Sambuc 
434f4a2713aSLionel Sambuc   if (CGF.CGM.getLangOpts().Exceptions &&
435f4a2713aSLionel Sambuc       !BaseClassDecl->hasTrivialDestructor())
436f4a2713aSLionel Sambuc     CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
437f4a2713aSLionel Sambuc                                           isBaseVirtual);
438f4a2713aSLionel Sambuc }
439f4a2713aSLionel Sambuc 
EmitAggMemberInitializer(CodeGenFunction & CGF,LValue LHS,Expr * Init,llvm::Value * ArrayIndexVar,QualType T,ArrayRef<VarDecl * > ArrayIndexes,unsigned Index)440f4a2713aSLionel Sambuc static void EmitAggMemberInitializer(CodeGenFunction &CGF,
441f4a2713aSLionel Sambuc                                      LValue LHS,
442f4a2713aSLionel Sambuc                                      Expr *Init,
443f4a2713aSLionel Sambuc                                      llvm::Value *ArrayIndexVar,
444f4a2713aSLionel Sambuc                                      QualType T,
445f4a2713aSLionel Sambuc                                      ArrayRef<VarDecl *> ArrayIndexes,
446f4a2713aSLionel Sambuc                                      unsigned Index) {
447f4a2713aSLionel Sambuc   if (Index == ArrayIndexes.size()) {
448f4a2713aSLionel Sambuc     LValue LV = LHS;
449f4a2713aSLionel Sambuc 
450f4a2713aSLionel Sambuc     if (ArrayIndexVar) {
451f4a2713aSLionel Sambuc       // If we have an array index variable, load it and use it as an offset.
452f4a2713aSLionel Sambuc       // Then, increment the value.
453f4a2713aSLionel Sambuc       llvm::Value *Dest = LHS.getAddress();
454f4a2713aSLionel Sambuc       llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar);
455f4a2713aSLionel Sambuc       Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress");
456f4a2713aSLionel Sambuc       llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1);
457f4a2713aSLionel Sambuc       Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc");
458f4a2713aSLionel Sambuc       CGF.Builder.CreateStore(Next, ArrayIndexVar);
459f4a2713aSLionel Sambuc 
460f4a2713aSLionel Sambuc       // Update the LValue.
461f4a2713aSLionel Sambuc       LV.setAddress(Dest);
462f4a2713aSLionel Sambuc       CharUnits Align = CGF.getContext().getTypeAlignInChars(T);
463f4a2713aSLionel Sambuc       LV.setAlignment(std::min(Align, LV.getAlignment()));
464f4a2713aSLionel Sambuc     }
465f4a2713aSLionel Sambuc 
466f4a2713aSLionel Sambuc     switch (CGF.getEvaluationKind(T)) {
467f4a2713aSLionel Sambuc     case TEK_Scalar:
468*0a6a1f1dSLionel Sambuc       CGF.EmitScalarInit(Init, /*decl*/ nullptr, LV, false);
469f4a2713aSLionel Sambuc       break;
470f4a2713aSLionel Sambuc     case TEK_Complex:
471f4a2713aSLionel Sambuc       CGF.EmitComplexExprIntoLValue(Init, LV, /*isInit*/ true);
472f4a2713aSLionel Sambuc       break;
473f4a2713aSLionel Sambuc     case TEK_Aggregate: {
474f4a2713aSLionel Sambuc       AggValueSlot Slot =
475f4a2713aSLionel Sambuc         AggValueSlot::forLValue(LV,
476f4a2713aSLionel Sambuc                                 AggValueSlot::IsDestructed,
477f4a2713aSLionel Sambuc                                 AggValueSlot::DoesNotNeedGCBarriers,
478f4a2713aSLionel Sambuc                                 AggValueSlot::IsNotAliased);
479f4a2713aSLionel Sambuc 
480f4a2713aSLionel Sambuc       CGF.EmitAggExpr(Init, Slot);
481f4a2713aSLionel Sambuc       break;
482f4a2713aSLionel Sambuc     }
483f4a2713aSLionel Sambuc     }
484f4a2713aSLionel Sambuc 
485f4a2713aSLionel Sambuc     return;
486f4a2713aSLionel Sambuc   }
487f4a2713aSLionel Sambuc 
488f4a2713aSLionel Sambuc   const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T);
489f4a2713aSLionel Sambuc   assert(Array && "Array initialization without the array type?");
490f4a2713aSLionel Sambuc   llvm::Value *IndexVar
491f4a2713aSLionel Sambuc     = CGF.GetAddrOfLocalVar(ArrayIndexes[Index]);
492f4a2713aSLionel Sambuc   assert(IndexVar && "Array index variable not loaded");
493f4a2713aSLionel Sambuc 
494f4a2713aSLionel Sambuc   // Initialize this index variable to zero.
495f4a2713aSLionel Sambuc   llvm::Value* Zero
496f4a2713aSLionel Sambuc     = llvm::Constant::getNullValue(
497f4a2713aSLionel Sambuc                               CGF.ConvertType(CGF.getContext().getSizeType()));
498f4a2713aSLionel Sambuc   CGF.Builder.CreateStore(Zero, IndexVar);
499f4a2713aSLionel Sambuc 
500f4a2713aSLionel Sambuc   // Start the loop with a block that tests the condition.
501f4a2713aSLionel Sambuc   llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond");
502f4a2713aSLionel Sambuc   llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end");
503f4a2713aSLionel Sambuc 
504f4a2713aSLionel Sambuc   CGF.EmitBlock(CondBlock);
505f4a2713aSLionel Sambuc 
506f4a2713aSLionel Sambuc   llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body");
507f4a2713aSLionel Sambuc   // Generate: if (loop-index < number-of-elements) fall to the loop body,
508f4a2713aSLionel Sambuc   // otherwise, go to the block after the for-loop.
509f4a2713aSLionel Sambuc   uint64_t NumElements = Array->getSize().getZExtValue();
510f4a2713aSLionel Sambuc   llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
511f4a2713aSLionel Sambuc   llvm::Value *NumElementsPtr =
512f4a2713aSLionel Sambuc     llvm::ConstantInt::get(Counter->getType(), NumElements);
513f4a2713aSLionel Sambuc   llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr,
514f4a2713aSLionel Sambuc                                                   "isless");
515f4a2713aSLionel Sambuc 
516f4a2713aSLionel Sambuc   // If the condition is true, execute the body.
517f4a2713aSLionel Sambuc   CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor);
518f4a2713aSLionel Sambuc 
519f4a2713aSLionel Sambuc   CGF.EmitBlock(ForBody);
520f4a2713aSLionel Sambuc   llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc");
521f4a2713aSLionel Sambuc 
522f4a2713aSLionel Sambuc   // Inside the loop body recurse to emit the inner loop or, eventually, the
523f4a2713aSLionel Sambuc   // constructor call.
524f4a2713aSLionel Sambuc   EmitAggMemberInitializer(CGF, LHS, Init, ArrayIndexVar,
525f4a2713aSLionel Sambuc                            Array->getElementType(), ArrayIndexes, Index + 1);
526f4a2713aSLionel Sambuc 
527f4a2713aSLionel Sambuc   CGF.EmitBlock(ContinueBlock);
528f4a2713aSLionel Sambuc 
529f4a2713aSLionel Sambuc   // Emit the increment of the loop counter.
530f4a2713aSLionel Sambuc   llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
531f4a2713aSLionel Sambuc   Counter = CGF.Builder.CreateLoad(IndexVar);
532f4a2713aSLionel Sambuc   NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc");
533f4a2713aSLionel Sambuc   CGF.Builder.CreateStore(NextVal, IndexVar);
534f4a2713aSLionel Sambuc 
535f4a2713aSLionel Sambuc   // Finally, branch back up to the condition for the next iteration.
536f4a2713aSLionel Sambuc   CGF.EmitBranch(CondBlock);
537f4a2713aSLionel Sambuc 
538f4a2713aSLionel Sambuc   // Emit the fall-through block.
539f4a2713aSLionel Sambuc   CGF.EmitBlock(AfterFor, true);
540f4a2713aSLionel Sambuc }
541f4a2713aSLionel Sambuc 
EmitMemberInitializer(CodeGenFunction & CGF,const CXXRecordDecl * ClassDecl,CXXCtorInitializer * MemberInit,const CXXConstructorDecl * Constructor,FunctionArgList & Args)542f4a2713aSLionel Sambuc static void EmitMemberInitializer(CodeGenFunction &CGF,
543f4a2713aSLionel Sambuc                                   const CXXRecordDecl *ClassDecl,
544f4a2713aSLionel Sambuc                                   CXXCtorInitializer *MemberInit,
545f4a2713aSLionel Sambuc                                   const CXXConstructorDecl *Constructor,
546f4a2713aSLionel Sambuc                                   FunctionArgList &Args) {
547*0a6a1f1dSLionel Sambuc   ApplyDebugLocation Loc(CGF, MemberInit->getSourceLocation());
548f4a2713aSLionel Sambuc   assert(MemberInit->isAnyMemberInitializer() &&
549f4a2713aSLionel Sambuc          "Must have member initializer!");
550f4a2713aSLionel Sambuc   assert(MemberInit->getInit() && "Must have initializer!");
551f4a2713aSLionel Sambuc 
552f4a2713aSLionel Sambuc   // non-static data member initializers.
553f4a2713aSLionel Sambuc   FieldDecl *Field = MemberInit->getAnyMember();
554f4a2713aSLionel Sambuc   QualType FieldType = Field->getType();
555f4a2713aSLionel Sambuc 
556f4a2713aSLionel Sambuc   llvm::Value *ThisPtr = CGF.LoadCXXThis();
557f4a2713aSLionel Sambuc   QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
558f4a2713aSLionel Sambuc   LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
559f4a2713aSLionel Sambuc 
560f4a2713aSLionel Sambuc   if (MemberInit->isIndirectMemberInitializer()) {
561f4a2713aSLionel Sambuc     // If we are initializing an anonymous union field, drill down to
562f4a2713aSLionel Sambuc     // the field.
563f4a2713aSLionel Sambuc     IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember();
564*0a6a1f1dSLionel Sambuc     for (const auto *I : IndirectField->chain())
565*0a6a1f1dSLionel Sambuc       LHS = CGF.EmitLValueForFieldInitialization(LHS, cast<FieldDecl>(I));
566f4a2713aSLionel Sambuc     FieldType = MemberInit->getIndirectMember()->getAnonField()->getType();
567f4a2713aSLionel Sambuc   } else {
568f4a2713aSLionel Sambuc     LHS = CGF.EmitLValueForFieldInitialization(LHS, Field);
569f4a2713aSLionel Sambuc   }
570f4a2713aSLionel Sambuc 
571f4a2713aSLionel Sambuc   // Special case: if we are in a copy or move constructor, and we are copying
572f4a2713aSLionel Sambuc   // an array of PODs or classes with trivial copy constructors, ignore the
573f4a2713aSLionel Sambuc   // AST and perform the copy we know is equivalent.
574f4a2713aSLionel Sambuc   // FIXME: This is hacky at best... if we had a bit more explicit information
575f4a2713aSLionel Sambuc   // in the AST, we could generalize it more easily.
576f4a2713aSLionel Sambuc   const ConstantArrayType *Array
577f4a2713aSLionel Sambuc     = CGF.getContext().getAsConstantArrayType(FieldType);
578f4a2713aSLionel Sambuc   if (Array && Constructor->isDefaulted() &&
579f4a2713aSLionel Sambuc       Constructor->isCopyOrMoveConstructor()) {
580f4a2713aSLionel Sambuc     QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
581f4a2713aSLionel Sambuc     CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
582f4a2713aSLionel Sambuc     if (BaseElementTy.isPODType(CGF.getContext()) ||
583f4a2713aSLionel Sambuc         (CE && CE->getConstructor()->isTrivial())) {
584*0a6a1f1dSLionel Sambuc       unsigned SrcArgIndex =
585*0a6a1f1dSLionel Sambuc           CGF.CGM.getCXXABI().getSrcArgforCopyCtor(Constructor, Args);
586f4a2713aSLionel Sambuc       llvm::Value *SrcPtr
587f4a2713aSLionel Sambuc         = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
588f4a2713aSLionel Sambuc       LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
589f4a2713aSLionel Sambuc       LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field);
590f4a2713aSLionel Sambuc 
591f4a2713aSLionel Sambuc       // Copy the aggregate.
592f4a2713aSLionel Sambuc       CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
593f4a2713aSLionel Sambuc                             LHS.isVolatileQualified());
594f4a2713aSLionel Sambuc       return;
595f4a2713aSLionel Sambuc     }
596f4a2713aSLionel Sambuc   }
597f4a2713aSLionel Sambuc 
598f4a2713aSLionel Sambuc   ArrayRef<VarDecl *> ArrayIndexes;
599f4a2713aSLionel Sambuc   if (MemberInit->getNumArrayIndices())
600f4a2713aSLionel Sambuc     ArrayIndexes = MemberInit->getArrayIndexes();
601f4a2713aSLionel Sambuc   CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit(), ArrayIndexes);
602f4a2713aSLionel Sambuc }
603f4a2713aSLionel Sambuc 
EmitInitializerForField(FieldDecl * Field,LValue LHS,Expr * Init,ArrayRef<VarDecl * > ArrayIndexes)604*0a6a1f1dSLionel Sambuc void CodeGenFunction::EmitInitializerForField(
605*0a6a1f1dSLionel Sambuc     FieldDecl *Field, LValue LHS, Expr *Init,
606f4a2713aSLionel Sambuc     ArrayRef<VarDecl *> ArrayIndexes) {
607f4a2713aSLionel Sambuc   QualType FieldType = Field->getType();
608f4a2713aSLionel Sambuc   switch (getEvaluationKind(FieldType)) {
609f4a2713aSLionel Sambuc   case TEK_Scalar:
610f4a2713aSLionel Sambuc     if (LHS.isSimple()) {
611f4a2713aSLionel Sambuc       EmitExprAsInit(Init, Field, LHS, false);
612f4a2713aSLionel Sambuc     } else {
613f4a2713aSLionel Sambuc       RValue RHS = RValue::get(EmitScalarExpr(Init));
614f4a2713aSLionel Sambuc       EmitStoreThroughLValue(RHS, LHS);
615f4a2713aSLionel Sambuc     }
616f4a2713aSLionel Sambuc     break;
617f4a2713aSLionel Sambuc   case TEK_Complex:
618f4a2713aSLionel Sambuc     EmitComplexExprIntoLValue(Init, LHS, /*isInit*/ true);
619f4a2713aSLionel Sambuc     break;
620f4a2713aSLionel Sambuc   case TEK_Aggregate: {
621*0a6a1f1dSLionel Sambuc     llvm::Value *ArrayIndexVar = nullptr;
622f4a2713aSLionel Sambuc     if (ArrayIndexes.size()) {
623f4a2713aSLionel Sambuc       llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
624f4a2713aSLionel Sambuc 
625f4a2713aSLionel Sambuc       // The LHS is a pointer to the first object we'll be constructing, as
626f4a2713aSLionel Sambuc       // a flat array.
627f4a2713aSLionel Sambuc       QualType BaseElementTy = getContext().getBaseElementType(FieldType);
628f4a2713aSLionel Sambuc       llvm::Type *BasePtr = ConvertType(BaseElementTy);
629f4a2713aSLionel Sambuc       BasePtr = llvm::PointerType::getUnqual(BasePtr);
630f4a2713aSLionel Sambuc       llvm::Value *BaseAddrPtr = Builder.CreateBitCast(LHS.getAddress(),
631f4a2713aSLionel Sambuc                                                        BasePtr);
632f4a2713aSLionel Sambuc       LHS = MakeAddrLValue(BaseAddrPtr, BaseElementTy);
633f4a2713aSLionel Sambuc 
634f4a2713aSLionel Sambuc       // Create an array index that will be used to walk over all of the
635f4a2713aSLionel Sambuc       // objects we're constructing.
636f4a2713aSLionel Sambuc       ArrayIndexVar = CreateTempAlloca(SizeTy, "object.index");
637f4a2713aSLionel Sambuc       llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
638f4a2713aSLionel Sambuc       Builder.CreateStore(Zero, ArrayIndexVar);
639f4a2713aSLionel Sambuc 
640f4a2713aSLionel Sambuc 
641f4a2713aSLionel Sambuc       // Emit the block variables for the array indices, if any.
642f4a2713aSLionel Sambuc       for (unsigned I = 0, N = ArrayIndexes.size(); I != N; ++I)
643f4a2713aSLionel Sambuc         EmitAutoVarDecl(*ArrayIndexes[I]);
644f4a2713aSLionel Sambuc     }
645f4a2713aSLionel Sambuc 
646f4a2713aSLionel Sambuc     EmitAggMemberInitializer(*this, LHS, Init, ArrayIndexVar, FieldType,
647f4a2713aSLionel Sambuc                              ArrayIndexes, 0);
648f4a2713aSLionel Sambuc   }
649f4a2713aSLionel Sambuc   }
650f4a2713aSLionel Sambuc 
651f4a2713aSLionel Sambuc   // Ensure that we destroy this object if an exception is thrown
652f4a2713aSLionel Sambuc   // later in the constructor.
653f4a2713aSLionel Sambuc   QualType::DestructionKind dtorKind = FieldType.isDestructedType();
654f4a2713aSLionel Sambuc   if (needsEHCleanup(dtorKind))
655f4a2713aSLionel Sambuc     pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
656f4a2713aSLionel Sambuc }
657f4a2713aSLionel Sambuc 
658f4a2713aSLionel Sambuc /// Checks whether the given constructor is a valid subject for the
659f4a2713aSLionel Sambuc /// complete-to-base constructor delegation optimization, i.e.
660f4a2713aSLionel Sambuc /// emitting the complete constructor as a simple call to the base
661f4a2713aSLionel Sambuc /// constructor.
IsConstructorDelegationValid(const CXXConstructorDecl * Ctor)662f4a2713aSLionel Sambuc static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
663f4a2713aSLionel Sambuc 
664f4a2713aSLionel Sambuc   // Currently we disable the optimization for classes with virtual
665f4a2713aSLionel Sambuc   // bases because (1) the addresses of parameter variables need to be
666f4a2713aSLionel Sambuc   // consistent across all initializers but (2) the delegate function
667f4a2713aSLionel Sambuc   // call necessarily creates a second copy of the parameter variable.
668f4a2713aSLionel Sambuc   //
669f4a2713aSLionel Sambuc   // The limiting example (purely theoretical AFAIK):
670f4a2713aSLionel Sambuc   //   struct A { A(int &c) { c++; } };
671f4a2713aSLionel Sambuc   //   struct B : virtual A {
672f4a2713aSLionel Sambuc   //     B(int count) : A(count) { printf("%d\n", count); }
673f4a2713aSLionel Sambuc   //   };
674f4a2713aSLionel Sambuc   // ...although even this example could in principle be emitted as a
675f4a2713aSLionel Sambuc   // delegation since the address of the parameter doesn't escape.
676f4a2713aSLionel Sambuc   if (Ctor->getParent()->getNumVBases()) {
677f4a2713aSLionel Sambuc     // TODO: white-list trivial vbase initializers.  This case wouldn't
678f4a2713aSLionel Sambuc     // be subject to the restrictions below.
679f4a2713aSLionel Sambuc 
680f4a2713aSLionel Sambuc     // TODO: white-list cases where:
681f4a2713aSLionel Sambuc     //  - there are no non-reference parameters to the constructor
682f4a2713aSLionel Sambuc     //  - the initializers don't access any non-reference parameters
683f4a2713aSLionel Sambuc     //  - the initializers don't take the address of non-reference
684f4a2713aSLionel Sambuc     //    parameters
685f4a2713aSLionel Sambuc     //  - etc.
686f4a2713aSLionel Sambuc     // If we ever add any of the above cases, remember that:
687f4a2713aSLionel Sambuc     //  - function-try-blocks will always blacklist this optimization
688f4a2713aSLionel Sambuc     //  - we need to perform the constructor prologue and cleanup in
689f4a2713aSLionel Sambuc     //    EmitConstructorBody.
690f4a2713aSLionel Sambuc 
691f4a2713aSLionel Sambuc     return false;
692f4a2713aSLionel Sambuc   }
693f4a2713aSLionel Sambuc 
694f4a2713aSLionel Sambuc   // We also disable the optimization for variadic functions because
695f4a2713aSLionel Sambuc   // it's impossible to "re-pass" varargs.
696f4a2713aSLionel Sambuc   if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
697f4a2713aSLionel Sambuc     return false;
698f4a2713aSLionel Sambuc 
699f4a2713aSLionel Sambuc   // FIXME: Decide if we can do a delegation of a delegating constructor.
700f4a2713aSLionel Sambuc   if (Ctor->isDelegatingConstructor())
701f4a2713aSLionel Sambuc     return false;
702f4a2713aSLionel Sambuc 
703f4a2713aSLionel Sambuc   return true;
704f4a2713aSLionel Sambuc }
705f4a2713aSLionel Sambuc 
706*0a6a1f1dSLionel Sambuc // Emit code in ctor (Prologue==true) or dtor (Prologue==false)
707*0a6a1f1dSLionel Sambuc // to poison the extra field paddings inserted under
708*0a6a1f1dSLionel Sambuc // -fsanitize-address-field-padding=1|2.
EmitAsanPrologueOrEpilogue(bool Prologue)709*0a6a1f1dSLionel Sambuc void CodeGenFunction::EmitAsanPrologueOrEpilogue(bool Prologue) {
710*0a6a1f1dSLionel Sambuc   ASTContext &Context = getContext();
711*0a6a1f1dSLionel Sambuc   const CXXRecordDecl *ClassDecl =
712*0a6a1f1dSLionel Sambuc       Prologue ? cast<CXXConstructorDecl>(CurGD.getDecl())->getParent()
713*0a6a1f1dSLionel Sambuc                : cast<CXXDestructorDecl>(CurGD.getDecl())->getParent();
714*0a6a1f1dSLionel Sambuc   if (!ClassDecl->mayInsertExtraPadding()) return;
715*0a6a1f1dSLionel Sambuc 
716*0a6a1f1dSLionel Sambuc   struct SizeAndOffset {
717*0a6a1f1dSLionel Sambuc     uint64_t Size;
718*0a6a1f1dSLionel Sambuc     uint64_t Offset;
719*0a6a1f1dSLionel Sambuc   };
720*0a6a1f1dSLionel Sambuc 
721*0a6a1f1dSLionel Sambuc   unsigned PtrSize = CGM.getDataLayout().getPointerSizeInBits();
722*0a6a1f1dSLionel Sambuc   const ASTRecordLayout &Info = Context.getASTRecordLayout(ClassDecl);
723*0a6a1f1dSLionel Sambuc 
724*0a6a1f1dSLionel Sambuc   // Populate sizes and offsets of fields.
725*0a6a1f1dSLionel Sambuc   SmallVector<SizeAndOffset, 16> SSV(Info.getFieldCount());
726*0a6a1f1dSLionel Sambuc   for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i)
727*0a6a1f1dSLionel Sambuc     SSV[i].Offset =
728*0a6a1f1dSLionel Sambuc         Context.toCharUnitsFromBits(Info.getFieldOffset(i)).getQuantity();
729*0a6a1f1dSLionel Sambuc 
730*0a6a1f1dSLionel Sambuc   size_t NumFields = 0;
731*0a6a1f1dSLionel Sambuc   for (const auto *Field : ClassDecl->fields()) {
732*0a6a1f1dSLionel Sambuc     const FieldDecl *D = Field;
733*0a6a1f1dSLionel Sambuc     std::pair<CharUnits, CharUnits> FieldInfo =
734*0a6a1f1dSLionel Sambuc         Context.getTypeInfoInChars(D->getType());
735*0a6a1f1dSLionel Sambuc     CharUnits FieldSize = FieldInfo.first;
736*0a6a1f1dSLionel Sambuc     assert(NumFields < SSV.size());
737*0a6a1f1dSLionel Sambuc     SSV[NumFields].Size = D->isBitField() ? 0 : FieldSize.getQuantity();
738*0a6a1f1dSLionel Sambuc     NumFields++;
739*0a6a1f1dSLionel Sambuc   }
740*0a6a1f1dSLionel Sambuc   assert(NumFields == SSV.size());
741*0a6a1f1dSLionel Sambuc   if (SSV.size() <= 1) return;
742*0a6a1f1dSLionel Sambuc 
743*0a6a1f1dSLionel Sambuc   // We will insert calls to __asan_* run-time functions.
744*0a6a1f1dSLionel Sambuc   // LLVM AddressSanitizer pass may decide to inline them later.
745*0a6a1f1dSLionel Sambuc   llvm::Type *Args[2] = {IntPtrTy, IntPtrTy};
746*0a6a1f1dSLionel Sambuc   llvm::FunctionType *FTy =
747*0a6a1f1dSLionel Sambuc       llvm::FunctionType::get(CGM.VoidTy, Args, false);
748*0a6a1f1dSLionel Sambuc   llvm::Constant *F = CGM.CreateRuntimeFunction(
749*0a6a1f1dSLionel Sambuc       FTy, Prologue ? "__asan_poison_intra_object_redzone"
750*0a6a1f1dSLionel Sambuc                     : "__asan_unpoison_intra_object_redzone");
751*0a6a1f1dSLionel Sambuc 
752*0a6a1f1dSLionel Sambuc   llvm::Value *ThisPtr = LoadCXXThis();
753*0a6a1f1dSLionel Sambuc   ThisPtr = Builder.CreatePtrToInt(ThisPtr, IntPtrTy);
754*0a6a1f1dSLionel Sambuc   uint64_t TypeSize = Info.getNonVirtualSize().getQuantity();
755*0a6a1f1dSLionel Sambuc   // For each field check if it has sufficient padding,
756*0a6a1f1dSLionel Sambuc   // if so (un)poison it with a call.
757*0a6a1f1dSLionel Sambuc   for (size_t i = 0; i < SSV.size(); i++) {
758*0a6a1f1dSLionel Sambuc     uint64_t AsanAlignment = 8;
759*0a6a1f1dSLionel Sambuc     uint64_t NextField = i == SSV.size() - 1 ? TypeSize : SSV[i + 1].Offset;
760*0a6a1f1dSLionel Sambuc     uint64_t PoisonSize = NextField - SSV[i].Offset - SSV[i].Size;
761*0a6a1f1dSLionel Sambuc     uint64_t EndOffset = SSV[i].Offset + SSV[i].Size;
762*0a6a1f1dSLionel Sambuc     if (PoisonSize < AsanAlignment || !SSV[i].Size ||
763*0a6a1f1dSLionel Sambuc         (NextField % AsanAlignment) != 0)
764*0a6a1f1dSLionel Sambuc       continue;
765*0a6a1f1dSLionel Sambuc     Builder.CreateCall2(
766*0a6a1f1dSLionel Sambuc         F, Builder.CreateAdd(ThisPtr, Builder.getIntN(PtrSize, EndOffset)),
767*0a6a1f1dSLionel Sambuc         Builder.getIntN(PtrSize, PoisonSize));
768*0a6a1f1dSLionel Sambuc   }
769*0a6a1f1dSLionel Sambuc }
770*0a6a1f1dSLionel Sambuc 
771f4a2713aSLionel Sambuc /// EmitConstructorBody - Emits the body of the current constructor.
EmitConstructorBody(FunctionArgList & Args)772f4a2713aSLionel Sambuc void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
773*0a6a1f1dSLionel Sambuc   EmitAsanPrologueOrEpilogue(true);
774f4a2713aSLionel Sambuc   const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
775f4a2713aSLionel Sambuc   CXXCtorType CtorType = CurGD.getCtorType();
776f4a2713aSLionel Sambuc 
777*0a6a1f1dSLionel Sambuc   assert((CGM.getTarget().getCXXABI().hasConstructorVariants() ||
778*0a6a1f1dSLionel Sambuc           CtorType == Ctor_Complete) &&
779*0a6a1f1dSLionel Sambuc          "can only generate complete ctor for this ABI");
780*0a6a1f1dSLionel Sambuc 
781f4a2713aSLionel Sambuc   // Before we go any further, try the complete->base constructor
782f4a2713aSLionel Sambuc   // delegation optimization.
783f4a2713aSLionel Sambuc   if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
784f4a2713aSLionel Sambuc       CGM.getTarget().getCXXABI().hasConstructorVariants()) {
785f4a2713aSLionel Sambuc     EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args, Ctor->getLocEnd());
786f4a2713aSLionel Sambuc     return;
787f4a2713aSLionel Sambuc   }
788f4a2713aSLionel Sambuc 
789*0a6a1f1dSLionel Sambuc   const FunctionDecl *Definition = 0;
790*0a6a1f1dSLionel Sambuc   Stmt *Body = Ctor->getBody(Definition);
791*0a6a1f1dSLionel Sambuc   assert(Definition == Ctor && "emitting wrong constructor body");
792f4a2713aSLionel Sambuc 
793f4a2713aSLionel Sambuc   // Enter the function-try-block before the constructor prologue if
794f4a2713aSLionel Sambuc   // applicable.
795f4a2713aSLionel Sambuc   bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
796f4a2713aSLionel Sambuc   if (IsTryBody)
797f4a2713aSLionel Sambuc     EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
798f4a2713aSLionel Sambuc 
799*0a6a1f1dSLionel Sambuc   RegionCounter Cnt = getPGORegionCounter(Body);
800*0a6a1f1dSLionel Sambuc   Cnt.beginRegion(Builder);
801*0a6a1f1dSLionel Sambuc 
802f4a2713aSLionel Sambuc   RunCleanupsScope RunCleanups(*this);
803f4a2713aSLionel Sambuc 
804f4a2713aSLionel Sambuc   // TODO: in restricted cases, we can emit the vbase initializers of
805f4a2713aSLionel Sambuc   // a complete ctor and then delegate to the base ctor.
806f4a2713aSLionel Sambuc 
807f4a2713aSLionel Sambuc   // Emit the constructor prologue, i.e. the base and member
808f4a2713aSLionel Sambuc   // initializers.
809f4a2713aSLionel Sambuc   EmitCtorPrologue(Ctor, CtorType, Args);
810f4a2713aSLionel Sambuc 
811f4a2713aSLionel Sambuc   // Emit the body of the statement.
812f4a2713aSLionel Sambuc   if (IsTryBody)
813f4a2713aSLionel Sambuc     EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
814f4a2713aSLionel Sambuc   else if (Body)
815f4a2713aSLionel Sambuc     EmitStmt(Body);
816f4a2713aSLionel Sambuc 
817f4a2713aSLionel Sambuc   // Emit any cleanup blocks associated with the member or base
818f4a2713aSLionel Sambuc   // initializers, which includes (along the exceptional path) the
819f4a2713aSLionel Sambuc   // destructors for those members and bases that were fully
820f4a2713aSLionel Sambuc   // constructed.
821f4a2713aSLionel Sambuc   RunCleanups.ForceCleanup();
822f4a2713aSLionel Sambuc 
823f4a2713aSLionel Sambuc   if (IsTryBody)
824f4a2713aSLionel Sambuc     ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
825f4a2713aSLionel Sambuc }
826f4a2713aSLionel Sambuc 
827f4a2713aSLionel Sambuc namespace {
828f4a2713aSLionel Sambuc   /// RAII object to indicate that codegen is copying the value representation
829f4a2713aSLionel Sambuc   /// instead of the object representation. Useful when copying a struct or
830f4a2713aSLionel Sambuc   /// class which has uninitialized members and we're only performing
831f4a2713aSLionel Sambuc   /// lvalue-to-rvalue conversion on the object but not its members.
832f4a2713aSLionel Sambuc   class CopyingValueRepresentation {
833f4a2713aSLionel Sambuc   public:
CopyingValueRepresentation(CodeGenFunction & CGF)834f4a2713aSLionel Sambuc     explicit CopyingValueRepresentation(CodeGenFunction &CGF)
835*0a6a1f1dSLionel Sambuc         : CGF(CGF), OldSanOpts(CGF.SanOpts) {
836*0a6a1f1dSLionel Sambuc       CGF.SanOpts.set(SanitizerKind::Bool, false);
837*0a6a1f1dSLionel Sambuc       CGF.SanOpts.set(SanitizerKind::Enum, false);
838f4a2713aSLionel Sambuc     }
~CopyingValueRepresentation()839f4a2713aSLionel Sambuc     ~CopyingValueRepresentation() {
840f4a2713aSLionel Sambuc       CGF.SanOpts = OldSanOpts;
841f4a2713aSLionel Sambuc     }
842f4a2713aSLionel Sambuc   private:
843f4a2713aSLionel Sambuc     CodeGenFunction &CGF;
844*0a6a1f1dSLionel Sambuc     SanitizerSet OldSanOpts;
845f4a2713aSLionel Sambuc   };
846f4a2713aSLionel Sambuc }
847f4a2713aSLionel Sambuc 
848f4a2713aSLionel Sambuc namespace {
849f4a2713aSLionel Sambuc   class FieldMemcpyizer {
850f4a2713aSLionel Sambuc   public:
FieldMemcpyizer(CodeGenFunction & CGF,const CXXRecordDecl * ClassDecl,const VarDecl * SrcRec)851f4a2713aSLionel Sambuc     FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl,
852f4a2713aSLionel Sambuc                     const VarDecl *SrcRec)
853f4a2713aSLionel Sambuc       : CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec),
854f4a2713aSLionel Sambuc         RecLayout(CGF.getContext().getASTRecordLayout(ClassDecl)),
855*0a6a1f1dSLionel Sambuc         FirstField(nullptr), LastField(nullptr), FirstFieldOffset(0),
856*0a6a1f1dSLionel Sambuc         LastFieldOffset(0), LastAddedFieldIndex(0) {}
857f4a2713aSLionel Sambuc 
isMemcpyableField(FieldDecl * F) const858*0a6a1f1dSLionel Sambuc     bool isMemcpyableField(FieldDecl *F) const {
859*0a6a1f1dSLionel Sambuc       // Never memcpy fields when we are adding poisoned paddings.
860*0a6a1f1dSLionel Sambuc       if (CGF.getContext().getLangOpts().SanitizeAddressFieldPadding)
861*0a6a1f1dSLionel Sambuc         return false;
862f4a2713aSLionel Sambuc       Qualifiers Qual = F->getType().getQualifiers();
863f4a2713aSLionel Sambuc       if (Qual.hasVolatile() || Qual.hasObjCLifetime())
864f4a2713aSLionel Sambuc         return false;
865f4a2713aSLionel Sambuc       return true;
866f4a2713aSLionel Sambuc     }
867f4a2713aSLionel Sambuc 
addMemcpyableField(FieldDecl * F)868f4a2713aSLionel Sambuc     void addMemcpyableField(FieldDecl *F) {
869*0a6a1f1dSLionel Sambuc       if (!FirstField)
870f4a2713aSLionel Sambuc         addInitialField(F);
871f4a2713aSLionel Sambuc       else
872f4a2713aSLionel Sambuc         addNextField(F);
873f4a2713aSLionel Sambuc     }
874f4a2713aSLionel Sambuc 
getMemcpySize(uint64_t FirstByteOffset) const875*0a6a1f1dSLionel Sambuc     CharUnits getMemcpySize(uint64_t FirstByteOffset) const {
876f4a2713aSLionel Sambuc       unsigned LastFieldSize =
877f4a2713aSLionel Sambuc         LastField->isBitField() ?
878f4a2713aSLionel Sambuc           LastField->getBitWidthValue(CGF.getContext()) :
879f4a2713aSLionel Sambuc           CGF.getContext().getTypeSize(LastField->getType());
880f4a2713aSLionel Sambuc       uint64_t MemcpySizeBits =
881*0a6a1f1dSLionel Sambuc         LastFieldOffset + LastFieldSize - FirstByteOffset +
882f4a2713aSLionel Sambuc         CGF.getContext().getCharWidth() - 1;
883f4a2713aSLionel Sambuc       CharUnits MemcpySize =
884f4a2713aSLionel Sambuc         CGF.getContext().toCharUnitsFromBits(MemcpySizeBits);
885f4a2713aSLionel Sambuc       return MemcpySize;
886f4a2713aSLionel Sambuc     }
887f4a2713aSLionel Sambuc 
emitMemcpy()888f4a2713aSLionel Sambuc     void emitMemcpy() {
889f4a2713aSLionel Sambuc       // Give the subclass a chance to bail out if it feels the memcpy isn't
890f4a2713aSLionel Sambuc       // worth it (e.g. Hasn't aggregated enough data).
891*0a6a1f1dSLionel Sambuc       if (!FirstField) {
892f4a2713aSLionel Sambuc         return;
893f4a2713aSLionel Sambuc       }
894f4a2713aSLionel Sambuc 
895f4a2713aSLionel Sambuc       CharUnits Alignment;
896f4a2713aSLionel Sambuc 
897*0a6a1f1dSLionel Sambuc       uint64_t FirstByteOffset;
898f4a2713aSLionel Sambuc       if (FirstField->isBitField()) {
899f4a2713aSLionel Sambuc         const CGRecordLayout &RL =
900f4a2713aSLionel Sambuc           CGF.getTypes().getCGRecordLayout(FirstField->getParent());
901f4a2713aSLionel Sambuc         const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField);
902f4a2713aSLionel Sambuc         Alignment = CharUnits::fromQuantity(BFInfo.StorageAlignment);
903*0a6a1f1dSLionel Sambuc         // FirstFieldOffset is not appropriate for bitfields,
904*0a6a1f1dSLionel Sambuc         // it won't tell us what the storage offset should be and thus might not
905*0a6a1f1dSLionel Sambuc         // be properly aligned.
906*0a6a1f1dSLionel Sambuc         //
907*0a6a1f1dSLionel Sambuc         // Instead calculate the storage offset using the offset of the field in
908*0a6a1f1dSLionel Sambuc         // the struct type.
909*0a6a1f1dSLionel Sambuc         const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
910*0a6a1f1dSLionel Sambuc         FirstByteOffset =
911*0a6a1f1dSLionel Sambuc             DL.getStructLayout(RL.getLLVMType())
912*0a6a1f1dSLionel Sambuc                 ->getElementOffsetInBits(RL.getLLVMFieldNo(FirstField));
913f4a2713aSLionel Sambuc       } else {
914f4a2713aSLionel Sambuc         Alignment = CGF.getContext().getDeclAlign(FirstField);
915*0a6a1f1dSLionel Sambuc         FirstByteOffset = FirstFieldOffset;
916f4a2713aSLionel Sambuc       }
917f4a2713aSLionel Sambuc 
918*0a6a1f1dSLionel Sambuc       assert((CGF.getContext().toCharUnitsFromBits(FirstByteOffset) %
919f4a2713aSLionel Sambuc               Alignment) == 0 && "Bad field alignment.");
920f4a2713aSLionel Sambuc 
921*0a6a1f1dSLionel Sambuc       CharUnits MemcpySize = getMemcpySize(FirstByteOffset);
922f4a2713aSLionel Sambuc       QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
923f4a2713aSLionel Sambuc       llvm::Value *ThisPtr = CGF.LoadCXXThis();
924f4a2713aSLionel Sambuc       LValue DestLV = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
925f4a2713aSLionel Sambuc       LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField);
926f4a2713aSLionel Sambuc       llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec));
927f4a2713aSLionel Sambuc       LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
928f4a2713aSLionel Sambuc       LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField);
929f4a2713aSLionel Sambuc 
930f4a2713aSLionel Sambuc       emitMemcpyIR(Dest.isBitField() ? Dest.getBitFieldAddr() : Dest.getAddress(),
931f4a2713aSLionel Sambuc                    Src.isBitField() ? Src.getBitFieldAddr() : Src.getAddress(),
932f4a2713aSLionel Sambuc                    MemcpySize, Alignment);
933f4a2713aSLionel Sambuc       reset();
934f4a2713aSLionel Sambuc     }
935f4a2713aSLionel Sambuc 
reset()936f4a2713aSLionel Sambuc     void reset() {
937*0a6a1f1dSLionel Sambuc       FirstField = nullptr;
938f4a2713aSLionel Sambuc     }
939f4a2713aSLionel Sambuc 
940f4a2713aSLionel Sambuc   protected:
941f4a2713aSLionel Sambuc     CodeGenFunction &CGF;
942f4a2713aSLionel Sambuc     const CXXRecordDecl *ClassDecl;
943f4a2713aSLionel Sambuc 
944f4a2713aSLionel Sambuc   private:
945f4a2713aSLionel Sambuc 
emitMemcpyIR(llvm::Value * DestPtr,llvm::Value * SrcPtr,CharUnits Size,CharUnits Alignment)946f4a2713aSLionel Sambuc     void emitMemcpyIR(llvm::Value *DestPtr, llvm::Value *SrcPtr,
947f4a2713aSLionel Sambuc                       CharUnits Size, CharUnits Alignment) {
948f4a2713aSLionel Sambuc       llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
949f4a2713aSLionel Sambuc       llvm::Type *DBP =
950f4a2713aSLionel Sambuc         llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), DPT->getAddressSpace());
951f4a2713aSLionel Sambuc       DestPtr = CGF.Builder.CreateBitCast(DestPtr, DBP);
952f4a2713aSLionel Sambuc 
953f4a2713aSLionel Sambuc       llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
954f4a2713aSLionel Sambuc       llvm::Type *SBP =
955f4a2713aSLionel Sambuc         llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), SPT->getAddressSpace());
956f4a2713aSLionel Sambuc       SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, SBP);
957f4a2713aSLionel Sambuc 
958f4a2713aSLionel Sambuc       CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity(),
959f4a2713aSLionel Sambuc                                Alignment.getQuantity());
960f4a2713aSLionel Sambuc     }
961f4a2713aSLionel Sambuc 
addInitialField(FieldDecl * F)962f4a2713aSLionel Sambuc     void addInitialField(FieldDecl *F) {
963f4a2713aSLionel Sambuc         FirstField = F;
964f4a2713aSLionel Sambuc         LastField = F;
965f4a2713aSLionel Sambuc         FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex());
966f4a2713aSLionel Sambuc         LastFieldOffset = FirstFieldOffset;
967f4a2713aSLionel Sambuc         LastAddedFieldIndex = F->getFieldIndex();
968f4a2713aSLionel Sambuc         return;
969f4a2713aSLionel Sambuc       }
970f4a2713aSLionel Sambuc 
addNextField(FieldDecl * F)971f4a2713aSLionel Sambuc     void addNextField(FieldDecl *F) {
972f4a2713aSLionel Sambuc       // For the most part, the following invariant will hold:
973f4a2713aSLionel Sambuc       //   F->getFieldIndex() == LastAddedFieldIndex + 1
974f4a2713aSLionel Sambuc       // The one exception is that Sema won't add a copy-initializer for an
975f4a2713aSLionel Sambuc       // unnamed bitfield, which will show up here as a gap in the sequence.
976f4a2713aSLionel Sambuc       assert(F->getFieldIndex() >= LastAddedFieldIndex + 1 &&
977f4a2713aSLionel Sambuc              "Cannot aggregate fields out of order.");
978f4a2713aSLionel Sambuc       LastAddedFieldIndex = F->getFieldIndex();
979f4a2713aSLionel Sambuc 
980f4a2713aSLionel Sambuc       // The 'first' and 'last' fields are chosen by offset, rather than field
981f4a2713aSLionel Sambuc       // index. This allows the code to support bitfields, as well as regular
982f4a2713aSLionel Sambuc       // fields.
983f4a2713aSLionel Sambuc       uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex());
984f4a2713aSLionel Sambuc       if (FOffset < FirstFieldOffset) {
985f4a2713aSLionel Sambuc         FirstField = F;
986f4a2713aSLionel Sambuc         FirstFieldOffset = FOffset;
987f4a2713aSLionel Sambuc       } else if (FOffset > LastFieldOffset) {
988f4a2713aSLionel Sambuc         LastField = F;
989f4a2713aSLionel Sambuc         LastFieldOffset = FOffset;
990f4a2713aSLionel Sambuc       }
991f4a2713aSLionel Sambuc     }
992f4a2713aSLionel Sambuc 
993f4a2713aSLionel Sambuc     const VarDecl *SrcRec;
994f4a2713aSLionel Sambuc     const ASTRecordLayout &RecLayout;
995f4a2713aSLionel Sambuc     FieldDecl *FirstField;
996f4a2713aSLionel Sambuc     FieldDecl *LastField;
997f4a2713aSLionel Sambuc     uint64_t FirstFieldOffset, LastFieldOffset;
998f4a2713aSLionel Sambuc     unsigned LastAddedFieldIndex;
999f4a2713aSLionel Sambuc   };
1000f4a2713aSLionel Sambuc 
1001f4a2713aSLionel Sambuc   class ConstructorMemcpyizer : public FieldMemcpyizer {
1002f4a2713aSLionel Sambuc   private:
1003f4a2713aSLionel Sambuc 
1004f4a2713aSLionel Sambuc     /// Get source argument for copy constructor. Returns null if not a copy
1005f4a2713aSLionel Sambuc     /// constructor.
getTrivialCopySource(CodeGenFunction & CGF,const CXXConstructorDecl * CD,FunctionArgList & Args)1006*0a6a1f1dSLionel Sambuc     static const VarDecl *getTrivialCopySource(CodeGenFunction &CGF,
1007*0a6a1f1dSLionel Sambuc                                                const CXXConstructorDecl *CD,
1008f4a2713aSLionel Sambuc                                                FunctionArgList &Args) {
1009f4a2713aSLionel Sambuc       if (CD->isCopyOrMoveConstructor() && CD->isDefaulted())
1010*0a6a1f1dSLionel Sambuc         return Args[CGF.CGM.getCXXABI().getSrcArgforCopyCtor(CD, Args)];
1011*0a6a1f1dSLionel Sambuc       return nullptr;
1012f4a2713aSLionel Sambuc     }
1013f4a2713aSLionel Sambuc 
1014f4a2713aSLionel Sambuc     // Returns true if a CXXCtorInitializer represents a member initialization
1015f4a2713aSLionel Sambuc     // that can be rolled into a memcpy.
isMemberInitMemcpyable(CXXCtorInitializer * MemberInit) const1016f4a2713aSLionel Sambuc     bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const {
1017f4a2713aSLionel Sambuc       if (!MemcpyableCtor)
1018f4a2713aSLionel Sambuc         return false;
1019f4a2713aSLionel Sambuc       FieldDecl *Field = MemberInit->getMember();
1020*0a6a1f1dSLionel Sambuc       assert(Field && "No field for member init.");
1021f4a2713aSLionel Sambuc       QualType FieldType = Field->getType();
1022f4a2713aSLionel Sambuc       CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
1023f4a2713aSLionel Sambuc 
1024f4a2713aSLionel Sambuc       // Bail out on non-POD, not-trivially-constructable members.
1025f4a2713aSLionel Sambuc       if (!(CE && CE->getConstructor()->isTrivial()) &&
1026f4a2713aSLionel Sambuc           !(FieldType.isTriviallyCopyableType(CGF.getContext()) ||
1027f4a2713aSLionel Sambuc             FieldType->isReferenceType()))
1028f4a2713aSLionel Sambuc         return false;
1029f4a2713aSLionel Sambuc 
1030f4a2713aSLionel Sambuc       // Bail out on volatile fields.
1031f4a2713aSLionel Sambuc       if (!isMemcpyableField(Field))
1032f4a2713aSLionel Sambuc         return false;
1033f4a2713aSLionel Sambuc 
1034f4a2713aSLionel Sambuc       // Otherwise we're good.
1035f4a2713aSLionel Sambuc       return true;
1036f4a2713aSLionel Sambuc     }
1037f4a2713aSLionel Sambuc 
1038f4a2713aSLionel Sambuc   public:
ConstructorMemcpyizer(CodeGenFunction & CGF,const CXXConstructorDecl * CD,FunctionArgList & Args)1039f4a2713aSLionel Sambuc     ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD,
1040f4a2713aSLionel Sambuc                           FunctionArgList &Args)
1041*0a6a1f1dSLionel Sambuc       : FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CGF, CD, Args)),
1042f4a2713aSLionel Sambuc         ConstructorDecl(CD),
1043f4a2713aSLionel Sambuc         MemcpyableCtor(CD->isDefaulted() &&
1044f4a2713aSLionel Sambuc                        CD->isCopyOrMoveConstructor() &&
1045f4a2713aSLionel Sambuc                        CGF.getLangOpts().getGC() == LangOptions::NonGC),
1046f4a2713aSLionel Sambuc         Args(Args) { }
1047f4a2713aSLionel Sambuc 
addMemberInitializer(CXXCtorInitializer * MemberInit)1048f4a2713aSLionel Sambuc     void addMemberInitializer(CXXCtorInitializer *MemberInit) {
1049f4a2713aSLionel Sambuc       if (isMemberInitMemcpyable(MemberInit)) {
1050f4a2713aSLionel Sambuc         AggregatedInits.push_back(MemberInit);
1051f4a2713aSLionel Sambuc         addMemcpyableField(MemberInit->getMember());
1052f4a2713aSLionel Sambuc       } else {
1053f4a2713aSLionel Sambuc         emitAggregatedInits();
1054f4a2713aSLionel Sambuc         EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit,
1055f4a2713aSLionel Sambuc                               ConstructorDecl, Args);
1056f4a2713aSLionel Sambuc       }
1057f4a2713aSLionel Sambuc     }
1058f4a2713aSLionel Sambuc 
emitAggregatedInits()1059f4a2713aSLionel Sambuc     void emitAggregatedInits() {
1060f4a2713aSLionel Sambuc       if (AggregatedInits.size() <= 1) {
1061f4a2713aSLionel Sambuc         // This memcpy is too small to be worthwhile. Fall back on default
1062f4a2713aSLionel Sambuc         // codegen.
1063f4a2713aSLionel Sambuc         if (!AggregatedInits.empty()) {
1064f4a2713aSLionel Sambuc           CopyingValueRepresentation CVR(CGF);
1065f4a2713aSLionel Sambuc           EmitMemberInitializer(CGF, ConstructorDecl->getParent(),
1066f4a2713aSLionel Sambuc                                 AggregatedInits[0], ConstructorDecl, Args);
1067f4a2713aSLionel Sambuc         }
1068f4a2713aSLionel Sambuc         reset();
1069f4a2713aSLionel Sambuc         return;
1070f4a2713aSLionel Sambuc       }
1071f4a2713aSLionel Sambuc 
1072f4a2713aSLionel Sambuc       pushEHDestructors();
1073f4a2713aSLionel Sambuc       emitMemcpy();
1074f4a2713aSLionel Sambuc       AggregatedInits.clear();
1075f4a2713aSLionel Sambuc     }
1076f4a2713aSLionel Sambuc 
pushEHDestructors()1077f4a2713aSLionel Sambuc     void pushEHDestructors() {
1078f4a2713aSLionel Sambuc       llvm::Value *ThisPtr = CGF.LoadCXXThis();
1079f4a2713aSLionel Sambuc       QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
1080f4a2713aSLionel Sambuc       LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
1081f4a2713aSLionel Sambuc 
1082f4a2713aSLionel Sambuc       for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
1083f4a2713aSLionel Sambuc         QualType FieldType = AggregatedInits[i]->getMember()->getType();
1084f4a2713aSLionel Sambuc         QualType::DestructionKind dtorKind = FieldType.isDestructedType();
1085f4a2713aSLionel Sambuc         if (CGF.needsEHCleanup(dtorKind))
1086f4a2713aSLionel Sambuc           CGF.pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
1087f4a2713aSLionel Sambuc       }
1088f4a2713aSLionel Sambuc     }
1089f4a2713aSLionel Sambuc 
finish()1090f4a2713aSLionel Sambuc     void finish() {
1091f4a2713aSLionel Sambuc       emitAggregatedInits();
1092f4a2713aSLionel Sambuc     }
1093f4a2713aSLionel Sambuc 
1094f4a2713aSLionel Sambuc   private:
1095f4a2713aSLionel Sambuc     const CXXConstructorDecl *ConstructorDecl;
1096f4a2713aSLionel Sambuc     bool MemcpyableCtor;
1097f4a2713aSLionel Sambuc     FunctionArgList &Args;
1098f4a2713aSLionel Sambuc     SmallVector<CXXCtorInitializer*, 16> AggregatedInits;
1099f4a2713aSLionel Sambuc   };
1100f4a2713aSLionel Sambuc 
1101f4a2713aSLionel Sambuc   class AssignmentMemcpyizer : public FieldMemcpyizer {
1102f4a2713aSLionel Sambuc   private:
1103f4a2713aSLionel Sambuc 
1104f4a2713aSLionel Sambuc     // Returns the memcpyable field copied by the given statement, if one
1105f4a2713aSLionel Sambuc     // exists. Otherwise returns null.
getMemcpyableField(Stmt * S)1106f4a2713aSLionel Sambuc     FieldDecl *getMemcpyableField(Stmt *S) {
1107f4a2713aSLionel Sambuc       if (!AssignmentsMemcpyable)
1108*0a6a1f1dSLionel Sambuc         return nullptr;
1109f4a2713aSLionel Sambuc       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
1110f4a2713aSLionel Sambuc         // Recognise trivial assignments.
1111f4a2713aSLionel Sambuc         if (BO->getOpcode() != BO_Assign)
1112*0a6a1f1dSLionel Sambuc           return nullptr;
1113f4a2713aSLionel Sambuc         MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS());
1114f4a2713aSLionel Sambuc         if (!ME)
1115*0a6a1f1dSLionel Sambuc           return nullptr;
1116f4a2713aSLionel Sambuc         FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1117f4a2713aSLionel Sambuc         if (!Field || !isMemcpyableField(Field))
1118*0a6a1f1dSLionel Sambuc           return nullptr;
1119f4a2713aSLionel Sambuc         Stmt *RHS = BO->getRHS();
1120f4a2713aSLionel Sambuc         if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS))
1121f4a2713aSLionel Sambuc           RHS = EC->getSubExpr();
1122f4a2713aSLionel Sambuc         if (!RHS)
1123*0a6a1f1dSLionel Sambuc           return nullptr;
1124f4a2713aSLionel Sambuc         MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS);
1125f4a2713aSLionel Sambuc         if (dyn_cast<FieldDecl>(ME2->getMemberDecl()) != Field)
1126*0a6a1f1dSLionel Sambuc           return nullptr;
1127f4a2713aSLionel Sambuc         return Field;
1128f4a2713aSLionel Sambuc       } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) {
1129f4a2713aSLionel Sambuc         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl());
1130f4a2713aSLionel Sambuc         if (!(MD && (MD->isCopyAssignmentOperator() ||
1131f4a2713aSLionel Sambuc                        MD->isMoveAssignmentOperator()) &&
1132f4a2713aSLionel Sambuc               MD->isTrivial()))
1133*0a6a1f1dSLionel Sambuc           return nullptr;
1134f4a2713aSLionel Sambuc         MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument());
1135f4a2713aSLionel Sambuc         if (!IOA)
1136*0a6a1f1dSLionel Sambuc           return nullptr;
1137f4a2713aSLionel Sambuc         FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl());
1138f4a2713aSLionel Sambuc         if (!Field || !isMemcpyableField(Field))
1139*0a6a1f1dSLionel Sambuc           return nullptr;
1140f4a2713aSLionel Sambuc         MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0));
1141f4a2713aSLionel Sambuc         if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl()))
1142*0a6a1f1dSLionel Sambuc           return nullptr;
1143f4a2713aSLionel Sambuc         return Field;
1144f4a2713aSLionel Sambuc       } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1145f4a2713aSLionel Sambuc         FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1146f4a2713aSLionel Sambuc         if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy)
1147*0a6a1f1dSLionel Sambuc           return nullptr;
1148f4a2713aSLionel Sambuc         Expr *DstPtr = CE->getArg(0);
1149f4a2713aSLionel Sambuc         if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr))
1150f4a2713aSLionel Sambuc           DstPtr = DC->getSubExpr();
1151f4a2713aSLionel Sambuc         UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr);
1152f4a2713aSLionel Sambuc         if (!DUO || DUO->getOpcode() != UO_AddrOf)
1153*0a6a1f1dSLionel Sambuc           return nullptr;
1154f4a2713aSLionel Sambuc         MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr());
1155f4a2713aSLionel Sambuc         if (!ME)
1156*0a6a1f1dSLionel Sambuc           return nullptr;
1157f4a2713aSLionel Sambuc         FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1158f4a2713aSLionel Sambuc         if (!Field || !isMemcpyableField(Field))
1159*0a6a1f1dSLionel Sambuc           return nullptr;
1160f4a2713aSLionel Sambuc         Expr *SrcPtr = CE->getArg(1);
1161f4a2713aSLionel Sambuc         if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr))
1162f4a2713aSLionel Sambuc           SrcPtr = SC->getSubExpr();
1163f4a2713aSLionel Sambuc         UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr);
1164f4a2713aSLionel Sambuc         if (!SUO || SUO->getOpcode() != UO_AddrOf)
1165*0a6a1f1dSLionel Sambuc           return nullptr;
1166f4a2713aSLionel Sambuc         MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr());
1167f4a2713aSLionel Sambuc         if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl()))
1168*0a6a1f1dSLionel Sambuc           return nullptr;
1169f4a2713aSLionel Sambuc         return Field;
1170f4a2713aSLionel Sambuc       }
1171f4a2713aSLionel Sambuc 
1172*0a6a1f1dSLionel Sambuc       return nullptr;
1173f4a2713aSLionel Sambuc     }
1174f4a2713aSLionel Sambuc 
1175f4a2713aSLionel Sambuc     bool AssignmentsMemcpyable;
1176f4a2713aSLionel Sambuc     SmallVector<Stmt*, 16> AggregatedStmts;
1177f4a2713aSLionel Sambuc 
1178f4a2713aSLionel Sambuc   public:
1179f4a2713aSLionel Sambuc 
AssignmentMemcpyizer(CodeGenFunction & CGF,const CXXMethodDecl * AD,FunctionArgList & Args)1180f4a2713aSLionel Sambuc     AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD,
1181f4a2713aSLionel Sambuc                          FunctionArgList &Args)
1182f4a2713aSLionel Sambuc       : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]),
1183f4a2713aSLionel Sambuc         AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) {
1184f4a2713aSLionel Sambuc       assert(Args.size() == 2);
1185f4a2713aSLionel Sambuc     }
1186f4a2713aSLionel Sambuc 
emitAssignment(Stmt * S)1187f4a2713aSLionel Sambuc     void emitAssignment(Stmt *S) {
1188f4a2713aSLionel Sambuc       FieldDecl *F = getMemcpyableField(S);
1189f4a2713aSLionel Sambuc       if (F) {
1190f4a2713aSLionel Sambuc         addMemcpyableField(F);
1191f4a2713aSLionel Sambuc         AggregatedStmts.push_back(S);
1192f4a2713aSLionel Sambuc       } else {
1193f4a2713aSLionel Sambuc         emitAggregatedStmts();
1194f4a2713aSLionel Sambuc         CGF.EmitStmt(S);
1195f4a2713aSLionel Sambuc       }
1196f4a2713aSLionel Sambuc     }
1197f4a2713aSLionel Sambuc 
emitAggregatedStmts()1198f4a2713aSLionel Sambuc     void emitAggregatedStmts() {
1199f4a2713aSLionel Sambuc       if (AggregatedStmts.size() <= 1) {
1200f4a2713aSLionel Sambuc         if (!AggregatedStmts.empty()) {
1201f4a2713aSLionel Sambuc           CopyingValueRepresentation CVR(CGF);
1202f4a2713aSLionel Sambuc           CGF.EmitStmt(AggregatedStmts[0]);
1203f4a2713aSLionel Sambuc         }
1204f4a2713aSLionel Sambuc         reset();
1205f4a2713aSLionel Sambuc       }
1206f4a2713aSLionel Sambuc 
1207f4a2713aSLionel Sambuc       emitMemcpy();
1208f4a2713aSLionel Sambuc       AggregatedStmts.clear();
1209f4a2713aSLionel Sambuc     }
1210f4a2713aSLionel Sambuc 
finish()1211f4a2713aSLionel Sambuc     void finish() {
1212f4a2713aSLionel Sambuc       emitAggregatedStmts();
1213f4a2713aSLionel Sambuc     }
1214f4a2713aSLionel Sambuc   };
1215f4a2713aSLionel Sambuc 
1216f4a2713aSLionel Sambuc }
1217f4a2713aSLionel Sambuc 
1218f4a2713aSLionel Sambuc /// EmitCtorPrologue - This routine generates necessary code to initialize
1219f4a2713aSLionel Sambuc /// base classes and non-static data members belonging to this constructor.
EmitCtorPrologue(const CXXConstructorDecl * CD,CXXCtorType CtorType,FunctionArgList & Args)1220f4a2713aSLionel Sambuc void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
1221f4a2713aSLionel Sambuc                                        CXXCtorType CtorType,
1222f4a2713aSLionel Sambuc                                        FunctionArgList &Args) {
1223f4a2713aSLionel Sambuc   if (CD->isDelegatingConstructor())
1224f4a2713aSLionel Sambuc     return EmitDelegatingCXXConstructorCall(CD, Args);
1225f4a2713aSLionel Sambuc 
1226f4a2713aSLionel Sambuc   const CXXRecordDecl *ClassDecl = CD->getParent();
1227f4a2713aSLionel Sambuc 
1228f4a2713aSLionel Sambuc   CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
1229f4a2713aSLionel Sambuc                                           E = CD->init_end();
1230f4a2713aSLionel Sambuc 
1231*0a6a1f1dSLionel Sambuc   llvm::BasicBlock *BaseCtorContinueBB = nullptr;
1232f4a2713aSLionel Sambuc   if (ClassDecl->getNumVBases() &&
1233f4a2713aSLionel Sambuc       !CGM.getTarget().getCXXABI().hasConstructorVariants()) {
1234f4a2713aSLionel Sambuc     // The ABIs that don't have constructor variants need to put a branch
1235f4a2713aSLionel Sambuc     // before the virtual base initialization code.
1236f4a2713aSLionel Sambuc     BaseCtorContinueBB =
1237f4a2713aSLionel Sambuc       CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this, ClassDecl);
1238f4a2713aSLionel Sambuc     assert(BaseCtorContinueBB);
1239f4a2713aSLionel Sambuc   }
1240f4a2713aSLionel Sambuc 
1241f4a2713aSLionel Sambuc   // Virtual base initializers first.
1242f4a2713aSLionel Sambuc   for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
1243f4a2713aSLionel Sambuc     EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
1244f4a2713aSLionel Sambuc   }
1245f4a2713aSLionel Sambuc 
1246f4a2713aSLionel Sambuc   if (BaseCtorContinueBB) {
1247f4a2713aSLionel Sambuc     // Complete object handler should continue to the remaining initializers.
1248f4a2713aSLionel Sambuc     Builder.CreateBr(BaseCtorContinueBB);
1249f4a2713aSLionel Sambuc     EmitBlock(BaseCtorContinueBB);
1250f4a2713aSLionel Sambuc   }
1251f4a2713aSLionel Sambuc 
1252f4a2713aSLionel Sambuc   // Then, non-virtual base initializers.
1253f4a2713aSLionel Sambuc   for (; B != E && (*B)->isBaseInitializer(); B++) {
1254f4a2713aSLionel Sambuc     assert(!(*B)->isBaseVirtual());
1255f4a2713aSLionel Sambuc     EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
1256f4a2713aSLionel Sambuc   }
1257f4a2713aSLionel Sambuc 
1258f4a2713aSLionel Sambuc   InitializeVTablePointers(ClassDecl);
1259f4a2713aSLionel Sambuc 
1260f4a2713aSLionel Sambuc   // And finally, initialize class members.
1261f4a2713aSLionel Sambuc   FieldConstructionScope FCS(*this, CXXThisValue);
1262f4a2713aSLionel Sambuc   ConstructorMemcpyizer CM(*this, CD, Args);
1263f4a2713aSLionel Sambuc   for (; B != E; B++) {
1264f4a2713aSLionel Sambuc     CXXCtorInitializer *Member = (*B);
1265f4a2713aSLionel Sambuc     assert(!Member->isBaseInitializer());
1266f4a2713aSLionel Sambuc     assert(Member->isAnyMemberInitializer() &&
1267f4a2713aSLionel Sambuc            "Delegating initializer on non-delegating constructor");
1268f4a2713aSLionel Sambuc     CM.addMemberInitializer(Member);
1269f4a2713aSLionel Sambuc   }
1270f4a2713aSLionel Sambuc   CM.finish();
1271f4a2713aSLionel Sambuc }
1272f4a2713aSLionel Sambuc 
1273f4a2713aSLionel Sambuc static bool
1274f4a2713aSLionel Sambuc FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
1275f4a2713aSLionel Sambuc 
1276f4a2713aSLionel Sambuc static bool
HasTrivialDestructorBody(ASTContext & Context,const CXXRecordDecl * BaseClassDecl,const CXXRecordDecl * MostDerivedClassDecl)1277f4a2713aSLionel Sambuc HasTrivialDestructorBody(ASTContext &Context,
1278f4a2713aSLionel Sambuc                          const CXXRecordDecl *BaseClassDecl,
1279f4a2713aSLionel Sambuc                          const CXXRecordDecl *MostDerivedClassDecl)
1280f4a2713aSLionel Sambuc {
1281f4a2713aSLionel Sambuc   // If the destructor is trivial we don't have to check anything else.
1282f4a2713aSLionel Sambuc   if (BaseClassDecl->hasTrivialDestructor())
1283f4a2713aSLionel Sambuc     return true;
1284f4a2713aSLionel Sambuc 
1285f4a2713aSLionel Sambuc   if (!BaseClassDecl->getDestructor()->hasTrivialBody())
1286f4a2713aSLionel Sambuc     return false;
1287f4a2713aSLionel Sambuc 
1288f4a2713aSLionel Sambuc   // Check fields.
1289*0a6a1f1dSLionel Sambuc   for (const auto *Field : BaseClassDecl->fields())
1290f4a2713aSLionel Sambuc     if (!FieldHasTrivialDestructorBody(Context, Field))
1291f4a2713aSLionel Sambuc       return false;
1292f4a2713aSLionel Sambuc 
1293f4a2713aSLionel Sambuc   // Check non-virtual bases.
1294*0a6a1f1dSLionel Sambuc   for (const auto &I : BaseClassDecl->bases()) {
1295*0a6a1f1dSLionel Sambuc     if (I.isVirtual())
1296f4a2713aSLionel Sambuc       continue;
1297f4a2713aSLionel Sambuc 
1298f4a2713aSLionel Sambuc     const CXXRecordDecl *NonVirtualBase =
1299*0a6a1f1dSLionel Sambuc       cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
1300f4a2713aSLionel Sambuc     if (!HasTrivialDestructorBody(Context, NonVirtualBase,
1301f4a2713aSLionel Sambuc                                   MostDerivedClassDecl))
1302f4a2713aSLionel Sambuc       return false;
1303f4a2713aSLionel Sambuc   }
1304f4a2713aSLionel Sambuc 
1305f4a2713aSLionel Sambuc   if (BaseClassDecl == MostDerivedClassDecl) {
1306f4a2713aSLionel Sambuc     // Check virtual bases.
1307*0a6a1f1dSLionel Sambuc     for (const auto &I : BaseClassDecl->vbases()) {
1308f4a2713aSLionel Sambuc       const CXXRecordDecl *VirtualBase =
1309*0a6a1f1dSLionel Sambuc         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
1310f4a2713aSLionel Sambuc       if (!HasTrivialDestructorBody(Context, VirtualBase,
1311f4a2713aSLionel Sambuc                                     MostDerivedClassDecl))
1312f4a2713aSLionel Sambuc         return false;
1313f4a2713aSLionel Sambuc     }
1314f4a2713aSLionel Sambuc   }
1315f4a2713aSLionel Sambuc 
1316f4a2713aSLionel Sambuc   return true;
1317f4a2713aSLionel Sambuc }
1318f4a2713aSLionel Sambuc 
1319f4a2713aSLionel Sambuc static bool
FieldHasTrivialDestructorBody(ASTContext & Context,const FieldDecl * Field)1320f4a2713aSLionel Sambuc FieldHasTrivialDestructorBody(ASTContext &Context,
1321f4a2713aSLionel Sambuc                               const FieldDecl *Field)
1322f4a2713aSLionel Sambuc {
1323f4a2713aSLionel Sambuc   QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
1324f4a2713aSLionel Sambuc 
1325f4a2713aSLionel Sambuc   const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
1326f4a2713aSLionel Sambuc   if (!RT)
1327f4a2713aSLionel Sambuc     return true;
1328f4a2713aSLionel Sambuc 
1329f4a2713aSLionel Sambuc   CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1330f4a2713aSLionel Sambuc   return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
1331f4a2713aSLionel Sambuc }
1332f4a2713aSLionel Sambuc 
1333f4a2713aSLionel Sambuc /// CanSkipVTablePointerInitialization - Check whether we need to initialize
1334f4a2713aSLionel Sambuc /// any vtable pointers before calling this destructor.
CanSkipVTablePointerInitialization(ASTContext & Context,const CXXDestructorDecl * Dtor)1335f4a2713aSLionel Sambuc static bool CanSkipVTablePointerInitialization(ASTContext &Context,
1336f4a2713aSLionel Sambuc                                                const CXXDestructorDecl *Dtor) {
1337f4a2713aSLionel Sambuc   if (!Dtor->hasTrivialBody())
1338f4a2713aSLionel Sambuc     return false;
1339f4a2713aSLionel Sambuc 
1340f4a2713aSLionel Sambuc   // Check the fields.
1341f4a2713aSLionel Sambuc   const CXXRecordDecl *ClassDecl = Dtor->getParent();
1342*0a6a1f1dSLionel Sambuc   for (const auto *Field : ClassDecl->fields())
1343f4a2713aSLionel Sambuc     if (!FieldHasTrivialDestructorBody(Context, Field))
1344f4a2713aSLionel Sambuc       return false;
1345f4a2713aSLionel Sambuc 
1346f4a2713aSLionel Sambuc   return true;
1347f4a2713aSLionel Sambuc }
1348f4a2713aSLionel Sambuc 
1349f4a2713aSLionel Sambuc /// EmitDestructorBody - Emits the body of the current destructor.
EmitDestructorBody(FunctionArgList & Args)1350f4a2713aSLionel Sambuc void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
1351f4a2713aSLionel Sambuc   const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
1352f4a2713aSLionel Sambuc   CXXDtorType DtorType = CurGD.getDtorType();
1353f4a2713aSLionel Sambuc 
1354f4a2713aSLionel Sambuc   // The call to operator delete in a deleting destructor happens
1355f4a2713aSLionel Sambuc   // outside of the function-try-block, which means it's always
1356f4a2713aSLionel Sambuc   // possible to delegate the destructor body to the complete
1357f4a2713aSLionel Sambuc   // destructor.  Do so.
1358f4a2713aSLionel Sambuc   if (DtorType == Dtor_Deleting) {
1359f4a2713aSLionel Sambuc     EnterDtorCleanups(Dtor, Dtor_Deleting);
1360f4a2713aSLionel Sambuc     EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
1361f4a2713aSLionel Sambuc                           /*Delegating=*/false, LoadCXXThis());
1362f4a2713aSLionel Sambuc     PopCleanupBlock();
1363f4a2713aSLionel Sambuc     return;
1364f4a2713aSLionel Sambuc   }
1365f4a2713aSLionel Sambuc 
1366f4a2713aSLionel Sambuc   Stmt *Body = Dtor->getBody();
1367f4a2713aSLionel Sambuc 
1368f4a2713aSLionel Sambuc   // If the body is a function-try-block, enter the try before
1369f4a2713aSLionel Sambuc   // anything else.
1370f4a2713aSLionel Sambuc   bool isTryBody = (Body && isa<CXXTryStmt>(Body));
1371f4a2713aSLionel Sambuc   if (isTryBody)
1372f4a2713aSLionel Sambuc     EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
1373*0a6a1f1dSLionel Sambuc   EmitAsanPrologueOrEpilogue(false);
1374f4a2713aSLionel Sambuc 
1375f4a2713aSLionel Sambuc   // Enter the epilogue cleanups.
1376f4a2713aSLionel Sambuc   RunCleanupsScope DtorEpilogue(*this);
1377f4a2713aSLionel Sambuc 
1378f4a2713aSLionel Sambuc   // If this is the complete variant, just invoke the base variant;
1379f4a2713aSLionel Sambuc   // the epilogue will destruct the virtual bases.  But we can't do
1380f4a2713aSLionel Sambuc   // this optimization if the body is a function-try-block, because
1381f4a2713aSLionel Sambuc   // we'd introduce *two* handler blocks.  In the Microsoft ABI, we
1382f4a2713aSLionel Sambuc   // always delegate because we might not have a definition in this TU.
1383f4a2713aSLionel Sambuc   switch (DtorType) {
1384*0a6a1f1dSLionel Sambuc   case Dtor_Comdat:
1385*0a6a1f1dSLionel Sambuc     llvm_unreachable("not expecting a COMDAT");
1386*0a6a1f1dSLionel Sambuc 
1387f4a2713aSLionel Sambuc   case Dtor_Deleting: llvm_unreachable("already handled deleting case");
1388f4a2713aSLionel Sambuc 
1389f4a2713aSLionel Sambuc   case Dtor_Complete:
1390f4a2713aSLionel Sambuc     assert((Body || getTarget().getCXXABI().isMicrosoft()) &&
1391f4a2713aSLionel Sambuc            "can't emit a dtor without a body for non-Microsoft ABIs");
1392f4a2713aSLionel Sambuc 
1393f4a2713aSLionel Sambuc     // Enter the cleanup scopes for virtual bases.
1394f4a2713aSLionel Sambuc     EnterDtorCleanups(Dtor, Dtor_Complete);
1395f4a2713aSLionel Sambuc 
1396f4a2713aSLionel Sambuc     if (!isTryBody) {
1397f4a2713aSLionel Sambuc       EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
1398f4a2713aSLionel Sambuc                             /*Delegating=*/false, LoadCXXThis());
1399f4a2713aSLionel Sambuc       break;
1400f4a2713aSLionel Sambuc     }
1401f4a2713aSLionel Sambuc     // Fallthrough: act like we're in the base variant.
1402f4a2713aSLionel Sambuc 
1403f4a2713aSLionel Sambuc   case Dtor_Base:
1404f4a2713aSLionel Sambuc     assert(Body);
1405f4a2713aSLionel Sambuc 
1406*0a6a1f1dSLionel Sambuc     RegionCounter Cnt = getPGORegionCounter(Body);
1407*0a6a1f1dSLionel Sambuc     Cnt.beginRegion(Builder);
1408*0a6a1f1dSLionel Sambuc 
1409f4a2713aSLionel Sambuc     // Enter the cleanup scopes for fields and non-virtual bases.
1410f4a2713aSLionel Sambuc     EnterDtorCleanups(Dtor, Dtor_Base);
1411f4a2713aSLionel Sambuc 
1412f4a2713aSLionel Sambuc     // Initialize the vtable pointers before entering the body.
1413f4a2713aSLionel Sambuc     if (!CanSkipVTablePointerInitialization(getContext(), Dtor))
1414f4a2713aSLionel Sambuc         InitializeVTablePointers(Dtor->getParent());
1415f4a2713aSLionel Sambuc 
1416f4a2713aSLionel Sambuc     if (isTryBody)
1417f4a2713aSLionel Sambuc       EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
1418f4a2713aSLionel Sambuc     else if (Body)
1419f4a2713aSLionel Sambuc       EmitStmt(Body);
1420f4a2713aSLionel Sambuc     else {
1421f4a2713aSLionel Sambuc       assert(Dtor->isImplicit() && "bodyless dtor not implicit");
1422f4a2713aSLionel Sambuc       // nothing to do besides what's in the epilogue
1423f4a2713aSLionel Sambuc     }
1424f4a2713aSLionel Sambuc     // -fapple-kext must inline any call to this dtor into
1425f4a2713aSLionel Sambuc     // the caller's body.
1426f4a2713aSLionel Sambuc     if (getLangOpts().AppleKext)
1427f4a2713aSLionel Sambuc       CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
1428f4a2713aSLionel Sambuc     break;
1429f4a2713aSLionel Sambuc   }
1430f4a2713aSLionel Sambuc 
1431f4a2713aSLionel Sambuc   // Jump out through the epilogue cleanups.
1432f4a2713aSLionel Sambuc   DtorEpilogue.ForceCleanup();
1433f4a2713aSLionel Sambuc 
1434f4a2713aSLionel Sambuc   // Exit the try if applicable.
1435f4a2713aSLionel Sambuc   if (isTryBody)
1436f4a2713aSLionel Sambuc     ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
1437f4a2713aSLionel Sambuc }
1438f4a2713aSLionel Sambuc 
emitImplicitAssignmentOperatorBody(FunctionArgList & Args)1439f4a2713aSLionel Sambuc void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) {
1440f4a2713aSLionel Sambuc   const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
1441f4a2713aSLionel Sambuc   const Stmt *RootS = AssignOp->getBody();
1442f4a2713aSLionel Sambuc   assert(isa<CompoundStmt>(RootS) &&
1443f4a2713aSLionel Sambuc          "Body of an implicit assignment operator should be compound stmt.");
1444f4a2713aSLionel Sambuc   const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
1445f4a2713aSLionel Sambuc 
1446f4a2713aSLionel Sambuc   LexicalScope Scope(*this, RootCS->getSourceRange());
1447f4a2713aSLionel Sambuc 
1448f4a2713aSLionel Sambuc   AssignmentMemcpyizer AM(*this, AssignOp, Args);
1449*0a6a1f1dSLionel Sambuc   for (auto *I : RootCS->body())
1450*0a6a1f1dSLionel Sambuc     AM.emitAssignment(I);
1451f4a2713aSLionel Sambuc   AM.finish();
1452f4a2713aSLionel Sambuc }
1453f4a2713aSLionel Sambuc 
1454f4a2713aSLionel Sambuc namespace {
1455f4a2713aSLionel Sambuc   /// Call the operator delete associated with the current destructor.
1456f4a2713aSLionel Sambuc   struct CallDtorDelete : EHScopeStack::Cleanup {
CallDtorDelete__anone7009f310411::CallDtorDelete1457f4a2713aSLionel Sambuc     CallDtorDelete() {}
1458f4a2713aSLionel Sambuc 
Emit__anone7009f310411::CallDtorDelete1459*0a6a1f1dSLionel Sambuc     void Emit(CodeGenFunction &CGF, Flags flags) override {
1460f4a2713aSLionel Sambuc       const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1461f4a2713aSLionel Sambuc       const CXXRecordDecl *ClassDecl = Dtor->getParent();
1462f4a2713aSLionel Sambuc       CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1463f4a2713aSLionel Sambuc                          CGF.getContext().getTagDeclType(ClassDecl));
1464f4a2713aSLionel Sambuc     }
1465f4a2713aSLionel Sambuc   };
1466f4a2713aSLionel Sambuc 
1467f4a2713aSLionel Sambuc   struct CallDtorDeleteConditional : EHScopeStack::Cleanup {
1468f4a2713aSLionel Sambuc     llvm::Value *ShouldDeleteCondition;
1469f4a2713aSLionel Sambuc   public:
CallDtorDeleteConditional__anone7009f310411::CallDtorDeleteConditional1470f4a2713aSLionel Sambuc     CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
1471f4a2713aSLionel Sambuc       : ShouldDeleteCondition(ShouldDeleteCondition) {
1472*0a6a1f1dSLionel Sambuc       assert(ShouldDeleteCondition != nullptr);
1473f4a2713aSLionel Sambuc     }
1474f4a2713aSLionel Sambuc 
Emit__anone7009f310411::CallDtorDeleteConditional1475*0a6a1f1dSLionel Sambuc     void Emit(CodeGenFunction &CGF, Flags flags) override {
1476f4a2713aSLionel Sambuc       llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
1477f4a2713aSLionel Sambuc       llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
1478f4a2713aSLionel Sambuc       llvm::Value *ShouldCallDelete
1479f4a2713aSLionel Sambuc         = CGF.Builder.CreateIsNull(ShouldDeleteCondition);
1480f4a2713aSLionel Sambuc       CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
1481f4a2713aSLionel Sambuc 
1482f4a2713aSLionel Sambuc       CGF.EmitBlock(callDeleteBB);
1483f4a2713aSLionel Sambuc       const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1484f4a2713aSLionel Sambuc       const CXXRecordDecl *ClassDecl = Dtor->getParent();
1485f4a2713aSLionel Sambuc       CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1486f4a2713aSLionel Sambuc                          CGF.getContext().getTagDeclType(ClassDecl));
1487f4a2713aSLionel Sambuc       CGF.Builder.CreateBr(continueBB);
1488f4a2713aSLionel Sambuc 
1489f4a2713aSLionel Sambuc       CGF.EmitBlock(continueBB);
1490f4a2713aSLionel Sambuc     }
1491f4a2713aSLionel Sambuc   };
1492f4a2713aSLionel Sambuc 
1493f4a2713aSLionel Sambuc   class DestroyField  : public EHScopeStack::Cleanup {
1494f4a2713aSLionel Sambuc     const FieldDecl *field;
1495f4a2713aSLionel Sambuc     CodeGenFunction::Destroyer *destroyer;
1496f4a2713aSLionel Sambuc     bool useEHCleanupForArray;
1497f4a2713aSLionel Sambuc 
1498f4a2713aSLionel Sambuc   public:
DestroyField(const FieldDecl * field,CodeGenFunction::Destroyer * destroyer,bool useEHCleanupForArray)1499f4a2713aSLionel Sambuc     DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
1500f4a2713aSLionel Sambuc                  bool useEHCleanupForArray)
1501f4a2713aSLionel Sambuc       : field(field), destroyer(destroyer),
1502f4a2713aSLionel Sambuc         useEHCleanupForArray(useEHCleanupForArray) {}
1503f4a2713aSLionel Sambuc 
Emit(CodeGenFunction & CGF,Flags flags)1504*0a6a1f1dSLionel Sambuc     void Emit(CodeGenFunction &CGF, Flags flags) override {
1505f4a2713aSLionel Sambuc       // Find the address of the field.
1506f4a2713aSLionel Sambuc       llvm::Value *thisValue = CGF.LoadCXXThis();
1507f4a2713aSLionel Sambuc       QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
1508f4a2713aSLionel Sambuc       LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
1509f4a2713aSLionel Sambuc       LValue LV = CGF.EmitLValueForField(ThisLV, field);
1510f4a2713aSLionel Sambuc       assert(LV.isSimple());
1511f4a2713aSLionel Sambuc 
1512f4a2713aSLionel Sambuc       CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
1513f4a2713aSLionel Sambuc                       flags.isForNormalCleanup() && useEHCleanupForArray);
1514f4a2713aSLionel Sambuc     }
1515f4a2713aSLionel Sambuc   };
1516f4a2713aSLionel Sambuc }
1517f4a2713aSLionel Sambuc 
1518*0a6a1f1dSLionel Sambuc /// \brief Emit all code that comes at the end of class's
1519f4a2713aSLionel Sambuc /// destructor. This is to call destructors on members and base classes
1520f4a2713aSLionel Sambuc /// in reverse order of their construction.
EnterDtorCleanups(const CXXDestructorDecl * DD,CXXDtorType DtorType)1521f4a2713aSLionel Sambuc void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
1522f4a2713aSLionel Sambuc                                         CXXDtorType DtorType) {
1523*0a6a1f1dSLionel Sambuc   assert((!DD->isTrivial() || DD->hasAttr<DLLExportAttr>()) &&
1524*0a6a1f1dSLionel Sambuc          "Should not emit dtor epilogue for non-exported trivial dtor!");
1525f4a2713aSLionel Sambuc 
1526f4a2713aSLionel Sambuc   // The deleting-destructor phase just needs to call the appropriate
1527f4a2713aSLionel Sambuc   // operator delete that Sema picked up.
1528f4a2713aSLionel Sambuc   if (DtorType == Dtor_Deleting) {
1529f4a2713aSLionel Sambuc     assert(DD->getOperatorDelete() &&
1530*0a6a1f1dSLionel Sambuc            "operator delete missing - EnterDtorCleanups");
1531f4a2713aSLionel Sambuc     if (CXXStructorImplicitParamValue) {
1532f4a2713aSLionel Sambuc       // If there is an implicit param to the deleting dtor, it's a boolean
1533f4a2713aSLionel Sambuc       // telling whether we should call delete at the end of the dtor.
1534f4a2713aSLionel Sambuc       EHStack.pushCleanup<CallDtorDeleteConditional>(
1535f4a2713aSLionel Sambuc           NormalAndEHCleanup, CXXStructorImplicitParamValue);
1536f4a2713aSLionel Sambuc     } else {
1537f4a2713aSLionel Sambuc       EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
1538f4a2713aSLionel Sambuc     }
1539f4a2713aSLionel Sambuc     return;
1540f4a2713aSLionel Sambuc   }
1541f4a2713aSLionel Sambuc 
1542f4a2713aSLionel Sambuc   const CXXRecordDecl *ClassDecl = DD->getParent();
1543f4a2713aSLionel Sambuc 
1544f4a2713aSLionel Sambuc   // Unions have no bases and do not call field destructors.
1545f4a2713aSLionel Sambuc   if (ClassDecl->isUnion())
1546f4a2713aSLionel Sambuc     return;
1547f4a2713aSLionel Sambuc 
1548f4a2713aSLionel Sambuc   // The complete-destructor phase just destructs all the virtual bases.
1549f4a2713aSLionel Sambuc   if (DtorType == Dtor_Complete) {
1550f4a2713aSLionel Sambuc 
1551f4a2713aSLionel Sambuc     // We push them in the forward order so that they'll be popped in
1552f4a2713aSLionel Sambuc     // the reverse order.
1553*0a6a1f1dSLionel Sambuc     for (const auto &Base : ClassDecl->vbases()) {
1554f4a2713aSLionel Sambuc       CXXRecordDecl *BaseClassDecl
1555f4a2713aSLionel Sambuc         = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1556f4a2713aSLionel Sambuc 
1557f4a2713aSLionel Sambuc       // Ignore trivial destructors.
1558f4a2713aSLionel Sambuc       if (BaseClassDecl->hasTrivialDestructor())
1559f4a2713aSLionel Sambuc         continue;
1560f4a2713aSLionel Sambuc 
1561f4a2713aSLionel Sambuc       EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1562f4a2713aSLionel Sambuc                                         BaseClassDecl,
1563f4a2713aSLionel Sambuc                                         /*BaseIsVirtual*/ true);
1564f4a2713aSLionel Sambuc     }
1565f4a2713aSLionel Sambuc 
1566f4a2713aSLionel Sambuc     return;
1567f4a2713aSLionel Sambuc   }
1568f4a2713aSLionel Sambuc 
1569f4a2713aSLionel Sambuc   assert(DtorType == Dtor_Base);
1570f4a2713aSLionel Sambuc 
1571f4a2713aSLionel Sambuc   // Destroy non-virtual bases.
1572*0a6a1f1dSLionel Sambuc   for (const auto &Base : ClassDecl->bases()) {
1573f4a2713aSLionel Sambuc     // Ignore virtual bases.
1574f4a2713aSLionel Sambuc     if (Base.isVirtual())
1575f4a2713aSLionel Sambuc       continue;
1576f4a2713aSLionel Sambuc 
1577f4a2713aSLionel Sambuc     CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
1578f4a2713aSLionel Sambuc 
1579f4a2713aSLionel Sambuc     // Ignore trivial destructors.
1580f4a2713aSLionel Sambuc     if (BaseClassDecl->hasTrivialDestructor())
1581f4a2713aSLionel Sambuc       continue;
1582f4a2713aSLionel Sambuc 
1583f4a2713aSLionel Sambuc     EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1584f4a2713aSLionel Sambuc                                       BaseClassDecl,
1585f4a2713aSLionel Sambuc                                       /*BaseIsVirtual*/ false);
1586f4a2713aSLionel Sambuc   }
1587f4a2713aSLionel Sambuc 
1588f4a2713aSLionel Sambuc   // Destroy direct fields.
1589*0a6a1f1dSLionel Sambuc   for (const auto *Field : ClassDecl->fields()) {
1590*0a6a1f1dSLionel Sambuc     QualType type = Field->getType();
1591f4a2713aSLionel Sambuc     QualType::DestructionKind dtorKind = type.isDestructedType();
1592f4a2713aSLionel Sambuc     if (!dtorKind) continue;
1593f4a2713aSLionel Sambuc 
1594f4a2713aSLionel Sambuc     // Anonymous union members do not have their destructors called.
1595f4a2713aSLionel Sambuc     const RecordType *RT = type->getAsUnionType();
1596f4a2713aSLionel Sambuc     if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
1597f4a2713aSLionel Sambuc 
1598f4a2713aSLionel Sambuc     CleanupKind cleanupKind = getCleanupKind(dtorKind);
1599*0a6a1f1dSLionel Sambuc     EHStack.pushCleanup<DestroyField>(cleanupKind, Field,
1600f4a2713aSLionel Sambuc                                       getDestroyer(dtorKind),
1601f4a2713aSLionel Sambuc                                       cleanupKind & EHCleanup);
1602f4a2713aSLionel Sambuc   }
1603f4a2713aSLionel Sambuc }
1604f4a2713aSLionel Sambuc 
1605f4a2713aSLionel Sambuc /// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1606f4a2713aSLionel Sambuc /// constructor for each of several members of an array.
1607f4a2713aSLionel Sambuc ///
1608f4a2713aSLionel Sambuc /// \param ctor the constructor to call for each element
1609f4a2713aSLionel Sambuc /// \param arrayType the type of the array to initialize
1610f4a2713aSLionel Sambuc /// \param arrayBegin an arrayType*
1611f4a2713aSLionel Sambuc /// \param zeroInitialize true if each element should be
1612f4a2713aSLionel Sambuc ///   zero-initialized before it is constructed
EmitCXXAggrConstructorCall(const CXXConstructorDecl * ctor,const ConstantArrayType * arrayType,llvm::Value * arrayBegin,const CXXConstructExpr * E,bool zeroInitialize)1613*0a6a1f1dSLionel Sambuc void CodeGenFunction::EmitCXXAggrConstructorCall(
1614*0a6a1f1dSLionel Sambuc     const CXXConstructorDecl *ctor, const ConstantArrayType *arrayType,
1615*0a6a1f1dSLionel Sambuc     llvm::Value *arrayBegin, const CXXConstructExpr *E, bool zeroInitialize) {
1616f4a2713aSLionel Sambuc   QualType elementType;
1617f4a2713aSLionel Sambuc   llvm::Value *numElements =
1618f4a2713aSLionel Sambuc     emitArrayLength(arrayType, elementType, arrayBegin);
1619f4a2713aSLionel Sambuc 
1620*0a6a1f1dSLionel Sambuc   EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin, E, zeroInitialize);
1621f4a2713aSLionel Sambuc }
1622f4a2713aSLionel Sambuc 
1623f4a2713aSLionel Sambuc /// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1624f4a2713aSLionel Sambuc /// constructor for each of several members of an array.
1625f4a2713aSLionel Sambuc ///
1626f4a2713aSLionel Sambuc /// \param ctor the constructor to call for each element
1627f4a2713aSLionel Sambuc /// \param numElements the number of elements in the array;
1628f4a2713aSLionel Sambuc ///   may be zero
1629f4a2713aSLionel Sambuc /// \param arrayBegin a T*, where T is the type constructed by ctor
1630f4a2713aSLionel Sambuc /// \param zeroInitialize true if each element should be
1631f4a2713aSLionel Sambuc ///   zero-initialized before it is constructed
EmitCXXAggrConstructorCall(const CXXConstructorDecl * ctor,llvm::Value * numElements,llvm::Value * arrayBegin,const CXXConstructExpr * E,bool zeroInitialize)1632*0a6a1f1dSLionel Sambuc void CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1633f4a2713aSLionel Sambuc                                                  llvm::Value *numElements,
1634f4a2713aSLionel Sambuc                                                  llvm::Value *arrayBegin,
1635*0a6a1f1dSLionel Sambuc                                                  const CXXConstructExpr *E,
1636f4a2713aSLionel Sambuc                                                  bool zeroInitialize) {
1637f4a2713aSLionel Sambuc 
1638f4a2713aSLionel Sambuc   // It's legal for numElements to be zero.  This can happen both
1639f4a2713aSLionel Sambuc   // dynamically, because x can be zero in 'new A[x]', and statically,
1640f4a2713aSLionel Sambuc   // because of GCC extensions that permit zero-length arrays.  There
1641f4a2713aSLionel Sambuc   // are probably legitimate places where we could assume that this
1642f4a2713aSLionel Sambuc   // doesn't happen, but it's not clear that it's worth it.
1643*0a6a1f1dSLionel Sambuc   llvm::BranchInst *zeroCheckBranch = nullptr;
1644f4a2713aSLionel Sambuc 
1645f4a2713aSLionel Sambuc   // Optimize for a constant count.
1646f4a2713aSLionel Sambuc   llvm::ConstantInt *constantCount
1647f4a2713aSLionel Sambuc     = dyn_cast<llvm::ConstantInt>(numElements);
1648f4a2713aSLionel Sambuc   if (constantCount) {
1649f4a2713aSLionel Sambuc     // Just skip out if the constant count is zero.
1650f4a2713aSLionel Sambuc     if (constantCount->isZero()) return;
1651f4a2713aSLionel Sambuc 
1652f4a2713aSLionel Sambuc   // Otherwise, emit the check.
1653f4a2713aSLionel Sambuc   } else {
1654f4a2713aSLionel Sambuc     llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1655f4a2713aSLionel Sambuc     llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1656f4a2713aSLionel Sambuc     zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1657f4a2713aSLionel Sambuc     EmitBlock(loopBB);
1658f4a2713aSLionel Sambuc   }
1659f4a2713aSLionel Sambuc 
1660f4a2713aSLionel Sambuc   // Find the end of the array.
1661f4a2713aSLionel Sambuc   llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1662f4a2713aSLionel Sambuc                                                     "arrayctor.end");
1663f4a2713aSLionel Sambuc 
1664f4a2713aSLionel Sambuc   // Enter the loop, setting up a phi for the current location to initialize.
1665f4a2713aSLionel Sambuc   llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1666f4a2713aSLionel Sambuc   llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1667f4a2713aSLionel Sambuc   EmitBlock(loopBB);
1668f4a2713aSLionel Sambuc   llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1669f4a2713aSLionel Sambuc                                          "arrayctor.cur");
1670f4a2713aSLionel Sambuc   cur->addIncoming(arrayBegin, entryBB);
1671f4a2713aSLionel Sambuc 
1672f4a2713aSLionel Sambuc   // Inside the loop body, emit the constructor call on the array element.
1673f4a2713aSLionel Sambuc 
1674f4a2713aSLionel Sambuc   QualType type = getContext().getTypeDeclType(ctor->getParent());
1675f4a2713aSLionel Sambuc 
1676f4a2713aSLionel Sambuc   // Zero initialize the storage, if requested.
1677f4a2713aSLionel Sambuc   if (zeroInitialize)
1678f4a2713aSLionel Sambuc     EmitNullInitialization(cur, type);
1679f4a2713aSLionel Sambuc 
1680f4a2713aSLionel Sambuc   // C++ [class.temporary]p4:
1681f4a2713aSLionel Sambuc   // There are two contexts in which temporaries are destroyed at a different
1682f4a2713aSLionel Sambuc   // point than the end of the full-expression. The first context is when a
1683f4a2713aSLionel Sambuc   // default constructor is called to initialize an element of an array.
1684f4a2713aSLionel Sambuc   // If the constructor has one or more default arguments, the destruction of
1685f4a2713aSLionel Sambuc   // every temporary created in a default argument expression is sequenced
1686f4a2713aSLionel Sambuc   // before the construction of the next array element, if any.
1687f4a2713aSLionel Sambuc 
1688f4a2713aSLionel Sambuc   {
1689f4a2713aSLionel Sambuc     RunCleanupsScope Scope(*this);
1690f4a2713aSLionel Sambuc 
1691f4a2713aSLionel Sambuc     // Evaluate the constructor and its arguments in a regular
1692f4a2713aSLionel Sambuc     // partial-destroy cleanup.
1693f4a2713aSLionel Sambuc     if (getLangOpts().Exceptions &&
1694f4a2713aSLionel Sambuc         !ctor->getParent()->hasTrivialDestructor()) {
1695f4a2713aSLionel Sambuc       Destroyer *destroyer = destroyCXXObject;
1696f4a2713aSLionel Sambuc       pushRegularPartialArrayCleanup(arrayBegin, cur, type, *destroyer);
1697f4a2713aSLionel Sambuc     }
1698f4a2713aSLionel Sambuc 
1699f4a2713aSLionel Sambuc     EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/false,
1700*0a6a1f1dSLionel Sambuc                            /*Delegating=*/false, cur, E);
1701f4a2713aSLionel Sambuc   }
1702f4a2713aSLionel Sambuc 
1703f4a2713aSLionel Sambuc   // Go to the next element.
1704f4a2713aSLionel Sambuc   llvm::Value *next =
1705f4a2713aSLionel Sambuc     Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
1706f4a2713aSLionel Sambuc                               "arrayctor.next");
1707f4a2713aSLionel Sambuc   cur->addIncoming(next, Builder.GetInsertBlock());
1708f4a2713aSLionel Sambuc 
1709f4a2713aSLionel Sambuc   // Check whether that's the end of the loop.
1710f4a2713aSLionel Sambuc   llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
1711f4a2713aSLionel Sambuc   llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
1712f4a2713aSLionel Sambuc   Builder.CreateCondBr(done, contBB, loopBB);
1713f4a2713aSLionel Sambuc 
1714f4a2713aSLionel Sambuc   // Patch the earlier check to skip over the loop.
1715f4a2713aSLionel Sambuc   if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
1716f4a2713aSLionel Sambuc 
1717f4a2713aSLionel Sambuc   EmitBlock(contBB);
1718f4a2713aSLionel Sambuc }
1719f4a2713aSLionel Sambuc 
destroyCXXObject(CodeGenFunction & CGF,llvm::Value * addr,QualType type)1720f4a2713aSLionel Sambuc void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
1721f4a2713aSLionel Sambuc                                        llvm::Value *addr,
1722f4a2713aSLionel Sambuc                                        QualType type) {
1723f4a2713aSLionel Sambuc   const RecordType *rtype = type->castAs<RecordType>();
1724f4a2713aSLionel Sambuc   const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
1725f4a2713aSLionel Sambuc   const CXXDestructorDecl *dtor = record->getDestructor();
1726f4a2713aSLionel Sambuc   assert(!dtor->isTrivial());
1727f4a2713aSLionel Sambuc   CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
1728f4a2713aSLionel Sambuc                             /*Delegating=*/false, addr);
1729f4a2713aSLionel Sambuc }
1730f4a2713aSLionel Sambuc 
EmitCXXConstructorCall(const CXXConstructorDecl * D,CXXCtorType Type,bool ForVirtualBase,bool Delegating,llvm::Value * This,const CXXConstructExpr * E)1731*0a6a1f1dSLionel Sambuc void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
1732*0a6a1f1dSLionel Sambuc                                              CXXCtorType Type,
1733*0a6a1f1dSLionel Sambuc                                              bool ForVirtualBase,
1734*0a6a1f1dSLionel Sambuc                                              bool Delegating, llvm::Value *This,
1735*0a6a1f1dSLionel Sambuc                                              const CXXConstructExpr *E) {
1736f4a2713aSLionel Sambuc   // If this is a trivial constructor, just emit what's needed.
1737*0a6a1f1dSLionel Sambuc   if (D->isTrivial() && !D->getParent()->mayInsertExtraPadding()) {
1738*0a6a1f1dSLionel Sambuc     if (E->getNumArgs() == 0) {
1739f4a2713aSLionel Sambuc       // Trivial default constructor, no codegen required.
1740f4a2713aSLionel Sambuc       assert(D->isDefaultConstructor() &&
1741f4a2713aSLionel Sambuc              "trivial 0-arg ctor not a default ctor");
1742f4a2713aSLionel Sambuc       return;
1743f4a2713aSLionel Sambuc     }
1744f4a2713aSLionel Sambuc 
1745*0a6a1f1dSLionel Sambuc     assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
1746f4a2713aSLionel Sambuc     assert(D->isCopyOrMoveConstructor() &&
1747f4a2713aSLionel Sambuc            "trivial 1-arg ctor not a copy/move ctor");
1748f4a2713aSLionel Sambuc 
1749*0a6a1f1dSLionel Sambuc     const Expr *Arg = E->getArg(0);
1750*0a6a1f1dSLionel Sambuc     QualType Ty = Arg->getType();
1751*0a6a1f1dSLionel Sambuc     llvm::Value *Src = EmitLValue(Arg).getAddress();
1752f4a2713aSLionel Sambuc     EmitAggregateCopy(This, Src, Ty);
1753f4a2713aSLionel Sambuc     return;
1754f4a2713aSLionel Sambuc   }
1755f4a2713aSLionel Sambuc 
1756*0a6a1f1dSLionel Sambuc   // C++11 [class.mfct.non-static]p2:
1757*0a6a1f1dSLionel Sambuc   //   If a non-static member function of a class X is called for an object that
1758*0a6a1f1dSLionel Sambuc   //   is not of type X, or of a type derived from X, the behavior is undefined.
1759*0a6a1f1dSLionel Sambuc   // FIXME: Provide a source location here.
1760*0a6a1f1dSLionel Sambuc   EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall, SourceLocation(), This,
1761*0a6a1f1dSLionel Sambuc                 getContext().getRecordType(D->getParent()));
1762f4a2713aSLionel Sambuc 
1763f4a2713aSLionel Sambuc   CallArgList Args;
1764f4a2713aSLionel Sambuc 
1765f4a2713aSLionel Sambuc   // Push the this ptr.
1766f4a2713aSLionel Sambuc   Args.add(RValue::get(This), D->getThisType(getContext()));
1767f4a2713aSLionel Sambuc 
1768*0a6a1f1dSLionel Sambuc   // Add the rest of the user-supplied arguments.
1769*0a6a1f1dSLionel Sambuc   const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
1770*0a6a1f1dSLionel Sambuc   EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end(), E->getConstructor());
1771*0a6a1f1dSLionel Sambuc 
1772*0a6a1f1dSLionel Sambuc   // Insert any ABI-specific implicit constructor arguments.
1773*0a6a1f1dSLionel Sambuc   unsigned ExtraArgs = CGM.getCXXABI().addImplicitConstructorArgs(
1774*0a6a1f1dSLionel Sambuc       *this, D, Type, ForVirtualBase, Delegating, Args);
1775*0a6a1f1dSLionel Sambuc 
1776*0a6a1f1dSLionel Sambuc   // Emit the call.
1777*0a6a1f1dSLionel Sambuc   llvm::Value *Callee = CGM.getAddrOfCXXStructor(D, getFromCtorType(Type));
1778*0a6a1f1dSLionel Sambuc   const CGFunctionInfo &Info =
1779*0a6a1f1dSLionel Sambuc       CGM.getTypes().arrangeCXXConstructorCall(Args, D, Type, ExtraArgs);
1780*0a6a1f1dSLionel Sambuc   EmitCall(Info, Callee, ReturnValueSlot(), Args, D);
1781*0a6a1f1dSLionel Sambuc }
1782*0a6a1f1dSLionel Sambuc 
1783*0a6a1f1dSLionel Sambuc void
EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl * D,llvm::Value * This,llvm::Value * Src,const CXXConstructExpr * E)1784*0a6a1f1dSLionel Sambuc CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
1785*0a6a1f1dSLionel Sambuc                                         llvm::Value *This, llvm::Value *Src,
1786*0a6a1f1dSLionel Sambuc                                         const CXXConstructExpr *E) {
1787*0a6a1f1dSLionel Sambuc   if (D->isTrivial() &&
1788*0a6a1f1dSLionel Sambuc       !D->getParent()->mayInsertExtraPadding()) {
1789*0a6a1f1dSLionel Sambuc     assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
1790*0a6a1f1dSLionel Sambuc     assert(D->isCopyOrMoveConstructor() &&
1791*0a6a1f1dSLionel Sambuc            "trivial 1-arg ctor not a copy/move ctor");
1792*0a6a1f1dSLionel Sambuc     EmitAggregateCopy(This, Src, E->arg_begin()->getType());
1793*0a6a1f1dSLionel Sambuc     return;
1794*0a6a1f1dSLionel Sambuc   }
1795*0a6a1f1dSLionel Sambuc   llvm::Value *Callee = CGM.getAddrOfCXXStructor(D, StructorType::Complete);
1796*0a6a1f1dSLionel Sambuc   assert(D->isInstance() &&
1797*0a6a1f1dSLionel Sambuc          "Trying to emit a member call expr on a static method!");
1798*0a6a1f1dSLionel Sambuc 
1799*0a6a1f1dSLionel Sambuc   const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
1800*0a6a1f1dSLionel Sambuc 
1801*0a6a1f1dSLionel Sambuc   CallArgList Args;
1802*0a6a1f1dSLionel Sambuc 
1803*0a6a1f1dSLionel Sambuc   // Push the this ptr.
1804*0a6a1f1dSLionel Sambuc   Args.add(RValue::get(This), D->getThisType(getContext()));
1805f4a2713aSLionel Sambuc 
1806f4a2713aSLionel Sambuc   // Push the src ptr.
1807*0a6a1f1dSLionel Sambuc   QualType QT = *(FPT->param_type_begin());
1808f4a2713aSLionel Sambuc   llvm::Type *t = CGM.getTypes().ConvertType(QT);
1809f4a2713aSLionel Sambuc   Src = Builder.CreateBitCast(Src, t);
1810f4a2713aSLionel Sambuc   Args.add(RValue::get(Src), QT);
1811f4a2713aSLionel Sambuc 
1812f4a2713aSLionel Sambuc   // Skip over first argument (Src).
1813*0a6a1f1dSLionel Sambuc   EmitCallArgs(Args, FPT, E->arg_begin() + 1, E->arg_end(), E->getConstructor(),
1814*0a6a1f1dSLionel Sambuc                /*ParamsToSkip*/ 1);
1815f4a2713aSLionel Sambuc 
1816f4a2713aSLionel Sambuc   EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, RequiredArgs::All),
1817f4a2713aSLionel Sambuc            Callee, ReturnValueSlot(), Args, D);
1818f4a2713aSLionel Sambuc }
1819f4a2713aSLionel Sambuc 
1820f4a2713aSLionel Sambuc void
EmitDelegateCXXConstructorCall(const CXXConstructorDecl * Ctor,CXXCtorType CtorType,const FunctionArgList & Args,SourceLocation Loc)1821f4a2713aSLionel Sambuc CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1822f4a2713aSLionel Sambuc                                                 CXXCtorType CtorType,
1823f4a2713aSLionel Sambuc                                                 const FunctionArgList &Args,
1824f4a2713aSLionel Sambuc                                                 SourceLocation Loc) {
1825f4a2713aSLionel Sambuc   CallArgList DelegateArgs;
1826f4a2713aSLionel Sambuc 
1827f4a2713aSLionel Sambuc   FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
1828f4a2713aSLionel Sambuc   assert(I != E && "no parameters to constructor");
1829f4a2713aSLionel Sambuc 
1830f4a2713aSLionel Sambuc   // this
1831f4a2713aSLionel Sambuc   DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType());
1832f4a2713aSLionel Sambuc   ++I;
1833f4a2713aSLionel Sambuc 
1834f4a2713aSLionel Sambuc   // vtt
1835f4a2713aSLionel Sambuc   if (llvm::Value *VTT = GetVTTParameter(GlobalDecl(Ctor, CtorType),
1836f4a2713aSLionel Sambuc                                          /*ForVirtualBase=*/false,
1837f4a2713aSLionel Sambuc                                          /*Delegating=*/true)) {
1838f4a2713aSLionel Sambuc     QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
1839f4a2713aSLionel Sambuc     DelegateArgs.add(RValue::get(VTT), VoidPP);
1840f4a2713aSLionel Sambuc 
1841f4a2713aSLionel Sambuc     if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
1842f4a2713aSLionel Sambuc       assert(I != E && "cannot skip vtt parameter, already done with args");
1843f4a2713aSLionel Sambuc       assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
1844f4a2713aSLionel Sambuc       ++I;
1845f4a2713aSLionel Sambuc     }
1846f4a2713aSLionel Sambuc   }
1847f4a2713aSLionel Sambuc 
1848f4a2713aSLionel Sambuc   // Explicit arguments.
1849f4a2713aSLionel Sambuc   for (; I != E; ++I) {
1850f4a2713aSLionel Sambuc     const VarDecl *param = *I;
1851f4a2713aSLionel Sambuc     // FIXME: per-argument source location
1852f4a2713aSLionel Sambuc     EmitDelegateCallArg(DelegateArgs, param, Loc);
1853f4a2713aSLionel Sambuc   }
1854f4a2713aSLionel Sambuc 
1855*0a6a1f1dSLionel Sambuc   llvm::Value *Callee =
1856*0a6a1f1dSLionel Sambuc       CGM.getAddrOfCXXStructor(Ctor, getFromCtorType(CtorType));
1857*0a6a1f1dSLionel Sambuc   EmitCall(CGM.getTypes()
1858*0a6a1f1dSLionel Sambuc                .arrangeCXXStructorDeclaration(Ctor, getFromCtorType(CtorType)),
1859f4a2713aSLionel Sambuc            Callee, ReturnValueSlot(), DelegateArgs, Ctor);
1860f4a2713aSLionel Sambuc }
1861f4a2713aSLionel Sambuc 
1862f4a2713aSLionel Sambuc namespace {
1863f4a2713aSLionel Sambuc   struct CallDelegatingCtorDtor : EHScopeStack::Cleanup {
1864f4a2713aSLionel Sambuc     const CXXDestructorDecl *Dtor;
1865f4a2713aSLionel Sambuc     llvm::Value *Addr;
1866f4a2713aSLionel Sambuc     CXXDtorType Type;
1867f4a2713aSLionel Sambuc 
CallDelegatingCtorDtor__anone7009f310511::CallDelegatingCtorDtor1868f4a2713aSLionel Sambuc     CallDelegatingCtorDtor(const CXXDestructorDecl *D, llvm::Value *Addr,
1869f4a2713aSLionel Sambuc                            CXXDtorType Type)
1870f4a2713aSLionel Sambuc       : Dtor(D), Addr(Addr), Type(Type) {}
1871f4a2713aSLionel Sambuc 
Emit__anone7009f310511::CallDelegatingCtorDtor1872*0a6a1f1dSLionel Sambuc     void Emit(CodeGenFunction &CGF, Flags flags) override {
1873f4a2713aSLionel Sambuc       CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
1874f4a2713aSLionel Sambuc                                 /*Delegating=*/true, Addr);
1875f4a2713aSLionel Sambuc     }
1876f4a2713aSLionel Sambuc   };
1877f4a2713aSLionel Sambuc }
1878f4a2713aSLionel Sambuc 
1879f4a2713aSLionel Sambuc void
EmitDelegatingCXXConstructorCall(const CXXConstructorDecl * Ctor,const FunctionArgList & Args)1880f4a2713aSLionel Sambuc CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
1881f4a2713aSLionel Sambuc                                                   const FunctionArgList &Args) {
1882f4a2713aSLionel Sambuc   assert(Ctor->isDelegatingConstructor());
1883f4a2713aSLionel Sambuc 
1884f4a2713aSLionel Sambuc   llvm::Value *ThisPtr = LoadCXXThis();
1885f4a2713aSLionel Sambuc 
1886f4a2713aSLionel Sambuc   QualType Ty = getContext().getTagDeclType(Ctor->getParent());
1887f4a2713aSLionel Sambuc   CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
1888f4a2713aSLionel Sambuc   AggValueSlot AggSlot =
1889f4a2713aSLionel Sambuc     AggValueSlot::forAddr(ThisPtr, Alignment, Qualifiers(),
1890f4a2713aSLionel Sambuc                           AggValueSlot::IsDestructed,
1891f4a2713aSLionel Sambuc                           AggValueSlot::DoesNotNeedGCBarriers,
1892f4a2713aSLionel Sambuc                           AggValueSlot::IsNotAliased);
1893f4a2713aSLionel Sambuc 
1894f4a2713aSLionel Sambuc   EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
1895f4a2713aSLionel Sambuc 
1896f4a2713aSLionel Sambuc   const CXXRecordDecl *ClassDecl = Ctor->getParent();
1897f4a2713aSLionel Sambuc   if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
1898f4a2713aSLionel Sambuc     CXXDtorType Type =
1899f4a2713aSLionel Sambuc       CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
1900f4a2713aSLionel Sambuc 
1901f4a2713aSLionel Sambuc     EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
1902f4a2713aSLionel Sambuc                                                 ClassDecl->getDestructor(),
1903f4a2713aSLionel Sambuc                                                 ThisPtr, Type);
1904f4a2713aSLionel Sambuc   }
1905f4a2713aSLionel Sambuc }
1906f4a2713aSLionel Sambuc 
EmitCXXDestructorCall(const CXXDestructorDecl * DD,CXXDtorType Type,bool ForVirtualBase,bool Delegating,llvm::Value * This)1907f4a2713aSLionel Sambuc void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
1908f4a2713aSLionel Sambuc                                             CXXDtorType Type,
1909f4a2713aSLionel Sambuc                                             bool ForVirtualBase,
1910f4a2713aSLionel Sambuc                                             bool Delegating,
1911f4a2713aSLionel Sambuc                                             llvm::Value *This) {
1912*0a6a1f1dSLionel Sambuc   CGM.getCXXABI().EmitDestructorCall(*this, DD, Type, ForVirtualBase,
1913*0a6a1f1dSLionel Sambuc                                      Delegating, This);
1914f4a2713aSLionel Sambuc }
1915f4a2713aSLionel Sambuc 
1916f4a2713aSLionel Sambuc namespace {
1917f4a2713aSLionel Sambuc   struct CallLocalDtor : EHScopeStack::Cleanup {
1918f4a2713aSLionel Sambuc     const CXXDestructorDecl *Dtor;
1919f4a2713aSLionel Sambuc     llvm::Value *Addr;
1920f4a2713aSLionel Sambuc 
CallLocalDtor__anone7009f310611::CallLocalDtor1921f4a2713aSLionel Sambuc     CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
1922f4a2713aSLionel Sambuc       : Dtor(D), Addr(Addr) {}
1923f4a2713aSLionel Sambuc 
Emit__anone7009f310611::CallLocalDtor1924*0a6a1f1dSLionel Sambuc     void Emit(CodeGenFunction &CGF, Flags flags) override {
1925f4a2713aSLionel Sambuc       CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1926f4a2713aSLionel Sambuc                                 /*ForVirtualBase=*/false,
1927f4a2713aSLionel Sambuc                                 /*Delegating=*/false, Addr);
1928f4a2713aSLionel Sambuc     }
1929f4a2713aSLionel Sambuc   };
1930f4a2713aSLionel Sambuc }
1931f4a2713aSLionel Sambuc 
PushDestructorCleanup(const CXXDestructorDecl * D,llvm::Value * Addr)1932f4a2713aSLionel Sambuc void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
1933f4a2713aSLionel Sambuc                                             llvm::Value *Addr) {
1934f4a2713aSLionel Sambuc   EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
1935f4a2713aSLionel Sambuc }
1936f4a2713aSLionel Sambuc 
PushDestructorCleanup(QualType T,llvm::Value * Addr)1937f4a2713aSLionel Sambuc void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
1938f4a2713aSLionel Sambuc   CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
1939f4a2713aSLionel Sambuc   if (!ClassDecl) return;
1940f4a2713aSLionel Sambuc   if (ClassDecl->hasTrivialDestructor()) return;
1941f4a2713aSLionel Sambuc 
1942f4a2713aSLionel Sambuc   const CXXDestructorDecl *D = ClassDecl->getDestructor();
1943f4a2713aSLionel Sambuc   assert(D && D->isUsed() && "destructor not marked as used!");
1944f4a2713aSLionel Sambuc   PushDestructorCleanup(D, Addr);
1945f4a2713aSLionel Sambuc }
1946f4a2713aSLionel Sambuc 
1947f4a2713aSLionel Sambuc void
InitializeVTablePointer(BaseSubobject Base,const CXXRecordDecl * NearestVBase,CharUnits OffsetFromNearestVBase,const CXXRecordDecl * VTableClass)1948f4a2713aSLionel Sambuc CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
1949f4a2713aSLionel Sambuc                                          const CXXRecordDecl *NearestVBase,
1950f4a2713aSLionel Sambuc                                          CharUnits OffsetFromNearestVBase,
1951f4a2713aSLionel Sambuc                                          const CXXRecordDecl *VTableClass) {
1952f4a2713aSLionel Sambuc   // Compute the address point.
1953f4a2713aSLionel Sambuc   bool NeedsVirtualOffset;
1954f4a2713aSLionel Sambuc   llvm::Value *VTableAddressPoint =
1955f4a2713aSLionel Sambuc       CGM.getCXXABI().getVTableAddressPointInStructor(
1956f4a2713aSLionel Sambuc           *this, VTableClass, Base, NearestVBase, NeedsVirtualOffset);
1957f4a2713aSLionel Sambuc   if (!VTableAddressPoint)
1958f4a2713aSLionel Sambuc     return;
1959f4a2713aSLionel Sambuc 
1960f4a2713aSLionel Sambuc   // Compute where to store the address point.
1961*0a6a1f1dSLionel Sambuc   llvm::Value *VirtualOffset = nullptr;
1962f4a2713aSLionel Sambuc   CharUnits NonVirtualOffset = CharUnits::Zero();
1963f4a2713aSLionel Sambuc 
1964f4a2713aSLionel Sambuc   if (NeedsVirtualOffset) {
1965f4a2713aSLionel Sambuc     // We need to use the virtual base offset offset because the virtual base
1966f4a2713aSLionel Sambuc     // might have a different offset in the most derived class.
1967f4a2713aSLionel Sambuc     VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(*this,
1968f4a2713aSLionel Sambuc                                                               LoadCXXThis(),
1969f4a2713aSLionel Sambuc                                                               VTableClass,
1970f4a2713aSLionel Sambuc                                                               NearestVBase);
1971f4a2713aSLionel Sambuc     NonVirtualOffset = OffsetFromNearestVBase;
1972f4a2713aSLionel Sambuc   } else {
1973f4a2713aSLionel Sambuc     // We can just use the base offset in the complete class.
1974f4a2713aSLionel Sambuc     NonVirtualOffset = Base.getBaseOffset();
1975f4a2713aSLionel Sambuc   }
1976f4a2713aSLionel Sambuc 
1977f4a2713aSLionel Sambuc   // Apply the offsets.
1978f4a2713aSLionel Sambuc   llvm::Value *VTableField = LoadCXXThis();
1979f4a2713aSLionel Sambuc 
1980f4a2713aSLionel Sambuc   if (!NonVirtualOffset.isZero() || VirtualOffset)
1981f4a2713aSLionel Sambuc     VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
1982f4a2713aSLionel Sambuc                                                   NonVirtualOffset,
1983f4a2713aSLionel Sambuc                                                   VirtualOffset);
1984f4a2713aSLionel Sambuc 
1985*0a6a1f1dSLionel Sambuc   // Finally, store the address point. Use the same LLVM types as the field to
1986*0a6a1f1dSLionel Sambuc   // support optimization.
1987*0a6a1f1dSLionel Sambuc   llvm::Type *VTablePtrTy =
1988*0a6a1f1dSLionel Sambuc       llvm::FunctionType::get(CGM.Int32Ty, /*isVarArg=*/true)
1989*0a6a1f1dSLionel Sambuc           ->getPointerTo()
1990*0a6a1f1dSLionel Sambuc           ->getPointerTo();
1991*0a6a1f1dSLionel Sambuc   VTableField = Builder.CreateBitCast(VTableField, VTablePtrTy->getPointerTo());
1992*0a6a1f1dSLionel Sambuc   VTableAddressPoint = Builder.CreateBitCast(VTableAddressPoint, VTablePtrTy);
1993f4a2713aSLionel Sambuc   llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
1994f4a2713aSLionel Sambuc   CGM.DecorateInstruction(Store, CGM.getTBAAInfoForVTablePtr());
1995f4a2713aSLionel Sambuc }
1996f4a2713aSLionel Sambuc 
1997f4a2713aSLionel Sambuc void
InitializeVTablePointers(BaseSubobject Base,const CXXRecordDecl * NearestVBase,CharUnits OffsetFromNearestVBase,bool BaseIsNonVirtualPrimaryBase,const CXXRecordDecl * VTableClass,VisitedVirtualBasesSetTy & VBases)1998f4a2713aSLionel Sambuc CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
1999f4a2713aSLionel Sambuc                                           const CXXRecordDecl *NearestVBase,
2000f4a2713aSLionel Sambuc                                           CharUnits OffsetFromNearestVBase,
2001f4a2713aSLionel Sambuc                                           bool BaseIsNonVirtualPrimaryBase,
2002f4a2713aSLionel Sambuc                                           const CXXRecordDecl *VTableClass,
2003f4a2713aSLionel Sambuc                                           VisitedVirtualBasesSetTy& VBases) {
2004f4a2713aSLionel Sambuc   // If this base is a non-virtual primary base the address point has already
2005f4a2713aSLionel Sambuc   // been set.
2006f4a2713aSLionel Sambuc   if (!BaseIsNonVirtualPrimaryBase) {
2007f4a2713aSLionel Sambuc     // Initialize the vtable pointer for this base.
2008f4a2713aSLionel Sambuc     InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
2009f4a2713aSLionel Sambuc                             VTableClass);
2010f4a2713aSLionel Sambuc   }
2011f4a2713aSLionel Sambuc 
2012f4a2713aSLionel Sambuc   const CXXRecordDecl *RD = Base.getBase();
2013f4a2713aSLionel Sambuc 
2014f4a2713aSLionel Sambuc   // Traverse bases.
2015*0a6a1f1dSLionel Sambuc   for (const auto &I : RD->bases()) {
2016f4a2713aSLionel Sambuc     CXXRecordDecl *BaseDecl
2017*0a6a1f1dSLionel Sambuc       = cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
2018f4a2713aSLionel Sambuc 
2019f4a2713aSLionel Sambuc     // Ignore classes without a vtable.
2020f4a2713aSLionel Sambuc     if (!BaseDecl->isDynamicClass())
2021f4a2713aSLionel Sambuc       continue;
2022f4a2713aSLionel Sambuc 
2023f4a2713aSLionel Sambuc     CharUnits BaseOffset;
2024f4a2713aSLionel Sambuc     CharUnits BaseOffsetFromNearestVBase;
2025f4a2713aSLionel Sambuc     bool BaseDeclIsNonVirtualPrimaryBase;
2026f4a2713aSLionel Sambuc 
2027*0a6a1f1dSLionel Sambuc     if (I.isVirtual()) {
2028f4a2713aSLionel Sambuc       // Check if we've visited this virtual base before.
2029*0a6a1f1dSLionel Sambuc       if (!VBases.insert(BaseDecl).second)
2030f4a2713aSLionel Sambuc         continue;
2031f4a2713aSLionel Sambuc 
2032f4a2713aSLionel Sambuc       const ASTRecordLayout &Layout =
2033f4a2713aSLionel Sambuc         getContext().getASTRecordLayout(VTableClass);
2034f4a2713aSLionel Sambuc 
2035f4a2713aSLionel Sambuc       BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
2036f4a2713aSLionel Sambuc       BaseOffsetFromNearestVBase = CharUnits::Zero();
2037f4a2713aSLionel Sambuc       BaseDeclIsNonVirtualPrimaryBase = false;
2038f4a2713aSLionel Sambuc     } else {
2039f4a2713aSLionel Sambuc       const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
2040f4a2713aSLionel Sambuc 
2041f4a2713aSLionel Sambuc       BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
2042f4a2713aSLionel Sambuc       BaseOffsetFromNearestVBase =
2043f4a2713aSLionel Sambuc         OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
2044f4a2713aSLionel Sambuc       BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
2045f4a2713aSLionel Sambuc     }
2046f4a2713aSLionel Sambuc 
2047f4a2713aSLionel Sambuc     InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
2048*0a6a1f1dSLionel Sambuc                              I.isVirtual() ? BaseDecl : NearestVBase,
2049f4a2713aSLionel Sambuc                              BaseOffsetFromNearestVBase,
2050f4a2713aSLionel Sambuc                              BaseDeclIsNonVirtualPrimaryBase,
2051f4a2713aSLionel Sambuc                              VTableClass, VBases);
2052f4a2713aSLionel Sambuc   }
2053f4a2713aSLionel Sambuc }
2054f4a2713aSLionel Sambuc 
InitializeVTablePointers(const CXXRecordDecl * RD)2055f4a2713aSLionel Sambuc void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
2056f4a2713aSLionel Sambuc   // Ignore classes without a vtable.
2057f4a2713aSLionel Sambuc   if (!RD->isDynamicClass())
2058f4a2713aSLionel Sambuc     return;
2059f4a2713aSLionel Sambuc 
2060f4a2713aSLionel Sambuc   // Initialize the vtable pointers for this class and all of its bases.
2061f4a2713aSLionel Sambuc   VisitedVirtualBasesSetTy VBases;
2062f4a2713aSLionel Sambuc   InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()),
2063*0a6a1f1dSLionel Sambuc                            /*NearestVBase=*/nullptr,
2064f4a2713aSLionel Sambuc                            /*OffsetFromNearestVBase=*/CharUnits::Zero(),
2065f4a2713aSLionel Sambuc                            /*BaseIsNonVirtualPrimaryBase=*/false, RD, VBases);
2066f4a2713aSLionel Sambuc 
2067f4a2713aSLionel Sambuc   if (RD->getNumVBases())
2068f4a2713aSLionel Sambuc     CGM.getCXXABI().initializeHiddenVirtualInheritanceMembers(*this, RD);
2069f4a2713aSLionel Sambuc }
2070f4a2713aSLionel Sambuc 
GetVTablePtr(llvm::Value * This,llvm::Type * Ty)2071f4a2713aSLionel Sambuc llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
2072f4a2713aSLionel Sambuc                                            llvm::Type *Ty) {
2073f4a2713aSLionel Sambuc   llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
2074f4a2713aSLionel Sambuc   llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
2075f4a2713aSLionel Sambuc   CGM.DecorateInstruction(VTable, CGM.getTBAAInfoForVTablePtr());
2076f4a2713aSLionel Sambuc   return VTable;
2077f4a2713aSLionel Sambuc }
2078f4a2713aSLionel Sambuc 
2079f4a2713aSLionel Sambuc 
2080f4a2713aSLionel Sambuc // FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
2081f4a2713aSLionel Sambuc // quite what we want.
skipNoOpCastsAndParens(const Expr * E)2082f4a2713aSLionel Sambuc static const Expr *skipNoOpCastsAndParens(const Expr *E) {
2083f4a2713aSLionel Sambuc   while (true) {
2084f4a2713aSLionel Sambuc     if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
2085f4a2713aSLionel Sambuc       E = PE->getSubExpr();
2086f4a2713aSLionel Sambuc       continue;
2087f4a2713aSLionel Sambuc     }
2088f4a2713aSLionel Sambuc 
2089f4a2713aSLionel Sambuc     if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
2090f4a2713aSLionel Sambuc       if (CE->getCastKind() == CK_NoOp) {
2091f4a2713aSLionel Sambuc         E = CE->getSubExpr();
2092f4a2713aSLionel Sambuc         continue;
2093f4a2713aSLionel Sambuc       }
2094f4a2713aSLionel Sambuc     }
2095f4a2713aSLionel Sambuc     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2096f4a2713aSLionel Sambuc       if (UO->getOpcode() == UO_Extension) {
2097f4a2713aSLionel Sambuc         E = UO->getSubExpr();
2098f4a2713aSLionel Sambuc         continue;
2099f4a2713aSLionel Sambuc       }
2100f4a2713aSLionel Sambuc     }
2101f4a2713aSLionel Sambuc     return E;
2102f4a2713aSLionel Sambuc   }
2103f4a2713aSLionel Sambuc }
2104f4a2713aSLionel Sambuc 
2105f4a2713aSLionel Sambuc bool
CanDevirtualizeMemberFunctionCall(const Expr * Base,const CXXMethodDecl * MD)2106f4a2713aSLionel Sambuc CodeGenFunction::CanDevirtualizeMemberFunctionCall(const Expr *Base,
2107f4a2713aSLionel Sambuc                                                    const CXXMethodDecl *MD) {
2108f4a2713aSLionel Sambuc   // When building with -fapple-kext, all calls must go through the vtable since
2109f4a2713aSLionel Sambuc   // the kernel linker can do runtime patching of vtables.
2110f4a2713aSLionel Sambuc   if (getLangOpts().AppleKext)
2111f4a2713aSLionel Sambuc     return false;
2112f4a2713aSLionel Sambuc 
2113f4a2713aSLionel Sambuc   // If the most derived class is marked final, we know that no subclass can
2114f4a2713aSLionel Sambuc   // override this member function and so we can devirtualize it. For example:
2115f4a2713aSLionel Sambuc   //
2116f4a2713aSLionel Sambuc   // struct A { virtual void f(); }
2117f4a2713aSLionel Sambuc   // struct B final : A { };
2118f4a2713aSLionel Sambuc   //
2119f4a2713aSLionel Sambuc   // void f(B *b) {
2120f4a2713aSLionel Sambuc   //   b->f();
2121f4a2713aSLionel Sambuc   // }
2122f4a2713aSLionel Sambuc   //
2123f4a2713aSLionel Sambuc   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
2124f4a2713aSLionel Sambuc   if (MostDerivedClassDecl->hasAttr<FinalAttr>())
2125f4a2713aSLionel Sambuc     return true;
2126f4a2713aSLionel Sambuc 
2127f4a2713aSLionel Sambuc   // If the member function is marked 'final', we know that it can't be
2128f4a2713aSLionel Sambuc   // overridden and can therefore devirtualize it.
2129f4a2713aSLionel Sambuc   if (MD->hasAttr<FinalAttr>())
2130f4a2713aSLionel Sambuc     return true;
2131f4a2713aSLionel Sambuc 
2132f4a2713aSLionel Sambuc   // Similarly, if the class itself is marked 'final' it can't be overridden
2133f4a2713aSLionel Sambuc   // and we can therefore devirtualize the member function call.
2134f4a2713aSLionel Sambuc   if (MD->getParent()->hasAttr<FinalAttr>())
2135f4a2713aSLionel Sambuc     return true;
2136f4a2713aSLionel Sambuc 
2137f4a2713aSLionel Sambuc   Base = skipNoOpCastsAndParens(Base);
2138f4a2713aSLionel Sambuc   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
2139f4a2713aSLionel Sambuc     if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
2140f4a2713aSLionel Sambuc       // This is a record decl. We know the type and can devirtualize it.
2141f4a2713aSLionel Sambuc       return VD->getType()->isRecordType();
2142f4a2713aSLionel Sambuc     }
2143f4a2713aSLionel Sambuc 
2144f4a2713aSLionel Sambuc     return false;
2145f4a2713aSLionel Sambuc   }
2146f4a2713aSLionel Sambuc 
2147f4a2713aSLionel Sambuc   // We can devirtualize calls on an object accessed by a class member access
2148f4a2713aSLionel Sambuc   // expression, since by C++11 [basic.life]p6 we know that it can't refer to
2149f4a2713aSLionel Sambuc   // a derived class object constructed in the same location.
2150f4a2713aSLionel Sambuc   if (const MemberExpr *ME = dyn_cast<MemberExpr>(Base))
2151f4a2713aSLionel Sambuc     if (const ValueDecl *VD = dyn_cast<ValueDecl>(ME->getMemberDecl()))
2152f4a2713aSLionel Sambuc       return VD->getType()->isRecordType();
2153f4a2713aSLionel Sambuc 
2154f4a2713aSLionel Sambuc   // We can always devirtualize calls on temporary object expressions.
2155f4a2713aSLionel Sambuc   if (isa<CXXConstructExpr>(Base))
2156f4a2713aSLionel Sambuc     return true;
2157f4a2713aSLionel Sambuc 
2158f4a2713aSLionel Sambuc   // And calls on bound temporaries.
2159f4a2713aSLionel Sambuc   if (isa<CXXBindTemporaryExpr>(Base))
2160f4a2713aSLionel Sambuc     return true;
2161f4a2713aSLionel Sambuc 
2162f4a2713aSLionel Sambuc   // Check if this is a call expr that returns a record type.
2163f4a2713aSLionel Sambuc   if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
2164f4a2713aSLionel Sambuc     return CE->getCallReturnType()->isRecordType();
2165f4a2713aSLionel Sambuc 
2166f4a2713aSLionel Sambuc   // We can't devirtualize the call.
2167f4a2713aSLionel Sambuc   return false;
2168f4a2713aSLionel Sambuc }
2169f4a2713aSLionel Sambuc 
EmitForwardingCallToLambda(const CXXMethodDecl * callOperator,CallArgList & callArgs)2170f4a2713aSLionel Sambuc void CodeGenFunction::EmitForwardingCallToLambda(
2171f4a2713aSLionel Sambuc                                       const CXXMethodDecl *callOperator,
2172f4a2713aSLionel Sambuc                                       CallArgList &callArgs) {
2173f4a2713aSLionel Sambuc   // Get the address of the call operator.
2174f4a2713aSLionel Sambuc   const CGFunctionInfo &calleeFnInfo =
2175f4a2713aSLionel Sambuc     CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
2176f4a2713aSLionel Sambuc   llvm::Value *callee =
2177f4a2713aSLionel Sambuc     CGM.GetAddrOfFunction(GlobalDecl(callOperator),
2178f4a2713aSLionel Sambuc                           CGM.getTypes().GetFunctionType(calleeFnInfo));
2179f4a2713aSLionel Sambuc 
2180f4a2713aSLionel Sambuc   // Prepare the return slot.
2181f4a2713aSLionel Sambuc   const FunctionProtoType *FPT =
2182f4a2713aSLionel Sambuc     callOperator->getType()->castAs<FunctionProtoType>();
2183*0a6a1f1dSLionel Sambuc   QualType resultType = FPT->getReturnType();
2184f4a2713aSLionel Sambuc   ReturnValueSlot returnSlot;
2185f4a2713aSLionel Sambuc   if (!resultType->isVoidType() &&
2186f4a2713aSLionel Sambuc       calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
2187f4a2713aSLionel Sambuc       !hasScalarEvaluationKind(calleeFnInfo.getReturnType()))
2188f4a2713aSLionel Sambuc     returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
2189f4a2713aSLionel Sambuc 
2190f4a2713aSLionel Sambuc   // We don't need to separately arrange the call arguments because
2191f4a2713aSLionel Sambuc   // the call can't be variadic anyway --- it's impossible to forward
2192f4a2713aSLionel Sambuc   // variadic arguments.
2193f4a2713aSLionel Sambuc 
2194f4a2713aSLionel Sambuc   // Now emit our call.
2195f4a2713aSLionel Sambuc   RValue RV = EmitCall(calleeFnInfo, callee, returnSlot,
2196f4a2713aSLionel Sambuc                        callArgs, callOperator);
2197f4a2713aSLionel Sambuc 
2198f4a2713aSLionel Sambuc   // If necessary, copy the returned value into the slot.
2199f4a2713aSLionel Sambuc   if (!resultType->isVoidType() && returnSlot.isNull())
2200f4a2713aSLionel Sambuc     EmitReturnOfRValue(RV, resultType);
2201f4a2713aSLionel Sambuc   else
2202f4a2713aSLionel Sambuc     EmitBranchThroughCleanup(ReturnBlock);
2203f4a2713aSLionel Sambuc }
2204f4a2713aSLionel Sambuc 
EmitLambdaBlockInvokeBody()2205f4a2713aSLionel Sambuc void CodeGenFunction::EmitLambdaBlockInvokeBody() {
2206f4a2713aSLionel Sambuc   const BlockDecl *BD = BlockInfo->getBlockDecl();
2207f4a2713aSLionel Sambuc   const VarDecl *variable = BD->capture_begin()->getVariable();
2208f4a2713aSLionel Sambuc   const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
2209f4a2713aSLionel Sambuc 
2210f4a2713aSLionel Sambuc   // Start building arguments for forwarding call
2211f4a2713aSLionel Sambuc   CallArgList CallArgs;
2212f4a2713aSLionel Sambuc 
2213f4a2713aSLionel Sambuc   QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2214f4a2713aSLionel Sambuc   llvm::Value *ThisPtr = GetAddrOfBlockDecl(variable, false);
2215f4a2713aSLionel Sambuc   CallArgs.add(RValue::get(ThisPtr), ThisType);
2216f4a2713aSLionel Sambuc 
2217f4a2713aSLionel Sambuc   // Add the rest of the parameters.
2218*0a6a1f1dSLionel Sambuc   for (auto param : BD->params())
2219f4a2713aSLionel Sambuc     EmitDelegateCallArg(CallArgs, param, param->getLocStart());
2220*0a6a1f1dSLionel Sambuc 
2221f4a2713aSLionel Sambuc   assert(!Lambda->isGenericLambda() &&
2222f4a2713aSLionel Sambuc             "generic lambda interconversion to block not implemented");
2223f4a2713aSLionel Sambuc   EmitForwardingCallToLambda(Lambda->getLambdaCallOperator(), CallArgs);
2224f4a2713aSLionel Sambuc }
2225f4a2713aSLionel Sambuc 
EmitLambdaToBlockPointerBody(FunctionArgList & Args)2226f4a2713aSLionel Sambuc void CodeGenFunction::EmitLambdaToBlockPointerBody(FunctionArgList &Args) {
2227f4a2713aSLionel Sambuc   if (cast<CXXMethodDecl>(CurCodeDecl)->isVariadic()) {
2228f4a2713aSLionel Sambuc     // FIXME: Making this work correctly is nasty because it requires either
2229f4a2713aSLionel Sambuc     // cloning the body of the call operator or making the call operator forward.
2230f4a2713aSLionel Sambuc     CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function");
2231f4a2713aSLionel Sambuc     return;
2232f4a2713aSLionel Sambuc   }
2233f4a2713aSLionel Sambuc 
2234f4a2713aSLionel Sambuc   EmitFunctionBody(Args, cast<FunctionDecl>(CurGD.getDecl())->getBody());
2235f4a2713aSLionel Sambuc }
2236f4a2713aSLionel Sambuc 
EmitLambdaDelegatingInvokeBody(const CXXMethodDecl * MD)2237f4a2713aSLionel Sambuc void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
2238f4a2713aSLionel Sambuc   const CXXRecordDecl *Lambda = MD->getParent();
2239f4a2713aSLionel Sambuc 
2240f4a2713aSLionel Sambuc   // Start building arguments for forwarding call
2241f4a2713aSLionel Sambuc   CallArgList CallArgs;
2242f4a2713aSLionel Sambuc 
2243f4a2713aSLionel Sambuc   QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2244f4a2713aSLionel Sambuc   llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
2245f4a2713aSLionel Sambuc   CallArgs.add(RValue::get(ThisPtr), ThisType);
2246f4a2713aSLionel Sambuc 
2247f4a2713aSLionel Sambuc   // Add the rest of the parameters.
2248*0a6a1f1dSLionel Sambuc   for (auto Param : MD->params())
2249*0a6a1f1dSLionel Sambuc     EmitDelegateCallArg(CallArgs, Param, Param->getLocStart());
2250*0a6a1f1dSLionel Sambuc 
2251f4a2713aSLionel Sambuc   const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
2252f4a2713aSLionel Sambuc   // For a generic lambda, find the corresponding call operator specialization
2253f4a2713aSLionel Sambuc   // to which the call to the static-invoker shall be forwarded.
2254f4a2713aSLionel Sambuc   if (Lambda->isGenericLambda()) {
2255f4a2713aSLionel Sambuc     assert(MD->isFunctionTemplateSpecialization());
2256f4a2713aSLionel Sambuc     const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
2257f4a2713aSLionel Sambuc     FunctionTemplateDecl *CallOpTemplate = CallOp->getDescribedFunctionTemplate();
2258*0a6a1f1dSLionel Sambuc     void *InsertPos = nullptr;
2259f4a2713aSLionel Sambuc     FunctionDecl *CorrespondingCallOpSpecialization =
2260*0a6a1f1dSLionel Sambuc         CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
2261f4a2713aSLionel Sambuc     assert(CorrespondingCallOpSpecialization);
2262f4a2713aSLionel Sambuc     CallOp = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
2263f4a2713aSLionel Sambuc   }
2264f4a2713aSLionel Sambuc   EmitForwardingCallToLambda(CallOp, CallArgs);
2265f4a2713aSLionel Sambuc }
2266f4a2713aSLionel Sambuc 
EmitLambdaStaticInvokeFunction(const CXXMethodDecl * MD)2267f4a2713aSLionel Sambuc void CodeGenFunction::EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD) {
2268f4a2713aSLionel Sambuc   if (MD->isVariadic()) {
2269f4a2713aSLionel Sambuc     // FIXME: Making this work correctly is nasty because it requires either
2270f4a2713aSLionel Sambuc     // cloning the body of the call operator or making the call operator forward.
2271f4a2713aSLionel Sambuc     CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
2272f4a2713aSLionel Sambuc     return;
2273f4a2713aSLionel Sambuc   }
2274f4a2713aSLionel Sambuc 
2275f4a2713aSLionel Sambuc   EmitLambdaDelegatingInvokeBody(MD);
2276f4a2713aSLionel Sambuc }
2277