clang 20.0.0git
RecordLayoutBuilder.cpp
Go to the documentation of this file.
1//=== RecordLayoutBuilder.cpp - Helper class for building record layouts ---==//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
11#include "clang/AST/Attr.h"
13#include "clang/AST/Decl.h"
14#include "clang/AST/DeclCXX.h"
15#include "clang/AST/DeclObjC.h"
16#include "clang/AST/Expr.h"
20#include "llvm/Support/Format.h"
21#include "llvm/Support/MathExtras.h"
22
23using namespace clang;
24
25namespace {
26
27/// BaseSubobjectInfo - Represents a single base subobject in a complete class.
28/// For a class hierarchy like
29///
30/// class A { };
31/// class B : A { };
32/// class C : A, B { };
33///
34/// The BaseSubobjectInfo graph for C will have three BaseSubobjectInfo
35/// instances, one for B and two for A.
36///
37/// If a base is virtual, it will only have one BaseSubobjectInfo allocated.
38struct BaseSubobjectInfo {
39 /// Class - The class for this base info.
40 const CXXRecordDecl *Class;
41
42 /// IsVirtual - Whether the BaseInfo represents a virtual base or not.
43 bool IsVirtual;
44
45 /// Bases - Information about the base subobjects.
47
48 /// PrimaryVirtualBaseInfo - Holds the base info for the primary virtual base
49 /// of this base info (if one exists).
50 BaseSubobjectInfo *PrimaryVirtualBaseInfo;
51
52 // FIXME: Document.
53 const BaseSubobjectInfo *Derived;
54};
55
56/// Externally provided layout. Typically used when the AST source, such
57/// as DWARF, lacks all the information that was available at compile time, such
58/// as alignment attributes on fields and pragmas in effect.
59struct ExternalLayout {
60 ExternalLayout() = default;
61
62 /// Overall record size in bits.
63 uint64_t Size = 0;
64
65 /// Overall record alignment in bits.
66 uint64_t Align = 0;
67
68 /// Record field offsets in bits.
69 llvm::DenseMap<const FieldDecl *, uint64_t> FieldOffsets;
70
71 /// Direct, non-virtual base offsets.
72 llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsets;
73
74 /// Virtual base offsets.
75 llvm::DenseMap<const CXXRecordDecl *, CharUnits> VirtualBaseOffsets;
76
77 /// Get the offset of the given field. The external source must provide
78 /// entries for all fields in the record.
79 uint64_t getExternalFieldOffset(const FieldDecl *FD) {
80 assert(FieldOffsets.count(FD) &&
81 "Field does not have an external offset");
82 return FieldOffsets[FD];
83 }
84
85 bool getExternalNVBaseOffset(const CXXRecordDecl *RD, CharUnits &BaseOffset) {
86 auto Known = BaseOffsets.find(RD);
87 if (Known == BaseOffsets.end())
88 return false;
89 BaseOffset = Known->second;
90 return true;
91 }
92
93 bool getExternalVBaseOffset(const CXXRecordDecl *RD, CharUnits &BaseOffset) {
94 auto Known = VirtualBaseOffsets.find(RD);
95 if (Known == VirtualBaseOffsets.end())
96 return false;
97 BaseOffset = Known->second;
98 return true;
99 }
100};
101
102/// EmptySubobjectMap - Keeps track of which empty subobjects exist at different
103/// offsets while laying out a C++ class.
104class EmptySubobjectMap {
105 const ASTContext &Context;
106 uint64_t CharWidth;
107
108 /// Class - The class whose empty entries we're keeping track of.
109 const CXXRecordDecl *Class;
110
111 /// EmptyClassOffsets - A map from offsets to empty record decls.
112 typedef llvm::TinyPtrVector<const CXXRecordDecl *> ClassVectorTy;
113 typedef llvm::DenseMap<CharUnits, ClassVectorTy> EmptyClassOffsetsMapTy;
114 EmptyClassOffsetsMapTy EmptyClassOffsets;
115
116 /// MaxEmptyClassOffset - The highest offset known to contain an empty
117 /// base subobject.
118 CharUnits MaxEmptyClassOffset;
119
120 /// ComputeEmptySubobjectSizes - Compute the size of the largest base or
121 /// member subobject that is empty.
122 void ComputeEmptySubobjectSizes();
123
124 void AddSubobjectAtOffset(const CXXRecordDecl *RD, CharUnits Offset);
125
126 void UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info,
127 CharUnits Offset, bool PlacingEmptyBase);
128
129 void UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD,
130 const CXXRecordDecl *Class, CharUnits Offset,
131 bool PlacingOverlappingField);
132 void UpdateEmptyFieldSubobjects(const FieldDecl *FD, CharUnits Offset,
133 bool PlacingOverlappingField);
134
135 /// AnyEmptySubobjectsBeyondOffset - Returns whether there are any empty
136 /// subobjects beyond the given offset.
137 bool AnyEmptySubobjectsBeyondOffset(CharUnits Offset) const {
138 return Offset <= MaxEmptyClassOffset;
139 }
140
142 const FieldDecl *Field) const {
143 uint64_t FieldOffset = Layout.getFieldOffset(Field->getFieldIndex());
144 assert(FieldOffset % CharWidth == 0 &&
145 "Field offset not at char boundary!");
146
147 return Context.toCharUnitsFromBits(FieldOffset);
148 }
149
150protected:
151 bool CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD,
152 CharUnits Offset) const;
153
154 bool CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info,
155 CharUnits Offset);
156
157 bool CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD,
158 const CXXRecordDecl *Class,
159 CharUnits Offset) const;
160 bool CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD,
161 CharUnits Offset) const;
162
163public:
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;
168
169 EmptySubobjectMap(const ASTContext &Context, const CXXRecordDecl *Class)
170 : Context(Context), CharWidth(Context.getCharWidth()), Class(Class) {
171 ComputeEmptySubobjectSizes();
172 }
173
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,
179 CharUnits Offset);
180
181 /// CanPlaceFieldAtOffset - Return whether a field can be placed at the given
182 /// offset.
183 bool CanPlaceFieldAtOffset(const FieldDecl *FD, CharUnits Offset);
184};
185
186void EmptySubobjectMap::ComputeEmptySubobjectSizes() {
187 // Check the bases.
188 for (const CXXBaseSpecifier &Base : Class->bases()) {
189 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
190
191 CharUnits EmptySize;
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();
196 } else {
197 // Otherwise, we get the largest empty subobject for the decl.
198 EmptySize = Layout.getSizeOfLargestEmptySubobject();
199 }
200
201 if (EmptySize > SizeOfLargestEmptySubobject)
202 SizeOfLargestEmptySubobject = EmptySize;
203 }
204
205 // Check the fields.
206 for (const FieldDecl *FD : Class->fields()) {
207 const RecordType *RT =
208 Context.getBaseElementType(FD->getType())->getAs<RecordType>();
209
210 // We only care about record types.
211 if (!RT)
212 continue;
213
214 CharUnits EmptySize;
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();
220 } else {
221 // Otherwise, we get the largest empty subobject for the decl.
222 EmptySize = Layout.getSizeOfLargestEmptySubobject();
223 }
224
225 if (EmptySize > SizeOfLargestEmptySubobject)
226 SizeOfLargestEmptySubobject = EmptySize;
227 }
228}
229
230bool
231EmptySubobjectMap::CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD,
232 CharUnits Offset) const {
233 // We only need to check empty bases.
234 if (!RD->isEmpty())
235 return true;
236
237 EmptyClassOffsetsMapTy::const_iterator I = EmptyClassOffsets.find(Offset);
238 if (I == EmptyClassOffsets.end())
239 return true;
240
241 const ClassVectorTy &Classes = I->second;
242 if (!llvm::is_contained(Classes, RD))
243 return true;
244
245 // There is already an empty class of the same type at this offset.
246 return false;
247}
248
249void EmptySubobjectMap::AddSubobjectAtOffset(const CXXRecordDecl *RD,
250 CharUnits Offset) {
251 // We only care about empty bases.
252 if (!RD->isEmpty())
253 return;
254
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 (llvm::is_contained(Classes, RD))
259 return;
260
261 Classes.push_back(RD);
262
263 // Update the empty class offset.
264 if (Offset > MaxEmptyClassOffset)
265 MaxEmptyClassOffset = Offset;
266}
267
268bool
269EmptySubobjectMap::CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info,
270 CharUnits Offset) {
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))
274 return true;
275
276 if (!CanPlaceSubobjectAtOffset(Info->Class, Offset))
277 return false;
278
279 // Traverse all non-virtual bases.
280 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
281 for (const BaseSubobjectInfo *Base : Info->Bases) {
282 if (Base->IsVirtual)
283 continue;
284
285 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
286
287 if (!CanPlaceBaseSubobjectAtOffset(Base, BaseOffset))
288 return false;
289 }
290
291 if (Info->PrimaryVirtualBaseInfo) {
292 BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
293
294 if (Info == PrimaryVirtualBaseInfo->Derived) {
295 if (!CanPlaceBaseSubobjectAtOffset(PrimaryVirtualBaseInfo, Offset))
296 return false;
297 }
298 }
299
300 // Traverse all member variables.
301 for (const FieldDecl *Field : Info->Class->fields()) {
302 if (Field->isBitField())
303 continue;
304
305 CharUnits FieldOffset = Offset + getFieldOffset(Layout, Field);
306 if (!CanPlaceFieldSubobjectAtOffset(Field, FieldOffset))
307 return false;
308 }
309
310 return true;
311}
312
313void EmptySubobjectMap::UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info,
314 CharUnits Offset,
315 bool PlacingEmptyBase) {
316 if (!PlacingEmptyBase && Offset >= SizeOfLargestEmptySubobject) {
317 // We know that the only empty subobjects that can conflict with empty
318 // subobject of non-empty bases, are empty bases that can be placed at
319 // offset zero. Because of this, we only need to keep track of empty base
320 // subobjects with offsets less than the size of the largest empty
321 // subobject for our class.
322 return;
323 }
324
325 AddSubobjectAtOffset(Info->Class, Offset);
326
327 // Traverse all non-virtual bases.
328 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
329 for (const BaseSubobjectInfo *Base : Info->Bases) {
330 if (Base->IsVirtual)
331 continue;
332
333 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
334 UpdateEmptyBaseSubobjects(Base, BaseOffset, PlacingEmptyBase);
335 }
336
337 if (Info->PrimaryVirtualBaseInfo) {
338 BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
339
340 if (Info == PrimaryVirtualBaseInfo->Derived)
341 UpdateEmptyBaseSubobjects(PrimaryVirtualBaseInfo, Offset,
342 PlacingEmptyBase);
343 }
344
345 // Traverse all member variables.
346 for (const FieldDecl *Field : Info->Class->fields()) {
347 if (Field->isBitField())
348 continue;
349
350 CharUnits FieldOffset = Offset + getFieldOffset(Layout, Field);
351 UpdateEmptyFieldSubobjects(Field, FieldOffset, PlacingEmptyBase);
352 }
353}
354
355bool EmptySubobjectMap::CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info,
356 CharUnits Offset) {
357 // If we know this class doesn't have any empty subobjects we don't need to
358 // bother checking.
359 if (SizeOfLargestEmptySubobject.isZero())
360 return true;
361
362 if (!CanPlaceBaseSubobjectAtOffset(Info, Offset))
363 return false;
364
365 // We are able to place the base at this offset. Make sure to update the
366 // empty base subobject map.
367 UpdateEmptyBaseSubobjects(Info, Offset, Info->Class->isEmpty());
368 return true;
369}
370
371bool
372EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD,
373 const CXXRecordDecl *Class,
374 CharUnits Offset) const {
375 // We don't have to keep looking past the maximum offset that's known to
376 // contain an empty class.
377 if (!AnyEmptySubobjectsBeyondOffset(Offset))
378 return true;
379
380 if (!CanPlaceSubobjectAtOffset(RD, Offset))
381 return false;
382
383 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
384
385 // Traverse all non-virtual bases.
386 for (const CXXBaseSpecifier &Base : RD->bases()) {
387 if (Base.isVirtual())
388 continue;
389
390 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
391
392 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
393 if (!CanPlaceFieldSubobjectAtOffset(BaseDecl, Class, BaseOffset))
394 return false;
395 }
396
397 if (RD == Class) {
398 // This is the most derived class, traverse virtual bases as well.
399 for (const CXXBaseSpecifier &Base : RD->vbases()) {
400 const CXXRecordDecl *VBaseDecl = Base.getType()->getAsCXXRecordDecl();
401
402 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
403 if (!CanPlaceFieldSubobjectAtOffset(VBaseDecl, Class, VBaseOffset))
404 return false;
405 }
406 }
407
408 // Traverse all member variables.
409 for (const FieldDecl *Field : RD->fields()) {
410 if (Field->isBitField())
411 continue;
412
413 CharUnits FieldOffset = Offset + getFieldOffset(Layout, Field);
414 if (!CanPlaceFieldSubobjectAtOffset(Field, FieldOffset))
415 return false;
416 }
417
418 return true;
419}
420
421bool
422EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD,
423 CharUnits Offset) const {
424 // We don't have to keep looking past the maximum offset that's known to
425 // contain an empty class.
426 if (!AnyEmptySubobjectsBeyondOffset(Offset))
427 return true;
428
429 QualType T = FD->getType();
430 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
431 return CanPlaceFieldSubobjectAtOffset(RD, RD, Offset);
432
433 // If we have an array type we need to look at every element.
434 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
435 QualType ElemTy = Context.getBaseElementType(AT);
436 const RecordType *RT = ElemTy->getAs<RecordType>();
437 if (!RT)
438 return true;
439
440 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
441 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
442
443 uint64_t NumElements = Context.getConstantArrayElementCount(AT);
444 CharUnits ElementOffset = Offset;
445 for (uint64_t I = 0; I != NumElements; ++I) {
446 // We don't have to keep looking past the maximum offset that's known to
447 // contain an empty class.
448 if (!AnyEmptySubobjectsBeyondOffset(ElementOffset))
449 return true;
450
451 if (!CanPlaceFieldSubobjectAtOffset(RD, RD, ElementOffset))
452 return false;
453
454 ElementOffset += Layout.getSize();
455 }
456 }
457
458 return true;
459}
460
461bool EmptySubobjectMap::CanPlaceFieldAtOffset(const FieldDecl *FD,
462 CharUnits Offset) {
463 if (!CanPlaceFieldSubobjectAtOffset(FD, Offset))
464 return false;
465
466 // We are able to place the member variable at this offset.
467 // Make sure to update the empty field subobject map.
468 UpdateEmptyFieldSubobjects(FD, Offset, FD->hasAttr<NoUniqueAddressAttr>());
469 return true;
470}
471
472void EmptySubobjectMap::UpdateEmptyFieldSubobjects(
473 const CXXRecordDecl *RD, const CXXRecordDecl *Class, CharUnits Offset,
474 bool PlacingOverlappingField) {
475 // We know that the only empty subobjects that can conflict with empty
476 // field subobjects are subobjects of empty bases and potentially-overlapping
477 // fields that can be placed at offset zero. Because of this, we only need to
478 // keep track of empty field subobjects with offsets less than the size of
479 // the largest empty subobject for our class.
480 //
481 // (Proof: we will only consider placing a subobject at offset zero or at
482 // >= the current dsize. The only cases where the earlier subobject can be
483 // placed beyond the end of dsize is if it's an empty base or a
484 // potentially-overlapping field.)
485 if (!PlacingOverlappingField && Offset >= SizeOfLargestEmptySubobject)
486 return;
487
488 AddSubobjectAtOffset(RD, Offset);
489
490 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
491
492 // Traverse all non-virtual bases.
493 for (const CXXBaseSpecifier &Base : RD->bases()) {
494 if (Base.isVirtual())
495 continue;
496
497 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
498
499 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
500 UpdateEmptyFieldSubobjects(BaseDecl, Class, BaseOffset,
501 PlacingOverlappingField);
502 }
503
504 if (RD == Class) {
505 // This is the most derived class, traverse virtual bases as well.
506 for (const CXXBaseSpecifier &Base : RD->vbases()) {
507 const CXXRecordDecl *VBaseDecl = Base.getType()->getAsCXXRecordDecl();
508
509 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
510 UpdateEmptyFieldSubobjects(VBaseDecl, Class, VBaseOffset,
511 PlacingOverlappingField);
512 }
513 }
514
515 // Traverse all member variables.
516 for (const FieldDecl *Field : RD->fields()) {
517 if (Field->isBitField())
518 continue;
519
520 CharUnits FieldOffset = Offset + getFieldOffset(Layout, Field);
521 UpdateEmptyFieldSubobjects(Field, FieldOffset, PlacingOverlappingField);
522 }
523}
524
525void EmptySubobjectMap::UpdateEmptyFieldSubobjects(
526 const FieldDecl *FD, CharUnits Offset, bool PlacingOverlappingField) {
527 QualType T = FD->getType();
528 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
529 UpdateEmptyFieldSubobjects(RD, RD, Offset, PlacingOverlappingField);
530 return;
531 }
532
533 // If we have an array type we need to update every element.
534 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
535 QualType ElemTy = Context.getBaseElementType(AT);
536 const RecordType *RT = ElemTy->getAs<RecordType>();
537 if (!RT)
538 return;
539
540 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
541 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
542
543 uint64_t NumElements = Context.getConstantArrayElementCount(AT);
544 CharUnits ElementOffset = Offset;
545
546 for (uint64_t I = 0; I != NumElements; ++I) {
547 // We know that the only empty subobjects that can conflict with empty
548 // field subobjects are subobjects of empty bases that can be placed at
549 // offset zero. Because of this, we only need to keep track of empty field
550 // subobjects with offsets less than the size of the largest empty
551 // subobject for our class.
552 if (!PlacingOverlappingField &&
553 ElementOffset >= SizeOfLargestEmptySubobject)
554 return;
555
556 UpdateEmptyFieldSubobjects(RD, RD, ElementOffset,
557 PlacingOverlappingField);
558 ElementOffset += Layout.getSize();
559 }
560 }
561}
562
564
565class ItaniumRecordLayoutBuilder {
566protected:
567 // FIXME: Remove this and make the appropriate fields public.
568 friend class clang::ASTContext;
569
570 const ASTContext &Context;
571
572 EmptySubobjectMap *EmptySubobjects;
573
574 /// Size - The current size of the record layout.
576
577 /// Alignment - The current alignment of the record layout.
578 CharUnits Alignment;
579
580 /// PreferredAlignment - The preferred alignment of the record layout.
581 CharUnits PreferredAlignment;
582
583 /// The alignment if attribute packed is not used.
584 CharUnits UnpackedAlignment;
585
586 /// \brief The maximum of the alignments of top-level members.
587 CharUnits UnadjustedAlignment;
588
589 SmallVector<uint64_t, 16> FieldOffsets;
590
591 /// Whether the external AST source has provided a layout for this
592 /// record.
593 LLVM_PREFERRED_TYPE(bool)
594 unsigned UseExternalLayout : 1;
595
596 /// Whether we need to infer alignment, even when we have an
597 /// externally-provided layout.
598 LLVM_PREFERRED_TYPE(bool)
599 unsigned InferAlignment : 1;
600
601 /// Packed - Whether the record is packed or not.
602 LLVM_PREFERRED_TYPE(bool)
603 unsigned Packed : 1;
604
605 LLVM_PREFERRED_TYPE(bool)
606 unsigned IsUnion : 1;
607
608 LLVM_PREFERRED_TYPE(bool)
609 unsigned IsMac68kAlign : 1;
610
611 LLVM_PREFERRED_TYPE(bool)
612 unsigned IsNaturalAlign : 1;
613
614 LLVM_PREFERRED_TYPE(bool)
615 unsigned IsMsStruct : 1;
616
617 /// UnfilledBitsInLastUnit - If the last field laid out was a bitfield,
618 /// this contains the number of bits in the last unit that can be used for
619 /// an adjacent bitfield if necessary. The unit in question is usually
620 /// a byte, but larger units are used if IsMsStruct.
621 unsigned char UnfilledBitsInLastUnit;
622
623 /// LastBitfieldStorageUnitSize - If IsMsStruct, represents the size of the
624 /// storage unit of the previous field if it was a bitfield.
625 unsigned char LastBitfieldStorageUnitSize;
626
627 /// MaxFieldAlignment - The maximum allowed field alignment. This is set by
628 /// #pragma pack.
629 CharUnits MaxFieldAlignment;
630
631 /// DataSize - The data size of the record being laid out.
632 uint64_t DataSize;
633
634 CharUnits NonVirtualSize;
635 CharUnits NonVirtualAlignment;
636 CharUnits PreferredNVAlignment;
637
638 /// If we've laid out a field but not included its tail padding in Size yet,
639 /// this is the size up to the end of that field.
640 CharUnits PaddedFieldSize;
641
642 /// PrimaryBase - the primary base class (if one exists) of the class
643 /// we're laying out.
644 const CXXRecordDecl *PrimaryBase;
645
646 /// PrimaryBaseIsVirtual - Whether the primary base of the class we're laying
647 /// out is virtual.
648 bool PrimaryBaseIsVirtual;
649
650 /// HasOwnVFPtr - Whether the class provides its own vtable/vftbl
651 /// pointer, as opposed to inheriting one from a primary base class.
652 bool HasOwnVFPtr;
653
654 /// the flag of field offset changing due to packed attribute.
655 bool HasPackedField;
656
657 /// HandledFirstNonOverlappingEmptyField - An auxiliary field used for AIX.
658 /// When there are OverlappingEmptyFields existing in the aggregate, the
659 /// flag shows if the following first non-empty or empty-but-non-overlapping
660 /// field has been handled, if any.
661 bool HandledFirstNonOverlappingEmptyField;
662
663 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
664
665 /// Bases - base classes and their offsets in the record.
666 BaseOffsetsMapTy Bases;
667
668 // VBases - virtual base classes and their offsets in the record.
670
671 /// IndirectPrimaryBases - Virtual base classes, direct or indirect, that are
672 /// primary base classes for some other direct or indirect base class.
673 CXXIndirectPrimaryBaseSet IndirectPrimaryBases;
674
675 /// FirstNearlyEmptyVBase - The first nearly empty virtual base class in
676 /// inheritance graph order. Used for determining the primary base class.
677 const CXXRecordDecl *FirstNearlyEmptyVBase;
678
679 /// VisitedVirtualBases - A set of all the visited virtual bases, used to
680 /// avoid visiting virtual bases more than once.
682
683 /// Valid if UseExternalLayout is true.
684 ExternalLayout External;
685
686 ItaniumRecordLayoutBuilder(const ASTContext &Context,
687 EmptySubobjectMap *EmptySubobjects)
688 : Context(Context), EmptySubobjects(EmptySubobjects), Size(0),
689 Alignment(CharUnits::One()), PreferredAlignment(CharUnits::One()),
690 UnpackedAlignment(CharUnits::One()),
691 UnadjustedAlignment(CharUnits::One()), UseExternalLayout(false),
692 InferAlignment(false), Packed(false), IsUnion(false),
693 IsMac68kAlign(false),
694 IsNaturalAlign(!Context.getTargetInfo().getTriple().isOSAIX()),
695 IsMsStruct(false), UnfilledBitsInLastUnit(0),
696 LastBitfieldStorageUnitSize(0), MaxFieldAlignment(CharUnits::Zero()),
697 DataSize(0), NonVirtualSize(CharUnits::Zero()),
698 NonVirtualAlignment(CharUnits::One()),
699 PreferredNVAlignment(CharUnits::One()),
700 PaddedFieldSize(CharUnits::Zero()), PrimaryBase(nullptr),
701 PrimaryBaseIsVirtual(false), HasOwnVFPtr(false), HasPackedField(false),
702 HandledFirstNonOverlappingEmptyField(false),
703 FirstNearlyEmptyVBase(nullptr) {}
704
705 void Layout(const RecordDecl *D);
706 void Layout(const CXXRecordDecl *D);
707 void Layout(const ObjCInterfaceDecl *D);
708
709 void LayoutFields(const RecordDecl *D);
710 void LayoutField(const FieldDecl *D, bool InsertExtraPadding);
711 void LayoutWideBitField(uint64_t FieldSize, uint64_t StorageUnitSize,
712 bool FieldPacked, const FieldDecl *D);
713 void LayoutBitField(const FieldDecl *D);
714
715 TargetCXXABI getCXXABI() const {
716 return Context.getTargetInfo().getCXXABI();
717 }
718
719 /// BaseSubobjectInfoAllocator - Allocator for BaseSubobjectInfo objects.
720 llvm::SpecificBumpPtrAllocator<BaseSubobjectInfo> BaseSubobjectInfoAllocator;
721
722 typedef llvm::DenseMap<const CXXRecordDecl *, BaseSubobjectInfo *>
723 BaseSubobjectInfoMapTy;
724
725 /// VirtualBaseInfo - Map from all the (direct or indirect) virtual bases
726 /// of the class we're laying out to their base subobject info.
727 BaseSubobjectInfoMapTy VirtualBaseInfo;
728
729 /// NonVirtualBaseInfo - Map from all the direct non-virtual bases of the
730 /// class we're laying out to their base subobject info.
731 BaseSubobjectInfoMapTy NonVirtualBaseInfo;
732
733 /// ComputeBaseSubobjectInfo - Compute the base subobject information for the
734 /// bases of the given class.
735 void ComputeBaseSubobjectInfo(const CXXRecordDecl *RD);
736
737 /// ComputeBaseSubobjectInfo - Compute the base subobject information for a
738 /// single class and all of its base classes.
739 BaseSubobjectInfo *ComputeBaseSubobjectInfo(const CXXRecordDecl *RD,
740 bool IsVirtual,
741 BaseSubobjectInfo *Derived);
742
743 /// DeterminePrimaryBase - Determine the primary base of the given class.
744 void DeterminePrimaryBase(const CXXRecordDecl *RD);
745
746 void SelectPrimaryVBase(const CXXRecordDecl *RD);
747
748 void EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign);
749
750 /// LayoutNonVirtualBases - Determines the primary base class (if any) and
751 /// lays it out. Will then proceed to lay out all non-virtual base clasess.
752 void LayoutNonVirtualBases(const CXXRecordDecl *RD);
753
754 /// LayoutNonVirtualBase - Lays out a single non-virtual base.
755 void LayoutNonVirtualBase(const BaseSubobjectInfo *Base);
756
757 void AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
758 CharUnits Offset);
759
760 /// LayoutVirtualBases - Lays out all the virtual bases.
761 void LayoutVirtualBases(const CXXRecordDecl *RD,
762 const CXXRecordDecl *MostDerivedClass);
763
764 /// LayoutVirtualBase - Lays out a single virtual base.
765 void LayoutVirtualBase(const BaseSubobjectInfo *Base);
766
767 /// LayoutBase - Will lay out a base and return the offset where it was
768 /// placed, in chars.
769 CharUnits LayoutBase(const BaseSubobjectInfo *Base);
770
771 /// InitializeLayout - Initialize record layout for the given record decl.
772 void InitializeLayout(const Decl *D);
773
774 /// FinishLayout - Finalize record layout. Adjust record size based on the
775 /// alignment.
776 void FinishLayout(const NamedDecl *D);
777
778 void UpdateAlignment(CharUnits NewAlignment, CharUnits UnpackedNewAlignment,
779 CharUnits PreferredAlignment);
780 void UpdateAlignment(CharUnits NewAlignment, CharUnits UnpackedNewAlignment) {
781 UpdateAlignment(NewAlignment, UnpackedNewAlignment, NewAlignment);
782 }
783 void UpdateAlignment(CharUnits NewAlignment) {
784 UpdateAlignment(NewAlignment, NewAlignment, NewAlignment);
785 }
786
787 /// Retrieve the externally-supplied field offset for the given
788 /// field.
789 ///
790 /// \param Field The field whose offset is being queried.
791 /// \param ComputedOffset The offset that we've computed for this field.
792 uint64_t updateExternalFieldOffset(const FieldDecl *Field,
793 uint64_t ComputedOffset);
794
795 void CheckFieldPadding(uint64_t Offset, uint64_t UnpaddedOffset,
796 uint64_t UnpackedOffset, unsigned UnpackedAlign,
797 bool isPacked, const FieldDecl *D);
798
799 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
800
801 CharUnits getSize() const {
802 assert(Size % Context.getCharWidth() == 0);
803 return Context.toCharUnitsFromBits(Size);
804 }
805 uint64_t getSizeInBits() const { return Size; }
806
807 void setSize(CharUnits NewSize) { Size = Context.toBits(NewSize); }
808 void setSize(uint64_t NewSize) { Size = NewSize; }
809
810 CharUnits getAlignment() const { return Alignment; }
811
812 CharUnits getDataSize() const {
813 assert(DataSize % Context.getCharWidth() == 0);
814 return Context.toCharUnitsFromBits(DataSize);
815 }
816 uint64_t getDataSizeInBits() const { return DataSize; }
817
818 void setDataSize(CharUnits NewSize) { DataSize = Context.toBits(NewSize); }
819 void setDataSize(uint64_t NewSize) { DataSize = NewSize; }
820
821 ItaniumRecordLayoutBuilder(const ItaniumRecordLayoutBuilder &) = delete;
822 void operator=(const ItaniumRecordLayoutBuilder &) = delete;
823};
824} // end anonymous namespace
825
826void ItaniumRecordLayoutBuilder::SelectPrimaryVBase(const CXXRecordDecl *RD) {
827 for (const auto &I : RD->bases()) {
828 assert(!I.getType()->isDependentType() &&
829 "Cannot layout class with dependent bases.");
830
831 const CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
832
833 // Check if this is a nearly empty virtual base.
834 if (I.isVirtual() && Context.isNearlyEmpty(Base)) {
835 // If it's not an indirect primary base, then we've found our primary
836 // base.
837 if (!IndirectPrimaryBases.count(Base)) {
838 PrimaryBase = Base;
839 PrimaryBaseIsVirtual = true;
840 return;
841 }
842
843 // Is this the first nearly empty virtual base?
844 if (!FirstNearlyEmptyVBase)
845 FirstNearlyEmptyVBase = Base;
846 }
847
848 SelectPrimaryVBase(Base);
849 if (PrimaryBase)
850 return;
851 }
852}
853
854/// DeterminePrimaryBase - Determine the primary base of the given class.
855void ItaniumRecordLayoutBuilder::DeterminePrimaryBase(const CXXRecordDecl *RD) {
856 // If the class isn't dynamic, it won't have a primary base.
857 if (!RD->isDynamicClass())
858 return;
859
860 // Compute all the primary virtual bases for all of our direct and
861 // indirect bases, and record all their primary virtual base classes.
862 RD->getIndirectPrimaryBases(IndirectPrimaryBases);
863
864 // If the record has a dynamic base class, attempt to choose a primary base
865 // class. It is the first (in direct base class order) non-virtual dynamic
866 // base class, if one exists.
867 for (const auto &I : RD->bases()) {
868 // Ignore virtual bases.
869 if (I.isVirtual())
870 continue;
871
872 const CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
873
874 if (Base->isDynamicClass()) {
875 // We found it.
876 PrimaryBase = Base;
877 PrimaryBaseIsVirtual = false;
878 return;
879 }
880 }
881
882 // Under the Itanium ABI, if there is no non-virtual primary base class,
883 // try to compute the primary virtual base. The primary virtual base is
884 // the first nearly empty virtual base that is not an indirect primary
885 // virtual base class, if one exists.
886 if (RD->getNumVBases() != 0) {
887 SelectPrimaryVBase(RD);
888 if (PrimaryBase)
889 return;
890 }
891
892 // Otherwise, it is the first indirect primary base class, if one exists.
893 if (FirstNearlyEmptyVBase) {
894 PrimaryBase = FirstNearlyEmptyVBase;
895 PrimaryBaseIsVirtual = true;
896 return;
897 }
898
899 assert(!PrimaryBase && "Should not get here with a primary base!");
900}
901
902BaseSubobjectInfo *ItaniumRecordLayoutBuilder::ComputeBaseSubobjectInfo(
903 const CXXRecordDecl *RD, bool IsVirtual, BaseSubobjectInfo *Derived) {
904 BaseSubobjectInfo *Info;
905
906 if (IsVirtual) {
907 // Check if we already have info about this virtual base.
908 BaseSubobjectInfo *&InfoSlot = VirtualBaseInfo[RD];
909 if (InfoSlot) {
910 assert(InfoSlot->Class == RD && "Wrong class for virtual base info!");
911 return InfoSlot;
912 }
913
914 // We don't, create it.
915 InfoSlot = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
916 Info = InfoSlot;
917 } else {
918 Info = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
919 }
920
921 Info->Class = RD;
922 Info->IsVirtual = IsVirtual;
923 Info->Derived = nullptr;
924 Info->PrimaryVirtualBaseInfo = nullptr;
925
926 const CXXRecordDecl *PrimaryVirtualBase = nullptr;
927 BaseSubobjectInfo *PrimaryVirtualBaseInfo = nullptr;
928
929 // Check if this base has a primary virtual base.
930 if (RD->getNumVBases()) {
931 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
932 if (Layout.isPrimaryBaseVirtual()) {
933 // This base does have a primary virtual base.
934 PrimaryVirtualBase = Layout.getPrimaryBase();
935 assert(PrimaryVirtualBase && "Didn't have a primary virtual base!");
936
937 // Now check if we have base subobject info about this primary base.
938 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
939
940 if (PrimaryVirtualBaseInfo) {
941 if (PrimaryVirtualBaseInfo->Derived) {
942 // We did have info about this primary base, and it turns out that it
943 // has already been claimed as a primary virtual base for another
944 // base.
945 PrimaryVirtualBase = nullptr;
946 } else {
947 // We can claim this base as our primary base.
948 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
949 PrimaryVirtualBaseInfo->Derived = Info;
950 }
951 }
952 }
953 }
954
955 // Now go through all direct bases.
956 for (const auto &I : RD->bases()) {
957 bool IsVirtual = I.isVirtual();
958
959 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
960
961 Info->Bases.push_back(ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, Info));
962 }
963
964 if (PrimaryVirtualBase && !PrimaryVirtualBaseInfo) {
965 // Traversing the bases must have created the base info for our primary
966 // virtual base.
967 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
968 assert(PrimaryVirtualBaseInfo &&
969 "Did not create a primary virtual base!");
970
971 // Claim the primary virtual base as our primary virtual base.
972 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
973 PrimaryVirtualBaseInfo->Derived = Info;
974 }
975
976 return Info;
977}
978
979void ItaniumRecordLayoutBuilder::ComputeBaseSubobjectInfo(
980 const CXXRecordDecl *RD) {
981 for (const auto &I : RD->bases()) {
982 bool IsVirtual = I.isVirtual();
983
984 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
985
986 // Compute the base subobject info for this base.
987 BaseSubobjectInfo *Info = ComputeBaseSubobjectInfo(BaseDecl, IsVirtual,
988 nullptr);
989
990 if (IsVirtual) {
991 // ComputeBaseInfo has already added this base for us.
992 assert(VirtualBaseInfo.count(BaseDecl) &&
993 "Did not add virtual base!");
994 } else {
995 // Add the base info to the map of non-virtual bases.
996 assert(!NonVirtualBaseInfo.count(BaseDecl) &&
997 "Non-virtual base already exists!");
998 NonVirtualBaseInfo.insert(std::make_pair(BaseDecl, Info));
999 }
1000 }
1001}
1002
1003void ItaniumRecordLayoutBuilder::EnsureVTablePointerAlignment(
1004 CharUnits UnpackedBaseAlign) {
1005 CharUnits BaseAlign = Packed ? CharUnits::One() : UnpackedBaseAlign;
1006
1007 // The maximum field alignment overrides base align.
1008 if (!MaxFieldAlignment.isZero()) {
1009 BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
1010 UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
1011 }
1012
1013 // Round up the current record size to pointer alignment.
1014 setSize(getSize().alignTo(BaseAlign));
1015
1016 // Update the alignment.
1017 UpdateAlignment(BaseAlign, UnpackedBaseAlign, BaseAlign);
1018}
1019
1020void ItaniumRecordLayoutBuilder::LayoutNonVirtualBases(
1021 const CXXRecordDecl *RD) {
1022 // Then, determine the primary base class.
1023 DeterminePrimaryBase(RD);
1024
1025 // Compute base subobject info.
1026 ComputeBaseSubobjectInfo(RD);
1027
1028 // If we have a primary base class, lay it out.
1029 if (PrimaryBase) {
1030 if (PrimaryBaseIsVirtual) {
1031 // If the primary virtual base was a primary virtual base of some other
1032 // base class we'll have to steal it.
1033 BaseSubobjectInfo *PrimaryBaseInfo = VirtualBaseInfo.lookup(PrimaryBase);
1034 PrimaryBaseInfo->Derived = nullptr;
1035
1036 // We have a virtual primary base, insert it as an indirect primary base.
1037 IndirectPrimaryBases.insert(PrimaryBase);
1038
1039 assert(!VisitedVirtualBases.count(PrimaryBase) &&
1040 "vbase already visited!");
1041 VisitedVirtualBases.insert(PrimaryBase);
1042
1043 LayoutVirtualBase(PrimaryBaseInfo);
1044 } else {
1045 BaseSubobjectInfo *PrimaryBaseInfo =
1046 NonVirtualBaseInfo.lookup(PrimaryBase);
1047 assert(PrimaryBaseInfo &&
1048 "Did not find base info for non-virtual primary base!");
1049
1050 LayoutNonVirtualBase(PrimaryBaseInfo);
1051 }
1052
1053 // If this class needs a vtable/vf-table and didn't get one from a
1054 // primary base, add it in now.
1055 } else if (RD->isDynamicClass()) {
1056 assert(DataSize == 0 && "Vtable pointer must be at offset zero!");
1057 CharUnits PtrWidth = Context.toCharUnitsFromBits(
1059 CharUnits PtrAlign = Context.toCharUnitsFromBits(
1061 EnsureVTablePointerAlignment(PtrAlign);
1062 HasOwnVFPtr = true;
1063
1064 assert(!IsUnion && "Unions cannot be dynamic classes.");
1065 HandledFirstNonOverlappingEmptyField = true;
1066
1067 setSize(getSize() + PtrWidth);
1068 setDataSize(getSize());
1069 }
1070
1071 // Now lay out the non-virtual bases.
1072 for (const auto &I : RD->bases()) {
1073
1074 // Ignore virtual bases.
1075 if (I.isVirtual())
1076 continue;
1077
1078 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
1079
1080 // Skip the primary base, because we've already laid it out. The
1081 // !PrimaryBaseIsVirtual check is required because we might have a
1082 // non-virtual base of the same type as a primary virtual base.
1083 if (BaseDecl == PrimaryBase && !PrimaryBaseIsVirtual)
1084 continue;
1085
1086 // Lay out the base.
1087 BaseSubobjectInfo *BaseInfo = NonVirtualBaseInfo.lookup(BaseDecl);
1088 assert(BaseInfo && "Did not find base info for non-virtual base!");
1089
1090 LayoutNonVirtualBase(BaseInfo);
1091 }
1092}
1093
1094void ItaniumRecordLayoutBuilder::LayoutNonVirtualBase(
1095 const BaseSubobjectInfo *Base) {
1096 // Layout the base.
1097 CharUnits Offset = LayoutBase(Base);
1098
1099 // Add its base class offset.
1100 assert(!Bases.count(Base->Class) && "base offset already exists!");
1101 Bases.insert(std::make_pair(Base->Class, Offset));
1102
1103 AddPrimaryVirtualBaseOffsets(Base, Offset);
1104}
1105
1106void ItaniumRecordLayoutBuilder::AddPrimaryVirtualBaseOffsets(
1107 const BaseSubobjectInfo *Info, CharUnits Offset) {
1108 // This base isn't interesting, it has no virtual bases.
1109 if (!Info->Class->getNumVBases())
1110 return;
1111
1112 // First, check if we have a virtual primary base to add offsets for.
1113 if (Info->PrimaryVirtualBaseInfo) {
1114 assert(Info->PrimaryVirtualBaseInfo->IsVirtual &&
1115 "Primary virtual base is not virtual!");
1116 if (Info->PrimaryVirtualBaseInfo->Derived == Info) {
1117 // Add the offset.
1118 assert(!VBases.count(Info->PrimaryVirtualBaseInfo->Class) &&
1119 "primary vbase offset already exists!");
1120 VBases.insert(std::make_pair(Info->PrimaryVirtualBaseInfo->Class,
1121 ASTRecordLayout::VBaseInfo(Offset, false)));
1122
1123 // Traverse the primary virtual base.
1124 AddPrimaryVirtualBaseOffsets(Info->PrimaryVirtualBaseInfo, Offset);
1125 }
1126 }
1127
1128 // Now go through all direct non-virtual bases.
1129 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
1130 for (const BaseSubobjectInfo *Base : Info->Bases) {
1131 if (Base->IsVirtual)
1132 continue;
1133
1134 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
1135 AddPrimaryVirtualBaseOffsets(Base, BaseOffset);
1136 }
1137}
1138
1139void ItaniumRecordLayoutBuilder::LayoutVirtualBases(
1140 const CXXRecordDecl *RD, const CXXRecordDecl *MostDerivedClass) {
1141 const CXXRecordDecl *PrimaryBase;
1142 bool PrimaryBaseIsVirtual;
1143
1144 if (MostDerivedClass == RD) {
1145 PrimaryBase = this->PrimaryBase;
1146 PrimaryBaseIsVirtual = this->PrimaryBaseIsVirtual;
1147 } else {
1148 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1149 PrimaryBase = Layout.getPrimaryBase();
1150 PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
1151 }
1152
1153 for (const CXXBaseSpecifier &Base : RD->bases()) {
1154 assert(!Base.getType()->isDependentType() &&
1155 "Cannot layout class with dependent bases.");
1156
1157 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
1158
1159 if (Base.isVirtual()) {
1160 if (PrimaryBase != BaseDecl || !PrimaryBaseIsVirtual) {
1161 bool IndirectPrimaryBase = IndirectPrimaryBases.count(BaseDecl);
1162
1163 // Only lay out the virtual base if it's not an indirect primary base.
1164 if (!IndirectPrimaryBase) {
1165 // Only visit virtual bases once.
1166 if (!VisitedVirtualBases.insert(BaseDecl).second)
1167 continue;
1168
1169 const BaseSubobjectInfo *BaseInfo = VirtualBaseInfo.lookup(BaseDecl);
1170 assert(BaseInfo && "Did not find virtual base info!");
1171 LayoutVirtualBase(BaseInfo);
1172 }
1173 }
1174 }
1175
1176 if (!BaseDecl->getNumVBases()) {
1177 // This base isn't interesting since it doesn't have any virtual bases.
1178 continue;
1179 }
1180
1181 LayoutVirtualBases(BaseDecl, MostDerivedClass);
1182 }
1183}
1184
1185void ItaniumRecordLayoutBuilder::LayoutVirtualBase(
1186 const BaseSubobjectInfo *Base) {
1187 assert(!Base->Derived && "Trying to lay out a primary virtual base!");
1188
1189 // Layout the base.
1190 CharUnits Offset = LayoutBase(Base);
1191
1192 // Add its base class offset.
1193 assert(!VBases.count(Base->Class) && "vbase offset already exists!");
1194 VBases.insert(std::make_pair(Base->Class,
1195 ASTRecordLayout::VBaseInfo(Offset, false)));
1196
1197 AddPrimaryVirtualBaseOffsets(Base, Offset);
1198}
1199
1201ItaniumRecordLayoutBuilder::LayoutBase(const BaseSubobjectInfo *Base) {
1202 assert(!IsUnion && "Unions cannot have base classes.");
1203
1204 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base->Class);
1205 CharUnits Offset;
1206
1207 // Query the external layout to see if it provides an offset.
1208 bool HasExternalLayout = false;
1209 if (UseExternalLayout) {
1210 if (Base->IsVirtual)
1211 HasExternalLayout = External.getExternalVBaseOffset(Base->Class, Offset);
1212 else
1213 HasExternalLayout = External.getExternalNVBaseOffset(Base->Class, Offset);
1214 }
1215
1216 auto getBaseOrPreferredBaseAlignFromUnpacked = [&](CharUnits UnpackedAlign) {
1217 // Clang <= 6 incorrectly applied the 'packed' attribute to base classes.
1218 // Per GCC's documentation, it only applies to non-static data members.
1219 return (Packed && ((Context.getLangOpts().getClangABICompat() <=
1221 Context.getTargetInfo().getTriple().isPS() ||
1222 Context.getTargetInfo().getTriple().isOSAIX()))
1223 ? CharUnits::One()
1224 : UnpackedAlign;
1225 };
1226
1227 CharUnits UnpackedBaseAlign = Layout.getNonVirtualAlignment();
1228 CharUnits UnpackedPreferredBaseAlign = Layout.getPreferredNVAlignment();
1229 CharUnits BaseAlign =
1230 getBaseOrPreferredBaseAlignFromUnpacked(UnpackedBaseAlign);
1231 CharUnits PreferredBaseAlign =
1232 getBaseOrPreferredBaseAlignFromUnpacked(UnpackedPreferredBaseAlign);
1233
1234 const bool DefaultsToAIXPowerAlignment =
1236 if (DefaultsToAIXPowerAlignment) {
1237 // AIX `power` alignment does not apply the preferred alignment for
1238 // non-union classes if the source of the alignment (the current base in
1239 // this context) follows introduction of the first subobject with
1240 // exclusively allocated space or zero-extent array.
1241 if (!Base->Class->isEmpty() && !HandledFirstNonOverlappingEmptyField) {
1242 // By handling a base class that is not empty, we're handling the
1243 // "first (inherited) member".
1244 HandledFirstNonOverlappingEmptyField = true;
1245 } else if (!IsNaturalAlign) {
1246 UnpackedPreferredBaseAlign = UnpackedBaseAlign;
1247 PreferredBaseAlign = BaseAlign;
1248 }
1249 }
1250
1251 CharUnits UnpackedAlignTo = !DefaultsToAIXPowerAlignment
1252 ? UnpackedBaseAlign
1253 : UnpackedPreferredBaseAlign;
1254 // If we have an empty base class, try to place it at offset 0.
1255 if (Base->Class->isEmpty() &&
1256 (!HasExternalLayout || Offset == CharUnits::Zero()) &&
1257 EmptySubobjects->CanPlaceBaseAtOffset(Base, CharUnits::Zero())) {
1258 setSize(std::max(getSize(), Layout.getSize()));
1259 // On PS4/PS5, don't update the alignment, to preserve compatibility.
1260 if (!Context.getTargetInfo().getTriple().isPS())
1261 UpdateAlignment(BaseAlign, UnpackedAlignTo, PreferredBaseAlign);
1262
1263 return CharUnits::Zero();
1264 }
1265
1266 // The maximum field alignment overrides the base align/(AIX-only) preferred
1267 // base align.
1268 if (!MaxFieldAlignment.isZero()) {
1269 BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
1270 PreferredBaseAlign = std::min(PreferredBaseAlign, MaxFieldAlignment);
1271 UnpackedAlignTo = std::min(UnpackedAlignTo, MaxFieldAlignment);
1272 }
1273
1274 CharUnits AlignTo =
1275 !DefaultsToAIXPowerAlignment ? BaseAlign : PreferredBaseAlign;
1276 if (!HasExternalLayout) {
1277 // Round up the current record size to the base's alignment boundary.
1278 Offset = getDataSize().alignTo(AlignTo);
1279
1280 // Try to place the base.
1281 while (!EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset))
1282 Offset += AlignTo;
1283 } else {
1284 bool Allowed = EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset);
1285 (void)Allowed;
1286 assert(Allowed && "Base subobject externally placed at overlapping offset");
1287
1288 if (InferAlignment && Offset < getDataSize().alignTo(AlignTo)) {
1289 // The externally-supplied base offset is before the base offset we
1290 // computed. Assume that the structure is packed.
1291 Alignment = CharUnits::One();
1292 InferAlignment = false;
1293 }
1294 }
1295
1296 if (!Base->Class->isEmpty()) {
1297 // Update the data size.
1298 setDataSize(Offset + Layout.getNonVirtualSize());
1299
1300 setSize(std::max(getSize(), getDataSize()));
1301 } else
1302 setSize(std::max(getSize(), Offset + Layout.getSize()));
1303
1304 // Remember max struct/class alignment.
1305 UpdateAlignment(BaseAlign, UnpackedAlignTo, PreferredBaseAlign);
1306
1307 return Offset;
1308}
1309
1310void ItaniumRecordLayoutBuilder::InitializeLayout(const Decl *D) {
1311 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
1312 IsUnion = RD->isUnion();
1313 IsMsStruct = RD->isMsStruct(Context);
1314 }
1315
1316 Packed = D->hasAttr<PackedAttr>();
1317
1318 // Honor the default struct packing maximum alignment flag.
1319 if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct) {
1320 MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
1321 }
1322
1323 // mac68k alignment supersedes maximum field alignment and attribute aligned,
1324 // and forces all structures to have 2-byte alignment. The IBM docs on it
1325 // allude to additional (more complicated) semantics, especially with regard
1326 // to bit-fields, but gcc appears not to follow that.
1327 if (D->hasAttr<AlignMac68kAttr>()) {
1328 assert(
1329 !D->hasAttr<AlignNaturalAttr>() &&
1330 "Having both mac68k and natural alignment on a decl is not allowed.");
1331 IsMac68kAlign = true;
1332 MaxFieldAlignment = CharUnits::fromQuantity(2);
1333 Alignment = CharUnits::fromQuantity(2);
1334 PreferredAlignment = CharUnits::fromQuantity(2);
1335 } else {
1336 if (D->hasAttr<AlignNaturalAttr>())
1337 IsNaturalAlign = true;
1338
1339 if (const MaxFieldAlignmentAttr *MFAA = D->getAttr<MaxFieldAlignmentAttr>())
1340 MaxFieldAlignment = Context.toCharUnitsFromBits(MFAA->getAlignment());
1341
1342 if (unsigned MaxAlign = D->getMaxAlignment())
1343 UpdateAlignment(Context.toCharUnitsFromBits(MaxAlign));
1344 }
1345
1346 HandledFirstNonOverlappingEmptyField =
1347 !Context.getTargetInfo().defaultsToAIXPowerAlignment() || IsNaturalAlign;
1348
1349 // If there is an external AST source, ask it for the various offsets.
1350 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
1351 if (ExternalASTSource *Source = Context.getExternalSource()) {
1352 UseExternalLayout = Source->layoutRecordType(
1353 RD, External.Size, External.Align, External.FieldOffsets,
1354 External.BaseOffsets, External.VirtualBaseOffsets);
1355
1356 // Update based on external alignment.
1357 if (UseExternalLayout) {
1358 if (External.Align > 0) {
1359 Alignment = Context.toCharUnitsFromBits(External.Align);
1360 PreferredAlignment = Context.toCharUnitsFromBits(External.Align);
1361 } else {
1362 // The external source didn't have alignment information; infer it.
1363 InferAlignment = true;
1364 }
1365 }
1366 }
1367}
1368
1369void ItaniumRecordLayoutBuilder::Layout(const RecordDecl *D) {
1370 InitializeLayout(D);
1371 LayoutFields(D);
1372
1373 // Finally, round the size of the total struct up to the alignment of the
1374 // struct itself.
1375 FinishLayout(D);
1376}
1377
1378void ItaniumRecordLayoutBuilder::Layout(const CXXRecordDecl *RD) {
1379 InitializeLayout(RD);
1380
1381 // Lay out the vtable and the non-virtual bases.
1382 LayoutNonVirtualBases(RD);
1383
1384 LayoutFields(RD);
1385
1386 NonVirtualSize = Context.toCharUnitsFromBits(
1387 llvm::alignTo(getSizeInBits(), Context.getTargetInfo().getCharAlign()));
1388 NonVirtualAlignment = Alignment;
1389 PreferredNVAlignment = PreferredAlignment;
1390
1391 // Lay out the virtual bases and add the primary virtual base offsets.
1392 LayoutVirtualBases(RD, RD);
1393
1394 // Finally, round the size of the total struct up to the alignment
1395 // of the struct itself.
1396 FinishLayout(RD);
1397
1398#ifndef NDEBUG
1399 // Check that we have base offsets for all bases.
1400 for (const CXXBaseSpecifier &Base : RD->bases()) {
1401 if (Base.isVirtual())
1402 continue;
1403
1404 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
1405
1406 assert(Bases.count(BaseDecl) && "Did not find base offset!");
1407 }
1408
1409 // And all virtual bases.
1410 for (const CXXBaseSpecifier &Base : RD->vbases()) {
1411 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
1412
1413 assert(VBases.count(BaseDecl) && "Did not find base offset!");
1414 }
1415#endif
1416}
1417
1418void ItaniumRecordLayoutBuilder::Layout(const ObjCInterfaceDecl *D) {
1419 if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
1420 const ASTRecordLayout &SL = Context.getASTObjCInterfaceLayout(SD);
1421
1422 UpdateAlignment(SL.getAlignment());
1423
1424 // We start laying out ivars not at the end of the superclass
1425 // structure, but at the next byte following the last field.
1426 setDataSize(SL.getDataSize());
1427 setSize(getDataSize());
1428 }
1429
1430 InitializeLayout(D);
1431 // Layout each ivar sequentially.
1432 for (const ObjCIvarDecl *IVD = D->all_declared_ivar_begin(); IVD;
1433 IVD = IVD->getNextIvar())
1434 LayoutField(IVD, false);
1435
1436 // Finally, round the size of the total struct up to the alignment of the
1437 // struct itself.
1438 FinishLayout(D);
1439}
1440
1441void ItaniumRecordLayoutBuilder::LayoutFields(const RecordDecl *D) {
1442 // Layout each field, for now, just sequentially, respecting alignment. In
1443 // the future, this will need to be tweakable by targets.
1444 bool InsertExtraPadding = D->mayInsertExtraPadding(/*EmitRemark=*/true);
1445 bool HasFlexibleArrayMember = D->hasFlexibleArrayMember();
1446 for (auto I = D->field_begin(), End = D->field_end(); I != End; ++I) {
1447 LayoutField(*I, InsertExtraPadding &&
1448 (std::next(I) != End || !HasFlexibleArrayMember));
1449 }
1450}
1451
1452// Rounds the specified size to have it a multiple of the char size.
1453static uint64_t
1455 const ASTContext &Context) {
1456 uint64_t CharAlignment = Context.getTargetInfo().getCharAlign();
1457 return llvm::alignTo(Size, CharAlignment);
1458}
1459
1460void ItaniumRecordLayoutBuilder::LayoutWideBitField(uint64_t FieldSize,
1461 uint64_t StorageUnitSize,
1462 bool FieldPacked,
1463 const FieldDecl *D) {
1464 assert(Context.getLangOpts().CPlusPlus &&
1465 "Can only have wide bit-fields in C++!");
1466
1467 // Itanium C++ ABI 2.4:
1468 // If sizeof(T)*8 < n, let T' be the largest integral POD type with
1469 // sizeof(T')*8 <= n.
1470
1471 QualType IntegralPODTypes[] = {
1472 Context.UnsignedCharTy, Context.UnsignedShortTy, Context.UnsignedIntTy,
1473 Context.UnsignedLongTy, Context.UnsignedLongLongTy
1474 };
1475
1476 QualType Type;
1477 for (const QualType &QT : IntegralPODTypes) {
1478 uint64_t Size = Context.getTypeSize(QT);
1479
1480 if (Size > FieldSize)
1481 break;
1482
1483 Type = QT;
1484 }
1485 assert(!Type.isNull() && "Did not find a type!");
1486
1487 CharUnits TypeAlign = Context.getTypeAlignInChars(Type);
1488
1489 // We're not going to use any of the unfilled bits in the last byte.
1490 UnfilledBitsInLastUnit = 0;
1491 LastBitfieldStorageUnitSize = 0;
1492
1493 uint64_t FieldOffset;
1494 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
1495
1496 if (IsUnion) {
1497 uint64_t RoundedFieldSize = roundUpSizeToCharAlignment(FieldSize,
1498 Context);
1499 setDataSize(std::max(getDataSizeInBits(), RoundedFieldSize));
1500 FieldOffset = 0;
1501 } else {
1502 // The bitfield is allocated starting at the next offset aligned
1503 // appropriately for T', with length n bits.
1504 FieldOffset = llvm::alignTo(getDataSizeInBits(), Context.toBits(TypeAlign));
1505
1506 uint64_t NewSizeInBits = FieldOffset + FieldSize;
1507
1508 setDataSize(
1509 llvm::alignTo(NewSizeInBits, Context.getTargetInfo().getCharAlign()));
1510 UnfilledBitsInLastUnit = getDataSizeInBits() - NewSizeInBits;
1511 }
1512
1513 // Place this field at the current location.
1514 FieldOffsets.push_back(FieldOffset);
1515
1516 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, FieldOffset,
1517 Context.toBits(TypeAlign), FieldPacked, D);
1518
1519 // Update the size.
1520 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1521
1522 // Remember max struct/class alignment.
1523 UpdateAlignment(TypeAlign);
1524}
1525
1526static bool isAIXLayout(const ASTContext &Context) {
1527 return Context.getTargetInfo().getTriple().getOS() == llvm::Triple::AIX;
1528}
1529
1530void ItaniumRecordLayoutBuilder::LayoutBitField(const FieldDecl *D) {
1531 bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
1532 uint64_t FieldSize = D->getBitWidthValue();
1533 TypeInfo FieldInfo = Context.getTypeInfo(D->getType());
1534 uint64_t StorageUnitSize = FieldInfo.Width;
1535 unsigned FieldAlign = FieldInfo.Align;
1536 bool AlignIsRequired = FieldInfo.isAlignRequired();
1537
1538 // UnfilledBitsInLastUnit is the difference between the end of the
1539 // last allocated bitfield (i.e. the first bit offset available for
1540 // bitfields) and the end of the current data size in bits (i.e. the
1541 // first bit offset available for non-bitfields). The current data
1542 // size in bits is always a multiple of the char size; additionally,
1543 // for ms_struct records it's also a multiple of the
1544 // LastBitfieldStorageUnitSize (if set).
1545
1546 // The struct-layout algorithm is dictated by the platform ABI,
1547 // which in principle could use almost any rules it likes. In
1548 // practice, UNIXy targets tend to inherit the algorithm described
1549 // in the System V generic ABI. The basic bitfield layout rule in
1550 // System V is to place bitfields at the next available bit offset
1551 // where the entire bitfield would fit in an aligned storage unit of
1552 // the declared type; it's okay if an earlier or later non-bitfield
1553 // is allocated in the same storage unit. However, some targets
1554 // (those that !useBitFieldTypeAlignment(), e.g. ARM APCS) don't
1555 // require this storage unit to be aligned, and therefore always put
1556 // the bitfield at the next available bit offset.
1557
1558 // ms_struct basically requests a complete replacement of the
1559 // platform ABI's struct-layout algorithm, with the high-level goal
1560 // of duplicating MSVC's layout. For non-bitfields, this follows
1561 // the standard algorithm. The basic bitfield layout rule is to
1562 // allocate an entire unit of the bitfield's declared type
1563 // (e.g. 'unsigned long'), then parcel it up among successive
1564 // bitfields whose declared types have the same size, making a new
1565 // unit as soon as the last can no longer store the whole value.
1566 // Since it completely replaces the platform ABI's algorithm,
1567 // settings like !useBitFieldTypeAlignment() do not apply.
1568
1569 // A zero-width bitfield forces the use of a new storage unit for
1570 // later bitfields. In general, this occurs by rounding up the
1571 // current size of the struct as if the algorithm were about to
1572 // place a non-bitfield of the field's formal type. Usually this
1573 // does not change the alignment of the struct itself, but it does
1574 // on some targets (those that useZeroLengthBitfieldAlignment(),
1575 // e.g. ARM). In ms_struct layout, zero-width bitfields are
1576 // ignored unless they follow a non-zero-width bitfield.
1577
1578 // A field alignment restriction (e.g. from #pragma pack) or
1579 // specification (e.g. from __attribute__((aligned))) changes the
1580 // formal alignment of the field. For System V, this alters the
1581 // required alignment of the notional storage unit that must contain
1582 // the bitfield. For ms_struct, this only affects the placement of
1583 // new storage units. In both cases, the effect of #pragma pack is
1584 // ignored on zero-width bitfields.
1585
1586 // On System V, a packed field (e.g. from #pragma pack or
1587 // __attribute__((packed))) always uses the next available bit
1588 // offset.
1589
1590 // In an ms_struct struct, the alignment of a fundamental type is
1591 // always equal to its size. This is necessary in order to mimic
1592 // the i386 alignment rules on targets which might not fully align
1593 // all types (e.g. Darwin PPC32, where alignof(long long) == 4).
1594
1595 // First, some simple bookkeeping to perform for ms_struct structs.
1596 if (IsMsStruct) {
1597 // The field alignment for integer types is always the size.
1598 FieldAlign = StorageUnitSize;
1599
1600 // If the previous field was not a bitfield, or was a bitfield
1601 // with a different storage unit size, or if this field doesn't fit into
1602 // the current storage unit, we're done with that storage unit.
1603 if (LastBitfieldStorageUnitSize != StorageUnitSize ||
1604 UnfilledBitsInLastUnit < FieldSize) {
1605 // Also, ignore zero-length bitfields after non-bitfields.
1606 if (!LastBitfieldStorageUnitSize && !FieldSize)
1607 FieldAlign = 1;
1608
1609 UnfilledBitsInLastUnit = 0;
1610 LastBitfieldStorageUnitSize = 0;
1611 }
1612 }
1613
1614 if (isAIXLayout(Context)) {
1615 if (StorageUnitSize < Context.getTypeSize(Context.UnsignedIntTy)) {
1616 // On AIX, [bool, char, short] bitfields have the same alignment
1617 // as [unsigned].
1618 StorageUnitSize = Context.getTypeSize(Context.UnsignedIntTy);
1619 } else if (StorageUnitSize > Context.getTypeSize(Context.UnsignedIntTy) &&
1620 Context.getTargetInfo().getTriple().isArch32Bit() &&
1621 FieldSize <= 32) {
1622 // Under 32-bit compile mode, the bitcontainer is 32 bits if a single
1623 // long long bitfield has length no greater than 32 bits.
1624 StorageUnitSize = 32;
1625
1626 if (!AlignIsRequired)
1627 FieldAlign = 32;
1628 }
1629
1630 if (FieldAlign < StorageUnitSize) {
1631 // The bitfield alignment should always be greater than or equal to
1632 // bitcontainer size.
1633 FieldAlign = StorageUnitSize;
1634 }
1635 }
1636
1637 // If the field is wider than its declared type, it follows
1638 // different rules in all cases, except on AIX.
1639 // On AIX, wide bitfield follows the same rules as normal bitfield.
1640 if (FieldSize > StorageUnitSize && !isAIXLayout(Context)) {
1641 LayoutWideBitField(FieldSize, StorageUnitSize, FieldPacked, D);
1642 return;
1643 }
1644
1645 // Compute the next available bit offset.
1646 uint64_t FieldOffset =
1647 IsUnion ? 0 : (getDataSizeInBits() - UnfilledBitsInLastUnit);
1648
1649 // Handle targets that don't honor bitfield type alignment.
1650 if (!IsMsStruct && !Context.getTargetInfo().useBitFieldTypeAlignment()) {
1651 // Some such targets do honor it on zero-width bitfields.
1652 if (FieldSize == 0 &&
1654 // Some targets don't honor leading zero-width bitfield.
1655 if (!IsUnion && FieldOffset == 0 &&
1657 FieldAlign = 1;
1658 else {
1659 // The alignment to round up to is the max of the field's natural
1660 // alignment and a target-specific fixed value (sometimes zero).
1661 unsigned ZeroLengthBitfieldBoundary =
1663 FieldAlign = std::max(FieldAlign, ZeroLengthBitfieldBoundary);
1664 }
1665 // If that doesn't apply, just ignore the field alignment.
1666 } else {
1667 FieldAlign = 1;
1668 }
1669 }
1670
1671 // Remember the alignment we would have used if the field were not packed.
1672 unsigned UnpackedFieldAlign = FieldAlign;
1673
1674 // Ignore the field alignment if the field is packed unless it has zero-size.
1675 if (!IsMsStruct && FieldPacked && FieldSize != 0)
1676 FieldAlign = 1;
1677
1678 // But, if there's an 'aligned' attribute on the field, honor that.
1679 unsigned ExplicitFieldAlign = D->getMaxAlignment();
1680 if (ExplicitFieldAlign) {
1681 FieldAlign = std::max(FieldAlign, ExplicitFieldAlign);
1682 UnpackedFieldAlign = std::max(UnpackedFieldAlign, ExplicitFieldAlign);
1683 }
1684
1685 // But, if there's a #pragma pack in play, that takes precedent over
1686 // even the 'aligned' attribute, for non-zero-width bitfields.
1687 unsigned MaxFieldAlignmentInBits = Context.toBits(MaxFieldAlignment);
1688 if (!MaxFieldAlignment.isZero() && FieldSize) {
1689 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignmentInBits);
1690 if (FieldPacked)
1691 FieldAlign = UnpackedFieldAlign;
1692 else
1693 FieldAlign = std::min(FieldAlign, MaxFieldAlignmentInBits);
1694 }
1695
1696 // But, ms_struct just ignores all of that in unions, even explicit
1697 // alignment attributes.
1698 if (IsMsStruct && IsUnion) {
1699 FieldAlign = UnpackedFieldAlign = 1;
1700 }
1701
1702 // For purposes of diagnostics, we're going to simultaneously
1703 // compute the field offsets that we would have used if we weren't
1704 // adding any alignment padding or if the field weren't packed.
1705 uint64_t UnpaddedFieldOffset = FieldOffset;
1706 uint64_t UnpackedFieldOffset = FieldOffset;
1707
1708 // Check if we need to add padding to fit the bitfield within an
1709 // allocation unit with the right size and alignment. The rules are
1710 // somewhat different here for ms_struct structs.
1711 if (IsMsStruct) {
1712 // If it's not a zero-width bitfield, and we can fit the bitfield
1713 // into the active storage unit (and we haven't already decided to
1714 // start a new storage unit), just do so, regardless of any other
1715 // other consideration. Otherwise, round up to the right alignment.
1716 if (FieldSize == 0 || FieldSize > UnfilledBitsInLastUnit) {
1717 FieldOffset = llvm::alignTo(FieldOffset, FieldAlign);
1718 UnpackedFieldOffset =
1719 llvm::alignTo(UnpackedFieldOffset, UnpackedFieldAlign);
1720 UnfilledBitsInLastUnit = 0;
1721 }
1722
1723 } else {
1724 // #pragma pack, with any value, suppresses the insertion of padding.
1725 bool AllowPadding = MaxFieldAlignment.isZero();
1726
1727 // Compute the real offset.
1728 if (FieldSize == 0 ||
1729 (AllowPadding &&
1730 (FieldOffset & (FieldAlign - 1)) + FieldSize > StorageUnitSize)) {
1731 FieldOffset = llvm::alignTo(FieldOffset, FieldAlign);
1732 } else if (ExplicitFieldAlign &&
1733 (MaxFieldAlignmentInBits == 0 ||
1734 ExplicitFieldAlign <= MaxFieldAlignmentInBits) &&
1736 // TODO: figure it out what needs to be done on targets that don't honor
1737 // bit-field type alignment like ARM APCS ABI.
1738 FieldOffset = llvm::alignTo(FieldOffset, ExplicitFieldAlign);
1739 }
1740
1741 // Repeat the computation for diagnostic purposes.
1742 if (FieldSize == 0 ||
1743 (AllowPadding &&
1744 (UnpackedFieldOffset & (UnpackedFieldAlign - 1)) + FieldSize >
1745 StorageUnitSize))
1746 UnpackedFieldOffset =
1747 llvm::alignTo(UnpackedFieldOffset, UnpackedFieldAlign);
1748 else if (ExplicitFieldAlign &&
1749 (MaxFieldAlignmentInBits == 0 ||
1750 ExplicitFieldAlign <= MaxFieldAlignmentInBits) &&
1752 UnpackedFieldOffset =
1753 llvm::alignTo(UnpackedFieldOffset, ExplicitFieldAlign);
1754 }
1755
1756 // If we're using external layout, give the external layout a chance
1757 // to override this information.
1758 if (UseExternalLayout)
1759 FieldOffset = updateExternalFieldOffset(D, FieldOffset);
1760
1761 // Okay, place the bitfield at the calculated offset.
1762 FieldOffsets.push_back(FieldOffset);
1763
1764 // Bookkeeping:
1765
1766 // Anonymous members don't affect the overall record alignment,
1767 // except on targets where they do.
1768 if (!IsMsStruct &&
1770 !D->getIdentifier())
1771 FieldAlign = UnpackedFieldAlign = 1;
1772
1773 // On AIX, zero-width bitfields pad out to the natural alignment boundary,
1774 // but do not increase the alignment greater than the MaxFieldAlignment, or 1
1775 // if packed.
1776 if (isAIXLayout(Context) && !FieldSize) {
1777 if (FieldPacked)
1778 FieldAlign = 1;
1779 if (!MaxFieldAlignment.isZero()) {
1780 UnpackedFieldAlign =
1781 std::min(UnpackedFieldAlign, MaxFieldAlignmentInBits);
1782 FieldAlign = std::min(FieldAlign, MaxFieldAlignmentInBits);
1783 }
1784 }
1785
1786 // Diagnose differences in layout due to padding or packing.
1787 if (!UseExternalLayout)
1788 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, UnpackedFieldOffset,
1789 UnpackedFieldAlign, FieldPacked, D);
1790
1791 // Update DataSize to include the last byte containing (part of) the bitfield.
1792
1793 // For unions, this is just a max operation, as usual.
1794 if (IsUnion) {
1795 // For ms_struct, allocate the entire storage unit --- unless this
1796 // is a zero-width bitfield, in which case just use a size of 1.
1797 uint64_t RoundedFieldSize;
1798 if (IsMsStruct) {
1799 RoundedFieldSize = (FieldSize ? StorageUnitSize
1800 : Context.getTargetInfo().getCharWidth());
1801
1802 // Otherwise, allocate just the number of bytes required to store
1803 // the bitfield.
1804 } else {
1805 RoundedFieldSize = roundUpSizeToCharAlignment(FieldSize, Context);
1806 }
1807 setDataSize(std::max(getDataSizeInBits(), RoundedFieldSize));
1808
1809 // For non-zero-width bitfields in ms_struct structs, allocate a new
1810 // storage unit if necessary.
1811 } else if (IsMsStruct && FieldSize) {
1812 // We should have cleared UnfilledBitsInLastUnit in every case
1813 // where we changed storage units.
1814 if (!UnfilledBitsInLastUnit) {
1815 setDataSize(FieldOffset + StorageUnitSize);
1816 UnfilledBitsInLastUnit = StorageUnitSize;
1817 }
1818 UnfilledBitsInLastUnit -= FieldSize;
1819 LastBitfieldStorageUnitSize = StorageUnitSize;
1820
1821 // Otherwise, bump the data size up to include the bitfield,
1822 // including padding up to char alignment, and then remember how
1823 // bits we didn't use.
1824 } else {
1825 uint64_t NewSizeInBits = FieldOffset + FieldSize;
1826 uint64_t CharAlignment = Context.getTargetInfo().getCharAlign();
1827 setDataSize(llvm::alignTo(NewSizeInBits, CharAlignment));
1828 UnfilledBitsInLastUnit = getDataSizeInBits() - NewSizeInBits;
1829
1830 // The only time we can get here for an ms_struct is if this is a
1831 // zero-width bitfield, which doesn't count as anything for the
1832 // purposes of unfilled bits.
1833 LastBitfieldStorageUnitSize = 0;
1834 }
1835
1836 // Update the size.
1837 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1838
1839 // Remember max struct/class alignment.
1840 UnadjustedAlignment =
1841 std::max(UnadjustedAlignment, Context.toCharUnitsFromBits(FieldAlign));
1842 UpdateAlignment(Context.toCharUnitsFromBits(FieldAlign),
1843 Context.toCharUnitsFromBits(UnpackedFieldAlign));
1844}
1845
1846void ItaniumRecordLayoutBuilder::LayoutField(const FieldDecl *D,
1847 bool InsertExtraPadding) {
1848 auto *FieldClass = D->getType()->getAsCXXRecordDecl();
1849 bool IsOverlappingEmptyField =
1850 D->isPotentiallyOverlapping() && FieldClass->isEmpty();
1851
1852 CharUnits FieldOffset =
1853 (IsUnion || IsOverlappingEmptyField) ? CharUnits::Zero() : getDataSize();
1854
1855 const bool DefaultsToAIXPowerAlignment =
1857 bool FoundFirstNonOverlappingEmptyFieldForAIX = false;
1858 if (DefaultsToAIXPowerAlignment && !HandledFirstNonOverlappingEmptyField) {
1859 assert(FieldOffset == CharUnits::Zero() &&
1860 "The first non-overlapping empty field should have been handled.");
1861
1862 if (!IsOverlappingEmptyField) {
1863 FoundFirstNonOverlappingEmptyFieldForAIX = true;
1864
1865 // We're going to handle the "first member" based on
1866 // `FoundFirstNonOverlappingEmptyFieldForAIX` during the current
1867 // invocation of this function; record it as handled for future
1868 // invocations (except for unions, because the current field does not
1869 // represent all "firsts").
1870 HandledFirstNonOverlappingEmptyField = !IsUnion;
1871 }
1872 }
1873
1874 if (D->isBitField()) {
1875 LayoutBitField(D);
1876 return;
1877 }
1878
1879 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
1880 // Reset the unfilled bits.
1881 UnfilledBitsInLastUnit = 0;
1882 LastBitfieldStorageUnitSize = 0;
1883
1884 llvm::Triple Target = Context.getTargetInfo().getTriple();
1885
1887 CharUnits FieldSize;
1888 CharUnits FieldAlign;
1889 // The amount of this class's dsize occupied by the field.
1890 // This is equal to FieldSize unless we're permitted to pack
1891 // into the field's tail padding.
1892 CharUnits EffectiveFieldSize;
1893
1894 auto setDeclInfo = [&](bool IsIncompleteArrayType) {
1895 auto TI = Context.getTypeInfoInChars(D->getType());
1896 FieldAlign = TI.Align;
1897 // Flexible array members don't have any size, but they have to be
1898 // aligned appropriately for their element type.
1899 EffectiveFieldSize = FieldSize =
1900 IsIncompleteArrayType ? CharUnits::Zero() : TI.Width;
1901 AlignRequirement = TI.AlignRequirement;
1902 };
1903
1904 if (D->getType()->isIncompleteArrayType()) {
1905 setDeclInfo(true /* IsIncompleteArrayType */);
1906 } else {
1907 setDeclInfo(false /* IsIncompleteArrayType */);
1908
1909 // A potentially-overlapping field occupies its dsize or nvsize, whichever
1910 // is larger.
1911 if (D->isPotentiallyOverlapping()) {
1912 const ASTRecordLayout &Layout = Context.getASTRecordLayout(FieldClass);
1913 EffectiveFieldSize =
1914 std::max(Layout.getNonVirtualSize(), Layout.getDataSize());
1915 }
1916
1917 if (IsMsStruct) {
1918 // If MS bitfield layout is required, figure out what type is being
1919 // laid out and align the field to the width of that type.
1920
1921 // Resolve all typedefs down to their base type and round up the field
1922 // alignment if necessary.
1923 QualType T = Context.getBaseElementType(D->getType());
1924 if (const BuiltinType *BTy = T->getAs<BuiltinType>()) {
1925 CharUnits TypeSize = Context.getTypeSizeInChars(BTy);
1926
1927 if (!llvm::isPowerOf2_64(TypeSize.getQuantity())) {
1928 assert(
1929 !Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment() &&
1930 "Non PowerOf2 size in MSVC mode");
1931 // Base types with sizes that aren't a power of two don't work
1932 // with the layout rules for MS structs. This isn't an issue in
1933 // MSVC itself since there are no such base data types there.
1934 // On e.g. x86_32 mingw and linux, long double is 12 bytes though.
1935 // Any structs involving that data type obviously can't be ABI
1936 // compatible with MSVC regardless of how it is laid out.
1937
1938 // Since ms_struct can be mass enabled (via a pragma or via the
1939 // -mms-bitfields command line parameter), this can trigger for
1940 // structs that don't actually need MSVC compatibility, so we
1941 // need to be able to sidestep the ms_struct layout for these types.
1942
1943 // Since the combination of -mms-bitfields together with structs
1944 // like max_align_t (which contains a long double) for mingw is
1945 // quite common (and GCC handles it silently), just handle it
1946 // silently there. For other targets that have ms_struct enabled
1947 // (most probably via a pragma or attribute), trigger a diagnostic
1948 // that defaults to an error.
1949 if (!Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
1950 Diag(D->getLocation(), diag::warn_npot_ms_struct);
1951 }
1952 if (TypeSize > FieldAlign &&
1953 llvm::isPowerOf2_64(TypeSize.getQuantity()))
1954 FieldAlign = TypeSize;
1955 }
1956 }
1957 }
1958
1959 bool FieldPacked = (Packed && (!FieldClass || FieldClass->isPOD() ||
1960 FieldClass->hasAttr<PackedAttr>() ||
1961 Context.getLangOpts().getClangABICompat() <=
1963 Target.isPS() || Target.isOSDarwin() ||
1964 Target.isOSAIX())) ||
1965 D->hasAttr<PackedAttr>();
1966
1967 // When used as part of a typedef, or together with a 'packed' attribute, the
1968 // 'aligned' attribute can be used to decrease alignment. In that case, it
1969 // overrides any computed alignment we have, and there is no need to upgrade
1970 // the alignment.
1971 auto alignedAttrCanDecreaseAIXAlignment = [AlignRequirement, FieldPacked] {
1972 // Enum alignment sources can be safely ignored here, because this only
1973 // helps decide whether we need the AIX alignment upgrade, which only
1974 // applies to floating-point types.
1975 return AlignRequirement == AlignRequirementKind::RequiredByTypedef ||
1976 (AlignRequirement == AlignRequirementKind::RequiredByRecord &&
1977 FieldPacked);
1978 };
1979
1980 // The AIX `power` alignment rules apply the natural alignment of the
1981 // "first member" if it is of a floating-point data type (or is an aggregate
1982 // whose recursively "first" member or element is such a type). The alignment
1983 // associated with these types for subsequent members use an alignment value
1984 // where the floating-point data type is considered to have 4-byte alignment.
1985 //
1986 // For the purposes of the foregoing: vtable pointers, non-empty base classes,
1987 // and zero-width bit-fields count as prior members; members of empty class
1988 // types marked `no_unique_address` are not considered to be prior members.
1989 CharUnits PreferredAlign = FieldAlign;
1990 if (DefaultsToAIXPowerAlignment && !alignedAttrCanDecreaseAIXAlignment() &&
1991 (FoundFirstNonOverlappingEmptyFieldForAIX || IsNaturalAlign)) {
1992 auto performBuiltinTypeAlignmentUpgrade = [&](const BuiltinType *BTy) {
1993 if (BTy->getKind() == BuiltinType::Double ||
1994 BTy->getKind() == BuiltinType::LongDouble) {
1995 assert(PreferredAlign == CharUnits::fromQuantity(4) &&
1996 "No need to upgrade the alignment value.");
1997 PreferredAlign = CharUnits::fromQuantity(8);
1998 }
1999 };
2000
2001 const Type *BaseTy = D->getType()->getBaseElementTypeUnsafe();
2002 if (const ComplexType *CTy = BaseTy->getAs<ComplexType>()) {
2003 performBuiltinTypeAlignmentUpgrade(
2004 CTy->getElementType()->castAs<BuiltinType>());
2005 } else if (const BuiltinType *BTy = BaseTy->getAs<BuiltinType>()) {
2006 performBuiltinTypeAlignmentUpgrade(BTy);
2007 } else if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
2008 const RecordDecl *RD = RT->getDecl();
2009 assert(RD && "Expected non-null RecordDecl.");
2010 const ASTRecordLayout &FieldRecord = Context.getASTRecordLayout(RD);
2011 PreferredAlign = FieldRecord.getPreferredAlignment();
2012 }
2013 }
2014
2015 // The align if the field is not packed. This is to check if the attribute
2016 // was unnecessary (-Wpacked).
2017 CharUnits UnpackedFieldAlign = FieldAlign;
2018 CharUnits PackedFieldAlign = CharUnits::One();
2019 CharUnits UnpackedFieldOffset = FieldOffset;
2020 CharUnits OriginalFieldAlign = UnpackedFieldAlign;
2021
2022 CharUnits MaxAlignmentInChars =
2024 PackedFieldAlign = std::max(PackedFieldAlign, MaxAlignmentInChars);
2025 PreferredAlign = std::max(PreferredAlign, MaxAlignmentInChars);
2026 UnpackedFieldAlign = std::max(UnpackedFieldAlign, MaxAlignmentInChars);
2027
2028 // The maximum field alignment overrides the aligned attribute.
2029 if (!MaxFieldAlignment.isZero()) {
2030 PackedFieldAlign = std::min(PackedFieldAlign, MaxFieldAlignment);
2031 PreferredAlign = std::min(PreferredAlign, MaxFieldAlignment);
2032 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignment);
2033 }
2034
2035
2036 if (!FieldPacked)
2037 FieldAlign = UnpackedFieldAlign;
2038 if (DefaultsToAIXPowerAlignment)
2039 UnpackedFieldAlign = PreferredAlign;
2040 if (FieldPacked) {
2041 PreferredAlign = PackedFieldAlign;
2042 FieldAlign = PackedFieldAlign;
2043 }
2044
2045 CharUnits AlignTo =
2046 !DefaultsToAIXPowerAlignment ? FieldAlign : PreferredAlign;
2047 // Round up the current record size to the field's alignment boundary.
2048 FieldOffset = FieldOffset.alignTo(AlignTo);
2049 UnpackedFieldOffset = UnpackedFieldOffset.alignTo(UnpackedFieldAlign);
2050
2051 if (UseExternalLayout) {
2052 FieldOffset = Context.toCharUnitsFromBits(
2053 updateExternalFieldOffset(D, Context.toBits(FieldOffset)));
2054
2055 if (!IsUnion && EmptySubobjects) {
2056 // Record the fact that we're placing a field at this offset.
2057 bool Allowed = EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset);
2058 (void)Allowed;
2059 assert(Allowed && "Externally-placed field cannot be placed here");
2060 }
2061 } else {
2062 if (!IsUnion && EmptySubobjects) {
2063 // Check if we can place the field at this offset.
2064 while (!EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset)) {
2065 // We couldn't place the field at the offset. Try again at a new offset.
2066 // We try offset 0 (for an empty field) and then dsize(C) onwards.
2067 if (FieldOffset == CharUnits::Zero() &&
2068 getDataSize() != CharUnits::Zero())
2069 FieldOffset = getDataSize().alignTo(AlignTo);
2070 else
2071 FieldOffset += AlignTo;
2072 }
2073 }
2074 }
2075
2076 // Place this field at the current location.
2077 FieldOffsets.push_back(Context.toBits(FieldOffset));
2078
2079 if (!UseExternalLayout)
2080 CheckFieldPadding(Context.toBits(FieldOffset), UnpaddedFieldOffset,
2081 Context.toBits(UnpackedFieldOffset),
2082 Context.toBits(UnpackedFieldAlign), FieldPacked, D);
2083
2084 if (InsertExtraPadding) {
2085 CharUnits ASanAlignment = CharUnits::fromQuantity(8);
2086 CharUnits ExtraSizeForAsan = ASanAlignment;
2087 if (FieldSize % ASanAlignment)
2088 ExtraSizeForAsan +=
2089 ASanAlignment - CharUnits::fromQuantity(FieldSize % ASanAlignment);
2090 EffectiveFieldSize = FieldSize = FieldSize + ExtraSizeForAsan;
2091 }
2092
2093 // Reserve space for this field.
2094 if (!IsOverlappingEmptyField) {
2095 uint64_t EffectiveFieldSizeInBits = Context.toBits(EffectiveFieldSize);
2096 if (IsUnion)
2097 setDataSize(std::max(getDataSizeInBits(), EffectiveFieldSizeInBits));
2098 else
2099 setDataSize(FieldOffset + EffectiveFieldSize);
2100
2101 PaddedFieldSize = std::max(PaddedFieldSize, FieldOffset + FieldSize);
2102 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
2103 } else {
2104 setSize(std::max(getSizeInBits(),
2105 (uint64_t)Context.toBits(FieldOffset + FieldSize)));
2106 }
2107
2108 // Remember max struct/class ABI-specified alignment.
2109 UnadjustedAlignment = std::max(UnadjustedAlignment, FieldAlign);
2110 UpdateAlignment(FieldAlign, UnpackedFieldAlign, PreferredAlign);
2111
2112 // For checking the alignment of inner fields against
2113 // the alignment of its parent record.
2114 if (const RecordDecl *RD = D->getParent()) {
2115 // Check if packed attribute or pragma pack is present.
2116 if (RD->hasAttr<PackedAttr>() || !MaxFieldAlignment.isZero())
2117 if (FieldAlign < OriginalFieldAlign)
2118 if (D->getType()->isRecordType()) {
2119 // If the offset is a multiple of the alignment of
2120 // the type, raise the warning.
2121 // TODO: Takes no account the alignment of the outer struct
2122 if (FieldOffset % OriginalFieldAlign != 0)
2123 Diag(D->getLocation(), diag::warn_unaligned_access)
2124 << Context.getTypeDeclType(RD) << D->getName() << D->getType();
2125 }
2126 }
2127
2128 if (Packed && !FieldPacked && PackedFieldAlign < FieldAlign)
2129 Diag(D->getLocation(), diag::warn_unpacked_field) << D;
2130}
2131
2132void ItaniumRecordLayoutBuilder::FinishLayout(const NamedDecl *D) {
2133 // In C++, records cannot be of size 0.
2134 if (Context.getLangOpts().CPlusPlus && getSizeInBits() == 0) {
2135 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
2136 // Compatibility with gcc requires a class (pod or non-pod)
2137 // which is not empty but of size 0; such as having fields of
2138 // array of zero-length, remains of Size 0
2139 if (RD->isEmpty())
2140 setSize(CharUnits::One());
2141 }
2142 else
2143 setSize(CharUnits::One());
2144 }
2145
2146 // If we have any remaining field tail padding, include that in the overall
2147 // size.
2148 setSize(std::max(getSizeInBits(), (uint64_t)Context.toBits(PaddedFieldSize)));
2149
2150 // Finally, round the size of the record up to the alignment of the
2151 // record itself.
2152 uint64_t UnpaddedSize = getSizeInBits() - UnfilledBitsInLastUnit;
2153 uint64_t UnpackedSizeInBits =
2154 llvm::alignTo(getSizeInBits(), Context.toBits(UnpackedAlignment));
2155
2156 uint64_t RoundedSize = llvm::alignTo(
2157 getSizeInBits(),
2159 ? Alignment
2160 : PreferredAlignment));
2161
2162 if (UseExternalLayout) {
2163 // If we're inferring alignment, and the external size is smaller than
2164 // our size after we've rounded up to alignment, conservatively set the
2165 // alignment to 1.
2166 if (InferAlignment && External.Size < RoundedSize) {
2167 Alignment = CharUnits::One();
2168 PreferredAlignment = CharUnits::One();
2169 InferAlignment = false;
2170 }
2171 setSize(External.Size);
2172 return;
2173 }
2174
2175 // Set the size to the final size.
2176 setSize(RoundedSize);
2177
2178 unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
2179 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
2180 // Warn if padding was introduced to the struct/class/union.
2181 if (getSizeInBits() > UnpaddedSize) {
2182 unsigned PadSize = getSizeInBits() - UnpaddedSize;
2183 bool InBits = true;
2184 if (PadSize % CharBitNum == 0) {
2185 PadSize = PadSize / CharBitNum;
2186 InBits = false;
2187 }
2188 Diag(RD->getLocation(), diag::warn_padded_struct_size)
2189 << Context.getTypeDeclType(RD)
2190 << PadSize
2191 << (InBits ? 1 : 0); // (byte|bit)
2192 }
2193
2194 const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
2195
2196 // Warn if we packed it unnecessarily, when the unpacked alignment is not
2197 // greater than the one after packing, the size in bits doesn't change and
2198 // the offset of each field is identical.
2199 // Unless the type is non-POD (for Clang ABI > 15), where the packed
2200 // attribute on such a type does allow the type to be packed into other
2201 // structures that use the packed attribute.
2202 if (Packed && UnpackedAlignment <= Alignment &&
2203 UnpackedSizeInBits == getSizeInBits() && !HasPackedField &&
2204 (!CXXRD || CXXRD->isPOD() ||
2205 Context.getLangOpts().getClangABICompat() <=
2207 Diag(D->getLocation(), diag::warn_unnecessary_packed)
2208 << Context.getTypeDeclType(RD);
2209 }
2210}
2211
2212void ItaniumRecordLayoutBuilder::UpdateAlignment(
2213 CharUnits NewAlignment, CharUnits UnpackedNewAlignment,
2214 CharUnits PreferredNewAlignment) {
2215 // The alignment is not modified when using 'mac68k' alignment or when
2216 // we have an externally-supplied layout that also provides overall alignment.
2217 if (IsMac68kAlign || (UseExternalLayout && !InferAlignment))
2218 return;
2219
2220 if (NewAlignment > Alignment) {
2221 assert(llvm::isPowerOf2_64(NewAlignment.getQuantity()) &&
2222 "Alignment not a power of 2");
2223 Alignment = NewAlignment;
2224 }
2225
2226 if (UnpackedNewAlignment > UnpackedAlignment) {
2227 assert(llvm::isPowerOf2_64(UnpackedNewAlignment.getQuantity()) &&
2228 "Alignment not a power of 2");
2229 UnpackedAlignment = UnpackedNewAlignment;
2230 }
2231
2232 if (PreferredNewAlignment > PreferredAlignment) {
2233 assert(llvm::isPowerOf2_64(PreferredNewAlignment.getQuantity()) &&
2234 "Alignment not a power of 2");
2235 PreferredAlignment = PreferredNewAlignment;
2236 }
2237}
2238
2240ItaniumRecordLayoutBuilder::updateExternalFieldOffset(const FieldDecl *Field,
2241 uint64_t ComputedOffset) {
2242 uint64_t ExternalFieldOffset = External.getExternalFieldOffset(Field);
2243
2244 if (InferAlignment && ExternalFieldOffset < ComputedOffset) {
2245 // The externally-supplied field offset is before the field offset we
2246 // computed. Assume that the structure is packed.
2247 Alignment = CharUnits::One();
2248 PreferredAlignment = CharUnits::One();
2249 InferAlignment = false;
2250 }
2251
2252 // Use the externally-supplied field offset.
2253 return ExternalFieldOffset;
2254}
2255
2256/// Get diagnostic %select index for tag kind for
2257/// field padding diagnostic message.
2258/// WARNING: Indexes apply to particular diagnostics only!
2259///
2260/// \returns diagnostic %select index.
2262 switch (Tag) {
2264 return 0;
2266 return 1;
2267 case TagTypeKind::Class:
2268 return 2;
2269 default: llvm_unreachable("Invalid tag kind for field padding diagnostic!");
2270 }
2271}
2272
2273void ItaniumRecordLayoutBuilder::CheckFieldPadding(
2274 uint64_t Offset, uint64_t UnpaddedOffset, uint64_t UnpackedOffset,
2275 unsigned UnpackedAlign, bool isPacked, const FieldDecl *D) {
2276 // We let objc ivars without warning, objc interfaces generally are not used
2277 // for padding tricks.
2278 if (isa<ObjCIvarDecl>(D))
2279 return;
2280
2281 // Don't warn about structs created without a SourceLocation. This can
2282 // be done by clients of the AST, such as codegen.
2283 if (D->getLocation().isInvalid())
2284 return;
2285
2286 unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
2287
2288 // Warn if padding was introduced to the struct/class.
2289 if (!IsUnion && Offset > UnpaddedOffset) {
2290 unsigned PadSize = Offset - UnpaddedOffset;
2291 bool InBits = true;
2292 if (PadSize % CharBitNum == 0) {
2293 PadSize = PadSize / CharBitNum;
2294 InBits = false;
2295 }
2296 if (D->getIdentifier()) {
2297 auto Diagnostic = D->isBitField() ? diag::warn_padded_struct_bitfield
2298 : diag::warn_padded_struct_field;
2300 << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
2301 << Context.getTypeDeclType(D->getParent()) << PadSize
2302 << (InBits ? 1 : 0) // (byte|bit)
2303 << D->getIdentifier();
2304 } else {
2305 auto Diagnostic = D->isBitField() ? diag::warn_padded_struct_anon_bitfield
2306 : diag::warn_padded_struct_anon_field;
2308 << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
2309 << Context.getTypeDeclType(D->getParent()) << PadSize
2310 << (InBits ? 1 : 0); // (byte|bit)
2311 }
2312 }
2313 if (isPacked && Offset != UnpackedOffset) {
2314 HasPackedField = true;
2315 }
2316}
2317
2319 const CXXRecordDecl *RD) {
2320 // If a class isn't polymorphic it doesn't have a key function.
2321 if (!RD->isPolymorphic())
2322 return nullptr;
2323
2324 // A class that is not externally visible doesn't have a key function. (Or
2325 // at least, there's no point to assigning a key function to such a class;
2326 // this doesn't affect the ABI.)
2327 if (!RD->isExternallyVisible())
2328 return nullptr;
2329
2330 // Template instantiations don't have key functions per Itanium C++ ABI 5.2.6.
2331 // Same behavior as GCC.
2333 if (TSK == TSK_ImplicitInstantiation ||
2336 return nullptr;
2337
2338 bool allowInlineFunctions =
2340
2341 for (const CXXMethodDecl *MD : RD->methods()) {
2342 if (!MD->isVirtual())
2343 continue;
2344
2345 if (MD->isPureVirtual())
2346 continue;
2347
2348 // Ignore implicit member functions, they are always marked as inline, but
2349 // they don't have a body until they're defined.
2350 if (MD->isImplicit())
2351 continue;
2352
2353 if (MD->isInlineSpecified() || MD->isConstexpr())
2354 continue;
2355
2356 if (MD->hasInlineBody())
2357 continue;
2358
2359 // Ignore inline deleted or defaulted functions.
2360 if (!MD->isUserProvided())
2361 continue;
2362
2363 // In certain ABIs, ignore functions with out-of-line inline definitions.
2364 if (!allowInlineFunctions) {
2365 const FunctionDecl *Def;
2366 if (MD->hasBody(Def) && Def->isInlineSpecified())
2367 continue;
2368 }
2369
2370 if (Context.getLangOpts().CUDA) {
2371 // While compiler may see key method in this TU, during CUDA
2372 // compilation we should ignore methods that are not accessible
2373 // on this side of compilation.
2374 if (Context.getLangOpts().CUDAIsDevice) {
2375 // In device mode ignore methods without __device__ attribute.
2376 if (!MD->hasAttr<CUDADeviceAttr>())
2377 continue;
2378 } else {
2379 // In host mode ignore __device__-only methods.
2380 if (!MD->hasAttr<CUDAHostAttr>() && MD->hasAttr<CUDADeviceAttr>())
2381 continue;
2382 }
2383 }
2384
2385 // If the key function is dllimport but the class isn't, then the class has
2386 // no key function. The DLL that exports the key function won't export the
2387 // vtable in this case.
2388 if (MD->hasAttr<DLLImportAttr>() && !RD->hasAttr<DLLImportAttr>() &&
2390 return nullptr;
2391
2392 // We found it.
2393 return MD;
2394 }
2395
2396 return nullptr;
2397}
2398
2399DiagnosticBuilder ItaniumRecordLayoutBuilder::Diag(SourceLocation Loc,
2400 unsigned DiagID) {
2401 return Context.getDiagnostics().Report(Loc, DiagID);
2402}
2403
2404/// Does the target C++ ABI require us to skip over the tail-padding
2405/// of the given class (considering it as a base class) when allocating
2406/// objects?
2408 switch (ABI.getTailPaddingUseRules()) {
2410 return false;
2411
2413 // FIXME: To the extent that this is meant to cover the Itanium ABI
2414 // rules, we should implement the restrictions about over-sized
2415 // bitfields:
2416 //
2417 // http://itanium-cxx-abi.github.io/cxx-abi/abi.html#POD :
2418 // In general, a type is considered a POD for the purposes of
2419 // layout if it is a POD type (in the sense of ISO C++
2420 // [basic.types]). However, a POD-struct or POD-union (in the
2421 // sense of ISO C++ [class]) with a bitfield member whose
2422 // declared width is wider than the declared type of the
2423 // bitfield is not a POD for the purpose of layout. Similarly,
2424 // an array type is not a POD for the purpose of layout if the
2425 // element type of the array is not a POD for the purpose of
2426 // layout.
2427 //
2428 // Where references to the ISO C++ are made in this paragraph,
2429 // the Technical Corrigendum 1 version of the standard is
2430 // intended.
2431 return RD->isPOD();
2432
2434 // This is equivalent to RD->getTypeForDecl().isCXX11PODType(),
2435 // but with a lot of abstraction penalty stripped off. This does
2436 // assume that these properties are set correctly even in C++98
2437 // mode; fortunately, that is true because we want to assign
2438 // consistently semantics to the type-traits intrinsics (or at
2439 // least as many of them as possible).
2440 return RD->isTrivial() && RD->isCXX11StandardLayout();
2441 }
2442
2443 llvm_unreachable("bad tail-padding use kind");
2444}
2445
2446static bool isMsLayout(const ASTContext &Context) {
2447 // Check if it's CUDA device compilation; ensure layout consistency with host.
2448 if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
2449 Context.getAuxTargetInfo())
2450 return Context.getAuxTargetInfo()->getCXXABI().isMicrosoft();
2451
2452 return Context.getTargetInfo().getCXXABI().isMicrosoft();
2453}
2454
2455// This section contains an implementation of struct layout that is, up to the
2456// included tests, compatible with cl.exe (2013). The layout produced is
2457// significantly different than those produced by the Itanium ABI. Here we note
2458// the most important differences.
2459//
2460// * The alignment of bitfields in unions is ignored when computing the
2461// alignment of the union.
2462// * The existence of zero-width bitfield that occurs after anything other than
2463// a non-zero length bitfield is ignored.
2464// * There is no explicit primary base for the purposes of layout. All bases
2465// with vfptrs are laid out first, followed by all bases without vfptrs.
2466// * The Itanium equivalent vtable pointers are split into a vfptr (virtual
2467// function pointer) and a vbptr (virtual base pointer). They can each be
2468// shared with a, non-virtual bases. These bases need not be the same. vfptrs
2469// always occur at offset 0. vbptrs can occur at an arbitrary offset and are
2470// placed after the lexicographically last non-virtual base. This placement
2471// is always before fields but can be in the middle of the non-virtual bases
2472// due to the two-pass layout scheme for non-virtual-bases.
2473// * Virtual bases sometimes require a 'vtordisp' field that is laid out before
2474// the virtual base and is used in conjunction with virtual overrides during
2475// construction and destruction. This is always a 4 byte value and is used as
2476// an alternative to constructor vtables.
2477// * vtordisps are allocated in a block of memory with size and alignment equal
2478// to the alignment of the completed structure (before applying __declspec(
2479// align())). The vtordisp always occur at the end of the allocation block,
2480// immediately prior to the virtual base.
2481// * vfptrs are injected after all bases and fields have been laid out. In
2482// order to guarantee proper alignment of all fields, the vfptr injection
2483// pushes all bases and fields back by the alignment imposed by those bases
2484// and fields. This can potentially add a significant amount of padding.
2485// vfptrs are always injected at offset 0.
2486// * vbptrs are injected after all bases and fields have been laid out. In
2487// order to guarantee proper alignment of all fields, the vfptr injection
2488// pushes all bases and fields back by the alignment imposed by those bases
2489// and fields. This can potentially add a significant amount of padding.
2490// vbptrs are injected immediately after the last non-virtual base as
2491// lexicographically ordered in the code. If this site isn't pointer aligned
2492// the vbptr is placed at the next properly aligned location. Enough padding
2493// is added to guarantee a fit.
2494// * The last zero sized non-virtual base can be placed at the end of the
2495// struct (potentially aliasing another object), or may alias with the first
2496// field, even if they are of the same type.
2497// * The last zero size virtual base may be placed at the end of the struct
2498// potentially aliasing another object.
2499// * The ABI attempts to avoid aliasing of zero sized bases by adding padding
2500// between bases or vbases with specific properties. The criteria for
2501// additional padding between two bases is that the first base is zero sized
2502// or ends with a zero sized subobject and the second base is zero sized or
2503// trails with a zero sized base or field (sharing of vfptrs can reorder the
2504// layout of the so the leading base is not always the first one declared).
2505// This rule does take into account fields that are not records, so padding
2506// will occur even if the last field is, e.g. an int. The padding added for
2507// bases is 1 byte. The padding added between vbases depends on the alignment
2508// of the object but is at least 4 bytes (in both 32 and 64 bit modes).
2509// * There is no concept of non-virtual alignment, non-virtual alignment and
2510// alignment are always identical.
2511// * There is a distinction between alignment and required alignment.
2512// __declspec(align) changes the required alignment of a struct. This
2513// alignment is _always_ obeyed, even in the presence of #pragma pack. A
2514// record inherits required alignment from all of its fields and bases.
2515// * __declspec(align) on bitfields has the effect of changing the bitfield's
2516// alignment instead of its required alignment. This is the only known way
2517// to make the alignment of a struct bigger than 8. Interestingly enough
2518// this alignment is also immune to the effects of #pragma pack and can be
2519// used to create structures with large alignment under #pragma pack.
2520// However, because it does not impact required alignment, such a structure,
2521// when used as a field or base, will not be aligned if #pragma pack is
2522// still active at the time of use.
2523//
2524// Known incompatibilities:
2525// * all: #pragma pack between fields in a record
2526// * 2010 and back: If the last field in a record is a bitfield, every object
2527// laid out after the record will have extra padding inserted before it. The
2528// extra padding will have size equal to the size of the storage class of the
2529// bitfield. 0 sized bitfields don't exhibit this behavior and the extra
2530// padding can be avoided by adding a 0 sized bitfield after the non-zero-
2531// sized bitfield.
2532// * 2012 and back: In 64-bit mode, if the alignment of a record is 16 or
2533// greater due to __declspec(align()) then a second layout phase occurs after
2534// The locations of the vf and vb pointers are known. This layout phase
2535// suffers from the "last field is a bitfield" bug in 2010 and results in
2536// _every_ field getting padding put in front of it, potentially including the
2537// vfptr, leaving the vfprt at a non-zero location which results in a fault if
2538// anything tries to read the vftbl. The second layout phase also treats
2539// bitfields as separate entities and gives them each storage rather than
2540// packing them. Additionally, because this phase appears to perform a
2541// (an unstable) sort on the members before laying them out and because merged
2542// bitfields have the same address, the bitfields end up in whatever order
2543// the sort left them in, a behavior we could never hope to replicate.
2544
2545namespace {
2546struct MicrosoftRecordLayoutBuilder {
2547 struct ElementInfo {
2549 CharUnits Alignment;
2550 };
2551 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
2552 MicrosoftRecordLayoutBuilder(const ASTContext &Context,
2553 EmptySubobjectMap *EmptySubobjects)
2554 : Context(Context), EmptySubobjects(EmptySubobjects) {}
2555
2556private:
2557 MicrosoftRecordLayoutBuilder(const MicrosoftRecordLayoutBuilder &) = delete;
2558 void operator=(const MicrosoftRecordLayoutBuilder &) = delete;
2559public:
2560 void layout(const RecordDecl *RD);
2561 void cxxLayout(const CXXRecordDecl *RD);
2562 /// Initializes size and alignment and honors some flags.
2563 void initializeLayout(const RecordDecl *RD);
2564 /// Initialized C++ layout, compute alignment and virtual alignment and
2565 /// existence of vfptrs and vbptrs. Alignment is needed before the vfptr is
2566 /// laid out.
2567 void initializeCXXLayout(const CXXRecordDecl *RD);
2568 void layoutNonVirtualBases(const CXXRecordDecl *RD);
2569 void layoutNonVirtualBase(const CXXRecordDecl *RD,
2570 const CXXRecordDecl *BaseDecl,
2571 const ASTRecordLayout &BaseLayout,
2572 const ASTRecordLayout *&PreviousBaseLayout);
2573 void injectVFPtr(const CXXRecordDecl *RD);
2574 void injectVBPtr(const CXXRecordDecl *RD);
2575 /// Lays out the fields of the record. Also rounds size up to
2576 /// alignment.
2577 void layoutFields(const RecordDecl *RD);
2578 void layoutField(const FieldDecl *FD);
2579 void layoutBitField(const FieldDecl *FD);
2580 /// Lays out a single zero-width bit-field in the record and handles
2581 /// special cases associated with zero-width bit-fields.
2582 void layoutZeroWidthBitField(const FieldDecl *FD);
2583 void layoutVirtualBases(const CXXRecordDecl *RD);
2584 void finalizeLayout(const RecordDecl *RD);
2585 /// Gets the size and alignment of a base taking pragma pack and
2586 /// __declspec(align) into account.
2587 ElementInfo getAdjustedElementInfo(const ASTRecordLayout &Layout);
2588 /// Gets the size and alignment of a field taking pragma pack and
2589 /// __declspec(align) into account. It also updates RequiredAlignment as a
2590 /// side effect because it is most convenient to do so here.
2591 ElementInfo getAdjustedElementInfo(const FieldDecl *FD);
2592 /// Places a field at an offset in CharUnits.
2593 void placeFieldAtOffset(CharUnits FieldOffset) {
2594 FieldOffsets.push_back(Context.toBits(FieldOffset));
2595 }
2596 /// Places a bitfield at a bit offset.
2597 void placeFieldAtBitOffset(uint64_t FieldOffset) {
2598 FieldOffsets.push_back(FieldOffset);
2599 }
2600 /// Compute the set of virtual bases for which vtordisps are required.
2601 void computeVtorDispSet(
2602 llvm::SmallPtrSetImpl<const CXXRecordDecl *> &HasVtorDispSet,
2603 const CXXRecordDecl *RD) const;
2604 const ASTContext &Context;
2605 EmptySubobjectMap *EmptySubobjects;
2606
2607 /// The size of the record being laid out.
2609 /// The non-virtual size of the record layout.
2610 CharUnits NonVirtualSize;
2611 /// The data size of the record layout.
2612 CharUnits DataSize;
2613 /// The current alignment of the record layout.
2614 CharUnits Alignment;
2615 /// The maximum allowed field alignment. This is set by #pragma pack.
2616 CharUnits MaxFieldAlignment;
2617 /// The alignment that this record must obey. This is imposed by
2618 /// __declspec(align()) on the record itself or one of its fields or bases.
2619 CharUnits RequiredAlignment;
2620 /// The size of the allocation of the currently active bitfield.
2621 /// This value isn't meaningful unless LastFieldIsNonZeroWidthBitfield
2622 /// is true.
2623 CharUnits CurrentBitfieldSize;
2624 /// Offset to the virtual base table pointer (if one exists).
2625 CharUnits VBPtrOffset;
2626 /// Minimum record size possible.
2627 CharUnits MinEmptyStructSize;
2628 /// The size and alignment info of a pointer.
2629 ElementInfo PointerInfo;
2630 /// The primary base class (if one exists).
2631 const CXXRecordDecl *PrimaryBase;
2632 /// The class we share our vb-pointer with.
2633 const CXXRecordDecl *SharedVBPtrBase;
2634 /// The collection of field offsets.
2635 SmallVector<uint64_t, 16> FieldOffsets;
2636 /// Base classes and their offsets in the record.
2637 BaseOffsetsMapTy Bases;
2638 /// virtual base classes and their offsets in the record.
2640 /// The number of remaining bits in our last bitfield allocation.
2641 /// This value isn't meaningful unless LastFieldIsNonZeroWidthBitfield is
2642 /// true.
2643 unsigned RemainingBitsInField;
2644 bool IsUnion : 1;
2645 /// True if the last field laid out was a bitfield and was not 0
2646 /// width.
2647 bool LastFieldIsNonZeroWidthBitfield : 1;
2648 /// True if the class has its own vftable pointer.
2649 bool HasOwnVFPtr : 1;
2650 /// True if the class has a vbtable pointer.
2651 bool HasVBPtr : 1;
2652 /// True if the last sub-object within the type is zero sized or the
2653 /// object itself is zero sized. This *does not* count members that are not
2654 /// records. Only used for MS-ABI.
2655 bool EndsWithZeroSizedObject : 1;
2656 /// True if this class is zero sized or first base is zero sized or
2657 /// has this property. Only used for MS-ABI.
2658 bool LeadsWithZeroSizedBase : 1;
2659
2660 /// True if the external AST source provided a layout for this record.
2661 bool UseExternalLayout : 1;
2662
2663 /// The layout provided by the external AST source. Only active if
2664 /// UseExternalLayout is true.
2665 ExternalLayout External;
2666};
2667} // namespace
2668
2669MicrosoftRecordLayoutBuilder::ElementInfo
2670MicrosoftRecordLayoutBuilder::getAdjustedElementInfo(
2671 const ASTRecordLayout &Layout) {
2672 ElementInfo Info;
2673 Info.Alignment = Layout.getAlignment();
2674 // Respect pragma pack.
2675 if (!MaxFieldAlignment.isZero())
2676 Info.Alignment = std::min(Info.Alignment, MaxFieldAlignment);
2677 // Track zero-sized subobjects here where it's already available.
2678 EndsWithZeroSizedObject = Layout.endsWithZeroSizedObject();
2679 // Respect required alignment, this is necessary because we may have adjusted
2680 // the alignment in the case of pragma pack. Note that the required alignment
2681 // doesn't actually apply to the struct alignment at this point.
2682 Alignment = std::max(Alignment, Info.Alignment);
2683 RequiredAlignment = std::max(RequiredAlignment, Layout.getRequiredAlignment());
2684 Info.Alignment = std::max(Info.Alignment, Layout.getRequiredAlignment());
2685 Info.Size = Layout.getNonVirtualSize();
2686 return Info;
2687}
2688
2689MicrosoftRecordLayoutBuilder::ElementInfo
2690MicrosoftRecordLayoutBuilder::getAdjustedElementInfo(
2691 const FieldDecl *FD) {
2692 // Get the alignment of the field type's natural alignment, ignore any
2693 // alignment attributes.
2694 auto TInfo =
2696 ElementInfo Info{TInfo.Width, TInfo.Align};
2697 // Respect align attributes on the field.
2698 CharUnits FieldRequiredAlignment =
2699 Context.toCharUnitsFromBits(FD->getMaxAlignment());
2700 // Respect align attributes on the type.
2701 if (Context.isAlignmentRequired(FD->getType()))
2702 FieldRequiredAlignment = std::max(
2703 Context.getTypeAlignInChars(FD->getType()), FieldRequiredAlignment);
2704 // Respect attributes applied to subobjects of the field.
2705 if (FD->isBitField())
2706 // For some reason __declspec align impacts alignment rather than required
2707 // alignment when it is applied to bitfields.
2708 Info.Alignment = std::max(Info.Alignment, FieldRequiredAlignment);
2709 else {
2710 if (auto RT =
2712 auto const &Layout = Context.getASTRecordLayout(RT->getDecl());
2713 EndsWithZeroSizedObject = Layout.endsWithZeroSizedObject();
2714 FieldRequiredAlignment = std::max(FieldRequiredAlignment,
2715 Layout.getRequiredAlignment());
2716 }
2717 // Capture required alignment as a side-effect.
2718 RequiredAlignment = std::max(RequiredAlignment, FieldRequiredAlignment);
2719 }
2720 // Respect pragma pack, attribute pack and declspec align
2721 if (!MaxFieldAlignment.isZero())
2722 Info.Alignment = std::min(Info.Alignment, MaxFieldAlignment);
2723 if (FD->hasAttr<PackedAttr>())
2724 Info.Alignment = CharUnits::One();
2725 Info.Alignment = std::max(Info.Alignment, FieldRequiredAlignment);
2726 return Info;
2727}
2728
2729void MicrosoftRecordLayoutBuilder::layout(const RecordDecl *RD) {
2730 // For C record layout, zero-sized records always have size 4.
2731 MinEmptyStructSize = CharUnits::fromQuantity(4);
2732 initializeLayout(RD);
2733 layoutFields(RD);
2734 DataSize = Size = Size.alignTo(Alignment);
2735 RequiredAlignment = std::max(
2736 RequiredAlignment, Context.toCharUnitsFromBits(RD->getMaxAlignment()));
2737 finalizeLayout(RD);
2738}
2739
2740void MicrosoftRecordLayoutBuilder::cxxLayout(const CXXRecordDecl *RD) {
2741 // The C++ standard says that empty structs have size 1.
2742 MinEmptyStructSize = CharUnits::One();
2743 initializeLayout(RD);
2744 initializeCXXLayout(RD);
2745 layoutNonVirtualBases(RD);
2746 layoutFields(RD);
2747 injectVBPtr(RD);
2748 injectVFPtr(RD);
2749 if (HasOwnVFPtr || (HasVBPtr && !SharedVBPtrBase))
2750 Alignment = std::max(Alignment, PointerInfo.Alignment);
2751 auto RoundingAlignment = Alignment;
2752 if (!MaxFieldAlignment.isZero())
2753 RoundingAlignment = std::min(RoundingAlignment, MaxFieldAlignment);
2754 if (!UseExternalLayout)
2755 Size = Size.alignTo(RoundingAlignment);
2756 NonVirtualSize = Size;
2757 RequiredAlignment = std::max(
2758 RequiredAlignment, Context.toCharUnitsFromBits(RD->getMaxAlignment()));
2759 layoutVirtualBases(RD);
2760 finalizeLayout(RD);
2761}
2762
2763void MicrosoftRecordLayoutBuilder::initializeLayout(const RecordDecl *RD) {
2764 IsUnion = RD->isUnion();
2766 Alignment = CharUnits::One();
2767 // In 64-bit mode we always perform an alignment step after laying out vbases.
2768 // In 32-bit mode we do not. The check to see if we need to perform alignment
2769 // checks the RequiredAlignment field and performs alignment if it isn't 0.
2770 RequiredAlignment = Context.getTargetInfo().getTriple().isArch64Bit()
2771 ? CharUnits::One()
2772 : CharUnits::Zero();
2773 // Compute the maximum field alignment.
2774 MaxFieldAlignment = CharUnits::Zero();
2775 // Honor the default struct packing maximum alignment flag.
2776 if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct)
2777 MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
2778 // Honor the packing attribute. The MS-ABI ignores pragma pack if its larger
2779 // than the pointer size.
2780 if (const MaxFieldAlignmentAttr *MFAA = RD->getAttr<MaxFieldAlignmentAttr>()){
2781 unsigned PackedAlignment = MFAA->getAlignment();
2782 if (PackedAlignment <=
2783 Context.getTargetInfo().getPointerWidth(LangAS::Default))
2784 MaxFieldAlignment = Context.toCharUnitsFromBits(PackedAlignment);
2785 }
2786 // Packed attribute forces max field alignment to be 1.
2787 if (RD->hasAttr<PackedAttr>())
2788 MaxFieldAlignment = CharUnits::One();
2789
2790 // Try to respect the external layout if present.
2791 UseExternalLayout = false;
2792 if (ExternalASTSource *Source = Context.getExternalSource())
2793 UseExternalLayout = Source->layoutRecordType(
2794 RD, External.Size, External.Align, External.FieldOffsets,
2795 External.BaseOffsets, External.VirtualBaseOffsets);
2796}
2797
2798void
2799MicrosoftRecordLayoutBuilder::initializeCXXLayout(const CXXRecordDecl *RD) {
2800 EndsWithZeroSizedObject = false;
2801 LeadsWithZeroSizedBase = false;
2802 HasOwnVFPtr = false;
2803 HasVBPtr = false;
2804 PrimaryBase = nullptr;
2805 SharedVBPtrBase = nullptr;
2806 // Calculate pointer size and alignment. These are used for vfptr and vbprt
2807 // injection.
2808 PointerInfo.Size = Context.toCharUnitsFromBits(
2809 Context.getTargetInfo().getPointerWidth(LangAS::Default));
2810 PointerInfo.Alignment = Context.toCharUnitsFromBits(
2811 Context.getTargetInfo().getPointerAlign(LangAS::Default));
2812 // Respect pragma pack.
2813 if (!MaxFieldAlignment.isZero())
2814 PointerInfo.Alignment = std::min(PointerInfo.Alignment, MaxFieldAlignment);
2815}
2816
2817void
2818MicrosoftRecordLayoutBuilder::layoutNonVirtualBases(const CXXRecordDecl *RD) {
2819 // The MS-ABI lays out all bases that contain leading vfptrs before it lays
2820 // out any bases that do not contain vfptrs. We implement this as two passes
2821 // over the bases. This approach guarantees that the primary base is laid out
2822 // first. We use these passes to calculate some additional aggregated
2823 // information about the bases, such as required alignment and the presence of
2824 // zero sized members.
2825 const ASTRecordLayout *PreviousBaseLayout = nullptr;
2826 bool HasPolymorphicBaseClass = false;
2827 // Iterate through the bases and lay out the non-virtual ones.
2828 for (const CXXBaseSpecifier &Base : RD->bases()) {
2829 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
2830 HasPolymorphicBaseClass |= BaseDecl->isPolymorphic();
2831 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
2832 // Mark and skip virtual bases.
2833 if (Base.isVirtual()) {
2834 HasVBPtr = true;
2835 continue;
2836 }
2837 // Check for a base to share a VBPtr with.
2838 if (!SharedVBPtrBase && BaseLayout.hasVBPtr()) {
2839 SharedVBPtrBase = BaseDecl;
2840 HasVBPtr = true;
2841 }
2842 // Only lay out bases with extendable VFPtrs on the first pass.
2843 if (!BaseLayout.hasExtendableVFPtr())
2844 continue;
2845 // If we don't have a primary base, this one qualifies.
2846 if (!PrimaryBase) {
2847 PrimaryBase = BaseDecl;
2848 LeadsWithZeroSizedBase = BaseLayout.leadsWithZeroSizedBase();
2849 }
2850 // Lay out the base.
2851 layoutNonVirtualBase(RD, BaseDecl, BaseLayout, PreviousBaseLayout);
2852 }
2853 // Figure out if we need a fresh VFPtr for this class.
2854 if (RD->isPolymorphic()) {
2855 if (!HasPolymorphicBaseClass)
2856 // This class introduces polymorphism, so we need a vftable to store the
2857 // RTTI information.
2858 HasOwnVFPtr = true;
2859 else if (!PrimaryBase) {
2860 // We have a polymorphic base class but can't extend its vftable. Add a
2861 // new vfptr if we would use any vftable slots.
2862 for (CXXMethodDecl *M : RD->methods()) {
2863 if (MicrosoftVTableContext::hasVtableSlot(M) &&
2864 M->size_overridden_methods() == 0) {
2865 HasOwnVFPtr = true;
2866 break;
2867 }
2868 }
2869 }
2870 }
2871 // If we don't have a primary base then we have a leading object that could
2872 // itself lead with a zero-sized object, something we track.
2873 bool CheckLeadingLayout = !PrimaryBase;
2874 // Iterate through the bases and lay out the non-virtual ones.
2875 for (const CXXBaseSpecifier &Base : RD->bases()) {
2876 if (Base.isVirtual())
2877 continue;
2878 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
2879 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
2880 // Only lay out bases without extendable VFPtrs on the second pass.
2881 if (BaseLayout.hasExtendableVFPtr()) {
2882 VBPtrOffset = Bases[BaseDecl] + BaseLayout.getNonVirtualSize();
2883 continue;
2884 }
2885 // If this is the first layout, check to see if it leads with a zero sized
2886 // object. If it does, so do we.
2887 if (CheckLeadingLayout) {
2888 CheckLeadingLayout = false;
2889 LeadsWithZeroSizedBase = BaseLayout.leadsWithZeroSizedBase();
2890 }
2891 // Lay out the base.
2892 layoutNonVirtualBase(RD, BaseDecl, BaseLayout, PreviousBaseLayout);
2893 VBPtrOffset = Bases[BaseDecl] + BaseLayout.getNonVirtualSize();
2894 }
2895 // Set our VBPtroffset if we know it at this point.
2896 if (!HasVBPtr)
2897 VBPtrOffset = CharUnits::fromQuantity(-1);
2898 else if (SharedVBPtrBase) {
2899 const ASTRecordLayout &Layout = Context.getASTRecordLayout(SharedVBPtrBase);
2900 VBPtrOffset = Bases[SharedVBPtrBase] + Layout.getVBPtrOffset();
2901 }
2902}
2903
2904static bool recordUsesEBO(const RecordDecl *RD) {
2905 if (!isa<CXXRecordDecl>(RD))
2906 return false;
2907 if (RD->hasAttr<EmptyBasesAttr>())
2908 return true;
2909 if (auto *LVA = RD->getAttr<LayoutVersionAttr>())
2910 // TODO: Double check with the next version of MSVC.
2911 if (LVA->getVersion() <= LangOptions::MSVC2015)
2912 return false;
2913 // TODO: Some later version of MSVC will change the default behavior of the
2914 // compiler to enable EBO by default. When this happens, we will need an
2915 // additional isCompatibleWithMSVC check.
2916 return false;
2917}
2918
2919void MicrosoftRecordLayoutBuilder::layoutNonVirtualBase(
2920 const CXXRecordDecl *RD, const CXXRecordDecl *BaseDecl,
2921 const ASTRecordLayout &BaseLayout,
2922 const ASTRecordLayout *&PreviousBaseLayout) {
2923 // Insert padding between two bases if the left first one is zero sized or
2924 // contains a zero sized subobject and the right is zero sized or one leads
2925 // with a zero sized base.
2926 bool MDCUsesEBO = recordUsesEBO(RD);
2927 if (PreviousBaseLayout && PreviousBaseLayout->endsWithZeroSizedObject() &&
2928 BaseLayout.leadsWithZeroSizedBase() && !MDCUsesEBO)
2929 Size++;
2930 ElementInfo Info = getAdjustedElementInfo(BaseLayout);
2931 CharUnits BaseOffset;
2932
2933 // Respect the external AST source base offset, if present.
2934 bool FoundBase = false;
2935 if (UseExternalLayout) {
2936 FoundBase = External.getExternalNVBaseOffset(BaseDecl, BaseOffset);
2937 if (BaseOffset > Size) {
2938 Size = BaseOffset;
2939 }
2940 }
2941
2942 if (!FoundBase) {
2943 if (MDCUsesEBO && BaseDecl->isEmpty() &&
2944 (BaseLayout.getNonVirtualSize() == CharUnits::Zero())) {
2945 BaseOffset = CharUnits::Zero();
2946 } else {
2947 // Otherwise, lay the base out at the end of the MDC.
2948 BaseOffset = Size = Size.alignTo(Info.Alignment);
2949 }
2950 }
2951 Bases.insert(std::make_pair(BaseDecl, BaseOffset));
2952 Size += BaseLayout.getNonVirtualSize();
2953 DataSize = Size;
2954 PreviousBaseLayout = &BaseLayout;
2955}
2956
2957void MicrosoftRecordLayoutBuilder::layoutFields(const RecordDecl *RD) {
2958 LastFieldIsNonZeroWidthBitfield = false;
2959 for (const FieldDecl *Field : RD->fields())
2960 layoutField(Field);
2961}
2962
2963void MicrosoftRecordLayoutBuilder::layoutField(const FieldDecl *FD) {
2964 if (FD->isBitField()) {
2965 layoutBitField(FD);
2966 return;
2967 }
2968 LastFieldIsNonZeroWidthBitfield = false;
2969 ElementInfo Info = getAdjustedElementInfo(FD);
2970 Alignment = std::max(Alignment, Info.Alignment);
2971
2972 const CXXRecordDecl *FieldClass = FD->getType()->getAsCXXRecordDecl();
2973 bool IsOverlappingEmptyField = FD->isPotentiallyOverlapping() &&
2974 FieldClass->isEmpty() &&
2975 FieldClass->fields().empty();
2976 CharUnits FieldOffset = CharUnits::Zero();
2977
2978 if (UseExternalLayout) {
2979 FieldOffset =
2980 Context.toCharUnitsFromBits(External.getExternalFieldOffset(FD));
2981 } else if (IsUnion) {
2982 FieldOffset = CharUnits::Zero();
2983 } else if (EmptySubobjects) {
2984 if (!IsOverlappingEmptyField)
2985 FieldOffset = DataSize.alignTo(Info.Alignment);
2986
2987 while (!EmptySubobjects->CanPlaceFieldAtOffset(FD, FieldOffset)) {
2988 const CXXRecordDecl *ParentClass = cast<CXXRecordDecl>(FD->getParent());
2989 bool HasBases = ParentClass && (!ParentClass->bases().empty() ||
2990 !ParentClass->vbases().empty());
2991 if (FieldOffset == CharUnits::Zero() && DataSize != CharUnits::Zero() &&
2992 HasBases) {
2993 // MSVC appears to only do this when there are base classes;
2994 // otherwise it overlaps no_unique_address fields in non-zero offsets.
2995 FieldOffset = DataSize.alignTo(Info.Alignment);
2996 } else {
2997 FieldOffset += Info.Alignment;
2998 }
2999 }
3000 } else {
3001 FieldOffset = Size.alignTo(Info.Alignment);
3002 }
3003 placeFieldAtOffset(FieldOffset);
3004
3005 if (!IsOverlappingEmptyField)
3006 DataSize = std::max(DataSize, FieldOffset + Info.Size);
3007
3008 Size = std::max(Size, FieldOffset + Info.Size);
3009}
3010
3011void MicrosoftRecordLayoutBuilder::layoutBitField(const FieldDecl *FD) {
3012 unsigned Width = FD->getBitWidthValue();
3013 if (Width == 0) {
3014 layoutZeroWidthBitField(FD);
3015 return;
3016 }
3017 ElementInfo Info = getAdjustedElementInfo(FD);
3018 // Clamp the bitfield to a containable size for the sake of being able
3019 // to lay them out. Sema will throw an error.
3020 if (Width > Context.toBits(Info.Size))
3021 Width = Context.toBits(Info.Size);
3022 // Check to see if this bitfield fits into an existing allocation. Note:
3023 // MSVC refuses to pack bitfields of formal types with different sizes
3024 // into the same allocation.
3025 if (!UseExternalLayout && !IsUnion && LastFieldIsNonZeroWidthBitfield &&
3026 CurrentBitfieldSize == Info.Size && Width <= RemainingBitsInField) {
3027 placeFieldAtBitOffset(Context.toBits(Size) - RemainingBitsInField);
3028 RemainingBitsInField -= Width;
3029 return;
3030 }
3031 LastFieldIsNonZeroWidthBitfield = true;
3032 CurrentBitfieldSize = Info.Size;
3033 if (UseExternalLayout) {
3034 auto FieldBitOffset = External.getExternalFieldOffset(FD);
3035 placeFieldAtBitOffset(FieldBitOffset);
3036 auto NewSize = Context.toCharUnitsFromBits(
3037 llvm::alignDown(FieldBitOffset, Context.toBits(Info.Alignment)) +
3038 Context.toBits(Info.Size));
3039 Size = std::max(Size, NewSize);
3040 Alignment = std::max(Alignment, Info.Alignment);
3041 } else if (IsUnion) {
3042 placeFieldAtOffset(CharUnits::Zero());
3043 Size = std::max(Size, Info.Size);
3044 // TODO: Add a Sema warning that MS ignores bitfield alignment in unions.
3045 } else {
3046 // Allocate a new block of memory and place the bitfield in it.
3047 CharUnits FieldOffset = Size.alignTo(Info.Alignment);
3048 placeFieldAtOffset(FieldOffset);
3049 Size = FieldOffset + Info.Size;
3050 Alignment = std::max(Alignment, Info.Alignment);
3051 RemainingBitsInField = Context.toBits(Info.Size) - Width;
3052 }
3053 DataSize = Size;
3054}
3055
3056void
3057MicrosoftRecordLayoutBuilder::layoutZeroWidthBitField(const FieldDecl *FD) {
3058 // Zero-width bitfields are ignored unless they follow a non-zero-width
3059 // bitfield.
3060 if (!LastFieldIsNonZeroWidthBitfield) {
3061 placeFieldAtOffset(IsUnion ? CharUnits::Zero() : Size);
3062 // TODO: Add a Sema warning that MS ignores alignment for zero
3063 // sized bitfields that occur after zero-size bitfields or non-bitfields.
3064 return;
3065 }
3066 LastFieldIsNonZeroWidthBitfield = false;
3067 ElementInfo Info = getAdjustedElementInfo(FD);
3068 if (IsUnion) {
3069 placeFieldAtOffset(CharUnits::Zero());
3070 Size = std::max(Size, Info.Size);
3071 // TODO: Add a Sema warning that MS ignores bitfield alignment in unions.
3072 } else {
3073 // Round up the current record size to the field's alignment boundary.
3074 CharUnits FieldOffset = Size.alignTo(Info.Alignment);
3075 placeFieldAtOffset(FieldOffset);
3076 Size = FieldOffset;
3077 Alignment = std::max(Alignment, Info.Alignment);
3078 }
3079 DataSize = Size;
3080}
3081
3082void MicrosoftRecordLayoutBuilder::injectVBPtr(const CXXRecordDecl *RD) {
3083 if (!HasVBPtr || SharedVBPtrBase)
3084 return;
3085 // Inject the VBPointer at the injection site.
3086 CharUnits InjectionSite = VBPtrOffset;
3087 // But before we do, make sure it's properly aligned.
3088 VBPtrOffset = VBPtrOffset.alignTo(PointerInfo.Alignment);
3089 // Determine where the first field should be laid out after the vbptr.
3090 CharUnits FieldStart = VBPtrOffset + PointerInfo.Size;
3091 // Shift everything after the vbptr down, unless we're using an external
3092 // layout.
3093 if (UseExternalLayout) {
3094 // It is possible that there were no fields or bases located after vbptr,
3095 // so the size was not adjusted before.
3096 if (Size < FieldStart)
3097 Size = FieldStart;
3098 return;
3099 }
3100 // Make sure that the amount we push the fields back by is a multiple of the
3101 // alignment.
3102 CharUnits Offset = (FieldStart - InjectionSite)
3103 .alignTo(std::max(RequiredAlignment, Alignment));
3104 Size += Offset;
3105 for (uint64_t &FieldOffset : FieldOffsets)
3106 FieldOffset += Context.toBits(Offset);
3107 for (BaseOffsetsMapTy::value_type &Base : Bases)
3108 if (Base.second >= InjectionSite)
3109 Base.second += Offset;
3110}
3111
3112void MicrosoftRecordLayoutBuilder::injectVFPtr(const CXXRecordDecl *RD) {
3113 if (!HasOwnVFPtr)
3114 return;
3115 // Make sure that the amount we push the struct back by is a multiple of the
3116 // alignment.
3117 CharUnits Offset =
3118 PointerInfo.Size.alignTo(std::max(RequiredAlignment, Alignment));
3119 // Push back the vbptr, but increase the size of the object and push back
3120 // regular fields by the offset only if not using external record layout.
3121 if (HasVBPtr)
3122 VBPtrOffset += Offset;
3123
3124 if (UseExternalLayout) {
3125 // The class may have size 0 and a vfptr (e.g. it's an interface class). The
3126 // size was not correctly set before in this case.
3127 if (Size.isZero())
3128 Size += Offset;
3129 return;
3130 }
3131
3132 Size += Offset;
3133
3134 // If we're using an external layout, the fields offsets have already
3135 // accounted for this adjustment.
3136 for (uint64_t &FieldOffset : FieldOffsets)
3137 FieldOffset += Context.toBits(Offset);
3138 for (BaseOffsetsMapTy::value_type &Base : Bases)
3139 Base.second += Offset;
3140}
3141
3142void MicrosoftRecordLayoutBuilder::layoutVirtualBases(const CXXRecordDecl *RD) {
3143 if (!HasVBPtr)
3144 return;
3145 // Vtordisps are always 4 bytes (even in 64-bit mode)
3146 CharUnits VtorDispSize = CharUnits::fromQuantity(4);
3147 CharUnits VtorDispAlignment = VtorDispSize;
3148 // vtordisps respect pragma pack.
3149 if (!MaxFieldAlignment.isZero())
3150 VtorDispAlignment = std::min(VtorDispAlignment, MaxFieldAlignment);
3151 // The alignment of the vtordisp is at least the required alignment of the
3152 // entire record. This requirement may be present to support vtordisp
3153 // injection.
3154 for (const CXXBaseSpecifier &VBase : RD->vbases()) {
3155 const CXXRecordDecl *BaseDecl = VBase.getType()->getAsCXXRecordDecl();
3156 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
3157 RequiredAlignment =
3158 std::max(RequiredAlignment, BaseLayout.getRequiredAlignment());
3159 }
3160 VtorDispAlignment = std::max(VtorDispAlignment, RequiredAlignment);
3161 // Compute the vtordisp set.
3163 computeVtorDispSet(HasVtorDispSet, RD);
3164 // Iterate through the virtual bases and lay them out.
3165 const ASTRecordLayout *PreviousBaseLayout = nullptr;
3166 for (const CXXBaseSpecifier &VBase : RD->vbases()) {
3167 const CXXRecordDecl *BaseDecl = VBase.getType()->getAsCXXRecordDecl();
3168 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
3169 bool HasVtordisp = HasVtorDispSet.contains(BaseDecl);
3170 // Insert padding between two bases if the left first one is zero sized or
3171 // contains a zero sized subobject and the right is zero sized or one leads
3172 // with a zero sized base. The padding between virtual bases is 4
3173 // bytes (in both 32 and 64 bits modes) and always involves rounding up to
3174 // the required alignment, we don't know why.
3175 if ((PreviousBaseLayout && PreviousBaseLayout->endsWithZeroSizedObject() &&
3176 BaseLayout.leadsWithZeroSizedBase() && !recordUsesEBO(RD)) ||
3177 HasVtordisp) {
3178 Size = Size.alignTo(VtorDispAlignment) + VtorDispSize;
3179 Alignment = std::max(VtorDispAlignment, Alignment);
3180 }
3181 // Insert the virtual base.
3182 ElementInfo Info = getAdjustedElementInfo(BaseLayout);
3183 CharUnits BaseOffset;
3184
3185 // Respect the external AST source base offset, if present.
3186 if (UseExternalLayout) {
3187 if (!External.getExternalVBaseOffset(BaseDecl, BaseOffset))
3188 BaseOffset = Size;
3189 } else
3190 BaseOffset = Size.alignTo(Info.Alignment);
3191
3192 assert(BaseOffset >= Size && "base offset already allocated");
3193
3194 VBases.insert(std::make_pair(BaseDecl,
3195 ASTRecordLayout::VBaseInfo(BaseOffset, HasVtordisp)));
3196 Size = BaseOffset + BaseLayout.getNonVirtualSize();
3197 PreviousBaseLayout = &BaseLayout;
3198 }
3199}
3200
3201void MicrosoftRecordLayoutBuilder::finalizeLayout(const RecordDecl *RD) {
3202 // Respect required alignment. Note that in 32-bit mode Required alignment
3203 // may be 0 and cause size not to be updated.
3204 DataSize = Size;
3205 if (!RequiredAlignment.isZero()) {
3206 Alignment = std::max(Alignment, RequiredAlignment);
3207 auto RoundingAlignment = Alignment;
3208 if (!MaxFieldAlignment.isZero())
3209 RoundingAlignment = std::min(RoundingAlignment, MaxFieldAlignment);
3210 RoundingAlignment = std::max(RoundingAlignment, RequiredAlignment);
3211 Size = Size.alignTo(RoundingAlignment);
3212 }
3213 if (Size.isZero()) {
3214 if (!recordUsesEBO(RD) || !cast<CXXRecordDecl>(RD)->isEmpty()) {
3215 EndsWithZeroSizedObject = true;
3216 LeadsWithZeroSizedBase = true;
3217 }
3218 // Zero-sized structures have size equal to their alignment if a
3219 // __declspec(align) came into play.
3220 if (RequiredAlignment >= MinEmptyStructSize)
3221 Size = Alignment;
3222 else
3223 Size = MinEmptyStructSize;
3224 }
3225
3226 if (UseExternalLayout) {
3227 Size = Context.toCharUnitsFromBits(External.Size);
3228 if (External.Align)
3229 Alignment = Context.toCharUnitsFromBits(External.Align);
3230 }
3231}
3232
3233// Recursively walks the non-virtual bases of a class and determines if any of
3234// them are in the bases with overridden methods set.
3235static bool
3236RequiresVtordisp(const llvm::SmallPtrSetImpl<const CXXRecordDecl *> &
3237 BasesWithOverriddenMethods,
3238 const CXXRecordDecl *RD) {
3239 if (BasesWithOverriddenMethods.count(RD))
3240 return true;
3241 // If any of a virtual bases non-virtual bases (recursively) requires a
3242 // vtordisp than so does this virtual base.
3243 for (const CXXBaseSpecifier &Base : RD->bases())
3244 if (!Base.isVirtual() &&
3245 RequiresVtordisp(BasesWithOverriddenMethods,
3246 Base.getType()->getAsCXXRecordDecl()))
3247 return true;
3248 return false;
3249}
3250
3251void MicrosoftRecordLayoutBuilder::computeVtorDispSet(
3252 llvm::SmallPtrSetImpl<const CXXRecordDecl *> &HasVtordispSet,
3253 const CXXRecordDecl *RD) const {
3254 // /vd2 or #pragma vtordisp(2): Always use vtordisps for virtual bases with
3255 // vftables.
3256 if (RD->getMSVtorDispMode() == MSVtorDispMode::ForVFTable) {
3257 for (const CXXBaseSpecifier &Base : RD->vbases()) {
3258 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
3259 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
3260 if (Layout.hasExtendableVFPtr())
3261 HasVtordispSet.insert(BaseDecl);
3262 }
3263 return;
3264 }
3265
3266 // If any of our bases need a vtordisp for this type, so do we. Check our
3267 // direct bases for vtordisp requirements.
3268 for (const CXXBaseSpecifier &Base : RD->bases()) {
3269 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
3270 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
3271 for (const auto &bi : Layout.getVBaseOffsetsMap())
3272 if (bi.second.hasVtorDisp())
3273 HasVtordispSet.insert(bi.first);
3274 }
3275 // We don't introduce any additional vtordisps if either:
3276 // * A user declared constructor or destructor aren't declared.
3277 // * #pragma vtordisp(0) or the /vd0 flag are in use.
3279 RD->getMSVtorDispMode() == MSVtorDispMode::Never)
3280 return;
3281 // /vd1 or #pragma vtordisp(1): Try to guess based on whether we think it's
3282 // possible for a partially constructed object with virtual base overrides to
3283 // escape a non-trivial constructor.
3284 assert(RD->getMSVtorDispMode() == MSVtorDispMode::ForVBaseOverride);
3285 // Compute a set of base classes which define methods we override. A virtual
3286 // base in this set will require a vtordisp. A virtual base that transitively
3287 // contains one of these bases as a non-virtual base will also require a
3288 // vtordisp.
3290 llvm::SmallPtrSet<const CXXRecordDecl *, 2> BasesWithOverriddenMethods;
3291 // Seed the working set with our non-destructor, non-pure virtual methods.
3292 for (const CXXMethodDecl *MD : RD->methods())
3293 if (MicrosoftVTableContext::hasVtableSlot(MD) &&
3294 !isa<CXXDestructorDecl>(MD) && !MD->isPureVirtual())
3295 Work.insert(MD);
3296 while (!Work.empty()) {
3297 const CXXMethodDecl *MD = *Work.begin();
3298 auto MethodRange = MD->overridden_methods();
3299 // If a virtual method has no-overrides it lives in its parent's vtable.
3300 if (MethodRange.begin() == MethodRange.end())
3301 BasesWithOverriddenMethods.insert(MD->getParent());
3302 else
3303 Work.insert(MethodRange.begin(), MethodRange.end());
3304 // We've finished processing this element, remove it from the working set.
3305 Work.erase(MD);
3306 }
3307 // For each of our virtual bases, check if it is in the set of overridden
3308 // bases or if it transitively contains a non-virtual base that is.
3309 for (const CXXBaseSpecifier &Base : RD->vbases()) {
3310 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
3311 if (!HasVtordispSet.count(BaseDecl) &&
3312 RequiresVtordisp(BasesWithOverriddenMethods, BaseDecl))
3313 HasVtordispSet.insert(BaseDecl);
3314 }
3315}
3316
3317/// getASTRecordLayout - Get or compute information about the layout of the
3318/// specified record (struct/union/class), which indicates its size and field
3319/// position information.
3320const ASTRecordLayout &
3322 // These asserts test different things. A record has a definition
3323 // as soon as we begin to parse the definition. That definition is
3324 // not a complete definition (which is what isDefinition() tests)
3325 // until we *finish* parsing the definition.
3326
3327 if (D->hasExternalLexicalStorage() && !D->getDefinition())
3328 getExternalSource()->CompleteType(const_cast<RecordDecl*>(D));
3329 // Complete the redecl chain (if necessary).
3330 (void)D->getMostRecentDecl();
3331
3332 D = D->getDefinition();
3333 assert(D && "Cannot get layout of forward declarations!");
3334 assert(!D->isInvalidDecl() && "Cannot get layout of invalid decl!");
3335 assert(D->isCompleteDefinition() && "Cannot layout type before complete!");
3336
3337 // Look up this layout, if already laid out, return what we have.
3338 // Note that we can't save a reference to the entry because this function
3339 // is recursive.
3340 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
3341 if (Entry) return *Entry;
3342
3343 const ASTRecordLayout *NewEntry = nullptr;
3344
3345 if (isMsLayout(*this)) {
3346 if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
3347 EmptySubobjectMap EmptySubobjects(*this, RD);
3348 MicrosoftRecordLayoutBuilder Builder(*this, &EmptySubobjects);
3349 Builder.cxxLayout(RD);
3350 NewEntry = new (*this) ASTRecordLayout(
3351 *this, Builder.Size, Builder.Alignment, Builder.Alignment,
3352 Builder.Alignment, Builder.RequiredAlignment, Builder.HasOwnVFPtr,
3353 Builder.HasOwnVFPtr || Builder.PrimaryBase, Builder.VBPtrOffset,
3354 Builder.DataSize, Builder.FieldOffsets, Builder.NonVirtualSize,
3355 Builder.Alignment, Builder.Alignment, CharUnits::Zero(),
3356 Builder.PrimaryBase, false, Builder.SharedVBPtrBase,
3357 Builder.EndsWithZeroSizedObject, Builder.LeadsWithZeroSizedBase,
3358 Builder.Bases, Builder.VBases);
3359 } else {
3360 MicrosoftRecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/nullptr);
3361 Builder.layout(D);
3362 NewEntry = new (*this) ASTRecordLayout(
3363 *this, Builder.Size, Builder.Alignment, Builder.Alignment,
3364 Builder.Alignment, Builder.RequiredAlignment, Builder.Size,
3365 Builder.FieldOffsets);
3366 }
3367 } else {
3368 if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
3369 EmptySubobjectMap EmptySubobjects(*this, RD);
3370 ItaniumRecordLayoutBuilder Builder(*this, &EmptySubobjects);
3371 Builder.Layout(RD);
3372
3373 // In certain situations, we are allowed to lay out objects in the
3374 // tail-padding of base classes. This is ABI-dependent.
3375 // FIXME: this should be stored in the record layout.
3376 bool skipTailPadding =
3377 mustSkipTailPadding(getTargetInfo().getCXXABI(), RD);
3378
3379 // FIXME: This should be done in FinalizeLayout.
3380 CharUnits DataSize =
3381 skipTailPadding ? Builder.getSize() : Builder.getDataSize();
3382 CharUnits NonVirtualSize =
3383 skipTailPadding ? DataSize : Builder.NonVirtualSize;
3384 NewEntry = new (*this) ASTRecordLayout(
3385 *this, Builder.getSize(), Builder.Alignment,
3386 Builder.PreferredAlignment, Builder.UnadjustedAlignment,
3387 /*RequiredAlignment : used by MS-ABI)*/
3388 Builder.Alignment, Builder.HasOwnVFPtr, RD->isDynamicClass(),
3389 CharUnits::fromQuantity(-1), DataSize, Builder.FieldOffsets,
3390 NonVirtualSize, Builder.NonVirtualAlignment,
3391 Builder.PreferredNVAlignment,
3392 EmptySubobjects.SizeOfLargestEmptySubobject, Builder.PrimaryBase,
3393 Builder.PrimaryBaseIsVirtual, nullptr, false, false, Builder.Bases,
3394 Builder.VBases);
3395 } else {
3396 ItaniumRecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/nullptr);
3397 Builder.Layout(D);
3398
3399 NewEntry = new (*this) ASTRecordLayout(
3400 *this, Builder.getSize(), Builder.Alignment,
3401 Builder.PreferredAlignment, Builder.UnadjustedAlignment,
3402 /*RequiredAlignment : used by MS-ABI)*/
3403 Builder.Alignment, Builder.getSize(), Builder.FieldOffsets);
3404 }
3405 }
3406
3407 ASTRecordLayouts[D] = NewEntry;
3408
3409 if (getLangOpts().DumpRecordLayouts) {
3410 llvm::outs() << "\n*** Dumping AST Record Layout\n";
3411 DumpRecordLayout(D, llvm::outs(), getLangOpts().DumpRecordLayoutsSimple);
3412 }
3413
3414 return *NewEntry;
3415}
3416
3418 if (!getTargetInfo().getCXXABI().hasKeyFunctions())
3419 return nullptr;
3420
3421 assert(RD->getDefinition() && "Cannot get key function for forward decl!");
3422 RD = RD->getDefinition();
3423
3424 // Beware:
3425 // 1) computing the key function might trigger deserialization, which might
3426 // invalidate iterators into KeyFunctions
3427 // 2) 'get' on the LazyDeclPtr might also trigger deserialization and
3428 // invalidate the LazyDeclPtr within the map itself
3429 LazyDeclPtr Entry = KeyFunctions[RD];
3430 const Decl *Result =
3431 Entry ? Entry.get(getExternalSource()) : computeKeyFunction(*this, RD);
3432
3433 // Store it back if it changed.
3434 if (Entry.isOffset() || Entry.isValid() != bool(Result))
3435 KeyFunctions[RD] = const_cast<Decl*>(Result);
3436
3437 return cast_or_null<CXXMethodDecl>(Result);
3438}
3439
3441 assert(Method == Method->getFirstDecl() &&
3442 "not working with method declaration from class definition");
3443
3444 // Look up the cache entry. Since we're working with the first
3445 // declaration, its parent must be the class definition, which is
3446 // the correct key for the KeyFunctions hash.
3447 const auto &Map = KeyFunctions;
3448 auto I = Map.find(Method->getParent());
3449
3450 // If it's not cached, there's nothing to do.
3451 if (I == Map.end()) return;
3452
3453 // If it is cached, check whether it's the target method, and if so,
3454 // remove it from the cache. Note, the call to 'get' might invalidate
3455 // the iterator and the LazyDeclPtr object within the map.
3456 LazyDeclPtr Ptr = I->second;
3457 if (Ptr.get(getExternalSource()) == Method) {
3458 // FIXME: remember that we did this for module / chained PCH state?
3459 KeyFunctions.erase(Method->getParent());
3460 }
3461}
3462
3463static uint64_t getFieldOffset(const ASTContext &C, const FieldDecl *FD) {
3464 const ASTRecordLayout &Layout = C.getASTRecordLayout(FD->getParent());
3465 return Layout.getFieldOffset(FD->getFieldIndex());
3466}
3467
3468uint64_t ASTContext::getFieldOffset(const ValueDecl *VD) const {
3469 uint64_t OffsetInBits;
3470 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
3471 OffsetInBits = ::getFieldOffset(*this, FD);
3472 } else {
3473 const IndirectFieldDecl *IFD = cast<IndirectFieldDecl>(VD);
3474
3475 OffsetInBits = 0;
3476 for (const NamedDecl *ND : IFD->chain())
3477 OffsetInBits += ::getFieldOffset(*this, cast<FieldDecl>(ND));
3478 }
3479
3480 return OffsetInBits;
3481}
3482
3484 const ObjCImplementationDecl *ID,
3485 const ObjCIvarDecl *Ivar) const {
3486 Ivar = Ivar->getCanonicalDecl();
3487 const ObjCInterfaceDecl *Container = Ivar->getContainingInterface();
3488
3489 // FIXME: We should eliminate the need to have ObjCImplementationDecl passed
3490 // in here; it should never be necessary because that should be the lexical
3491 // decl context for the ivar.
3492
3493 // If we know have an implementation (and the ivar is in it) then
3494 // look up in the implementation layout.
3495 const ASTRecordLayout *RL;
3496 if (ID && declaresSameEntity(ID->getClassInterface(), Container))
3498 else
3499 RL = &getASTObjCInterfaceLayout(Container);
3500
3501 // Compute field index.
3502 //
3503 // FIXME: The index here is closely tied to how ASTContext::getObjCLayout is
3504 // implemented. This should be fixed to get the information from the layout
3505 // directly.
3506 unsigned Index = 0;
3507
3508 for (const ObjCIvarDecl *IVD = Container->all_declared_ivar_begin();
3509 IVD; IVD = IVD->getNextIvar()) {
3510 if (Ivar == IVD)
3511 break;
3512 ++Index;
3513 }
3514 assert(Index < RL->getFieldCount() && "Ivar is not inside record layout!");
3515
3516 return RL->getFieldOffset(Index);
3517}
3518
3519/// getObjCLayout - Get or compute information about the layout of the
3520/// given interface.
3521///
3522/// \param Impl - If given, also include the layout of the interface's
3523/// implementation. This may differ by including synthesized ivars.
3524const ASTRecordLayout &
3525ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
3526 const ObjCImplementationDecl *Impl) const {
3527 // Retrieve the definition
3528 if (D->hasExternalLexicalStorage() && !D->getDefinition())
3530 D = D->getDefinition();
3531 assert(D && !D->isInvalidDecl() && D->isThisDeclarationADefinition() &&
3532 "Invalid interface decl!");
3533
3534 // Look up this layout, if already laid out, return what we have.
3535 const ObjCContainerDecl *Key =
3536 Impl ? (const ObjCContainerDecl*) Impl : (const ObjCContainerDecl*) D;
3537 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
3538 return *Entry;
3539
3540 // Add in synthesized ivar count if laying out an implementation.
3541 if (Impl) {
3542 unsigned SynthCount = CountNonClassIvars(D);
3543 // If there aren't any synthesized ivars then reuse the interface
3544 // entry. Note we can't cache this because we simply free all
3545 // entries later; however we shouldn't look up implementations
3546 // frequently.
3547 if (SynthCount == 0)
3548 return getObjCLayout(D, nullptr);
3549 }
3550
3551 ItaniumRecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/nullptr);
3552 Builder.Layout(D);
3553
3554 const ASTRecordLayout *NewEntry = new (*this) ASTRecordLayout(
3555 *this, Builder.getSize(), Builder.Alignment, Builder.PreferredAlignment,
3556 Builder.UnadjustedAlignment,
3557 /*RequiredAlignment : used by MS-ABI)*/
3558 Builder.Alignment, Builder.getDataSize(), Builder.FieldOffsets);
3559
3560 ObjCLayouts[Key] = NewEntry;
3561
3562 return *NewEntry;
3563}
3564
3565static void PrintOffset(raw_ostream &OS,
3566 CharUnits Offset, unsigned IndentLevel) {
3567 OS << llvm::format("%10" PRId64 " | ", (int64_t)Offset.getQuantity());
3568 OS.indent(IndentLevel * 2);
3569}
3570
3571static void PrintBitFieldOffset(raw_ostream &OS, CharUnits Offset,
3572 unsigned Begin, unsigned Width,
3573 unsigned IndentLevel) {
3574 llvm::SmallString<10> Buffer;
3575 {
3576 llvm::raw_svector_ostream BufferOS(Buffer);
3577 BufferOS << Offset.getQuantity() << ':';
3578 if (Width == 0) {
3579 BufferOS << '-';
3580 } else {
3581 BufferOS << Begin << '-' << (Begin + Width - 1);
3582 }
3583 }
3584
3585 OS << llvm::right_justify(Buffer, 10) << " | ";
3586 OS.indent(IndentLevel * 2);
3587}
3588
3589static void PrintIndentNoOffset(raw_ostream &OS, unsigned IndentLevel) {
3590 OS << " | ";
3591 OS.indent(IndentLevel * 2);
3592}
3593
3594static void DumpRecordLayout(raw_ostream &OS, const RecordDecl *RD,
3595 const ASTContext &C,
3596 CharUnits Offset,
3597 unsigned IndentLevel,
3598 const char* Description,
3599 bool PrintSizeInfo,
3600 bool IncludeVirtualBases) {
3601 const ASTRecordLayout &Layout = C.getASTRecordLayout(RD);
3602 auto CXXRD = dyn_cast<CXXRecordDecl>(RD);
3603
3604 PrintOffset(OS, Offset, IndentLevel);
3605 OS << C.getTypeDeclType(const_cast<RecordDecl *>(RD));
3606 if (Description)
3607 OS << ' ' << Description;
3608 if (CXXRD && CXXRD->isEmpty())
3609 OS << " (empty)";
3610 OS << '\n';
3611
3612 IndentLevel++;
3613
3614 // Dump bases.
3615 if (CXXRD) {
3616 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
3617 bool HasOwnVFPtr = Layout.hasOwnVFPtr();
3618 bool HasOwnVBPtr = Layout.hasOwnVBPtr();
3619
3620 // Vtable pointer.
3621 if (CXXRD->isDynamicClass() && !PrimaryBase && !isMsLayout(C)) {
3622 PrintOffset(OS, Offset, IndentLevel);
3623 OS << '(' << *RD << " vtable pointer)\n";
3624 } else if (HasOwnVFPtr) {
3625 PrintOffset(OS, Offset, IndentLevel);
3626 // vfptr (for Microsoft C++ ABI)
3627 OS << '(' << *RD << " vftable pointer)\n";
3628 }
3629
3630 // Collect nvbases.
3632 for (const CXXBaseSpecifier &Base : CXXRD->bases()) {
3633 assert(!Base.getType()->isDependentType() &&
3634 "Cannot layout class with dependent bases.");
3635 if (!Base.isVirtual())
3636 Bases.push_back(Base.getType()->getAsCXXRecordDecl());
3637 }
3638
3639 // Sort nvbases by offset.
3640 llvm::stable_sort(
3641 Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
3642 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
3643 });
3644
3645 // Dump (non-virtual) bases
3646 for (const CXXRecordDecl *Base : Bases) {
3647 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base);
3648 DumpRecordLayout(OS, Base, C, BaseOffset, IndentLevel,
3649 Base == PrimaryBase ? "(primary base)" : "(base)",
3650 /*PrintSizeInfo=*/false,
3651 /*IncludeVirtualBases=*/false);
3652 }
3653
3654 // vbptr (for Microsoft C++ ABI)
3655 if (HasOwnVBPtr) {
3656 PrintOffset(OS, Offset + Layout.getVBPtrOffset(), IndentLevel);
3657 OS << '(' << *RD << " vbtable pointer)\n";
3658 }
3659 }
3660
3661 // Dump fields.
3662 for (const FieldDecl *Field : RD->fields()) {
3663 uint64_t LocalFieldOffsetInBits =
3664 Layout.getFieldOffset(Field->getFieldIndex());
3665 CharUnits FieldOffset =
3666 Offset + C.toCharUnitsFromBits(LocalFieldOffsetInBits);
3667
3668 // Recursively dump fields of record type.
3669 if (auto RT = Field->getType()->getAs<RecordType>()) {
3670 DumpRecordLayout(OS, RT->getDecl(), C, FieldOffset, IndentLevel,
3671 Field->getName().data(),
3672 /*PrintSizeInfo=*/false,
3673 /*IncludeVirtualBases=*/true);
3674 continue;
3675 }
3676
3677 if (Field->isBitField()) {
3678 uint64_t LocalFieldByteOffsetInBits = C.toBits(FieldOffset - Offset);
3679 unsigned Begin = LocalFieldOffsetInBits - LocalFieldByteOffsetInBits;
3680 unsigned Width = Field->getBitWidthValue();
3681 PrintBitFieldOffset(OS, FieldOffset, Begin, Width, IndentLevel);
3682 } else {
3683 PrintOffset(OS, FieldOffset, IndentLevel);
3684 }
3685 const QualType &FieldType = C.getLangOpts().DumpRecordLayoutsCanonical
3686 ? Field->getType().getCanonicalType()
3687 : Field->getType();
3688 OS << FieldType << ' ' << *Field << '\n';
3689 }
3690
3691 // Dump virtual bases.
3692 if (CXXRD && IncludeVirtualBases) {
3693 const ASTRecordLayout::VBaseOffsetsMapTy &VtorDisps =
3694 Layout.getVBaseOffsetsMap();
3695
3696 for (const CXXBaseSpecifier &Base : CXXRD->vbases()) {
3697 assert(Base.isVirtual() && "Found non-virtual class!");
3698 const CXXRecordDecl *VBase = Base.getType()->getAsCXXRecordDecl();
3699
3700 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBase);
3701
3702 if (VtorDisps.find(VBase)->second.hasVtorDisp()) {
3703 PrintOffset(OS, VBaseOffset - CharUnits::fromQuantity(4), IndentLevel);
3704 OS << "(vtordisp for vbase " << *VBase << ")\n";
3705 }
3706
3707 DumpRecordLayout(OS, VBase, C, VBaseOffset, IndentLevel,
3708 VBase == Layout.getPrimaryBase() ?
3709 "(primary virtual base)" : "(virtual base)",
3710 /*PrintSizeInfo=*/false,
3711 /*IncludeVirtualBases=*/false);
3712 }
3713 }
3714
3715 if (!PrintSizeInfo) return;
3716
3717 PrintIndentNoOffset(OS, IndentLevel - 1);
3718 OS << "[sizeof=" << Layout.getSize().getQuantity();
3719 if (CXXRD && !isMsLayout(C))
3720 OS << ", dsize=" << Layout.getDataSize().getQuantity();
3721 OS << ", align=" << Layout.getAlignment().getQuantity();
3722 if (C.getTargetInfo().defaultsToAIXPowerAlignment())
3723 OS << ", preferredalign=" << Layout.getPreferredAlignment().getQuantity();
3724
3725 if (CXXRD) {
3726 OS << ",\n";
3727 PrintIndentNoOffset(OS, IndentLevel - 1);
3728 OS << " nvsize=" << Layout.getNonVirtualSize().getQuantity();
3729 OS << ", nvalign=" << Layout.getNonVirtualAlignment().getQuantity();
3730 if (C.getTargetInfo().defaultsToAIXPowerAlignment())
3731 OS << ", preferrednvalign="
3733 }
3734 OS << "]\n";
3735}
3736
3737void ASTContext::DumpRecordLayout(const RecordDecl *RD, raw_ostream &OS,
3738 bool Simple) const {
3739 if (!Simple) {
3740 ::DumpRecordLayout(OS, RD, *this, CharUnits(), 0, nullptr,
3741 /*PrintSizeInfo*/ true,
3742 /*IncludeVirtualBases=*/true);
3743 return;
3744 }
3745
3746 // The "simple" format is designed to be parsed by the
3747 // layout-override testing code. There shouldn't be any external
3748 // uses of this format --- when LLDB overrides a layout, it sets up
3749 // the data structures directly --- so feel free to adjust this as
3750 // you like as long as you also update the rudimentary parser for it
3751 // in libFrontend.
3752
3753 const ASTRecordLayout &Info = getASTRecordLayout(RD);
3754 OS << "Type: " << getTypeDeclType(RD) << "\n";
3755 OS << "\nLayout: ";
3756 OS << "<ASTRecordLayout\n";
3757 OS << " Size:" << toBits(Info.getSize()) << "\n";
3758 if (!isMsLayout(*this))
3759 OS << " DataSize:" << toBits(Info.getDataSize()) << "\n";
3760 OS << " Alignment:" << toBits(Info.getAlignment()) << "\n";
3761 if (Target->defaultsToAIXPowerAlignment())
3762 OS << " PreferredAlignment:" << toBits(Info.getPreferredAlignment())
3763 << "\n";
3764 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3765 OS << " BaseOffsets: [";
3766 const CXXRecordDecl *Base = nullptr;
3767 for (auto I : CXXRD->bases()) {
3768 if (I.isVirtual())
3769 continue;
3770 if (Base)
3771 OS << ", ";
3772 Base = I.getType()->getAsCXXRecordDecl();
3773 OS << Info.CXXInfo->BaseOffsets[Base].getQuantity();
3774 }
3775 OS << "]>\n";
3776 OS << " VBaseOffsets: [";
3777 const CXXRecordDecl *VBase = nullptr;
3778 for (auto I : CXXRD->vbases()) {
3779 if (VBase)
3780 OS << ", ";
3781 VBase = I.getType()->getAsCXXRecordDecl();
3782 OS << Info.CXXInfo->VBaseOffsets[VBase].VBaseOffset.getQuantity();
3783 }
3784 OS << "]>\n";
3785 }
3786 OS << " FieldOffsets: [";
3787 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i) {
3788 if (i)
3789 OS << ", ";
3790 OS << Info.getFieldOffset(i);
3791 }
3792 OS << "]>\n";
3793}
Defines the clang::ASTContext interface.
const Decl * D
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
static unsigned getCharWidth(tok::TokenKind kind, const TargetInfo &Target)
llvm::MachO::Target Target
Definition: MachO.h:51
static const CXXMethodDecl * computeKeyFunction(ASTContext &Context, const CXXRecordDecl *RD)
static bool mustSkipTailPadding(TargetCXXABI ABI, const CXXRecordDecl *RD)
Does the target C++ ABI require us to skip over the tail-padding of the given class (considering it a...
static bool isAIXLayout(const ASTContext &Context)
static void PrintIndentNoOffset(raw_ostream &OS, unsigned IndentLevel)
static uint64_t roundUpSizeToCharAlignment(uint64_t Size, const ASTContext &Context)
static void PrintOffset(raw_ostream &OS, CharUnits Offset, unsigned IndentLevel)
static unsigned getPaddingDiagFromTagKind(TagTypeKind Tag)
Get diagnostic select index for tag kind for field padding diagnostic message.
static void DumpRecordLayout(raw_ostream &OS, const RecordDecl *RD, const ASTContext &C, CharUnits Offset, unsigned IndentLevel, const char *Description, bool PrintSizeInfo, bool IncludeVirtualBases)
static bool isMsLayout(const ASTContext &Context)
static uint64_t getFieldOffset(const ASTContext &C, const FieldDecl *FD)
static bool RequiresVtordisp(const llvm::SmallPtrSetImpl< const CXXRecordDecl * > &BasesWithOverriddenMethods, const CXXRecordDecl *RD)
static void PrintBitFieldOffset(raw_ostream &OS, CharUnits Offset, unsigned Begin, unsigned Width, unsigned IndentLevel)
static bool recordUsesEBO(const RecordDecl *RD)
SourceLocation Loc
Definition: SemaObjC.cpp:759
SourceLocation Begin
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2915
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
uint64_t getFieldOffset(const ValueDecl *FD) const
Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
void DumpRecordLayout(const RecordDecl *RD, raw_ostream &OS, bool Simple=false) const
const CXXMethodDecl * getCurrentKeyFunction(const CXXRecordDecl *RD)
Get our current best idea for the key function of the given record decl, or nullptr if there isn't on...
const ASTRecordLayout & getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const
Get or compute information about the layout of the specified Objective-C implementation.
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1703
const LangOptions & getLangOpts() const
Definition: ASTContext.h:834
const ASTRecordLayout & getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const
Get or compute information about the layout of the specified Objective-C interface.
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const
bool isNearlyEmpty(const CXXRecordDecl *RD) const
const TargetInfo * getAuxTargetInfo() const
Definition: ASTContext.h:800
CanQualType UnsignedLongTy
Definition: ASTContext.h:1170
TypeInfo getTypeInfo(const Type *T) const
Get the size and alignment of the specified complete type in bits.
bool isAlignmentRequired(const Type *T) const
Determine if the alignment the type has was required using an alignment attribute.
void setNonKeyFunction(const CXXMethodDecl *method)
Observe that the given method cannot be a key function.
TypeInfoChars getTypeInfoInChars(const Type *T) const
int64_t toBits(CharUnits CharSize) const
Convert a size in characters to a size in bits.
uint64_t lookupFieldBitOffset(const ObjCInterfaceDecl *OID, const ObjCImplementationDecl *ID, const ObjCIvarDecl *Ivar) const
Get the offset of an ObjCIvarDecl in bits.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2482
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType UnsignedCharTy
Definition: ASTContext.h:1170
CanQualType UnsignedIntTy
Definition: ASTContext.h:1170
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1171
CanQualType UnsignedShortTy
Definition: ASTContext.h:1170
DiagnosticsEngine & getDiagnostics() const
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:799
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
Definition: ASTContext.h:1274
uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const
Return number of constant array elements.
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2486
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:38
bool endsWithZeroSizedObject() const
Definition: RecordLayout.h:313
bool hasOwnVFPtr() const
hasOwnVFPtr - Does this class provide its own virtual-function table pointer, rather than inheriting ...
Definition: RecordLayout.h:280
CharUnits getAlignment() const
getAlignment - Get the record alignment in characters.
Definition: RecordLayout.h:182
CharUnits getPreferredAlignment() const
getPreferredFieldAlignment - Get the record preferred alignment in characters.
Definition: RecordLayout.h:186
bool hasOwnVBPtr() const
hasOwnVBPtr - Does this class provide its own virtual-base table pointer, rather than inheriting one ...
Definition: RecordLayout.h:300
llvm::DenseMap< const CXXRecordDecl *, VBaseInfo > VBaseOffsetsMapTy
Definition: RecordLayout.h:59
CharUnits getSize() const
getSize - Get the record size in characters.
Definition: RecordLayout.h:193
unsigned getFieldCount() const
getFieldCount - Get the number of fields in the layout.
Definition: RecordLayout.h:196
bool hasVBPtr() const
hasVBPtr - Does this class have a virtual function table pointer.
Definition: RecordLayout.h:306
bool leadsWithZeroSizedBase() const
Definition: RecordLayout.h:317
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
Definition: RecordLayout.h:200
CharUnits getNonVirtualAlignment() const
getNonVirtualAlignment - Get the non-virtual alignment (in chars) of an object, which is the alignmen...
Definition: RecordLayout.h:218
CharUnits getVBPtrOffset() const
getVBPtrOffset - Get the offset for virtual base table pointer.
Definition: RecordLayout.h:324
CharUnits getDataSize() const
getDataSize() - Get the record data size, which is the record size without tail padding,...
Definition: RecordLayout.h:206
CharUnits getRequiredAlignment() const
Definition: RecordLayout.h:311
CharUnits getSizeOfLargestEmptySubobject() const
Definition: RecordLayout.h:268
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:249
CharUnits getPreferredNVAlignment() const
getPreferredNVAlignment - Get the preferred non-virtual alignment (in chars) of an object,...
Definition: RecordLayout.h:227
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const
getVBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:259
const VBaseOffsetsMapTy & getVBaseOffsetsMap() const
Definition: RecordLayout.h:334
const CXXRecordDecl * getPrimaryBase() const
getPrimaryBase - Get the primary base for this record.
Definition: RecordLayout.h:234
bool hasExtendableVFPtr() const
hasVFPtr - Does this class have a virtual function table pointer that can be extended by a derived cl...
Definition: RecordLayout.h:288
bool isPrimaryBaseVirtual() const
isPrimaryBaseVirtual - Get whether the primary base for this record is virtual or not.
Definition: RecordLayout.h:242
CharUnits getNonVirtualSize() const
getNonVirtualSize - Get the non-virtual size (in chars) of an object, which is the size of the object...
Definition: RecordLayout.h:210
This class is used for builtin types like 'int'.
Definition: Type.h:3034
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
A set of all the primary bases for a class.
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2078
overridden_method_range overridden_methods() const
Definition: DeclCXX.cpp:2626
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2204
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
void getIndirectPrimaryBases(CXXIndirectPrimaryBaseSet &Bases) const
Get the indirect primary bases for this class.
bool hasUserDeclaredDestructor() const
Determine whether this class has a user-declared destructor.
Definition: DeclCXX.h:1013
base_class_range bases()
Definition: DeclCXX.h:620
method_range methods() const
Definition: DeclCXX.h:662
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:565
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition: DeclCXX.h:1226
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:1999
base_class_range vbases()
Definition: DeclCXX.h:637
bool isDynamicClass() const
Definition: DeclCXX.h:586
bool isCXX11StandardLayout() const
Determine whether this class was standard-layout per C++11 [class]p7, specifically using the C++11 ru...
Definition: DeclCXX.h:1241
bool hasUserDeclaredConstructor() const
Determine whether this class has any user-declared constructors.
Definition: DeclCXX.h:792
bool isPOD() const
Whether this class is a POD-type (C++ [class]p4)
Definition: DeclCXX.h:1183
MSVtorDispMode getMSVtorDispMode() const
Controls when vtordisps will be emitted if this record is used as a virtual base.
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition: DeclCXX.h:1198
bool isTrivial() const
Determine whether this class is considered trivial.
Definition: DeclCXX.h:1448
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition: DeclCXX.h:635
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:122
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition: CharUnits.h:58
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:63
CharUnits alignTo(const CharUnits &Align) const
alignTo - Returns the next integer (mod 2**64) that is greater than or equal to this quantity and is ...
Definition: CharUnits.h:201
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition: CharUnits.h:53
Complex values, per C99 6.2.5p11.
Definition: Type.h:3145
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3615
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1854
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
Definition: DeclBase.h:1065
T * getAttr() const
Definition: DeclBase.h:576
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition: DeclBase.cpp:534
bool isInvalidDecl() const
Definition: DeclBase.h:591
SourceLocation getLocation() const
Definition: DeclBase.h:442
bool hasAttr() const
Definition: DeclBase.h:580
A little helper class used to produce diagnostics.
Definition: Diagnostic.h:1220
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine a...
Definition: Diagnostic.h:1512
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1493
Abstract interface for external sources of AST nodes.
virtual void CompleteType(TagDecl *Tag)
Gives the external AST source an opportunity to complete an incomplete type.
Represents a member of a struct/union/class.
Definition: Decl.h:3033
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3136
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition: Decl.cpp:4602
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition: Decl.h:3118
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3264
bool isPotentiallyOverlapping() const
Determine if this field is of potentially-overlapping class type, that is, subobject with the [[no_un...
Definition: Decl.cpp:4656
Represents a function declaration or definition.
Definition: Decl.h:1935
bool isInlineSpecified() const
Determine whether the "inline" keyword was specified for this function.
Definition: Decl.h:2774
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3335
ArrayRef< NamedDecl * > chain() const
Definition: Decl.h:3357
@ Ver6
Attempt to be ABI-compatible with code generated by Clang 6.0.x (SVN r321711).
@ Ver15
Attempt to be ABI-compatible with code generated by Clang 15.0.x.
This represents a decl that may have a name.
Definition: Decl.h:253
bool isExternallyVisible() const
Definition: Decl.h:412
ObjCContainerDecl - Represents a container for method declarations.
Definition: DeclObjC.h:947
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2596
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1951
ObjCInterfaceDecl * getContainingInterface()
Return the class interface that this ivar is logically contained in; this is either the interface whe...
Definition: DeclObjC.cpp:1873
ObjCIvarDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition: DeclObjC.h:1990
A (possibly-)qualified type.
Definition: Type.h:929
Represents a struct/union/class.
Definition: Decl.h:4162
bool isMsStruct(const ASTContext &C) const
Get whether or not this is an ms_struct which can be turned on with an attribute, pragma,...
Definition: Decl.cpp:5127
field_range fields() const
Definition: Decl.h:4368
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:6077
RecordDecl * getDecl() const
Definition: Type.h:6087
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:215
Encodes a location in the source.
bool isUnion() const
Definition: Decl.h:3784
The basic abstraction for the target C++ ABI.
Definition: TargetCXXABI.h:28
TailPaddingUseRules getTailPaddingUseRules() const
Definition: TargetCXXABI.h:280
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
bool canKeyFunctionBeInline() const
Can an out-of-line inline function serve as a key function?
Definition: TargetCXXABI.h:238
@ AlwaysUseTailPadding
The tail-padding of a base class is always theoretically available, even if it's POD.
Definition: TargetCXXABI.h:270
@ UseTailPaddingUnlessPOD11
Only allocate objects in the tail padding of a base class if the base class is not POD according to t...
Definition: TargetCXXABI.h:278
@ UseTailPaddingUnlessPOD03
Only allocate objects in the tail padding of a base class if the base class is not POD according to t...
Definition: TargetCXXABI.h:274
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1262
bool useLeadingZeroLengthBitfield() const
Check whether zero length bitfield alignment is respected if they are leading members.
Definition: TargetInfo.h:945
uint64_t getPointerWidth(LangAS AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition: TargetInfo.h:478
virtual bool hasPS4DLLImportExport() const
Definition: TargetInfo.h:1306
virtual bool defaultsToAIXPowerAlignment() const
Whether target defaults to the power alignment rules of AIX.
Definition: TargetInfo.h:1751
unsigned getCharAlign() const
Definition: TargetInfo.h:510
unsigned getZeroLengthBitfieldBoundary() const
Get the fixed alignment value in bits for a member that follows a zero length bitfield.
Definition: TargetInfo.h:951
bool useExplicitBitFieldAlignment() const
Check whether explicit bitfield alignment attributes should be.
Definition: TargetInfo.h:961
uint64_t getPointerAlign(LangAS AddrSpace) const
Definition: TargetInfo.h:482
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1333
unsigned getCharWidth() const
Definition: TargetInfo.h:509
bool useZeroLengthBitfieldAlignment() const
Check whether zero length bitfields should force alignment of the next member.
Definition: TargetInfo.h:939
bool useBitFieldTypeAlignment() const
Check whether the alignment of bit-field types is respected when laying out structures.
Definition: TargetInfo.h:933
The base class of the type hierarchy.
Definition: Type.h:1828
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1916
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8686
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8736
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition: Type.cpp:638
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:671
QualType getType() const
Definition: Decl.h:682
Defines the clang::TargetInfo interface.
bool Zero(InterpState &S, CodePtr OpPC)
Definition: Interp.h:2353
The JSON file list parser is used to communicate input to InstallAPI.
@ External
External linkage, which indicates that the entity can be referred to from other translation units.
@ Result
The result type of a method or function.
TagTypeKind
The kind of a tag type.
Definition: Type.h:6876
@ Interface
The "__interface" keyword.
@ Struct
The "struct" keyword.
@ Class
The "class" keyword.
const FunctionProtoType * T
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1274
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:188
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:206
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:202
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:194
AlignRequirementKind
Definition: ASTContext.h:144
@ None
The alignment was not explicit in code.
@ RequiredByTypedef
The alignment comes from an alignment attribute on a typedef.
@ RequiredByRecord
The alignment comes from an alignment attribute on a record type.
@ Class
The "class" keyword introduces the elaborated-type-specifier.
unsigned long uint64_t
#define false
Definition: stdbool.h:26
bool isValid() const
Whether this pointer is non-NULL.
bool isOffset() const
Whether this pointer is currently stored as an offset.
T * get(ExternalASTSource *Source) const
Retrieve the pointer to the AST node that this lazy pointer points to.
bool isAlignRequired()
Definition: ASTContext.h:167
uint64_t Width
Definition: ASTContext.h:159
unsigned Align
Definition: ASTContext.h:160
All virtual base related information about a given record decl.