CGRecordLayoutBuilder.cpp revision d0eb3b93e89f0ab83a2305eb0ec42076f8d46142
1//===--- CGRecordLayoutBuilder.cpp - Record builder helper ------*- 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// This is a helper class used to build CGRecordLayout objects and LLVM types.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGRecordLayoutBuilder.h"
15
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/Attr.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/RecordLayout.h"
21#include "CodeGenTypes.h"
22#include "llvm/DerivedTypes.h"
23#include "llvm/Target/TargetData.h"
24
25
26using namespace clang;
27using namespace CodeGen;
28
29void CGRecordLayoutBuilder::Layout(const RecordDecl *D) {
30  Alignment = Types.getContext().getASTRecordLayout(D).getAlignment() / 8;
31  Packed = D->hasAttr<PackedAttr>();
32
33  if (D->isUnion()) {
34    LayoutUnion(D);
35    return;
36  }
37
38  if (LayoutFields(D))
39    return;
40
41  // We weren't able to layout the struct. Try again with a packed struct
42  Packed = true;
43  AlignmentAsLLVMStruct = 1;
44  NextFieldOffsetInBytes = 0;
45  FieldTypes.clear();
46  LLVMFields.clear();
47  LLVMBitFields.clear();
48
49  LayoutFields(D);
50}
51
52void CGRecordLayoutBuilder::LayoutBitField(const FieldDecl *D,
53                                           uint64_t FieldOffset) {
54  uint64_t FieldSize =
55    D->getBitWidth()->EvaluateAsInt(Types.getContext()).getZExtValue();
56
57  if (FieldSize == 0)
58    return;
59
60  uint64_t NextFieldOffset = NextFieldOffsetInBytes * 8;
61  unsigned NumBytesToAppend;
62
63  if (FieldOffset < NextFieldOffset) {
64    assert(BitsAvailableInLastField && "Bitfield size mismatch!");
65    assert(NextFieldOffsetInBytes && "Must have laid out at least one byte!");
66
67    // The bitfield begins in the previous bit-field.
68    NumBytesToAppend =
69      llvm::RoundUpToAlignment(FieldSize - BitsAvailableInLastField, 8) / 8;
70  } else {
71    assert(FieldOffset % 8 == 0 && "Field offset not aligned correctly");
72
73    // Append padding if necessary.
74    AppendBytes((FieldOffset - NextFieldOffset) / 8);
75
76    NumBytesToAppend =
77      llvm::RoundUpToAlignment(FieldSize, 8) / 8;
78
79    assert(NumBytesToAppend && "No bytes to append!");
80  }
81
82  const llvm::Type *Ty = Types.ConvertTypeForMemRecursive(D->getType());
83  uint64_t TypeSizeInBits = getTypeSizeInBytes(Ty) * 8;
84
85  LLVMBitFields.push_back(LLVMBitFieldInfo(D, FieldOffset / TypeSizeInBits,
86                                           FieldOffset % TypeSizeInBits,
87                                           FieldSize));
88
89  AppendBytes(NumBytesToAppend);
90
91  AlignmentAsLLVMStruct = std::max(AlignmentAsLLVMStruct, getTypeAlignment(Ty));
92
93  BitsAvailableInLastField =
94    NextFieldOffsetInBytes * 8 - (FieldOffset + FieldSize);
95}
96
97bool CGRecordLayoutBuilder::LayoutField(const FieldDecl *D,
98                                        uint64_t FieldOffset) {
99  // If the field is packed, then we need a packed struct.
100  if (!Packed && D->hasAttr<PackedAttr>())
101    return false;
102
103  if (D->isBitField()) {
104    // We must use packed structs for unnamed bit fields since they
105    // don't affect the struct alignment.
106    if (!Packed && !D->getDeclName())
107      return false;
108
109    LayoutBitField(D, FieldOffset);
110    return true;
111  }
112
113  assert(FieldOffset % 8 == 0 && "FieldOffset is not on a byte boundary!");
114  uint64_t FieldOffsetInBytes = FieldOffset / 8;
115
116  const llvm::Type *Ty = Types.ConvertTypeForMemRecursive(D->getType());
117  unsigned TypeAlignment = getTypeAlignment(Ty);
118
119  // If the type alignment is larger then the struct alignment, we must use
120  // a packed struct.
121  if (TypeAlignment > Alignment) {
122    assert(!Packed && "Alignment is wrong even with packed struct!");
123    return false;
124  }
125
126  if (const RecordType *RT = D->getType()->getAs<RecordType>()) {
127    const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
128    if (const PragmaPackAttr *PPA = RD->getAttr<PragmaPackAttr>()) {
129      if (PPA->getAlignment() != TypeAlignment * 8 && !Packed)
130        return false;
131    }
132  }
133
134  // Round up the field offset to the alignment of the field type.
135  uint64_t AlignedNextFieldOffsetInBytes =
136    llvm::RoundUpToAlignment(NextFieldOffsetInBytes, TypeAlignment);
137
138  if (FieldOffsetInBytes < AlignedNextFieldOffsetInBytes) {
139    assert(!Packed && "Could not place field even with packed struct!");
140    return false;
141  }
142
143  if (AlignedNextFieldOffsetInBytes < FieldOffsetInBytes) {
144    // Even with alignment, the field offset is not at the right place,
145    // insert padding.
146    uint64_t PaddingInBytes = FieldOffsetInBytes - NextFieldOffsetInBytes;
147
148    AppendBytes(PaddingInBytes);
149  }
150
151  // Now append the field.
152  LLVMFields.push_back(LLVMFieldInfo(D, FieldTypes.size()));
153  AppendField(FieldOffsetInBytes, Ty);
154
155  return true;
156}
157
158void CGRecordLayoutBuilder::LayoutUnion(const RecordDecl *D) {
159  assert(D->isUnion() && "Can't call LayoutUnion on a non-union record!");
160
161  const ASTRecordLayout &Layout = Types.getContext().getASTRecordLayout(D);
162
163  const llvm::Type *Ty = 0;
164  uint64_t Size = 0;
165  unsigned Align = 0;
166
167  unsigned FieldNo = 0;
168  for (RecordDecl::field_iterator Field = D->field_begin(),
169       FieldEnd = D->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
170    assert(Layout.getFieldOffset(FieldNo) == 0 &&
171          "Union field offset did not start at the beginning of record!");
172
173    if (Field->isBitField()) {
174      uint64_t FieldSize =
175        Field->getBitWidth()->EvaluateAsInt(Types.getContext()).getZExtValue();
176
177      // Ignore zero sized bit fields.
178      if (FieldSize == 0)
179        continue;
180
181      // Add the bit field info.
182      Types.addBitFieldInfo(*Field, 0, 0, FieldSize);
183    } else
184      Types.addFieldInfo(*Field, 0);
185
186    const llvm::Type *FieldTy =
187      Types.ConvertTypeForMemRecursive(Field->getType());
188    unsigned FieldAlign = Types.getTargetData().getABITypeAlignment(FieldTy);
189    uint64_t FieldSize = Types.getTargetData().getTypeAllocSize(FieldTy);
190
191    if (FieldAlign < Align)
192      continue;
193
194    if (FieldAlign > Align || FieldSize > Size) {
195      Ty = FieldTy;
196      Align = FieldAlign;
197      Size = FieldSize;
198    }
199  }
200
201  // Now add our field.
202  if (Ty)
203    AppendField(0, Ty);
204
205  // Append tail padding.
206  if (Layout.getSize() / 8 > Size)
207    AppendPadding(Layout.getSize() / 8, Align);
208}
209
210bool CGRecordLayoutBuilder::LayoutFields(const RecordDecl *D) {
211  assert(!D->isUnion() && "Can't call LayoutFields on a union!");
212  assert(Alignment && "Did not set alignment!");
213
214  const ASTRecordLayout &Layout = Types.getContext().getASTRecordLayout(D);
215
216  unsigned FieldNo = 0;
217
218  for (RecordDecl::field_iterator Field = D->field_begin(),
219       FieldEnd = D->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
220    if (!LayoutField(*Field, Layout.getFieldOffset(FieldNo))) {
221      assert(!Packed &&
222             "Could not layout fields even with a packed LLVM struct!");
223      return false;
224    }
225  }
226
227  // Append tail padding if necessary.
228  AppendTailPadding(Layout.getSize());
229
230  return true;
231}
232
233void CGRecordLayoutBuilder::AppendTailPadding(uint64_t RecordSize) {
234  assert(RecordSize % 8 == 0 && "Invalid record size!");
235
236  uint64_t RecordSizeInBytes = RecordSize / 8;
237  assert(NextFieldOffsetInBytes <= RecordSizeInBytes && "Size mismatch!");
238
239  unsigned NumPadBytes = RecordSizeInBytes - NextFieldOffsetInBytes;
240  AppendBytes(NumPadBytes);
241}
242
243void CGRecordLayoutBuilder::AppendField(uint64_t FieldOffsetInBytes,
244                                        const llvm::Type *FieldTy) {
245  AlignmentAsLLVMStruct = std::max(AlignmentAsLLVMStruct,
246                                   getTypeAlignment(FieldTy));
247
248  uint64_t FieldSizeInBytes = getTypeSizeInBytes(FieldTy);
249
250  FieldTypes.push_back(FieldTy);
251
252  NextFieldOffsetInBytes = FieldOffsetInBytes + FieldSizeInBytes;
253  BitsAvailableInLastField = 0;
254}
255
256void
257CGRecordLayoutBuilder::AppendPadding(uint64_t FieldOffsetInBytes,
258                                     const llvm::Type *FieldTy) {
259  AppendPadding(FieldOffsetInBytes, getTypeAlignment(FieldTy));
260}
261
262void CGRecordLayoutBuilder::AppendPadding(uint64_t FieldOffsetInBytes,
263                                          unsigned FieldAlignment) {
264  assert(NextFieldOffsetInBytes <= FieldOffsetInBytes &&
265         "Incorrect field layout!");
266
267  // Round up the field offset to the alignment of the field type.
268  uint64_t AlignedNextFieldOffsetInBytes =
269    llvm::RoundUpToAlignment(NextFieldOffsetInBytes, FieldAlignment);
270
271  if (AlignedNextFieldOffsetInBytes < FieldOffsetInBytes) {
272    // Even with alignment, the field offset is not at the right place,
273    // insert padding.
274    uint64_t PaddingInBytes = FieldOffsetInBytes - NextFieldOffsetInBytes;
275
276    AppendBytes(PaddingInBytes);
277  }
278}
279
280void CGRecordLayoutBuilder::AppendBytes(uint64_t NumBytes) {
281  if (NumBytes == 0)
282    return;
283
284  const llvm::Type *Ty = llvm::Type::getInt8Ty(Types.getLLVMContext());
285  if (NumBytes > 1)
286    Ty = llvm::ArrayType::get(Ty, NumBytes);
287
288  // Append the padding field
289  AppendField(NextFieldOffsetInBytes, Ty);
290}
291
292unsigned CGRecordLayoutBuilder::getTypeAlignment(const llvm::Type *Ty) const {
293  if (Packed)
294    return 1;
295
296  return Types.getTargetData().getABITypeAlignment(Ty);
297}
298
299uint64_t CGRecordLayoutBuilder::getTypeSizeInBytes(const llvm::Type *Ty) const {
300  return Types.getTargetData().getTypeAllocSize(Ty);
301}
302
303void CGRecordLayoutBuilder::CheckForMemberPointer(const FieldDecl *FD) {
304  // This record already contains a member pointer.
305  if (ContainsMemberPointer)
306    return;
307
308  // Can only have member pointers if we're compiling C++.
309  if (!Types.getContext().getLangOptions().CPlusPlus)
310    return;
311
312  QualType Ty = FD->getType();
313
314  if (Ty->isMemberPointerType()) {
315    // We have a member pointer!
316    ContainsMemberPointer = true;
317    return;
318  }
319
320}
321
322CGRecordLayout *
323CGRecordLayoutBuilder::ComputeLayout(CodeGenTypes &Types,
324                                     const RecordDecl *D) {
325  CGRecordLayoutBuilder Builder(Types);
326
327  Builder.Layout(D);
328
329  const llvm::Type *Ty = llvm::StructType::get(Types.getLLVMContext(),
330                                               Builder.FieldTypes,
331                                               Builder.Packed);
332  assert(Types.getContext().getASTRecordLayout(D).getSize() / 8 ==
333         Types.getTargetData().getTypeAllocSize(Ty) &&
334         "Type size mismatch!");
335
336  // Add all the field numbers.
337  for (unsigned i = 0, e = Builder.LLVMFields.size(); i != e; ++i) {
338    const FieldDecl *FD = Builder.LLVMFields[i].first;
339    unsigned FieldNo = Builder.LLVMFields[i].second;
340
341    Types.addFieldInfo(FD, FieldNo);
342  }
343
344  // Add bitfield info.
345  for (unsigned i = 0, e = Builder.LLVMBitFields.size(); i != e; ++i) {
346    const LLVMBitFieldInfo &Info = Builder.LLVMBitFields[i];
347
348    Types.addBitFieldInfo(Info.FD, Info.FieldNo, Info.Start, Info.Size);
349  }
350
351  return new CGRecordLayout(Ty, Builder.ContainsMemberPointer);
352}
353