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"
25#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} // end anonymous namespace
517
519 const CXXRecordDecl *ClassDecl,
520 CXXCtorInitializer *BaseInit) {
521 assert(BaseInit->isBaseInitializer() && "Must have base initializer!");
522
523 Address ThisPtr = CGF.LoadCXXThisAddress();
524
525 const auto *BaseClassDecl = BaseInit->getBaseClass()->castAsCXXRecordDecl();
526
527 bool isBaseVirtual = BaseInit->isBaseVirtual();
528
529 // If the initializer for the base (other than the constructor
530 // itself) accesses 'this' in any way, we need to initialize the
531 // vtables.
533 BaseInit->getInit()))
534 CGF.InitializeVTablePointers(ClassDecl);
535
536 // We can pretend to be a complete class because it only matters for
537 // virtual bases, and we only do virtual bases for complete ctors.
539 ThisPtr, ClassDecl, BaseClassDecl, isBaseVirtual);
543 CGF.getOverlapForBaseInit(ClassDecl, BaseClassDecl, isBaseVirtual));
544
545 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
546
547 if (CGF.CGM.getLangOpts().Exceptions &&
548 !BaseClassDecl->hasTrivialDestructor())
549 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
550 isBaseVirtual);
551}
552
554 CXXCtorInitializer *MemberInit,
555 LValue &LHS) {
556 FieldDecl *Field = MemberInit->getAnyMember();
557 if (MemberInit->isIndirectMemberInitializer()) {
558 // If we are initializing an anonymous union field, drill down to the field.
559 IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember();
560 for (const auto *I : IndirectField->chain())
562 } else {
563 LHS = CGF.EmitLValueForFieldInitialization(LHS, Field);
564 }
565}
566
568 const CXXRecordDecl *ClassDecl,
569 CXXCtorInitializer *MemberInit,
571 FunctionArgList &Args) {
572 ApplyAtomGroup Grp(CGF.getDebugInfo());
573 ApplyDebugLocation Loc(CGF, MemberInit->getSourceLocation());
574 assert(MemberInit->isAnyMemberInitializer() &&
575 "Must have member initializer!");
576 assert(MemberInit->getInit() && "Must have initializer!");
577
578 // non-static data member initializers.
579 FieldDecl *Field = MemberInit->getAnyMember();
580 QualType FieldType = Field->getType();
581
582 llvm::Value *ThisPtr = CGF.LoadCXXThis();
583 CanQualType RecordTy = CGF.getContext().getCanonicalTagType(ClassDecl);
584 LValue LHS;
585
586 // If a base constructor is being emitted, create an LValue that has the
587 // non-virtual alignment.
588 if (CGF.CurGD.getCtorType() == Ctor_Base)
589 LHS = CGF.MakeNaturalAlignPointeeAddrLValue(ThisPtr, RecordTy);
590 else
591 LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
592
593 EmitLValueForAnyFieldInitialization(CGF, MemberInit, LHS);
594
595 // Special case: if we are in a copy or move constructor, and we are copying
596 // an array of PODs or classes with trivial copy constructors, ignore the
597 // AST and perform the copy we know is equivalent.
598 // FIXME: This is hacky at best... if we had a bit more explicit information
599 // in the AST, we could generalize it more easily.
600 const ConstantArrayType *Array =
601 CGF.getContext().getAsConstantArrayType(FieldType);
602 if (Array && Constructor->isDefaulted() &&
603 Constructor->isCopyOrMoveConstructor()) {
604 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
605 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
606 if (BaseElementTy.isPODType(CGF.getContext()) ||
608 CGF.getContext()))) {
609 unsigned SrcArgIndex =
611 llvm::Value *SrcPtr =
612 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
613 LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
614 LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field);
615
616 // Copy the aggregate.
617 CGF.EmitAggregateCopy(LHS, Src, FieldType,
618 CGF.getOverlapForFieldInit(Field),
619 LHS.isVolatileQualified());
620 // Ensure that we destroy the objects if an exception is thrown later in
621 // the constructor.
622 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
623 if (CGF.needsEHCleanup(dtorKind))
624 CGF.pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
625 return;
626 }
627 }
628
629 CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit());
630}
631
633 Expr *Init) {
634 QualType FieldType = Field->getType();
635 switch (getEvaluationKind(FieldType)) {
636 case TEK_Scalar:
637 if (LHS.isSimple()) {
638 EmitExprAsInit(Init, Field, LHS, false);
639 } else {
641 EmitStoreThroughLValue(RHS, LHS);
642 }
643 break;
644 case TEK_Complex:
645 EmitComplexExprIntoLValue(Init, LHS, /*isInit*/ true);
646 break;
647 case TEK_Aggregate: {
652 // Checks are made by the code that calls constructor.
654 EmitAggExpr(Init, Slot);
655 break;
656 }
657 }
658
659 // Ensure that we destroy this object if an exception is thrown
660 // later in the constructor.
661 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
662 if (needsEHCleanup(dtorKind))
663 pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
664}
665
666/// Checks whether the given constructor is a valid subject for the
667/// complete-to-base constructor delegation optimization, i.e.
668/// emitting the complete constructor as a simple call to the base
669/// constructor.
671 const CXXConstructorDecl *Ctor) {
672
673 // Currently we disable the optimization for classes with virtual
674 // bases because (1) the addresses of parameter variables need to be
675 // consistent across all initializers but (2) the delegate function
676 // call necessarily creates a second copy of the parameter variable.
677 //
678 // The limiting example (purely theoretical AFAIK):
679 // struct A { A(int &c) { c++; } };
680 // struct B : virtual A {
681 // B(int count) : A(count) { printf("%d\n", count); }
682 // };
683 // ...although even this example could in principle be emitted as a
684 // delegation since the address of the parameter doesn't escape.
685 if (Ctor->getParent()->getNumVBases()) {
686 // TODO: white-list trivial vbase initializers. This case wouldn't
687 // be subject to the restrictions below.
688
689 // TODO: white-list cases where:
690 // - there are no non-reference parameters to the constructor
691 // - the initializers don't access any non-reference parameters
692 // - the initializers don't take the address of non-reference
693 // parameters
694 // - etc.
695 // If we ever add any of the above cases, remember that:
696 // - function-try-blocks will always exclude this optimization
697 // - we need to perform the constructor prologue and cleanup in
698 // EmitConstructorBody.
699
700 return false;
701 }
702
703 // We also disable the optimization for variadic functions because
704 // it's impossible to "re-pass" varargs.
705 if (Ctor->getType()->castAs<FunctionProtoType>()->isVariadic())
706 return false;
707
708 // FIXME: Decide if we can do a delegation of a delegating constructor.
709 if (Ctor->isDelegatingConstructor())
710 return false;
711
712 return true;
713}
714
715// Emit code in ctor (Prologue==true) or dtor (Prologue==false)
716// to poison the extra field paddings inserted under
717// -fsanitize-address-field-padding=1|2.
719 ASTContext &Context = getContext();
720 const CXXRecordDecl *ClassDecl =
721 Prologue ? cast<CXXConstructorDecl>(CurGD.getDecl())->getParent()
722 : cast<CXXDestructorDecl>(CurGD.getDecl())->getParent();
723 if (!ClassDecl->mayInsertExtraPadding())
724 return;
725
726 struct SizeAndOffset {
727 uint64_t Size;
728 uint64_t Offset;
729 };
730
731 unsigned PtrSize = CGM.getDataLayout().getPointerSizeInBits();
732 const ASTRecordLayout &Info = Context.getASTRecordLayout(ClassDecl);
733
734 // Populate sizes and offsets of fields.
736 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i)
737 SSV[i].Offset =
738 Context.toCharUnitsFromBits(Info.getFieldOffset(i)).getQuantity();
739
740 size_t NumFields = 0;
741 for (const auto *Field : ClassDecl->fields()) {
742 const FieldDecl *D = Field;
743 auto FieldInfo = Context.getTypeInfoInChars(D->getType());
744 CharUnits FieldSize = FieldInfo.Width;
745 assert(NumFields < SSV.size());
746 SSV[NumFields].Size = D->isBitField() ? 0 : FieldSize.getQuantity();
747 NumFields++;
748 }
749 assert(NumFields == SSV.size());
750 if (SSV.size() <= 1)
751 return;
752
753 // We will insert calls to __asan_* run-time functions.
754 // LLVM AddressSanitizer pass may decide to inline them later.
755 llvm::Type *Args[2] = {IntPtrTy, IntPtrTy};
756 llvm::FunctionType *FTy = llvm::FunctionType::get(CGM.VoidTy, Args, false);
757 llvm::FunctionCallee F = CGM.CreateRuntimeFunction(
758 FTy, Prologue ? "__asan_poison_intra_object_redzone"
759 : "__asan_unpoison_intra_object_redzone");
760
761 llvm::Value *ThisPtr = LoadCXXThis();
762 ThisPtr = Builder.CreatePtrToInt(ThisPtr, IntPtrTy);
763 uint64_t TypeSize = Info.getNonVirtualSize().getQuantity();
764 // For each field check if it has sufficient padding,
765 // if so (un)poison it with a call.
766 for (size_t i = 0; i < SSV.size(); i++) {
767 uint64_t AsanAlignment = 8;
768 uint64_t NextField = i == SSV.size() - 1 ? TypeSize : SSV[i + 1].Offset;
769 uint64_t PoisonSize = NextField - SSV[i].Offset - SSV[i].Size;
770 uint64_t EndOffset = SSV[i].Offset + SSV[i].Size;
771 if (PoisonSize < AsanAlignment || !SSV[i].Size ||
772 (NextField % AsanAlignment) != 0)
773 continue;
774 Builder.CreateCall(
775 F, {Builder.CreateAdd(ThisPtr, Builder.getIntN(PtrSize, EndOffset)),
776 Builder.getIntN(PtrSize, PoisonSize)});
777 }
778}
779
780/// EmitConstructorBody - Emits the body of the current constructor.
783 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
784 CXXCtorType CtorType = CurGD.getCtorType();
785
786 assert((CGM.getTarget().getCXXABI().hasConstructorVariants() ||
787 CtorType == Ctor_Complete) &&
788 "can only generate complete ctor for this ABI");
789
790 // Before we go any further, try the complete->base constructor
791 // delegation optimization.
792 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
793 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
795 return;
796 }
797
798 const FunctionDecl *Definition = nullptr;
799 Stmt *Body = Ctor->getBody(Definition);
800 assert(Definition == Ctor && "emitting wrong constructor body");
801
802 // Enter the function-try-block before the constructor prologue if
803 // applicable.
804 bool IsTryBody = isa_and_nonnull<CXXTryStmt>(Body);
805 if (IsTryBody)
806 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
807
810
811 RunCleanupsScope RunCleanups(*this);
812
813 // TODO: in restricted cases, we can emit the vbase initializers of
814 // a complete ctor and then delegate to the base ctor.
815
816 // Emit the constructor prologue, i.e. the base and member
817 // initializers.
818 EmitCtorPrologue(Ctor, CtorType, Args);
819
820 // Emit the body of the statement.
821 if (IsTryBody)
822 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
823 else if (Body)
824 EmitStmt(Body);
825
826 // Emit any cleanup blocks associated with the member or base
827 // initializers, which includes (along the exceptional path) the
828 // destructors for those members and bases that were fully
829 // constructed.
830 RunCleanups.ForceCleanup();
831
832 if (IsTryBody)
833 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
834}
835
836namespace {
837/// RAII object to indicate that codegen is copying the value representation
838/// instead of the object representation. Useful when copying a struct or
839/// class which has uninitialized members and we're only performing
840/// lvalue-to-rvalue conversion on the object but not its members.
841class CopyingValueRepresentation {
842public:
843 explicit CopyingValueRepresentation(CodeGenFunction &CGF)
844 : CGF(CGF), OldSanOpts(CGF.SanOpts) {
845 CGF.SanOpts.set(SanitizerKind::Bool, false);
846 CGF.SanOpts.set(SanitizerKind::Enum, false);
847 }
848 ~CopyingValueRepresentation() { CGF.SanOpts = OldSanOpts; }
849
850private:
851 CodeGenFunction &CGF;
852 SanitizerSet OldSanOpts;
853};
854} // end anonymous namespace
855
856namespace {
857class FieldMemcpyizer {
858public:
859 FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl,
860 const VarDecl *SrcRec)
861 : CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec),
862 RecLayout(CGF.getContext().getASTRecordLayout(ClassDecl)),
863 FirstField(nullptr), LastField(nullptr), FirstFieldOffset(0),
864 LastFieldOffset(0), LastAddedFieldIndex(0) {}
865
866 bool isMemcpyableField(FieldDecl *F) const {
867 // Never memcpy fields when we are adding poisoned paddings.
868 if (CGF.getContext().getLangOpts().SanitizeAddressFieldPadding)
869 return false;
870 Qualifiers Qual = F->getType().getQualifiers();
871 if (Qual.hasVolatile() || Qual.hasObjCLifetime())
872 return false;
873 if (PointerAuthQualifier Q = F->getType().getPointerAuth();
874 Q && Q.isAddressDiscriminated())
875 return false;
876 // Non-trivially-copyable fields with pointer field protection need to be
877 // copied one by one.
878 if (!CGF.getContext().arePFPFieldsTriviallyCopyable(ClassDecl) &&
879 CGF.getContext().isPFPField(F))
880 return false;
881 return true;
882 }
883
884 void addMemcpyableField(FieldDecl *F) {
886 return;
887 if (!FirstField)
888 addInitialField(F);
889 else
890 addNextField(F);
891 }
892
893 CharUnits getMemcpySize(uint64_t FirstByteOffset) const {
894 ASTContext &Ctx = CGF.getContext();
895 unsigned LastFieldSize =
896 LastField->isBitField()
897 ? LastField->getBitWidthValue()
898 : Ctx.toBits(
899 Ctx.getTypeInfoDataSizeInChars(LastField->getType()).Width);
900 uint64_t MemcpySizeBits = LastFieldOffset + LastFieldSize -
901 FirstByteOffset + Ctx.getCharWidth() - 1;
902 CharUnits MemcpySize = Ctx.toCharUnitsFromBits(MemcpySizeBits);
903 return MemcpySize;
904 }
905
906 void emitMemcpy() {
907 // Give the subclass a chance to bail out if it feels the memcpy isn't
908 // worth it (e.g. Hasn't aggregated enough data).
909 if (!FirstField) {
910 return;
911 }
912
913 // Unreachable, e.g. after a noreturn member copy; drop it like EmitStmt.
914 if (!CGF.HaveInsertPoint()) {
915 reset();
916 return;
917 }
918
919 uint64_t FirstByteOffset;
920 if (FirstField->isBitField()) {
921 const CGRecordLayout &RL =
922 CGF.getTypes().getCGRecordLayout(FirstField->getParent());
923 const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField);
924 // FirstFieldOffset is not appropriate for bitfields,
925 // we need to use the storage offset instead.
926 FirstByteOffset = CGF.getContext().toBits(BFInfo.StorageOffset);
927 } else {
928 FirstByteOffset = FirstFieldOffset;
929 }
930
931 CharUnits MemcpySize = getMemcpySize(FirstByteOffset);
932 CanQualType RecordTy = CGF.getContext().getCanonicalTagType(ClassDecl);
933 Address ThisPtr = CGF.LoadCXXThisAddress();
934 LValue DestLV = CGF.MakeAddrLValue(ThisPtr, RecordTy);
935 LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField);
936 llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec));
937 LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
938 LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField);
939
940 emitMemcpyIR(Dest.isBitField() ? Dest.getBitFieldAddress()
941 : Dest.getAddress(),
942 Src.isBitField() ? Src.getBitFieldAddress() : Src.getAddress(),
943 MemcpySize);
944 reset();
945 }
946
947 void reset() { FirstField = nullptr; }
948
949protected:
950 CodeGenFunction &CGF;
951 const CXXRecordDecl *ClassDecl;
952
953private:
954 void emitMemcpyIR(Address DestPtr, Address SrcPtr, CharUnits Size) {
955 DestPtr = DestPtr.withElementType(CGF.Int8Ty);
956 SrcPtr = SrcPtr.withElementType(CGF.Int8Ty);
957 auto *I = CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity());
958 CGF.addInstToCurrentSourceAtom(I, nullptr);
959 }
960
961 void addInitialField(FieldDecl *F) {
962 FirstField = F;
963 LastField = F;
964 FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex());
965 LastFieldOffset = FirstFieldOffset;
966 LastAddedFieldIndex = F->getFieldIndex();
967 }
968
969 void addNextField(FieldDecl *F) {
970 // For the most part, the following invariant will hold:
971 // F->getFieldIndex() == LastAddedFieldIndex + 1
972 // The one exception is that Sema won't add a copy-initializer for an
973 // unnamed bitfield, which will show up here as a gap in the sequence.
974 assert(F->getFieldIndex() >= LastAddedFieldIndex + 1 &&
975 "Cannot aggregate fields out of order.");
976 LastAddedFieldIndex = F->getFieldIndex();
977
978 // The 'first' and 'last' fields are chosen by offset, rather than field
979 // index. This allows the code to support bitfields, as well as regular
980 // fields.
981 uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex());
982 if (FOffset < FirstFieldOffset) {
983 FirstField = F;
984 FirstFieldOffset = FOffset;
985 } else if (FOffset >= LastFieldOffset) {
986 LastField = F;
987 LastFieldOffset = FOffset;
988 }
989 }
990
991 const VarDecl *SrcRec;
992 const ASTRecordLayout &RecLayout;
993 FieldDecl *FirstField;
994 FieldDecl *LastField;
995 uint64_t FirstFieldOffset, LastFieldOffset;
996 unsigned LastAddedFieldIndex;
997};
998
999class ConstructorMemcpyizer : public FieldMemcpyizer {
1000private:
1001 /// Get source argument for copy constructor. Returns null if not a copy
1002 /// constructor.
1003 static const VarDecl *getTrivialCopySource(CodeGenFunction &CGF,
1004 const CXXConstructorDecl *CD,
1005 FunctionArgList &Args) {
1006 if (CD->isCopyOrMoveConstructor() && CD->isDefaulted())
1007 return Args[CGF.CGM.getCXXABI().getSrcArgforCopyCtor(CD, Args)];
1008 return nullptr;
1009 }
1010
1011 // Returns true if a CXXCtorInitializer represents a member initialization
1012 // that can be rolled into a memcpy.
1013 bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const {
1014 if (!MemcpyableCtor)
1015 return false;
1016 FieldDecl *Field = MemberInit->getMember();
1017 assert(Field && "No field for member init.");
1018 QualType FieldType = Field->getType();
1019 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
1020
1021 // Bail out on non-memcpyable, not-trivially-copyable members.
1023 CGF.getContext())) &&
1024 !(FieldType.isTriviallyCopyableType(CGF.getContext()) ||
1025 FieldType->isReferenceType()))
1026 return false;
1027
1028 // Bail out on volatile fields.
1029 if (!isMemcpyableField(Field))
1030 return false;
1031
1032 // Otherwise we're good.
1033 return true;
1034 }
1035
1036public:
1037 ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD,
1038 FunctionArgList &Args)
1039 : FieldMemcpyizer(CGF, CD->getParent(),
1040 getTrivialCopySource(CGF, CD, Args)),
1041 ConstructorDecl(CD),
1042 MemcpyableCtor(CD->isDefaulted() && CD->isCopyOrMoveConstructor() &&
1043 CGF.getLangOpts().getGC() == LangOptions::NonGC),
1044 Args(Args) {}
1045
1046 void addMemberInitializer(CXXCtorInitializer *MemberInit) {
1047 if (isMemberInitMemcpyable(MemberInit)) {
1048 AggregatedInits.push_back(MemberInit);
1049 addMemcpyableField(MemberInit->getMember());
1050 } else {
1051 emitAggregatedInits();
1052 EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit,
1053 ConstructorDecl, Args);
1054 }
1055 }
1056
1057 void emitAggregatedInits() {
1058 if (AggregatedInits.size() <= 1) {
1059 // This memcpy is too small to be worthwhile. Fall back on default
1060 // codegen.
1061 if (!AggregatedInits.empty()) {
1062 CopyingValueRepresentation CVR(CGF);
1063 EmitMemberInitializer(CGF, ConstructorDecl->getParent(),
1064 AggregatedInits[0], ConstructorDecl, Args);
1065 AggregatedInits.clear();
1066 }
1067 reset();
1068 return;
1069 }
1070
1071 pushEHDestructors();
1072 ApplyAtomGroup Grp(CGF.getDebugInfo());
1073 emitMemcpy();
1074 AggregatedInits.clear();
1075 }
1076
1077 void pushEHDestructors() {
1078 Address ThisPtr = CGF.LoadCXXThisAddress();
1079 CanQualType RecordTy = CGF.getContext().getCanonicalTagType(ClassDecl);
1080 LValue LHS = CGF.MakeAddrLValue(ThisPtr, RecordTy);
1081
1082 for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
1083 CXXCtorInitializer *MemberInit = AggregatedInits[i];
1084 QualType FieldType = MemberInit->getAnyMember()->getType();
1085 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
1086 if (!CGF.needsEHCleanup(dtorKind))
1087 continue;
1088 LValue FieldLHS = LHS;
1089 EmitLValueForAnyFieldInitialization(CGF, MemberInit, FieldLHS);
1090 CGF.pushEHDestroy(dtorKind, FieldLHS.getAddress(), FieldType);
1091 }
1092 }
1093
1094 void finish() { emitAggregatedInits(); }
1095
1096private:
1097 const CXXConstructorDecl *ConstructorDecl;
1098 bool MemcpyableCtor;
1099 FunctionArgList &Args;
1100 SmallVector<CXXCtorInitializer *, 16> AggregatedInits;
1101};
1102
1103class AssignmentMemcpyizer : public FieldMemcpyizer {
1104private:
1105 // Returns the memcpyable field copied by the given statement, if one
1106 // exists. Otherwise returns null.
1107 FieldDecl *getMemcpyableField(Stmt *S) {
1108 if (!AssignmentsMemcpyable)
1109 return nullptr;
1110 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
1111 // Recognise trivial assignments.
1112 if (BO->getOpcode() != BO_Assign)
1113 return nullptr;
1114 MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS());
1115 if (!ME)
1116 return nullptr;
1117 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1118 if (!Field || !isMemcpyableField(Field))
1119 return nullptr;
1120 Stmt *RHS = BO->getRHS();
1121 if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS))
1122 RHS = EC->getSubExpr();
1123 if (!RHS)
1124 return nullptr;
1125 if (MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS)) {
1126 if (ME2->getMemberDecl() == Field)
1127 return Field;
1128 }
1129 return nullptr;
1130 } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) {
1131 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl());
1132 if (!(MD && MD->isMemcpyEquivalentSpecialMember(CGF.getContext())))
1133 return nullptr;
1134 MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument());
1135 if (!IOA)
1136 return nullptr;
1137 FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl());
1138 if (!Field || !isMemcpyableField(Field))
1139 return nullptr;
1140 MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0));
1141 if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl()))
1142 return nullptr;
1143 return Field;
1144 } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1145 FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1146 if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy)
1147 return nullptr;
1148 Expr *DstPtr = CE->getArg(0);
1149 if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr))
1150 DstPtr = DC->getSubExpr();
1151 UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr);
1152 if (!DUO || DUO->getOpcode() != UO_AddrOf)
1153 return nullptr;
1154 MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr());
1155 if (!ME)
1156 return nullptr;
1157 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1158 if (!Field || !isMemcpyableField(Field))
1159 return nullptr;
1160 Expr *SrcPtr = CE->getArg(1);
1161 if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr))
1162 SrcPtr = SC->getSubExpr();
1163 UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr);
1164 if (!SUO || SUO->getOpcode() != UO_AddrOf)
1165 return nullptr;
1166 MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr());
1167 if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl()))
1168 return nullptr;
1169 return Field;
1170 }
1171
1172 return nullptr;
1173 }
1174
1175 bool AssignmentsMemcpyable;
1176 SmallVector<Stmt *, 16> AggregatedStmts;
1177
1178public:
1179 AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD,
1180 FunctionArgList &Args)
1181 : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]),
1182 AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) {
1183 assert(Args.size() == 2);
1184 }
1185
1186 void emitAssignment(Stmt *S) {
1187 FieldDecl *F = getMemcpyableField(S);
1188 if (F) {
1189 addMemcpyableField(F);
1190 AggregatedStmts.push_back(S);
1191 } else {
1192 emitAggregatedStmts();
1193 CGF.EmitStmt(S);
1194 }
1195 }
1196
1197 void emitAggregatedStmts() {
1198 if (AggregatedStmts.size() <= 1) {
1199 if (!AggregatedStmts.empty()) {
1200 CopyingValueRepresentation CVR(CGF);
1201 CGF.EmitStmt(AggregatedStmts[0]);
1202 }
1203 reset();
1204 }
1205
1206 ApplyAtomGroup Grp(CGF.getDebugInfo());
1207 emitMemcpy();
1208 AggregatedStmts.clear();
1209 }
1210
1211 void finish() { emitAggregatedStmts(); }
1212};
1213
1214} // end anonymous namespace
1215
1216/// EmitCtorPrologue - This routine generates necessary code to initialize
1217/// base classes and non-static data members belonging to this constructor.
1219 CXXCtorType CtorType,
1220 FunctionArgList &Args) {
1221 if (CD->isDelegatingConstructor())
1222 return EmitDelegatingCXXConstructorCall(CD, Args);
1223
1224 const CXXRecordDecl *ClassDecl = CD->getParent();
1225
1226 // Virtual base initializers aren't needed if:
1227 // - This is a base ctor variant
1228 // - There are no vbases
1229 // - The class is abstract, so a complete object of it cannot be constructed
1230 //
1231 // The check for an abstract class is necessary because sema may not have
1232 // marked virtual base destructors referenced.
1233 bool ConstructVBases = CtorType != Ctor_Base &&
1234 ClassDecl->getNumVBases() != 0 &&
1235 !ClassDecl->isAbstract();
1236
1237 // In the Microsoft C++ ABI, there are no constructor variants. Instead, the
1238 // constructor of a class with virtual bases takes an additional parameter to
1239 // conditionally construct the virtual bases. Emit that check here.
1240 llvm::BasicBlock *BaseCtorContinueBB = nullptr;
1241 if (ConstructVBases &&
1242 !CGM.getTarget().getCXXABI().hasConstructorVariants()) {
1243 BaseCtorContinueBB =
1244 CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this, ClassDecl);
1245 assert(BaseCtorContinueBB);
1246 }
1247
1248 // Create three separate ranges for the different types of initializers.
1249 auto AllInits = CD->inits();
1250
1251 // Find the boundaries between the three groups.
1252 auto VirtualBaseEnd = std::find_if(
1253 AllInits.begin(), AllInits.end(), [](const CXXCtorInitializer *Init) {
1254 return !(Init->isBaseInitializer() && Init->isBaseVirtual());
1255 });
1256
1257 auto NonVirtualBaseEnd = std::find_if(VirtualBaseEnd, AllInits.end(),
1258 [](const CXXCtorInitializer *Init) {
1259 return !Init->isBaseInitializer();
1260 });
1261
1262 // Create the three ranges.
1263 auto VirtualBaseInits = llvm::make_range(AllInits.begin(), VirtualBaseEnd);
1264 auto NonVirtualBaseInits =
1265 llvm::make_range(VirtualBaseEnd, NonVirtualBaseEnd);
1266 auto MemberInits = llvm::make_range(NonVirtualBaseEnd, AllInits.end());
1267
1268 // Process virtual base initializers, if necessary.
1269 if (ConstructVBases) {
1270 for (CXXCtorInitializer *Initializer : VirtualBaseInits) {
1271 SaveAndRestore ThisRAII(CXXThisValue);
1272 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1273 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1275 CXXThisValue = Builder.CreateLaunderInvariantGroup(LoadCXXThis());
1276 EmitBaseInitializer(*this, ClassDecl, Initializer);
1277 }
1278 }
1279
1280 if (BaseCtorContinueBB) {
1281 // Complete object handler should continue to the remaining initializers.
1282 Builder.CreateBr(BaseCtorContinueBB);
1283 EmitBlock(BaseCtorContinueBB);
1284 }
1285
1286 // Then, non-virtual base initializers.
1287 for (CXXCtorInitializer *Initializer : NonVirtualBaseInits) {
1288 assert(!Initializer->isBaseVirtual());
1289 SaveAndRestore ThisRAII(CXXThisValue);
1290 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1291 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1293 CXXThisValue = Builder.CreateLaunderInvariantGroup(LoadCXXThis());
1294 EmitBaseInitializer(*this, ClassDecl, Initializer);
1295 }
1296
1297 InitializeVTablePointers(ClassDecl);
1298
1299 // And finally, initialize class members.
1301 ConstructorMemcpyizer CM(*this, CD, Args);
1302 for (CXXCtorInitializer *Member : MemberInits) {
1303 assert(!Member->isBaseInitializer());
1304 assert(Member->isAnyMemberInitializer() &&
1305 "Delegating initializer on non-delegating constructor");
1306 CM.addMemberInitializer(Member);
1307 }
1308
1309 CM.finish();
1310}
1311
1313 CodeGenFunction &CGF,
1314 llvm::Value *ShouldDeleteCondition) {
1315 Address ThisPtr = CGF.LoadCXXThisAddress();
1316 llvm::BasicBlock *ScalarBB = CGF.createBasicBlock("dtor.scalar");
1317 llvm::BasicBlock *callDeleteBB =
1318 CGF.createBasicBlock("dtor.call_delete_after_array_destroy");
1319 llvm::BasicBlock *VectorBB = CGF.createBasicBlock("dtor.vector");
1320 auto *CondTy = cast<llvm::IntegerType>(ShouldDeleteCondition->getType());
1321 llvm::Value *CheckTheBitForArrayDestroy = CGF.Builder.CreateAnd(
1322 ShouldDeleteCondition, llvm::ConstantInt::get(CondTy, 2));
1323 llvm::Value *ShouldDestroyArray =
1324 CGF.Builder.CreateIsNull(CheckTheBitForArrayDestroy);
1325 CGF.Builder.CreateCondBr(ShouldDestroyArray, ScalarBB, VectorBB);
1326
1327 CGF.EmitBlock(VectorBB);
1328
1329 llvm::Value *numElements = nullptr;
1330 llvm::Value *allocatedPtr = nullptr;
1331 CharUnits cookieSize;
1332 QualType EltTy = DD->getThisType()->getPointeeType();
1333 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, ThisPtr, EltTy, numElements,
1334 allocatedPtr, cookieSize);
1335
1336 // Destroy the elements.
1338
1339 assert(dtorKind);
1340 assert(numElements && "no element count for a type with a destructor!");
1341
1342 CharUnits elementSize = CGF.getContext().getTypeSizeInChars(EltTy);
1343 CharUnits elementAlign =
1344 ThisPtr.getAlignment().alignmentOfArrayElement(elementSize);
1345
1346 llvm::Value *arrayBegin = ThisPtr.emitRawPointer(CGF);
1347 llvm::Value *arrayEnd = CGF.Builder.CreateInBoundsGEP(
1348 ThisPtr.getElementType(), arrayBegin, numElements, "delete.end");
1349
1350 // We already checked that the array is not 0-length before entering vector
1351 // deleting dtor.
1352 CGF.emitArrayDestroy(arrayBegin, arrayEnd, EltTy, elementAlign,
1353 CGF.getDestroyer(dtorKind),
1354 /*checkZeroLength*/ false, CGF.needsEHCleanup(dtorKind));
1355
1356 llvm::BasicBlock *VectorBBCont = CGF.createBasicBlock("dtor.vector.cont");
1357 CGF.EmitBlock(VectorBBCont);
1358
1359 llvm::Value *CheckTheBitForDeleteCall = CGF.Builder.CreateAnd(
1360 ShouldDeleteCondition, llvm::ConstantInt::get(CondTy, 1));
1361
1362 llvm::Value *ShouldCallDelete =
1363 CGF.Builder.CreateIsNull(CheckTheBitForDeleteCall);
1364 CGF.Builder.CreateCondBr(ShouldCallDelete, CGF.ReturnBlock.getBlock(),
1365 callDeleteBB);
1366 CGF.EmitBlock(callDeleteBB);
1368 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1369 if (Dtor->getArrayOperatorDelete()) {
1370 if (!Dtor->getGlobalArrayOperatorDelete()) {
1371 CGF.EmitDeleteCall(Dtor->getArrayOperatorDelete(), allocatedPtr,
1372 CGF.getContext().getCanonicalTagType(ClassDecl),
1373 numElements, cookieSize);
1374 } else {
1375 // If global operator[] is set, the class had its own operator delete[].
1376 // In that case, check the 4th bit. If it is set, we need to call
1377 // ::delete[].
1378 llvm::Value *CheckTheBitForGlobDeleteCall = CGF.Builder.CreateAnd(
1379 ShouldDeleteCondition, llvm::ConstantInt::get(CondTy, 4));
1380
1381 llvm::Value *ShouldCallGlobDelete =
1382 CGF.Builder.CreateIsNull(CheckTheBitForGlobDeleteCall);
1383 llvm::BasicBlock *GlobDelete =
1384 CGF.createBasicBlock("dtor.call_glob_delete_after_array_destroy");
1385 llvm::BasicBlock *ClassDelete =
1386 CGF.createBasicBlock("dtor.call_class_delete_after_array_destroy");
1387 CGF.Builder.CreateCondBr(ShouldCallGlobDelete, ClassDelete, GlobDelete);
1388 CGF.EmitBlock(ClassDelete);
1389 CGF.EmitDeleteCall(Dtor->getArrayOperatorDelete(), allocatedPtr,
1390 CGF.getContext().getCanonicalTagType(ClassDecl),
1391 numElements, cookieSize);
1393
1394 CGF.EmitBlock(GlobDelete);
1395 // Use __global_delete wrapper instead of directly calling
1396 // ::operator delete to match MSVC's behavior. See the doc comment on
1397 // getOrCreateMSVCGlobalDeleteWrapper for details.
1398 llvm::Constant *GlobalDeleteWrapper =
1400 Dtor->getGlobalArrayOperatorDelete());
1401 // For dllexport classes, emit forwarding bodies since the dtor is
1402 // exported and another TU may not provide the forwarding body.
1403 if (Dtor->hasAttr<DLLExportAttr>())
1405 CGF.EmitDeleteCall(Dtor->getGlobalArrayOperatorDelete(), allocatedPtr,
1406 CGF.getContext().getCanonicalTagType(ClassDecl),
1407 numElements, cookieSize, GlobalDeleteWrapper);
1408 }
1409 } else {
1410 // No operators delete[] were found, so emit a trap.
1412 }
1413
1415 CGF.EmitBlock(ScalarBB);
1416}
1417
1418/// EmitDestructorBody - Emits the body of the current destructor.
1420 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
1421 CXXDtorType DtorType = CurGD.getDtorType();
1422
1423 // For an abstract class, non-base destructors are never used (and can't
1424 // be emitted in general, because vbase dtors may not have been validated
1425 // by Sema), but the Itanium ABI doesn't make them optional and Clang may
1426 // in fact emit references to them from other compilations, so emit them
1427 // as functions containing a trap instruction.
1428 if (DtorType != Dtor_Base && Dtor->getParent()->isAbstract()) {
1430 return;
1431 }
1432
1433 Stmt *Body = Dtor->getBody();
1434 if (Body) {
1437 }
1438
1439 // The call to operator delete in a deleting destructor happens
1440 // outside of the function-try-block, which means it's always
1441 // possible to delegate the destructor body to the complete
1442 // destructor. Do so.
1443 if (DtorType == Dtor_Deleting || DtorType == Dtor_VectorDeleting) {
1444 if (CXXStructorImplicitParamValue && DtorType == Dtor_VectorDeleting)
1445 EmitConditionalArrayDtorCall(Dtor, *this, CXXStructorImplicitParamValue);
1446 RunCleanupsScope DtorEpilogue(*this);
1448 if (HaveInsertPoint()) {
1449 QualType ThisTy = Dtor->getFunctionObjectParameterType();
1450 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
1451 /*Delegating=*/false, LoadCXXThisAddress(), ThisTy);
1452 }
1453 return;
1454 }
1455
1456 // If the body is a function-try-block, enter the try before
1457 // anything else.
1458 bool isTryBody = isa_and_nonnull<CXXTryStmt>(Body);
1459 if (isTryBody)
1460 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
1462
1463 // Enter the epilogue cleanups.
1464 RunCleanupsScope DtorEpilogue(*this);
1465
1466 // If this is the complete variant, just invoke the base variant;
1467 // the epilogue will destruct the virtual bases. But we can't do
1468 // this optimization if the body is a function-try-block, because
1469 // we'd introduce *two* handler blocks. In the Microsoft ABI, we
1470 // always delegate because we might not have a definition in this TU.
1471 switch (DtorType) {
1472 case Dtor_Unified:
1473 llvm_unreachable("not expecting a unified dtor");
1474 case Dtor_Comdat:
1475 llvm_unreachable("not expecting a COMDAT");
1476 case Dtor_Deleting:
1477 llvm_unreachable("already handled deleting case");
1479 llvm_unreachable("already handled vector deleting case");
1480
1481 case Dtor_Complete:
1482 assert((Body || getTarget().getCXXABI().isMicrosoft()) &&
1483 "can't emit a dtor without a body for non-Microsoft ABIs");
1484
1485 // Enter the cleanup scopes for virtual bases.
1487
1488 if (!isTryBody) {
1489 QualType ThisTy = Dtor->getFunctionObjectParameterType();
1490 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
1491 /*Delegating=*/false, LoadCXXThisAddress(), ThisTy);
1492 break;
1493 }
1494
1495 // Fallthrough: act like we're in the base variant.
1496 [[fallthrough]];
1497
1498 case Dtor_Base:
1499 assert(Body);
1500
1501 // Enter the cleanup scopes for fields and non-virtual bases.
1503
1504 // Initialize the vtable pointers before entering the body.
1506 // Insert the llvm.launder.invariant.group intrinsic before initializing
1507 // the vptrs to cancel any previous assumptions we might have made.
1508 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1509 CGM.getCodeGenOpts().OptimizationLevel > 0)
1510 CXXThisValue = Builder.CreateLaunderInvariantGroup(LoadCXXThis());
1511 InitializeVTablePointers(Dtor->getParent());
1512 }
1513
1514 if (isTryBody)
1515 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
1516 else if (Body)
1517 EmitStmt(Body);
1518 else {
1519 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
1520 // nothing to do besides what's in the epilogue
1521 }
1522 // -fapple-kext must inline any call to this dtor into
1523 // the caller's body.
1524 if (getLangOpts().AppleKext)
1525 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
1526
1527 break;
1528 }
1529
1530 // Jump out through the epilogue cleanups.
1531 DtorEpilogue.ForceCleanup();
1532
1533 // Exit the try if applicable.
1534 if (isTryBody)
1535 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
1536}
1537
1539 FunctionArgList &Args) {
1540 const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
1541 const Stmt *RootS = AssignOp->getBody();
1542 assert(isa<CompoundStmt>(RootS) &&
1543 "Body of an implicit assignment operator should be compound stmt.");
1544 const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
1545
1546 LexicalScope Scope(*this, RootCS->getSourceRange());
1547
1550 AssignmentMemcpyizer AM(*this, AssignOp, Args);
1551 for (auto *I : RootCS->body())
1552 AM.emitAssignment(I);
1553
1554 AM.finish();
1555}
1556
1557namespace {
1558llvm::Value *LoadThisForDtorDelete(CodeGenFunction &CGF,
1559 const CXXDestructorDecl *DD) {
1560 if (Expr *ThisArg = DD->getOperatorDeleteThisArg())
1561 return CGF.EmitScalarExpr(ThisArg);
1562 return CGF.LoadCXXThis();
1563}
1564
1565/// Call the operator delete associated with the current destructor.
1566struct CallDtorDelete final : EHScopeStack::Cleanup {
1567 CallDtorDelete() {}
1568
1569 void Emit(CodeGenFunction &CGF, Flags flags) override {
1571 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1572 CGF.EmitDeleteCall(Dtor->getOperatorDelete(),
1573 LoadThisForDtorDelete(CGF, Dtor),
1574 CGF.getContext().getCanonicalTagType(ClassDecl));
1575 }
1576};
1577
1578// This function implements generation of scalar deleting destructor body for
1579// the case when the destructor also accepts an implicit flag. Right now only
1580// Microsoft ABI requires deleting destructors to accept implicit flags.
1581// The flag indicates whether an operator delete should be called and whether
1582// it should be a class-specific operator delete or a global one.
1583void EmitConditionalDtorDeleteCall(CodeGenFunction &CGF,
1584 llvm::Value *ShouldDeleteCondition,
1585 bool ReturnAfterDelete) {
1586 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1587 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1588 const FunctionDecl *OD = Dtor->getOperatorDelete();
1589 assert(OD->isDestroyingOperatorDelete() == ReturnAfterDelete &&
1590 "unexpected value for ReturnAfterDelete");
1591 auto *CondTy = cast<llvm::IntegerType>(ShouldDeleteCondition->getType());
1592 // MSVC calls global operator delete inside of the dtor body, but clang
1593 // aligned with this behavior only after a particular version. This is not
1594 // ABI-compatible with previous versions.
1595 ASTContext &Context = CGF.getContext();
1596 bool CallGlobDelete = Context.getTargetInfo().callGlobalDeleteInDeletingDtor(
1597 Context.getLangOpts());
1598 if (CallGlobDelete && OD->isDestroyingOperatorDelete()) {
1599 llvm::BasicBlock *CallDtor = CGF.createBasicBlock("dtor.call_dtor");
1600 llvm::BasicBlock *DontCallDtor = CGF.createBasicBlock("dtor.entry_cont");
1601 // Third bit set signals that global operator delete is called. That means
1602 // despite class having destroying operator delete which is responsible
1603 // for calling dtor, we need to call dtor because global operator delete
1604 // won't do that.
1605 llvm::Value *Check3rdBit = CGF.Builder.CreateAnd(
1606 ShouldDeleteCondition, llvm::ConstantInt::get(CondTy, 4));
1607 llvm::Value *ShouldCallDtor = CGF.Builder.CreateIsNull(Check3rdBit);
1608 CGF.Builder.CreateCondBr(ShouldCallDtor, DontCallDtor, CallDtor);
1609 CGF.EmitBlock(CallDtor);
1610 QualType ThisTy = Dtor->getFunctionObjectParameterType();
1611 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
1612 /*Delegating=*/false, CGF.LoadCXXThisAddress(),
1613 ThisTy);
1614 CGF.Builder.CreateBr(DontCallDtor);
1615 CGF.EmitBlock(DontCallDtor);
1616 }
1617 llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
1618 llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
1619 // First bit set signals that operator delete must be called.
1620 llvm::Value *Check1stBit = CGF.Builder.CreateAnd(
1621 ShouldDeleteCondition, llvm::ConstantInt::get(CondTy, 1));
1622 llvm::Value *ShouldCallDelete = CGF.Builder.CreateIsNull(Check1stBit);
1623 CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
1624
1625 CGF.EmitBlock(callDeleteBB);
1626 auto EmitDeleteAndGoToEnd = [&](const FunctionDecl *DeleteOp,
1627 llvm::Constant *CalleeOverride = nullptr) {
1628 CGF.EmitDeleteCall(DeleteOp, LoadThisForDtorDelete(CGF, Dtor),
1629 Context.getCanonicalTagType(ClassDecl),
1630 /*NumElements=*/nullptr, /*CookieSize=*/CharUnits(),
1631 CalleeOverride);
1632 if (ReturnAfterDelete)
1634 else
1635 CGF.Builder.CreateBr(continueBB);
1636 };
1637 // If Sema only found a global operator delete previously, the dtor can
1638 // always call it. Otherwise we need to check the third bit and call the
1639 // appropriate operator delete, i.e. global or class-specific.
1640 if (const FunctionDecl *GlobOD = Dtor->getOperatorGlobalDelete();
1641 isa<CXXMethodDecl>(OD) && GlobOD && CallGlobDelete) {
1642 // Third bit set signals that global operator delete is called, i.e.
1643 // ::delete appears on the callsite.
1644 llvm::Value *CheckTheBitForGlobDeleteCall = CGF.Builder.CreateAnd(
1645 ShouldDeleteCondition, llvm::ConstantInt::get(CondTy, 4));
1646 llvm::Value *ShouldCallGlobDelete =
1647 CGF.Builder.CreateIsNull(CheckTheBitForGlobDeleteCall);
1648 llvm::BasicBlock *GlobDelete =
1649 CGF.createBasicBlock("dtor.call_glob_delete");
1650 llvm::BasicBlock *ClassDelete =
1651 CGF.createBasicBlock("dtor.call_class_delete");
1652 CGF.Builder.CreateCondBr(ShouldCallGlobDelete, ClassDelete, GlobDelete);
1653 CGF.EmitBlock(GlobDelete);
1654
1655 // Use __global_delete wrapper instead of directly calling
1656 // ::operator delete to match MSVC's behavior. See the doc comment on
1657 // getOrCreateMSVCGlobalDeleteWrapper for details.
1658 llvm::Constant *GlobalDeleteWrapper =
1660 // For dllexport classes, emit forwarding bodies since the dtor is
1661 // exported and another TU may not provide the forwarding body.
1662 if (Dtor->hasAttr<DLLExportAttr>())
1664 EmitDeleteAndGoToEnd(GlobOD, GlobalDeleteWrapper);
1665 CGF.EmitBlock(ClassDelete);
1666 }
1667 EmitDeleteAndGoToEnd(OD);
1668 CGF.EmitBlock(continueBB);
1669}
1670
1671struct CallDtorDeleteConditional final : EHScopeStack::Cleanup {
1672 llvm::Value *ShouldDeleteCondition;
1673
1674public:
1675 CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
1676 : ShouldDeleteCondition(ShouldDeleteCondition) {
1677 assert(ShouldDeleteCondition != nullptr);
1678 }
1679
1680 void Emit(CodeGenFunction &CGF, Flags flags) override {
1681 EmitConditionalDtorDeleteCall(CGF, ShouldDeleteCondition,
1682 /*ReturnAfterDelete*/ false);
1683 }
1684};
1685
1686class DestroyField final : public EHScopeStack::Cleanup {
1687 const FieldDecl *field;
1688 CodeGenFunction::Destroyer *destroyer;
1689 bool useEHCleanupForArray;
1690
1691public:
1692 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
1693 bool useEHCleanupForArray)
1694 : field(field), destroyer(destroyer),
1695 useEHCleanupForArray(useEHCleanupForArray) {}
1696
1697 void Emit(CodeGenFunction &CGF, Flags flags) override {
1698 // Find the address of the field.
1699 Address thisValue = CGF.LoadCXXThisAddress();
1700 CanQualType RecordTy =
1701 CGF.getContext().getCanonicalTagType(field->getParent());
1702 LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
1703 LValue LV = CGF.EmitLValueForField(ThisLV, field);
1704 assert(LV.isSimple());
1705
1706 CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
1707 flags.isForNormalCleanup() && useEHCleanupForArray);
1708 }
1709};
1710
1711class DeclAsInlineDebugLocation {
1712 CGDebugInfo *DI;
1713 llvm::DILocation *InlinedAt;
1714 std::optional<ApplyDebugLocation> Location;
1715
1716public:
1717 DeclAsInlineDebugLocation(CodeGenFunction &CGF, const NamedDecl &Decl)
1718 : DI(CGF.getDebugInfo()) {
1719 if (!DI)
1720 return;
1721 InlinedAt = DI->getInlinedAt();
1722 DI->setInlinedAt(CGF.Builder.getCurrentDebugLocation());
1723 Location.emplace(CGF, Decl.getLocation());
1724 }
1725
1726 ~DeclAsInlineDebugLocation() {
1727 if (!DI)
1728 return;
1729 Location.reset();
1730 DI->setInlinedAt(InlinedAt);
1731 }
1732};
1733
1734static void EmitSanitizerDtorCallback(
1735 CodeGenFunction &CGF, StringRef Name, llvm::Value *Ptr,
1736 std::optional<CharUnits::QuantityType> PoisonSize = {}) {
1737 CodeGenFunction::SanitizerScope SanScope(&CGF);
1738 // Pass in void pointer and size of region as arguments to runtime
1739 // function
1740 SmallVector<llvm::Value *, 2> Args = {Ptr};
1741 SmallVector<llvm::Type *, 2> ArgTypes = {CGF.VoidPtrTy};
1742
1743 if (PoisonSize.has_value()) {
1744 Args.emplace_back(llvm::ConstantInt::get(CGF.SizeTy, *PoisonSize));
1745 ArgTypes.emplace_back(CGF.SizeTy);
1746 }
1747
1748 llvm::FunctionType *FnType =
1749 llvm::FunctionType::get(CGF.VoidTy, ArgTypes, false);
1750 llvm::FunctionCallee Fn = CGF.CGM.CreateRuntimeFunction(FnType, Name);
1751
1752 CGF.EmitNounwindRuntimeCall(Fn, Args);
1753}
1754
1755static void
1756EmitSanitizerDtorFieldsCallback(CodeGenFunction &CGF, llvm::Value *Ptr,
1757 CharUnits::QuantityType PoisonSize) {
1758 EmitSanitizerDtorCallback(CGF, "__sanitizer_dtor_callback_fields", Ptr,
1759 PoisonSize);
1760}
1761
1762/// Poison base class with a trivial destructor.
1763struct SanitizeDtorTrivialBase final : EHScopeStack::Cleanup {
1764 const CXXRecordDecl *BaseClass;
1765 bool BaseIsVirtual;
1766 SanitizeDtorTrivialBase(const CXXRecordDecl *Base, bool BaseIsVirtual)
1767 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
1768
1769 void Emit(CodeGenFunction &CGF, Flags flags) override {
1770 const CXXRecordDecl *DerivedClass =
1771 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
1772
1774 CGF.LoadCXXThisAddress(), DerivedClass, BaseClass, BaseIsVirtual);
1775
1776 const ASTRecordLayout &BaseLayout =
1777 CGF.getContext().getASTRecordLayout(BaseClass);
1778 CharUnits BaseSize = BaseLayout.getSize();
1779
1780 if (!BaseSize.isPositive())
1781 return;
1782
1783 // Use the base class declaration location as inline DebugLocation. All
1784 // fields of the class are destroyed.
1785 DeclAsInlineDebugLocation InlineHere(CGF, *BaseClass);
1786 EmitSanitizerDtorFieldsCallback(CGF, Addr.emitRawPointer(CGF),
1787 BaseSize.getQuantity());
1788
1789 // Prevent the current stack frame from disappearing from the stack trace.
1790 CGF.CurFn->addFnAttr("disable-tail-calls", "true");
1791 }
1792};
1793
1794class SanitizeDtorFieldRange final : public EHScopeStack::Cleanup {
1795 const CXXDestructorDecl *Dtor;
1796 unsigned StartIndex;
1797 unsigned EndIndex;
1798
1799public:
1800 SanitizeDtorFieldRange(const CXXDestructorDecl *Dtor, unsigned StartIndex,
1801 unsigned EndIndex)
1802 : Dtor(Dtor), StartIndex(StartIndex), EndIndex(EndIndex) {}
1803
1804 // Generate function call for handling object poisoning.
1805 // Disables tail call elimination, to prevent the current stack frame
1806 // from disappearing from the stack trace.
1807 void Emit(CodeGenFunction &CGF, Flags flags) override {
1808 const ASTContext &Context = CGF.getContext();
1809 const ASTRecordLayout &Layout =
1810 Context.getASTRecordLayout(Dtor->getParent());
1811
1812 // It's a first trivial field so it should be at the begining of a char,
1813 // still round up start offset just in case.
1814 CharUnits PoisonStart = Context.toCharUnitsFromBits(
1815 Layout.getFieldOffset(StartIndex) + Context.getCharWidth() - 1);
1816 llvm::ConstantInt *OffsetSizePtr =
1817 llvm::ConstantInt::get(CGF.SizeTy, PoisonStart.getQuantity());
1818
1819 llvm::Value *OffsetPtr =
1820 CGF.Builder.CreateGEP(CGF.Int8Ty, CGF.LoadCXXThis(), OffsetSizePtr);
1821
1822 CharUnits PoisonEnd;
1823 if (EndIndex >= Layout.getFieldCount()) {
1824 PoisonEnd = Layout.getNonVirtualSize();
1825 } else {
1826 PoisonEnd = Context.toCharUnitsFromBits(Layout.getFieldOffset(EndIndex));
1827 }
1828 CharUnits PoisonSize = PoisonEnd - PoisonStart;
1829 if (!PoisonSize.isPositive())
1830 return;
1831
1832 // Use the top field declaration location as inline DebugLocation.
1833 DeclAsInlineDebugLocation InlineHere(
1834 CGF, **std::next(Dtor->getParent()->field_begin(), StartIndex));
1835 EmitSanitizerDtorFieldsCallback(CGF, OffsetPtr, PoisonSize.getQuantity());
1836
1837 // Prevent the current stack frame from disappearing from the stack trace.
1838 CGF.CurFn->addFnAttr("disable-tail-calls", "true");
1839 }
1840};
1841
1842class SanitizeDtorVTable final : public EHScopeStack::Cleanup {
1843 const CXXDestructorDecl *Dtor;
1844
1845public:
1846 SanitizeDtorVTable(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
1847
1848 // Generate function call for handling vtable pointer poisoning.
1849 void Emit(CodeGenFunction &CGF, Flags flags) override {
1850 assert(Dtor->getParent()->isDynamicClass());
1851 (void)Dtor;
1852 // Poison vtable and vtable ptr if they exist for this class.
1853 llvm::Value *VTablePtr = CGF.LoadCXXThis();
1854
1855 // Pass in void pointer and size of region as arguments to runtime
1856 // function
1857 EmitSanitizerDtorCallback(CGF, "__sanitizer_dtor_callback_vptr", VTablePtr);
1858 }
1859};
1860
1861class SanitizeDtorCleanupBuilder {
1862 ASTContext &Context;
1863 EHScopeStack &EHStack;
1864 const CXXDestructorDecl *DD;
1865 std::optional<unsigned> StartIndex;
1866
1867public:
1868 SanitizeDtorCleanupBuilder(ASTContext &Context, EHScopeStack &EHStack,
1869 const CXXDestructorDecl *DD)
1870 : Context(Context), EHStack(EHStack), DD(DD), StartIndex(std::nullopt) {}
1871 void PushCleanupForField(const FieldDecl *Field) {
1872 if (CodeGenUtils::isEmptyFieldForLayout(Context, Field))
1873 return;
1874 unsigned FieldIndex = Field->getFieldIndex();
1875 if (CodeGenUtils::fieldHasTrivialDestructorBody(Context, Field)) {
1876 if (!StartIndex)
1877 StartIndex = FieldIndex;
1878 } else if (StartIndex) {
1879 EHStack.pushCleanup<SanitizeDtorFieldRange>(NormalAndEHCleanup, DD,
1880 *StartIndex, FieldIndex);
1881 StartIndex = std::nullopt;
1882 }
1883 }
1884 void End() {
1885 if (StartIndex)
1886 EHStack.pushCleanup<SanitizeDtorFieldRange>(NormalAndEHCleanup, DD,
1887 *StartIndex, -1);
1888 }
1889};
1890} // end anonymous namespace
1891
1892/// Emit all code that comes at the end of class's
1893/// destructor. This is to call destructors on members and base classes
1894/// in reverse order of their construction.
1895///
1896/// For a deleting destructor, this also handles the case where a destroying
1897/// operator delete completely overrides the definition.
1899 CXXDtorType DtorType) {
1900 assert((!DD->isTrivial() || DD->hasAttr<DLLExportAttr>()) &&
1901 "Should not emit dtor epilogue for non-exported trivial dtor!");
1902
1903 // The deleting-destructor phase just needs to call the appropriate
1904 // operator delete that Sema picked up.
1905 if (DtorType == Dtor_Deleting) {
1906 assert(DD->getOperatorDelete() &&
1907 "operator delete missing - EnterDtorCleanups");
1908 if (CXXStructorImplicitParamValue) {
1909 // If there is an implicit param to the deleting dtor, it's a boolean
1910 // telling whether this is a deleting destructor.
1912 EmitConditionalDtorDeleteCall(*this, CXXStructorImplicitParamValue,
1913 /*ReturnAfterDelete*/ true);
1914 else
1915 EHStack.pushCleanup<CallDtorDeleteConditional>(
1916 NormalAndEHCleanup, CXXStructorImplicitParamValue);
1917 } else {
1919 const CXXRecordDecl *ClassDecl = DD->getParent();
1921 LoadThisForDtorDelete(*this, DD),
1922 getContext().getCanonicalTagType(ClassDecl));
1924 } else {
1925 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
1926 }
1927 }
1928 return;
1929 }
1930
1931 const CXXRecordDecl *ClassDecl = DD->getParent();
1932
1933 // Unions have no bases and do not call field destructors.
1934 if (ClassDecl->isUnion())
1935 return;
1936
1937 // The complete-destructor phase just destructs all the virtual bases.
1938 if (DtorType == Dtor_Complete) {
1939 // Poison the vtable pointer such that access after the base
1940 // and member destructors are invoked is invalid.
1941 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1942 SanOpts.has(SanitizerKind::Memory) && ClassDecl->getNumVBases() &&
1943 ClassDecl->isPolymorphic())
1944 EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
1945
1946 // We push them in the forward order so that they'll be popped in
1947 // the reverse order.
1948 for (const auto &Base : ClassDecl->vbases()) {
1949 auto *BaseClassDecl = Base.getType()->castAsCXXRecordDecl();
1950 if (BaseClassDecl->hasTrivialDestructor()) {
1951 // Under SanitizeMemoryUseAfterDtor, poison the trivial base class
1952 // memory. For non-trival base classes the same is done in the class
1953 // destructor.
1954 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1955 SanOpts.has(SanitizerKind::Memory) && !BaseClassDecl->isEmpty())
1956 EHStack.pushCleanup<SanitizeDtorTrivialBase>(NormalAndEHCleanup,
1957 BaseClassDecl,
1958 /*BaseIsVirtual*/ true);
1959 } else {
1960 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup, BaseClassDecl,
1961 /*BaseIsVirtual*/ true);
1962 }
1963 }
1964
1965 return;
1966 }
1967
1968 assert(DtorType == Dtor_Base);
1969 // Poison the vtable pointer if it has no virtual bases, but inherits
1970 // virtual functions.
1971 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1972 SanOpts.has(SanitizerKind::Memory) && !ClassDecl->getNumVBases() &&
1973 ClassDecl->isPolymorphic())
1974 EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
1975
1976 // Destroy non-virtual bases.
1977 for (const auto &Base : ClassDecl->bases()) {
1978 // Ignore virtual bases.
1979 if (Base.isVirtual())
1980 continue;
1981
1982 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
1983
1984 if (BaseClassDecl->hasTrivialDestructor()) {
1985 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1986 SanOpts.has(SanitizerKind::Memory) && !BaseClassDecl->isEmpty())
1987 EHStack.pushCleanup<SanitizeDtorTrivialBase>(NormalAndEHCleanup,
1988 BaseClassDecl,
1989 /*BaseIsVirtual*/ false);
1990 } else {
1991 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup, BaseClassDecl,
1992 /*BaseIsVirtual*/ false);
1993 }
1994 }
1995
1996 // Poison fields such that access after their destructors are
1997 // invoked, and before the base class destructor runs, is invalid.
1998 bool SanitizeFields = CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1999 SanOpts.has(SanitizerKind::Memory);
2000 SanitizeDtorCleanupBuilder SanitizeBuilder(getContext(), EHStack, DD);
2001
2002 // Destroy direct fields.
2003 for (const auto *Field : ClassDecl->fields()) {
2004 if (SanitizeFields)
2005 SanitizeBuilder.PushCleanupForField(Field);
2006
2007 QualType type = Field->getType();
2008 QualType::DestructionKind dtorKind = type.isDestructedType();
2009 if (!dtorKind)
2010 continue;
2011
2012 // Anonymous union members do not have their destructors called.
2013 const RecordType *RT = type->getAsUnionType();
2014 if (RT && RT->getDecl()->isAnonymousStructOrUnion())
2015 continue;
2016
2017 CleanupKind cleanupKind = getCleanupKind(dtorKind);
2018 EHStack.pushCleanup<DestroyField>(
2019 cleanupKind, Field, getDestroyer(dtorKind), cleanupKind & EHCleanup);
2020 }
2021
2022 if (SanitizeFields)
2023 SanitizeBuilder.End();
2024}
2025
2026/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
2027/// constructor for each of several members of an array.
2028///
2029/// \param ctor the constructor to call for each element
2030/// \param arrayType the type of the array to initialize
2031/// \param arrayBegin an arrayType*
2032/// \param zeroInitialize true if each element should be
2033/// zero-initialized before it is constructed
2035 const ArrayType *arrayType,
2036 Address arrayBegin,
2037 const CXXConstructExpr *E,
2038 bool NewPointerIsChecked,
2039 bool zeroInitialize) {
2040 QualType elementType;
2041 llvm::Value *numElements =
2042 emitArrayLength(arrayType, elementType, arrayBegin);
2043
2044 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin, E,
2045 NewPointerIsChecked, zeroInitialize);
2046}
2047
2048/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
2049/// constructor for each of several members of an array.
2050///
2051/// \param ctor the constructor to call for each element
2052/// \param numElements the number of elements in the array;
2053/// may be zero
2054/// \param arrayBase a T*, where T is the type constructed by ctor
2055/// \param zeroInitialize true if each element should be
2056/// zero-initialized before it is constructed
2058 const CXXConstructorDecl *ctor, llvm::Value *numElements, Address arrayBase,
2059 const CXXConstructExpr *E, bool NewPointerIsChecked, bool zeroInitialize) {
2060 // It's legal for numElements to be zero. This can happen both
2061 // dynamically, because x can be zero in 'new A[x]', and statically,
2062 // because of GCC extensions that permit zero-length arrays. There
2063 // are probably legitimate places where we could assume that this
2064 // doesn't happen, but it's not clear that it's worth it.
2065 llvm::CondBrInst *zeroCheckBranch = nullptr;
2066
2067 // Optimize for a constant count.
2068 llvm::ConstantInt *constantCount = dyn_cast<llvm::ConstantInt>(numElements);
2069 if (constantCount) {
2070 // Just skip out if the constant count is zero.
2071 if (constantCount->isZero())
2072 return;
2073
2074 // Otherwise, emit the check.
2075 } else {
2076 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
2077 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
2078 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
2079 EmitBlock(loopBB);
2080 }
2081
2082 // Find the end of the array.
2083 llvm::Type *elementType = arrayBase.getElementType();
2084 llvm::Value *arrayBegin = arrayBase.emitRawPointer(*this);
2085 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(
2086 elementType, arrayBegin, numElements, "arrayctor.end");
2087
2088 // Enter the loop, setting up a phi for the current location to initialize.
2089 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
2090 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
2091 EmitBlock(loopBB);
2092 llvm::PHINode *cur =
2093 Builder.CreatePHI(arrayBegin->getType(), 2, "arrayctor.cur");
2094 cur->addIncoming(arrayBegin, entryBB);
2095
2096 // Inside the loop body, emit the constructor call on the array element.
2097 if (CGM.shouldEmitConvergenceTokens())
2099
2100 // The alignment of the base, adjusted by the size of a single element,
2101 // provides a conservative estimate of the alignment of every element.
2102 // (This assumes we never start tracking offsetted alignments.)
2103 //
2104 // Note that these are complete objects and so we don't need to
2105 // use the non-virtual size or alignment.
2107 CharUnits eltAlignment = arrayBase.getAlignment().alignmentOfArrayElement(
2108 getContext().getTypeSizeInChars(type));
2109 Address curAddr = Address(cur, elementType, eltAlignment);
2110
2111 // Zero initialize the storage, if requested.
2112 if (zeroInitialize)
2113 EmitNullInitialization(curAddr, type);
2114
2115 // C++ [class.temporary]p4:
2116 // There are two contexts in which temporaries are destroyed at a different
2117 // point than the end of the full-expression. The first context is when a
2118 // default constructor is called to initialize an element of an array.
2119 // If the constructor has one or more default arguments, the destruction of
2120 // every temporary created in a default argument expression is sequenced
2121 // before the construction of the next array element, if any.
2122
2123 {
2124 RunCleanupsScope Scope(*this);
2125
2126 // Evaluate the constructor and its arguments in a regular
2127 // partial-destroy cleanup.
2128 if (getLangOpts().Exceptions &&
2129 !ctor->getParent()->hasTrivialDestructor()) {
2130 Destroyer *destroyer = destroyCXXObject;
2131 pushRegularPartialArrayCleanup(arrayBegin, cur, type, eltAlignment,
2132 *destroyer);
2133 }
2134 auto currAVS = AggValueSlot::forAddr(
2135 curAddr, type.getQualifiers(), AggValueSlot::IsDestructed,
2138 NewPointerIsChecked ? AggValueSlot::IsSanitizerChecked
2140 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/false,
2141 /*Delegating=*/false, currAVS, E);
2142 }
2143
2144 // Go to the next element.
2145 llvm::Value *next = Builder.CreateInBoundsGEP(
2146 elementType, cur, llvm::ConstantInt::get(SizeTy, 1), "arrayctor.next");
2147 cur->addIncoming(next, Builder.GetInsertBlock());
2148
2149 // Check whether that's the end of the loop.
2150 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
2151 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
2152 Builder.CreateCondBr(done, contBB, loopBB);
2153
2154 // Patch the earlier check to skip over the loop.
2155 if (zeroCheckBranch)
2156 zeroCheckBranch->setSuccessor(0, contBB);
2157
2158 if (CGM.shouldEmitConvergenceTokens())
2159 ConvergenceTokenStack.pop_back();
2160
2161 EmitBlock(contBB);
2162}
2163
2165 QualType type) {
2166 const CXXDestructorDecl *dtor = type->castAsCXXRecordDecl()->getDestructor();
2167 assert(!dtor->isTrivial());
2168 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
2169 /*Delegating=*/false, addr, type);
2170}
2171
2173 const CXXConstructorDecl *D, CXXCtorType Type, bool ForVirtualBase,
2174 bool Delegating, AggValueSlot ThisAVS, const CXXConstructExpr *E) {
2175 CallArgList Args;
2176 Address This = ThisAVS.getAddress();
2177 LangAS SlotAS = ThisAVS.getQualifiers().getAddressSpace();
2179 llvm::Value *ThisPtr =
2181
2182 if (SlotAS != ThisAS) {
2183 unsigned TargetThisAS = getContext().getTargetAddressSpace(ThisAS);
2184 llvm::Type *NewType =
2185 llvm::PointerType::get(getLLVMContext(), TargetThisAS);
2186 ThisPtr = performAddrSpaceCast(ThisPtr, NewType);
2187 }
2188
2189 // Push the this ptr.
2190 Args.add(RValue::get(ThisPtr), D->getThisType());
2191
2192 // If this is a trivial constructor, emit a memcpy now before we lose
2193 // the alignment information on the argument.
2194 // FIXME: It would be better to preserve alignment information into CallArg.
2196 assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
2197
2198 const Expr *Arg = E->getArg(0);
2199 LValue Src = EmitCheckedLValue(Arg, TCK_Load);
2201 LValue Dest = MakeAddrLValue(This, DestTy);
2202 EmitAggregateCopyCtor(Dest, Src, ThisAVS.mayOverlap());
2203 return;
2204 }
2205
2206 // Add the rest of the user-supplied arguments.
2207 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
2209 ? EvaluationOrder::ForceLeftToRight
2210 : EvaluationOrder::Default;
2211 EmitCallArgs(Args, FPT, E->arguments(), E->getConstructor(),
2212 /*ParamsToSkip*/ 0, Order);
2213
2214 EmitCXXConstructorCall(D, Type, ForVirtualBase, Delegating, This, Args,
2215 ThisAVS.mayOverlap(), E->getExprLoc(),
2216 ThisAVS.isSanitizerChecked());
2217}
2218
2220 const CXXConstructorDecl *Ctor,
2221 CXXCtorType Type, CallArgList &Args) {
2222 // We can't forward a variadic call.
2223 if (Ctor->isVariadic())
2224 return false;
2225
2227 // If the parameters are callee-cleanup, it's not safe to forward.
2228 for (auto *P : Ctor->parameters())
2229 if (P->needsDestruction(CGF.getContext()))
2230 return false;
2231
2232 // Likewise if they're inalloca.
2234 Args, Ctor, Type, 0, 0, CGF.getCurrentFunctionDecl());
2235 if (Info.usesInAlloca())
2236 return false;
2237 }
2238
2239 // Anything else should be OK.
2240 return true;
2241}
2242
2244 const CXXConstructorDecl *D, CXXCtorType Type, bool ForVirtualBase,
2245 bool Delegating, Address This, CallArgList &Args,
2247 bool NewPointerIsChecked, llvm::CallBase **CallOrInvoke) {
2248 const CXXRecordDecl *ClassDecl = D->getParent();
2249
2250 if (!NewPointerIsChecked)
2252 getContext().getCanonicalTagType(ClassDecl),
2253 CharUnits::Zero());
2254
2255 if (D->isTrivial() && D->isDefaultConstructor()) {
2256 assert(Args.size() == 1 && "trivial default ctor with args");
2257 return;
2258 }
2259
2260 // If this is a trivial constructor, just emit what's needed. If this is a
2261 // union copy constructor, we must emit a memcpy, because the AST does not
2262 // model that copy.
2264 assert(Args.size() == 2 && "unexpected argcount for trivial ctor");
2267 Args[1].getRValue(*this).getScalarVal(), SrcTy);
2268 LValue SrcLVal = MakeAddrLValue(Src, SrcTy);
2269 CanQualType DestTy = getContext().getCanonicalTagType(ClassDecl);
2270 LValue DestLVal = MakeAddrLValue(This, DestTy);
2271 EmitAggregateCopyCtor(DestLVal, SrcLVal, Overlap);
2272 return;
2273 }
2274
2275 bool PassPrototypeArgs = true;
2276 // Check whether we can actually emit the constructor before trying to do so.
2277 if (auto Inherited = D->getInheritedConstructor()) {
2278 PassPrototypeArgs = getTypes().inheritingCtorHasParams(Inherited, Type);
2279 if (PassPrototypeArgs && !canEmitDelegateCallArgs(*this, D, Type, Args)) {
2281 Delegating, Args);
2282 return;
2283 }
2284 }
2285
2286 // Insert any ABI-specific implicit constructor arguments.
2288 CGM.getCXXABI().addImplicitConstructorArgs(*this, D, Type, ForVirtualBase,
2289 Delegating, Args);
2290
2291 // Emit the call.
2292 llvm::Constant *CalleePtr = CGM.getAddrOfCXXStructor(GlobalDecl(D, Type));
2293 const CGFunctionInfo &Info = CGM.getTypes().arrangeCXXConstructorCall(
2294 Args, D, Type, ExtraArgs.Prefix, ExtraArgs.Suffix,
2295 getCurrentFunctionDecl(), PassPrototypeArgs);
2296 CGCallee Callee = CGCallee::forDirect(CalleePtr, GlobalDecl(D, Type));
2297 EmitCall(Info, Callee, ReturnValueSlot(), Args, CallOrInvoke, false, Loc);
2298
2299 // Generate vtable assumptions if we're constructing a complete object
2300 // with a vtable. We don't do this for base subobjects for two reasons:
2301 // first, it's incorrect for classes with virtual bases, and second, we're
2302 // about to overwrite the vptrs anyway.
2303 // We also have to make sure if we can refer to vtable:
2304 // - Otherwise we can refer to vtable if it's safe to speculatively emit.
2305 // FIXME: If vtable is used by ctor/dtor, or if vtable is external and we are
2306 // sure that definition of vtable is not hidden,
2307 // then we are always safe to refer to it.
2308 // FIXME: It looks like InstCombine is very inefficient on dealing with
2309 // assumes. Make assumption loads require -fstrict-vtable-pointers
2310 // temporarily.
2311 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2312 ClassDecl->isDynamicClass() && Type != Ctor_Base &&
2313 CGM.getCXXABI().canSpeculativelyEmitVTable(ClassDecl) &&
2314 CGM.getCodeGenOpts().StrictVTablePointers)
2315 EmitVTableAssumptionLoads(ClassDecl, This);
2316}
2317
2319 const CXXConstructorDecl *D, bool ForVirtualBase, Address This,
2320 bool InheritedFromVBase, const CXXInheritedCtorInitExpr *E) {
2321 CallArgList Args;
2323 This, D->getThisType()->getPointeeType())),
2324 D->getThisType());
2325
2326 // Forward the parameters.
2327 if (InheritedFromVBase &&
2328 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
2329 // Nothing to do; this construction is not responsible for constructing
2330 // the base class containing the inherited constructor.
2331 // FIXME: Can we just pass undef's for the remaining arguments if we don't
2332 // have constructor variants?
2333 Args.push_back(ThisArg);
2334 } else if (!CXXInheritedCtorInitExprArgs.empty()) {
2335 // The inheriting constructor was inlined; just inject its arguments.
2336 assert(CXXInheritedCtorInitExprArgs.size() >= D->getNumParams() &&
2337 "wrong number of parameters for inherited constructor call");
2338 Args = CXXInheritedCtorInitExprArgs;
2339 Args[0] = ThisArg;
2340 } else {
2341 // The inheriting constructor was not inlined. Emit delegating arguments.
2342 Args.push_back(ThisArg);
2343 const auto *OuterCtor = cast<CXXConstructorDecl>(CurCodeDecl);
2344 assert(OuterCtor->getNumParams() == D->getNumParams());
2345 assert(!OuterCtor->isVariadic() && "should have been inlined");
2346
2347 for (const auto *Param : OuterCtor->parameters()) {
2348 assert(getContext().hasSameUnqualifiedType(
2349 OuterCtor->getParamDecl(Param->getFunctionScopeIndex())->getType(),
2350 Param->getType()));
2351 EmitDelegateCallArg(Args, Param, E->getLocation());
2352
2353 // Forward __attribute__(pass_object_size).
2354 if (Param->hasAttr<PassObjectSizeAttr>()) {
2355 auto *POSParam = SizeArguments[Param];
2356 assert(POSParam && "missing pass_object_size value for forwarding");
2357 EmitDelegateCallArg(Args, POSParam, E->getLocation());
2358 }
2359 }
2360 }
2361
2362 EmitCXXConstructorCall(D, Ctor_Base, ForVirtualBase, /*Delegating*/ false,
2364 /*NewPointerIsChecked*/ true);
2365}
2366
2368 const CXXConstructorDecl *Ctor, CXXCtorType CtorType, bool ForVirtualBase,
2369 bool Delegating, CallArgList &Args) {
2370 GlobalDecl GD(Ctor, CtorType);
2372 ApplyInlineDebugLocation DebugScope(*this, GD);
2373 RunCleanupsScope RunCleanups(*this);
2374
2375 // Save the arguments to be passed to the inherited constructor.
2376 CXXInheritedCtorInitExprArgs = Args;
2377
2378 FunctionArgList Params;
2379 QualType RetType = BuildFunctionArgList(CurGD, Params);
2380 FnRetTy = RetType;
2381
2382 // Insert any ABI-specific implicit constructor arguments.
2383 CGM.getCXXABI().addImplicitConstructorArgs(*this, Ctor, CtorType,
2384 ForVirtualBase, Delegating, Args);
2385
2386 // Emit a simplified prolog. We only need to emit the implicit params.
2387 assert(Args.size() >= Params.size() && "too few arguments for call");
2388 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2389 if (I < Params.size() && isa<ImplicitParamDecl>(Params[I])) {
2390 const RValue &RV = Args[I].getRValue(*this);
2391 assert(!RV.isComplex() && "complex indirect params not supported");
2392 ParamValue Val = RV.isScalar()
2395 EmitParmDecl(*Params[I], Val, I + 1);
2396 }
2397 }
2398
2399 // Create a return value slot if the ABI implementation wants one.
2400 // FIXME: This is dumb, we should ask the ABI not to try to set the return
2401 // value instead.
2402 if (!RetType->isVoidType())
2403 ReturnValue = CreateIRTempWithoutCast(RetType, "retval.inhctor");
2404
2405 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
2406 CXXThisValue = CXXABIThisValue;
2407
2408 // Directly emit the constructor initializers.
2409 EmitCtorPrologue(Ctor, CtorType, Params);
2410}
2411
2413 llvm::Value *VTableGlobal =
2414 CGM.getCXXABI().getVTableAddressPoint(Vptr.Base, Vptr.VTableClass);
2415 if (!VTableGlobal)
2416 return;
2417
2418 // We can just use the base offset in the complete class.
2419 CharUnits NonVirtualOffset = Vptr.Base.getBaseOffset();
2420
2421 if (!NonVirtualOffset.isZero())
2422 This =
2423 ApplyNonVirtualAndVirtualOffset(*this, This, NonVirtualOffset, nullptr,
2424 Vptr.VTableClass, Vptr.NearestVBase);
2425
2426 llvm::Value *VPtrValue =
2427 GetVTablePtr(This, VTableGlobal->getType(), Vptr.VTableClass);
2428 llvm::Value *Cmp =
2429 Builder.CreateICmpEQ(VPtrValue, VTableGlobal, "cmp.vtables");
2430 Builder.CreateAssumption(Cmp);
2431}
2432
2434 Address This) {
2435 if (CGM.getCXXABI().doStructorsInitializeVPtrs(ClassDecl))
2436 for (const VPtr &Vptr : getVTablePointers(ClassDecl))
2438}
2439
2441 const CXXConstructorDecl *D, Address This, Address Src,
2442 const CXXConstructExpr *E) {
2443 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
2444
2445 CallArgList Args;
2446
2447 // Push the this ptr.
2449 D->getThisType());
2450
2451 // Push the src ptr.
2452 QualType QT = *(FPT->param_type_begin());
2453 llvm::Type *t = CGM.getTypes().ConvertType(QT);
2454 llvm::Value *Val = getAsNaturalPointerTo(Src, D->getThisType());
2455 llvm::Value *SrcVal = Builder.CreateBitCast(Val, t);
2456 Args.add(RValue::get(SrcVal), QT);
2457
2458 // Skip over first argument (Src).
2459 EmitCallArgs(Args, FPT, drop_begin(E->arguments(), 1), E->getConstructor(),
2460 /*ParamsToSkip*/ 1);
2461
2462 EmitCXXConstructorCall(D, Ctor_Complete, /*ForVirtualBase*/ false,
2463 /*Delegating*/ false, This, Args,
2465 /*NewPointerIsChecked*/ false);
2466}
2467
2469 const CXXConstructorDecl *Ctor, CXXCtorType CtorType,
2470 const FunctionArgList &Args, SourceLocation Loc) {
2471 CallArgList DelegateArgs;
2472
2473 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
2474 assert(I != E && "no parameters to constructor");
2475
2476 // this
2479 This, (*I)->getType()->getPointeeType())),
2480 (*I)->getType());
2481 ++I;
2482
2483 // FIXME: The location of the VTT parameter in the parameter list is
2484 // specific to the Itanium ABI and shouldn't be hardcoded here.
2485 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
2486 assert(I != E && "cannot skip vtt parameter, already done with args");
2487 assert((*I)->getType()->isPointerType() &&
2488 "skipping parameter not of vtt type");
2489 ++I;
2490 }
2491
2492 // Explicit arguments.
2493 for (; I != E; ++I) {
2494 const VarDecl *param = *I;
2495 // FIXME: per-argument source location
2496 EmitDelegateCallArg(DelegateArgs, param, Loc);
2497 }
2498
2499 EmitCXXConstructorCall(Ctor, CtorType, /*ForVirtualBase=*/false,
2500 /*Delegating=*/true, This, DelegateArgs,
2502 /*NewPointerIsChecked=*/true);
2503}
2504
2505namespace {
2506struct CallDelegatingCtorDtor final : EHScopeStack::Cleanup {
2507 const CXXDestructorDecl *Dtor;
2508 Address Addr;
2510
2511 CallDelegatingCtorDtor(const CXXDestructorDecl *D, Address Addr,
2513 : Dtor(D), Addr(Addr), Type(Type) {}
2514
2515 void Emit(CodeGenFunction &CGF, Flags flags) override {
2516 // We are calling the destructor from within the constructor.
2517 // Therefore, "this" should have the expected type.
2518 QualType ThisTy = Dtor->getFunctionObjectParameterType();
2519 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
2520 /*Delegating=*/true, Addr, ThisTy);
2521 }
2522};
2523} // end anonymous namespace
2524
2526 const CXXConstructorDecl *Ctor, const FunctionArgList &Args) {
2527 assert(Ctor->isDelegatingConstructor());
2528
2529 Address ThisPtr = LoadCXXThisAddress();
2530
2535 // Checks are made by the code that calls constructor.
2537
2538 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
2539
2540 const CXXRecordDecl *ClassDecl = Ctor->getParent();
2541 if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
2543 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
2544
2545 EHStack.pushCleanup<CallDelegatingCtorDtor>(
2546 EHCleanup, ClassDecl->getDestructor(), ThisPtr, Type);
2547 }
2548}
2549
2552 bool ForVirtualBase,
2553 bool Delegating, Address This,
2554 QualType ThisTy) {
2555 CGM.getCXXABI().EmitDestructorCall(*this, DD, Type, ForVirtualBase,
2556 Delegating, This, ThisTy);
2557}
2558
2559namespace {
2560struct CallLocalDtor final : EHScopeStack::Cleanup {
2561 const CXXDestructorDecl *Dtor;
2562 Address Addr;
2563 QualType Ty;
2564
2565 CallLocalDtor(const CXXDestructorDecl *D, Address Addr, QualType Ty)
2566 : Dtor(D), Addr(Addr), Ty(Ty) {}
2567
2568 void Emit(CodeGenFunction &CGF, Flags flags) override {
2570 /*ForVirtualBase=*/false,
2571 /*Delegating=*/false, Addr, Ty);
2572 }
2573};
2574} // end anonymous namespace
2575
2578 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr, T);
2579}
2580
2582 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
2583 if (!ClassDecl)
2584 return;
2585 if (ClassDecl->hasTrivialDestructor())
2586 return;
2587
2588 const CXXDestructorDecl *D = ClassDecl->getDestructor();
2589 assert(D && D->isUsed() && "destructor not marked as used!");
2591}
2592
2594 // Compute the address point.
2595 llvm::Value *VTableAddressPoint =
2596 CGM.getCXXABI().getVTableAddressPointInStructor(
2597 *this, Vptr.VTableClass, Vptr.Base, Vptr.NearestVBase);
2598
2599 if (!VTableAddressPoint)
2600 return;
2601
2602 // Compute where to store the address point.
2603 llvm::Value *VirtualOffset = nullptr;
2604 CharUnits NonVirtualOffset = CharUnits::Zero();
2605
2606 if (CGM.getCXXABI().isVirtualOffsetNeededForVTableField(*this, Vptr)) {
2607 // We need to use the virtual base offset offset because the virtual base
2608 // might have a different offset in the most derived class.
2609
2610 VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(
2611 *this, LoadCXXThisAddress(), Vptr.VTableClass, Vptr.NearestVBase);
2612 NonVirtualOffset = Vptr.OffsetFromNearestVBase;
2613 } else {
2614 // We can just use the base offset in the complete class.
2615 NonVirtualOffset = Vptr.Base.getBaseOffset();
2616 }
2617
2618 // Apply the offsets.
2619 Address VTableField = LoadCXXThisAddress();
2620 if (!NonVirtualOffset.isZero() || VirtualOffset)
2621 VTableField = ApplyNonVirtualAndVirtualOffset(
2622 *this, VTableField, NonVirtualOffset, VirtualOffset, Vptr.VTableClass,
2623 Vptr.NearestVBase);
2624
2625 // Finally, store the address point. Use the same LLVM types as the field to
2626 // support optimization.
2627 unsigned GlobalsAS = CGM.getDataLayout().getDefaultGlobalsAddressSpace();
2628 llvm::Type *PtrTy = llvm::PointerType::get(CGM.getLLVMContext(), GlobalsAS);
2629 // vtable field is derived from `this` pointer, therefore they should be in
2630 // the same addr space. Note that this might not be LLVM address space 0.
2631 VTableField = VTableField.withElementType(PtrTy);
2632
2633 if (auto AuthenticationInfo = CGM.getVTablePointerAuthInfo(
2634 this, Vptr.Base.getBase(), VTableField.emitRawPointer(*this)))
2635 VTableAddressPoint =
2636 EmitPointerAuthSign(*AuthenticationInfo, VTableAddressPoint);
2637
2638 llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
2639 TBAAAccessInfo TBAAInfo = CGM.getTBAAVTablePtrAccessInfo(PtrTy);
2640 CGM.DecorateInstructionWithTBAA(Store, TBAAInfo);
2641 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2642 CGM.getCodeGenOpts().StrictVTablePointers)
2643 CGM.DecorateInstructionWithInvariantGroup(Store, Vptr.VTableClass);
2644}
2645
2648 CodeGenFunction::VPtrsVector VPtrsResult;
2651 /*NearestVBase=*/nullptr,
2652 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
2653 /*BaseIsNonVirtualPrimaryBase=*/false, VTableClass, VBases,
2654 VPtrsResult);
2655 return VPtrsResult;
2656}
2657
2659 const CXXRecordDecl *NearestVBase,
2660 CharUnits OffsetFromNearestVBase,
2661 bool BaseIsNonVirtualPrimaryBase,
2662 const CXXRecordDecl *VTableClass,
2664 VPtrsVector &Vptrs) {
2665 // If this base is a non-virtual primary base the address point has already
2666 // been set.
2667 if (!BaseIsNonVirtualPrimaryBase) {
2668 // Initialize the vtable pointer for this base.
2669 VPtr Vptr = {Base, NearestVBase, OffsetFromNearestVBase, VTableClass};
2670 Vptrs.push_back(Vptr);
2671 }
2672
2673 const CXXRecordDecl *RD = Base.getBase();
2674
2675 // Traverse bases.
2676 for (const auto &I : RD->bases()) {
2677 auto *BaseDecl = I.getType()->castAsCXXRecordDecl();
2678 // Ignore classes without a vtable.
2679 if (!BaseDecl->isDynamicClass())
2680 continue;
2681
2682 CharUnits BaseOffset;
2683 CharUnits BaseOffsetFromNearestVBase;
2684 bool BaseDeclIsNonVirtualPrimaryBase;
2685
2686 if (I.isVirtual()) {
2687 // Check if we've visited this virtual base before.
2688 if (!VBases.insert(BaseDecl).second)
2689 continue;
2690
2691 const ASTRecordLayout &Layout =
2692 getContext().getASTRecordLayout(VTableClass);
2693
2694 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
2695 BaseOffsetFromNearestVBase = CharUnits::Zero();
2696 BaseDeclIsNonVirtualPrimaryBase = false;
2697 } else {
2698 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
2699
2700 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
2701 BaseOffsetFromNearestVBase =
2702 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
2703 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
2704 }
2705
2707 BaseSubobject(BaseDecl, BaseOffset),
2708 I.isVirtual() ? BaseDecl : NearestVBase, BaseOffsetFromNearestVBase,
2709 BaseDeclIsNonVirtualPrimaryBase, VTableClass, VBases, Vptrs);
2710 }
2711}
2712
2714 // Ignore classes without a vtable.
2715 if (!RD->isDynamicClass())
2716 return;
2717
2718 // Initialize the vtable pointers for this class and all of its bases.
2719 if (CGM.getCXXABI().doStructorsInitializeVPtrs(RD))
2720 for (const VPtr &Vptr : getVTablePointers(RD))
2722
2723 if (RD->getNumVBases())
2724 CGM.getCXXABI().initializeHiddenVirtualInheritanceMembers(*this, RD);
2725}
2726
2727llvm::Value *CodeGenFunction::GetVTablePtr(Address This, llvm::Type *VTableTy,
2728 const CXXRecordDecl *RD,
2729 VTableAuthMode AuthMode) {
2730 Address VTablePtrSrc = This.withElementType(VTableTy);
2731 llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
2732 TBAAAccessInfo TBAAInfo = CGM.getTBAAVTablePtrAccessInfo(VTableTy);
2733 CGM.DecorateInstructionWithTBAA(VTable, TBAAInfo);
2734
2735 if (auto AuthenticationInfo =
2736 CGM.getVTablePointerAuthInfo(this, RD, This.emitRawPointer(*this))) {
2737 if (AuthMode != VTableAuthMode::UnsafeUbsanStrip) {
2738 VTable = cast<llvm::Instruction>(
2739 EmitPointerAuthAuth(*AuthenticationInfo, VTable));
2740 if (AuthMode == VTableAuthMode::MustTrap) {
2741 // This is clearly suboptimal but until we have an ability
2742 // to rely on the authentication intrinsic trapping and force
2743 // an authentication to occur we don't really have a choice.
2744 VTable =
2745 cast<llvm::Instruction>(Builder.CreateBitCast(VTable, Int8PtrTy));
2746 Builder.CreateLoad(RawAddress(VTable, Int8Ty, CGM.getPointerAlign()),
2747 /* IsVolatile */ true);
2748 }
2749 } else {
2752 nullptr),
2753 VTable));
2754 }
2755 }
2756
2757 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2758 CGM.getCodeGenOpts().StrictVTablePointers)
2759 CGM.DecorateInstructionWithInvariantGroup(VTable, RD);
2760
2761 return VTable;
2762}
2763
2764// If a class has a single non-virtual base and does not introduce or override
2765// virtual member functions or fields, it will have the same layout as its base.
2766// This function returns the least derived such class.
2767//
2768// Casting an instance of a base class to such a derived class is technically
2769// undefined behavior, but it is a relatively common hack for introducing member
2770// functions on class instances with specific properties (e.g. llvm::Operator)
2771// that works under most compilers and should not have security implications, so
2772// we allow it by default. It can be disabled with -fsanitize=cfi-cast-strict.
2773static const CXXRecordDecl *
2775 if (!RD->field_empty())
2776 return RD;
2777
2778 if (RD->getNumVBases() != 0)
2779 return RD;
2780
2781 if (RD->getNumBases() != 1)
2782 return RD;
2783
2784 for (const CXXMethodDecl *MD : RD->methods()) {
2785 if (MD->isVirtual()) {
2786 // Virtual member functions are only ok if they are implicit destructors
2787 // because the implicit destructor will have the same semantics as the
2788 // base class's destructor if no fields are added.
2789 if (isa<CXXDestructorDecl>(MD) && MD->isImplicit())
2790 continue;
2791 return RD;
2792 }
2793 }
2794
2797}
2798
2800 llvm::Value *VTable,
2801 SourceLocation Loc) {
2802 if (SanOpts.has(SanitizerKind::CFIVCall))
2804 // Emit the intrinsics of (type_test and assume) for the features of WPD and
2805 // speculative devirtualization. For WPD, emit the intrinsics only for the
2806 // case of non_public LTO visibility.
2807 // TODO: refactor this condition and similar ones into a function (e.g.,
2808 // ShouldEmitDevirtualizationMD) to encapsulate the details of the different
2809 // types of devirtualization.
2810 else if ((CGM.getCodeGenOpts().WholeProgramVTables &&
2811 !CGM.AlwaysHasLTOVisibilityPublic(RD)) ||
2812 CGM.getCodeGenOpts().DevirtualizeSpeculatively) {
2813 CanQualType Ty = CGM.getContext().getCanonicalTagType(RD);
2814 llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(Ty);
2815 llvm::Value *TypeId = llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD);
2816
2817 // If we already know that the call has hidden LTO visibility, emit
2818 // @llvm.type.test(). Otherwise emit @llvm.public.type.test(), which WPD
2819 // will convert to @llvm.type.test() if we assert at link time that we have
2820 // whole program visibility.
2821 llvm::Intrinsic::ID IID = CGM.HasHiddenLTOVisibility(RD)
2822 ? llvm::Intrinsic::type_test
2823 : llvm::Intrinsic::public_type_test;
2824 llvm::Value *TypeTest =
2825 Builder.CreateCall(CGM.getIntrinsic(IID), {VTable, TypeId});
2826 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::assume), TypeTest);
2827 }
2828}
2829
2830/// Converts the CFITypeCheckKind into SanitizerKind::SanitizerOrdinal and
2831/// llvm::SanitizerStatKind.
2832static std::pair<SanitizerKind::SanitizerOrdinal, llvm::SanitizerStatKind>
2834 switch (TCK) {
2836 return std::make_pair(SanitizerKind::SO_CFIVCall, llvm::SanStat_CFI_VCall);
2838 return std::make_pair(SanitizerKind::SO_CFINVCall,
2839 llvm::SanStat_CFI_NVCall);
2841 return std::make_pair(SanitizerKind::SO_CFIDerivedCast,
2842 llvm::SanStat_CFI_DerivedCast);
2844 return std::make_pair(SanitizerKind::SO_CFIUnrelatedCast,
2845 llvm::SanStat_CFI_UnrelatedCast);
2849 llvm_unreachable("unexpected sanitizer kind");
2850 }
2851 llvm_unreachable("Unknown CFITypeCheckKind enum");
2852}
2853
2855 llvm::Value *VTable,
2856 CFITypeCheckKind TCK,
2857 SourceLocation Loc) {
2858 if (!SanOpts.has(SanitizerKind::CFICastStrict))
2860
2861 auto [Ordinal, _] = SanitizerInfoFromCFICheckKind(TCK);
2862 SanitizerDebugLocation SanScope(this, {Ordinal},
2863 SanitizerHandler::CFICheckFail);
2864
2865 EmitVTablePtrCheck(RD, VTable, TCK, Loc);
2866}
2867
2869 bool MayBeNull,
2870 CFITypeCheckKind TCK,
2871 SourceLocation Loc) {
2872 if (!getLangOpts().CPlusPlus)
2873 return;
2874
2875 const auto *ClassDecl = T->getAsCXXRecordDecl();
2876 if (!ClassDecl)
2877 return;
2878
2879 if (!ClassDecl->isCompleteDefinition() || !ClassDecl->isDynamicClass())
2880 return;
2881
2882 if (!SanOpts.has(SanitizerKind::CFICastStrict))
2883 ClassDecl = LeastDerivedClassWithSameLayout(ClassDecl);
2884
2885 auto [Ordinal, _] = SanitizerInfoFromCFICheckKind(TCK);
2886 SanitizerDebugLocation SanScope(this, {Ordinal},
2887 SanitizerHandler::CFICheckFail);
2888
2889 llvm::BasicBlock *ContBlock = nullptr;
2890
2891 if (MayBeNull) {
2892 llvm::Value *DerivedNotNull =
2893 Builder.CreateIsNotNull(Derived.emitRawPointer(*this), "cast.nonnull");
2894
2895 llvm::BasicBlock *CheckBlock = createBasicBlock("cast.check");
2896 ContBlock = createBasicBlock("cast.cont");
2897
2898 Builder.CreateCondBr(DerivedNotNull, CheckBlock, ContBlock);
2899
2900 EmitBlock(CheckBlock);
2901 }
2902
2903 llvm::Value *VTable;
2904 std::tie(VTable, ClassDecl) =
2905 CGM.getCXXABI().LoadVTablePtr(*this, Derived, ClassDecl);
2906
2907 EmitVTablePtrCheck(ClassDecl, VTable, TCK, Loc);
2908
2909 if (MayBeNull) {
2910 Builder.CreateBr(ContBlock);
2911 EmitBlock(ContBlock);
2912 }
2913}
2914
2916 llvm::Value *VTable,
2917 CFITypeCheckKind TCK,
2918 SourceLocation Loc) {
2919 assert(IsSanitizerScope);
2920
2921 if (!CGM.getCodeGenOpts().SanitizeCfiCrossDso &&
2922 !CGM.HasHiddenLTOVisibility(RD))
2923 return;
2924
2925 auto [M, _] = SanitizerInfoFromCFICheckKind(TCK);
2926 if (getContext().getNoSanitizeList().containsType(
2928 return;
2929
2930 CanQualType T = CGM.getContext().getCanonicalTagType(RD);
2931 llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(T);
2932 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
2933 llvm::Value *TypeTest = Builder.CreateCall(
2934 CGM.getIntrinsic(llvm::Intrinsic::type_test), {VTable, TypeId});
2935
2936 EmitVTableCheck(TCK, T, MD, VTable, TypeTest, Loc,
2937 CGM.getCodeGenOpts().SanitizeCfiCrossDso);
2938}
2939
2941 llvm::Metadata *MD, llvm::Value *VTable,
2942 llvm::Value *TypeTest, SourceLocation Loc,
2943 bool UseCrossDsoSlowPath) {
2944 assert(IsSanitizerScope);
2945 auto [M, SSK] = SanitizerInfoFromCFICheckKind(TCK);
2947
2948 llvm::ConstantInt *CrossDsoTypeId =
2949 UseCrossDsoSlowPath ? CGM.CreateCrossDsoCfiTypeId(MD) : nullptr;
2950 if (!CrossDsoTypeId && (CGM.getCodeGenOpts().SanitizeTrap.has(M) ||
2951 CGM.getCodeGenOpts().SanitizeMinimalRuntime)) {
2952 EmitCheck(std::make_pair(TypeTest, M), SanitizerHandler::CFICheckFail, {},
2953 {});
2954 return;
2955 }
2956
2957 if (CGM.getCodeGenOpts().SanitizeTrap.has(M)) {
2958 EmitCfiSlowPathCheck(M, TypeTest, CrossDsoTypeId, VTable, {});
2959 return;
2960 }
2961
2962 llvm::Constant *StaticData[] = {
2963 llvm::ConstantInt::get(Int8Ty, TCK),
2966 };
2967
2968 if (CrossDsoTypeId) {
2969 EmitCfiSlowPathCheck(M, TypeTest, CrossDsoTypeId, VTable, StaticData);
2970 return;
2971 }
2972
2973 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
2974 CGM.getLLVMContext(),
2975 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
2976 llvm::Value *ValidVtable = Builder.CreateCall(
2977 CGM.getIntrinsic(llvm::Intrinsic::type_test), {VTable, AllVtables});
2978 EmitCheck(std::make_pair(TypeTest, M), SanitizerHandler::CFICheckFail,
2979 StaticData, {VTable, ValidVtable});
2980}
2981
2983 if (!CGM.getCodeGenOpts().WholeProgramVTables ||
2984 !CGM.HasHiddenLTOVisibility(RD))
2985 return false;
2986
2987 if (CGM.getCodeGenOpts().VirtualFunctionElimination)
2988 return true;
2989
2990 if (!SanOpts.has(SanitizerKind::CFIVCall) ||
2991 !CGM.getCodeGenOpts().SanitizeTrap.has(SanitizerKind::CFIVCall))
2992 return false;
2993
2994 std::string TypeName = RD->getQualifiedNameAsString();
2995 return !getContext().getNoSanitizeList().containsType(SanitizerKind::CFIVCall,
2996 TypeName);
2997}
2998
3000 const CXXRecordDecl *RD, llvm::Value *VTable, llvm::Type *VTableTy,
3001 uint64_t VTableByteOffset, SourceLocation /*Loc*/) {
3002 auto CheckOrdinal = SanitizerKind::SO_CFIVCall;
3003 auto CheckHandler = SanitizerHandler::CFICheckFail;
3004 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
3005
3006 CanQualType T = CGM.getContext().getCanonicalTagType(RD);
3007 llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(T);
3008 llvm::Value *TypeId = llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD);
3009
3010 auto CheckedLoadIntrinsic = CGM.getLangOpts().RelativeCXXABIVTables
3011 ? llvm::Intrinsic::type_checked_load_relative
3012 : llvm::Intrinsic::type_checked_load;
3013 llvm::Value *CheckedLoad = Builder.CreateCall(
3014 CGM.getIntrinsic(CheckedLoadIntrinsic),
3015 {VTable, llvm::ConstantInt::get(Int32Ty, VTableByteOffset), TypeId});
3016
3017 llvm::Value *CheckResult = Builder.CreateExtractValue(CheckedLoad, 1);
3018
3019 std::string TypeName = RD->getQualifiedNameAsString();
3020 if (SanOpts.has(SanitizerKind::CFIVCall) &&
3021 !getContext().getNoSanitizeList().containsType(SanitizerKind::CFIVCall,
3022 TypeName)) {
3023 EmitSanitizerStatReport(llvm::SanStat_CFI_VCall);
3024 EmitCheck(std::make_pair(CheckResult, CheckOrdinal), CheckHandler, {}, {});
3025 }
3026
3027 return Builder.CreateBitCast(Builder.CreateExtractValue(CheckedLoad, 0),
3028 VTableTy);
3029}
3030
3032 const CXXMethodDecl *callOperator, CallArgList &callArgs,
3033 const CGFunctionInfo *calleeFnInfo, llvm::Constant *calleePtr) {
3034 // Get the address of the call operator.
3035 if (!calleeFnInfo)
3036 calleeFnInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
3037
3038 if (!calleePtr)
3039 calleePtr =
3040 CGM.GetAddrOfFunction(GlobalDecl(callOperator),
3041 CGM.getTypes().GetFunctionType(*calleeFnInfo));
3042
3043 // Prepare the return slot.
3044 const FunctionProtoType *FPT =
3045 callOperator->getType()->castAs<FunctionProtoType>();
3046 QualType resultType = FPT->getReturnType();
3047 ReturnValueSlot returnSlot;
3048 if (!resultType->isVoidType() &&
3049 calleeFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
3050 !hasScalarEvaluationKind(calleeFnInfo->getReturnType()))
3051 returnSlot =
3052 ReturnValueSlot(ReturnValue, resultType.isVolatileQualified(),
3053 /*IsUnused=*/false, /*IsExternallyDestructed=*/true);
3054
3055 // We don't need to separately arrange the call arguments because
3056 // the call can't be variadic anyway --- it's impossible to forward
3057 // variadic arguments.
3058
3059 // Now emit our call.
3060 auto callee = CGCallee::forDirect(calleePtr, GlobalDecl(callOperator));
3061 RValue RV = EmitCall(*calleeFnInfo, callee, returnSlot, callArgs);
3062
3063 // If necessary, copy the returned value into the slot.
3064 if (!resultType->isVoidType() && returnSlot.isNull()) {
3065 if (getLangOpts().ObjCAutoRefCount && resultType->isObjCRetainableType()) {
3067 }
3068 EmitReturnOfRValue(RV, resultType);
3069 } else
3071}
3072
3074 const BlockDecl *BD = BlockInfo->getBlockDecl();
3075 const VarDecl *variable = BD->capture_begin()->getVariable();
3076 const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
3077 const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
3078
3079 if (CallOp->isVariadic()) {
3080 // FIXME: Making this work correctly is nasty because it requires either
3081 // cloning the body of the call operator or making the call operator
3082 // forward.
3083 CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function");
3084 return;
3085 }
3086
3087 // Start building arguments for forwarding call
3088 CallArgList CallArgs;
3089
3090 CanQualType ThisType =
3091 getContext().getPointerType(getContext().getCanonicalTagType(Lambda));
3092 Address ThisPtr = GetAddrOfBlockDecl(variable);
3093 CallArgs.add(RValue::get(getAsNaturalPointerTo(ThisPtr, ThisType)), ThisType);
3094
3095 // Add the rest of the parameters.
3096 for (auto *param : BD->parameters())
3097 EmitDelegateCallArg(CallArgs, param, param->getBeginLoc());
3098
3099 assert(!Lambda->isGenericLambda() &&
3100 "generic lambda interconversion to block not implemented");
3101 EmitForwardingCallToLambda(CallOp, CallArgs);
3102}
3103
3105 if (MD->isVariadic()) {
3106 // FIXME: Making this work correctly is nasty because it requires either
3107 // cloning the body of the call operator or making the call operator
3108 // forward.
3109 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
3110 return;
3111 }
3112
3113 const CXXRecordDecl *Lambda = MD->getParent();
3114
3115 // Start building arguments for forwarding call
3116 CallArgList CallArgs;
3117
3118 CanQualType LambdaType = getContext().getCanonicalTagType(Lambda);
3119 CanQualType ThisType = getContext().getPointerType(LambdaType);
3120 Address ThisPtr = CreateMemTempWithoutCast(LambdaType, "unused.capture");
3121 CallArgs.add(RValue::get(ThisPtr.emitRawPointer(*this)), ThisType);
3122
3123 EmitLambdaDelegatingInvokeBody(MD, CallArgs);
3124}
3125
3127 CallArgList &CallArgs) {
3128 // Add the rest of the forwarded parameters.
3129 for (auto *Param : MD->parameters())
3130 EmitDelegateCallArg(CallArgs, Param, Param->getBeginLoc());
3131
3132 const CXXRecordDecl *Lambda = MD->getParent();
3133 const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
3134 // For a generic lambda, find the corresponding call operator specialization
3135 // to which the call to the static-invoker shall be forwarded.
3136 if (Lambda->isGenericLambda()) {
3139 FunctionTemplateDecl *CallOpTemplate =
3141 llvm::FoldingSetInsertToken InsertToken;
3142 FunctionDecl *CorrespondingCallOpSpecialization =
3143 CallOpTemplate->findSpecialization(TAL->asArray(), InsertToken);
3144 assert(CorrespondingCallOpSpecialization);
3145 CallOp = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
3146 }
3147
3148 // Special lambda forwarding when there are inalloca parameters.
3149 if (hasInAllocaArg(MD)) {
3150 const CGFunctionInfo *ImplFnInfo = nullptr;
3151 llvm::Function *ImplFn = nullptr;
3152 EmitLambdaInAllocaImplFn(CallOp, &ImplFnInfo, &ImplFn);
3153
3154 EmitForwardingCallToLambda(CallOp, CallArgs, ImplFnInfo, ImplFn);
3155 return;
3156 }
3157
3158 EmitForwardingCallToLambda(CallOp, CallArgs);
3159}
3160
3162 if (MD->isVariadic()) {
3163 // FIXME: Making this work correctly is nasty because it requires either
3164 // cloning the body of the call operator or making the call operator
3165 // forward.
3166 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
3167 return;
3168 }
3169
3170 // Forward %this argument.
3171 CallArgList CallArgs;
3173 CanQualType ThisType = getContext().getPointerType(LambdaType);
3174 llvm::Value *ThisArg = CurFn->getArg(0);
3175 CallArgs.add(RValue::get(ThisArg), ThisType);
3176
3177 EmitLambdaDelegatingInvokeBody(MD, CallArgs);
3178}
3179
3181 const CXXMethodDecl *CallOp, const CGFunctionInfo **ImplFnInfo,
3182 llvm::Function **ImplFn) {
3183 const CGFunctionInfo &FnInfo =
3184 CGM.getTypes().arrangeCXXMethodDeclaration(CallOp);
3185 llvm::Function *CallOpFn =
3186 cast<llvm::Function>(CGM.GetAddrOfFunction(GlobalDecl(CallOp)));
3187
3188 // Emit function containing the original call op body. __invoke will delegate
3189 // to this function.
3191 for (auto I = FnInfo.arg_begin(); I != FnInfo.arg_end(); ++I)
3192 ArgTypes.push_back(I->type);
3193 *ImplFnInfo = &CGM.getTypes().arrangeLLVMFunctionInfo(
3194 FnInfo.getReturnType(), FnInfoOpts::IsDelegateCall, ArgTypes,
3195 FnInfo.getExtInfo(), {}, FnInfo.getRequiredArgs(), CallOp);
3196
3197 // Create mangled name as if this was a method named __impl. If for some
3198 // reason the name doesn't look as expected then just tack __impl to the
3199 // front.
3200 // TODO: Use the name mangler to produce the right name instead of using
3201 // string replacement.
3202 StringRef CallOpName = CallOpFn->getName();
3203 std::string ImplName;
3204 if (size_t Pos = CallOpName.find_first_of("<lambda"))
3205 ImplName = ("?__impl@" + CallOpName.drop_front(Pos)).str();
3206 else
3207 ImplName = ("__impl" + CallOpName).str();
3208
3209 llvm::Function *Fn = CallOpFn->getParent()->getFunction(ImplName);
3210 if (!Fn) {
3211 Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(**ImplFnInfo),
3212 llvm::GlobalValue::InternalLinkage, ImplName,
3213 CGM.getModule());
3214 CGM.SetInternalFunctionAttributes(CallOp, Fn, **ImplFnInfo);
3215
3216 const GlobalDecl &GD = GlobalDecl(CallOp);
3217 const auto *D = cast<FunctionDecl>(GD.getDecl());
3218 CodeGenFunction(CGM).GenerateCode(GD, Fn, **ImplFnInfo);
3219 CGM.SetLLVMFunctionAttributesForDefinition(D, Fn);
3220 }
3221 *ImplFn = Fn;
3222}
#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:2774
static void EmitBaseInitializer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl, CXXCtorInitializer *BaseInit)
Definition CGClass.cpp:518
static std::pair< SanitizerKind::SanitizerOrdinal, llvm::SanitizerStatKind > SanitizerInfoFromCFICheckKind(CodeGenFunction::CFITypeCheckKind TCK)
Converts the CFITypeCheckKind into SanitizerKind::SanitizerOrdinal and llvm::SanitizerStatKind.
Definition CGClass.cpp:2833
static void EmitConditionalArrayDtorCall(const CXXDestructorDecl *DD, CodeGenFunction &CGF, llvm::Value *ShouldDeleteCondition)
Definition CGClass.cpp:1312
static void EmitMemberInitializer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl, CXXCtorInitializer *MemberInit, const CXXConstructorDecl *Constructor, FunctionArgList &Args)
Definition CGClass.cpp:567
static void EmitLValueForAnyFieldInitialization(CodeGenFunction &CGF, CXXCtorInitializer *MemberInit, LValue &LHS)
Definition CGClass.cpp:553
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:245
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:971
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:3820
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:4856
capture_const_iterator capture_begin() const
Definition Decl.h:4985
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:4942
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:1553
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1696
arg_range arguments()
Definition ExprCXX.h:1677
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1616
bool isListInitialization() const
Whether this constructor call was written as list-initialization.
Definition ExprCXX.h:1635
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1693
Represents a C++ constructor within a class.
Definition DeclCXX.h:2645
init_iterator init_begin()
Retrieve an iterator to the first initializer.
Definition DeclCXX.h:2760
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:2809
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:2894
Represents a C++ base or member initializer.
Definition DeclCXX.h:2410
FieldDecl * getMember() const
If this is a member initializer, returns the declaration of the non-static data member being initiali...
Definition DeclCXX.h:2550
Expr * getInit() const
Get the initializer.
Definition DeclCXX.h:2612
SourceLocation getSourceLocation() const
Determine the source location of the initializer.
Definition DeclCXX.cpp:2953
bool isAnyMemberInitializer() const
Definition DeclCXX.h:2490
bool isBaseInitializer() const
Determine whether this initializer is initializing a base class.
Definition DeclCXX.h:2482
bool isIndirectMemberInitializer() const
Definition DeclCXX.h:2494
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:2556
IndirectFieldDecl * getIndirectMember() const
Definition DeclCXX.h:2564
bool isBaseVirtual() const
Returns whether the base is virtual or not.
Definition DeclCXX.h:2536
Represents a C++ destructor within a class.
Definition DeclCXX.h:2924
const FunctionDecl * getOperatorDelete() const
Definition DeclCXX.cpp:3230
Expr * getOperatorDeleteThisArg() const
Definition DeclCXX.h:2963
Represents a call to an inherited base class constructor from an inheriting constructor.
Definition ExprCXX.h:1756
SourceLocation getLocation() const LLVM_READONLY
Definition ExprCXX.h:1809
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2153
bool isVirtual() const
Definition DeclCXX.h:2208
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2296
QualType getThisType() const
Return the type of the this pointer.
Definition DeclCXX.cpp:2859
QualType getFunctionObjectParameterType() const
Definition DeclCXX.h:2320
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:1382
base_class_range bases()
Definition DeclCXX.h:609
method_range methods() const
Definition DeclCXX.h:651
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition DeclCXX.h:1224
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:603
base_class_iterator bases_begin()
Definition DeclCXX.h:616
base_class_range vbases()
Definition DeclCXX.h:626
bool isAbstract() const
Determine whether this class has a pure virtual function.
Definition DeclCXX.h:1231
bool isDynamicClass() const
Definition DeclCXX.h:575
bool hasDefinition() const
Definition DeclCXX.h:562
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition DeclCXX.h:1196
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:624
const CXXBaseSpecifier *const * path_const_iterator
Definition Expr.h:3812
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:177
int64_t QuantityType
Definition CharUnits.h:40
bool isPositive() const
Test whether the quantity is greater than zero.
Definition CharUnits.h:107
bool isZero() const
Test whether the quantity equals zero.
Definition CharUnits.h:101
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
Definition CharUnits.h:155
static CharUnits One()
Construct a CharUnits quantity of one.
Definition CharUnits.h:55
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:184
static CharUnits Zero()
Construct a CharUnits quantity of zero.
Definition CharUnits.h:52
@ 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:707
Address getAddress() const
Definition CGValue.h:689
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:703
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:398
Address CreateGEP(CodeGenFunction &CGF, Address Addr, llvm::Value *Index, const llvm::Twine &Name="")
Definition CGBuilder.h:312
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
Definition CGBuilder.h:128
llvm::CallInst * CreateMemCpy(Address Dest, Address Src, llvm::Value *Size, bool IsVolatile=false)
Definition CGBuilder.h:407
Address CreateInBoundsGEP(Address Addr, ArrayRef< llvm::Value * > IdxList, llvm::Type *ElementType, CharUnits Align, const Twine &Name="")
Definition CGBuilder.h:366
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:2522
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:2727
GlobalDecl CurGD
CurGD - The GlobalDecl for the current function being compiled.
void EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor, const FunctionArgList &Args)
Definition CGClass.cpp:2525
void emitDestroy(Address addr, QualType type, Destroyer *destroyer, bool useEHCleanupForArray)
emitDestroy - Immediately perform the destruction of the given object.
Definition CGDecl.cpp:2482
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:2468
llvm::Value * performAddrSpaceCast(llvm::Value *Src, llvm::Type *DestTy)
SanitizerSet SanOpts
Sanitizers enabled for this function.
CodeGenUtils::EvaluationOrder EvaluationOrder
void EmitAsanPrologueOrEpilogue(bool Prologue)
Definition CGClass.cpp:718
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:2367
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:2355
void EmitVTablePtrCheckForCall(const CXXRecordDecl *RD, llvm::Value *VTable, CFITypeCheckKind TCK, SourceLocation Loc)
EmitVTablePtrCheckForCall - Virtual method MD is being called via VTable.
Definition CGClass.cpp:2854
void EmitLambdaStaticInvokeBody(const CXXMethodDecl *MD)
Definition CGClass.cpp:3104
void EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD, CallArgList &CallArgs)
Definition CGClass.cpp:3126
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:2682
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:4161
void EmitForwardingCallToLambda(const CXXMethodDecl *LambdaCallOperator, CallArgList &CallArgs, const CGFunctionInfo *CallOpFnInfo=nullptr, llvm::Constant *CallOpFn=nullptr)
Definition CGClass.cpp:3031
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:4701
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:670
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:2915
void EmitConstructorBody(FunctionArgList &Args)
EmitConstructorBody - Emits the body of the current constructor.
Definition CGClass.cpp:781
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:3180
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:2034
VPtrsVector getVTablePointers(const CXXRecordDecl *VTableClass)
Definition CGClass.cpp:2647
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:2868
@ 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:2550
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:2338
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:2581
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:4051
llvm::ConvergenceControlInst * emitConvergenceLoopToken(llvm::BasicBlock *BB)
Definition CGStmt.cpp:3575
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:5966
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:194
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:1898
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:2172
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:4309
llvm::Value * EmitVTableTypeCheckedLoad(const CXXRecordDecl *RD, llvm::Value *VTable, llvm::Type *VTableTy, uint64_t VTableByteOffset, SourceLocation Loc)
Emit a type checked load from the given vtable.
Definition CGClass.cpp:2999
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:2433
void EmitDestructorBody(FunctionArgList &Args)
EmitDestructorBody - Emits the body of the current destructor.
Definition CGClass.cpp:1419
LValue EmitLValueForFieldInitialization(LValue Base, const FieldDecl *Field)
EmitLValueForFieldInitialization - Like EmitLValueForField, except that if the Field is a reference,...
Definition CGExpr.cpp:6125
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:5703
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:1218
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:236
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:2799
void EmitVTableCheck(CFITypeCheckKind TCK, CanQualType T, llvm::Metadata *MD, llvm::Value *VTable, llvm::Value *TypeTest, SourceLocation Loc, bool UseCrossDsoSlowPath)
Emit a CFI check failure handler or trap for a vtable type test result.
Definition CGClass.cpp:2940
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:2801
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:2741
void EmitInitializerForField(FieldDecl *Field, LValue LHS, Expr *Init)
Definition CGClass.cpp:632
void EmitLambdaInAllocaCallOpBody(const CXXMethodDecl *MD)
Definition CGClass.cpp:3161
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:59
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:2440
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:1538
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:4443
LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK)
Same as EmitLValue but additionally we generate checking code to guard against undefined behavior.
Definition CGExpr.cpp:1742
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:2318
bool sanitizePerformTypeCheck() const
Whether any type-checking sanitizers are enabled.
Definition CGExpr.cpp:755
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:5089
LValue MakeAddrLValue(Address Addr, QualType T, AlignmentSource Source=AlignmentSource::Type)
void EmitTrapCallAndMakeUnreachable()
Emit a call to '@llvm.trap()' and clear the current insert point.
Definition CGExpr.cpp:4752
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:2593
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:2982
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:2713
void EmitVTableAssumptionLoad(const VPtr &vptr, Address This)
Emit assumption that vptr load == global vtable.
Definition CGClass.cpp:2412
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
Definition CGStmt.cpp:658
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:2174
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:504
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:411
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:1751
body_range body()
Definition Stmt.h:1814
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3858
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclBase.h:444
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:602
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:586
This represents one expression.
Definition Expr.h:114
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:3341
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3444
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3426
Represents a function declaration or definition.
Definition Decl.h:2082
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2974
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3284
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4280
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4268
bool isDestroyingOperatorDelete() const
Determine whether this is a destroying operator delete.
Definition Decl.cpp:3624
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3835
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2947
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2546
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3137
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4404
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2554
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3899
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5548
param_type_iterator param_type_begin() const
Definition TypeBase.h:5992
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5952
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:5084
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:3648
ArrayRef< NamedDecl * > chain() const
Definition Decl.h:3669
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3516
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3751
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition Type.cpp:5845
QualType getPointeeType() const
Definition TypeBase.h:3769
std::string getQualifiedNameAsString() const
Definition Decl.cpp:1683
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:3092
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:1469
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8704
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8618
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:8763
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:2914
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:4709
bool mayInsertExtraPadding(bool EmitRemark=false) const
Whether we are allowed to insert extra padding between fields.
Definition Decl.cpp:5468
bool field_empty() const
Definition Decl.h:4717
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:3999
bool isUnion() const
Definition Decl.h:4109
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:9200
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:9498
bool isReferenceType() const
Definition TypeBase.h:8839
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
Expr * getSubExpr() const
Definition Expr.h:2354
Opcode getOpcode() const
Definition Expr.h:2349
QualType getType() const
Definition Decl.h:725
QualType getType() const
Definition Value.cpp:238
Represents a variable declaration or definition.
Definition Decl.h:934
bool isInitializerOfDynamicClass(const CXXCtorInitializer *BaseInit)
Return whether BaseInit initializes a base class that is dynamic, that is, one whose vtable pointer m...
bool canSkipVTablePointerInitialization(ASTContext &Ctx, const CXXDestructorDecl *Dtor)
Check whether we need to initialize any vtable pointers before calling this destructor.
bool fieldHasTrivialDestructorBody(ASTContext &Ctx, const FieldDecl *Field)
Check whether destructing Field has no observable behaviors, and thus can be skipped when creating a ...
bool isEmptyFieldForLayout(const ASTContext &Ctx, const FieldDecl *FD)
Return true iff the field is "empty", that is, either a zero-width bit-field or an isEmptyRecordForLa...
bool baseInitializerUsesThis(ASTContext &Ctx, const Expr *Init)
Check whether Init uses 'this' in a way which requires the vtable to be properly set.
@ 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
@ 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
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