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