1 //===--- CGRecordLayoutBuilder.cpp - CGRecordLayout builder  ----*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Builder implementation for CGRecordLayout objects.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CGRecordLayout.h"
15 #include "CGCXXABI.h"
16 #include "CodeGenTypes.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/Attr.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/RecordLayout.h"
23 #include "clang/Frontend/CodeGenOptions.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/Type.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/MathExtras.h"
29 #include "llvm/Support/raw_ostream.h"
30 using namespace clang;
31 using namespace CodeGen;
32 
33 namespace {
34 /// The CGRecordLowering is responsible for lowering an ASTRecordLayout to an
35 /// llvm::Type.  Some of the lowering is straightforward, some is not.  Here we
36 /// detail some of the complexities and weirdnesses here.
37 /// * LLVM does not have unions - Unions can, in theory be represented by any
38 ///   llvm::Type with correct size.  We choose a field via a specific heuristic
39 ///   and add padding if necessary.
40 /// * LLVM does not have bitfields - Bitfields are collected into contiguous
41 ///   runs and allocated as a single storage type for the run.  ASTRecordLayout
42 ///   contains enough information to determine where the runs break.  Microsoft
43 ///   and Itanium follow different rules and use different codepaths.
44 /// * It is desired that, when possible, bitfields use the appropriate iN type
45 ///   when lowered to llvm types.  For example unsigned x : 24 gets lowered to
46 ///   i24.  This isn't always possible because i24 has storage size of 32 bit
47 ///   and if it is possible to use that extra byte of padding we must use
48 ///   [i8 x 3] instead of i24.  The function clipTailPadding does this.
49 ///   C++ examples that require clipping:
50 ///   struct { int a : 24; char b; }; // a must be clipped, b goes at offset 3
51 ///   struct A { int a : 24; }; // a must be clipped because a struct like B
52 //    could exist: struct B : A { char b; }; // b goes at offset 3
53 /// * Clang ignores 0 sized bitfields and 0 sized bases but *not* zero sized
54 ///   fields.  The existing asserts suggest that LLVM assumes that *every* field
55 ///   has an underlying storage type.  Therefore empty structures containing
56 ///   zero sized subobjects such as empty records or zero sized arrays still get
57 ///   a zero sized (empty struct) storage type.
58 /// * Clang reads the complete type rather than the base type when generating
59 ///   code to access fields.  Bitfields in tail position with tail padding may
60 ///   be clipped in the base class but not the complete class (we may discover
61 ///   that the tail padding is not used in the complete class.) However,
62 ///   because LLVM reads from the complete type it can generate incorrect code
63 ///   if we do not clip the tail padding off of the bitfield in the complete
64 ///   layout.  This introduces a somewhat awkward extra unnecessary clip stage.
65 ///   The location of the clip is stored internally as a sentinal of type
66 ///   SCISSOR.  If LLVM were updated to read base types (which it probably
67 ///   should because locations of things such as VBases are bogus in the llvm
68 ///   type anyway) then we could eliminate the SCISSOR.
69 /// * Itanium allows nearly empty primary virtual bases.  These bases don't get
70 ///   get their own storage because they're laid out as part of another base
71 ///   or at the beginning of the structure.  Determining if a VBase actually
72 ///   gets storage awkwardly involves a walk of all bases.
73 /// * VFPtrs and VBPtrs do *not* make a record NotZeroInitializable.
74 struct CGRecordLowering {
75   // MemberInfo is a helper structure that contains information about a record
76   // member.  In additional to the standard member types, there exists a
77   // sentinal member type that ensures correct rounding.
78   struct MemberInfo {
79     CharUnits Offset;
80     enum InfoKind { VFPtr, VBPtr, Field, Base, VBase, Scissor } Kind;
81     llvm::Type *Data;
82     union {
83       const FieldDecl *FD;
84       const CXXRecordDecl *RD;
85     };
86     MemberInfo(CharUnits Offset, InfoKind Kind, llvm::Type *Data,
87                const FieldDecl *FD = nullptr)
88       : Offset(Offset), Kind(Kind), Data(Data), FD(FD) {}
89     MemberInfo(CharUnits Offset, InfoKind Kind, llvm::Type *Data,
90                const CXXRecordDecl *RD)
91       : Offset(Offset), Kind(Kind), Data(Data), RD(RD) {}
92     // MemberInfos are sorted so we define a < operator.
93     bool operator <(const MemberInfo& a) const { return Offset < a.Offset; }
94   };
95   // The constructor.
96   CGRecordLowering(CodeGenTypes &Types, const RecordDecl *D, bool Packed);
97   // Short helper routines.
98   /// \brief Constructs a MemberInfo instance from an offset and llvm::Type *.
99   MemberInfo StorageInfo(CharUnits Offset, llvm::Type *Data) {
100     return MemberInfo(Offset, MemberInfo::Field, Data);
101   }
102 
103   /// The Microsoft bitfield layout rule allocates discrete storage
104   /// units of the field's formal type and only combines adjacent
105   /// fields of the same formal type.  We want to emit a layout with
106   /// these discrete storage units instead of combining them into a
107   /// continuous run.
108   bool isDiscreteBitFieldABI() {
109     return Context.getTargetInfo().getCXXABI().isMicrosoft() ||
110            D->isMsStruct(Context);
111   }
112 
113   /// The Itanium base layout rule allows virtual bases to overlap
114   /// other bases, which complicates layout in specific ways.
115   ///
116   /// Note specifically that the ms_struct attribute doesn't change this.
117   bool isOverlappingVBaseABI() {
118     return !Context.getTargetInfo().getCXXABI().isMicrosoft();
119   }
120 
121   /// \brief Wraps llvm::Type::getIntNTy with some implicit arguments.
122   llvm::Type *getIntNType(uint64_t NumBits) {
123     return llvm::Type::getIntNTy(Types.getLLVMContext(),
124         (unsigned)llvm::RoundUpToAlignment(NumBits, 8));
125   }
126   /// \brief Gets an llvm type of size NumBytes and alignment 1.
127   llvm::Type *getByteArrayType(CharUnits NumBytes) {
128     assert(!NumBytes.isZero() && "Empty byte arrays aren't allowed.");
129     llvm::Type *Type = llvm::Type::getInt8Ty(Types.getLLVMContext());
130     return NumBytes == CharUnits::One() ? Type :
131         (llvm::Type *)llvm::ArrayType::get(Type, NumBytes.getQuantity());
132   }
133   /// \brief Gets the storage type for a field decl and handles storage
134   /// for itanium bitfields that are smaller than their declared type.
135   llvm::Type *getStorageType(const FieldDecl *FD) {
136     llvm::Type *Type = Types.ConvertTypeForMem(FD->getType());
137     if (!FD->isBitField()) return Type;
138     if (isDiscreteBitFieldABI()) return Type;
139     return getIntNType(std::min(FD->getBitWidthValue(Context),
140                              (unsigned)Context.toBits(getSize(Type))));
141   }
142   /// \brief Gets the llvm Basesubobject type from a CXXRecordDecl.
143   llvm::Type *getStorageType(const CXXRecordDecl *RD) {
144     return Types.getCGRecordLayout(RD).getBaseSubobjectLLVMType();
145   }
146   CharUnits bitsToCharUnits(uint64_t BitOffset) {
147     return Context.toCharUnitsFromBits(BitOffset);
148   }
149   CharUnits getSize(llvm::Type *Type) {
150     return CharUnits::fromQuantity(DataLayout.getTypeAllocSize(Type));
151   }
152   CharUnits getAlignment(llvm::Type *Type) {
153     return CharUnits::fromQuantity(DataLayout.getABITypeAlignment(Type));
154   }
155   bool isZeroInitializable(const FieldDecl *FD) {
156     const Type *Type = FD->getType()->getBaseElementTypeUnsafe();
157     if (const MemberPointerType *MPT = Type->getAs<MemberPointerType>())
158       return Types.getCXXABI().isZeroInitializable(MPT);
159     if (const RecordType *RT = Type->getAs<RecordType>())
160       return isZeroInitializable(RT->getDecl());
161     return true;
162   }
163   bool isZeroInitializable(const RecordDecl *RD) {
164     return Types.getCGRecordLayout(RD).isZeroInitializable();
165   }
166   void appendPaddingBytes(CharUnits Size) {
167     if (!Size.isZero())
168       FieldTypes.push_back(getByteArrayType(Size));
169   }
170   uint64_t getFieldBitOffset(const FieldDecl *FD) {
171     return Layout.getFieldOffset(FD->getFieldIndex());
172   }
173   // Layout routines.
174   void setBitFieldInfo(const FieldDecl *FD, CharUnits StartOffset,
175                        llvm::Type *StorageType);
176   /// \brief Lowers an ASTRecordLayout to a llvm type.
177   void lower(bool NonVirtualBaseType);
178   void lowerUnion();
179   void accumulateFields();
180   void accumulateBitFields(RecordDecl::field_iterator Field,
181                         RecordDecl::field_iterator FieldEnd);
182   void accumulateBases();
183   void accumulateVPtrs();
184   void accumulateVBases();
185   /// \brief Recursively searches all of the bases to find out if a vbase is
186   /// not the primary vbase of some base class.
187   bool hasOwnStorage(const CXXRecordDecl *Decl, const CXXRecordDecl *Query);
188   void calculateZeroInit();
189   /// \brief Lowers bitfield storage types to I8 arrays for bitfields with tail
190   /// padding that is or can potentially be used.
191   void clipTailPadding();
192   /// \brief Determines if we need a packed llvm struct.
193   void determinePacked(bool NVBaseType);
194   /// \brief Inserts padding everwhere it's needed.
195   void insertPadding();
196   /// \brief Fills out the structures that are ultimately consumed.
197   void fillOutputFields();
198   // Input memoization fields.
199   CodeGenTypes &Types;
200   const ASTContext &Context;
201   const RecordDecl *D;
202   const CXXRecordDecl *RD;
203   const ASTRecordLayout &Layout;
204   const llvm::DataLayout &DataLayout;
205   // Helpful intermediate data-structures.
206   std::vector<MemberInfo> Members;
207   // Output fields, consumed by CodeGenTypes::ComputeRecordLayout.
208   SmallVector<llvm::Type *, 16> FieldTypes;
209   llvm::DenseMap<const FieldDecl *, unsigned> Fields;
210   llvm::DenseMap<const FieldDecl *, CGBitFieldInfo> BitFields;
211   llvm::DenseMap<const CXXRecordDecl *, unsigned> NonVirtualBases;
212   llvm::DenseMap<const CXXRecordDecl *, unsigned> VirtualBases;
213   bool IsZeroInitializable : 1;
214   bool IsZeroInitializableAsBase : 1;
215   bool Packed : 1;
216 private:
217   CGRecordLowering(const CGRecordLowering &) = delete;
218   void operator =(const CGRecordLowering &) = delete;
219 };
220 } // namespace {
221 
222 CGRecordLowering::CGRecordLowering(CodeGenTypes &Types, const RecordDecl *D,                                 bool Packed)
223   : Types(Types), Context(Types.getContext()), D(D),
224     RD(dyn_cast<CXXRecordDecl>(D)),
225     Layout(Types.getContext().getASTRecordLayout(D)),
226     DataLayout(Types.getDataLayout()), IsZeroInitializable(true),
227     IsZeroInitializableAsBase(true), Packed(Packed) {}
228 
229 void CGRecordLowering::setBitFieldInfo(
230     const FieldDecl *FD, CharUnits StartOffset, llvm::Type *StorageType) {
231   CGBitFieldInfo &Info = BitFields[FD->getCanonicalDecl()];
232   Info.IsSigned = FD->getType()->isSignedIntegerOrEnumerationType();
233   Info.Offset = (unsigned)(getFieldBitOffset(FD) - Context.toBits(StartOffset));
234   Info.Size = FD->getBitWidthValue(Context);
235   Info.StorageSize = (unsigned)DataLayout.getTypeAllocSizeInBits(StorageType);
236   // Here we calculate the actual storage alignment of the bits.  E.g if we've
237   // got an alignment >= 2 and the bitfield starts at offset 6 we've got an
238   // alignment of 2.
239   Info.StorageAlignment =
240       Layout.getAlignment().alignmentAtOffset(StartOffset).getQuantity();
241   if (Info.Size > Info.StorageSize)
242     Info.Size = Info.StorageSize;
243   // Reverse the bit offsets for big endian machines. Because we represent
244   // a bitfield as a single large integer load, we can imagine the bits
245   // counting from the most-significant-bit instead of the
246   // least-significant-bit.
247   if (DataLayout.isBigEndian())
248     Info.Offset = Info.StorageSize - (Info.Offset + Info.Size);
249 }
250 
251 void CGRecordLowering::lower(bool NVBaseType) {
252   // The lowering process implemented in this function takes a variety of
253   // carefully ordered phases.
254   // 1) Store all members (fields and bases) in a list and sort them by offset.
255   // 2) Add a 1-byte capstone member at the Size of the structure.
256   // 3) Clip bitfield storages members if their tail padding is or might be
257   //    used by another field or base.  The clipping process uses the capstone
258   //    by treating it as another object that occurs after the record.
259   // 4) Determine if the llvm-struct requires packing.  It's important that this
260   //    phase occur after clipping, because clipping changes the llvm type.
261   //    This phase reads the offset of the capstone when determining packedness
262   //    and updates the alignment of the capstone to be equal of the alignment
263   //    of the record after doing so.
264   // 5) Insert padding everywhere it is needed.  This phase requires 'Packed' to
265   //    have been computed and needs to know the alignment of the record in
266   //    order to understand if explicit tail padding is needed.
267   // 6) Remove the capstone, we don't need it anymore.
268   // 7) Determine if this record can be zero-initialized.  This phase could have
269   //    been placed anywhere after phase 1.
270   // 8) Format the complete list of members in a way that can be consumed by
271   //    CodeGenTypes::ComputeRecordLayout.
272   CharUnits Size = NVBaseType ? Layout.getNonVirtualSize() : Layout.getSize();
273   if (D->isUnion())
274     return lowerUnion();
275   accumulateFields();
276   // RD implies C++.
277   if (RD) {
278     accumulateVPtrs();
279     accumulateBases();
280     if (Members.empty())
281       return appendPaddingBytes(Size);
282     if (!NVBaseType)
283       accumulateVBases();
284   }
285   std::stable_sort(Members.begin(), Members.end());
286   Members.push_back(StorageInfo(Size, getIntNType(8)));
287   clipTailPadding();
288   determinePacked(NVBaseType);
289   insertPadding();
290   Members.pop_back();
291   calculateZeroInit();
292   fillOutputFields();
293 }
294 
295 void CGRecordLowering::lowerUnion() {
296   CharUnits LayoutSize = Layout.getSize();
297   llvm::Type *StorageType = nullptr;
298   bool SeenNamedMember = false;
299   // Iterate through the fields setting bitFieldInfo and the Fields array. Also
300   // locate the "most appropriate" storage type.  The heuristic for finding the
301   // storage type isn't necessary, the first (non-0-length-bitfield) field's
302   // type would work fine and be simpler but would be different than what we've
303   // been doing and cause lit tests to change.
304   for (const auto *Field : D->fields()) {
305     if (Field->isBitField()) {
306       // Skip 0 sized bitfields.
307       if (Field->getBitWidthValue(Context) == 0)
308         continue;
309       llvm::Type *FieldType = getStorageType(Field);
310       if (LayoutSize < getSize(FieldType))
311         FieldType = getByteArrayType(LayoutSize);
312       setBitFieldInfo(Field, CharUnits::Zero(), FieldType);
313     }
314     Fields[Field->getCanonicalDecl()] = 0;
315     llvm::Type *FieldType = getStorageType(Field);
316     // Compute zero-initializable status.
317     // This union might not be zero initialized: it may contain a pointer to
318     // data member which might have some exotic initialization sequence.
319     // If this is the case, then we aught not to try and come up with a "better"
320     // type, it might not be very easy to come up with a Constant which
321     // correctly initializes it.
322     if (!SeenNamedMember && Field->getDeclName()) {
323       SeenNamedMember = true;
324       if (!isZeroInitializable(Field)) {
325         IsZeroInitializable = IsZeroInitializableAsBase = false;
326         StorageType = FieldType;
327       }
328     }
329     // Because our union isn't zero initializable, we won't be getting a better
330     // storage type.
331     if (!IsZeroInitializable)
332       continue;
333     // Conditionally update our storage type if we've got a new "better" one.
334     if (!StorageType ||
335         getAlignment(FieldType) >  getAlignment(StorageType) ||
336         (getAlignment(FieldType) == getAlignment(StorageType) &&
337         getSize(FieldType) > getSize(StorageType)))
338       StorageType = FieldType;
339   }
340   // If we have no storage type just pad to the appropriate size and return.
341   if (!StorageType)
342     return appendPaddingBytes(LayoutSize);
343   // If our storage size was bigger than our required size (can happen in the
344   // case of packed bitfields on Itanium) then just use an I8 array.
345   if (LayoutSize < getSize(StorageType))
346     StorageType = getByteArrayType(LayoutSize);
347   FieldTypes.push_back(StorageType);
348   appendPaddingBytes(LayoutSize - getSize(StorageType));
349   // Set packed if we need it.
350   if (LayoutSize % getAlignment(StorageType))
351     Packed = true;
352 }
353 
354 void CGRecordLowering::accumulateFields() {
355   for (RecordDecl::field_iterator Field = D->field_begin(),
356                                   FieldEnd = D->field_end();
357     Field != FieldEnd;)
358     if (Field->isBitField()) {
359       RecordDecl::field_iterator Start = Field;
360       // Iterate to gather the list of bitfields.
361       for (++Field; Field != FieldEnd && Field->isBitField(); ++Field);
362       accumulateBitFields(Start, Field);
363     } else {
364       Members.push_back(MemberInfo(
365           bitsToCharUnits(getFieldBitOffset(*Field)), MemberInfo::Field,
366           getStorageType(*Field), *Field));
367       ++Field;
368     }
369 }
370 
371 void
372 CGRecordLowering::accumulateBitFields(RecordDecl::field_iterator Field,
373                                       RecordDecl::field_iterator FieldEnd) {
374   // Run stores the first element of the current run of bitfields.  FieldEnd is
375   // used as a special value to note that we don't have a current run.  A
376   // bitfield run is a contiguous collection of bitfields that can be stored in
377   // the same storage block.  Zero-sized bitfields and bitfields that would
378   // cross an alignment boundary break a run and start a new one.
379   RecordDecl::field_iterator Run = FieldEnd;
380   // Tail is the offset of the first bit off the end of the current run.  It's
381   // used to determine if the ASTRecordLayout is treating these two bitfields as
382   // contiguous.  StartBitOffset is offset of the beginning of the Run.
383   uint64_t StartBitOffset, Tail = 0;
384   if (isDiscreteBitFieldABI()) {
385     for (; Field != FieldEnd; ++Field) {
386       uint64_t BitOffset = getFieldBitOffset(*Field);
387       // Zero-width bitfields end runs.
388       if (Field->getBitWidthValue(Context) == 0) {
389         Run = FieldEnd;
390         continue;
391       }
392       llvm::Type *Type = Types.ConvertTypeForMem(Field->getType());
393       // If we don't have a run yet, or don't live within the previous run's
394       // allocated storage then we allocate some storage and start a new run.
395       if (Run == FieldEnd || BitOffset >= Tail) {
396         Run = Field;
397         StartBitOffset = BitOffset;
398         Tail = StartBitOffset + DataLayout.getTypeAllocSizeInBits(Type);
399         // Add the storage member to the record.  This must be added to the
400         // record before the bitfield members so that it gets laid out before
401         // the bitfields it contains get laid out.
402         Members.push_back(StorageInfo(bitsToCharUnits(StartBitOffset), Type));
403       }
404       // Bitfields get the offset of their storage but come afterward and remain
405       // there after a stable sort.
406       Members.push_back(MemberInfo(bitsToCharUnits(StartBitOffset),
407                                    MemberInfo::Field, nullptr, *Field));
408     }
409     return;
410   }
411   for (;;) {
412     // Check to see if we need to start a new run.
413     if (Run == FieldEnd) {
414       // If we're out of fields, return.
415       if (Field == FieldEnd)
416         break;
417       // Any non-zero-length bitfield can start a new run.
418       if (Field->getBitWidthValue(Context) != 0) {
419         Run = Field;
420         StartBitOffset = getFieldBitOffset(*Field);
421         Tail = StartBitOffset + Field->getBitWidthValue(Context);
422       }
423       ++Field;
424       continue;
425     }
426     // Add bitfields to the run as long as they qualify.
427     if (Field != FieldEnd && Field->getBitWidthValue(Context) != 0 &&
428         Tail == getFieldBitOffset(*Field)) {
429       Tail += Field->getBitWidthValue(Context);
430       ++Field;
431       continue;
432     }
433     // We've hit a break-point in the run and need to emit a storage field.
434     llvm::Type *Type = getIntNType(Tail - StartBitOffset);
435     // Add the storage member to the record and set the bitfield info for all of
436     // the bitfields in the run.  Bitfields get the offset of their storage but
437     // come afterward and remain there after a stable sort.
438     Members.push_back(StorageInfo(bitsToCharUnits(StartBitOffset), Type));
439     for (; Run != Field; ++Run)
440       Members.push_back(MemberInfo(bitsToCharUnits(StartBitOffset),
441                                    MemberInfo::Field, nullptr, *Run));
442     Run = FieldEnd;
443   }
444 }
445 
446 void CGRecordLowering::accumulateBases() {
447   // If we've got a primary virtual base, we need to add it with the bases.
448   if (Layout.isPrimaryBaseVirtual()) {
449     const CXXRecordDecl *BaseDecl = Layout.getPrimaryBase();
450     Members.push_back(MemberInfo(CharUnits::Zero(), MemberInfo::Base,
451                                  getStorageType(BaseDecl), BaseDecl));
452   }
453   // Accumulate the non-virtual bases.
454   for (const auto &Base : RD->bases()) {
455     if (Base.isVirtual())
456       continue;
457 
458     // Bases can be zero-sized even if not technically empty if they
459     // contain only a trailing array member.
460     const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
461     if (!BaseDecl->isEmpty() &&
462         !Context.getASTRecordLayout(BaseDecl).getSize().isZero())
463       Members.push_back(MemberInfo(Layout.getBaseClassOffset(BaseDecl),
464           MemberInfo::Base, getStorageType(BaseDecl), BaseDecl));
465   }
466 }
467 
468 void CGRecordLowering::accumulateVPtrs() {
469   if (Layout.hasOwnVFPtr())
470     Members.push_back(MemberInfo(CharUnits::Zero(), MemberInfo::VFPtr,
471         llvm::FunctionType::get(getIntNType(32), /*isVarArg=*/true)->
472             getPointerTo()->getPointerTo()));
473   if (Layout.hasOwnVBPtr())
474     Members.push_back(MemberInfo(Layout.getVBPtrOffset(), MemberInfo::VBPtr,
475         llvm::Type::getInt32PtrTy(Types.getLLVMContext())));
476 }
477 
478 void CGRecordLowering::accumulateVBases() {
479   CharUnits ScissorOffset = Layout.getNonVirtualSize();
480   // In the itanium ABI, it's possible to place a vbase at a dsize that is
481   // smaller than the nvsize.  Here we check to see if such a base is placed
482   // before the nvsize and set the scissor offset to that, instead of the
483   // nvsize.
484   if (isOverlappingVBaseABI())
485     for (const auto &Base : RD->vbases()) {
486       const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
487       if (BaseDecl->isEmpty())
488         continue;
489       // If the vbase is a primary virtual base of some base, then it doesn't
490       // get its own storage location but instead lives inside of that base.
491       if (Context.isNearlyEmpty(BaseDecl) && !hasOwnStorage(RD, BaseDecl))
492         continue;
493       ScissorOffset = std::min(ScissorOffset,
494                                Layout.getVBaseClassOffset(BaseDecl));
495     }
496   Members.push_back(MemberInfo(ScissorOffset, MemberInfo::Scissor, nullptr,
497                                RD));
498   for (const auto &Base : RD->vbases()) {
499     const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
500     if (BaseDecl->isEmpty())
501       continue;
502     CharUnits Offset = Layout.getVBaseClassOffset(BaseDecl);
503     // If the vbase is a primary virtual base of some base, then it doesn't
504     // get its own storage location but instead lives inside of that base.
505     if (isOverlappingVBaseABI() &&
506         Context.isNearlyEmpty(BaseDecl) &&
507         !hasOwnStorage(RD, BaseDecl)) {
508       Members.push_back(MemberInfo(Offset, MemberInfo::VBase, nullptr,
509                                    BaseDecl));
510       continue;
511     }
512     // If we've got a vtordisp, add it as a storage type.
513     if (Layout.getVBaseOffsetsMap().find(BaseDecl)->second.hasVtorDisp())
514       Members.push_back(StorageInfo(Offset - CharUnits::fromQuantity(4),
515                                     getIntNType(32)));
516     Members.push_back(MemberInfo(Offset, MemberInfo::VBase,
517                                  getStorageType(BaseDecl), BaseDecl));
518   }
519 }
520 
521 bool CGRecordLowering::hasOwnStorage(const CXXRecordDecl *Decl,
522                                      const CXXRecordDecl *Query) {
523   const ASTRecordLayout &DeclLayout = Context.getASTRecordLayout(Decl);
524   if (DeclLayout.isPrimaryBaseVirtual() && DeclLayout.getPrimaryBase() == Query)
525     return false;
526   for (const auto &Base : Decl->bases())
527     if (!hasOwnStorage(Base.getType()->getAsCXXRecordDecl(), Query))
528       return false;
529   return true;
530 }
531 
532 void CGRecordLowering::calculateZeroInit() {
533   for (std::vector<MemberInfo>::const_iterator Member = Members.begin(),
534                                                MemberEnd = Members.end();
535        IsZeroInitializableAsBase && Member != MemberEnd; ++Member) {
536     if (Member->Kind == MemberInfo::Field) {
537       if (!Member->FD || isZeroInitializable(Member->FD))
538         continue;
539       IsZeroInitializable = IsZeroInitializableAsBase = false;
540     } else if (Member->Kind == MemberInfo::Base ||
541                Member->Kind == MemberInfo::VBase) {
542       if (isZeroInitializable(Member->RD))
543         continue;
544       IsZeroInitializable = false;
545       if (Member->Kind == MemberInfo::Base)
546         IsZeroInitializableAsBase = false;
547     }
548   }
549 }
550 
551 void CGRecordLowering::clipTailPadding() {
552   std::vector<MemberInfo>::iterator Prior = Members.begin();
553   CharUnits Tail = getSize(Prior->Data);
554   for (std::vector<MemberInfo>::iterator Member = Prior + 1,
555                                          MemberEnd = Members.end();
556        Member != MemberEnd; ++Member) {
557     // Only members with data and the scissor can cut into tail padding.
558     if (!Member->Data && Member->Kind != MemberInfo::Scissor)
559       continue;
560     if (Member->Offset < Tail) {
561       assert(Prior->Kind == MemberInfo::Field && !Prior->FD &&
562              "Only storage fields have tail padding!");
563       Prior->Data = getByteArrayType(bitsToCharUnits(llvm::RoundUpToAlignment(
564           cast<llvm::IntegerType>(Prior->Data)->getIntegerBitWidth(), 8)));
565     }
566     if (Member->Data)
567       Prior = Member;
568     Tail = Prior->Offset + getSize(Prior->Data);
569   }
570 }
571 
572 void CGRecordLowering::determinePacked(bool NVBaseType) {
573   if (Packed)
574     return;
575   CharUnits Alignment = CharUnits::One();
576   CharUnits NVAlignment = CharUnits::One();
577   CharUnits NVSize =
578       !NVBaseType && RD ? Layout.getNonVirtualSize() : CharUnits::Zero();
579   for (std::vector<MemberInfo>::const_iterator Member = Members.begin(),
580                                                MemberEnd = Members.end();
581        Member != MemberEnd; ++Member) {
582     if (!Member->Data)
583       continue;
584     // If any member falls at an offset that it not a multiple of its alignment,
585     // then the entire record must be packed.
586     if (Member->Offset % getAlignment(Member->Data))
587       Packed = true;
588     if (Member->Offset < NVSize)
589       NVAlignment = std::max(NVAlignment, getAlignment(Member->Data));
590     Alignment = std::max(Alignment, getAlignment(Member->Data));
591   }
592   // If the size of the record (the capstone's offset) is not a multiple of the
593   // record's alignment, it must be packed.
594   if (Members.back().Offset % Alignment)
595     Packed = true;
596   // If the non-virtual sub-object is not a multiple of the non-virtual
597   // sub-object's alignment, it must be packed.  We cannot have a packed
598   // non-virtual sub-object and an unpacked complete object or vise versa.
599   if (NVSize % NVAlignment)
600     Packed = true;
601   // Update the alignment of the sentinal.
602   if (!Packed)
603     Members.back().Data = getIntNType(Context.toBits(Alignment));
604 }
605 
606 void CGRecordLowering::insertPadding() {
607   std::vector<std::pair<CharUnits, CharUnits> > Padding;
608   CharUnits Size = CharUnits::Zero();
609   for (std::vector<MemberInfo>::const_iterator Member = Members.begin(),
610                                                MemberEnd = Members.end();
611        Member != MemberEnd; ++Member) {
612     if (!Member->Data)
613       continue;
614     CharUnits Offset = Member->Offset;
615     assert(Offset >= Size);
616     // Insert padding if we need to.
617     if (Offset != Size.RoundUpToAlignment(Packed ? CharUnits::One() :
618                                           getAlignment(Member->Data)))
619       Padding.push_back(std::make_pair(Size, Offset - Size));
620     Size = Offset + getSize(Member->Data);
621   }
622   if (Padding.empty())
623     return;
624   // Add the padding to the Members list and sort it.
625   for (std::vector<std::pair<CharUnits, CharUnits> >::const_iterator
626         Pad = Padding.begin(), PadEnd = Padding.end();
627         Pad != PadEnd; ++Pad)
628     Members.push_back(StorageInfo(Pad->first, getByteArrayType(Pad->second)));
629   std::stable_sort(Members.begin(), Members.end());
630 }
631 
632 void CGRecordLowering::fillOutputFields() {
633   for (std::vector<MemberInfo>::const_iterator Member = Members.begin(),
634                                                MemberEnd = Members.end();
635        Member != MemberEnd; ++Member) {
636     if (Member->Data)
637       FieldTypes.push_back(Member->Data);
638     if (Member->Kind == MemberInfo::Field) {
639       if (Member->FD)
640         Fields[Member->FD->getCanonicalDecl()] = FieldTypes.size() - 1;
641       // A field without storage must be a bitfield.
642       if (!Member->Data)
643         setBitFieldInfo(Member->FD, Member->Offset, FieldTypes.back());
644     } else if (Member->Kind == MemberInfo::Base)
645       NonVirtualBases[Member->RD] = FieldTypes.size() - 1;
646     else if (Member->Kind == MemberInfo::VBase)
647       VirtualBases[Member->RD] = FieldTypes.size() - 1;
648   }
649 }
650 
651 CGBitFieldInfo CGBitFieldInfo::MakeInfo(CodeGenTypes &Types,
652                                         const FieldDecl *FD,
653                                         uint64_t Offset, uint64_t Size,
654                                         uint64_t StorageSize,
655                                         uint64_t StorageAlignment) {
656   // This function is vestigial from CGRecordLayoutBuilder days but is still
657   // used in GCObjCRuntime.cpp.  That usage has a "fixme" attached to it that
658   // when addressed will allow for the removal of this function.
659   llvm::Type *Ty = Types.ConvertTypeForMem(FD->getType());
660   CharUnits TypeSizeInBytes =
661     CharUnits::fromQuantity(Types.getDataLayout().getTypeAllocSize(Ty));
662   uint64_t TypeSizeInBits = Types.getContext().toBits(TypeSizeInBytes);
663 
664   bool IsSigned = FD->getType()->isSignedIntegerOrEnumerationType();
665 
666   if (Size > TypeSizeInBits) {
667     // We have a wide bit-field. The extra bits are only used for padding, so
668     // if we have a bitfield of type T, with size N:
669     //
670     // T t : N;
671     //
672     // We can just assume that it's:
673     //
674     // T t : sizeof(T);
675     //
676     Size = TypeSizeInBits;
677   }
678 
679   // Reverse the bit offsets for big endian machines. Because we represent
680   // a bitfield as a single large integer load, we can imagine the bits
681   // counting from the most-significant-bit instead of the
682   // least-significant-bit.
683   if (Types.getDataLayout().isBigEndian()) {
684     Offset = StorageSize - (Offset + Size);
685   }
686 
687   return CGBitFieldInfo(Offset, Size, IsSigned, StorageSize, StorageAlignment);
688 }
689 
690 CGRecordLayout *CodeGenTypes::ComputeRecordLayout(const RecordDecl *D,
691                                                   llvm::StructType *Ty) {
692   CGRecordLowering Builder(*this, D, /*Packed=*/false);
693 
694   Builder.lower(/*NonVirtualBaseType=*/false);
695 
696   // If we're in C++, compute the base subobject type.
697   llvm::StructType *BaseTy = nullptr;
698   if (isa<CXXRecordDecl>(D) && !D->isUnion() && !D->hasAttr<FinalAttr>()) {
699     BaseTy = Ty;
700     if (Builder.Layout.getNonVirtualSize() != Builder.Layout.getSize()) {
701       CGRecordLowering BaseBuilder(*this, D, /*Packed=*/Builder.Packed);
702       BaseBuilder.lower(/*NonVirtualBaseType=*/true);
703       BaseTy = llvm::StructType::create(
704           getLLVMContext(), BaseBuilder.FieldTypes, "", BaseBuilder.Packed);
705       addRecordTypeName(D, BaseTy, ".base");
706       // BaseTy and Ty must agree on their packedness for getLLVMFieldNo to work
707       // on both of them with the same index.
708       assert(Builder.Packed == BaseBuilder.Packed &&
709              "Non-virtual and complete types must agree on packedness");
710     }
711   }
712 
713   // Fill in the struct *after* computing the base type.  Filling in the body
714   // signifies that the type is no longer opaque and record layout is complete,
715   // but we may need to recursively layout D while laying D out as a base type.
716   Ty->setBody(Builder.FieldTypes, Builder.Packed);
717 
718   CGRecordLayout *RL =
719     new CGRecordLayout(Ty, BaseTy, Builder.IsZeroInitializable,
720                         Builder.IsZeroInitializableAsBase);
721 
722   RL->NonVirtualBases.swap(Builder.NonVirtualBases);
723   RL->CompleteObjectVirtualBases.swap(Builder.VirtualBases);
724 
725   // Add all the field numbers.
726   RL->FieldInfo.swap(Builder.Fields);
727 
728   // Add bitfield info.
729   RL->BitFields.swap(Builder.BitFields);
730 
731   // Dump the layout, if requested.
732   if (getContext().getLangOpts().DumpRecordLayouts) {
733     llvm::outs() << "\n*** Dumping IRgen Record Layout\n";
734     llvm::outs() << "Record: ";
735     D->dump(llvm::outs());
736     llvm::outs() << "\nLayout: ";
737     RL->print(llvm::outs());
738   }
739 
740 #ifndef NDEBUG
741   // Verify that the computed LLVM struct size matches the AST layout size.
742   const ASTRecordLayout &Layout = getContext().getASTRecordLayout(D);
743 
744   uint64_t TypeSizeInBits = getContext().toBits(Layout.getSize());
745   assert(TypeSizeInBits == getDataLayout().getTypeAllocSizeInBits(Ty) &&
746          "Type size mismatch!");
747 
748   if (BaseTy) {
749     CharUnits NonVirtualSize  = Layout.getNonVirtualSize();
750 
751     uint64_t AlignedNonVirtualTypeSizeInBits =
752       getContext().toBits(NonVirtualSize);
753 
754     assert(AlignedNonVirtualTypeSizeInBits ==
755            getDataLayout().getTypeAllocSizeInBits(BaseTy) &&
756            "Type size mismatch!");
757   }
758 
759   // Verify that the LLVM and AST field offsets agree.
760   llvm::StructType *ST =
761     dyn_cast<llvm::StructType>(RL->getLLVMType());
762   const llvm::StructLayout *SL = getDataLayout().getStructLayout(ST);
763 
764   const ASTRecordLayout &AST_RL = getContext().getASTRecordLayout(D);
765   RecordDecl::field_iterator it = D->field_begin();
766   for (unsigned i = 0, e = AST_RL.getFieldCount(); i != e; ++i, ++it) {
767     const FieldDecl *FD = *it;
768 
769     // For non-bit-fields, just check that the LLVM struct offset matches the
770     // AST offset.
771     if (!FD->isBitField()) {
772       unsigned FieldNo = RL->getLLVMFieldNo(FD);
773       assert(AST_RL.getFieldOffset(i) == SL->getElementOffsetInBits(FieldNo) &&
774              "Invalid field offset!");
775       continue;
776     }
777 
778     // Ignore unnamed bit-fields.
779     if (!FD->getDeclName())
780       continue;
781 
782     // Don't inspect zero-length bitfields.
783     if (FD->getBitWidthValue(getContext()) == 0)
784       continue;
785 
786     const CGBitFieldInfo &Info = RL->getBitFieldInfo(FD);
787     llvm::Type *ElementTy = ST->getTypeAtIndex(RL->getLLVMFieldNo(FD));
788 
789     // Unions have overlapping elements dictating their layout, but for
790     // non-unions we can verify that this section of the layout is the exact
791     // expected size.
792     if (D->isUnion()) {
793       // For unions we verify that the start is zero and the size
794       // is in-bounds. However, on BE systems, the offset may be non-zero, but
795       // the size + offset should match the storage size in that case as it
796       // "starts" at the back.
797       if (getDataLayout().isBigEndian())
798         assert(static_cast<unsigned>(Info.Offset + Info.Size) ==
799                Info.StorageSize &&
800                "Big endian union bitfield does not end at the back");
801       else
802         assert(Info.Offset == 0 &&
803                "Little endian union bitfield with a non-zero offset");
804       assert(Info.StorageSize <= SL->getSizeInBits() &&
805              "Union not large enough for bitfield storage");
806     } else {
807       assert(Info.StorageSize ==
808              getDataLayout().getTypeAllocSizeInBits(ElementTy) &&
809              "Storage size does not match the element type size");
810     }
811     assert(Info.Size > 0 && "Empty bitfield!");
812     assert(static_cast<unsigned>(Info.Offset) + Info.Size <= Info.StorageSize &&
813            "Bitfield outside of its allocated storage");
814   }
815 #endif
816 
817   return RL;
818 }
819 
820 void CGRecordLayout::print(raw_ostream &OS) const {
821   OS << "<CGRecordLayout\n";
822   OS << "  LLVMType:" << *CompleteObjectType << "\n";
823   if (BaseSubobjectType)
824     OS << "  NonVirtualBaseLLVMType:" << *BaseSubobjectType << "\n";
825   OS << "  IsZeroInitializable:" << IsZeroInitializable << "\n";
826   OS << "  BitFields:[\n";
827 
828   // Print bit-field infos in declaration order.
829   std::vector<std::pair<unsigned, const CGBitFieldInfo*> > BFIs;
830   for (llvm::DenseMap<const FieldDecl*, CGBitFieldInfo>::const_iterator
831          it = BitFields.begin(), ie = BitFields.end();
832        it != ie; ++it) {
833     const RecordDecl *RD = it->first->getParent();
834     unsigned Index = 0;
835     for (RecordDecl::field_iterator
836            it2 = RD->field_begin(); *it2 != it->first; ++it2)
837       ++Index;
838     BFIs.push_back(std::make_pair(Index, &it->second));
839   }
840   llvm::array_pod_sort(BFIs.begin(), BFIs.end());
841   for (unsigned i = 0, e = BFIs.size(); i != e; ++i) {
842     OS.indent(4);
843     BFIs[i].second->print(OS);
844     OS << "\n";
845   }
846 
847   OS << "]>\n";
848 }
849 
850 void CGRecordLayout::dump() const {
851   print(llvm::errs());
852 }
853 
854 void CGBitFieldInfo::print(raw_ostream &OS) const {
855   OS << "<CGBitFieldInfo"
856      << " Offset:" << Offset
857      << " Size:" << Size
858      << " IsSigned:" << IsSigned
859      << " StorageSize:" << StorageSize
860      << " StorageAlignment:" << StorageAlignment << ">";
861 }
862 
863 void CGBitFieldInfo::dump() const {
864   print(llvm::errs());
865 }
866