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