blob: 8a18197a5698e538b501aa5919ea1466ce58f7e1 [file] [log] [blame]
Anders Carlsson79474332009-07-18 20:20:21 +00001//=== ASTRecordLayoutBuilder.cpp - Helper class for building record layouts ==//
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#include "RecordLayoutBuilder.h"
11
12#include "clang/AST/Attr.h"
13#include "clang/AST/Decl.h"
Anders Carlsson6d9f6f32009-07-19 00:18:47 +000014#include "clang/AST/DeclCXX.h"
Anders Carlsson4f516282009-07-18 20:50:59 +000015#include "clang/AST/DeclObjC.h"
Anders Carlsson79474332009-07-18 20:20:21 +000016#include "clang/AST/Expr.h"
17#include "clang/AST/RecordLayout.h"
18#include "clang/Basic/TargetInfo.h"
Mike Stumpd8fe7b22009-08-05 22:37:18 +000019#include <llvm/ADT/SmallSet.h>
Anders Carlsson79474332009-07-18 20:20:21 +000020#include <llvm/Support/MathExtras.h>
21
22using namespace clang;
23
24ASTRecordLayoutBuilder::ASTRecordLayoutBuilder(ASTContext &Ctx)
Anders Carlsson6d9f6f32009-07-19 00:18:47 +000025 : Ctx(Ctx), Size(0), Alignment(8), StructPacking(0), NextOffset(0),
Anders Carlssonfc8cfa82009-07-28 19:24:15 +000026 IsUnion(false), NonVirtualSize(0), NonVirtualAlignment(8) {}
Anders Carlsson79474332009-07-18 20:20:21 +000027
Mike Stump25094802009-08-06 00:38:46 +000028/// LayoutVtable - Lay out the vtable and set PrimaryBase.
Mike Stump3dc7eb92009-07-30 00:22:38 +000029void ASTRecordLayoutBuilder::LayoutVtable(const CXXRecordDecl *RD) {
Mike Stumpd8fe7b22009-08-05 22:37:18 +000030 // FIXME: audit indirect virtual bases
Mike Stump25094802009-08-06 00:38:46 +000031 if (!RD->isPolymorphic() && !RD->getNumVBases()) {
32 // There is no primary base in this case.
Mike Stumpc266c6d2009-08-07 19:00:50 +000033 setPrimaryBase(0, false);
Mike Stumpd8fe7b22009-08-05 22:37:18 +000034 return;
Mike Stump25094802009-08-06 00:38:46 +000035 }
Mike Stumpd8fe7b22009-08-05 22:37:18 +000036
37 SelectPrimaryBase(RD);
38 if (PrimaryBase == 0) {
39 int AS = 0;
40 UpdateAlignment(Ctx.Target.getPointerAlign(AS));
41 Size += Ctx.Target.getPointerWidth(AS);
42 NextOffset = Size;
43 }
Mike Stump3dc7eb92009-07-30 00:22:38 +000044}
45
Anders Carlsson6d9f6f32009-07-19 00:18:47 +000046void
47ASTRecordLayoutBuilder::LayoutNonVirtualBases(const CXXRecordDecl *RD) {
Anders Carlsson6d9f6f32009-07-19 00:18:47 +000048 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
49 e = RD->bases_end(); i != e; ++i) {
50 if (!i->isVirtual()) {
51 const CXXRecordDecl *Base =
Ted Kremenekc23c7e62009-07-29 21:53:49 +000052 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Mike Stump25094802009-08-06 00:38:46 +000053 // Skip the PrimaryBase here, as it is laid down first.
54 if (Base != PrimaryBase)
Mike Stump6b2556f2009-08-06 13:41:24 +000055 LayoutBaseNonVirtually(Base);
Anders Carlsson6d9f6f32009-07-19 00:18:47 +000056 }
57 }
58}
59
Mike Stumpd8fe7b22009-08-05 22:37:18 +000060// Helper routines related to the abi definition from:
61// http://www.codesourcery.com/public/cxx-abi/abi.html
62//
63/// IsNearlyEmpty - Indicates when a class has a vtable pointer, but
64/// no other data.
65bool ASTRecordLayoutBuilder::IsNearlyEmpty(const CXXRecordDecl *RD) {
66 // FIXME: Audit the corners
67 if (!RD->isDynamicClass())
68 return false;
69 const ASTRecordLayout &BaseInfo = Ctx.getASTRecordLayout(RD);
70 if (BaseInfo.getNonVirtualSize() == Ctx.Target.getPointerWidth(0))
71 return true;
72 return false;
73}
74
75void ASTRecordLayoutBuilder::SelectPrimaryForBase(const CXXRecordDecl *RD,
76 llvm::SmallSet<const CXXRecordDecl*, 32> &IndirectPrimary) {
77 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
78 e = RD->bases_end(); i != e; ++i) {
79 if (!i->isVirtual()) {
80 const CXXRecordDecl *Base =
81 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
82 // Only bases with virtual bases participate in computing the
83 // indirect primary base classes.
84 // FIXME: audit indirect virtual bases
85 if (Base->getNumVBases() == 0)
86 return;
87 // FIXME: This information is recomputed a whole lot, cache it instead.
88 SelectPrimaryBase(Base);
89 IndirectPrimary.insert(PrimaryBase);
90 SelectPrimaryForBase(Base, IndirectPrimary);
91 }
92 }
93}
94
95/// SelectPrimaryBase - Selects the primary base for the given class and
96/// records that with setPrimaryBase.
97void ASTRecordLayoutBuilder::SelectPrimaryBase(const CXXRecordDecl *RD) {
98 // The primary base is the first non-virtual indirect or direct base class,
99 // if one exists.
100 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
101 e = RD->bases_end(); i != e; ++i) {
102 if (!i->isVirtual()) {
103 const CXXRecordDecl *Base =
104 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
105 if (Base->isDynamicClass()) {
Mike Stumpc266c6d2009-08-07 19:00:50 +0000106 setPrimaryBase(Base, false);
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000107 return;
108 }
109 }
110 }
111
112 // Otherwise, it is the first nearly empty virtual base that is not an
113 // indirect primary base class, if one exists.
114
115 // If we have no virtual bases at this point, bail out as the searching below
116 // is expensive.
117 // FIXME: audit indirect virtual bases
118 if (RD->getNumVBases() == 0) {
Mike Stumpc266c6d2009-08-07 19:00:50 +0000119 setPrimaryBase(0, false);
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000120 return;
121 }
122
Mike Stumpe9c85a72009-08-06 12:52:13 +0000123 // First, we compute all the primary bases for all of our direct and indirect
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000124 // non-virtual bases, and record all their primary base classes.
125 const CXXRecordDecl *FirstPrimary = 0;
126 llvm::SmallSet<const CXXRecordDecl*, 32> IndirectPrimary;
127 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
128 e = RD->bases_end(); i != e; ++i) {
129 if (!i->isVirtual()) {
130 const CXXRecordDecl *Base =
131 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
132 SelectPrimaryForBase(Base, IndirectPrimary);
133 }
134 }
135
136 // Then we can search for the first nearly empty virtual base itself.
137 // FIXME: audit indirect virtual bases
138 for (CXXRecordDecl::base_class_const_iterator i = RD->vbases_begin(),
139 e = RD->vbases_end(); i != e; ++i) {
140 const CXXRecordDecl *Base =
141 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
142 if (IsNearlyEmpty(Base)) {
143 if (FirstPrimary==0)
144 FirstPrimary = Base;
145 if (!IndirectPrimary.count(Base)) {
Mike Stumpc266c6d2009-08-07 19:00:50 +0000146 setPrimaryBase(Base, true);
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000147 return;
148 }
149 }
150 }
151
Mike Stumpc266c6d2009-08-07 19:00:50 +0000152 // Otherwise if is the first nearly empty virtual base, if one exists,
153 // otherwise there is no primary base class.
154 setPrimaryBase(FirstPrimary, true);
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000155 return;
156}
157
Mike Stump6b2556f2009-08-06 13:41:24 +0000158void ASTRecordLayoutBuilder::LayoutVirtualBase(const CXXRecordDecl *RD) {
159 LayoutBaseNonVirtually(RD);
160}
161
162void ASTRecordLayoutBuilder::LayoutVirtualBases(const CXXRecordDecl *RD) {
163 // FIXME: audit indirect virtual bases
164 for (CXXRecordDecl::base_class_const_iterator i = RD->vbases_begin(),
165 e = RD->vbases_end(); i != e; ++i) {
166 const CXXRecordDecl *Base =
167 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
168 if (Base != PrimaryBase)
169 LayoutVirtualBase(Base);
170 }
171}
172
173void ASTRecordLayoutBuilder::LayoutBaseNonVirtually(const CXXRecordDecl *RD) {
Anders Carlsson6d9f6f32009-07-19 00:18:47 +0000174 const ASTRecordLayout &BaseInfo = Ctx.getASTRecordLayout(RD);
175 assert(BaseInfo.getDataSize() > 0 &&
176 "FIXME: Handle empty classes.");
177
Anders Carlssonfc8cfa82009-07-28 19:24:15 +0000178 unsigned BaseAlign = BaseInfo.getNonVirtualAlign();
179 uint64_t BaseSize = BaseInfo.getNonVirtualSize();
Anders Carlsson6d9f6f32009-07-19 00:18:47 +0000180
181 // Round up the current record size to the base's alignment boundary.
182 Size = (Size + (BaseAlign-1)) & ~(BaseAlign-1);
183
Anders Carlssonfc8cfa82009-07-28 19:24:15 +0000184 // Add base class offsets.
185 Bases.push_back(RD);
186 BaseOffsets.push_back(Size);
187
Anders Carlsson6d9f6f32009-07-19 00:18:47 +0000188 // Reserve space for this base.
189 Size += BaseSize;
190
191 // Remember the next available offset.
192 NextOffset = Size;
193
194 // Remember max struct/class alignment.
195 UpdateAlignment(BaseAlign);
196}
197
Anders Carlsson79474332009-07-18 20:20:21 +0000198void ASTRecordLayoutBuilder::Layout(const RecordDecl *D) {
199 IsUnion = D->isUnion();
Anders Carlsson68e0b682009-08-08 18:23:56 +0000200
201 if (D->hasAttr<PackedAttr>())
202 StructPacking = 1;
203 if (const PragmaPackAttr *PPA = D->getAttr<PragmaPackAttr>())
204 StructPacking = PPA->getAlignment();
Anders Carlsson79474332009-07-18 20:20:21 +0000205
206 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
207 UpdateAlignment(AA->getAlignment());
Anders Carlsson6d9f6f32009-07-19 00:18:47 +0000208
209 // If this is a C++ class, lay out the nonvirtual bases.
Mike Stump6b2556f2009-08-06 13:41:24 +0000210 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D);
211 if (RD) {
Mike Stump3dc7eb92009-07-30 00:22:38 +0000212 LayoutVtable(RD);
Mike Stump25094802009-08-06 00:38:46 +0000213 // PrimaryBase goes first.
214 if (PrimaryBase)
Mike Stump6b2556f2009-08-06 13:41:24 +0000215 LayoutBaseNonVirtually(PrimaryBase);
Mike Stump3dc7eb92009-07-30 00:22:38 +0000216 LayoutNonVirtualBases(RD);
Mike Stump3dc7eb92009-07-30 00:22:38 +0000217 }
Anders Carlsson6d9f6f32009-07-19 00:18:47 +0000218
Anders Carlsson118ce162009-07-18 21:48:39 +0000219 LayoutFields(D);
Anders Carlsson79474332009-07-18 20:20:21 +0000220
Anders Carlssonfc8cfa82009-07-28 19:24:15 +0000221 NonVirtualSize = Size;
222 NonVirtualAlignment = Alignment;
Mike Stump3dc7eb92009-07-30 00:22:38 +0000223
Mike Stump6b2556f2009-08-06 13:41:24 +0000224 if (RD)
225 LayoutVirtualBases(RD);
226
Anders Carlsson79474332009-07-18 20:20:21 +0000227 // Finally, round the size of the total struct up to the alignment of the
228 // struct itself.
229 FinishLayout();
230}
231
Anders Carlsson4f516282009-07-18 20:50:59 +0000232void ASTRecordLayoutBuilder::Layout(const ObjCInterfaceDecl *D,
233 const ObjCImplementationDecl *Impl) {
234 if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
235 const ASTRecordLayout &SL = Ctx.getASTObjCInterfaceLayout(SD);
236
237 UpdateAlignment(SL.getAlignment());
238
239 // We start laying out ivars not at the end of the superclass
240 // structure, but at the next byte following the last field.
Anders Carlsson27b50132009-07-18 21:26:44 +0000241 Size = llvm::RoundUpToAlignment(SL.getDataSize(), 8);
Anders Carlsson4f516282009-07-18 20:50:59 +0000242 NextOffset = Size;
243 }
244
Anders Carlsson68e0b682009-08-08 18:23:56 +0000245 if (D->hasAttr<PackedAttr>())
246 StructPacking = 1;
Anders Carlsson4f516282009-07-18 20:50:59 +0000247
248 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
249 UpdateAlignment(AA->getAlignment());
250
251 // Layout each ivar sequentially.
252 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
253 Ctx.ShallowCollectObjCIvars(D, Ivars, Impl);
254 for (unsigned i = 0, e = Ivars.size(); i != e; ++i)
255 LayoutField(Ivars[i]);
256
257 // Finally, round the size of the total struct up to the alignment of the
258 // struct itself.
259 FinishLayout();
260}
261
Anders Carlsson118ce162009-07-18 21:48:39 +0000262void ASTRecordLayoutBuilder::LayoutFields(const RecordDecl *D) {
263 // Layout each field, for now, just sequentially, respecting alignment. In
264 // the future, this will need to be tweakable by targets.
265 for (RecordDecl::field_iterator Field = D->field_begin(),
266 FieldEnd = D->field_end(); Field != FieldEnd; ++Field)
267 LayoutField(*Field);
268}
269
Anders Carlsson79474332009-07-18 20:20:21 +0000270void ASTRecordLayoutBuilder::LayoutField(const FieldDecl *D) {
271 unsigned FieldPacking = StructPacking;
272 uint64_t FieldOffset = IsUnion ? 0 : Size;
273 uint64_t FieldSize;
274 unsigned FieldAlign;
275
276 // FIXME: Should this override struct packing? Probably we want to
277 // take the minimum?
Anders Carlsson68e0b682009-08-08 18:23:56 +0000278 if (D->hasAttr<PackedAttr>())
279 FieldPacking = 1;
Anders Carlsson79474332009-07-18 20:20:21 +0000280
281 if (const Expr *BitWidthExpr = D->getBitWidth()) {
282 // TODO: Need to check this algorithm on other targets!
283 // (tested on Linux-X86)
284 FieldSize = BitWidthExpr->EvaluateAsInt(Ctx).getZExtValue();
285
286 std::pair<uint64_t, unsigned> FieldInfo = Ctx.getTypeInfo(D->getType());
287 uint64_t TypeSize = FieldInfo.first;
288
289 // Determine the alignment of this bitfield. The packing
290 // attributes define a maximum and the alignment attribute defines
291 // a minimum.
292 // FIXME: What is the right behavior when the specified alignment
293 // is smaller than the specified packing?
294 FieldAlign = FieldInfo.second;
295 if (FieldPacking)
296 FieldAlign = std::min(FieldAlign, FieldPacking);
297 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
298 FieldAlign = std::max(FieldAlign, AA->getAlignment());
299
300 // Check if we need to add padding to give the field the correct
301 // alignment.
302 if (FieldSize == 0 || (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize)
303 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
304
305 // Padding members don't affect overall alignment
306 if (!D->getIdentifier())
307 FieldAlign = 1;
308 } else {
309 if (D->getType()->isIncompleteArrayType()) {
310 // This is a flexible array member; we can't directly
311 // query getTypeInfo about these, so we figure it out here.
312 // Flexible array members don't have any size, but they
313 // have to be aligned appropriately for their element type.
314 FieldSize = 0;
315 const ArrayType* ATy = Ctx.getAsArrayType(D->getType());
316 FieldAlign = Ctx.getTypeAlign(ATy->getElementType());
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000317 } else if (const ReferenceType *RT = D->getType()->getAs<ReferenceType>()) {
Anders Carlsson79474332009-07-18 20:20:21 +0000318 unsigned AS = RT->getPointeeType().getAddressSpace();
319 FieldSize = Ctx.Target.getPointerWidth(AS);
320 FieldAlign = Ctx.Target.getPointerAlign(AS);
321 } else {
322 std::pair<uint64_t, unsigned> FieldInfo = Ctx.getTypeInfo(D->getType());
323 FieldSize = FieldInfo.first;
324 FieldAlign = FieldInfo.second;
325 }
326
327 // Determine the alignment of this bitfield. The packing
328 // attributes define a maximum and the alignment attribute defines
329 // a minimum. Additionally, the packing alignment must be at least
330 // a byte for non-bitfields.
331 //
332 // FIXME: What is the right behavior when the specified alignment
333 // is smaller than the specified packing?
334 if (FieldPacking)
335 FieldAlign = std::min(FieldAlign, std::max(8U, FieldPacking));
336 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
337 FieldAlign = std::max(FieldAlign, AA->getAlignment());
338
339 // Round up the current record size to the field's alignment boundary.
340 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
341 }
342
343 // Place this field at the current location.
344 FieldOffsets.push_back(FieldOffset);
345
346 // Reserve space for this field.
347 if (IsUnion)
348 Size = std::max(Size, FieldSize);
349 else
350 Size = FieldOffset + FieldSize;
351
352 // Remember the next available offset.
353 NextOffset = Size;
354
355 // Remember max struct/class alignment.
356 UpdateAlignment(FieldAlign);
357}
358
359void ASTRecordLayoutBuilder::FinishLayout() {
360 // In C++, records cannot be of size 0.
361 if (Ctx.getLangOptions().CPlusPlus && Size == 0)
362 Size = 8;
363 // Finally, round the size of the record up to the alignment of the
364 // record itself.
365 Size = (Size + (Alignment-1)) & ~(Alignment-1);
366}
367
368void ASTRecordLayoutBuilder::UpdateAlignment(unsigned NewAlignment) {
369 if (NewAlignment <= Alignment)
370 return;
371
372 assert(llvm::isPowerOf2_32(NewAlignment && "Alignment not a power of 2"));
373
374 Alignment = NewAlignment;
375}
376
377const ASTRecordLayout *
378ASTRecordLayoutBuilder::ComputeLayout(ASTContext &Ctx,
379 const RecordDecl *D) {
380 ASTRecordLayoutBuilder Builder(Ctx);
381
382 Builder.Layout(D);
383
Anders Carlssonfc8cfa82009-07-28 19:24:15 +0000384 if (!isa<CXXRecordDecl>(D))
385 return new ASTRecordLayout(Builder.Size, Builder.Alignment, Builder.Size,
386 Builder.FieldOffsets.data(),
387 Builder.FieldOffsets.size());
Anders Carlsson6d9f6f32009-07-19 00:18:47 +0000388
Anders Carlssonfc8cfa82009-07-28 19:24:15 +0000389 // FIXME: This is not always correct. See the part about bitfields at
390 // http://www.codesourcery.com/public/cxx-abi/abi.html#POD for more info.
391 // FIXME: IsPODForThePurposeOfLayout should be stored in the record layout.
392 bool IsPODForThePurposeOfLayout = cast<CXXRecordDecl>(D)->isPOD();
393
394 assert(Builder.Bases.size() == Builder.BaseOffsets.size() &&
395 "Base offsets vector must be same size as bases vector!");
396
397 // FIXME: This should be done in FinalizeLayout.
Anders Carlsson6d9f6f32009-07-19 00:18:47 +0000398 uint64_t DataSize =
399 IsPODForThePurposeOfLayout ? Builder.Size : Builder.NextOffset;
Anders Carlssonfc8cfa82009-07-28 19:24:15 +0000400 uint64_t NonVirtualSize =
401 IsPODForThePurposeOfLayout ? DataSize : Builder.NonVirtualSize;
Anders Carlsson6d9f6f32009-07-19 00:18:47 +0000402
403 return new ASTRecordLayout(Builder.Size, Builder.Alignment, DataSize,
Anders Carlsson4f516282009-07-18 20:50:59 +0000404 Builder.FieldOffsets.data(),
Anders Carlssonfc8cfa82009-07-28 19:24:15 +0000405 Builder.FieldOffsets.size(),
406 NonVirtualSize,
407 Builder.NonVirtualAlignment,
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000408 Builder.PrimaryBase,
Mike Stumpc266c6d2009-08-07 19:00:50 +0000409 Builder.PrimaryBaseWasVirtual,
Anders Carlssonfc8cfa82009-07-28 19:24:15 +0000410 Builder.Bases.data(),
411 Builder.BaseOffsets.data(),
412 Builder.Bases.size());
Anders Carlsson4f516282009-07-18 20:50:59 +0000413}
414
415const ASTRecordLayout *
416ASTRecordLayoutBuilder::ComputeLayout(ASTContext &Ctx,
417 const ObjCInterfaceDecl *D,
418 const ObjCImplementationDecl *Impl) {
419 ASTRecordLayoutBuilder Builder(Ctx);
420
421 Builder.Layout(D, Impl);
422
423 return new ASTRecordLayout(Builder.Size, Builder.Alignment,
424 Builder.NextOffset,
Anders Carlsson79474332009-07-18 20:20:21 +0000425 Builder.FieldOffsets.data(),
426 Builder.FieldOffsets.size());
427}