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