1 //=== RecordLayoutBuilder.cpp - Helper class for building record layouts ---==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "clang/AST/RecordLayout.h"
11 #include "clang/AST/ASTContext.h"
12 #include "clang/AST/Attr.h"
13 #include "clang/AST/CXXInheritance.h"
14 #include "clang/AST/Decl.h"
15 #include "clang/AST/DeclCXX.h"
16 #include "clang/AST/DeclObjC.h"
17 #include "clang/AST/Expr.h"
18 #include "clang/Basic/TargetInfo.h"
19 #include "clang/Sema/SemaDiagnostic.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/Support/Format.h"
22 #include "llvm/Support/MathExtras.h"
24 using namespace clang;
28 /// BaseSubobjectInfo - Represents a single base subobject in a complete class.
29 /// For a class hierarchy like
33 /// class C : A, B { };
35 /// The BaseSubobjectInfo graph for C will have three BaseSubobjectInfo
36 /// instances, one for B and two for A.
38 /// If a base is virtual, it will only have one BaseSubobjectInfo allocated.
39 struct BaseSubobjectInfo {
40 /// Class - The class for this base info.
41 const CXXRecordDecl *Class;
43 /// IsVirtual - Whether the BaseInfo represents a virtual base or not.
46 /// Bases - Information about the base subobjects.
47 SmallVector<BaseSubobjectInfo*, 4> Bases;
49 /// PrimaryVirtualBaseInfo - Holds the base info for the primary virtual base
50 /// of this base info (if one exists).
51 BaseSubobjectInfo *PrimaryVirtualBaseInfo;
54 const BaseSubobjectInfo *Derived;
57 /// \brief Externally provided layout. Typically used when the AST source, such
58 /// as DWARF, lacks all the information that was available at compile time, such
59 /// as alignment attributes on fields and pragmas in effect.
60 struct ExternalLayout {
61 ExternalLayout() : Size(0), Align(0) {}
63 /// \brief Overall record size in bits.
66 /// \brief Overall record alignment in bits.
69 /// \brief Record field offsets in bits.
70 llvm::DenseMap<const FieldDecl *, uint64_t> FieldOffsets;
72 /// \brief Direct, non-virtual base offsets.
73 llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsets;
75 /// \brief Virtual base offsets.
76 llvm::DenseMap<const CXXRecordDecl *, CharUnits> VirtualBaseOffsets;
78 /// Get the offset of the given field. The external source must provide
79 /// entries for all fields in the record.
80 uint64_t getExternalFieldOffset(const FieldDecl *FD) {
81 assert(FieldOffsets.count(FD) &&
82 "Field does not have an external offset");
83 return FieldOffsets[FD];
86 bool getExternalNVBaseOffset(const CXXRecordDecl *RD, CharUnits &BaseOffset) {
87 auto Known = BaseOffsets.find(RD);
88 if (Known == BaseOffsets.end())
90 BaseOffset = Known->second;
94 bool getExternalVBaseOffset(const CXXRecordDecl *RD, CharUnits &BaseOffset) {
95 auto Known = VirtualBaseOffsets.find(RD);
96 if (Known == VirtualBaseOffsets.end())
98 BaseOffset = Known->second;
103 /// EmptySubobjectMap - Keeps track of which empty subobjects exist at different
104 /// offsets while laying out a C++ class.
105 class EmptySubobjectMap {
106 const ASTContext &Context;
109 /// Class - The class whose empty entries we're keeping track of.
110 const CXXRecordDecl *Class;
112 /// EmptyClassOffsets - A map from offsets to empty record decls.
113 typedef llvm::TinyPtrVector<const CXXRecordDecl *> ClassVectorTy;
114 typedef llvm::DenseMap<CharUnits, ClassVectorTy> EmptyClassOffsetsMapTy;
115 EmptyClassOffsetsMapTy EmptyClassOffsets;
117 /// MaxEmptyClassOffset - The highest offset known to contain an empty
119 CharUnits MaxEmptyClassOffset;
121 /// ComputeEmptySubobjectSizes - Compute the size of the largest base or
122 /// member subobject that is empty.
123 void ComputeEmptySubobjectSizes();
125 void AddSubobjectAtOffset(const CXXRecordDecl *RD, CharUnits Offset);
127 void UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info,
128 CharUnits Offset, bool PlacingEmptyBase);
130 void UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD,
131 const CXXRecordDecl *Class,
133 void UpdateEmptyFieldSubobjects(const FieldDecl *FD, CharUnits Offset);
135 /// AnyEmptySubobjectsBeyondOffset - Returns whether there are any empty
136 /// subobjects beyond the given offset.
137 bool AnyEmptySubobjectsBeyondOffset(CharUnits Offset) const {
138 return Offset <= MaxEmptyClassOffset;
142 getFieldOffset(const ASTRecordLayout &Layout, unsigned FieldNo) const {
143 uint64_t FieldOffset = Layout.getFieldOffset(FieldNo);
144 assert(FieldOffset % CharWidth == 0 &&
145 "Field offset not at char boundary!");
147 return Context.toCharUnitsFromBits(FieldOffset);
151 bool CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD,
152 CharUnits Offset) const;
154 bool CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info,
157 bool CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD,
158 const CXXRecordDecl *Class,
159 CharUnits Offset) const;
160 bool CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD,
161 CharUnits Offset) const;
164 /// This holds the size of the largest empty subobject (either a base
165 /// or a member). Will be zero if the record being built doesn't contain
166 /// any empty classes.
167 CharUnits SizeOfLargestEmptySubobject;
169 EmptySubobjectMap(const ASTContext &Context, const CXXRecordDecl *Class)
170 : Context(Context), CharWidth(Context.getCharWidth()), Class(Class) {
171 ComputeEmptySubobjectSizes();
174 /// CanPlaceBaseAtOffset - Return whether the given base class can be placed
175 /// at the given offset.
176 /// Returns false if placing the record will result in two components
177 /// (direct or indirect) of the same type having the same offset.
178 bool CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info,
181 /// CanPlaceFieldAtOffset - Return whether a field can be placed at the given
183 bool CanPlaceFieldAtOffset(const FieldDecl *FD, CharUnits Offset);
186 void EmptySubobjectMap::ComputeEmptySubobjectSizes() {
188 for (const CXXBaseSpecifier &Base : Class->bases()) {
189 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
192 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
193 if (BaseDecl->isEmpty()) {
194 // If the class decl is empty, get its size.
195 EmptySize = Layout.getSize();
197 // Otherwise, we get the largest empty subobject for the decl.
198 EmptySize = Layout.getSizeOfLargestEmptySubobject();
201 if (EmptySize > SizeOfLargestEmptySubobject)
202 SizeOfLargestEmptySubobject = EmptySize;
206 for (const FieldDecl *FD : Class->fields()) {
207 const RecordType *RT =
208 Context.getBaseElementType(FD->getType())->getAs<RecordType>();
210 // We only care about record types.
215 const CXXRecordDecl *MemberDecl = RT->getAsCXXRecordDecl();
216 const ASTRecordLayout &Layout = Context.getASTRecordLayout(MemberDecl);
217 if (MemberDecl->isEmpty()) {
218 // If the class decl is empty, get its size.
219 EmptySize = Layout.getSize();
221 // Otherwise, we get the largest empty subobject for the decl.
222 EmptySize = Layout.getSizeOfLargestEmptySubobject();
225 if (EmptySize > SizeOfLargestEmptySubobject)
226 SizeOfLargestEmptySubobject = EmptySize;
231 EmptySubobjectMap::CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD,
232 CharUnits Offset) const {
233 // We only need to check empty bases.
237 EmptyClassOffsetsMapTy::const_iterator I = EmptyClassOffsets.find(Offset);
238 if (I == EmptyClassOffsets.end())
241 const ClassVectorTy &Classes = I->second;
242 if (std::find(Classes.begin(), Classes.end(), RD) == Classes.end())
245 // There is already an empty class of the same type at this offset.
249 void EmptySubobjectMap::AddSubobjectAtOffset(const CXXRecordDecl *RD,
251 // We only care about empty bases.
255 // If we have empty structures inside a union, we can assign both
256 // the same offset. Just avoid pushing them twice in the list.
257 ClassVectorTy &Classes = EmptyClassOffsets[Offset];
258 if (std::find(Classes.begin(), Classes.end(), RD) != Classes.end())
261 Classes.push_back(RD);
263 // Update the empty class offset.
264 if (Offset > MaxEmptyClassOffset)
265 MaxEmptyClassOffset = Offset;
269 EmptySubobjectMap::CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info,
271 // We don't have to keep looking past the maximum offset that's known to
272 // contain an empty class.
273 if (!AnyEmptySubobjectsBeyondOffset(Offset))
276 if (!CanPlaceSubobjectAtOffset(Info->Class, Offset))
279 // Traverse all non-virtual bases.
280 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
281 for (const BaseSubobjectInfo *Base : Info->Bases) {
285 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
287 if (!CanPlaceBaseSubobjectAtOffset(Base, BaseOffset))
291 if (Info->PrimaryVirtualBaseInfo) {
292 BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
294 if (Info == PrimaryVirtualBaseInfo->Derived) {
295 if (!CanPlaceBaseSubobjectAtOffset(PrimaryVirtualBaseInfo, Offset))
300 // Traverse all member variables.
301 unsigned FieldNo = 0;
302 for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(),
303 E = Info->Class->field_end(); I != E; ++I, ++FieldNo) {
307 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
308 if (!CanPlaceFieldSubobjectAtOffset(*I, FieldOffset))
315 void EmptySubobjectMap::UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info,
317 bool PlacingEmptyBase) {
318 if (!PlacingEmptyBase && Offset >= SizeOfLargestEmptySubobject) {
319 // We know that the only empty subobjects that can conflict with empty
320 // subobject of non-empty bases, are empty bases that can be placed at
321 // offset zero. Because of this, we only need to keep track of empty base
322 // subobjects with offsets less than the size of the largest empty
323 // subobject for our class.
327 AddSubobjectAtOffset(Info->Class, Offset);
329 // Traverse all non-virtual bases.
330 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
331 for (const BaseSubobjectInfo *Base : Info->Bases) {
335 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
336 UpdateEmptyBaseSubobjects(Base, BaseOffset, PlacingEmptyBase);
339 if (Info->PrimaryVirtualBaseInfo) {
340 BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
342 if (Info == PrimaryVirtualBaseInfo->Derived)
343 UpdateEmptyBaseSubobjects(PrimaryVirtualBaseInfo, Offset,
347 // Traverse all member variables.
348 unsigned FieldNo = 0;
349 for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(),
350 E = Info->Class->field_end(); I != E; ++I, ++FieldNo) {
354 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
355 UpdateEmptyFieldSubobjects(*I, FieldOffset);
359 bool EmptySubobjectMap::CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info,
361 // If we know this class doesn't have any empty subobjects we don't need to
363 if (SizeOfLargestEmptySubobject.isZero())
366 if (!CanPlaceBaseSubobjectAtOffset(Info, Offset))
369 // We are able to place the base at this offset. Make sure to update the
370 // empty base subobject map.
371 UpdateEmptyBaseSubobjects(Info, Offset, Info->Class->isEmpty());
376 EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD,
377 const CXXRecordDecl *Class,
378 CharUnits Offset) const {
379 // We don't have to keep looking past the maximum offset that's known to
380 // contain an empty class.
381 if (!AnyEmptySubobjectsBeyondOffset(Offset))
384 if (!CanPlaceSubobjectAtOffset(RD, Offset))
387 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
389 // Traverse all non-virtual bases.
390 for (const CXXBaseSpecifier &Base : RD->bases()) {
391 if (Base.isVirtual())
394 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
396 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
397 if (!CanPlaceFieldSubobjectAtOffset(BaseDecl, Class, BaseOffset))
402 // This is the most derived class, traverse virtual bases as well.
403 for (const CXXBaseSpecifier &Base : RD->vbases()) {
404 const CXXRecordDecl *VBaseDecl = Base.getType()->getAsCXXRecordDecl();
406 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
407 if (!CanPlaceFieldSubobjectAtOffset(VBaseDecl, Class, VBaseOffset))
412 // Traverse all member variables.
413 unsigned FieldNo = 0;
414 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
415 I != E; ++I, ++FieldNo) {
419 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
421 if (!CanPlaceFieldSubobjectAtOffset(*I, FieldOffset))
429 EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD,
430 CharUnits Offset) const {
431 // We don't have to keep looking past the maximum offset that's known to
432 // contain an empty class.
433 if (!AnyEmptySubobjectsBeyondOffset(Offset))
436 QualType T = FD->getType();
437 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
438 return CanPlaceFieldSubobjectAtOffset(RD, RD, Offset);
440 // If we have an array type we need to look at every element.
441 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
442 QualType ElemTy = Context.getBaseElementType(AT);
443 const RecordType *RT = ElemTy->getAs<RecordType>();
447 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
448 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
450 uint64_t NumElements = Context.getConstantArrayElementCount(AT);
451 CharUnits ElementOffset = Offset;
452 for (uint64_t I = 0; I != NumElements; ++I) {
453 // We don't have to keep looking past the maximum offset that's known to
454 // contain an empty class.
455 if (!AnyEmptySubobjectsBeyondOffset(ElementOffset))
458 if (!CanPlaceFieldSubobjectAtOffset(RD, RD, ElementOffset))
461 ElementOffset += Layout.getSize();
469 EmptySubobjectMap::CanPlaceFieldAtOffset(const FieldDecl *FD,
471 if (!CanPlaceFieldSubobjectAtOffset(FD, Offset))
474 // We are able to place the member variable at this offset.
475 // Make sure to update the empty base subobject map.
476 UpdateEmptyFieldSubobjects(FD, Offset);
480 void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD,
481 const CXXRecordDecl *Class,
483 // We know that the only empty subobjects that can conflict with empty
484 // field subobjects are subobjects of empty bases that can be placed at offset
485 // zero. Because of this, we only need to keep track of empty field
486 // subobjects with offsets less than the size of the largest empty
487 // subobject for our class.
488 if (Offset >= SizeOfLargestEmptySubobject)
491 AddSubobjectAtOffset(RD, Offset);
493 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
495 // Traverse all non-virtual bases.
496 for (const CXXBaseSpecifier &Base : RD->bases()) {
497 if (Base.isVirtual())
500 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
502 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
503 UpdateEmptyFieldSubobjects(BaseDecl, Class, BaseOffset);
507 // This is the most derived class, traverse virtual bases as well.
508 for (const CXXBaseSpecifier &Base : RD->vbases()) {
509 const CXXRecordDecl *VBaseDecl = Base.getType()->getAsCXXRecordDecl();
511 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
512 UpdateEmptyFieldSubobjects(VBaseDecl, Class, VBaseOffset);
516 // Traverse all member variables.
517 unsigned FieldNo = 0;
518 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
519 I != E; ++I, ++FieldNo) {
523 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
525 UpdateEmptyFieldSubobjects(*I, FieldOffset);
529 void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const FieldDecl *FD,
531 QualType T = FD->getType();
532 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
533 UpdateEmptyFieldSubobjects(RD, RD, Offset);
537 // If we have an array type we need to update every element.
538 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
539 QualType ElemTy = Context.getBaseElementType(AT);
540 const RecordType *RT = ElemTy->getAs<RecordType>();
544 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
545 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
547 uint64_t NumElements = Context.getConstantArrayElementCount(AT);
548 CharUnits ElementOffset = Offset;
550 for (uint64_t I = 0; I != NumElements; ++I) {
551 // We know that the only empty subobjects that can conflict with empty
552 // field subobjects are subobjects of empty bases that can be placed at
553 // offset zero. Because of this, we only need to keep track of empty field
554 // subobjects with offsets less than the size of the largest empty
555 // subobject for our class.
556 if (ElementOffset >= SizeOfLargestEmptySubobject)
559 UpdateEmptyFieldSubobjects(RD, RD, ElementOffset);
560 ElementOffset += Layout.getSize();
565 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> ClassSetTy;
567 class ItaniumRecordLayoutBuilder {
569 // FIXME: Remove this and make the appropriate fields public.
570 friend class clang::ASTContext;
572 const ASTContext &Context;
574 EmptySubobjectMap *EmptySubobjects;
576 /// Size - The current size of the record layout.
579 /// Alignment - The current alignment of the record layout.
582 /// \brief The alignment if attribute packed is not used.
583 CharUnits UnpackedAlignment;
585 SmallVector<uint64_t, 16> FieldOffsets;
587 /// \brief Whether the external AST source has provided a layout for this
589 unsigned UseExternalLayout : 1;
591 /// \brief Whether we need to infer alignment, even when we have an
592 /// externally-provided layout.
593 unsigned InferAlignment : 1;
595 /// Packed - Whether the record is packed or not.
598 unsigned IsUnion : 1;
600 unsigned IsMac68kAlign : 1;
602 unsigned IsMsStruct : 1;
604 /// UnfilledBitsInLastUnit - If the last field laid out was a bitfield,
605 /// this contains the number of bits in the last unit that can be used for
606 /// an adjacent bitfield if necessary. The unit in question is usually
607 /// a byte, but larger units are used if IsMsStruct.
608 unsigned char UnfilledBitsInLastUnit;
609 /// LastBitfieldTypeSize - If IsMsStruct, represents the size of the type
610 /// of the previous field if it was a bitfield.
611 unsigned char LastBitfieldTypeSize;
613 /// MaxFieldAlignment - The maximum allowed field alignment. This is set by
615 CharUnits MaxFieldAlignment;
617 /// DataSize - The data size of the record being laid out.
620 CharUnits NonVirtualSize;
621 CharUnits NonVirtualAlignment;
623 /// PrimaryBase - the primary base class (if one exists) of the class
624 /// we're laying out.
625 const CXXRecordDecl *PrimaryBase;
627 /// PrimaryBaseIsVirtual - Whether the primary base of the class we're laying
629 bool PrimaryBaseIsVirtual;
631 /// HasOwnVFPtr - Whether the class provides its own vtable/vftbl
632 /// pointer, as opposed to inheriting one from a primary base class.
635 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
637 /// Bases - base classes and their offsets in the record.
638 BaseOffsetsMapTy Bases;
640 // VBases - virtual base classes and their offsets in the record.
641 ASTRecordLayout::VBaseOffsetsMapTy VBases;
643 /// IndirectPrimaryBases - Virtual base classes, direct or indirect, that are
644 /// primary base classes for some other direct or indirect base class.
645 CXXIndirectPrimaryBaseSet IndirectPrimaryBases;
647 /// FirstNearlyEmptyVBase - The first nearly empty virtual base class in
648 /// inheritance graph order. Used for determining the primary base class.
649 const CXXRecordDecl *FirstNearlyEmptyVBase;
651 /// VisitedVirtualBases - A set of all the visited virtual bases, used to
652 /// avoid visiting virtual bases more than once.
653 llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
655 /// Valid if UseExternalLayout is true.
656 ExternalLayout External;
658 ItaniumRecordLayoutBuilder(const ASTContext &Context,
659 EmptySubobjectMap *EmptySubobjects)
660 : Context(Context), EmptySubobjects(EmptySubobjects), Size(0),
661 Alignment(CharUnits::One()), UnpackedAlignment(CharUnits::One()),
662 UseExternalLayout(false), InferAlignment(false), Packed(false),
663 IsUnion(false), IsMac68kAlign(false), IsMsStruct(false),
664 UnfilledBitsInLastUnit(0), LastBitfieldTypeSize(0),
665 MaxFieldAlignment(CharUnits::Zero()), DataSize(0),
666 NonVirtualSize(CharUnits::Zero()),
667 NonVirtualAlignment(CharUnits::One()), PrimaryBase(nullptr),
668 PrimaryBaseIsVirtual(false), HasOwnVFPtr(false),
669 FirstNearlyEmptyVBase(nullptr) {}
671 void Layout(const RecordDecl *D);
672 void Layout(const CXXRecordDecl *D);
673 void Layout(const ObjCInterfaceDecl *D);
675 void LayoutFields(const RecordDecl *D);
676 void LayoutField(const FieldDecl *D, bool InsertExtraPadding);
677 void LayoutWideBitField(uint64_t FieldSize, uint64_t TypeSize,
678 bool FieldPacked, const FieldDecl *D);
679 void LayoutBitField(const FieldDecl *D);
681 TargetCXXABI getCXXABI() const {
682 return Context.getTargetInfo().getCXXABI();
685 /// BaseSubobjectInfoAllocator - Allocator for BaseSubobjectInfo objects.
686 llvm::SpecificBumpPtrAllocator<BaseSubobjectInfo> BaseSubobjectInfoAllocator;
688 typedef llvm::DenseMap<const CXXRecordDecl *, BaseSubobjectInfo *>
689 BaseSubobjectInfoMapTy;
691 /// VirtualBaseInfo - Map from all the (direct or indirect) virtual bases
692 /// of the class we're laying out to their base subobject info.
693 BaseSubobjectInfoMapTy VirtualBaseInfo;
695 /// NonVirtualBaseInfo - Map from all the direct non-virtual bases of the
696 /// class we're laying out to their base subobject info.
697 BaseSubobjectInfoMapTy NonVirtualBaseInfo;
699 /// ComputeBaseSubobjectInfo - Compute the base subobject information for the
700 /// bases of the given class.
701 void ComputeBaseSubobjectInfo(const CXXRecordDecl *RD);
703 /// ComputeBaseSubobjectInfo - Compute the base subobject information for a
704 /// single class and all of its base classes.
705 BaseSubobjectInfo *ComputeBaseSubobjectInfo(const CXXRecordDecl *RD,
707 BaseSubobjectInfo *Derived);
709 /// DeterminePrimaryBase - Determine the primary base of the given class.
710 void DeterminePrimaryBase(const CXXRecordDecl *RD);
712 void SelectPrimaryVBase(const CXXRecordDecl *RD);
714 void EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign);
716 /// LayoutNonVirtualBases - Determines the primary base class (if any) and
717 /// lays it out. Will then proceed to lay out all non-virtual base clasess.
718 void LayoutNonVirtualBases(const CXXRecordDecl *RD);
720 /// LayoutNonVirtualBase - Lays out a single non-virtual base.
721 void LayoutNonVirtualBase(const BaseSubobjectInfo *Base);
723 void AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
726 /// LayoutVirtualBases - Lays out all the virtual bases.
727 void LayoutVirtualBases(const CXXRecordDecl *RD,
728 const CXXRecordDecl *MostDerivedClass);
730 /// LayoutVirtualBase - Lays out a single virtual base.
731 void LayoutVirtualBase(const BaseSubobjectInfo *Base);
733 /// LayoutBase - Will lay out a base and return the offset where it was
734 /// placed, in chars.
735 CharUnits LayoutBase(const BaseSubobjectInfo *Base);
737 /// InitializeLayout - Initialize record layout for the given record decl.
738 void InitializeLayout(const Decl *D);
740 /// FinishLayout - Finalize record layout. Adjust record size based on the
742 void FinishLayout(const NamedDecl *D);
744 void UpdateAlignment(CharUnits NewAlignment, CharUnits UnpackedNewAlignment);
745 void UpdateAlignment(CharUnits NewAlignment) {
746 UpdateAlignment(NewAlignment, NewAlignment);
749 /// \brief Retrieve the externally-supplied field offset for the given
752 /// \param Field The field whose offset is being queried.
753 /// \param ComputedOffset The offset that we've computed for this field.
754 uint64_t updateExternalFieldOffset(const FieldDecl *Field,
755 uint64_t ComputedOffset);
757 void CheckFieldPadding(uint64_t Offset, uint64_t UnpaddedOffset,
758 uint64_t UnpackedOffset, unsigned UnpackedAlign,
759 bool isPacked, const FieldDecl *D);
761 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
763 CharUnits getSize() const {
764 assert(Size % Context.getCharWidth() == 0);
765 return Context.toCharUnitsFromBits(Size);
767 uint64_t getSizeInBits() const { return Size; }
769 void setSize(CharUnits NewSize) { Size = Context.toBits(NewSize); }
770 void setSize(uint64_t NewSize) { Size = NewSize; }
772 CharUnits getAligment() const { return Alignment; }
774 CharUnits getDataSize() const {
775 assert(DataSize % Context.getCharWidth() == 0);
776 return Context.toCharUnitsFromBits(DataSize);
778 uint64_t getDataSizeInBits() const { return DataSize; }
780 void setDataSize(CharUnits NewSize) { DataSize = Context.toBits(NewSize); }
781 void setDataSize(uint64_t NewSize) { DataSize = NewSize; }
783 ItaniumRecordLayoutBuilder(const ItaniumRecordLayoutBuilder &) = delete;
784 void operator=(const ItaniumRecordLayoutBuilder &) = delete;
786 } // end anonymous namespace
788 void ItaniumRecordLayoutBuilder::SelectPrimaryVBase(const CXXRecordDecl *RD) {
789 for (const auto &I : RD->bases()) {
790 assert(!I.getType()->isDependentType() &&
791 "Cannot layout class with dependent bases.");
793 const CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
795 // Check if this is a nearly empty virtual base.
796 if (I.isVirtual() && Context.isNearlyEmpty(Base)) {
797 // If it's not an indirect primary base, then we've found our primary
799 if (!IndirectPrimaryBases.count(Base)) {
801 PrimaryBaseIsVirtual = true;
805 // Is this the first nearly empty virtual base?
806 if (!FirstNearlyEmptyVBase)
807 FirstNearlyEmptyVBase = Base;
810 SelectPrimaryVBase(Base);
816 /// DeterminePrimaryBase - Determine the primary base of the given class.
817 void ItaniumRecordLayoutBuilder::DeterminePrimaryBase(const CXXRecordDecl *RD) {
818 // If the class isn't dynamic, it won't have a primary base.
819 if (!RD->isDynamicClass())
822 // Compute all the primary virtual bases for all of our direct and
823 // indirect bases, and record all their primary virtual base classes.
824 RD->getIndirectPrimaryBases(IndirectPrimaryBases);
826 // If the record has a dynamic base class, attempt to choose a primary base
827 // class. It is the first (in direct base class order) non-virtual dynamic
828 // base class, if one exists.
829 for (const auto &I : RD->bases()) {
830 // Ignore virtual bases.
834 const CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
836 if (Base->isDynamicClass()) {
839 PrimaryBaseIsVirtual = false;
844 // Under the Itanium ABI, if there is no non-virtual primary base class,
845 // try to compute the primary virtual base. The primary virtual base is
846 // the first nearly empty virtual base that is not an indirect primary
847 // virtual base class, if one exists.
848 if (RD->getNumVBases() != 0) {
849 SelectPrimaryVBase(RD);
854 // Otherwise, it is the first indirect primary base class, if one exists.
855 if (FirstNearlyEmptyVBase) {
856 PrimaryBase = FirstNearlyEmptyVBase;
857 PrimaryBaseIsVirtual = true;
861 assert(!PrimaryBase && "Should not get here with a primary base!");
864 BaseSubobjectInfo *ItaniumRecordLayoutBuilder::ComputeBaseSubobjectInfo(
865 const CXXRecordDecl *RD, bool IsVirtual, BaseSubobjectInfo *Derived) {
866 BaseSubobjectInfo *Info;
869 // Check if we already have info about this virtual base.
870 BaseSubobjectInfo *&InfoSlot = VirtualBaseInfo[RD];
872 assert(InfoSlot->Class == RD && "Wrong class for virtual base info!");
876 // We don't, create it.
877 InfoSlot = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
880 Info = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
884 Info->IsVirtual = IsVirtual;
885 Info->Derived = nullptr;
886 Info->PrimaryVirtualBaseInfo = nullptr;
888 const CXXRecordDecl *PrimaryVirtualBase = nullptr;
889 BaseSubobjectInfo *PrimaryVirtualBaseInfo = nullptr;
891 // Check if this base has a primary virtual base.
892 if (RD->getNumVBases()) {
893 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
894 if (Layout.isPrimaryBaseVirtual()) {
895 // This base does have a primary virtual base.
896 PrimaryVirtualBase = Layout.getPrimaryBase();
897 assert(PrimaryVirtualBase && "Didn't have a primary virtual base!");
899 // Now check if we have base subobject info about this primary base.
900 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
902 if (PrimaryVirtualBaseInfo) {
903 if (PrimaryVirtualBaseInfo->Derived) {
904 // We did have info about this primary base, and it turns out that it
905 // has already been claimed as a primary virtual base for another
907 PrimaryVirtualBase = nullptr;
909 // We can claim this base as our primary base.
910 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
911 PrimaryVirtualBaseInfo->Derived = Info;
917 // Now go through all direct bases.
918 for (const auto &I : RD->bases()) {
919 bool IsVirtual = I.isVirtual();
921 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
923 Info->Bases.push_back(ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, Info));
926 if (PrimaryVirtualBase && !PrimaryVirtualBaseInfo) {
927 // Traversing the bases must have created the base info for our primary
929 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
930 assert(PrimaryVirtualBaseInfo &&
931 "Did not create a primary virtual base!");
933 // Claim the primary virtual base as our primary virtual base.
934 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
935 PrimaryVirtualBaseInfo->Derived = Info;
941 void ItaniumRecordLayoutBuilder::ComputeBaseSubobjectInfo(
942 const CXXRecordDecl *RD) {
943 for (const auto &I : RD->bases()) {
944 bool IsVirtual = I.isVirtual();
946 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
948 // Compute the base subobject info for this base.
949 BaseSubobjectInfo *Info = ComputeBaseSubobjectInfo(BaseDecl, IsVirtual,
953 // ComputeBaseInfo has already added this base for us.
954 assert(VirtualBaseInfo.count(BaseDecl) &&
955 "Did not add virtual base!");
957 // Add the base info to the map of non-virtual bases.
958 assert(!NonVirtualBaseInfo.count(BaseDecl) &&
959 "Non-virtual base already exists!");
960 NonVirtualBaseInfo.insert(std::make_pair(BaseDecl, Info));
965 void ItaniumRecordLayoutBuilder::EnsureVTablePointerAlignment(
966 CharUnits UnpackedBaseAlign) {
967 CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
969 // The maximum field alignment overrides base align.
970 if (!MaxFieldAlignment.isZero()) {
971 BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
972 UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
975 // Round up the current record size to pointer alignment.
976 setSize(getSize().RoundUpToAlignment(BaseAlign));
977 setDataSize(getSize());
979 // Update the alignment.
980 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
983 void ItaniumRecordLayoutBuilder::LayoutNonVirtualBases(
984 const CXXRecordDecl *RD) {
985 // Then, determine the primary base class.
986 DeterminePrimaryBase(RD);
988 // Compute base subobject info.
989 ComputeBaseSubobjectInfo(RD);
991 // If we have a primary base class, lay it out.
993 if (PrimaryBaseIsVirtual) {
994 // If the primary virtual base was a primary virtual base of some other
995 // base class we'll have to steal it.
996 BaseSubobjectInfo *PrimaryBaseInfo = VirtualBaseInfo.lookup(PrimaryBase);
997 PrimaryBaseInfo->Derived = nullptr;
999 // We have a virtual primary base, insert it as an indirect primary base.
1000 IndirectPrimaryBases.insert(PrimaryBase);
1002 assert(!VisitedVirtualBases.count(PrimaryBase) &&
1003 "vbase already visited!");
1004 VisitedVirtualBases.insert(PrimaryBase);
1006 LayoutVirtualBase(PrimaryBaseInfo);
1008 BaseSubobjectInfo *PrimaryBaseInfo =
1009 NonVirtualBaseInfo.lookup(PrimaryBase);
1010 assert(PrimaryBaseInfo &&
1011 "Did not find base info for non-virtual primary base!");
1013 LayoutNonVirtualBase(PrimaryBaseInfo);
1016 // If this class needs a vtable/vf-table and didn't get one from a
1017 // primary base, add it in now.
1018 } else if (RD->isDynamicClass()) {
1019 assert(DataSize == 0 && "Vtable pointer must be at offset zero!");
1020 CharUnits PtrWidth =
1021 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
1022 CharUnits PtrAlign =
1023 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0));
1024 EnsureVTablePointerAlignment(PtrAlign);
1026 setSize(getSize() + PtrWidth);
1027 setDataSize(getSize());
1030 // Now lay out the non-virtual bases.
1031 for (const auto &I : RD->bases()) {
1033 // Ignore virtual bases.
1037 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
1039 // Skip the primary base, because we've already laid it out. The
1040 // !PrimaryBaseIsVirtual check is required because we might have a
1041 // non-virtual base of the same type as a primary virtual base.
1042 if (BaseDecl == PrimaryBase && !PrimaryBaseIsVirtual)
1045 // Lay out the base.
1046 BaseSubobjectInfo *BaseInfo = NonVirtualBaseInfo.lookup(BaseDecl);
1047 assert(BaseInfo && "Did not find base info for non-virtual base!");
1049 LayoutNonVirtualBase(BaseInfo);
1053 void ItaniumRecordLayoutBuilder::LayoutNonVirtualBase(
1054 const BaseSubobjectInfo *Base) {
1056 CharUnits Offset = LayoutBase(Base);
1058 // Add its base class offset.
1059 assert(!Bases.count(Base->Class) && "base offset already exists!");
1060 Bases.insert(std::make_pair(Base->Class, Offset));
1062 AddPrimaryVirtualBaseOffsets(Base, Offset);
1065 void ItaniumRecordLayoutBuilder::AddPrimaryVirtualBaseOffsets(
1066 const BaseSubobjectInfo *Info, CharUnits Offset) {
1067 // This base isn't interesting, it has no virtual bases.
1068 if (!Info->Class->getNumVBases())
1071 // First, check if we have a virtual primary base to add offsets for.
1072 if (Info->PrimaryVirtualBaseInfo) {
1073 assert(Info->PrimaryVirtualBaseInfo->IsVirtual &&
1074 "Primary virtual base is not virtual!");
1075 if (Info->PrimaryVirtualBaseInfo->Derived == Info) {
1077 assert(!VBases.count(Info->PrimaryVirtualBaseInfo->Class) &&
1078 "primary vbase offset already exists!");
1079 VBases.insert(std::make_pair(Info->PrimaryVirtualBaseInfo->Class,
1080 ASTRecordLayout::VBaseInfo(Offset, false)));
1082 // Traverse the primary virtual base.
1083 AddPrimaryVirtualBaseOffsets(Info->PrimaryVirtualBaseInfo, Offset);
1087 // Now go through all direct non-virtual bases.
1088 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
1089 for (const BaseSubobjectInfo *Base : Info->Bases) {
1090 if (Base->IsVirtual)
1093 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
1094 AddPrimaryVirtualBaseOffsets(Base, BaseOffset);
1098 void ItaniumRecordLayoutBuilder::LayoutVirtualBases(
1099 const CXXRecordDecl *RD, const CXXRecordDecl *MostDerivedClass) {
1100 const CXXRecordDecl *PrimaryBase;
1101 bool PrimaryBaseIsVirtual;
1103 if (MostDerivedClass == RD) {
1104 PrimaryBase = this->PrimaryBase;
1105 PrimaryBaseIsVirtual = this->PrimaryBaseIsVirtual;
1107 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1108 PrimaryBase = Layout.getPrimaryBase();
1109 PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
1112 for (const CXXBaseSpecifier &Base : RD->bases()) {
1113 assert(!Base.getType()->isDependentType() &&
1114 "Cannot layout class with dependent bases.");
1116 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
1118 if (Base.isVirtual()) {
1119 if (PrimaryBase != BaseDecl || !PrimaryBaseIsVirtual) {
1120 bool IndirectPrimaryBase = IndirectPrimaryBases.count(BaseDecl);
1122 // Only lay out the virtual base if it's not an indirect primary base.
1123 if (!IndirectPrimaryBase) {
1124 // Only visit virtual bases once.
1125 if (!VisitedVirtualBases.insert(BaseDecl).second)
1128 const BaseSubobjectInfo *BaseInfo = VirtualBaseInfo.lookup(BaseDecl);
1129 assert(BaseInfo && "Did not find virtual base info!");
1130 LayoutVirtualBase(BaseInfo);
1135 if (!BaseDecl->getNumVBases()) {
1136 // This base isn't interesting since it doesn't have any virtual bases.
1140 LayoutVirtualBases(BaseDecl, MostDerivedClass);
1144 void ItaniumRecordLayoutBuilder::LayoutVirtualBase(
1145 const BaseSubobjectInfo *Base) {
1146 assert(!Base->Derived && "Trying to lay out a primary virtual base!");
1149 CharUnits Offset = LayoutBase(Base);
1151 // Add its base class offset.
1152 assert(!VBases.count(Base->Class) && "vbase offset already exists!");
1153 VBases.insert(std::make_pair(Base->Class,
1154 ASTRecordLayout::VBaseInfo(Offset, false)));
1156 AddPrimaryVirtualBaseOffsets(Base, Offset);
1160 ItaniumRecordLayoutBuilder::LayoutBase(const BaseSubobjectInfo *Base) {
1161 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base->Class);
1166 // Query the external layout to see if it provides an offset.
1167 bool HasExternalLayout = false;
1168 if (UseExternalLayout) {
1169 llvm::DenseMap<const CXXRecordDecl *, CharUnits>::iterator Known;
1170 if (Base->IsVirtual)
1171 HasExternalLayout = External.getExternalNVBaseOffset(Base->Class, Offset);
1173 HasExternalLayout = External.getExternalVBaseOffset(Base->Class, Offset);
1176 CharUnits UnpackedBaseAlign = Layout.getNonVirtualAlignment();
1177 CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
1179 // If we have an empty base class, try to place it at offset 0.
1180 if (Base->Class->isEmpty() &&
1181 (!HasExternalLayout || Offset == CharUnits::Zero()) &&
1182 EmptySubobjects->CanPlaceBaseAtOffset(Base, CharUnits::Zero())) {
1183 setSize(std::max(getSize(), Layout.getSize()));
1184 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
1186 return CharUnits::Zero();
1189 // The maximum field alignment overrides base align.
1190 if (!MaxFieldAlignment.isZero()) {
1191 BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
1192 UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
1195 if (!HasExternalLayout) {
1196 // Round up the current record size to the base's alignment boundary.
1197 Offset = getDataSize().RoundUpToAlignment(BaseAlign);
1199 // Try to place the base.
1200 while (!EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset))
1201 Offset += BaseAlign;
1203 bool Allowed = EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset);
1205 assert(Allowed && "Base subobject externally placed at overlapping offset");
1207 if (InferAlignment && Offset < getDataSize().RoundUpToAlignment(BaseAlign)){
1208 // The externally-supplied base offset is before the base offset we
1209 // computed. Assume that the structure is packed.
1210 Alignment = CharUnits::One();
1211 InferAlignment = false;
1215 if (!Base->Class->isEmpty()) {
1216 // Update the data size.
1217 setDataSize(Offset + Layout.getNonVirtualSize());
1219 setSize(std::max(getSize(), getDataSize()));
1221 setSize(std::max(getSize(), Offset + Layout.getSize()));
1223 // Remember max struct/class alignment.
1224 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
1229 void ItaniumRecordLayoutBuilder::InitializeLayout(const Decl *D) {
1230 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
1231 IsUnion = RD->isUnion();
1232 IsMsStruct = RD->isMsStruct(Context);
1235 Packed = D->hasAttr<PackedAttr>();
1237 // Honor the default struct packing maximum alignment flag.
1238 if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct) {
1239 MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
1242 // mac68k alignment supersedes maximum field alignment and attribute aligned,
1243 // and forces all structures to have 2-byte alignment. The IBM docs on it
1244 // allude to additional (more complicated) semantics, especially with regard
1245 // to bit-fields, but gcc appears not to follow that.
1246 if (D->hasAttr<AlignMac68kAttr>()) {
1247 IsMac68kAlign = true;
1248 MaxFieldAlignment = CharUnits::fromQuantity(2);
1249 Alignment = CharUnits::fromQuantity(2);
1251 if (const MaxFieldAlignmentAttr *MFAA = D->getAttr<MaxFieldAlignmentAttr>())
1252 MaxFieldAlignment = Context.toCharUnitsFromBits(MFAA->getAlignment());
1254 if (unsigned MaxAlign = D->getMaxAlignment())
1255 UpdateAlignment(Context.toCharUnitsFromBits(MaxAlign));
1258 // If there is an external AST source, ask it for the various offsets.
1259 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
1260 if (ExternalASTSource *Source = Context.getExternalSource()) {
1261 UseExternalLayout = Source->layoutRecordType(
1262 RD, External.Size, External.Align, External.FieldOffsets,
1263 External.BaseOffsets, External.VirtualBaseOffsets);
1265 // Update based on external alignment.
1266 if (UseExternalLayout) {
1267 if (External.Align > 0) {
1268 Alignment = Context.toCharUnitsFromBits(External.Align);
1270 // The external source didn't have alignment information; infer it.
1271 InferAlignment = true;
1277 void ItaniumRecordLayoutBuilder::Layout(const RecordDecl *D) {
1278 InitializeLayout(D);
1281 // Finally, round the size of the total struct up to the alignment of the
1286 void ItaniumRecordLayoutBuilder::Layout(const CXXRecordDecl *RD) {
1287 InitializeLayout(RD);
1289 // Lay out the vtable and the non-virtual bases.
1290 LayoutNonVirtualBases(RD);
1294 NonVirtualSize = Context.toCharUnitsFromBits(
1295 llvm::RoundUpToAlignment(getSizeInBits(),
1296 Context.getTargetInfo().getCharAlign()));
1297 NonVirtualAlignment = Alignment;
1299 // Lay out the virtual bases and add the primary virtual base offsets.
1300 LayoutVirtualBases(RD, RD);
1302 // Finally, round the size of the total struct up to the alignment
1303 // of the struct itself.
1307 // Check that we have base offsets for all bases.
1308 for (const CXXBaseSpecifier &Base : RD->bases()) {
1309 if (Base.isVirtual())
1312 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
1314 assert(Bases.count(BaseDecl) && "Did not find base offset!");
1317 // And all virtual bases.
1318 for (const CXXBaseSpecifier &Base : RD->vbases()) {
1319 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
1321 assert(VBases.count(BaseDecl) && "Did not find base offset!");
1326 void ItaniumRecordLayoutBuilder::Layout(const ObjCInterfaceDecl *D) {
1327 if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
1328 const ASTRecordLayout &SL = Context.getASTObjCInterfaceLayout(SD);
1330 UpdateAlignment(SL.getAlignment());
1332 // We start laying out ivars not at the end of the superclass
1333 // structure, but at the next byte following the last field.
1334 setSize(SL.getDataSize());
1335 setDataSize(getSize());
1338 InitializeLayout(D);
1339 // Layout each ivar sequentially.
1340 for (const ObjCIvarDecl *IVD = D->all_declared_ivar_begin(); IVD;
1341 IVD = IVD->getNextIvar())
1342 LayoutField(IVD, false);
1344 // Finally, round the size of the total struct up to the alignment of the
1349 void ItaniumRecordLayoutBuilder::LayoutFields(const RecordDecl *D) {
1350 // Layout each field, for now, just sequentially, respecting alignment. In
1351 // the future, this will need to be tweakable by targets.
1352 bool InsertExtraPadding = D->mayInsertExtraPadding(/*EmitRemark=*/true);
1353 bool HasFlexibleArrayMember = D->hasFlexibleArrayMember();
1354 for (auto I = D->field_begin(), End = D->field_end(); I != End; ++I) {
1358 InsertExtraPadding && (Next != End || !HasFlexibleArrayMember));
1362 // Rounds the specified size to have it a multiple of the char size.
1364 roundUpSizeToCharAlignment(uint64_t Size,
1365 const ASTContext &Context) {
1366 uint64_t CharAlignment = Context.getTargetInfo().getCharAlign();
1367 return llvm::RoundUpToAlignment(Size, CharAlignment);
1370 void ItaniumRecordLayoutBuilder::LayoutWideBitField(uint64_t FieldSize,
1373 const FieldDecl *D) {
1374 assert(Context.getLangOpts().CPlusPlus &&
1375 "Can only have wide bit-fields in C++!");
1377 // Itanium C++ ABI 2.4:
1378 // If sizeof(T)*8 < n, let T' be the largest integral POD type with
1379 // sizeof(T')*8 <= n.
1381 QualType IntegralPODTypes[] = {
1382 Context.UnsignedCharTy, Context.UnsignedShortTy, Context.UnsignedIntTy,
1383 Context.UnsignedLongTy, Context.UnsignedLongLongTy
1387 for (const QualType &QT : IntegralPODTypes) {
1388 uint64_t Size = Context.getTypeSize(QT);
1390 if (Size > FieldSize)
1395 assert(!Type.isNull() && "Did not find a type!");
1397 CharUnits TypeAlign = Context.getTypeAlignInChars(Type);
1399 // We're not going to use any of the unfilled bits in the last byte.
1400 UnfilledBitsInLastUnit = 0;
1401 LastBitfieldTypeSize = 0;
1403 uint64_t FieldOffset;
1404 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
1407 uint64_t RoundedFieldSize = roundUpSizeToCharAlignment(FieldSize,
1409 setDataSize(std::max(getDataSizeInBits(), RoundedFieldSize));
1412 // The bitfield is allocated starting at the next offset aligned
1413 // appropriately for T', with length n bits.
1414 FieldOffset = llvm::RoundUpToAlignment(getDataSizeInBits(),
1415 Context.toBits(TypeAlign));
1417 uint64_t NewSizeInBits = FieldOffset + FieldSize;
1419 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits,
1420 Context.getTargetInfo().getCharAlign()));
1421 UnfilledBitsInLastUnit = getDataSizeInBits() - NewSizeInBits;
1424 // Place this field at the current location.
1425 FieldOffsets.push_back(FieldOffset);
1427 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, FieldOffset,
1428 Context.toBits(TypeAlign), FieldPacked, D);
1431 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1433 // Remember max struct/class alignment.
1434 UpdateAlignment(TypeAlign);
1437 void ItaniumRecordLayoutBuilder::LayoutBitField(const FieldDecl *D) {
1438 bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
1439 uint64_t FieldSize = D->getBitWidthValue(Context);
1440 TypeInfo FieldInfo = Context.getTypeInfo(D->getType());
1441 uint64_t TypeSize = FieldInfo.Width;
1442 unsigned FieldAlign = FieldInfo.Align;
1444 // UnfilledBitsInLastUnit is the difference between the end of the
1445 // last allocated bitfield (i.e. the first bit offset available for
1446 // bitfields) and the end of the current data size in bits (i.e. the
1447 // first bit offset available for non-bitfields). The current data
1448 // size in bits is always a multiple of the char size; additionally,
1449 // for ms_struct records it's also a multiple of the
1450 // LastBitfieldTypeSize (if set).
1452 // The struct-layout algorithm is dictated by the platform ABI,
1453 // which in principle could use almost any rules it likes. In
1454 // practice, UNIXy targets tend to inherit the algorithm described
1455 // in the System V generic ABI. The basic bitfield layout rule in
1456 // System V is to place bitfields at the next available bit offset
1457 // where the entire bitfield would fit in an aligned storage unit of
1458 // the declared type; it's okay if an earlier or later non-bitfield
1459 // is allocated in the same storage unit. However, some targets
1460 // (those that !useBitFieldTypeAlignment(), e.g. ARM APCS) don't
1461 // require this storage unit to be aligned, and therefore always put
1462 // the bitfield at the next available bit offset.
1464 // ms_struct basically requests a complete replacement of the
1465 // platform ABI's struct-layout algorithm, with the high-level goal
1466 // of duplicating MSVC's layout. For non-bitfields, this follows
1467 // the standard algorithm. The basic bitfield layout rule is to
1468 // allocate an entire unit of the bitfield's declared type
1469 // (e.g. 'unsigned long'), then parcel it up among successive
1470 // bitfields whose declared types have the same size, making a new
1471 // unit as soon as the last can no longer store the whole value.
1472 // Since it completely replaces the platform ABI's algorithm,
1473 // settings like !useBitFieldTypeAlignment() do not apply.
1475 // A zero-width bitfield forces the use of a new storage unit for
1476 // later bitfields. In general, this occurs by rounding up the
1477 // current size of the struct as if the algorithm were about to
1478 // place a non-bitfield of the field's formal type. Usually this
1479 // does not change the alignment of the struct itself, but it does
1480 // on some targets (those that useZeroLengthBitfieldAlignment(),
1481 // e.g. ARM). In ms_struct layout, zero-width bitfields are
1482 // ignored unless they follow a non-zero-width bitfield.
1484 // A field alignment restriction (e.g. from #pragma pack) or
1485 // specification (e.g. from __attribute__((aligned))) changes the
1486 // formal alignment of the field. For System V, this alters the
1487 // required alignment of the notional storage unit that must contain
1488 // the bitfield. For ms_struct, this only affects the placement of
1489 // new storage units. In both cases, the effect of #pragma pack is
1490 // ignored on zero-width bitfields.
1492 // On System V, a packed field (e.g. from #pragma pack or
1493 // __attribute__((packed))) always uses the next available bit
1496 // In an ms_struct struct, the alignment of a fundamental type is
1497 // always equal to its size. This is necessary in order to mimic
1498 // the i386 alignment rules on targets which might not fully align
1499 // all types (e.g. Darwin PPC32, where alignof(long long) == 4).
1501 // First, some simple bookkeeping to perform for ms_struct structs.
1503 // The field alignment for integer types is always the size.
1504 FieldAlign = TypeSize;
1506 // If the previous field was not a bitfield, or was a bitfield
1507 // with a different storage unit size, we're done with that
1509 if (LastBitfieldTypeSize != TypeSize) {
1510 // Also, ignore zero-length bitfields after non-bitfields.
1511 if (!LastBitfieldTypeSize && !FieldSize)
1514 UnfilledBitsInLastUnit = 0;
1515 LastBitfieldTypeSize = 0;
1519 // If the field is wider than its declared type, it follows
1520 // different rules in all cases.
1521 if (FieldSize > TypeSize) {
1522 LayoutWideBitField(FieldSize, TypeSize, FieldPacked, D);
1526 // Compute the next available bit offset.
1527 uint64_t FieldOffset =
1528 IsUnion ? 0 : (getDataSizeInBits() - UnfilledBitsInLastUnit);
1530 // Handle targets that don't honor bitfield type alignment.
1531 if (!IsMsStruct && !Context.getTargetInfo().useBitFieldTypeAlignment()) {
1532 // Some such targets do honor it on zero-width bitfields.
1533 if (FieldSize == 0 &&
1534 Context.getTargetInfo().useZeroLengthBitfieldAlignment()) {
1535 // The alignment to round up to is the max of the field's natural
1536 // alignment and a target-specific fixed value (sometimes zero).
1537 unsigned ZeroLengthBitfieldBoundary =
1538 Context.getTargetInfo().getZeroLengthBitfieldBoundary();
1539 FieldAlign = std::max(FieldAlign, ZeroLengthBitfieldBoundary);
1541 // If that doesn't apply, just ignore the field alignment.
1547 // Remember the alignment we would have used if the field were not packed.
1548 unsigned UnpackedFieldAlign = FieldAlign;
1550 // Ignore the field alignment if the field is packed unless it has zero-size.
1551 if (!IsMsStruct && FieldPacked && FieldSize != 0)
1554 // But, if there's an 'aligned' attribute on the field, honor that.
1555 unsigned ExplicitFieldAlign = D->getMaxAlignment();
1556 if (ExplicitFieldAlign) {
1557 FieldAlign = std::max(FieldAlign, ExplicitFieldAlign);
1558 UnpackedFieldAlign = std::max(UnpackedFieldAlign, ExplicitFieldAlign);
1561 // But, if there's a #pragma pack in play, that takes precedent over
1562 // even the 'aligned' attribute, for non-zero-width bitfields.
1563 if (!MaxFieldAlignment.isZero() && FieldSize) {
1564 unsigned MaxFieldAlignmentInBits = Context.toBits(MaxFieldAlignment);
1565 FieldAlign = std::min(FieldAlign, MaxFieldAlignmentInBits);
1566 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignmentInBits);
1569 // But, ms_struct just ignores all of that in unions, even explicit
1570 // alignment attributes.
1571 if (IsMsStruct && IsUnion) {
1572 FieldAlign = UnpackedFieldAlign = 1;
1575 // For purposes of diagnostics, we're going to simultaneously
1576 // compute the field offsets that we would have used if we weren't
1577 // adding any alignment padding or if the field weren't packed.
1578 uint64_t UnpaddedFieldOffset = FieldOffset;
1579 uint64_t UnpackedFieldOffset = FieldOffset;
1581 // Check if we need to add padding to fit the bitfield within an
1582 // allocation unit with the right size and alignment. The rules are
1583 // somewhat different here for ms_struct structs.
1585 // If it's not a zero-width bitfield, and we can fit the bitfield
1586 // into the active storage unit (and we haven't already decided to
1587 // start a new storage unit), just do so, regardless of any other
1588 // other consideration. Otherwise, round up to the right alignment.
1589 if (FieldSize == 0 || FieldSize > UnfilledBitsInLastUnit) {
1590 FieldOffset = llvm::RoundUpToAlignment(FieldOffset, FieldAlign);
1591 UnpackedFieldOffset = llvm::RoundUpToAlignment(UnpackedFieldOffset,
1592 UnpackedFieldAlign);
1593 UnfilledBitsInLastUnit = 0;
1597 // #pragma pack, with any value, suppresses the insertion of padding.
1598 bool AllowPadding = MaxFieldAlignment.isZero();
1600 // Compute the real offset.
1601 if (FieldSize == 0 ||
1603 (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize)) {
1604 FieldOffset = llvm::RoundUpToAlignment(FieldOffset, FieldAlign);
1605 } else if (ExplicitFieldAlign) {
1606 // TODO: figure it out what needs to be done on targets that don't honor
1607 // bit-field type alignment like ARM APCS ABI.
1608 FieldOffset = llvm::RoundUpToAlignment(FieldOffset, ExplicitFieldAlign);
1611 // Repeat the computation for diagnostic purposes.
1612 if (FieldSize == 0 ||
1614 (UnpackedFieldOffset & (UnpackedFieldAlign-1)) + FieldSize > TypeSize))
1615 UnpackedFieldOffset = llvm::RoundUpToAlignment(UnpackedFieldOffset,
1616 UnpackedFieldAlign);
1617 else if (ExplicitFieldAlign)
1618 UnpackedFieldOffset = llvm::RoundUpToAlignment(UnpackedFieldOffset,
1619 ExplicitFieldAlign);
1622 // If we're using external layout, give the external layout a chance
1623 // to override this information.
1624 if (UseExternalLayout)
1625 FieldOffset = updateExternalFieldOffset(D, FieldOffset);
1627 // Okay, place the bitfield at the calculated offset.
1628 FieldOffsets.push_back(FieldOffset);
1632 // Anonymous members don't affect the overall record alignment,
1633 // except on targets where they do.
1635 !Context.getTargetInfo().useZeroLengthBitfieldAlignment() &&
1636 !D->getIdentifier())
1637 FieldAlign = UnpackedFieldAlign = 1;
1639 // Diagnose differences in layout due to padding or packing.
1640 if (!UseExternalLayout)
1641 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, UnpackedFieldOffset,
1642 UnpackedFieldAlign, FieldPacked, D);
1644 // Update DataSize to include the last byte containing (part of) the bitfield.
1646 // For unions, this is just a max operation, as usual.
1648 // For ms_struct, allocate the entire storage unit --- unless this
1649 // is a zero-width bitfield, in which case just use a size of 1.
1650 uint64_t RoundedFieldSize;
1653 (FieldSize ? TypeSize : Context.getTargetInfo().getCharWidth());
1655 // Otherwise, allocate just the number of bytes required to store
1658 RoundedFieldSize = roundUpSizeToCharAlignment(FieldSize, Context);
1660 setDataSize(std::max(getDataSizeInBits(), RoundedFieldSize));
1662 // For non-zero-width bitfields in ms_struct structs, allocate a new
1663 // storage unit if necessary.
1664 } else if (IsMsStruct && FieldSize) {
1665 // We should have cleared UnfilledBitsInLastUnit in every case
1666 // where we changed storage units.
1667 if (!UnfilledBitsInLastUnit) {
1668 setDataSize(FieldOffset + TypeSize);
1669 UnfilledBitsInLastUnit = TypeSize;
1671 UnfilledBitsInLastUnit -= FieldSize;
1672 LastBitfieldTypeSize = TypeSize;
1674 // Otherwise, bump the data size up to include the bitfield,
1675 // including padding up to char alignment, and then remember how
1676 // bits we didn't use.
1678 uint64_t NewSizeInBits = FieldOffset + FieldSize;
1679 uint64_t CharAlignment = Context.getTargetInfo().getCharAlign();
1680 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits, CharAlignment));
1681 UnfilledBitsInLastUnit = getDataSizeInBits() - NewSizeInBits;
1683 // The only time we can get here for an ms_struct is if this is a
1684 // zero-width bitfield, which doesn't count as anything for the
1685 // purposes of unfilled bits.
1686 LastBitfieldTypeSize = 0;
1690 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1692 // Remember max struct/class alignment.
1693 UpdateAlignment(Context.toCharUnitsFromBits(FieldAlign),
1694 Context.toCharUnitsFromBits(UnpackedFieldAlign));
1697 void ItaniumRecordLayoutBuilder::LayoutField(const FieldDecl *D,
1698 bool InsertExtraPadding) {
1699 if (D->isBitField()) {
1704 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
1706 // Reset the unfilled bits.
1707 UnfilledBitsInLastUnit = 0;
1708 LastBitfieldTypeSize = 0;
1710 bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
1711 CharUnits FieldOffset =
1712 IsUnion ? CharUnits::Zero() : getDataSize();
1713 CharUnits FieldSize;
1714 CharUnits FieldAlign;
1716 if (D->getType()->isIncompleteArrayType()) {
1717 // This is a flexible array member; we can't directly
1718 // query getTypeInfo about these, so we figure it out here.
1719 // Flexible array members don't have any size, but they
1720 // have to be aligned appropriately for their element type.
1721 FieldSize = CharUnits::Zero();
1722 const ArrayType* ATy = Context.getAsArrayType(D->getType());
1723 FieldAlign = Context.getTypeAlignInChars(ATy->getElementType());
1724 } else if (const ReferenceType *RT = D->getType()->getAs<ReferenceType>()) {
1725 unsigned AS = RT->getPointeeType().getAddressSpace();
1727 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(AS));
1729 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(AS));
1731 std::pair<CharUnits, CharUnits> FieldInfo =
1732 Context.getTypeInfoInChars(D->getType());
1733 FieldSize = FieldInfo.first;
1734 FieldAlign = FieldInfo.second;
1737 // If MS bitfield layout is required, figure out what type is being
1738 // laid out and align the field to the width of that type.
1740 // Resolve all typedefs down to their base type and round up the field
1741 // alignment if necessary.
1742 QualType T = Context.getBaseElementType(D->getType());
1743 if (const BuiltinType *BTy = T->getAs<BuiltinType>()) {
1744 CharUnits TypeSize = Context.getTypeSizeInChars(BTy);
1745 if (TypeSize > FieldAlign)
1746 FieldAlign = TypeSize;
1751 // The align if the field is not packed. This is to check if the attribute
1752 // was unnecessary (-Wpacked).
1753 CharUnits UnpackedFieldAlign = FieldAlign;
1754 CharUnits UnpackedFieldOffset = FieldOffset;
1757 FieldAlign = CharUnits::One();
1758 CharUnits MaxAlignmentInChars =
1759 Context.toCharUnitsFromBits(D->getMaxAlignment());
1760 FieldAlign = std::max(FieldAlign, MaxAlignmentInChars);
1761 UnpackedFieldAlign = std::max(UnpackedFieldAlign, MaxAlignmentInChars);
1763 // The maximum field alignment overrides the aligned attribute.
1764 if (!MaxFieldAlignment.isZero()) {
1765 FieldAlign = std::min(FieldAlign, MaxFieldAlignment);
1766 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignment);
1769 // Round up the current record size to the field's alignment boundary.
1770 FieldOffset = FieldOffset.RoundUpToAlignment(FieldAlign);
1771 UnpackedFieldOffset =
1772 UnpackedFieldOffset.RoundUpToAlignment(UnpackedFieldAlign);
1774 if (UseExternalLayout) {
1775 FieldOffset = Context.toCharUnitsFromBits(
1776 updateExternalFieldOffset(D, Context.toBits(FieldOffset)));
1778 if (!IsUnion && EmptySubobjects) {
1779 // Record the fact that we're placing a field at this offset.
1780 bool Allowed = EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset);
1782 assert(Allowed && "Externally-placed field cannot be placed here");
1785 if (!IsUnion && EmptySubobjects) {
1786 // Check if we can place the field at this offset.
1787 while (!EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset)) {
1788 // We couldn't place the field at the offset. Try again at a new offset.
1789 FieldOffset += FieldAlign;
1794 // Place this field at the current location.
1795 FieldOffsets.push_back(Context.toBits(FieldOffset));
1797 if (!UseExternalLayout)
1798 CheckFieldPadding(Context.toBits(FieldOffset), UnpaddedFieldOffset,
1799 Context.toBits(UnpackedFieldOffset),
1800 Context.toBits(UnpackedFieldAlign), FieldPacked, D);
1802 if (InsertExtraPadding) {
1803 CharUnits ASanAlignment = CharUnits::fromQuantity(8);
1804 CharUnits ExtraSizeForAsan = ASanAlignment;
1805 if (FieldSize % ASanAlignment)
1807 ASanAlignment - CharUnits::fromQuantity(FieldSize % ASanAlignment);
1808 FieldSize += ExtraSizeForAsan;
1811 // Reserve space for this field.
1812 uint64_t FieldSizeInBits = Context.toBits(FieldSize);
1814 setDataSize(std::max(getDataSizeInBits(), FieldSizeInBits));
1816 setDataSize(FieldOffset + FieldSize);
1819 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1821 // Remember max struct/class alignment.
1822 UpdateAlignment(FieldAlign, UnpackedFieldAlign);
1825 void ItaniumRecordLayoutBuilder::FinishLayout(const NamedDecl *D) {
1826 // In C++, records cannot be of size 0.
1827 if (Context.getLangOpts().CPlusPlus && getSizeInBits() == 0) {
1828 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
1829 // Compatibility with gcc requires a class (pod or non-pod)
1830 // which is not empty but of size 0; such as having fields of
1831 // array of zero-length, remains of Size 0
1833 setSize(CharUnits::One());
1836 setSize(CharUnits::One());
1839 // Finally, round the size of the record up to the alignment of the
1841 uint64_t UnpaddedSize = getSizeInBits() - UnfilledBitsInLastUnit;
1842 uint64_t UnpackedSizeInBits =
1843 llvm::RoundUpToAlignment(getSizeInBits(),
1844 Context.toBits(UnpackedAlignment));
1845 CharUnits UnpackedSize = Context.toCharUnitsFromBits(UnpackedSizeInBits);
1846 uint64_t RoundedSize
1847 = llvm::RoundUpToAlignment(getSizeInBits(), Context.toBits(Alignment));
1849 if (UseExternalLayout) {
1850 // If we're inferring alignment, and the external size is smaller than
1851 // our size after we've rounded up to alignment, conservatively set the
1853 if (InferAlignment && External.Size < RoundedSize) {
1854 Alignment = CharUnits::One();
1855 InferAlignment = false;
1857 setSize(External.Size);
1861 // Set the size to the final size.
1862 setSize(RoundedSize);
1864 unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
1865 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
1866 // Warn if padding was introduced to the struct/class/union.
1867 if (getSizeInBits() > UnpaddedSize) {
1868 unsigned PadSize = getSizeInBits() - UnpaddedSize;
1870 if (PadSize % CharBitNum == 0) {
1871 PadSize = PadSize / CharBitNum;
1874 Diag(RD->getLocation(), diag::warn_padded_struct_size)
1875 << Context.getTypeDeclType(RD)
1877 << (InBits ? 1 : 0); // (byte|bit)
1880 // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
1881 // bother since there won't be alignment issues.
1882 if (Packed && UnpackedAlignment > CharUnits::One() &&
1883 getSize() == UnpackedSize)
1884 Diag(D->getLocation(), diag::warn_unnecessary_packed)
1885 << Context.getTypeDeclType(RD);
1889 void ItaniumRecordLayoutBuilder::UpdateAlignment(
1890 CharUnits NewAlignment, CharUnits UnpackedNewAlignment) {
1891 // The alignment is not modified when using 'mac68k' alignment or when
1892 // we have an externally-supplied layout that also provides overall alignment.
1893 if (IsMac68kAlign || (UseExternalLayout && !InferAlignment))
1896 if (NewAlignment > Alignment) {
1897 assert(llvm::isPowerOf2_64(NewAlignment.getQuantity()) &&
1898 "Alignment not a power of 2");
1899 Alignment = NewAlignment;
1902 if (UnpackedNewAlignment > UnpackedAlignment) {
1903 assert(llvm::isPowerOf2_64(UnpackedNewAlignment.getQuantity()) &&
1904 "Alignment not a power of 2");
1905 UnpackedAlignment = UnpackedNewAlignment;
1910 ItaniumRecordLayoutBuilder::updateExternalFieldOffset(const FieldDecl *Field,
1911 uint64_t ComputedOffset) {
1912 uint64_t ExternalFieldOffset = External.getExternalFieldOffset(Field);
1914 if (InferAlignment && ExternalFieldOffset < ComputedOffset) {
1915 // The externally-supplied field offset is before the field offset we
1916 // computed. Assume that the structure is packed.
1917 Alignment = CharUnits::One();
1918 InferAlignment = false;
1921 // Use the externally-supplied field offset.
1922 return ExternalFieldOffset;
1925 /// \brief Get diagnostic %select index for tag kind for
1926 /// field padding diagnostic message.
1927 /// WARNING: Indexes apply to particular diagnostics only!
1929 /// \returns diagnostic %select index.
1930 static unsigned getPaddingDiagFromTagKind(TagTypeKind Tag) {
1932 case TTK_Struct: return 0;
1933 case TTK_Interface: return 1;
1934 case TTK_Class: return 2;
1935 default: llvm_unreachable("Invalid tag kind for field padding diagnostic!");
1939 void ItaniumRecordLayoutBuilder::CheckFieldPadding(
1940 uint64_t Offset, uint64_t UnpaddedOffset, uint64_t UnpackedOffset,
1941 unsigned UnpackedAlign, bool isPacked, const FieldDecl *D) {
1942 // We let objc ivars without warning, objc interfaces generally are not used
1943 // for padding tricks.
1944 if (isa<ObjCIvarDecl>(D))
1947 // Don't warn about structs created without a SourceLocation. This can
1948 // be done by clients of the AST, such as codegen.
1949 if (D->getLocation().isInvalid())
1952 unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
1954 // Warn if padding was introduced to the struct/class.
1955 if (!IsUnion && Offset > UnpaddedOffset) {
1956 unsigned PadSize = Offset - UnpaddedOffset;
1958 if (PadSize % CharBitNum == 0) {
1959 PadSize = PadSize / CharBitNum;
1962 if (D->getIdentifier())
1963 Diag(D->getLocation(), diag::warn_padded_struct_field)
1964 << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
1965 << Context.getTypeDeclType(D->getParent())
1967 << (InBits ? 1 : 0) // (byte|bit)
1968 << D->getIdentifier();
1970 Diag(D->getLocation(), diag::warn_padded_struct_anon_field)
1971 << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
1972 << Context.getTypeDeclType(D->getParent())
1974 << (InBits ? 1 : 0); // (byte|bit)
1977 // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
1978 // bother since there won't be alignment issues.
1979 if (isPacked && UnpackedAlign > CharBitNum && Offset == UnpackedOffset)
1980 Diag(D->getLocation(), diag::warn_unnecessary_packed)
1981 << D->getIdentifier();
1984 static const CXXMethodDecl *computeKeyFunction(ASTContext &Context,
1985 const CXXRecordDecl *RD) {
1986 // If a class isn't polymorphic it doesn't have a key function.
1987 if (!RD->isPolymorphic())
1990 // A class that is not externally visible doesn't have a key function. (Or
1991 // at least, there's no point to assigning a key function to such a class;
1992 // this doesn't affect the ABI.)
1993 if (!RD->isExternallyVisible())
1996 // Template instantiations don't have key functions per Itanium C++ ABI 5.2.6.
1997 // Same behavior as GCC.
1998 TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
1999 if (TSK == TSK_ImplicitInstantiation ||
2000 TSK == TSK_ExplicitInstantiationDeclaration ||
2001 TSK == TSK_ExplicitInstantiationDefinition)
2004 bool allowInlineFunctions =
2005 Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline();
2007 for (const CXXMethodDecl *MD : RD->methods()) {
2008 if (!MD->isVirtual())
2014 // Ignore implicit member functions, they are always marked as inline, but
2015 // they don't have a body until they're defined.
2016 if (MD->isImplicit())
2019 if (MD->isInlineSpecified())
2022 if (MD->hasInlineBody())
2025 // Ignore inline deleted or defaulted functions.
2026 if (!MD->isUserProvided())
2029 // In certain ABIs, ignore functions with out-of-line inline definitions.
2030 if (!allowInlineFunctions) {
2031 const FunctionDecl *Def;
2032 if (MD->hasBody(Def) && Def->isInlineSpecified())
2036 if (Context.getLangOpts().CUDA) {
2037 // While compiler may see key method in this TU, during CUDA
2038 // compilation we should ignore methods that are not accessible
2039 // on this side of compilation.
2040 if (Context.getLangOpts().CUDAIsDevice) {
2041 // In device mode ignore methods without __device__ attribute.
2042 if (!MD->hasAttr<CUDADeviceAttr>())
2045 // In host mode ignore __device__-only methods.
2046 if (!MD->hasAttr<CUDAHostAttr>() && MD->hasAttr<CUDADeviceAttr>())
2051 // If the key function is dllimport but the class isn't, then the class has
2052 // no key function. The DLL that exports the key function won't export the
2053 // vtable in this case.
2054 if (MD->hasAttr<DLLImportAttr>() && !RD->hasAttr<DLLImportAttr>())
2064 DiagnosticBuilder ItaniumRecordLayoutBuilder::Diag(SourceLocation Loc,
2066 return Context.getDiagnostics().Report(Loc, DiagID);
2069 /// Does the target C++ ABI require us to skip over the tail-padding
2070 /// of the given class (considering it as a base class) when allocating
2072 static bool mustSkipTailPadding(TargetCXXABI ABI, const CXXRecordDecl *RD) {
2073 switch (ABI.getTailPaddingUseRules()) {
2074 case TargetCXXABI::AlwaysUseTailPadding:
2077 case TargetCXXABI::UseTailPaddingUnlessPOD03:
2078 // FIXME: To the extent that this is meant to cover the Itanium ABI
2079 // rules, we should implement the restrictions about over-sized
2082 // http://mentorembedded.github.com/cxx-abi/abi.html#POD :
2083 // In general, a type is considered a POD for the purposes of
2084 // layout if it is a POD type (in the sense of ISO C++
2085 // [basic.types]). However, a POD-struct or POD-union (in the
2086 // sense of ISO C++ [class]) with a bitfield member whose
2087 // declared width is wider than the declared type of the
2088 // bitfield is not a POD for the purpose of layout. Similarly,
2089 // an array type is not a POD for the purpose of layout if the
2090 // element type of the array is not a POD for the purpose of
2093 // Where references to the ISO C++ are made in this paragraph,
2094 // the Technical Corrigendum 1 version of the standard is
2098 case TargetCXXABI::UseTailPaddingUnlessPOD11:
2099 // This is equivalent to RD->getTypeForDecl().isCXX11PODType(),
2100 // but with a lot of abstraction penalty stripped off. This does
2101 // assume that these properties are set correctly even in C++98
2102 // mode; fortunately, that is true because we want to assign
2103 // consistently semantics to the type-traits intrinsics (or at
2104 // least as many of them as possible).
2105 return RD->isTrivial() && RD->isStandardLayout();
2108 llvm_unreachable("bad tail-padding use kind");
2111 static bool isMsLayout(const ASTContext &Context) {
2112 return Context.getTargetInfo().getCXXABI().isMicrosoft();
2115 // This section contains an implementation of struct layout that is, up to the
2116 // included tests, compatible with cl.exe (2013). The layout produced is
2117 // significantly different than those produced by the Itanium ABI. Here we note
2118 // the most important differences.
2120 // * The alignment of bitfields in unions is ignored when computing the
2121 // alignment of the union.
2122 // * The existence of zero-width bitfield that occurs after anything other than
2123 // a non-zero length bitfield is ignored.
2124 // * There is no explicit primary base for the purposes of layout. All bases
2125 // with vfptrs are laid out first, followed by all bases without vfptrs.
2126 // * The Itanium equivalent vtable pointers are split into a vfptr (virtual
2127 // function pointer) and a vbptr (virtual base pointer). They can each be
2128 // shared with a, non-virtual bases. These bases need not be the same. vfptrs
2129 // always occur at offset 0. vbptrs can occur at an arbitrary offset and are
2130 // placed after the lexiographically last non-virtual base. This placement
2131 // is always before fields but can be in the middle of the non-virtual bases
2132 // due to the two-pass layout scheme for non-virtual-bases.
2133 // * Virtual bases sometimes require a 'vtordisp' field that is laid out before
2134 // the virtual base and is used in conjunction with virtual overrides during
2135 // construction and destruction. This is always a 4 byte value and is used as
2136 // an alternative to constructor vtables.
2137 // * vtordisps are allocated in a block of memory with size and alignment equal
2138 // to the alignment of the completed structure (before applying __declspec(
2139 // align())). The vtordisp always occur at the end of the allocation block,
2140 // immediately prior to the virtual base.
2141 // * vfptrs are injected after all bases and fields have been laid out. In
2142 // order to guarantee proper alignment of all fields, the vfptr injection
2143 // pushes all bases and fields back by the alignment imposed by those bases
2144 // and fields. This can potentially add a significant amount of padding.
2145 // vfptrs are always injected at offset 0.
2146 // * vbptrs are injected after all bases and fields have been laid out. In
2147 // order to guarantee proper alignment of all fields, the vfptr injection
2148 // pushes all bases and fields back by the alignment imposed by those bases
2149 // and fields. This can potentially add a significant amount of padding.
2150 // vbptrs are injected immediately after the last non-virtual base as
2151 // lexiographically ordered in the code. If this site isn't pointer aligned
2152 // the vbptr is placed at the next properly aligned location. Enough padding
2153 // is added to guarantee a fit.
2154 // * The last zero sized non-virtual base can be placed at the end of the
2155 // struct (potentially aliasing another object), or may alias with the first
2156 // field, even if they are of the same type.
2157 // * The last zero size virtual base may be placed at the end of the struct
2158 // potentially aliasing another object.
2159 // * The ABI attempts to avoid aliasing of zero sized bases by adding padding
2160 // between bases or vbases with specific properties. The criteria for
2161 // additional padding between two bases is that the first base is zero sized
2162 // or ends with a zero sized subobject and the second base is zero sized or
2163 // trails with a zero sized base or field (sharing of vfptrs can reorder the
2164 // layout of the so the leading base is not always the first one declared).
2165 // This rule does take into account fields that are not records, so padding
2166 // will occur even if the last field is, e.g. an int. The padding added for
2167 // bases is 1 byte. The padding added between vbases depends on the alignment
2168 // of the object but is at least 4 bytes (in both 32 and 64 bit modes).
2169 // * There is no concept of non-virtual alignment, non-virtual alignment and
2170 // alignment are always identical.
2171 // * There is a distinction between alignment and required alignment.
2172 // __declspec(align) changes the required alignment of a struct. This
2173 // alignment is _always_ obeyed, even in the presence of #pragma pack. A
2174 // record inherits required alignment from all of its fields and bases.
2175 // * __declspec(align) on bitfields has the effect of changing the bitfield's
2176 // alignment instead of its required alignment. This is the only known way
2177 // to make the alignment of a struct bigger than 8. Interestingly enough
2178 // this alignment is also immune to the effects of #pragma pack and can be
2179 // used to create structures with large alignment under #pragma pack.
2180 // However, because it does not impact required alignment, such a structure,
2181 // when used as a field or base, will not be aligned if #pragma pack is
2182 // still active at the time of use.
2184 // Known incompatibilities:
2185 // * all: #pragma pack between fields in a record
2186 // * 2010 and back: If the last field in a record is a bitfield, every object
2187 // laid out after the record will have extra padding inserted before it. The
2188 // extra padding will have size equal to the size of the storage class of the
2189 // bitfield. 0 sized bitfields don't exhibit this behavior and the extra
2190 // padding can be avoided by adding a 0 sized bitfield after the non-zero-
2192 // * 2012 and back: In 64-bit mode, if the alignment of a record is 16 or
2193 // greater due to __declspec(align()) then a second layout phase occurs after
2194 // The locations of the vf and vb pointers are known. This layout phase
2195 // suffers from the "last field is a bitfield" bug in 2010 and results in
2196 // _every_ field getting padding put in front of it, potentially including the
2197 // vfptr, leaving the vfprt at a non-zero location which results in a fault if
2198 // anything tries to read the vftbl. The second layout phase also treats
2199 // bitfields as separate entities and gives them each storage rather than
2200 // packing them. Additionally, because this phase appears to perform a
2201 // (an unstable) sort on the members before laying them out and because merged
2202 // bitfields have the same address, the bitfields end up in whatever order
2203 // the sort left them in, a behavior we could never hope to replicate.
2206 struct MicrosoftRecordLayoutBuilder {
2207 struct ElementInfo {
2209 CharUnits Alignment;
2211 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
2212 MicrosoftRecordLayoutBuilder(const ASTContext &Context) : Context(Context) {}
2214 MicrosoftRecordLayoutBuilder(const MicrosoftRecordLayoutBuilder &) = delete;
2215 void operator=(const MicrosoftRecordLayoutBuilder &) = delete;
2217 void layout(const RecordDecl *RD);
2218 void cxxLayout(const CXXRecordDecl *RD);
2219 /// \brief Initializes size and alignment and honors some flags.
2220 void initializeLayout(const RecordDecl *RD);
2221 /// \brief Initialized C++ layout, compute alignment and virtual alignment and
2222 /// existence of vfptrs and vbptrs. Alignment is needed before the vfptr is
2224 void initializeCXXLayout(const CXXRecordDecl *RD);
2225 void layoutNonVirtualBases(const CXXRecordDecl *RD);
2226 void layoutNonVirtualBase(const CXXRecordDecl *BaseDecl,
2227 const ASTRecordLayout &BaseLayout,
2228 const ASTRecordLayout *&PreviousBaseLayout);
2229 void injectVFPtr(const CXXRecordDecl *RD);
2230 void injectVBPtr(const CXXRecordDecl *RD);
2231 /// \brief Lays out the fields of the record. Also rounds size up to
2233 void layoutFields(const RecordDecl *RD);
2234 void layoutField(const FieldDecl *FD);
2235 void layoutBitField(const FieldDecl *FD);
2236 /// \brief Lays out a single zero-width bit-field in the record and handles
2237 /// special cases associated with zero-width bit-fields.
2238 void layoutZeroWidthBitField(const FieldDecl *FD);
2239 void layoutVirtualBases(const CXXRecordDecl *RD);
2240 void finalizeLayout(const RecordDecl *RD);
2241 /// \brief Gets the size and alignment of a base taking pragma pack and
2242 /// __declspec(align) into account.
2243 ElementInfo getAdjustedElementInfo(const ASTRecordLayout &Layout);
2244 /// \brief Gets the size and alignment of a field taking pragma pack and
2245 /// __declspec(align) into account. It also updates RequiredAlignment as a
2246 /// side effect because it is most convenient to do so here.
2247 ElementInfo getAdjustedElementInfo(const FieldDecl *FD);
2248 /// \brief Places a field at an offset in CharUnits.
2249 void placeFieldAtOffset(CharUnits FieldOffset) {
2250 FieldOffsets.push_back(Context.toBits(FieldOffset));
2252 /// \brief Places a bitfield at a bit offset.
2253 void placeFieldAtBitOffset(uint64_t FieldOffset) {
2254 FieldOffsets.push_back(FieldOffset);
2256 /// \brief Compute the set of virtual bases for which vtordisps are required.
2257 void computeVtorDispSet(
2258 llvm::SmallPtrSetImpl<const CXXRecordDecl *> &HasVtorDispSet,
2259 const CXXRecordDecl *RD) const;
2260 const ASTContext &Context;
2261 /// \brief The size of the record being laid out.
2263 /// \brief The non-virtual size of the record layout.
2264 CharUnits NonVirtualSize;
2265 /// \brief The data size of the record layout.
2267 /// \brief The current alignment of the record layout.
2268 CharUnits Alignment;
2269 /// \brief The maximum allowed field alignment. This is set by #pragma pack.
2270 CharUnits MaxFieldAlignment;
2271 /// \brief The alignment that this record must obey. This is imposed by
2272 /// __declspec(align()) on the record itself or one of its fields or bases.
2273 CharUnits RequiredAlignment;
2274 /// \brief The size of the allocation of the currently active bitfield.
2275 /// This value isn't meaningful unless LastFieldIsNonZeroWidthBitfield
2277 CharUnits CurrentBitfieldSize;
2278 /// \brief Offset to the virtual base table pointer (if one exists).
2279 CharUnits VBPtrOffset;
2280 /// \brief Minimum record size possible.
2281 CharUnits MinEmptyStructSize;
2282 /// \brief The size and alignment info of a pointer.
2283 ElementInfo PointerInfo;
2284 /// \brief The primary base class (if one exists).
2285 const CXXRecordDecl *PrimaryBase;
2286 /// \brief The class we share our vb-pointer with.
2287 const CXXRecordDecl *SharedVBPtrBase;
2288 /// \brief The collection of field offsets.
2289 SmallVector<uint64_t, 16> FieldOffsets;
2290 /// \brief Base classes and their offsets in the record.
2291 BaseOffsetsMapTy Bases;
2292 /// \brief virtual base classes and their offsets in the record.
2293 ASTRecordLayout::VBaseOffsetsMapTy VBases;
2294 /// \brief The number of remaining bits in our last bitfield allocation.
2295 /// This value isn't meaningful unless LastFieldIsNonZeroWidthBitfield is
2297 unsigned RemainingBitsInField;
2299 /// \brief True if the last field laid out was a bitfield and was not 0
2301 bool LastFieldIsNonZeroWidthBitfield : 1;
2302 /// \brief True if the class has its own vftable pointer.
2303 bool HasOwnVFPtr : 1;
2304 /// \brief True if the class has a vbtable pointer.
2306 /// \brief True if the last sub-object within the type is zero sized or the
2307 /// object itself is zero sized. This *does not* count members that are not
2308 /// records. Only used for MS-ABI.
2309 bool EndsWithZeroSizedObject : 1;
2310 /// \brief True if this class is zero sized or first base is zero sized or
2311 /// has this property. Only used for MS-ABI.
2312 bool LeadsWithZeroSizedBase : 1;
2314 /// \brief True if the external AST source provided a layout for this record.
2315 bool UseExternalLayout : 1;
2317 /// \brief The layout provided by the external AST source. Only active if
2318 /// UseExternalLayout is true.
2319 ExternalLayout External;
2323 MicrosoftRecordLayoutBuilder::ElementInfo
2324 MicrosoftRecordLayoutBuilder::getAdjustedElementInfo(
2325 const ASTRecordLayout &Layout) {
2327 Info.Alignment = Layout.getAlignment();
2328 // Respect pragma pack.
2329 if (!MaxFieldAlignment.isZero())
2330 Info.Alignment = std::min(Info.Alignment, MaxFieldAlignment);
2331 // Track zero-sized subobjects here where it's already available.
2332 EndsWithZeroSizedObject = Layout.hasZeroSizedSubObject();
2333 // Respect required alignment, this is necessary because we may have adjusted
2334 // the alignment in the case of pragam pack. Note that the required alignment
2335 // doesn't actually apply to the struct alignment at this point.
2336 Alignment = std::max(Alignment, Info.Alignment);
2337 RequiredAlignment = std::max(RequiredAlignment, Layout.getRequiredAlignment());
2338 Info.Alignment = std::max(Info.Alignment, Layout.getRequiredAlignment());
2339 Info.Size = Layout.getNonVirtualSize();
2343 MicrosoftRecordLayoutBuilder::ElementInfo
2344 MicrosoftRecordLayoutBuilder::getAdjustedElementInfo(
2345 const FieldDecl *FD) {
2346 // Get the alignment of the field type's natural alignment, ignore any
2347 // alignment attributes.
2349 std::tie(Info.Size, Info.Alignment) =
2350 Context.getTypeInfoInChars(FD->getType()->getUnqualifiedDesugaredType());
2351 // Respect align attributes on the field.
2352 CharUnits FieldRequiredAlignment =
2353 Context.toCharUnitsFromBits(FD->getMaxAlignment());
2354 // Respect align attributes on the type.
2355 if (Context.isAlignmentRequired(FD->getType()))
2356 FieldRequiredAlignment = std::max(
2357 Context.getTypeAlignInChars(FD->getType()), FieldRequiredAlignment);
2358 // Respect attributes applied to subobjects of the field.
2359 if (FD->isBitField())
2360 // For some reason __declspec align impacts alignment rather than required
2361 // alignment when it is applied to bitfields.
2362 Info.Alignment = std::max(Info.Alignment, FieldRequiredAlignment);
2365 FD->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
2366 auto const &Layout = Context.getASTRecordLayout(RT->getDecl());
2367 EndsWithZeroSizedObject = Layout.hasZeroSizedSubObject();
2368 FieldRequiredAlignment = std::max(FieldRequiredAlignment,
2369 Layout.getRequiredAlignment());
2371 // Capture required alignment as a side-effect.
2372 RequiredAlignment = std::max(RequiredAlignment, FieldRequiredAlignment);
2374 // Respect pragma pack, attribute pack and declspec align
2375 if (!MaxFieldAlignment.isZero())
2376 Info.Alignment = std::min(Info.Alignment, MaxFieldAlignment);
2377 if (FD->hasAttr<PackedAttr>())
2378 Info.Alignment = CharUnits::One();
2379 Info.Alignment = std::max(Info.Alignment, FieldRequiredAlignment);
2383 void MicrosoftRecordLayoutBuilder::layout(const RecordDecl *RD) {
2384 // For C record layout, zero-sized records always have size 4.
2385 MinEmptyStructSize = CharUnits::fromQuantity(4);
2386 initializeLayout(RD);
2388 DataSize = Size = Size.RoundUpToAlignment(Alignment);
2389 RequiredAlignment = std::max(
2390 RequiredAlignment, Context.toCharUnitsFromBits(RD->getMaxAlignment()));
2394 void MicrosoftRecordLayoutBuilder::cxxLayout(const CXXRecordDecl *RD) {
2395 // The C++ standard says that empty structs have size 1.
2396 MinEmptyStructSize = CharUnits::One();
2397 initializeLayout(RD);
2398 initializeCXXLayout(RD);
2399 layoutNonVirtualBases(RD);
2403 if (HasOwnVFPtr || (HasVBPtr && !SharedVBPtrBase))
2404 Alignment = std::max(Alignment, PointerInfo.Alignment);
2405 auto RoundingAlignment = Alignment;
2406 if (!MaxFieldAlignment.isZero())
2407 RoundingAlignment = std::min(RoundingAlignment, MaxFieldAlignment);
2408 NonVirtualSize = Size = Size.RoundUpToAlignment(RoundingAlignment);
2409 RequiredAlignment = std::max(
2410 RequiredAlignment, Context.toCharUnitsFromBits(RD->getMaxAlignment()));
2411 layoutVirtualBases(RD);
2415 void MicrosoftRecordLayoutBuilder::initializeLayout(const RecordDecl *RD) {
2416 IsUnion = RD->isUnion();
2417 Size = CharUnits::Zero();
2418 Alignment = CharUnits::One();
2419 // In 64-bit mode we always perform an alignment step after laying out vbases.
2420 // In 32-bit mode we do not. The check to see if we need to perform alignment
2421 // checks the RequiredAlignment field and performs alignment if it isn't 0.
2422 RequiredAlignment = Context.getTargetInfo().getTriple().isArch64Bit()
2424 : CharUnits::Zero();
2425 // Compute the maximum field alignment.
2426 MaxFieldAlignment = CharUnits::Zero();
2427 // Honor the default struct packing maximum alignment flag.
2428 if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct)
2429 MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
2430 // Honor the packing attribute. The MS-ABI ignores pragma pack if its larger
2431 // than the pointer size.
2432 if (const MaxFieldAlignmentAttr *MFAA = RD->getAttr<MaxFieldAlignmentAttr>()){
2433 unsigned PackedAlignment = MFAA->getAlignment();
2434 if (PackedAlignment <= Context.getTargetInfo().getPointerWidth(0))
2435 MaxFieldAlignment = Context.toCharUnitsFromBits(PackedAlignment);
2437 // Packed attribute forces max field alignment to be 1.
2438 if (RD->hasAttr<PackedAttr>())
2439 MaxFieldAlignment = CharUnits::One();
2441 // Try to respect the external layout if present.
2442 UseExternalLayout = false;
2443 if (ExternalASTSource *Source = Context.getExternalSource())
2444 UseExternalLayout = Source->layoutRecordType(
2445 RD, External.Size, External.Align, External.FieldOffsets,
2446 External.BaseOffsets, External.VirtualBaseOffsets);
2450 MicrosoftRecordLayoutBuilder::initializeCXXLayout(const CXXRecordDecl *RD) {
2451 EndsWithZeroSizedObject = false;
2452 LeadsWithZeroSizedBase = false;
2453 HasOwnVFPtr = false;
2455 PrimaryBase = nullptr;
2456 SharedVBPtrBase = nullptr;
2457 // Calculate pointer size and alignment. These are used for vfptr and vbprt
2460 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
2461 PointerInfo.Alignment =
2462 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0));
2463 // Respect pragma pack.
2464 if (!MaxFieldAlignment.isZero())
2465 PointerInfo.Alignment = std::min(PointerInfo.Alignment, MaxFieldAlignment);
2469 MicrosoftRecordLayoutBuilder::layoutNonVirtualBases(const CXXRecordDecl *RD) {
2470 // The MS-ABI lays out all bases that contain leading vfptrs before it lays
2471 // out any bases that do not contain vfptrs. We implement this as two passes
2472 // over the bases. This approach guarantees that the primary base is laid out
2473 // first. We use these passes to calculate some additional aggregated
2474 // information about the bases, such as reqruied alignment and the presence of
2475 // zero sized members.
2476 const ASTRecordLayout *PreviousBaseLayout = nullptr;
2477 // Iterate through the bases and lay out the non-virtual ones.
2478 for (const CXXBaseSpecifier &Base : RD->bases()) {
2479 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
2480 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
2481 // Mark and skip virtual bases.
2482 if (Base.isVirtual()) {
2486 // Check fo a base to share a VBPtr with.
2487 if (!SharedVBPtrBase && BaseLayout.hasVBPtr()) {
2488 SharedVBPtrBase = BaseDecl;
2491 // Only lay out bases with extendable VFPtrs on the first pass.
2492 if (!BaseLayout.hasExtendableVFPtr())
2494 // If we don't have a primary base, this one qualifies.
2496 PrimaryBase = BaseDecl;
2497 LeadsWithZeroSizedBase = BaseLayout.leadsWithZeroSizedBase();
2499 // Lay out the base.
2500 layoutNonVirtualBase(BaseDecl, BaseLayout, PreviousBaseLayout);
2502 // Figure out if we need a fresh VFPtr for this class.
2503 if (!PrimaryBase && RD->isDynamicClass())
2504 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
2505 e = RD->method_end();
2506 !HasOwnVFPtr && i != e; ++i)
2507 HasOwnVFPtr = i->isVirtual() && i->size_overridden_methods() == 0;
2508 // If we don't have a primary base then we have a leading object that could
2509 // itself lead with a zero-sized object, something we track.
2510 bool CheckLeadingLayout = !PrimaryBase;
2511 // Iterate through the bases and lay out the non-virtual ones.
2512 for (const CXXBaseSpecifier &Base : RD->bases()) {
2513 if (Base.isVirtual())
2515 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
2516 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
2517 // Only lay out bases without extendable VFPtrs on the second pass.
2518 if (BaseLayout.hasExtendableVFPtr()) {
2519 VBPtrOffset = Bases[BaseDecl] + BaseLayout.getNonVirtualSize();
2522 // If this is the first layout, check to see if it leads with a zero sized
2523 // object. If it does, so do we.
2524 if (CheckLeadingLayout) {
2525 CheckLeadingLayout = false;
2526 LeadsWithZeroSizedBase = BaseLayout.leadsWithZeroSizedBase();
2528 // Lay out the base.
2529 layoutNonVirtualBase(BaseDecl, BaseLayout, PreviousBaseLayout);
2530 VBPtrOffset = Bases[BaseDecl] + BaseLayout.getNonVirtualSize();
2532 // Set our VBPtroffset if we know it at this point.
2534 VBPtrOffset = CharUnits::fromQuantity(-1);
2535 else if (SharedVBPtrBase) {
2536 const ASTRecordLayout &Layout = Context.getASTRecordLayout(SharedVBPtrBase);
2537 VBPtrOffset = Bases[SharedVBPtrBase] + Layout.getVBPtrOffset();
2541 void MicrosoftRecordLayoutBuilder::layoutNonVirtualBase(
2542 const CXXRecordDecl *BaseDecl,
2543 const ASTRecordLayout &BaseLayout,
2544 const ASTRecordLayout *&PreviousBaseLayout) {
2545 // Insert padding between two bases if the left first one is zero sized or
2546 // contains a zero sized subobject and the right is zero sized or one leads
2547 // with a zero sized base.
2548 if (PreviousBaseLayout && PreviousBaseLayout->hasZeroSizedSubObject() &&
2549 BaseLayout.leadsWithZeroSizedBase())
2551 ElementInfo Info = getAdjustedElementInfo(BaseLayout);
2552 CharUnits BaseOffset;
2554 // Respect the external AST source base offset, if present.
2555 bool FoundBase = false;
2556 if (UseExternalLayout) {
2557 FoundBase = External.getExternalNVBaseOffset(BaseDecl, BaseOffset);
2559 assert(BaseOffset >= Size && "base offset already allocated");
2563 BaseOffset = Size.RoundUpToAlignment(Info.Alignment);
2564 Bases.insert(std::make_pair(BaseDecl, BaseOffset));
2565 Size = BaseOffset + BaseLayout.getNonVirtualSize();
2566 PreviousBaseLayout = &BaseLayout;
2569 void MicrosoftRecordLayoutBuilder::layoutFields(const RecordDecl *RD) {
2570 LastFieldIsNonZeroWidthBitfield = false;
2571 for (const FieldDecl *Field : RD->fields())
2575 void MicrosoftRecordLayoutBuilder::layoutField(const FieldDecl *FD) {
2576 if (FD->isBitField()) {
2580 LastFieldIsNonZeroWidthBitfield = false;
2581 ElementInfo Info = getAdjustedElementInfo(FD);
2582 Alignment = std::max(Alignment, Info.Alignment);
2584 placeFieldAtOffset(CharUnits::Zero());
2585 Size = std::max(Size, Info.Size);
2587 CharUnits FieldOffset;
2588 if (UseExternalLayout) {
2590 Context.toCharUnitsFromBits(External.getExternalFieldOffset(FD));
2591 assert(FieldOffset >= Size && "field offset already allocated");
2593 FieldOffset = Size.RoundUpToAlignment(Info.Alignment);
2595 placeFieldAtOffset(FieldOffset);
2596 Size = FieldOffset + Info.Size;
2600 void MicrosoftRecordLayoutBuilder::layoutBitField(const FieldDecl *FD) {
2601 unsigned Width = FD->getBitWidthValue(Context);
2603 layoutZeroWidthBitField(FD);
2606 ElementInfo Info = getAdjustedElementInfo(FD);
2607 // Clamp the bitfield to a containable size for the sake of being able
2608 // to lay them out. Sema will throw an error.
2609 if (Width > Context.toBits(Info.Size))
2610 Width = Context.toBits(Info.Size);
2611 // Check to see if this bitfield fits into an existing allocation. Note:
2612 // MSVC refuses to pack bitfields of formal types with different sizes
2613 // into the same allocation.
2614 if (!IsUnion && LastFieldIsNonZeroWidthBitfield &&
2615 CurrentBitfieldSize == Info.Size && Width <= RemainingBitsInField) {
2616 placeFieldAtBitOffset(Context.toBits(Size) - RemainingBitsInField);
2617 RemainingBitsInField -= Width;
2620 LastFieldIsNonZeroWidthBitfield = true;
2621 CurrentBitfieldSize = Info.Size;
2623 placeFieldAtOffset(CharUnits::Zero());
2624 Size = std::max(Size, Info.Size);
2625 // TODO: Add a Sema warning that MS ignores bitfield alignment in unions.
2627 // Allocate a new block of memory and place the bitfield in it.
2628 CharUnits FieldOffset = Size.RoundUpToAlignment(Info.Alignment);
2629 placeFieldAtOffset(FieldOffset);
2630 Size = FieldOffset + Info.Size;
2631 Alignment = std::max(Alignment, Info.Alignment);
2632 RemainingBitsInField = Context.toBits(Info.Size) - Width;
2637 MicrosoftRecordLayoutBuilder::layoutZeroWidthBitField(const FieldDecl *FD) {
2638 // Zero-width bitfields are ignored unless they follow a non-zero-width
2640 if (!LastFieldIsNonZeroWidthBitfield) {
2641 placeFieldAtOffset(IsUnion ? CharUnits::Zero() : Size);
2642 // TODO: Add a Sema warning that MS ignores alignment for zero
2643 // sized bitfields that occur after zero-size bitfields or non-bitfields.
2646 LastFieldIsNonZeroWidthBitfield = false;
2647 ElementInfo Info = getAdjustedElementInfo(FD);
2649 placeFieldAtOffset(CharUnits::Zero());
2650 Size = std::max(Size, Info.Size);
2651 // TODO: Add a Sema warning that MS ignores bitfield alignment in unions.
2653 // Round up the current record size to the field's alignment boundary.
2654 CharUnits FieldOffset = Size.RoundUpToAlignment(Info.Alignment);
2655 placeFieldAtOffset(FieldOffset);
2657 Alignment = std::max(Alignment, Info.Alignment);
2661 void MicrosoftRecordLayoutBuilder::injectVBPtr(const CXXRecordDecl *RD) {
2662 if (!HasVBPtr || SharedVBPtrBase)
2664 // Inject the VBPointer at the injection site.
2665 CharUnits InjectionSite = VBPtrOffset;
2666 // But before we do, make sure it's properly aligned.
2667 VBPtrOffset = VBPtrOffset.RoundUpToAlignment(PointerInfo.Alignment);
2668 // Shift everything after the vbptr down, unless we're using an external
2670 if (UseExternalLayout)
2672 // Determine where the first field should be laid out after the vbptr.
2673 CharUnits FieldStart = VBPtrOffset + PointerInfo.Size;
2674 // Make sure that the amount we push the fields back by is a multiple of the
2676 CharUnits Offset = (FieldStart - InjectionSite).RoundUpToAlignment(
2677 std::max(RequiredAlignment, Alignment));
2679 for (uint64_t &FieldOffset : FieldOffsets)
2680 FieldOffset += Context.toBits(Offset);
2681 for (BaseOffsetsMapTy::value_type &Base : Bases)
2682 if (Base.second >= InjectionSite)
2683 Base.second += Offset;
2686 void MicrosoftRecordLayoutBuilder::injectVFPtr(const CXXRecordDecl *RD) {
2689 // Make sure that the amount we push the struct back by is a multiple of the
2691 CharUnits Offset = PointerInfo.Size.RoundUpToAlignment(
2692 std::max(RequiredAlignment, Alignment));
2693 // Push back the vbptr, but increase the size of the object and push back
2694 // regular fields by the offset only if not using external record layout.
2696 VBPtrOffset += Offset;
2698 if (UseExternalLayout)
2703 // If we're using an external layout, the fields offsets have already
2704 // accounted for this adjustment.
2705 for (uint64_t &FieldOffset : FieldOffsets)
2706 FieldOffset += Context.toBits(Offset);
2707 for (BaseOffsetsMapTy::value_type &Base : Bases)
2708 Base.second += Offset;
2711 void MicrosoftRecordLayoutBuilder::layoutVirtualBases(const CXXRecordDecl *RD) {
2714 // Vtordisps are always 4 bytes (even in 64-bit mode)
2715 CharUnits VtorDispSize = CharUnits::fromQuantity(4);
2716 CharUnits VtorDispAlignment = VtorDispSize;
2717 // vtordisps respect pragma pack.
2718 if (!MaxFieldAlignment.isZero())
2719 VtorDispAlignment = std::min(VtorDispAlignment, MaxFieldAlignment);
2720 // The alignment of the vtordisp is at least the required alignment of the
2721 // entire record. This requirement may be present to support vtordisp
2723 for (const CXXBaseSpecifier &VBase : RD->vbases()) {
2724 const CXXRecordDecl *BaseDecl = VBase.getType()->getAsCXXRecordDecl();
2725 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
2727 std::max(RequiredAlignment, BaseLayout.getRequiredAlignment());
2729 VtorDispAlignment = std::max(VtorDispAlignment, RequiredAlignment);
2730 // Compute the vtordisp set.
2731 llvm::SmallPtrSet<const CXXRecordDecl *, 2> HasVtorDispSet;
2732 computeVtorDispSet(HasVtorDispSet, RD);
2733 // Iterate through the virtual bases and lay them out.
2734 const ASTRecordLayout *PreviousBaseLayout = nullptr;
2735 for (const CXXBaseSpecifier &VBase : RD->vbases()) {
2736 const CXXRecordDecl *BaseDecl = VBase.getType()->getAsCXXRecordDecl();
2737 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
2738 bool HasVtordisp = HasVtorDispSet.count(BaseDecl) > 0;
2739 // Insert padding between two bases if the left first one is zero sized or
2740 // contains a zero sized subobject and the right is zero sized or one leads
2741 // with a zero sized base. The padding between virtual bases is 4
2742 // bytes (in both 32 and 64 bits modes) and always involves rounding up to
2743 // the required alignment, we don't know why.
2744 if ((PreviousBaseLayout && PreviousBaseLayout->hasZeroSizedSubObject() &&
2745 BaseLayout.leadsWithZeroSizedBase()) || HasVtordisp) {
2746 Size = Size.RoundUpToAlignment(VtorDispAlignment) + VtorDispSize;
2747 Alignment = std::max(VtorDispAlignment, Alignment);
2749 // Insert the virtual base.
2750 ElementInfo Info = getAdjustedElementInfo(BaseLayout);
2751 CharUnits BaseOffset;
2753 // Respect the external AST source base offset, if present.
2754 bool FoundBase = false;
2755 if (UseExternalLayout) {
2756 FoundBase = External.getExternalVBaseOffset(BaseDecl, BaseOffset);
2758 assert(BaseOffset >= Size && "base offset already allocated");
2761 BaseOffset = Size.RoundUpToAlignment(Info.Alignment);
2763 VBases.insert(std::make_pair(BaseDecl,
2764 ASTRecordLayout::VBaseInfo(BaseOffset, HasVtordisp)));
2765 Size = BaseOffset + BaseLayout.getNonVirtualSize();
2766 PreviousBaseLayout = &BaseLayout;
2770 void MicrosoftRecordLayoutBuilder::finalizeLayout(const RecordDecl *RD) {
2771 // Respect required alignment. Note that in 32-bit mode Required alignment
2772 // may be 0 and cause size not to be updated.
2774 if (!RequiredAlignment.isZero()) {
2775 Alignment = std::max(Alignment, RequiredAlignment);
2776 auto RoundingAlignment = Alignment;
2777 if (!MaxFieldAlignment.isZero())
2778 RoundingAlignment = std::min(RoundingAlignment, MaxFieldAlignment);
2779 RoundingAlignment = std::max(RoundingAlignment, RequiredAlignment);
2780 Size = Size.RoundUpToAlignment(RoundingAlignment);
2782 if (Size.isZero()) {
2783 EndsWithZeroSizedObject = true;
2784 LeadsWithZeroSizedBase = true;
2785 // Zero-sized structures have size equal to their alignment if a
2786 // __declspec(align) came into play.
2787 if (RequiredAlignment >= MinEmptyStructSize)
2790 Size = MinEmptyStructSize;
2793 if (UseExternalLayout) {
2794 Size = Context.toCharUnitsFromBits(External.Size);
2796 Alignment = Context.toCharUnitsFromBits(External.Align);
2800 // Recursively walks the non-virtual bases of a class and determines if any of
2801 // them are in the bases with overridden methods set.
2803 RequiresVtordisp(const llvm::SmallPtrSetImpl<const CXXRecordDecl *> &
2804 BasesWithOverriddenMethods,
2805 const CXXRecordDecl *RD) {
2806 if (BasesWithOverriddenMethods.count(RD))
2808 // If any of a virtual bases non-virtual bases (recursively) requires a
2809 // vtordisp than so does this virtual base.
2810 for (const CXXBaseSpecifier &Base : RD->bases())
2811 if (!Base.isVirtual() &&
2812 RequiresVtordisp(BasesWithOverriddenMethods,
2813 Base.getType()->getAsCXXRecordDecl()))
2818 void MicrosoftRecordLayoutBuilder::computeVtorDispSet(
2819 llvm::SmallPtrSetImpl<const CXXRecordDecl *> &HasVtordispSet,
2820 const CXXRecordDecl *RD) const {
2821 // /vd2 or #pragma vtordisp(2): Always use vtordisps for virtual bases with
2823 if (RD->getMSVtorDispMode() == MSVtorDispAttr::ForVFTable) {
2824 for (const CXXBaseSpecifier &Base : RD->vbases()) {
2825 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
2826 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
2827 if (Layout.hasExtendableVFPtr())
2828 HasVtordispSet.insert(BaseDecl);
2833 // If any of our bases need a vtordisp for this type, so do we. Check our
2834 // direct bases for vtordisp requirements.
2835 for (const CXXBaseSpecifier &Base : RD->bases()) {
2836 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
2837 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
2838 for (const auto &bi : Layout.getVBaseOffsetsMap())
2839 if (bi.second.hasVtorDisp())
2840 HasVtordispSet.insert(bi.first);
2842 // We don't introduce any additional vtordisps if either:
2843 // * A user declared constructor or destructor aren't declared.
2844 // * #pragma vtordisp(0) or the /vd0 flag are in use.
2845 if ((!RD->hasUserDeclaredConstructor() && !RD->hasUserDeclaredDestructor()) ||
2846 RD->getMSVtorDispMode() == MSVtorDispAttr::Never)
2848 // /vd1 or #pragma vtordisp(1): Try to guess based on whether we think it's
2849 // possible for a partially constructed object with virtual base overrides to
2850 // escape a non-trivial constructor.
2851 assert(RD->getMSVtorDispMode() == MSVtorDispAttr::ForVBaseOverride);
2852 // Compute a set of base classes which define methods we override. A virtual
2853 // base in this set will require a vtordisp. A virtual base that transitively
2854 // contains one of these bases as a non-virtual base will also require a
2856 llvm::SmallPtrSet<const CXXMethodDecl *, 8> Work;
2857 llvm::SmallPtrSet<const CXXRecordDecl *, 2> BasesWithOverriddenMethods;
2858 // Seed the working set with our non-destructor, non-pure virtual methods.
2859 for (const CXXMethodDecl *MD : RD->methods())
2860 if (MD->isVirtual() && !isa<CXXDestructorDecl>(MD) && !MD->isPure())
2862 while (!Work.empty()) {
2863 const CXXMethodDecl *MD = *Work.begin();
2864 CXXMethodDecl::method_iterator i = MD->begin_overridden_methods(),
2865 e = MD->end_overridden_methods();
2866 // If a virtual method has no-overrides it lives in its parent's vtable.
2868 BasesWithOverriddenMethods.insert(MD->getParent());
2871 // We've finished processing this element, remove it from the working set.
2874 // For each of our virtual bases, check if it is in the set of overridden
2875 // bases or if it transitively contains a non-virtual base that is.
2876 for (const CXXBaseSpecifier &Base : RD->vbases()) {
2877 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
2878 if (!HasVtordispSet.count(BaseDecl) &&
2879 RequiresVtordisp(BasesWithOverriddenMethods, BaseDecl))
2880 HasVtordispSet.insert(BaseDecl);
2884 /// getASTRecordLayout - Get or compute information about the layout of the
2885 /// specified record (struct/union/class), which indicates its size and field
2886 /// position information.
2887 const ASTRecordLayout &
2888 ASTContext::getASTRecordLayout(const RecordDecl *D) const {
2889 // These asserts test different things. A record has a definition
2890 // as soon as we begin to parse the definition. That definition is
2891 // not a complete definition (which is what isDefinition() tests)
2892 // until we *finish* parsing the definition.
2894 if (D->hasExternalLexicalStorage() && !D->getDefinition())
2895 getExternalSource()->CompleteType(const_cast<RecordDecl*>(D));
2897 D = D->getDefinition();
2898 assert(D && "Cannot get layout of forward declarations!");
2899 assert(!D->isInvalidDecl() && "Cannot get layout of invalid decl!");
2900 assert(D->isCompleteDefinition() && "Cannot layout type before complete!");
2902 // Look up this layout, if already laid out, return what we have.
2903 // Note that we can't save a reference to the entry because this function
2905 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
2906 if (Entry) return *Entry;
2908 const ASTRecordLayout *NewEntry = nullptr;
2910 if (isMsLayout(*this)) {
2911 MicrosoftRecordLayoutBuilder Builder(*this);
2912 if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
2913 Builder.cxxLayout(RD);
2914 NewEntry = new (*this) ASTRecordLayout(
2915 *this, Builder.Size, Builder.Alignment, Builder.RequiredAlignment,
2916 Builder.HasOwnVFPtr, Builder.HasOwnVFPtr || Builder.PrimaryBase,
2917 Builder.VBPtrOffset, Builder.NonVirtualSize,
2918 Builder.FieldOffsets.data(), Builder.FieldOffsets.size(),
2919 Builder.NonVirtualSize, Builder.Alignment, CharUnits::Zero(),
2920 Builder.PrimaryBase, false, Builder.SharedVBPtrBase,
2921 Builder.EndsWithZeroSizedObject, Builder.LeadsWithZeroSizedBase,
2922 Builder.Bases, Builder.VBases);
2925 NewEntry = new (*this) ASTRecordLayout(
2926 *this, Builder.Size, Builder.Alignment, Builder.RequiredAlignment,
2927 Builder.Size, Builder.FieldOffsets.data(),
2928 Builder.FieldOffsets.size());
2931 if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
2932 EmptySubobjectMap EmptySubobjects(*this, RD);
2933 ItaniumRecordLayoutBuilder Builder(*this, &EmptySubobjects);
2936 // In certain situations, we are allowed to lay out objects in the
2937 // tail-padding of base classes. This is ABI-dependent.
2938 // FIXME: this should be stored in the record layout.
2939 bool skipTailPadding =
2940 mustSkipTailPadding(getTargetInfo().getCXXABI(), RD);
2942 // FIXME: This should be done in FinalizeLayout.
2943 CharUnits DataSize =
2944 skipTailPadding ? Builder.getSize() : Builder.getDataSize();
2945 CharUnits NonVirtualSize =
2946 skipTailPadding ? DataSize : Builder.NonVirtualSize;
2947 NewEntry = new (*this) ASTRecordLayout(
2948 *this, Builder.getSize(), Builder.Alignment,
2949 /*RequiredAlignment : used by MS-ABI)*/
2950 Builder.Alignment, Builder.HasOwnVFPtr, RD->isDynamicClass(),
2951 CharUnits::fromQuantity(-1), DataSize, Builder.FieldOffsets.data(),
2952 Builder.FieldOffsets.size(), NonVirtualSize,
2953 Builder.NonVirtualAlignment,
2954 EmptySubobjects.SizeOfLargestEmptySubobject, Builder.PrimaryBase,
2955 Builder.PrimaryBaseIsVirtual, nullptr, false, false, Builder.Bases,
2958 ItaniumRecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/nullptr);
2961 NewEntry = new (*this) ASTRecordLayout(
2962 *this, Builder.getSize(), Builder.Alignment,
2963 /*RequiredAlignment : used by MS-ABI)*/
2964 Builder.Alignment, Builder.getSize(), Builder.FieldOffsets.data(),
2965 Builder.FieldOffsets.size());
2969 ASTRecordLayouts[D] = NewEntry;
2971 if (getLangOpts().DumpRecordLayouts) {
2972 llvm::outs() << "\n*** Dumping AST Record Layout\n";
2973 DumpRecordLayout(D, llvm::outs(), getLangOpts().DumpRecordLayoutsSimple);
2979 const CXXMethodDecl *ASTContext::getCurrentKeyFunction(const CXXRecordDecl *RD) {
2980 if (!getTargetInfo().getCXXABI().hasKeyFunctions())
2983 assert(RD->getDefinition() && "Cannot get key function for forward decl!");
2984 RD = cast<CXXRecordDecl>(RD->getDefinition());
2987 // 1) computing the key function might trigger deserialization, which might
2988 // invalidate iterators into KeyFunctions
2989 // 2) 'get' on the LazyDeclPtr might also trigger deserialization and
2990 // invalidate the LazyDeclPtr within the map itself
2991 LazyDeclPtr Entry = KeyFunctions[RD];
2992 const Decl *Result =
2993 Entry ? Entry.get(getExternalSource()) : computeKeyFunction(*this, RD);
2995 // Store it back if it changed.
2996 if (Entry.isOffset() || Entry.isValid() != bool(Result))
2997 KeyFunctions[RD] = const_cast<Decl*>(Result);
2999 return cast_or_null<CXXMethodDecl>(Result);
3002 void ASTContext::setNonKeyFunction(const CXXMethodDecl *Method) {
3003 assert(Method == Method->getFirstDecl() &&
3004 "not working with method declaration from class definition");
3006 // Look up the cache entry. Since we're working with the first
3007 // declaration, its parent must be the class definition, which is
3008 // the correct key for the KeyFunctions hash.
3009 const auto &Map = KeyFunctions;
3010 auto I = Map.find(Method->getParent());
3012 // If it's not cached, there's nothing to do.
3013 if (I == Map.end()) return;
3015 // If it is cached, check whether it's the target method, and if so,
3016 // remove it from the cache. Note, the call to 'get' might invalidate
3017 // the iterator and the LazyDeclPtr object within the map.
3018 LazyDeclPtr Ptr = I->second;
3019 if (Ptr.get(getExternalSource()) == Method) {
3020 // FIXME: remember that we did this for module / chained PCH state?
3021 KeyFunctions.erase(Method->getParent());
3025 static uint64_t getFieldOffset(const ASTContext &C, const FieldDecl *FD) {
3026 const ASTRecordLayout &Layout = C.getASTRecordLayout(FD->getParent());
3027 return Layout.getFieldOffset(FD->getFieldIndex());
3030 uint64_t ASTContext::getFieldOffset(const ValueDecl *VD) const {
3031 uint64_t OffsetInBits;
3032 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
3033 OffsetInBits = ::getFieldOffset(*this, FD);
3035 const IndirectFieldDecl *IFD = cast<IndirectFieldDecl>(VD);
3038 for (const NamedDecl *ND : IFD->chain())
3039 OffsetInBits += ::getFieldOffset(*this, cast<FieldDecl>(ND));
3042 return OffsetInBits;
3045 /// getObjCLayout - Get or compute information about the layout of the
3046 /// given interface.
3048 /// \param Impl - If given, also include the layout of the interface's
3049 /// implementation. This may differ by including synthesized ivars.
3050 const ASTRecordLayout &
3051 ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
3052 const ObjCImplementationDecl *Impl) const {
3053 // Retrieve the definition
3054 if (D->hasExternalLexicalStorage() && !D->getDefinition())
3055 getExternalSource()->CompleteType(const_cast<ObjCInterfaceDecl*>(D));
3056 D = D->getDefinition();
3057 assert(D && D->isThisDeclarationADefinition() && "Invalid interface decl!");
3059 // Look up this layout, if already laid out, return what we have.
3060 const ObjCContainerDecl *Key =
3061 Impl ? (const ObjCContainerDecl*) Impl : (const ObjCContainerDecl*) D;
3062 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
3065 // Add in synthesized ivar count if laying out an implementation.
3067 unsigned SynthCount = CountNonClassIvars(D);
3068 // If there aren't any sythesized ivars then reuse the interface
3069 // entry. Note we can't cache this because we simply free all
3070 // entries later; however we shouldn't look up implementations
3072 if (SynthCount == 0)
3073 return getObjCLayout(D, nullptr);
3076 ItaniumRecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/nullptr);
3079 const ASTRecordLayout *NewEntry =
3080 new (*this) ASTRecordLayout(*this, Builder.getSize(),
3082 /*RequiredAlignment : used by MS-ABI)*/
3084 Builder.getDataSize(),
3085 Builder.FieldOffsets.data(),
3086 Builder.FieldOffsets.size());
3088 ObjCLayouts[Key] = NewEntry;
3093 static void PrintOffset(raw_ostream &OS,
3094 CharUnits Offset, unsigned IndentLevel) {
3095 OS << llvm::format("%10" PRId64 " | ", (int64_t)Offset.getQuantity());
3096 OS.indent(IndentLevel * 2);
3099 static void PrintBitFieldOffset(raw_ostream &OS, CharUnits Offset,
3100 unsigned Begin, unsigned Width,
3101 unsigned IndentLevel) {
3102 llvm::SmallString<10> Buffer;
3104 llvm::raw_svector_ostream BufferOS(Buffer);
3105 BufferOS << Offset.getQuantity() << ':';
3109 BufferOS << Begin << '-' << (Begin + Width - 1);
3113 OS << llvm::right_justify(Buffer, 10) << " | ";
3114 OS.indent(IndentLevel * 2);
3117 static void PrintIndentNoOffset(raw_ostream &OS, unsigned IndentLevel) {
3119 OS.indent(IndentLevel * 2);
3122 static void DumpRecordLayout(raw_ostream &OS, const RecordDecl *RD,
3123 const ASTContext &C,
3125 unsigned IndentLevel,
3126 const char* Description,
3128 bool IncludeVirtualBases) {
3129 const ASTRecordLayout &Layout = C.getASTRecordLayout(RD);
3130 auto CXXRD = dyn_cast<CXXRecordDecl>(RD);
3132 PrintOffset(OS, Offset, IndentLevel);
3133 OS << C.getTypeDeclType(const_cast<RecordDecl*>(RD)).getAsString();
3135 OS << ' ' << Description;
3136 if (CXXRD && CXXRD->isEmpty())
3144 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
3145 bool HasOwnVFPtr = Layout.hasOwnVFPtr();
3146 bool HasOwnVBPtr = Layout.hasOwnVBPtr();
3149 if (CXXRD->isDynamicClass() && !PrimaryBase && !isMsLayout(C)) {
3150 PrintOffset(OS, Offset, IndentLevel);
3151 OS << '(' << *RD << " vtable pointer)\n";
3152 } else if (HasOwnVFPtr) {
3153 PrintOffset(OS, Offset, IndentLevel);
3154 // vfptr (for Microsoft C++ ABI)
3155 OS << '(' << *RD << " vftable pointer)\n";
3159 SmallVector<const CXXRecordDecl *, 4> Bases;
3160 for (const CXXBaseSpecifier &Base : CXXRD->bases()) {
3161 assert(!Base.getType()->isDependentType() &&
3162 "Cannot layout class with dependent bases.");
3163 if (!Base.isVirtual())
3164 Bases.push_back(Base.getType()->getAsCXXRecordDecl());
3167 // Sort nvbases by offset.
3168 std::stable_sort(Bases.begin(), Bases.end(),
3169 [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
3170 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
3173 // Dump (non-virtual) bases
3174 for (const CXXRecordDecl *Base : Bases) {
3175 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base);
3176 DumpRecordLayout(OS, Base, C, BaseOffset, IndentLevel,
3177 Base == PrimaryBase ? "(primary base)" : "(base)",
3178 /*PrintSizeInfo=*/false,
3179 /*IncludeVirtualBases=*/false);
3182 // vbptr (for Microsoft C++ ABI)
3184 PrintOffset(OS, Offset + Layout.getVBPtrOffset(), IndentLevel);
3185 OS << '(' << *RD << " vbtable pointer)\n";
3190 uint64_t FieldNo = 0;
3191 for (RecordDecl::field_iterator I = RD->field_begin(),
3192 E = RD->field_end(); I != E; ++I, ++FieldNo) {
3193 const FieldDecl &Field = **I;
3194 uint64_t LocalFieldOffsetInBits = Layout.getFieldOffset(FieldNo);
3195 CharUnits FieldOffset =
3196 Offset + C.toCharUnitsFromBits(LocalFieldOffsetInBits);
3198 // Recursively dump fields of record type.
3199 if (auto RT = Field.getType()->getAs<RecordType>()) {
3200 DumpRecordLayout(OS, RT->getDecl(), C, FieldOffset, IndentLevel,
3201 Field.getName().data(),
3202 /*PrintSizeInfo=*/false,
3203 /*IncludeVirtualBases=*/true);
3207 if (Field.isBitField()) {
3208 uint64_t LocalFieldByteOffsetInBits = C.toBits(FieldOffset - Offset);
3209 unsigned Begin = LocalFieldOffsetInBits - LocalFieldByteOffsetInBits;
3210 unsigned Width = Field.getBitWidthValue(C);
3211 PrintBitFieldOffset(OS, FieldOffset, Begin, Width, IndentLevel);
3213 PrintOffset(OS, FieldOffset, IndentLevel);
3215 OS << Field.getType().getAsString() << ' ' << Field << '\n';
3218 // Dump virtual bases.
3219 if (CXXRD && IncludeVirtualBases) {
3220 const ASTRecordLayout::VBaseOffsetsMapTy &VtorDisps =
3221 Layout.getVBaseOffsetsMap();
3223 for (const CXXBaseSpecifier &Base : CXXRD->vbases()) {
3224 assert(Base.isVirtual() && "Found non-virtual class!");
3225 const CXXRecordDecl *VBase = Base.getType()->getAsCXXRecordDecl();
3227 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBase);
3229 if (VtorDisps.find(VBase)->second.hasVtorDisp()) {
3230 PrintOffset(OS, VBaseOffset - CharUnits::fromQuantity(4), IndentLevel);
3231 OS << "(vtordisp for vbase " << *VBase << ")\n";
3234 DumpRecordLayout(OS, VBase, C, VBaseOffset, IndentLevel,
3235 VBase == Layout.getPrimaryBase() ?
3236 "(primary virtual base)" : "(virtual base)",
3237 /*PrintSizeInfo=*/false,
3238 /*IncludeVirtualBases=*/false);
3242 if (!PrintSizeInfo) return;
3244 PrintIndentNoOffset(OS, IndentLevel - 1);
3245 OS << "[sizeof=" << Layout.getSize().getQuantity();
3246 if (CXXRD && !isMsLayout(C))
3247 OS << ", dsize=" << Layout.getDataSize().getQuantity();
3248 OS << ", align=" << Layout.getAlignment().getQuantity();
3252 PrintIndentNoOffset(OS, IndentLevel - 1);
3253 OS << " nvsize=" << Layout.getNonVirtualSize().getQuantity();
3254 OS << ", nvalign=" << Layout.getNonVirtualAlignment().getQuantity();
3259 void ASTContext::DumpRecordLayout(const RecordDecl *RD,
3261 bool Simple) const {
3263 ::DumpRecordLayout(OS, RD, *this, CharUnits(), 0, nullptr,
3264 /*PrintSizeInfo*/true,
3265 /*IncludeVirtualBases=*/true);
3269 // The "simple" format is designed to be parsed by the
3270 // layout-override testing code. There shouldn't be any external
3271 // uses of this format --- when LLDB overrides a layout, it sets up
3272 // the data structures directly --- so feel free to adjust this as
3273 // you like as long as you also update the rudimentary parser for it
3276 const ASTRecordLayout &Info = getASTRecordLayout(RD);
3277 OS << "Type: " << getTypeDeclType(RD).getAsString() << "\n";
3279 OS << "<ASTRecordLayout\n";
3280 OS << " Size:" << toBits(Info.getSize()) << "\n";
3281 if (!isMsLayout(*this))
3282 OS << " DataSize:" << toBits(Info.getDataSize()) << "\n";
3283 OS << " Alignment:" << toBits(Info.getAlignment()) << "\n";
3284 OS << " FieldOffsets: [";
3285 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i) {
3287 OS << Info.getFieldOffset(i);