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