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