1 //=== RecordLayoutBuilder.cpp - Helper class for building record layouts ---==//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "clang/AST/RecordLayout.h"
11 #include "clang/AST/ASTContext.h"
12 #include "clang/AST/Attr.h"
13 #include "clang/AST/CXXInheritance.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"
18 #include "clang/Basic/TargetInfo.h"
19 #include "clang/Sema/SemaDiagnostic.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/Support/CrashRecoveryContext.h"
22 #include "llvm/Support/Format.h"
23 #include "llvm/Support/MathExtras.h"
24 
25 using namespace clang;
26 
27 namespace {
28 
29 /// BaseSubobjectInfo - Represents a single base subobject in a complete class.
30 /// For a class hierarchy like
31 ///
32 /// class A { };
33 /// class B : A { };
34 /// class C : A, B { };
35 ///
36 /// The BaseSubobjectInfo graph for C will have three BaseSubobjectInfo
37 /// instances, one for B and two for A.
38 ///
39 /// If a base is virtual, it will only have one BaseSubobjectInfo allocated.
40 struct BaseSubobjectInfo {
41   /// Class - The class for this base info.
42   const CXXRecordDecl *Class;
43 
44   /// IsVirtual - Whether the BaseInfo represents a virtual base or not.
45   bool IsVirtual;
46 
47   /// Bases - Information about the base subobjects.
48   SmallVector<BaseSubobjectInfo*, 4> Bases;
49 
50   /// PrimaryVirtualBaseInfo - Holds the base info for the primary virtual base
51   /// of this base info (if one exists).
52   BaseSubobjectInfo *PrimaryVirtualBaseInfo;
53 
54   // FIXME: Document.
55   const BaseSubobjectInfo *Derived;
56 };
57 
58 /// EmptySubobjectMap - Keeps track of which empty subobjects exist at different
59 /// offsets while laying out a C++ class.
60 class EmptySubobjectMap {
61   const ASTContext &Context;
62   uint64_t CharWidth;
63 
64   /// Class - The class whose empty entries we're keeping track of.
65   const CXXRecordDecl *Class;
66 
67   /// EmptyClassOffsets - A map from offsets to empty record decls.
68   typedef SmallVector<const CXXRecordDecl *, 1> ClassVectorTy;
69   typedef llvm::DenseMap<CharUnits, ClassVectorTy> EmptyClassOffsetsMapTy;
70   EmptyClassOffsetsMapTy EmptyClassOffsets;
71 
72   /// MaxEmptyClassOffset - The highest offset known to contain an empty
73   /// base subobject.
74   CharUnits MaxEmptyClassOffset;
75 
76   /// ComputeEmptySubobjectSizes - Compute the size of the largest base or
77   /// member subobject that is empty.
78   void ComputeEmptySubobjectSizes();
79 
80   void AddSubobjectAtOffset(const CXXRecordDecl *RD, CharUnits Offset);
81 
82   void UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info,
83                                  CharUnits Offset, bool PlacingEmptyBase);
84 
85   void UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD,
86                                   const CXXRecordDecl *Class,
87                                   CharUnits Offset);
88   void UpdateEmptyFieldSubobjects(const FieldDecl *FD, CharUnits Offset);
89 
90   /// AnyEmptySubobjectsBeyondOffset - Returns whether there are any empty
91   /// subobjects beyond the given offset.
92   bool AnyEmptySubobjectsBeyondOffset(CharUnits Offset) const {
93     return Offset <= MaxEmptyClassOffset;
94   }
95 
96   CharUnits
97   getFieldOffset(const ASTRecordLayout &Layout, unsigned FieldNo) const {
98     uint64_t FieldOffset = Layout.getFieldOffset(FieldNo);
99     assert(FieldOffset % CharWidth == 0 &&
100            "Field offset not at char boundary!");
101 
102     return Context.toCharUnitsFromBits(FieldOffset);
103   }
104 
105 protected:
106   bool CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD,
107                                  CharUnits Offset) const;
108 
109   bool CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info,
110                                      CharUnits Offset);
111 
112   bool CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD,
113                                       const CXXRecordDecl *Class,
114                                       CharUnits Offset) const;
115   bool CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD,
116                                       CharUnits Offset) const;
117 
118 public:
119   /// This holds the size of the largest empty subobject (either a base
120   /// or a member). Will be zero if the record being built doesn't contain
121   /// any empty classes.
122   CharUnits SizeOfLargestEmptySubobject;
123 
124   EmptySubobjectMap(const ASTContext &Context, const CXXRecordDecl *Class)
125   : Context(Context), CharWidth(Context.getCharWidth()), Class(Class) {
126       ComputeEmptySubobjectSizes();
127   }
128 
129   /// CanPlaceBaseAtOffset - Return whether the given base class can be placed
130   /// at the given offset.
131   /// Returns false if placing the record will result in two components
132   /// (direct or indirect) of the same type having the same offset.
133   bool CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info,
134                             CharUnits Offset);
135 
136   /// CanPlaceFieldAtOffset - Return whether a field can be placed at the given
137   /// offset.
138   bool CanPlaceFieldAtOffset(const FieldDecl *FD, CharUnits Offset);
139 };
140 
141 void EmptySubobjectMap::ComputeEmptySubobjectSizes() {
142   // Check the bases.
143   for (CXXRecordDecl::base_class_const_iterator I = Class->bases_begin(),
144        E = Class->bases_end(); I != E; ++I) {
145     const CXXRecordDecl *BaseDecl =
146       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
147 
148     CharUnits EmptySize;
149     const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
150     if (BaseDecl->isEmpty()) {
151       // If the class decl is empty, get its size.
152       EmptySize = Layout.getSize();
153     } else {
154       // Otherwise, we get the largest empty subobject for the decl.
155       EmptySize = Layout.getSizeOfLargestEmptySubobject();
156     }
157 
158     if (EmptySize > SizeOfLargestEmptySubobject)
159       SizeOfLargestEmptySubobject = EmptySize;
160   }
161 
162   // Check the fields.
163   for (CXXRecordDecl::field_iterator I = Class->field_begin(),
164        E = Class->field_end(); I != E; ++I) {
165 
166     const RecordType *RT =
167       Context.getBaseElementType(I->getType())->getAs<RecordType>();
168 
169     // We only care about record types.
170     if (!RT)
171       continue;
172 
173     CharUnits EmptySize;
174     const CXXRecordDecl *MemberDecl = cast<CXXRecordDecl>(RT->getDecl());
175     const ASTRecordLayout &Layout = Context.getASTRecordLayout(MemberDecl);
176     if (MemberDecl->isEmpty()) {
177       // If the class decl is empty, get its size.
178       EmptySize = Layout.getSize();
179     } else {
180       // Otherwise, we get the largest empty subobject for the decl.
181       EmptySize = Layout.getSizeOfLargestEmptySubobject();
182     }
183 
184     if (EmptySize > SizeOfLargestEmptySubobject)
185       SizeOfLargestEmptySubobject = EmptySize;
186   }
187 }
188 
189 bool
190 EmptySubobjectMap::CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD,
191                                              CharUnits Offset) const {
192   // We only need to check empty bases.
193   if (!RD->isEmpty())
194     return true;
195 
196   EmptyClassOffsetsMapTy::const_iterator I = EmptyClassOffsets.find(Offset);
197   if (I == EmptyClassOffsets.end())
198     return true;
199 
200   const ClassVectorTy& Classes = I->second;
201   if (std::find(Classes.begin(), Classes.end(), RD) == Classes.end())
202     return true;
203 
204   // There is already an empty class of the same type at this offset.
205   return false;
206 }
207 
208 void EmptySubobjectMap::AddSubobjectAtOffset(const CXXRecordDecl *RD,
209                                              CharUnits Offset) {
210   // We only care about empty bases.
211   if (!RD->isEmpty())
212     return;
213 
214   // If we have empty structures inside a union, we can assign both
215   // the same offset. Just avoid pushing them twice in the list.
216   ClassVectorTy& Classes = EmptyClassOffsets[Offset];
217   if (std::find(Classes.begin(), Classes.end(), RD) != Classes.end())
218     return;
219 
220   Classes.push_back(RD);
221 
222   // Update the empty class offset.
223   if (Offset > MaxEmptyClassOffset)
224     MaxEmptyClassOffset = Offset;
225 }
226 
227 bool
228 EmptySubobjectMap::CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info,
229                                                  CharUnits Offset) {
230   // We don't have to keep looking past the maximum offset that's known to
231   // contain an empty class.
232   if (!AnyEmptySubobjectsBeyondOffset(Offset))
233     return true;
234 
235   if (!CanPlaceSubobjectAtOffset(Info->Class, Offset))
236     return false;
237 
238   // Traverse all non-virtual bases.
239   const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
240   for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) {
241     BaseSubobjectInfo* Base = Info->Bases[I];
242     if (Base->IsVirtual)
243       continue;
244 
245     CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
246 
247     if (!CanPlaceBaseSubobjectAtOffset(Base, BaseOffset))
248       return false;
249   }
250 
251   if (Info->PrimaryVirtualBaseInfo) {
252     BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
253 
254     if (Info == PrimaryVirtualBaseInfo->Derived) {
255       if (!CanPlaceBaseSubobjectAtOffset(PrimaryVirtualBaseInfo, Offset))
256         return false;
257     }
258   }
259 
260   // Traverse all member variables.
261   unsigned FieldNo = 0;
262   for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(),
263        E = Info->Class->field_end(); I != E; ++I, ++FieldNo) {
264     if (I->isBitField())
265       continue;
266 
267     CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
268     if (!CanPlaceFieldSubobjectAtOffset(*I, FieldOffset))
269       return false;
270   }
271 
272   return true;
273 }
274 
275 void EmptySubobjectMap::UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info,
276                                                   CharUnits Offset,
277                                                   bool PlacingEmptyBase) {
278   if (!PlacingEmptyBase && Offset >= SizeOfLargestEmptySubobject) {
279     // We know that the only empty subobjects that can conflict with empty
280     // subobject of non-empty bases, are empty bases that can be placed at
281     // offset zero. Because of this, we only need to keep track of empty base
282     // subobjects with offsets less than the size of the largest empty
283     // subobject for our class.
284     return;
285   }
286 
287   AddSubobjectAtOffset(Info->Class, Offset);
288 
289   // Traverse all non-virtual bases.
290   const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
291   for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) {
292     BaseSubobjectInfo* Base = Info->Bases[I];
293     if (Base->IsVirtual)
294       continue;
295 
296     CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
297     UpdateEmptyBaseSubobjects(Base, BaseOffset, PlacingEmptyBase);
298   }
299 
300   if (Info->PrimaryVirtualBaseInfo) {
301     BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
302 
303     if (Info == PrimaryVirtualBaseInfo->Derived)
304       UpdateEmptyBaseSubobjects(PrimaryVirtualBaseInfo, Offset,
305                                 PlacingEmptyBase);
306   }
307 
308   // Traverse all member variables.
309   unsigned FieldNo = 0;
310   for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(),
311        E = Info->Class->field_end(); I != E; ++I, ++FieldNo) {
312     if (I->isBitField())
313       continue;
314 
315     CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
316     UpdateEmptyFieldSubobjects(*I, FieldOffset);
317   }
318 }
319 
320 bool EmptySubobjectMap::CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info,
321                                              CharUnits Offset) {
322   // If we know this class doesn't have any empty subobjects we don't need to
323   // bother checking.
324   if (SizeOfLargestEmptySubobject.isZero())
325     return true;
326 
327   if (!CanPlaceBaseSubobjectAtOffset(Info, Offset))
328     return false;
329 
330   // We are able to place the base at this offset. Make sure to update the
331   // empty base subobject map.
332   UpdateEmptyBaseSubobjects(Info, Offset, Info->Class->isEmpty());
333   return true;
334 }
335 
336 bool
337 EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD,
338                                                   const CXXRecordDecl *Class,
339                                                   CharUnits Offset) const {
340   // We don't have to keep looking past the maximum offset that's known to
341   // contain an empty class.
342   if (!AnyEmptySubobjectsBeyondOffset(Offset))
343     return true;
344 
345   if (!CanPlaceSubobjectAtOffset(RD, Offset))
346     return false;
347 
348   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
349 
350   // Traverse all non-virtual bases.
351   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
352        E = RD->bases_end(); I != E; ++I) {
353     if (I->isVirtual())
354       continue;
355 
356     const CXXRecordDecl *BaseDecl =
357       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
358 
359     CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
360     if (!CanPlaceFieldSubobjectAtOffset(BaseDecl, Class, BaseOffset))
361       return false;
362   }
363 
364   if (RD == Class) {
365     // This is the most derived class, traverse virtual bases as well.
366     for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
367          E = RD->vbases_end(); I != E; ++I) {
368       const CXXRecordDecl *VBaseDecl =
369         cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
370 
371       CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
372       if (!CanPlaceFieldSubobjectAtOffset(VBaseDecl, Class, VBaseOffset))
373         return false;
374     }
375   }
376 
377   // Traverse all member variables.
378   unsigned FieldNo = 0;
379   for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
380        I != E; ++I, ++FieldNo) {
381     if (I->isBitField())
382       continue;
383 
384     CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
385 
386     if (!CanPlaceFieldSubobjectAtOffset(*I, FieldOffset))
387       return false;
388   }
389 
390   return true;
391 }
392 
393 bool
394 EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD,
395                                                   CharUnits Offset) const {
396   // We don't have to keep looking past the maximum offset that's known to
397   // contain an empty class.
398   if (!AnyEmptySubobjectsBeyondOffset(Offset))
399     return true;
400 
401   QualType T = FD->getType();
402   if (const RecordType *RT = T->getAs<RecordType>()) {
403     const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
404     return CanPlaceFieldSubobjectAtOffset(RD, RD, Offset);
405   }
406 
407   // If we have an array type we need to look at every element.
408   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
409     QualType ElemTy = Context.getBaseElementType(AT);
410     const RecordType *RT = ElemTy->getAs<RecordType>();
411     if (!RT)
412       return true;
413 
414     const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
415     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
416 
417     uint64_t NumElements = Context.getConstantArrayElementCount(AT);
418     CharUnits ElementOffset = Offset;
419     for (uint64_t I = 0; I != NumElements; ++I) {
420       // We don't have to keep looking past the maximum offset that's known to
421       // contain an empty class.
422       if (!AnyEmptySubobjectsBeyondOffset(ElementOffset))
423         return true;
424 
425       if (!CanPlaceFieldSubobjectAtOffset(RD, RD, ElementOffset))
426         return false;
427 
428       ElementOffset += Layout.getSize();
429     }
430   }
431 
432   return true;
433 }
434 
435 bool
436 EmptySubobjectMap::CanPlaceFieldAtOffset(const FieldDecl *FD,
437                                          CharUnits Offset) {
438   if (!CanPlaceFieldSubobjectAtOffset(FD, Offset))
439     return false;
440 
441   // We are able to place the member variable at this offset.
442   // Make sure to update the empty base subobject map.
443   UpdateEmptyFieldSubobjects(FD, Offset);
444   return true;
445 }
446 
447 void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD,
448                                                    const CXXRecordDecl *Class,
449                                                    CharUnits Offset) {
450   // We know that the only empty subobjects that can conflict with empty
451   // field subobjects are subobjects of empty bases that can be placed at offset
452   // zero. Because of this, we only need to keep track of empty field
453   // subobjects with offsets less than the size of the largest empty
454   // subobject for our class.
455   if (Offset >= SizeOfLargestEmptySubobject)
456     return;
457 
458   AddSubobjectAtOffset(RD, Offset);
459 
460   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
461 
462   // Traverse all non-virtual bases.
463   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
464        E = RD->bases_end(); I != E; ++I) {
465     if (I->isVirtual())
466       continue;
467 
468     const CXXRecordDecl *BaseDecl =
469       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
470 
471     CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
472     UpdateEmptyFieldSubobjects(BaseDecl, Class, BaseOffset);
473   }
474 
475   if (RD == Class) {
476     // This is the most derived class, traverse virtual bases as well.
477     for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
478          E = RD->vbases_end(); I != E; ++I) {
479       const CXXRecordDecl *VBaseDecl =
480       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
481 
482       CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
483       UpdateEmptyFieldSubobjects(VBaseDecl, Class, VBaseOffset);
484     }
485   }
486 
487   // Traverse all member variables.
488   unsigned FieldNo = 0;
489   for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
490        I != E; ++I, ++FieldNo) {
491     if (I->isBitField())
492       continue;
493 
494     CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
495 
496     UpdateEmptyFieldSubobjects(*I, FieldOffset);
497   }
498 }
499 
500 void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const FieldDecl *FD,
501                                                    CharUnits Offset) {
502   QualType T = FD->getType();
503   if (const RecordType *RT = T->getAs<RecordType>()) {
504     const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
505     UpdateEmptyFieldSubobjects(RD, RD, Offset);
506     return;
507   }
508 
509   // If we have an array type we need to update every element.
510   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
511     QualType ElemTy = Context.getBaseElementType(AT);
512     const RecordType *RT = ElemTy->getAs<RecordType>();
513     if (!RT)
514       return;
515 
516     const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
517     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
518 
519     uint64_t NumElements = Context.getConstantArrayElementCount(AT);
520     CharUnits ElementOffset = Offset;
521 
522     for (uint64_t I = 0; I != NumElements; ++I) {
523       // We know that the only empty subobjects that can conflict with empty
524       // field subobjects are subobjects of empty bases that can be placed at
525       // offset zero. Because of this, we only need to keep track of empty field
526       // subobjects with offsets less than the size of the largest empty
527       // subobject for our class.
528       if (ElementOffset >= SizeOfLargestEmptySubobject)
529         return;
530 
531       UpdateEmptyFieldSubobjects(RD, RD, ElementOffset);
532       ElementOffset += Layout.getSize();
533     }
534   }
535 }
536 
537 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> ClassSetTy;
538 
539 class RecordLayoutBuilder {
540 protected:
541   // FIXME: Remove this and make the appropriate fields public.
542   friend class clang::ASTContext;
543 
544   const ASTContext &Context;
545 
546   EmptySubobjectMap *EmptySubobjects;
547 
548   /// Size - The current size of the record layout.
549   uint64_t Size;
550 
551   /// Alignment - The current alignment of the record layout.
552   CharUnits Alignment;
553 
554   /// \brief The alignment if attribute packed is not used.
555   CharUnits UnpackedAlignment;
556 
557   SmallVector<uint64_t, 16> FieldOffsets;
558 
559   /// \brief Whether the external AST source has provided a layout for this
560   /// record.
561   unsigned ExternalLayout : 1;
562 
563   /// \brief Whether we need to infer alignment, even when we have an
564   /// externally-provided layout.
565   unsigned InferAlignment : 1;
566 
567   /// Packed - Whether the record is packed or not.
568   unsigned Packed : 1;
569 
570   unsigned IsUnion : 1;
571 
572   unsigned IsMac68kAlign : 1;
573 
574   unsigned IsMsStruct : 1;
575 
576   /// UnfilledBitsInLastUnit - If the last field laid out was a bitfield,
577   /// this contains the number of bits in the last unit that can be used for
578   /// an adjacent bitfield if necessary.  The unit in question is usually
579   /// a byte, but larger units are used if IsMsStruct.
580   unsigned char UnfilledBitsInLastUnit;
581   /// LastBitfieldTypeSize - If IsMsStruct, represents the size of the type
582   /// of the previous field if it was a bitfield.
583   unsigned char LastBitfieldTypeSize;
584 
585   /// MaxFieldAlignment - The maximum allowed field alignment. This is set by
586   /// #pragma pack.
587   CharUnits MaxFieldAlignment;
588 
589   /// DataSize - The data size of the record being laid out.
590   uint64_t DataSize;
591 
592   CharUnits NonVirtualSize;
593   CharUnits NonVirtualAlignment;
594 
595   /// PrimaryBase - the primary base class (if one exists) of the class
596   /// we're laying out.
597   const CXXRecordDecl *PrimaryBase;
598 
599   /// PrimaryBaseIsVirtual - Whether the primary base of the class we're laying
600   /// out is virtual.
601   bool PrimaryBaseIsVirtual;
602 
603   /// HasOwnVFPtr - Whether the class provides its own vtable/vftbl
604   /// pointer, as opposed to inheriting one from a primary base class.
605   bool HasOwnVFPtr;
606 
607   typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
608 
609   /// Bases - base classes and their offsets in the record.
610   BaseOffsetsMapTy Bases;
611 
612   // VBases - virtual base classes and their offsets in the record.
613   ASTRecordLayout::VBaseOffsetsMapTy VBases;
614 
615   /// IndirectPrimaryBases - Virtual base classes, direct or indirect, that are
616   /// primary base classes for some other direct or indirect base class.
617   CXXIndirectPrimaryBaseSet IndirectPrimaryBases;
618 
619   /// FirstNearlyEmptyVBase - The first nearly empty virtual base class in
620   /// inheritance graph order. Used for determining the primary base class.
621   const CXXRecordDecl *FirstNearlyEmptyVBase;
622 
623   /// VisitedVirtualBases - A set of all the visited virtual bases, used to
624   /// avoid visiting virtual bases more than once.
625   llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
626 
627   /// \brief Externally-provided size.
628   uint64_t ExternalSize;
629 
630   /// \brief Externally-provided alignment.
631   uint64_t ExternalAlign;
632 
633   /// \brief Externally-provided field offsets.
634   llvm::DenseMap<const FieldDecl *, uint64_t> ExternalFieldOffsets;
635 
636   /// \brief Externally-provided direct, non-virtual base offsets.
637   llvm::DenseMap<const CXXRecordDecl *, CharUnits> ExternalBaseOffsets;
638 
639   /// \brief Externally-provided virtual base offsets.
640   llvm::DenseMap<const CXXRecordDecl *, CharUnits> ExternalVirtualBaseOffsets;
641 
642   RecordLayoutBuilder(const ASTContext &Context,
643                       EmptySubobjectMap *EmptySubobjects)
644     : Context(Context), EmptySubobjects(EmptySubobjects), Size(0),
645       Alignment(CharUnits::One()), UnpackedAlignment(CharUnits::One()),
646       ExternalLayout(false), InferAlignment(false),
647       Packed(false), IsUnion(false), IsMac68kAlign(false), IsMsStruct(false),
648       UnfilledBitsInLastUnit(0), LastBitfieldTypeSize(0),
649       MaxFieldAlignment(CharUnits::Zero()),
650       DataSize(0), NonVirtualSize(CharUnits::Zero()),
651       NonVirtualAlignment(CharUnits::One()),
652       PrimaryBase(0), PrimaryBaseIsVirtual(false),
653       HasOwnVFPtr(false),
654       FirstNearlyEmptyVBase(0) { }
655 
656   /// Reset this RecordLayoutBuilder to a fresh state, using the given
657   /// alignment as the initial alignment.  This is used for the
658   /// correct layout of vb-table pointers in MSVC.
659   void resetWithTargetAlignment(CharUnits TargetAlignment) {
660     const ASTContext &Context = this->Context;
661     EmptySubobjectMap *EmptySubobjects = this->EmptySubobjects;
662     this->~RecordLayoutBuilder();
663     new (this) RecordLayoutBuilder(Context, EmptySubobjects);
664     Alignment = UnpackedAlignment = TargetAlignment;
665   }
666 
667   void Layout(const RecordDecl *D);
668   void Layout(const CXXRecordDecl *D);
669   void Layout(const ObjCInterfaceDecl *D);
670 
671   void LayoutFields(const RecordDecl *D);
672   void LayoutField(const FieldDecl *D);
673   void LayoutWideBitField(uint64_t FieldSize, uint64_t TypeSize,
674                           bool FieldPacked, const FieldDecl *D);
675   void LayoutBitField(const FieldDecl *D);
676 
677   TargetCXXABI getCXXABI() const {
678     return Context.getTargetInfo().getCXXABI();
679   }
680 
681   /// BaseSubobjectInfoAllocator - Allocator for BaseSubobjectInfo objects.
682   llvm::SpecificBumpPtrAllocator<BaseSubobjectInfo> BaseSubobjectInfoAllocator;
683 
684   typedef llvm::DenseMap<const CXXRecordDecl *, BaseSubobjectInfo *>
685     BaseSubobjectInfoMapTy;
686 
687   /// VirtualBaseInfo - Map from all the (direct or indirect) virtual bases
688   /// of the class we're laying out to their base subobject info.
689   BaseSubobjectInfoMapTy VirtualBaseInfo;
690 
691   /// NonVirtualBaseInfo - Map from all the direct non-virtual bases of the
692   /// class we're laying out to their base subobject info.
693   BaseSubobjectInfoMapTy NonVirtualBaseInfo;
694 
695   /// ComputeBaseSubobjectInfo - Compute the base subobject information for the
696   /// bases of the given class.
697   void ComputeBaseSubobjectInfo(const CXXRecordDecl *RD);
698 
699   /// ComputeBaseSubobjectInfo - Compute the base subobject information for a
700   /// single class and all of its base classes.
701   BaseSubobjectInfo *ComputeBaseSubobjectInfo(const CXXRecordDecl *RD,
702                                               bool IsVirtual,
703                                               BaseSubobjectInfo *Derived);
704 
705   /// DeterminePrimaryBase - Determine the primary base of the given class.
706   void DeterminePrimaryBase(const CXXRecordDecl *RD);
707 
708   void SelectPrimaryVBase(const CXXRecordDecl *RD);
709 
710   void EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign);
711 
712   /// LayoutNonVirtualBases - Determines the primary base class (if any) and
713   /// lays it out. Will then proceed to lay out all non-virtual base clasess.
714   void LayoutNonVirtualBases(const CXXRecordDecl *RD);
715 
716   /// LayoutNonVirtualBase - Lays out a single non-virtual base.
717   void LayoutNonVirtualBase(const BaseSubobjectInfo *Base);
718 
719   void AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
720                                     CharUnits Offset);
721 
722   /// LayoutVirtualBases - Lays out all the virtual bases.
723   void LayoutVirtualBases(const CXXRecordDecl *RD,
724                           const CXXRecordDecl *MostDerivedClass);
725 
726   /// LayoutVirtualBase - Lays out a single virtual base.
727   void LayoutVirtualBase(const BaseSubobjectInfo *Base);
728 
729   /// LayoutBase - Will lay out a base and return the offset where it was
730   /// placed, in chars.
731   CharUnits LayoutBase(const BaseSubobjectInfo *Base);
732 
733   /// InitializeLayout - Initialize record layout for the given record decl.
734   void InitializeLayout(const Decl *D);
735 
736   /// FinishLayout - Finalize record layout. Adjust record size based on the
737   /// alignment.
738   void FinishLayout(const NamedDecl *D);
739 
740   void UpdateAlignment(CharUnits NewAlignment, CharUnits UnpackedNewAlignment);
741   void UpdateAlignment(CharUnits NewAlignment) {
742     UpdateAlignment(NewAlignment, NewAlignment);
743   }
744 
745   /// \brief Retrieve the externally-supplied field offset for the given
746   /// field.
747   ///
748   /// \param Field The field whose offset is being queried.
749   /// \param ComputedOffset The offset that we've computed for this field.
750   uint64_t updateExternalFieldOffset(const FieldDecl *Field,
751                                      uint64_t ComputedOffset);
752 
753   void CheckFieldPadding(uint64_t Offset, uint64_t UnpaddedOffset,
754                           uint64_t UnpackedOffset, unsigned UnpackedAlign,
755                           bool isPacked, const FieldDecl *D);
756 
757   DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
758 
759   CharUnits getSize() const {
760     assert(Size % Context.getCharWidth() == 0);
761     return Context.toCharUnitsFromBits(Size);
762   }
763   uint64_t getSizeInBits() const { return Size; }
764 
765   void setSize(CharUnits NewSize) { Size = Context.toBits(NewSize); }
766   void setSize(uint64_t NewSize) { Size = NewSize; }
767 
768   CharUnits getAligment() const { return Alignment; }
769 
770   CharUnits getDataSize() const {
771     assert(DataSize % Context.getCharWidth() == 0);
772     return Context.toCharUnitsFromBits(DataSize);
773   }
774   uint64_t getDataSizeInBits() const { return DataSize; }
775 
776   void setDataSize(CharUnits NewSize) { DataSize = Context.toBits(NewSize); }
777   void setDataSize(uint64_t NewSize) { DataSize = NewSize; }
778 
779   RecordLayoutBuilder(const RecordLayoutBuilder &) LLVM_DELETED_FUNCTION;
780   void operator=(const RecordLayoutBuilder &) LLVM_DELETED_FUNCTION;
781 };
782 } // end anonymous namespace
783 
784 void
785 RecordLayoutBuilder::SelectPrimaryVBase(const CXXRecordDecl *RD) {
786   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
787          E = RD->bases_end(); I != E; ++I) {
788     assert(!I->getType()->isDependentType() &&
789            "Cannot layout class with dependent bases.");
790 
791     const CXXRecordDecl *Base =
792       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
793 
794     // Check if this is a nearly empty virtual base.
795     if (I->isVirtual() && Context.isNearlyEmpty(Base)) {
796       // If it's not an indirect primary base, then we've found our primary
797       // base.
798       if (!IndirectPrimaryBases.count(Base)) {
799         PrimaryBase = Base;
800         PrimaryBaseIsVirtual = true;
801         return;
802       }
803 
804       // Is this the first nearly empty virtual base?
805       if (!FirstNearlyEmptyVBase)
806         FirstNearlyEmptyVBase = Base;
807     }
808 
809     SelectPrimaryVBase(Base);
810     if (PrimaryBase)
811       return;
812   }
813 }
814 
815 /// DeterminePrimaryBase - Determine the primary base of the given class.
816 void RecordLayoutBuilder::DeterminePrimaryBase(const CXXRecordDecl *RD) {
817   // If the class isn't dynamic, it won't have a primary base.
818   if (!RD->isDynamicClass())
819     return;
820 
821   // Compute all the primary virtual bases for all of our direct and
822   // indirect bases, and record all their primary virtual base classes.
823   RD->getIndirectPrimaryBases(IndirectPrimaryBases);
824 
825   // If the record has a dynamic base class, attempt to choose a primary base
826   // class. It is the first (in direct base class order) non-virtual dynamic
827   // base class, if one exists.
828   for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
829          e = RD->bases_end(); i != e; ++i) {
830     // Ignore virtual bases.
831     if (i->isVirtual())
832       continue;
833 
834     const CXXRecordDecl *Base =
835       cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
836 
837     if (Base->isDynamicClass()) {
838       // We found it.
839       PrimaryBase = Base;
840       PrimaryBaseIsVirtual = false;
841       return;
842     }
843   }
844 
845   // Under the Itanium ABI, if there is no non-virtual primary base class,
846   // try to compute the primary virtual base.  The primary virtual base is
847   // the first nearly empty virtual base that is not an indirect primary
848   // virtual base class, if one exists.
849   if (RD->getNumVBases() != 0) {
850     SelectPrimaryVBase(RD);
851     if (PrimaryBase)
852       return;
853   }
854 
855   // Otherwise, it is the first indirect primary base class, if one exists.
856   if (FirstNearlyEmptyVBase) {
857     PrimaryBase = FirstNearlyEmptyVBase;
858     PrimaryBaseIsVirtual = true;
859     return;
860   }
861 
862   assert(!PrimaryBase && "Should not get here with a primary base!");
863 }
864 
865 BaseSubobjectInfo *
866 RecordLayoutBuilder::ComputeBaseSubobjectInfo(const CXXRecordDecl *RD,
867                                               bool IsVirtual,
868                                               BaseSubobjectInfo *Derived) {
869   BaseSubobjectInfo *Info;
870 
871   if (IsVirtual) {
872     // Check if we already have info about this virtual base.
873     BaseSubobjectInfo *&InfoSlot = VirtualBaseInfo[RD];
874     if (InfoSlot) {
875       assert(InfoSlot->Class == RD && "Wrong class for virtual base info!");
876       return InfoSlot;
877     }
878 
879     // We don't, create it.
880     InfoSlot = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
881     Info = InfoSlot;
882   } else {
883     Info = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
884   }
885 
886   Info->Class = RD;
887   Info->IsVirtual = IsVirtual;
888   Info->Derived = 0;
889   Info->PrimaryVirtualBaseInfo = 0;
890 
891   const CXXRecordDecl *PrimaryVirtualBase = 0;
892   BaseSubobjectInfo *PrimaryVirtualBaseInfo = 0;
893 
894   // Check if this base has a primary virtual base.
895   if (RD->getNumVBases()) {
896     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
897     if (Layout.isPrimaryBaseVirtual()) {
898       // This base does have a primary virtual base.
899       PrimaryVirtualBase = Layout.getPrimaryBase();
900       assert(PrimaryVirtualBase && "Didn't have a primary virtual base!");
901 
902       // Now check if we have base subobject info about this primary base.
903       PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
904 
905       if (PrimaryVirtualBaseInfo) {
906         if (PrimaryVirtualBaseInfo->Derived) {
907           // We did have info about this primary base, and it turns out that it
908           // has already been claimed as a primary virtual base for another
909           // base.
910           PrimaryVirtualBase = 0;
911         } else {
912           // We can claim this base as our primary base.
913           Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
914           PrimaryVirtualBaseInfo->Derived = Info;
915         }
916       }
917     }
918   }
919 
920   // Now go through all direct bases.
921   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
922        E = RD->bases_end(); I != E; ++I) {
923     bool IsVirtual = I->isVirtual();
924 
925     const CXXRecordDecl *BaseDecl =
926       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
927 
928     Info->Bases.push_back(ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, Info));
929   }
930 
931   if (PrimaryVirtualBase && !PrimaryVirtualBaseInfo) {
932     // Traversing the bases must have created the base info for our primary
933     // virtual base.
934     PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
935     assert(PrimaryVirtualBaseInfo &&
936            "Did not create a primary virtual base!");
937 
938     // Claim the primary virtual base as our primary virtual base.
939     Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
940     PrimaryVirtualBaseInfo->Derived = Info;
941   }
942 
943   return Info;
944 }
945 
946 void RecordLayoutBuilder::ComputeBaseSubobjectInfo(const CXXRecordDecl *RD) {
947   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
948        E = RD->bases_end(); I != E; ++I) {
949     bool IsVirtual = I->isVirtual();
950 
951     const CXXRecordDecl *BaseDecl =
952       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
953 
954     // Compute the base subobject info for this base.
955     BaseSubobjectInfo *Info = ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, 0);
956 
957     if (IsVirtual) {
958       // ComputeBaseInfo has already added this base for us.
959       assert(VirtualBaseInfo.count(BaseDecl) &&
960              "Did not add virtual base!");
961     } else {
962       // Add the base info to the map of non-virtual bases.
963       assert(!NonVirtualBaseInfo.count(BaseDecl) &&
964              "Non-virtual base already exists!");
965       NonVirtualBaseInfo.insert(std::make_pair(BaseDecl, Info));
966     }
967   }
968 }
969 
970 void
971 RecordLayoutBuilder::EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign) {
972   CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
973 
974   // The maximum field alignment overrides base align.
975   if (!MaxFieldAlignment.isZero()) {
976     BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
977     UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
978   }
979 
980   // Round up the current record size to pointer alignment.
981   setSize(getSize().RoundUpToAlignment(BaseAlign));
982   setDataSize(getSize());
983 
984   // Update the alignment.
985   UpdateAlignment(BaseAlign, UnpackedBaseAlign);
986 }
987 
988 void
989 RecordLayoutBuilder::LayoutNonVirtualBases(const CXXRecordDecl *RD) {
990   // Then, determine the primary base class.
991   DeterminePrimaryBase(RD);
992 
993   // Compute base subobject info.
994   ComputeBaseSubobjectInfo(RD);
995 
996   // If we have a primary base class, lay it out.
997   if (PrimaryBase) {
998     if (PrimaryBaseIsVirtual) {
999       // If the primary virtual base was a primary virtual base of some other
1000       // base class we'll have to steal it.
1001       BaseSubobjectInfo *PrimaryBaseInfo = VirtualBaseInfo.lookup(PrimaryBase);
1002       PrimaryBaseInfo->Derived = 0;
1003 
1004       // We have a virtual primary base, insert it as an indirect primary base.
1005       IndirectPrimaryBases.insert(PrimaryBase);
1006 
1007       assert(!VisitedVirtualBases.count(PrimaryBase) &&
1008              "vbase already visited!");
1009       VisitedVirtualBases.insert(PrimaryBase);
1010 
1011       LayoutVirtualBase(PrimaryBaseInfo);
1012     } else {
1013       BaseSubobjectInfo *PrimaryBaseInfo =
1014         NonVirtualBaseInfo.lookup(PrimaryBase);
1015       assert(PrimaryBaseInfo &&
1016              "Did not find base info for non-virtual primary base!");
1017 
1018       LayoutNonVirtualBase(PrimaryBaseInfo);
1019     }
1020 
1021   // If this class needs a vtable/vf-table and didn't get one from a
1022   // primary base, add it in now.
1023   } else if (RD->isDynamicClass()) {
1024     assert(DataSize == 0 && "Vtable pointer must be at offset zero!");
1025     CharUnits PtrWidth =
1026       Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
1027     CharUnits PtrAlign =
1028       Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0));
1029     EnsureVTablePointerAlignment(PtrAlign);
1030     HasOwnVFPtr = true;
1031     setSize(getSize() + PtrWidth);
1032     setDataSize(getSize());
1033   }
1034 
1035   // Now lay out the non-virtual bases.
1036   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1037          E = RD->bases_end(); I != E; ++I) {
1038 
1039     // Ignore virtual bases.
1040     if (I->isVirtual())
1041       continue;
1042 
1043     const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
1044 
1045     // Skip the primary base, because we've already laid it out.  The
1046     // !PrimaryBaseIsVirtual check is required because we might have a
1047     // non-virtual base of the same type as a primary virtual base.
1048     if (BaseDecl == PrimaryBase && !PrimaryBaseIsVirtual)
1049       continue;
1050 
1051     // Lay out the base.
1052     BaseSubobjectInfo *BaseInfo = NonVirtualBaseInfo.lookup(BaseDecl);
1053     assert(BaseInfo && "Did not find base info for non-virtual base!");
1054 
1055     LayoutNonVirtualBase(BaseInfo);
1056   }
1057 }
1058 
1059 void RecordLayoutBuilder::LayoutNonVirtualBase(const BaseSubobjectInfo *Base) {
1060   // Layout the base.
1061   CharUnits Offset = LayoutBase(Base);
1062 
1063   // Add its base class offset.
1064   assert(!Bases.count(Base->Class) && "base offset already exists!");
1065   Bases.insert(std::make_pair(Base->Class, Offset));
1066 
1067   AddPrimaryVirtualBaseOffsets(Base, Offset);
1068 }
1069 
1070 void
1071 RecordLayoutBuilder::AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
1072                                                   CharUnits Offset) {
1073   // This base isn't interesting, it has no virtual bases.
1074   if (!Info->Class->getNumVBases())
1075     return;
1076 
1077   // First, check if we have a virtual primary base to add offsets for.
1078   if (Info->PrimaryVirtualBaseInfo) {
1079     assert(Info->PrimaryVirtualBaseInfo->IsVirtual &&
1080            "Primary virtual base is not virtual!");
1081     if (Info->PrimaryVirtualBaseInfo->Derived == Info) {
1082       // Add the offset.
1083       assert(!VBases.count(Info->PrimaryVirtualBaseInfo->Class) &&
1084              "primary vbase offset already exists!");
1085       VBases.insert(std::make_pair(Info->PrimaryVirtualBaseInfo->Class,
1086                                    ASTRecordLayout::VBaseInfo(Offset, false)));
1087 
1088       // Traverse the primary virtual base.
1089       AddPrimaryVirtualBaseOffsets(Info->PrimaryVirtualBaseInfo, Offset);
1090     }
1091   }
1092 
1093   // Now go through all direct non-virtual bases.
1094   const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
1095   for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) {
1096     const BaseSubobjectInfo *Base = Info->Bases[I];
1097     if (Base->IsVirtual)
1098       continue;
1099 
1100     CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
1101     AddPrimaryVirtualBaseOffsets(Base, BaseOffset);
1102   }
1103 }
1104 
1105 void
1106 RecordLayoutBuilder::LayoutVirtualBases(const CXXRecordDecl *RD,
1107                                         const CXXRecordDecl *MostDerivedClass) {
1108   const CXXRecordDecl *PrimaryBase;
1109   bool PrimaryBaseIsVirtual;
1110 
1111   if (MostDerivedClass == RD) {
1112     PrimaryBase = this->PrimaryBase;
1113     PrimaryBaseIsVirtual = this->PrimaryBaseIsVirtual;
1114   } else {
1115     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1116     PrimaryBase = Layout.getPrimaryBase();
1117     PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
1118   }
1119 
1120   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1121          E = RD->bases_end(); I != E; ++I) {
1122     assert(!I->getType()->isDependentType() &&
1123            "Cannot layout class with dependent bases.");
1124 
1125     const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
1126 
1127     if (I->isVirtual()) {
1128       if (PrimaryBase != BaseDecl || !PrimaryBaseIsVirtual) {
1129         bool IndirectPrimaryBase = IndirectPrimaryBases.count(BaseDecl);
1130 
1131         // Only lay out the virtual base if it's not an indirect primary base.
1132         if (!IndirectPrimaryBase) {
1133           // Only visit virtual bases once.
1134           if (!VisitedVirtualBases.insert(BaseDecl))
1135             continue;
1136 
1137           const BaseSubobjectInfo *BaseInfo = VirtualBaseInfo.lookup(BaseDecl);
1138           assert(BaseInfo && "Did not find virtual base info!");
1139           LayoutVirtualBase(BaseInfo);
1140         }
1141       }
1142     }
1143 
1144     if (!BaseDecl->getNumVBases()) {
1145       // This base isn't interesting since it doesn't have any virtual bases.
1146       continue;
1147     }
1148 
1149     LayoutVirtualBases(BaseDecl, MostDerivedClass);
1150   }
1151 }
1152 
1153 void RecordLayoutBuilder::LayoutVirtualBase(const BaseSubobjectInfo *Base) {
1154   assert(!Base->Derived && "Trying to lay out a primary virtual base!");
1155 
1156   // Layout the base.
1157   CharUnits Offset = LayoutBase(Base);
1158 
1159   // Add its base class offset.
1160   assert(!VBases.count(Base->Class) && "vbase offset already exists!");
1161   VBases.insert(std::make_pair(Base->Class,
1162                        ASTRecordLayout::VBaseInfo(Offset, false)));
1163 
1164   AddPrimaryVirtualBaseOffsets(Base, Offset);
1165 }
1166 
1167 CharUnits RecordLayoutBuilder::LayoutBase(const BaseSubobjectInfo *Base) {
1168   const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base->Class);
1169 
1170 
1171   CharUnits Offset;
1172 
1173   // Query the external layout to see if it provides an offset.
1174   bool HasExternalLayout = false;
1175   if (ExternalLayout) {
1176     llvm::DenseMap<const CXXRecordDecl *, CharUnits>::iterator Known;
1177     if (Base->IsVirtual) {
1178       Known = ExternalVirtualBaseOffsets.find(Base->Class);
1179       if (Known != ExternalVirtualBaseOffsets.end()) {
1180         Offset = Known->second;
1181         HasExternalLayout = true;
1182       }
1183     } else {
1184       Known = ExternalBaseOffsets.find(Base->Class);
1185       if (Known != ExternalBaseOffsets.end()) {
1186         Offset = Known->second;
1187         HasExternalLayout = true;
1188       }
1189     }
1190   }
1191 
1192   CharUnits UnpackedBaseAlign = Layout.getNonVirtualAlignment();
1193   CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
1194 
1195   // If we have an empty base class, try to place it at offset 0.
1196   if (Base->Class->isEmpty() &&
1197       (!HasExternalLayout || Offset == CharUnits::Zero()) &&
1198       EmptySubobjects->CanPlaceBaseAtOffset(Base, CharUnits::Zero())) {
1199     setSize(std::max(getSize(), Layout.getSize()));
1200     UpdateAlignment(BaseAlign, UnpackedBaseAlign);
1201 
1202     return CharUnits::Zero();
1203   }
1204 
1205   // The maximum field alignment overrides base align.
1206   if (!MaxFieldAlignment.isZero()) {
1207     BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
1208     UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
1209   }
1210 
1211   if (!HasExternalLayout) {
1212     // Round up the current record size to the base's alignment boundary.
1213     Offset = getDataSize().RoundUpToAlignment(BaseAlign);
1214 
1215     // Try to place the base.
1216     while (!EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset))
1217       Offset += BaseAlign;
1218   } else {
1219     bool Allowed = EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset);
1220     (void)Allowed;
1221     assert(Allowed && "Base subobject externally placed at overlapping offset");
1222 
1223     if (InferAlignment && Offset < getDataSize().RoundUpToAlignment(BaseAlign)){
1224       // The externally-supplied base offset is before the base offset we
1225       // computed. Assume that the structure is packed.
1226       Alignment = CharUnits::One();
1227       InferAlignment = false;
1228     }
1229   }
1230 
1231   if (!Base->Class->isEmpty()) {
1232     // Update the data size.
1233     setDataSize(Offset + Layout.getNonVirtualSize());
1234 
1235     setSize(std::max(getSize(), getDataSize()));
1236   } else
1237     setSize(std::max(getSize(), Offset + Layout.getSize()));
1238 
1239   // Remember max struct/class alignment.
1240   UpdateAlignment(BaseAlign, UnpackedBaseAlign);
1241 
1242   return Offset;
1243 }
1244 
1245 void RecordLayoutBuilder::InitializeLayout(const Decl *D) {
1246   if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
1247     IsUnion = RD->isUnion();
1248     IsMsStruct = RD->isMsStruct(Context);
1249   }
1250 
1251   Packed = D->hasAttr<PackedAttr>();
1252 
1253   // Honor the default struct packing maximum alignment flag.
1254   if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct) {
1255     MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
1256   }
1257 
1258   // mac68k alignment supersedes maximum field alignment and attribute aligned,
1259   // and forces all structures to have 2-byte alignment. The IBM docs on it
1260   // allude to additional (more complicated) semantics, especially with regard
1261   // to bit-fields, but gcc appears not to follow that.
1262   if (D->hasAttr<AlignMac68kAttr>()) {
1263     IsMac68kAlign = true;
1264     MaxFieldAlignment = CharUnits::fromQuantity(2);
1265     Alignment = CharUnits::fromQuantity(2);
1266   } else {
1267     if (const MaxFieldAlignmentAttr *MFAA = D->getAttr<MaxFieldAlignmentAttr>())
1268       MaxFieldAlignment = Context.toCharUnitsFromBits(MFAA->getAlignment());
1269 
1270     if (unsigned MaxAlign = D->getMaxAlignment())
1271       UpdateAlignment(Context.toCharUnitsFromBits(MaxAlign));
1272   }
1273 
1274   // If there is an external AST source, ask it for the various offsets.
1275   if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
1276     if (ExternalASTSource *External = Context.getExternalSource()) {
1277       ExternalLayout = External->layoutRecordType(RD,
1278                                                   ExternalSize,
1279                                                   ExternalAlign,
1280                                                   ExternalFieldOffsets,
1281                                                   ExternalBaseOffsets,
1282                                                   ExternalVirtualBaseOffsets);
1283 
1284       // Update based on external alignment.
1285       if (ExternalLayout) {
1286         if (ExternalAlign > 0) {
1287           Alignment = Context.toCharUnitsFromBits(ExternalAlign);
1288         } else {
1289           // The external source didn't have alignment information; infer it.
1290           InferAlignment = true;
1291         }
1292       }
1293     }
1294 }
1295 
1296 void RecordLayoutBuilder::Layout(const RecordDecl *D) {
1297   InitializeLayout(D);
1298   LayoutFields(D);
1299 
1300   // Finally, round the size of the total struct up to the alignment of the
1301   // struct itself.
1302   FinishLayout(D);
1303 }
1304 
1305 void RecordLayoutBuilder::Layout(const CXXRecordDecl *RD) {
1306   InitializeLayout(RD);
1307 
1308   // Lay out the vtable and the non-virtual bases.
1309   LayoutNonVirtualBases(RD);
1310 
1311   LayoutFields(RD);
1312 
1313   NonVirtualSize = Context.toCharUnitsFromBits(
1314         llvm::RoundUpToAlignment(getSizeInBits(),
1315                                  Context.getTargetInfo().getCharAlign()));
1316   NonVirtualAlignment = Alignment;
1317 
1318   // Lay out the virtual bases and add the primary virtual base offsets.
1319   LayoutVirtualBases(RD, RD);
1320 
1321   // Finally, round the size of the total struct up to the alignment
1322   // of the struct itself.
1323   FinishLayout(RD);
1324 
1325 #ifndef NDEBUG
1326   // Check that we have base offsets for all bases.
1327   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1328        E = RD->bases_end(); I != E; ++I) {
1329     if (I->isVirtual())
1330       continue;
1331 
1332     const CXXRecordDecl *BaseDecl =
1333       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1334 
1335     assert(Bases.count(BaseDecl) && "Did not find base offset!");
1336   }
1337 
1338   // And all virtual bases.
1339   for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
1340        E = RD->vbases_end(); I != E; ++I) {
1341     const CXXRecordDecl *BaseDecl =
1342       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1343 
1344     assert(VBases.count(BaseDecl) && "Did not find base offset!");
1345   }
1346 #endif
1347 }
1348 
1349 void RecordLayoutBuilder::Layout(const ObjCInterfaceDecl *D) {
1350   if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
1351     const ASTRecordLayout &SL = Context.getASTObjCInterfaceLayout(SD);
1352 
1353     UpdateAlignment(SL.getAlignment());
1354 
1355     // We start laying out ivars not at the end of the superclass
1356     // structure, but at the next byte following the last field.
1357     setSize(SL.getDataSize());
1358     setDataSize(getSize());
1359   }
1360 
1361   InitializeLayout(D);
1362   // Layout each ivar sequentially.
1363   for (const ObjCIvarDecl *IVD = D->all_declared_ivar_begin(); IVD;
1364        IVD = IVD->getNextIvar())
1365     LayoutField(IVD);
1366 
1367   // Finally, round the size of the total struct up to the alignment of the
1368   // struct itself.
1369   FinishLayout(D);
1370 }
1371 
1372 void RecordLayoutBuilder::LayoutFields(const RecordDecl *D) {
1373   // Layout each field, for now, just sequentially, respecting alignment.  In
1374   // the future, this will need to be tweakable by targets.
1375   for (RecordDecl::field_iterator Field = D->field_begin(),
1376        FieldEnd = D->field_end(); Field != FieldEnd; ++Field)
1377     LayoutField(*Field);
1378 }
1379 
1380 void RecordLayoutBuilder::LayoutWideBitField(uint64_t FieldSize,
1381                                              uint64_t TypeSize,
1382                                              bool FieldPacked,
1383                                              const FieldDecl *D) {
1384   assert(Context.getLangOpts().CPlusPlus &&
1385          "Can only have wide bit-fields in C++!");
1386 
1387   // Itanium C++ ABI 2.4:
1388   //   If sizeof(T)*8 < n, let T' be the largest integral POD type with
1389   //   sizeof(T')*8 <= n.
1390 
1391   QualType IntegralPODTypes[] = {
1392     Context.UnsignedCharTy, Context.UnsignedShortTy, Context.UnsignedIntTy,
1393     Context.UnsignedLongTy, Context.UnsignedLongLongTy
1394   };
1395 
1396   QualType Type;
1397   for (unsigned I = 0, E = llvm::array_lengthof(IntegralPODTypes);
1398        I != E; ++I) {
1399     uint64_t Size = Context.getTypeSize(IntegralPODTypes[I]);
1400 
1401     if (Size > FieldSize)
1402       break;
1403 
1404     Type = IntegralPODTypes[I];
1405   }
1406   assert(!Type.isNull() && "Did not find a type!");
1407 
1408   CharUnits TypeAlign = Context.getTypeAlignInChars(Type);
1409 
1410   // We're not going to use any of the unfilled bits in the last byte.
1411   UnfilledBitsInLastUnit = 0;
1412   LastBitfieldTypeSize = 0;
1413 
1414   uint64_t FieldOffset;
1415   uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
1416 
1417   if (IsUnion) {
1418     setDataSize(std::max(getDataSizeInBits(), FieldSize));
1419     FieldOffset = 0;
1420   } else {
1421     // The bitfield is allocated starting at the next offset aligned
1422     // appropriately for T', with length n bits.
1423     FieldOffset = llvm::RoundUpToAlignment(getDataSizeInBits(),
1424                                            Context.toBits(TypeAlign));
1425 
1426     uint64_t NewSizeInBits = FieldOffset + FieldSize;
1427 
1428     setDataSize(llvm::RoundUpToAlignment(NewSizeInBits,
1429                                          Context.getTargetInfo().getCharAlign()));
1430     UnfilledBitsInLastUnit = getDataSizeInBits() - NewSizeInBits;
1431   }
1432 
1433   // Place this field at the current location.
1434   FieldOffsets.push_back(FieldOffset);
1435 
1436   CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, FieldOffset,
1437                     Context.toBits(TypeAlign), FieldPacked, D);
1438 
1439   // Update the size.
1440   setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1441 
1442   // Remember max struct/class alignment.
1443   UpdateAlignment(TypeAlign);
1444 }
1445 
1446 void RecordLayoutBuilder::LayoutBitField(const FieldDecl *D) {
1447   bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
1448   uint64_t FieldSize = D->getBitWidthValue(Context);
1449   std::pair<uint64_t, unsigned> FieldInfo = Context.getTypeInfo(D->getType());
1450   uint64_t TypeSize = FieldInfo.first;
1451   unsigned FieldAlign = FieldInfo.second;
1452 
1453   // UnfilledBitsInLastUnit is the difference between the end of the
1454   // last allocated bitfield (i.e. the first bit offset available for
1455   // bitfields) and the end of the current data size in bits (i.e. the
1456   // first bit offset available for non-bitfields).  The current data
1457   // size in bits is always a multiple of the char size; additionally,
1458   // for ms_struct records it's also a multiple of the
1459   // LastBitfieldTypeSize (if set).
1460 
1461   // The basic bitfield layout rule for ms_struct is to allocate an
1462   // entire unit of the bitfield's declared type (e.g. 'unsigned
1463   // long'), then parcel it up among successive bitfields whose
1464   // declared types have the same size, making a new unit as soon as
1465   // the last can no longer store the whole value.
1466 
1467   // The standard bitfield layout rule for non-ms_struct is to place
1468   // bitfields at the next available bit offset where the entire
1469   // bitfield would fit in an aligned storage unit of the declared
1470   // type (even if there are also non-bitfields within that same
1471   // unit).  However, some targets (those that !useBitFieldTypeAlignment())
1472   // don't require this storage unit to be aligned, and therefore
1473   // always put the bit-field at the next available bit offset.
1474   // Such targets generally do interpret zero-width bitfields as
1475   // forcing the use of a new storage unit.
1476 
1477   // First, some simple bookkeeping to perform for ms_struct structs.
1478   if (IsMsStruct) {
1479     // The field alignment for integer types is always the size.
1480     FieldAlign = TypeSize;
1481 
1482     // If the previous field was not a bitfield, or was a bitfield
1483     // with a different storage unit size, we're done with that
1484     // storage unit.
1485     if (LastBitfieldTypeSize != TypeSize) {
1486       // Also, ignore zero-length bitfields after non-bitfields.
1487       if (!LastBitfieldTypeSize && !FieldSize)
1488         FieldAlign = 1;
1489 
1490       UnfilledBitsInLastUnit = 0;
1491       LastBitfieldTypeSize = 0;
1492     }
1493   }
1494 
1495   // If the field is wider than its declared type, it follows
1496   // different rules in all cases.
1497   if (FieldSize > TypeSize) {
1498     LayoutWideBitField(FieldSize, TypeSize, FieldPacked, D);
1499     return;
1500   }
1501 
1502   // Compute the next available bit offset.
1503   uint64_t FieldOffset =
1504     IsUnion ? 0 : (getDataSizeInBits() - UnfilledBitsInLastUnit);
1505 
1506   // Handle targets that don't honor bitfield type alignment.
1507   if (!Context.getTargetInfo().useBitFieldTypeAlignment()) {
1508     // Some such targets do honor it on zero-width bitfields.
1509     if (FieldSize == 0 &&
1510         Context.getTargetInfo().useZeroLengthBitfieldAlignment()) {
1511       // The alignment to round up to is the max of the field's natural
1512       // alignment and a target-specific fixed value (sometimes zero).
1513       unsigned ZeroLengthBitfieldBoundary =
1514         Context.getTargetInfo().getZeroLengthBitfieldBoundary();
1515       FieldAlign = std::max(FieldAlign, ZeroLengthBitfieldBoundary);
1516 
1517     // If that doesn't apply, just ignore the field alignment.
1518     } else {
1519       FieldAlign = 1;
1520     }
1521   }
1522 
1523   // Remember the alignment we would have used if the field were not packed.
1524   unsigned UnpackedFieldAlign = FieldAlign;
1525 
1526   // Ignore the field alignment if the field is packed.
1527   if (FieldPacked)
1528     FieldAlign = 1;
1529 
1530   // But, if there's an 'aligned' attribute on the field, honor that.
1531   if (unsigned ExplicitFieldAlign = D->getMaxAlignment()) {
1532     FieldAlign = std::max(FieldAlign, ExplicitFieldAlign);
1533     UnpackedFieldAlign = std::max(UnpackedFieldAlign, ExplicitFieldAlign);
1534   }
1535 
1536   // But, if there's a #pragma pack in play, that takes precedent over
1537   // even the 'aligned' attribute, for non-zero-width bitfields.
1538   if (!MaxFieldAlignment.isZero() && FieldSize) {
1539     unsigned MaxFieldAlignmentInBits = Context.toBits(MaxFieldAlignment);
1540     FieldAlign = std::min(FieldAlign, MaxFieldAlignmentInBits);
1541     UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignmentInBits);
1542   }
1543 
1544   // For purposes of diagnostics, we're going to simultaneously
1545   // compute the field offsets that we would have used if we weren't
1546   // adding any alignment padding or if the field weren't packed.
1547   uint64_t UnpaddedFieldOffset = FieldOffset;
1548   uint64_t UnpackedFieldOffset = FieldOffset;
1549 
1550   // Check if we need to add padding to fit the bitfield within an
1551   // allocation unit with the right size and alignment.  The rules are
1552   // somewhat different here for ms_struct structs.
1553   if (IsMsStruct) {
1554     // If it's not a zero-width bitfield, and we can fit the bitfield
1555     // into the active storage unit (and we haven't already decided to
1556     // start a new storage unit), just do so, regardless of any other
1557     // other consideration.  Otherwise, round up to the right alignment.
1558     if (FieldSize == 0 || FieldSize > UnfilledBitsInLastUnit) {
1559       FieldOffset = llvm::RoundUpToAlignment(FieldOffset, FieldAlign);
1560       UnpackedFieldOffset = llvm::RoundUpToAlignment(UnpackedFieldOffset,
1561                                                      UnpackedFieldAlign);
1562       UnfilledBitsInLastUnit = 0;
1563     }
1564 
1565   } else {
1566     // #pragma pack, with any value, suppresses the insertion of padding.
1567     bool AllowPadding = MaxFieldAlignment.isZero();
1568 
1569     // Compute the real offset.
1570     if (FieldSize == 0 ||
1571         (AllowPadding &&
1572          (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize)) {
1573       FieldOffset = llvm::RoundUpToAlignment(FieldOffset, FieldAlign);
1574     }
1575 
1576     // Repeat the computation for diagnostic purposes.
1577     if (FieldSize == 0 ||
1578         (AllowPadding &&
1579          (UnpackedFieldOffset & (UnpackedFieldAlign-1)) + FieldSize > TypeSize))
1580       UnpackedFieldOffset = llvm::RoundUpToAlignment(UnpackedFieldOffset,
1581                                                      UnpackedFieldAlign);
1582   }
1583 
1584   // If we're using external layout, give the external layout a chance
1585   // to override this information.
1586   if (ExternalLayout)
1587     FieldOffset = updateExternalFieldOffset(D, FieldOffset);
1588 
1589   // Okay, place the bitfield at the calculated offset.
1590   FieldOffsets.push_back(FieldOffset);
1591 
1592   // Bookkeeping:
1593 
1594   // Anonymous members don't affect the overall record alignment,
1595   // except on targets where they do.
1596   if (!IsMsStruct &&
1597       !Context.getTargetInfo().useZeroLengthBitfieldAlignment() &&
1598       !D->getIdentifier())
1599     FieldAlign = UnpackedFieldAlign = 1;
1600 
1601   // Diagnose differences in layout due to padding or packing.
1602   if (!ExternalLayout)
1603     CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, UnpackedFieldOffset,
1604                       UnpackedFieldAlign, FieldPacked, D);
1605 
1606   // Update DataSize to include the last byte containing (part of) the bitfield.
1607 
1608   // For unions, this is just a max operation, as usual.
1609   if (IsUnion) {
1610     // FIXME: I think FieldSize should be TypeSize here.
1611     setDataSize(std::max(getDataSizeInBits(), FieldSize));
1612 
1613   // For non-zero-width bitfields in ms_struct structs, allocate a new
1614   // storage unit if necessary.
1615   } else if (IsMsStruct && FieldSize) {
1616     // We should have cleared UnfilledBitsInLastUnit in every case
1617     // where we changed storage units.
1618     if (!UnfilledBitsInLastUnit) {
1619       setDataSize(FieldOffset + TypeSize);
1620       UnfilledBitsInLastUnit = TypeSize;
1621     }
1622     UnfilledBitsInLastUnit -= FieldSize;
1623     LastBitfieldTypeSize = TypeSize;
1624 
1625   // Otherwise, bump the data size up to include the bitfield,
1626   // including padding up to char alignment, and then remember how
1627   // bits we didn't use.
1628   } else {
1629     uint64_t NewSizeInBits = FieldOffset + FieldSize;
1630     uint64_t CharAlignment = Context.getTargetInfo().getCharAlign();
1631     setDataSize(llvm::RoundUpToAlignment(NewSizeInBits, CharAlignment));
1632     UnfilledBitsInLastUnit = getDataSizeInBits() - NewSizeInBits;
1633 
1634     // The only time we can get here for an ms_struct is if this is a
1635     // zero-width bitfield, which doesn't count as anything for the
1636     // purposes of unfilled bits.
1637     LastBitfieldTypeSize = 0;
1638   }
1639 
1640   // Update the size.
1641   setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1642 
1643   // Remember max struct/class alignment.
1644   UpdateAlignment(Context.toCharUnitsFromBits(FieldAlign),
1645                   Context.toCharUnitsFromBits(UnpackedFieldAlign));
1646 }
1647 
1648 void RecordLayoutBuilder::LayoutField(const FieldDecl *D) {
1649   if (D->isBitField()) {
1650     LayoutBitField(D);
1651     return;
1652   }
1653 
1654   uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
1655 
1656   // Reset the unfilled bits.
1657   UnfilledBitsInLastUnit = 0;
1658   LastBitfieldTypeSize = 0;
1659 
1660   bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
1661   CharUnits FieldOffset =
1662     IsUnion ? CharUnits::Zero() : getDataSize();
1663   CharUnits FieldSize;
1664   CharUnits FieldAlign;
1665 
1666   if (D->getType()->isIncompleteArrayType()) {
1667     // This is a flexible array member; we can't directly
1668     // query getTypeInfo about these, so we figure it out here.
1669     // Flexible array members don't have any size, but they
1670     // have to be aligned appropriately for their element type.
1671     FieldSize = CharUnits::Zero();
1672     const ArrayType* ATy = Context.getAsArrayType(D->getType());
1673     FieldAlign = Context.getTypeAlignInChars(ATy->getElementType());
1674   } else if (const ReferenceType *RT = D->getType()->getAs<ReferenceType>()) {
1675     unsigned AS = RT->getPointeeType().getAddressSpace();
1676     FieldSize =
1677       Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(AS));
1678     FieldAlign =
1679       Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(AS));
1680   } else {
1681     std::pair<CharUnits, CharUnits> FieldInfo =
1682       Context.getTypeInfoInChars(D->getType());
1683     FieldSize = FieldInfo.first;
1684     FieldAlign = FieldInfo.second;
1685 
1686     if (IsMsStruct) {
1687       // If MS bitfield layout is required, figure out what type is being
1688       // laid out and align the field to the width of that type.
1689 
1690       // Resolve all typedefs down to their base type and round up the field
1691       // alignment if necessary.
1692       QualType T = Context.getBaseElementType(D->getType());
1693       if (const BuiltinType *BTy = T->getAs<BuiltinType>()) {
1694         CharUnits TypeSize = Context.getTypeSizeInChars(BTy);
1695         if (TypeSize > FieldAlign)
1696           FieldAlign = TypeSize;
1697       }
1698     }
1699   }
1700 
1701   // The align if the field is not packed. This is to check if the attribute
1702   // was unnecessary (-Wpacked).
1703   CharUnits UnpackedFieldAlign = FieldAlign;
1704   CharUnits UnpackedFieldOffset = FieldOffset;
1705 
1706   if (FieldPacked)
1707     FieldAlign = CharUnits::One();
1708   CharUnits MaxAlignmentInChars =
1709     Context.toCharUnitsFromBits(D->getMaxAlignment());
1710   FieldAlign = std::max(FieldAlign, MaxAlignmentInChars);
1711   UnpackedFieldAlign = std::max(UnpackedFieldAlign, MaxAlignmentInChars);
1712 
1713   // The maximum field alignment overrides the aligned attribute.
1714   if (!MaxFieldAlignment.isZero()) {
1715     FieldAlign = std::min(FieldAlign, MaxFieldAlignment);
1716     UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignment);
1717   }
1718 
1719   // Round up the current record size to the field's alignment boundary.
1720   FieldOffset = FieldOffset.RoundUpToAlignment(FieldAlign);
1721   UnpackedFieldOffset =
1722     UnpackedFieldOffset.RoundUpToAlignment(UnpackedFieldAlign);
1723 
1724   if (ExternalLayout) {
1725     FieldOffset = Context.toCharUnitsFromBits(
1726                     updateExternalFieldOffset(D, Context.toBits(FieldOffset)));
1727 
1728     if (!IsUnion && EmptySubobjects) {
1729       // Record the fact that we're placing a field at this offset.
1730       bool Allowed = EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset);
1731       (void)Allowed;
1732       assert(Allowed && "Externally-placed field cannot be placed here");
1733     }
1734   } else {
1735     if (!IsUnion && EmptySubobjects) {
1736       // Check if we can place the field at this offset.
1737       while (!EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset)) {
1738         // We couldn't place the field at the offset. Try again at a new offset.
1739         FieldOffset += FieldAlign;
1740       }
1741     }
1742   }
1743 
1744   // Place this field at the current location.
1745   FieldOffsets.push_back(Context.toBits(FieldOffset));
1746 
1747   if (!ExternalLayout)
1748     CheckFieldPadding(Context.toBits(FieldOffset), UnpaddedFieldOffset,
1749                       Context.toBits(UnpackedFieldOffset),
1750                       Context.toBits(UnpackedFieldAlign), FieldPacked, D);
1751 
1752   // Reserve space for this field.
1753   uint64_t FieldSizeInBits = Context.toBits(FieldSize);
1754   if (IsUnion)
1755     setDataSize(std::max(getDataSizeInBits(), FieldSizeInBits));
1756   else
1757     setDataSize(FieldOffset + FieldSize);
1758 
1759   // Update the size.
1760   setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1761 
1762   // Remember max struct/class alignment.
1763   UpdateAlignment(FieldAlign, UnpackedFieldAlign);
1764 }
1765 
1766 void RecordLayoutBuilder::FinishLayout(const NamedDecl *D) {
1767   // In C++, records cannot be of size 0.
1768   if (Context.getLangOpts().CPlusPlus && getSizeInBits() == 0) {
1769     if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
1770       // Compatibility with gcc requires a class (pod or non-pod)
1771       // which is not empty but of size 0; such as having fields of
1772       // array of zero-length, remains of Size 0
1773       if (RD->isEmpty())
1774         setSize(CharUnits::One());
1775     }
1776     else
1777       setSize(CharUnits::One());
1778   }
1779 
1780   // Finally, round the size of the record up to the alignment of the
1781   // record itself.
1782   uint64_t UnpaddedSize = getSizeInBits() - UnfilledBitsInLastUnit;
1783   uint64_t UnpackedSizeInBits =
1784   llvm::RoundUpToAlignment(getSizeInBits(),
1785                            Context.toBits(UnpackedAlignment));
1786   CharUnits UnpackedSize = Context.toCharUnitsFromBits(UnpackedSizeInBits);
1787   uint64_t RoundedSize
1788     = llvm::RoundUpToAlignment(getSizeInBits(), Context.toBits(Alignment));
1789 
1790   if (ExternalLayout) {
1791     // If we're inferring alignment, and the external size is smaller than
1792     // our size after we've rounded up to alignment, conservatively set the
1793     // alignment to 1.
1794     if (InferAlignment && ExternalSize < RoundedSize) {
1795       Alignment = CharUnits::One();
1796       InferAlignment = false;
1797     }
1798     setSize(ExternalSize);
1799     return;
1800   }
1801 
1802   // Set the size to the final size.
1803   setSize(RoundedSize);
1804 
1805   unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
1806   if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
1807     // Warn if padding was introduced to the struct/class/union.
1808     if (getSizeInBits() > UnpaddedSize) {
1809       unsigned PadSize = getSizeInBits() - UnpaddedSize;
1810       bool InBits = true;
1811       if (PadSize % CharBitNum == 0) {
1812         PadSize = PadSize / CharBitNum;
1813         InBits = false;
1814       }
1815       Diag(RD->getLocation(), diag::warn_padded_struct_size)
1816           << Context.getTypeDeclType(RD)
1817           << PadSize
1818           << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1); // plural or not
1819     }
1820 
1821     // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
1822     // bother since there won't be alignment issues.
1823     if (Packed && UnpackedAlignment > CharUnits::One() &&
1824         getSize() == UnpackedSize)
1825       Diag(D->getLocation(), diag::warn_unnecessary_packed)
1826           << Context.getTypeDeclType(RD);
1827   }
1828 }
1829 
1830 void RecordLayoutBuilder::UpdateAlignment(CharUnits NewAlignment,
1831                                           CharUnits UnpackedNewAlignment) {
1832   // The alignment is not modified when using 'mac68k' alignment or when
1833   // we have an externally-supplied layout that also provides overall alignment.
1834   if (IsMac68kAlign || (ExternalLayout && !InferAlignment))
1835     return;
1836 
1837   if (NewAlignment > Alignment) {
1838     assert(llvm::isPowerOf2_32(NewAlignment.getQuantity() &&
1839            "Alignment not a power of 2"));
1840     Alignment = NewAlignment;
1841   }
1842 
1843   if (UnpackedNewAlignment > UnpackedAlignment) {
1844     assert(llvm::isPowerOf2_32(UnpackedNewAlignment.getQuantity() &&
1845            "Alignment not a power of 2"));
1846     UnpackedAlignment = UnpackedNewAlignment;
1847   }
1848 }
1849 
1850 uint64_t
1851 RecordLayoutBuilder::updateExternalFieldOffset(const FieldDecl *Field,
1852                                                uint64_t ComputedOffset) {
1853   assert(ExternalFieldOffsets.find(Field) != ExternalFieldOffsets.end() &&
1854          "Field does not have an external offset");
1855 
1856   uint64_t ExternalFieldOffset = ExternalFieldOffsets[Field];
1857 
1858   if (InferAlignment && ExternalFieldOffset < ComputedOffset) {
1859     // The externally-supplied field offset is before the field offset we
1860     // computed. Assume that the structure is packed.
1861     Alignment = CharUnits::One();
1862     InferAlignment = false;
1863   }
1864 
1865   // Use the externally-supplied field offset.
1866   return ExternalFieldOffset;
1867 }
1868 
1869 /// \brief Get diagnostic %select index for tag kind for
1870 /// field padding diagnostic message.
1871 /// WARNING: Indexes apply to particular diagnostics only!
1872 ///
1873 /// \returns diagnostic %select index.
1874 static unsigned getPaddingDiagFromTagKind(TagTypeKind Tag) {
1875   switch (Tag) {
1876   case TTK_Struct: return 0;
1877   case TTK_Interface: return 1;
1878   case TTK_Class: return 2;
1879   default: llvm_unreachable("Invalid tag kind for field padding diagnostic!");
1880   }
1881 }
1882 
1883 void RecordLayoutBuilder::CheckFieldPadding(uint64_t Offset,
1884                                             uint64_t UnpaddedOffset,
1885                                             uint64_t UnpackedOffset,
1886                                             unsigned UnpackedAlign,
1887                                             bool isPacked,
1888                                             const FieldDecl *D) {
1889   // We let objc ivars without warning, objc interfaces generally are not used
1890   // for padding tricks.
1891   if (isa<ObjCIvarDecl>(D))
1892     return;
1893 
1894   // Don't warn about structs created without a SourceLocation.  This can
1895   // be done by clients of the AST, such as codegen.
1896   if (D->getLocation().isInvalid())
1897     return;
1898 
1899   unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
1900 
1901   // Warn if padding was introduced to the struct/class.
1902   if (!IsUnion && Offset > UnpaddedOffset) {
1903     unsigned PadSize = Offset - UnpaddedOffset;
1904     bool InBits = true;
1905     if (PadSize % CharBitNum == 0) {
1906       PadSize = PadSize / CharBitNum;
1907       InBits = false;
1908     }
1909     if (D->getIdentifier())
1910       Diag(D->getLocation(), diag::warn_padded_struct_field)
1911           << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
1912           << Context.getTypeDeclType(D->getParent())
1913           << PadSize
1914           << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1) // plural or not
1915           << D->getIdentifier();
1916     else
1917       Diag(D->getLocation(), diag::warn_padded_struct_anon_field)
1918           << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
1919           << Context.getTypeDeclType(D->getParent())
1920           << PadSize
1921           << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1); // plural or not
1922   }
1923 
1924   // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
1925   // bother since there won't be alignment issues.
1926   if (isPacked && UnpackedAlign > CharBitNum && Offset == UnpackedOffset)
1927     Diag(D->getLocation(), diag::warn_unnecessary_packed)
1928         << D->getIdentifier();
1929 }
1930 
1931 static const CXXMethodDecl *computeKeyFunction(ASTContext &Context,
1932                                                const CXXRecordDecl *RD) {
1933   // If a class isn't polymorphic it doesn't have a key function.
1934   if (!RD->isPolymorphic())
1935     return 0;
1936 
1937   // A class that is not externally visible doesn't have a key function. (Or
1938   // at least, there's no point to assigning a key function to such a class;
1939   // this doesn't affect the ABI.)
1940   if (!RD->isExternallyVisible())
1941     return 0;
1942 
1943   // Template instantiations don't have key functions,see Itanium C++ ABI 5.2.6.
1944   // Same behavior as GCC.
1945   TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
1946   if (TSK == TSK_ImplicitInstantiation ||
1947       TSK == TSK_ExplicitInstantiationDefinition)
1948     return 0;
1949 
1950   bool allowInlineFunctions =
1951     Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline();
1952 
1953   for (CXXRecordDecl::method_iterator I = RD->method_begin(),
1954          E = RD->method_end(); I != E; ++I) {
1955     const CXXMethodDecl *MD = *I;
1956 
1957     if (!MD->isVirtual())
1958       continue;
1959 
1960     if (MD->isPure())
1961       continue;
1962 
1963     // Ignore implicit member functions, they are always marked as inline, but
1964     // they don't have a body until they're defined.
1965     if (MD->isImplicit())
1966       continue;
1967 
1968     if (MD->isInlineSpecified())
1969       continue;
1970 
1971     if (MD->hasInlineBody())
1972       continue;
1973 
1974     // Ignore inline deleted or defaulted functions.
1975     if (!MD->isUserProvided())
1976       continue;
1977 
1978     // In certain ABIs, ignore functions with out-of-line inline definitions.
1979     if (!allowInlineFunctions) {
1980       const FunctionDecl *Def;
1981       if (MD->hasBody(Def) && Def->isInlineSpecified())
1982         continue;
1983     }
1984 
1985     // We found it.
1986     return MD;
1987   }
1988 
1989   return 0;
1990 }
1991 
1992 DiagnosticBuilder
1993 RecordLayoutBuilder::Diag(SourceLocation Loc, unsigned DiagID) {
1994   return Context.getDiagnostics().Report(Loc, DiagID);
1995 }
1996 
1997 /// Does the target C++ ABI require us to skip over the tail-padding
1998 /// of the given class (considering it as a base class) when allocating
1999 /// objects?
2000 static bool mustSkipTailPadding(TargetCXXABI ABI, const CXXRecordDecl *RD) {
2001   switch (ABI.getTailPaddingUseRules()) {
2002   case TargetCXXABI::AlwaysUseTailPadding:
2003     return false;
2004 
2005   case TargetCXXABI::UseTailPaddingUnlessPOD03:
2006     // FIXME: To the extent that this is meant to cover the Itanium ABI
2007     // rules, we should implement the restrictions about over-sized
2008     // bitfields:
2009     //
2010     // http://mentorembedded.github.com/cxx-abi/abi.html#POD :
2011     //   In general, a type is considered a POD for the purposes of
2012     //   layout if it is a POD type (in the sense of ISO C++
2013     //   [basic.types]). However, a POD-struct or POD-union (in the
2014     //   sense of ISO C++ [class]) with a bitfield member whose
2015     //   declared width is wider than the declared type of the
2016     //   bitfield is not a POD for the purpose of layout.  Similarly,
2017     //   an array type is not a POD for the purpose of layout if the
2018     //   element type of the array is not a POD for the purpose of
2019     //   layout.
2020     //
2021     //   Where references to the ISO C++ are made in this paragraph,
2022     //   the Technical Corrigendum 1 version of the standard is
2023     //   intended.
2024     return RD->isPOD();
2025 
2026   case TargetCXXABI::UseTailPaddingUnlessPOD11:
2027     // This is equivalent to RD->getTypeForDecl().isCXX11PODType(),
2028     // but with a lot of abstraction penalty stripped off.  This does
2029     // assume that these properties are set correctly even in C++98
2030     // mode; fortunately, that is true because we want to assign
2031     // consistently semantics to the type-traits intrinsics (or at
2032     // least as many of them as possible).
2033     return RD->isTrivial() && RD->isStandardLayout();
2034   }
2035 
2036   llvm_unreachable("bad tail-padding use kind");
2037 }
2038 
2039 static bool isMsLayout(const RecordDecl* D) {
2040   return D->getASTContext().getTargetInfo().getCXXABI().isMicrosoft();
2041 }
2042 
2043 // This section contains an implementation of struct layout that is, up to the
2044 // included tests, compatible with cl.exe (2012).  The layout produced is
2045 // significantly different than those produced by the Itanium ABI.  Here we note
2046 // the most important differences.
2047 //
2048 // * The alignment of bitfields in unions is ignored when computing the
2049 //   alignment of the union.
2050 // * The existence of zero-width bitfield that occurs after anything other than
2051 //   a non-zero length bitfield is ignored.
2052 // * The Itanium equivalent vtable pointers are split into a vfptr (virtual
2053 //   function pointer) and a vbptr (virtual base pointer).  They can each be
2054 //   shared with a, non-virtual bases. These bases need not be the same.  vfptrs
2055 //   always occur at offset 0.  vbptrs can occur at an
2056 //   arbitrary offset and are placed after non-virtual bases but before fields.
2057 // * Virtual bases sometimes require a 'vtordisp' field that is laid out before
2058 //   the virtual base and is used in conjunction with virtual overrides during
2059 //   construction and destruction.
2060 // * vfptrs are allocated in a block of memory equal to the alignment of the
2061 //   fields and non-virtual bases at offset 0 in 32 bit mode and in a pointer
2062 //   sized block of memory in 64 bit mode.
2063 // * vbptrs are allocated in a block of memory equal to the alignment of the
2064 //   fields and non-virtual bases.  This block is at a potentially unaligned
2065 //   offset.  If the allocation slot is unaligned and the alignment is less than
2066 //   or equal to the pointer size, additional space is allocated so that the
2067 //   pointer can be aligned properly.  This causes very strange effects on the
2068 //   placement of objects after the allocated block. (see the code).
2069 // * vtordisps are allocated in a block of memory with size and alignment equal
2070 //   to the alignment of the completed structure (before applying __declspec(
2071 //   align())).  The vtordisp always occur at the end of the allocation block,
2072 //   immediately prior to the virtual base.
2073 // * The last zero sized non-virtual base is allocated after the placement of
2074 //   vbptr if one exists and can be placed at the end of the struct, potentially
2075 //   aliasing either the first member or another struct allocated after this
2076 //   one.
2077 // * The last zero size virtual base may be placed at the end of the struct.
2078 //   and can potentially alias a zero sized type in the next struct.
2079 // * If the last field is a non-zero length bitfield, all virtual bases will
2080 //   have extra padding added before them for no obvious reason.  The padding
2081 //   has the same number of bits as the type of the bitfield.
2082 // * When laying out empty non-virtual bases, an extra byte of padding is added
2083 //   if the non-virtual base before the empty non-virtual base has a vbptr.
2084 // * The ABI attempts to avoid aliasing of zero sized bases by adding padding
2085 //   between bases or vbases with specific properties.  The criteria for
2086 //   additional padding between two bases is that the first base is zero sized
2087 //   or has a zero sized subobject and the second base is zero sized or leads
2088 //   with a zero sized base (sharing of vfptrs can reorder the layout of the
2089 //   so the leading base is not always the first one declared).  The padding
2090 //   added for bases is 1 byte.  The padding added for vbases depends on the
2091 //   alignment of the object but is at least 4 bytes (in both 32 and 64 bit
2092 //   modes).
2093 // * There is no concept of non-virtual alignment or any distinction between
2094 //   data size and non-virtual size.
2095 // * __declspec(align) on bitfields has the effect of changing the bitfield's
2096 //   alignment instead of its required alignment.  This has implications on how
2097 //   it interacts with pragam pack.
2098 
2099 namespace {
2100 struct MicrosoftRecordLayoutBuilder {
2101   struct ElementInfo {
2102     CharUnits Size;
2103     CharUnits Alignment;
2104   };
2105   typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
2106   MicrosoftRecordLayoutBuilder(const ASTContext &Context) : Context(Context) {}
2107 private:
2108   MicrosoftRecordLayoutBuilder(const MicrosoftRecordLayoutBuilder &)
2109   LLVM_DELETED_FUNCTION;
2110   void operator=(const MicrosoftRecordLayoutBuilder &) LLVM_DELETED_FUNCTION;
2111 public:
2112   void layout(const RecordDecl *RD);
2113   void cxxLayout(const CXXRecordDecl *RD);
2114   /// \brief Initializes size and alignment and honors some flags.
2115   void initializeLayout(const RecordDecl *RD);
2116   /// \brief Initialized C++ layout, compute alignment and virtual alignment and
2117   /// existence of vfptrs and vbptrs.  Alignment is needed before the vfptr is
2118   /// laid out.
2119   void initializeCXXLayout(const CXXRecordDecl *RD);
2120   void layoutNonVirtualBases(const CXXRecordDecl *RD);
2121   void layoutNonVirtualBase(const CXXRecordDecl *BaseDecl,
2122                             const ASTRecordLayout &BaseLayout,
2123                             const ASTRecordLayout *&PreviousBaseLayout);
2124   void injectVFPtr(const CXXRecordDecl *RD);
2125   void injectVBPtr(const CXXRecordDecl *RD);
2126   void injectVPtrs(const CXXRecordDecl *RD);
2127   /// \brief Lays out the fields of the record.  Also rounds size up to
2128   /// alignment.
2129   void layoutFields(const RecordDecl *RD);
2130   void layoutField(const FieldDecl *FD);
2131   void layoutBitField(const FieldDecl *FD);
2132   /// \brief Lays out a single zero-width bit-field in the record and handles
2133   /// special cases associated with zero-width bit-fields.
2134   void layoutZeroWidthBitField(const FieldDecl *FD);
2135   void layoutVirtualBases(const CXXRecordDecl *RD);
2136   void finalizeLayout(const RecordDecl *RD);
2137   /// \brief Gets the size and alignment of a base taking pragma pack and
2138   /// __declspec(align) into account.
2139   ElementInfo getAdjustedElementInfo(const ASTRecordLayout &Layout);
2140   /// \brief Gets the size and alignment of a field taking pragma  pack and
2141   /// __declspec(align) into account.  It also updates RequiredAlignment as a
2142   /// side effect because it is most convenient to do so here.
2143   ElementInfo getAdjustedElementInfo(const FieldDecl *FD);
2144   /// \brief Places a field at an offset in CharUnits.
2145   void placeFieldAtOffset(CharUnits FieldOffset) {
2146     FieldOffsets.push_back(Context.toBits(FieldOffset));
2147   }
2148   /// \brief Places a bitfield at a bit offset.
2149   void placeFieldAtBitOffset(uint64_t FieldOffset) {
2150     FieldOffsets.push_back(FieldOffset);
2151   }
2152   /// \brief Compute the set of virtual bases for which vtordisps are required.
2153   llvm::SmallPtrSet<const CXXRecordDecl *, 2>
2154   computeVtorDispSet(const CXXRecordDecl *RD);
2155   const ASTContext &Context;
2156   /// \brief The size of the record being laid out.
2157   CharUnits Size;
2158   /// \brief The data alignment of the record layout.
2159   CharUnits DataSize;
2160   /// \brief The current alignment of the record layout.
2161   CharUnits Alignment;
2162   /// \brief The maximum allowed field alignment. This is set by #pragma pack.
2163   CharUnits MaxFieldAlignment;
2164   /// \brief The alignment that this record must obey.  This is imposed by
2165   /// __declspec(align()) on the record itself or one of its fields or bases.
2166   CharUnits RequiredAlignment;
2167   /// \brief The size of the allocation of the currently active bitfield.
2168   /// This value isn't meaningful unless LastFieldIsNonZeroWidthBitfield
2169   /// is true.
2170   CharUnits CurrentBitfieldSize;
2171   /// \brief Offset to the virtual base table pointer (if one exists).
2172   CharUnits VBPtrOffset;
2173   /// \brief The size and alignment info of a pointer.
2174   ElementInfo PointerInfo;
2175   /// \brief The primary base class (if one exists).
2176   const CXXRecordDecl *PrimaryBase;
2177   /// \brief The class we share our vb-pointer with.
2178   const CXXRecordDecl *SharedVBPtrBase;
2179   /// \brief The collection of field offsets.
2180   SmallVector<uint64_t, 16> FieldOffsets;
2181   /// \brief Base classes and their offsets in the record.
2182   BaseOffsetsMapTy Bases;
2183   /// \brief virtual base classes and their offsets in the record.
2184   ASTRecordLayout::VBaseOffsetsMapTy VBases;
2185   /// \brief The number of remaining bits in our last bitfield allocation.
2186   /// This value isn't meaningful unless LastFieldIsNonZeroWidthBitfield is
2187   /// true.
2188   unsigned RemainingBitsInField;
2189   bool IsUnion : 1;
2190   /// \brief True if the last field laid out was a bitfield and was not 0
2191   /// width.
2192   bool LastFieldIsNonZeroWidthBitfield : 1;
2193   /// \brief True if the class has its own vftable pointer.
2194   bool HasOwnVFPtr : 1;
2195   /// \brief True if the class has a vbtable pointer.
2196   bool HasVBPtr : 1;
2197   /// \brief Lets us know if we're in 64-bit mode
2198   bool Is64BitMode : 1;
2199   /// \brief True if this class contains a zero sized member or base or a base
2200   /// with a zero sized member or base.  Only used for MS-ABI.
2201   bool HasZeroSizedSubObject : 1;
2202   /// \brief True if this class is zero sized or first base is zero sized or
2203   /// has this property.  Only used for MS-ABI.
2204   bool LeadsWithZeroSizedBase : 1;
2205 };
2206 } // namespace
2207 
2208 MicrosoftRecordLayoutBuilder::ElementInfo
2209 MicrosoftRecordLayoutBuilder::getAdjustedElementInfo(
2210     const ASTRecordLayout &Layout) {
2211   ElementInfo Info;
2212   Info.Alignment = Layout.getAlignment();
2213   // Respect pragma pack.
2214   if (!MaxFieldAlignment.isZero())
2215     Info.Alignment = std::min(Info.Alignment, MaxFieldAlignment);
2216   // Track zero-sized subobjects here where it's already available.
2217   if (Layout.hasZeroSizedSubObject())
2218     HasZeroSizedSubObject = true;
2219   // Respect required alignment, this is necessary because we may have adjusted
2220   // the alignment in the case of pragam pack.  Note that the required alignment
2221   // doesn't actually apply to the struct alignment at this point.
2222   Alignment = std::max(Alignment, Info.Alignment);
2223   Info.Alignment = std::max(Info.Alignment, Layout.getRequiredAlignment());
2224   Info.Size = Layout.getDataSize();
2225   return Info;
2226 }
2227 
2228 MicrosoftRecordLayoutBuilder::ElementInfo
2229 MicrosoftRecordLayoutBuilder::getAdjustedElementInfo(
2230     const FieldDecl *FD) {
2231   ElementInfo Info;
2232   // Respect align attributes.
2233   CharUnits FieldRequiredAlignment =
2234       Context.toCharUnitsFromBits(FD->getMaxAlignment());
2235   // Respect attributes applied to subobjects of the field.
2236   if (const RecordType *RT =
2237       FD->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
2238     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RT->getDecl());
2239     // Get the element info for a layout, respecting pack.
2240     Info = getAdjustedElementInfo(Layout);
2241     // Nomally getAdjustedElementInfo returns the non-virtual size, which is
2242     // correct for bases but not for fields.
2243     Info.Size = Context.getTypeInfoInChars(FD->getType()).first;
2244     // Capture required alignment as a side-effect.
2245     RequiredAlignment = std::max(RequiredAlignment,
2246                                  Layout.getRequiredAlignment());
2247   }
2248   else {
2249     llvm::tie(Info.Size, Info.Alignment) =
2250         Context.getTypeInfoInChars(FD->getType());
2251     if (FD->isBitField() && FD->getMaxAlignment() != 0)
2252       Info.Alignment = std::max(Info.Alignment, FieldRequiredAlignment);
2253     // Respect pragma pack.
2254     if (!MaxFieldAlignment.isZero())
2255       Info.Alignment = std::min(Info.Alignment, MaxFieldAlignment);
2256   }
2257   // Respect packed field attribute.
2258   if (FD->hasAttr<PackedAttr>())
2259     Info.Alignment = CharUnits::One();
2260   // Take required alignment into account.  __declspec(align) on bitfields
2261   // impacts the alignment rather than the required alignment.
2262   if (!FD->isBitField()) {
2263     Info.Alignment = std::max(Info.Alignment, FieldRequiredAlignment);
2264     // Capture required alignment as a side-effect.
2265     RequiredAlignment = std::max(RequiredAlignment, FieldRequiredAlignment);
2266   }
2267   // TODO: Add a Sema warning that MS ignores bitfield alignment in unions.
2268   if (!(FD->isBitField() && IsUnion)) {
2269     Alignment = std::max(Alignment, Info.Alignment);
2270     if (!MaxFieldAlignment.isZero())
2271       Alignment = std::min(Alignment, MaxFieldAlignment);
2272   }
2273   return Info;
2274 }
2275 
2276 void MicrosoftRecordLayoutBuilder::layout(const RecordDecl *RD) {
2277   initializeLayout(RD);
2278   layoutFields(RD);
2279   DataSize = Size = Size.RoundUpToAlignment(Alignment);
2280   finalizeLayout(RD);
2281 }
2282 
2283 void MicrosoftRecordLayoutBuilder::cxxLayout(const CXXRecordDecl *RD) {
2284   initializeLayout(RD);
2285   initializeCXXLayout(RD);
2286   layoutNonVirtualBases(RD);
2287   layoutFields(RD);
2288   injectVPtrs(RD);
2289   DataSize = Size = Size.RoundUpToAlignment(Alignment);
2290   layoutVirtualBases(RD);
2291   finalizeLayout(RD);
2292 }
2293 
2294 void MicrosoftRecordLayoutBuilder::initializeLayout(const RecordDecl *RD) {
2295   IsUnion = RD->isUnion();
2296   Is64BitMode = Context.getTargetInfo().getPointerWidth(0) == 64;
2297   Size = CharUnits::Zero();
2298   Alignment = CharUnits::One();
2299   // In 64-bit mode we always perform an alignment step after laying out vbases.
2300   // In 32-bit mode we do not.  The check to see if we need to perform alignment
2301   // checks the RequiredAlignment field and performs alignment if it isn't 0.
2302   RequiredAlignment = Is64BitMode ? CharUnits::One() : CharUnits::Zero();
2303   RequiredAlignment = std::max(RequiredAlignment,
2304     Context.toCharUnitsFromBits(RD->getMaxAlignment()));
2305   // Compute the maximum field alignment.
2306   MaxFieldAlignment = CharUnits::Zero();
2307   // Honor the default struct packing maximum alignment flag.
2308   if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct)
2309       MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
2310   // Honor the packing attribute.  The MS-ABI ignores pragma pack if its larger
2311   // than the pointer size.
2312   if (const MaxFieldAlignmentAttr *MFAA = RD->getAttr<MaxFieldAlignmentAttr>()){
2313     unsigned PackedAlignment = MFAA->getAlignment();
2314     if (PackedAlignment <= Context.getTargetInfo().getPointerWidth(0))
2315       MaxFieldAlignment = Context.toCharUnitsFromBits(PackedAlignment);
2316   }
2317   // Packed attribute forces max field alignment to be 1.
2318   if (RD->hasAttr<PackedAttr>())
2319     MaxFieldAlignment = CharUnits::One();
2320 }
2321 
2322 void
2323 MicrosoftRecordLayoutBuilder::initializeCXXLayout(const CXXRecordDecl *RD) {
2324   HasZeroSizedSubObject = false;
2325   LeadsWithZeroSizedBase = false;
2326   HasOwnVFPtr = false;
2327   HasVBPtr = false;
2328   PrimaryBase = 0;
2329   SharedVBPtrBase = 0;
2330   // Calculate pointer size and alignment.  These are used for vfptr and vbprt
2331   // injection.
2332   PointerInfo.Size =
2333       Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
2334   PointerInfo.Alignment = PointerInfo.Size;
2335   // Respect pragma pack.
2336   if (!MaxFieldAlignment.isZero())
2337     PointerInfo.Alignment = std::min(PointerInfo.Alignment, MaxFieldAlignment);
2338 }
2339 
2340 void
2341 MicrosoftRecordLayoutBuilder::layoutNonVirtualBases(const CXXRecordDecl *RD) {
2342   // The MS-ABI lays out all bases that contain leading vfptrs before it lays
2343   // out any bases that do not contain vfptrs.  We implement this as two passes
2344   // over the bases.  This approach guarantees that the primary base is laid out
2345   // first.  We use these passes to calculate some additional aggregated
2346   // information about the bases, such as reqruied alignment and the presence of
2347   // zero sized members.
2348   const ASTRecordLayout* PreviousBaseLayout = 0;
2349   // Iterate through the bases and lay out the non-virtual ones.
2350   for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
2351                                                 e = RD->bases_end();
2352        i != e; ++i) {
2353     const CXXRecordDecl *BaseDecl = i->getType()->getAsCXXRecordDecl();
2354     const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
2355     // Track RequiredAlignment for all bases in this pass.
2356     RequiredAlignment = std::max(RequiredAlignment,
2357                                  BaseLayout.getRequiredAlignment());
2358     // Mark and skip virtual bases.
2359     if (i->isVirtual()) {
2360       HasVBPtr = true;
2361       continue;
2362     }
2363     // Check fo a base to share a VBPtr with.
2364     if (!SharedVBPtrBase && BaseLayout.hasVBPtr()) {
2365       SharedVBPtrBase = BaseDecl;
2366       HasVBPtr = true;
2367     }
2368     // Only lay out bases with extendable VFPtrs on the first pass.
2369     if (!BaseLayout.hasExtendableVFPtr())
2370       continue;
2371     // If we don't have a primary base, this one qualifies.
2372     if (!PrimaryBase) {
2373       PrimaryBase = BaseDecl;
2374       LeadsWithZeroSizedBase = BaseLayout.leadsWithZeroSizedBase();
2375     }
2376     // Lay out the base.
2377     layoutNonVirtualBase(BaseDecl, BaseLayout, PreviousBaseLayout);
2378   }
2379   // Figure out if we need a fresh VFPtr for this class.
2380   if (!PrimaryBase && RD->isDynamicClass())
2381     for (CXXRecordDecl::method_iterator i = RD->method_begin(),
2382                                         e = RD->method_end();
2383          !HasOwnVFPtr && i != e; ++i)
2384       HasOwnVFPtr = i->isVirtual() && i->size_overridden_methods() == 0;
2385   // If we don't have a primary base then we have a leading object that could
2386   // itself lead with a zero-sized object, something we track.
2387   bool CheckLeadingLayout = !PrimaryBase;
2388   // Iterate through the bases and lay out the non-virtual ones.
2389   for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
2390                                                 e = RD->bases_end();
2391        i != e; ++i) {
2392     if (i->isVirtual())
2393       continue;
2394     const CXXRecordDecl *BaseDecl = i->getType()->getAsCXXRecordDecl();
2395     const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
2396     // Only lay out bases without extendable VFPtrs on the second pass.
2397     if (BaseLayout.hasExtendableVFPtr())
2398       continue;
2399     // If this is the first layout, check to see if it leads with a zero sized
2400     // object.  If it does, so do we.
2401     if (CheckLeadingLayout) {
2402       CheckLeadingLayout = false;
2403       LeadsWithZeroSizedBase = BaseLayout.leadsWithZeroSizedBase();
2404     }
2405     // Lay out the base.
2406     layoutNonVirtualBase(BaseDecl, BaseLayout, PreviousBaseLayout);
2407   }
2408   // Set our VBPtroffset if we know it at this point.
2409   if (!HasVBPtr)
2410     VBPtrOffset = CharUnits::fromQuantity(-1);
2411   else if (SharedVBPtrBase) {
2412     const ASTRecordLayout &Layout = Context.getASTRecordLayout(SharedVBPtrBase);
2413     VBPtrOffset = Bases[SharedVBPtrBase] + Layout.getVBPtrOffset();
2414   }
2415 }
2416 
2417 void MicrosoftRecordLayoutBuilder::layoutNonVirtualBase(
2418     const CXXRecordDecl *BaseDecl,
2419     const ASTRecordLayout &BaseLayout,
2420     const ASTRecordLayout *&PreviousBaseLayout) {
2421   // Insert padding between two bases if the left first one is zero sized or
2422   // contains a zero sized subobject and the right is zero sized or one leads
2423   // with a zero sized base.
2424   if (PreviousBaseLayout && PreviousBaseLayout->hasZeroSizedSubObject() &&
2425       BaseLayout.leadsWithZeroSizedBase())
2426     Size++;
2427   ElementInfo Info = getAdjustedElementInfo(BaseLayout);
2428   CharUnits BaseOffset = Size.RoundUpToAlignment(Info.Alignment);
2429   Bases.insert(std::make_pair(BaseDecl, BaseOffset));
2430   Size = BaseOffset + BaseLayout.getDataSize();
2431   PreviousBaseLayout = &BaseLayout;
2432   VBPtrOffset = Size;
2433 }
2434 
2435 void MicrosoftRecordLayoutBuilder::layoutFields(const RecordDecl *RD) {
2436   LastFieldIsNonZeroWidthBitfield = false;
2437   for (RecordDecl::field_iterator Field = RD->field_begin(),
2438                                   FieldEnd = RD->field_end();
2439        Field != FieldEnd; ++Field)
2440     layoutField(*Field);
2441 }
2442 
2443 void MicrosoftRecordLayoutBuilder::layoutField(const FieldDecl *FD) {
2444   if (FD->isBitField()) {
2445     layoutBitField(FD);
2446     return;
2447   }
2448   LastFieldIsNonZeroWidthBitfield = false;
2449   ElementInfo Info = getAdjustedElementInfo(FD);
2450   if (IsUnion) {
2451     placeFieldAtOffset(CharUnits::Zero());
2452     Size = std::max(Size, Info.Size);
2453   } else {
2454     CharUnits FieldOffset = Size.RoundUpToAlignment(Info.Alignment);
2455     placeFieldAtOffset(FieldOffset);
2456     Size = FieldOffset + Info.Size;
2457   }
2458 }
2459 
2460 void MicrosoftRecordLayoutBuilder::layoutBitField(const FieldDecl *FD) {
2461   unsigned Width = FD->getBitWidthValue(Context);
2462   if (Width == 0) {
2463     layoutZeroWidthBitField(FD);
2464     return;
2465   }
2466   ElementInfo Info = getAdjustedElementInfo(FD);
2467   // Clamp the bitfield to a containable size for the sake of being able
2468   // to lay them out.  Sema will throw an error.
2469   if (Width > Context.toBits(Info.Size))
2470     Width = Context.toBits(Info.Size);
2471   // Check to see if this bitfield fits into an existing allocation.  Note:
2472   // MSVC refuses to pack bitfields of formal types with different sizes
2473   // into the same allocation.
2474   if (!IsUnion && LastFieldIsNonZeroWidthBitfield &&
2475       CurrentBitfieldSize == Info.Size && Width <= RemainingBitsInField) {
2476     placeFieldAtBitOffset(Context.toBits(Size) - RemainingBitsInField);
2477     RemainingBitsInField -= Width;
2478     return;
2479   }
2480   LastFieldIsNonZeroWidthBitfield = true;
2481   CurrentBitfieldSize = Info.Size;
2482   if (IsUnion) {
2483     placeFieldAtOffset(CharUnits::Zero());
2484     Size = std::max(Size, Info.Size);
2485   } else {
2486     // Allocate a new block of memory and place the bitfield in it.
2487     CharUnits FieldOffset = Size.RoundUpToAlignment(Info.Alignment);
2488     placeFieldAtOffset(FieldOffset);
2489     Size = FieldOffset + Info.Size;
2490     RemainingBitsInField = Context.toBits(Info.Size) - Width;
2491   }
2492 }
2493 
2494 void
2495 MicrosoftRecordLayoutBuilder::layoutZeroWidthBitField(const FieldDecl *FD) {
2496   // Zero-width bitfields are ignored unless they follow a non-zero-width
2497   // bitfield.
2498   if (!LastFieldIsNonZeroWidthBitfield) {
2499     placeFieldAtOffset(IsUnion ? CharUnits::Zero() : Size);
2500     // TODO: Add a Sema warning that MS ignores alignment for zero
2501     // sized bitfields that occur after zero-size bitfields or non-bitfields.
2502     return;
2503   }
2504   LastFieldIsNonZeroWidthBitfield = false;
2505   ElementInfo Info = getAdjustedElementInfo(FD);
2506   if (IsUnion) {
2507     placeFieldAtOffset(CharUnits::Zero());
2508     Size = std::max(Size, Info.Size);
2509   } else {
2510     // Round up the current record size to the field's alignment boundary.
2511     CharUnits FieldOffset = Size.RoundUpToAlignment(Info.Alignment);
2512     placeFieldAtOffset(FieldOffset);
2513     Size = FieldOffset;
2514   }
2515 }
2516 
2517 void MicrosoftRecordLayoutBuilder::injectVBPtr(const CXXRecordDecl *RD) {
2518   if (!HasVBPtr || SharedVBPtrBase)
2519     return;
2520   // Inject the VBPointer at the injection site.
2521   CharUnits InjectionSite = VBPtrOffset;
2522   // But before we do, make sure it's properly aligned.
2523   VBPtrOffset = VBPtrOffset.RoundUpToAlignment(PointerInfo.Alignment);
2524   // Determine where the first field should be laid out after the vbptr.
2525   CharUnits FieldStart = VBPtrOffset + PointerInfo.Size;
2526   // Make sure that the amount we push the fields back by is a multiple of the
2527   // alignment.
2528   CharUnits Offset = (FieldStart - InjectionSite).RoundUpToAlignment(Alignment);
2529   // Increase the size of the object and push back all fields by the offset
2530   // amount.
2531   Size += Offset;
2532   for (SmallVector<uint64_t, 16>::iterator i = FieldOffsets.begin(),
2533                                            e = FieldOffsets.end();
2534        i != e; ++i)
2535     *i += Context.toBits(Offset);
2536   for (BaseOffsetsMapTy::iterator i = Bases.begin(), e = Bases.end();
2537        i != e; ++i)
2538        if (i->second >= InjectionSite)
2539          i->second += Offset;
2540   // The presence of a vbptr suppresses zero sized objects that are not in
2541   // virtual bases.
2542   HasZeroSizedSubObject = false;
2543 }
2544 
2545 void MicrosoftRecordLayoutBuilder::injectVFPtr(const CXXRecordDecl *RD) {
2546   if (!HasOwnVFPtr)
2547     return;
2548   // Make sure that the amount we push the struct back by is a multiple of the
2549   // alignment.
2550   CharUnits Offset = PointerInfo.Size.RoundUpToAlignment(Alignment);
2551   // Increase the size of the object and push back all fields, the vbptr and all
2552   // bases by the offset amount.
2553   Size += Offset;
2554   for (SmallVector<uint64_t, 16>::iterator i = FieldOffsets.begin(),
2555                                            e = FieldOffsets.end();
2556        i != e; ++i)
2557     *i += Context.toBits(Offset);
2558   if (HasVBPtr)
2559     VBPtrOffset += Offset;
2560   for (BaseOffsetsMapTy::iterator i = Bases.begin(), e = Bases.end();
2561        i != e; ++i)
2562     i->second += Offset;
2563 }
2564 
2565 void MicrosoftRecordLayoutBuilder::injectVPtrs(const CXXRecordDecl *RD) {
2566   if (!(HasOwnVFPtr || (HasVBPtr && !SharedVBPtrBase)))
2567     return;
2568   if (!Is64BitMode || RequiredAlignment <= CharUnits::fromQuantity(8)) {
2569     // Note that the VBPtr is injected first.  It depends on the alignment of
2570     // the object *before* the alignment is updated by inserting a pointer into
2571     // the record.
2572     injectVBPtr(RD);
2573     injectVFPtr(RD);
2574     Alignment = std::max(Alignment, PointerInfo.Alignment);
2575     return;
2576   }
2577   // In 64-bit mode, structs with RequiredAlignment greater than 8 get special
2578   // layout rules.  Likely this is to avoid excessive padding intruced around
2579   // the vfptrs and vbptrs.  The special rules involve re-laying out the struct
2580   // and inserting the vfptr and vbptr as if they were fields/bases.
2581   FieldOffsets.clear();
2582   Bases.clear();
2583   Size = CharUnits::Zero();
2584   Alignment = std::max(Alignment, PointerInfo.Alignment);
2585   if (HasOwnVFPtr)
2586     Size = PointerInfo.Size;
2587   layoutNonVirtualBases(RD);
2588   if (HasVBPtr && !SharedVBPtrBase) {
2589     const CXXRecordDecl *PenultBaseDecl = 0;
2590     const CXXRecordDecl *LastBaseDecl = 0;
2591     // Iterate through the bases and find the last two non-virtual bases.
2592     for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
2593                                                   e = RD->bases_end();
2594           i != e; ++i) {
2595       if (i->isVirtual())
2596         continue;
2597       const CXXRecordDecl *BaseDecl = i->getType()->getAsCXXRecordDecl();
2598       if (!LastBaseDecl || Bases[BaseDecl] > Bases[LastBaseDecl]) {
2599         PenultBaseDecl = LastBaseDecl;
2600         LastBaseDecl = BaseDecl;
2601       }
2602     }
2603     const ASTRecordLayout *PenultBaseLayout = PenultBaseDecl ?
2604         &Context.getASTRecordLayout(PenultBaseDecl) : 0;
2605     const ASTRecordLayout *LastBaseLayout = LastBaseDecl ?
2606         &Context.getASTRecordLayout(LastBaseDecl) : 0;
2607     // Calculate the vbptr offset.  The rule is different than in the general
2608     // case layout.  Particularly, if the last two non-virtual bases are both
2609     // zero sized, the site of the vbptr is *before* the padding that occurs
2610     // between the two zero sized bases and the vbptr potentially aliases with
2611     // the first of these two bases.  We have no understanding of why this is
2612     // different from the general case layout but it may have to do with lazy
2613     // placement of zero sized bases.
2614     VBPtrOffset = Size;
2615     if (LastBaseLayout && LastBaseLayout->getDataSize().isZero()) {
2616       VBPtrOffset = Bases[LastBaseDecl];
2617       if (PenultBaseLayout && PenultBaseLayout->getDataSize().isZero())
2618         VBPtrOffset = Bases[PenultBaseDecl];
2619     }
2620     // Once we've located a spot for the vbptr, place it.
2621     VBPtrOffset = VBPtrOffset.RoundUpToAlignment(PointerInfo.Alignment);
2622     Size = VBPtrOffset + PointerInfo.Size;
2623     if (LastBaseLayout && LastBaseLayout->getDataSize().isZero()) {
2624       // Add the padding between zero sized bases after the vbptr.
2625       if (PenultBaseLayout && PenultBaseLayout->getDataSize().isZero())
2626         Size += CharUnits::One();
2627       Size = Size.RoundUpToAlignment(LastBaseLayout->getRequiredAlignment());
2628       Bases[LastBaseDecl] = Size;
2629     }
2630   }
2631   layoutFields(RD);
2632   // The presence of a vbptr suppresses zero sized objects that are not in
2633   // virtual bases.
2634   HasZeroSizedSubObject = false;
2635 }
2636 
2637 void MicrosoftRecordLayoutBuilder::layoutVirtualBases(const CXXRecordDecl *RD) {
2638   if (!HasVBPtr)
2639     return;
2640   // Vtordisps are always 4 bytes (even in 64-bit mode)
2641   CharUnits VtorDispSize = CharUnits::fromQuantity(4);
2642   CharUnits VtorDispAlignment = VtorDispSize;
2643   // vtordisps respect pragma pack.
2644   if (!MaxFieldAlignment.isZero())
2645     VtorDispAlignment = std::min(VtorDispAlignment, MaxFieldAlignment);
2646   // The alignment of the vtordisp is at least the required alignment of the
2647   // entire record.  This requirement may be present to support vtordisp
2648   // injection.
2649   VtorDispAlignment = std::max(VtorDispAlignment, RequiredAlignment);
2650   // Compute the vtordisp set.
2651   llvm::SmallPtrSet<const CXXRecordDecl *, 2> HasVtordispSet =
2652       computeVtorDispSet(RD);
2653   // Iterate through the virtual bases and lay them out.
2654   const ASTRecordLayout* PreviousBaseLayout = 0;
2655   for (CXXRecordDecl::base_class_const_iterator i = RD->vbases_begin(),
2656                                                 e = RD->vbases_end();
2657        i != e; ++i) {
2658     const CXXRecordDecl *BaseDecl = i->getType()->getAsCXXRecordDecl();
2659     const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
2660     bool HasVtordisp = HasVtordispSet.count(BaseDecl);
2661     // If the last field we laid out was a non-zero length bitfield then add
2662     // some extra padding for no obvious reason.
2663     if (LastFieldIsNonZeroWidthBitfield)
2664       Size += CurrentBitfieldSize;
2665     // Insert padding between two bases if the left first one is zero sized or
2666     // contains a zero sized subobject and the right is zero sized or one leads
2667     // with a zero sized base.  The padding between virtual bases is 4
2668     // bytes (in both 32 and 64 bits modes) and always involves rounding up to
2669     // the required alignment, we don't know why.
2670     if (PreviousBaseLayout && PreviousBaseLayout->hasZeroSizedSubObject() &&
2671         BaseLayout.leadsWithZeroSizedBase())
2672       Size = Size.RoundUpToAlignment(VtorDispAlignment) + VtorDispSize;
2673     // Insert the vtordisp.
2674     if (HasVtordisp)
2675       Size = Size.RoundUpToAlignment(VtorDispAlignment) + VtorDispSize;
2676     // Insert the virtual base.
2677     ElementInfo Info = getAdjustedElementInfo(BaseLayout);
2678     CharUnits BaseOffset = Size.RoundUpToAlignment(Info.Alignment);
2679     VBases.insert(std::make_pair(BaseDecl,
2680         ASTRecordLayout::VBaseInfo(BaseOffset, HasVtordisp)));
2681     Size = BaseOffset + BaseLayout.getDataSize();
2682     PreviousBaseLayout = &BaseLayout;
2683   }
2684 }
2685 
2686 void MicrosoftRecordLayoutBuilder::finalizeLayout(const RecordDecl *RD) {
2687   // Respect required alignment.  Note that in 32-bit mode Required alignment
2688   // may be 0 nad cause size not to be updated.
2689   if (!RequiredAlignment.isZero()) {
2690     Alignment = std::max(Alignment, RequiredAlignment);
2691     Size = Size.RoundUpToAlignment(Alignment);
2692   }
2693   // Zero-sized structures have size equal to their alignment.
2694   if (Size.isZero()) {
2695     HasZeroSizedSubObject = true;
2696     LeadsWithZeroSizedBase = true;
2697     Size = Alignment;
2698   }
2699 }
2700 
2701 static bool
2702 RequiresVtordisp(const llvm::SmallPtrSet<const CXXRecordDecl *, 2> &HasVtordisp,
2703                  const CXXRecordDecl *RD) {
2704   if (HasVtordisp.count(RD))
2705     return true;
2706   // If any of a virtual bases non-virtual bases (recursively) requires a
2707   // vtordisp than so does this virtual base.
2708   for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
2709                                                 e = RD->bases_end();
2710        i != e; ++i)
2711     if (!i->isVirtual() &&
2712         RequiresVtordisp(
2713             HasVtordisp,
2714             cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl())))
2715       return true;
2716   return false;
2717 }
2718 
2719 llvm::SmallPtrSet<const CXXRecordDecl *, 2>
2720 MicrosoftRecordLayoutBuilder::computeVtorDispSet(const CXXRecordDecl *RD) {
2721   llvm::SmallPtrSet<const CXXRecordDecl *, 2> HasVtordispSet;
2722   // If any of our bases need a vtordisp for this type, so do we.  Check our
2723   // direct bases for vtordisp requirements.
2724   for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
2725                                                 e = RD->bases_end();
2726        i != e; ++i) {
2727     const CXXRecordDecl *BaseDecl =
2728         cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
2729     const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
2730     for (ASTRecordLayout::VBaseOffsetsMapTy::const_iterator
2731              bi = Layout.getVBaseOffsetsMap().begin(),
2732              be = Layout.getVBaseOffsetsMap().end();
2733          bi != be; ++bi)
2734       if (bi->second.hasVtorDisp())
2735         HasVtordispSet.insert(bi->first);
2736   }
2737   // If we define a constructor or destructor and override a function that is
2738   // defined in a virtual base's vtable, that virtual bases need a vtordisp.
2739   // Here we collect a list of classes with vtables for which our virtual bases
2740   // actually live.  The virtual bases with this property will require
2741   // vtordisps.  In addition, virtual bases that contain non-virtual bases that
2742   // define functions we override also require vtordisps, this case is checked
2743   // explicitly below.
2744   if (RD->hasUserDeclaredConstructor() || RD->hasUserDeclaredDestructor()) {
2745     llvm::SmallPtrSet<const CXXMethodDecl *, 8> Work;
2746     // Seed the working set with our non-destructor virtual methods.
2747     for (CXXRecordDecl::method_iterator i = RD->method_begin(),
2748                                         e = RD->method_end();
2749          i != e; ++i)
2750       if ((*i)->isVirtual() && !isa<CXXDestructorDecl>(*i))
2751         Work.insert(*i);
2752     while (!Work.empty()) {
2753       const CXXMethodDecl *MD = *Work.begin();
2754       CXXMethodDecl::method_iterator i = MD->begin_overridden_methods(),
2755                                      e = MD->end_overridden_methods();
2756       if (i == e)
2757         // If a virtual method has no-overrides it lives in its parent's vtable.
2758         HasVtordispSet.insert(MD->getParent());
2759       else
2760         Work.insert(i, e);
2761       // We've finished processing this element, remove it from the working set.
2762       Work.erase(MD);
2763     }
2764   }
2765   // Re-check all of our vbases for vtordisp requirements (in case their
2766   // non-virtual bases have vtordisp requirements).
2767   for (CXXRecordDecl::base_class_const_iterator i = RD->vbases_begin(),
2768                                                 e = RD->vbases_end();
2769        i != e; ++i) {
2770     const CXXRecordDecl *BaseDecl =  i->getType()->getAsCXXRecordDecl();
2771     if (!HasVtordispSet.count(BaseDecl) &&
2772         RequiresVtordisp(HasVtordispSet, BaseDecl))
2773       HasVtordispSet.insert(BaseDecl);
2774   }
2775   return HasVtordispSet;
2776 }
2777 
2778 /// \brief Get or compute information about the layout of the specified record
2779 /// (struct/union/class), which indicates its size and field position
2780 /// information.
2781 const ASTRecordLayout *
2782 ASTContext::BuildMicrosoftASTRecordLayout(const RecordDecl *D) const {
2783   MicrosoftRecordLayoutBuilder Builder(*this);
2784   if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
2785     Builder.cxxLayout(RD);
2786     return new (*this) ASTRecordLayout(
2787         *this, Builder.Size, Builder.Alignment, Builder.RequiredAlignment,
2788         Builder.HasOwnVFPtr,
2789         Builder.HasOwnVFPtr || Builder.PrimaryBase,
2790         Builder.VBPtrOffset, Builder.DataSize, Builder.FieldOffsets.data(),
2791         Builder.FieldOffsets.size(), Builder.DataSize,
2792         Builder.Alignment, CharUnits::Zero(), Builder.PrimaryBase,
2793         false, Builder.SharedVBPtrBase,
2794         Builder.HasZeroSizedSubObject, Builder.LeadsWithZeroSizedBase,
2795         Builder.Bases, Builder.VBases);
2796   } else {
2797     Builder.layout(D);
2798     return new (*this) ASTRecordLayout(
2799         *this, Builder.Size, Builder.Alignment, Builder.RequiredAlignment,
2800         Builder.Size, Builder.FieldOffsets.data(), Builder.FieldOffsets.size());
2801   }
2802 }
2803 
2804 /// getASTRecordLayout - Get or compute information about the layout of the
2805 /// specified record (struct/union/class), which indicates its size and field
2806 /// position information.
2807 const ASTRecordLayout &
2808 ASTContext::getASTRecordLayout(const RecordDecl *D) const {
2809   // These asserts test different things.  A record has a definition
2810   // as soon as we begin to parse the definition.  That definition is
2811   // not a complete definition (which is what isDefinition() tests)
2812   // until we *finish* parsing the definition.
2813 
2814   if (D->hasExternalLexicalStorage() && !D->getDefinition())
2815     getExternalSource()->CompleteType(const_cast<RecordDecl*>(D));
2816 
2817   D = D->getDefinition();
2818   assert(D && "Cannot get layout of forward declarations!");
2819   assert(!D->isInvalidDecl() && "Cannot get layout of invalid decl!");
2820   assert(D->isCompleteDefinition() && "Cannot layout type before complete!");
2821 
2822   // Look up this layout, if already laid out, return what we have.
2823   // Note that we can't save a reference to the entry because this function
2824   // is recursive.
2825   const ASTRecordLayout *Entry = ASTRecordLayouts[D];
2826   if (Entry) return *Entry;
2827 
2828   const ASTRecordLayout *NewEntry = 0;
2829 
2830   if (isMsLayout(D) && !D->getASTContext().getExternalSource()) {
2831     NewEntry = BuildMicrosoftASTRecordLayout(D);
2832   } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
2833     EmptySubobjectMap EmptySubobjects(*this, RD);
2834     RecordLayoutBuilder Builder(*this, &EmptySubobjects);
2835     Builder.Layout(RD);
2836 
2837     // In certain situations, we are allowed to lay out objects in the
2838     // tail-padding of base classes.  This is ABI-dependent.
2839     // FIXME: this should be stored in the record layout.
2840     bool skipTailPadding =
2841       mustSkipTailPadding(getTargetInfo().getCXXABI(), cast<CXXRecordDecl>(D));
2842 
2843     // FIXME: This should be done in FinalizeLayout.
2844     CharUnits DataSize =
2845       skipTailPadding ? Builder.getSize() : Builder.getDataSize();
2846     CharUnits NonVirtualSize =
2847       skipTailPadding ? DataSize : Builder.NonVirtualSize;
2848     NewEntry =
2849       new (*this) ASTRecordLayout(*this, Builder.getSize(),
2850                                   Builder.Alignment,
2851                                   /*RequiredAlignment : used by MS-ABI)*/
2852                                   Builder.Alignment,
2853                                   Builder.HasOwnVFPtr,
2854                                   RD->isDynamicClass(),
2855                                   CharUnits::fromQuantity(-1),
2856                                   DataSize,
2857                                   Builder.FieldOffsets.data(),
2858                                   Builder.FieldOffsets.size(),
2859                                   NonVirtualSize,
2860                                   Builder.NonVirtualAlignment,
2861                                   EmptySubobjects.SizeOfLargestEmptySubobject,
2862                                   Builder.PrimaryBase,
2863                                   Builder.PrimaryBaseIsVirtual,
2864                                   0, false, false,
2865                                   Builder.Bases, Builder.VBases);
2866   } else {
2867     RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/0);
2868     Builder.Layout(D);
2869 
2870     NewEntry =
2871       new (*this) ASTRecordLayout(*this, Builder.getSize(),
2872                                   Builder.Alignment,
2873                                   /*RequiredAlignment : used by MS-ABI)*/
2874                                   Builder.Alignment,
2875                                   Builder.getSize(),
2876                                   Builder.FieldOffsets.data(),
2877                                   Builder.FieldOffsets.size());
2878   }
2879 
2880   ASTRecordLayouts[D] = NewEntry;
2881 
2882   if (getLangOpts().DumpRecordLayouts) {
2883     llvm::outs() << "\n*** Dumping AST Record Layout\n";
2884     DumpRecordLayout(D, llvm::outs(), getLangOpts().DumpRecordLayoutsSimple);
2885   }
2886 
2887   return *NewEntry;
2888 }
2889 
2890 const CXXMethodDecl *ASTContext::getCurrentKeyFunction(const CXXRecordDecl *RD) {
2891   if (!getTargetInfo().getCXXABI().hasKeyFunctions())
2892     return 0;
2893 
2894   assert(RD->getDefinition() && "Cannot get key function for forward decl!");
2895   RD = cast<CXXRecordDecl>(RD->getDefinition());
2896 
2897   LazyDeclPtr &Entry = KeyFunctions[RD];
2898   if (!Entry)
2899     Entry = const_cast<CXXMethodDecl*>(computeKeyFunction(*this, RD));
2900 
2901   return cast_or_null<CXXMethodDecl>(Entry.get(getExternalSource()));
2902 }
2903 
2904 void ASTContext::setNonKeyFunction(const CXXMethodDecl *Method) {
2905   assert(Method == Method->getFirstDecl() &&
2906          "not working with method declaration from class definition");
2907 
2908   // Look up the cache entry.  Since we're working with the first
2909   // declaration, its parent must be the class definition, which is
2910   // the correct key for the KeyFunctions hash.
2911   llvm::DenseMap<const CXXRecordDecl*, LazyDeclPtr>::iterator
2912     I = KeyFunctions.find(Method->getParent());
2913 
2914   // If it's not cached, there's nothing to do.
2915   if (I == KeyFunctions.end()) return;
2916 
2917   // If it is cached, check whether it's the target method, and if so,
2918   // remove it from the cache.
2919   if (I->second.get(getExternalSource()) == Method) {
2920     // FIXME: remember that we did this for module / chained PCH state?
2921     KeyFunctions.erase(I);
2922   }
2923 }
2924 
2925 static uint64_t getFieldOffset(const ASTContext &C, const FieldDecl *FD) {
2926   const ASTRecordLayout &Layout = C.getASTRecordLayout(FD->getParent());
2927   return Layout.getFieldOffset(FD->getFieldIndex());
2928 }
2929 
2930 uint64_t ASTContext::getFieldOffset(const ValueDecl *VD) const {
2931   uint64_t OffsetInBits;
2932   if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
2933     OffsetInBits = ::getFieldOffset(*this, FD);
2934   } else {
2935     const IndirectFieldDecl *IFD = cast<IndirectFieldDecl>(VD);
2936 
2937     OffsetInBits = 0;
2938     for (IndirectFieldDecl::chain_iterator CI = IFD->chain_begin(),
2939                                            CE = IFD->chain_end();
2940          CI != CE; ++CI)
2941       OffsetInBits += ::getFieldOffset(*this, cast<FieldDecl>(*CI));
2942   }
2943 
2944   return OffsetInBits;
2945 }
2946 
2947 /// getObjCLayout - Get or compute information about the layout of the
2948 /// given interface.
2949 ///
2950 /// \param Impl - If given, also include the layout of the interface's
2951 /// implementation. This may differ by including synthesized ivars.
2952 const ASTRecordLayout &
2953 ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
2954                           const ObjCImplementationDecl *Impl) const {
2955   // Retrieve the definition
2956   if (D->hasExternalLexicalStorage() && !D->getDefinition())
2957     getExternalSource()->CompleteType(const_cast<ObjCInterfaceDecl*>(D));
2958   D = D->getDefinition();
2959   assert(D && D->isThisDeclarationADefinition() && "Invalid interface decl!");
2960 
2961   // Look up this layout, if already laid out, return what we have.
2962   const ObjCContainerDecl *Key =
2963     Impl ? (const ObjCContainerDecl*) Impl : (const ObjCContainerDecl*) D;
2964   if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
2965     return *Entry;
2966 
2967   // Add in synthesized ivar count if laying out an implementation.
2968   if (Impl) {
2969     unsigned SynthCount = CountNonClassIvars(D);
2970     // If there aren't any sythesized ivars then reuse the interface
2971     // entry. Note we can't cache this because we simply free all
2972     // entries later; however we shouldn't look up implementations
2973     // frequently.
2974     if (SynthCount == 0)
2975       return getObjCLayout(D, 0);
2976   }
2977 
2978   RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/0);
2979   Builder.Layout(D);
2980 
2981   const ASTRecordLayout *NewEntry =
2982     new (*this) ASTRecordLayout(*this, Builder.getSize(),
2983                                 Builder.Alignment,
2984                                 /*RequiredAlignment : used by MS-ABI)*/
2985                                 Builder.Alignment,
2986                                 Builder.getDataSize(),
2987                                 Builder.FieldOffsets.data(),
2988                                 Builder.FieldOffsets.size());
2989 
2990   ObjCLayouts[Key] = NewEntry;
2991 
2992   return *NewEntry;
2993 }
2994 
2995 static void PrintOffset(raw_ostream &OS,
2996                         CharUnits Offset, unsigned IndentLevel) {
2997   OS << llvm::format("%4" PRId64 " | ", (int64_t)Offset.getQuantity());
2998   OS.indent(IndentLevel * 2);
2999 }
3000 
3001 static void PrintIndentNoOffset(raw_ostream &OS, unsigned IndentLevel) {
3002   OS << "     | ";
3003   OS.indent(IndentLevel * 2);
3004 }
3005 
3006 static void DumpCXXRecordLayout(raw_ostream &OS,
3007                                 const CXXRecordDecl *RD, const ASTContext &C,
3008                                 CharUnits Offset,
3009                                 unsigned IndentLevel,
3010                                 const char* Description,
3011                                 bool IncludeVirtualBases) {
3012   const ASTRecordLayout &Layout = C.getASTRecordLayout(RD);
3013 
3014   PrintOffset(OS, Offset, IndentLevel);
3015   OS << C.getTypeDeclType(const_cast<CXXRecordDecl *>(RD)).getAsString();
3016   if (Description)
3017     OS << ' ' << Description;
3018   if (RD->isEmpty())
3019     OS << " (empty)";
3020   OS << '\n';
3021 
3022   IndentLevel++;
3023 
3024   const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
3025   bool HasOwnVFPtr = Layout.hasOwnVFPtr();
3026   bool HasOwnVBPtr = Layout.hasOwnVBPtr();
3027 
3028   // Vtable pointer.
3029   if (RD->isDynamicClass() && !PrimaryBase && !isMsLayout(RD)) {
3030     PrintOffset(OS, Offset, IndentLevel);
3031     OS << '(' << *RD << " vtable pointer)\n";
3032   } else if (HasOwnVFPtr) {
3033     PrintOffset(OS, Offset, IndentLevel);
3034     // vfptr (for Microsoft C++ ABI)
3035     OS << '(' << *RD << " vftable pointer)\n";
3036   }
3037 
3038   // Dump (non-virtual) bases
3039   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
3040          E = RD->bases_end(); I != E; ++I) {
3041     assert(!I->getType()->isDependentType() &&
3042            "Cannot layout class with dependent bases.");
3043     if (I->isVirtual())
3044       continue;
3045 
3046     const CXXRecordDecl *Base =
3047       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
3048 
3049     CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base);
3050 
3051     DumpCXXRecordLayout(OS, Base, C, BaseOffset, IndentLevel,
3052                         Base == PrimaryBase ? "(primary base)" : "(base)",
3053                         /*IncludeVirtualBases=*/false);
3054   }
3055 
3056   // vbptr (for Microsoft C++ ABI)
3057   if (HasOwnVBPtr) {
3058     PrintOffset(OS, Offset + Layout.getVBPtrOffset(), IndentLevel);
3059     OS << '(' << *RD << " vbtable pointer)\n";
3060   }
3061 
3062   // Dump fields.
3063   uint64_t FieldNo = 0;
3064   for (CXXRecordDecl::field_iterator I = RD->field_begin(),
3065          E = RD->field_end(); I != E; ++I, ++FieldNo) {
3066     const FieldDecl &Field = **I;
3067     CharUnits FieldOffset = Offset +
3068       C.toCharUnitsFromBits(Layout.getFieldOffset(FieldNo));
3069 
3070     if (const RecordType *RT = Field.getType()->getAs<RecordType>()) {
3071       if (const CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3072         DumpCXXRecordLayout(OS, D, C, FieldOffset, IndentLevel,
3073                             Field.getName().data(),
3074                             /*IncludeVirtualBases=*/true);
3075         continue;
3076       }
3077     }
3078 
3079     PrintOffset(OS, FieldOffset, IndentLevel);
3080     OS << Field.getType().getAsString() << ' ' << Field << '\n';
3081   }
3082 
3083   if (!IncludeVirtualBases)
3084     return;
3085 
3086   // Dump virtual bases.
3087   const ASTRecordLayout::VBaseOffsetsMapTy &vtordisps =
3088     Layout.getVBaseOffsetsMap();
3089   for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
3090          E = RD->vbases_end(); I != E; ++I) {
3091     assert(I->isVirtual() && "Found non-virtual class!");
3092     const CXXRecordDecl *VBase =
3093       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
3094 
3095     CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBase);
3096 
3097     if (vtordisps.find(VBase)->second.hasVtorDisp()) {
3098       PrintOffset(OS, VBaseOffset - CharUnits::fromQuantity(4), IndentLevel);
3099       OS << "(vtordisp for vbase " << *VBase << ")\n";
3100     }
3101 
3102     DumpCXXRecordLayout(OS, VBase, C, VBaseOffset, IndentLevel,
3103                         VBase == PrimaryBase ?
3104                         "(primary virtual base)" : "(virtual base)",
3105                         /*IncludeVirtualBases=*/false);
3106   }
3107 
3108   PrintIndentNoOffset(OS, IndentLevel - 1);
3109   OS << "[sizeof=" << Layout.getSize().getQuantity();
3110   if (!isMsLayout(RD))
3111     OS << ", dsize=" << Layout.getDataSize().getQuantity();
3112   OS << ", align=" << Layout.getAlignment().getQuantity() << '\n';
3113 
3114   PrintIndentNoOffset(OS, IndentLevel - 1);
3115   OS << " nvsize=" << Layout.getNonVirtualSize().getQuantity();
3116   OS << ", nvalign=" << Layout.getNonVirtualAlignment().getQuantity() << "]\n";
3117   OS << '\n';
3118 }
3119 
3120 void ASTContext::DumpRecordLayout(const RecordDecl *RD,
3121                                   raw_ostream &OS,
3122                                   bool Simple) const {
3123   const ASTRecordLayout &Info = getASTRecordLayout(RD);
3124 
3125   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
3126     if (!Simple)
3127       return DumpCXXRecordLayout(OS, CXXRD, *this, CharUnits(), 0, 0,
3128                                  /*IncludeVirtualBases=*/true);
3129 
3130   OS << "Type: " << getTypeDeclType(RD).getAsString() << "\n";
3131   if (!Simple) {
3132     OS << "Record: ";
3133     RD->dump();
3134   }
3135   OS << "\nLayout: ";
3136   OS << "<ASTRecordLayout\n";
3137   OS << "  Size:" << toBits(Info.getSize()) << "\n";
3138   if (!isMsLayout(RD))
3139     OS << "  DataSize:" << toBits(Info.getDataSize()) << "\n";
3140   OS << "  Alignment:" << toBits(Info.getAlignment()) << "\n";
3141   OS << "  FieldOffsets: [";
3142   for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i) {
3143     if (i) OS << ", ";
3144     OS << Info.getFieldOffset(i);
3145   }
3146   OS << "]>\n";
3147 }
3148