CGRecordLayoutBuilder.cpp revision 200583
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  BitsAvailableInLastField =
92    NextFieldOffsetInBytes * 8 - (FieldOffset + FieldSize);
93}
94
95bool CGRecordLayoutBuilder::LayoutField(const FieldDecl *D,
96                                        uint64_t FieldOffset) {
97  // If the field is packed, then we need a packed struct.
98  if (!Packed && D->hasAttr<PackedAttr>())
99    return false;
100
101  if (D->isBitField()) {
102    // We must use packed structs for unnamed bit fields since they
103    // don't affect the struct alignment.
104    if (!Packed && !D->getDeclName())
105      return false;
106
107    LayoutBitField(D, FieldOffset);
108    return true;
109  }
110
111  assert(FieldOffset % 8 == 0 && "FieldOffset is not on a byte boundary!");
112  uint64_t FieldOffsetInBytes = FieldOffset / 8;
113
114  const llvm::Type *Ty = Types.ConvertTypeForMemRecursive(D->getType());
115  unsigned TypeAlignment = getTypeAlignment(Ty);
116
117  // If the type alignment is larger then the struct alignment, we must use
118  // a packed struct.
119  if (TypeAlignment > Alignment) {
120    assert(!Packed && "Alignment is wrong even with packed struct!");
121    return false;
122  }
123
124  if (const RecordType *RT = D->getType()->getAs<RecordType>()) {
125    const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
126    if (const PragmaPackAttr *PPA = RD->getAttr<PragmaPackAttr>()) {
127      if (PPA->getAlignment() != TypeAlignment * 8 && !Packed)
128        return false;
129    }
130  }
131
132  // Round up the field offset to the alignment of the field type.
133  uint64_t AlignedNextFieldOffsetInBytes =
134    llvm::RoundUpToAlignment(NextFieldOffsetInBytes, TypeAlignment);
135
136  if (FieldOffsetInBytes < AlignedNextFieldOffsetInBytes) {
137    assert(!Packed && "Could not place field even with packed struct!");
138    return false;
139  }
140
141  if (AlignedNextFieldOffsetInBytes < FieldOffsetInBytes) {
142    // Even with alignment, the field offset is not at the right place,
143    // insert padding.
144    uint64_t PaddingInBytes = FieldOffsetInBytes - NextFieldOffsetInBytes;
145
146    AppendBytes(PaddingInBytes);
147  }
148
149  // Now append the field.
150  LLVMFields.push_back(LLVMFieldInfo(D, FieldTypes.size()));
151  AppendField(FieldOffsetInBytes, Ty);
152
153  return true;
154}
155
156void CGRecordLayoutBuilder::LayoutUnion(const RecordDecl *D) {
157  assert(D->isUnion() && "Can't call LayoutUnion on a non-union record!");
158
159  const ASTRecordLayout &Layout = Types.getContext().getASTRecordLayout(D);
160
161  const llvm::Type *Ty = 0;
162  uint64_t Size = 0;
163  unsigned Align = 0;
164
165  unsigned FieldNo = 0;
166  for (RecordDecl::field_iterator Field = D->field_begin(),
167       FieldEnd = D->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
168    assert(Layout.getFieldOffset(FieldNo) == 0 &&
169          "Union field offset did not start at the beginning of record!");
170
171    if (Field->isBitField()) {
172      uint64_t FieldSize =
173        Field->getBitWidth()->EvaluateAsInt(Types.getContext()).getZExtValue();
174
175      // Ignore zero sized bit fields.
176      if (FieldSize == 0)
177        continue;
178
179      // Add the bit field info.
180      Types.addBitFieldInfo(*Field, 0, 0, FieldSize);
181    } else
182      Types.addFieldInfo(*Field, 0);
183
184    const llvm::Type *FieldTy =
185      Types.ConvertTypeForMemRecursive(Field->getType());
186    unsigned FieldAlign = Types.getTargetData().getABITypeAlignment(FieldTy);
187    uint64_t FieldSize = Types.getTargetData().getTypeAllocSize(FieldTy);
188
189    if (FieldAlign < Align)
190      continue;
191
192    if (FieldAlign > Align || FieldSize > Size) {
193      Ty = FieldTy;
194      Align = FieldAlign;
195      Size = FieldSize;
196    }
197  }
198
199  // Now add our field.
200  if (Ty) {
201    AppendField(0, Ty);
202
203    if (getTypeAlignment(Ty) > Layout.getAlignment() / 8) {
204      // We need a packed struct.
205      Packed = true;
206      Align = 1;
207    }
208  }
209  if (!Align) {
210    assert((D->field_begin() == D->field_end()) && "LayoutUnion - Align 0");
211    Align = 1;
212  }
213
214  // Append tail padding.
215  if (Layout.getSize() / 8 > Size)
216    AppendPadding(Layout.getSize() / 8, Align);
217}
218
219bool CGRecordLayoutBuilder::LayoutFields(const RecordDecl *D) {
220  assert(!D->isUnion() && "Can't call LayoutFields on a union!");
221  assert(Alignment && "Did not set alignment!");
222
223  const ASTRecordLayout &Layout = Types.getContext().getASTRecordLayout(D);
224
225  unsigned FieldNo = 0;
226
227  for (RecordDecl::field_iterator Field = D->field_begin(),
228       FieldEnd = D->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
229    if (!LayoutField(*Field, Layout.getFieldOffset(FieldNo))) {
230      assert(!Packed &&
231             "Could not layout fields even with a packed LLVM struct!");
232      return false;
233    }
234  }
235
236  // Append tail padding if necessary.
237  AppendTailPadding(Layout.getSize());
238
239  return true;
240}
241
242void CGRecordLayoutBuilder::AppendTailPadding(uint64_t RecordSize) {
243  assert(RecordSize % 8 == 0 && "Invalid record size!");
244
245  uint64_t RecordSizeInBytes = RecordSize / 8;
246  assert(NextFieldOffsetInBytes <= RecordSizeInBytes && "Size mismatch!");
247
248  uint64_t AlignedNextFieldOffset =
249    llvm::RoundUpToAlignment(NextFieldOffsetInBytes, AlignmentAsLLVMStruct);
250
251  if (AlignedNextFieldOffset == RecordSizeInBytes) {
252    // We don't need any padding.
253    return;
254  }
255
256  unsigned NumPadBytes = RecordSizeInBytes - NextFieldOffsetInBytes;
257  AppendBytes(NumPadBytes);
258}
259
260void CGRecordLayoutBuilder::AppendField(uint64_t FieldOffsetInBytes,
261                                        const llvm::Type *FieldTy) {
262  AlignmentAsLLVMStruct = std::max(AlignmentAsLLVMStruct,
263                                   getTypeAlignment(FieldTy));
264
265  uint64_t FieldSizeInBytes = getTypeSizeInBytes(FieldTy);
266
267  FieldTypes.push_back(FieldTy);
268
269  NextFieldOffsetInBytes = FieldOffsetInBytes + FieldSizeInBytes;
270  BitsAvailableInLastField = 0;
271}
272
273void
274CGRecordLayoutBuilder::AppendPadding(uint64_t FieldOffsetInBytes,
275                                     const llvm::Type *FieldTy) {
276  AppendPadding(FieldOffsetInBytes, getTypeAlignment(FieldTy));
277}
278
279void CGRecordLayoutBuilder::AppendPadding(uint64_t FieldOffsetInBytes,
280                                          unsigned FieldAlignment) {
281  assert(NextFieldOffsetInBytes <= FieldOffsetInBytes &&
282         "Incorrect field layout!");
283
284  // Round up the field offset to the alignment of the field type.
285  uint64_t AlignedNextFieldOffsetInBytes =
286    llvm::RoundUpToAlignment(NextFieldOffsetInBytes, FieldAlignment);
287
288  if (AlignedNextFieldOffsetInBytes < FieldOffsetInBytes) {
289    // Even with alignment, the field offset is not at the right place,
290    // insert padding.
291    uint64_t PaddingInBytes = FieldOffsetInBytes - NextFieldOffsetInBytes;
292
293    AppendBytes(PaddingInBytes);
294  }
295}
296
297void CGRecordLayoutBuilder::AppendBytes(uint64_t NumBytes) {
298  if (NumBytes == 0)
299    return;
300
301  const llvm::Type *Ty = llvm::Type::getInt8Ty(Types.getLLVMContext());
302  if (NumBytes > 1)
303    Ty = llvm::ArrayType::get(Ty, NumBytes);
304
305  // Append the padding field
306  AppendField(NextFieldOffsetInBytes, Ty);
307}
308
309unsigned CGRecordLayoutBuilder::getTypeAlignment(const llvm::Type *Ty) const {
310  if (Packed)
311    return 1;
312
313  return Types.getTargetData().getABITypeAlignment(Ty);
314}
315
316uint64_t CGRecordLayoutBuilder::getTypeSizeInBytes(const llvm::Type *Ty) const {
317  return Types.getTargetData().getTypeAllocSize(Ty);
318}
319
320void CGRecordLayoutBuilder::CheckForMemberPointer(const FieldDecl *FD) {
321  // This record already contains a member pointer.
322  if (ContainsMemberPointer)
323    return;
324
325  // Can only have member pointers if we're compiling C++.
326  if (!Types.getContext().getLangOptions().CPlusPlus)
327    return;
328
329  QualType Ty = FD->getType();
330
331  if (Ty->isMemberPointerType()) {
332    // We have a member pointer!
333    ContainsMemberPointer = true;
334    return;
335  }
336
337}
338
339CGRecordLayout *
340CGRecordLayoutBuilder::ComputeLayout(CodeGenTypes &Types,
341                                     const RecordDecl *D) {
342  CGRecordLayoutBuilder Builder(Types);
343
344  Builder.Layout(D);
345
346  const llvm::Type *Ty = llvm::StructType::get(Types.getLLVMContext(),
347                                               Builder.FieldTypes,
348                                               Builder.Packed);
349  assert(Types.getContext().getASTRecordLayout(D).getSize() / 8 ==
350         Types.getTargetData().getTypeAllocSize(Ty) &&
351         "Type size mismatch!");
352
353  // Add all the field numbers.
354  for (unsigned i = 0, e = Builder.LLVMFields.size(); i != e; ++i) {
355    const FieldDecl *FD = Builder.LLVMFields[i].first;
356    unsigned FieldNo = Builder.LLVMFields[i].second;
357
358    Types.addFieldInfo(FD, FieldNo);
359  }
360
361  // Add bitfield info.
362  for (unsigned i = 0, e = Builder.LLVMBitFields.size(); i != e; ++i) {
363    const LLVMBitFieldInfo &Info = Builder.LLVMBitFields[i];
364
365    Types.addBitFieldInfo(Info.FD, Info.FieldNo, Info.Start, Info.Size);
366  }
367
368  return new CGRecordLayout(Ty, Builder.ContainsMemberPointer);
369}
370