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