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 "clang/AST/ASTContext.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/RecordLayout.h"
20 #include "CodeGenTypes.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Type.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include "llvm/Target/TargetData.h"
26 using namespace clang;
27 using namespace CodeGen;
28 
29 namespace clang {
30 namespace CodeGen {
31 
32 class CGRecordLayoutBuilder {
33 public:
34   /// FieldTypes - Holds the LLVM types that the struct is created from.
35   std::vector<const llvm::Type *> FieldTypes;
36 
37   /// LLVMFieldInfo - Holds a field and its corresponding LLVM field number.
38   typedef std::pair<const FieldDecl *, unsigned> LLVMFieldInfo;
39   llvm::SmallVector<LLVMFieldInfo, 16> LLVMFields;
40 
41   /// LLVMBitFieldInfo - Holds location and size information about a bit field.
42   typedef std::pair<const FieldDecl *, CGBitFieldInfo> LLVMBitFieldInfo;
43   llvm::SmallVector<LLVMBitFieldInfo, 16> LLVMBitFields;
44 
45   /// ContainsPointerToDataMember - Whether one of the fields in this record
46   /// layout is a pointer to data member, or a struct that contains pointer to
47   /// data member.
48   bool ContainsPointerToDataMember;
49 
50   /// Packed - Whether the resulting LLVM struct will be packed or not.
51   bool Packed;
52 
53 private:
54   CodeGenTypes &Types;
55 
56   /// Alignment - Contains the alignment of the RecordDecl.
57   //
58   // FIXME: This is not needed and should be removed.
59   unsigned Alignment;
60 
61   /// AlignmentAsLLVMStruct - Will contain the maximum alignment of all the
62   /// LLVM types.
63   unsigned AlignmentAsLLVMStruct;
64 
65   /// BitsAvailableInLastField - If a bit field spans only part of a LLVM field,
66   /// this will have the number of bits still available in the field.
67   char BitsAvailableInLastField;
68 
69   /// NextFieldOffsetInBytes - Holds the next field offset in bytes.
70   uint64_t NextFieldOffsetInBytes;
71 
72   /// LayoutUnionField - Will layout a field in an union and return the type
73   /// that the field will have.
74   const llvm::Type *LayoutUnionField(const FieldDecl *Field,
75                                      const ASTRecordLayout &Layout);
76 
77   /// LayoutUnion - Will layout a union RecordDecl.
78   void LayoutUnion(const RecordDecl *D);
79 
80   /// LayoutField - try to layout all fields in the record decl.
81   /// Returns false if the operation failed because the struct is not packed.
82   bool LayoutFields(const RecordDecl *D);
83 
84   /// LayoutBases - layout the bases and vtable pointer of a record decl.
85   void LayoutBases(const CXXRecordDecl *RD, const ASTRecordLayout &Layout);
86 
87   /// LayoutField - layout a single field. Returns false if the operation failed
88   /// because the current struct is not packed.
89   bool LayoutField(const FieldDecl *D, uint64_t FieldOffset);
90 
91   /// LayoutBitField - layout a single bit field.
92   void LayoutBitField(const FieldDecl *D, uint64_t FieldOffset);
93 
94   /// AppendField - Appends a field with the given offset and type.
95   void AppendField(uint64_t FieldOffsetInBytes, const llvm::Type *FieldTy);
96 
97   /// AppendPadding - Appends enough padding bytes so that the total
98   /// struct size is a multiple of the field alignment.
99   void AppendPadding(uint64_t FieldOffsetInBytes, unsigned FieldAlignment);
100 
101   /// AppendBytes - Append a given number of bytes to the record.
102   void AppendBytes(uint64_t NumBytes);
103 
104   /// AppendTailPadding - Append enough tail padding so that the type will have
105   /// the passed size.
106   void AppendTailPadding(uint64_t RecordSize);
107 
108   unsigned getTypeAlignment(const llvm::Type *Ty) const;
109 
110   /// CheckForPointerToDataMember - Check if the given type contains a pointer
111   /// to data member.
112   void CheckForPointerToDataMember(QualType T);
113 
114 public:
115   CGRecordLayoutBuilder(CodeGenTypes &Types)
116     : ContainsPointerToDataMember(false), Packed(false), Types(Types),
117       Alignment(0), AlignmentAsLLVMStruct(1),
118       BitsAvailableInLastField(0), NextFieldOffsetInBytes(0) { }
119 
120   /// Layout - Will layout a RecordDecl.
121   void Layout(const RecordDecl *D);
122 };
123 
124 }
125 }
126 
127 void CGRecordLayoutBuilder::Layout(const RecordDecl *D) {
128   Alignment = Types.getContext().getASTRecordLayout(D).getAlignment() / 8;
129   Packed = D->hasAttr<PackedAttr>();
130 
131   if (D->isUnion()) {
132     LayoutUnion(D);
133     return;
134   }
135 
136   if (LayoutFields(D))
137     return;
138 
139   // We weren't able to layout the struct. Try again with a packed struct
140   Packed = true;
141   AlignmentAsLLVMStruct = 1;
142   NextFieldOffsetInBytes = 0;
143   FieldTypes.clear();
144   LLVMFields.clear();
145   LLVMBitFields.clear();
146 
147   LayoutFields(D);
148 }
149 
150 static CGBitFieldInfo ComputeBitFieldInfo(CodeGenTypes &Types,
151                                           const FieldDecl *FD,
152                                           uint64_t FieldOffset,
153                                           uint64_t FieldSize) {
154   const RecordDecl *RD = FD->getParent();
155   const ASTRecordLayout &RL = Types.getContext().getASTRecordLayout(RD);
156   uint64_t ContainingTypeSizeInBits = RL.getSize();
157   unsigned ContainingTypeAlign = RL.getAlignment();
158 
159   const llvm::Type *Ty = Types.ConvertTypeForMemRecursive(FD->getType());
160   uint64_t TypeSizeInBytes = Types.getTargetData().getTypeAllocSize(Ty);
161   uint64_t TypeSizeInBits = TypeSizeInBytes * 8;
162 
163   bool IsSigned = FD->getType()->isSignedIntegerType();
164 
165   if (FieldSize > TypeSizeInBits) {
166     // We have a wide bit-field. The extra bits are only used for padding, so
167     // if we have a bitfield of type T, with size N:
168     //
169     // T t : N;
170     //
171     // We can just assume that it's:
172     //
173     // T t : sizeof(T);
174     //
175     FieldSize = TypeSizeInBits;
176   }
177 
178   // Compute the access components. The policy we use is to start by attempting
179   // to access using the width of the bit-field type itself and to always access
180   // at aligned indices of that type. If such an access would fail because it
181   // extends past the bound of the type, then we reduce size to the next smaller
182   // power of two and retry. The current algorithm assumes pow2 sized types,
183   // although this is easy to fix.
184   //
185   // FIXME: This algorithm is wrong on big-endian systems, I think.
186   assert(llvm::isPowerOf2_32(TypeSizeInBits) && "Unexpected type size!");
187   CGBitFieldInfo::AccessInfo Components[3];
188   unsigned NumComponents = 0;
189   unsigned AccessedTargetBits = 0;       // The tumber of target bits accessed.
190   unsigned AccessWidth = TypeSizeInBits; // The current access width to attempt.
191 
192   // Round down from the field offset to find the first access position that is
193   // at an aligned offset of the initial access type.
194   uint64_t AccessStart = FieldOffset - (FieldOffset % AccessWidth);
195 
196   // Adjust initial access size to fit within record.
197   while (AccessWidth > 8 &&
198          AccessStart + AccessWidth > ContainingTypeSizeInBits) {
199     AccessWidth >>= 1;
200     AccessStart = FieldOffset - (FieldOffset % AccessWidth);
201   }
202 
203   while (AccessedTargetBits < FieldSize) {
204     // Check that we can access using a type of this size, without reading off
205     // the end of the structure. This can occur with packed structures and
206     // -fno-bitfield-type-align, for example.
207     if (AccessStart + AccessWidth > ContainingTypeSizeInBits) {
208       // If so, reduce access size to the next smaller power-of-two and retry.
209       AccessWidth >>= 1;
210       assert(AccessWidth >= 8 && "Cannot access under byte size!");
211       continue;
212     }
213 
214     // Otherwise, add an access component.
215 
216     // First, compute the bits inside this access which are part of the
217     // target. We are reading bits [AccessStart, AccessStart + AccessWidth); the
218     // intersection with [FieldOffset, FieldOffset + FieldSize) gives the bits
219     // in the target that we are reading.
220     assert(FieldOffset < AccessStart + AccessWidth && "Invalid access start!");
221     assert(AccessStart < FieldOffset + FieldSize && "Invalid access start!");
222     uint64_t AccessBitsInFieldStart = std::max(AccessStart, FieldOffset);
223     uint64_t AccessBitsInFieldSize =
224       std::min(AccessWidth + AccessStart,
225                FieldOffset + FieldSize) - AccessBitsInFieldStart;
226 
227     assert(NumComponents < 3 && "Unexpected number of components!");
228     CGBitFieldInfo::AccessInfo &AI = Components[NumComponents++];
229     AI.FieldIndex = 0;
230     // FIXME: We still follow the old access pattern of only using the field
231     // byte offset. We should switch this once we fix the struct layout to be
232     // pretty.
233     AI.FieldByteOffset = AccessStart / 8;
234     AI.FieldBitStart = AccessBitsInFieldStart - AccessStart;
235     AI.AccessWidth = AccessWidth;
236     AI.AccessAlignment = llvm::MinAlign(ContainingTypeAlign, AccessStart) / 8;
237     AI.TargetBitOffset = AccessedTargetBits;
238     AI.TargetBitWidth = AccessBitsInFieldSize;
239 
240     AccessStart += AccessWidth;
241     AccessedTargetBits += AI.TargetBitWidth;
242   }
243 
244   assert(AccessedTargetBits == FieldSize && "Invalid bit-field access!");
245   return CGBitFieldInfo(FieldSize, NumComponents, Components, IsSigned);
246 }
247 
248 void CGRecordLayoutBuilder::LayoutBitField(const FieldDecl *D,
249                                            uint64_t FieldOffset) {
250   uint64_t FieldSize =
251     D->getBitWidth()->EvaluateAsInt(Types.getContext()).getZExtValue();
252 
253   if (FieldSize == 0)
254     return;
255 
256   uint64_t NextFieldOffset = NextFieldOffsetInBytes * 8;
257   unsigned NumBytesToAppend;
258 
259   if (FieldOffset < NextFieldOffset) {
260     assert(BitsAvailableInLastField && "Bitfield size mismatch!");
261     assert(NextFieldOffsetInBytes && "Must have laid out at least one byte!");
262 
263     // The bitfield begins in the previous bit-field.
264     NumBytesToAppend =
265       llvm::RoundUpToAlignment(FieldSize - BitsAvailableInLastField, 8) / 8;
266   } else {
267     assert(FieldOffset % 8 == 0 && "Field offset not aligned correctly");
268 
269     // Append padding if necessary.
270     AppendBytes((FieldOffset - NextFieldOffset) / 8);
271 
272     NumBytesToAppend =
273       llvm::RoundUpToAlignment(FieldSize, 8) / 8;
274 
275     assert(NumBytesToAppend && "No bytes to append!");
276   }
277 
278   // Add the bit field info.
279   LLVMBitFields.push_back(
280     LLVMBitFieldInfo(D, ComputeBitFieldInfo(Types, D, FieldOffset, FieldSize)));
281 
282   AppendBytes(NumBytesToAppend);
283 
284   BitsAvailableInLastField =
285     NextFieldOffsetInBytes * 8 - (FieldOffset + FieldSize);
286 }
287 
288 bool CGRecordLayoutBuilder::LayoutField(const FieldDecl *D,
289                                         uint64_t FieldOffset) {
290   // If the field is packed, then we need a packed struct.
291   if (!Packed && D->hasAttr<PackedAttr>())
292     return false;
293 
294   if (D->isBitField()) {
295     // We must use packed structs for unnamed bit fields since they
296     // don't affect the struct alignment.
297     if (!Packed && !D->getDeclName())
298       return false;
299 
300     LayoutBitField(D, FieldOffset);
301     return true;
302   }
303 
304   // Check if we have a pointer to data member in this field.
305   CheckForPointerToDataMember(D->getType());
306 
307   assert(FieldOffset % 8 == 0 && "FieldOffset is not on a byte boundary!");
308   uint64_t FieldOffsetInBytes = FieldOffset / 8;
309 
310   const llvm::Type *Ty = Types.ConvertTypeForMemRecursive(D->getType());
311   unsigned TypeAlignment = getTypeAlignment(Ty);
312 
313   // If the type alignment is larger then the struct alignment, we must use
314   // a packed struct.
315   if (TypeAlignment > Alignment) {
316     assert(!Packed && "Alignment is wrong even with packed struct!");
317     return false;
318   }
319 
320   if (const RecordType *RT = D->getType()->getAs<RecordType>()) {
321     const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
322     if (const PragmaPackAttr *PPA = RD->getAttr<PragmaPackAttr>()) {
323       if (PPA->getAlignment() != TypeAlignment * 8 && !Packed)
324         return false;
325     }
326   }
327 
328   // Round up the field offset to the alignment of the field type.
329   uint64_t AlignedNextFieldOffsetInBytes =
330     llvm::RoundUpToAlignment(NextFieldOffsetInBytes, TypeAlignment);
331 
332   if (FieldOffsetInBytes < AlignedNextFieldOffsetInBytes) {
333     assert(!Packed && "Could not place field even with packed struct!");
334     return false;
335   }
336 
337   if (AlignedNextFieldOffsetInBytes < FieldOffsetInBytes) {
338     // Even with alignment, the field offset is not at the right place,
339     // insert padding.
340     uint64_t PaddingInBytes = FieldOffsetInBytes - NextFieldOffsetInBytes;
341 
342     AppendBytes(PaddingInBytes);
343   }
344 
345   // Now append the field.
346   LLVMFields.push_back(LLVMFieldInfo(D, FieldTypes.size()));
347   AppendField(FieldOffsetInBytes, Ty);
348 
349   return true;
350 }
351 
352 const llvm::Type *
353 CGRecordLayoutBuilder::LayoutUnionField(const FieldDecl *Field,
354                                         const ASTRecordLayout &Layout) {
355   if (Field->isBitField()) {
356     uint64_t FieldSize =
357       Field->getBitWidth()->EvaluateAsInt(Types.getContext()).getZExtValue();
358 
359     // Ignore zero sized bit fields.
360     if (FieldSize == 0)
361       return 0;
362 
363     const llvm::Type *FieldTy = llvm::Type::getInt8Ty(Types.getLLVMContext());
364     unsigned NumBytesToAppend =
365       llvm::RoundUpToAlignment(FieldSize, 8) / 8;
366 
367     if (NumBytesToAppend > 1)
368       FieldTy = llvm::ArrayType::get(FieldTy, NumBytesToAppend);
369 
370     // Add the bit field info.
371     LLVMBitFields.push_back(
372       LLVMBitFieldInfo(Field, ComputeBitFieldInfo(Types, Field, 0, FieldSize)));
373     return FieldTy;
374   }
375 
376   // This is a regular union field.
377   LLVMFields.push_back(LLVMFieldInfo(Field, 0));
378   return Types.ConvertTypeForMemRecursive(Field->getType());
379 }
380 
381 void CGRecordLayoutBuilder::LayoutUnion(const RecordDecl *D) {
382   assert(D->isUnion() && "Can't call LayoutUnion on a non-union record!");
383 
384   const ASTRecordLayout &Layout = Types.getContext().getASTRecordLayout(D);
385 
386   const llvm::Type *Ty = 0;
387   uint64_t Size = 0;
388   unsigned Align = 0;
389 
390   bool HasOnlyZeroSizedBitFields = true;
391 
392   unsigned FieldNo = 0;
393   for (RecordDecl::field_iterator Field = D->field_begin(),
394        FieldEnd = D->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
395     assert(Layout.getFieldOffset(FieldNo) == 0 &&
396           "Union field offset did not start at the beginning of record!");
397     const llvm::Type *FieldTy = LayoutUnionField(*Field, Layout);
398 
399     if (!FieldTy)
400       continue;
401 
402     HasOnlyZeroSizedBitFields = false;
403 
404     unsigned FieldAlign = Types.getTargetData().getABITypeAlignment(FieldTy);
405     uint64_t FieldSize = Types.getTargetData().getTypeAllocSize(FieldTy);
406 
407     if (FieldAlign < Align)
408       continue;
409 
410     if (FieldAlign > Align || FieldSize > Size) {
411       Ty = FieldTy;
412       Align = FieldAlign;
413       Size = FieldSize;
414     }
415   }
416 
417   // Now add our field.
418   if (Ty) {
419     AppendField(0, Ty);
420 
421     if (getTypeAlignment(Ty) > Layout.getAlignment() / 8) {
422       // We need a packed struct.
423       Packed = true;
424       Align = 1;
425     }
426   }
427   if (!Align) {
428     assert(HasOnlyZeroSizedBitFields &&
429            "0-align record did not have all zero-sized bit-fields!");
430     Align = 1;
431   }
432 
433   // Append tail padding.
434   if (Layout.getSize() / 8 > Size)
435     AppendPadding(Layout.getSize() / 8, Align);
436 }
437 
438 void CGRecordLayoutBuilder::LayoutBases(const CXXRecordDecl *RD,
439                                         const ASTRecordLayout &Layout) {
440   // Check if we need to add a vtable pointer.
441   if (RD->isDynamicClass() && !Layout.getPrimaryBase()) {
442     const llvm::Type *FunctionType =
443       llvm::FunctionType::get(llvm::Type::getInt32Ty(Types.getLLVMContext()),
444                               /*isVarArg=*/true);
445     const llvm::Type *VTableTy = FunctionType->getPointerTo();
446 
447     assert(NextFieldOffsetInBytes == 0 &&
448            "VTable pointer must come first!");
449     AppendField(NextFieldOffsetInBytes, VTableTy->getPointerTo());
450   }
451 }
452 
453 bool CGRecordLayoutBuilder::LayoutFields(const RecordDecl *D) {
454   assert(!D->isUnion() && "Can't call LayoutFields on a union!");
455   assert(Alignment && "Did not set alignment!");
456 
457   const ASTRecordLayout &Layout = Types.getContext().getASTRecordLayout(D);
458 
459   if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
460     LayoutBases(RD, Layout);
461 
462   unsigned FieldNo = 0;
463 
464   for (RecordDecl::field_iterator Field = D->field_begin(),
465        FieldEnd = D->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
466     if (!LayoutField(*Field, Layout.getFieldOffset(FieldNo))) {
467       assert(!Packed &&
468              "Could not layout fields even with a packed LLVM struct!");
469       return false;
470     }
471   }
472 
473   // Append tail padding if necessary.
474   AppendTailPadding(Layout.getSize());
475 
476   return true;
477 }
478 
479 void CGRecordLayoutBuilder::AppendTailPadding(uint64_t RecordSize) {
480   assert(RecordSize % 8 == 0 && "Invalid record size!");
481 
482   uint64_t RecordSizeInBytes = RecordSize / 8;
483   assert(NextFieldOffsetInBytes <= RecordSizeInBytes && "Size mismatch!");
484 
485   uint64_t AlignedNextFieldOffset =
486     llvm::RoundUpToAlignment(NextFieldOffsetInBytes, AlignmentAsLLVMStruct);
487 
488   if (AlignedNextFieldOffset == RecordSizeInBytes) {
489     // We don't need any padding.
490     return;
491   }
492 
493   unsigned NumPadBytes = RecordSizeInBytes - NextFieldOffsetInBytes;
494   AppendBytes(NumPadBytes);
495 }
496 
497 void CGRecordLayoutBuilder::AppendField(uint64_t FieldOffsetInBytes,
498                                         const llvm::Type *FieldTy) {
499   AlignmentAsLLVMStruct = std::max(AlignmentAsLLVMStruct,
500                                    getTypeAlignment(FieldTy));
501 
502   uint64_t FieldSizeInBytes = Types.getTargetData().getTypeAllocSize(FieldTy);
503 
504   FieldTypes.push_back(FieldTy);
505 
506   NextFieldOffsetInBytes = FieldOffsetInBytes + FieldSizeInBytes;
507   BitsAvailableInLastField = 0;
508 }
509 
510 void CGRecordLayoutBuilder::AppendPadding(uint64_t FieldOffsetInBytes,
511                                           unsigned FieldAlignment) {
512   assert(NextFieldOffsetInBytes <= FieldOffsetInBytes &&
513          "Incorrect field layout!");
514 
515   // Round up the field offset to the alignment of the field type.
516   uint64_t AlignedNextFieldOffsetInBytes =
517     llvm::RoundUpToAlignment(NextFieldOffsetInBytes, FieldAlignment);
518 
519   if (AlignedNextFieldOffsetInBytes < FieldOffsetInBytes) {
520     // Even with alignment, the field offset is not at the right place,
521     // insert padding.
522     uint64_t PaddingInBytes = FieldOffsetInBytes - NextFieldOffsetInBytes;
523 
524     AppendBytes(PaddingInBytes);
525   }
526 }
527 
528 void CGRecordLayoutBuilder::AppendBytes(uint64_t NumBytes) {
529   if (NumBytes == 0)
530     return;
531 
532   const llvm::Type *Ty = llvm::Type::getInt8Ty(Types.getLLVMContext());
533   if (NumBytes > 1)
534     Ty = llvm::ArrayType::get(Ty, NumBytes);
535 
536   // Append the padding field
537   AppendField(NextFieldOffsetInBytes, Ty);
538 }
539 
540 unsigned CGRecordLayoutBuilder::getTypeAlignment(const llvm::Type *Ty) const {
541   if (Packed)
542     return 1;
543 
544   return Types.getTargetData().getABITypeAlignment(Ty);
545 }
546 
547 void CGRecordLayoutBuilder::CheckForPointerToDataMember(QualType T) {
548   // This record already contains a member pointer.
549   if (ContainsPointerToDataMember)
550     return;
551 
552   // Can only have member pointers if we're compiling C++.
553   if (!Types.getContext().getLangOptions().CPlusPlus)
554     return;
555 
556   T = Types.getContext().getBaseElementType(T);
557 
558   if (const MemberPointerType *MPT = T->getAs<MemberPointerType>()) {
559     if (!MPT->getPointeeType()->isFunctionType()) {
560       // We have a pointer to data member.
561       ContainsPointerToDataMember = true;
562     }
563   } else if (const RecordType *RT = T->getAs<RecordType>()) {
564     const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
565 
566     // FIXME: It would be better if there was a way to explicitly compute the
567     // record layout instead of converting to a type.
568     Types.ConvertTagDeclType(RD);
569 
570     const CGRecordLayout &Layout = Types.getCGRecordLayout(RD);
571 
572     if (Layout.containsPointerToDataMember())
573       ContainsPointerToDataMember = true;
574   }
575 }
576 
577 CGRecordLayout *CodeGenTypes::ComputeRecordLayout(const RecordDecl *D) {
578   CGRecordLayoutBuilder Builder(*this);
579 
580   Builder.Layout(D);
581 
582   const llvm::Type *Ty = llvm::StructType::get(getLLVMContext(),
583                                                Builder.FieldTypes,
584                                                Builder.Packed);
585 
586   CGRecordLayout *RL =
587     new CGRecordLayout(Ty, Builder.ContainsPointerToDataMember);
588 
589   // Add all the field numbers.
590   for (unsigned i = 0, e = Builder.LLVMFields.size(); i != e; ++i)
591     RL->FieldInfo.insert(Builder.LLVMFields[i]);
592 
593   // Add bitfield info.
594   for (unsigned i = 0, e = Builder.LLVMBitFields.size(); i != e; ++i)
595     RL->BitFields.insert(Builder.LLVMBitFields[i]);
596 
597   // Dump the layout, if requested.
598   if (getContext().getLangOptions().DumpRecordLayouts) {
599     llvm::errs() << "\n*** Dumping IRgen Record Layout\n";
600     llvm::errs() << "Record: ";
601     D->dump();
602     llvm::errs() << "\nLayout: ";
603     RL->dump();
604   }
605 
606 #ifndef NDEBUG
607   // Verify that the computed LLVM struct size matches the AST layout size.
608   uint64_t TypeSizeInBits = getContext().getASTRecordLayout(D).getSize();
609   assert(TypeSizeInBits == getTargetData().getTypeAllocSizeInBits(Ty) &&
610          "Type size mismatch!");
611 
612   // Verify that the LLVM and AST field offsets agree.
613   const llvm::StructType *ST =
614     dyn_cast<llvm::StructType>(RL->getLLVMType());
615   const llvm::StructLayout *SL = getTargetData().getStructLayout(ST);
616 
617   const ASTRecordLayout &AST_RL = getContext().getASTRecordLayout(D);
618   RecordDecl::field_iterator it = D->field_begin();
619   for (unsigned i = 0, e = AST_RL.getFieldCount(); i != e; ++i, ++it) {
620     const FieldDecl *FD = *it;
621 
622     // For non-bit-fields, just check that the LLVM struct offset matches the
623     // AST offset.
624     if (!FD->isBitField()) {
625       unsigned FieldNo = RL->getLLVMFieldNo(FD);
626       assert(AST_RL.getFieldOffset(i) == SL->getElementOffsetInBits(FieldNo) &&
627              "Invalid field offset!");
628       continue;
629     }
630 
631     // Ignore unnamed bit-fields.
632     if (!FD->getDeclName())
633       continue;
634 
635     const CGBitFieldInfo &Info = RL->getBitFieldInfo(FD);
636     for (unsigned i = 0, e = Info.getNumComponents(); i != e; ++i) {
637       const CGBitFieldInfo::AccessInfo &AI = Info.getComponent(i);
638 
639       // Verify that every component access is within the structure.
640       uint64_t FieldOffset = SL->getElementOffsetInBits(AI.FieldIndex);
641       uint64_t AccessBitOffset = FieldOffset + AI.FieldByteOffset * 8;
642       assert(AccessBitOffset + AI.AccessWidth <= TypeSizeInBits &&
643              "Invalid bit-field access (out of range)!");
644     }
645   }
646 #endif
647 
648   return RL;
649 }
650 
651 void CGRecordLayout::print(llvm::raw_ostream &OS) const {
652   OS << "<CGRecordLayout\n";
653   OS << "  LLVMType:" << *LLVMType << "\n";
654   OS << "  ContainsPointerToDataMember:" << ContainsPointerToDataMember << "\n";
655   OS << "  BitFields:[\n";
656 
657   // Print bit-field infos in declaration order.
658   std::vector<std::pair<unsigned, const CGBitFieldInfo*> > BFIs;
659   for (llvm::DenseMap<const FieldDecl*, CGBitFieldInfo>::const_iterator
660          it = BitFields.begin(), ie = BitFields.end();
661        it != ie; ++it) {
662     const RecordDecl *RD = it->first->getParent();
663     unsigned Index = 0;
664     for (RecordDecl::field_iterator
665            it2 = RD->field_begin(); *it2 != it->first; ++it2)
666       ++Index;
667     BFIs.push_back(std::make_pair(Index, &it->second));
668   }
669   llvm::array_pod_sort(BFIs.begin(), BFIs.end());
670   for (unsigned i = 0, e = BFIs.size(); i != e; ++i) {
671     OS.indent(4);
672     BFIs[i].second->print(OS);
673     OS << "\n";
674   }
675 
676   OS << "]>\n";
677 }
678 
679 void CGRecordLayout::dump() const {
680   print(llvm::errs());
681 }
682 
683 void CGBitFieldInfo::print(llvm::raw_ostream &OS) const {
684   OS << "<CGBitFieldInfo";
685   OS << " Size:" << Size;
686   OS << " IsSigned:" << IsSigned << "\n";
687 
688   OS.indent(4 + strlen("<CGBitFieldInfo"));
689   OS << " NumComponents:" << getNumComponents();
690   OS << " Components: [";
691   if (getNumComponents()) {
692     OS << "\n";
693     for (unsigned i = 0, e = getNumComponents(); i != e; ++i) {
694       const AccessInfo &AI = getComponent(i);
695       OS.indent(8);
696       OS << "<AccessInfo"
697          << " FieldIndex:" << AI.FieldIndex
698          << " FieldByteOffset:" << AI.FieldByteOffset
699          << " FieldBitStart:" << AI.FieldBitStart
700          << " AccessWidth:" << AI.AccessWidth << "\n";
701       OS.indent(8 + strlen("<AccessInfo"));
702       OS << " AccessAlignment:" << AI.AccessAlignment
703          << " TargetBitOffset:" << AI.TargetBitOffset
704          << " TargetBitWidth:" << AI.TargetBitWidth
705          << ">\n";
706     }
707     OS.indent(4);
708   }
709   OS << "]>";
710 }
711 
712 void CGBitFieldInfo::dump() const {
713   print(llvm::errs());
714 }
715