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