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 = 0)
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);
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   bool useMSABI() {
103     return Context.getTargetInfo().getCXXABI().isMicrosoft() ||
104            D->isMsStruct(Context);
105   }
106   /// \brief Wraps llvm::Type::getIntNTy with some implicit arguments.
107   llvm::Type *getIntNType(uint64_t NumBits) {
108     return llvm::Type::getIntNTy(Types.getLLVMContext(),
109         (unsigned)llvm::RoundUpToAlignment(NumBits, 8));
110   }
111   /// \brief Gets an llvm type of size NumBytes and alignment 1.
112   llvm::Type *getByteArrayType(CharUnits NumBytes) {
113     assert(!NumBytes.isZero() && "Empty byte arrays aren't allowed.");
114     llvm::Type *Type = llvm::Type::getInt8Ty(Types.getLLVMContext());
115     return NumBytes == CharUnits::One() ? Type :
116         (llvm::Type *)llvm::ArrayType::get(Type, NumBytes.getQuantity());
117   }
118   /// \brief Gets the storage type for a field decl and handles storage
119   /// for itanium bitfields that are smaller than their declared type.
120   llvm::Type *getStorageType(const FieldDecl *FD) {
121     llvm::Type *Type = Types.ConvertTypeForMem(FD->getType());
122     return useMSABI() || !FD->isBitField() ? Type :
123         getIntNType(std::min(FD->getBitWidthValue(Context),
124                              (unsigned)Context.toBits(getSize(Type))));
125   }
126   /// \brief Gets the llvm Basesubobject type from a CXXRecordDecl.
127   llvm::Type *getStorageType(const CXXRecordDecl *RD) {
128     return Types.getCGRecordLayout(RD).getBaseSubobjectLLVMType();
129   }
130   CharUnits bitsToCharUnits(uint64_t BitOffset) {
131     return Context.toCharUnitsFromBits(BitOffset);
132   }
133   CharUnits getSize(llvm::Type *Type) {
134     return CharUnits::fromQuantity(DataLayout.getTypeAllocSize(Type));
135   }
136   CharUnits getAlignment(llvm::Type *Type) {
137     return CharUnits::fromQuantity(DataLayout.getABITypeAlignment(Type));
138   }
139   bool isZeroInitializable(const FieldDecl *FD) {
140     const Type *Type = FD->getType()->getBaseElementTypeUnsafe();
141     if (const MemberPointerType *MPT = Type->getAs<MemberPointerType>())
142       return Types.getCXXABI().isZeroInitializable(MPT);
143     if (const RecordType *RT = Type->getAs<RecordType>())
144       return isZeroInitializable(RT->getDecl());
145     return true;
146   }
147   bool isZeroInitializable(const RecordDecl *RD) {
148     return Types.getCGRecordLayout(RD).isZeroInitializable();
149   }
150   void appendPaddingBytes(CharUnits Size) {
151     if (!Size.isZero())
152       FieldTypes.push_back(getByteArrayType(Size));
153   }
154   uint64_t getFieldBitOffset(const FieldDecl *FD) {
155     return Layout.getFieldOffset(FD->getFieldIndex());
156   }
157   // Layout routines.
158   void setBitFieldInfo(const FieldDecl *FD, CharUnits StartOffset,
159                        llvm::Type *StorageType);
160   /// \brief Lowers an ASTRecordLayout to a llvm type.
161   void lower(bool NonVirtualBaseType);
162   void lowerUnion();
163   void accumulateFields();
164   void accumulateBitFields(RecordDecl::field_iterator Field,
165                         RecordDecl::field_iterator FieldEnd);
166   void accumulateBases();
167   void accumulateVPtrs();
168   void accumulateVBases();
169   /// \brief Recursively searches all of the bases to find out if a vbase is
170   /// not the primary vbase of some base class.
171   bool hasOwnStorage(const CXXRecordDecl *Decl, const CXXRecordDecl *Query);
172   void calculateZeroInit();
173   /// \brief Lowers bitfield storage types to I8 arrays for bitfields with tail
174   /// padding that is or can potentially be used.
175   void clipTailPadding();
176   /// \brief Determines if we need a packed llvm struct.
177   void determinePacked();
178   /// \brief Inserts padding everwhere it's needed.
179   void insertPadding();
180   /// \brief Fills out the structures that are ultimately consumed.
181   void fillOutputFields();
182   // Input memoization fields.
183   CodeGenTypes &Types;
184   const ASTContext &Context;
185   const RecordDecl *D;
186   const CXXRecordDecl *RD;
187   const ASTRecordLayout &Layout;
188   const llvm::DataLayout &DataLayout;
189   // Helpful intermediate data-structures.
190   std::vector<MemberInfo> Members;
191   // Output fields, consumed by CodeGenTypes::ComputeRecordLayout.
192   SmallVector<llvm::Type *, 16> FieldTypes;
193   llvm::DenseMap<const FieldDecl *, unsigned> Fields;
194   llvm::DenseMap<const FieldDecl *, CGBitFieldInfo> BitFields;
195   llvm::DenseMap<const CXXRecordDecl *, unsigned> NonVirtualBases;
196   llvm::DenseMap<const CXXRecordDecl *, unsigned> VirtualBases;
197   bool IsZeroInitializable : 1;
198   bool IsZeroInitializableAsBase : 1;
199   bool Packed : 1;
200 private:
201   CGRecordLowering(const CGRecordLowering &) LLVM_DELETED_FUNCTION;
202   void operator =(const CGRecordLowering &) LLVM_DELETED_FUNCTION;
203 };
204 } // namespace {
205 
206 CGRecordLowering::CGRecordLowering(CodeGenTypes &Types, const RecordDecl *D)
207   : Types(Types), Context(Types.getContext()), D(D),
208     RD(dyn_cast<CXXRecordDecl>(D)),
209     Layout(Types.getContext().getASTRecordLayout(D)),
210     DataLayout(Types.getDataLayout()), IsZeroInitializable(true),
211     IsZeroInitializableAsBase(true), Packed(false) {}
212 
213 void CGRecordLowering::setBitFieldInfo(
214     const FieldDecl *FD, CharUnits StartOffset, llvm::Type *StorageType) {
215   CGBitFieldInfo &Info = BitFields[FD];
216   Info.IsSigned = FD->getType()->isSignedIntegerOrEnumerationType();
217   Info.Offset = (unsigned)(getFieldBitOffset(FD) - Context.toBits(StartOffset));
218   Info.Size = FD->getBitWidthValue(Context);
219   Info.StorageSize = (unsigned)DataLayout.getTypeAllocSizeInBits(StorageType);
220   // Here we calculate the actual storage alignment of the bits.  E.g if we've
221   // got an alignment >= 2 and the bitfield starts at offset 6 we've got an
222   // alignment of 2.
223   Info.StorageAlignment =
224       Layout.getAlignment().alignmentAtOffset(StartOffset).getQuantity();
225   if (Info.Size > Info.StorageSize)
226     Info.Size = Info.StorageSize;
227   // Reverse the bit offsets for big endian machines. Because we represent
228   // a bitfield as a single large integer load, we can imagine the bits
229   // counting from the most-significant-bit instead of the
230   // least-significant-bit.
231   if (DataLayout.isBigEndian())
232     Info.Offset = Info.StorageSize - (Info.Offset + Info.Size);
233 }
234 
235 void CGRecordLowering::lower(bool NVBaseType) {
236   // The lowering process implemented in this function takes a variety of
237   // carefully ordered phases.
238   // 1) Store all members (fields and bases) in a list and sort them by offset.
239   // 2) Add a 1-byte capstone member at the Size of the structure.
240   // 3) Clip bitfield storages members if their tail padding is or might be
241   //    used by another field or base.  The clipping process uses the capstone
242   //    by treating it as another object that occurs after the record.
243   // 4) Determine if the llvm-struct requires packing.  It's important that this
244   //    phase occur after clipping, because clipping changes the llvm type.
245   //    This phase reads the offset of the capstone when determining packedness
246   //    and updates the alignment of the capstone to be equal of the alignment
247   //    of the record after doing so.
248   // 5) Insert padding everywhere it is needed.  This phase requires 'Packed' to
249   //    have been computed and needs to know the alignment of the record in
250   //    order to understand if explicit tail padding is needed.
251   // 6) Remove the capstone, we don't need it anymore.
252   // 7) Determine if this record can be zero-initialized.  This phase could have
253   //    been placed anywhere after phase 1.
254   // 8) Format the complete list of members in a way that can be consumed by
255   //    CodeGenTypes::ComputeRecordLayout.
256   CharUnits Size = NVBaseType ? Layout.getNonVirtualSize() : Layout.getSize();
257   if (D->isUnion())
258     return lowerUnion();
259   accumulateFields();
260   // RD implies C++.
261   if (RD) {
262     accumulateVPtrs();
263     accumulateBases();
264     if (Members.empty())
265       return appendPaddingBytes(Size);
266     if (!NVBaseType)
267       accumulateVBases();
268   }
269   std::stable_sort(Members.begin(), Members.end());
270   Members.push_back(StorageInfo(Size, getIntNType(8)));
271   clipTailPadding();
272   determinePacked();
273   insertPadding();
274   Members.pop_back();
275   calculateZeroInit();
276   fillOutputFields();
277 }
278 
279 void CGRecordLowering::lowerUnion() {
280   llvm::Type *StorageType = 0;
281   // Compute zero-initializable status.
282   if (!D->field_empty() && !isZeroInitializable(*D->field_begin()))
283     IsZeroInitializable = IsZeroInitializableAsBase = false;
284   // Iterate through the fields setting bitFieldInfo and the Fields array. Also
285   // locate the "most appropriate" storage type.  The heuristic for finding the
286   // storage type isn't necessary, the first (non-0-length-bitfield) field's
287   // type would work fine and be simpler but would be differen than what we've
288   // been doing and cause lit tests to change.
289   for (RecordDecl::field_iterator Field = D->field_begin(),
290                                   FieldEnd = D->field_end();
291        Field != FieldEnd; ++Field) {
292     if (Field->isBitField()) {
293       // Skip 0 sized bitfields.
294       if (Field->getBitWidthValue(Context) == 0)
295         continue;
296       setBitFieldInfo(*Field, CharUnits::Zero(), getStorageType(*Field));
297     }
298     Fields[*Field] = 0;
299     llvm::Type *FieldType = getStorageType(*Field);
300     // Conditionally update our storage type if we've got a new "better" one.
301     if (!StorageType ||
302         getAlignment(FieldType) >  getAlignment(StorageType) ||
303         (getAlignment(FieldType) == getAlignment(StorageType) &&
304         getSize(FieldType) > getSize(StorageType)))
305       StorageType = FieldType;
306   }
307   CharUnits LayoutSize = Layout.getSize();
308   // If we have no storage type just pad to the appropriate size and return.
309   if (!StorageType)
310     return appendPaddingBytes(LayoutSize);
311   // If our storage size was bigger than our required size (can happen in the
312   // case of packed bitfields on Itanium) then just use an I8 array.
313   if (LayoutSize < getSize(StorageType))
314     StorageType = getByteArrayType(LayoutSize);
315   FieldTypes.push_back(StorageType);
316   appendPaddingBytes(LayoutSize - getSize(StorageType));
317   // Set packed if we need it.
318   if (LayoutSize % getAlignment(StorageType))
319     Packed = true;
320 }
321 
322 void CGRecordLowering::accumulateFields() {
323   for (RecordDecl::field_iterator Field = D->field_begin(),
324                                   FieldEnd = D->field_end();
325     Field != FieldEnd;)
326     if (Field->isBitField()) {
327       RecordDecl::field_iterator Start = Field;
328       // Iterate to gather the list of bitfields.
329       for (++Field; Field != FieldEnd && Field->isBitField(); ++Field);
330       accumulateBitFields(Start, Field);
331     } else {
332       Members.push_back(MemberInfo(
333           bitsToCharUnits(getFieldBitOffset(*Field)), MemberInfo::Field,
334           getStorageType(*Field), *Field));
335       ++Field;
336     }
337 }
338 
339 void
340 CGRecordLowering::accumulateBitFields(RecordDecl::field_iterator Field,
341                                       RecordDecl::field_iterator FieldEnd) {
342   // Run stores the first element of the current run of bitfields.  FieldEnd is
343   // used as a special value to note that we don't have a current run.  A
344   // bitfield run is a contiguous collection of bitfields that can be stored in
345   // the same storage block.  Zero-sized bitfields and bitfields that would
346   // cross an alignment boundary break a run and start a new one.
347   RecordDecl::field_iterator Run = FieldEnd;
348   // Tail is the offset of the first bit off the end of the current run.  It's
349   // used to determine if the ASTRecordLayout is treating these two bitfields as
350   // contiguous.  StartBitOffset is offset of the beginning of the Run.
351   uint64_t StartBitOffset, Tail = 0;
352   if (useMSABI()) {
353     for (; Field != FieldEnd; ++Field) {
354       uint64_t BitOffset = getFieldBitOffset(*Field);
355       // Zero-width bitfields end runs.
356       if (Field->getBitWidthValue(Context) == 0) {
357         Run = FieldEnd;
358         continue;
359       }
360       llvm::Type *Type = Types.ConvertTypeForMem(Field->getType());
361       // If we don't have a run yet, or don't live within the previous run's
362       // allocated storage then we allocate some storage and start a new run.
363       if (Run == FieldEnd || BitOffset >= Tail) {
364         Run = Field;
365         StartBitOffset = BitOffset;
366         Tail = StartBitOffset + DataLayout.getTypeAllocSizeInBits(Type);
367         // Add the storage member to the record.  This must be added to the
368         // record before the bitfield members so that it gets laid out before
369         // the bitfields it contains get laid out.
370         Members.push_back(StorageInfo(bitsToCharUnits(StartBitOffset), Type));
371       }
372       // Bitfields get the offset of their storage but come afterward and remain
373       // there after a stable sort.
374       Members.push_back(MemberInfo(bitsToCharUnits(StartBitOffset),
375                                    MemberInfo::Field, 0, *Field));
376     }
377     return;
378   }
379   for (;;) {
380     // Check to see if we need to start a new run.
381     if (Run == FieldEnd) {
382       // If we're out of fields, return.
383       if (Field == FieldEnd)
384         break;
385       // Any non-zero-length bitfield can start a new run.
386       if (Field->getBitWidthValue(Context) != 0) {
387         Run = Field;
388         StartBitOffset = getFieldBitOffset(*Field);
389         Tail = StartBitOffset + Field->getBitWidthValue(Context);
390       }
391       ++Field;
392       continue;
393     }
394     // Add bitfields to the run as long as they qualify.
395     if (Field != FieldEnd && Field->getBitWidthValue(Context) != 0 &&
396         Tail == getFieldBitOffset(*Field)) {
397       Tail += Field->getBitWidthValue(Context);
398       ++Field;
399       continue;
400     }
401     // We've hit a break-point in the run and need to emit a storage field.
402     llvm::Type *Type = getIntNType(Tail - StartBitOffset);
403     // Add the storage member to the record and set the bitfield info for all of
404     // the bitfields in the run.  Bitfields get the offset of their storage but
405     // come afterward and remain there after a stable sort.
406     Members.push_back(StorageInfo(bitsToCharUnits(StartBitOffset), Type));
407     for (; Run != Field; ++Run)
408       Members.push_back(MemberInfo(bitsToCharUnits(StartBitOffset),
409                                    MemberInfo::Field, 0, *Run));
410     Run = FieldEnd;
411   }
412 }
413 
414 void CGRecordLowering::accumulateBases() {
415   // If we've got a primary virtual base, we need to add it with the bases.
416   if (Layout.isPrimaryBaseVirtual())
417     Members.push_back(StorageInfo(
418       CharUnits::Zero(),
419       getStorageType(Layout.getPrimaryBase())));
420   // Accumulate the non-virtual bases.
421   for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
422                                                 BaseEnd = RD->bases_end();
423         Base != BaseEnd; ++Base) {
424     if (Base->isVirtual())
425       continue;
426     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
427     if (!BaseDecl->isEmpty())
428       Members.push_back(MemberInfo(Layout.getBaseClassOffset(BaseDecl),
429           MemberInfo::Base, getStorageType(BaseDecl), BaseDecl));
430   }
431 }
432 
433 void CGRecordLowering::accumulateVPtrs() {
434   if (Layout.hasOwnVFPtr())
435     Members.push_back(MemberInfo(CharUnits::Zero(), MemberInfo::VFPtr,
436         llvm::FunctionType::get(getIntNType(32), /*isVarArg=*/true)->
437             getPointerTo()->getPointerTo()));
438   if (Layout.hasOwnVBPtr())
439     Members.push_back(MemberInfo(Layout.getVBPtrOffset(), MemberInfo::VBPtr,
440         llvm::Type::getInt32PtrTy(Types.getLLVMContext())));
441 }
442 
443 void CGRecordLowering::accumulateVBases() {
444   Members.push_back(MemberInfo(Layout.getNonVirtualSize(),
445                                MemberInfo::Scissor, 0, RD));
446   for (CXXRecordDecl::base_class_const_iterator Base = RD->vbases_begin(),
447                                                 BaseEnd = RD->vbases_end();
448        Base != BaseEnd; ++Base) {
449     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
450     if (BaseDecl->isEmpty())
451       continue;
452     CharUnits Offset = Layout.getVBaseClassOffset(BaseDecl);
453     // If the vbase is a primary virtual base of some base, then it doesn't
454     // get its own storage location but instead lives inside of that base.
455     if (!useMSABI() && Context.isNearlyEmpty(BaseDecl) &&
456         !hasOwnStorage(RD, BaseDecl)) {
457       Members.push_back(MemberInfo(Offset, MemberInfo::VBase, 0, BaseDecl));
458       continue;
459     }
460     // If we've got a vtordisp, add it as a storage type.
461     if (Layout.getVBaseOffsetsMap().find(BaseDecl)->second.hasVtorDisp())
462       Members.push_back(StorageInfo(Offset - CharUnits::fromQuantity(4),
463                                     getIntNType(32)));
464     Members.push_back(MemberInfo(Offset, MemberInfo::VBase,
465                                  getStorageType(BaseDecl), BaseDecl));
466   }
467 }
468 
469 bool CGRecordLowering::hasOwnStorage(const CXXRecordDecl *Decl,
470                                      const CXXRecordDecl *Query) {
471   const ASTRecordLayout &DeclLayout = Context.getASTRecordLayout(Decl);
472   if (DeclLayout.isPrimaryBaseVirtual() && DeclLayout.getPrimaryBase() == Query)
473     return false;
474   for (CXXRecordDecl::base_class_const_iterator Base = Decl->bases_begin(),
475                                                 BaseEnd = Decl->bases_end();
476        Base != BaseEnd; ++Base)
477     if (!hasOwnStorage(Base->getType()->getAsCXXRecordDecl(), Query))
478       return false;
479   return true;
480 }
481 
482 void CGRecordLowering::calculateZeroInit() {
483   for (std::vector<MemberInfo>::const_iterator Member = Members.begin(),
484                                                MemberEnd = Members.end();
485        IsZeroInitializableAsBase && Member != MemberEnd; ++Member) {
486     if (Member->Kind == MemberInfo::Field) {
487       if (!Member->FD || isZeroInitializable(Member->FD))
488         continue;
489       IsZeroInitializable = IsZeroInitializableAsBase = false;
490     } else if (Member->Kind == MemberInfo::Base ||
491                Member->Kind == MemberInfo::VBase) {
492       if (isZeroInitializable(Member->RD))
493         continue;
494       IsZeroInitializable = false;
495       if (Member->Kind == MemberInfo::Base)
496         IsZeroInitializableAsBase = false;
497     }
498   }
499 }
500 
501 void CGRecordLowering::clipTailPadding() {
502   std::vector<MemberInfo>::iterator Prior = Members.begin();
503   CharUnits Tail = getSize(Prior->Data);
504   for (std::vector<MemberInfo>::iterator Member = Prior + 1,
505                                          MemberEnd = Members.end();
506        Member != MemberEnd; ++Member) {
507     // Only members with data and the scissor can cut into tail padding.
508     if (!Member->Data && Member->Kind != MemberInfo::Scissor)
509       continue;
510     if (Member->Offset < Tail) {
511       assert(Prior->Kind == MemberInfo::Field && !Prior->FD &&
512              "Only storage fields have tail padding!");
513       Prior->Data = getByteArrayType(bitsToCharUnits(llvm::RoundUpToAlignment(
514           cast<llvm::IntegerType>(Prior->Data)->getIntegerBitWidth(), 8)));
515     }
516     if (Member->Data)
517       Prior = Member;
518     Tail = Prior->Offset + getSize(Prior->Data);
519   }
520 }
521 
522 void CGRecordLowering::determinePacked() {
523   CharUnits Alignment = CharUnits::One();
524   for (std::vector<MemberInfo>::const_iterator Member = Members.begin(),
525                                                MemberEnd = Members.end();
526        Member != MemberEnd; ++Member) {
527     if (!Member->Data)
528       continue;
529     // If any member falls at an offset that it not a multiple of its alignment,
530     // then the entire record must be packed.
531     if (Member->Offset % getAlignment(Member->Data))
532       Packed = true;
533     Alignment = std::max(Alignment, getAlignment(Member->Data));
534   }
535   // If the size of the record (the capstone's offset) is not a multiple of the
536   // record's alignment, it must be packed.
537   if (Members.back().Offset % Alignment)
538     Packed = true;
539   // Update the alignment of the sentinal.
540   if (!Packed)
541     Members.back().Data = getIntNType(Context.toBits(Alignment));
542 }
543 
544 void CGRecordLowering::insertPadding() {
545   std::vector<std::pair<CharUnits, CharUnits> > Padding;
546   CharUnits Size = CharUnits::Zero();
547   for (std::vector<MemberInfo>::const_iterator Member = Members.begin(),
548                                                MemberEnd = Members.end();
549        Member != MemberEnd; ++Member) {
550     if (!Member->Data)
551       continue;
552     CharUnits Offset = Member->Offset;
553     assert(Offset >= Size);
554     // Insert padding if we need to.
555     if (Offset != Size.RoundUpToAlignment(Packed ? CharUnits::One() :
556                                           getAlignment(Member->Data)))
557       Padding.push_back(std::make_pair(Size, Offset - Size));
558     Size = Offset + getSize(Member->Data);
559   }
560   if (Padding.empty())
561     return;
562   // Add the padding to the Members list and sort it.
563   for (std::vector<std::pair<CharUnits, CharUnits> >::const_iterator
564         Pad = Padding.begin(), PadEnd = Padding.end();
565         Pad != PadEnd; ++Pad)
566     Members.push_back(StorageInfo(Pad->first, getByteArrayType(Pad->second)));
567   std::stable_sort(Members.begin(), Members.end());
568 }
569 
570 void CGRecordLowering::fillOutputFields() {
571   for (std::vector<MemberInfo>::const_iterator Member = Members.begin(),
572                                                MemberEnd = Members.end();
573        Member != MemberEnd; ++Member) {
574     if (Member->Data)
575       FieldTypes.push_back(Member->Data);
576     if (Member->Kind == MemberInfo::Field) {
577       if (Member->FD)
578         Fields[Member->FD] = FieldTypes.size() - 1;
579       // A field without storage must be a bitfield.
580       if (!Member->Data)
581         setBitFieldInfo(Member->FD, Member->Offset, FieldTypes.back());
582     } else if (Member->Kind == MemberInfo::Base)
583       NonVirtualBases[Member->RD] = FieldTypes.size() - 1;
584     else if (Member->Kind == MemberInfo::VBase)
585       VirtualBases[Member->RD] = FieldTypes.size() - 1;
586   }
587 }
588 
589 CGBitFieldInfo CGBitFieldInfo::MakeInfo(CodeGenTypes &Types,
590                                         const FieldDecl *FD,
591                                         uint64_t Offset, uint64_t Size,
592                                         uint64_t StorageSize,
593                                         uint64_t StorageAlignment) {
594   // This function is vestigial from CGRecordLayoutBuilder days but is still
595   // used in GCObjCRuntime.cpp.  That usage has a "fixme" attached to it that
596   // when addressed will allow for the removal of this function.
597   llvm::Type *Ty = Types.ConvertTypeForMem(FD->getType());
598   CharUnits TypeSizeInBytes =
599     CharUnits::fromQuantity(Types.getDataLayout().getTypeAllocSize(Ty));
600   uint64_t TypeSizeInBits = Types.getContext().toBits(TypeSizeInBytes);
601 
602   bool IsSigned = FD->getType()->isSignedIntegerOrEnumerationType();
603 
604   if (Size > TypeSizeInBits) {
605     // We have a wide bit-field. The extra bits are only used for padding, so
606     // if we have a bitfield of type T, with size N:
607     //
608     // T t : N;
609     //
610     // We can just assume that it's:
611     //
612     // T t : sizeof(T);
613     //
614     Size = TypeSizeInBits;
615   }
616 
617   // Reverse the bit offsets for big endian machines. Because we represent
618   // a bitfield as a single large integer load, we can imagine the bits
619   // counting from the most-significant-bit instead of the
620   // least-significant-bit.
621   if (Types.getDataLayout().isBigEndian()) {
622     Offset = StorageSize - (Offset + Size);
623   }
624 
625   return CGBitFieldInfo(Offset, Size, IsSigned, StorageSize, StorageAlignment);
626 }
627 
628 CGRecordLayout *CodeGenTypes::ComputeRecordLayout(const RecordDecl *D,
629                                                   llvm::StructType *Ty) {
630   CGRecordLowering Builder(*this, D);
631 
632   Builder.lower(false);
633 
634   Ty->setBody(Builder.FieldTypes, Builder.Packed);
635 
636   // If we're in C++, compute the base subobject type.
637   llvm::StructType *BaseTy = 0;
638   if (isa<CXXRecordDecl>(D) && !D->isUnion() && !D->hasAttr<FinalAttr>()) {
639     BaseTy = Ty;
640     if (Builder.Layout.getNonVirtualSize() != Builder.Layout.getSize()) {
641       CGRecordLowering BaseBuilder(*this, D);
642       BaseBuilder.lower(true);
643       BaseTy = llvm::StructType::create(
644           getLLVMContext(), BaseBuilder.FieldTypes, "", BaseBuilder.Packed);
645       addRecordTypeName(D, BaseTy, ".base");
646     }
647   }
648 
649   CGRecordLayout *RL =
650     new CGRecordLayout(Ty, BaseTy, Builder.IsZeroInitializable,
651                         Builder.IsZeroInitializableAsBase);
652 
653   RL->NonVirtualBases.swap(Builder.NonVirtualBases);
654   RL->CompleteObjectVirtualBases.swap(Builder.VirtualBases);
655 
656   // Add all the field numbers.
657   RL->FieldInfo.swap(Builder.Fields);
658 
659   // Add bitfield info.
660   RL->BitFields.swap(Builder.BitFields);
661 
662   // Dump the layout, if requested.
663   if (getContext().getLangOpts().DumpRecordLayouts) {
664     llvm::outs() << "\n*** Dumping IRgen Record Layout\n";
665     llvm::outs() << "Record: ";
666     D->dump(llvm::outs());
667     llvm::outs() << "\nLayout: ";
668     RL->print(llvm::outs());
669   }
670 
671 #ifndef NDEBUG
672   // Verify that the computed LLVM struct size matches the AST layout size.
673   const ASTRecordLayout &Layout = getContext().getASTRecordLayout(D);
674 
675   uint64_t TypeSizeInBits = getContext().toBits(Layout.getSize());
676   assert(TypeSizeInBits == getDataLayout().getTypeAllocSizeInBits(Ty) &&
677          "Type size mismatch!");
678 
679   if (BaseTy) {
680     CharUnits NonVirtualSize  = Layout.getNonVirtualSize();
681 
682     uint64_t AlignedNonVirtualTypeSizeInBits =
683       getContext().toBits(NonVirtualSize);
684 
685     assert(AlignedNonVirtualTypeSizeInBits ==
686            getDataLayout().getTypeAllocSizeInBits(BaseTy) &&
687            "Type size mismatch!");
688   }
689 
690   // Verify that the LLVM and AST field offsets agree.
691   llvm::StructType *ST =
692     dyn_cast<llvm::StructType>(RL->getLLVMType());
693   const llvm::StructLayout *SL = getDataLayout().getStructLayout(ST);
694 
695   const ASTRecordLayout &AST_RL = getContext().getASTRecordLayout(D);
696   RecordDecl::field_iterator it = D->field_begin();
697   for (unsigned i = 0, e = AST_RL.getFieldCount(); i != e; ++i, ++it) {
698     const FieldDecl *FD = *it;
699 
700     // For non-bit-fields, just check that the LLVM struct offset matches the
701     // AST offset.
702     if (!FD->isBitField()) {
703       unsigned FieldNo = RL->getLLVMFieldNo(FD);
704       assert(AST_RL.getFieldOffset(i) == SL->getElementOffsetInBits(FieldNo) &&
705              "Invalid field offset!");
706       continue;
707     }
708 
709     // Ignore unnamed bit-fields.
710     if (!FD->getDeclName())
711       continue;
712 
713     // Don't inspect zero-length bitfields.
714     if (FD->getBitWidthValue(getContext()) == 0)
715       continue;
716 
717     const CGBitFieldInfo &Info = RL->getBitFieldInfo(FD);
718     llvm::Type *ElementTy = ST->getTypeAtIndex(RL->getLLVMFieldNo(FD));
719 
720     // Unions have overlapping elements dictating their layout, but for
721     // non-unions we can verify that this section of the layout is the exact
722     // expected size.
723     if (D->isUnion()) {
724       // For unions we verify that the start is zero and the size
725       // is in-bounds. However, on BE systems, the offset may be non-zero, but
726       // the size + offset should match the storage size in that case as it
727       // "starts" at the back.
728       if (getDataLayout().isBigEndian())
729         assert(static_cast<unsigned>(Info.Offset + Info.Size) ==
730                Info.StorageSize &&
731                "Big endian union bitfield does not end at the back");
732       else
733         assert(Info.Offset == 0 &&
734                "Little endian union bitfield with a non-zero offset");
735       assert(Info.StorageSize <= SL->getSizeInBits() &&
736              "Union not large enough for bitfield storage");
737     } else {
738       assert(Info.StorageSize ==
739              getDataLayout().getTypeAllocSizeInBits(ElementTy) &&
740              "Storage size does not match the element type size");
741     }
742     assert(Info.Size > 0 && "Empty bitfield!");
743     assert(static_cast<unsigned>(Info.Offset) + Info.Size <= Info.StorageSize &&
744            "Bitfield outside of its allocated storage");
745   }
746 #endif
747 
748   return RL;
749 }
750 
751 void CGRecordLayout::print(raw_ostream &OS) const {
752   OS << "<CGRecordLayout\n";
753   OS << "  LLVMType:" << *CompleteObjectType << "\n";
754   if (BaseSubobjectType)
755     OS << "  NonVirtualBaseLLVMType:" << *BaseSubobjectType << "\n";
756   OS << "  IsZeroInitializable:" << IsZeroInitializable << "\n";
757   OS << "  BitFields:[\n";
758 
759   // Print bit-field infos in declaration order.
760   std::vector<std::pair<unsigned, const CGBitFieldInfo*> > BFIs;
761   for (llvm::DenseMap<const FieldDecl*, CGBitFieldInfo>::const_iterator
762          it = BitFields.begin(), ie = BitFields.end();
763        it != ie; ++it) {
764     const RecordDecl *RD = it->first->getParent();
765     unsigned Index = 0;
766     for (RecordDecl::field_iterator
767            it2 = RD->field_begin(); *it2 != it->first; ++it2)
768       ++Index;
769     BFIs.push_back(std::make_pair(Index, &it->second));
770   }
771   llvm::array_pod_sort(BFIs.begin(), BFIs.end());
772   for (unsigned i = 0, e = BFIs.size(); i != e; ++i) {
773     OS.indent(4);
774     BFIs[i].second->print(OS);
775     OS << "\n";
776   }
777 
778   OS << "]>\n";
779 }
780 
781 void CGRecordLayout::dump() const {
782   print(llvm::errs());
783 }
784 
785 void CGBitFieldInfo::print(raw_ostream &OS) const {
786   OS << "<CGBitFieldInfo"
787      << " Offset:" << Offset
788      << " Size:" << Size
789      << " IsSigned:" << IsSigned
790      << " StorageSize:" << StorageSize
791      << " StorageAlignment:" << StorageAlignment << ">";
792 }
793 
794 void CGBitFieldInfo::dump() const {
795   print(llvm::errs());
796 }
797