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