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   /// VBPtrOffset - Virtual base table offset. Only for MS layout.
608   CharUnits VBPtrOffset;
609 
610   typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
611 
612   /// Bases - base classes and their offsets in the record.
613   BaseOffsetsMapTy Bases;
614 
615   // VBases - virtual base classes and their offsets in the record.
616   ASTRecordLayout::VBaseOffsetsMapTy VBases;
617 
618   /// IndirectPrimaryBases - Virtual base classes, direct or indirect, that are
619   /// primary base classes for some other direct or indirect base class.
620   CXXIndirectPrimaryBaseSet IndirectPrimaryBases;
621 
622   /// FirstNearlyEmptyVBase - The first nearly empty virtual base class in
623   /// inheritance graph order. Used for determining the primary base class.
624   const CXXRecordDecl *FirstNearlyEmptyVBase;
625 
626   /// VisitedVirtualBases - A set of all the visited virtual bases, used to
627   /// avoid visiting virtual bases more than once.
628   llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
629 
630   /// \brief Externally-provided size.
631   uint64_t ExternalSize;
632 
633   /// \brief Externally-provided alignment.
634   uint64_t ExternalAlign;
635 
636   /// \brief Externally-provided field offsets.
637   llvm::DenseMap<const FieldDecl *, uint64_t> ExternalFieldOffsets;
638 
639   /// \brief Externally-provided direct, non-virtual base offsets.
640   llvm::DenseMap<const CXXRecordDecl *, CharUnits> ExternalBaseOffsets;
641 
642   /// \brief Externally-provided virtual base offsets.
643   llvm::DenseMap<const CXXRecordDecl *, CharUnits> ExternalVirtualBaseOffsets;
644 
645   RecordLayoutBuilder(const ASTContext &Context,
646                       EmptySubobjectMap *EmptySubobjects)
647     : Context(Context), EmptySubobjects(EmptySubobjects), Size(0),
648       Alignment(CharUnits::One()), UnpackedAlignment(CharUnits::One()),
649       ExternalLayout(false), InferAlignment(false),
650       Packed(false), IsUnion(false), IsMac68kAlign(false), IsMsStruct(false),
651       UnfilledBitsInLastUnit(0), LastBitfieldTypeSize(0),
652       MaxFieldAlignment(CharUnits::Zero()),
653       DataSize(0), NonVirtualSize(CharUnits::Zero()),
654       NonVirtualAlignment(CharUnits::One()),
655       PrimaryBase(0), PrimaryBaseIsVirtual(false),
656       HasOwnVFPtr(false),
657       VBPtrOffset(CharUnits::fromQuantity(-1)),
658       FirstNearlyEmptyVBase(0) { }
659 
660   /// Reset this RecordLayoutBuilder to a fresh state, using the given
661   /// alignment as the initial alignment.  This is used for the
662   /// correct layout of vb-table pointers in MSVC.
663   void resetWithTargetAlignment(CharUnits TargetAlignment) {
664     const ASTContext &Context = this->Context;
665     EmptySubobjectMap *EmptySubobjects = this->EmptySubobjects;
666     this->~RecordLayoutBuilder();
667     new (this) RecordLayoutBuilder(Context, EmptySubobjects);
668     Alignment = UnpackedAlignment = TargetAlignment;
669   }
670 
671   void Layout(const RecordDecl *D);
672   void Layout(const CXXRecordDecl *D);
673   void Layout(const ObjCInterfaceDecl *D);
674 
675   void LayoutFields(const RecordDecl *D);
676   void LayoutField(const FieldDecl *D);
677   void LayoutWideBitField(uint64_t FieldSize, uint64_t TypeSize,
678                           bool FieldPacked, const FieldDecl *D);
679   void LayoutBitField(const FieldDecl *D);
680 
681   TargetCXXABI getCXXABI() const {
682     return Context.getTargetInfo().getCXXABI();
683   }
684 
685   bool isMicrosoftCXXABI() const {
686     return getCXXABI().isMicrosoft();
687   }
688 
689   void MSLayoutVirtualBases(const CXXRecordDecl *RD);
690 
691   /// BaseSubobjectInfoAllocator - Allocator for BaseSubobjectInfo objects.
692   llvm::SpecificBumpPtrAllocator<BaseSubobjectInfo> BaseSubobjectInfoAllocator;
693 
694   typedef llvm::DenseMap<const CXXRecordDecl *, BaseSubobjectInfo *>
695     BaseSubobjectInfoMapTy;
696 
697   /// VirtualBaseInfo - Map from all the (direct or indirect) virtual bases
698   /// of the class we're laying out to their base subobject info.
699   BaseSubobjectInfoMapTy VirtualBaseInfo;
700 
701   /// NonVirtualBaseInfo - Map from all the direct non-virtual bases of the
702   /// class we're laying out to their base subobject info.
703   BaseSubobjectInfoMapTy NonVirtualBaseInfo;
704 
705   /// ComputeBaseSubobjectInfo - Compute the base subobject information for the
706   /// bases of the given class.
707   void ComputeBaseSubobjectInfo(const CXXRecordDecl *RD);
708 
709   /// ComputeBaseSubobjectInfo - Compute the base subobject information for a
710   /// single class and all of its base classes.
711   BaseSubobjectInfo *ComputeBaseSubobjectInfo(const CXXRecordDecl *RD,
712                                               bool IsVirtual,
713                                               BaseSubobjectInfo *Derived);
714 
715   /// DeterminePrimaryBase - Determine the primary base of the given class.
716   void DeterminePrimaryBase(const CXXRecordDecl *RD);
717 
718   void SelectPrimaryVBase(const CXXRecordDecl *RD);
719 
720   void EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign);
721 
722   /// LayoutNonVirtualBases - Determines the primary base class (if any) and
723   /// lays it out. Will then proceed to lay out all non-virtual base clasess.
724   void LayoutNonVirtualBases(const CXXRecordDecl *RD);
725 
726   /// LayoutNonVirtualBase - Lays out a single non-virtual base.
727   void LayoutNonVirtualBase(const BaseSubobjectInfo *Base);
728 
729   void AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
730                                     CharUnits Offset);
731 
732   bool needsVFTable(const CXXRecordDecl *RD) const;
733   bool hasNewVirtualFunction(const CXXRecordDecl *RD,
734                              bool IgnoreDestructor = false) const;
735   bool isPossiblePrimaryBase(const CXXRecordDecl *Base) const;
736 
737   void computeVtordisps(const CXXRecordDecl *RD,
738                         ClassSetTy &VtordispVBases);
739 
740   /// LayoutVirtualBases - Lays out all the virtual bases.
741   void LayoutVirtualBases(const CXXRecordDecl *RD,
742                           const CXXRecordDecl *MostDerivedClass);
743 
744   /// LayoutVirtualBase - Lays out a single virtual base.
745   void LayoutVirtualBase(const BaseSubobjectInfo *Base,
746                          bool IsVtordispNeed = false);
747 
748   /// LayoutBase - Will lay out a base and return the offset where it was
749   /// placed, in chars.
750   CharUnits LayoutBase(const BaseSubobjectInfo *Base);
751 
752   /// InitializeLayout - Initialize record layout for the given record decl.
753   void InitializeLayout(const Decl *D);
754 
755   /// FinishLayout - Finalize record layout. Adjust record size based on the
756   /// alignment.
757   void FinishLayout(const NamedDecl *D);
758 
759   void UpdateAlignment(CharUnits NewAlignment, CharUnits UnpackedNewAlignment);
760   void UpdateAlignment(CharUnits NewAlignment) {
761     UpdateAlignment(NewAlignment, NewAlignment);
762   }
763 
764   /// \brief Retrieve the externally-supplied field offset for the given
765   /// field.
766   ///
767   /// \param Field The field whose offset is being queried.
768   /// \param ComputedOffset The offset that we've computed for this field.
769   uint64_t updateExternalFieldOffset(const FieldDecl *Field,
770                                      uint64_t ComputedOffset);
771 
772   void CheckFieldPadding(uint64_t Offset, uint64_t UnpaddedOffset,
773                           uint64_t UnpackedOffset, unsigned UnpackedAlign,
774                           bool isPacked, const FieldDecl *D);
775 
776   DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
777 
778   CharUnits getSize() const {
779     assert(Size % Context.getCharWidth() == 0);
780     return Context.toCharUnitsFromBits(Size);
781   }
782   uint64_t getSizeInBits() const { return Size; }
783 
784   void setSize(CharUnits NewSize) { Size = Context.toBits(NewSize); }
785   void setSize(uint64_t NewSize) { Size = NewSize; }
786 
787   CharUnits getAligment() const { return Alignment; }
788 
789   CharUnits getDataSize() const {
790     assert(DataSize % Context.getCharWidth() == 0);
791     return Context.toCharUnitsFromBits(DataSize);
792   }
793   uint64_t getDataSizeInBits() const { return DataSize; }
794 
795   void setDataSize(CharUnits NewSize) { DataSize = Context.toBits(NewSize); }
796   void setDataSize(uint64_t NewSize) { DataSize = NewSize; }
797 
798   RecordLayoutBuilder(const RecordLayoutBuilder &) LLVM_DELETED_FUNCTION;
799   void operator=(const RecordLayoutBuilder &) LLVM_DELETED_FUNCTION;
800 };
801 } // end anonymous namespace
802 
803 void
804 RecordLayoutBuilder::SelectPrimaryVBase(const CXXRecordDecl *RD) {
805   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
806          E = RD->bases_end(); I != E; ++I) {
807     assert(!I->getType()->isDependentType() &&
808            "Cannot layout class with dependent bases.");
809 
810     const CXXRecordDecl *Base =
811       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
812 
813     // Check if this is a nearly empty virtual base.
814     if (I->isVirtual() && Context.isNearlyEmpty(Base)) {
815       // If it's not an indirect primary base, then we've found our primary
816       // base.
817       if (!IndirectPrimaryBases.count(Base)) {
818         PrimaryBase = Base;
819         PrimaryBaseIsVirtual = true;
820         return;
821       }
822 
823       // Is this the first nearly empty virtual base?
824       if (!FirstNearlyEmptyVBase)
825         FirstNearlyEmptyVBase = Base;
826     }
827 
828     SelectPrimaryVBase(Base);
829     if (PrimaryBase)
830       return;
831   }
832 }
833 
834 /// DeterminePrimaryBase - Determine the primary base of the given class.
835 void RecordLayoutBuilder::DeterminePrimaryBase(const CXXRecordDecl *RD) {
836   // If the class isn't dynamic, it won't have a primary base.
837   if (!RD->isDynamicClass())
838     return;
839 
840   // Compute all the primary virtual bases for all of our direct and
841   // indirect bases, and record all their primary virtual base classes.
842   RD->getIndirectPrimaryBases(IndirectPrimaryBases);
843 
844   // If the record has a dynamic base class, attempt to choose a primary base
845   // class. It is the first (in direct base class order) non-virtual dynamic
846   // base class, if one exists.
847   for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
848          e = RD->bases_end(); i != e; ++i) {
849     // Ignore virtual bases.
850     if (i->isVirtual())
851       continue;
852 
853     const CXXRecordDecl *Base =
854       cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
855 
856     if (isPossiblePrimaryBase(Base)) {
857       // We found it.
858       PrimaryBase = Base;
859       PrimaryBaseIsVirtual = false;
860       return;
861     }
862   }
863 
864   // The Microsoft ABI doesn't have primary virtual bases.
865   if (isMicrosoftCXXABI()) {
866     assert(!PrimaryBase && "Should not get here with a primary base!");
867     return;
868   }
869 
870   // Under the Itanium ABI, if there is no non-virtual primary base class,
871   // try to compute the primary virtual base.  The primary virtual base is
872   // the first nearly empty virtual base that is not an indirect primary
873   // virtual base class, if one exists.
874   if (RD->getNumVBases() != 0) {
875     SelectPrimaryVBase(RD);
876     if (PrimaryBase)
877       return;
878   }
879 
880   // Otherwise, it is the first indirect primary base class, if one exists.
881   if (FirstNearlyEmptyVBase) {
882     PrimaryBase = FirstNearlyEmptyVBase;
883     PrimaryBaseIsVirtual = true;
884     return;
885   }
886 
887   assert(!PrimaryBase && "Should not get here with a primary base!");
888 }
889 
890 BaseSubobjectInfo *
891 RecordLayoutBuilder::ComputeBaseSubobjectInfo(const CXXRecordDecl *RD,
892                                               bool IsVirtual,
893                                               BaseSubobjectInfo *Derived) {
894   BaseSubobjectInfo *Info;
895 
896   if (IsVirtual) {
897     // Check if we already have info about this virtual base.
898     BaseSubobjectInfo *&InfoSlot = VirtualBaseInfo[RD];
899     if (InfoSlot) {
900       assert(InfoSlot->Class == RD && "Wrong class for virtual base info!");
901       return InfoSlot;
902     }
903 
904     // We don't, create it.
905     InfoSlot = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
906     Info = InfoSlot;
907   } else {
908     Info = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
909   }
910 
911   Info->Class = RD;
912   Info->IsVirtual = IsVirtual;
913   Info->Derived = 0;
914   Info->PrimaryVirtualBaseInfo = 0;
915 
916   const CXXRecordDecl *PrimaryVirtualBase = 0;
917   BaseSubobjectInfo *PrimaryVirtualBaseInfo = 0;
918 
919   // Check if this base has a primary virtual base.
920   if (RD->getNumVBases()) {
921     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
922     if (Layout.isPrimaryBaseVirtual()) {
923       // This base does have a primary virtual base.
924       PrimaryVirtualBase = Layout.getPrimaryBase();
925       assert(PrimaryVirtualBase && "Didn't have a primary virtual base!");
926 
927       // Now check if we have base subobject info about this primary base.
928       PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
929 
930       if (PrimaryVirtualBaseInfo) {
931         if (PrimaryVirtualBaseInfo->Derived) {
932           // We did have info about this primary base, and it turns out that it
933           // has already been claimed as a primary virtual base for another
934           // base.
935           PrimaryVirtualBase = 0;
936         } else {
937           // We can claim this base as our primary base.
938           Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
939           PrimaryVirtualBaseInfo->Derived = Info;
940         }
941       }
942     }
943   }
944 
945   // Now go through all direct bases.
946   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
947        E = RD->bases_end(); I != E; ++I) {
948     bool IsVirtual = I->isVirtual();
949 
950     const CXXRecordDecl *BaseDecl =
951       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
952 
953     Info->Bases.push_back(ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, Info));
954   }
955 
956   if (PrimaryVirtualBase && !PrimaryVirtualBaseInfo) {
957     // Traversing the bases must have created the base info for our primary
958     // virtual base.
959     PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
960     assert(PrimaryVirtualBaseInfo &&
961            "Did not create a primary virtual base!");
962 
963     // Claim the primary virtual base as our primary virtual base.
964     Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
965     PrimaryVirtualBaseInfo->Derived = Info;
966   }
967 
968   return Info;
969 }
970 
971 void RecordLayoutBuilder::ComputeBaseSubobjectInfo(const CXXRecordDecl *RD) {
972   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
973        E = RD->bases_end(); I != E; ++I) {
974     bool IsVirtual = I->isVirtual();
975 
976     const CXXRecordDecl *BaseDecl =
977       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
978 
979     // Compute the base subobject info for this base.
980     BaseSubobjectInfo *Info = ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, 0);
981 
982     if (IsVirtual) {
983       // ComputeBaseInfo has already added this base for us.
984       assert(VirtualBaseInfo.count(BaseDecl) &&
985              "Did not add virtual base!");
986     } else {
987       // Add the base info to the map of non-virtual bases.
988       assert(!NonVirtualBaseInfo.count(BaseDecl) &&
989              "Non-virtual base already exists!");
990       NonVirtualBaseInfo.insert(std::make_pair(BaseDecl, Info));
991     }
992   }
993 }
994 
995 void
996 RecordLayoutBuilder::EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign) {
997   CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
998 
999   // The maximum field alignment overrides base align.
1000   if (!MaxFieldAlignment.isZero()) {
1001     BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
1002     UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
1003   }
1004 
1005   // Round up the current record size to pointer alignment.
1006   setSize(getSize().RoundUpToAlignment(BaseAlign));
1007   setDataSize(getSize());
1008 
1009   // Update the alignment.
1010   UpdateAlignment(BaseAlign, UnpackedBaseAlign);
1011 }
1012 
1013 void
1014 RecordLayoutBuilder::LayoutNonVirtualBases(const CXXRecordDecl *RD) {
1015   // Then, determine the primary base class.
1016   DeterminePrimaryBase(RD);
1017 
1018   // Compute base subobject info.
1019   ComputeBaseSubobjectInfo(RD);
1020 
1021   // If we have a primary base class, lay it out.
1022   if (PrimaryBase) {
1023     if (PrimaryBaseIsVirtual) {
1024       // If the primary virtual base was a primary virtual base of some other
1025       // base class we'll have to steal it.
1026       BaseSubobjectInfo *PrimaryBaseInfo = VirtualBaseInfo.lookup(PrimaryBase);
1027       PrimaryBaseInfo->Derived = 0;
1028 
1029       // We have a virtual primary base, insert it as an indirect primary base.
1030       IndirectPrimaryBases.insert(PrimaryBase);
1031 
1032       assert(!VisitedVirtualBases.count(PrimaryBase) &&
1033              "vbase already visited!");
1034       VisitedVirtualBases.insert(PrimaryBase);
1035 
1036       LayoutVirtualBase(PrimaryBaseInfo);
1037     } else {
1038       BaseSubobjectInfo *PrimaryBaseInfo =
1039         NonVirtualBaseInfo.lookup(PrimaryBase);
1040       assert(PrimaryBaseInfo &&
1041              "Did not find base info for non-virtual primary base!");
1042 
1043       LayoutNonVirtualBase(PrimaryBaseInfo);
1044     }
1045 
1046   // If this class needs a vtable/vf-table and didn't get one from a
1047   // primary base, add it in now.
1048   } else if (needsVFTable(RD)) {
1049     assert(DataSize == 0 && "Vtable pointer must be at offset zero!");
1050     CharUnits PtrWidth =
1051       Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
1052     CharUnits PtrAlign =
1053       Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0));
1054     EnsureVTablePointerAlignment(PtrAlign);
1055     HasOwnVFPtr = true;
1056     setSize(getSize() + PtrWidth);
1057     setDataSize(getSize());
1058   }
1059 
1060   bool HasDirectVirtualBases = false;
1061   bool HasNonVirtualBaseWithVBTable = false;
1062 
1063   // Now lay out the non-virtual bases.
1064   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1065          E = RD->bases_end(); I != E; ++I) {
1066 
1067     // Ignore virtual bases, but remember that we saw one.
1068     if (I->isVirtual()) {
1069       HasDirectVirtualBases = true;
1070       continue;
1071     }
1072 
1073     const CXXRecordDecl *BaseDecl =
1074       cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
1075 
1076     // Remember if this base has virtual bases itself.
1077     if (BaseDecl->getNumVBases())
1078       HasNonVirtualBaseWithVBTable = true;
1079 
1080     // Skip the primary base, because we've already laid it out.  The
1081     // !PrimaryBaseIsVirtual check is required because we might have a
1082     // non-virtual base of the same type as a primary virtual base.
1083     if (BaseDecl == PrimaryBase && !PrimaryBaseIsVirtual)
1084       continue;
1085 
1086     // Lay out the base.
1087     BaseSubobjectInfo *BaseInfo = NonVirtualBaseInfo.lookup(BaseDecl);
1088     assert(BaseInfo && "Did not find base info for non-virtual base!");
1089 
1090     LayoutNonVirtualBase(BaseInfo);
1091   }
1092 
1093   // In the MS ABI, add the vb-table pointer if we need one, which is
1094   // whenever we have a virtual base and we can't re-use a vb-table
1095   // pointer from a non-virtual base.
1096   if (isMicrosoftCXXABI() &&
1097       HasDirectVirtualBases && !HasNonVirtualBaseWithVBTable) {
1098     CharUnits PtrWidth =
1099       Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
1100     CharUnits PtrAlign =
1101       Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0));
1102 
1103     // MSVC potentially over-aligns the vb-table pointer by giving it
1104     // the max alignment of all the non-virtual objects in the class.
1105     // This is completely unnecessary, but we're not here to pass
1106     // judgment.
1107     //
1108     // Note that we've only laid out the non-virtual bases, so on the
1109     // first pass Alignment won't be set correctly here, but if the
1110     // vb-table doesn't end up aligned correctly we'll come through
1111     // and redo the layout from scratch with the right alignment.
1112     //
1113     // TODO: Instead of doing this, just lay out the fields as if the
1114     // vb-table were at offset zero, then retroactively bump the field
1115     // offsets up.
1116     PtrAlign = std::max(PtrAlign, Alignment);
1117 
1118     EnsureVTablePointerAlignment(PtrAlign);
1119     VBPtrOffset = getSize();
1120     setSize(getSize() + PtrWidth);
1121     setDataSize(getSize());
1122   }
1123 }
1124 
1125 void RecordLayoutBuilder::LayoutNonVirtualBase(const BaseSubobjectInfo *Base) {
1126   // Layout the base.
1127   CharUnits Offset = LayoutBase(Base);
1128 
1129   // Add its base class offset.
1130   assert(!Bases.count(Base->Class) && "base offset already exists!");
1131   Bases.insert(std::make_pair(Base->Class, Offset));
1132 
1133   AddPrimaryVirtualBaseOffsets(Base, Offset);
1134 }
1135 
1136 void
1137 RecordLayoutBuilder::AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
1138                                                   CharUnits Offset) {
1139   // This base isn't interesting, it has no virtual bases.
1140   if (!Info->Class->getNumVBases())
1141     return;
1142 
1143   // First, check if we have a virtual primary base to add offsets for.
1144   if (Info->PrimaryVirtualBaseInfo) {
1145     assert(Info->PrimaryVirtualBaseInfo->IsVirtual &&
1146            "Primary virtual base is not virtual!");
1147     if (Info->PrimaryVirtualBaseInfo->Derived == Info) {
1148       // Add the offset.
1149       assert(!VBases.count(Info->PrimaryVirtualBaseInfo->Class) &&
1150              "primary vbase offset already exists!");
1151       VBases.insert(std::make_pair(Info->PrimaryVirtualBaseInfo->Class,
1152                                    ASTRecordLayout::VBaseInfo(Offset, false)));
1153 
1154       // Traverse the primary virtual base.
1155       AddPrimaryVirtualBaseOffsets(Info->PrimaryVirtualBaseInfo, Offset);
1156     }
1157   }
1158 
1159   // Now go through all direct non-virtual bases.
1160   const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
1161   for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) {
1162     const BaseSubobjectInfo *Base = Info->Bases[I];
1163     if (Base->IsVirtual)
1164       continue;
1165 
1166     CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
1167     AddPrimaryVirtualBaseOffsets(Base, BaseOffset);
1168   }
1169 }
1170 
1171 /// needsVFTable - Return true if this class needs a vtable or vf-table
1172 /// when laid out as a base class.  These are treated the same because
1173 /// they're both always laid out at offset zero.
1174 ///
1175 /// This function assumes that the class has no primary base.
1176 bool RecordLayoutBuilder::needsVFTable(const CXXRecordDecl *RD) const {
1177   assert(!PrimaryBase);
1178 
1179   // In the Itanium ABI, every dynamic class needs a vtable: even if
1180   // this class has no virtual functions as a base class (i.e. it's
1181   // non-polymorphic or only has virtual functions from virtual
1182   // bases),x it still needs a vtable to locate its virtual bases.
1183   if (!isMicrosoftCXXABI())
1184     return RD->isDynamicClass();
1185 
1186   // In the MS ABI, we need a vfptr if the class has virtual functions
1187   // other than those declared by its virtual bases.  The AST doesn't
1188   // tell us that directly, and checking manually for virtual
1189   // functions that aren't overrides is expensive, but there are
1190   // some important shortcuts:
1191 
1192   //  - Non-polymorphic classes have no virtual functions at all.
1193   if (!RD->isPolymorphic()) return false;
1194 
1195   //  - Polymorphic classes with no virtual bases must either declare
1196   //    virtual functions directly or inherit them, but in the latter
1197   //    case we would have a primary base.
1198   if (RD->getNumVBases() == 0) return true;
1199 
1200   return hasNewVirtualFunction(RD);
1201 }
1202 
1203 /// Does the given class inherit non-virtually from any of the classes
1204 /// in the given set?
1205 static bool hasNonVirtualBaseInSet(const CXXRecordDecl *RD,
1206                                    const ClassSetTy &set) {
1207   for (CXXRecordDecl::base_class_const_iterator
1208          I = RD->bases_begin(), E = RD->bases_end(); I != E; ++I) {
1209     // Ignore virtual links.
1210     if (I->isVirtual()) continue;
1211 
1212     // Check whether the set contains the base.
1213     const CXXRecordDecl *base = I->getType()->getAsCXXRecordDecl();
1214     if (set.count(base))
1215       return true;
1216 
1217     // Otherwise, recurse and propagate.
1218     if (hasNonVirtualBaseInSet(base, set))
1219       return true;
1220   }
1221 
1222   return false;
1223 }
1224 
1225 /// Does the given method (B::foo()) already override a method (A::foo())
1226 /// such that A requires a vtordisp in B?  If so, we don't need to add a
1227 /// new vtordisp for B in a yet-more-derived class C providing C::foo().
1228 static bool overridesMethodRequiringVtorDisp(const ASTContext &Context,
1229                                              const CXXMethodDecl *M) {
1230   CXXMethodDecl::method_iterator
1231     I = M->begin_overridden_methods(), E = M->end_overridden_methods();
1232   if (I == E) return false;
1233 
1234   const ASTRecordLayout::VBaseOffsetsMapTy &offsets =
1235     Context.getASTRecordLayout(M->getParent()).getVBaseOffsetsMap();
1236   do {
1237     const CXXMethodDecl *overridden = *I;
1238 
1239     // If the overridden method's class isn't recognized as a virtual
1240     // base in the derived class, ignore it.
1241     ASTRecordLayout::VBaseOffsetsMapTy::const_iterator
1242       it = offsets.find(overridden->getParent());
1243     if (it == offsets.end()) continue;
1244 
1245     // Otherwise, check if the overridden method's class needs a vtordisp.
1246     if (it->second.hasVtorDisp()) return true;
1247 
1248   } while (++I != E);
1249   return false;
1250 }
1251 
1252 /// In the Microsoft ABI, decide which of the virtual bases require a
1253 /// vtordisp field.
1254 void RecordLayoutBuilder::computeVtordisps(const CXXRecordDecl *RD,
1255                                            ClassSetTy &vtordispVBases) {
1256   // Bail out if we have no virtual bases.
1257   assert(RD->getNumVBases());
1258 
1259   // Build up the set of virtual bases that we haven't decided yet.
1260   ClassSetTy undecidedVBases;
1261   for (CXXRecordDecl::base_class_const_iterator
1262          I = RD->vbases_begin(), E = RD->vbases_end(); I != E; ++I) {
1263     const CXXRecordDecl *vbase = I->getType()->getAsCXXRecordDecl();
1264     undecidedVBases.insert(vbase);
1265   }
1266   assert(!undecidedVBases.empty());
1267 
1268   // A virtual base requires a vtordisp field in a derived class if it
1269   // requires a vtordisp field in a base class.  Walk all the direct
1270   // bases and collect this information.
1271   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1272        E = RD->bases_end(); I != E; ++I) {
1273     const CXXRecordDecl *base = I->getType()->getAsCXXRecordDecl();
1274     const ASTRecordLayout &baseLayout = Context.getASTRecordLayout(base);
1275 
1276     // Iterate over the set of virtual bases provided by this class.
1277     for (ASTRecordLayout::VBaseOffsetsMapTy::const_iterator
1278            VI = baseLayout.getVBaseOffsetsMap().begin(),
1279            VE = baseLayout.getVBaseOffsetsMap().end(); VI != VE; ++VI) {
1280       // If it doesn't need a vtordisp in this base, ignore it.
1281       if (!VI->second.hasVtorDisp()) continue;
1282 
1283       // If we've already seen it and decided it needs a vtordisp, ignore it.
1284       if (!undecidedVBases.erase(VI->first))
1285         continue;
1286 
1287       // Add it.
1288       vtordispVBases.insert(VI->first);
1289 
1290       // Quit as soon as we've decided everything.
1291       if (undecidedVBases.empty())
1292         return;
1293     }
1294   }
1295 
1296   // Okay, we have virtual bases that we haven't yet decided about.  A
1297   // virtual base requires a vtordisp if any the non-destructor
1298   // virtual methods declared in this class directly override a method
1299   // provided by that virtual base.  (If so, we need to emit a thunk
1300   // for that method, to be used in the construction vftable, which
1301   // applies an additional 'vtordisp' this-adjustment.)
1302 
1303   // Collect the set of bases directly overridden by any method in this class.
1304   // It's possible that some of these classes won't be virtual bases, or won't be
1305   // provided by virtual bases, or won't be virtual bases in the overridden
1306   // instance but are virtual bases elsewhere.  Only the last matters for what
1307   // we're doing, and we can ignore those:  if we don't directly override
1308   // a method provided by a virtual copy of a base class, but we do directly
1309   // override a method provided by a non-virtual copy of that base class,
1310   // then we must indirectly override the method provided by the virtual base,
1311   // and so we should already have collected it in the loop above.
1312   ClassSetTy overriddenBases;
1313   for (CXXRecordDecl::method_iterator
1314          M = RD->method_begin(), E = RD->method_end(); M != E; ++M) {
1315     // Ignore non-virtual methods and destructors.
1316     if (isa<CXXDestructorDecl>(*M) || !M->isVirtual())
1317       continue;
1318 
1319     for (CXXMethodDecl::method_iterator I = M->begin_overridden_methods(),
1320           E = M->end_overridden_methods(); I != E; ++I) {
1321       const CXXMethodDecl *overriddenMethod = (*I);
1322 
1323       // Ignore methods that override methods from vbases that require
1324       // require vtordisps.
1325       if (overridesMethodRequiringVtorDisp(Context, overriddenMethod))
1326         continue;
1327 
1328       // As an optimization, check immediately whether we're overriding
1329       // something from the undecided set.
1330       const CXXRecordDecl *overriddenBase = overriddenMethod->getParent();
1331       if (undecidedVBases.erase(overriddenBase)) {
1332         vtordispVBases.insert(overriddenBase);
1333         if (undecidedVBases.empty()) return;
1334 
1335         // We can't 'continue;' here because one of our undecided
1336         // vbases might non-virtually inherit from this base.
1337         // Consider:
1338         //   struct A { virtual void foo(); };
1339         //   struct B : A {};
1340         //   struct C : virtual A, virtual B { virtual void foo(); };
1341         // We need a vtordisp for B here.
1342       }
1343 
1344       // Otherwise, just collect it.
1345       overriddenBases.insert(overriddenBase);
1346     }
1347   }
1348 
1349   // Walk the undecided v-bases and check whether they (non-virtually)
1350   // provide any of the overridden bases.  We don't need to consider
1351   // virtual links because the vtordisp inheres to the layout
1352   // subobject containing the base.
1353   for (ClassSetTy::const_iterator
1354          I = undecidedVBases.begin(), E = undecidedVBases.end(); I != E; ++I) {
1355     if (hasNonVirtualBaseInSet(*I, overriddenBases))
1356       vtordispVBases.insert(*I);
1357   }
1358 }
1359 
1360 /// hasNewVirtualFunction - Does the given polymorphic class declare a
1361 /// virtual function that does not override a method from any of its
1362 /// base classes?
1363 bool
1364 RecordLayoutBuilder::hasNewVirtualFunction(const CXXRecordDecl *RD,
1365                                            bool IgnoreDestructor) const {
1366   if (!RD->getNumBases())
1367     return true;
1368 
1369   for (CXXRecordDecl::method_iterator method = RD->method_begin();
1370        method != RD->method_end();
1371        ++method) {
1372     if (method->isVirtual() && !method->size_overridden_methods() &&
1373         !(IgnoreDestructor && method->getKind() == Decl::CXXDestructor)) {
1374       return true;
1375     }
1376   }
1377   return false;
1378 }
1379 
1380 /// isPossiblePrimaryBase - Is the given base class an acceptable
1381 /// primary base class?
1382 bool
1383 RecordLayoutBuilder::isPossiblePrimaryBase(const CXXRecordDecl *base) const {
1384   // In the Itanium ABI, a class can be a primary base class if it has
1385   // a vtable for any reason.
1386   if (!isMicrosoftCXXABI())
1387     return base->isDynamicClass();
1388 
1389   // In the MS ABI, a class can only be a primary base class if it
1390   // provides a vf-table at a static offset.  That means it has to be
1391   // non-virtual base.  The existence of a separate vb-table means
1392   // that it's possible to get virtual functions only from a virtual
1393   // base, which we have to guard against.
1394 
1395   // First off, it has to have virtual functions.
1396   if (!base->isPolymorphic()) return false;
1397 
1398   // If it has no virtual bases, then the vfptr must be at a static offset.
1399   if (!base->getNumVBases()) return true;
1400 
1401   // Otherwise, the necessary information is cached in the layout.
1402   const ASTRecordLayout &layout = Context.getASTRecordLayout(base);
1403 
1404   // If the base has its own vfptr, it can be a primary base.
1405   if (layout.hasOwnVFPtr()) return true;
1406 
1407   // If the base has a primary base class, then it can be a primary base.
1408   if (layout.getPrimaryBase()) return true;
1409 
1410   // Otherwise it can't.
1411   return false;
1412 }
1413 
1414 void
1415 RecordLayoutBuilder::LayoutVirtualBases(const CXXRecordDecl *RD,
1416                                         const CXXRecordDecl *MostDerivedClass) {
1417   const CXXRecordDecl *PrimaryBase;
1418   bool PrimaryBaseIsVirtual;
1419 
1420   if (MostDerivedClass == RD) {
1421     PrimaryBase = this->PrimaryBase;
1422     PrimaryBaseIsVirtual = this->PrimaryBaseIsVirtual;
1423   } else {
1424     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1425     PrimaryBase = Layout.getPrimaryBase();
1426     PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
1427   }
1428 
1429   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1430          E = RD->bases_end(); I != E; ++I) {
1431     assert(!I->getType()->isDependentType() &&
1432            "Cannot layout class with dependent bases.");
1433 
1434     const CXXRecordDecl *BaseDecl =
1435       cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
1436 
1437     if (I->isVirtual()) {
1438       if (PrimaryBase != BaseDecl || !PrimaryBaseIsVirtual) {
1439         bool IndirectPrimaryBase = IndirectPrimaryBases.count(BaseDecl);
1440 
1441         // Only lay out the virtual base if it's not an indirect primary base.
1442         if (!IndirectPrimaryBase) {
1443           // Only visit virtual bases once.
1444           if (!VisitedVirtualBases.insert(BaseDecl))
1445             continue;
1446 
1447           const BaseSubobjectInfo *BaseInfo = VirtualBaseInfo.lookup(BaseDecl);
1448           assert(BaseInfo && "Did not find virtual base info!");
1449           LayoutVirtualBase(BaseInfo);
1450         }
1451       }
1452     }
1453 
1454     if (!BaseDecl->getNumVBases()) {
1455       // This base isn't interesting since it doesn't have any virtual bases.
1456       continue;
1457     }
1458 
1459     LayoutVirtualBases(BaseDecl, MostDerivedClass);
1460   }
1461 }
1462 
1463 void RecordLayoutBuilder::MSLayoutVirtualBases(const CXXRecordDecl *RD) {
1464   if (!RD->getNumVBases())
1465     return;
1466 
1467   ClassSetTy VtordispVBases;
1468   computeVtordisps(RD, VtordispVBases);
1469 
1470   // This is substantially simplified because there are no virtual
1471   // primary bases.
1472   for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
1473        E = RD->vbases_end(); I != E; ++I) {
1474     const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
1475     const BaseSubobjectInfo *BaseInfo = VirtualBaseInfo.lookup(BaseDecl);
1476     assert(BaseInfo && "Did not find virtual base info!");
1477 
1478     // If this base requires a vtordisp, add enough space for an int field.
1479     // This is apparently always 32-bits, even on x64.
1480     bool vtordispNeeded = false;
1481     if (VtordispVBases.count(BaseDecl)) {
1482       CharUnits IntSize =
1483         CharUnits::fromQuantity(Context.getTargetInfo().getIntWidth() / 8);
1484 
1485       setSize(getSize() + IntSize);
1486       setDataSize(getSize());
1487       vtordispNeeded = true;
1488     }
1489 
1490     LayoutVirtualBase(BaseInfo, vtordispNeeded);
1491   }
1492 }
1493 
1494 void RecordLayoutBuilder::LayoutVirtualBase(const BaseSubobjectInfo *Base,
1495                                             bool IsVtordispNeed) {
1496   assert(!Base->Derived && "Trying to lay out a primary virtual base!");
1497 
1498   // Layout the base.
1499   CharUnits Offset = LayoutBase(Base);
1500 
1501   // Add its base class offset.
1502   assert(!VBases.count(Base->Class) && "vbase offset already exists!");
1503   VBases.insert(std::make_pair(Base->Class,
1504                        ASTRecordLayout::VBaseInfo(Offset, IsVtordispNeed)));
1505 
1506   if (!isMicrosoftCXXABI())
1507     AddPrimaryVirtualBaseOffsets(Base, Offset);
1508 }
1509 
1510 CharUnits RecordLayoutBuilder::LayoutBase(const BaseSubobjectInfo *Base) {
1511   const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base->Class);
1512 
1513 
1514   CharUnits Offset;
1515 
1516   // Query the external layout to see if it provides an offset.
1517   bool HasExternalLayout = false;
1518   if (ExternalLayout) {
1519     llvm::DenseMap<const CXXRecordDecl *, CharUnits>::iterator Known;
1520     if (Base->IsVirtual) {
1521       Known = ExternalVirtualBaseOffsets.find(Base->Class);
1522       if (Known != ExternalVirtualBaseOffsets.end()) {
1523         Offset = Known->second;
1524         HasExternalLayout = true;
1525       }
1526     } else {
1527       Known = ExternalBaseOffsets.find(Base->Class);
1528       if (Known != ExternalBaseOffsets.end()) {
1529         Offset = Known->second;
1530         HasExternalLayout = true;
1531       }
1532     }
1533   }
1534 
1535   CharUnits UnpackedBaseAlign = Layout.getNonVirtualAlign();
1536   CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
1537 
1538   // If we have an empty base class, try to place it at offset 0.
1539   if (Base->Class->isEmpty() &&
1540       (!HasExternalLayout || Offset == CharUnits::Zero()) &&
1541       EmptySubobjects->CanPlaceBaseAtOffset(Base, CharUnits::Zero())) {
1542     setSize(std::max(getSize(), Layout.getSize()));
1543     UpdateAlignment(BaseAlign, UnpackedBaseAlign);
1544 
1545     return CharUnits::Zero();
1546   }
1547 
1548   // The maximum field alignment overrides base align.
1549   if (!MaxFieldAlignment.isZero()) {
1550     BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
1551     UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
1552   }
1553 
1554   if (!HasExternalLayout) {
1555     // Round up the current record size to the base's alignment boundary.
1556     Offset = getDataSize().RoundUpToAlignment(BaseAlign);
1557 
1558     // Try to place the base.
1559     while (!EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset))
1560       Offset += BaseAlign;
1561   } else {
1562     bool Allowed = EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset);
1563     (void)Allowed;
1564     assert(Allowed && "Base subobject externally placed at overlapping offset");
1565 
1566     if (InferAlignment && Offset < getDataSize().RoundUpToAlignment(BaseAlign)){
1567       // The externally-supplied base offset is before the base offset we
1568       // computed. Assume that the structure is packed.
1569       Alignment = CharUnits::One();
1570       InferAlignment = false;
1571     }
1572   }
1573 
1574   if (!Base->Class->isEmpty()) {
1575     // Update the data size.
1576     setDataSize(Offset + Layout.getNonVirtualSize());
1577 
1578     setSize(std::max(getSize(), getDataSize()));
1579   } else
1580     setSize(std::max(getSize(), Offset + Layout.getSize()));
1581 
1582   // Remember max struct/class alignment.
1583   UpdateAlignment(BaseAlign, UnpackedBaseAlign);
1584 
1585   return Offset;
1586 }
1587 
1588 void RecordLayoutBuilder::InitializeLayout(const Decl *D) {
1589   if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
1590     IsUnion = RD->isUnion();
1591     IsMsStruct = RD->isMsStruct(Context);
1592   }
1593 
1594   Packed = D->hasAttr<PackedAttr>();
1595 
1596   // Honor the default struct packing maximum alignment flag.
1597   if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct) {
1598     MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
1599   }
1600 
1601   // mac68k alignment supersedes maximum field alignment and attribute aligned,
1602   // and forces all structures to have 2-byte alignment. The IBM docs on it
1603   // allude to additional (more complicated) semantics, especially with regard
1604   // to bit-fields, but gcc appears not to follow that.
1605   if (D->hasAttr<AlignMac68kAttr>()) {
1606     IsMac68kAlign = true;
1607     MaxFieldAlignment = CharUnits::fromQuantity(2);
1608     Alignment = CharUnits::fromQuantity(2);
1609   } else {
1610     if (const MaxFieldAlignmentAttr *MFAA = D->getAttr<MaxFieldAlignmentAttr>())
1611       MaxFieldAlignment = Context.toCharUnitsFromBits(MFAA->getAlignment());
1612 
1613     if (unsigned MaxAlign = D->getMaxAlignment())
1614       UpdateAlignment(Context.toCharUnitsFromBits(MaxAlign));
1615   }
1616 
1617   // If there is an external AST source, ask it for the various offsets.
1618   if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
1619     if (ExternalASTSource *External = Context.getExternalSource()) {
1620       ExternalLayout = External->layoutRecordType(RD,
1621                                                   ExternalSize,
1622                                                   ExternalAlign,
1623                                                   ExternalFieldOffsets,
1624                                                   ExternalBaseOffsets,
1625                                                   ExternalVirtualBaseOffsets);
1626 
1627       // Update based on external alignment.
1628       if (ExternalLayout) {
1629         if (ExternalAlign > 0) {
1630           Alignment = Context.toCharUnitsFromBits(ExternalAlign);
1631         } else {
1632           // The external source didn't have alignment information; infer it.
1633           InferAlignment = true;
1634         }
1635       }
1636     }
1637 }
1638 
1639 void RecordLayoutBuilder::Layout(const RecordDecl *D) {
1640   InitializeLayout(D);
1641   LayoutFields(D);
1642 
1643   // Finally, round the size of the total struct up to the alignment of the
1644   // struct itself.
1645   FinishLayout(D);
1646 }
1647 
1648 void RecordLayoutBuilder::Layout(const CXXRecordDecl *RD) {
1649   InitializeLayout(RD);
1650 
1651   // Lay out the vtable and the non-virtual bases.
1652   LayoutNonVirtualBases(RD);
1653 
1654   LayoutFields(RD);
1655 
1656   NonVirtualSize = Context.toCharUnitsFromBits(
1657         llvm::RoundUpToAlignment(getSizeInBits(),
1658                                  Context.getTargetInfo().getCharAlign()));
1659   NonVirtualAlignment = Alignment;
1660 
1661   if (isMicrosoftCXXABI()) {
1662     if (NonVirtualSize != NonVirtualSize.RoundUpToAlignment(Alignment)) {
1663     CharUnits AlignMember =
1664       NonVirtualSize.RoundUpToAlignment(Alignment) - NonVirtualSize;
1665 
1666     setSize(getSize() + AlignMember);
1667     setDataSize(getSize());
1668 
1669     NonVirtualSize = Context.toCharUnitsFromBits(
1670                              llvm::RoundUpToAlignment(getSizeInBits(),
1671                              Context.getTargetInfo().getCharAlign()));
1672     }
1673 
1674     MSLayoutVirtualBases(RD);
1675   } else {
1676     // Lay out the virtual bases and add the primary virtual base offsets.
1677     LayoutVirtualBases(RD, RD);
1678   }
1679 
1680   // Finally, round the size of the total struct up to the alignment
1681   // of the struct itself.
1682   FinishLayout(RD);
1683 
1684 #ifndef NDEBUG
1685   // Check that we have base offsets for all bases.
1686   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1687        E = RD->bases_end(); I != E; ++I) {
1688     if (I->isVirtual())
1689       continue;
1690 
1691     const CXXRecordDecl *BaseDecl =
1692       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1693 
1694     assert(Bases.count(BaseDecl) && "Did not find base offset!");
1695   }
1696 
1697   // And all virtual bases.
1698   for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
1699        E = RD->vbases_end(); I != E; ++I) {
1700     const CXXRecordDecl *BaseDecl =
1701       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1702 
1703     assert(VBases.count(BaseDecl) && "Did not find base offset!");
1704   }
1705 #endif
1706 }
1707 
1708 void RecordLayoutBuilder::Layout(const ObjCInterfaceDecl *D) {
1709   if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
1710     const ASTRecordLayout &SL = Context.getASTObjCInterfaceLayout(SD);
1711 
1712     UpdateAlignment(SL.getAlignment());
1713 
1714     // We start laying out ivars not at the end of the superclass
1715     // structure, but at the next byte following the last field.
1716     setSize(SL.getDataSize());
1717     setDataSize(getSize());
1718   }
1719 
1720   InitializeLayout(D);
1721   // Layout each ivar sequentially.
1722   for (const ObjCIvarDecl *IVD = D->all_declared_ivar_begin(); IVD;
1723        IVD = IVD->getNextIvar())
1724     LayoutField(IVD);
1725 
1726   // Finally, round the size of the total struct up to the alignment of the
1727   // struct itself.
1728   FinishLayout(D);
1729 }
1730 
1731 void RecordLayoutBuilder::LayoutFields(const RecordDecl *D) {
1732   // Layout each field, for now, just sequentially, respecting alignment.  In
1733   // the future, this will need to be tweakable by targets.
1734   for (RecordDecl::field_iterator Field = D->field_begin(),
1735        FieldEnd = D->field_end(); Field != FieldEnd; ++Field)
1736     LayoutField(*Field);
1737 }
1738 
1739 void RecordLayoutBuilder::LayoutWideBitField(uint64_t FieldSize,
1740                                              uint64_t TypeSize,
1741                                              bool FieldPacked,
1742                                              const FieldDecl *D) {
1743   assert(Context.getLangOpts().CPlusPlus &&
1744          "Can only have wide bit-fields in C++!");
1745 
1746   // Itanium C++ ABI 2.4:
1747   //   If sizeof(T)*8 < n, let T' be the largest integral POD type with
1748   //   sizeof(T')*8 <= n.
1749 
1750   QualType IntegralPODTypes[] = {
1751     Context.UnsignedCharTy, Context.UnsignedShortTy, Context.UnsignedIntTy,
1752     Context.UnsignedLongTy, Context.UnsignedLongLongTy
1753   };
1754 
1755   QualType Type;
1756   for (unsigned I = 0, E = llvm::array_lengthof(IntegralPODTypes);
1757        I != E; ++I) {
1758     uint64_t Size = Context.getTypeSize(IntegralPODTypes[I]);
1759 
1760     if (Size > FieldSize)
1761       break;
1762 
1763     Type = IntegralPODTypes[I];
1764   }
1765   assert(!Type.isNull() && "Did not find a type!");
1766 
1767   CharUnits TypeAlign = Context.getTypeAlignInChars(Type);
1768 
1769   // We're not going to use any of the unfilled bits in the last byte.
1770   UnfilledBitsInLastUnit = 0;
1771   LastBitfieldTypeSize = 0;
1772 
1773   uint64_t FieldOffset;
1774   uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
1775 
1776   if (IsUnion) {
1777     setDataSize(std::max(getDataSizeInBits(), FieldSize));
1778     FieldOffset = 0;
1779   } else {
1780     // The bitfield is allocated starting at the next offset aligned
1781     // appropriately for T', with length n bits.
1782     FieldOffset = llvm::RoundUpToAlignment(getDataSizeInBits(),
1783                                            Context.toBits(TypeAlign));
1784 
1785     uint64_t NewSizeInBits = FieldOffset + FieldSize;
1786 
1787     setDataSize(llvm::RoundUpToAlignment(NewSizeInBits,
1788                                          Context.getTargetInfo().getCharAlign()));
1789     UnfilledBitsInLastUnit = getDataSizeInBits() - NewSizeInBits;
1790   }
1791 
1792   // Place this field at the current location.
1793   FieldOffsets.push_back(FieldOffset);
1794 
1795   CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, FieldOffset,
1796                     Context.toBits(TypeAlign), FieldPacked, D);
1797 
1798   // Update the size.
1799   setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1800 
1801   // Remember max struct/class alignment.
1802   UpdateAlignment(TypeAlign);
1803 }
1804 
1805 void RecordLayoutBuilder::LayoutBitField(const FieldDecl *D) {
1806   bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
1807   uint64_t FieldSize = D->getBitWidthValue(Context);
1808   std::pair<uint64_t, unsigned> FieldInfo = Context.getTypeInfo(D->getType());
1809   uint64_t TypeSize = FieldInfo.first;
1810   unsigned FieldAlign = FieldInfo.second;
1811 
1812   if (IsMsStruct) {
1813     // The field alignment for integer types in ms_struct structs is
1814     // always the size.
1815     FieldAlign = TypeSize;
1816     // Ignore zero-length bitfields after non-bitfields in ms_struct structs.
1817     if (!FieldSize && !LastBitfieldTypeSize)
1818       FieldAlign = 1;
1819     // If a bitfield is followed by a bitfield of a different size, don't
1820     // pack the bits together in ms_struct structs.
1821     if (LastBitfieldTypeSize != TypeSize) {
1822       UnfilledBitsInLastUnit = 0;
1823       LastBitfieldTypeSize = 0;
1824     }
1825   }
1826 
1827   uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
1828   uint64_t FieldOffset = IsUnion ? 0 : UnpaddedFieldOffset;
1829 
1830   bool ZeroLengthBitfield = false;
1831   if (!Context.getTargetInfo().useBitFieldTypeAlignment() &&
1832       Context.getTargetInfo().useZeroLengthBitfieldAlignment() &&
1833       FieldSize == 0) {
1834     // The alignment of a zero-length bitfield affects the alignment
1835     // of the next member.  The alignment is the max of the zero
1836     // length bitfield's alignment and a target specific fixed value.
1837     ZeroLengthBitfield = true;
1838     unsigned ZeroLengthBitfieldBoundary =
1839       Context.getTargetInfo().getZeroLengthBitfieldBoundary();
1840     if (ZeroLengthBitfieldBoundary > FieldAlign)
1841       FieldAlign = ZeroLengthBitfieldBoundary;
1842   }
1843 
1844   if (FieldSize > TypeSize) {
1845     LayoutWideBitField(FieldSize, TypeSize, FieldPacked, D);
1846     return;
1847   }
1848 
1849   // The align if the field is not packed. This is to check if the attribute
1850   // was unnecessary (-Wpacked).
1851   unsigned UnpackedFieldAlign = FieldAlign;
1852   uint64_t UnpackedFieldOffset = FieldOffset;
1853   if (!Context.getTargetInfo().useBitFieldTypeAlignment() && !ZeroLengthBitfield)
1854     UnpackedFieldAlign = 1;
1855 
1856   if (FieldPacked ||
1857       (!Context.getTargetInfo().useBitFieldTypeAlignment() && !ZeroLengthBitfield))
1858     FieldAlign = 1;
1859   FieldAlign = std::max(FieldAlign, D->getMaxAlignment());
1860   UnpackedFieldAlign = std::max(UnpackedFieldAlign, D->getMaxAlignment());
1861 
1862   // The maximum field alignment overrides the aligned attribute.
1863   if (!MaxFieldAlignment.isZero() && FieldSize != 0) {
1864     unsigned MaxFieldAlignmentInBits = Context.toBits(MaxFieldAlignment);
1865     FieldAlign = std::min(FieldAlign, MaxFieldAlignmentInBits);
1866     UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignmentInBits);
1867   }
1868 
1869   // ms_struct bitfields always have to start at a round alignment.
1870   if (IsMsStruct && !LastBitfieldTypeSize) {
1871     FieldOffset = llvm::RoundUpToAlignment(FieldOffset, FieldAlign);
1872     UnpackedFieldOffset = llvm::RoundUpToAlignment(UnpackedFieldOffset,
1873                                                    UnpackedFieldAlign);
1874   }
1875 
1876   // Check if we need to add padding to give the field the correct alignment.
1877   if (FieldSize == 0 ||
1878       (MaxFieldAlignment.isZero() &&
1879        (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize))
1880     FieldOffset = llvm::RoundUpToAlignment(FieldOffset, FieldAlign);
1881 
1882   if (FieldSize == 0 ||
1883       (MaxFieldAlignment.isZero() &&
1884        (UnpackedFieldOffset & (UnpackedFieldAlign-1)) + FieldSize > TypeSize))
1885     UnpackedFieldOffset = llvm::RoundUpToAlignment(UnpackedFieldOffset,
1886                                                    UnpackedFieldAlign);
1887 
1888   // Padding members don't affect overall alignment, unless zero length bitfield
1889   // alignment is enabled.
1890   if (!D->getIdentifier() &&
1891       !Context.getTargetInfo().useZeroLengthBitfieldAlignment() &&
1892       !IsMsStruct)
1893     FieldAlign = UnpackedFieldAlign = 1;
1894 
1895   if (ExternalLayout)
1896     FieldOffset = updateExternalFieldOffset(D, FieldOffset);
1897 
1898   // Place this field at the current location.
1899   FieldOffsets.push_back(FieldOffset);
1900 
1901   if (!ExternalLayout)
1902     CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, UnpackedFieldOffset,
1903                       UnpackedFieldAlign, FieldPacked, D);
1904 
1905   // Update DataSize to include the last byte containing (part of) the bitfield.
1906   if (IsUnion) {
1907     // FIXME: I think FieldSize should be TypeSize here.
1908     setDataSize(std::max(getDataSizeInBits(), FieldSize));
1909   } else {
1910     if (IsMsStruct && FieldSize) {
1911       // Under ms_struct, a bitfield always takes up space equal to the size
1912       // of the type.  We can't just change the alignment computation on the
1913       // other codepath because of the way this interacts with #pragma pack:
1914       // in a packed struct, we need to allocate misaligned space in the
1915       // struct to hold the bitfield.
1916       if (!UnfilledBitsInLastUnit) {
1917         setDataSize(FieldOffset + TypeSize);
1918         UnfilledBitsInLastUnit = TypeSize - FieldSize;
1919       } else if (UnfilledBitsInLastUnit < FieldSize) {
1920         setDataSize(getDataSizeInBits() + TypeSize);
1921         UnfilledBitsInLastUnit = TypeSize - FieldSize;
1922       } else {
1923         UnfilledBitsInLastUnit -= FieldSize;
1924       }
1925       LastBitfieldTypeSize = TypeSize;
1926     } else {
1927       uint64_t NewSizeInBits = FieldOffset + FieldSize;
1928       uint64_t BitfieldAlignment = Context.getTargetInfo().getCharAlign();
1929       setDataSize(llvm::RoundUpToAlignment(NewSizeInBits, BitfieldAlignment));
1930       UnfilledBitsInLastUnit = getDataSizeInBits() - NewSizeInBits;
1931       LastBitfieldTypeSize = 0;
1932     }
1933   }
1934 
1935   // Update the size.
1936   setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1937 
1938   // Remember max struct/class alignment.
1939   UpdateAlignment(Context.toCharUnitsFromBits(FieldAlign),
1940                   Context.toCharUnitsFromBits(UnpackedFieldAlign));
1941 }
1942 
1943 void RecordLayoutBuilder::LayoutField(const FieldDecl *D) {
1944   if (D->isBitField()) {
1945     LayoutBitField(D);
1946     return;
1947   }
1948 
1949   uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
1950 
1951   // Reset the unfilled bits.
1952   UnfilledBitsInLastUnit = 0;
1953   LastBitfieldTypeSize = 0;
1954 
1955   bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
1956   CharUnits FieldOffset =
1957     IsUnion ? CharUnits::Zero() : getDataSize();
1958   CharUnits FieldSize;
1959   CharUnits FieldAlign;
1960 
1961   if (D->getType()->isIncompleteArrayType()) {
1962     // This is a flexible array member; we can't directly
1963     // query getTypeInfo about these, so we figure it out here.
1964     // Flexible array members don't have any size, but they
1965     // have to be aligned appropriately for their element type.
1966     FieldSize = CharUnits::Zero();
1967     const ArrayType* ATy = Context.getAsArrayType(D->getType());
1968     FieldAlign = Context.getTypeAlignInChars(ATy->getElementType());
1969   } else if (const ReferenceType *RT = D->getType()->getAs<ReferenceType>()) {
1970     unsigned AS = RT->getPointeeType().getAddressSpace();
1971     FieldSize =
1972       Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(AS));
1973     FieldAlign =
1974       Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(AS));
1975   } else {
1976     std::pair<CharUnits, CharUnits> FieldInfo =
1977       Context.getTypeInfoInChars(D->getType());
1978     FieldSize = FieldInfo.first;
1979     FieldAlign = FieldInfo.second;
1980 
1981     if (IsMsStruct) {
1982       // If MS bitfield layout is required, figure out what type is being
1983       // laid out and align the field to the width of that type.
1984 
1985       // Resolve all typedefs down to their base type and round up the field
1986       // alignment if necessary.
1987       QualType T = Context.getBaseElementType(D->getType());
1988       if (const BuiltinType *BTy = T->getAs<BuiltinType>()) {
1989         CharUnits TypeSize = Context.getTypeSizeInChars(BTy);
1990         if (TypeSize > FieldAlign)
1991           FieldAlign = TypeSize;
1992       }
1993     }
1994   }
1995 
1996   // The align if the field is not packed. This is to check if the attribute
1997   // was unnecessary (-Wpacked).
1998   CharUnits UnpackedFieldAlign = FieldAlign;
1999   CharUnits UnpackedFieldOffset = FieldOffset;
2000 
2001   if (FieldPacked)
2002     FieldAlign = CharUnits::One();
2003   CharUnits MaxAlignmentInChars =
2004     Context.toCharUnitsFromBits(D->getMaxAlignment());
2005   FieldAlign = std::max(FieldAlign, MaxAlignmentInChars);
2006   UnpackedFieldAlign = std::max(UnpackedFieldAlign, MaxAlignmentInChars);
2007 
2008   // The maximum field alignment overrides the aligned attribute.
2009   if (!MaxFieldAlignment.isZero()) {
2010     FieldAlign = std::min(FieldAlign, MaxFieldAlignment);
2011     UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignment);
2012   }
2013 
2014   // Round up the current record size to the field's alignment boundary.
2015   FieldOffset = FieldOffset.RoundUpToAlignment(FieldAlign);
2016   UnpackedFieldOffset =
2017     UnpackedFieldOffset.RoundUpToAlignment(UnpackedFieldAlign);
2018 
2019   if (ExternalLayout) {
2020     FieldOffset = Context.toCharUnitsFromBits(
2021                     updateExternalFieldOffset(D, Context.toBits(FieldOffset)));
2022 
2023     if (!IsUnion && EmptySubobjects) {
2024       // Record the fact that we're placing a field at this offset.
2025       bool Allowed = EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset);
2026       (void)Allowed;
2027       assert(Allowed && "Externally-placed field cannot be placed here");
2028     }
2029   } else {
2030     if (!IsUnion && EmptySubobjects) {
2031       // Check if we can place the field at this offset.
2032       while (!EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset)) {
2033         // We couldn't place the field at the offset. Try again at a new offset.
2034         FieldOffset += FieldAlign;
2035       }
2036     }
2037   }
2038 
2039   // Place this field at the current location.
2040   FieldOffsets.push_back(Context.toBits(FieldOffset));
2041 
2042   if (!ExternalLayout)
2043     CheckFieldPadding(Context.toBits(FieldOffset), UnpaddedFieldOffset,
2044                       Context.toBits(UnpackedFieldOffset),
2045                       Context.toBits(UnpackedFieldAlign), FieldPacked, D);
2046 
2047   // Reserve space for this field.
2048   uint64_t FieldSizeInBits = Context.toBits(FieldSize);
2049   if (IsUnion)
2050     setDataSize(std::max(getDataSizeInBits(), FieldSizeInBits));
2051   else
2052     setDataSize(FieldOffset + FieldSize);
2053 
2054   // Update the size.
2055   setSize(std::max(getSizeInBits(), getDataSizeInBits()));
2056 
2057   // Remember max struct/class alignment.
2058   UpdateAlignment(FieldAlign, UnpackedFieldAlign);
2059 }
2060 
2061 void RecordLayoutBuilder::FinishLayout(const NamedDecl *D) {
2062   // In C++, records cannot be of size 0.
2063   if (Context.getLangOpts().CPlusPlus && getSizeInBits() == 0) {
2064     if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
2065       // Compatibility with gcc requires a class (pod or non-pod)
2066       // which is not empty but of size 0; such as having fields of
2067       // array of zero-length, remains of Size 0
2068       if (RD->isEmpty())
2069         setSize(CharUnits::One());
2070     }
2071     else
2072       setSize(CharUnits::One());
2073   }
2074 
2075   // Finally, round the size of the record up to the alignment of the
2076   // record itself.
2077   uint64_t UnpaddedSize = getSizeInBits() - UnfilledBitsInLastUnit;
2078   uint64_t UnpackedSizeInBits =
2079   llvm::RoundUpToAlignment(getSizeInBits(),
2080                            Context.toBits(UnpackedAlignment));
2081   CharUnits UnpackedSize = Context.toCharUnitsFromBits(UnpackedSizeInBits);
2082   uint64_t RoundedSize
2083     = llvm::RoundUpToAlignment(getSizeInBits(), Context.toBits(Alignment));
2084 
2085   if (ExternalLayout) {
2086     // If we're inferring alignment, and the external size is smaller than
2087     // our size after we've rounded up to alignment, conservatively set the
2088     // alignment to 1.
2089     if (InferAlignment && ExternalSize < RoundedSize) {
2090       Alignment = CharUnits::One();
2091       InferAlignment = false;
2092     }
2093     setSize(ExternalSize);
2094     return;
2095   }
2096 
2097 
2098   // MSVC doesn't round up to the alignment of the record with virtual bases.
2099   if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
2100     if (isMicrosoftCXXABI() && RD->getNumVBases())
2101       return;
2102   }
2103 
2104   // Set the size to the final size.
2105   setSize(RoundedSize);
2106 
2107   unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
2108   if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
2109     // Warn if padding was introduced to the struct/class/union.
2110     if (getSizeInBits() > UnpaddedSize) {
2111       unsigned PadSize = getSizeInBits() - UnpaddedSize;
2112       bool InBits = true;
2113       if (PadSize % CharBitNum == 0) {
2114         PadSize = PadSize / CharBitNum;
2115         InBits = false;
2116       }
2117       Diag(RD->getLocation(), diag::warn_padded_struct_size)
2118           << Context.getTypeDeclType(RD)
2119           << PadSize
2120           << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1); // plural or not
2121     }
2122 
2123     // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
2124     // bother since there won't be alignment issues.
2125     if (Packed && UnpackedAlignment > CharUnits::One() &&
2126         getSize() == UnpackedSize)
2127       Diag(D->getLocation(), diag::warn_unnecessary_packed)
2128           << Context.getTypeDeclType(RD);
2129   }
2130 }
2131 
2132 void RecordLayoutBuilder::UpdateAlignment(CharUnits NewAlignment,
2133                                           CharUnits UnpackedNewAlignment) {
2134   // The alignment is not modified when using 'mac68k' alignment or when
2135   // we have an externally-supplied layout that also provides overall alignment.
2136   if (IsMac68kAlign || (ExternalLayout && !InferAlignment))
2137     return;
2138 
2139   if (NewAlignment > Alignment) {
2140     assert(llvm::isPowerOf2_32(NewAlignment.getQuantity() &&
2141            "Alignment not a power of 2"));
2142     Alignment = NewAlignment;
2143   }
2144 
2145   if (UnpackedNewAlignment > UnpackedAlignment) {
2146     assert(llvm::isPowerOf2_32(UnpackedNewAlignment.getQuantity() &&
2147            "Alignment not a power of 2"));
2148     UnpackedAlignment = UnpackedNewAlignment;
2149   }
2150 }
2151 
2152 uint64_t
2153 RecordLayoutBuilder::updateExternalFieldOffset(const FieldDecl *Field,
2154                                                uint64_t ComputedOffset) {
2155   assert(ExternalFieldOffsets.find(Field) != ExternalFieldOffsets.end() &&
2156          "Field does not have an external offset");
2157 
2158   uint64_t ExternalFieldOffset = ExternalFieldOffsets[Field];
2159 
2160   if (InferAlignment && ExternalFieldOffset < ComputedOffset) {
2161     // The externally-supplied field offset is before the field offset we
2162     // computed. Assume that the structure is packed.
2163     Alignment = CharUnits::One();
2164     InferAlignment = false;
2165   }
2166 
2167   // Use the externally-supplied field offset.
2168   return ExternalFieldOffset;
2169 }
2170 
2171 /// \brief Get diagnostic %select index for tag kind for
2172 /// field padding diagnostic message.
2173 /// WARNING: Indexes apply to particular diagnostics only!
2174 ///
2175 /// \returns diagnostic %select index.
2176 static unsigned getPaddingDiagFromTagKind(TagTypeKind Tag) {
2177   switch (Tag) {
2178   case TTK_Struct: return 0;
2179   case TTK_Interface: return 1;
2180   case TTK_Class: return 2;
2181   default: llvm_unreachable("Invalid tag kind for field padding diagnostic!");
2182   }
2183 }
2184 
2185 void RecordLayoutBuilder::CheckFieldPadding(uint64_t Offset,
2186                                             uint64_t UnpaddedOffset,
2187                                             uint64_t UnpackedOffset,
2188                                             unsigned UnpackedAlign,
2189                                             bool isPacked,
2190                                             const FieldDecl *D) {
2191   // We let objc ivars without warning, objc interfaces generally are not used
2192   // for padding tricks.
2193   if (isa<ObjCIvarDecl>(D))
2194     return;
2195 
2196   // Don't warn about structs created without a SourceLocation.  This can
2197   // be done by clients of the AST, such as codegen.
2198   if (D->getLocation().isInvalid())
2199     return;
2200 
2201   unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
2202 
2203   // Warn if padding was introduced to the struct/class.
2204   if (!IsUnion && Offset > UnpaddedOffset) {
2205     unsigned PadSize = Offset - UnpaddedOffset;
2206     bool InBits = true;
2207     if (PadSize % CharBitNum == 0) {
2208       PadSize = PadSize / CharBitNum;
2209       InBits = false;
2210     }
2211     if (D->getIdentifier())
2212       Diag(D->getLocation(), diag::warn_padded_struct_field)
2213           << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
2214           << Context.getTypeDeclType(D->getParent())
2215           << PadSize
2216           << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1) // plural or not
2217           << D->getIdentifier();
2218     else
2219       Diag(D->getLocation(), diag::warn_padded_struct_anon_field)
2220           << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
2221           << Context.getTypeDeclType(D->getParent())
2222           << PadSize
2223           << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1); // plural or not
2224   }
2225 
2226   // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
2227   // bother since there won't be alignment issues.
2228   if (isPacked && UnpackedAlign > CharBitNum && Offset == UnpackedOffset)
2229     Diag(D->getLocation(), diag::warn_unnecessary_packed)
2230         << D->getIdentifier();
2231 }
2232 
2233 static const CXXMethodDecl *computeKeyFunction(ASTContext &Context,
2234                                                const CXXRecordDecl *RD) {
2235   // If a class isn't polymorphic it doesn't have a key function.
2236   if (!RD->isPolymorphic())
2237     return 0;
2238 
2239   // A class that is not externally visible doesn't have a key function. (Or
2240   // at least, there's no point to assigning a key function to such a class;
2241   // this doesn't affect the ABI.)
2242   if (!RD->isExternallyVisible())
2243     return 0;
2244 
2245   // Template instantiations don't have key functions,see Itanium C++ ABI 5.2.6.
2246   // Same behavior as GCC.
2247   TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
2248   if (TSK == TSK_ImplicitInstantiation ||
2249       TSK == TSK_ExplicitInstantiationDefinition)
2250     return 0;
2251 
2252   bool allowInlineFunctions =
2253     Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline();
2254 
2255   for (CXXRecordDecl::method_iterator I = RD->method_begin(),
2256          E = RD->method_end(); I != E; ++I) {
2257     const CXXMethodDecl *MD = *I;
2258 
2259     if (!MD->isVirtual())
2260       continue;
2261 
2262     if (MD->isPure())
2263       continue;
2264 
2265     // Ignore implicit member functions, they are always marked as inline, but
2266     // they don't have a body until they're defined.
2267     if (MD->isImplicit())
2268       continue;
2269 
2270     if (MD->isInlineSpecified())
2271       continue;
2272 
2273     if (MD->hasInlineBody())
2274       continue;
2275 
2276     // Ignore inline deleted or defaulted functions.
2277     if (!MD->isUserProvided())
2278       continue;
2279 
2280     // In certain ABIs, ignore functions with out-of-line inline definitions.
2281     if (!allowInlineFunctions) {
2282       const FunctionDecl *Def;
2283       if (MD->hasBody(Def) && Def->isInlineSpecified())
2284         continue;
2285     }
2286 
2287     // We found it.
2288     return MD;
2289   }
2290 
2291   return 0;
2292 }
2293 
2294 DiagnosticBuilder
2295 RecordLayoutBuilder::Diag(SourceLocation Loc, unsigned DiagID) {
2296   return Context.getDiagnostics().Report(Loc, DiagID);
2297 }
2298 
2299 /// Does the target C++ ABI require us to skip over the tail-padding
2300 /// of the given class (considering it as a base class) when allocating
2301 /// objects?
2302 static bool mustSkipTailPadding(TargetCXXABI ABI, const CXXRecordDecl *RD) {
2303   switch (ABI.getTailPaddingUseRules()) {
2304   case TargetCXXABI::AlwaysUseTailPadding:
2305     return false;
2306 
2307   case TargetCXXABI::UseTailPaddingUnlessPOD03:
2308     // FIXME: To the extent that this is meant to cover the Itanium ABI
2309     // rules, we should implement the restrictions about over-sized
2310     // bitfields:
2311     //
2312     // http://mentorembedded.github.com/cxx-abi/abi.html#POD :
2313     //   In general, a type is considered a POD for the purposes of
2314     //   layout if it is a POD type (in the sense of ISO C++
2315     //   [basic.types]). However, a POD-struct or POD-union (in the
2316     //   sense of ISO C++ [class]) with a bitfield member whose
2317     //   declared width is wider than the declared type of the
2318     //   bitfield is not a POD for the purpose of layout.  Similarly,
2319     //   an array type is not a POD for the purpose of layout if the
2320     //   element type of the array is not a POD for the purpose of
2321     //   layout.
2322     //
2323     //   Where references to the ISO C++ are made in this paragraph,
2324     //   the Technical Corrigendum 1 version of the standard is
2325     //   intended.
2326     return RD->isPOD();
2327 
2328   case TargetCXXABI::UseTailPaddingUnlessPOD11:
2329     // This is equivalent to RD->getTypeForDecl().isCXX11PODType(),
2330     // but with a lot of abstraction penalty stripped off.  This does
2331     // assume that these properties are set correctly even in C++98
2332     // mode; fortunately, that is true because we want to assign
2333     // consistently semantics to the type-traits intrinsics (or at
2334     // least as many of them as possible).
2335     return RD->isTrivial() && RD->isStandardLayout();
2336   }
2337 
2338   llvm_unreachable("bad tail-padding use kind");
2339 }
2340 
2341 /// getASTRecordLayout - Get or compute information about the layout of the
2342 /// specified record (struct/union/class), which indicates its size and field
2343 /// position information.
2344 const ASTRecordLayout &
2345 ASTContext::getASTRecordLayout(const RecordDecl *D) const {
2346   // These asserts test different things.  A record has a definition
2347   // as soon as we begin to parse the definition.  That definition is
2348   // not a complete definition (which is what isDefinition() tests)
2349   // until we *finish* parsing the definition.
2350 
2351   if (D->hasExternalLexicalStorage() && !D->getDefinition())
2352     getExternalSource()->CompleteType(const_cast<RecordDecl*>(D));
2353 
2354   D = D->getDefinition();
2355   assert(D && "Cannot get layout of forward declarations!");
2356   assert(!D->isInvalidDecl() && "Cannot get layout of invalid decl!");
2357   assert(D->isCompleteDefinition() && "Cannot layout type before complete!");
2358 
2359   // Look up this layout, if already laid out, return what we have.
2360   // Note that we can't save a reference to the entry because this function
2361   // is recursive.
2362   const ASTRecordLayout *Entry = ASTRecordLayouts[D];
2363   if (Entry) return *Entry;
2364 
2365   const ASTRecordLayout *NewEntry;
2366 
2367   if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
2368     EmptySubobjectMap EmptySubobjects(*this, RD);
2369     RecordLayoutBuilder Builder(*this, &EmptySubobjects);
2370     Builder.Layout(RD);
2371 
2372     // MSVC gives the vb-table pointer an alignment equal to that of
2373     // the non-virtual part of the structure.  That's an inherently
2374     // multi-pass operation.  If our first pass doesn't give us
2375     // adequate alignment, try again with the specified minimum
2376     // alignment.  This is *much* more maintainable than computing the
2377     // alignment in advance in a separately-coded pass; it's also
2378     // significantly more efficient in the common case where the
2379     // vb-table doesn't need extra padding.
2380     if (Builder.VBPtrOffset != CharUnits::fromQuantity(-1) &&
2381         (Builder.VBPtrOffset % Builder.NonVirtualAlignment) != 0) {
2382       Builder.resetWithTargetAlignment(Builder.NonVirtualAlignment);
2383       Builder.Layout(RD);
2384     }
2385 
2386     // In certain situations, we are allowed to lay out objects in the
2387     // tail-padding of base classes.  This is ABI-dependent.
2388     // FIXME: this should be stored in the record layout.
2389     bool skipTailPadding =
2390       mustSkipTailPadding(getTargetInfo().getCXXABI(), cast<CXXRecordDecl>(D));
2391 
2392     // FIXME: This should be done in FinalizeLayout.
2393     CharUnits DataSize =
2394       skipTailPadding ? Builder.getSize() : Builder.getDataSize();
2395     CharUnits NonVirtualSize =
2396       skipTailPadding ? DataSize : Builder.NonVirtualSize;
2397 
2398     NewEntry =
2399       new (*this) ASTRecordLayout(*this, Builder.getSize(),
2400                                   Builder.Alignment,
2401                                   Builder.HasOwnVFPtr,
2402                                   Builder.VBPtrOffset,
2403                                   DataSize,
2404                                   Builder.FieldOffsets.data(),
2405                                   Builder.FieldOffsets.size(),
2406                                   NonVirtualSize,
2407                                   Builder.NonVirtualAlignment,
2408                                   EmptySubobjects.SizeOfLargestEmptySubobject,
2409                                   Builder.PrimaryBase,
2410                                   Builder.PrimaryBaseIsVirtual,
2411                                   Builder.Bases, Builder.VBases);
2412   } else {
2413     RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/0);
2414     Builder.Layout(D);
2415 
2416     NewEntry =
2417       new (*this) ASTRecordLayout(*this, Builder.getSize(),
2418                                   Builder.Alignment,
2419                                   Builder.getSize(),
2420                                   Builder.FieldOffsets.data(),
2421                                   Builder.FieldOffsets.size());
2422   }
2423 
2424   ASTRecordLayouts[D] = NewEntry;
2425 
2426   if (getLangOpts().DumpRecordLayouts) {
2427     llvm::outs() << "\n*** Dumping AST Record Layout\n";
2428     DumpRecordLayout(D, llvm::outs(), getLangOpts().DumpRecordLayoutsSimple);
2429   }
2430 
2431   return *NewEntry;
2432 }
2433 
2434 const CXXMethodDecl *ASTContext::getCurrentKeyFunction(const CXXRecordDecl *RD) {
2435   if (!getTargetInfo().getCXXABI().hasKeyFunctions())
2436     return 0;
2437 
2438   assert(RD->getDefinition() && "Cannot get key function for forward decl!");
2439   RD = cast<CXXRecordDecl>(RD->getDefinition());
2440 
2441   const CXXMethodDecl *&entry = KeyFunctions[RD];
2442   if (!entry) {
2443     entry = computeKeyFunction(*this, RD);
2444   }
2445 
2446   return entry;
2447 }
2448 
2449 void ASTContext::setNonKeyFunction(const CXXMethodDecl *method) {
2450   assert(method == method->getFirstDeclaration() &&
2451          "not working with method declaration from class definition");
2452 
2453   // Look up the cache entry.  Since we're working with the first
2454   // declaration, its parent must be the class definition, which is
2455   // the correct key for the KeyFunctions hash.
2456   llvm::DenseMap<const CXXRecordDecl*, const CXXMethodDecl*>::iterator
2457     i = KeyFunctions.find(method->getParent());
2458 
2459   // If it's not cached, there's nothing to do.
2460   if (i == KeyFunctions.end()) return;
2461 
2462   // If it is cached, check whether it's the target method, and if so,
2463   // remove it from the cache.
2464   if (i->second == method) {
2465     // FIXME: remember that we did this for module / chained PCH state?
2466     KeyFunctions.erase(i);
2467   }
2468 }
2469 
2470 static uint64_t getFieldOffset(const ASTContext &C, const FieldDecl *FD) {
2471   const ASTRecordLayout &Layout = C.getASTRecordLayout(FD->getParent());
2472   return Layout.getFieldOffset(FD->getFieldIndex());
2473 }
2474 
2475 uint64_t ASTContext::getFieldOffset(const ValueDecl *VD) const {
2476   uint64_t OffsetInBits;
2477   if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
2478     OffsetInBits = ::getFieldOffset(*this, FD);
2479   } else {
2480     const IndirectFieldDecl *IFD = cast<IndirectFieldDecl>(VD);
2481 
2482     OffsetInBits = 0;
2483     for (IndirectFieldDecl::chain_iterator CI = IFD->chain_begin(),
2484                                            CE = IFD->chain_end();
2485          CI != CE; ++CI)
2486       OffsetInBits += ::getFieldOffset(*this, cast<FieldDecl>(*CI));
2487   }
2488 
2489   return OffsetInBits;
2490 }
2491 
2492 /// getObjCLayout - Get or compute information about the layout of the
2493 /// given interface.
2494 ///
2495 /// \param Impl - If given, also include the layout of the interface's
2496 /// implementation. This may differ by including synthesized ivars.
2497 const ASTRecordLayout &
2498 ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
2499                           const ObjCImplementationDecl *Impl) const {
2500   // Retrieve the definition
2501   if (D->hasExternalLexicalStorage() && !D->getDefinition())
2502     getExternalSource()->CompleteType(const_cast<ObjCInterfaceDecl*>(D));
2503   D = D->getDefinition();
2504   assert(D && D->isThisDeclarationADefinition() && "Invalid interface decl!");
2505 
2506   // Look up this layout, if already laid out, return what we have.
2507   const ObjCContainerDecl *Key =
2508     Impl ? (const ObjCContainerDecl*) Impl : (const ObjCContainerDecl*) D;
2509   if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
2510     return *Entry;
2511 
2512   // Add in synthesized ivar count if laying out an implementation.
2513   if (Impl) {
2514     unsigned SynthCount = CountNonClassIvars(D);
2515     // If there aren't any sythesized ivars then reuse the interface
2516     // entry. Note we can't cache this because we simply free all
2517     // entries later; however we shouldn't look up implementations
2518     // frequently.
2519     if (SynthCount == 0)
2520       return getObjCLayout(D, 0);
2521   }
2522 
2523   RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/0);
2524   Builder.Layout(D);
2525 
2526   const ASTRecordLayout *NewEntry =
2527     new (*this) ASTRecordLayout(*this, Builder.getSize(),
2528                                 Builder.Alignment,
2529                                 Builder.getDataSize(),
2530                                 Builder.FieldOffsets.data(),
2531                                 Builder.FieldOffsets.size());
2532 
2533   ObjCLayouts[Key] = NewEntry;
2534 
2535   return *NewEntry;
2536 }
2537 
2538 static void PrintOffset(raw_ostream &OS,
2539                         CharUnits Offset, unsigned IndentLevel) {
2540   OS << llvm::format("%4" PRId64 " | ", (int64_t)Offset.getQuantity());
2541   OS.indent(IndentLevel * 2);
2542 }
2543 
2544 static void PrintIndentNoOffset(raw_ostream &OS, unsigned IndentLevel) {
2545   OS << "     | ";
2546   OS.indent(IndentLevel * 2);
2547 }
2548 
2549 static void DumpCXXRecordLayout(raw_ostream &OS,
2550                                 const CXXRecordDecl *RD, const ASTContext &C,
2551                                 CharUnits Offset,
2552                                 unsigned IndentLevel,
2553                                 const char* Description,
2554                                 bool IncludeVirtualBases) {
2555   const ASTRecordLayout &Layout = C.getASTRecordLayout(RD);
2556 
2557   PrintOffset(OS, Offset, IndentLevel);
2558   OS << C.getTypeDeclType(const_cast<CXXRecordDecl *>(RD)).getAsString();
2559   if (Description)
2560     OS << ' ' << Description;
2561   if (RD->isEmpty())
2562     OS << " (empty)";
2563   OS << '\n';
2564 
2565   IndentLevel++;
2566 
2567   const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
2568   bool HasVfptr = Layout.hasOwnVFPtr();
2569   bool HasVbptr = Layout.getVBPtrOffset() != CharUnits::fromQuantity(-1);
2570 
2571   // Vtable pointer.
2572   if (RD->isDynamicClass() && !PrimaryBase &&
2573       !C.getTargetInfo().getCXXABI().isMicrosoft()) {
2574     PrintOffset(OS, Offset, IndentLevel);
2575     OS << '(' << *RD << " vtable pointer)\n";
2576   }
2577 
2578   // Dump (non-virtual) bases
2579   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
2580          E = RD->bases_end(); I != E; ++I) {
2581     assert(!I->getType()->isDependentType() &&
2582            "Cannot layout class with dependent bases.");
2583     if (I->isVirtual())
2584       continue;
2585 
2586     const CXXRecordDecl *Base =
2587       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
2588 
2589     CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base);
2590 
2591     DumpCXXRecordLayout(OS, Base, C, BaseOffset, IndentLevel,
2592                         Base == PrimaryBase ? "(primary base)" : "(base)",
2593                         /*IncludeVirtualBases=*/false);
2594   }
2595 
2596   // vfptr and vbptr (for Microsoft C++ ABI)
2597   if (HasVfptr) {
2598     PrintOffset(OS, Offset, IndentLevel);
2599     OS << '(' << *RD << " vftable pointer)\n";
2600   }
2601   if (HasVbptr) {
2602     PrintOffset(OS, Offset + Layout.getVBPtrOffset(), IndentLevel);
2603     OS << '(' << *RD << " vbtable pointer)\n";
2604   }
2605 
2606   // Dump fields.
2607   uint64_t FieldNo = 0;
2608   for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2609          E = RD->field_end(); I != E; ++I, ++FieldNo) {
2610     const FieldDecl &Field = **I;
2611     CharUnits FieldOffset = Offset +
2612       C.toCharUnitsFromBits(Layout.getFieldOffset(FieldNo));
2613 
2614     if (const RecordType *RT = Field.getType()->getAs<RecordType>()) {
2615       if (const CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2616         DumpCXXRecordLayout(OS, D, C, FieldOffset, IndentLevel,
2617                             Field.getName().data(),
2618                             /*IncludeVirtualBases=*/true);
2619         continue;
2620       }
2621     }
2622 
2623     PrintOffset(OS, FieldOffset, IndentLevel);
2624     OS << Field.getType().getAsString() << ' ' << Field << '\n';
2625   }
2626 
2627   if (!IncludeVirtualBases)
2628     return;
2629 
2630   // Dump virtual bases.
2631   const ASTRecordLayout::VBaseOffsetsMapTy &vtordisps =
2632     Layout.getVBaseOffsetsMap();
2633   for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
2634          E = RD->vbases_end(); I != E; ++I) {
2635     assert(I->isVirtual() && "Found non-virtual class!");
2636     const CXXRecordDecl *VBase =
2637       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
2638 
2639     CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBase);
2640 
2641     if (vtordisps.find(VBase)->second.hasVtorDisp()) {
2642       PrintOffset(OS, VBaseOffset - CharUnits::fromQuantity(4), IndentLevel);
2643       OS << "(vtordisp for vbase " << *VBase << ")\n";
2644     }
2645 
2646     DumpCXXRecordLayout(OS, VBase, C, VBaseOffset, IndentLevel,
2647                         VBase == PrimaryBase ?
2648                         "(primary virtual base)" : "(virtual base)",
2649                         /*IncludeVirtualBases=*/false);
2650   }
2651 
2652   PrintIndentNoOffset(OS, IndentLevel - 1);
2653   OS << "[sizeof=" << Layout.getSize().getQuantity();
2654   OS << ", dsize=" << Layout.getDataSize().getQuantity();
2655   OS << ", align=" << Layout.getAlignment().getQuantity() << '\n';
2656 
2657   PrintIndentNoOffset(OS, IndentLevel - 1);
2658   OS << " nvsize=" << Layout.getNonVirtualSize().getQuantity();
2659   OS << ", nvalign=" << Layout.getNonVirtualAlign().getQuantity() << "]\n";
2660   OS << '\n';
2661 }
2662 
2663 void ASTContext::DumpRecordLayout(const RecordDecl *RD,
2664                                   raw_ostream &OS,
2665                                   bool Simple) const {
2666   const ASTRecordLayout &Info = getASTRecordLayout(RD);
2667 
2668   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
2669     if (!Simple)
2670       return DumpCXXRecordLayout(OS, CXXRD, *this, CharUnits(), 0, 0,
2671                                  /*IncludeVirtualBases=*/true);
2672 
2673   OS << "Type: " << getTypeDeclType(RD).getAsString() << "\n";
2674   if (!Simple) {
2675     OS << "Record: ";
2676     RD->dump();
2677   }
2678   OS << "\nLayout: ";
2679   OS << "<ASTRecordLayout\n";
2680   OS << "  Size:" << toBits(Info.getSize()) << "\n";
2681   OS << "  DataSize:" << toBits(Info.getDataSize()) << "\n";
2682   OS << "  Alignment:" << toBits(Info.getAlignment()) << "\n";
2683   OS << "  FieldOffsets: [";
2684   for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i) {
2685     if (i) OS << ", ";
2686     OS << Info.getFieldOffset(i);
2687   }
2688   OS << "]>\n";
2689 }
2690