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