blob: 17c5640c643aa76a4a9d19ded3c1a23974ee0728 [file] [log] [blame]
Daniel Dunbar270e2032010-03-31 00:11:27 +00001//===--- CGRecordLayoutBuilder.cpp - CGRecordLayout builder ----*- C++ -*-===//
Anders Carlsson45372a62009-07-23 03:17:50 +00002//
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//
Daniel Dunbar270e2032010-03-31 00:11:27 +000010// Builder implementation for CGRecordLayout objects.
Anders Carlsson45372a62009-07-23 03:17:50 +000011//
12//===----------------------------------------------------------------------===//
13
Daniel Dunbar2924ade2010-03-30 22:26:10 +000014#include "CGRecordLayout.h"
Anders Carlsson45372a62009-07-23 03:17:50 +000015#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"
Daniel Dunbar93c62962010-04-12 18:14:18 +000022#include "llvm/Type.h"
Daniel Dunbar3b2ae7a2010-04-21 19:10:49 +000023#include "llvm/Support/Debug.h"
Daniel Dunbar93c62962010-04-12 18:14:18 +000024#include "llvm/Support/raw_ostream.h"
Anders Carlsson45372a62009-07-23 03:17:50 +000025#include "llvm/Target/TargetData.h"
Anders Carlsson45372a62009-07-23 03:17:50 +000026using namespace clang;
27using namespace CodeGen;
28
Daniel Dunbar270e2032010-03-31 00:11:27 +000029namespace clang {
30namespace CodeGen {
31
32class CGRecordLayoutBuilder {
33public:
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.
Daniel Dunbarc7a984a2010-04-06 01:07:41 +000042 typedef std::pair<const FieldDecl *, CGBitFieldInfo> LLVMBitFieldInfo;
Daniel Dunbar270e2032010-03-31 00:11:27 +000043 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
53private:
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
Anders Carlsson86664462010-04-17 20:49:27 +000072 /// 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
Daniel Dunbar270e2032010-03-31 00:11:27 +000077 /// 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
Daniel Dunbar270e2032010-03-31 00:11:27 +000097 /// 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;
Daniel Dunbar270e2032010-03-31 00:11:27 +0000109
110 /// CheckForPointerToDataMember - Check if the given type contains a pointer
111 /// to data member.
112 void CheckForPointerToDataMember(QualType T);
113
114public:
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
Anders Carlsson45372a62009-07-23 03:17:50 +0000127void CGRecordLayoutBuilder::Layout(const RecordDecl *D) {
Anders Carlssona5dd7222009-08-08 19:38:24 +0000128 Alignment = Types.getContext().getASTRecordLayout(D).getAlignment() / 8;
Anders Carlssond0eb3b92009-09-02 17:51:33 +0000129 Packed = D->hasAttr<PackedAttr>();
Anders Carlssona5dd7222009-08-08 19:38:24 +0000130
Anders Carlsson5a6e3982009-07-23 03:43:54 +0000131 if (D->isUnion()) {
132 LayoutUnion(D);
133 return;
134 }
Anders Carlssona860e752009-08-08 18:23:56 +0000135
Anders Carlsson45372a62009-07-23 03:17:50 +0000136 if (LayoutFields(D))
137 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000138
Anders Carlsson45372a62009-07-23 03:17:50 +0000139 // We weren't able to layout the struct. Try again with a packed struct
Anders Carlsson4b5584b2009-07-23 17:24:40 +0000140 Packed = true;
Anders Carlsson45372a62009-07-23 03:17:50 +0000141 AlignmentAsLLVMStruct = 1;
Anders Carlssonc2cc1d52009-07-28 17:56:36 +0000142 NextFieldOffsetInBytes = 0;
Anders Carlsson45372a62009-07-23 03:17:50 +0000143 FieldTypes.clear();
Anders Carlsson45372a62009-07-23 03:17:50 +0000144 LLVMFields.clear();
145 LLVMBitFields.clear();
Mike Stump1eb44332009-09-09 15:08:12 +0000146
Anders Carlsson45372a62009-07-23 03:17:50 +0000147 LayoutFields(D);
148}
149
Daniel Dunbar9b28daf2010-04-12 21:01:28 +0000150static CGBitFieldInfo ComputeBitFieldInfo(CodeGenTypes &Types,
151 const FieldDecl *FD,
152 uint64_t FieldOffset,
153 uint64_t FieldSize) {
Daniel Dunbare1467a42010-04-22 02:35:46 +0000154 const RecordDecl *RD = FD->getParent();
Daniel Dunbar89da8742010-04-22 03:17:04 +0000155 const ASTRecordLayout &RL = Types.getContext().getASTRecordLayout(RD);
156 uint64_t ContainingTypeSizeInBits = RL.getSize();
157 unsigned ContainingTypeAlign = RL.getAlignment();
Daniel Dunbare1467a42010-04-22 02:35:46 +0000158
Daniel Dunbar9b28daf2010-04-12 21:01:28 +0000159 const llvm::Type *Ty = Types.ConvertTypeForMemRecursive(FD->getType());
Daniel Dunbarab970f92010-04-13 20:58:55 +0000160 uint64_t TypeSizeInBytes = Types.getTargetData().getTypeAllocSize(Ty);
161 uint64_t TypeSizeInBits = TypeSizeInBytes * 8;
Daniel Dunbar9b28daf2010-04-12 21:01:28 +0000162
163 bool IsSigned = FD->getType()->isSignedIntegerType();
Daniel Dunbar9b28daf2010-04-12 21:01:28 +0000164
Anders Carlsson1c7658f2010-04-16 16:23:02 +0000165 if (FieldSize > TypeSizeInBits) {
Anders Carlsson6ba38152010-04-17 22:54:57 +0000166 // 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;
Anders Carlsson1c7658f2010-04-16 16:23:02 +0000176 }
177
Daniel Dunbare1467a42010-04-22 02:35:46 +0000178 // 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.
Anders Carlsson1c7658f2010-04-16 16:23:02 +0000191
Daniel Dunbare1467a42010-04-22 02:35:46 +0000192 // 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 % TypeSizeInBits);
Daniel Dunbar2df25692010-04-15 05:09:32 +0000195
Daniel Dunbare1467a42010-04-22 02:35:46 +0000196 while (AccessedTargetBits < FieldSize) {
197 // Check that we can access using a type of this size, without reading off
198 // the end of the structure. This can occur with packed structures and
199 // -fno-bitfield-type-align, for example.
200 if (AccessStart + AccessWidth > ContainingTypeSizeInBits) {
201 // If so, reduce access size to the next smaller power-of-two and retry.
202 AccessWidth >>= 1;
203 assert(AccessWidth >= 8 && "Cannot access under byte size!");
204 continue;
205 }
Daniel Dunbarab970f92010-04-13 20:58:55 +0000206
Daniel Dunbare1467a42010-04-22 02:35:46 +0000207 // Otherwise, add an access component.
Daniel Dunbarab970f92010-04-13 20:58:55 +0000208
Daniel Dunbare1467a42010-04-22 02:35:46 +0000209 // First, compute the bits inside this access which are part of the
210 // target. We are reading bits [AccessStart, AccessStart + AccessWidth); the
211 // intersection with [FieldOffset, FieldOffset + FieldSize) gives the bits
212 // in the target that we are reading.
213 uint64_t AccessBitsInFieldStart = std::max(AccessStart, FieldOffset);
214 uint64_t AccessBitsInFieldSize =
215 std::min(AccessWidth - (AccessBitsInFieldStart - AccessStart),
216 FieldSize - (AccessBitsInFieldStart-FieldOffset));
217
218 assert(NumComponents < 3 && "Unexpected number of components!");
219 CGBitFieldInfo::AccessInfo &AI = Components[NumComponents++];
220 AI.FieldIndex = 0;
221 // FIXME: We still follow the old access pattern of only using the field
222 // byte offset. We should switch this once we fix the struct layout to be
223 // pretty.
224 AI.FieldByteOffset = AccessStart / 8;
225 AI.FieldBitStart = AccessBitsInFieldStart - AccessStart;
226 AI.AccessWidth = AccessWidth;
Daniel Dunbar89da8742010-04-22 03:17:04 +0000227 AI.AccessAlignment = llvm::MinAlign(ContainingTypeAlign, AccessStart) / 8;
Daniel Dunbare1467a42010-04-22 02:35:46 +0000228 AI.TargetBitOffset = AccessedTargetBits;
229 AI.TargetBitWidth = AccessBitsInFieldSize;
230
231 AccessStart += AccessWidth;
232 AccessedTargetBits += AI.TargetBitWidth;
Daniel Dunbarab970f92010-04-13 20:58:55 +0000233 }
234
Daniel Dunbare1467a42010-04-22 02:35:46 +0000235 assert(AccessedTargetBits == FieldSize && "Invalid bit-field access!");
Daniel Dunbar2df25692010-04-15 05:09:32 +0000236 return CGBitFieldInfo(FieldSize, NumComponents, Components, IsSigned);
Daniel Dunbar9b28daf2010-04-12 21:01:28 +0000237}
238
Anders Carlsson45372a62009-07-23 03:17:50 +0000239void CGRecordLayoutBuilder::LayoutBitField(const FieldDecl *D,
240 uint64_t FieldOffset) {
Mike Stump1eb44332009-09-09 15:08:12 +0000241 uint64_t FieldSize =
Anders Carlsson45372a62009-07-23 03:17:50 +0000242 D->getBitWidth()->EvaluateAsInt(Types.getContext()).getZExtValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000243
Anders Carlsson45372a62009-07-23 03:17:50 +0000244 if (FieldSize == 0)
245 return;
246
Anders Carlssonc2cc1d52009-07-28 17:56:36 +0000247 uint64_t NextFieldOffset = NextFieldOffsetInBytes * 8;
Anders Carlsson45372a62009-07-23 03:17:50 +0000248 unsigned NumBytesToAppend;
Mike Stump1eb44332009-09-09 15:08:12 +0000249
Anders Carlsson45372a62009-07-23 03:17:50 +0000250 if (FieldOffset < NextFieldOffset) {
251 assert(BitsAvailableInLastField && "Bitfield size mismatch!");
Anders Carlssonc2cc1d52009-07-28 17:56:36 +0000252 assert(NextFieldOffsetInBytes && "Must have laid out at least one byte!");
Mike Stump1eb44332009-09-09 15:08:12 +0000253
Anders Carlsson45372a62009-07-23 03:17:50 +0000254 // The bitfield begins in the previous bit-field.
Mike Stump1eb44332009-09-09 15:08:12 +0000255 NumBytesToAppend =
Anders Carlsson45372a62009-07-23 03:17:50 +0000256 llvm::RoundUpToAlignment(FieldSize - BitsAvailableInLastField, 8) / 8;
257 } else {
258 assert(FieldOffset % 8 == 0 && "Field offset not aligned correctly");
259
260 // Append padding if necessary.
261 AppendBytes((FieldOffset - NextFieldOffset) / 8);
Mike Stump1eb44332009-09-09 15:08:12 +0000262
263 NumBytesToAppend =
Anders Carlsson45372a62009-07-23 03:17:50 +0000264 llvm::RoundUpToAlignment(FieldSize, 8) / 8;
Mike Stump1eb44332009-09-09 15:08:12 +0000265
Anders Carlsson45372a62009-07-23 03:17:50 +0000266 assert(NumBytesToAppend && "No bytes to append!");
267 }
268
Daniel Dunbar9b28daf2010-04-12 21:01:28 +0000269 // Add the bit field info.
270 LLVMBitFields.push_back(
271 LLVMBitFieldInfo(D, ComputeBitFieldInfo(Types, D, FieldOffset, FieldSize)));
Mike Stump1eb44332009-09-09 15:08:12 +0000272
Anders Carlsson45372a62009-07-23 03:17:50 +0000273 AppendBytes(NumBytesToAppend);
Mike Stump1eb44332009-09-09 15:08:12 +0000274
Mike Stump1eb44332009-09-09 15:08:12 +0000275 BitsAvailableInLastField =
Anders Carlssonc2cc1d52009-07-28 17:56:36 +0000276 NextFieldOffsetInBytes * 8 - (FieldOffset + FieldSize);
Anders Carlsson45372a62009-07-23 03:17:50 +0000277}
278
279bool CGRecordLayoutBuilder::LayoutField(const FieldDecl *D,
280 uint64_t FieldOffset) {
Anders Carlsson45372a62009-07-23 03:17:50 +0000281 // If the field is packed, then we need a packed struct.
Anders Carlssona860e752009-08-08 18:23:56 +0000282 if (!Packed && D->hasAttr<PackedAttr>())
Anders Carlsson45372a62009-07-23 03:17:50 +0000283 return false;
284
285 if (D->isBitField()) {
286 // We must use packed structs for unnamed bit fields since they
287 // don't affect the struct alignment.
Anders Carlsson4b5584b2009-07-23 17:24:40 +0000288 if (!Packed && !D->getDeclName())
Anders Carlsson45372a62009-07-23 03:17:50 +0000289 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000290
Anders Carlsson45372a62009-07-23 03:17:50 +0000291 LayoutBitField(D, FieldOffset);
292 return true;
293 }
Mike Stump1eb44332009-09-09 15:08:12 +0000294
Anders Carlsson2c12d032010-02-02 05:17:25 +0000295 // Check if we have a pointer to data member in this field.
296 CheckForPointerToDataMember(D->getType());
Daniel Dunbar270e2032010-03-31 00:11:27 +0000297
Anders Carlsson45372a62009-07-23 03:17:50 +0000298 assert(FieldOffset % 8 == 0 && "FieldOffset is not on a byte boundary!");
Anders Carlsson45372a62009-07-23 03:17:50 +0000299 uint64_t FieldOffsetInBytes = FieldOffset / 8;
Mike Stump1eb44332009-09-09 15:08:12 +0000300
Anders Carlssonde9f2c92009-08-04 16:29:15 +0000301 const llvm::Type *Ty = Types.ConvertTypeForMemRecursive(D->getType());
302 unsigned TypeAlignment = getTypeAlignment(Ty);
303
Anders Carlssona5dd7222009-08-08 19:38:24 +0000304 // If the type alignment is larger then the struct alignment, we must use
305 // a packed struct.
306 if (TypeAlignment > Alignment) {
307 assert(!Packed && "Alignment is wrong even with packed struct!");
308 return false;
309 }
Mike Stump1eb44332009-09-09 15:08:12 +0000310
Anders Carlssona5dd7222009-08-08 19:38:24 +0000311 if (const RecordType *RT = D->getType()->getAs<RecordType>()) {
312 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
313 if (const PragmaPackAttr *PPA = RD->getAttr<PragmaPackAttr>()) {
314 if (PPA->getAlignment() != TypeAlignment * 8 && !Packed)
315 return false;
316 }
317 }
318
Anders Carlssonde9f2c92009-08-04 16:29:15 +0000319 // Round up the field offset to the alignment of the field type.
Mike Stump1eb44332009-09-09 15:08:12 +0000320 uint64_t AlignedNextFieldOffsetInBytes =
Anders Carlssonde9f2c92009-08-04 16:29:15 +0000321 llvm::RoundUpToAlignment(NextFieldOffsetInBytes, TypeAlignment);
322
323 if (FieldOffsetInBytes < AlignedNextFieldOffsetInBytes) {
324 assert(!Packed && "Could not place field even with packed struct!");
325 return false;
326 }
Mike Stump1eb44332009-09-09 15:08:12 +0000327
Anders Carlssonde9f2c92009-08-04 16:29:15 +0000328 if (AlignedNextFieldOffsetInBytes < FieldOffsetInBytes) {
329 // Even with alignment, the field offset is not at the right place,
330 // insert padding.
331 uint64_t PaddingInBytes = FieldOffsetInBytes - NextFieldOffsetInBytes;
Mike Stump1eb44332009-09-09 15:08:12 +0000332
Anders Carlssonde9f2c92009-08-04 16:29:15 +0000333 AppendBytes(PaddingInBytes);
334 }
Mike Stump1eb44332009-09-09 15:08:12 +0000335
Anders Carlsson45372a62009-07-23 03:17:50 +0000336 // Now append the field.
337 LLVMFields.push_back(LLVMFieldInfo(D, FieldTypes.size()));
Anders Carlsson728d7cd2009-07-24 02:45:50 +0000338 AppendField(FieldOffsetInBytes, Ty);
Mike Stump1eb44332009-09-09 15:08:12 +0000339
Anders Carlsson45372a62009-07-23 03:17:50 +0000340 return true;
341}
342
Anders Carlsson86664462010-04-17 20:49:27 +0000343const llvm::Type *
344CGRecordLayoutBuilder::LayoutUnionField(const FieldDecl *Field,
345 const ASTRecordLayout &Layout) {
346 if (Field->isBitField()) {
347 uint64_t FieldSize =
348 Field->getBitWidth()->EvaluateAsInt(Types.getContext()).getZExtValue();
349
350 // Ignore zero sized bit fields.
351 if (FieldSize == 0)
352 return 0;
353
Daniel Dunbar8ab78a72010-04-20 17:52:30 +0000354 const llvm::Type *FieldTy = llvm::Type::getInt8Ty(Types.getLLVMContext());
355 unsigned NumBytesToAppend =
356 llvm::RoundUpToAlignment(FieldSize, 8) / 8;
Anders Carlssond62328e2010-04-17 21:04:52 +0000357
Daniel Dunbar8ab78a72010-04-20 17:52:30 +0000358 if (NumBytesToAppend > 1)
359 FieldTy = llvm::ArrayType::get(FieldTy, NumBytesToAppend);
Anders Carlssond62328e2010-04-17 21:04:52 +0000360
Anders Carlsson86664462010-04-17 20:49:27 +0000361 // Add the bit field info.
362 LLVMBitFields.push_back(
363 LLVMBitFieldInfo(Field, ComputeBitFieldInfo(Types, Field, 0, FieldSize)));
Anders Carlssond62328e2010-04-17 21:04:52 +0000364 return FieldTy;
Anders Carlsson86664462010-04-17 20:49:27 +0000365 }
Daniel Dunbar8ab78a72010-04-20 17:52:30 +0000366
Anders Carlsson86664462010-04-17 20:49:27 +0000367 // This is a regular union field.
368 LLVMFields.push_back(LLVMFieldInfo(Field, 0));
369 return Types.ConvertTypeForMemRecursive(Field->getType());
370}
371
Anders Carlsson5a6e3982009-07-23 03:43:54 +0000372void CGRecordLayoutBuilder::LayoutUnion(const RecordDecl *D) {
373 assert(D->isUnion() && "Can't call LayoutUnion on a non-union record!");
Mike Stump1eb44332009-09-09 15:08:12 +0000374
Anders Carlsson5a6e3982009-07-23 03:43:54 +0000375 const ASTRecordLayout &Layout = Types.getContext().getASTRecordLayout(D);
Mike Stump1eb44332009-09-09 15:08:12 +0000376
Anders Carlsson5a6e3982009-07-23 03:43:54 +0000377 const llvm::Type *Ty = 0;
378 uint64_t Size = 0;
379 unsigned Align = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000380
Anders Carlsson21fd7d72010-01-28 18:22:03 +0000381 bool HasOnlyZeroSizedBitFields = true;
Daniel Dunbar270e2032010-03-31 00:11:27 +0000382
Anders Carlsson5a6e3982009-07-23 03:43:54 +0000383 unsigned FieldNo = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000384 for (RecordDecl::field_iterator Field = D->field_begin(),
Anders Carlsson5a6e3982009-07-23 03:43:54 +0000385 FieldEnd = D->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
Mike Stump1eb44332009-09-09 15:08:12 +0000386 assert(Layout.getFieldOffset(FieldNo) == 0 &&
Anders Carlsson5a6e3982009-07-23 03:43:54 +0000387 "Union field offset did not start at the beginning of record!");
Anders Carlsson86664462010-04-17 20:49:27 +0000388 const llvm::Type *FieldTy = LayoutUnionField(*Field, Layout);
Anders Carlsson2cc8f172009-07-23 04:00:39 +0000389
Anders Carlsson86664462010-04-17 20:49:27 +0000390 if (!FieldTy)
391 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000392
Anders Carlsson21fd7d72010-01-28 18:22:03 +0000393 HasOnlyZeroSizedBitFields = false;
Daniel Dunbar270e2032010-03-31 00:11:27 +0000394
Anders Carlsson177d4d82009-07-23 21:52:03 +0000395 unsigned FieldAlign = Types.getTargetData().getABITypeAlignment(FieldTy);
396 uint64_t FieldSize = Types.getTargetData().getTypeAllocSize(FieldTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000397
Anders Carlsson5a6e3982009-07-23 03:43:54 +0000398 if (FieldAlign < Align)
399 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000400
Anders Carlsson5a6e3982009-07-23 03:43:54 +0000401 if (FieldAlign > Align || FieldSize > Size) {
402 Ty = FieldTy;
403 Align = FieldAlign;
404 Size = FieldSize;
405 }
406 }
Mike Stump1eb44332009-09-09 15:08:12 +0000407
Anders Carlsson5a6e3982009-07-23 03:43:54 +0000408 // Now add our field.
Anders Carlsson36620002009-09-03 22:56:02 +0000409 if (Ty) {
Anders Carlsson728d7cd2009-07-24 02:45:50 +0000410 AppendField(0, Ty);
Anders Carlsson36620002009-09-03 22:56:02 +0000411
412 if (getTypeAlignment(Ty) > Layout.getAlignment() / 8) {
413 // We need a packed struct.
414 Packed = true;
415 Align = 1;
416 }
417 }
Fariborz Jahaniane5041702009-11-06 20:47:40 +0000418 if (!Align) {
Anders Carlsson21fd7d72010-01-28 18:22:03 +0000419 assert(HasOnlyZeroSizedBitFields &&
420 "0-align record did not have all zero-sized bit-fields!");
Fariborz Jahaniane5041702009-11-06 20:47:40 +0000421 Align = 1;
422 }
Daniel Dunbar270e2032010-03-31 00:11:27 +0000423
Anders Carlsson5a6e3982009-07-23 03:43:54 +0000424 // Append tail padding.
425 if (Layout.getSize() / 8 > Size)
426 AppendPadding(Layout.getSize() / 8, Align);
427}
428
Anders Carlsson4b3e5be2009-12-16 17:27:20 +0000429void CGRecordLayoutBuilder::LayoutBases(const CXXRecordDecl *RD,
430 const ASTRecordLayout &Layout) {
431 // Check if we need to add a vtable pointer.
432 if (RD->isDynamicClass() && !Layout.getPrimaryBase()) {
Daniel Dunbar270e2032010-03-31 00:11:27 +0000433 const llvm::Type *Int8PtrTy =
Anders Carlsson4b3e5be2009-12-16 17:27:20 +0000434 llvm::Type::getInt8PtrTy(Types.getLLVMContext());
Daniel Dunbar270e2032010-03-31 00:11:27 +0000435
Anders Carlsson4b3e5be2009-12-16 17:27:20 +0000436 assert(NextFieldOffsetInBytes == 0 &&
Anders Carlsson046c2942010-04-17 20:15:18 +0000437 "VTable pointer must come first!");
Anders Carlsson4b3e5be2009-12-16 17:27:20 +0000438 AppendField(NextFieldOffsetInBytes, Int8PtrTy->getPointerTo());
439 }
440}
441
Anders Carlsson45372a62009-07-23 03:17:50 +0000442bool CGRecordLayoutBuilder::LayoutFields(const RecordDecl *D) {
443 assert(!D->isUnion() && "Can't call LayoutFields on a union!");
Anders Carlssona5dd7222009-08-08 19:38:24 +0000444 assert(Alignment && "Did not set alignment!");
Mike Stump1eb44332009-09-09 15:08:12 +0000445
Anders Carlsson5a6e3982009-07-23 03:43:54 +0000446 const ASTRecordLayout &Layout = Types.getContext().getASTRecordLayout(D);
Mike Stump1eb44332009-09-09 15:08:12 +0000447
Anders Carlsson4b3e5be2009-12-16 17:27:20 +0000448 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
449 LayoutBases(RD, Layout);
Daniel Dunbar270e2032010-03-31 00:11:27 +0000450
Anders Carlsson45372a62009-07-23 03:17:50 +0000451 unsigned FieldNo = 0;
Fariborz Jahaniancad86652009-07-27 20:57:45 +0000452
Mike Stump1eb44332009-09-09 15:08:12 +0000453 for (RecordDecl::field_iterator Field = D->field_begin(),
Anders Carlsson45372a62009-07-23 03:17:50 +0000454 FieldEnd = D->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
455 if (!LayoutField(*Field, Layout.getFieldOffset(FieldNo))) {
Mike Stump1eb44332009-09-09 15:08:12 +0000456 assert(!Packed &&
Anders Carlsson45372a62009-07-23 03:17:50 +0000457 "Could not layout fields even with a packed LLVM struct!");
458 return false;
459 }
460 }
461
462 // Append tail padding if necessary.
Anders Carlssonc1efe362009-07-27 14:55:54 +0000463 AppendTailPadding(Layout.getSize());
Mike Stump1eb44332009-09-09 15:08:12 +0000464
Anders Carlsson45372a62009-07-23 03:17:50 +0000465 return true;
466}
467
Anders Carlssonc1efe362009-07-27 14:55:54 +0000468void CGRecordLayoutBuilder::AppendTailPadding(uint64_t RecordSize) {
469 assert(RecordSize % 8 == 0 && "Invalid record size!");
Mike Stump1eb44332009-09-09 15:08:12 +0000470
Anders Carlssonc1efe362009-07-27 14:55:54 +0000471 uint64_t RecordSizeInBytes = RecordSize / 8;
Anders Carlssonc2cc1d52009-07-28 17:56:36 +0000472 assert(NextFieldOffsetInBytes <= RecordSizeInBytes && "Size mismatch!");
Mike Stump1eb44332009-09-09 15:08:12 +0000473
Daniel Dunbar270e2032010-03-31 00:11:27 +0000474 uint64_t AlignedNextFieldOffset =
Anders Carlssonc2456822009-12-08 01:24:23 +0000475 llvm::RoundUpToAlignment(NextFieldOffsetInBytes, AlignmentAsLLVMStruct);
476
477 if (AlignedNextFieldOffset == RecordSizeInBytes) {
478 // We don't need any padding.
479 return;
480 }
Daniel Dunbar270e2032010-03-31 00:11:27 +0000481
Anders Carlssonc2cc1d52009-07-28 17:56:36 +0000482 unsigned NumPadBytes = RecordSizeInBytes - NextFieldOffsetInBytes;
Anders Carlssonc1efe362009-07-27 14:55:54 +0000483 AppendBytes(NumPadBytes);
484}
485
Mike Stump1eb44332009-09-09 15:08:12 +0000486void CGRecordLayoutBuilder::AppendField(uint64_t FieldOffsetInBytes,
Anders Carlsson45372a62009-07-23 03:17:50 +0000487 const llvm::Type *FieldTy) {
488 AlignmentAsLLVMStruct = std::max(AlignmentAsLLVMStruct,
489 getTypeAlignment(FieldTy));
Anders Carlsson728d7cd2009-07-24 02:45:50 +0000490
Daniel Dunbar9b28daf2010-04-12 21:01:28 +0000491 uint64_t FieldSizeInBytes = Types.getTargetData().getTypeAllocSize(FieldTy);
Anders Carlsson728d7cd2009-07-24 02:45:50 +0000492
Anders Carlsson45372a62009-07-23 03:17:50 +0000493 FieldTypes.push_back(FieldTy);
Anders Carlsson45372a62009-07-23 03:17:50 +0000494
Anders Carlssonc2cc1d52009-07-28 17:56:36 +0000495 NextFieldOffsetInBytes = FieldOffsetInBytes + FieldSizeInBytes;
Anders Carlsson45372a62009-07-23 03:17:50 +0000496 BitsAvailableInLastField = 0;
497}
498
Mike Stump1eb44332009-09-09 15:08:12 +0000499void CGRecordLayoutBuilder::AppendPadding(uint64_t FieldOffsetInBytes,
Anders Carlsson45372a62009-07-23 03:17:50 +0000500 unsigned FieldAlignment) {
Anders Carlsson45372a62009-07-23 03:17:50 +0000501 assert(NextFieldOffsetInBytes <= FieldOffsetInBytes &&
502 "Incorrect field layout!");
Mike Stump1eb44332009-09-09 15:08:12 +0000503
Anders Carlsson45372a62009-07-23 03:17:50 +0000504 // Round up the field offset to the alignment of the field type.
Mike Stump1eb44332009-09-09 15:08:12 +0000505 uint64_t AlignedNextFieldOffsetInBytes =
Anders Carlsson45372a62009-07-23 03:17:50 +0000506 llvm::RoundUpToAlignment(NextFieldOffsetInBytes, FieldAlignment);
507
508 if (AlignedNextFieldOffsetInBytes < FieldOffsetInBytes) {
509 // Even with alignment, the field offset is not at the right place,
510 // insert padding.
511 uint64_t PaddingInBytes = FieldOffsetInBytes - NextFieldOffsetInBytes;
512
513 AppendBytes(PaddingInBytes);
514 }
515}
516
517void CGRecordLayoutBuilder::AppendBytes(uint64_t NumBytes) {
518 if (NumBytes == 0)
519 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000520
Owen Anderson0032b272009-08-13 21:57:51 +0000521 const llvm::Type *Ty = llvm::Type::getInt8Ty(Types.getLLVMContext());
Anders Carlssonc1efe362009-07-27 14:55:54 +0000522 if (NumBytes > 1)
Anders Carlsson45372a62009-07-23 03:17:50 +0000523 Ty = llvm::ArrayType::get(Ty, NumBytes);
Mike Stump1eb44332009-09-09 15:08:12 +0000524
Anders Carlsson45372a62009-07-23 03:17:50 +0000525 // Append the padding field
Anders Carlssonc2cc1d52009-07-28 17:56:36 +0000526 AppendField(NextFieldOffsetInBytes, Ty);
Anders Carlsson45372a62009-07-23 03:17:50 +0000527}
528
529unsigned CGRecordLayoutBuilder::getTypeAlignment(const llvm::Type *Ty) const {
Anders Carlsson4b5584b2009-07-23 17:24:40 +0000530 if (Packed)
Anders Carlsson45372a62009-07-23 03:17:50 +0000531 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000532
Anders Carlsson45372a62009-07-23 03:17:50 +0000533 return Types.getTargetData().getABITypeAlignment(Ty);
534}
535
Anders Carlsson2c12d032010-02-02 05:17:25 +0000536void CGRecordLayoutBuilder::CheckForPointerToDataMember(QualType T) {
Anders Carlssonfc3eaa42009-08-23 01:25:01 +0000537 // This record already contains a member pointer.
Anders Carlsson2c12d032010-02-02 05:17:25 +0000538 if (ContainsPointerToDataMember)
Anders Carlssonfc3eaa42009-08-23 01:25:01 +0000539 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000540
Anders Carlssonfc3eaa42009-08-23 01:25:01 +0000541 // Can only have member pointers if we're compiling C++.
542 if (!Types.getContext().getLangOptions().CPlusPlus)
543 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000544
Anders Carlsson2c12d032010-02-02 05:17:25 +0000545 T = Types.getContext().getBaseElementType(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000546
Anders Carlsson2c12d032010-02-02 05:17:25 +0000547 if (const MemberPointerType *MPT = T->getAs<MemberPointerType>()) {
548 if (!MPT->getPointeeType()->isFunctionType()) {
549 // We have a pointer to data member.
550 ContainsPointerToDataMember = true;
551 }
552 } else if (const RecordType *RT = T->getAs<RecordType>()) {
553 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Daniel Dunbar270e2032010-03-31 00:11:27 +0000554
Anders Carlsson2c12d032010-02-02 05:17:25 +0000555 // FIXME: It would be better if there was a way to explicitly compute the
556 // record layout instead of converting to a type.
557 Types.ConvertTagDeclType(RD);
Daniel Dunbar270e2032010-03-31 00:11:27 +0000558
Anders Carlsson2c12d032010-02-02 05:17:25 +0000559 const CGRecordLayout &Layout = Types.getCGRecordLayout(RD);
Daniel Dunbar270e2032010-03-31 00:11:27 +0000560
Anders Carlsson2c12d032010-02-02 05:17:25 +0000561 if (Layout.containsPointerToDataMember())
562 ContainsPointerToDataMember = true;
Daniel Dunbar270e2032010-03-31 00:11:27 +0000563 }
Anders Carlssonfc3eaa42009-08-23 01:25:01 +0000564}
565
Daniel Dunbar270e2032010-03-31 00:11:27 +0000566CGRecordLayout *CodeGenTypes::ComputeRecordLayout(const RecordDecl *D) {
567 CGRecordLayoutBuilder Builder(*this);
Mike Stump1eb44332009-09-09 15:08:12 +0000568
Anders Carlsson45372a62009-07-23 03:17:50 +0000569 Builder.Layout(D);
Anders Carlsson4c98efd2009-07-24 15:20:52 +0000570
Daniel Dunbar270e2032010-03-31 00:11:27 +0000571 const llvm::Type *Ty = llvm::StructType::get(getLLVMContext(),
Owen Anderson47a434f2009-08-05 23:18:46 +0000572 Builder.FieldTypes,
Anders Carlsson4b5584b2009-07-23 17:24:40 +0000573 Builder.Packed);
Mike Stump1eb44332009-09-09 15:08:12 +0000574
Daniel Dunbar198bcb42010-03-31 01:09:11 +0000575 CGRecordLayout *RL =
576 new CGRecordLayout(Ty, Builder.ContainsPointerToDataMember);
577
Anders Carlsson45372a62009-07-23 03:17:50 +0000578 // Add all the field numbers.
Daniel Dunbarc7a984a2010-04-06 01:07:41 +0000579 for (unsigned i = 0, e = Builder.LLVMFields.size(); i != e; ++i)
580 RL->FieldInfo.insert(Builder.LLVMFields[i]);
Anders Carlsson45372a62009-07-23 03:17:50 +0000581
582 // Add bitfield info.
Daniel Dunbarc7a984a2010-04-06 01:07:41 +0000583 for (unsigned i = 0, e = Builder.LLVMBitFields.size(); i != e; ++i)
584 RL->BitFields.insert(Builder.LLVMBitFields[i]);
Mike Stump1eb44332009-09-09 15:08:12 +0000585
Daniel Dunbar2e7b7c22010-04-19 20:44:47 +0000586 // Dump the layout, if requested.
Daniel Dunbarab970f92010-04-13 20:58:55 +0000587 if (getContext().getLangOptions().DumpRecordLayouts) {
Daniel Dunbar8d8ab742010-04-19 20:44:53 +0000588 llvm::errs() << "\n*** Dumping IRgen Record Layout\n";
Daniel Dunbarab970f92010-04-13 20:58:55 +0000589 llvm::errs() << "Record: ";
590 D->dump();
591 llvm::errs() << "\nLayout: ";
Daniel Dunbar93c62962010-04-12 18:14:18 +0000592 RL->dump();
Daniel Dunbarab970f92010-04-13 20:58:55 +0000593 }
Daniel Dunbar93c62962010-04-12 18:14:18 +0000594
Daniel Dunbare1467a42010-04-22 02:35:46 +0000595#ifndef NDEBUG
Daniel Dunbar2e7b7c22010-04-19 20:44:47 +0000596 // Verify that the computed LLVM struct size matches the AST layout size.
Daniel Dunbare1467a42010-04-22 02:35:46 +0000597 uint64_t TypeSizeInBits = getContext().getASTRecordLayout(D).getSize();
598 assert(TypeSizeInBits == getTargetData().getTypeAllocSizeInBits(Ty) &&
Daniel Dunbar2e7b7c22010-04-19 20:44:47 +0000599 "Type size mismatch!");
600
Daniel Dunbar3b2ae7a2010-04-21 19:10:49 +0000601 // Verify that the LLVM and AST field offsets agree.
Daniel Dunbar3b2ae7a2010-04-21 19:10:49 +0000602 const llvm::StructType *ST =
603 dyn_cast<llvm::StructType>(RL->getLLVMType());
604 const llvm::StructLayout *SL = getTargetData().getStructLayout(ST);
605
606 const ASTRecordLayout &AST_RL = getContext().getASTRecordLayout(D);
607 RecordDecl::field_iterator it = D->field_begin();
608 for (unsigned i = 0, e = AST_RL.getFieldCount(); i != e; ++i, ++it) {
609 const FieldDecl *FD = *it;
Daniel Dunbare1467a42010-04-22 02:35:46 +0000610
611 // For non-bit-fields, just check that the LLVM struct offset matches the
612 // AST offset.
613 if (!FD->isBitField()) {
Daniel Dunbar3b2ae7a2010-04-21 19:10:49 +0000614 unsigned FieldNo = RL->getLLVMFieldNo(FD);
615 assert(AST_RL.getFieldOffset(i) == SL->getElementOffsetInBits(FieldNo) &&
616 "Invalid field offset!");
Daniel Dunbare1467a42010-04-22 02:35:46 +0000617 continue;
618 }
619
620 // Ignore unnamed bit-fields.
621 if (!FD->getDeclName())
622 continue;
623
624 const CGBitFieldInfo &Info = RL->getBitFieldInfo(FD);
625 for (unsigned i = 0, e = Info.getNumComponents(); i != e; ++i) {
626 const CGBitFieldInfo::AccessInfo &AI = Info.getComponent(i);
627
628 // Verify that every component access is within the structure.
629 uint64_t FieldOffset = SL->getElementOffsetInBits(AI.FieldIndex);
630 uint64_t AccessBitOffset = FieldOffset + AI.FieldByteOffset * 8;
631 assert(AccessBitOffset + AI.AccessWidth <= TypeSizeInBits &&
632 "Invalid bit-field access (out of range)!");
Daniel Dunbar3b2ae7a2010-04-21 19:10:49 +0000633 }
634 }
635#endif
Daniel Dunbar2e7b7c22010-04-19 20:44:47 +0000636
Daniel Dunbar198bcb42010-03-31 01:09:11 +0000637 return RL;
Anders Carlsson45372a62009-07-23 03:17:50 +0000638}
Daniel Dunbar93c62962010-04-12 18:14:18 +0000639
640void CGRecordLayout::print(llvm::raw_ostream &OS) const {
641 OS << "<CGRecordLayout\n";
642 OS << " LLVMType:" << *LLVMType << "\n";
643 OS << " ContainsPointerToDataMember:" << ContainsPointerToDataMember << "\n";
644 OS << " BitFields:[\n";
Daniel Dunbarad759532010-04-22 02:35:36 +0000645
646 // Print bit-field infos in declaration order.
647 std::vector<std::pair<unsigned, const CGBitFieldInfo*> > BFIs;
Daniel Dunbar93c62962010-04-12 18:14:18 +0000648 for (llvm::DenseMap<const FieldDecl*, CGBitFieldInfo>::const_iterator
649 it = BitFields.begin(), ie = BitFields.end();
650 it != ie; ++it) {
Daniel Dunbarad759532010-04-22 02:35:36 +0000651 const RecordDecl *RD = it->first->getParent();
652 unsigned Index = 0;
653 for (RecordDecl::field_iterator
654 it2 = RD->field_begin(); *it2 != it->first; ++it2)
655 ++Index;
656 BFIs.push_back(std::make_pair(Index, &it->second));
657 }
658 llvm::array_pod_sort(BFIs.begin(), BFIs.end());
659 for (unsigned i = 0, e = BFIs.size(); i != e; ++i) {
Daniel Dunbarab970f92010-04-13 20:58:55 +0000660 OS.indent(4);
Daniel Dunbarad759532010-04-22 02:35:36 +0000661 BFIs[i].second->print(OS);
Daniel Dunbar93c62962010-04-12 18:14:18 +0000662 OS << "\n";
663 }
Daniel Dunbarad759532010-04-22 02:35:36 +0000664
Daniel Dunbar93c62962010-04-12 18:14:18 +0000665 OS << "]>\n";
666}
667
668void CGRecordLayout::dump() const {
669 print(llvm::errs());
670}
671
672void CGBitFieldInfo::print(llvm::raw_ostream &OS) const {
673 OS << "<CGBitFieldInfo";
Daniel Dunbar93c62962010-04-12 18:14:18 +0000674 OS << " Size:" << Size;
Daniel Dunbarab970f92010-04-13 20:58:55 +0000675 OS << " IsSigned:" << IsSigned << "\n";
676
677 OS.indent(4 + strlen("<CGBitFieldInfo"));
678 OS << " NumComponents:" << getNumComponents();
679 OS << " Components: [";
680 if (getNumComponents()) {
681 OS << "\n";
682 for (unsigned i = 0, e = getNumComponents(); i != e; ++i) {
683 const AccessInfo &AI = getComponent(i);
684 OS.indent(8);
685 OS << "<AccessInfo"
686 << " FieldIndex:" << AI.FieldIndex
687 << " FieldByteOffset:" << AI.FieldByteOffset
688 << " FieldBitStart:" << AI.FieldBitStart
689 << " AccessWidth:" << AI.AccessWidth << "\n";
690 OS.indent(8 + strlen("<AccessInfo"));
691 OS << " AccessAlignment:" << AI.AccessAlignment
692 << " TargetBitOffset:" << AI.TargetBitOffset
693 << " TargetBitWidth:" << AI.TargetBitWidth
694 << ">\n";
695 }
696 OS.indent(4);
697 }
698 OS << "]>";
Daniel Dunbar93c62962010-04-12 18:14:18 +0000699}
700
701void CGBitFieldInfo::dump() const {
702 print(llvm::errs());
703}