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