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