blob: 3131fdb852cc891d9ca00f25a17ff83038a67f9c [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.
33 setPrimaryBase(0);
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)
55 LayoutNonVirtualBase(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()) {
106 setPrimaryBase(Base);
107 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) {
119 setPrimaryBase(0);
120 return;
121 }
122
123 // First, we compute all the primary bases for all of out direct and indirect
124 // 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)) {
146 setPrimaryBase(Base);
147 return;
148 }
149 }
150 }
151
152 // Otherwise if is the first nearly empty base, if one exists, otherwise
153 // there is no primary base class.
154 setPrimaryBase(FirstPrimary);
155 return;
156}
157
Anders Carlsson6d9f6f32009-07-19 00:18:47 +0000158void ASTRecordLayoutBuilder::LayoutNonVirtualBase(const CXXRecordDecl *RD) {
159 const ASTRecordLayout &BaseInfo = Ctx.getASTRecordLayout(RD);
160 assert(BaseInfo.getDataSize() > 0 &&
161 "FIXME: Handle empty classes.");
162
Anders Carlssonfc8cfa82009-07-28 19:24:15 +0000163 unsigned BaseAlign = BaseInfo.getNonVirtualAlign();
164 uint64_t BaseSize = BaseInfo.getNonVirtualSize();
Anders Carlsson6d9f6f32009-07-19 00:18:47 +0000165
166 // Round up the current record size to the base's alignment boundary.
167 Size = (Size + (BaseAlign-1)) & ~(BaseAlign-1);
168
Anders Carlssonfc8cfa82009-07-28 19:24:15 +0000169 // Add base class offsets.
170 Bases.push_back(RD);
171 BaseOffsets.push_back(Size);
172
Anders Carlsson6d9f6f32009-07-19 00:18:47 +0000173 // Reserve space for this base.
174 Size += BaseSize;
175
176 // Remember the next available offset.
177 NextOffset = Size;
178
179 // Remember max struct/class alignment.
180 UpdateAlignment(BaseAlign);
181}
182
Anders Carlsson79474332009-07-18 20:20:21 +0000183void ASTRecordLayoutBuilder::Layout(const RecordDecl *D) {
184 IsUnion = D->isUnion();
185
186 if (const PackedAttr* PA = D->getAttr<PackedAttr>())
187 StructPacking = PA->getAlignment();
188
189 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
190 UpdateAlignment(AA->getAlignment());
Anders Carlsson6d9f6f32009-07-19 00:18:47 +0000191
192 // If this is a C++ class, lay out the nonvirtual bases.
Mike Stump57724c22009-07-30 18:01:44 +0000193 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
Mike Stump3dc7eb92009-07-30 00:22:38 +0000194 LayoutVtable(RD);
Mike Stump25094802009-08-06 00:38:46 +0000195 // PrimaryBase goes first.
196 if (PrimaryBase)
197 LayoutNonVirtualBase(PrimaryBase);
Mike Stump3dc7eb92009-07-30 00:22:38 +0000198 LayoutNonVirtualBases(RD);
Mike Stump3dc7eb92009-07-30 00:22:38 +0000199 }
Anders Carlsson6d9f6f32009-07-19 00:18:47 +0000200
Anders Carlsson118ce162009-07-18 21:48:39 +0000201 LayoutFields(D);
Anders Carlsson79474332009-07-18 20:20:21 +0000202
Anders Carlssonfc8cfa82009-07-28 19:24:15 +0000203 NonVirtualSize = Size;
204 NonVirtualAlignment = Alignment;
Mike Stump3dc7eb92009-07-30 00:22:38 +0000205
Anders Carlsson79474332009-07-18 20:20:21 +0000206 // Finally, round the size of the total struct up to the alignment of the
207 // struct itself.
208 FinishLayout();
209}
210
Anders Carlsson4f516282009-07-18 20:50:59 +0000211void ASTRecordLayoutBuilder::Layout(const ObjCInterfaceDecl *D,
212 const ObjCImplementationDecl *Impl) {
213 if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
214 const ASTRecordLayout &SL = Ctx.getASTObjCInterfaceLayout(SD);
215
216 UpdateAlignment(SL.getAlignment());
217
218 // We start laying out ivars not at the end of the superclass
219 // structure, but at the next byte following the last field.
Anders Carlsson27b50132009-07-18 21:26:44 +0000220 Size = llvm::RoundUpToAlignment(SL.getDataSize(), 8);
Anders Carlsson4f516282009-07-18 20:50:59 +0000221 NextOffset = Size;
222 }
223
224 if (const PackedAttr *PA = D->getAttr<PackedAttr>())
225 StructPacking = PA->getAlignment();
226
227 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
228 UpdateAlignment(AA->getAlignment());
229
230 // Layout each ivar sequentially.
231 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
232 Ctx.ShallowCollectObjCIvars(D, Ivars, Impl);
233 for (unsigned i = 0, e = Ivars.size(); i != e; ++i)
234 LayoutField(Ivars[i]);
235
236 // Finally, round the size of the total struct up to the alignment of the
237 // struct itself.
238 FinishLayout();
239}
240
Anders Carlsson118ce162009-07-18 21:48:39 +0000241void ASTRecordLayoutBuilder::LayoutFields(const RecordDecl *D) {
242 // Layout each field, for now, just sequentially, respecting alignment. In
243 // the future, this will need to be tweakable by targets.
244 for (RecordDecl::field_iterator Field = D->field_begin(),
245 FieldEnd = D->field_end(); Field != FieldEnd; ++Field)
246 LayoutField(*Field);
247}
248
Anders Carlsson79474332009-07-18 20:20:21 +0000249void ASTRecordLayoutBuilder::LayoutField(const FieldDecl *D) {
250 unsigned FieldPacking = StructPacking;
251 uint64_t FieldOffset = IsUnion ? 0 : Size;
252 uint64_t FieldSize;
253 unsigned FieldAlign;
254
255 // FIXME: Should this override struct packing? Probably we want to
256 // take the minimum?
257 if (const PackedAttr *PA = D->getAttr<PackedAttr>())
258 FieldPacking = PA->getAlignment();
259
260 if (const Expr *BitWidthExpr = D->getBitWidth()) {
261 // TODO: Need to check this algorithm on other targets!
262 // (tested on Linux-X86)
263 FieldSize = BitWidthExpr->EvaluateAsInt(Ctx).getZExtValue();
264
265 std::pair<uint64_t, unsigned> FieldInfo = Ctx.getTypeInfo(D->getType());
266 uint64_t TypeSize = FieldInfo.first;
267
268 // Determine the alignment of this bitfield. The packing
269 // attributes define a maximum and the alignment attribute defines
270 // a minimum.
271 // FIXME: What is the right behavior when the specified alignment
272 // is smaller than the specified packing?
273 FieldAlign = FieldInfo.second;
274 if (FieldPacking)
275 FieldAlign = std::min(FieldAlign, FieldPacking);
276 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
277 FieldAlign = std::max(FieldAlign, AA->getAlignment());
278
279 // Check if we need to add padding to give the field the correct
280 // alignment.
281 if (FieldSize == 0 || (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize)
282 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
283
284 // Padding members don't affect overall alignment
285 if (!D->getIdentifier())
286 FieldAlign = 1;
287 } else {
288 if (D->getType()->isIncompleteArrayType()) {
289 // This is a flexible array member; we can't directly
290 // query getTypeInfo about these, so we figure it out here.
291 // Flexible array members don't have any size, but they
292 // have to be aligned appropriately for their element type.
293 FieldSize = 0;
294 const ArrayType* ATy = Ctx.getAsArrayType(D->getType());
295 FieldAlign = Ctx.getTypeAlign(ATy->getElementType());
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000296 } else if (const ReferenceType *RT = D->getType()->getAs<ReferenceType>()) {
Anders Carlsson79474332009-07-18 20:20:21 +0000297 unsigned AS = RT->getPointeeType().getAddressSpace();
298 FieldSize = Ctx.Target.getPointerWidth(AS);
299 FieldAlign = Ctx.Target.getPointerAlign(AS);
300 } else {
301 std::pair<uint64_t, unsigned> FieldInfo = Ctx.getTypeInfo(D->getType());
302 FieldSize = FieldInfo.first;
303 FieldAlign = FieldInfo.second;
304 }
305
306 // Determine the alignment of this bitfield. The packing
307 // attributes define a maximum and the alignment attribute defines
308 // a minimum. Additionally, the packing alignment must be at least
309 // a byte for non-bitfields.
310 //
311 // FIXME: What is the right behavior when the specified alignment
312 // is smaller than the specified packing?
313 if (FieldPacking)
314 FieldAlign = std::min(FieldAlign, std::max(8U, FieldPacking));
315 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
316 FieldAlign = std::max(FieldAlign, AA->getAlignment());
317
318 // Round up the current record size to the field's alignment boundary.
319 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
320 }
321
322 // Place this field at the current location.
323 FieldOffsets.push_back(FieldOffset);
324
325 // Reserve space for this field.
326 if (IsUnion)
327 Size = std::max(Size, FieldSize);
328 else
329 Size = FieldOffset + FieldSize;
330
331 // Remember the next available offset.
332 NextOffset = Size;
333
334 // Remember max struct/class alignment.
335 UpdateAlignment(FieldAlign);
336}
337
338void ASTRecordLayoutBuilder::FinishLayout() {
339 // In C++, records cannot be of size 0.
340 if (Ctx.getLangOptions().CPlusPlus && Size == 0)
341 Size = 8;
342 // Finally, round the size of the record up to the alignment of the
343 // record itself.
344 Size = (Size + (Alignment-1)) & ~(Alignment-1);
345}
346
347void ASTRecordLayoutBuilder::UpdateAlignment(unsigned NewAlignment) {
348 if (NewAlignment <= Alignment)
349 return;
350
351 assert(llvm::isPowerOf2_32(NewAlignment && "Alignment not a power of 2"));
352
353 Alignment = NewAlignment;
354}
355
356const ASTRecordLayout *
357ASTRecordLayoutBuilder::ComputeLayout(ASTContext &Ctx,
358 const RecordDecl *D) {
359 ASTRecordLayoutBuilder Builder(Ctx);
360
361 Builder.Layout(D);
362
Anders Carlssonfc8cfa82009-07-28 19:24:15 +0000363 if (!isa<CXXRecordDecl>(D))
364 return new ASTRecordLayout(Builder.Size, Builder.Alignment, Builder.Size,
365 Builder.FieldOffsets.data(),
366 Builder.FieldOffsets.size());
Anders Carlsson6d9f6f32009-07-19 00:18:47 +0000367
Anders Carlssonfc8cfa82009-07-28 19:24:15 +0000368 // FIXME: This is not always correct. See the part about bitfields at
369 // http://www.codesourcery.com/public/cxx-abi/abi.html#POD for more info.
370 // FIXME: IsPODForThePurposeOfLayout should be stored in the record layout.
371 bool IsPODForThePurposeOfLayout = cast<CXXRecordDecl>(D)->isPOD();
372
373 assert(Builder.Bases.size() == Builder.BaseOffsets.size() &&
374 "Base offsets vector must be same size as bases vector!");
375
376 // FIXME: This should be done in FinalizeLayout.
Anders Carlsson6d9f6f32009-07-19 00:18:47 +0000377 uint64_t DataSize =
378 IsPODForThePurposeOfLayout ? Builder.Size : Builder.NextOffset;
Anders Carlssonfc8cfa82009-07-28 19:24:15 +0000379 uint64_t NonVirtualSize =
380 IsPODForThePurposeOfLayout ? DataSize : Builder.NonVirtualSize;
Anders Carlsson6d9f6f32009-07-19 00:18:47 +0000381
382 return new ASTRecordLayout(Builder.Size, Builder.Alignment, DataSize,
Anders Carlsson4f516282009-07-18 20:50:59 +0000383 Builder.FieldOffsets.data(),
Anders Carlssonfc8cfa82009-07-28 19:24:15 +0000384 Builder.FieldOffsets.size(),
385 NonVirtualSize,
386 Builder.NonVirtualAlignment,
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000387 Builder.PrimaryBase,
Anders Carlssonfc8cfa82009-07-28 19:24:15 +0000388 Builder.Bases.data(),
389 Builder.BaseOffsets.data(),
390 Builder.Bases.size());
Anders Carlsson4f516282009-07-18 20:50:59 +0000391}
392
393const ASTRecordLayout *
394ASTRecordLayoutBuilder::ComputeLayout(ASTContext &Ctx,
395 const ObjCInterfaceDecl *D,
396 const ObjCImplementationDecl *Impl) {
397 ASTRecordLayoutBuilder Builder(Ctx);
398
399 Builder.Layout(D, Impl);
400
401 return new ASTRecordLayout(Builder.Size, Builder.Alignment,
402 Builder.NextOffset,
Anders Carlsson79474332009-07-18 20:20:21 +0000403 Builder.FieldOffsets.data(),
404 Builder.FieldOffsets.size());
405}