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