1 //===--- CGClass.cpp - Emit LLVM Code for C++ classes -----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This contains code dealing with C++ code generation of classes
12 //===----------------------------------------------------------------------===//
16 #include "CGDebugInfo.h"
17 #include "CGRecordLayout.h"
18 #include "CodeGenFunction.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/TargetBuiltins.h"
25 #include "clang/CodeGen/CGFunctionInfo.h"
26 #include "clang/Frontend/CodeGenOptions.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 AlignmentSource *alignSource) {
133 // Ask the ABI to compute the actual address.
135 CGM.getCXXABI().EmitMemberDataPointerAddress(*this, E, base,
136 memberPtr, memberPtrType);
138 QualType memberType = memberPtrType->getPointeeType();
139 CharUnits memberAlign = getNaturalTypeAlignment(memberType, alignSource);
141 CGM.getDynamicOffsetAlignment(base.getAlignment(),
142 memberPtrType->getClass()->getAsCXXRecordDecl(),
144 return Address(ptr, memberAlign);
147 CharUnits CodeGenModule::computeNonVirtualBaseClassOffset(
148 const CXXRecordDecl *DerivedClass, CastExpr::path_const_iterator Start,
149 CastExpr::path_const_iterator End) {
150 CharUnits Offset = CharUnits::Zero();
152 const ASTContext &Context = getContext();
153 const CXXRecordDecl *RD = DerivedClass;
155 for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
156 const CXXBaseSpecifier *Base = *I;
157 assert(!Base->isVirtual() && "Should not see virtual bases here!");
160 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
162 const CXXRecordDecl *BaseDecl =
163 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
166 Offset += Layout.getBaseClassOffset(BaseDecl);
175 CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
176 CastExpr::path_const_iterator PathBegin,
177 CastExpr::path_const_iterator PathEnd) {
178 assert(PathBegin != PathEnd && "Base path should not be empty!");
181 computeNonVirtualBaseClassOffset(ClassDecl, PathBegin, PathEnd);
185 llvm::Type *PtrDiffTy =
186 Types.ConvertType(getContext().getPointerDiffType());
188 return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
191 /// Gets the address of a direct base class within a complete object.
192 /// This should only be used for (1) non-virtual bases or (2) virtual bases
193 /// when the type is known to be complete (e.g. in complete destructors).
195 /// The object pointed to by 'This' is assumed to be non-null.
197 CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(Address This,
198 const CXXRecordDecl *Derived,
199 const CXXRecordDecl *Base,
200 bool BaseIsVirtual) {
201 // 'this' must be a pointer (in some address space) to Derived.
202 assert(This.getElementType() == ConvertType(Derived));
204 // Compute the offset of the virtual base.
206 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
208 Offset = Layout.getVBaseClassOffset(Base);
210 Offset = Layout.getBaseClassOffset(Base);
212 // Shift and cast down to the base type.
213 // TODO: for complete types, this should be possible with a GEP.
215 if (!Offset.isZero()) {
216 V = Builder.CreateElementBitCast(V, Int8Ty);
217 V = Builder.CreateConstInBoundsByteGEP(V, Offset);
219 V = Builder.CreateElementBitCast(V, ConvertType(Base));
225 ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, Address addr,
226 CharUnits nonVirtualOffset,
227 llvm::Value *virtualOffset,
228 const CXXRecordDecl *derivedClass,
229 const CXXRecordDecl *nearestVBase) {
230 // Assert that we have something to do.
231 assert(!nonVirtualOffset.isZero() || virtualOffset != nullptr);
233 // Compute the offset from the static and dynamic components.
234 llvm::Value *baseOffset;
235 if (!nonVirtualOffset.isZero()) {
236 baseOffset = llvm::ConstantInt::get(CGF.PtrDiffTy,
237 nonVirtualOffset.getQuantity());
239 baseOffset = CGF.Builder.CreateAdd(virtualOffset, baseOffset);
242 baseOffset = virtualOffset;
245 // Apply the base offset.
246 llvm::Value *ptr = addr.getPointer();
247 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
248 ptr = CGF.Builder.CreateInBoundsGEP(ptr, baseOffset, "add.ptr");
250 // If we have a virtual component, the alignment of the result will
251 // be relative only to the known alignment of that vbase.
254 assert(nearestVBase && "virtual offset without vbase?");
255 alignment = CGF.CGM.getVBaseAlignment(addr.getAlignment(),
256 derivedClass, nearestVBase);
258 alignment = addr.getAlignment();
260 alignment = alignment.alignmentAtOffset(nonVirtualOffset);
262 return Address(ptr, alignment);
265 Address CodeGenFunction::GetAddressOfBaseClass(
266 Address Value, const CXXRecordDecl *Derived,
267 CastExpr::path_const_iterator PathBegin,
268 CastExpr::path_const_iterator PathEnd, bool NullCheckValue,
269 SourceLocation Loc) {
270 assert(PathBegin != PathEnd && "Base path should not be empty!");
272 CastExpr::path_const_iterator Start = PathBegin;
273 const CXXRecordDecl *VBase = nullptr;
275 // Sema has done some convenient canonicalization here: if the
276 // access path involved any virtual steps, the conversion path will
277 // *start* with a step down to the correct virtual base subobject,
278 // and hence will not require any further steps.
279 if ((*Start)->isVirtual()) {
281 cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
285 // Compute the static offset of the ultimate destination within its
286 // allocating subobject (the virtual base, if there is one, or else
287 // the "complete" object that we see).
288 CharUnits NonVirtualOffset = CGM.computeNonVirtualBaseClassOffset(
289 VBase ? VBase : Derived, Start, PathEnd);
291 // If there's a virtual step, we can sometimes "devirtualize" it.
292 // For now, that's limited to when the derived type is final.
293 // TODO: "devirtualize" this for accesses to known-complete objects.
294 if (VBase && Derived->hasAttr<FinalAttr>()) {
295 const ASTRecordLayout &layout = getContext().getASTRecordLayout(Derived);
296 CharUnits vBaseOffset = layout.getVBaseClassOffset(VBase);
297 NonVirtualOffset += vBaseOffset;
298 VBase = nullptr; // we no longer have a virtual step
301 // Get the base pointer type.
302 llvm::Type *BasePtrTy =
303 ConvertType((PathEnd[-1])->getType())->getPointerTo();
305 QualType DerivedTy = getContext().getRecordType(Derived);
306 CharUnits DerivedAlign = CGM.getClassPointerAlignment(Derived);
308 // If the static offset is zero and we don't have a virtual step,
309 // just do a bitcast; null checks are unnecessary.
310 if (NonVirtualOffset.isZero() && !VBase) {
311 if (sanitizePerformTypeCheck()) {
312 EmitTypeCheck(TCK_Upcast, Loc, Value.getPointer(),
313 DerivedTy, DerivedAlign, !NullCheckValue);
315 return Builder.CreateBitCast(Value, BasePtrTy);
318 llvm::BasicBlock *origBB = nullptr;
319 llvm::BasicBlock *endBB = nullptr;
321 // Skip over the offset (and the vtable load) if we're supposed to
322 // null-check the pointer.
323 if (NullCheckValue) {
324 origBB = Builder.GetInsertBlock();
325 llvm::BasicBlock *notNullBB = createBasicBlock("cast.notnull");
326 endBB = createBasicBlock("cast.end");
328 llvm::Value *isNull = Builder.CreateIsNull(Value.getPointer());
329 Builder.CreateCondBr(isNull, endBB, notNullBB);
330 EmitBlock(notNullBB);
333 if (sanitizePerformTypeCheck()) {
334 EmitTypeCheck(VBase ? TCK_UpcastToVirtualBase : TCK_Upcast, Loc,
335 Value.getPointer(), DerivedTy, DerivedAlign, true);
338 // Compute the virtual offset.
339 llvm::Value *VirtualOffset = nullptr;
342 CGM.getCXXABI().GetVirtualBaseClassOffset(*this, Value, Derived, VBase);
345 // Apply both offsets.
346 Value = ApplyNonVirtualAndVirtualOffset(*this, Value, NonVirtualOffset,
347 VirtualOffset, Derived, VBase);
349 // Cast to the destination type.
350 Value = Builder.CreateBitCast(Value, BasePtrTy);
352 // Build a phi if we needed a null check.
353 if (NullCheckValue) {
354 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
355 Builder.CreateBr(endBB);
358 llvm::PHINode *PHI = Builder.CreatePHI(BasePtrTy, 2, "cast.result");
359 PHI->addIncoming(Value.getPointer(), notNullBB);
360 PHI->addIncoming(llvm::Constant::getNullValue(BasePtrTy), origBB);
361 Value = Address(PHI, Value.getAlignment());
368 CodeGenFunction::GetAddressOfDerivedClass(Address BaseAddr,
369 const CXXRecordDecl *Derived,
370 CastExpr::path_const_iterator PathBegin,
371 CastExpr::path_const_iterator PathEnd,
372 bool NullCheckValue) {
373 assert(PathBegin != PathEnd && "Base path should not be empty!");
376 getContext().getCanonicalType(getContext().getTagDeclType(Derived));
377 llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
379 llvm::Value *NonVirtualOffset =
380 CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
382 if (!NonVirtualOffset) {
383 // No offset, we can just cast back.
384 return Builder.CreateBitCast(BaseAddr, DerivedPtrTy);
387 llvm::BasicBlock *CastNull = nullptr;
388 llvm::BasicBlock *CastNotNull = nullptr;
389 llvm::BasicBlock *CastEnd = nullptr;
391 if (NullCheckValue) {
392 CastNull = createBasicBlock("cast.null");
393 CastNotNull = createBasicBlock("cast.notnull");
394 CastEnd = createBasicBlock("cast.end");
396 llvm::Value *IsNull = Builder.CreateIsNull(BaseAddr.getPointer());
397 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
398 EmitBlock(CastNotNull);
402 llvm::Value *Value = Builder.CreateBitCast(BaseAddr.getPointer(), Int8PtrTy);
403 Value = Builder.CreateGEP(Value, Builder.CreateNeg(NonVirtualOffset),
407 Value = Builder.CreateBitCast(Value, DerivedPtrTy);
409 // Produce a PHI if we had a null-check.
410 if (NullCheckValue) {
411 Builder.CreateBr(CastEnd);
413 Builder.CreateBr(CastEnd);
416 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
417 PHI->addIncoming(Value, CastNotNull);
418 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
422 return Address(Value, CGM.getClassPointerAlignment(Derived));
425 llvm::Value *CodeGenFunction::GetVTTParameter(GlobalDecl GD,
428 if (!CGM.getCXXABI().NeedsVTTParameter(GD)) {
429 // This constructor/destructor does not need a VTT parameter.
433 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CurCodeDecl)->getParent();
434 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
438 uint64_t SubVTTIndex;
441 // If this is a delegating constructor call, just load the VTT.
443 } else if (RD == Base) {
444 // If the record matches the base, this is the complete ctor/dtor
445 // variant calling the base variant in a class with virtual bases.
446 assert(!CGM.getCXXABI().NeedsVTTParameter(CurGD) &&
447 "doing no-op VTT offset in base dtor/ctor?");
448 assert(!ForVirtualBase && "Can't have same class as virtual base!");
451 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
452 CharUnits BaseOffset = ForVirtualBase ?
453 Layout.getVBaseClassOffset(Base) :
454 Layout.getBaseClassOffset(Base);
457 CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
458 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
461 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
462 // A VTT parameter was passed to the constructor, use it.
464 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
466 // We're the complete constructor, so get the VTT by name.
467 VTT = CGM.getVTables().GetAddrOfVTT(RD);
468 VTT = Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
475 /// Call the destructor for a direct base class.
476 struct CallBaseDtor final : EHScopeStack::Cleanup {
477 const CXXRecordDecl *BaseClass;
479 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
480 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
482 void Emit(CodeGenFunction &CGF, Flags flags) override {
483 const CXXRecordDecl *DerivedClass =
484 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
486 const CXXDestructorDecl *D = BaseClass->getDestructor();
488 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThisAddress(),
489 DerivedClass, BaseClass,
491 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual,
492 /*Delegating=*/false, Addr);
496 /// A visitor which checks whether an initializer uses 'this' in a
497 /// way which requires the vtable to be properly set.
498 struct DynamicThisUseChecker : ConstEvaluatedExprVisitor<DynamicThisUseChecker> {
499 typedef ConstEvaluatedExprVisitor<DynamicThisUseChecker> super;
503 DynamicThisUseChecker(const ASTContext &C) : super(C), UsesThis(false) {}
505 // Black-list all explicit and implicit references to 'this'.
507 // Do we need to worry about external references to 'this' derived
508 // from arbitrary code? If so, then anything which runs arbitrary
509 // external code might potentially access the vtable.
510 void VisitCXXThisExpr(const CXXThisExpr *E) { UsesThis = true; }
512 } // end anonymous namespace
514 static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
515 DynamicThisUseChecker Checker(C);
517 return Checker.UsesThis;
520 static void EmitBaseInitializer(CodeGenFunction &CGF,
521 const CXXRecordDecl *ClassDecl,
522 CXXCtorInitializer *BaseInit,
523 CXXCtorType CtorType) {
524 assert(BaseInit->isBaseInitializer() &&
525 "Must have base initializer!");
527 Address ThisPtr = CGF.LoadCXXThisAddress();
529 const Type *BaseType = BaseInit->getBaseClass();
530 CXXRecordDecl *BaseClassDecl =
531 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
533 bool isBaseVirtual = BaseInit->isBaseVirtual();
535 // The base constructor doesn't construct virtual bases.
536 if (CtorType == Ctor_Base && isBaseVirtual)
539 // If the initializer for the base (other than the constructor
540 // itself) accesses 'this' in any way, we need to initialize the
542 if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
543 CGF.InitializeVTablePointers(ClassDecl);
545 // We can pretend to be a complete class because it only matters for
546 // virtual bases, and we only do virtual bases for complete ctors.
548 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
551 AggValueSlot AggSlot =
552 AggValueSlot::forAddr(V, Qualifiers(),
553 AggValueSlot::IsDestructed,
554 AggValueSlot::DoesNotNeedGCBarriers,
555 AggValueSlot::IsNotAliased);
557 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
559 if (CGF.CGM.getLangOpts().Exceptions &&
560 !BaseClassDecl->hasTrivialDestructor())
561 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
565 static bool isMemcpyEquivalentSpecialMember(const CXXMethodDecl *D) {
566 auto *CD = dyn_cast<CXXConstructorDecl>(D);
567 if (!(CD && CD->isCopyOrMoveConstructor()) &&
568 !D->isCopyAssignmentOperator() && !D->isMoveAssignmentOperator())
571 // We can emit a memcpy for a trivial copy or move constructor/assignment.
572 if (D->isTrivial() && !D->getParent()->mayInsertExtraPadding())
575 // We *must* emit a memcpy for a defaulted union copy or move op.
576 if (D->getParent()->isUnion() && D->isDefaulted())
582 static void EmitLValueForAnyFieldInitialization(CodeGenFunction &CGF,
583 CXXCtorInitializer *MemberInit,
585 FieldDecl *Field = MemberInit->getAnyMember();
586 if (MemberInit->isIndirectMemberInitializer()) {
587 // If we are initializing an anonymous union field, drill down to the field.
588 IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember();
589 for (const auto *I : IndirectField->chain())
590 LHS = CGF.EmitLValueForFieldInitialization(LHS, cast<FieldDecl>(I));
592 LHS = CGF.EmitLValueForFieldInitialization(LHS, Field);
596 static void EmitMemberInitializer(CodeGenFunction &CGF,
597 const CXXRecordDecl *ClassDecl,
598 CXXCtorInitializer *MemberInit,
599 const CXXConstructorDecl *Constructor,
600 FunctionArgList &Args) {
601 ApplyDebugLocation Loc(CGF, MemberInit->getSourceLocation());
602 assert(MemberInit->isAnyMemberInitializer() &&
603 "Must have member initializer!");
604 assert(MemberInit->getInit() && "Must have initializer!");
606 // non-static data member initializers.
607 FieldDecl *Field = MemberInit->getAnyMember();
608 QualType FieldType = Field->getType();
610 llvm::Value *ThisPtr = CGF.LoadCXXThis();
611 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
612 LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
614 EmitLValueForAnyFieldInitialization(CGF, MemberInit, LHS);
616 // Special case: if we are in a copy or move constructor, and we are copying
617 // an array of PODs or classes with trivial copy constructors, ignore the
618 // AST and perform the copy we know is equivalent.
619 // FIXME: This is hacky at best... if we had a bit more explicit information
620 // in the AST, we could generalize it more easily.
621 const ConstantArrayType *Array
622 = CGF.getContext().getAsConstantArrayType(FieldType);
623 if (Array && Constructor->isDefaulted() &&
624 Constructor->isCopyOrMoveConstructor()) {
625 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
626 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
627 if (BaseElementTy.isPODType(CGF.getContext()) ||
628 (CE && isMemcpyEquivalentSpecialMember(CE->getConstructor()))) {
629 unsigned SrcArgIndex =
630 CGF.CGM.getCXXABI().getSrcArgforCopyCtor(Constructor, Args);
632 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
633 LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
634 LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field);
636 // Copy the aggregate.
637 CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
638 LHS.isVolatileQualified());
639 // Ensure that we destroy the objects if an exception is thrown later in
641 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
642 if (CGF.needsEHCleanup(dtorKind))
643 CGF.pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
648 CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit());
651 void CodeGenFunction::EmitInitializerForField(FieldDecl *Field, LValue LHS,
653 QualType FieldType = Field->getType();
654 switch (getEvaluationKind(FieldType)) {
656 if (LHS.isSimple()) {
657 EmitExprAsInit(Init, Field, LHS, false);
659 RValue RHS = RValue::get(EmitScalarExpr(Init));
660 EmitStoreThroughLValue(RHS, LHS);
664 EmitComplexExprIntoLValue(Init, LHS, /*isInit*/ true);
666 case TEK_Aggregate: {
668 AggValueSlot::forLValue(LHS,
669 AggValueSlot::IsDestructed,
670 AggValueSlot::DoesNotNeedGCBarriers,
671 AggValueSlot::IsNotAliased);
672 EmitAggExpr(Init, Slot);
677 // Ensure that we destroy this object if an exception is thrown
678 // later in the constructor.
679 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
680 if (needsEHCleanup(dtorKind))
681 pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
684 /// Checks whether the given constructor is a valid subject for the
685 /// complete-to-base constructor delegation optimization, i.e.
686 /// emitting the complete constructor as a simple call to the base
688 static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
690 // Currently we disable the optimization for classes with virtual
691 // bases because (1) the addresses of parameter variables need to be
692 // consistent across all initializers but (2) the delegate function
693 // call necessarily creates a second copy of the parameter variable.
695 // The limiting example (purely theoretical AFAIK):
696 // struct A { A(int &c) { c++; } };
697 // struct B : virtual A {
698 // B(int count) : A(count) { printf("%d\n", count); }
700 // ...although even this example could in principle be emitted as a
701 // delegation since the address of the parameter doesn't escape.
702 if (Ctor->getParent()->getNumVBases()) {
703 // TODO: white-list trivial vbase initializers. This case wouldn't
704 // be subject to the restrictions below.
706 // TODO: white-list cases where:
707 // - there are no non-reference parameters to the constructor
708 // - the initializers don't access any non-reference parameters
709 // - the initializers don't take the address of non-reference
712 // If we ever add any of the above cases, remember that:
713 // - function-try-blocks will always blacklist this optimization
714 // - we need to perform the constructor prologue and cleanup in
715 // EmitConstructorBody.
720 // We also disable the optimization for variadic functions because
721 // it's impossible to "re-pass" varargs.
722 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
725 // FIXME: Decide if we can do a delegation of a delegating constructor.
726 if (Ctor->isDelegatingConstructor())
732 // Emit code in ctor (Prologue==true) or dtor (Prologue==false)
733 // to poison the extra field paddings inserted under
734 // -fsanitize-address-field-padding=1|2.
735 void CodeGenFunction::EmitAsanPrologueOrEpilogue(bool Prologue) {
736 ASTContext &Context = getContext();
737 const CXXRecordDecl *ClassDecl =
738 Prologue ? cast<CXXConstructorDecl>(CurGD.getDecl())->getParent()
739 : cast<CXXDestructorDecl>(CurGD.getDecl())->getParent();
740 if (!ClassDecl->mayInsertExtraPadding()) return;
742 struct SizeAndOffset {
747 unsigned PtrSize = CGM.getDataLayout().getPointerSizeInBits();
748 const ASTRecordLayout &Info = Context.getASTRecordLayout(ClassDecl);
750 // Populate sizes and offsets of fields.
751 SmallVector<SizeAndOffset, 16> SSV(Info.getFieldCount());
752 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i)
754 Context.toCharUnitsFromBits(Info.getFieldOffset(i)).getQuantity();
756 size_t NumFields = 0;
757 for (const auto *Field : ClassDecl->fields()) {
758 const FieldDecl *D = Field;
759 std::pair<CharUnits, CharUnits> FieldInfo =
760 Context.getTypeInfoInChars(D->getType());
761 CharUnits FieldSize = FieldInfo.first;
762 assert(NumFields < SSV.size());
763 SSV[NumFields].Size = D->isBitField() ? 0 : FieldSize.getQuantity();
766 assert(NumFields == SSV.size());
767 if (SSV.size() <= 1) return;
769 // We will insert calls to __asan_* run-time functions.
770 // LLVM AddressSanitizer pass may decide to inline them later.
771 llvm::Type *Args[2] = {IntPtrTy, IntPtrTy};
772 llvm::FunctionType *FTy =
773 llvm::FunctionType::get(CGM.VoidTy, Args, false);
774 llvm::Constant *F = CGM.CreateRuntimeFunction(
775 FTy, Prologue ? "__asan_poison_intra_object_redzone"
776 : "__asan_unpoison_intra_object_redzone");
778 llvm::Value *ThisPtr = LoadCXXThis();
779 ThisPtr = Builder.CreatePtrToInt(ThisPtr, IntPtrTy);
780 uint64_t TypeSize = Info.getNonVirtualSize().getQuantity();
781 // For each field check if it has sufficient padding,
782 // if so (un)poison it with a call.
783 for (size_t i = 0; i < SSV.size(); i++) {
784 uint64_t AsanAlignment = 8;
785 uint64_t NextField = i == SSV.size() - 1 ? TypeSize : SSV[i + 1].Offset;
786 uint64_t PoisonSize = NextField - SSV[i].Offset - SSV[i].Size;
787 uint64_t EndOffset = SSV[i].Offset + SSV[i].Size;
788 if (PoisonSize < AsanAlignment || !SSV[i].Size ||
789 (NextField % AsanAlignment) != 0)
792 F, {Builder.CreateAdd(ThisPtr, Builder.getIntN(PtrSize, EndOffset)),
793 Builder.getIntN(PtrSize, PoisonSize)});
797 /// EmitConstructorBody - Emits the body of the current constructor.
798 void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
799 EmitAsanPrologueOrEpilogue(true);
800 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
801 CXXCtorType CtorType = CurGD.getCtorType();
803 assert((CGM.getTarget().getCXXABI().hasConstructorVariants() ||
804 CtorType == Ctor_Complete) &&
805 "can only generate complete ctor for this ABI");
807 // Before we go any further, try the complete->base constructor
808 // delegation optimization.
809 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
810 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
811 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args, Ctor->getLocEnd());
815 const FunctionDecl *Definition = nullptr;
816 Stmt *Body = Ctor->getBody(Definition);
817 assert(Definition == Ctor && "emitting wrong constructor body");
819 // Enter the function-try-block before the constructor prologue if
821 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
823 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
825 incrementProfileCounter(Body);
827 RunCleanupsScope RunCleanups(*this);
829 // TODO: in restricted cases, we can emit the vbase initializers of
830 // a complete ctor and then delegate to the base ctor.
832 // Emit the constructor prologue, i.e. the base and member
834 EmitCtorPrologue(Ctor, CtorType, Args);
836 // Emit the body of the statement.
838 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
842 // Emit any cleanup blocks associated with the member or base
843 // initializers, which includes (along the exceptional path) the
844 // destructors for those members and bases that were fully
846 RunCleanups.ForceCleanup();
849 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
853 /// RAII object to indicate that codegen is copying the value representation
854 /// instead of the object representation. Useful when copying a struct or
855 /// class which has uninitialized members and we're only performing
856 /// lvalue-to-rvalue conversion on the object but not its members.
857 class CopyingValueRepresentation {
859 explicit CopyingValueRepresentation(CodeGenFunction &CGF)
860 : CGF(CGF), OldSanOpts(CGF.SanOpts) {
861 CGF.SanOpts.set(SanitizerKind::Bool, false);
862 CGF.SanOpts.set(SanitizerKind::Enum, false);
864 ~CopyingValueRepresentation() {
865 CGF.SanOpts = OldSanOpts;
868 CodeGenFunction &CGF;
869 SanitizerSet OldSanOpts;
871 } // end anonymous namespace
874 class FieldMemcpyizer {
876 FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl,
877 const VarDecl *SrcRec)
878 : CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec),
879 RecLayout(CGF.getContext().getASTRecordLayout(ClassDecl)),
880 FirstField(nullptr), LastField(nullptr), FirstFieldOffset(0),
881 LastFieldOffset(0), LastAddedFieldIndex(0) {}
883 bool isMemcpyableField(FieldDecl *F) const {
884 // Never memcpy fields when we are adding poisoned paddings.
885 if (CGF.getContext().getLangOpts().SanitizeAddressFieldPadding)
887 Qualifiers Qual = F->getType().getQualifiers();
888 if (Qual.hasVolatile() || Qual.hasObjCLifetime())
893 void addMemcpyableField(FieldDecl *F) {
900 CharUnits getMemcpySize(uint64_t FirstByteOffset) const {
901 unsigned LastFieldSize =
902 LastField->isBitField() ?
903 LastField->getBitWidthValue(CGF.getContext()) :
904 CGF.getContext().getTypeSize(LastField->getType());
905 uint64_t MemcpySizeBits =
906 LastFieldOffset + LastFieldSize - FirstByteOffset +
907 CGF.getContext().getCharWidth() - 1;
908 CharUnits MemcpySize =
909 CGF.getContext().toCharUnitsFromBits(MemcpySizeBits);
914 // Give the subclass a chance to bail out if it feels the memcpy isn't
915 // worth it (e.g. Hasn't aggregated enough data).
920 uint64_t FirstByteOffset;
921 if (FirstField->isBitField()) {
922 const CGRecordLayout &RL =
923 CGF.getTypes().getCGRecordLayout(FirstField->getParent());
924 const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField);
925 // FirstFieldOffset is not appropriate for bitfields,
926 // we need to use the storage offset instead.
927 FirstByteOffset = CGF.getContext().toBits(BFInfo.StorageOffset);
929 FirstByteOffset = FirstFieldOffset;
932 CharUnits MemcpySize = getMemcpySize(FirstByteOffset);
933 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
934 Address ThisPtr = CGF.LoadCXXThisAddress();
935 LValue DestLV = CGF.MakeAddrLValue(ThisPtr, RecordTy);
936 LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField);
937 llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec));
938 LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
939 LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField);
941 emitMemcpyIR(Dest.isBitField() ? Dest.getBitFieldAddress() : Dest.getAddress(),
942 Src.isBitField() ? Src.getBitFieldAddress() : Src.getAddress(),
948 FirstField = nullptr;
952 CodeGenFunction &CGF;
953 const CXXRecordDecl *ClassDecl;
956 void emitMemcpyIR(Address DestPtr, Address SrcPtr, CharUnits Size) {
957 llvm::PointerType *DPT = DestPtr.getType();
959 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), DPT->getAddressSpace());
960 DestPtr = CGF.Builder.CreateBitCast(DestPtr, DBP);
962 llvm::PointerType *SPT = SrcPtr.getType();
964 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), SPT->getAddressSpace());
965 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, SBP);
967 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity());
970 void addInitialField(FieldDecl *F) {
973 FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex());
974 LastFieldOffset = FirstFieldOffset;
975 LastAddedFieldIndex = F->getFieldIndex();
978 void addNextField(FieldDecl *F) {
979 // For the most part, the following invariant will hold:
980 // F->getFieldIndex() == LastAddedFieldIndex + 1
981 // The one exception is that Sema won't add a copy-initializer for an
982 // unnamed bitfield, which will show up here as a gap in the sequence.
983 assert(F->getFieldIndex() >= LastAddedFieldIndex + 1 &&
984 "Cannot aggregate fields out of order.");
985 LastAddedFieldIndex = F->getFieldIndex();
987 // The 'first' and 'last' fields are chosen by offset, rather than field
988 // index. This allows the code to support bitfields, as well as regular
990 uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex());
991 if (FOffset < FirstFieldOffset) {
993 FirstFieldOffset = FOffset;
994 } else if (FOffset > LastFieldOffset) {
996 LastFieldOffset = FOffset;
1000 const VarDecl *SrcRec;
1001 const ASTRecordLayout &RecLayout;
1002 FieldDecl *FirstField;
1003 FieldDecl *LastField;
1004 uint64_t FirstFieldOffset, LastFieldOffset;
1005 unsigned LastAddedFieldIndex;
1008 class ConstructorMemcpyizer : public FieldMemcpyizer {
1010 /// Get source argument for copy constructor. Returns null if not a copy
1012 static const VarDecl *getTrivialCopySource(CodeGenFunction &CGF,
1013 const CXXConstructorDecl *CD,
1014 FunctionArgList &Args) {
1015 if (CD->isCopyOrMoveConstructor() && CD->isDefaulted())
1016 return Args[CGF.CGM.getCXXABI().getSrcArgforCopyCtor(CD, Args)];
1020 // Returns true if a CXXCtorInitializer represents a member initialization
1021 // that can be rolled into a memcpy.
1022 bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const {
1023 if (!MemcpyableCtor)
1025 FieldDecl *Field = MemberInit->getMember();
1026 assert(Field && "No field for member init.");
1027 QualType FieldType = Field->getType();
1028 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
1030 // Bail out on non-memcpyable, not-trivially-copyable members.
1031 if (!(CE && isMemcpyEquivalentSpecialMember(CE->getConstructor())) &&
1032 !(FieldType.isTriviallyCopyableType(CGF.getContext()) ||
1033 FieldType->isReferenceType()))
1036 // Bail out on volatile fields.
1037 if (!isMemcpyableField(Field))
1040 // Otherwise we're good.
1045 ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD,
1046 FunctionArgList &Args)
1047 : FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CGF, CD, Args)),
1048 ConstructorDecl(CD),
1049 MemcpyableCtor(CD->isDefaulted() &&
1050 CD->isCopyOrMoveConstructor() &&
1051 CGF.getLangOpts().getGC() == LangOptions::NonGC),
1054 void addMemberInitializer(CXXCtorInitializer *MemberInit) {
1055 if (isMemberInitMemcpyable(MemberInit)) {
1056 AggregatedInits.push_back(MemberInit);
1057 addMemcpyableField(MemberInit->getMember());
1059 emitAggregatedInits();
1060 EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit,
1061 ConstructorDecl, Args);
1065 void emitAggregatedInits() {
1066 if (AggregatedInits.size() <= 1) {
1067 // This memcpy is too small to be worthwhile. Fall back on default
1069 if (!AggregatedInits.empty()) {
1070 CopyingValueRepresentation CVR(CGF);
1071 EmitMemberInitializer(CGF, ConstructorDecl->getParent(),
1072 AggregatedInits[0], ConstructorDecl, Args);
1073 AggregatedInits.clear();
1079 pushEHDestructors();
1081 AggregatedInits.clear();
1084 void pushEHDestructors() {
1085 Address ThisPtr = CGF.LoadCXXThisAddress();
1086 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
1087 LValue LHS = CGF.MakeAddrLValue(ThisPtr, RecordTy);
1089 for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
1090 CXXCtorInitializer *MemberInit = AggregatedInits[i];
1091 QualType FieldType = MemberInit->getAnyMember()->getType();
1092 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
1093 if (!CGF.needsEHCleanup(dtorKind))
1095 LValue FieldLHS = LHS;
1096 EmitLValueForAnyFieldInitialization(CGF, MemberInit, FieldLHS);
1097 CGF.pushEHDestroy(dtorKind, FieldLHS.getAddress(), FieldType);
1102 emitAggregatedInits();
1106 const CXXConstructorDecl *ConstructorDecl;
1107 bool MemcpyableCtor;
1108 FunctionArgList &Args;
1109 SmallVector<CXXCtorInitializer*, 16> AggregatedInits;
1112 class AssignmentMemcpyizer : public FieldMemcpyizer {
1114 // Returns the memcpyable field copied by the given statement, if one
1115 // exists. Otherwise returns null.
1116 FieldDecl *getMemcpyableField(Stmt *S) {
1117 if (!AssignmentsMemcpyable)
1119 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
1120 // Recognise trivial assignments.
1121 if (BO->getOpcode() != BO_Assign)
1123 MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS());
1126 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1127 if (!Field || !isMemcpyableField(Field))
1129 Stmt *RHS = BO->getRHS();
1130 if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS))
1131 RHS = EC->getSubExpr();
1134 MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS);
1135 if (dyn_cast<FieldDecl>(ME2->getMemberDecl()) != Field)
1138 } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) {
1139 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl());
1140 if (!(MD && isMemcpyEquivalentSpecialMember(MD)))
1142 MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument());
1145 FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl());
1146 if (!Field || !isMemcpyableField(Field))
1148 MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0));
1149 if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl()))
1152 } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1153 FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1154 if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy)
1156 Expr *DstPtr = CE->getArg(0);
1157 if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr))
1158 DstPtr = DC->getSubExpr();
1159 UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr);
1160 if (!DUO || DUO->getOpcode() != UO_AddrOf)
1162 MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr());
1165 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1166 if (!Field || !isMemcpyableField(Field))
1168 Expr *SrcPtr = CE->getArg(1);
1169 if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr))
1170 SrcPtr = SC->getSubExpr();
1171 UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr);
1172 if (!SUO || SUO->getOpcode() != UO_AddrOf)
1174 MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr());
1175 if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl()))
1183 bool AssignmentsMemcpyable;
1184 SmallVector<Stmt*, 16> AggregatedStmts;
1187 AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD,
1188 FunctionArgList &Args)
1189 : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]),
1190 AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) {
1191 assert(Args.size() == 2);
1194 void emitAssignment(Stmt *S) {
1195 FieldDecl *F = getMemcpyableField(S);
1197 addMemcpyableField(F);
1198 AggregatedStmts.push_back(S);
1200 emitAggregatedStmts();
1205 void emitAggregatedStmts() {
1206 if (AggregatedStmts.size() <= 1) {
1207 if (!AggregatedStmts.empty()) {
1208 CopyingValueRepresentation CVR(CGF);
1209 CGF.EmitStmt(AggregatedStmts[0]);
1215 AggregatedStmts.clear();
1219 emitAggregatedStmts();
1222 } // end anonymous namespace
1224 static bool isInitializerOfDynamicClass(const CXXCtorInitializer *BaseInit) {
1225 const Type *BaseType = BaseInit->getBaseClass();
1226 const auto *BaseClassDecl =
1227 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
1228 return BaseClassDecl->isDynamicClass();
1231 /// EmitCtorPrologue - This routine generates necessary code to initialize
1232 /// base classes and non-static data members belonging to this constructor.
1233 void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
1234 CXXCtorType CtorType,
1235 FunctionArgList &Args) {
1236 if (CD->isDelegatingConstructor())
1237 return EmitDelegatingCXXConstructorCall(CD, Args);
1239 const CXXRecordDecl *ClassDecl = CD->getParent();
1241 CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
1244 llvm::BasicBlock *BaseCtorContinueBB = nullptr;
1245 if (ClassDecl->getNumVBases() &&
1246 !CGM.getTarget().getCXXABI().hasConstructorVariants()) {
1247 // The ABIs that don't have constructor variants need to put a branch
1248 // before the virtual base initialization code.
1249 BaseCtorContinueBB =
1250 CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this, ClassDecl);
1251 assert(BaseCtorContinueBB);
1254 llvm::Value *const OldThis = CXXThisValue;
1255 // Virtual base initializers first.
1256 for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
1257 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1258 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1259 isInitializerOfDynamicClass(*B))
1260 CXXThisValue = Builder.CreateInvariantGroupBarrier(LoadCXXThis());
1261 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
1264 if (BaseCtorContinueBB) {
1265 // Complete object handler should continue to the remaining initializers.
1266 Builder.CreateBr(BaseCtorContinueBB);
1267 EmitBlock(BaseCtorContinueBB);
1270 // Then, non-virtual base initializers.
1271 for (; B != E && (*B)->isBaseInitializer(); B++) {
1272 assert(!(*B)->isBaseVirtual());
1274 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1275 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1276 isInitializerOfDynamicClass(*B))
1277 CXXThisValue = Builder.CreateInvariantGroupBarrier(LoadCXXThis());
1278 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
1281 CXXThisValue = OldThis;
1283 InitializeVTablePointers(ClassDecl);
1285 // And finally, initialize class members.
1286 FieldConstructionScope FCS(*this, LoadCXXThisAddress());
1287 ConstructorMemcpyizer CM(*this, CD, Args);
1288 for (; B != E; B++) {
1289 CXXCtorInitializer *Member = (*B);
1290 assert(!Member->isBaseInitializer());
1291 assert(Member->isAnyMemberInitializer() &&
1292 "Delegating initializer on non-delegating constructor");
1293 CM.addMemberInitializer(Member);
1299 FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
1302 HasTrivialDestructorBody(ASTContext &Context,
1303 const CXXRecordDecl *BaseClassDecl,
1304 const CXXRecordDecl *MostDerivedClassDecl)
1306 // If the destructor is trivial we don't have to check anything else.
1307 if (BaseClassDecl->hasTrivialDestructor())
1310 if (!BaseClassDecl->getDestructor()->hasTrivialBody())
1314 for (const auto *Field : BaseClassDecl->fields())
1315 if (!FieldHasTrivialDestructorBody(Context, Field))
1318 // Check non-virtual bases.
1319 for (const auto &I : BaseClassDecl->bases()) {
1323 const CXXRecordDecl *NonVirtualBase =
1324 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
1325 if (!HasTrivialDestructorBody(Context, NonVirtualBase,
1326 MostDerivedClassDecl))
1330 if (BaseClassDecl == MostDerivedClassDecl) {
1331 // Check virtual bases.
1332 for (const auto &I : BaseClassDecl->vbases()) {
1333 const CXXRecordDecl *VirtualBase =
1334 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
1335 if (!HasTrivialDestructorBody(Context, VirtualBase,
1336 MostDerivedClassDecl))
1345 FieldHasTrivialDestructorBody(ASTContext &Context,
1346 const FieldDecl *Field)
1348 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
1350 const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
1354 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1356 // The destructor for an implicit anonymous union member is never invoked.
1357 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
1360 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
1363 /// CanSkipVTablePointerInitialization - Check whether we need to initialize
1364 /// any vtable pointers before calling this destructor.
1365 static bool CanSkipVTablePointerInitialization(CodeGenFunction &CGF,
1366 const CXXDestructorDecl *Dtor) {
1367 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1368 if (!ClassDecl->isDynamicClass())
1371 if (!Dtor->hasTrivialBody())
1374 // Check the fields.
1375 for (const auto *Field : ClassDecl->fields())
1376 if (!FieldHasTrivialDestructorBody(CGF.getContext(), Field))
1382 /// EmitDestructorBody - Emits the body of the current destructor.
1383 void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
1384 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
1385 CXXDtorType DtorType = CurGD.getDtorType();
1387 Stmt *Body = Dtor->getBody();
1389 incrementProfileCounter(Body);
1391 // The call to operator delete in a deleting destructor happens
1392 // outside of the function-try-block, which means it's always
1393 // possible to delegate the destructor body to the complete
1394 // destructor. Do so.
1395 if (DtorType == Dtor_Deleting) {
1396 EnterDtorCleanups(Dtor, Dtor_Deleting);
1397 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
1398 /*Delegating=*/false, LoadCXXThisAddress());
1403 // If the body is a function-try-block, enter the try before
1405 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
1407 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
1408 EmitAsanPrologueOrEpilogue(false);
1410 // Enter the epilogue cleanups.
1411 RunCleanupsScope DtorEpilogue(*this);
1413 // If this is the complete variant, just invoke the base variant;
1414 // the epilogue will destruct the virtual bases. But we can't do
1415 // this optimization if the body is a function-try-block, because
1416 // we'd introduce *two* handler blocks. In the Microsoft ABI, we
1417 // always delegate because we might not have a definition in this TU.
1420 llvm_unreachable("not expecting a COMDAT");
1422 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
1425 assert((Body || getTarget().getCXXABI().isMicrosoft()) &&
1426 "can't emit a dtor without a body for non-Microsoft ABIs");
1428 // Enter the cleanup scopes for virtual bases.
1429 EnterDtorCleanups(Dtor, Dtor_Complete);
1432 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
1433 /*Delegating=*/false, LoadCXXThisAddress());
1436 // Fallthrough: act like we're in the base variant.
1441 // Enter the cleanup scopes for fields and non-virtual bases.
1442 EnterDtorCleanups(Dtor, Dtor_Base);
1444 // Initialize the vtable pointers before entering the body.
1445 if (!CanSkipVTablePointerInitialization(*this, Dtor)) {
1446 // Insert the llvm.invariant.group.barrier intrinsic before initializing
1447 // the vptrs to cancel any previous assumptions we might have made.
1448 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1449 CGM.getCodeGenOpts().OptimizationLevel > 0)
1450 CXXThisValue = Builder.CreateInvariantGroupBarrier(LoadCXXThis());
1451 InitializeVTablePointers(Dtor->getParent());
1455 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
1459 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
1460 // nothing to do besides what's in the epilogue
1462 // -fapple-kext must inline any call to this dtor into
1463 // the caller's body.
1464 if (getLangOpts().AppleKext)
1465 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
1470 // Jump out through the epilogue cleanups.
1471 DtorEpilogue.ForceCleanup();
1473 // Exit the try if applicable.
1475 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
1478 void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) {
1479 const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
1480 const Stmt *RootS = AssignOp->getBody();
1481 assert(isa<CompoundStmt>(RootS) &&
1482 "Body of an implicit assignment operator should be compound stmt.");
1483 const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
1485 LexicalScope Scope(*this, RootCS->getSourceRange());
1487 incrementProfileCounter(RootCS);
1488 AssignmentMemcpyizer AM(*this, AssignOp, Args);
1489 for (auto *I : RootCS->body())
1490 AM.emitAssignment(I);
1495 /// Call the operator delete associated with the current destructor.
1496 struct CallDtorDelete final : EHScopeStack::Cleanup {
1499 void Emit(CodeGenFunction &CGF, Flags flags) override {
1500 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1501 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1502 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1503 CGF.getContext().getTagDeclType(ClassDecl));
1507 struct CallDtorDeleteConditional final : EHScopeStack::Cleanup {
1508 llvm::Value *ShouldDeleteCondition;
1511 CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
1512 : ShouldDeleteCondition(ShouldDeleteCondition) {
1513 assert(ShouldDeleteCondition != nullptr);
1516 void Emit(CodeGenFunction &CGF, Flags flags) override {
1517 llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
1518 llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
1519 llvm::Value *ShouldCallDelete
1520 = CGF.Builder.CreateIsNull(ShouldDeleteCondition);
1521 CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
1523 CGF.EmitBlock(callDeleteBB);
1524 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1525 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1526 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1527 CGF.getContext().getTagDeclType(ClassDecl));
1528 CGF.Builder.CreateBr(continueBB);
1530 CGF.EmitBlock(continueBB);
1534 class DestroyField final : public EHScopeStack::Cleanup {
1535 const FieldDecl *field;
1536 CodeGenFunction::Destroyer *destroyer;
1537 bool useEHCleanupForArray;
1540 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
1541 bool useEHCleanupForArray)
1542 : field(field), destroyer(destroyer),
1543 useEHCleanupForArray(useEHCleanupForArray) {}
1545 void Emit(CodeGenFunction &CGF, Flags flags) override {
1546 // Find the address of the field.
1547 Address thisValue = CGF.LoadCXXThisAddress();
1548 QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
1549 LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
1550 LValue LV = CGF.EmitLValueForField(ThisLV, field);
1551 assert(LV.isSimple());
1553 CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
1554 flags.isForNormalCleanup() && useEHCleanupForArray);
1558 static void EmitSanitizerDtorCallback(CodeGenFunction &CGF, llvm::Value *Ptr,
1559 CharUnits::QuantityType PoisonSize) {
1560 // Pass in void pointer and size of region as arguments to runtime
1562 llvm::Value *Args[] = {CGF.Builder.CreateBitCast(Ptr, CGF.VoidPtrTy),
1563 llvm::ConstantInt::get(CGF.SizeTy, PoisonSize)};
1565 llvm::Type *ArgTypes[] = {CGF.VoidPtrTy, CGF.SizeTy};
1567 llvm::FunctionType *FnType =
1568 llvm::FunctionType::get(CGF.VoidTy, ArgTypes, false);
1570 CGF.CGM.CreateRuntimeFunction(FnType, "__sanitizer_dtor_callback");
1571 CGF.EmitNounwindRuntimeCall(Fn, Args);
1574 class SanitizeDtorMembers final : public EHScopeStack::Cleanup {
1575 const CXXDestructorDecl *Dtor;
1578 SanitizeDtorMembers(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
1580 // Generate function call for handling object poisoning.
1581 // Disables tail call elimination, to prevent the current stack frame
1582 // from disappearing from the stack trace.
1583 void Emit(CodeGenFunction &CGF, Flags flags) override {
1584 const ASTRecordLayout &Layout =
1585 CGF.getContext().getASTRecordLayout(Dtor->getParent());
1587 // Nothing to poison.
1588 if (Layout.getFieldCount() == 0)
1591 // Prevent the current stack frame from disappearing from the stack trace.
1592 CGF.CurFn->addFnAttr("disable-tail-calls", "true");
1594 // Construct pointer to region to begin poisoning, and calculate poison
1595 // size, so that only members declared in this class are poisoned.
1596 ASTContext &Context = CGF.getContext();
1597 unsigned fieldIndex = 0;
1598 int startIndex = -1;
1599 // RecordDecl::field_iterator Field;
1600 for (const FieldDecl *Field : Dtor->getParent()->fields()) {
1601 // Poison field if it is trivial
1602 if (FieldHasTrivialDestructorBody(Context, Field)) {
1603 // Start sanitizing at this field
1605 startIndex = fieldIndex;
1607 // Currently on the last field, and it must be poisoned with the
1609 if (fieldIndex == Layout.getFieldCount() - 1) {
1610 PoisonMembers(CGF, startIndex, Layout.getFieldCount());
1612 } else if (startIndex >= 0) {
1613 // No longer within a block of memory to poison, so poison the block
1614 PoisonMembers(CGF, startIndex, fieldIndex);
1615 // Re-set the start index
1623 /// \param layoutStartOffset index of the ASTRecordLayout field to
1624 /// start poisoning (inclusive)
1625 /// \param layoutEndOffset index of the ASTRecordLayout field to
1626 /// end poisoning (exclusive)
1627 void PoisonMembers(CodeGenFunction &CGF, unsigned layoutStartOffset,
1628 unsigned layoutEndOffset) {
1629 ASTContext &Context = CGF.getContext();
1630 const ASTRecordLayout &Layout =
1631 Context.getASTRecordLayout(Dtor->getParent());
1633 llvm::ConstantInt *OffsetSizePtr = llvm::ConstantInt::get(
1635 Context.toCharUnitsFromBits(Layout.getFieldOffset(layoutStartOffset))
1638 llvm::Value *OffsetPtr = CGF.Builder.CreateGEP(
1639 CGF.Builder.CreateBitCast(CGF.LoadCXXThis(), CGF.Int8PtrTy),
1642 CharUnits::QuantityType PoisonSize;
1643 if (layoutEndOffset >= Layout.getFieldCount()) {
1644 PoisonSize = Layout.getNonVirtualSize().getQuantity() -
1645 Context.toCharUnitsFromBits(
1646 Layout.getFieldOffset(layoutStartOffset))
1649 PoisonSize = Context.toCharUnitsFromBits(
1650 Layout.getFieldOffset(layoutEndOffset) -
1651 Layout.getFieldOffset(layoutStartOffset))
1655 if (PoisonSize == 0)
1658 EmitSanitizerDtorCallback(CGF, OffsetPtr, PoisonSize);
1662 class SanitizeDtorVTable final : public EHScopeStack::Cleanup {
1663 const CXXDestructorDecl *Dtor;
1666 SanitizeDtorVTable(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
1668 // Generate function call for handling vtable pointer poisoning.
1669 void Emit(CodeGenFunction &CGF, Flags flags) override {
1670 assert(Dtor->getParent()->isDynamicClass());
1672 ASTContext &Context = CGF.getContext();
1673 // Poison vtable and vtable ptr if they exist for this class.
1674 llvm::Value *VTablePtr = CGF.LoadCXXThis();
1676 CharUnits::QuantityType PoisonSize =
1677 Context.toCharUnitsFromBits(CGF.PointerWidthInBits).getQuantity();
1678 // Pass in void pointer and size of region as arguments to runtime
1680 EmitSanitizerDtorCallback(CGF, VTablePtr, PoisonSize);
1683 } // end anonymous namespace
1685 /// \brief Emit all code that comes at the end of class's
1686 /// destructor. This is to call destructors on members and base classes
1687 /// in reverse order of their construction.
1688 void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
1689 CXXDtorType DtorType) {
1690 assert((!DD->isTrivial() || DD->hasAttr<DLLExportAttr>()) &&
1691 "Should not emit dtor epilogue for non-exported trivial dtor!");
1693 // The deleting-destructor phase just needs to call the appropriate
1694 // operator delete that Sema picked up.
1695 if (DtorType == Dtor_Deleting) {
1696 assert(DD->getOperatorDelete() &&
1697 "operator delete missing - EnterDtorCleanups");
1698 if (CXXStructorImplicitParamValue) {
1699 // If there is an implicit param to the deleting dtor, it's a boolean
1700 // telling whether we should call delete at the end of the dtor.
1701 EHStack.pushCleanup<CallDtorDeleteConditional>(
1702 NormalAndEHCleanup, CXXStructorImplicitParamValue);
1704 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
1709 const CXXRecordDecl *ClassDecl = DD->getParent();
1711 // Unions have no bases and do not call field destructors.
1712 if (ClassDecl->isUnion())
1715 // The complete-destructor phase just destructs all the virtual bases.
1716 if (DtorType == Dtor_Complete) {
1717 // Poison the vtable pointer such that access after the base
1718 // and member destructors are invoked is invalid.
1719 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1720 SanOpts.has(SanitizerKind::Memory) && ClassDecl->getNumVBases() &&
1721 ClassDecl->isPolymorphic())
1722 EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
1724 // We push them in the forward order so that they'll be popped in
1725 // the reverse order.
1726 for (const auto &Base : ClassDecl->vbases()) {
1727 CXXRecordDecl *BaseClassDecl
1728 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1730 // Ignore trivial destructors.
1731 if (BaseClassDecl->hasTrivialDestructor())
1734 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1736 /*BaseIsVirtual*/ true);
1742 assert(DtorType == Dtor_Base);
1743 // Poison the vtable pointer if it has no virtual bases, but inherits
1744 // virtual functions.
1745 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1746 SanOpts.has(SanitizerKind::Memory) && !ClassDecl->getNumVBases() &&
1747 ClassDecl->isPolymorphic())
1748 EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
1750 // Destroy non-virtual bases.
1751 for (const auto &Base : ClassDecl->bases()) {
1752 // Ignore virtual bases.
1753 if (Base.isVirtual())
1756 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
1758 // Ignore trivial destructors.
1759 if (BaseClassDecl->hasTrivialDestructor())
1762 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1764 /*BaseIsVirtual*/ false);
1767 // Poison fields such that access after their destructors are
1768 // invoked, and before the base class destructor runs, is invalid.
1769 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1770 SanOpts.has(SanitizerKind::Memory))
1771 EHStack.pushCleanup<SanitizeDtorMembers>(NormalAndEHCleanup, DD);
1773 // Destroy direct fields.
1774 for (const auto *Field : ClassDecl->fields()) {
1775 QualType type = Field->getType();
1776 QualType::DestructionKind dtorKind = type.isDestructedType();
1777 if (!dtorKind) continue;
1779 // Anonymous union members do not have their destructors called.
1780 const RecordType *RT = type->getAsUnionType();
1781 if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
1783 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1784 EHStack.pushCleanup<DestroyField>(cleanupKind, Field,
1785 getDestroyer(dtorKind),
1786 cleanupKind & EHCleanup);
1790 /// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1791 /// constructor for each of several members of an array.
1793 /// \param ctor the constructor to call for each element
1794 /// \param arrayType the type of the array to initialize
1795 /// \param arrayBegin an arrayType*
1796 /// \param zeroInitialize true if each element should be
1797 /// zero-initialized before it is constructed
1798 void CodeGenFunction::EmitCXXAggrConstructorCall(
1799 const CXXConstructorDecl *ctor, const ArrayType *arrayType,
1800 Address arrayBegin, const CXXConstructExpr *E, bool zeroInitialize) {
1801 QualType elementType;
1802 llvm::Value *numElements =
1803 emitArrayLength(arrayType, elementType, arrayBegin);
1805 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin, E, zeroInitialize);
1808 /// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1809 /// constructor for each of several members of an array.
1811 /// \param ctor the constructor to call for each element
1812 /// \param numElements the number of elements in the array;
1814 /// \param arrayBase a T*, where T is the type constructed by ctor
1815 /// \param zeroInitialize true if each element should be
1816 /// zero-initialized before it is constructed
1817 void CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1818 llvm::Value *numElements,
1820 const CXXConstructExpr *E,
1821 bool zeroInitialize) {
1822 // It's legal for numElements to be zero. This can happen both
1823 // dynamically, because x can be zero in 'new A[x]', and statically,
1824 // because of GCC extensions that permit zero-length arrays. There
1825 // are probably legitimate places where we could assume that this
1826 // doesn't happen, but it's not clear that it's worth it.
1827 llvm::BranchInst *zeroCheckBranch = nullptr;
1829 // Optimize for a constant count.
1830 llvm::ConstantInt *constantCount
1831 = dyn_cast<llvm::ConstantInt>(numElements);
1832 if (constantCount) {
1833 // Just skip out if the constant count is zero.
1834 if (constantCount->isZero()) return;
1836 // Otherwise, emit the check.
1838 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1839 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1840 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1844 // Find the end of the array.
1845 llvm::Value *arrayBegin = arrayBase.getPointer();
1846 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1849 // Enter the loop, setting up a phi for the current location to initialize.
1850 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1851 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1853 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1855 cur->addIncoming(arrayBegin, entryBB);
1857 // Inside the loop body, emit the constructor call on the array element.
1859 // The alignment of the base, adjusted by the size of a single element,
1860 // provides a conservative estimate of the alignment of every element.
1861 // (This assumes we never start tracking offsetted alignments.)
1863 // Note that these are complete objects and so we don't need to
1864 // use the non-virtual size or alignment.
1865 QualType type = getContext().getTypeDeclType(ctor->getParent());
1866 CharUnits eltAlignment =
1867 arrayBase.getAlignment()
1868 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
1869 Address curAddr = Address(cur, eltAlignment);
1871 // Zero initialize the storage, if requested.
1873 EmitNullInitialization(curAddr, type);
1875 // C++ [class.temporary]p4:
1876 // There are two contexts in which temporaries are destroyed at a different
1877 // point than the end of the full-expression. The first context is when a
1878 // default constructor is called to initialize an element of an array.
1879 // If the constructor has one or more default arguments, the destruction of
1880 // every temporary created in a default argument expression is sequenced
1881 // before the construction of the next array element, if any.
1884 RunCleanupsScope Scope(*this);
1886 // Evaluate the constructor and its arguments in a regular
1887 // partial-destroy cleanup.
1888 if (getLangOpts().Exceptions &&
1889 !ctor->getParent()->hasTrivialDestructor()) {
1890 Destroyer *destroyer = destroyCXXObject;
1891 pushRegularPartialArrayCleanup(arrayBegin, cur, type, eltAlignment,
1895 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/false,
1896 /*Delegating=*/false, curAddr, E);
1899 // Go to the next element.
1901 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
1903 cur->addIncoming(next, Builder.GetInsertBlock());
1905 // Check whether that's the end of the loop.
1906 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
1907 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
1908 Builder.CreateCondBr(done, contBB, loopBB);
1910 // Patch the earlier check to skip over the loop.
1911 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
1916 void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
1919 const RecordType *rtype = type->castAs<RecordType>();
1920 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
1921 const CXXDestructorDecl *dtor = record->getDestructor();
1922 assert(!dtor->isTrivial());
1923 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
1924 /*Delegating=*/false, addr);
1927 void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
1929 bool ForVirtualBase,
1930 bool Delegating, Address This,
1931 const CXXConstructExpr *E) {
1934 // Push the this ptr.
1935 Args.add(RValue::get(This.getPointer()), D->getThisType(getContext()));
1937 // If this is a trivial constructor, emit a memcpy now before we lose
1938 // the alignment information on the argument.
1939 // FIXME: It would be better to preserve alignment information into CallArg.
1940 if (isMemcpyEquivalentSpecialMember(D)) {
1941 assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
1943 const Expr *Arg = E->getArg(0);
1944 QualType SrcTy = Arg->getType();
1945 Address Src = EmitLValue(Arg).getAddress();
1946 QualType DestTy = getContext().getTypeDeclType(D->getParent());
1947 EmitAggregateCopyCtor(This, Src, DestTy, SrcTy);
1951 // Add the rest of the user-supplied arguments.
1952 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
1953 EmitCallArgs(Args, FPT, E->arguments(), E->getConstructor());
1955 EmitCXXConstructorCall(D, Type, ForVirtualBase, Delegating, This, Args);
1958 static bool canEmitDelegateCallArgs(CodeGenFunction &CGF,
1959 const CXXConstructorDecl *Ctor,
1960 CXXCtorType Type, CallArgList &Args) {
1961 // We can't forward a variadic call.
1962 if (Ctor->isVariadic())
1965 if (CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
1966 // If the parameters are callee-cleanup, it's not safe to forward.
1967 for (auto *P : Ctor->parameters())
1968 if (P->getType().isDestructedType())
1971 // Likewise if they're inalloca.
1972 const CGFunctionInfo &Info =
1973 CGF.CGM.getTypes().arrangeCXXConstructorCall(Args, Ctor, Type, 0);
1974 if (Info.usesInAlloca())
1978 // Anything else should be OK.
1982 void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
1984 bool ForVirtualBase,
1987 CallArgList &Args) {
1988 const CXXRecordDecl *ClassDecl = D->getParent();
1990 // C++11 [class.mfct.non-static]p2:
1991 // If a non-static member function of a class X is called for an object that
1992 // is not of type X, or of a type derived from X, the behavior is undefined.
1993 // FIXME: Provide a source location here.
1994 EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall, SourceLocation(),
1995 This.getPointer(), getContext().getRecordType(ClassDecl));
1997 if (D->isTrivial() && D->isDefaultConstructor()) {
1998 assert(Args.size() == 1 && "trivial default ctor with args");
2002 // If this is a trivial constructor, just emit what's needed. If this is a
2003 // union copy constructor, we must emit a memcpy, because the AST does not
2005 if (isMemcpyEquivalentSpecialMember(D)) {
2006 assert(Args.size() == 2 && "unexpected argcount for trivial ctor");
2008 QualType SrcTy = D->getParamDecl(0)->getType().getNonReferenceType();
2009 Address Src(Args[1].RV.getScalarVal(), getNaturalTypeAlignment(SrcTy));
2010 QualType DestTy = getContext().getTypeDeclType(ClassDecl);
2011 EmitAggregateCopyCtor(This, Src, DestTy, SrcTy);
2015 // Check whether we can actually emit the constructor before trying to do so.
2016 if (auto Inherited = D->getInheritedConstructor()) {
2017 if (getTypes().inheritingCtorHasParams(Inherited, Type) &&
2018 !canEmitDelegateCallArgs(*this, D, Type, Args)) {
2019 EmitInlinedInheritingCXXConstructorCall(D, Type, ForVirtualBase,
2025 // Insert any ABI-specific implicit constructor arguments.
2026 unsigned ExtraArgs = CGM.getCXXABI().addImplicitConstructorArgs(
2027 *this, D, Type, ForVirtualBase, Delegating, Args);
2030 llvm::Constant *CalleePtr =
2031 CGM.getAddrOfCXXStructor(D, getFromCtorType(Type));
2032 const CGFunctionInfo &Info =
2033 CGM.getTypes().arrangeCXXConstructorCall(Args, D, Type, ExtraArgs);
2034 CGCallee Callee = CGCallee::forDirect(CalleePtr, D);
2035 EmitCall(Info, Callee, ReturnValueSlot(), Args);
2037 // Generate vtable assumptions if we're constructing a complete object
2038 // with a vtable. We don't do this for base subobjects for two reasons:
2039 // first, it's incorrect for classes with virtual bases, and second, we're
2040 // about to overwrite the vptrs anyway.
2041 // We also have to make sure if we can refer to vtable:
2042 // - Otherwise we can refer to vtable if it's safe to speculatively emit.
2043 // FIXME: If vtable is used by ctor/dtor, or if vtable is external and we are
2044 // sure that definition of vtable is not hidden,
2045 // then we are always safe to refer to it.
2046 // FIXME: It looks like InstCombine is very inefficient on dealing with
2047 // assumes. Make assumption loads require -fstrict-vtable-pointers temporarily.
2048 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2049 ClassDecl->isDynamicClass() && Type != Ctor_Base &&
2050 CGM.getCXXABI().canSpeculativelyEmitVTable(ClassDecl) &&
2051 CGM.getCodeGenOpts().StrictVTablePointers)
2052 EmitVTableAssumptionLoads(ClassDecl, This);
2055 void CodeGenFunction::EmitInheritedCXXConstructorCall(
2056 const CXXConstructorDecl *D, bool ForVirtualBase, Address This,
2057 bool InheritedFromVBase, const CXXInheritedCtorInitExpr *E) {
2059 CallArg ThisArg(RValue::get(This.getPointer()), D->getThisType(getContext()),
2060 /*NeedsCopy=*/false);
2062 // Forward the parameters.
2063 if (InheritedFromVBase &&
2064 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
2065 // Nothing to do; this construction is not responsible for constructing
2066 // the base class containing the inherited constructor.
2067 // FIXME: Can we just pass undef's for the remaining arguments if we don't
2068 // have constructor variants?
2069 Args.push_back(ThisArg);
2070 } else if (!CXXInheritedCtorInitExprArgs.empty()) {
2071 // The inheriting constructor was inlined; just inject its arguments.
2072 assert(CXXInheritedCtorInitExprArgs.size() >= D->getNumParams() &&
2073 "wrong number of parameters for inherited constructor call");
2074 Args = CXXInheritedCtorInitExprArgs;
2077 // The inheriting constructor was not inlined. Emit delegating arguments.
2078 Args.push_back(ThisArg);
2079 const auto *OuterCtor = cast<CXXConstructorDecl>(CurCodeDecl);
2080 assert(OuterCtor->getNumParams() == D->getNumParams());
2081 assert(!OuterCtor->isVariadic() && "should have been inlined");
2083 for (const auto *Param : OuterCtor->parameters()) {
2084 assert(getContext().hasSameUnqualifiedType(
2085 OuterCtor->getParamDecl(Param->getFunctionScopeIndex())->getType(),
2087 EmitDelegateCallArg(Args, Param, E->getLocation());
2089 // Forward __attribute__(pass_object_size).
2090 if (Param->hasAttr<PassObjectSizeAttr>()) {
2091 auto *POSParam = SizeArguments[Param];
2092 assert(POSParam && "missing pass_object_size value for forwarding");
2093 EmitDelegateCallArg(Args, POSParam, E->getLocation());
2098 EmitCXXConstructorCall(D, Ctor_Base, ForVirtualBase, /*Delegating*/false,
2102 void CodeGenFunction::EmitInlinedInheritingCXXConstructorCall(
2103 const CXXConstructorDecl *Ctor, CXXCtorType CtorType, bool ForVirtualBase,
2104 bool Delegating, CallArgList &Args) {
2105 InlinedInheritingConstructorScope Scope(*this, GlobalDecl(Ctor, CtorType));
2107 // Save the arguments to be passed to the inherited constructor.
2108 CXXInheritedCtorInitExprArgs = Args;
2110 FunctionArgList Params;
2111 QualType RetType = BuildFunctionArgList(CurGD, Params);
2114 // Insert any ABI-specific implicit constructor arguments.
2115 CGM.getCXXABI().addImplicitConstructorArgs(*this, Ctor, CtorType,
2116 ForVirtualBase, Delegating, Args);
2118 // Emit a simplified prolog. We only need to emit the implicit params.
2119 assert(Args.size() >= Params.size() && "too few arguments for call");
2120 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2121 if (I < Params.size() && isa<ImplicitParamDecl>(Params[I])) {
2122 const RValue &RV = Args[I].RV;
2123 assert(!RV.isComplex() && "complex indirect params not supported");
2124 ParamValue Val = RV.isScalar()
2125 ? ParamValue::forDirect(RV.getScalarVal())
2126 : ParamValue::forIndirect(RV.getAggregateAddress());
2127 EmitParmDecl(*Params[I], Val, I + 1);
2131 // Create a return value slot if the ABI implementation wants one.
2132 // FIXME: This is dumb, we should ask the ABI not to try to set the return
2134 if (!RetType->isVoidType())
2135 ReturnValue = CreateIRTemp(RetType, "retval.inhctor");
2137 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
2138 CXXThisValue = CXXABIThisValue;
2140 // Directly emit the constructor initializers.
2141 EmitCtorPrologue(Ctor, CtorType, Params);
2144 void CodeGenFunction::EmitVTableAssumptionLoad(const VPtr &Vptr, Address This) {
2145 llvm::Value *VTableGlobal =
2146 CGM.getCXXABI().getVTableAddressPoint(Vptr.Base, Vptr.VTableClass);
2150 // We can just use the base offset in the complete class.
2151 CharUnits NonVirtualOffset = Vptr.Base.getBaseOffset();
2153 if (!NonVirtualOffset.isZero())
2155 ApplyNonVirtualAndVirtualOffset(*this, This, NonVirtualOffset, nullptr,
2156 Vptr.VTableClass, Vptr.NearestVBase);
2158 llvm::Value *VPtrValue =
2159 GetVTablePtr(This, VTableGlobal->getType(), Vptr.VTableClass);
2161 Builder.CreateICmpEQ(VPtrValue, VTableGlobal, "cmp.vtables");
2162 Builder.CreateAssumption(Cmp);
2165 void CodeGenFunction::EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl,
2167 if (CGM.getCXXABI().doStructorsInitializeVPtrs(ClassDecl))
2168 for (const VPtr &Vptr : getVTablePointers(ClassDecl))
2169 EmitVTableAssumptionLoad(Vptr, This);
2173 CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
2174 Address This, Address Src,
2175 const CXXConstructExpr *E) {
2176 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
2180 // Push the this ptr.
2181 Args.add(RValue::get(This.getPointer()), D->getThisType(getContext()));
2183 // Push the src ptr.
2184 QualType QT = *(FPT->param_type_begin());
2185 llvm::Type *t = CGM.getTypes().ConvertType(QT);
2186 Src = Builder.CreateBitCast(Src, t);
2187 Args.add(RValue::get(Src.getPointer()), QT);
2189 // Skip over first argument (Src).
2190 EmitCallArgs(Args, FPT, drop_begin(E->arguments(), 1), E->getConstructor(),
2191 /*ParamsToSkip*/ 1);
2193 EmitCXXConstructorCall(D, Ctor_Complete, false, false, This, Args);
2197 CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
2198 CXXCtorType CtorType,
2199 const FunctionArgList &Args,
2200 SourceLocation Loc) {
2201 CallArgList DelegateArgs;
2203 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
2204 assert(I != E && "no parameters to constructor");
2207 Address This = LoadCXXThisAddress();
2208 DelegateArgs.add(RValue::get(This.getPointer()), (*I)->getType());
2211 // FIXME: The location of the VTT parameter in the parameter list is
2212 // specific to the Itanium ABI and shouldn't be hardcoded here.
2213 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
2214 assert(I != E && "cannot skip vtt parameter, already done with args");
2215 assert((*I)->getType()->isPointerType() &&
2216 "skipping parameter not of vtt type");
2220 // Explicit arguments.
2221 for (; I != E; ++I) {
2222 const VarDecl *param = *I;
2223 // FIXME: per-argument source location
2224 EmitDelegateCallArg(DelegateArgs, param, Loc);
2227 EmitCXXConstructorCall(Ctor, CtorType, /*ForVirtualBase=*/false,
2228 /*Delegating=*/true, This, DelegateArgs);
2232 struct CallDelegatingCtorDtor final : EHScopeStack::Cleanup {
2233 const CXXDestructorDecl *Dtor;
2237 CallDelegatingCtorDtor(const CXXDestructorDecl *D, Address Addr,
2239 : Dtor(D), Addr(Addr), Type(Type) {}
2241 void Emit(CodeGenFunction &CGF, Flags flags) override {
2242 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
2243 /*Delegating=*/true, Addr);
2246 } // end anonymous namespace
2249 CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
2250 const FunctionArgList &Args) {
2251 assert(Ctor->isDelegatingConstructor());
2253 Address ThisPtr = LoadCXXThisAddress();
2255 AggValueSlot AggSlot =
2256 AggValueSlot::forAddr(ThisPtr, Qualifiers(),
2257 AggValueSlot::IsDestructed,
2258 AggValueSlot::DoesNotNeedGCBarriers,
2259 AggValueSlot::IsNotAliased);
2261 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
2263 const CXXRecordDecl *ClassDecl = Ctor->getParent();
2264 if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
2266 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
2268 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
2269 ClassDecl->getDestructor(),
2274 void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
2276 bool ForVirtualBase,
2279 CGM.getCXXABI().EmitDestructorCall(*this, DD, Type, ForVirtualBase,
2284 struct CallLocalDtor final : EHScopeStack::Cleanup {
2285 const CXXDestructorDecl *Dtor;
2288 CallLocalDtor(const CXXDestructorDecl *D, Address Addr)
2289 : Dtor(D), Addr(Addr) {}
2291 void Emit(CodeGenFunction &CGF, Flags flags) override {
2292 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
2293 /*ForVirtualBase=*/false,
2294 /*Delegating=*/false, Addr);
2297 } // end anonymous namespace
2299 void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
2301 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
2304 void CodeGenFunction::PushDestructorCleanup(QualType T, Address Addr) {
2305 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
2306 if (!ClassDecl) return;
2307 if (ClassDecl->hasTrivialDestructor()) return;
2309 const CXXDestructorDecl *D = ClassDecl->getDestructor();
2310 assert(D && D->isUsed() && "destructor not marked as used!");
2311 PushDestructorCleanup(D, Addr);
2314 void CodeGenFunction::InitializeVTablePointer(const VPtr &Vptr) {
2315 // Compute the address point.
2316 llvm::Value *VTableAddressPoint =
2317 CGM.getCXXABI().getVTableAddressPointInStructor(
2318 *this, Vptr.VTableClass, Vptr.Base, Vptr.NearestVBase);
2320 if (!VTableAddressPoint)
2323 // Compute where to store the address point.
2324 llvm::Value *VirtualOffset = nullptr;
2325 CharUnits NonVirtualOffset = CharUnits::Zero();
2327 if (CGM.getCXXABI().isVirtualOffsetNeededForVTableField(*this, Vptr)) {
2328 // We need to use the virtual base offset offset because the virtual base
2329 // might have a different offset in the most derived class.
2331 VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(
2332 *this, LoadCXXThisAddress(), Vptr.VTableClass, Vptr.NearestVBase);
2333 NonVirtualOffset = Vptr.OffsetFromNearestVBase;
2335 // We can just use the base offset in the complete class.
2336 NonVirtualOffset = Vptr.Base.getBaseOffset();
2339 // Apply the offsets.
2340 Address VTableField = LoadCXXThisAddress();
2342 if (!NonVirtualOffset.isZero() || VirtualOffset)
2343 VTableField = ApplyNonVirtualAndVirtualOffset(
2344 *this, VTableField, NonVirtualOffset, VirtualOffset, Vptr.VTableClass,
2347 // Finally, store the address point. Use the same LLVM types as the field to
2348 // support optimization.
2349 llvm::Type *VTablePtrTy =
2350 llvm::FunctionType::get(CGM.Int32Ty, /*isVarArg=*/true)
2353 VTableField = Builder.CreateBitCast(VTableField, VTablePtrTy->getPointerTo());
2354 VTableAddressPoint = Builder.CreateBitCast(VTableAddressPoint, VTablePtrTy);
2356 llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
2357 CGM.DecorateInstructionWithTBAA(Store, CGM.getTBAAInfoForVTablePtr());
2358 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2359 CGM.getCodeGenOpts().StrictVTablePointers)
2360 CGM.DecorateInstructionWithInvariantGroup(Store, Vptr.VTableClass);
2363 CodeGenFunction::VPtrsVector
2364 CodeGenFunction::getVTablePointers(const CXXRecordDecl *VTableClass) {
2365 CodeGenFunction::VPtrsVector VPtrsResult;
2366 VisitedVirtualBasesSetTy VBases;
2367 getVTablePointers(BaseSubobject(VTableClass, CharUnits::Zero()),
2368 /*NearestVBase=*/nullptr,
2369 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
2370 /*BaseIsNonVirtualPrimaryBase=*/false, VTableClass, VBases,
2375 void CodeGenFunction::getVTablePointers(BaseSubobject Base,
2376 const CXXRecordDecl *NearestVBase,
2377 CharUnits OffsetFromNearestVBase,
2378 bool BaseIsNonVirtualPrimaryBase,
2379 const CXXRecordDecl *VTableClass,
2380 VisitedVirtualBasesSetTy &VBases,
2381 VPtrsVector &Vptrs) {
2382 // If this base is a non-virtual primary base the address point has already
2384 if (!BaseIsNonVirtualPrimaryBase) {
2385 // Initialize the vtable pointer for this base.
2386 VPtr Vptr = {Base, NearestVBase, OffsetFromNearestVBase, VTableClass};
2387 Vptrs.push_back(Vptr);
2390 const CXXRecordDecl *RD = Base.getBase();
2393 for (const auto &I : RD->bases()) {
2394 CXXRecordDecl *BaseDecl
2395 = cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
2397 // Ignore classes without a vtable.
2398 if (!BaseDecl->isDynamicClass())
2401 CharUnits BaseOffset;
2402 CharUnits BaseOffsetFromNearestVBase;
2403 bool BaseDeclIsNonVirtualPrimaryBase;
2405 if (I.isVirtual()) {
2406 // Check if we've visited this virtual base before.
2407 if (!VBases.insert(BaseDecl).second)
2410 const ASTRecordLayout &Layout =
2411 getContext().getASTRecordLayout(VTableClass);
2413 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
2414 BaseOffsetFromNearestVBase = CharUnits::Zero();
2415 BaseDeclIsNonVirtualPrimaryBase = false;
2417 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
2419 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
2420 BaseOffsetFromNearestVBase =
2421 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
2422 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
2426 BaseSubobject(BaseDecl, BaseOffset),
2427 I.isVirtual() ? BaseDecl : NearestVBase, BaseOffsetFromNearestVBase,
2428 BaseDeclIsNonVirtualPrimaryBase, VTableClass, VBases, Vptrs);
2432 void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
2433 // Ignore classes without a vtable.
2434 if (!RD->isDynamicClass())
2437 // Initialize the vtable pointers for this class and all of its bases.
2438 if (CGM.getCXXABI().doStructorsInitializeVPtrs(RD))
2439 for (const VPtr &Vptr : getVTablePointers(RD))
2440 InitializeVTablePointer(Vptr);
2442 if (RD->getNumVBases())
2443 CGM.getCXXABI().initializeHiddenVirtualInheritanceMembers(*this, RD);
2446 llvm::Value *CodeGenFunction::GetVTablePtr(Address This,
2447 llvm::Type *VTableTy,
2448 const CXXRecordDecl *RD) {
2449 Address VTablePtrSrc = Builder.CreateElementBitCast(This, VTableTy);
2450 llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
2451 CGM.DecorateInstructionWithTBAA(VTable, CGM.getTBAAInfoForVTablePtr());
2453 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2454 CGM.getCodeGenOpts().StrictVTablePointers)
2455 CGM.DecorateInstructionWithInvariantGroup(VTable, RD);
2460 // If a class has a single non-virtual base and does not introduce or override
2461 // virtual member functions or fields, it will have the same layout as its base.
2462 // This function returns the least derived such class.
2464 // Casting an instance of a base class to such a derived class is technically
2465 // undefined behavior, but it is a relatively common hack for introducing member
2466 // functions on class instances with specific properties (e.g. llvm::Operator)
2467 // that works under most compilers and should not have security implications, so
2468 // we allow it by default. It can be disabled with -fsanitize=cfi-cast-strict.
2469 static const CXXRecordDecl *
2470 LeastDerivedClassWithSameLayout(const CXXRecordDecl *RD) {
2471 if (!RD->field_empty())
2474 if (RD->getNumVBases() != 0)
2477 if (RD->getNumBases() != 1)
2480 for (const CXXMethodDecl *MD : RD->methods()) {
2481 if (MD->isVirtual()) {
2482 // Virtual member functions are only ok if they are implicit destructors
2483 // because the implicit destructor will have the same semantics as the
2484 // base class's destructor if no fields are added.
2485 if (isa<CXXDestructorDecl>(MD) && MD->isImplicit())
2491 return LeastDerivedClassWithSameLayout(
2492 RD->bases_begin()->getType()->getAsCXXRecordDecl());
2495 void CodeGenFunction::EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD,
2496 llvm::Value *VTable,
2497 SourceLocation Loc) {
2498 if (CGM.getCodeGenOpts().WholeProgramVTables &&
2499 CGM.HasHiddenLTOVisibility(RD)) {
2500 llvm::Metadata *MD =
2501 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
2502 llvm::Value *TypeId =
2503 llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD);
2505 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
2506 llvm::Value *TypeTest =
2507 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
2508 {CastedVTable, TypeId});
2509 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::assume), TypeTest);
2512 if (SanOpts.has(SanitizerKind::CFIVCall))
2513 EmitVTablePtrCheckForCall(RD, VTable, CodeGenFunction::CFITCK_VCall, Loc);
2516 void CodeGenFunction::EmitVTablePtrCheckForCall(const CXXRecordDecl *RD,
2517 llvm::Value *VTable,
2518 CFITypeCheckKind TCK,
2519 SourceLocation Loc) {
2520 if (!SanOpts.has(SanitizerKind::CFICastStrict))
2521 RD = LeastDerivedClassWithSameLayout(RD);
2523 EmitVTablePtrCheck(RD, VTable, TCK, Loc);
2526 void CodeGenFunction::EmitVTablePtrCheckForCast(QualType T,
2527 llvm::Value *Derived,
2529 CFITypeCheckKind TCK,
2530 SourceLocation Loc) {
2531 if (!getLangOpts().CPlusPlus)
2534 auto *ClassTy = T->getAs<RecordType>();
2538 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassTy->getDecl());
2540 if (!ClassDecl->isCompleteDefinition() || !ClassDecl->isDynamicClass())
2543 if (!SanOpts.has(SanitizerKind::CFICastStrict))
2544 ClassDecl = LeastDerivedClassWithSameLayout(ClassDecl);
2546 llvm::BasicBlock *ContBlock = nullptr;
2549 llvm::Value *DerivedNotNull =
2550 Builder.CreateIsNotNull(Derived, "cast.nonnull");
2552 llvm::BasicBlock *CheckBlock = createBasicBlock("cast.check");
2553 ContBlock = createBasicBlock("cast.cont");
2555 Builder.CreateCondBr(DerivedNotNull, CheckBlock, ContBlock);
2557 EmitBlock(CheckBlock);
2560 llvm::Value *VTable =
2561 GetVTablePtr(Address(Derived, getPointerAlign()), Int8PtrTy, ClassDecl);
2563 EmitVTablePtrCheck(ClassDecl, VTable, TCK, Loc);
2566 Builder.CreateBr(ContBlock);
2567 EmitBlock(ContBlock);
2571 void CodeGenFunction::EmitVTablePtrCheck(const CXXRecordDecl *RD,
2572 llvm::Value *VTable,
2573 CFITypeCheckKind TCK,
2574 SourceLocation Loc) {
2575 if (!CGM.getCodeGenOpts().SanitizeCfiCrossDso &&
2576 !CGM.HasHiddenLTOVisibility(RD))
2579 std::string TypeName = RD->getQualifiedNameAsString();
2580 if (getContext().getSanitizerBlacklist().isBlacklistedType(TypeName))
2583 SanitizerScope SanScope(this);
2584 llvm::SanitizerStatKind SSK;
2587 SSK = llvm::SanStat_CFI_VCall;
2590 SSK = llvm::SanStat_CFI_NVCall;
2592 case CFITCK_DerivedCast:
2593 SSK = llvm::SanStat_CFI_DerivedCast;
2595 case CFITCK_UnrelatedCast:
2596 SSK = llvm::SanStat_CFI_UnrelatedCast;
2599 llvm_unreachable("not expecting CFITCK_ICall");
2601 EmitSanitizerStatReport(SSK);
2603 llvm::Metadata *MD =
2604 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
2605 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
2607 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
2608 llvm::Value *TypeTest = Builder.CreateCall(
2609 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, TypeId});
2614 M = SanitizerKind::CFIVCall;
2617 M = SanitizerKind::CFINVCall;
2619 case CFITCK_DerivedCast:
2620 M = SanitizerKind::CFIDerivedCast;
2622 case CFITCK_UnrelatedCast:
2623 M = SanitizerKind::CFIUnrelatedCast;
2626 llvm_unreachable("not expecting CFITCK_ICall");
2629 llvm::Constant *StaticData[] = {
2630 llvm::ConstantInt::get(Int8Ty, TCK),
2631 EmitCheckSourceLocation(Loc),
2632 EmitCheckTypeDescriptor(QualType(RD->getTypeForDecl(), 0)),
2635 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
2636 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
2637 EmitCfiSlowPathCheck(M, TypeTest, CrossDsoTypeId, CastedVTable, StaticData);
2641 if (CGM.getCodeGenOpts().SanitizeTrap.has(M)) {
2642 EmitTrapCheck(TypeTest);
2646 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
2647 CGM.getLLVMContext(),
2648 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
2649 llvm::Value *ValidVtable = Builder.CreateCall(
2650 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, AllVtables});
2651 EmitCheck(std::make_pair(TypeTest, M), SanitizerHandler::CFICheckFail,
2652 StaticData, {CastedVTable, ValidVtable});
2655 bool CodeGenFunction::ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD) {
2656 if (!CGM.getCodeGenOpts().WholeProgramVTables ||
2657 !SanOpts.has(SanitizerKind::CFIVCall) ||
2658 !CGM.getCodeGenOpts().SanitizeTrap.has(SanitizerKind::CFIVCall) ||
2659 !CGM.HasHiddenLTOVisibility(RD))
2662 std::string TypeName = RD->getQualifiedNameAsString();
2663 return !getContext().getSanitizerBlacklist().isBlacklistedType(TypeName);
2666 llvm::Value *CodeGenFunction::EmitVTableTypeCheckedLoad(
2667 const CXXRecordDecl *RD, llvm::Value *VTable, uint64_t VTableByteOffset) {
2668 SanitizerScope SanScope(this);
2670 EmitSanitizerStatReport(llvm::SanStat_CFI_VCall);
2672 llvm::Metadata *MD =
2673 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
2674 llvm::Value *TypeId = llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD);
2676 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
2677 llvm::Value *CheckedLoad = Builder.CreateCall(
2678 CGM.getIntrinsic(llvm::Intrinsic::type_checked_load),
2679 {CastedVTable, llvm::ConstantInt::get(Int32Ty, VTableByteOffset),
2681 llvm::Value *CheckResult = Builder.CreateExtractValue(CheckedLoad, 1);
2683 EmitCheck(std::make_pair(CheckResult, SanitizerKind::CFIVCall),
2684 SanitizerHandler::CFICheckFail, nullptr, nullptr);
2686 return Builder.CreateBitCast(
2687 Builder.CreateExtractValue(CheckedLoad, 0),
2688 cast<llvm::PointerType>(VTable->getType())->getElementType());
2692 CodeGenFunction::CanDevirtualizeMemberFunctionCall(const Expr *Base,
2693 const CXXMethodDecl *MD) {
2694 // When building with -fapple-kext, all calls must go through the vtable since
2695 // the kernel linker can do runtime patching of vtables.
2696 if (getLangOpts().AppleKext)
2699 // If the member function is marked 'final', we know that it can't be
2700 // overridden and can therefore devirtualize it unless it's pure virtual.
2701 if (MD->hasAttr<FinalAttr>())
2702 return !MD->isPure();
2704 // If the base expression (after skipping derived-to-base conversions) is a
2705 // class prvalue, then we can devirtualize.
2706 Base = Base->getBestDynamicClassTypeExpr();
2707 if (Base->isRValue() && Base->getType()->isRecordType())
2710 // If we don't even know what we would call, we can't devirtualize.
2711 const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
2712 if (!BestDynamicDecl)
2715 // There may be a method corresponding to MD in a derived class.
2716 const CXXMethodDecl *DevirtualizedMethod =
2717 MD->getCorrespondingMethodInClass(BestDynamicDecl);
2719 // If that method is pure virtual, we can't devirtualize. If this code is
2720 // reached, the result would be UB, not a direct call to the derived class
2721 // function, and we can't assume the derived class function is defined.
2722 if (DevirtualizedMethod->isPure())
2725 // If that method is marked final, we can devirtualize it.
2726 if (DevirtualizedMethod->hasAttr<FinalAttr>())
2729 // Similarly, if the class itself is marked 'final' it can't be overridden
2730 // and we can therefore devirtualize the member function call.
2731 if (BestDynamicDecl->hasAttr<FinalAttr>())
2734 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
2735 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
2736 // This is a record decl. We know the type and can devirtualize it.
2737 return VD->getType()->isRecordType();
2743 // We can devirtualize calls on an object accessed by a class member access
2744 // expression, since by C++11 [basic.life]p6 we know that it can't refer to
2745 // a derived class object constructed in the same location.
2746 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Base))
2747 if (const ValueDecl *VD = dyn_cast<ValueDecl>(ME->getMemberDecl()))
2748 return VD->getType()->isRecordType();
2750 // Likewise for calls on an object accessed by a (non-reference) pointer to
2752 if (auto *BO = dyn_cast<BinaryOperator>(Base)) {
2753 if (BO->isPtrMemOp()) {
2754 auto *MPT = BO->getRHS()->getType()->castAs<MemberPointerType>();
2755 if (MPT->getPointeeType()->isRecordType())
2760 // We can't devirtualize the call.
2764 void CodeGenFunction::EmitForwardingCallToLambda(
2765 const CXXMethodDecl *callOperator,
2766 CallArgList &callArgs) {
2767 // Get the address of the call operator.
2768 const CGFunctionInfo &calleeFnInfo =
2769 CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
2770 llvm::Constant *calleePtr =
2771 CGM.GetAddrOfFunction(GlobalDecl(callOperator),
2772 CGM.getTypes().GetFunctionType(calleeFnInfo));
2774 // Prepare the return slot.
2775 const FunctionProtoType *FPT =
2776 callOperator->getType()->castAs<FunctionProtoType>();
2777 QualType resultType = FPT->getReturnType();
2778 ReturnValueSlot returnSlot;
2779 if (!resultType->isVoidType() &&
2780 calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
2781 !hasScalarEvaluationKind(calleeFnInfo.getReturnType()))
2782 returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
2784 // We don't need to separately arrange the call arguments because
2785 // the call can't be variadic anyway --- it's impossible to forward
2786 // variadic arguments.
2788 // Now emit our call.
2789 auto callee = CGCallee::forDirect(calleePtr, callOperator);
2790 RValue RV = EmitCall(calleeFnInfo, callee, returnSlot, callArgs);
2792 // If necessary, copy the returned value into the slot.
2793 if (!resultType->isVoidType() && returnSlot.isNull())
2794 EmitReturnOfRValue(RV, resultType);
2796 EmitBranchThroughCleanup(ReturnBlock);
2799 void CodeGenFunction::EmitLambdaBlockInvokeBody() {
2800 const BlockDecl *BD = BlockInfo->getBlockDecl();
2801 const VarDecl *variable = BD->capture_begin()->getVariable();
2802 const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
2804 // Start building arguments for forwarding call
2805 CallArgList CallArgs;
2807 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2808 Address ThisPtr = GetAddrOfBlockDecl(variable, false);
2809 CallArgs.add(RValue::get(ThisPtr.getPointer()), ThisType);
2811 // Add the rest of the parameters.
2812 for (auto param : BD->parameters())
2813 EmitDelegateCallArg(CallArgs, param, param->getLocStart());
2815 assert(!Lambda->isGenericLambda() &&
2816 "generic lambda interconversion to block not implemented");
2817 EmitForwardingCallToLambda(Lambda->getLambdaCallOperator(), CallArgs);
2820 void CodeGenFunction::EmitLambdaToBlockPointerBody(FunctionArgList &Args) {
2821 if (cast<CXXMethodDecl>(CurCodeDecl)->isVariadic()) {
2822 // FIXME: Making this work correctly is nasty because it requires either
2823 // cloning the body of the call operator or making the call operator forward.
2824 CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function");
2828 EmitFunctionBody(Args, cast<FunctionDecl>(CurGD.getDecl())->getBody());
2831 void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
2832 const CXXRecordDecl *Lambda = MD->getParent();
2834 // Start building arguments for forwarding call
2835 CallArgList CallArgs;
2837 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2838 llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
2839 CallArgs.add(RValue::get(ThisPtr), ThisType);
2841 // Add the rest of the parameters.
2842 for (auto Param : MD->parameters())
2843 EmitDelegateCallArg(CallArgs, Param, Param->getLocStart());
2845 const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
2846 // For a generic lambda, find the corresponding call operator specialization
2847 // to which the call to the static-invoker shall be forwarded.
2848 if (Lambda->isGenericLambda()) {
2849 assert(MD->isFunctionTemplateSpecialization());
2850 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
2851 FunctionTemplateDecl *CallOpTemplate = CallOp->getDescribedFunctionTemplate();
2852 void *InsertPos = nullptr;
2853 FunctionDecl *CorrespondingCallOpSpecialization =
2854 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
2855 assert(CorrespondingCallOpSpecialization);
2856 CallOp = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
2858 EmitForwardingCallToLambda(CallOp, CallArgs);
2861 void CodeGenFunction::EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD) {
2862 if (MD->isVariadic()) {
2863 // FIXME: Making this work correctly is nasty because it requires either
2864 // cloning the body of the call operator or making the call operator forward.
2865 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
2869 EmitLambdaDelegatingInvokeBody(MD);