clang API Documentation

RecordLayoutBuilder.cpp
Go to the documentation of this file.
00001 //=== RecordLayoutBuilder.cpp - Helper class for building record layouts ---==//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 
00010 #include "clang/AST/Attr.h"
00011 #include "clang/AST/CXXInheritance.h"
00012 #include "clang/AST/Decl.h"
00013 #include "clang/AST/DeclCXX.h"
00014 #include "clang/AST/DeclObjC.h"
00015 #include "clang/AST/Expr.h"
00016 #include "clang/AST/RecordLayout.h"
00017 #include "clang/Basic/TargetInfo.h"
00018 #include "clang/Sema/SemaDiagnostic.h"
00019 #include "llvm/Support/Format.h"
00020 #include "llvm/ADT/SmallSet.h"
00021 #include "llvm/Support/MathExtras.h"
00022 #include "llvm/Support/CrashRecoveryContext.h"
00023 
00024 using namespace clang;
00025 
00026 namespace {
00027 
00028 /// BaseSubobjectInfo - Represents a single base subobject in a complete class.
00029 /// For a class hierarchy like
00030 ///
00031 /// class A { };
00032 /// class B : A { };
00033 /// class C : A, B { };
00034 ///
00035 /// The BaseSubobjectInfo graph for C will have three BaseSubobjectInfo
00036 /// instances, one for B and two for A.
00037 ///
00038 /// If a base is virtual, it will only have one BaseSubobjectInfo allocated.
00039 struct BaseSubobjectInfo {
00040   /// Class - The class for this base info.
00041   const CXXRecordDecl *Class;
00042 
00043   /// IsVirtual - Whether the BaseInfo represents a virtual base or not.
00044   bool IsVirtual;
00045 
00046   /// Bases - Information about the base subobjects.
00047   SmallVector<BaseSubobjectInfo*, 4> Bases;
00048 
00049   /// PrimaryVirtualBaseInfo - Holds the base info for the primary virtual base
00050   /// of this base info (if one exists).
00051   BaseSubobjectInfo *PrimaryVirtualBaseInfo;
00052 
00053   // FIXME: Document.
00054   const BaseSubobjectInfo *Derived;
00055 };
00056 
00057 /// EmptySubobjectMap - Keeps track of which empty subobjects exist at different
00058 /// offsets while laying out a C++ class.
00059 class EmptySubobjectMap {
00060   const ASTContext &Context;
00061   uint64_t CharWidth;
00062   
00063   /// Class - The class whose empty entries we're keeping track of.
00064   const CXXRecordDecl *Class;
00065 
00066   /// EmptyClassOffsets - A map from offsets to empty record decls.
00067   typedef SmallVector<const CXXRecordDecl *, 1> ClassVectorTy;
00068   typedef llvm::DenseMap<CharUnits, ClassVectorTy> EmptyClassOffsetsMapTy;
00069   EmptyClassOffsetsMapTy EmptyClassOffsets;
00070   
00071   /// MaxEmptyClassOffset - The highest offset known to contain an empty
00072   /// base subobject.
00073   CharUnits MaxEmptyClassOffset;
00074   
00075   /// ComputeEmptySubobjectSizes - Compute the size of the largest base or
00076   /// member subobject that is empty.
00077   void ComputeEmptySubobjectSizes();
00078   
00079   void AddSubobjectAtOffset(const CXXRecordDecl *RD, CharUnits Offset);
00080   
00081   void UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info,
00082                                  CharUnits Offset, bool PlacingEmptyBase);
00083   
00084   void UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD, 
00085                                   const CXXRecordDecl *Class,
00086                                   CharUnits Offset);
00087   void UpdateEmptyFieldSubobjects(const FieldDecl *FD, CharUnits Offset);
00088   
00089   /// AnyEmptySubobjectsBeyondOffset - Returns whether there are any empty
00090   /// subobjects beyond the given offset.
00091   bool AnyEmptySubobjectsBeyondOffset(CharUnits Offset) const {
00092     return Offset <= MaxEmptyClassOffset;
00093   }
00094 
00095   CharUnits 
00096   getFieldOffset(const ASTRecordLayout &Layout, unsigned FieldNo) const {
00097     uint64_t FieldOffset = Layout.getFieldOffset(FieldNo);
00098     assert(FieldOffset % CharWidth == 0 && 
00099            "Field offset not at char boundary!");
00100 
00101     return Context.toCharUnitsFromBits(FieldOffset);
00102   }
00103 
00104 protected:
00105   bool CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD,
00106                                  CharUnits Offset) const;
00107 
00108   bool CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info,
00109                                      CharUnits Offset);
00110 
00111   bool CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD, 
00112                                       const CXXRecordDecl *Class,
00113                                       CharUnits Offset) const;
00114   bool CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD,
00115                                       CharUnits Offset) const;
00116 
00117 public:
00118   /// This holds the size of the largest empty subobject (either a base
00119   /// or a member). Will be zero if the record being built doesn't contain
00120   /// any empty classes.
00121   CharUnits SizeOfLargestEmptySubobject;
00122 
00123   EmptySubobjectMap(const ASTContext &Context, const CXXRecordDecl *Class)
00124   : Context(Context), CharWidth(Context.getCharWidth()), Class(Class) {
00125       ComputeEmptySubobjectSizes();
00126   }
00127 
00128   /// CanPlaceBaseAtOffset - Return whether the given base class can be placed
00129   /// at the given offset.
00130   /// Returns false if placing the record will result in two components
00131   /// (direct or indirect) of the same type having the same offset.
00132   bool CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info,
00133                             CharUnits Offset);
00134 
00135   /// CanPlaceFieldAtOffset - Return whether a field can be placed at the given
00136   /// offset.
00137   bool CanPlaceFieldAtOffset(const FieldDecl *FD, CharUnits Offset);
00138 };
00139 
00140 void EmptySubobjectMap::ComputeEmptySubobjectSizes() {
00141   // Check the bases.
00142   for (CXXRecordDecl::base_class_const_iterator I = Class->bases_begin(),
00143        E = Class->bases_end(); I != E; ++I) {
00144     const CXXRecordDecl *BaseDecl =
00145       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
00146 
00147     CharUnits EmptySize;
00148     const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
00149     if (BaseDecl->isEmpty()) {
00150       // If the class decl is empty, get its size.
00151       EmptySize = Layout.getSize();
00152     } else {
00153       // Otherwise, we get the largest empty subobject for the decl.
00154       EmptySize = Layout.getSizeOfLargestEmptySubobject();
00155     }
00156 
00157     if (EmptySize > SizeOfLargestEmptySubobject)
00158       SizeOfLargestEmptySubobject = EmptySize;
00159   }
00160 
00161   // Check the fields.
00162   for (CXXRecordDecl::field_iterator I = Class->field_begin(),
00163        E = Class->field_end(); I != E; ++I) {
00164     const FieldDecl &FD = *I;
00165 
00166     const RecordType *RT =
00167       Context.getBaseElementType(FD.getType())->getAs<RecordType>();
00168 
00169     // We only care about record types.
00170     if (!RT)
00171       continue;
00172 
00173     CharUnits EmptySize;
00174     const CXXRecordDecl *MemberDecl = cast<CXXRecordDecl>(RT->getDecl());
00175     const ASTRecordLayout &Layout = Context.getASTRecordLayout(MemberDecl);
00176     if (MemberDecl->isEmpty()) {
00177       // If the class decl is empty, get its size.
00178       EmptySize = Layout.getSize();
00179     } else {
00180       // Otherwise, we get the largest empty subobject for the decl.
00181       EmptySize = Layout.getSizeOfLargestEmptySubobject();
00182     }
00183 
00184     if (EmptySize > SizeOfLargestEmptySubobject)
00185       SizeOfLargestEmptySubobject = EmptySize;
00186   }
00187 }
00188 
00189 bool
00190 EmptySubobjectMap::CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD, 
00191                                              CharUnits Offset) const {
00192   // We only need to check empty bases.
00193   if (!RD->isEmpty())
00194     return true;
00195 
00196   EmptyClassOffsetsMapTy::const_iterator I = EmptyClassOffsets.find(Offset);
00197   if (I == EmptyClassOffsets.end())
00198     return true;
00199   
00200   const ClassVectorTy& Classes = I->second;
00201   if (std::find(Classes.begin(), Classes.end(), RD) == Classes.end())
00202     return true;
00203 
00204   // There is already an empty class of the same type at this offset.
00205   return false;
00206 }
00207   
00208 void EmptySubobjectMap::AddSubobjectAtOffset(const CXXRecordDecl *RD, 
00209                                              CharUnits Offset) {
00210   // We only care about empty bases.
00211   if (!RD->isEmpty())
00212     return;
00213 
00214   // If we have empty structures inside an union, we can assign both
00215   // the same offset. Just avoid pushing them twice in the list.
00216   ClassVectorTy& Classes = EmptyClassOffsets[Offset];
00217   if (std::find(Classes.begin(), Classes.end(), RD) != Classes.end())
00218     return;
00219   
00220   Classes.push_back(RD);
00221   
00222   // Update the empty class offset.
00223   if (Offset > MaxEmptyClassOffset)
00224     MaxEmptyClassOffset = Offset;
00225 }
00226 
00227 bool
00228 EmptySubobjectMap::CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info,
00229                                                  CharUnits Offset) {
00230   // We don't have to keep looking past the maximum offset that's known to
00231   // contain an empty class.
00232   if (!AnyEmptySubobjectsBeyondOffset(Offset))
00233     return true;
00234 
00235   if (!CanPlaceSubobjectAtOffset(Info->Class, Offset))
00236     return false;
00237 
00238   // Traverse all non-virtual bases.
00239   const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
00240   for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) {
00241     BaseSubobjectInfo* Base = Info->Bases[I];
00242     if (Base->IsVirtual)
00243       continue;
00244 
00245     CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
00246 
00247     if (!CanPlaceBaseSubobjectAtOffset(Base, BaseOffset))
00248       return false;
00249   }
00250 
00251   if (Info->PrimaryVirtualBaseInfo) {
00252     BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
00253 
00254     if (Info == PrimaryVirtualBaseInfo->Derived) {
00255       if (!CanPlaceBaseSubobjectAtOffset(PrimaryVirtualBaseInfo, Offset))
00256         return false;
00257     }
00258   }
00259   
00260   // Traverse all member variables.
00261   unsigned FieldNo = 0;
00262   for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(), 
00263        E = Info->Class->field_end(); I != E; ++I, ++FieldNo) {
00264     const FieldDecl *FD = &*I;
00265     if (FD->isBitField())
00266       continue;
00267   
00268     CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
00269     if (!CanPlaceFieldSubobjectAtOffset(FD, FieldOffset))
00270       return false;
00271   }
00272   
00273   return true;
00274 }
00275 
00276 void EmptySubobjectMap::UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info, 
00277                                                   CharUnits Offset,
00278                                                   bool PlacingEmptyBase) {
00279   if (!PlacingEmptyBase && Offset >= SizeOfLargestEmptySubobject) {
00280     // We know that the only empty subobjects that can conflict with empty
00281     // subobject of non-empty bases, are empty bases that can be placed at
00282     // offset zero. Because of this, we only need to keep track of empty base 
00283     // subobjects with offsets less than the size of the largest empty
00284     // subobject for our class.    
00285     return;
00286   }
00287 
00288   AddSubobjectAtOffset(Info->Class, Offset);
00289 
00290   // Traverse all non-virtual bases.
00291   const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
00292   for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) {
00293     BaseSubobjectInfo* Base = Info->Bases[I];
00294     if (Base->IsVirtual)
00295       continue;
00296 
00297     CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
00298     UpdateEmptyBaseSubobjects(Base, BaseOffset, PlacingEmptyBase);
00299   }
00300 
00301   if (Info->PrimaryVirtualBaseInfo) {
00302     BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
00303     
00304     if (Info == PrimaryVirtualBaseInfo->Derived)
00305       UpdateEmptyBaseSubobjects(PrimaryVirtualBaseInfo, Offset,
00306                                 PlacingEmptyBase);
00307   }
00308 
00309   // Traverse all member variables.
00310   unsigned FieldNo = 0;
00311   for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(), 
00312        E = Info->Class->field_end(); I != E; ++I, ++FieldNo) {
00313     const FieldDecl *FD = &*I;
00314     if (FD->isBitField())
00315       continue;
00316 
00317     CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
00318     UpdateEmptyFieldSubobjects(FD, FieldOffset);
00319   }
00320 }
00321 
00322 bool EmptySubobjectMap::CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info,
00323                                              CharUnits Offset) {
00324   // If we know this class doesn't have any empty subobjects we don't need to
00325   // bother checking.
00326   if (SizeOfLargestEmptySubobject.isZero())
00327     return true;
00328 
00329   if (!CanPlaceBaseSubobjectAtOffset(Info, Offset))
00330     return false;
00331 
00332   // We are able to place the base at this offset. Make sure to update the
00333   // empty base subobject map.
00334   UpdateEmptyBaseSubobjects(Info, Offset, Info->Class->isEmpty());
00335   return true;
00336 }
00337 
00338 bool
00339 EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD, 
00340                                                   const CXXRecordDecl *Class,
00341                                                   CharUnits Offset) const {
00342   // We don't have to keep looking past the maximum offset that's known to
00343   // contain an empty class.
00344   if (!AnyEmptySubobjectsBeyondOffset(Offset))
00345     return true;
00346 
00347   if (!CanPlaceSubobjectAtOffset(RD, Offset))
00348     return false;
00349   
00350   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
00351 
00352   // Traverse all non-virtual bases.
00353   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
00354        E = RD->bases_end(); I != E; ++I) {
00355     if (I->isVirtual())
00356       continue;
00357 
00358     const CXXRecordDecl *BaseDecl =
00359       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
00360 
00361     CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
00362     if (!CanPlaceFieldSubobjectAtOffset(BaseDecl, Class, BaseOffset))
00363       return false;
00364   }
00365 
00366   if (RD == Class) {
00367     // This is the most derived class, traverse virtual bases as well.
00368     for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
00369          E = RD->vbases_end(); I != E; ++I) {
00370       const CXXRecordDecl *VBaseDecl =
00371         cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
00372       
00373       CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
00374       if (!CanPlaceFieldSubobjectAtOffset(VBaseDecl, Class, VBaseOffset))
00375         return false;
00376     }
00377   }
00378     
00379   // Traverse all member variables.
00380   unsigned FieldNo = 0;
00381   for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
00382        I != E; ++I, ++FieldNo) {
00383     const FieldDecl *FD = &*I;
00384     if (FD->isBitField())
00385       continue;
00386 
00387     CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
00388     
00389     if (!CanPlaceFieldSubobjectAtOffset(FD, FieldOffset))
00390       return false;
00391   }
00392 
00393   return true;
00394 }
00395 
00396 bool
00397 EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD,
00398                                                   CharUnits Offset) const {
00399   // We don't have to keep looking past the maximum offset that's known to
00400   // contain an empty class.
00401   if (!AnyEmptySubobjectsBeyondOffset(Offset))
00402     return true;
00403   
00404   QualType T = FD->getType();
00405   if (const RecordType *RT = T->getAs<RecordType>()) {
00406     const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
00407     return CanPlaceFieldSubobjectAtOffset(RD, RD, Offset);
00408   }
00409 
00410   // If we have an array type we need to look at every element.
00411   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
00412     QualType ElemTy = Context.getBaseElementType(AT);
00413     const RecordType *RT = ElemTy->getAs<RecordType>();
00414     if (!RT)
00415       return true;
00416   
00417     const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
00418     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
00419 
00420     uint64_t NumElements = Context.getConstantArrayElementCount(AT);
00421     CharUnits ElementOffset = Offset;
00422     for (uint64_t I = 0; I != NumElements; ++I) {
00423       // We don't have to keep looking past the maximum offset that's known to
00424       // contain an empty class.
00425       if (!AnyEmptySubobjectsBeyondOffset(ElementOffset))
00426         return true;
00427       
00428       if (!CanPlaceFieldSubobjectAtOffset(RD, RD, ElementOffset))
00429         return false;
00430 
00431       ElementOffset += Layout.getSize();
00432     }
00433   }
00434 
00435   return true;
00436 }
00437 
00438 bool
00439 EmptySubobjectMap::CanPlaceFieldAtOffset(const FieldDecl *FD, 
00440                                          CharUnits Offset) {
00441   if (!CanPlaceFieldSubobjectAtOffset(FD, Offset))
00442     return false;
00443   
00444   // We are able to place the member variable at this offset.
00445   // Make sure to update the empty base subobject map.
00446   UpdateEmptyFieldSubobjects(FD, Offset);
00447   return true;
00448 }
00449 
00450 void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD, 
00451                                                    const CXXRecordDecl *Class,
00452                                                    CharUnits Offset) {
00453   // We know that the only empty subobjects that can conflict with empty
00454   // field subobjects are subobjects of empty bases that can be placed at offset
00455   // zero. Because of this, we only need to keep track of empty field 
00456   // subobjects with offsets less than the size of the largest empty
00457   // subobject for our class.
00458   if (Offset >= SizeOfLargestEmptySubobject)
00459     return;
00460 
00461   AddSubobjectAtOffset(RD, Offset);
00462 
00463   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
00464 
00465   // Traverse all non-virtual bases.
00466   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
00467        E = RD->bases_end(); I != E; ++I) {
00468     if (I->isVirtual())
00469       continue;
00470 
00471     const CXXRecordDecl *BaseDecl =
00472       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
00473 
00474     CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
00475     UpdateEmptyFieldSubobjects(BaseDecl, Class, BaseOffset);
00476   }
00477 
00478   if (RD == Class) {
00479     // This is the most derived class, traverse virtual bases as well.
00480     for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
00481          E = RD->vbases_end(); I != E; ++I) {
00482       const CXXRecordDecl *VBaseDecl =
00483       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
00484       
00485       CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
00486       UpdateEmptyFieldSubobjects(VBaseDecl, Class, VBaseOffset);
00487     }
00488   }
00489   
00490   // Traverse all member variables.
00491   unsigned FieldNo = 0;
00492   for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
00493        I != E; ++I, ++FieldNo) {
00494     const FieldDecl *FD = &*I;
00495     if (FD->isBitField())
00496       continue;
00497 
00498     CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
00499 
00500     UpdateEmptyFieldSubobjects(FD, FieldOffset);
00501   }
00502 }
00503   
00504 void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const FieldDecl *FD,
00505                                                    CharUnits Offset) {
00506   QualType T = FD->getType();
00507   if (const RecordType *RT = T->getAs<RecordType>()) {
00508     const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
00509     UpdateEmptyFieldSubobjects(RD, RD, Offset);
00510     return;
00511   }
00512 
00513   // If we have an array type we need to update every element.
00514   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
00515     QualType ElemTy = Context.getBaseElementType(AT);
00516     const RecordType *RT = ElemTy->getAs<RecordType>();
00517     if (!RT)
00518       return;
00519     
00520     const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
00521     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
00522     
00523     uint64_t NumElements = Context.getConstantArrayElementCount(AT);
00524     CharUnits ElementOffset = Offset;
00525     
00526     for (uint64_t I = 0; I != NumElements; ++I) {
00527       // We know that the only empty subobjects that can conflict with empty
00528       // field subobjects are subobjects of empty bases that can be placed at 
00529       // offset zero. Because of this, we only need to keep track of empty field
00530       // subobjects with offsets less than the size of the largest empty
00531       // subobject for our class.
00532       if (ElementOffset >= SizeOfLargestEmptySubobject)
00533         return;
00534 
00535       UpdateEmptyFieldSubobjects(RD, RD, ElementOffset);
00536       ElementOffset += Layout.getSize();
00537     }
00538   }
00539 }
00540 
00541 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> ClassSetTy;
00542 
00543 class RecordLayoutBuilder {
00544 protected:
00545   // FIXME: Remove this and make the appropriate fields public.
00546   friend class clang::ASTContext;
00547 
00548   const ASTContext &Context;
00549 
00550   EmptySubobjectMap *EmptySubobjects;
00551 
00552   /// Size - The current size of the record layout.
00553   uint64_t Size;
00554 
00555   /// Alignment - The current alignment of the record layout.
00556   CharUnits Alignment;
00557 
00558   /// \brief The alignment if attribute packed is not used.
00559   CharUnits UnpackedAlignment;
00560 
00561   SmallVector<uint64_t, 16> FieldOffsets;
00562 
00563   /// \brief Whether the external AST source has provided a layout for this
00564   /// record.
00565   unsigned ExternalLayout : 1;
00566 
00567   /// \brief Whether we need to infer alignment, even when we have an 
00568   /// externally-provided layout.
00569   unsigned InferAlignment : 1;
00570   
00571   /// Packed - Whether the record is packed or not.
00572   unsigned Packed : 1;
00573 
00574   unsigned IsUnion : 1;
00575 
00576   unsigned IsMac68kAlign : 1;
00577   
00578   unsigned IsMsStruct : 1;
00579 
00580   /// UnfilledBitsInLastByte - If the last field laid out was a bitfield,
00581   /// this contains the number of bits in the last byte that can be used for
00582   /// an adjacent bitfield if necessary.
00583   unsigned char UnfilledBitsInLastByte;
00584 
00585   /// MaxFieldAlignment - The maximum allowed field alignment. This is set by
00586   /// #pragma pack.
00587   CharUnits MaxFieldAlignment;
00588 
00589   /// DataSize - The data size of the record being laid out.
00590   uint64_t DataSize;
00591 
00592   CharUnits NonVirtualSize;
00593   CharUnits NonVirtualAlignment;
00594 
00595   FieldDecl *ZeroLengthBitfield;
00596 
00597   /// PrimaryBase - the primary base class (if one exists) of the class
00598   /// we're laying out.
00599   const CXXRecordDecl *PrimaryBase;
00600 
00601   /// PrimaryBaseIsVirtual - Whether the primary base of the class we're laying
00602   /// out is virtual.
00603   bool PrimaryBaseIsVirtual;
00604 
00605   /// HasOwnVFPtr - Whether the class provides its own vtable/vftbl
00606   /// pointer, as opposed to inheriting one from a primary base class.
00607   bool HasOwnVFPtr;
00608 
00609   /// VBPtrOffset - Virtual base table offset. Only for MS layout.
00610   CharUnits VBPtrOffset;
00611 
00612   typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
00613 
00614   /// Bases - base classes and their offsets in the record.
00615   BaseOffsetsMapTy Bases;
00616 
00617   // VBases - virtual base classes and their offsets in the record.
00618   ASTRecordLayout::VBaseOffsetsMapTy VBases;
00619 
00620   /// IndirectPrimaryBases - Virtual base classes, direct or indirect, that are
00621   /// primary base classes for some other direct or indirect base class.
00622   CXXIndirectPrimaryBaseSet IndirectPrimaryBases;
00623 
00624   /// FirstNearlyEmptyVBase - The first nearly empty virtual base class in
00625   /// inheritance graph order. Used for determining the primary base class.
00626   const CXXRecordDecl *FirstNearlyEmptyVBase;
00627 
00628   /// VisitedVirtualBases - A set of all the visited virtual bases, used to
00629   /// avoid visiting virtual bases more than once.
00630   llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
00631 
00632   /// \brief Externally-provided size.
00633   uint64_t ExternalSize;
00634   
00635   /// \brief Externally-provided alignment.
00636   uint64_t ExternalAlign;
00637   
00638   /// \brief Externally-provided field offsets.
00639   llvm::DenseMap<const FieldDecl *, uint64_t> ExternalFieldOffsets;
00640 
00641   /// \brief Externally-provided direct, non-virtual base offsets.
00642   llvm::DenseMap<const CXXRecordDecl *, CharUnits> ExternalBaseOffsets;
00643 
00644   /// \brief Externally-provided virtual base offsets.
00645   llvm::DenseMap<const CXXRecordDecl *, CharUnits> ExternalVirtualBaseOffsets;
00646 
00647   RecordLayoutBuilder(const ASTContext &Context,
00648                       EmptySubobjectMap *EmptySubobjects)
00649     : Context(Context), EmptySubobjects(EmptySubobjects), Size(0), 
00650       Alignment(CharUnits::One()), UnpackedAlignment(CharUnits::One()),
00651       ExternalLayout(false), InferAlignment(false), 
00652       Packed(false), IsUnion(false), IsMac68kAlign(false), IsMsStruct(false),
00653       UnfilledBitsInLastByte(0), MaxFieldAlignment(CharUnits::Zero()), 
00654       DataSize(0), NonVirtualSize(CharUnits::Zero()), 
00655       NonVirtualAlignment(CharUnits::One()), 
00656       ZeroLengthBitfield(0), PrimaryBase(0), 
00657       PrimaryBaseIsVirtual(false),
00658       HasOwnVFPtr(false),
00659       VBPtrOffset(CharUnits::fromQuantity(-1)),
00660       FirstNearlyEmptyVBase(0) { }
00661 
00662   /// Reset this RecordLayoutBuilder to a fresh state, using the given
00663   /// alignment as the initial alignment.  This is used for the
00664   /// correct layout of vb-table pointers in MSVC.
00665   void resetWithTargetAlignment(CharUnits TargetAlignment) {
00666     const ASTContext &Context = this->Context;
00667     EmptySubobjectMap *EmptySubobjects = this->EmptySubobjects;
00668     this->~RecordLayoutBuilder();
00669     new (this) RecordLayoutBuilder(Context, EmptySubobjects);
00670     Alignment = UnpackedAlignment = TargetAlignment;
00671   }
00672 
00673   void Layout(const RecordDecl *D);
00674   void Layout(const CXXRecordDecl *D);
00675   void Layout(const ObjCInterfaceDecl *D);
00676 
00677   void LayoutFields(const RecordDecl *D);
00678   void LayoutField(const FieldDecl *D);
00679   void LayoutWideBitField(uint64_t FieldSize, uint64_t TypeSize,
00680                           bool FieldPacked, const FieldDecl *D);
00681   void LayoutBitField(const FieldDecl *D);
00682 
00683   bool isMicrosoftCXXABI() const {
00684     return Context.getTargetInfo().getCXXABI() == CXXABI_Microsoft;
00685   }
00686 
00687   void MSLayoutVirtualBases(const CXXRecordDecl *RD);
00688 
00689   /// BaseSubobjectInfoAllocator - Allocator for BaseSubobjectInfo objects.
00690   llvm::SpecificBumpPtrAllocator<BaseSubobjectInfo> BaseSubobjectInfoAllocator;
00691   
00692   typedef llvm::DenseMap<const CXXRecordDecl *, BaseSubobjectInfo *>
00693     BaseSubobjectInfoMapTy;
00694 
00695   /// VirtualBaseInfo - Map from all the (direct or indirect) virtual bases
00696   /// of the class we're laying out to their base subobject info.
00697   BaseSubobjectInfoMapTy VirtualBaseInfo;
00698   
00699   /// NonVirtualBaseInfo - Map from all the direct non-virtual bases of the
00700   /// class we're laying out to their base subobject info.
00701   BaseSubobjectInfoMapTy NonVirtualBaseInfo;
00702 
00703   /// ComputeBaseSubobjectInfo - Compute the base subobject information for the
00704   /// bases of the given class.
00705   void ComputeBaseSubobjectInfo(const CXXRecordDecl *RD);
00706 
00707   /// ComputeBaseSubobjectInfo - Compute the base subobject information for a
00708   /// single class and all of its base classes.
00709   BaseSubobjectInfo *ComputeBaseSubobjectInfo(const CXXRecordDecl *RD, 
00710                                               bool IsVirtual,
00711                                               BaseSubobjectInfo *Derived);
00712 
00713   /// DeterminePrimaryBase - Determine the primary base of the given class.
00714   void DeterminePrimaryBase(const CXXRecordDecl *RD);
00715 
00716   void SelectPrimaryVBase(const CXXRecordDecl *RD);
00717 
00718   void EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign);
00719 
00720   /// LayoutNonVirtualBases - Determines the primary base class (if any) and
00721   /// lays it out. Will then proceed to lay out all non-virtual base clasess.
00722   void LayoutNonVirtualBases(const CXXRecordDecl *RD);
00723 
00724   /// LayoutNonVirtualBase - Lays out a single non-virtual base.
00725   void LayoutNonVirtualBase(const BaseSubobjectInfo *Base);
00726 
00727   void AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
00728                                     CharUnits Offset);
00729 
00730   bool needsVFTable(const CXXRecordDecl *RD) const;
00731   bool hasNewVirtualFunction(const CXXRecordDecl *RD,
00732                              bool IgnoreDestructor = false) const;
00733   bool isPossiblePrimaryBase(const CXXRecordDecl *Base) const;
00734 
00735   void computeVtordisps(const CXXRecordDecl *RD, 
00736                         ClassSetTy &VtordispVBases);
00737 
00738   /// LayoutVirtualBases - Lays out all the virtual bases.
00739   void LayoutVirtualBases(const CXXRecordDecl *RD,
00740                           const CXXRecordDecl *MostDerivedClass);
00741 
00742   /// LayoutVirtualBase - Lays out a single virtual base.
00743   void LayoutVirtualBase(const BaseSubobjectInfo *Base, 
00744                          bool IsVtordispNeed = false);
00745 
00746   /// LayoutBase - Will lay out a base and return the offset where it was
00747   /// placed, in chars.
00748   CharUnits LayoutBase(const BaseSubobjectInfo *Base);
00749 
00750   /// InitializeLayout - Initialize record layout for the given record decl.
00751   void InitializeLayout(const Decl *D);
00752 
00753   /// FinishLayout - Finalize record layout. Adjust record size based on the
00754   /// alignment.
00755   void FinishLayout(const NamedDecl *D);
00756 
00757   void UpdateAlignment(CharUnits NewAlignment, CharUnits UnpackedNewAlignment);
00758   void UpdateAlignment(CharUnits NewAlignment) {
00759     UpdateAlignment(NewAlignment, NewAlignment);
00760   }
00761 
00762   /// \brief Retrieve the externally-supplied field offset for the given
00763   /// field.
00764   ///
00765   /// \param Field The field whose offset is being queried.
00766   /// \param ComputedOffset The offset that we've computed for this field.
00767   uint64_t updateExternalFieldOffset(const FieldDecl *Field, 
00768                                      uint64_t ComputedOffset);
00769   
00770   void CheckFieldPadding(uint64_t Offset, uint64_t UnpaddedOffset,
00771                           uint64_t UnpackedOffset, unsigned UnpackedAlign,
00772                           bool isPacked, const FieldDecl *D);
00773 
00774   DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
00775 
00776   CharUnits getSize() const { 
00777     assert(Size % Context.getCharWidth() == 0);
00778     return Context.toCharUnitsFromBits(Size); 
00779   }
00780   uint64_t getSizeInBits() const { return Size; }
00781 
00782   void setSize(CharUnits NewSize) { Size = Context.toBits(NewSize); }
00783   void setSize(uint64_t NewSize) { Size = NewSize; }
00784 
00785   CharUnits getAligment() const { return Alignment; }
00786 
00787   CharUnits getDataSize() const { 
00788     assert(DataSize % Context.getCharWidth() == 0);
00789     return Context.toCharUnitsFromBits(DataSize); 
00790   }
00791   uint64_t getDataSizeInBits() const { return DataSize; }
00792 
00793   void setDataSize(CharUnits NewSize) { DataSize = Context.toBits(NewSize); }
00794   void setDataSize(uint64_t NewSize) { DataSize = NewSize; }
00795 
00796   RecordLayoutBuilder(const RecordLayoutBuilder&);   // DO NOT IMPLEMENT
00797   void operator=(const RecordLayoutBuilder&); // DO NOT IMPLEMENT
00798 public:
00799   static const CXXMethodDecl *ComputeKeyFunction(const CXXRecordDecl *RD);
00800 };
00801 } // end anonymous namespace
00802 
00803 void
00804 RecordLayoutBuilder::SelectPrimaryVBase(const CXXRecordDecl *RD) {
00805   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
00806          E = RD->bases_end(); I != E; ++I) {
00807     assert(!I->getType()->isDependentType() &&
00808            "Cannot layout class with dependent bases.");
00809 
00810     const CXXRecordDecl *Base =
00811       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
00812 
00813     // Check if this is a nearly empty virtual base.
00814     if (I->isVirtual() && Context.isNearlyEmpty(Base)) {
00815       // If it's not an indirect primary base, then we've found our primary
00816       // base.
00817       if (!IndirectPrimaryBases.count(Base)) {
00818         PrimaryBase = Base;
00819         PrimaryBaseIsVirtual = true;
00820         return;
00821       }
00822 
00823       // Is this the first nearly empty virtual base?
00824       if (!FirstNearlyEmptyVBase)
00825         FirstNearlyEmptyVBase = Base;
00826     }
00827 
00828     SelectPrimaryVBase(Base);
00829     if (PrimaryBase)
00830       return;
00831   }
00832 }
00833 
00834 /// DeterminePrimaryBase - Determine the primary base of the given class.
00835 void RecordLayoutBuilder::DeterminePrimaryBase(const CXXRecordDecl *RD) {
00836   // If the class isn't dynamic, it won't have a primary base.
00837   if (!RD->isDynamicClass())
00838     return;
00839 
00840   // Compute all the primary virtual bases for all of our direct and
00841   // indirect bases, and record all their primary virtual base classes.
00842   RD->getIndirectPrimaryBases(IndirectPrimaryBases);
00843 
00844   // If the record has a dynamic base class, attempt to choose a primary base
00845   // class. It is the first (in direct base class order) non-virtual dynamic
00846   // base class, if one exists.
00847   for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
00848          e = RD->bases_end(); i != e; ++i) {
00849     // Ignore virtual bases.
00850     if (i->isVirtual())
00851       continue;
00852 
00853     const CXXRecordDecl *Base =
00854       cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
00855 
00856     if (isPossiblePrimaryBase(Base)) {
00857       // We found it.
00858       PrimaryBase = Base;
00859       PrimaryBaseIsVirtual = false;
00860       return;
00861     }
00862   }
00863 
00864   // The Microsoft ABI doesn't have primary virtual bases.
00865   if (isMicrosoftCXXABI()) {
00866     assert(!PrimaryBase && "Should not get here with a primary base!");
00867     return;
00868   }
00869 
00870   // Under the Itanium ABI, if there is no non-virtual primary base class,
00871   // try to compute the primary virtual base.  The primary virtual base is
00872   // the first nearly empty virtual base that is not an indirect primary
00873   // virtual base class, if one exists.
00874   if (RD->getNumVBases() != 0) {
00875     SelectPrimaryVBase(RD);
00876     if (PrimaryBase)
00877       return;
00878   }
00879 
00880   // Otherwise, it is the first indirect primary base class, if one exists.
00881   if (FirstNearlyEmptyVBase) {
00882     PrimaryBase = FirstNearlyEmptyVBase;
00883     PrimaryBaseIsVirtual = true;
00884     return;
00885   }
00886 
00887   assert(!PrimaryBase && "Should not get here with a primary base!");
00888 }
00889 
00890 BaseSubobjectInfo *
00891 RecordLayoutBuilder::ComputeBaseSubobjectInfo(const CXXRecordDecl *RD, 
00892                                               bool IsVirtual,
00893                                               BaseSubobjectInfo *Derived) {
00894   BaseSubobjectInfo *Info;
00895   
00896   if (IsVirtual) {
00897     // Check if we already have info about this virtual base.
00898     BaseSubobjectInfo *&InfoSlot = VirtualBaseInfo[RD];
00899     if (InfoSlot) {
00900       assert(InfoSlot->Class == RD && "Wrong class for virtual base info!");
00901       return InfoSlot;
00902     }
00903 
00904     // We don't, create it.
00905     InfoSlot = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
00906     Info = InfoSlot;
00907   } else {
00908     Info = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
00909   }
00910   
00911   Info->Class = RD;
00912   Info->IsVirtual = IsVirtual;
00913   Info->Derived = 0;
00914   Info->PrimaryVirtualBaseInfo = 0;
00915   
00916   const CXXRecordDecl *PrimaryVirtualBase = 0;
00917   BaseSubobjectInfo *PrimaryVirtualBaseInfo = 0;
00918 
00919   // Check if this base has a primary virtual base.
00920   if (RD->getNumVBases()) {
00921     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
00922     if (Layout.isPrimaryBaseVirtual()) {
00923       // This base does have a primary virtual base.
00924       PrimaryVirtualBase = Layout.getPrimaryBase();
00925       assert(PrimaryVirtualBase && "Didn't have a primary virtual base!");
00926       
00927       // Now check if we have base subobject info about this primary base.
00928       PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
00929       
00930       if (PrimaryVirtualBaseInfo) {
00931         if (PrimaryVirtualBaseInfo->Derived) {
00932           // We did have info about this primary base, and it turns out that it
00933           // has already been claimed as a primary virtual base for another
00934           // base. 
00935           PrimaryVirtualBase = 0;        
00936         } else {
00937           // We can claim this base as our primary base.
00938           Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
00939           PrimaryVirtualBaseInfo->Derived = Info;
00940         }
00941       }
00942     }
00943   }
00944 
00945   // Now go through all direct bases.
00946   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
00947        E = RD->bases_end(); I != E; ++I) {
00948     bool IsVirtual = I->isVirtual();
00949     
00950     const CXXRecordDecl *BaseDecl =
00951       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
00952     
00953     Info->Bases.push_back(ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, Info));
00954   }
00955   
00956   if (PrimaryVirtualBase && !PrimaryVirtualBaseInfo) {
00957     // Traversing the bases must have created the base info for our primary
00958     // virtual base.
00959     PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
00960     assert(PrimaryVirtualBaseInfo &&
00961            "Did not create a primary virtual base!");
00962       
00963     // Claim the primary virtual base as our primary virtual base.
00964     Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
00965     PrimaryVirtualBaseInfo->Derived = Info;
00966   }
00967   
00968   return Info;
00969 }
00970 
00971 void RecordLayoutBuilder::ComputeBaseSubobjectInfo(const CXXRecordDecl *RD) {
00972   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
00973        E = RD->bases_end(); I != E; ++I) {
00974     bool IsVirtual = I->isVirtual();
00975 
00976     const CXXRecordDecl *BaseDecl =
00977       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
00978     
00979     // Compute the base subobject info for this base.
00980     BaseSubobjectInfo *Info = ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, 0);
00981 
00982     if (IsVirtual) {
00983       // ComputeBaseInfo has already added this base for us.
00984       assert(VirtualBaseInfo.count(BaseDecl) &&
00985              "Did not add virtual base!");
00986     } else {
00987       // Add the base info to the map of non-virtual bases.
00988       assert(!NonVirtualBaseInfo.count(BaseDecl) &&
00989              "Non-virtual base already exists!");
00990       NonVirtualBaseInfo.insert(std::make_pair(BaseDecl, Info));
00991     }
00992   }
00993 }
00994 
00995 void
00996 RecordLayoutBuilder::EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign) {
00997   CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
00998 
00999   // The maximum field alignment overrides base align.
01000   if (!MaxFieldAlignment.isZero()) {
01001     BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
01002     UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
01003   }
01004 
01005   // Round up the current record size to pointer alignment.
01006   setSize(getSize().RoundUpToAlignment(BaseAlign));
01007   setDataSize(getSize());
01008 
01009   // Update the alignment.
01010   UpdateAlignment(BaseAlign, UnpackedBaseAlign);
01011 }
01012 
01013 void
01014 RecordLayoutBuilder::LayoutNonVirtualBases(const CXXRecordDecl *RD) {
01015   // Then, determine the primary base class.
01016   DeterminePrimaryBase(RD);
01017 
01018   // Compute base subobject info.
01019   ComputeBaseSubobjectInfo(RD);
01020   
01021   // If we have a primary base class, lay it out.
01022   if (PrimaryBase) {
01023     if (PrimaryBaseIsVirtual) {
01024       // If the primary virtual base was a primary virtual base of some other
01025       // base class we'll have to steal it.
01026       BaseSubobjectInfo *PrimaryBaseInfo = VirtualBaseInfo.lookup(PrimaryBase);
01027       PrimaryBaseInfo->Derived = 0;
01028       
01029       // We have a virtual primary base, insert it as an indirect primary base.
01030       IndirectPrimaryBases.insert(PrimaryBase);
01031 
01032       assert(!VisitedVirtualBases.count(PrimaryBase) &&
01033              "vbase already visited!");
01034       VisitedVirtualBases.insert(PrimaryBase);
01035 
01036       LayoutVirtualBase(PrimaryBaseInfo);
01037     } else {
01038       BaseSubobjectInfo *PrimaryBaseInfo = 
01039         NonVirtualBaseInfo.lookup(PrimaryBase);
01040       assert(PrimaryBaseInfo && 
01041              "Did not find base info for non-virtual primary base!");
01042 
01043       LayoutNonVirtualBase(PrimaryBaseInfo);
01044     }
01045 
01046   // If this class needs a vtable/vf-table and didn't get one from a
01047   // primary base, add it in now.
01048   } else if (needsVFTable(RD)) {
01049     assert(DataSize == 0 && "Vtable pointer must be at offset zero!");
01050     CharUnits PtrWidth = 
01051       Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
01052     CharUnits PtrAlign = 
01053       Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0));
01054     EnsureVTablePointerAlignment(PtrAlign);
01055     HasOwnVFPtr = true;
01056     setSize(getSize() + PtrWidth);
01057     setDataSize(getSize());
01058   }
01059 
01060   bool HasDirectVirtualBases = false;
01061   bool HasNonVirtualBaseWithVBTable = false;
01062 
01063   // Now lay out the non-virtual bases.
01064   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
01065          E = RD->bases_end(); I != E; ++I) {
01066 
01067     // Ignore virtual bases, but remember that we saw one.
01068     if (I->isVirtual()) {
01069       HasDirectVirtualBases = true;
01070       continue;
01071     }
01072 
01073     const CXXRecordDecl *BaseDecl =
01074       cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
01075 
01076     // Remember if this base has virtual bases itself.
01077     if (BaseDecl->getNumVBases())
01078       HasNonVirtualBaseWithVBTable = true;
01079 
01080     // Skip the primary base, because we've already laid it out.  The
01081     // !PrimaryBaseIsVirtual check is required because we might have a
01082     // non-virtual base of the same type as a primary virtual base.
01083     if (BaseDecl == PrimaryBase && !PrimaryBaseIsVirtual)
01084       continue;
01085 
01086     // Lay out the base.
01087     BaseSubobjectInfo *BaseInfo = NonVirtualBaseInfo.lookup(BaseDecl);
01088     assert(BaseInfo && "Did not find base info for non-virtual base!");
01089 
01090     LayoutNonVirtualBase(BaseInfo);
01091   }
01092 
01093   // In the MS ABI, add the vb-table pointer if we need one, which is
01094   // whenever we have a virtual base and we can't re-use a vb-table
01095   // pointer from a non-virtual base.
01096   if (isMicrosoftCXXABI() &&
01097       HasDirectVirtualBases && !HasNonVirtualBaseWithVBTable) {
01098     CharUnits PtrWidth = 
01099       Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
01100     CharUnits PtrAlign = 
01101       Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0));
01102 
01103     // MSVC potentially over-aligns the vb-table pointer by giving it
01104     // the max alignment of all the non-virtual objects in the class.
01105     // This is completely unnecessary, but we're not here to pass
01106     // judgment.
01107     //
01108     // Note that we've only laid out the non-virtual bases, so on the
01109     // first pass Alignment won't be set correctly here, but if the
01110     // vb-table doesn't end up aligned correctly we'll come through
01111     // and redo the layout from scratch with the right alignment.
01112     //
01113     // TODO: Instead of doing this, just lay out the fields as if the
01114     // vb-table were at offset zero, then retroactively bump the field
01115     // offsets up.
01116     PtrAlign = std::max(PtrAlign, Alignment);
01117 
01118     EnsureVTablePointerAlignment(PtrAlign);
01119     VBPtrOffset = getSize();
01120     setSize(getSize() + PtrWidth);
01121     setDataSize(getSize());
01122   }
01123 }
01124 
01125 void RecordLayoutBuilder::LayoutNonVirtualBase(const BaseSubobjectInfo *Base) {
01126   // Layout the base.
01127   CharUnits Offset = LayoutBase(Base);
01128 
01129   // Add its base class offset.
01130   assert(!Bases.count(Base->Class) && "base offset already exists!");
01131   Bases.insert(std::make_pair(Base->Class, Offset));
01132 
01133   AddPrimaryVirtualBaseOffsets(Base, Offset);
01134 }
01135 
01136 void
01137 RecordLayoutBuilder::AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info, 
01138                                                   CharUnits Offset) {
01139   // This base isn't interesting, it has no virtual bases.
01140   if (!Info->Class->getNumVBases())
01141     return;
01142   
01143   // First, check if we have a virtual primary base to add offsets for.
01144   if (Info->PrimaryVirtualBaseInfo) {
01145     assert(Info->PrimaryVirtualBaseInfo->IsVirtual && 
01146            "Primary virtual base is not virtual!");
01147     if (Info->PrimaryVirtualBaseInfo->Derived == Info) {
01148       // Add the offset.
01149       assert(!VBases.count(Info->PrimaryVirtualBaseInfo->Class) && 
01150              "primary vbase offset already exists!");
01151       VBases.insert(std::make_pair(Info->PrimaryVirtualBaseInfo->Class,
01152                                    ASTRecordLayout::VBaseInfo(Offset, false)));
01153 
01154       // Traverse the primary virtual base.
01155       AddPrimaryVirtualBaseOffsets(Info->PrimaryVirtualBaseInfo, Offset);
01156     }
01157   }
01158 
01159   // Now go through all direct non-virtual bases.
01160   const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
01161   for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) {
01162     const BaseSubobjectInfo *Base = Info->Bases[I];
01163     if (Base->IsVirtual)
01164       continue;
01165 
01166     CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
01167     AddPrimaryVirtualBaseOffsets(Base, BaseOffset);
01168   }
01169 }
01170 
01171 /// needsVFTable - Return true if this class needs a vtable or vf-table
01172 /// when laid out as a base class.  These are treated the same because
01173 /// they're both always laid out at offset zero.
01174 ///
01175 /// This function assumes that the class has no primary base.
01176 bool RecordLayoutBuilder::needsVFTable(const CXXRecordDecl *RD) const {
01177   assert(!PrimaryBase);
01178 
01179   // In the Itanium ABI, every dynamic class needs a vtable: even if
01180   // this class has no virtual functions as a base class (i.e. it's
01181   // non-polymorphic or only has virtual functions from virtual
01182   // bases),x it still needs a vtable to locate its virtual bases.
01183   if (!isMicrosoftCXXABI())
01184     return RD->isDynamicClass();
01185 
01186   // In the MS ABI, we need a vfptr if the class has virtual functions
01187   // other than those declared by its virtual bases.  The AST doesn't
01188   // tell us that directly, and checking manually for virtual
01189   // functions that aren't overrides is expensive, but there are
01190   // some important shortcuts:
01191 
01192   //  - Non-polymorphic classes have no virtual functions at all.
01193   if (!RD->isPolymorphic()) return false;
01194 
01195   //  - Polymorphic classes with no virtual bases must either declare
01196   //    virtual functions directly or inherit them, but in the latter
01197   //    case we would have a primary base.
01198   if (RD->getNumVBases() == 0) return true;
01199 
01200   return hasNewVirtualFunction(RD);
01201 }
01202 
01203 /// Does the given class inherit non-virtually from any of the classes
01204 /// in the given set?
01205 static bool hasNonVirtualBaseInSet(const CXXRecordDecl *RD, 
01206                                    const ClassSetTy &set) {
01207   for (CXXRecordDecl::base_class_const_iterator
01208          I = RD->bases_begin(), E = RD->bases_end(); I != E; ++I) {
01209     // Ignore virtual links.
01210     if (I->isVirtual()) continue;
01211 
01212     // Check whether the set contains the base.
01213     const CXXRecordDecl *base = I->getType()->getAsCXXRecordDecl();
01214     if (set.count(base))
01215       return true;
01216 
01217     // Otherwise, recurse and propagate.
01218     if (hasNonVirtualBaseInSet(base, set))
01219       return true;
01220   }
01221 
01222   return false;
01223 }
01224 
01225 /// Does the given method (B::foo()) already override a method (A::foo())
01226 /// such that A requires a vtordisp in B?  If so, we don't need to add a
01227 /// new vtordisp for B in a yet-more-derived class C providing C::foo().
01228 static bool overridesMethodRequiringVtorDisp(const ASTContext &Context,
01229                                              const CXXMethodDecl *M) {
01230   CXXMethodDecl::method_iterator
01231     I = M->begin_overridden_methods(), E = M->end_overridden_methods();
01232   if (I == E) return false;
01233 
01234   const ASTRecordLayout::VBaseOffsetsMapTy &offsets =
01235     Context.getASTRecordLayout(M->getParent()).getVBaseOffsetsMap();
01236   do {
01237     const CXXMethodDecl *overridden = *I;
01238 
01239     // If the overridden method's class isn't recognized as a virtual
01240     // base in the derived class, ignore it.
01241     ASTRecordLayout::VBaseOffsetsMapTy::const_iterator
01242       it = offsets.find(overridden->getParent());
01243     if (it == offsets.end()) continue;
01244 
01245     // Otherwise, check if the overridden method's class needs a vtordisp.
01246     if (it->second.hasVtorDisp()) return true;
01247 
01248   } while (++I != E);
01249   return false;
01250 }                                             
01251 
01252 /// In the Microsoft ABI, decide which of the virtual bases require a
01253 /// vtordisp field.
01254 void RecordLayoutBuilder::computeVtordisps(const CXXRecordDecl *RD,
01255                                            ClassSetTy &vtordispVBases) {
01256   // Bail out if we have no virtual bases.
01257   assert(RD->getNumVBases());
01258 
01259   // Build up the set of virtual bases that we haven't decided yet.
01260   ClassSetTy undecidedVBases;
01261   for (CXXRecordDecl::base_class_const_iterator
01262          I = RD->vbases_begin(), E = RD->vbases_end(); I != E; ++I) {
01263     const CXXRecordDecl *vbase = I->getType()->getAsCXXRecordDecl();
01264     undecidedVBases.insert(vbase);
01265   }
01266   assert(!undecidedVBases.empty());
01267 
01268   // A virtual base requires a vtordisp field in a derived class if it
01269   // requires a vtordisp field in a base class.  Walk all the direct
01270   // bases and collect this information.
01271   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
01272        E = RD->bases_end(); I != E; ++I) {
01273     const CXXRecordDecl *base = I->getType()->getAsCXXRecordDecl();
01274     const ASTRecordLayout &baseLayout = Context.getASTRecordLayout(base);
01275 
01276     // Iterate over the set of virtual bases provided by this class.
01277     for (ASTRecordLayout::VBaseOffsetsMapTy::const_iterator
01278            VI = baseLayout.getVBaseOffsetsMap().begin(),
01279            VE = baseLayout.getVBaseOffsetsMap().end(); VI != VE; ++VI) {
01280       // If it doesn't need a vtordisp in this base, ignore it.
01281       if (!VI->second.hasVtorDisp()) continue;
01282 
01283       // If we've already seen it and decided it needs a vtordisp, ignore it.
01284       if (!undecidedVBases.erase(VI->first)) 
01285         continue;
01286 
01287       // Add it.
01288       vtordispVBases.insert(VI->first);
01289 
01290       // Quit as soon as we've decided everything.
01291       if (undecidedVBases.empty()) 
01292         return;
01293     }
01294   }
01295 
01296   // Okay, we have virtual bases that we haven't yet decided about.  A
01297   // virtual base requires a vtordisp if any the non-destructor
01298   // virtual methods declared in this class directly override a method
01299   // provided by that virtual base.  (If so, we need to emit a thunk
01300   // for that method, to be used in the construction vftable, which
01301   // applies an additional 'vtordisp' this-adjustment.)
01302 
01303   // Collect the set of bases directly overridden by any method in this class.
01304   // It's possible that some of these classes won't be virtual bases, or won't be
01305   // provided by virtual bases, or won't be virtual bases in the overridden
01306   // instance but are virtual bases elsewhere.  Only the last matters for what
01307   // we're doing, and we can ignore those:  if we don't directly override
01308   // a method provided by a virtual copy of a base class, but we do directly
01309   // override a method provided by a non-virtual copy of that base class,
01310   // then we must indirectly override the method provided by the virtual base,
01311   // and so we should already have collected it in the loop above.
01312   ClassSetTy overriddenBases;
01313   for (CXXRecordDecl::method_iterator
01314          M = RD->method_begin(), E = RD->method_end(); M != E; ++M) {
01315     // Ignore non-virtual methods and destructors.
01316     if (isa<CXXDestructorDecl>(*M) || !M->isVirtual())
01317       continue;
01318     
01319     for (CXXMethodDecl::method_iterator I = M->begin_overridden_methods(),
01320           E = M->end_overridden_methods(); I != E; ++I) {
01321       const CXXMethodDecl *overriddenMethod = (*I);
01322 
01323       // Ignore methods that override methods from vbases that require
01324       // require vtordisps.
01325       if (overridesMethodRequiringVtorDisp(Context, overriddenMethod))
01326         continue;
01327 
01328       // As an optimization, check immediately whether we're overriding
01329       // something from the undecided set.
01330       const CXXRecordDecl *overriddenBase = overriddenMethod->getParent();
01331       if (undecidedVBases.erase(overriddenBase)) {
01332         vtordispVBases.insert(overriddenBase);
01333         if (undecidedVBases.empty()) return;
01334 
01335         // We can't 'continue;' here because one of our undecided
01336         // vbases might non-virtually inherit from this base.
01337         // Consider:
01338         //   struct A { virtual void foo(); };
01339         //   struct B : A {};
01340         //   struct C : virtual A, virtual B { virtual void foo(); };
01341         // We need a vtordisp for B here.
01342       }
01343 
01344       // Otherwise, just collect it.
01345       overriddenBases.insert(overriddenBase);
01346     }
01347   }
01348 
01349   // Walk the undecided v-bases and check whether they (non-virtually)
01350   // provide any of the overridden bases.  We don't need to consider
01351   // virtual links because the vtordisp inheres to the layout
01352   // subobject containing the base.
01353   for (ClassSetTy::const_iterator
01354          I = undecidedVBases.begin(), E = undecidedVBases.end(); I != E; ++I) {
01355     if (hasNonVirtualBaseInSet(*I, overriddenBases))
01356       vtordispVBases.insert(*I);
01357   }
01358 }
01359 
01360 /// hasNewVirtualFunction - Does the given polymorphic class declare a
01361 /// virtual function that does not override a method from any of its
01362 /// base classes?
01363 bool 
01364 RecordLayoutBuilder::hasNewVirtualFunction(const CXXRecordDecl *RD, 
01365                                            bool IgnoreDestructor) const {
01366   if (!RD->getNumBases()) 
01367     return true;
01368 
01369   for (CXXRecordDecl::method_iterator method = RD->method_begin();
01370        method != RD->method_end();
01371        ++method) {
01372     if (method->isVirtual() && !method->size_overridden_methods() &&
01373         !(IgnoreDestructor && method->getKind() == Decl::CXXDestructor)) {
01374       return true;
01375     }
01376   }
01377   return false;
01378 }
01379 
01380 /// isPossiblePrimaryBase - Is the given base class an acceptable
01381 /// primary base class?
01382 bool 
01383 RecordLayoutBuilder::isPossiblePrimaryBase(const CXXRecordDecl *base) const {
01384   // In the Itanium ABI, a class can be a primary base class if it has
01385   // a vtable for any reason.
01386   if (!isMicrosoftCXXABI())
01387     return base->isDynamicClass();
01388 
01389   // In the MS ABI, a class can only be a primary base class if it
01390   // provides a vf-table at a static offset.  That means it has to be
01391   // non-virtual base.  The existence of a separate vb-table means
01392   // that it's possible to get virtual functions only from a virtual
01393   // base, which we have to guard against.
01394 
01395   // First off, it has to have virtual functions.
01396   if (!base->isPolymorphic()) return false;
01397 
01398   // If it has no virtual bases, then the vfptr must be at a static offset.
01399   if (!base->getNumVBases()) return true;
01400   
01401   // Otherwise, the necessary information is cached in the layout.
01402   const ASTRecordLayout &layout = Context.getASTRecordLayout(base);
01403 
01404   // If the base has its own vfptr, it can be a primary base.
01405   if (layout.hasOwnVFPtr()) return true;
01406 
01407   // If the base has a primary base class, then it can be a primary base.
01408   if (layout.getPrimaryBase()) return true;
01409 
01410   // Otherwise it can't.
01411   return false;
01412 }
01413 
01414 void
01415 RecordLayoutBuilder::LayoutVirtualBases(const CXXRecordDecl *RD,
01416                                         const CXXRecordDecl *MostDerivedClass) {
01417   const CXXRecordDecl *PrimaryBase;
01418   bool PrimaryBaseIsVirtual;
01419 
01420   if (MostDerivedClass == RD) {
01421     PrimaryBase = this->PrimaryBase;
01422     PrimaryBaseIsVirtual = this->PrimaryBaseIsVirtual;
01423   } else {
01424     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
01425     PrimaryBase = Layout.getPrimaryBase();
01426     PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
01427   }
01428 
01429   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
01430          E = RD->bases_end(); I != E; ++I) {
01431     assert(!I->getType()->isDependentType() &&
01432            "Cannot layout class with dependent bases.");
01433 
01434     const CXXRecordDecl *BaseDecl =
01435       cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
01436 
01437     if (I->isVirtual()) {
01438       if (PrimaryBase != BaseDecl || !PrimaryBaseIsVirtual) {
01439         bool IndirectPrimaryBase = IndirectPrimaryBases.count(BaseDecl);
01440 
01441         // Only lay out the virtual base if it's not an indirect primary base.
01442         if (!IndirectPrimaryBase) {
01443           // Only visit virtual bases once.
01444           if (!VisitedVirtualBases.insert(BaseDecl))
01445             continue;
01446 
01447           const BaseSubobjectInfo *BaseInfo = VirtualBaseInfo.lookup(BaseDecl);
01448           assert(BaseInfo && "Did not find virtual base info!");
01449           LayoutVirtualBase(BaseInfo);
01450         }
01451       }
01452     }
01453 
01454     if (!BaseDecl->getNumVBases()) {
01455       // This base isn't interesting since it doesn't have any virtual bases.
01456       continue;
01457     }
01458 
01459     LayoutVirtualBases(BaseDecl, MostDerivedClass);
01460   }
01461 }
01462 
01463 void RecordLayoutBuilder::MSLayoutVirtualBases(const CXXRecordDecl *RD) {
01464   if (!RD->getNumVBases())
01465     return;
01466 
01467   ClassSetTy VtordispVBases;
01468   computeVtordisps(RD, VtordispVBases);
01469   
01470   // This is substantially simplified because there are no virtual
01471   // primary bases.
01472   for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
01473        E = RD->vbases_end(); I != E; ++I) {
01474     const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
01475     const BaseSubobjectInfo *BaseInfo = VirtualBaseInfo.lookup(BaseDecl);
01476     assert(BaseInfo && "Did not find virtual base info!");
01477 
01478     // If this base requires a vtordisp, add enough space for an int field.
01479     // This is apparently always 32-bits, even on x64.
01480     bool vtordispNeeded = false;
01481     if (VtordispVBases.count(BaseDecl)) {
01482       CharUnits IntSize = 
01483         CharUnits::fromQuantity(Context.getTargetInfo().getIntWidth() / 8);
01484 
01485       setSize(getSize() + IntSize);
01486       setDataSize(getSize());
01487       vtordispNeeded = true;
01488     }
01489 
01490     LayoutVirtualBase(BaseInfo, vtordispNeeded);
01491   }
01492 }
01493 
01494 void RecordLayoutBuilder::LayoutVirtualBase(const BaseSubobjectInfo *Base,
01495                                             bool IsVtordispNeed) {
01496   assert(!Base->Derived && "Trying to lay out a primary virtual base!");
01497   
01498   // Layout the base.
01499   CharUnits Offset = LayoutBase(Base);
01500 
01501   // Add its base class offset.
01502   assert(!VBases.count(Base->Class) && "vbase offset already exists!");
01503   VBases.insert(std::make_pair(Base->Class, 
01504                        ASTRecordLayout::VBaseInfo(Offset, IsVtordispNeed)));
01505 
01506   if (!isMicrosoftCXXABI())
01507     AddPrimaryVirtualBaseOffsets(Base, Offset);
01508 }
01509 
01510 CharUnits RecordLayoutBuilder::LayoutBase(const BaseSubobjectInfo *Base) {
01511   const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base->Class);
01512 
01513   
01514   CharUnits Offset;
01515   
01516   // Query the external layout to see if it provides an offset.
01517   bool HasExternalLayout = false;
01518   if (ExternalLayout) {
01519     llvm::DenseMap<const CXXRecordDecl *, CharUnits>::iterator Known;
01520     if (Base->IsVirtual) {
01521       Known = ExternalVirtualBaseOffsets.find(Base->Class);
01522       if (Known != ExternalVirtualBaseOffsets.end()) {
01523         Offset = Known->second;
01524         HasExternalLayout = true;
01525       }
01526     } else {
01527       Known = ExternalBaseOffsets.find(Base->Class);
01528       if (Known != ExternalBaseOffsets.end()) {
01529         Offset = Known->second;
01530         HasExternalLayout = true;
01531       }
01532     }
01533   }
01534   
01535   // If we have an empty base class, try to place it at offset 0.
01536   if (Base->Class->isEmpty() &&
01537       (!HasExternalLayout || Offset == CharUnits::Zero()) &&
01538       EmptySubobjects->CanPlaceBaseAtOffset(Base, CharUnits::Zero())) {
01539     setSize(std::max(getSize(), Layout.getSize()));
01540 
01541     return CharUnits::Zero();
01542   }
01543 
01544   CharUnits UnpackedBaseAlign = Layout.getNonVirtualAlign();
01545   CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
01546 
01547   // The maximum field alignment overrides base align.
01548   if (!MaxFieldAlignment.isZero()) {
01549     BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
01550     UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
01551   }
01552 
01553   if (!HasExternalLayout) {
01554     // Round up the current record size to the base's alignment boundary.
01555     Offset = getDataSize().RoundUpToAlignment(BaseAlign);
01556 
01557     // Try to place the base.
01558     while (!EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset))
01559       Offset += BaseAlign;
01560   } else {
01561     bool Allowed = EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset);
01562     (void)Allowed;
01563     assert(Allowed && "Base subobject externally placed at overlapping offset");
01564   }
01565   
01566   if (!Base->Class->isEmpty()) {
01567     // Update the data size.
01568     setDataSize(Offset + Layout.getNonVirtualSize());
01569 
01570     setSize(std::max(getSize(), getDataSize()));
01571   } else
01572     setSize(std::max(getSize(), Offset + Layout.getSize()));
01573 
01574   // Remember max struct/class alignment.
01575   UpdateAlignment(BaseAlign, UnpackedBaseAlign);
01576 
01577   return Offset;
01578 }
01579 
01580 void RecordLayoutBuilder::InitializeLayout(const Decl *D) {
01581   if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
01582     IsUnion = RD->isUnion();
01583 
01584   Packed = D->hasAttr<PackedAttr>();
01585   
01586   IsMsStruct = D->hasAttr<MsStructAttr>();
01587 
01588   // Honor the default struct packing maximum alignment flag.
01589   if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct) {
01590     MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
01591   }
01592 
01593   // mac68k alignment supersedes maximum field alignment and attribute aligned,
01594   // and forces all structures to have 2-byte alignment. The IBM docs on it
01595   // allude to additional (more complicated) semantics, especially with regard
01596   // to bit-fields, but gcc appears not to follow that.
01597   if (D->hasAttr<AlignMac68kAttr>()) {
01598     IsMac68kAlign = true;
01599     MaxFieldAlignment = CharUnits::fromQuantity(2);
01600     Alignment = CharUnits::fromQuantity(2);
01601   } else {
01602     if (const MaxFieldAlignmentAttr *MFAA = D->getAttr<MaxFieldAlignmentAttr>())
01603       MaxFieldAlignment = Context.toCharUnitsFromBits(MFAA->getAlignment());
01604 
01605     if (unsigned MaxAlign = D->getMaxAlignment())
01606       UpdateAlignment(Context.toCharUnitsFromBits(MaxAlign));
01607   }
01608   
01609   // If there is an external AST source, ask it for the various offsets.
01610   if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
01611     if (ExternalASTSource *External = Context.getExternalSource()) {
01612       ExternalLayout = External->layoutRecordType(RD, 
01613                                                   ExternalSize,
01614                                                   ExternalAlign,
01615                                                   ExternalFieldOffsets,
01616                                                   ExternalBaseOffsets,
01617                                                   ExternalVirtualBaseOffsets);
01618       
01619       // Update based on external alignment.
01620       if (ExternalLayout) {
01621         if (ExternalAlign > 0) {
01622           Alignment = Context.toCharUnitsFromBits(ExternalAlign);
01623           UnpackedAlignment = Alignment;
01624         } else {
01625           // The external source didn't have alignment information; infer it.
01626           InferAlignment = true;
01627         }
01628       }
01629     }
01630 }
01631 
01632 void RecordLayoutBuilder::Layout(const RecordDecl *D) {
01633   InitializeLayout(D);
01634   LayoutFields(D);
01635 
01636   // Finally, round the size of the total struct up to the alignment of the
01637   // struct itself.
01638   FinishLayout(D);
01639 }
01640 
01641 void RecordLayoutBuilder::Layout(const CXXRecordDecl *RD) {
01642   InitializeLayout(RD);
01643 
01644   // Lay out the vtable and the non-virtual bases.
01645   LayoutNonVirtualBases(RD);
01646 
01647   LayoutFields(RD);
01648 
01649   NonVirtualSize = Context.toCharUnitsFromBits(
01650         llvm::RoundUpToAlignment(getSizeInBits(), 
01651                                  Context.getTargetInfo().getCharAlign()));
01652   NonVirtualAlignment = Alignment;
01653 
01654   if (isMicrosoftCXXABI()) {
01655     if (NonVirtualSize != NonVirtualSize.RoundUpToAlignment(Alignment)) {
01656     CharUnits AlignMember = 
01657       NonVirtualSize.RoundUpToAlignment(Alignment) - NonVirtualSize;
01658 
01659     setSize(getSize() + AlignMember);
01660     setDataSize(getSize());
01661 
01662     NonVirtualSize = Context.toCharUnitsFromBits(
01663                              llvm::RoundUpToAlignment(getSizeInBits(),
01664                              Context.getTargetInfo().getCharAlign()));
01665     }
01666 
01667     MSLayoutVirtualBases(RD);
01668   } else {
01669     // Lay out the virtual bases and add the primary virtual base offsets.
01670     LayoutVirtualBases(RD, RD);
01671   }
01672 
01673   // Finally, round the size of the total struct up to the alignment
01674   // of the struct itself.
01675   FinishLayout(RD);
01676 
01677 #ifndef NDEBUG
01678   // Check that we have base offsets for all bases.
01679   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
01680        E = RD->bases_end(); I != E; ++I) {
01681     if (I->isVirtual())
01682       continue;
01683 
01684     const CXXRecordDecl *BaseDecl =
01685       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
01686 
01687     assert(Bases.count(BaseDecl) && "Did not find base offset!");
01688   }
01689 
01690   // And all virtual bases.
01691   for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
01692        E = RD->vbases_end(); I != E; ++I) {
01693     const CXXRecordDecl *BaseDecl =
01694       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
01695 
01696     assert(VBases.count(BaseDecl) && "Did not find base offset!");
01697   }
01698 #endif
01699 }
01700 
01701 void RecordLayoutBuilder::Layout(const ObjCInterfaceDecl *D) {
01702   if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
01703     const ASTRecordLayout &SL = Context.getASTObjCInterfaceLayout(SD);
01704 
01705     UpdateAlignment(SL.getAlignment());
01706 
01707     // We start laying out ivars not at the end of the superclass
01708     // structure, but at the next byte following the last field.
01709     setSize(SL.getDataSize());
01710     setDataSize(getSize());
01711   }
01712 
01713   InitializeLayout(D);
01714   // Layout each ivar sequentially.
01715   for (const ObjCIvarDecl *IVD = D->all_declared_ivar_begin(); IVD;
01716        IVD = IVD->getNextIvar())
01717     LayoutField(IVD);
01718 
01719   // Finally, round the size of the total struct up to the alignment of the
01720   // struct itself.
01721   FinishLayout(D);
01722 }
01723 
01724 void RecordLayoutBuilder::LayoutFields(const RecordDecl *D) {
01725   // Layout each field, for now, just sequentially, respecting alignment.  In
01726   // the future, this will need to be tweakable by targets.
01727   const FieldDecl *LastFD = 0;
01728   ZeroLengthBitfield = 0;
01729   unsigned RemainingInAlignment = 0;
01730   for (RecordDecl::field_iterator Field = D->field_begin(),
01731        FieldEnd = D->field_end(); Field != FieldEnd; ++Field) {
01732     if (IsMsStruct) {
01733       FieldDecl *FD = &*Field;
01734       if (Context.ZeroBitfieldFollowsBitfield(FD, LastFD))
01735         ZeroLengthBitfield = FD;
01736       // Zero-length bitfields following non-bitfield members are
01737       // ignored:
01738       else if (Context.ZeroBitfieldFollowsNonBitfield(FD, LastFD))
01739         continue;
01740       // FIXME. streamline these conditions into a simple one.
01741       else if (Context.BitfieldFollowsBitfield(FD, LastFD) ||
01742                Context.BitfieldFollowsNonBitfield(FD, LastFD) ||
01743                Context.NonBitfieldFollowsBitfield(FD, LastFD)) {
01744         // 1) Adjacent bit fields are packed into the same 1-, 2-, or
01745         // 4-byte allocation unit if the integral types are the same
01746         // size and if the next bit field fits into the current
01747         // allocation unit without crossing the boundary imposed by the
01748         // common alignment requirements of the bit fields.
01749         // 2) Establish a new alignment for a bitfield following
01750         // a non-bitfield if size of their types differ.
01751         // 3) Establish a new alignment for a non-bitfield following
01752         // a bitfield if size of their types differ.
01753         std::pair<uint64_t, unsigned> FieldInfo = 
01754           Context.getTypeInfo(FD->getType());
01755         uint64_t TypeSize = FieldInfo.first;
01756         unsigned FieldAlign = FieldInfo.second;
01757         // This check is needed for 'long long' in -m32 mode.
01758         if (TypeSize > FieldAlign &&
01759             (Context.hasSameType(FD->getType(), 
01760                                 Context.UnsignedLongLongTy) 
01761              ||Context.hasSameType(FD->getType(), 
01762                                    Context.LongLongTy)))
01763           FieldAlign = TypeSize;
01764         FieldInfo = Context.getTypeInfo(LastFD->getType());
01765         uint64_t TypeSizeLastFD = FieldInfo.first;
01766         unsigned FieldAlignLastFD = FieldInfo.second;
01767         // This check is needed for 'long long' in -m32 mode.
01768         if (TypeSizeLastFD > FieldAlignLastFD &&
01769             (Context.hasSameType(LastFD->getType(), 
01770                                 Context.UnsignedLongLongTy)
01771              || Context.hasSameType(LastFD->getType(), 
01772                                     Context.LongLongTy)))
01773           FieldAlignLastFD = TypeSizeLastFD;
01774         
01775         if (TypeSizeLastFD != TypeSize) {
01776           if (RemainingInAlignment &&
01777               LastFD && LastFD->isBitField() &&
01778               LastFD->getBitWidthValue(Context)) {
01779             // If previous field was a bitfield with some remaining unfilled
01780             // bits, pad the field so current field starts on its type boundary.
01781             uint64_t FieldOffset = 
01782             getDataSizeInBits() - UnfilledBitsInLastByte;
01783             uint64_t NewSizeInBits = RemainingInAlignment + FieldOffset;
01784             setDataSize(llvm::RoundUpToAlignment(NewSizeInBits,
01785                                                  Context.getTargetInfo().getCharAlign()));
01786             setSize(std::max(getSizeInBits(), getDataSizeInBits()));
01787             RemainingInAlignment = 0;
01788           }
01789           
01790           uint64_t UnpaddedFieldOffset = 
01791             getDataSizeInBits() - UnfilledBitsInLastByte;
01792           FieldAlign = std::max(FieldAlign, FieldAlignLastFD);
01793           
01794           // The maximum field alignment overrides the aligned attribute.
01795           if (!MaxFieldAlignment.isZero()) {
01796             unsigned MaxFieldAlignmentInBits = 
01797               Context.toBits(MaxFieldAlignment);
01798             FieldAlign = std::min(FieldAlign, MaxFieldAlignmentInBits);
01799           }
01800           
01801           uint64_t NewSizeInBits = 
01802             llvm::RoundUpToAlignment(UnpaddedFieldOffset, FieldAlign);
01803           setDataSize(llvm::RoundUpToAlignment(NewSizeInBits,
01804                                                Context.getTargetInfo().getCharAlign()));
01805           UnfilledBitsInLastByte = getDataSizeInBits() - NewSizeInBits;
01806           setSize(std::max(getSizeInBits(), getDataSizeInBits()));
01807         }
01808         if (FD->isBitField()) {
01809           uint64_t FieldSize = FD->getBitWidthValue(Context);
01810           assert (FieldSize > 0 && "LayoutFields - ms_struct layout");
01811           if (RemainingInAlignment < FieldSize)
01812             RemainingInAlignment = TypeSize - FieldSize;
01813           else
01814             RemainingInAlignment -= FieldSize;
01815         }
01816       }
01817       else if (FD->isBitField()) {
01818         uint64_t FieldSize = FD->getBitWidthValue(Context);
01819         std::pair<uint64_t, unsigned> FieldInfo = 
01820           Context.getTypeInfo(FD->getType());
01821         uint64_t TypeSize = FieldInfo.first;
01822         RemainingInAlignment = TypeSize - FieldSize;
01823       }
01824       LastFD = FD;
01825     }
01826     else if (!Context.getTargetInfo().useBitFieldTypeAlignment() &&
01827              Context.getTargetInfo().useZeroLengthBitfieldAlignment()) {             
01828       FieldDecl *FD = &*Field;
01829       if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
01830         ZeroLengthBitfield = FD;
01831     }
01832     LayoutField(&*Field);
01833   }
01834   if (IsMsStruct && RemainingInAlignment &&
01835       LastFD && LastFD->isBitField() && LastFD->getBitWidthValue(Context)) {
01836     // If we ended a bitfield before the full length of the type then
01837     // pad the struct out to the full length of the last type.
01838     uint64_t FieldOffset = 
01839       getDataSizeInBits() - UnfilledBitsInLastByte;
01840     uint64_t NewSizeInBits = RemainingInAlignment + FieldOffset;
01841     setDataSize(llvm::RoundUpToAlignment(NewSizeInBits,
01842                                          Context.getTargetInfo().getCharAlign()));
01843     setSize(std::max(getSizeInBits(), getDataSizeInBits()));
01844   }
01845 }
01846 
01847 void RecordLayoutBuilder::LayoutWideBitField(uint64_t FieldSize,
01848                                              uint64_t TypeSize,
01849                                              bool FieldPacked,
01850                                              const FieldDecl *D) {
01851   assert(Context.getLangOpts().CPlusPlus &&
01852          "Can only have wide bit-fields in C++!");
01853 
01854   // Itanium C++ ABI 2.4:
01855   //   If sizeof(T)*8 < n, let T' be the largest integral POD type with
01856   //   sizeof(T')*8 <= n.
01857 
01858   QualType IntegralPODTypes[] = {
01859     Context.UnsignedCharTy, Context.UnsignedShortTy, Context.UnsignedIntTy,
01860     Context.UnsignedLongTy, Context.UnsignedLongLongTy
01861   };
01862 
01863   QualType Type;
01864   for (unsigned I = 0, E = llvm::array_lengthof(IntegralPODTypes);
01865        I != E; ++I) {
01866     uint64_t Size = Context.getTypeSize(IntegralPODTypes[I]);
01867 
01868     if (Size > FieldSize)
01869       break;
01870 
01871     Type = IntegralPODTypes[I];
01872   }
01873   assert(!Type.isNull() && "Did not find a type!");
01874 
01875   CharUnits TypeAlign = Context.getTypeAlignInChars(Type);
01876 
01877   // We're not going to use any of the unfilled bits in the last byte.
01878   UnfilledBitsInLastByte = 0;
01879 
01880   uint64_t FieldOffset;
01881   uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastByte;
01882 
01883   if (IsUnion) {
01884     setDataSize(std::max(getDataSizeInBits(), FieldSize));
01885     FieldOffset = 0;
01886   } else {
01887     // The bitfield is allocated starting at the next offset aligned 
01888     // appropriately for T', with length n bits.
01889     FieldOffset = llvm::RoundUpToAlignment(getDataSizeInBits(), 
01890                                            Context.toBits(TypeAlign));
01891 
01892     uint64_t NewSizeInBits = FieldOffset + FieldSize;
01893 
01894     setDataSize(llvm::RoundUpToAlignment(NewSizeInBits, 
01895                                          Context.getTargetInfo().getCharAlign()));
01896     UnfilledBitsInLastByte = getDataSizeInBits() - NewSizeInBits;
01897   }
01898 
01899   // Place this field at the current location.
01900   FieldOffsets.push_back(FieldOffset);
01901 
01902   CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, FieldOffset,
01903                     Context.toBits(TypeAlign), FieldPacked, D);
01904 
01905   // Update the size.
01906   setSize(std::max(getSizeInBits(), getDataSizeInBits()));
01907 
01908   // Remember max struct/class alignment.
01909   UpdateAlignment(TypeAlign);
01910 }
01911 
01912 void RecordLayoutBuilder::LayoutBitField(const FieldDecl *D) {
01913   bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
01914   uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastByte;
01915   uint64_t FieldOffset = IsUnion ? 0 : UnpaddedFieldOffset;
01916   uint64_t FieldSize = D->getBitWidthValue(Context);
01917 
01918   std::pair<uint64_t, unsigned> FieldInfo = Context.getTypeInfo(D->getType());
01919   uint64_t TypeSize = FieldInfo.first;
01920   unsigned FieldAlign = FieldInfo.second;
01921   
01922   // This check is needed for 'long long' in -m32 mode.
01923   if (IsMsStruct && (TypeSize > FieldAlign) && 
01924       (Context.hasSameType(D->getType(), 
01925                            Context.UnsignedLongLongTy) 
01926        || Context.hasSameType(D->getType(), Context.LongLongTy)))
01927     FieldAlign = TypeSize;
01928 
01929   if (ZeroLengthBitfield) {
01930     std::pair<uint64_t, unsigned> FieldInfo;
01931     unsigned ZeroLengthBitfieldAlignment;
01932     if (IsMsStruct) {
01933       // If a zero-length bitfield is inserted after a bitfield,
01934       // and the alignment of the zero-length bitfield is
01935       // greater than the member that follows it, `bar', `bar' 
01936       // will be aligned as the type of the zero-length bitfield.
01937       if (ZeroLengthBitfield != D) {
01938         FieldInfo = Context.getTypeInfo(ZeroLengthBitfield->getType());
01939         ZeroLengthBitfieldAlignment = FieldInfo.second;
01940         // Ignore alignment of subsequent zero-length bitfields.
01941         if ((ZeroLengthBitfieldAlignment > FieldAlign) || (FieldSize == 0))
01942           FieldAlign = ZeroLengthBitfieldAlignment;
01943         if (FieldSize)
01944           ZeroLengthBitfield = 0;
01945       }
01946     } else {
01947       // The alignment of a zero-length bitfield affects the alignment
01948       // of the next member.  The alignment is the max of the zero 
01949       // length bitfield's alignment and a target specific fixed value.
01950       unsigned ZeroLengthBitfieldBoundary =
01951         Context.getTargetInfo().getZeroLengthBitfieldBoundary();
01952       if (ZeroLengthBitfieldBoundary > FieldAlign)
01953         FieldAlign = ZeroLengthBitfieldBoundary;
01954     }
01955   }
01956 
01957   if (FieldSize > TypeSize) {
01958     LayoutWideBitField(FieldSize, TypeSize, FieldPacked, D);
01959     return;
01960   }
01961 
01962   // The align if the field is not packed. This is to check if the attribute
01963   // was unnecessary (-Wpacked).
01964   unsigned UnpackedFieldAlign = FieldAlign;
01965   uint64_t UnpackedFieldOffset = FieldOffset;
01966   if (!Context.getTargetInfo().useBitFieldTypeAlignment() && !ZeroLengthBitfield)
01967     UnpackedFieldAlign = 1;
01968 
01969   if (FieldPacked || 
01970       (!Context.getTargetInfo().useBitFieldTypeAlignment() && !ZeroLengthBitfield))
01971     FieldAlign = 1;
01972   FieldAlign = std::max(FieldAlign, D->getMaxAlignment());
01973   UnpackedFieldAlign = std::max(UnpackedFieldAlign, D->getMaxAlignment());
01974 
01975   // The maximum field alignment overrides the aligned attribute.
01976   if (!MaxFieldAlignment.isZero() && FieldSize != 0) {
01977     unsigned MaxFieldAlignmentInBits = Context.toBits(MaxFieldAlignment);
01978     FieldAlign = std::min(FieldAlign, MaxFieldAlignmentInBits);
01979     UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignmentInBits);
01980   }
01981 
01982   // Check if we need to add padding to give the field the correct alignment.
01983   if (FieldSize == 0 || 
01984       (MaxFieldAlignment.isZero() &&
01985        (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize))
01986     FieldOffset = llvm::RoundUpToAlignment(FieldOffset, FieldAlign);
01987 
01988   if (FieldSize == 0 ||
01989       (MaxFieldAlignment.isZero() &&
01990        (UnpackedFieldOffset & (UnpackedFieldAlign-1)) + FieldSize > TypeSize))
01991     UnpackedFieldOffset = llvm::RoundUpToAlignment(UnpackedFieldOffset,
01992                                                    UnpackedFieldAlign);
01993 
01994   // Padding members don't affect overall alignment, unless zero length bitfield
01995   // alignment is enabled.
01996   if (!D->getIdentifier() && !Context.getTargetInfo().useZeroLengthBitfieldAlignment())
01997     FieldAlign = UnpackedFieldAlign = 1;
01998 
01999   if (!IsMsStruct)
02000     ZeroLengthBitfield = 0;
02001 
02002   if (ExternalLayout)
02003     FieldOffset = updateExternalFieldOffset(D, FieldOffset);
02004 
02005   // Place this field at the current location.
02006   FieldOffsets.push_back(FieldOffset);
02007 
02008   if (!ExternalLayout)
02009     CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, UnpackedFieldOffset,
02010                       UnpackedFieldAlign, FieldPacked, D);
02011 
02012   // Update DataSize to include the last byte containing (part of) the bitfield.
02013   if (IsUnion) {
02014     // FIXME: I think FieldSize should be TypeSize here.
02015     setDataSize(std::max(getDataSizeInBits(), FieldSize));
02016   } else {
02017     uint64_t NewSizeInBits = FieldOffset + FieldSize;
02018 
02019     setDataSize(llvm::RoundUpToAlignment(NewSizeInBits, 
02020                                          Context.getTargetInfo().getCharAlign()));
02021     UnfilledBitsInLastByte = getDataSizeInBits() - NewSizeInBits;
02022   }
02023 
02024   // Update the size.
02025   setSize(std::max(getSizeInBits(), getDataSizeInBits()));
02026 
02027   // Remember max struct/class alignment.
02028   UpdateAlignment(Context.toCharUnitsFromBits(FieldAlign), 
02029                   Context.toCharUnitsFromBits(UnpackedFieldAlign));
02030 }
02031 
02032 void RecordLayoutBuilder::LayoutField(const FieldDecl *D) {  
02033   if (D->isBitField()) {
02034     LayoutBitField(D);
02035     return;
02036   }
02037 
02038   uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastByte;
02039 
02040   // Reset the unfilled bits.
02041   UnfilledBitsInLastByte = 0;
02042 
02043   bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
02044   CharUnits FieldOffset = 
02045     IsUnion ? CharUnits::Zero() : getDataSize();
02046   CharUnits FieldSize;
02047   CharUnits FieldAlign;
02048 
02049   if (D->getType()->isIncompleteArrayType()) {
02050     // This is a flexible array member; we can't directly
02051     // query getTypeInfo about these, so we figure it out here.
02052     // Flexible array members don't have any size, but they
02053     // have to be aligned appropriately for their element type.
02054     FieldSize = CharUnits::Zero();
02055     const ArrayType* ATy = Context.getAsArrayType(D->getType());
02056     FieldAlign = Context.getTypeAlignInChars(ATy->getElementType());
02057   } else if (const ReferenceType *RT = D->getType()->getAs<ReferenceType>()) {
02058     unsigned AS = RT->getPointeeType().getAddressSpace();
02059     FieldSize = 
02060       Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(AS));
02061     FieldAlign = 
02062       Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(AS));
02063   } else {
02064     std::pair<CharUnits, CharUnits> FieldInfo = 
02065       Context.getTypeInfoInChars(D->getType());
02066     FieldSize = FieldInfo.first;
02067     FieldAlign = FieldInfo.second;
02068 
02069     if (ZeroLengthBitfield) {
02070       CharUnits ZeroLengthBitfieldBoundary = 
02071         Context.toCharUnitsFromBits(
02072           Context.getTargetInfo().getZeroLengthBitfieldBoundary());
02073       if (ZeroLengthBitfieldBoundary == CharUnits::Zero()) {
02074         // If a zero-length bitfield is inserted after a bitfield,
02075         // and the alignment of the zero-length bitfield is
02076         // greater than the member that follows it, `bar', `bar' 
02077         // will be aligned as the type of the zero-length bitfield.
02078         std::pair<CharUnits, CharUnits> FieldInfo = 
02079           Context.getTypeInfoInChars(ZeroLengthBitfield->getType());
02080         CharUnits ZeroLengthBitfieldAlignment = FieldInfo.second;        
02081         if (ZeroLengthBitfieldAlignment > FieldAlign)
02082           FieldAlign = ZeroLengthBitfieldAlignment;
02083       } else if (ZeroLengthBitfieldBoundary > FieldAlign) {
02084         // Align 'bar' based on a fixed alignment specified by the target.
02085         assert(Context.getTargetInfo().useZeroLengthBitfieldAlignment() &&
02086                "ZeroLengthBitfieldBoundary should only be used in conjunction"
02087                " with useZeroLengthBitfieldAlignment.");
02088         FieldAlign = ZeroLengthBitfieldBoundary;
02089       }
02090       ZeroLengthBitfield = 0;
02091     }
02092 
02093     if (Context.getLangOpts().MSBitfields || IsMsStruct) {
02094       // If MS bitfield layout is required, figure out what type is being
02095       // laid out and align the field to the width of that type.
02096       
02097       // Resolve all typedefs down to their base type and round up the field
02098       // alignment if necessary.
02099       QualType T = Context.getBaseElementType(D->getType());
02100       if (const BuiltinType *BTy = T->getAs<BuiltinType>()) {
02101         CharUnits TypeSize = Context.getTypeSizeInChars(BTy);
02102         if (TypeSize > FieldAlign)
02103           FieldAlign = TypeSize;
02104       }
02105     }
02106   }
02107 
02108   // The align if the field is not packed. This is to check if the attribute
02109   // was unnecessary (-Wpacked).
02110   CharUnits UnpackedFieldAlign = FieldAlign;
02111   CharUnits UnpackedFieldOffset = FieldOffset;
02112 
02113   if (FieldPacked)
02114     FieldAlign = CharUnits::One();
02115   CharUnits MaxAlignmentInChars = 
02116     Context.toCharUnitsFromBits(D->getMaxAlignment());
02117   FieldAlign = std::max(FieldAlign, MaxAlignmentInChars);
02118   UnpackedFieldAlign = std::max(UnpackedFieldAlign, MaxAlignmentInChars);
02119 
02120   // The maximum field alignment overrides the aligned attribute.
02121   if (!MaxFieldAlignment.isZero()) {
02122     FieldAlign = std::min(FieldAlign, MaxFieldAlignment);
02123     UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignment);
02124   }
02125 
02126   // Round up the current record size to the field's alignment boundary.
02127   FieldOffset = FieldOffset.RoundUpToAlignment(FieldAlign);
02128   UnpackedFieldOffset = 
02129     UnpackedFieldOffset.RoundUpToAlignment(UnpackedFieldAlign);
02130 
02131   if (ExternalLayout) {
02132     FieldOffset = Context.toCharUnitsFromBits(
02133                     updateExternalFieldOffset(D, Context.toBits(FieldOffset)));
02134     
02135     if (!IsUnion && EmptySubobjects) {
02136       // Record the fact that we're placing a field at this offset.
02137       bool Allowed = EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset);
02138       (void)Allowed;
02139       assert(Allowed && "Externally-placed field cannot be placed here");      
02140     }
02141   } else {
02142     if (!IsUnion && EmptySubobjects) {
02143       // Check if we can place the field at this offset.
02144       while (!EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset)) {
02145         // We couldn't place the field at the offset. Try again at a new offset.
02146         FieldOffset += FieldAlign;
02147       }
02148     }
02149   }
02150   
02151   // Place this field at the current location.
02152   FieldOffsets.push_back(Context.toBits(FieldOffset));
02153 
02154   if (!ExternalLayout)
02155     CheckFieldPadding(Context.toBits(FieldOffset), UnpaddedFieldOffset, 
02156                       Context.toBits(UnpackedFieldOffset),
02157                       Context.toBits(UnpackedFieldAlign), FieldPacked, D);
02158 
02159   // Reserve space for this field.
02160   uint64_t FieldSizeInBits = Context.toBits(FieldSize);
02161   if (IsUnion)
02162     setDataSize(std::max(getDataSizeInBits(), FieldSizeInBits));
02163   else
02164     setDataSize(FieldOffset + FieldSize);
02165 
02166   // Update the size.
02167   setSize(std::max(getSizeInBits(), getDataSizeInBits()));
02168 
02169   // Remember max struct/class alignment.
02170   UpdateAlignment(FieldAlign, UnpackedFieldAlign);
02171 }
02172 
02173 void RecordLayoutBuilder::FinishLayout(const NamedDecl *D) {
02174   if (ExternalLayout) {
02175     setSize(ExternalSize);
02176     return;
02177   }
02178   
02179   // In C++, records cannot be of size 0.
02180   if (Context.getLangOpts().CPlusPlus && getSizeInBits() == 0) {
02181     if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
02182       // Compatibility with gcc requires a class (pod or non-pod)
02183       // which is not empty but of size 0; such as having fields of
02184       // array of zero-length, remains of Size 0
02185       if (RD->isEmpty())
02186         setSize(CharUnits::One());
02187     }
02188     else
02189       setSize(CharUnits::One());
02190   }
02191 
02192   // MSVC doesn't round up to the alignment of the record with virtual bases.
02193   if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
02194     if (isMicrosoftCXXABI() && RD->getNumVBases())
02195       return;
02196   }
02197 
02198   // Finally, round the size of the record up to the alignment of the
02199   // record itself.
02200   uint64_t UnpaddedSize = getSizeInBits() - UnfilledBitsInLastByte;
02201   uint64_t UnpackedSizeInBits = 
02202     llvm::RoundUpToAlignment(getSizeInBits(), 
02203                              Context.toBits(UnpackedAlignment));
02204   CharUnits UnpackedSize = Context.toCharUnitsFromBits(UnpackedSizeInBits);
02205   setSize(llvm::RoundUpToAlignment(getSizeInBits(), Context.toBits(Alignment)));
02206 
02207   unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
02208   if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
02209     // Warn if padding was introduced to the struct/class/union.
02210     if (getSizeInBits() > UnpaddedSize) {
02211       unsigned PadSize = getSizeInBits() - UnpaddedSize;
02212       bool InBits = true;
02213       if (PadSize % CharBitNum == 0) {
02214         PadSize = PadSize / CharBitNum;
02215         InBits = false;
02216       }
02217       Diag(RD->getLocation(), diag::warn_padded_struct_size)
02218           << Context.getTypeDeclType(RD)
02219           << PadSize
02220           << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1); // plural or not
02221     }
02222 
02223     // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
02224     // bother since there won't be alignment issues.
02225     if (Packed && UnpackedAlignment > CharUnits::One() && 
02226         getSize() == UnpackedSize)
02227       Diag(D->getLocation(), diag::warn_unnecessary_packed)
02228           << Context.getTypeDeclType(RD);
02229   }
02230 }
02231 
02232 void RecordLayoutBuilder::UpdateAlignment(CharUnits NewAlignment,
02233                                           CharUnits UnpackedNewAlignment) {
02234   // The alignment is not modified when using 'mac68k' alignment or when
02235   // we have an externally-supplied layout that also provides overall alignment.
02236   if (IsMac68kAlign || (ExternalLayout && !InferAlignment))
02237     return;
02238 
02239   if (NewAlignment > Alignment) {
02240     assert(llvm::isPowerOf2_32(NewAlignment.getQuantity() && 
02241            "Alignment not a power of 2"));
02242     Alignment = NewAlignment;
02243   }
02244 
02245   if (UnpackedNewAlignment > UnpackedAlignment) {
02246     assert(llvm::isPowerOf2_32(UnpackedNewAlignment.getQuantity() &&
02247            "Alignment not a power of 2"));
02248     UnpackedAlignment = UnpackedNewAlignment;
02249   }
02250 }
02251 
02252 uint64_t
02253 RecordLayoutBuilder::updateExternalFieldOffset(const FieldDecl *Field, 
02254                                                uint64_t ComputedOffset) {
02255   assert(ExternalFieldOffsets.find(Field) != ExternalFieldOffsets.end() &&
02256          "Field does not have an external offset");
02257   
02258   uint64_t ExternalFieldOffset = ExternalFieldOffsets[Field];
02259   
02260   if (InferAlignment && ExternalFieldOffset < ComputedOffset) {
02261     // The externally-supplied field offset is before the field offset we
02262     // computed. Assume that the structure is packed.
02263     Alignment = CharUnits::fromQuantity(1);
02264     InferAlignment = false;
02265   }
02266   
02267   // Use the externally-supplied field offset.
02268   return ExternalFieldOffset;
02269 }
02270 
02271 void RecordLayoutBuilder::CheckFieldPadding(uint64_t Offset,
02272                                             uint64_t UnpaddedOffset,
02273                                             uint64_t UnpackedOffset,
02274                                             unsigned UnpackedAlign,
02275                                             bool isPacked,
02276                                             const FieldDecl *D) {
02277   // We let objc ivars without warning, objc interfaces generally are not used
02278   // for padding tricks.
02279   if (isa<ObjCIvarDecl>(D))
02280     return;
02281 
02282   // Don't warn about structs created without a SourceLocation.  This can
02283   // be done by clients of the AST, such as codegen.
02284   if (D->getLocation().isInvalid())
02285     return;
02286   
02287   unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
02288 
02289   // Warn if padding was introduced to the struct/class.
02290   if (!IsUnion && Offset > UnpaddedOffset) {
02291     unsigned PadSize = Offset - UnpaddedOffset;
02292     bool InBits = true;
02293     if (PadSize % CharBitNum == 0) {
02294       PadSize = PadSize / CharBitNum;
02295       InBits = false;
02296     }
02297     if (D->getIdentifier())
02298       Diag(D->getLocation(), diag::warn_padded_struct_field)
02299           << (D->getParent()->isStruct() ? 0 : 1) // struct|class
02300           << Context.getTypeDeclType(D->getParent())
02301           << PadSize
02302           << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1) // plural or not
02303           << D->getIdentifier();
02304     else
02305       Diag(D->getLocation(), diag::warn_padded_struct_anon_field)
02306           << (D->getParent()->isStruct() ? 0 : 1) // struct|class
02307           << Context.getTypeDeclType(D->getParent())
02308           << PadSize
02309           << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1); // plural or not
02310   }
02311 
02312   // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
02313   // bother since there won't be alignment issues.
02314   if (isPacked && UnpackedAlign > CharBitNum && Offset == UnpackedOffset)
02315     Diag(D->getLocation(), diag::warn_unnecessary_packed)
02316         << D->getIdentifier();
02317 }
02318 
02319 const CXXMethodDecl *
02320 RecordLayoutBuilder::ComputeKeyFunction(const CXXRecordDecl *RD) {
02321   // If a class isn't polymorphic it doesn't have a key function.
02322   if (!RD->isPolymorphic())
02323     return 0;
02324 
02325   // A class that is not externally visible doesn't have a key function. (Or
02326   // at least, there's no point to assigning a key function to such a class;
02327   // this doesn't affect the ABI.)
02328   if (RD->getLinkage() != ExternalLinkage)
02329     return 0;
02330 
02331   // Template instantiations don't have key functions,see Itanium C++ ABI 5.2.6.
02332   // Same behavior as GCC.
02333   TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
02334   if (TSK == TSK_ImplicitInstantiation ||
02335       TSK == TSK_ExplicitInstantiationDefinition)
02336     return 0;
02337 
02338   for (CXXRecordDecl::method_iterator I = RD->method_begin(),
02339          E = RD->method_end(); I != E; ++I) {
02340     const CXXMethodDecl *MD = &*I;
02341 
02342     if (!MD->isVirtual())
02343       continue;
02344 
02345     if (MD->isPure())
02346       continue;
02347 
02348     // Ignore implicit member functions, they are always marked as inline, but
02349     // they don't have a body until they're defined.
02350     if (MD->isImplicit())
02351       continue;
02352 
02353     if (MD->isInlineSpecified())
02354       continue;
02355 
02356     if (MD->hasInlineBody())
02357       continue;
02358 
02359     // We found it.
02360     return MD;
02361   }
02362 
02363   return 0;
02364 }
02365 
02366 DiagnosticBuilder
02367 RecordLayoutBuilder::Diag(SourceLocation Loc, unsigned DiagID) {
02368   return Context.getDiagnostics().Report(Loc, DiagID);
02369 }
02370 
02371 /// getASTRecordLayout - Get or compute information about the layout of the
02372 /// specified record (struct/union/class), which indicates its size and field
02373 /// position information.
02374 const ASTRecordLayout &
02375 ASTContext::getASTRecordLayout(const RecordDecl *D) const {
02376   // These asserts test different things.  A record has a definition
02377   // as soon as we begin to parse the definition.  That definition is
02378   // not a complete definition (which is what isDefinition() tests)
02379   // until we *finish* parsing the definition.
02380 
02381   if (D->hasExternalLexicalStorage() && !D->getDefinition())
02382     getExternalSource()->CompleteType(const_cast<RecordDecl*>(D));
02383     
02384   D = D->getDefinition();
02385   assert(D && "Cannot get layout of forward declarations!");
02386   assert(D->isCompleteDefinition() && "Cannot layout type before complete!");
02387 
02388   // Look up this layout, if already laid out, return what we have.
02389   // Note that we can't save a reference to the entry because this function
02390   // is recursive.
02391   const ASTRecordLayout *Entry = ASTRecordLayouts[D];
02392   if (Entry) return *Entry;
02393 
02394   const ASTRecordLayout *NewEntry;
02395 
02396   if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
02397     EmptySubobjectMap EmptySubobjects(*this, RD);
02398     RecordLayoutBuilder Builder(*this, &EmptySubobjects);
02399     Builder.Layout(RD);
02400 
02401     // MSVC gives the vb-table pointer an alignment equal to that of
02402     // the non-virtual part of the structure.  That's an inherently
02403     // multi-pass operation.  If our first pass doesn't give us
02404     // adequate alignment, try again with the specified minimum
02405     // alignment.  This is *much* more maintainable than computing the
02406     // alignment in advance in a separately-coded pass; it's also
02407     // significantly more efficient in the common case where the
02408     // vb-table doesn't need extra padding.
02409     if (Builder.VBPtrOffset != CharUnits::fromQuantity(-1) &&
02410         (Builder.VBPtrOffset % Builder.NonVirtualAlignment) != 0) {
02411       Builder.resetWithTargetAlignment(Builder.NonVirtualAlignment);
02412       Builder.Layout(RD);
02413     }
02414 
02415     // FIXME: This is not always correct. See the part about bitfields at
02416     // http://www.codesourcery.com/public/cxx-abi/abi.html#POD for more info.
02417     // FIXME: IsPODForThePurposeOfLayout should be stored in the record layout.
02418     // This does not affect the calculations of MSVC layouts
02419     bool IsPODForThePurposeOfLayout = 
02420       (!Builder.isMicrosoftCXXABI() && cast<CXXRecordDecl>(D)->isPOD());
02421 
02422     // FIXME: This should be done in FinalizeLayout.
02423     CharUnits DataSize =
02424       IsPODForThePurposeOfLayout ? Builder.getSize() : Builder.getDataSize();
02425     CharUnits NonVirtualSize = 
02426       IsPODForThePurposeOfLayout ? DataSize : Builder.NonVirtualSize;
02427 
02428     NewEntry =
02429       new (*this) ASTRecordLayout(*this, Builder.getSize(), 
02430                                   Builder.Alignment,
02431                                   Builder.HasOwnVFPtr,
02432                                   Builder.VBPtrOffset,
02433                                   DataSize, 
02434                                   Builder.FieldOffsets.data(),
02435                                   Builder.FieldOffsets.size(),
02436                                   NonVirtualSize,
02437                                   Builder.NonVirtualAlignment,
02438                                   EmptySubobjects.SizeOfLargestEmptySubobject,
02439                                   Builder.PrimaryBase,
02440                                   Builder.PrimaryBaseIsVirtual,
02441                                   Builder.Bases, Builder.VBases);
02442   } else {
02443     RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/0);
02444     Builder.Layout(D);
02445 
02446     NewEntry =
02447       new (*this) ASTRecordLayout(*this, Builder.getSize(), 
02448                                   Builder.Alignment,
02449                                   Builder.getSize(),
02450                                   Builder.FieldOffsets.data(),
02451                                   Builder.FieldOffsets.size());
02452   }
02453 
02454   ASTRecordLayouts[D] = NewEntry;
02455 
02456   if (getLangOpts().DumpRecordLayouts) {
02457     llvm::errs() << "\n*** Dumping AST Record Layout\n";
02458     DumpRecordLayout(D, llvm::errs(), getLangOpts().DumpRecordLayoutsSimple);
02459   }
02460 
02461   return *NewEntry;
02462 }
02463 
02464 const CXXMethodDecl *ASTContext::getKeyFunction(const CXXRecordDecl *RD) {
02465   RD = cast<CXXRecordDecl>(RD->getDefinition());
02466   assert(RD && "Cannot get key function for forward declarations!");
02467 
02468   const CXXMethodDecl *&Entry = KeyFunctions[RD];
02469   if (!Entry)
02470     Entry = RecordLayoutBuilder::ComputeKeyFunction(RD);
02471 
02472   return Entry;
02473 }
02474 
02475 static uint64_t getFieldOffset(const ASTContext &C, const FieldDecl *FD) {
02476   const ASTRecordLayout &Layout = C.getASTRecordLayout(FD->getParent());
02477   return Layout.getFieldOffset(FD->getFieldIndex());
02478 }
02479 
02480 uint64_t ASTContext::getFieldOffset(const ValueDecl *VD) const {
02481   uint64_t OffsetInBits;
02482   if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
02483     OffsetInBits = ::getFieldOffset(*this, FD);
02484   } else {
02485     const IndirectFieldDecl *IFD = cast<IndirectFieldDecl>(VD);
02486 
02487     OffsetInBits = 0;
02488     for (IndirectFieldDecl::chain_iterator CI = IFD->chain_begin(),
02489                                            CE = IFD->chain_end();
02490          CI != CE; ++CI)
02491       OffsetInBits += ::getFieldOffset(*this, cast<FieldDecl>(*CI));
02492   }
02493 
02494   return OffsetInBits;
02495 }
02496 
02497 /// getObjCLayout - Get or compute information about the layout of the
02498 /// given interface.
02499 ///
02500 /// \param Impl - If given, also include the layout of the interface's
02501 /// implementation. This may differ by including synthesized ivars.
02502 const ASTRecordLayout &
02503 ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
02504                           const ObjCImplementationDecl *Impl) const {
02505   // Retrieve the definition
02506   if (D->hasExternalLexicalStorage() && !D->getDefinition())
02507     getExternalSource()->CompleteType(const_cast<ObjCInterfaceDecl*>(D));
02508   D = D->getDefinition();
02509   assert(D && D->isThisDeclarationADefinition() && "Invalid interface decl!");
02510 
02511   // Look up this layout, if already laid out, return what we have.
02512   ObjCContainerDecl *Key =
02513     Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
02514   if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
02515     return *Entry;
02516 
02517   // Add in synthesized ivar count if laying out an implementation.
02518   if (Impl) {
02519     unsigned SynthCount = CountNonClassIvars(D);
02520     // If there aren't any sythesized ivars then reuse the interface
02521     // entry. Note we can't cache this because we simply free all
02522     // entries later; however we shouldn't look up implementations
02523     // frequently.
02524     if (SynthCount == 0)
02525       return getObjCLayout(D, 0);
02526   }
02527 
02528   RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/0);
02529   Builder.Layout(D);
02530 
02531   const ASTRecordLayout *NewEntry =
02532     new (*this) ASTRecordLayout(*this, Builder.getSize(), 
02533                                 Builder.Alignment,
02534                                 Builder.getDataSize(),
02535                                 Builder.FieldOffsets.data(),
02536                                 Builder.FieldOffsets.size());
02537 
02538   ObjCLayouts[Key] = NewEntry;
02539 
02540   return *NewEntry;
02541 }
02542 
02543 static void PrintOffset(raw_ostream &OS,
02544                         CharUnits Offset, unsigned IndentLevel) {
02545   OS << llvm::format("%4" PRId64 " | ", (int64_t)Offset.getQuantity());
02546   OS.indent(IndentLevel * 2);
02547 }
02548 
02549 static void DumpCXXRecordLayout(raw_ostream &OS,
02550                                 const CXXRecordDecl *RD, const ASTContext &C,
02551                                 CharUnits Offset,
02552                                 unsigned IndentLevel,
02553                                 const char* Description,
02554                                 bool IncludeVirtualBases) {
02555   const ASTRecordLayout &Layout = C.getASTRecordLayout(RD);
02556 
02557   PrintOffset(OS, Offset, IndentLevel);
02558   OS << C.getTypeDeclType(const_cast<CXXRecordDecl *>(RD)).getAsString();
02559   if (Description)
02560     OS << ' ' << Description;
02561   if (RD->isEmpty())
02562     OS << " (empty)";
02563   OS << '\n';
02564 
02565   IndentLevel++;
02566 
02567   const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
02568   bool HasVfptr = Layout.hasOwnVFPtr();
02569   bool HasVbptr = Layout.getVBPtrOffset() != CharUnits::fromQuantity(-1);
02570 
02571   // Vtable pointer.
02572   if (RD->isDynamicClass() && !PrimaryBase &&
02573       C.getTargetInfo().getCXXABI() != CXXABI_Microsoft) {
02574     PrintOffset(OS, Offset, IndentLevel);
02575     OS << '(' << *RD << " vtable pointer)\n";
02576   }
02577   
02578   // Dump (non-virtual) bases
02579   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
02580          E = RD->bases_end(); I != E; ++I) {
02581     assert(!I->getType()->isDependentType() &&
02582            "Cannot layout class with dependent bases.");
02583     if (I->isVirtual())
02584       continue;
02585 
02586     const CXXRecordDecl *Base =
02587       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
02588 
02589     CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base);
02590 
02591     DumpCXXRecordLayout(OS, Base, C, BaseOffset, IndentLevel,
02592                         Base == PrimaryBase ? "(primary base)" : "(base)",
02593                         /*IncludeVirtualBases=*/false);
02594   }
02595 
02596   // vfptr and vbptr (for Microsoft C++ ABI)
02597   if (HasVfptr) {
02598     PrintOffset(OS, Offset, IndentLevel);
02599     OS << '(' << *RD << " vftable pointer)\n";
02600   }
02601   if (HasVbptr) {
02602     PrintOffset(OS, Offset + Layout.getVBPtrOffset(), IndentLevel);
02603     OS << '(' << *RD << " vbtable pointer)\n";
02604   }
02605 
02606   // Dump fields.
02607   uint64_t FieldNo = 0;
02608   for (CXXRecordDecl::field_iterator I = RD->field_begin(),
02609          E = RD->field_end(); I != E; ++I, ++FieldNo) {
02610     const FieldDecl &Field = *I;
02611     CharUnits FieldOffset = Offset + 
02612       C.toCharUnitsFromBits(Layout.getFieldOffset(FieldNo));
02613 
02614     if (const RecordType *RT = Field.getType()->getAs<RecordType>()) {
02615       if (const CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
02616         DumpCXXRecordLayout(OS, D, C, FieldOffset, IndentLevel,
02617                             Field.getName().data(),
02618                             /*IncludeVirtualBases=*/true);
02619         continue;
02620       }
02621     }
02622 
02623     PrintOffset(OS, FieldOffset, IndentLevel);
02624     OS << Field.getType().getAsString() << ' ' << Field << '\n';
02625   }
02626 
02627   if (!IncludeVirtualBases)
02628     return;
02629 
02630   // Dump virtual bases.
02631   const ASTRecordLayout::VBaseOffsetsMapTy &vtordisps = 
02632     Layout.getVBaseOffsetsMap();
02633   for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
02634          E = RD->vbases_end(); I != E; ++I) {
02635     assert(I->isVirtual() && "Found non-virtual class!");
02636     const CXXRecordDecl *VBase =
02637       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
02638 
02639     CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBase);
02640 
02641     if (vtordisps.find(VBase)->second.hasVtorDisp()) {
02642       PrintOffset(OS, VBaseOffset - CharUnits::fromQuantity(4), IndentLevel);
02643       OS << "(vtordisp for vbase " << *VBase << ")\n";
02644     }
02645 
02646     DumpCXXRecordLayout(OS, VBase, C, VBaseOffset, IndentLevel,
02647                         VBase == PrimaryBase ?
02648                         "(primary virtual base)" : "(virtual base)",
02649                         /*IncludeVirtualBases=*/false);
02650   }
02651 
02652   OS << "  sizeof=" << Layout.getSize().getQuantity();
02653   OS << ", dsize=" << Layout.getDataSize().getQuantity();
02654   OS << ", align=" << Layout.getAlignment().getQuantity() << '\n';
02655   OS << "  nvsize=" << Layout.getNonVirtualSize().getQuantity();
02656   OS << ", nvalign=" << Layout.getNonVirtualAlign().getQuantity() << '\n';
02657   OS << '\n';
02658 }
02659 
02660 void ASTContext::DumpRecordLayout(const RecordDecl *RD,
02661                                   raw_ostream &OS,
02662                                   bool Simple) const {
02663   const ASTRecordLayout &Info = getASTRecordLayout(RD);
02664 
02665   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
02666     if (!Simple)
02667       return DumpCXXRecordLayout(OS, CXXRD, *this, CharUnits(), 0, 0,
02668                                  /*IncludeVirtualBases=*/true);
02669 
02670   OS << "Type: " << getTypeDeclType(RD).getAsString() << "\n";
02671   if (!Simple) {
02672     OS << "Record: ";
02673     RD->dump();
02674   }
02675   OS << "\nLayout: ";
02676   OS << "<ASTRecordLayout\n";
02677   OS << "  Size:" << toBits(Info.getSize()) << "\n";
02678   OS << "  DataSize:" << toBits(Info.getDataSize()) << "\n";
02679   OS << "  Alignment:" << toBits(Info.getAlignment()) << "\n";
02680   OS << "  FieldOffsets: [";
02681   for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i) {
02682     if (i) OS << ", ";
02683     OS << Info.getFieldOffset(i);
02684   }
02685   OS << "]>\n";
02686 }