1 //===--- CGClass.cpp - Emit LLVM Code for C++ classes -----------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 // This contains code dealing with C++ code generation of classes
11 //===----------------------------------------------------------------------===//
15 #include "CGDebugInfo.h"
16 #include "CGRecordLayout.h"
17 #include "CodeGenFunction.h"
18 #include "TargetInfo.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/EvaluatedExprVisitor.h"
22 #include "clang/AST/RecordLayout.h"
23 #include "clang/AST/StmtCXX.h"
24 #include "clang/Basic/CodeGenOptions.h"
25 #include "clang/Basic/TargetBuiltins.h"
26 #include "clang/CodeGen/CGFunctionInfo.h"
27 #include "llvm/IR/Intrinsics.h"
28 #include "llvm/IR/Metadata.h"
29 #include "llvm/Transforms/Utils/SanitizerStats.h"
31 using namespace clang;
32 using namespace CodeGen;
34 /// Return the best known alignment for an unknown pointer to a
36 CharUnits CodeGenModule::getClassPointerAlignment(const CXXRecordDecl *RD) {
37 if (!RD->isCompleteDefinition())
38 return CharUnits::One(); // Hopefully won't be used anywhere.
40 auto &layout = getContext().getASTRecordLayout(RD);
42 // If the class is final, then we know that the pointer points to an
43 // object of that type and can use the full alignment.
44 if (RD->hasAttr<FinalAttr>()) {
45 return layout.getAlignment();
47 // Otherwise, we have to assume it could be a subclass.
49 return layout.getNonVirtualAlignment();
53 /// Return the best known alignment for a pointer to a virtual base,
54 /// given the alignment of a pointer to the derived class.
55 CharUnits CodeGenModule::getVBaseAlignment(CharUnits actualDerivedAlign,
56 const CXXRecordDecl *derivedClass,
57 const CXXRecordDecl *vbaseClass) {
58 // The basic idea here is that an underaligned derived pointer might
59 // indicate an underaligned base pointer.
61 assert(vbaseClass->isCompleteDefinition());
62 auto &baseLayout = getContext().getASTRecordLayout(vbaseClass);
63 CharUnits expectedVBaseAlign = baseLayout.getNonVirtualAlignment();
65 return getDynamicOffsetAlignment(actualDerivedAlign, derivedClass,
70 CodeGenModule::getDynamicOffsetAlignment(CharUnits actualBaseAlign,
71 const CXXRecordDecl *baseDecl,
72 CharUnits expectedTargetAlign) {
73 // If the base is an incomplete type (which is, alas, possible with
74 // member pointers), be pessimistic.
75 if (!baseDecl->isCompleteDefinition())
76 return std::min(actualBaseAlign, expectedTargetAlign);
78 auto &baseLayout = getContext().getASTRecordLayout(baseDecl);
79 CharUnits expectedBaseAlign = baseLayout.getNonVirtualAlignment();
81 // If the class is properly aligned, assume the target offset is, too.
83 // This actually isn't necessarily the right thing to do --- if the
84 // class is a complete object, but it's only properly aligned for a
85 // base subobject, then the alignments of things relative to it are
86 // probably off as well. (Note that this requires the alignment of
87 // the target to be greater than the NV alignment of the derived
90 // However, our approach to this kind of under-alignment can only
91 // ever be best effort; after all, we're never going to propagate
92 // alignments through variables or parameters. Note, in particular,
93 // that constructing a polymorphic type in an address that's less
94 // than pointer-aligned will generally trap in the constructor,
95 // unless we someday add some sort of attribute to change the
96 // assumed alignment of 'this'. So our goal here is pretty much
97 // just to allow the user to explicitly say that a pointer is
98 // under-aligned and then safely access its fields and vtables.
99 if (actualBaseAlign >= expectedBaseAlign) {
100 return expectedTargetAlign;
103 // Otherwise, we might be offset by an arbitrary multiple of the
104 // actual alignment. The correct adjustment is to take the min of
105 // the two alignments.
106 return std::min(actualBaseAlign, expectedTargetAlign);
109 Address CodeGenFunction::LoadCXXThisAddress() {
110 assert(CurFuncDecl && "loading 'this' without a func declaration?");
111 assert(isa<CXXMethodDecl>(CurFuncDecl));
113 // Lazily compute CXXThisAlignment.
114 if (CXXThisAlignment.isZero()) {
115 // Just use the best known alignment for the parent.
116 // TODO: if we're currently emitting a complete-object ctor/dtor,
117 // we can always use the complete-object alignment.
118 auto RD = cast<CXXMethodDecl>(CurFuncDecl)->getParent();
119 CXXThisAlignment = CGM.getClassPointerAlignment(RD);
122 return Address(LoadCXXThis(), CXXThisAlignment);
125 /// Emit the address of a field using a member data pointer.
127 /// \param E Only used for emergency diagnostics
129 CodeGenFunction::EmitCXXMemberDataPointerAddress(const Expr *E, Address base,
130 llvm::Value *memberPtr,
131 const MemberPointerType *memberPtrType,
132 LValueBaseInfo *BaseInfo,
133 TBAAAccessInfo *TBAAInfo) {
134 // Ask the ABI to compute the actual address.
136 CGM.getCXXABI().EmitMemberDataPointerAddress(*this, E, base,
137 memberPtr, memberPtrType);
139 QualType memberType = memberPtrType->getPointeeType();
140 CharUnits memberAlign = getNaturalTypeAlignment(memberType, BaseInfo,
143 CGM.getDynamicOffsetAlignment(base.getAlignment(),
144 memberPtrType->getClass()->getAsCXXRecordDecl(),
146 return Address(ptr, memberAlign);
149 CharUnits CodeGenModule::computeNonVirtualBaseClassOffset(
150 const CXXRecordDecl *DerivedClass, CastExpr::path_const_iterator Start,
151 CastExpr::path_const_iterator End) {
152 CharUnits Offset = CharUnits::Zero();
154 const ASTContext &Context = getContext();
155 const CXXRecordDecl *RD = DerivedClass;
157 for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
158 const CXXBaseSpecifier *Base = *I;
159 assert(!Base->isVirtual() && "Should not see virtual bases here!");
162 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
164 const CXXRecordDecl *BaseDecl =
165 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
168 Offset += Layout.getBaseClassOffset(BaseDecl);
177 CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
178 CastExpr::path_const_iterator PathBegin,
179 CastExpr::path_const_iterator PathEnd) {
180 assert(PathBegin != PathEnd && "Base path should not be empty!");
183 computeNonVirtualBaseClassOffset(ClassDecl, PathBegin, PathEnd);
187 llvm::Type *PtrDiffTy =
188 Types.ConvertType(getContext().getPointerDiffType());
190 return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
193 /// Gets the address of a direct base class within a complete object.
194 /// This should only be used for (1) non-virtual bases or (2) virtual bases
195 /// when the type is known to be complete (e.g. in complete destructors).
197 /// The object pointed to by 'This' is assumed to be non-null.
199 CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(Address This,
200 const CXXRecordDecl *Derived,
201 const CXXRecordDecl *Base,
202 bool BaseIsVirtual) {
203 // 'this' must be a pointer (in some address space) to Derived.
204 assert(This.getElementType() == ConvertType(Derived));
206 // Compute the offset of the virtual base.
208 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
210 Offset = Layout.getVBaseClassOffset(Base);
212 Offset = Layout.getBaseClassOffset(Base);
214 // Shift and cast down to the base type.
215 // TODO: for complete types, this should be possible with a GEP.
217 if (!Offset.isZero()) {
218 V = Builder.CreateElementBitCast(V, Int8Ty);
219 V = Builder.CreateConstInBoundsByteGEP(V, Offset);
221 V = Builder.CreateElementBitCast(V, ConvertType(Base));
227 ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, Address addr,
228 CharUnits nonVirtualOffset,
229 llvm::Value *virtualOffset,
230 const CXXRecordDecl *derivedClass,
231 const CXXRecordDecl *nearestVBase) {
232 // Assert that we have something to do.
233 assert(!nonVirtualOffset.isZero() || virtualOffset != nullptr);
235 // Compute the offset from the static and dynamic components.
236 llvm::Value *baseOffset;
237 if (!nonVirtualOffset.isZero()) {
238 baseOffset = llvm::ConstantInt::get(CGF.PtrDiffTy,
239 nonVirtualOffset.getQuantity());
241 baseOffset = CGF.Builder.CreateAdd(virtualOffset, baseOffset);
244 baseOffset = virtualOffset;
247 // Apply the base offset.
248 llvm::Value *ptr = addr.getPointer();
249 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
250 ptr = CGF.Builder.CreateInBoundsGEP(ptr, baseOffset, "add.ptr");
252 // If we have a virtual component, the alignment of the result will
253 // be relative only to the known alignment of that vbase.
256 assert(nearestVBase && "virtual offset without vbase?");
257 alignment = CGF.CGM.getVBaseAlignment(addr.getAlignment(),
258 derivedClass, nearestVBase);
260 alignment = addr.getAlignment();
262 alignment = alignment.alignmentAtOffset(nonVirtualOffset);
264 return Address(ptr, alignment);
267 Address CodeGenFunction::GetAddressOfBaseClass(
268 Address Value, const CXXRecordDecl *Derived,
269 CastExpr::path_const_iterator PathBegin,
270 CastExpr::path_const_iterator PathEnd, bool NullCheckValue,
271 SourceLocation Loc) {
272 assert(PathBegin != PathEnd && "Base path should not be empty!");
274 CastExpr::path_const_iterator Start = PathBegin;
275 const CXXRecordDecl *VBase = nullptr;
277 // Sema has done some convenient canonicalization here: if the
278 // access path involved any virtual steps, the conversion path will
279 // *start* with a step down to the correct virtual base subobject,
280 // and hence will not require any further steps.
281 if ((*Start)->isVirtual()) {
283 cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
287 // Compute the static offset of the ultimate destination within its
288 // allocating subobject (the virtual base, if there is one, or else
289 // the "complete" object that we see).
290 CharUnits NonVirtualOffset = CGM.computeNonVirtualBaseClassOffset(
291 VBase ? VBase : Derived, Start, PathEnd);
293 // If there's a virtual step, we can sometimes "devirtualize" it.
294 // For now, that's limited to when the derived type is final.
295 // TODO: "devirtualize" this for accesses to known-complete objects.
296 if (VBase && Derived->hasAttr<FinalAttr>()) {
297 const ASTRecordLayout &layout = getContext().getASTRecordLayout(Derived);
298 CharUnits vBaseOffset = layout.getVBaseClassOffset(VBase);
299 NonVirtualOffset += vBaseOffset;
300 VBase = nullptr; // we no longer have a virtual step
303 // Get the base pointer type.
304 llvm::Type *BasePtrTy =
305 ConvertType((PathEnd[-1])->getType())
306 ->getPointerTo(Value.getType()->getPointerAddressSpace());
308 QualType DerivedTy = getContext().getRecordType(Derived);
309 CharUnits DerivedAlign = CGM.getClassPointerAlignment(Derived);
311 // If the static offset is zero and we don't have a virtual step,
312 // just do a bitcast; null checks are unnecessary.
313 if (NonVirtualOffset.isZero() && !VBase) {
314 if (sanitizePerformTypeCheck()) {
315 SanitizerSet SkippedChecks;
316 SkippedChecks.set(SanitizerKind::Null, !NullCheckValue);
317 EmitTypeCheck(TCK_Upcast, Loc, Value.getPointer(),
318 DerivedTy, DerivedAlign, SkippedChecks);
320 return Builder.CreateBitCast(Value, BasePtrTy);
323 llvm::BasicBlock *origBB = nullptr;
324 llvm::BasicBlock *endBB = nullptr;
326 // Skip over the offset (and the vtable load) if we're supposed to
327 // null-check the pointer.
328 if (NullCheckValue) {
329 origBB = Builder.GetInsertBlock();
330 llvm::BasicBlock *notNullBB = createBasicBlock("cast.notnull");
331 endBB = createBasicBlock("cast.end");
333 llvm::Value *isNull = Builder.CreateIsNull(Value.getPointer());
334 Builder.CreateCondBr(isNull, endBB, notNullBB);
335 EmitBlock(notNullBB);
338 if (sanitizePerformTypeCheck()) {
339 SanitizerSet SkippedChecks;
340 SkippedChecks.set(SanitizerKind::Null, true);
341 EmitTypeCheck(VBase ? TCK_UpcastToVirtualBase : TCK_Upcast, Loc,
342 Value.getPointer(), DerivedTy, DerivedAlign, SkippedChecks);
345 // Compute the virtual offset.
346 llvm::Value *VirtualOffset = nullptr;
349 CGM.getCXXABI().GetVirtualBaseClassOffset(*this, Value, Derived, VBase);
352 // Apply both offsets.
353 Value = ApplyNonVirtualAndVirtualOffset(*this, Value, NonVirtualOffset,
354 VirtualOffset, Derived, VBase);
356 // Cast to the destination type.
357 Value = Builder.CreateBitCast(Value, BasePtrTy);
359 // Build a phi if we needed a null check.
360 if (NullCheckValue) {
361 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
362 Builder.CreateBr(endBB);
365 llvm::PHINode *PHI = Builder.CreatePHI(BasePtrTy, 2, "cast.result");
366 PHI->addIncoming(Value.getPointer(), notNullBB);
367 PHI->addIncoming(llvm::Constant::getNullValue(BasePtrTy), origBB);
368 Value = Address(PHI, Value.getAlignment());
375 CodeGenFunction::GetAddressOfDerivedClass(Address BaseAddr,
376 const CXXRecordDecl *Derived,
377 CastExpr::path_const_iterator PathBegin,
378 CastExpr::path_const_iterator PathEnd,
379 bool NullCheckValue) {
380 assert(PathBegin != PathEnd && "Base path should not be empty!");
383 getContext().getCanonicalType(getContext().getTagDeclType(Derived));
384 llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
386 llvm::Value *NonVirtualOffset =
387 CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
389 if (!NonVirtualOffset) {
390 // No offset, we can just cast back.
391 return Builder.CreateBitCast(BaseAddr, DerivedPtrTy);
394 llvm::BasicBlock *CastNull = nullptr;
395 llvm::BasicBlock *CastNotNull = nullptr;
396 llvm::BasicBlock *CastEnd = nullptr;
398 if (NullCheckValue) {
399 CastNull = createBasicBlock("cast.null");
400 CastNotNull = createBasicBlock("cast.notnull");
401 CastEnd = createBasicBlock("cast.end");
403 llvm::Value *IsNull = Builder.CreateIsNull(BaseAddr.getPointer());
404 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
405 EmitBlock(CastNotNull);
409 llvm::Value *Value = Builder.CreateBitCast(BaseAddr.getPointer(), Int8PtrTy);
410 Value = Builder.CreateInBoundsGEP(Value, Builder.CreateNeg(NonVirtualOffset),
414 Value = Builder.CreateBitCast(Value, DerivedPtrTy);
416 // Produce a PHI if we had a null-check.
417 if (NullCheckValue) {
418 Builder.CreateBr(CastEnd);
420 Builder.CreateBr(CastEnd);
423 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
424 PHI->addIncoming(Value, CastNotNull);
425 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
429 return Address(Value, CGM.getClassPointerAlignment(Derived));
432 llvm::Value *CodeGenFunction::GetVTTParameter(GlobalDecl GD,
435 if (!CGM.getCXXABI().NeedsVTTParameter(GD)) {
436 // This constructor/destructor does not need a VTT parameter.
440 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CurCodeDecl)->getParent();
441 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
445 uint64_t SubVTTIndex;
448 // If this is a delegating constructor call, just load the VTT.
450 } else if (RD == Base) {
451 // If the record matches the base, this is the complete ctor/dtor
452 // variant calling the base variant in a class with virtual bases.
453 assert(!CGM.getCXXABI().NeedsVTTParameter(CurGD) &&
454 "doing no-op VTT offset in base dtor/ctor?");
455 assert(!ForVirtualBase && "Can't have same class as virtual base!");
458 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
459 CharUnits BaseOffset = ForVirtualBase ?
460 Layout.getVBaseClassOffset(Base) :
461 Layout.getBaseClassOffset(Base);
464 CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
465 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
468 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
469 // A VTT parameter was passed to the constructor, use it.
471 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
473 // We're the complete constructor, so get the VTT by name.
474 VTT = CGM.getVTables().GetAddrOfVTT(RD);
475 VTT = Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
482 /// Call the destructor for a direct base class.
483 struct CallBaseDtor final : EHScopeStack::Cleanup {
484 const CXXRecordDecl *BaseClass;
486 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
487 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
489 void Emit(CodeGenFunction &CGF, Flags flags) override {
490 const CXXRecordDecl *DerivedClass =
491 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
493 const CXXDestructorDecl *D = BaseClass->getDestructor();
494 // We are already inside a destructor, so presumably the object being
495 // destroyed should have the expected type.
496 QualType ThisTy = D->getThisObjectType();
498 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThisAddress(),
499 DerivedClass, BaseClass,
501 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual,
502 /*Delegating=*/false, Addr, ThisTy);
506 /// A visitor which checks whether an initializer uses 'this' in a
507 /// way which requires the vtable to be properly set.
508 struct DynamicThisUseChecker : ConstEvaluatedExprVisitor<DynamicThisUseChecker> {
509 typedef ConstEvaluatedExprVisitor<DynamicThisUseChecker> super;
513 DynamicThisUseChecker(const ASTContext &C) : super(C), UsesThis(false) {}
515 // Black-list all explicit and implicit references to 'this'.
517 // Do we need to worry about external references to 'this' derived
518 // from arbitrary code? If so, then anything which runs arbitrary
519 // external code might potentially access the vtable.
520 void VisitCXXThisExpr(const CXXThisExpr *E) { UsesThis = true; }
522 } // end anonymous namespace
524 static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
525 DynamicThisUseChecker Checker(C);
527 return Checker.UsesThis;
530 static void EmitBaseInitializer(CodeGenFunction &CGF,
531 const CXXRecordDecl *ClassDecl,
532 CXXCtorInitializer *BaseInit) {
533 assert(BaseInit->isBaseInitializer() &&
534 "Must have base initializer!");
536 Address ThisPtr = CGF.LoadCXXThisAddress();
538 const Type *BaseType = BaseInit->getBaseClass();
539 CXXRecordDecl *BaseClassDecl =
540 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
542 bool isBaseVirtual = BaseInit->isBaseVirtual();
544 // If the initializer for the base (other than the constructor
545 // itself) accesses 'this' in any way, we need to initialize the
547 if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
548 CGF.InitializeVTablePointers(ClassDecl);
550 // We can pretend to be a complete class because it only matters for
551 // virtual bases, and we only do virtual bases for complete ctors.
553 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
556 AggValueSlot AggSlot =
557 AggValueSlot::forAddr(
559 AggValueSlot::IsDestructed,
560 AggValueSlot::DoesNotNeedGCBarriers,
561 AggValueSlot::IsNotAliased,
562 CGF.getOverlapForBaseInit(ClassDecl, BaseClassDecl, isBaseVirtual));
564 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
566 if (CGF.CGM.getLangOpts().Exceptions &&
567 !BaseClassDecl->hasTrivialDestructor())
568 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
572 static bool isMemcpyEquivalentSpecialMember(const CXXMethodDecl *D) {
573 auto *CD = dyn_cast<CXXConstructorDecl>(D);
574 if (!(CD && CD->isCopyOrMoveConstructor()) &&
575 !D->isCopyAssignmentOperator() && !D->isMoveAssignmentOperator())
578 // We can emit a memcpy for a trivial copy or move constructor/assignment.
579 if (D->isTrivial() && !D->getParent()->mayInsertExtraPadding())
582 // We *must* emit a memcpy for a defaulted union copy or move op.
583 if (D->getParent()->isUnion() && D->isDefaulted())
589 static void EmitLValueForAnyFieldInitialization(CodeGenFunction &CGF,
590 CXXCtorInitializer *MemberInit,
592 FieldDecl *Field = MemberInit->getAnyMember();
593 if (MemberInit->isIndirectMemberInitializer()) {
594 // If we are initializing an anonymous union field, drill down to the field.
595 IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember();
596 for (const auto *I : IndirectField->chain())
597 LHS = CGF.EmitLValueForFieldInitialization(LHS, cast<FieldDecl>(I));
599 LHS = CGF.EmitLValueForFieldInitialization(LHS, Field);
603 static void EmitMemberInitializer(CodeGenFunction &CGF,
604 const CXXRecordDecl *ClassDecl,
605 CXXCtorInitializer *MemberInit,
606 const CXXConstructorDecl *Constructor,
607 FunctionArgList &Args) {
608 ApplyDebugLocation Loc(CGF, MemberInit->getSourceLocation());
609 assert(MemberInit->isAnyMemberInitializer() &&
610 "Must have member initializer!");
611 assert(MemberInit->getInit() && "Must have initializer!");
613 // non-static data member initializers.
614 FieldDecl *Field = MemberInit->getAnyMember();
615 QualType FieldType = Field->getType();
617 llvm::Value *ThisPtr = CGF.LoadCXXThis();
618 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
621 // If a base constructor is being emitted, create an LValue that has the
622 // non-virtual alignment.
623 if (CGF.CurGD.getCtorType() == Ctor_Base)
624 LHS = CGF.MakeNaturalAlignPointeeAddrLValue(ThisPtr, RecordTy);
626 LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
628 EmitLValueForAnyFieldInitialization(CGF, MemberInit, LHS);
630 // Special case: if we are in a copy or move constructor, and we are copying
631 // an array of PODs or classes with trivial copy constructors, ignore the
632 // AST and perform the copy we know is equivalent.
633 // FIXME: This is hacky at best... if we had a bit more explicit information
634 // in the AST, we could generalize it more easily.
635 const ConstantArrayType *Array
636 = CGF.getContext().getAsConstantArrayType(FieldType);
637 if (Array && Constructor->isDefaulted() &&
638 Constructor->isCopyOrMoveConstructor()) {
639 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
640 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
641 if (BaseElementTy.isPODType(CGF.getContext()) ||
642 (CE && isMemcpyEquivalentSpecialMember(CE->getConstructor()))) {
643 unsigned SrcArgIndex =
644 CGF.CGM.getCXXABI().getSrcArgforCopyCtor(Constructor, Args);
646 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
647 LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
648 LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field);
650 // Copy the aggregate.
651 CGF.EmitAggregateCopy(LHS, Src, FieldType, CGF.getOverlapForFieldInit(Field),
652 LHS.isVolatileQualified());
653 // Ensure that we destroy the objects if an exception is thrown later in
655 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
656 if (CGF.needsEHCleanup(dtorKind))
657 CGF.pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
662 CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit());
665 void CodeGenFunction::EmitInitializerForField(FieldDecl *Field, LValue LHS,
667 QualType FieldType = Field->getType();
668 switch (getEvaluationKind(FieldType)) {
670 if (LHS.isSimple()) {
671 EmitExprAsInit(Init, Field, LHS, false);
673 RValue RHS = RValue::get(EmitScalarExpr(Init));
674 EmitStoreThroughLValue(RHS, LHS);
678 EmitComplexExprIntoLValue(Init, LHS, /*isInit*/ true);
680 case TEK_Aggregate: {
682 AggValueSlot::forLValue(
684 AggValueSlot::IsDestructed,
685 AggValueSlot::DoesNotNeedGCBarriers,
686 AggValueSlot::IsNotAliased,
687 getOverlapForFieldInit(Field),
688 AggValueSlot::IsNotZeroed,
689 // Checks are made by the code that calls constructor.
690 AggValueSlot::IsSanitizerChecked);
691 EmitAggExpr(Init, Slot);
696 // Ensure that we destroy this object if an exception is thrown
697 // later in the constructor.
698 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
699 if (needsEHCleanup(dtorKind))
700 pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
703 /// Checks whether the given constructor is a valid subject for the
704 /// complete-to-base constructor delegation optimization, i.e.
705 /// emitting the complete constructor as a simple call to the base
707 bool CodeGenFunction::IsConstructorDelegationValid(
708 const CXXConstructorDecl *Ctor) {
710 // Currently we disable the optimization for classes with virtual
711 // bases because (1) the addresses of parameter variables need to be
712 // consistent across all initializers but (2) the delegate function
713 // call necessarily creates a second copy of the parameter variable.
715 // The limiting example (purely theoretical AFAIK):
716 // struct A { A(int &c) { c++; } };
717 // struct B : virtual A {
718 // B(int count) : A(count) { printf("%d\n", count); }
720 // ...although even this example could in principle be emitted as a
721 // delegation since the address of the parameter doesn't escape.
722 if (Ctor->getParent()->getNumVBases()) {
723 // TODO: white-list trivial vbase initializers. This case wouldn't
724 // be subject to the restrictions below.
726 // TODO: white-list cases where:
727 // - there are no non-reference parameters to the constructor
728 // - the initializers don't access any non-reference parameters
729 // - the initializers don't take the address of non-reference
732 // If we ever add any of the above cases, remember that:
733 // - function-try-blocks will always blacklist this optimization
734 // - we need to perform the constructor prologue and cleanup in
735 // EmitConstructorBody.
740 // We also disable the optimization for variadic functions because
741 // it's impossible to "re-pass" varargs.
742 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
745 // FIXME: Decide if we can do a delegation of a delegating constructor.
746 if (Ctor->isDelegatingConstructor())
752 // Emit code in ctor (Prologue==true) or dtor (Prologue==false)
753 // to poison the extra field paddings inserted under
754 // -fsanitize-address-field-padding=1|2.
755 void CodeGenFunction::EmitAsanPrologueOrEpilogue(bool Prologue) {
756 ASTContext &Context = getContext();
757 const CXXRecordDecl *ClassDecl =
758 Prologue ? cast<CXXConstructorDecl>(CurGD.getDecl())->getParent()
759 : cast<CXXDestructorDecl>(CurGD.getDecl())->getParent();
760 if (!ClassDecl->mayInsertExtraPadding()) return;
762 struct SizeAndOffset {
767 unsigned PtrSize = CGM.getDataLayout().getPointerSizeInBits();
768 const ASTRecordLayout &Info = Context.getASTRecordLayout(ClassDecl);
770 // Populate sizes and offsets of fields.
771 SmallVector<SizeAndOffset, 16> SSV(Info.getFieldCount());
772 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i)
774 Context.toCharUnitsFromBits(Info.getFieldOffset(i)).getQuantity();
776 size_t NumFields = 0;
777 for (const auto *Field : ClassDecl->fields()) {
778 const FieldDecl *D = Field;
779 std::pair<CharUnits, CharUnits> FieldInfo =
780 Context.getTypeInfoInChars(D->getType());
781 CharUnits FieldSize = FieldInfo.first;
782 assert(NumFields < SSV.size());
783 SSV[NumFields].Size = D->isBitField() ? 0 : FieldSize.getQuantity();
786 assert(NumFields == SSV.size());
787 if (SSV.size() <= 1) return;
789 // We will insert calls to __asan_* run-time functions.
790 // LLVM AddressSanitizer pass may decide to inline them later.
791 llvm::Type *Args[2] = {IntPtrTy, IntPtrTy};
792 llvm::FunctionType *FTy =
793 llvm::FunctionType::get(CGM.VoidTy, Args, false);
794 llvm::FunctionCallee F = CGM.CreateRuntimeFunction(
795 FTy, Prologue ? "__asan_poison_intra_object_redzone"
796 : "__asan_unpoison_intra_object_redzone");
798 llvm::Value *ThisPtr = LoadCXXThis();
799 ThisPtr = Builder.CreatePtrToInt(ThisPtr, IntPtrTy);
800 uint64_t TypeSize = Info.getNonVirtualSize().getQuantity();
801 // For each field check if it has sufficient padding,
802 // if so (un)poison it with a call.
803 for (size_t i = 0; i < SSV.size(); i++) {
804 uint64_t AsanAlignment = 8;
805 uint64_t NextField = i == SSV.size() - 1 ? TypeSize : SSV[i + 1].Offset;
806 uint64_t PoisonSize = NextField - SSV[i].Offset - SSV[i].Size;
807 uint64_t EndOffset = SSV[i].Offset + SSV[i].Size;
808 if (PoisonSize < AsanAlignment || !SSV[i].Size ||
809 (NextField % AsanAlignment) != 0)
812 F, {Builder.CreateAdd(ThisPtr, Builder.getIntN(PtrSize, EndOffset)),
813 Builder.getIntN(PtrSize, PoisonSize)});
817 /// EmitConstructorBody - Emits the body of the current constructor.
818 void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
819 EmitAsanPrologueOrEpilogue(true);
820 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
821 CXXCtorType CtorType = CurGD.getCtorType();
823 assert((CGM.getTarget().getCXXABI().hasConstructorVariants() ||
824 CtorType == Ctor_Complete) &&
825 "can only generate complete ctor for this ABI");
827 // Before we go any further, try the complete->base constructor
828 // delegation optimization.
829 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
830 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
831 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args, Ctor->getEndLoc());
835 const FunctionDecl *Definition = nullptr;
836 Stmt *Body = Ctor->getBody(Definition);
837 assert(Definition == Ctor && "emitting wrong constructor body");
839 // Enter the function-try-block before the constructor prologue if
841 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
843 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
845 incrementProfileCounter(Body);
847 RunCleanupsScope RunCleanups(*this);
849 // TODO: in restricted cases, we can emit the vbase initializers of
850 // a complete ctor and then delegate to the base ctor.
852 // Emit the constructor prologue, i.e. the base and member
854 EmitCtorPrologue(Ctor, CtorType, Args);
856 // Emit the body of the statement.
858 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
862 // Emit any cleanup blocks associated with the member or base
863 // initializers, which includes (along the exceptional path) the
864 // destructors for those members and bases that were fully
866 RunCleanups.ForceCleanup();
869 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
873 /// RAII object to indicate that codegen is copying the value representation
874 /// instead of the object representation. Useful when copying a struct or
875 /// class which has uninitialized members and we're only performing
876 /// lvalue-to-rvalue conversion on the object but not its members.
877 class CopyingValueRepresentation {
879 explicit CopyingValueRepresentation(CodeGenFunction &CGF)
880 : CGF(CGF), OldSanOpts(CGF.SanOpts) {
881 CGF.SanOpts.set(SanitizerKind::Bool, false);
882 CGF.SanOpts.set(SanitizerKind::Enum, false);
884 ~CopyingValueRepresentation() {
885 CGF.SanOpts = OldSanOpts;
888 CodeGenFunction &CGF;
889 SanitizerSet OldSanOpts;
891 } // end anonymous namespace
894 class FieldMemcpyizer {
896 FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl,
897 const VarDecl *SrcRec)
898 : CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec),
899 RecLayout(CGF.getContext().getASTRecordLayout(ClassDecl)),
900 FirstField(nullptr), LastField(nullptr), FirstFieldOffset(0),
901 LastFieldOffset(0), LastAddedFieldIndex(0) {}
903 bool isMemcpyableField(FieldDecl *F) const {
904 // Never memcpy fields when we are adding poisoned paddings.
905 if (CGF.getContext().getLangOpts().SanitizeAddressFieldPadding)
907 Qualifiers Qual = F->getType().getQualifiers();
908 if (Qual.hasVolatile() || Qual.hasObjCLifetime())
913 void addMemcpyableField(FieldDecl *F) {
920 CharUnits getMemcpySize(uint64_t FirstByteOffset) const {
921 ASTContext &Ctx = CGF.getContext();
922 unsigned LastFieldSize =
923 LastField->isBitField()
924 ? LastField->getBitWidthValue(Ctx)
926 Ctx.getTypeInfoDataSizeInChars(LastField->getType()).first);
927 uint64_t MemcpySizeBits = LastFieldOffset + LastFieldSize -
928 FirstByteOffset + Ctx.getCharWidth() - 1;
929 CharUnits MemcpySize = Ctx.toCharUnitsFromBits(MemcpySizeBits);
934 // Give the subclass a chance to bail out if it feels the memcpy isn't
935 // worth it (e.g. Hasn't aggregated enough data).
940 uint64_t FirstByteOffset;
941 if (FirstField->isBitField()) {
942 const CGRecordLayout &RL =
943 CGF.getTypes().getCGRecordLayout(FirstField->getParent());
944 const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField);
945 // FirstFieldOffset is not appropriate for bitfields,
946 // we need to use the storage offset instead.
947 FirstByteOffset = CGF.getContext().toBits(BFInfo.StorageOffset);
949 FirstByteOffset = FirstFieldOffset;
952 CharUnits MemcpySize = getMemcpySize(FirstByteOffset);
953 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
954 Address ThisPtr = CGF.LoadCXXThisAddress();
955 LValue DestLV = CGF.MakeAddrLValue(ThisPtr, RecordTy);
956 LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField);
957 llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec));
958 LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
959 LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField);
961 emitMemcpyIR(Dest.isBitField() ? Dest.getBitFieldAddress() : Dest.getAddress(),
962 Src.isBitField() ? Src.getBitFieldAddress() : Src.getAddress(),
968 FirstField = nullptr;
972 CodeGenFunction &CGF;
973 const CXXRecordDecl *ClassDecl;
976 void emitMemcpyIR(Address DestPtr, Address SrcPtr, CharUnits Size) {
977 llvm::PointerType *DPT = DestPtr.getType();
979 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), DPT->getAddressSpace());
980 DestPtr = CGF.Builder.CreateBitCast(DestPtr, DBP);
982 llvm::PointerType *SPT = SrcPtr.getType();
984 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), SPT->getAddressSpace());
985 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, SBP);
987 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity());
990 void addInitialField(FieldDecl *F) {
993 FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex());
994 LastFieldOffset = FirstFieldOffset;
995 LastAddedFieldIndex = F->getFieldIndex();
998 void addNextField(FieldDecl *F) {
999 // For the most part, the following invariant will hold:
1000 // F->getFieldIndex() == LastAddedFieldIndex + 1
1001 // The one exception is that Sema won't add a copy-initializer for an
1002 // unnamed bitfield, which will show up here as a gap in the sequence.
1003 assert(F->getFieldIndex() >= LastAddedFieldIndex + 1 &&
1004 "Cannot aggregate fields out of order.");
1005 LastAddedFieldIndex = F->getFieldIndex();
1007 // The 'first' and 'last' fields are chosen by offset, rather than field
1008 // index. This allows the code to support bitfields, as well as regular
1010 uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex());
1011 if (FOffset < FirstFieldOffset) {
1013 FirstFieldOffset = FOffset;
1014 } else if (FOffset >= LastFieldOffset) {
1016 LastFieldOffset = FOffset;
1020 const VarDecl *SrcRec;
1021 const ASTRecordLayout &RecLayout;
1022 FieldDecl *FirstField;
1023 FieldDecl *LastField;
1024 uint64_t FirstFieldOffset, LastFieldOffset;
1025 unsigned LastAddedFieldIndex;
1028 class ConstructorMemcpyizer : public FieldMemcpyizer {
1030 /// Get source argument for copy constructor. Returns null if not a copy
1032 static const VarDecl *getTrivialCopySource(CodeGenFunction &CGF,
1033 const CXXConstructorDecl *CD,
1034 FunctionArgList &Args) {
1035 if (CD->isCopyOrMoveConstructor() && CD->isDefaulted())
1036 return Args[CGF.CGM.getCXXABI().getSrcArgforCopyCtor(CD, Args)];
1040 // Returns true if a CXXCtorInitializer represents a member initialization
1041 // that can be rolled into a memcpy.
1042 bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const {
1043 if (!MemcpyableCtor)
1045 FieldDecl *Field = MemberInit->getMember();
1046 assert(Field && "No field for member init.");
1047 QualType FieldType = Field->getType();
1048 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
1050 // Bail out on non-memcpyable, not-trivially-copyable members.
1051 if (!(CE && isMemcpyEquivalentSpecialMember(CE->getConstructor())) &&
1052 !(FieldType.isTriviallyCopyableType(CGF.getContext()) ||
1053 FieldType->isReferenceType()))
1056 // Bail out on volatile fields.
1057 if (!isMemcpyableField(Field))
1060 // Otherwise we're good.
1065 ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD,
1066 FunctionArgList &Args)
1067 : FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CGF, CD, Args)),
1068 ConstructorDecl(CD),
1069 MemcpyableCtor(CD->isDefaulted() &&
1070 CD->isCopyOrMoveConstructor() &&
1071 CGF.getLangOpts().getGC() == LangOptions::NonGC),
1074 void addMemberInitializer(CXXCtorInitializer *MemberInit) {
1075 if (isMemberInitMemcpyable(MemberInit)) {
1076 AggregatedInits.push_back(MemberInit);
1077 addMemcpyableField(MemberInit->getMember());
1079 emitAggregatedInits();
1080 EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit,
1081 ConstructorDecl, Args);
1085 void emitAggregatedInits() {
1086 if (AggregatedInits.size() <= 1) {
1087 // This memcpy is too small to be worthwhile. Fall back on default
1089 if (!AggregatedInits.empty()) {
1090 CopyingValueRepresentation CVR(CGF);
1091 EmitMemberInitializer(CGF, ConstructorDecl->getParent(),
1092 AggregatedInits[0], ConstructorDecl, Args);
1093 AggregatedInits.clear();
1099 pushEHDestructors();
1101 AggregatedInits.clear();
1104 void pushEHDestructors() {
1105 Address ThisPtr = CGF.LoadCXXThisAddress();
1106 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
1107 LValue LHS = CGF.MakeAddrLValue(ThisPtr, RecordTy);
1109 for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
1110 CXXCtorInitializer *MemberInit = AggregatedInits[i];
1111 QualType FieldType = MemberInit->getAnyMember()->getType();
1112 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
1113 if (!CGF.needsEHCleanup(dtorKind))
1115 LValue FieldLHS = LHS;
1116 EmitLValueForAnyFieldInitialization(CGF, MemberInit, FieldLHS);
1117 CGF.pushEHDestroy(dtorKind, FieldLHS.getAddress(), FieldType);
1122 emitAggregatedInits();
1126 const CXXConstructorDecl *ConstructorDecl;
1127 bool MemcpyableCtor;
1128 FunctionArgList &Args;
1129 SmallVector<CXXCtorInitializer*, 16> AggregatedInits;
1132 class AssignmentMemcpyizer : public FieldMemcpyizer {
1134 // Returns the memcpyable field copied by the given statement, if one
1135 // exists. Otherwise returns null.
1136 FieldDecl *getMemcpyableField(Stmt *S) {
1137 if (!AssignmentsMemcpyable)
1139 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
1140 // Recognise trivial assignments.
1141 if (BO->getOpcode() != BO_Assign)
1143 MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS());
1146 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1147 if (!Field || !isMemcpyableField(Field))
1149 Stmt *RHS = BO->getRHS();
1150 if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS))
1151 RHS = EC->getSubExpr();
1154 if (MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS)) {
1155 if (ME2->getMemberDecl() == Field)
1159 } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) {
1160 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl());
1161 if (!(MD && isMemcpyEquivalentSpecialMember(MD)))
1163 MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument());
1166 FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl());
1167 if (!Field || !isMemcpyableField(Field))
1169 MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0));
1170 if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl()))
1173 } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1174 FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1175 if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy)
1177 Expr *DstPtr = CE->getArg(0);
1178 if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr))
1179 DstPtr = DC->getSubExpr();
1180 UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr);
1181 if (!DUO || DUO->getOpcode() != UO_AddrOf)
1183 MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr());
1186 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1187 if (!Field || !isMemcpyableField(Field))
1189 Expr *SrcPtr = CE->getArg(1);
1190 if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr))
1191 SrcPtr = SC->getSubExpr();
1192 UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr);
1193 if (!SUO || SUO->getOpcode() != UO_AddrOf)
1195 MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr());
1196 if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl()))
1204 bool AssignmentsMemcpyable;
1205 SmallVector<Stmt*, 16> AggregatedStmts;
1208 AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD,
1209 FunctionArgList &Args)
1210 : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]),
1211 AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) {
1212 assert(Args.size() == 2);
1215 void emitAssignment(Stmt *S) {
1216 FieldDecl *F = getMemcpyableField(S);
1218 addMemcpyableField(F);
1219 AggregatedStmts.push_back(S);
1221 emitAggregatedStmts();
1226 void emitAggregatedStmts() {
1227 if (AggregatedStmts.size() <= 1) {
1228 if (!AggregatedStmts.empty()) {
1229 CopyingValueRepresentation CVR(CGF);
1230 CGF.EmitStmt(AggregatedStmts[0]);
1236 AggregatedStmts.clear();
1240 emitAggregatedStmts();
1243 } // end anonymous namespace
1245 static bool isInitializerOfDynamicClass(const CXXCtorInitializer *BaseInit) {
1246 const Type *BaseType = BaseInit->getBaseClass();
1247 const auto *BaseClassDecl =
1248 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
1249 return BaseClassDecl->isDynamicClass();
1252 /// EmitCtorPrologue - This routine generates necessary code to initialize
1253 /// base classes and non-static data members belonging to this constructor.
1254 void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
1255 CXXCtorType CtorType,
1256 FunctionArgList &Args) {
1257 if (CD->isDelegatingConstructor())
1258 return EmitDelegatingCXXConstructorCall(CD, Args);
1260 const CXXRecordDecl *ClassDecl = CD->getParent();
1262 CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
1265 // Virtual base initializers first, if any. They aren't needed if:
1266 // - This is a base ctor variant
1267 // - There are no vbases
1268 // - The class is abstract, so a complete object of it cannot be constructed
1270 // The check for an abstract class is necessary because sema may not have
1271 // marked virtual base destructors referenced.
1272 bool ConstructVBases = CtorType != Ctor_Base &&
1273 ClassDecl->getNumVBases() != 0 &&
1274 !ClassDecl->isAbstract();
1276 // In the Microsoft C++ ABI, there are no constructor variants. Instead, the
1277 // constructor of a class with virtual bases takes an additional parameter to
1278 // conditionally construct the virtual bases. Emit that check here.
1279 llvm::BasicBlock *BaseCtorContinueBB = nullptr;
1280 if (ConstructVBases &&
1281 !CGM.getTarget().getCXXABI().hasConstructorVariants()) {
1282 BaseCtorContinueBB =
1283 CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this, ClassDecl);
1284 assert(BaseCtorContinueBB);
1287 llvm::Value *const OldThis = CXXThisValue;
1288 for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
1289 if (!ConstructVBases)
1291 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1292 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1293 isInitializerOfDynamicClass(*B))
1294 CXXThisValue = Builder.CreateLaunderInvariantGroup(LoadCXXThis());
1295 EmitBaseInitializer(*this, ClassDecl, *B);
1298 if (BaseCtorContinueBB) {
1299 // Complete object handler should continue to the remaining initializers.
1300 Builder.CreateBr(BaseCtorContinueBB);
1301 EmitBlock(BaseCtorContinueBB);
1304 // Then, non-virtual base initializers.
1305 for (; B != E && (*B)->isBaseInitializer(); B++) {
1306 assert(!(*B)->isBaseVirtual());
1308 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1309 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1310 isInitializerOfDynamicClass(*B))
1311 CXXThisValue = Builder.CreateLaunderInvariantGroup(LoadCXXThis());
1312 EmitBaseInitializer(*this, ClassDecl, *B);
1315 CXXThisValue = OldThis;
1317 InitializeVTablePointers(ClassDecl);
1319 // And finally, initialize class members.
1320 FieldConstructionScope FCS(*this, LoadCXXThisAddress());
1321 ConstructorMemcpyizer CM(*this, CD, Args);
1322 for (; B != E; B++) {
1323 CXXCtorInitializer *Member = (*B);
1324 assert(!Member->isBaseInitializer());
1325 assert(Member->isAnyMemberInitializer() &&
1326 "Delegating initializer on non-delegating constructor");
1327 CM.addMemberInitializer(Member);
1333 FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
1336 HasTrivialDestructorBody(ASTContext &Context,
1337 const CXXRecordDecl *BaseClassDecl,
1338 const CXXRecordDecl *MostDerivedClassDecl)
1340 // If the destructor is trivial we don't have to check anything else.
1341 if (BaseClassDecl->hasTrivialDestructor())
1344 if (!BaseClassDecl->getDestructor()->hasTrivialBody())
1348 for (const auto *Field : BaseClassDecl->fields())
1349 if (!FieldHasTrivialDestructorBody(Context, Field))
1352 // Check non-virtual bases.
1353 for (const auto &I : BaseClassDecl->bases()) {
1357 const CXXRecordDecl *NonVirtualBase =
1358 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
1359 if (!HasTrivialDestructorBody(Context, NonVirtualBase,
1360 MostDerivedClassDecl))
1364 if (BaseClassDecl == MostDerivedClassDecl) {
1365 // Check virtual bases.
1366 for (const auto &I : BaseClassDecl->vbases()) {
1367 const CXXRecordDecl *VirtualBase =
1368 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
1369 if (!HasTrivialDestructorBody(Context, VirtualBase,
1370 MostDerivedClassDecl))
1379 FieldHasTrivialDestructorBody(ASTContext &Context,
1380 const FieldDecl *Field)
1382 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
1384 const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
1388 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1390 // The destructor for an implicit anonymous union member is never invoked.
1391 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
1394 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
1397 /// CanSkipVTablePointerInitialization - Check whether we need to initialize
1398 /// any vtable pointers before calling this destructor.
1399 static bool CanSkipVTablePointerInitialization(CodeGenFunction &CGF,
1400 const CXXDestructorDecl *Dtor) {
1401 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1402 if (!ClassDecl->isDynamicClass())
1405 if (!Dtor->hasTrivialBody())
1408 // Check the fields.
1409 for (const auto *Field : ClassDecl->fields())
1410 if (!FieldHasTrivialDestructorBody(CGF.getContext(), Field))
1416 /// EmitDestructorBody - Emits the body of the current destructor.
1417 void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
1418 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
1419 CXXDtorType DtorType = CurGD.getDtorType();
1421 // For an abstract class, non-base destructors are never used (and can't
1422 // be emitted in general, because vbase dtors may not have been validated
1423 // by Sema), but the Itanium ABI doesn't make them optional and Clang may
1424 // in fact emit references to them from other compilations, so emit them
1425 // as functions containing a trap instruction.
1426 if (DtorType != Dtor_Base && Dtor->getParent()->isAbstract()) {
1427 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
1428 TrapCall->setDoesNotReturn();
1429 TrapCall->setDoesNotThrow();
1430 Builder.CreateUnreachable();
1431 Builder.ClearInsertionPoint();
1435 Stmt *Body = Dtor->getBody();
1437 incrementProfileCounter(Body);
1439 // The call to operator delete in a deleting destructor happens
1440 // outside of the function-try-block, which means it's always
1441 // possible to delegate the destructor body to the complete
1442 // destructor. Do so.
1443 if (DtorType == Dtor_Deleting) {
1444 RunCleanupsScope DtorEpilogue(*this);
1445 EnterDtorCleanups(Dtor, Dtor_Deleting);
1446 if (HaveInsertPoint()) {
1447 QualType ThisTy = Dtor->getThisObjectType();
1448 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
1449 /*Delegating=*/false, LoadCXXThisAddress(), ThisTy);
1454 // If the body is a function-try-block, enter the try before
1456 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
1458 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
1459 EmitAsanPrologueOrEpilogue(false);
1461 // Enter the epilogue cleanups.
1462 RunCleanupsScope DtorEpilogue(*this);
1464 // If this is the complete variant, just invoke the base variant;
1465 // the epilogue will destruct the virtual bases. But we can't do
1466 // this optimization if the body is a function-try-block, because
1467 // we'd introduce *two* handler blocks. In the Microsoft ABI, we
1468 // always delegate because we might not have a definition in this TU.
1470 case Dtor_Comdat: llvm_unreachable("not expecting a COMDAT");
1471 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
1474 assert((Body || getTarget().getCXXABI().isMicrosoft()) &&
1475 "can't emit a dtor without a body for non-Microsoft ABIs");
1477 // Enter the cleanup scopes for virtual bases.
1478 EnterDtorCleanups(Dtor, Dtor_Complete);
1481 QualType ThisTy = Dtor->getThisObjectType();
1482 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
1483 /*Delegating=*/false, LoadCXXThisAddress(), ThisTy);
1487 // Fallthrough: act like we're in the base variant.
1493 // Enter the cleanup scopes for fields and non-virtual bases.
1494 EnterDtorCleanups(Dtor, Dtor_Base);
1496 // Initialize the vtable pointers before entering the body.
1497 if (!CanSkipVTablePointerInitialization(*this, Dtor)) {
1498 // Insert the llvm.launder.invariant.group intrinsic before initializing
1499 // the vptrs to cancel any previous assumptions we might have made.
1500 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1501 CGM.getCodeGenOpts().OptimizationLevel > 0)
1502 CXXThisValue = Builder.CreateLaunderInvariantGroup(LoadCXXThis());
1503 InitializeVTablePointers(Dtor->getParent());
1507 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
1511 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
1512 // nothing to do besides what's in the epilogue
1514 // -fapple-kext must inline any call to this dtor into
1515 // the caller's body.
1516 if (getLangOpts().AppleKext)
1517 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
1522 // Jump out through the epilogue cleanups.
1523 DtorEpilogue.ForceCleanup();
1525 // Exit the try if applicable.
1527 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
1530 void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) {
1531 const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
1532 const Stmt *RootS = AssignOp->getBody();
1533 assert(isa<CompoundStmt>(RootS) &&
1534 "Body of an implicit assignment operator should be compound stmt.");
1535 const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
1537 LexicalScope Scope(*this, RootCS->getSourceRange());
1539 incrementProfileCounter(RootCS);
1540 AssignmentMemcpyizer AM(*this, AssignOp, Args);
1541 for (auto *I : RootCS->body())
1542 AM.emitAssignment(I);
1547 llvm::Value *LoadThisForDtorDelete(CodeGenFunction &CGF,
1548 const CXXDestructorDecl *DD) {
1549 if (Expr *ThisArg = DD->getOperatorDeleteThisArg())
1550 return CGF.EmitScalarExpr(ThisArg);
1551 return CGF.LoadCXXThis();
1554 /// Call the operator delete associated with the current destructor.
1555 struct CallDtorDelete final : EHScopeStack::Cleanup {
1558 void Emit(CodeGenFunction &CGF, Flags flags) override {
1559 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1560 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1561 CGF.EmitDeleteCall(Dtor->getOperatorDelete(),
1562 LoadThisForDtorDelete(CGF, Dtor),
1563 CGF.getContext().getTagDeclType(ClassDecl));
1567 void EmitConditionalDtorDeleteCall(CodeGenFunction &CGF,
1568 llvm::Value *ShouldDeleteCondition,
1569 bool ReturnAfterDelete) {
1570 llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
1571 llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
1572 llvm::Value *ShouldCallDelete
1573 = CGF.Builder.CreateIsNull(ShouldDeleteCondition);
1574 CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
1576 CGF.EmitBlock(callDeleteBB);
1577 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1578 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1579 CGF.EmitDeleteCall(Dtor->getOperatorDelete(),
1580 LoadThisForDtorDelete(CGF, Dtor),
1581 CGF.getContext().getTagDeclType(ClassDecl));
1582 assert(Dtor->getOperatorDelete()->isDestroyingOperatorDelete() ==
1583 ReturnAfterDelete &&
1584 "unexpected value for ReturnAfterDelete");
1585 if (ReturnAfterDelete)
1586 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
1588 CGF.Builder.CreateBr(continueBB);
1590 CGF.EmitBlock(continueBB);
1593 struct CallDtorDeleteConditional final : EHScopeStack::Cleanup {
1594 llvm::Value *ShouldDeleteCondition;
1597 CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
1598 : ShouldDeleteCondition(ShouldDeleteCondition) {
1599 assert(ShouldDeleteCondition != nullptr);
1602 void Emit(CodeGenFunction &CGF, Flags flags) override {
1603 EmitConditionalDtorDeleteCall(CGF, ShouldDeleteCondition,
1604 /*ReturnAfterDelete*/false);
1608 class DestroyField final : public EHScopeStack::Cleanup {
1609 const FieldDecl *field;
1610 CodeGenFunction::Destroyer *destroyer;
1611 bool useEHCleanupForArray;
1614 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
1615 bool useEHCleanupForArray)
1616 : field(field), destroyer(destroyer),
1617 useEHCleanupForArray(useEHCleanupForArray) {}
1619 void Emit(CodeGenFunction &CGF, Flags flags) override {
1620 // Find the address of the field.
1621 Address thisValue = CGF.LoadCXXThisAddress();
1622 QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
1623 LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
1624 LValue LV = CGF.EmitLValueForField(ThisLV, field);
1625 assert(LV.isSimple());
1627 CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
1628 flags.isForNormalCleanup() && useEHCleanupForArray);
1632 static void EmitSanitizerDtorCallback(CodeGenFunction &CGF, llvm::Value *Ptr,
1633 CharUnits::QuantityType PoisonSize) {
1634 CodeGenFunction::SanitizerScope SanScope(&CGF);
1635 // Pass in void pointer and size of region as arguments to runtime
1637 llvm::Value *Args[] = {CGF.Builder.CreateBitCast(Ptr, CGF.VoidPtrTy),
1638 llvm::ConstantInt::get(CGF.SizeTy, PoisonSize)};
1640 llvm::Type *ArgTypes[] = {CGF.VoidPtrTy, CGF.SizeTy};
1642 llvm::FunctionType *FnType =
1643 llvm::FunctionType::get(CGF.VoidTy, ArgTypes, false);
1644 llvm::FunctionCallee Fn =
1645 CGF.CGM.CreateRuntimeFunction(FnType, "__sanitizer_dtor_callback");
1646 CGF.EmitNounwindRuntimeCall(Fn, Args);
1649 class SanitizeDtorMembers final : public EHScopeStack::Cleanup {
1650 const CXXDestructorDecl *Dtor;
1653 SanitizeDtorMembers(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
1655 // Generate function call for handling object poisoning.
1656 // Disables tail call elimination, to prevent the current stack frame
1657 // from disappearing from the stack trace.
1658 void Emit(CodeGenFunction &CGF, Flags flags) override {
1659 const ASTRecordLayout &Layout =
1660 CGF.getContext().getASTRecordLayout(Dtor->getParent());
1662 // Nothing to poison.
1663 if (Layout.getFieldCount() == 0)
1666 // Prevent the current stack frame from disappearing from the stack trace.
1667 CGF.CurFn->addFnAttr("disable-tail-calls", "true");
1669 // Construct pointer to region to begin poisoning, and calculate poison
1670 // size, so that only members declared in this class are poisoned.
1671 ASTContext &Context = CGF.getContext();
1672 unsigned fieldIndex = 0;
1673 int startIndex = -1;
1674 // RecordDecl::field_iterator Field;
1675 for (const FieldDecl *Field : Dtor->getParent()->fields()) {
1676 // Poison field if it is trivial
1677 if (FieldHasTrivialDestructorBody(Context, Field)) {
1678 // Start sanitizing at this field
1680 startIndex = fieldIndex;
1682 // Currently on the last field, and it must be poisoned with the
1684 if (fieldIndex == Layout.getFieldCount() - 1) {
1685 PoisonMembers(CGF, startIndex, Layout.getFieldCount());
1687 } else if (startIndex >= 0) {
1688 // No longer within a block of memory to poison, so poison the block
1689 PoisonMembers(CGF, startIndex, fieldIndex);
1690 // Re-set the start index
1698 /// \param layoutStartOffset index of the ASTRecordLayout field to
1699 /// start poisoning (inclusive)
1700 /// \param layoutEndOffset index of the ASTRecordLayout field to
1701 /// end poisoning (exclusive)
1702 void PoisonMembers(CodeGenFunction &CGF, unsigned layoutStartOffset,
1703 unsigned layoutEndOffset) {
1704 ASTContext &Context = CGF.getContext();
1705 const ASTRecordLayout &Layout =
1706 Context.getASTRecordLayout(Dtor->getParent());
1708 llvm::ConstantInt *OffsetSizePtr = llvm::ConstantInt::get(
1710 Context.toCharUnitsFromBits(Layout.getFieldOffset(layoutStartOffset))
1713 llvm::Value *OffsetPtr = CGF.Builder.CreateGEP(
1714 CGF.Builder.CreateBitCast(CGF.LoadCXXThis(), CGF.Int8PtrTy),
1717 CharUnits::QuantityType PoisonSize;
1718 if (layoutEndOffset >= Layout.getFieldCount()) {
1719 PoisonSize = Layout.getNonVirtualSize().getQuantity() -
1720 Context.toCharUnitsFromBits(
1721 Layout.getFieldOffset(layoutStartOffset))
1724 PoisonSize = Context.toCharUnitsFromBits(
1725 Layout.getFieldOffset(layoutEndOffset) -
1726 Layout.getFieldOffset(layoutStartOffset))
1730 if (PoisonSize == 0)
1733 EmitSanitizerDtorCallback(CGF, OffsetPtr, PoisonSize);
1737 class SanitizeDtorVTable final : public EHScopeStack::Cleanup {
1738 const CXXDestructorDecl *Dtor;
1741 SanitizeDtorVTable(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
1743 // Generate function call for handling vtable pointer poisoning.
1744 void Emit(CodeGenFunction &CGF, Flags flags) override {
1745 assert(Dtor->getParent()->isDynamicClass());
1747 ASTContext &Context = CGF.getContext();
1748 // Poison vtable and vtable ptr if they exist for this class.
1749 llvm::Value *VTablePtr = CGF.LoadCXXThis();
1751 CharUnits::QuantityType PoisonSize =
1752 Context.toCharUnitsFromBits(CGF.PointerWidthInBits).getQuantity();
1753 // Pass in void pointer and size of region as arguments to runtime
1755 EmitSanitizerDtorCallback(CGF, VTablePtr, PoisonSize);
1758 } // end anonymous namespace
1760 /// Emit all code that comes at the end of class's
1761 /// destructor. This is to call destructors on members and base classes
1762 /// in reverse order of their construction.
1764 /// For a deleting destructor, this also handles the case where a destroying
1765 /// operator delete completely overrides the definition.
1766 void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
1767 CXXDtorType DtorType) {
1768 assert((!DD->isTrivial() || DD->hasAttr<DLLExportAttr>()) &&
1769 "Should not emit dtor epilogue for non-exported trivial dtor!");
1771 // The deleting-destructor phase just needs to call the appropriate
1772 // operator delete that Sema picked up.
1773 if (DtorType == Dtor_Deleting) {
1774 assert(DD->getOperatorDelete() &&
1775 "operator delete missing - EnterDtorCleanups");
1776 if (CXXStructorImplicitParamValue) {
1777 // If there is an implicit param to the deleting dtor, it's a boolean
1778 // telling whether this is a deleting destructor.
1779 if (DD->getOperatorDelete()->isDestroyingOperatorDelete())
1780 EmitConditionalDtorDeleteCall(*this, CXXStructorImplicitParamValue,
1781 /*ReturnAfterDelete*/true);
1783 EHStack.pushCleanup<CallDtorDeleteConditional>(
1784 NormalAndEHCleanup, CXXStructorImplicitParamValue);
1786 if (DD->getOperatorDelete()->isDestroyingOperatorDelete()) {
1787 const CXXRecordDecl *ClassDecl = DD->getParent();
1788 EmitDeleteCall(DD->getOperatorDelete(),
1789 LoadThisForDtorDelete(*this, DD),
1790 getContext().getTagDeclType(ClassDecl));
1791 EmitBranchThroughCleanup(ReturnBlock);
1793 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
1799 const CXXRecordDecl *ClassDecl = DD->getParent();
1801 // Unions have no bases and do not call field destructors.
1802 if (ClassDecl->isUnion())
1805 // The complete-destructor phase just destructs all the virtual bases.
1806 if (DtorType == Dtor_Complete) {
1807 // Poison the vtable pointer such that access after the base
1808 // and member destructors are invoked is invalid.
1809 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1810 SanOpts.has(SanitizerKind::Memory) && ClassDecl->getNumVBases() &&
1811 ClassDecl->isPolymorphic())
1812 EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
1814 // We push them in the forward order so that they'll be popped in
1815 // the reverse order.
1816 for (const auto &Base : ClassDecl->vbases()) {
1817 CXXRecordDecl *BaseClassDecl
1818 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1820 // Ignore trivial destructors.
1821 if (BaseClassDecl->hasTrivialDestructor())
1824 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1826 /*BaseIsVirtual*/ true);
1832 assert(DtorType == Dtor_Base);
1833 // Poison the vtable pointer if it has no virtual bases, but inherits
1834 // virtual functions.
1835 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1836 SanOpts.has(SanitizerKind::Memory) && !ClassDecl->getNumVBases() &&
1837 ClassDecl->isPolymorphic())
1838 EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
1840 // Destroy non-virtual bases.
1841 for (const auto &Base : ClassDecl->bases()) {
1842 // Ignore virtual bases.
1843 if (Base.isVirtual())
1846 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
1848 // Ignore trivial destructors.
1849 if (BaseClassDecl->hasTrivialDestructor())
1852 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1854 /*BaseIsVirtual*/ false);
1857 // Poison fields such that access after their destructors are
1858 // invoked, and before the base class destructor runs, is invalid.
1859 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1860 SanOpts.has(SanitizerKind::Memory))
1861 EHStack.pushCleanup<SanitizeDtorMembers>(NormalAndEHCleanup, DD);
1863 // Destroy direct fields.
1864 for (const auto *Field : ClassDecl->fields()) {
1865 QualType type = Field->getType();
1866 QualType::DestructionKind dtorKind = type.isDestructedType();
1867 if (!dtorKind) continue;
1869 // Anonymous union members do not have their destructors called.
1870 const RecordType *RT = type->getAsUnionType();
1871 if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
1873 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1874 EHStack.pushCleanup<DestroyField>(cleanupKind, Field,
1875 getDestroyer(dtorKind),
1876 cleanupKind & EHCleanup);
1880 /// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1881 /// constructor for each of several members of an array.
1883 /// \param ctor the constructor to call for each element
1884 /// \param arrayType the type of the array to initialize
1885 /// \param arrayBegin an arrayType*
1886 /// \param zeroInitialize true if each element should be
1887 /// zero-initialized before it is constructed
1888 void CodeGenFunction::EmitCXXAggrConstructorCall(
1889 const CXXConstructorDecl *ctor, const ArrayType *arrayType,
1890 Address arrayBegin, const CXXConstructExpr *E, bool NewPointerIsChecked,
1891 bool zeroInitialize) {
1892 QualType elementType;
1893 llvm::Value *numElements =
1894 emitArrayLength(arrayType, elementType, arrayBegin);
1896 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin, E,
1897 NewPointerIsChecked, zeroInitialize);
1900 /// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1901 /// constructor for each of several members of an array.
1903 /// \param ctor the constructor to call for each element
1904 /// \param numElements the number of elements in the array;
1906 /// \param arrayBase a T*, where T is the type constructed by ctor
1907 /// \param zeroInitialize true if each element should be
1908 /// zero-initialized before it is constructed
1909 void CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1910 llvm::Value *numElements,
1912 const CXXConstructExpr *E,
1913 bool NewPointerIsChecked,
1914 bool zeroInitialize) {
1915 // It's legal for numElements to be zero. This can happen both
1916 // dynamically, because x can be zero in 'new A[x]', and statically,
1917 // because of GCC extensions that permit zero-length arrays. There
1918 // are probably legitimate places where we could assume that this
1919 // doesn't happen, but it's not clear that it's worth it.
1920 llvm::BranchInst *zeroCheckBranch = nullptr;
1922 // Optimize for a constant count.
1923 llvm::ConstantInt *constantCount
1924 = dyn_cast<llvm::ConstantInt>(numElements);
1925 if (constantCount) {
1926 // Just skip out if the constant count is zero.
1927 if (constantCount->isZero()) return;
1929 // Otherwise, emit the check.
1931 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1932 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1933 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1937 // Find the end of the array.
1938 llvm::Value *arrayBegin = arrayBase.getPointer();
1939 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1942 // Enter the loop, setting up a phi for the current location to initialize.
1943 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1944 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1946 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1948 cur->addIncoming(arrayBegin, entryBB);
1950 // Inside the loop body, emit the constructor call on the array element.
1952 // The alignment of the base, adjusted by the size of a single element,
1953 // provides a conservative estimate of the alignment of every element.
1954 // (This assumes we never start tracking offsetted alignments.)
1956 // Note that these are complete objects and so we don't need to
1957 // use the non-virtual size or alignment.
1958 QualType type = getContext().getTypeDeclType(ctor->getParent());
1959 CharUnits eltAlignment =
1960 arrayBase.getAlignment()
1961 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
1962 Address curAddr = Address(cur, eltAlignment);
1964 // Zero initialize the storage, if requested.
1966 EmitNullInitialization(curAddr, type);
1968 // C++ [class.temporary]p4:
1969 // There are two contexts in which temporaries are destroyed at a different
1970 // point than the end of the full-expression. The first context is when a
1971 // default constructor is called to initialize an element of an array.
1972 // If the constructor has one or more default arguments, the destruction of
1973 // every temporary created in a default argument expression is sequenced
1974 // before the construction of the next array element, if any.
1977 RunCleanupsScope Scope(*this);
1979 // Evaluate the constructor and its arguments in a regular
1980 // partial-destroy cleanup.
1981 if (getLangOpts().Exceptions &&
1982 !ctor->getParent()->hasTrivialDestructor()) {
1983 Destroyer *destroyer = destroyCXXObject;
1984 pushRegularPartialArrayCleanup(arrayBegin, cur, type, eltAlignment,
1987 auto currAVS = AggValueSlot::forAddr(
1988 curAddr, type.getQualifiers(), AggValueSlot::IsDestructed,
1989 AggValueSlot::DoesNotNeedGCBarriers, AggValueSlot::IsNotAliased,
1990 AggValueSlot::DoesNotOverlap, AggValueSlot::IsNotZeroed,
1991 NewPointerIsChecked ? AggValueSlot::IsSanitizerChecked
1992 : AggValueSlot::IsNotSanitizerChecked);
1993 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/false,
1994 /*Delegating=*/false, currAVS, E);
1997 // Go to the next element.
1999 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
2001 cur->addIncoming(next, Builder.GetInsertBlock());
2003 // Check whether that's the end of the loop.
2004 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
2005 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
2006 Builder.CreateCondBr(done, contBB, loopBB);
2008 // Patch the earlier check to skip over the loop.
2009 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
2014 void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
2017 const RecordType *rtype = type->castAs<RecordType>();
2018 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
2019 const CXXDestructorDecl *dtor = record->getDestructor();
2020 assert(!dtor->isTrivial());
2021 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
2022 /*Delegating=*/false, addr, type);
2025 void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
2027 bool ForVirtualBase,
2029 AggValueSlot ThisAVS,
2030 const CXXConstructExpr *E) {
2032 Address This = ThisAVS.getAddress();
2033 LangAS SlotAS = ThisAVS.getQualifiers().getAddressSpace();
2034 QualType ThisType = D->getThisType();
2035 LangAS ThisAS = ThisType.getTypePtr()->getPointeeType().getAddressSpace();
2036 llvm::Value *ThisPtr = This.getPointer();
2038 if (SlotAS != ThisAS) {
2039 unsigned TargetThisAS = getContext().getTargetAddressSpace(ThisAS);
2040 llvm::Type *NewType =
2041 ThisPtr->getType()->getPointerElementType()->getPointerTo(TargetThisAS);
2042 ThisPtr = getTargetHooks().performAddrSpaceCast(*this, This.getPointer(),
2043 ThisAS, SlotAS, NewType);
2046 // Push the this ptr.
2047 Args.add(RValue::get(ThisPtr), D->getThisType());
2049 // If this is a trivial constructor, emit a memcpy now before we lose
2050 // the alignment information on the argument.
2051 // FIXME: It would be better to preserve alignment information into CallArg.
2052 if (isMemcpyEquivalentSpecialMember(D)) {
2053 assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
2055 const Expr *Arg = E->getArg(0);
2056 LValue Src = EmitLValue(Arg);
2057 QualType DestTy = getContext().getTypeDeclType(D->getParent());
2058 LValue Dest = MakeAddrLValue(This, DestTy);
2059 EmitAggregateCopyCtor(Dest, Src, ThisAVS.mayOverlap());
2063 // Add the rest of the user-supplied arguments.
2064 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
2065 EvaluationOrder Order = E->isListInitialization()
2066 ? EvaluationOrder::ForceLeftToRight
2067 : EvaluationOrder::Default;
2068 EmitCallArgs(Args, FPT, E->arguments(), E->getConstructor(),
2069 /*ParamsToSkip*/ 0, Order);
2071 EmitCXXConstructorCall(D, Type, ForVirtualBase, Delegating, This, Args,
2072 ThisAVS.mayOverlap(), E->getExprLoc(),
2073 ThisAVS.isSanitizerChecked());
2076 static bool canEmitDelegateCallArgs(CodeGenFunction &CGF,
2077 const CXXConstructorDecl *Ctor,
2078 CXXCtorType Type, CallArgList &Args) {
2079 // We can't forward a variadic call.
2080 if (Ctor->isVariadic())
2083 if (CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2084 // If the parameters are callee-cleanup, it's not safe to forward.
2085 for (auto *P : Ctor->parameters())
2086 if (P->getType().isDestructedType())
2089 // Likewise if they're inalloca.
2090 const CGFunctionInfo &Info =
2091 CGF.CGM.getTypes().arrangeCXXConstructorCall(Args, Ctor, Type, 0, 0);
2092 if (Info.usesInAlloca())
2096 // Anything else should be OK.
2100 void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
2102 bool ForVirtualBase,
2106 AggValueSlot::Overlap_t Overlap,
2108 bool NewPointerIsChecked) {
2109 const CXXRecordDecl *ClassDecl = D->getParent();
2111 if (!NewPointerIsChecked)
2112 EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall, Loc, This.getPointer(),
2113 getContext().getRecordType(ClassDecl), CharUnits::Zero());
2115 if (D->isTrivial() && D->isDefaultConstructor()) {
2116 assert(Args.size() == 1 && "trivial default ctor with args");
2120 // If this is a trivial constructor, just emit what's needed. If this is a
2121 // union copy constructor, we must emit a memcpy, because the AST does not
2123 if (isMemcpyEquivalentSpecialMember(D)) {
2124 assert(Args.size() == 2 && "unexpected argcount for trivial ctor");
2126 QualType SrcTy = D->getParamDecl(0)->getType().getNonReferenceType();
2127 Address Src(Args[1].getRValue(*this).getScalarVal(),
2128 getNaturalTypeAlignment(SrcTy));
2129 LValue SrcLVal = MakeAddrLValue(Src, SrcTy);
2130 QualType DestTy = getContext().getTypeDeclType(ClassDecl);
2131 LValue DestLVal = MakeAddrLValue(This, DestTy);
2132 EmitAggregateCopyCtor(DestLVal, SrcLVal, Overlap);
2136 bool PassPrototypeArgs = true;
2137 // Check whether we can actually emit the constructor before trying to do so.
2138 if (auto Inherited = D->getInheritedConstructor()) {
2139 PassPrototypeArgs = getTypes().inheritingCtorHasParams(Inherited, Type);
2140 if (PassPrototypeArgs && !canEmitDelegateCallArgs(*this, D, Type, Args)) {
2141 EmitInlinedInheritingCXXConstructorCall(D, Type, ForVirtualBase,
2147 // Insert any ABI-specific implicit constructor arguments.
2148 CGCXXABI::AddedStructorArgs ExtraArgs =
2149 CGM.getCXXABI().addImplicitConstructorArgs(*this, D, Type, ForVirtualBase,
2153 llvm::Constant *CalleePtr = CGM.getAddrOfCXXStructor(GlobalDecl(D, Type));
2154 const CGFunctionInfo &Info = CGM.getTypes().arrangeCXXConstructorCall(
2155 Args, D, Type, ExtraArgs.Prefix, ExtraArgs.Suffix, PassPrototypeArgs);
2156 CGCallee Callee = CGCallee::forDirect(CalleePtr, GlobalDecl(D, Type));
2157 EmitCall(Info, Callee, ReturnValueSlot(), Args);
2159 // Generate vtable assumptions if we're constructing a complete object
2160 // with a vtable. We don't do this for base subobjects for two reasons:
2161 // first, it's incorrect for classes with virtual bases, and second, we're
2162 // about to overwrite the vptrs anyway.
2163 // We also have to make sure if we can refer to vtable:
2164 // - Otherwise we can refer to vtable if it's safe to speculatively emit.
2165 // FIXME: If vtable is used by ctor/dtor, or if vtable is external and we are
2166 // sure that definition of vtable is not hidden,
2167 // then we are always safe to refer to it.
2168 // FIXME: It looks like InstCombine is very inefficient on dealing with
2169 // assumes. Make assumption loads require -fstrict-vtable-pointers temporarily.
2170 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2171 ClassDecl->isDynamicClass() && Type != Ctor_Base &&
2172 CGM.getCXXABI().canSpeculativelyEmitVTable(ClassDecl) &&
2173 CGM.getCodeGenOpts().StrictVTablePointers)
2174 EmitVTableAssumptionLoads(ClassDecl, This);
2177 void CodeGenFunction::EmitInheritedCXXConstructorCall(
2178 const CXXConstructorDecl *D, bool ForVirtualBase, Address This,
2179 bool InheritedFromVBase, const CXXInheritedCtorInitExpr *E) {
2181 CallArg ThisArg(RValue::get(This.getPointer()), D->getThisType());
2183 // Forward the parameters.
2184 if (InheritedFromVBase &&
2185 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
2186 // Nothing to do; this construction is not responsible for constructing
2187 // the base class containing the inherited constructor.
2188 // FIXME: Can we just pass undef's for the remaining arguments if we don't
2189 // have constructor variants?
2190 Args.push_back(ThisArg);
2191 } else if (!CXXInheritedCtorInitExprArgs.empty()) {
2192 // The inheriting constructor was inlined; just inject its arguments.
2193 assert(CXXInheritedCtorInitExprArgs.size() >= D->getNumParams() &&
2194 "wrong number of parameters for inherited constructor call");
2195 Args = CXXInheritedCtorInitExprArgs;
2198 // The inheriting constructor was not inlined. Emit delegating arguments.
2199 Args.push_back(ThisArg);
2200 const auto *OuterCtor = cast<CXXConstructorDecl>(CurCodeDecl);
2201 assert(OuterCtor->getNumParams() == D->getNumParams());
2202 assert(!OuterCtor->isVariadic() && "should have been inlined");
2204 for (const auto *Param : OuterCtor->parameters()) {
2205 assert(getContext().hasSameUnqualifiedType(
2206 OuterCtor->getParamDecl(Param->getFunctionScopeIndex())->getType(),
2208 EmitDelegateCallArg(Args, Param, E->getLocation());
2210 // Forward __attribute__(pass_object_size).
2211 if (Param->hasAttr<PassObjectSizeAttr>()) {
2212 auto *POSParam = SizeArguments[Param];
2213 assert(POSParam && "missing pass_object_size value for forwarding");
2214 EmitDelegateCallArg(Args, POSParam, E->getLocation());
2219 EmitCXXConstructorCall(D, Ctor_Base, ForVirtualBase, /*Delegating*/false,
2220 This, Args, AggValueSlot::MayOverlap,
2221 E->getLocation(), /*NewPointerIsChecked*/true);
2224 void CodeGenFunction::EmitInlinedInheritingCXXConstructorCall(
2225 const CXXConstructorDecl *Ctor, CXXCtorType CtorType, bool ForVirtualBase,
2226 bool Delegating, CallArgList &Args) {
2227 GlobalDecl GD(Ctor, CtorType);
2228 InlinedInheritingConstructorScope Scope(*this, GD);
2229 ApplyInlineDebugLocation DebugScope(*this, GD);
2230 RunCleanupsScope RunCleanups(*this);
2232 // Save the arguments to be passed to the inherited constructor.
2233 CXXInheritedCtorInitExprArgs = Args;
2235 FunctionArgList Params;
2236 QualType RetType = BuildFunctionArgList(CurGD, Params);
2239 // Insert any ABI-specific implicit constructor arguments.
2240 CGM.getCXXABI().addImplicitConstructorArgs(*this, Ctor, CtorType,
2241 ForVirtualBase, Delegating, Args);
2243 // Emit a simplified prolog. We only need to emit the implicit params.
2244 assert(Args.size() >= Params.size() && "too few arguments for call");
2245 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2246 if (I < Params.size() && isa<ImplicitParamDecl>(Params[I])) {
2247 const RValue &RV = Args[I].getRValue(*this);
2248 assert(!RV.isComplex() && "complex indirect params not supported");
2249 ParamValue Val = RV.isScalar()
2250 ? ParamValue::forDirect(RV.getScalarVal())
2251 : ParamValue::forIndirect(RV.getAggregateAddress());
2252 EmitParmDecl(*Params[I], Val, I + 1);
2256 // Create a return value slot if the ABI implementation wants one.
2257 // FIXME: This is dumb, we should ask the ABI not to try to set the return
2259 if (!RetType->isVoidType())
2260 ReturnValue = CreateIRTemp(RetType, "retval.inhctor");
2262 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
2263 CXXThisValue = CXXABIThisValue;
2265 // Directly emit the constructor initializers.
2266 EmitCtorPrologue(Ctor, CtorType, Params);
2269 void CodeGenFunction::EmitVTableAssumptionLoad(const VPtr &Vptr, Address This) {
2270 llvm::Value *VTableGlobal =
2271 CGM.getCXXABI().getVTableAddressPoint(Vptr.Base, Vptr.VTableClass);
2275 // We can just use the base offset in the complete class.
2276 CharUnits NonVirtualOffset = Vptr.Base.getBaseOffset();
2278 if (!NonVirtualOffset.isZero())
2280 ApplyNonVirtualAndVirtualOffset(*this, This, NonVirtualOffset, nullptr,
2281 Vptr.VTableClass, Vptr.NearestVBase);
2283 llvm::Value *VPtrValue =
2284 GetVTablePtr(This, VTableGlobal->getType(), Vptr.VTableClass);
2286 Builder.CreateICmpEQ(VPtrValue, VTableGlobal, "cmp.vtables");
2287 Builder.CreateAssumption(Cmp);
2290 void CodeGenFunction::EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl,
2292 if (CGM.getCXXABI().doStructorsInitializeVPtrs(ClassDecl))
2293 for (const VPtr &Vptr : getVTablePointers(ClassDecl))
2294 EmitVTableAssumptionLoad(Vptr, This);
2298 CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
2299 Address This, Address Src,
2300 const CXXConstructExpr *E) {
2301 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
2305 // Push the this ptr.
2306 Args.add(RValue::get(This.getPointer()), D->getThisType());
2308 // Push the src ptr.
2309 QualType QT = *(FPT->param_type_begin());
2310 llvm::Type *t = CGM.getTypes().ConvertType(QT);
2311 Src = Builder.CreateBitCast(Src, t);
2312 Args.add(RValue::get(Src.getPointer()), QT);
2314 // Skip over first argument (Src).
2315 EmitCallArgs(Args, FPT, drop_begin(E->arguments(), 1), E->getConstructor(),
2316 /*ParamsToSkip*/ 1);
2318 EmitCXXConstructorCall(D, Ctor_Complete, /*ForVirtualBase*/false,
2319 /*Delegating*/false, This, Args,
2320 AggValueSlot::MayOverlap, E->getExprLoc(),
2321 /*NewPointerIsChecked*/false);
2325 CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
2326 CXXCtorType CtorType,
2327 const FunctionArgList &Args,
2328 SourceLocation Loc) {
2329 CallArgList DelegateArgs;
2331 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
2332 assert(I != E && "no parameters to constructor");
2335 Address This = LoadCXXThisAddress();
2336 DelegateArgs.add(RValue::get(This.getPointer()), (*I)->getType());
2339 // FIXME: The location of the VTT parameter in the parameter list is
2340 // specific to the Itanium ABI and shouldn't be hardcoded here.
2341 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
2342 assert(I != E && "cannot skip vtt parameter, already done with args");
2343 assert((*I)->getType()->isPointerType() &&
2344 "skipping parameter not of vtt type");
2348 // Explicit arguments.
2349 for (; I != E; ++I) {
2350 const VarDecl *param = *I;
2351 // FIXME: per-argument source location
2352 EmitDelegateCallArg(DelegateArgs, param, Loc);
2355 EmitCXXConstructorCall(Ctor, CtorType, /*ForVirtualBase=*/false,
2356 /*Delegating=*/true, This, DelegateArgs,
2357 AggValueSlot::MayOverlap, Loc,
2358 /*NewPointerIsChecked=*/true);
2362 struct CallDelegatingCtorDtor final : EHScopeStack::Cleanup {
2363 const CXXDestructorDecl *Dtor;
2367 CallDelegatingCtorDtor(const CXXDestructorDecl *D, Address Addr,
2369 : Dtor(D), Addr(Addr), Type(Type) {}
2371 void Emit(CodeGenFunction &CGF, Flags flags) override {
2372 // We are calling the destructor from within the constructor.
2373 // Therefore, "this" should have the expected type.
2374 QualType ThisTy = Dtor->getThisObjectType();
2375 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
2376 /*Delegating=*/true, Addr, ThisTy);
2379 } // end anonymous namespace
2382 CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
2383 const FunctionArgList &Args) {
2384 assert(Ctor->isDelegatingConstructor());
2386 Address ThisPtr = LoadCXXThisAddress();
2388 AggValueSlot AggSlot =
2389 AggValueSlot::forAddr(ThisPtr, Qualifiers(),
2390 AggValueSlot::IsDestructed,
2391 AggValueSlot::DoesNotNeedGCBarriers,
2392 AggValueSlot::IsNotAliased,
2393 AggValueSlot::MayOverlap,
2394 AggValueSlot::IsNotZeroed,
2395 // Checks are made by the code that calls constructor.
2396 AggValueSlot::IsSanitizerChecked);
2398 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
2400 const CXXRecordDecl *ClassDecl = Ctor->getParent();
2401 if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
2403 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
2405 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
2406 ClassDecl->getDestructor(),
2411 void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
2413 bool ForVirtualBase,
2414 bool Delegating, Address This,
2416 CGM.getCXXABI().EmitDestructorCall(*this, DD, Type, ForVirtualBase,
2417 Delegating, This, ThisTy);
2421 struct CallLocalDtor final : EHScopeStack::Cleanup {
2422 const CXXDestructorDecl *Dtor;
2426 CallLocalDtor(const CXXDestructorDecl *D, Address Addr, QualType Ty)
2427 : Dtor(D), Addr(Addr), Ty(Ty) {}
2429 void Emit(CodeGenFunction &CGF, Flags flags) override {
2430 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
2431 /*ForVirtualBase=*/false,
2432 /*Delegating=*/false, Addr, Ty);
2435 } // end anonymous namespace
2437 void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
2438 QualType T, Address Addr) {
2439 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr, T);
2442 void CodeGenFunction::PushDestructorCleanup(QualType T, Address Addr) {
2443 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
2444 if (!ClassDecl) return;
2445 if (ClassDecl->hasTrivialDestructor()) return;
2447 const CXXDestructorDecl *D = ClassDecl->getDestructor();
2448 assert(D && D->isUsed() && "destructor not marked as used!");
2449 PushDestructorCleanup(D, T, Addr);
2452 void CodeGenFunction::InitializeVTablePointer(const VPtr &Vptr) {
2453 // Compute the address point.
2454 llvm::Value *VTableAddressPoint =
2455 CGM.getCXXABI().getVTableAddressPointInStructor(
2456 *this, Vptr.VTableClass, Vptr.Base, Vptr.NearestVBase);
2458 if (!VTableAddressPoint)
2461 // Compute where to store the address point.
2462 llvm::Value *VirtualOffset = nullptr;
2463 CharUnits NonVirtualOffset = CharUnits::Zero();
2465 if (CGM.getCXXABI().isVirtualOffsetNeededForVTableField(*this, Vptr)) {
2466 // We need to use the virtual base offset offset because the virtual base
2467 // might have a different offset in the most derived class.
2469 VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(
2470 *this, LoadCXXThisAddress(), Vptr.VTableClass, Vptr.NearestVBase);
2471 NonVirtualOffset = Vptr.OffsetFromNearestVBase;
2473 // We can just use the base offset in the complete class.
2474 NonVirtualOffset = Vptr.Base.getBaseOffset();
2477 // Apply the offsets.
2478 Address VTableField = LoadCXXThisAddress();
2480 if (!NonVirtualOffset.isZero() || VirtualOffset)
2481 VTableField = ApplyNonVirtualAndVirtualOffset(
2482 *this, VTableField, NonVirtualOffset, VirtualOffset, Vptr.VTableClass,
2485 // Finally, store the address point. Use the same LLVM types as the field to
2486 // support optimization.
2487 llvm::Type *VTablePtrTy =
2488 llvm::FunctionType::get(CGM.Int32Ty, /*isVarArg=*/true)
2491 VTableField = Builder.CreateBitCast(VTableField, VTablePtrTy->getPointerTo());
2492 VTableAddressPoint = Builder.CreateBitCast(VTableAddressPoint, VTablePtrTy);
2494 llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
2495 TBAAAccessInfo TBAAInfo = CGM.getTBAAVTablePtrAccessInfo(VTablePtrTy);
2496 CGM.DecorateInstructionWithTBAA(Store, TBAAInfo);
2497 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2498 CGM.getCodeGenOpts().StrictVTablePointers)
2499 CGM.DecorateInstructionWithInvariantGroup(Store, Vptr.VTableClass);
2502 CodeGenFunction::VPtrsVector
2503 CodeGenFunction::getVTablePointers(const CXXRecordDecl *VTableClass) {
2504 CodeGenFunction::VPtrsVector VPtrsResult;
2505 VisitedVirtualBasesSetTy VBases;
2506 getVTablePointers(BaseSubobject(VTableClass, CharUnits::Zero()),
2507 /*NearestVBase=*/nullptr,
2508 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
2509 /*BaseIsNonVirtualPrimaryBase=*/false, VTableClass, VBases,
2514 void CodeGenFunction::getVTablePointers(BaseSubobject Base,
2515 const CXXRecordDecl *NearestVBase,
2516 CharUnits OffsetFromNearestVBase,
2517 bool BaseIsNonVirtualPrimaryBase,
2518 const CXXRecordDecl *VTableClass,
2519 VisitedVirtualBasesSetTy &VBases,
2520 VPtrsVector &Vptrs) {
2521 // If this base is a non-virtual primary base the address point has already
2523 if (!BaseIsNonVirtualPrimaryBase) {
2524 // Initialize the vtable pointer for this base.
2525 VPtr Vptr = {Base, NearestVBase, OffsetFromNearestVBase, VTableClass};
2526 Vptrs.push_back(Vptr);
2529 const CXXRecordDecl *RD = Base.getBase();
2532 for (const auto &I : RD->bases()) {
2533 CXXRecordDecl *BaseDecl
2534 = cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
2536 // Ignore classes without a vtable.
2537 if (!BaseDecl->isDynamicClass())
2540 CharUnits BaseOffset;
2541 CharUnits BaseOffsetFromNearestVBase;
2542 bool BaseDeclIsNonVirtualPrimaryBase;
2544 if (I.isVirtual()) {
2545 // Check if we've visited this virtual base before.
2546 if (!VBases.insert(BaseDecl).second)
2549 const ASTRecordLayout &Layout =
2550 getContext().getASTRecordLayout(VTableClass);
2552 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
2553 BaseOffsetFromNearestVBase = CharUnits::Zero();
2554 BaseDeclIsNonVirtualPrimaryBase = false;
2556 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
2558 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
2559 BaseOffsetFromNearestVBase =
2560 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
2561 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
2565 BaseSubobject(BaseDecl, BaseOffset),
2566 I.isVirtual() ? BaseDecl : NearestVBase, BaseOffsetFromNearestVBase,
2567 BaseDeclIsNonVirtualPrimaryBase, VTableClass, VBases, Vptrs);
2571 void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
2572 // Ignore classes without a vtable.
2573 if (!RD->isDynamicClass())
2576 // Initialize the vtable pointers for this class and all of its bases.
2577 if (CGM.getCXXABI().doStructorsInitializeVPtrs(RD))
2578 for (const VPtr &Vptr : getVTablePointers(RD))
2579 InitializeVTablePointer(Vptr);
2581 if (RD->getNumVBases())
2582 CGM.getCXXABI().initializeHiddenVirtualInheritanceMembers(*this, RD);
2585 llvm::Value *CodeGenFunction::GetVTablePtr(Address This,
2586 llvm::Type *VTableTy,
2587 const CXXRecordDecl *RD) {
2588 Address VTablePtrSrc = Builder.CreateElementBitCast(This, VTableTy);
2589 llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
2590 TBAAAccessInfo TBAAInfo = CGM.getTBAAVTablePtrAccessInfo(VTableTy);
2591 CGM.DecorateInstructionWithTBAA(VTable, TBAAInfo);
2593 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2594 CGM.getCodeGenOpts().StrictVTablePointers)
2595 CGM.DecorateInstructionWithInvariantGroup(VTable, RD);
2600 // If a class has a single non-virtual base and does not introduce or override
2601 // virtual member functions or fields, it will have the same layout as its base.
2602 // This function returns the least derived such class.
2604 // Casting an instance of a base class to such a derived class is technically
2605 // undefined behavior, but it is a relatively common hack for introducing member
2606 // functions on class instances with specific properties (e.g. llvm::Operator)
2607 // that works under most compilers and should not have security implications, so
2608 // we allow it by default. It can be disabled with -fsanitize=cfi-cast-strict.
2609 static const CXXRecordDecl *
2610 LeastDerivedClassWithSameLayout(const CXXRecordDecl *RD) {
2611 if (!RD->field_empty())
2614 if (RD->getNumVBases() != 0)
2617 if (RD->getNumBases() != 1)
2620 for (const CXXMethodDecl *MD : RD->methods()) {
2621 if (MD->isVirtual()) {
2622 // Virtual member functions are only ok if they are implicit destructors
2623 // because the implicit destructor will have the same semantics as the
2624 // base class's destructor if no fields are added.
2625 if (isa<CXXDestructorDecl>(MD) && MD->isImplicit())
2631 return LeastDerivedClassWithSameLayout(
2632 RD->bases_begin()->getType()->getAsCXXRecordDecl());
2635 void CodeGenFunction::EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD,
2636 llvm::Value *VTable,
2637 SourceLocation Loc) {
2638 if (SanOpts.has(SanitizerKind::CFIVCall))
2639 EmitVTablePtrCheckForCall(RD, VTable, CodeGenFunction::CFITCK_VCall, Loc);
2640 else if (CGM.getCodeGenOpts().WholeProgramVTables &&
2641 CGM.HasHiddenLTOVisibility(RD)) {
2642 llvm::Metadata *MD =
2643 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
2644 llvm::Value *TypeId =
2645 llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD);
2647 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
2648 llvm::Value *TypeTest =
2649 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
2650 {CastedVTable, TypeId});
2651 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::assume), TypeTest);
2655 void CodeGenFunction::EmitVTablePtrCheckForCall(const CXXRecordDecl *RD,
2656 llvm::Value *VTable,
2657 CFITypeCheckKind TCK,
2658 SourceLocation Loc) {
2659 if (!SanOpts.has(SanitizerKind::CFICastStrict))
2660 RD = LeastDerivedClassWithSameLayout(RD);
2662 EmitVTablePtrCheck(RD, VTable, TCK, Loc);
2665 void CodeGenFunction::EmitVTablePtrCheckForCast(QualType T,
2666 llvm::Value *Derived,
2668 CFITypeCheckKind TCK,
2669 SourceLocation Loc) {
2670 if (!getLangOpts().CPlusPlus)
2673 auto *ClassTy = T->getAs<RecordType>();
2677 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassTy->getDecl());
2679 if (!ClassDecl->isCompleteDefinition() || !ClassDecl->isDynamicClass())
2682 if (!SanOpts.has(SanitizerKind::CFICastStrict))
2683 ClassDecl = LeastDerivedClassWithSameLayout(ClassDecl);
2685 llvm::BasicBlock *ContBlock = nullptr;
2688 llvm::Value *DerivedNotNull =
2689 Builder.CreateIsNotNull(Derived, "cast.nonnull");
2691 llvm::BasicBlock *CheckBlock = createBasicBlock("cast.check");
2692 ContBlock = createBasicBlock("cast.cont");
2694 Builder.CreateCondBr(DerivedNotNull, CheckBlock, ContBlock);
2696 EmitBlock(CheckBlock);
2699 llvm::Value *VTable;
2700 std::tie(VTable, ClassDecl) = CGM.getCXXABI().LoadVTablePtr(
2701 *this, Address(Derived, getPointerAlign()), ClassDecl);
2703 EmitVTablePtrCheck(ClassDecl, VTable, TCK, Loc);
2706 Builder.CreateBr(ContBlock);
2707 EmitBlock(ContBlock);
2711 void CodeGenFunction::EmitVTablePtrCheck(const CXXRecordDecl *RD,
2712 llvm::Value *VTable,
2713 CFITypeCheckKind TCK,
2714 SourceLocation Loc) {
2715 if (!CGM.getCodeGenOpts().SanitizeCfiCrossDso &&
2716 !CGM.HasHiddenLTOVisibility(RD))
2720 llvm::SanitizerStatKind SSK;
2723 M = SanitizerKind::CFIVCall;
2724 SSK = llvm::SanStat_CFI_VCall;
2727 M = SanitizerKind::CFINVCall;
2728 SSK = llvm::SanStat_CFI_NVCall;
2730 case CFITCK_DerivedCast:
2731 M = SanitizerKind::CFIDerivedCast;
2732 SSK = llvm::SanStat_CFI_DerivedCast;
2734 case CFITCK_UnrelatedCast:
2735 M = SanitizerKind::CFIUnrelatedCast;
2736 SSK = llvm::SanStat_CFI_UnrelatedCast;
2739 case CFITCK_NVMFCall:
2740 case CFITCK_VMFCall:
2741 llvm_unreachable("unexpected sanitizer kind");
2744 std::string TypeName = RD->getQualifiedNameAsString();
2745 if (getContext().getSanitizerBlacklist().isBlacklistedType(M, TypeName))
2748 SanitizerScope SanScope(this);
2749 EmitSanitizerStatReport(SSK);
2751 llvm::Metadata *MD =
2752 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
2753 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
2755 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
2756 llvm::Value *TypeTest = Builder.CreateCall(
2757 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, TypeId});
2759 llvm::Constant *StaticData[] = {
2760 llvm::ConstantInt::get(Int8Ty, TCK),
2761 EmitCheckSourceLocation(Loc),
2762 EmitCheckTypeDescriptor(QualType(RD->getTypeForDecl(), 0)),
2765 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
2766 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
2767 EmitCfiSlowPathCheck(M, TypeTest, CrossDsoTypeId, CastedVTable, StaticData);
2771 if (CGM.getCodeGenOpts().SanitizeTrap.has(M)) {
2772 EmitTrapCheck(TypeTest);
2776 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
2777 CGM.getLLVMContext(),
2778 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
2779 llvm::Value *ValidVtable = Builder.CreateCall(
2780 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, AllVtables});
2781 EmitCheck(std::make_pair(TypeTest, M), SanitizerHandler::CFICheckFail,
2782 StaticData, {CastedVTable, ValidVtable});
2785 bool CodeGenFunction::ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD) {
2786 if (!CGM.getCodeGenOpts().WholeProgramVTables ||
2787 !SanOpts.has(SanitizerKind::CFIVCall) ||
2788 !CGM.getCodeGenOpts().SanitizeTrap.has(SanitizerKind::CFIVCall) ||
2789 !CGM.HasHiddenLTOVisibility(RD))
2792 std::string TypeName = RD->getQualifiedNameAsString();
2793 return !getContext().getSanitizerBlacklist().isBlacklistedType(
2794 SanitizerKind::CFIVCall, TypeName);
2797 llvm::Value *CodeGenFunction::EmitVTableTypeCheckedLoad(
2798 const CXXRecordDecl *RD, llvm::Value *VTable, uint64_t VTableByteOffset) {
2799 SanitizerScope SanScope(this);
2801 EmitSanitizerStatReport(llvm::SanStat_CFI_VCall);
2803 llvm::Metadata *MD =
2804 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
2805 llvm::Value *TypeId = llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD);
2807 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
2808 llvm::Value *CheckedLoad = Builder.CreateCall(
2809 CGM.getIntrinsic(llvm::Intrinsic::type_checked_load),
2810 {CastedVTable, llvm::ConstantInt::get(Int32Ty, VTableByteOffset),
2812 llvm::Value *CheckResult = Builder.CreateExtractValue(CheckedLoad, 1);
2814 EmitCheck(std::make_pair(CheckResult, SanitizerKind::CFIVCall),
2815 SanitizerHandler::CFICheckFail, nullptr, nullptr);
2817 return Builder.CreateBitCast(
2818 Builder.CreateExtractValue(CheckedLoad, 0),
2819 cast<llvm::PointerType>(VTable->getType())->getElementType());
2822 void CodeGenFunction::EmitForwardingCallToLambda(
2823 const CXXMethodDecl *callOperator,
2824 CallArgList &callArgs) {
2825 // Get the address of the call operator.
2826 const CGFunctionInfo &calleeFnInfo =
2827 CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
2828 llvm::Constant *calleePtr =
2829 CGM.GetAddrOfFunction(GlobalDecl(callOperator),
2830 CGM.getTypes().GetFunctionType(calleeFnInfo));
2832 // Prepare the return slot.
2833 const FunctionProtoType *FPT =
2834 callOperator->getType()->castAs<FunctionProtoType>();
2835 QualType resultType = FPT->getReturnType();
2836 ReturnValueSlot returnSlot;
2837 if (!resultType->isVoidType() &&
2838 calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
2839 !hasScalarEvaluationKind(calleeFnInfo.getReturnType()))
2840 returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
2842 // We don't need to separately arrange the call arguments because
2843 // the call can't be variadic anyway --- it's impossible to forward
2844 // variadic arguments.
2846 // Now emit our call.
2847 auto callee = CGCallee::forDirect(calleePtr, GlobalDecl(callOperator));
2848 RValue RV = EmitCall(calleeFnInfo, callee, returnSlot, callArgs);
2850 // If necessary, copy the returned value into the slot.
2851 if (!resultType->isVoidType() && returnSlot.isNull()) {
2852 if (getLangOpts().ObjCAutoRefCount && resultType->isObjCRetainableType()) {
2853 RV = RValue::get(EmitARCRetainAutoreleasedReturnValue(RV.getScalarVal()));
2855 EmitReturnOfRValue(RV, resultType);
2857 EmitBranchThroughCleanup(ReturnBlock);
2860 void CodeGenFunction::EmitLambdaBlockInvokeBody() {
2861 const BlockDecl *BD = BlockInfo->getBlockDecl();
2862 const VarDecl *variable = BD->capture_begin()->getVariable();
2863 const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
2864 const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
2866 if (CallOp->isVariadic()) {
2867 // FIXME: Making this work correctly is nasty because it requires either
2868 // cloning the body of the call operator or making the call operator
2870 CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function");
2874 // Start building arguments for forwarding call
2875 CallArgList CallArgs;
2877 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2878 Address ThisPtr = GetAddrOfBlockDecl(variable);
2879 CallArgs.add(RValue::get(ThisPtr.getPointer()), ThisType);
2881 // Add the rest of the parameters.
2882 for (auto param : BD->parameters())
2883 EmitDelegateCallArg(CallArgs, param, param->getBeginLoc());
2885 assert(!Lambda->isGenericLambda() &&
2886 "generic lambda interconversion to block not implemented");
2887 EmitForwardingCallToLambda(CallOp, CallArgs);
2890 void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
2891 const CXXRecordDecl *Lambda = MD->getParent();
2893 // Start building arguments for forwarding call
2894 CallArgList CallArgs;
2896 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2897 llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
2898 CallArgs.add(RValue::get(ThisPtr), ThisType);
2900 // Add the rest of the parameters.
2901 for (auto Param : MD->parameters())
2902 EmitDelegateCallArg(CallArgs, Param, Param->getBeginLoc());
2904 const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
2905 // For a generic lambda, find the corresponding call operator specialization
2906 // to which the call to the static-invoker shall be forwarded.
2907 if (Lambda->isGenericLambda()) {
2908 assert(MD->isFunctionTemplateSpecialization());
2909 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
2910 FunctionTemplateDecl *CallOpTemplate = CallOp->getDescribedFunctionTemplate();
2911 void *InsertPos = nullptr;
2912 FunctionDecl *CorrespondingCallOpSpecialization =
2913 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
2914 assert(CorrespondingCallOpSpecialization);
2915 CallOp = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
2917 EmitForwardingCallToLambda(CallOp, CallArgs);
2920 void CodeGenFunction::EmitLambdaStaticInvokeBody(const CXXMethodDecl *MD) {
2921 if (MD->isVariadic()) {
2922 // FIXME: Making this work correctly is nasty because it requires either
2923 // cloning the body of the call operator or making the call operator forward.
2924 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
2928 EmitLambdaDelegatingInvokeBody(MD);