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