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