blob: 4390e66c8b1c491a1ff5713bd08fce9bd5d426a6 [file] [log] [blame]
Anders Carlsson35a36eb2010-05-26 05:41:04 +00001//=== RecordLayoutBuilder.cpp - Helper class for building record layouts ---==//
Anders Carlsson79474332009-07-18 20:20:21 +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
Chandler Carruth3a022472012-12-04 09:13:33 +000010#include "clang/AST/RecordLayout.h"
Benjamin Kramer2ef30312012-07-04 18:45:14 +000011#include "clang/AST/ASTContext.h"
Anders Carlsson79474332009-07-18 20:20:21 +000012#include "clang/AST/Attr.h"
Anders Carlsson5adde292010-11-24 22:55:48 +000013#include "clang/AST/CXXInheritance.h"
Anders Carlsson79474332009-07-18 20:20:21 +000014#include "clang/AST/Decl.h"
Anders Carlsson6d9f6f32009-07-19 00:18:47 +000015#include "clang/AST/DeclCXX.h"
Anders Carlsson4f516282009-07-18 20:50:59 +000016#include "clang/AST/DeclObjC.h"
Anders Carlsson79474332009-07-18 20:20:21 +000017#include "clang/AST/Expr.h"
Anders Carlsson79474332009-07-18 20:20:21 +000018#include "clang/Basic/TargetInfo.h"
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +000019#include "clang/Sema/SemaDiagnostic.h"
Daniel Dunbaraa423af2010-04-08 02:59:49 +000020#include "llvm/ADT/SmallSet.h"
Ted Kremenekf75d0892011-03-19 01:00:36 +000021#include "llvm/Support/CrashRecoveryContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "llvm/Support/Format.h"
23#include "llvm/Support/MathExtras.h"
Anders Carlsson79474332009-07-18 20:20:21 +000024
25using namespace clang;
26
Benjamin Kramerc7656cd2010-05-26 09:58:31 +000027namespace {
Anders Carlssonf58de112010-05-26 15:32:58 +000028
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000029/// BaseSubobjectInfo - Represents a single base subobject in a complete class.
30/// For a class hierarchy like
31///
32/// class A { };
33/// class B : A { };
34/// class C : A, B { };
35///
36/// The BaseSubobjectInfo graph for C will have three BaseSubobjectInfo
37/// instances, one for B and two for A.
38///
39/// If a base is virtual, it will only have one BaseSubobjectInfo allocated.
40struct BaseSubobjectInfo {
41 /// Class - The class for this base info.
Anders Carlsson056818f2010-05-28 21:13:31 +000042 const CXXRecordDecl *Class;
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000043
44 /// IsVirtual - Whether the BaseInfo represents a virtual base or not.
Anders Carlsson056818f2010-05-28 21:13:31 +000045 bool IsVirtual;
46
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000047 /// Bases - Information about the base subobjects.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000048 SmallVector<BaseSubobjectInfo*, 4> Bases;
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000049
Anders Carlssone3c24c72010-05-29 17:35:14 +000050 /// PrimaryVirtualBaseInfo - Holds the base info for the primary virtual base
51 /// of this base info (if one exists).
52 BaseSubobjectInfo *PrimaryVirtualBaseInfo;
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000053
54 // FIXME: Document.
55 const BaseSubobjectInfo *Derived;
Anders Carlsson056818f2010-05-28 21:13:31 +000056};
57
Anders Carlssonf58de112010-05-26 15:32:58 +000058/// EmptySubobjectMap - Keeps track of which empty subobjects exist at different
59/// offsets while laying out a C++ class.
60class EmptySubobjectMap {
Jay Foad39c79802011-01-12 09:06:06 +000061 const ASTContext &Context;
Anders Carlsson233e2722010-10-31 21:54:55 +000062 uint64_t CharWidth;
63
Anders Carlssonf58de112010-05-26 15:32:58 +000064 /// Class - The class whose empty entries we're keeping track of.
65 const CXXRecordDecl *Class;
Daniel Dunbar592a85c2010-05-27 02:25:46 +000066
Anders Carlsson439edd12010-05-27 05:41:06 +000067 /// EmptyClassOffsets - A map from offsets to empty record decls.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000068 typedef SmallVector<const CXXRecordDecl *, 1> ClassVectorTy;
Anders Carlssonf8f756d2010-10-31 21:22:43 +000069 typedef llvm::DenseMap<CharUnits, ClassVectorTy> EmptyClassOffsetsMapTy;
Anders Carlsson439edd12010-05-27 05:41:06 +000070 EmptyClassOffsetsMapTy EmptyClassOffsets;
71
Anders Carlssoncc5de092010-06-08 15:56:03 +000072 /// MaxEmptyClassOffset - The highest offset known to contain an empty
73 /// base subobject.
Anders Carlsson725190f2010-10-31 21:39:24 +000074 CharUnits MaxEmptyClassOffset;
Anders Carlssoncc5de092010-06-08 15:56:03 +000075
Daniel Dunbar592a85c2010-05-27 02:25:46 +000076 /// ComputeEmptySubobjectSizes - Compute the size of the largest base or
Anders Carlssonc5ca1f72010-05-26 15:54:25 +000077 /// member subobject that is empty.
78 void ComputeEmptySubobjectSizes();
Anders Carlsson439edd12010-05-27 05:41:06 +000079
Anders Carlsson725190f2010-10-31 21:39:24 +000080 void AddSubobjectAtOffset(const CXXRecordDecl *RD, CharUnits Offset);
Anders Carlssondb319762010-05-27 18:20:57 +000081
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000082 void UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +000083 CharUnits Offset, bool PlacingEmptyBase);
Anders Carlsson439edd12010-05-27 05:41:06 +000084
Anders Carlssondb319762010-05-27 18:20:57 +000085 void UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD,
86 const CXXRecordDecl *Class,
Anders Carlsson28466ab2010-10-31 22:13:23 +000087 CharUnits Offset);
88 void UpdateEmptyFieldSubobjects(const FieldDecl *FD, CharUnits Offset);
Anders Carlssondb319762010-05-27 18:20:57 +000089
Anders Carlssoncc5de092010-06-08 15:56:03 +000090 /// AnyEmptySubobjectsBeyondOffset - Returns whether there are any empty
91 /// subobjects beyond the given offset.
Anders Carlsson725190f2010-10-31 21:39:24 +000092 bool AnyEmptySubobjectsBeyondOffset(CharUnits Offset) const {
Anders Carlssoncc5de092010-06-08 15:56:03 +000093 return Offset <= MaxEmptyClassOffset;
94 }
95
Anders Carlsson233e2722010-10-31 21:54:55 +000096 CharUnits
97 getFieldOffset(const ASTRecordLayout &Layout, unsigned FieldNo) const {
98 uint64_t FieldOffset = Layout.getFieldOffset(FieldNo);
99 assert(FieldOffset % CharWidth == 0 &&
100 "Field offset not at char boundary!");
101
Ken Dyck7c4026b2011-01-24 01:28:50 +0000102 return Context.toCharUnitsFromBits(FieldOffset);
Anders Carlssonf8f756d2010-10-31 21:22:43 +0000103 }
Anders Carlssonf8f756d2010-10-31 21:22:43 +0000104
Charles Davisc2c576a2010-08-19 00:55:19 +0000105protected:
Anders Carlsson725190f2010-10-31 21:39:24 +0000106 bool CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD,
107 CharUnits Offset) const;
Charles Davisc2c576a2010-08-19 00:55:19 +0000108
109 bool CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000110 CharUnits Offset);
Charles Davisc2c576a2010-08-19 00:55:19 +0000111
112 bool CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD,
113 const CXXRecordDecl *Class,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000114 CharUnits Offset) const;
Charles Davisc2c576a2010-08-19 00:55:19 +0000115 bool CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD,
Anders Carlsson233e2722010-10-31 21:54:55 +0000116 CharUnits Offset) const;
Charles Davisc2c576a2010-08-19 00:55:19 +0000117
Anders Carlssonf58de112010-05-26 15:32:58 +0000118public:
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000119 /// This holds the size of the largest empty subobject (either a base
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000120 /// or a member). Will be zero if the record being built doesn't contain
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000121 /// any empty classes.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000122 CharUnits SizeOfLargestEmptySubobject;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000123
Jay Foad39c79802011-01-12 09:06:06 +0000124 EmptySubobjectMap(const ASTContext &Context, const CXXRecordDecl *Class)
Anders Carlsson28466ab2010-10-31 22:13:23 +0000125 : Context(Context), CharWidth(Context.getCharWidth()), Class(Class) {
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000126 ComputeEmptySubobjectSizes();
127 }
128
129 /// CanPlaceBaseAtOffset - Return whether the given base class can be placed
130 /// at the given offset.
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000131 /// Returns false if placing the record will result in two components
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000132 /// (direct or indirect) of the same type having the same offset.
Anders Carlssoncc5de092010-06-08 15:56:03 +0000133 bool CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000134 CharUnits Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000135
136 /// CanPlaceFieldAtOffset - Return whether a field can be placed at the given
137 /// offset.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000138 bool CanPlaceFieldAtOffset(const FieldDecl *FD, CharUnits Offset);
Anders Carlssonf58de112010-05-26 15:32:58 +0000139};
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000140
141void EmptySubobjectMap::ComputeEmptySubobjectSizes() {
142 // Check the bases.
143 for (CXXRecordDecl::base_class_const_iterator I = Class->bases_begin(),
144 E = Class->bases_end(); I != E; ++I) {
145 const CXXRecordDecl *BaseDecl =
146 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
147
Anders Carlsson28466ab2010-10-31 22:13:23 +0000148 CharUnits EmptySize;
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000149 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
150 if (BaseDecl->isEmpty()) {
151 // If the class decl is empty, get its size.
Ken Dyckc8ae5502011-02-09 01:59:34 +0000152 EmptySize = Layout.getSize();
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000153 } else {
154 // Otherwise, we get the largest empty subobject for the decl.
155 EmptySize = Layout.getSizeOfLargestEmptySubobject();
156 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000157
Anders Carlsson28466ab2010-10-31 22:13:23 +0000158 if (EmptySize > SizeOfLargestEmptySubobject)
159 SizeOfLargestEmptySubobject = EmptySize;
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000160 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000161
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000162 // Check the fields.
163 for (CXXRecordDecl::field_iterator I = Class->field_begin(),
164 E = Class->field_end(); I != E; ++I) {
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000165
166 const RecordType *RT =
David Blaikie40ed2972012-06-06 20:45:41 +0000167 Context.getBaseElementType(I->getType())->getAs<RecordType>();
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000168
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000169 // We only care about record types.
170 if (!RT)
171 continue;
172
Anders Carlsson28466ab2010-10-31 22:13:23 +0000173 CharUnits EmptySize;
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000174 const CXXRecordDecl *MemberDecl = cast<CXXRecordDecl>(RT->getDecl());
175 const ASTRecordLayout &Layout = Context.getASTRecordLayout(MemberDecl);
176 if (MemberDecl->isEmpty()) {
177 // If the class decl is empty, get its size.
Ken Dyckc8ae5502011-02-09 01:59:34 +0000178 EmptySize = Layout.getSize();
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000179 } else {
180 // Otherwise, we get the largest empty subobject for the decl.
181 EmptySize = Layout.getSizeOfLargestEmptySubobject();
182 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000183
Anders Carlsson28466ab2010-10-31 22:13:23 +0000184 if (EmptySize > SizeOfLargestEmptySubobject)
185 SizeOfLargestEmptySubobject = EmptySize;
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000186 }
187}
188
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000189bool
Anders Carlssondb319762010-05-27 18:20:57 +0000190EmptySubobjectMap::CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD,
Anders Carlsson725190f2010-10-31 21:39:24 +0000191 CharUnits Offset) const {
Anders Carlssondb319762010-05-27 18:20:57 +0000192 // We only need to check empty bases.
193 if (!RD->isEmpty())
194 return true;
195
Anders Carlsson725190f2010-10-31 21:39:24 +0000196 EmptyClassOffsetsMapTy::const_iterator I = EmptyClassOffsets.find(Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000197 if (I == EmptyClassOffsets.end())
198 return true;
199
200 const ClassVectorTy& Classes = I->second;
201 if (std::find(Classes.begin(), Classes.end(), RD) == Classes.end())
202 return true;
203
204 // There is already an empty class of the same type at this offset.
205 return false;
206}
207
208void EmptySubobjectMap::AddSubobjectAtOffset(const CXXRecordDecl *RD,
Anders Carlsson725190f2010-10-31 21:39:24 +0000209 CharUnits Offset) {
Anders Carlssondb319762010-05-27 18:20:57 +0000210 // We only care about empty bases.
211 if (!RD->isEmpty())
212 return;
213
Reid Kleckner369f3162013-05-14 20:30:42 +0000214 // If we have empty structures inside a union, we can assign both
Rafael Espindola7bcde192010-12-29 23:02:58 +0000215 // the same offset. Just avoid pushing them twice in the list.
Anders Carlsson725190f2010-10-31 21:39:24 +0000216 ClassVectorTy& Classes = EmptyClassOffsets[Offset];
Rafael Espindola7bcde192010-12-29 23:02:58 +0000217 if (std::find(Classes.begin(), Classes.end(), RD) != Classes.end())
218 return;
219
Anders Carlssondb319762010-05-27 18:20:57 +0000220 Classes.push_back(RD);
Anders Carlssoncc5de092010-06-08 15:56:03 +0000221
222 // Update the empty class offset.
Anders Carlsson725190f2010-10-31 21:39:24 +0000223 if (Offset > MaxEmptyClassOffset)
224 MaxEmptyClassOffset = Offset;
Anders Carlssondb319762010-05-27 18:20:57 +0000225}
226
227bool
Anders Carlsson28466ab2010-10-31 22:13:23 +0000228EmptySubobjectMap::CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info,
229 CharUnits Offset) {
Anders Carlsson45c1d282010-06-08 16:20:35 +0000230 // We don't have to keep looking past the maximum offset that's known to
231 // contain an empty class.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000232 if (!AnyEmptySubobjectsBeyondOffset(Offset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000233 return true;
234
Anders Carlsson28466ab2010-10-31 22:13:23 +0000235 if (!CanPlaceSubobjectAtOffset(Info->Class, Offset))
Anders Carlssondb319762010-05-27 18:20:57 +0000236 return false;
237
Anders Carlsson439edd12010-05-27 05:41:06 +0000238 // Traverse all non-virtual bases.
Anders Carlssona7774a62010-05-29 21:10:24 +0000239 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
Anders Carlsson439edd12010-05-27 05:41:06 +0000240 for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) {
Anders Carlssona7f3cdb2010-05-28 21:24:37 +0000241 BaseSubobjectInfo* Base = Info->Bases[I];
Anders Carlsson439edd12010-05-27 05:41:06 +0000242 if (Base->IsVirtual)
243 continue;
244
Anders Carlsson0a14ee92010-11-01 00:21:58 +0000245 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
Anders Carlsson439edd12010-05-27 05:41:06 +0000246
247 if (!CanPlaceBaseSubobjectAtOffset(Base, BaseOffset))
248 return false;
249 }
250
Anders Carlssone3c24c72010-05-29 17:35:14 +0000251 if (Info->PrimaryVirtualBaseInfo) {
252 BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
Anders Carlsson439edd12010-05-27 05:41:06 +0000253
254 if (Info == PrimaryVirtualBaseInfo->Derived) {
255 if (!CanPlaceBaseSubobjectAtOffset(PrimaryVirtualBaseInfo, Offset))
256 return false;
257 }
258 }
259
Anders Carlssondb319762010-05-27 18:20:57 +0000260 // Traverse all member variables.
261 unsigned FieldNo = 0;
262 for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(),
263 E = Info->Class->field_end(); I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +0000264 if (I->isBitField())
Anders Carlsson233e2722010-10-31 21:54:55 +0000265 continue;
266
Anders Carlsson28466ab2010-10-31 22:13:23 +0000267 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
David Blaikie40ed2972012-06-06 20:45:41 +0000268 if (!CanPlaceFieldSubobjectAtOffset(*I, FieldOffset))
Anders Carlssondb319762010-05-27 18:20:57 +0000269 return false;
270 }
271
Anders Carlsson439edd12010-05-27 05:41:06 +0000272 return true;
273}
274
Anders Carlssona7f3cdb2010-05-28 21:24:37 +0000275void EmptySubobjectMap::UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000276 CharUnits Offset,
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000277 bool PlacingEmptyBase) {
278 if (!PlacingEmptyBase && Offset >= SizeOfLargestEmptySubobject) {
279 // We know that the only empty subobjects that can conflict with empty
280 // subobject of non-empty bases, are empty bases that can be placed at
281 // offset zero. Because of this, we only need to keep track of empty base
282 // subobjects with offsets less than the size of the largest empty
283 // subobject for our class.
284 return;
285 }
286
Anders Carlsson28466ab2010-10-31 22:13:23 +0000287 AddSubobjectAtOffset(Info->Class, Offset);
Anders Carlssona7774a62010-05-29 21:10:24 +0000288
Anders Carlsson439edd12010-05-27 05:41:06 +0000289 // Traverse all non-virtual bases.
Anders Carlssona7774a62010-05-29 21:10:24 +0000290 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
Anders Carlsson439edd12010-05-27 05:41:06 +0000291 for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) {
Anders Carlssona7f3cdb2010-05-28 21:24:37 +0000292 BaseSubobjectInfo* Base = Info->Bases[I];
Anders Carlsson439edd12010-05-27 05:41:06 +0000293 if (Base->IsVirtual)
294 continue;
Anders Carlssona7774a62010-05-29 21:10:24 +0000295
Anders Carlsson0a14ee92010-11-01 00:21:58 +0000296 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000297 UpdateEmptyBaseSubobjects(Base, BaseOffset, PlacingEmptyBase);
Anders Carlsson439edd12010-05-27 05:41:06 +0000298 }
299
Anders Carlssone3c24c72010-05-29 17:35:14 +0000300 if (Info->PrimaryVirtualBaseInfo) {
301 BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
Anders Carlsson439edd12010-05-27 05:41:06 +0000302
303 if (Info == PrimaryVirtualBaseInfo->Derived)
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000304 UpdateEmptyBaseSubobjects(PrimaryVirtualBaseInfo, Offset,
305 PlacingEmptyBase);
Anders Carlsson439edd12010-05-27 05:41:06 +0000306 }
Anders Carlssondb319762010-05-27 18:20:57 +0000307
Anders Carlssondb319762010-05-27 18:20:57 +0000308 // Traverse all member variables.
309 unsigned FieldNo = 0;
310 for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(),
311 E = Info->Class->field_end(); I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +0000312 if (I->isBitField())
Anders Carlsson233e2722010-10-31 21:54:55 +0000313 continue;
Anders Carlssona7774a62010-05-29 21:10:24 +0000314
Anders Carlsson28466ab2010-10-31 22:13:23 +0000315 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
David Blaikie40ed2972012-06-06 20:45:41 +0000316 UpdateEmptyFieldSubobjects(*I, FieldOffset);
Anders Carlssondb319762010-05-27 18:20:57 +0000317 }
Anders Carlsson439edd12010-05-27 05:41:06 +0000318}
319
Anders Carlssona60b86a2010-05-29 20:49:49 +0000320bool EmptySubobjectMap::CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000321 CharUnits Offset) {
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000322 // If we know this class doesn't have any empty subobjects we don't need to
323 // bother checking.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000324 if (SizeOfLargestEmptySubobject.isZero())
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000325 return true;
326
Anders Carlsson439edd12010-05-27 05:41:06 +0000327 if (!CanPlaceBaseSubobjectAtOffset(Info, Offset))
328 return false;
Anders Carlssondb319762010-05-27 18:20:57 +0000329
330 // We are able to place the base at this offset. Make sure to update the
331 // empty base subobject map.
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000332 UpdateEmptyBaseSubobjects(Info, Offset, Info->Class->isEmpty());
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000333 return true;
334}
335
Anders Carlssondb319762010-05-27 18:20:57 +0000336bool
337EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD,
338 const CXXRecordDecl *Class,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000339 CharUnits Offset) const {
Anders Carlsson45c1d282010-06-08 16:20:35 +0000340 // We don't have to keep looking past the maximum offset that's known to
341 // contain an empty class.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000342 if (!AnyEmptySubobjectsBeyondOffset(Offset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000343 return true;
344
Anders Carlsson28466ab2010-10-31 22:13:23 +0000345 if (!CanPlaceSubobjectAtOffset(RD, Offset))
Anders Carlssondb319762010-05-27 18:20:57 +0000346 return false;
347
348 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
349
350 // Traverse all non-virtual bases.
351 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
352 E = RD->bases_end(); I != E; ++I) {
353 if (I->isVirtual())
354 continue;
355
356 const CXXRecordDecl *BaseDecl =
357 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
358
Anders Carlsson0a14ee92010-11-01 00:21:58 +0000359 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
Anders Carlssondb319762010-05-27 18:20:57 +0000360 if (!CanPlaceFieldSubobjectAtOffset(BaseDecl, Class, BaseOffset))
361 return false;
362 }
363
Anders Carlsson44687202010-06-08 19:09:24 +0000364 if (RD == Class) {
365 // This is the most derived class, traverse virtual bases as well.
366 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
367 E = RD->vbases_end(); I != E; ++I) {
368 const CXXRecordDecl *VBaseDecl =
369 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
370
Anders Carlsson3f018712010-10-31 23:45:59 +0000371 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
Anders Carlsson44687202010-06-08 19:09:24 +0000372 if (!CanPlaceFieldSubobjectAtOffset(VBaseDecl, Class, VBaseOffset))
373 return false;
374 }
375 }
376
Anders Carlssondb319762010-05-27 18:20:57 +0000377 // Traverse all member variables.
378 unsigned FieldNo = 0;
379 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
380 I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +0000381 if (I->isBitField())
Anders Carlsson233e2722010-10-31 21:54:55 +0000382 continue;
383
Anders Carlsson28466ab2010-10-31 22:13:23 +0000384 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
Anders Carlssondb319762010-05-27 18:20:57 +0000385
David Blaikie40ed2972012-06-06 20:45:41 +0000386 if (!CanPlaceFieldSubobjectAtOffset(*I, FieldOffset))
Anders Carlssondb319762010-05-27 18:20:57 +0000387 return false;
388 }
389
390 return true;
391}
392
Anders Carlsson233e2722010-10-31 21:54:55 +0000393bool
394EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD,
395 CharUnits Offset) const {
Anders Carlsson45c1d282010-06-08 16:20:35 +0000396 // We don't have to keep looking past the maximum offset that's known to
397 // contain an empty class.
Anders Carlsson233e2722010-10-31 21:54:55 +0000398 if (!AnyEmptySubobjectsBeyondOffset(Offset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000399 return true;
400
Anders Carlssondb319762010-05-27 18:20:57 +0000401 QualType T = FD->getType();
402 if (const RecordType *RT = T->getAs<RecordType>()) {
403 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson28466ab2010-10-31 22:13:23 +0000404 return CanPlaceFieldSubobjectAtOffset(RD, RD, Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000405 }
406
407 // If we have an array type we need to look at every element.
408 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
409 QualType ElemTy = Context.getBaseElementType(AT);
410 const RecordType *RT = ElemTy->getAs<RecordType>();
411 if (!RT)
412 return true;
413
414 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
415 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
416
417 uint64_t NumElements = Context.getConstantArrayElementCount(AT);
Anders Carlsson233e2722010-10-31 21:54:55 +0000418 CharUnits ElementOffset = Offset;
Anders Carlssondb319762010-05-27 18:20:57 +0000419 for (uint64_t I = 0; I != NumElements; ++I) {
Anders Carlsson45c1d282010-06-08 16:20:35 +0000420 // We don't have to keep looking past the maximum offset that's known to
421 // contain an empty class.
Anders Carlsson233e2722010-10-31 21:54:55 +0000422 if (!AnyEmptySubobjectsBeyondOffset(ElementOffset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000423 return true;
424
Anders Carlsson28466ab2010-10-31 22:13:23 +0000425 if (!CanPlaceFieldSubobjectAtOffset(RD, RD, ElementOffset))
Anders Carlssondb319762010-05-27 18:20:57 +0000426 return false;
427
Ken Dyckc8ae5502011-02-09 01:59:34 +0000428 ElementOffset += Layout.getSize();
Anders Carlssondb319762010-05-27 18:20:57 +0000429 }
430 }
431
432 return true;
433}
434
435bool
Anders Carlsson28466ab2010-10-31 22:13:23 +0000436EmptySubobjectMap::CanPlaceFieldAtOffset(const FieldDecl *FD,
437 CharUnits Offset) {
438 if (!CanPlaceFieldSubobjectAtOffset(FD, Offset))
Anders Carlssondb319762010-05-27 18:20:57 +0000439 return false;
440
441 // We are able to place the member variable at this offset.
442 // Make sure to update the empty base subobject map.
443 UpdateEmptyFieldSubobjects(FD, Offset);
444 return true;
445}
446
447void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD,
448 const CXXRecordDecl *Class,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000449 CharUnits Offset) {
Anders Carlssonae111dc2010-06-13 17:49:16 +0000450 // We know that the only empty subobjects that can conflict with empty
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000451 // field subobjects are subobjects of empty bases that can be placed at offset
Anders Carlssonae111dc2010-06-13 17:49:16 +0000452 // zero. Because of this, we only need to keep track of empty field
453 // subobjects with offsets less than the size of the largest empty
454 // subobject for our class.
455 if (Offset >= SizeOfLargestEmptySubobject)
456 return;
457
Anders Carlsson28466ab2010-10-31 22:13:23 +0000458 AddSubobjectAtOffset(RD, Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000459
460 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
461
462 // Traverse all non-virtual bases.
463 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
464 E = RD->bases_end(); I != E; ++I) {
465 if (I->isVirtual())
466 continue;
467
468 const CXXRecordDecl *BaseDecl =
469 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
470
Anders Carlsson0a14ee92010-11-01 00:21:58 +0000471 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
Anders Carlssondb319762010-05-27 18:20:57 +0000472 UpdateEmptyFieldSubobjects(BaseDecl, Class, BaseOffset);
473 }
474
Anders Carlsson44687202010-06-08 19:09:24 +0000475 if (RD == Class) {
476 // This is the most derived class, traverse virtual bases as well.
477 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
478 E = RD->vbases_end(); I != E; ++I) {
479 const CXXRecordDecl *VBaseDecl =
480 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
481
Anders Carlsson3f018712010-10-31 23:45:59 +0000482 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
Anders Carlsson44687202010-06-08 19:09:24 +0000483 UpdateEmptyFieldSubobjects(VBaseDecl, Class, VBaseOffset);
484 }
485 }
486
Anders Carlssondb319762010-05-27 18:20:57 +0000487 // Traverse all member variables.
488 unsigned FieldNo = 0;
489 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
490 I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +0000491 if (I->isBitField())
Anders Carlsson09814d32010-11-01 15:14:51 +0000492 continue;
493
Anders Carlsson28466ab2010-10-31 22:13:23 +0000494 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
Anders Carlssondb319762010-05-27 18:20:57 +0000495
David Blaikie40ed2972012-06-06 20:45:41 +0000496 UpdateEmptyFieldSubobjects(*I, FieldOffset);
Anders Carlssondb319762010-05-27 18:20:57 +0000497 }
498}
499
500void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const FieldDecl *FD,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000501 CharUnits Offset) {
Anders Carlssondb319762010-05-27 18:20:57 +0000502 QualType T = FD->getType();
503 if (const RecordType *RT = T->getAs<RecordType>()) {
504 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
505 UpdateEmptyFieldSubobjects(RD, RD, Offset);
506 return;
507 }
508
509 // If we have an array type we need to update every element.
510 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
511 QualType ElemTy = Context.getBaseElementType(AT);
512 const RecordType *RT = ElemTy->getAs<RecordType>();
513 if (!RT)
514 return;
515
516 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
517 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
518
519 uint64_t NumElements = Context.getConstantArrayElementCount(AT);
Anders Carlsson28466ab2010-10-31 22:13:23 +0000520 CharUnits ElementOffset = Offset;
Anders Carlssondb319762010-05-27 18:20:57 +0000521
522 for (uint64_t I = 0; I != NumElements; ++I) {
Anders Carlssonae111dc2010-06-13 17:49:16 +0000523 // We know that the only empty subobjects that can conflict with empty
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000524 // field subobjects are subobjects of empty bases that can be placed at
Anders Carlssonae111dc2010-06-13 17:49:16 +0000525 // offset zero. Because of this, we only need to keep track of empty field
526 // subobjects with offsets less than the size of the largest empty
527 // subobject for our class.
528 if (ElementOffset >= SizeOfLargestEmptySubobject)
529 return;
530
Anders Carlssondb319762010-05-27 18:20:57 +0000531 UpdateEmptyFieldSubobjects(RD, RD, ElementOffset);
Ken Dyckc8ae5502011-02-09 01:59:34 +0000532 ElementOffset += Layout.getSize();
Anders Carlssondb319762010-05-27 18:20:57 +0000533 }
534 }
535}
536
John McCalle42a3362012-05-01 08:55:32 +0000537typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> ClassSetTy;
538
Anders Carlssonc2226202010-05-26 05:58:59 +0000539class RecordLayoutBuilder {
Charles Davisc2c576a2010-08-19 00:55:19 +0000540protected:
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000541 // FIXME: Remove this and make the appropriate fields public.
542 friend class clang::ASTContext;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000543
Jay Foad39c79802011-01-12 09:06:06 +0000544 const ASTContext &Context;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000545
Anders Carlssonf58de112010-05-26 15:32:58 +0000546 EmptySubobjectMap *EmptySubobjects;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000547
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000548 /// Size - The current size of the record layout.
549 uint64_t Size;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000550
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000551 /// Alignment - The current alignment of the record layout.
Ken Dyck4731d5b2011-02-16 02:05:21 +0000552 CharUnits Alignment;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000553
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000554 /// \brief The alignment if attribute packed is not used.
Ken Dyck1300b3b2011-02-16 02:11:31 +0000555 CharUnits UnpackedAlignment;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000556
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000557 SmallVector<uint64_t, 16> FieldOffsets;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000558
Douglas Gregore9fc3772012-01-26 07:55:45 +0000559 /// \brief Whether the external AST source has provided a layout for this
560 /// record.
561 unsigned ExternalLayout : 1;
Douglas Gregor44ba7892012-01-28 00:53:29 +0000562
563 /// \brief Whether we need to infer alignment, even when we have an
564 /// externally-provided layout.
565 unsigned InferAlignment : 1;
Douglas Gregore9fc3772012-01-26 07:55:45 +0000566
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000567 /// Packed - Whether the record is packed or not.
Daniel Dunbar6da10982010-05-27 05:45:51 +0000568 unsigned Packed : 1;
569
570 unsigned IsUnion : 1;
571
572 unsigned IsMac68kAlign : 1;
Fariborz Jahanianbcb23a12011-04-26 23:52:16 +0000573
574 unsigned IsMsStruct : 1;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000575
Eli Friedman2782dac2013-06-26 20:50:34 +0000576 /// UnfilledBitsInLastUnit - If the last field laid out was a bitfield,
577 /// this contains the number of bits in the last unit that can be used for
578 /// an adjacent bitfield if necessary. The unit in question is usually
579 /// a byte, but larger units are used if IsMsStruct.
580 unsigned char UnfilledBitsInLastUnit;
581 /// LastBitfieldTypeSize - If IsMsStruct, represents the size of the type
582 /// of the previous field if it was a bitfield.
583 unsigned char LastBitfieldTypeSize;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000584
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000585 /// MaxFieldAlignment - The maximum allowed field alignment. This is set by
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000586 /// #pragma pack.
Ken Dyck02ced6f2011-02-17 01:49:42 +0000587 CharUnits MaxFieldAlignment;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000588
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000589 /// DataSize - The data size of the record being laid out.
590 uint64_t DataSize;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000591
Ken Dyckaf1c83f2011-02-16 01:52:01 +0000592 CharUnits NonVirtualSize;
Ken Dycka2d3dda2011-02-16 01:43:15 +0000593 CharUnits NonVirtualAlignment;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000594
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000595 /// PrimaryBase - the primary base class (if one exists) of the class
596 /// we're laying out.
597 const CXXRecordDecl *PrimaryBase;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000598
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000599 /// PrimaryBaseIsVirtual - Whether the primary base of the class we're laying
600 /// out is virtual.
601 bool PrimaryBaseIsVirtual;
602
John McCalle42a3362012-05-01 08:55:32 +0000603 /// HasOwnVFPtr - Whether the class provides its own vtable/vftbl
604 /// pointer, as opposed to inheriting one from a primary base class.
605 bool HasOwnVFPtr;
Eli Friedman43114f92011-10-21 22:49:56 +0000606
Anders Carlsson22f57202010-10-31 21:01:46 +0000607 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000608
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000609 /// Bases - base classes and their offsets in the record.
610 BaseOffsetsMapTy Bases;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000611
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000612 // VBases - virtual base classes and their offsets in the record.
John McCalle42a3362012-05-01 08:55:32 +0000613 ASTRecordLayout::VBaseOffsetsMapTy VBases;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000614
615 /// IndirectPrimaryBases - Virtual base classes, direct or indirect, that are
616 /// primary base classes for some other direct or indirect base class.
Anders Carlsson5adde292010-11-24 22:55:48 +0000617 CXXIndirectPrimaryBaseSet IndirectPrimaryBases;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000618
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000619 /// FirstNearlyEmptyVBase - The first nearly empty virtual base class in
620 /// inheritance graph order. Used for determining the primary base class.
621 const CXXRecordDecl *FirstNearlyEmptyVBase;
622
623 /// VisitedVirtualBases - A set of all the visited virtual bases, used to
624 /// avoid visiting virtual bases more than once.
625 llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000626
Douglas Gregore9fc3772012-01-26 07:55:45 +0000627 /// \brief Externally-provided size.
628 uint64_t ExternalSize;
629
630 /// \brief Externally-provided alignment.
631 uint64_t ExternalAlign;
632
633 /// \brief Externally-provided field offsets.
634 llvm::DenseMap<const FieldDecl *, uint64_t> ExternalFieldOffsets;
635
636 /// \brief Externally-provided direct, non-virtual base offsets.
637 llvm::DenseMap<const CXXRecordDecl *, CharUnits> ExternalBaseOffsets;
638
639 /// \brief Externally-provided virtual base offsets.
640 llvm::DenseMap<const CXXRecordDecl *, CharUnits> ExternalVirtualBaseOffsets;
641
John McCall0153cd32011-11-08 04:01:03 +0000642 RecordLayoutBuilder(const ASTContext &Context,
643 EmptySubobjectMap *EmptySubobjects)
Ken Dyck4731d5b2011-02-16 02:05:21 +0000644 : Context(Context), EmptySubobjects(EmptySubobjects), Size(0),
John McCall0153cd32011-11-08 04:01:03 +0000645 Alignment(CharUnits::One()), UnpackedAlignment(CharUnits::One()),
Douglas Gregor44ba7892012-01-28 00:53:29 +0000646 ExternalLayout(false), InferAlignment(false),
647 Packed(false), IsUnion(false), IsMac68kAlign(false), IsMsStruct(false),
Eli Friedman2782dac2013-06-26 20:50:34 +0000648 UnfilledBitsInLastUnit(0), LastBitfieldTypeSize(0),
649 MaxFieldAlignment(CharUnits::Zero()),
Ken Dyck02ced6f2011-02-17 01:49:42 +0000650 DataSize(0), NonVirtualSize(CharUnits::Zero()),
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000651 NonVirtualAlignment(CharUnits::One()),
Eli Friedman481673f2013-06-26 23:47:39 +0000652 PrimaryBase(0), PrimaryBaseIsVirtual(false),
John McCalle42a3362012-05-01 08:55:32 +0000653 HasOwnVFPtr(false),
Eli Friedman84d2d3a2011-09-27 19:12:27 +0000654 FirstNearlyEmptyVBase(0) { }
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000655
John McCall0153cd32011-11-08 04:01:03 +0000656 /// Reset this RecordLayoutBuilder to a fresh state, using the given
657 /// alignment as the initial alignment. This is used for the
658 /// correct layout of vb-table pointers in MSVC.
659 void resetWithTargetAlignment(CharUnits TargetAlignment) {
660 const ASTContext &Context = this->Context;
661 EmptySubobjectMap *EmptySubobjects = this->EmptySubobjects;
662 this->~RecordLayoutBuilder();
663 new (this) RecordLayoutBuilder(Context, EmptySubobjects);
664 Alignment = UnpackedAlignment = TargetAlignment;
665 }
666
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000667 void Layout(const RecordDecl *D);
Anders Carlssonc28a6c92010-05-26 15:10:00 +0000668 void Layout(const CXXRecordDecl *D);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000669 void Layout(const ObjCInterfaceDecl *D);
670
671 void LayoutFields(const RecordDecl *D);
672 void LayoutField(const FieldDecl *D);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000673 void LayoutWideBitField(uint64_t FieldSize, uint64_t TypeSize,
674 bool FieldPacked, const FieldDecl *D);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000675 void LayoutBitField(const FieldDecl *D);
John McCall0153cd32011-11-08 04:01:03 +0000676
John McCall359b8852013-01-25 22:30:49 +0000677 TargetCXXABI getCXXABI() const {
678 return Context.getTargetInfo().getCXXABI();
679 }
680
Anders Carlssone3c24c72010-05-29 17:35:14 +0000681 /// BaseSubobjectInfoAllocator - Allocator for BaseSubobjectInfo objects.
682 llvm::SpecificBumpPtrAllocator<BaseSubobjectInfo> BaseSubobjectInfoAllocator;
683
684 typedef llvm::DenseMap<const CXXRecordDecl *, BaseSubobjectInfo *>
685 BaseSubobjectInfoMapTy;
686
687 /// VirtualBaseInfo - Map from all the (direct or indirect) virtual bases
688 /// of the class we're laying out to their base subobject info.
689 BaseSubobjectInfoMapTy VirtualBaseInfo;
690
691 /// NonVirtualBaseInfo - Map from all the direct non-virtual bases of the
692 /// class we're laying out to their base subobject info.
693 BaseSubobjectInfoMapTy NonVirtualBaseInfo;
694
695 /// ComputeBaseSubobjectInfo - Compute the base subobject information for the
696 /// bases of the given class.
697 void ComputeBaseSubobjectInfo(const CXXRecordDecl *RD);
698
699 /// ComputeBaseSubobjectInfo - Compute the base subobject information for a
700 /// single class and all of its base classes.
701 BaseSubobjectInfo *ComputeBaseSubobjectInfo(const CXXRecordDecl *RD,
702 bool IsVirtual,
703 BaseSubobjectInfo *Derived);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000704
705 /// DeterminePrimaryBase - Determine the primary base of the given class.
706 void DeterminePrimaryBase(const CXXRecordDecl *RD);
707
708 void SelectPrimaryVBase(const CXXRecordDecl *RD);
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000709
Eli Friedman43114f92011-10-21 22:49:56 +0000710 void EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign);
Charles Davisc2c576a2010-08-19 00:55:19 +0000711
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000712 /// LayoutNonVirtualBases - Determines the primary base class (if any) and
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000713 /// lays it out. Will then proceed to lay out all non-virtual base clasess.
714 void LayoutNonVirtualBases(const CXXRecordDecl *RD);
715
716 /// LayoutNonVirtualBase - Lays out a single non-virtual base.
Anders Carlssonbb0e6782010-05-29 17:42:25 +0000717 void LayoutNonVirtualBase(const BaseSubobjectInfo *Base);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000718
Anders Carlssona2f8e412010-10-31 22:20:42 +0000719 void AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
720 CharUnits Offset);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000721
722 /// LayoutVirtualBases - Lays out all the virtual bases.
723 void LayoutVirtualBases(const CXXRecordDecl *RD,
724 const CXXRecordDecl *MostDerivedClass);
725
726 /// LayoutVirtualBase - Lays out a single virtual base.
Warren Hunt55d8e822013-10-23 23:53:07 +0000727 void LayoutVirtualBase(const BaseSubobjectInfo *Base);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000728
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000729 /// LayoutBase - Will lay out a base and return the offset where it was
Anders Carlssona2f8e412010-10-31 22:20:42 +0000730 /// placed, in chars.
731 CharUnits LayoutBase(const BaseSubobjectInfo *Base);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000732
Anders Carlssonc28a6c92010-05-26 15:10:00 +0000733 /// InitializeLayout - Initialize record layout for the given record decl.
Daniel Dunbar6da10982010-05-27 05:45:51 +0000734 void InitializeLayout(const Decl *D);
Anders Carlssonc28a6c92010-05-26 15:10:00 +0000735
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000736 /// FinishLayout - Finalize record layout. Adjust record size based on the
737 /// alignment.
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000738 void FinishLayout(const NamedDecl *D);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000739
Ken Dyck85ef0432011-02-19 18:58:07 +0000740 void UpdateAlignment(CharUnits NewAlignment, CharUnits UnpackedNewAlignment);
741 void UpdateAlignment(CharUnits NewAlignment) {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000742 UpdateAlignment(NewAlignment, NewAlignment);
743 }
744
Douglas Gregor44ba7892012-01-28 00:53:29 +0000745 /// \brief Retrieve the externally-supplied field offset for the given
746 /// field.
747 ///
748 /// \param Field The field whose offset is being queried.
749 /// \param ComputedOffset The offset that we've computed for this field.
750 uint64_t updateExternalFieldOffset(const FieldDecl *Field,
751 uint64_t ComputedOffset);
752
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000753 void CheckFieldPadding(uint64_t Offset, uint64_t UnpaddedOffset,
754 uint64_t UnpackedOffset, unsigned UnpackedAlign,
755 bool isPacked, const FieldDecl *D);
756
757 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000758
Ken Dyckecfc7552011-02-24 01:13:28 +0000759 CharUnits getSize() const {
Ken Dyck3c215f22011-02-24 01:33:05 +0000760 assert(Size % Context.getCharWidth() == 0);
Ken Dyckecfc7552011-02-24 01:13:28 +0000761 return Context.toCharUnitsFromBits(Size);
762 }
763 uint64_t getSizeInBits() const { return Size; }
764
765 void setSize(CharUnits NewSize) { Size = Context.toBits(NewSize); }
766 void setSize(uint64_t NewSize) { Size = NewSize; }
767
Eli Friedman84d2d3a2011-09-27 19:12:27 +0000768 CharUnits getAligment() const { return Alignment; }
769
Ken Dyckecfc7552011-02-24 01:13:28 +0000770 CharUnits getDataSize() const {
Ken Dyck3c215f22011-02-24 01:33:05 +0000771 assert(DataSize % Context.getCharWidth() == 0);
Ken Dyckecfc7552011-02-24 01:13:28 +0000772 return Context.toCharUnitsFromBits(DataSize);
773 }
774 uint64_t getDataSizeInBits() const { return DataSize; }
775
776 void setDataSize(CharUnits NewSize) { DataSize = Context.toBits(NewSize); }
777 void setDataSize(uint64_t NewSize) { DataSize = NewSize; }
778
Dmitri Gribenkoa664e5b2012-09-15 20:20:27 +0000779 RecordLayoutBuilder(const RecordLayoutBuilder &) LLVM_DELETED_FUNCTION;
780 void operator=(const RecordLayoutBuilder &) LLVM_DELETED_FUNCTION;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000781};
Benjamin Kramerc7656cd2010-05-26 09:58:31 +0000782} // end anonymous namespace
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000783
Anders Carlsson81430692009-09-22 03:02:06 +0000784void
Anders Carlssonc2226202010-05-26 05:58:59 +0000785RecordLayoutBuilder::SelectPrimaryVBase(const CXXRecordDecl *RD) {
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000786 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000787 E = RD->bases_end(); I != E; ++I) {
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000788 assert(!I->getType()->isDependentType() &&
Sebastian Redl1054fae2009-10-25 17:03:50 +0000789 "Cannot layout class with dependent bases.");
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000790
Mike Stump11289f42009-09-09 15:08:12 +0000791 const CXXRecordDecl *Base =
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000792 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000793
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000794 // Check if this is a nearly empty virtual base.
Anders Carlsson60a62632010-11-25 01:51:53 +0000795 if (I->isVirtual() && Context.isNearlyEmpty(Base)) {
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000796 // If it's not an indirect primary base, then we've found our primary
797 // base.
Anders Carlsson81430692009-09-22 03:02:06 +0000798 if (!IndirectPrimaryBases.count(Base)) {
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000799 PrimaryBase = Base;
800 PrimaryBaseIsVirtual = true;
Mike Stump6f3793b2009-08-12 21:50:08 +0000801 return;
802 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000803
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000804 // Is this the first nearly empty virtual base?
805 if (!FirstNearlyEmptyVBase)
806 FirstNearlyEmptyVBase = Base;
Mike Stump6f3793b2009-08-12 21:50:08 +0000807 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000808
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000809 SelectPrimaryVBase(Base);
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000810 if (PrimaryBase)
Zhongxing Xuec345b72010-02-15 04:28:35 +0000811 return;
Mike Stump6f3793b2009-08-12 21:50:08 +0000812 }
813}
814
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000815/// DeterminePrimaryBase - Determine the primary base of the given class.
Anders Carlssonc2226202010-05-26 05:58:59 +0000816void RecordLayoutBuilder::DeterminePrimaryBase(const CXXRecordDecl *RD) {
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000817 // If the class isn't dynamic, it won't have a primary base.
818 if (!RD->isDynamicClass())
819 return;
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000820
Anders Carlsson81430692009-09-22 03:02:06 +0000821 // Compute all the primary virtual bases for all of our direct and
Mike Stump590a7c72009-08-13 23:26:06 +0000822 // indirect bases, and record all their primary virtual base classes.
Anders Carlsson5adde292010-11-24 22:55:48 +0000823 RD->getIndirectPrimaryBases(IndirectPrimaryBases);
Mike Stump590a7c72009-08-13 23:26:06 +0000824
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000825 // If the record has a dynamic base class, attempt to choose a primary base
826 // class. It is the first (in direct base class order) non-virtual dynamic
Anders Carlsson81430692009-09-22 03:02:06 +0000827 // base class, if one exists.
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000828 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000829 e = RD->bases_end(); i != e; ++i) {
Anders Carlsson03ff3792009-11-27 22:05:05 +0000830 // Ignore virtual bases.
831 if (i->isVirtual())
832 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000833
Anders Carlsson03ff3792009-11-27 22:05:05 +0000834 const CXXRecordDecl *Base =
835 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
836
Warren Hunt55d8e822013-10-23 23:53:07 +0000837 if (Base->isDynamicClass()) {
Anders Carlsson03ff3792009-11-27 22:05:05 +0000838 // We found it.
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000839 PrimaryBase = Base;
840 PrimaryBaseIsVirtual = false;
Anders Carlsson03ff3792009-11-27 22:05:05 +0000841 return;
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000842 }
843 }
844
Eli Friedman5e9534b2011-10-18 00:55:28 +0000845 // Under the Itanium ABI, if there is no non-virtual primary base class,
846 // try to compute the primary virtual base. The primary virtual base is
847 // the first nearly empty virtual base that is not an indirect primary
848 // virtual base class, if one exists.
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000849 if (RD->getNumVBases() != 0) {
850 SelectPrimaryVBase(RD);
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000851 if (PrimaryBase)
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000852 return;
853 }
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000854
Eli Friedman5e9534b2011-10-18 00:55:28 +0000855 // Otherwise, it is the first indirect primary base class, if one exists.
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000856 if (FirstNearlyEmptyVBase) {
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000857 PrimaryBase = FirstNearlyEmptyVBase;
858 PrimaryBaseIsVirtual = true;
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000859 return;
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000860 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000861
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000862 assert(!PrimaryBase && "Should not get here with a primary base!");
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000863}
864
Anders Carlssone3c24c72010-05-29 17:35:14 +0000865BaseSubobjectInfo *
866RecordLayoutBuilder::ComputeBaseSubobjectInfo(const CXXRecordDecl *RD,
867 bool IsVirtual,
868 BaseSubobjectInfo *Derived) {
869 BaseSubobjectInfo *Info;
870
871 if (IsVirtual) {
872 // Check if we already have info about this virtual base.
873 BaseSubobjectInfo *&InfoSlot = VirtualBaseInfo[RD];
874 if (InfoSlot) {
875 assert(InfoSlot->Class == RD && "Wrong class for virtual base info!");
876 return InfoSlot;
877 }
878
879 // We don't, create it.
880 InfoSlot = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
881 Info = InfoSlot;
882 } else {
883 Info = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
884 }
885
886 Info->Class = RD;
887 Info->IsVirtual = IsVirtual;
888 Info->Derived = 0;
889 Info->PrimaryVirtualBaseInfo = 0;
890
891 const CXXRecordDecl *PrimaryVirtualBase = 0;
892 BaseSubobjectInfo *PrimaryVirtualBaseInfo = 0;
893
894 // Check if this base has a primary virtual base.
895 if (RD->getNumVBases()) {
896 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Anders Carlsson7f95cd12010-11-24 23:12:57 +0000897 if (Layout.isPrimaryBaseVirtual()) {
Anders Carlssone3c24c72010-05-29 17:35:14 +0000898 // This base does have a primary virtual base.
899 PrimaryVirtualBase = Layout.getPrimaryBase();
900 assert(PrimaryVirtualBase && "Didn't have a primary virtual base!");
901
902 // Now check if we have base subobject info about this primary base.
903 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
904
905 if (PrimaryVirtualBaseInfo) {
906 if (PrimaryVirtualBaseInfo->Derived) {
907 // We did have info about this primary base, and it turns out that it
908 // has already been claimed as a primary virtual base for another
909 // base.
910 PrimaryVirtualBase = 0;
911 } else {
912 // We can claim this base as our primary base.
913 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
914 PrimaryVirtualBaseInfo->Derived = Info;
915 }
916 }
917 }
918 }
919
920 // Now go through all direct bases.
921 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
922 E = RD->bases_end(); I != E; ++I) {
923 bool IsVirtual = I->isVirtual();
924
925 const CXXRecordDecl *BaseDecl =
926 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
927
928 Info->Bases.push_back(ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, Info));
929 }
930
931 if (PrimaryVirtualBase && !PrimaryVirtualBaseInfo) {
932 // Traversing the bases must have created the base info for our primary
933 // virtual base.
934 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
935 assert(PrimaryVirtualBaseInfo &&
936 "Did not create a primary virtual base!");
937
938 // Claim the primary virtual base as our primary virtual base.
939 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
940 PrimaryVirtualBaseInfo->Derived = Info;
941 }
942
943 return Info;
944}
945
946void RecordLayoutBuilder::ComputeBaseSubobjectInfo(const CXXRecordDecl *RD) {
947 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
948 E = RD->bases_end(); I != E; ++I) {
949 bool IsVirtual = I->isVirtual();
950
951 const CXXRecordDecl *BaseDecl =
952 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
953
954 // Compute the base subobject info for this base.
955 BaseSubobjectInfo *Info = ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, 0);
956
957 if (IsVirtual) {
958 // ComputeBaseInfo has already added this base for us.
959 assert(VirtualBaseInfo.count(BaseDecl) &&
960 "Did not add virtual base!");
961 } else {
962 // Add the base info to the map of non-virtual bases.
963 assert(!NonVirtualBaseInfo.count(BaseDecl) &&
964 "Non-virtual base already exists!");
965 NonVirtualBaseInfo.insert(std::make_pair(BaseDecl, Info));
966 }
967 }
968}
969
Anders Carlsson09ffa322010-03-10 22:21:28 +0000970void
Eli Friedman43114f92011-10-21 22:49:56 +0000971RecordLayoutBuilder::EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign) {
Eli Friedman5e9534b2011-10-18 00:55:28 +0000972 CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
973
974 // The maximum field alignment overrides base align.
975 if (!MaxFieldAlignment.isZero()) {
976 BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
977 UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
978 }
979
980 // Round up the current record size to pointer alignment.
Eli Friedman43114f92011-10-21 22:49:56 +0000981 setSize(getSize().RoundUpToAlignment(BaseAlign));
982 setDataSize(getSize());
Eli Friedman5e9534b2011-10-18 00:55:28 +0000983
984 // Update the alignment.
985 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
986}
987
988void
Anders Carlssonc2226202010-05-26 05:58:59 +0000989RecordLayoutBuilder::LayoutNonVirtualBases(const CXXRecordDecl *RD) {
Anders Carlssone3c24c72010-05-29 17:35:14 +0000990 // Then, determine the primary base class.
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000991 DeterminePrimaryBase(RD);
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000992
Anders Carlssone3c24c72010-05-29 17:35:14 +0000993 // Compute base subobject info.
994 ComputeBaseSubobjectInfo(RD);
995
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000996 // If we have a primary base class, lay it out.
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000997 if (PrimaryBase) {
998 if (PrimaryBaseIsVirtual) {
Anders Carlssone3c24c72010-05-29 17:35:14 +0000999 // If the primary virtual base was a primary virtual base of some other
1000 // base class we'll have to steal it.
1001 BaseSubobjectInfo *PrimaryBaseInfo = VirtualBaseInfo.lookup(PrimaryBase);
1002 PrimaryBaseInfo->Derived = 0;
1003
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001004 // We have a virtual primary base, insert it as an indirect primary base.
Anders Carlssond20e7cd2010-05-26 05:20:58 +00001005 IndirectPrimaryBases.insert(PrimaryBase);
Anders Carlssonfe900962010-03-11 05:42:17 +00001006
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001007 assert(!VisitedVirtualBases.count(PrimaryBase) &&
Anders Carlssond20e7cd2010-05-26 05:20:58 +00001008 "vbase already visited!");
1009 VisitedVirtualBases.insert(PrimaryBase);
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001010
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001011 LayoutVirtualBase(PrimaryBaseInfo);
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001012 } else {
1013 BaseSubobjectInfo *PrimaryBaseInfo =
1014 NonVirtualBaseInfo.lookup(PrimaryBase);
1015 assert(PrimaryBaseInfo &&
1016 "Did not find base info for non-virtual primary base!");
1017
1018 LayoutNonVirtualBase(PrimaryBaseInfo);
1019 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001020
John McCall0153cd32011-11-08 04:01:03 +00001021 // If this class needs a vtable/vf-table and didn't get one from a
1022 // primary base, add it in now.
Warren Hunt55d8e822013-10-23 23:53:07 +00001023 } else if (RD->isDynamicClass()) {
Eli Friedman5e9534b2011-10-18 00:55:28 +00001024 assert(DataSize == 0 && "Vtable pointer must be at offset zero!");
Eli Friedman5e9534b2011-10-18 00:55:28 +00001025 CharUnits PtrWidth =
1026 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Eli Friedman43114f92011-10-21 22:49:56 +00001027 CharUnits PtrAlign =
1028 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0));
1029 EnsureVTablePointerAlignment(PtrAlign);
John McCalle42a3362012-05-01 08:55:32 +00001030 HasOwnVFPtr = true;
Eli Friedman5e9534b2011-10-18 00:55:28 +00001031 setSize(getSize() + PtrWidth);
1032 setDataSize(getSize());
1033 }
1034
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001035 // Now lay out the non-virtual bases.
1036 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001037 E = RD->bases_end(); I != E; ++I) {
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001038
Benjamin Kramer273670a2013-10-25 07:40:50 +00001039 // Ignore virtual bases.
1040 if (I->isVirtual())
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001041 continue;
1042
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001043 const CXXRecordDecl *BaseDecl =
John McCall0153cd32011-11-08 04:01:03 +00001044 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001045
John McCall0153cd32011-11-08 04:01:03 +00001046 // Skip the primary base, because we've already laid it out. The
1047 // !PrimaryBaseIsVirtual check is required because we might have a
1048 // non-virtual base of the same type as a primary virtual base.
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001049 if (BaseDecl == PrimaryBase && !PrimaryBaseIsVirtual)
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001050 continue;
1051
1052 // Lay out the base.
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001053 BaseSubobjectInfo *BaseInfo = NonVirtualBaseInfo.lookup(BaseDecl);
1054 assert(BaseInfo && "Did not find base info for non-virtual base!");
1055
1056 LayoutNonVirtualBase(BaseInfo);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001057 }
1058}
1059
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001060void RecordLayoutBuilder::LayoutNonVirtualBase(const BaseSubobjectInfo *Base) {
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001061 // Layout the base.
Anders Carlssona2f8e412010-10-31 22:20:42 +00001062 CharUnits Offset = LayoutBase(Base);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001063
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001064 // Add its base class offset.
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001065 assert(!Bases.count(Base->Class) && "base offset already exists!");
Anders Carlssona2f8e412010-10-31 22:20:42 +00001066 Bases.insert(std::make_pair(Base->Class, Offset));
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001067
1068 AddPrimaryVirtualBaseOffsets(Base, Offset);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001069}
Mike Stump2b84dd32009-11-05 04:02:15 +00001070
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001071void
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001072RecordLayoutBuilder::AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
Anders Carlssona2f8e412010-10-31 22:20:42 +00001073 CharUnits Offset) {
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001074 // This base isn't interesting, it has no virtual bases.
1075 if (!Info->Class->getNumVBases())
1076 return;
1077
1078 // First, check if we have a virtual primary base to add offsets for.
1079 if (Info->PrimaryVirtualBaseInfo) {
1080 assert(Info->PrimaryVirtualBaseInfo->IsVirtual &&
1081 "Primary virtual base is not virtual!");
1082 if (Info->PrimaryVirtualBaseInfo->Derived == Info) {
1083 // Add the offset.
1084 assert(!VBases.count(Info->PrimaryVirtualBaseInfo->Class) &&
1085 "primary vbase offset already exists!");
1086 VBases.insert(std::make_pair(Info->PrimaryVirtualBaseInfo->Class,
John McCalle42a3362012-05-01 08:55:32 +00001087 ASTRecordLayout::VBaseInfo(Offset, false)));
Anders Carlssonea7b1822010-04-15 16:12:58 +00001088
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001089 // Traverse the primary virtual base.
1090 AddPrimaryVirtualBaseOffsets(Info->PrimaryVirtualBaseInfo, Offset);
1091 }
Anders Carlssonea7b1822010-04-15 16:12:58 +00001092 }
1093
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001094 // Now go through all direct non-virtual bases.
1095 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
1096 for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) {
1097 const BaseSubobjectInfo *Base = Info->Bases[I];
1098 if (Base->IsVirtual)
Anders Carlssonea7b1822010-04-15 16:12:58 +00001099 continue;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001100
Anders Carlsson0a14ee92010-11-01 00:21:58 +00001101 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001102 AddPrimaryVirtualBaseOffsets(Base, BaseOffset);
Anders Carlssonea7b1822010-04-15 16:12:58 +00001103 }
1104}
1105
1106void
Anders Carlssonc2226202010-05-26 05:58:59 +00001107RecordLayoutBuilder::LayoutVirtualBases(const CXXRecordDecl *RD,
Anders Carlssonea7b1822010-04-15 16:12:58 +00001108 const CXXRecordDecl *MostDerivedClass) {
Anders Carlssonde710c92010-03-11 04:33:54 +00001109 const CXXRecordDecl *PrimaryBase;
Anders Carlsson291279e2010-04-10 18:42:27 +00001110 bool PrimaryBaseIsVirtual;
Anders Carlssonfe900962010-03-11 05:42:17 +00001111
Anders Carlsson291279e2010-04-10 18:42:27 +00001112 if (MostDerivedClass == RD) {
Anders Carlssond20e7cd2010-05-26 05:20:58 +00001113 PrimaryBase = this->PrimaryBase;
1114 PrimaryBaseIsVirtual = this->PrimaryBaseIsVirtual;
Anders Carlsson291279e2010-04-10 18:42:27 +00001115 } else {
Anders Carlsson5efc56e2010-04-16 15:07:51 +00001116 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Anders Carlssonde710c92010-03-11 04:33:54 +00001117 PrimaryBase = Layout.getPrimaryBase();
Anders Carlsson7f95cd12010-11-24 23:12:57 +00001118 PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
Anders Carlsson291279e2010-04-10 18:42:27 +00001119 }
1120
Anders Carlssonf7b7a1e2010-03-11 04:24:02 +00001121 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1122 E = RD->bases_end(); I != E; ++I) {
1123 assert(!I->getType()->isDependentType() &&
Sebastian Redl1054fae2009-10-25 17:03:50 +00001124 "Cannot layout class with dependent bases.");
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001125
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001126 const CXXRecordDecl *BaseDecl =
John McCall0153cd32011-11-08 04:01:03 +00001127 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
Anders Carlssonf7b7a1e2010-03-11 04:24:02 +00001128
1129 if (I->isVirtual()) {
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001130 if (PrimaryBase != BaseDecl || !PrimaryBaseIsVirtual) {
1131 bool IndirectPrimaryBase = IndirectPrimaryBases.count(BaseDecl);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001132
Anders Carlsson291279e2010-04-10 18:42:27 +00001133 // Only lay out the virtual base if it's not an indirect primary base.
1134 if (!IndirectPrimaryBase) {
1135 // Only visit virtual bases once.
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001136 if (!VisitedVirtualBases.insert(BaseDecl))
Anders Carlsson291279e2010-04-10 18:42:27 +00001137 continue;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001138
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001139 const BaseSubobjectInfo *BaseInfo = VirtualBaseInfo.lookup(BaseDecl);
1140 assert(BaseInfo && "Did not find virtual base info!");
1141 LayoutVirtualBase(BaseInfo);
Anders Carlsson6a848892010-03-11 04:10:39 +00001142 }
Mike Stump2b84dd32009-11-05 04:02:15 +00001143 }
Mike Stumpc2f591b2009-08-13 22:53:07 +00001144 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001145
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001146 if (!BaseDecl->getNumVBases()) {
Anders Carlssonf7b7a1e2010-03-11 04:24:02 +00001147 // This base isn't interesting since it doesn't have any virtual bases.
1148 continue;
Mike Stump996576f32009-08-16 19:04:13 +00001149 }
Anders Carlssonf7b7a1e2010-03-11 04:24:02 +00001150
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001151 LayoutVirtualBases(BaseDecl, MostDerivedClass);
Mike Stump6b2556f2009-08-06 13:41:24 +00001152 }
1153}
1154
Warren Hunt55d8e822013-10-23 23:53:07 +00001155void RecordLayoutBuilder::LayoutVirtualBase(const BaseSubobjectInfo *Base) {
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001156 assert(!Base->Derived && "Trying to lay out a primary virtual base!");
1157
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001158 // Layout the base.
Anders Carlssona2f8e412010-10-31 22:20:42 +00001159 CharUnits Offset = LayoutBase(Base);
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001160
1161 // Add its base class offset.
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001162 assert(!VBases.count(Base->Class) && "vbase offset already exists!");
John McCalle42a3362012-05-01 08:55:32 +00001163 VBases.insert(std::make_pair(Base->Class,
Warren Hunt55d8e822013-10-23 23:53:07 +00001164 ASTRecordLayout::VBaseInfo(Offset, false)));
John McCalle42a3362012-05-01 08:55:32 +00001165
Warren Hunt55d8e822013-10-23 23:53:07 +00001166 AddPrimaryVirtualBaseOffsets(Base, Offset);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001167}
1168
Anders Carlssona2f8e412010-10-31 22:20:42 +00001169CharUnits RecordLayoutBuilder::LayoutBase(const BaseSubobjectInfo *Base) {
Anders Carlssond7f3fcf2010-05-29 20:47:33 +00001170 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base->Class);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001171
Douglas Gregore9fc3772012-01-26 07:55:45 +00001172
1173 CharUnits Offset;
1174
1175 // Query the external layout to see if it provides an offset.
1176 bool HasExternalLayout = false;
1177 if (ExternalLayout) {
1178 llvm::DenseMap<const CXXRecordDecl *, CharUnits>::iterator Known;
1179 if (Base->IsVirtual) {
1180 Known = ExternalVirtualBaseOffsets.find(Base->Class);
1181 if (Known != ExternalVirtualBaseOffsets.end()) {
1182 Offset = Known->second;
1183 HasExternalLayout = true;
1184 }
1185 } else {
1186 Known = ExternalBaseOffsets.find(Base->Class);
1187 if (Known != ExternalBaseOffsets.end()) {
1188 Offset = Known->second;
1189 HasExternalLayout = true;
1190 }
1191 }
1192 }
1193
Eli Friedman69d27d22013-07-16 00:21:28 +00001194 CharUnits UnpackedBaseAlign = Layout.getNonVirtualAlign();
1195 CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
1196
Anders Carlsson09ffa322010-03-10 22:21:28 +00001197 // If we have an empty base class, try to place it at offset 0.
Anders Carlssond7f3fcf2010-05-29 20:47:33 +00001198 if (Base->Class->isEmpty() &&
Douglas Gregore9fc3772012-01-26 07:55:45 +00001199 (!HasExternalLayout || Offset == CharUnits::Zero()) &&
Anders Carlsson28466ab2010-10-31 22:13:23 +00001200 EmptySubobjects->CanPlaceBaseAtOffset(Base, CharUnits::Zero())) {
Ken Dyck1b4420e2011-02-28 02:01:38 +00001201 setSize(std::max(getSize(), Layout.getSize()));
Eli Friedman69d27d22013-07-16 00:21:28 +00001202 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001203
Anders Carlssona2f8e412010-10-31 22:20:42 +00001204 return CharUnits::Zero();
Anders Carlsson09ffa322010-03-10 22:21:28 +00001205 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001206
Argyrios Kyrtzidis8b542742010-12-09 00:35:20 +00001207 // The maximum field alignment overrides base align.
Ken Dyck02ced6f2011-02-17 01:49:42 +00001208 if (!MaxFieldAlignment.isZero()) {
Ken Dyck85ef0432011-02-19 18:58:07 +00001209 BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
1210 UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
Argyrios Kyrtzidis8b542742010-12-09 00:35:20 +00001211 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001212
Douglas Gregore9fc3772012-01-26 07:55:45 +00001213 if (!HasExternalLayout) {
1214 // Round up the current record size to the base's alignment boundary.
1215 Offset = getDataSize().RoundUpToAlignment(BaseAlign);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001216
Douglas Gregore9fc3772012-01-26 07:55:45 +00001217 // Try to place the base.
1218 while (!EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset))
1219 Offset += BaseAlign;
1220 } else {
1221 bool Allowed = EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset);
1222 (void)Allowed;
1223 assert(Allowed && "Base subobject externally placed at overlapping offset");
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001224
1225 if (InferAlignment && Offset < getDataSize().RoundUpToAlignment(BaseAlign)){
1226 // The externally-supplied base offset is before the base offset we
1227 // computed. Assume that the structure is packed.
1228 Alignment = CharUnits::One();
1229 InferAlignment = false;
1230 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00001231 }
1232
Anders Carlssond7f3fcf2010-05-29 20:47:33 +00001233 if (!Base->Class->isEmpty()) {
Anders Carlsson09ffa322010-03-10 22:21:28 +00001234 // Update the data size.
Ken Dyck1b4420e2011-02-28 02:01:38 +00001235 setDataSize(Offset + Layout.getNonVirtualSize());
Anders Carlsson09ffa322010-03-10 22:21:28 +00001236
Ken Dyck1b4420e2011-02-28 02:01:38 +00001237 setSize(std::max(getSize(), getDataSize()));
Anders Carlsson09ffa322010-03-10 22:21:28 +00001238 } else
Ken Dyck1b4420e2011-02-28 02:01:38 +00001239 setSize(std::max(getSize(), Offset + Layout.getSize()));
Anders Carlsson09ffa322010-03-10 22:21:28 +00001240
1241 // Remember max struct/class alignment.
Argyrios Kyrtzidis8b542742010-12-09 00:35:20 +00001242 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001243
Ken Dyck1b4420e2011-02-28 02:01:38 +00001244 return Offset;
Anders Carlsson09ffa322010-03-10 22:21:28 +00001245}
1246
Daniel Dunbar6da10982010-05-27 05:45:51 +00001247void RecordLayoutBuilder::InitializeLayout(const Decl *D) {
Eli Friedman9ee2d0472012-10-12 23:29:20 +00001248 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Daniel Dunbar6da10982010-05-27 05:45:51 +00001249 IsUnion = RD->isUnion();
Eli Friedman9ee2d0472012-10-12 23:29:20 +00001250 IsMsStruct = RD->isMsStruct(Context);
1251 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001252
Eli Friedman9ee2d0472012-10-12 23:29:20 +00001253 Packed = D->hasAttr<PackedAttr>();
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001254
Daniel Dunbar096ed292011-10-05 21:04:55 +00001255 // Honor the default struct packing maximum alignment flag.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001256 if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct) {
Daniel Dunbar096ed292011-10-05 21:04:55 +00001257 MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
1258 }
1259
Daniel Dunbar6da10982010-05-27 05:45:51 +00001260 // mac68k alignment supersedes maximum field alignment and attribute aligned,
1261 // and forces all structures to have 2-byte alignment. The IBM docs on it
1262 // allude to additional (more complicated) semantics, especially with regard
1263 // to bit-fields, but gcc appears not to follow that.
1264 if (D->hasAttr<AlignMac68kAttr>()) {
1265 IsMac68kAlign = true;
Ken Dyck02ced6f2011-02-17 01:49:42 +00001266 MaxFieldAlignment = CharUnits::fromQuantity(2);
Ken Dyck4731d5b2011-02-16 02:05:21 +00001267 Alignment = CharUnits::fromQuantity(2);
Daniel Dunbar6da10982010-05-27 05:45:51 +00001268 } else {
1269 if (const MaxFieldAlignmentAttr *MFAA = D->getAttr<MaxFieldAlignmentAttr>())
Ken Dyck02ced6f2011-02-17 01:49:42 +00001270 MaxFieldAlignment = Context.toCharUnitsFromBits(MFAA->getAlignment());
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001271
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001272 if (unsigned MaxAlign = D->getMaxAlignment())
Ken Dyck85ef0432011-02-19 18:58:07 +00001273 UpdateAlignment(Context.toCharUnitsFromBits(MaxAlign));
Daniel Dunbar6da10982010-05-27 05:45:51 +00001274 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00001275
1276 // If there is an external AST source, ask it for the various offsets.
1277 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
1278 if (ExternalASTSource *External = Context.getExternalSource()) {
1279 ExternalLayout = External->layoutRecordType(RD,
1280 ExternalSize,
1281 ExternalAlign,
1282 ExternalFieldOffsets,
1283 ExternalBaseOffsets,
1284 ExternalVirtualBaseOffsets);
1285
1286 // Update based on external alignment.
1287 if (ExternalLayout) {
Douglas Gregor44ba7892012-01-28 00:53:29 +00001288 if (ExternalAlign > 0) {
1289 Alignment = Context.toCharUnitsFromBits(ExternalAlign);
Douglas Gregor44ba7892012-01-28 00:53:29 +00001290 } else {
1291 // The external source didn't have alignment information; infer it.
1292 InferAlignment = true;
1293 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00001294 }
1295 }
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001296}
Anders Carlsson6d9f6f32009-07-19 00:18:47 +00001297
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001298void RecordLayoutBuilder::Layout(const RecordDecl *D) {
1299 InitializeLayout(D);
Anders Carlsson118ce162009-07-18 21:48:39 +00001300 LayoutFields(D);
Mike Stump11289f42009-09-09 15:08:12 +00001301
Anders Carlsson79474332009-07-18 20:20:21 +00001302 // Finally, round the size of the total struct up to the alignment of the
1303 // struct itself.
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001304 FinishLayout(D);
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001305}
1306
1307void RecordLayoutBuilder::Layout(const CXXRecordDecl *RD) {
1308 InitializeLayout(RD);
1309
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001310 // Lay out the vtable and the non-virtual bases.
1311 LayoutNonVirtualBases(RD);
1312
1313 LayoutFields(RD);
1314
Ken Dycke7380752011-03-10 01:53:59 +00001315 NonVirtualSize = Context.toCharUnitsFromBits(
1316 llvm::RoundUpToAlignment(getSizeInBits(),
Douglas Gregore8bbc122011-09-02 00:18:52 +00001317 Context.getTargetInfo().getCharAlign()));
Ken Dyck4731d5b2011-02-16 02:05:21 +00001318 NonVirtualAlignment = Alignment;
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001319
Warren Hunt55d8e822013-10-23 23:53:07 +00001320 // Lay out the virtual bases and add the primary virtual base offsets.
1321 LayoutVirtualBases(RD, RD);
John McCall0153cd32011-11-08 04:01:03 +00001322
1323 // Finally, round the size of the total struct up to the alignment
Eli Friedman83a12582011-12-01 00:37:01 +00001324 // of the struct itself.
1325 FinishLayout(RD);
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001326
Anders Carlsson5b441d72010-04-10 21:24:48 +00001327#ifndef NDEBUG
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001328 // Check that we have base offsets for all bases.
1329 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1330 E = RD->bases_end(); I != E; ++I) {
1331 if (I->isVirtual())
1332 continue;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001333
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001334 const CXXRecordDecl *BaseDecl =
1335 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1336
1337 assert(Bases.count(BaseDecl) && "Did not find base offset!");
1338 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001339
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001340 // And all virtual bases.
1341 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
1342 E = RD->vbases_end(); I != E; ++I) {
1343 const CXXRecordDecl *BaseDecl =
1344 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001345
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001346 assert(VBases.count(BaseDecl) && "Did not find base offset!");
Anders Carlsson5b441d72010-04-10 21:24:48 +00001347 }
1348#endif
Anders Carlsson79474332009-07-18 20:20:21 +00001349}
1350
Anders Carlssonc2226202010-05-26 05:58:59 +00001351void RecordLayoutBuilder::Layout(const ObjCInterfaceDecl *D) {
Anders Carlsson4f516282009-07-18 20:50:59 +00001352 if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
Anders Carlsson5efc56e2010-04-16 15:07:51 +00001353 const ASTRecordLayout &SL = Context.getASTObjCInterfaceLayout(SD);
Anders Carlsson4f516282009-07-18 20:50:59 +00001354
Ken Dyck85ef0432011-02-19 18:58:07 +00001355 UpdateAlignment(SL.getAlignment());
Mike Stump11289f42009-09-09 15:08:12 +00001356
Anders Carlsson4f516282009-07-18 20:50:59 +00001357 // We start laying out ivars not at the end of the superclass
1358 // structure, but at the next byte following the last field.
Ken Dyckecfc7552011-02-24 01:13:28 +00001359 setSize(SL.getDataSize());
Ken Dyck1b4420e2011-02-28 02:01:38 +00001360 setDataSize(getSize());
Anders Carlsson4f516282009-07-18 20:50:59 +00001361 }
Mike Stump11289f42009-09-09 15:08:12 +00001362
Daniel Dunbar6da10982010-05-27 05:45:51 +00001363 InitializeLayout(D);
Anders Carlsson4f516282009-07-18 20:50:59 +00001364 // Layout each ivar sequentially.
Jordy Rosea91768e2011-07-22 02:08:32 +00001365 for (const ObjCIvarDecl *IVD = D->all_declared_ivar_begin(); IVD;
1366 IVD = IVD->getNextIvar())
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001367 LayoutField(IVD);
Mike Stump11289f42009-09-09 15:08:12 +00001368
Anders Carlsson4f516282009-07-18 20:50:59 +00001369 // Finally, round the size of the total struct up to the alignment of the
1370 // struct itself.
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001371 FinishLayout(D);
Anders Carlsson4f516282009-07-18 20:50:59 +00001372}
1373
Anders Carlssonc2226202010-05-26 05:58:59 +00001374void RecordLayoutBuilder::LayoutFields(const RecordDecl *D) {
Anders Carlsson118ce162009-07-18 21:48:39 +00001375 // Layout each field, for now, just sequentially, respecting alignment. In
1376 // the future, this will need to be tweakable by targets.
Mike Stump11289f42009-09-09 15:08:12 +00001377 for (RecordDecl::field_iterator Field = D->field_begin(),
Eli Friedman481673f2013-06-26 23:47:39 +00001378 FieldEnd = D->field_end(); Field != FieldEnd; ++Field)
David Blaikie40ed2972012-06-06 20:45:41 +00001379 LayoutField(*Field);
Anders Carlsson118ce162009-07-18 21:48:39 +00001380}
1381
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001382void RecordLayoutBuilder::LayoutWideBitField(uint64_t FieldSize,
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001383 uint64_t TypeSize,
1384 bool FieldPacked,
1385 const FieldDecl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001386 assert(Context.getLangOpts().CPlusPlus &&
Anders Carlsson57235162010-04-16 15:57:11 +00001387 "Can only have wide bit-fields in C++!");
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001388
Anders Carlsson57235162010-04-16 15:57:11 +00001389 // Itanium C++ ABI 2.4:
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001390 // If sizeof(T)*8 < n, let T' be the largest integral POD type with
Anders Carlsson57235162010-04-16 15:57:11 +00001391 // sizeof(T')*8 <= n.
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001392
Anders Carlsson57235162010-04-16 15:57:11 +00001393 QualType IntegralPODTypes[] = {
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001394 Context.UnsignedCharTy, Context.UnsignedShortTy, Context.UnsignedIntTy,
Anders Carlsson57235162010-04-16 15:57:11 +00001395 Context.UnsignedLongTy, Context.UnsignedLongLongTy
1396 };
1397
Anders Carlsson57235162010-04-16 15:57:11 +00001398 QualType Type;
1399 for (unsigned I = 0, E = llvm::array_lengthof(IntegralPODTypes);
1400 I != E; ++I) {
1401 uint64_t Size = Context.getTypeSize(IntegralPODTypes[I]);
Anders Carlsson57235162010-04-16 15:57:11 +00001402
1403 if (Size > FieldSize)
1404 break;
1405
1406 Type = IntegralPODTypes[I];
1407 }
1408 assert(!Type.isNull() && "Did not find a type!");
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001409
Ken Dyckdbe37f32011-03-01 01:36:00 +00001410 CharUnits TypeAlign = Context.getTypeAlignInChars(Type);
Anders Carlsson57235162010-04-16 15:57:11 +00001411
1412 // We're not going to use any of the unfilled bits in the last byte.
Eli Friedman2782dac2013-06-26 20:50:34 +00001413 UnfilledBitsInLastUnit = 0;
1414 LastBitfieldTypeSize = 0;
Anders Carlsson57235162010-04-16 15:57:11 +00001415
Anders Carlssonaad5fa82010-04-17 20:21:41 +00001416 uint64_t FieldOffset;
Eli Friedman2782dac2013-06-26 20:50:34 +00001417 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001418
Anders Carlsson57235162010-04-16 15:57:11 +00001419 if (IsUnion) {
Ken Dyckecfc7552011-02-24 01:13:28 +00001420 setDataSize(std::max(getDataSizeInBits(), FieldSize));
Anders Carlssonaad5fa82010-04-17 20:21:41 +00001421 FieldOffset = 0;
Anders Carlsson57235162010-04-16 15:57:11 +00001422 } else {
Chad Rosiere1a6a0e2011-08-05 22:38:04 +00001423 // The bitfield is allocated starting at the next offset aligned
1424 // appropriately for T', with length n bits.
Ken Dyckdbe37f32011-03-01 01:36:00 +00001425 FieldOffset = llvm::RoundUpToAlignment(getDataSizeInBits(),
1426 Context.toBits(TypeAlign));
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001427
Anders Carlsson57235162010-04-16 15:57:11 +00001428 uint64_t NewSizeInBits = FieldOffset + FieldSize;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001429
Ken Dycka1a2e8d2011-03-10 02:00:35 +00001430 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits,
Douglas Gregore8bbc122011-09-02 00:18:52 +00001431 Context.getTargetInfo().getCharAlign()));
Eli Friedman2782dac2013-06-26 20:50:34 +00001432 UnfilledBitsInLastUnit = getDataSizeInBits() - NewSizeInBits;
Anders Carlsson57235162010-04-16 15:57:11 +00001433 }
1434
1435 // Place this field at the current location.
1436 FieldOffsets.push_back(FieldOffset);
1437
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001438 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, FieldOffset,
Ken Dyckdbe37f32011-03-01 01:36:00 +00001439 Context.toBits(TypeAlign), FieldPacked, D);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001440
Anders Carlsson57235162010-04-16 15:57:11 +00001441 // Update the size.
Ken Dyckecfc7552011-02-24 01:13:28 +00001442 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001443
Anders Carlsson57235162010-04-16 15:57:11 +00001444 // Remember max struct/class alignment.
Ken Dyckdbe37f32011-03-01 01:36:00 +00001445 UpdateAlignment(TypeAlign);
Anders Carlsson57235162010-04-16 15:57:11 +00001446}
1447
Anders Carlssonc2226202010-05-26 05:58:59 +00001448void RecordLayoutBuilder::LayoutBitField(const FieldDecl *D) {
Anders Carlsson07209442009-11-22 17:37:31 +00001449 bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
Richard Smithcaf33902011-10-10 18:28:20 +00001450 uint64_t FieldSize = D->getBitWidthValue(Context);
Anders Carlsson5efc56e2010-04-16 15:07:51 +00001451 std::pair<uint64_t, unsigned> FieldInfo = Context.getTypeInfo(D->getType());
Anders Carlsson07209442009-11-22 17:37:31 +00001452 uint64_t TypeSize = FieldInfo.first;
1453 unsigned FieldAlign = FieldInfo.second;
Eli Friedman2782dac2013-06-26 20:50:34 +00001454
1455 if (IsMsStruct) {
1456 // The field alignment for integer types in ms_struct structs is
1457 // always the size.
Fariborz Jahanian7adbed62011-05-09 22:03:17 +00001458 FieldAlign = TypeSize;
Eli Friedman2782dac2013-06-26 20:50:34 +00001459 // Ignore zero-length bitfields after non-bitfields in ms_struct structs.
1460 if (!FieldSize && !LastBitfieldTypeSize)
1461 FieldAlign = 1;
1462 // If a bitfield is followed by a bitfield of a different size, don't
1463 // pack the bits together in ms_struct structs.
1464 if (LastBitfieldTypeSize != TypeSize) {
1465 UnfilledBitsInLastUnit = 0;
1466 LastBitfieldTypeSize = 0;
1467 }
1468 }
1469
1470 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
1471 uint64_t FieldOffset = IsUnion ? 0 : UnpaddedFieldOffset;
Chad Rosier18903ee2011-08-04 01:21:14 +00001472
Eli Friedman481673f2013-06-26 23:47:39 +00001473 bool ZeroLengthBitfield = false;
1474 if (!Context.getTargetInfo().useBitFieldTypeAlignment() &&
1475 Context.getTargetInfo().useZeroLengthBitfieldAlignment() &&
1476 FieldSize == 0) {
Eli Friedman2782dac2013-06-26 20:50:34 +00001477 // The alignment of a zero-length bitfield affects the alignment
1478 // of the next member. The alignment is the max of the zero
1479 // length bitfield's alignment and a target specific fixed value.
Eli Friedman481673f2013-06-26 23:47:39 +00001480 ZeroLengthBitfield = true;
Eli Friedman2782dac2013-06-26 20:50:34 +00001481 unsigned ZeroLengthBitfieldBoundary =
1482 Context.getTargetInfo().getZeroLengthBitfieldBoundary();
1483 if (ZeroLengthBitfieldBoundary > FieldAlign)
1484 FieldAlign = ZeroLengthBitfieldBoundary;
Fariborz Jahanianfc0fe6e2011-05-03 20:21:04 +00001485 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001486
Anders Carlsson57235162010-04-16 15:57:11 +00001487 if (FieldSize > TypeSize) {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001488 LayoutWideBitField(FieldSize, TypeSize, FieldPacked, D);
Anders Carlsson57235162010-04-16 15:57:11 +00001489 return;
1490 }
1491
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001492 // The align if the field is not packed. This is to check if the attribute
1493 // was unnecessary (-Wpacked).
1494 unsigned UnpackedFieldAlign = FieldAlign;
1495 uint64_t UnpackedFieldOffset = FieldOffset;
Douglas Gregore8bbc122011-09-02 00:18:52 +00001496 if (!Context.getTargetInfo().useBitFieldTypeAlignment() && !ZeroLengthBitfield)
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001497 UnpackedFieldAlign = 1;
1498
Chad Rosiere1a6a0e2011-08-05 22:38:04 +00001499 if (FieldPacked ||
Douglas Gregore8bbc122011-09-02 00:18:52 +00001500 (!Context.getTargetInfo().useBitFieldTypeAlignment() && !ZeroLengthBitfield))
Anders Carlsson07209442009-11-22 17:37:31 +00001501 FieldAlign = 1;
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001502 FieldAlign = std::max(FieldAlign, D->getMaxAlignment());
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001503 UnpackedFieldAlign = std::max(UnpackedFieldAlign, D->getMaxAlignment());
Anders Carlsson07209442009-11-22 17:37:31 +00001504
1505 // The maximum field alignment overrides the aligned attribute.
Eli Friedmana91d38a2011-12-02 02:38:48 +00001506 if (!MaxFieldAlignment.isZero() && FieldSize != 0) {
Ken Dyck02ced6f2011-02-17 01:49:42 +00001507 unsigned MaxFieldAlignmentInBits = Context.toBits(MaxFieldAlignment);
1508 FieldAlign = std::min(FieldAlign, MaxFieldAlignmentInBits);
1509 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignmentInBits);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001510 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001511
Eli Friedman2782dac2013-06-26 20:50:34 +00001512 // ms_struct bitfields always have to start at a round alignment.
1513 if (IsMsStruct && !LastBitfieldTypeSize) {
1514 FieldOffset = llvm::RoundUpToAlignment(FieldOffset, FieldAlign);
1515 UnpackedFieldOffset = llvm::RoundUpToAlignment(UnpackedFieldOffset,
1516 UnpackedFieldAlign);
1517 }
1518
Douglas Gregor44ba7892012-01-28 00:53:29 +00001519 // Check if we need to add padding to give the field the correct alignment.
1520 if (FieldSize == 0 ||
1521 (MaxFieldAlignment.isZero() &&
1522 (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize))
1523 FieldOffset = llvm::RoundUpToAlignment(FieldOffset, FieldAlign);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001524
Douglas Gregor44ba7892012-01-28 00:53:29 +00001525 if (FieldSize == 0 ||
1526 (MaxFieldAlignment.isZero() &&
1527 (UnpackedFieldOffset & (UnpackedFieldAlign-1)) + FieldSize > TypeSize))
1528 UnpackedFieldOffset = llvm::RoundUpToAlignment(UnpackedFieldOffset,
1529 UnpackedFieldAlign);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001530
Chad Rosiere1a6a0e2011-08-05 22:38:04 +00001531 // Padding members don't affect overall alignment, unless zero length bitfield
1532 // alignment is enabled.
Eli Friedman2782dac2013-06-26 20:50:34 +00001533 if (!D->getIdentifier() &&
1534 !Context.getTargetInfo().useZeroLengthBitfieldAlignment() &&
1535 !IsMsStruct)
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001536 FieldAlign = UnpackedFieldAlign = 1;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001537
Douglas Gregor44ba7892012-01-28 00:53:29 +00001538 if (ExternalLayout)
1539 FieldOffset = updateExternalFieldOffset(D, FieldOffset);
1540
Anders Carlsson07209442009-11-22 17:37:31 +00001541 // Place this field at the current location.
1542 FieldOffsets.push_back(FieldOffset);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001543
Douglas Gregore9fc3772012-01-26 07:55:45 +00001544 if (!ExternalLayout)
1545 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, UnpackedFieldOffset,
1546 UnpackedFieldAlign, FieldPacked, D);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001547
Anders Carlssonba958402009-11-22 19:13:51 +00001548 // Update DataSize to include the last byte containing (part of) the bitfield.
1549 if (IsUnion) {
1550 // FIXME: I think FieldSize should be TypeSize here.
Ken Dyckecfc7552011-02-24 01:13:28 +00001551 setDataSize(std::max(getDataSizeInBits(), FieldSize));
Anders Carlssonba958402009-11-22 19:13:51 +00001552 } else {
Eli Friedman2782dac2013-06-26 20:50:34 +00001553 if (IsMsStruct && FieldSize) {
1554 // Under ms_struct, a bitfield always takes up space equal to the size
1555 // of the type. We can't just change the alignment computation on the
1556 // other codepath because of the way this interacts with #pragma pack:
1557 // in a packed struct, we need to allocate misaligned space in the
1558 // struct to hold the bitfield.
1559 if (!UnfilledBitsInLastUnit) {
1560 setDataSize(FieldOffset + TypeSize);
1561 UnfilledBitsInLastUnit = TypeSize - FieldSize;
1562 } else if (UnfilledBitsInLastUnit < FieldSize) {
1563 setDataSize(getDataSizeInBits() + TypeSize);
1564 UnfilledBitsInLastUnit = TypeSize - FieldSize;
1565 } else {
1566 UnfilledBitsInLastUnit -= FieldSize;
1567 }
1568 LastBitfieldTypeSize = TypeSize;
1569 } else {
1570 uint64_t NewSizeInBits = FieldOffset + FieldSize;
1571 uint64_t BitfieldAlignment = Context.getTargetInfo().getCharAlign();
1572 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits, BitfieldAlignment));
1573 UnfilledBitsInLastUnit = getDataSizeInBits() - NewSizeInBits;
1574 LastBitfieldTypeSize = 0;
1575 }
Anders Carlssonba958402009-11-22 19:13:51 +00001576 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001577
Anders Carlssonba958402009-11-22 19:13:51 +00001578 // Update the size.
Ken Dyckecfc7552011-02-24 01:13:28 +00001579 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001580
Anders Carlsson07209442009-11-22 17:37:31 +00001581 // Remember max struct/class alignment.
Ken Dyck85ef0432011-02-19 18:58:07 +00001582 UpdateAlignment(Context.toCharUnitsFromBits(FieldAlign),
1583 Context.toCharUnitsFromBits(UnpackedFieldAlign));
Anders Carlsson07209442009-11-22 17:37:31 +00001584}
1585
Douglas Gregore9fc3772012-01-26 07:55:45 +00001586void RecordLayoutBuilder::LayoutField(const FieldDecl *D) {
Anders Carlsson07209442009-11-22 17:37:31 +00001587 if (D->isBitField()) {
1588 LayoutBitField(D);
1589 return;
1590 }
1591
Eli Friedman2782dac2013-06-26 20:50:34 +00001592 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001593
Anders Carlssonba958402009-11-22 19:13:51 +00001594 // Reset the unfilled bits.
Eli Friedman2782dac2013-06-26 20:50:34 +00001595 UnfilledBitsInLastUnit = 0;
1596 LastBitfieldTypeSize = 0;
Anders Carlssonba958402009-11-22 19:13:51 +00001597
Anders Carlsson07209442009-11-22 17:37:31 +00001598 bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
Ken Dyck6d90e892011-02-20 02:06:09 +00001599 CharUnits FieldOffset =
Ken Dyckecfc7552011-02-24 01:13:28 +00001600 IsUnion ? CharUnits::Zero() : getDataSize();
Ken Dyck6d90e892011-02-20 02:06:09 +00001601 CharUnits FieldSize;
1602 CharUnits FieldAlign;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001603
Anders Carlsson07209442009-11-22 17:37:31 +00001604 if (D->getType()->isIncompleteArrayType()) {
1605 // This is a flexible array member; we can't directly
1606 // query getTypeInfo about these, so we figure it out here.
1607 // Flexible array members don't have any size, but they
1608 // have to be aligned appropriately for their element type.
Ken Dyck6d90e892011-02-20 02:06:09 +00001609 FieldSize = CharUnits::Zero();
Anders Carlsson5efc56e2010-04-16 15:07:51 +00001610 const ArrayType* ATy = Context.getAsArrayType(D->getType());
Ken Dyck6d90e892011-02-20 02:06:09 +00001611 FieldAlign = Context.getTypeAlignInChars(ATy->getElementType());
Anders Carlsson07209442009-11-22 17:37:31 +00001612 } else if (const ReferenceType *RT = D->getType()->getAs<ReferenceType>()) {
1613 unsigned AS = RT->getPointeeType().getAddressSpace();
Ken Dyck6d90e892011-02-20 02:06:09 +00001614 FieldSize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001615 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(AS));
Ken Dyck6d90e892011-02-20 02:06:09 +00001616 FieldAlign =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001617 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(AS));
Anders Carlsson79474332009-07-18 20:20:21 +00001618 } else {
Ken Dyck6d90e892011-02-20 02:06:09 +00001619 std::pair<CharUnits, CharUnits> FieldInfo =
1620 Context.getTypeInfoInChars(D->getType());
Anders Carlsson07209442009-11-22 17:37:31 +00001621 FieldSize = FieldInfo.first;
1622 FieldAlign = FieldInfo.second;
Chad Rosier18903ee2011-08-04 01:21:14 +00001623
Eli Friedman9ee2d0472012-10-12 23:29:20 +00001624 if (IsMsStruct) {
Douglas Gregordbe39272011-02-01 15:15:22 +00001625 // If MS bitfield layout is required, figure out what type is being
1626 // laid out and align the field to the width of that type.
1627
1628 // Resolve all typedefs down to their base type and round up the field
1629 // alignment if necessary.
1630 QualType T = Context.getBaseElementType(D->getType());
1631 if (const BuiltinType *BTy = T->getAs<BuiltinType>()) {
Ken Dyck6d90e892011-02-20 02:06:09 +00001632 CharUnits TypeSize = Context.getTypeSizeInChars(BTy);
Douglas Gregordbe39272011-02-01 15:15:22 +00001633 if (TypeSize > FieldAlign)
1634 FieldAlign = TypeSize;
1635 }
1636 }
Anders Carlsson79474332009-07-18 20:20:21 +00001637 }
Mike Stump11289f42009-09-09 15:08:12 +00001638
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001639 // The align if the field is not packed. This is to check if the attribute
1640 // was unnecessary (-Wpacked).
Ken Dyck6d90e892011-02-20 02:06:09 +00001641 CharUnits UnpackedFieldAlign = FieldAlign;
1642 CharUnits UnpackedFieldOffset = FieldOffset;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001643
Anders Carlsson07209442009-11-22 17:37:31 +00001644 if (FieldPacked)
Ken Dyck6d90e892011-02-20 02:06:09 +00001645 FieldAlign = CharUnits::One();
1646 CharUnits MaxAlignmentInChars =
1647 Context.toCharUnitsFromBits(D->getMaxAlignment());
1648 FieldAlign = std::max(FieldAlign, MaxAlignmentInChars);
1649 UnpackedFieldAlign = std::max(UnpackedFieldAlign, MaxAlignmentInChars);
Anders Carlsson07209442009-11-22 17:37:31 +00001650
1651 // The maximum field alignment overrides the aligned attribute.
Ken Dyck02ced6f2011-02-17 01:49:42 +00001652 if (!MaxFieldAlignment.isZero()) {
Ken Dyck6d90e892011-02-20 02:06:09 +00001653 FieldAlign = std::min(FieldAlign, MaxFieldAlignment);
1654 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignment);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001655 }
Anders Carlsson07209442009-11-22 17:37:31 +00001656
Douglas Gregor44ba7892012-01-28 00:53:29 +00001657 // Round up the current record size to the field's alignment boundary.
1658 FieldOffset = FieldOffset.RoundUpToAlignment(FieldAlign);
1659 UnpackedFieldOffset =
1660 UnpackedFieldOffset.RoundUpToAlignment(UnpackedFieldAlign);
1661
1662 if (ExternalLayout) {
1663 FieldOffset = Context.toCharUnitsFromBits(
1664 updateExternalFieldOffset(D, Context.toBits(FieldOffset)));
1665
1666 if (!IsUnion && EmptySubobjects) {
1667 // Record the fact that we're placing a field at this offset.
1668 bool Allowed = EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset);
1669 (void)Allowed;
1670 assert(Allowed && "Externally-placed field cannot be placed here");
1671 }
1672 } else {
Douglas Gregore9fc3772012-01-26 07:55:45 +00001673 if (!IsUnion && EmptySubobjects) {
1674 // Check if we can place the field at this offset.
1675 while (!EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset)) {
1676 // We couldn't place the field at the offset. Try again at a new offset.
1677 FieldOffset += FieldAlign;
1678 }
Anders Carlsson07209442009-11-22 17:37:31 +00001679 }
Anders Carlsson07209442009-11-22 17:37:31 +00001680 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00001681
Anders Carlsson79474332009-07-18 20:20:21 +00001682 // Place this field at the current location.
Ken Dyck6d90e892011-02-20 02:06:09 +00001683 FieldOffsets.push_back(Context.toBits(FieldOffset));
Mike Stump11289f42009-09-09 15:08:12 +00001684
Douglas Gregore9fc3772012-01-26 07:55:45 +00001685 if (!ExternalLayout)
1686 CheckFieldPadding(Context.toBits(FieldOffset), UnpaddedFieldOffset,
1687 Context.toBits(UnpackedFieldOffset),
1688 Context.toBits(UnpackedFieldAlign), FieldPacked, D);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001689
Anders Carlsson79474332009-07-18 20:20:21 +00001690 // Reserve space for this field.
Eli Friedman43f18342012-01-12 23:27:03 +00001691 uint64_t FieldSizeInBits = Context.toBits(FieldSize);
Anders Carlsson79474332009-07-18 20:20:21 +00001692 if (IsUnion)
Eli Friedman2e108372012-01-12 23:48:56 +00001693 setDataSize(std::max(getDataSizeInBits(), FieldSizeInBits));
Anders Carlsson79474332009-07-18 20:20:21 +00001694 else
Eli Friedman2e108372012-01-12 23:48:56 +00001695 setDataSize(FieldOffset + FieldSize);
Mike Stump11289f42009-09-09 15:08:12 +00001696
Eli Friedman2e108372012-01-12 23:48:56 +00001697 // Update the size.
1698 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
Mike Stump11289f42009-09-09 15:08:12 +00001699
Anders Carlsson79474332009-07-18 20:20:21 +00001700 // Remember max struct/class alignment.
Ken Dyck6d90e892011-02-20 02:06:09 +00001701 UpdateAlignment(FieldAlign, UnpackedFieldAlign);
Anders Carlsson79474332009-07-18 20:20:21 +00001702}
1703
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001704void RecordLayoutBuilder::FinishLayout(const NamedDecl *D) {
Anders Carlsson79474332009-07-18 20:20:21 +00001705 // In C++, records cannot be of size 0.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001706 if (Context.getLangOpts().CPlusPlus && getSizeInBits() == 0) {
Fariborz Jahanian09b23312011-02-02 19:36:18 +00001707 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
1708 // Compatibility with gcc requires a class (pod or non-pod)
1709 // which is not empty but of size 0; such as having fields of
1710 // array of zero-length, remains of Size 0
1711 if (RD->isEmpty())
Ken Dyck1b4420e2011-02-28 02:01:38 +00001712 setSize(CharUnits::One());
Fariborz Jahanian09b23312011-02-02 19:36:18 +00001713 }
1714 else
Ken Dyck1b4420e2011-02-28 02:01:38 +00001715 setSize(CharUnits::One());
Fariborz Jahanian09b23312011-02-02 19:36:18 +00001716 }
Eli Friedman83a12582011-12-01 00:37:01 +00001717
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001718 // Finally, round the size of the record up to the alignment of the
1719 // record itself.
Eli Friedman2782dac2013-06-26 20:50:34 +00001720 uint64_t UnpaddedSize = getSizeInBits() - UnfilledBitsInLastUnit;
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001721 uint64_t UnpackedSizeInBits =
1722 llvm::RoundUpToAlignment(getSizeInBits(),
1723 Context.toBits(UnpackedAlignment));
1724 CharUnits UnpackedSize = Context.toCharUnitsFromBits(UnpackedSizeInBits);
1725 uint64_t RoundedSize
1726 = llvm::RoundUpToAlignment(getSizeInBits(), Context.toBits(Alignment));
1727
1728 if (ExternalLayout) {
1729 // If we're inferring alignment, and the external size is smaller than
1730 // our size after we've rounded up to alignment, conservatively set the
1731 // alignment to 1.
1732 if (InferAlignment && ExternalSize < RoundedSize) {
1733 Alignment = CharUnits::One();
1734 InferAlignment = false;
1735 }
1736 setSize(ExternalSize);
1737 return;
1738 }
1739
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001740 // Set the size to the final size.
1741 setSize(RoundedSize);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001742
Douglas Gregore8bbc122011-09-02 00:18:52 +00001743 unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001744 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
1745 // Warn if padding was introduced to the struct/class/union.
Ken Dyckecfc7552011-02-24 01:13:28 +00001746 if (getSizeInBits() > UnpaddedSize) {
1747 unsigned PadSize = getSizeInBits() - UnpaddedSize;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001748 bool InBits = true;
1749 if (PadSize % CharBitNum == 0) {
1750 PadSize = PadSize / CharBitNum;
1751 InBits = false;
1752 }
1753 Diag(RD->getLocation(), diag::warn_padded_struct_size)
1754 << Context.getTypeDeclType(RD)
1755 << PadSize
1756 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1); // plural or not
1757 }
1758
1759 // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
1760 // bother since there won't be alignment issues.
Ken Dyckecfc7552011-02-24 01:13:28 +00001761 if (Packed && UnpackedAlignment > CharUnits::One() &&
Ken Dyck1b4420e2011-02-28 02:01:38 +00001762 getSize() == UnpackedSize)
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001763 Diag(D->getLocation(), diag::warn_unnecessary_packed)
1764 << Context.getTypeDeclType(RD);
1765 }
Anders Carlsson79474332009-07-18 20:20:21 +00001766}
1767
Ken Dyck85ef0432011-02-19 18:58:07 +00001768void RecordLayoutBuilder::UpdateAlignment(CharUnits NewAlignment,
1769 CharUnits UnpackedNewAlignment) {
Douglas Gregore9fc3772012-01-26 07:55:45 +00001770 // The alignment is not modified when using 'mac68k' alignment or when
Douglas Gregor44ba7892012-01-28 00:53:29 +00001771 // we have an externally-supplied layout that also provides overall alignment.
1772 if (IsMac68kAlign || (ExternalLayout && !InferAlignment))
Daniel Dunbar6da10982010-05-27 05:45:51 +00001773 return;
1774
Ken Dyck85ef0432011-02-19 18:58:07 +00001775 if (NewAlignment > Alignment) {
1776 assert(llvm::isPowerOf2_32(NewAlignment.getQuantity() &&
1777 "Alignment not a power of 2"));
1778 Alignment = NewAlignment;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001779 }
1780
Ken Dyck85ef0432011-02-19 18:58:07 +00001781 if (UnpackedNewAlignment > UnpackedAlignment) {
1782 assert(llvm::isPowerOf2_32(UnpackedNewAlignment.getQuantity() &&
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001783 "Alignment not a power of 2"));
Ken Dyck85ef0432011-02-19 18:58:07 +00001784 UnpackedAlignment = UnpackedNewAlignment;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001785 }
1786}
1787
Douglas Gregor44ba7892012-01-28 00:53:29 +00001788uint64_t
1789RecordLayoutBuilder::updateExternalFieldOffset(const FieldDecl *Field,
1790 uint64_t ComputedOffset) {
1791 assert(ExternalFieldOffsets.find(Field) != ExternalFieldOffsets.end() &&
1792 "Field does not have an external offset");
1793
1794 uint64_t ExternalFieldOffset = ExternalFieldOffsets[Field];
1795
1796 if (InferAlignment && ExternalFieldOffset < ComputedOffset) {
1797 // The externally-supplied field offset is before the field offset we
1798 // computed. Assume that the structure is packed.
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001799 Alignment = CharUnits::One();
Douglas Gregor44ba7892012-01-28 00:53:29 +00001800 InferAlignment = false;
1801 }
1802
1803 // Use the externally-supplied field offset.
Benjamin Kramer648e68b2012-08-31 22:14:25 +00001804 return ExternalFieldOffset;
1805}
1806
1807/// \brief Get diagnostic %select index for tag kind for
1808/// field padding diagnostic message.
1809/// WARNING: Indexes apply to particular diagnostics only!
1810///
1811/// \returns diagnostic %select index.
1812static unsigned getPaddingDiagFromTagKind(TagTypeKind Tag) {
1813 switch (Tag) {
1814 case TTK_Struct: return 0;
1815 case TTK_Interface: return 1;
1816 case TTK_Class: return 2;
1817 default: llvm_unreachable("Invalid tag kind for field padding diagnostic!");
1818 }
1819}
1820
1821void RecordLayoutBuilder::CheckFieldPadding(uint64_t Offset,
1822 uint64_t UnpaddedOffset,
1823 uint64_t UnpackedOffset,
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001824 unsigned UnpackedAlign,
1825 bool isPacked,
1826 const FieldDecl *D) {
1827 // We let objc ivars without warning, objc interfaces generally are not used
1828 // for padding tricks.
1829 if (isa<ObjCIvarDecl>(D))
Anders Carlsson79474332009-07-18 20:20:21 +00001830 return;
Mike Stump11289f42009-09-09 15:08:12 +00001831
Ted Kremenekfed48af2011-09-06 19:40:45 +00001832 // Don't warn about structs created without a SourceLocation. This can
1833 // be done by clients of the AST, such as codegen.
1834 if (D->getLocation().isInvalid())
1835 return;
1836
Douglas Gregore8bbc122011-09-02 00:18:52 +00001837 unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
Mike Stump11289f42009-09-09 15:08:12 +00001838
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001839 // Warn if padding was introduced to the struct/class.
1840 if (!IsUnion && Offset > UnpaddedOffset) {
1841 unsigned PadSize = Offset - UnpaddedOffset;
1842 bool InBits = true;
1843 if (PadSize % CharBitNum == 0) {
1844 PadSize = PadSize / CharBitNum;
1845 InBits = false;
Benjamin Kramer648e68b2012-08-31 22:14:25 +00001846 }
1847 if (D->getIdentifier())
1848 Diag(D->getLocation(), diag::warn_padded_struct_field)
1849 << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
1850 << Context.getTypeDeclType(D->getParent())
1851 << PadSize
1852 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1) // plural or not
1853 << D->getIdentifier();
1854 else
1855 Diag(D->getLocation(), diag::warn_padded_struct_anon_field)
1856 << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
1857 << Context.getTypeDeclType(D->getParent())
1858 << PadSize
1859 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1); // plural or not
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001860 }
1861
1862 // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
1863 // bother since there won't be alignment issues.
1864 if (isPacked && UnpackedAlign > CharBitNum && Offset == UnpackedOffset)
1865 Diag(D->getLocation(), diag::warn_unnecessary_packed)
1866 << D->getIdentifier();
Anders Carlsson79474332009-07-18 20:20:21 +00001867}
Mike Stump11289f42009-09-09 15:08:12 +00001868
John McCall6bd2a892013-01-25 22:31:03 +00001869static const CXXMethodDecl *computeKeyFunction(ASTContext &Context,
1870 const CXXRecordDecl *RD) {
Daniel Dunbarccabe482010-04-19 20:44:53 +00001871 // If a class isn't polymorphic it doesn't have a key function.
Anders Carlsson5ebf8b42009-12-07 04:35:11 +00001872 if (!RD->isPolymorphic())
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001873 return 0;
Eli Friedmanf2c79b62009-12-08 03:56:49 +00001874
Eli Friedman300f55d2011-06-10 21:53:06 +00001875 // A class that is not externally visible doesn't have a key function. (Or
Eli Friedmanf2c79b62009-12-08 03:56:49 +00001876 // at least, there's no point to assigning a key function to such a class;
1877 // this doesn't affect the ABI.)
Rafael Espindola3ae00052013-05-13 00:12:11 +00001878 if (!RD->isExternallyVisible())
Eli Friedmanf2c79b62009-12-08 03:56:49 +00001879 return 0;
1880
Argyrios Kyrtzidis8c64bbe2010-10-13 02:39:41 +00001881 // Template instantiations don't have key functions,see Itanium C++ ABI 5.2.6.
1882 // Same behavior as GCC.
1883 TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
1884 if (TSK == TSK_ImplicitInstantiation ||
1885 TSK == TSK_ExplicitInstantiationDefinition)
1886 return 0;
1887
John McCall6bd2a892013-01-25 22:31:03 +00001888 bool allowInlineFunctions =
1889 Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline();
1890
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001891 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
1892 E = RD->method_end(); I != E; ++I) {
David Blaikie40ed2972012-06-06 20:45:41 +00001893 const CXXMethodDecl *MD = *I;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001894
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001895 if (!MD->isVirtual())
1896 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001897
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001898 if (MD->isPure())
1899 continue;
Eli Friedmanf2c79b62009-12-08 03:56:49 +00001900
Anders Carlssonf98849e2009-12-02 17:15:43 +00001901 // Ignore implicit member functions, they are always marked as inline, but
1902 // they don't have a body until they're defined.
1903 if (MD->isImplicit())
1904 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001905
Douglas Gregora318efd2010-01-05 19:06:31 +00001906 if (MD->isInlineSpecified())
1907 continue;
Eli Friedman71a26d82009-12-06 20:50:05 +00001908
1909 if (MD->hasInlineBody())
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001910 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001911
Benjamin Kramer4a902082012-08-03 15:43:22 +00001912 // Ignore inline deleted or defaulted functions.
Benjamin Kramer73d1be72012-08-03 08:39:58 +00001913 if (!MD->isUserProvided())
1914 continue;
1915
John McCall6bd2a892013-01-25 22:31:03 +00001916 // In certain ABIs, ignore functions with out-of-line inline definitions.
1917 if (!allowInlineFunctions) {
1918 const FunctionDecl *Def;
1919 if (MD->hasBody(Def) && Def->isInlineSpecified())
1920 continue;
1921 }
1922
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001923 // We found it.
1924 return MD;
1925 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001926
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001927 return 0;
1928}
1929
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001930DiagnosticBuilder
1931RecordLayoutBuilder::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +00001932 return Context.getDiagnostics().Report(Loc, DiagID);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001933}
1934
John McCall5c1f1d02013-01-29 01:14:22 +00001935/// Does the target C++ ABI require us to skip over the tail-padding
1936/// of the given class (considering it as a base class) when allocating
1937/// objects?
1938static bool mustSkipTailPadding(TargetCXXABI ABI, const CXXRecordDecl *RD) {
1939 switch (ABI.getTailPaddingUseRules()) {
1940 case TargetCXXABI::AlwaysUseTailPadding:
1941 return false;
1942
1943 case TargetCXXABI::UseTailPaddingUnlessPOD03:
1944 // FIXME: To the extent that this is meant to cover the Itanium ABI
1945 // rules, we should implement the restrictions about over-sized
1946 // bitfields:
1947 //
1948 // http://mentorembedded.github.com/cxx-abi/abi.html#POD :
1949 // In general, a type is considered a POD for the purposes of
1950 // layout if it is a POD type (in the sense of ISO C++
1951 // [basic.types]). However, a POD-struct or POD-union (in the
1952 // sense of ISO C++ [class]) with a bitfield member whose
1953 // declared width is wider than the declared type of the
1954 // bitfield is not a POD for the purpose of layout. Similarly,
1955 // an array type is not a POD for the purpose of layout if the
1956 // element type of the array is not a POD for the purpose of
1957 // layout.
1958 //
1959 // Where references to the ISO C++ are made in this paragraph,
1960 // the Technical Corrigendum 1 version of the standard is
1961 // intended.
1962 return RD->isPOD();
1963
1964 case TargetCXXABI::UseTailPaddingUnlessPOD11:
1965 // This is equivalent to RD->getTypeForDecl().isCXX11PODType(),
1966 // but with a lot of abstraction penalty stripped off. This does
1967 // assume that these properties are set correctly even in C++98
1968 // mode; fortunately, that is true because we want to assign
1969 // consistently semantics to the type-traits intrinsics (or at
1970 // least as many of them as possible).
1971 return RD->isTrivial() && RD->isStandardLayout();
1972 }
1973
1974 llvm_unreachable("bad tail-padding use kind");
1975}
1976
Warren Hunt8f8bad72013-10-11 20:19:00 +00001977static bool isMsLayout(const RecordDecl* D) {
Warren Hunt55d8e822013-10-23 23:53:07 +00001978 return D->getASTContext().getTargetInfo().getCXXABI().isMicrosoft();
Warren Hunt8f8bad72013-10-11 20:19:00 +00001979}
1980
1981// This section contains an implementation of struct layout that is, up to the
1982// included tests, compatible with cl.exe (2012). The layout produced is
1983// significantly different than those produced by the Itanium ABI. Here we note
1984// the most important differences.
1985//
1986// * The alignment of bitfields in unions is ignored when computing the
1987// alignment of the union.
1988// * The existance of zero-width bitfield that occurs after anything other than
1989// a non-zero length bitfield is ignored.
1990// * The Itanium equivalent vtable pointers are split into a vfptr (virtual
1991// function pointer) and a vbptr (virtual base pointer). They can each be
Warren Hunt55d8e822013-10-23 23:53:07 +00001992// shared with a, non-virtual bases. These bases need not be the same. vfptrs
1993// always occur at offset 0. vbptrs can occur at an
Warren Hunt8f8bad72013-10-11 20:19:00 +00001994// arbitrary offset and are placed after non-virtual bases but before fields.
1995// * Virtual bases sometimes require a 'vtordisp' field that is laid out before
1996// the virtual base and is used in conjunction with virtual overrides during
1997// construction and destruction.
1998// * vfptrs are allocated in a block of memory equal to the alignment of the
Warren Hunt55d8e822013-10-23 23:53:07 +00001999// fields and non-virtual bases at offset 0 in 32 bit mode and in a pointer
2000// sized block of memory in 64 bit mode.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002001// * vbptrs are allocated in a block of memory equal to the alignment of the
Warren Hunt55d8e822013-10-23 23:53:07 +00002002// fields and non-virtual bases. This block is at a potentially unaligned
2003// offset. If the allocation slot is unaligned and the alignment is less than
2004// or equal to the pointer size, additional space is allocated so that the
2005// pointer can be aligned properly. This causes very strange effects on the
2006// placement of objects after the allocated block. (see the code).
Warren Hunt8f8bad72013-10-11 20:19:00 +00002007// * vtordisps are allocated in a block of memory with size and alignment equal
2008// to the alignment of the completed structure (before applying __declspec(
Warren Hunt55d8e822013-10-23 23:53:07 +00002009// align())). The vtordisp always occur at the end of the allocation block,
2010// immediately prior to the virtual base.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002011// * The last zero sized non-virtual base is allocated after the placement of
2012// vbptr if one exists and can be placed at the end of the struct, potentially
2013// aliasing either the first member or another struct allocated after this
2014// one.
2015// * The last zero size virtual base may be placed at the end of the struct.
2016// and can potentially alias a zero sized type in the next struct.
Warren Hunt6b7048d2013-11-06 00:54:59 +00002017// * If the last field is a non-zero length bitfield and we have any virtual
2018// bases then some extra padding is added before the virtual bases for no
2019// obvious reason.
Warren Huntc0df47d2013-11-19 22:11:09 +00002020// * When laying out empty non-virtual bases, an extra byte of padding is added
2021// if the non-virtual base before the empty non-virtual base has a vbptr.
Warren Hunt6b7048d2013-11-06 00:54:59 +00002022
Warren Hunt8f8bad72013-10-11 20:19:00 +00002023
2024namespace {
2025struct MicrosoftRecordLayoutBuilder {
2026 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
2027 MicrosoftRecordLayoutBuilder(const ASTContext &Context) : Context(Context) {}
2028private:
2029 MicrosoftRecordLayoutBuilder(const MicrosoftRecordLayoutBuilder &)
2030 LLVM_DELETED_FUNCTION;
2031 void operator=(const MicrosoftRecordLayoutBuilder &) LLVM_DELETED_FUNCTION;
2032public:
2033
2034 void layout(const RecordDecl *RD);
2035 void cxxLayout(const CXXRecordDecl *RD);
2036 /// \brief Initializes size and alignment and honors some flags.
2037 void initializeLayout(const RecordDecl *RD);
2038 /// \brief Initialized C++ layout, compute alignment and virtual alignment and
2039 /// existance of vfptrs and vbptrs. Alignment is needed before the vfptr is
2040 /// laid out.
2041 void initializeCXXLayout(const CXXRecordDecl *RD);
2042 void layoutVFPtr(const CXXRecordDecl *RD);
2043 void layoutNonVirtualBases(const CXXRecordDecl *RD);
2044 void layoutNonVirtualBase(const CXXRecordDecl *RD);
2045 void layoutVBPtr(const CXXRecordDecl *RD);
2046 /// \brief Lays out the fields of the record. Also rounds size up to
2047 /// alignment.
2048 void layoutFields(const RecordDecl *RD);
2049 void layoutField(const FieldDecl *FD);
2050 void layoutBitField(const FieldDecl *FD);
2051 /// \brief Lays out a single zero-width bit-field in the record and handles
2052 /// special cases associated with zero-width bit-fields.
2053 void layoutZeroWidthBitField(const FieldDecl *FD);
2054 void layoutVirtualBases(const CXXRecordDecl *RD);
2055 void layoutVirtualBase(const CXXRecordDecl *RD, bool HasVtordisp);
2056 /// \brief Flushes the lazy virtual base and conditionally rounds up to
2057 /// alignment.
2058 void finalizeCXXLayout(const CXXRecordDecl *RD);
2059 void honorDeclspecAlign(const RecordDecl *RD);
2060
2061 /// \brief Updates the alignment of the type. This function doesn't take any
2062 /// properties (such as packedness) into account. getAdjustedFieldInfo()
2063 /// adjustes for packedness.
2064 void updateAlignment(CharUnits NewAlignment) {
2065 Alignment = std::max(Alignment, NewAlignment);
2066 }
2067 /// \brief Gets the size and alignment taking attributes into account.
2068 std::pair<CharUnits, CharUnits> getAdjustedFieldInfo(const FieldDecl *FD);
2069 /// \brief Places a field at offset 0.
2070 void placeFieldAtZero() { FieldOffsets.push_back(0); }
2071 /// \brief Places a field at an offset in CharUnits.
2072 void placeFieldAtOffset(CharUnits FieldOffset) {
2073 FieldOffsets.push_back(Context.toBits(FieldOffset));
2074 }
2075 /// \brief Places a bitfield at a bit offset.
2076 void placeFieldAtBitOffset(uint64_t FieldOffset) {
2077 FieldOffsets.push_back(FieldOffset);
2078 }
2079 /// \brief Compute the set of virtual bases for which vtordisps are required.
2080 llvm::SmallPtrSet<const CXXRecordDecl *, 2>
2081 computeVtorDispSet(const CXXRecordDecl *RD);
2082
2083 const ASTContext &Context;
2084 /// \brief The size of the record being laid out.
2085 CharUnits Size;
2086 /// \brief The current alignment of the record layout.
2087 CharUnits Alignment;
2088 /// \brief The collection of field offsets.
2089 SmallVector<uint64_t, 16> FieldOffsets;
2090 /// \brief The maximum allowed field alignment. This is set by #pragma pack.
2091 CharUnits MaxFieldAlignment;
2092 /// \brief Alignment does not occur for virtual bases unless something
2093 /// forces it to by explicitly using __declspec(align())
2094 bool AlignAfterVBases : 1;
2095 bool IsUnion : 1;
2096 /// \brief True if the last field laid out was a bitfield and was not 0
2097 /// width.
2098 bool LastFieldIsNonZeroWidthBitfield : 1;
2099 /// \brief The size of the allocation of the currently active bitfield.
2100 /// This value isn't meaningful unless LastFieldIsNonZeroWidthBitfield
2101 /// is true.
2102 CharUnits CurrentBitfieldSize;
2103 /// \brief The number of remaining bits in our last bitfield allocation.
2104 /// This value isn't meaningful unless LastFieldIsNonZeroWidthBitfield is
2105 /// true.
2106 unsigned RemainingBitsInField;
2107
2108 /// \brief The data alignment of the record layout.
2109 CharUnits DataSize;
2110 /// \brief The alignment of the non-virtual portion of the record layout
Warren Hunt55d8e822013-10-23 23:53:07 +00002111 /// without the impact of the virtual pointers.
2112 /// Only used for C++ layouts.
2113 CharUnits BasesAndFieldsAlignment;
2114 /// \brief The alignment of the non-virtual portion of the record layout
2115 /// Only used for C++ layouts.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002116 CharUnits NonVirtualAlignment;
2117 /// \brief The additional alignment imposed by the virtual bases.
2118 CharUnits VirtualAlignment;
2119 /// \brief The primary base class (if one exists).
2120 const CXXRecordDecl *PrimaryBase;
2121 /// \brief The class we share our vb-pointer with.
2122 const CXXRecordDecl *SharedVBPtrBase;
Warren Hunt486e7142013-11-13 22:16:13 +00002123 /// \brief True if the class has a vftable pointer that can be extended
2124 /// by this class or classes derived from it. Such a vfptr will always occur
2125 /// at offset 0.
2126 bool HasExtendableVFPtr : 1;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002127 /// \brief True if the class has a (not necessarily its own) vbtable pointer.
2128 bool HasVBPtr : 1;
2129 /// \brief Offset to the virtual base table pointer (if one exists).
2130 CharUnits VBPtrOffset;
2131 /// \brief Base classes and their offsets in the record.
2132 BaseOffsetsMapTy Bases;
2133 /// \brief virtual base classes and their offsets in the record.
2134 ASTRecordLayout::VBaseOffsetsMapTy VBases;
2135 /// \brief The size of a pointer.
2136 CharUnits PointerSize;
2137 /// \brief The alignment of a pointer.
2138 CharUnits PointerAlignment;
2139 /// \brief Holds an empty base we haven't yet laid out.
2140 const CXXRecordDecl *LazyEmptyBase;
Warren Hunt55d8e822013-10-23 23:53:07 +00002141 /// \brief Lets us know if the last base we laid out was empty. Only used
2142 /// when adjusting the placement of a last zero-sized base in 64 bit mode.
2143 bool LastBaseWasEmpty;
2144 /// \brief Lets us know if we're in 64-bit mode
2145 bool Is64BitMode;
Warren Huntc0df47d2013-11-19 22:11:09 +00002146 /// \brief True if the last non-virtual base has a vbptr.
2147 bool LastNonVirtualBaseHasVBPtr;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002148};
2149} // namespace
2150
2151std::pair<CharUnits, CharUnits>
2152MicrosoftRecordLayoutBuilder::getAdjustedFieldInfo(const FieldDecl *FD) {
Warren Hunt5ae586a2013-11-01 23:59:41 +00002153 std::pair<CharUnits, CharUnits> FieldInfo =
2154 Context.getTypeInfoInChars(FD->getType());
Warren Hunt8f8bad72013-10-11 20:19:00 +00002155
2156 // If we're not on win32 and using ms_struct the field alignment will be wrong
2157 // for 64 bit types, so we fix that here.
2158 if (FD->getASTContext().getTargetInfo().getTriple().getOS() !=
2159 llvm::Triple::Win32) {
2160 QualType T = Context.getBaseElementType(FD->getType());
2161 if (const BuiltinType *BTy = T->getAs<BuiltinType>()) {
2162 CharUnits TypeSize = Context.getTypeSizeInChars(BTy);
2163 if (TypeSize > FieldInfo.second)
2164 FieldInfo.second = TypeSize;
2165 }
2166 }
2167
2168 // Respect packed attribute.
2169 if (FD->hasAttr<PackedAttr>())
2170 FieldInfo.second = CharUnits::One();
2171 // Respect pack pragma.
2172 else if (!MaxFieldAlignment.isZero())
2173 FieldInfo.second = std::min(FieldInfo.second, MaxFieldAlignment);
2174 // Respect alignment attributes.
2175 if (unsigned fieldAlign = FD->getMaxAlignment()) {
2176 CharUnits FieldAlign = Context.toCharUnitsFromBits(fieldAlign);
2177 AlignAfterVBases = true;
2178 FieldInfo.second = std::max(FieldInfo.second, FieldAlign);
2179 }
2180 return FieldInfo;
2181}
2182
2183void MicrosoftRecordLayoutBuilder::initializeLayout(const RecordDecl *RD) {
2184 IsUnion = RD->isUnion();
Warren Hunt5ae586a2013-11-01 23:59:41 +00002185 Is64BitMode = Context.getTargetInfo().getPointerWidth(0) == 64;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002186
2187 Size = CharUnits::Zero();
2188 Alignment = CharUnits::One();
2189 AlignAfterVBases = false;
2190
2191 // Compute the maximum field alignment.
2192 MaxFieldAlignment = CharUnits::Zero();
2193 // Honor the default struct packing maximum alignment flag.
2194 if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct)
2195 MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
2196 // Honor the packing attribute.
2197 if (const MaxFieldAlignmentAttr *MFAA = RD->getAttr<MaxFieldAlignmentAttr>())
2198 MaxFieldAlignment = Context.toCharUnitsFromBits(MFAA->getAlignment());
2199 // Packed attribute forces max field alignment to be 1.
2200 if (RD->hasAttr<PackedAttr>())
2201 MaxFieldAlignment = CharUnits::One();
2202}
2203
2204void MicrosoftRecordLayoutBuilder::layout(const RecordDecl *RD) {
2205 initializeLayout(RD);
2206 layoutFields(RD);
2207 honorDeclspecAlign(RD);
2208}
2209
2210void MicrosoftRecordLayoutBuilder::cxxLayout(const CXXRecordDecl *RD) {
2211 initializeLayout(RD);
2212 initializeCXXLayout(RD);
2213 layoutVFPtr(RD);
2214 layoutNonVirtualBases(RD);
2215 layoutVBPtr(RD);
2216 layoutFields(RD);
2217 DataSize = Size;
2218 NonVirtualAlignment = Alignment;
2219 layoutVirtualBases(RD);
2220 finalizeCXXLayout(RD);
2221 honorDeclspecAlign(RD);
2222}
2223
2224void
2225MicrosoftRecordLayoutBuilder::initializeCXXLayout(const CXXRecordDecl *RD) {
2226 // Calculate pointer size and alignment.
2227 PointerSize =
2228 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
2229 PointerAlignment = PointerSize;
2230 if (!MaxFieldAlignment.isZero())
2231 PointerAlignment = std::min(PointerAlignment, MaxFieldAlignment);
2232
2233 // Initialize information about the bases.
2234 HasVBPtr = false;
Warren Hunt486e7142013-11-13 22:16:13 +00002235 HasExtendableVFPtr = false;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002236 SharedVBPtrBase = 0;
2237 PrimaryBase = 0;
2238 VirtualAlignment = CharUnits::One();
Warren Hunt55d8e822013-10-23 23:53:07 +00002239 AlignAfterVBases = Is64BitMode;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002240
2241 // If the record has a dynamic base class, attempt to choose a primary base
2242 // class. It is the first (in direct base class order) non-virtual dynamic
2243 // base class, if one exists.
2244 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
2245 e = RD->bases_end();
2246 i != e; ++i) {
2247 const CXXRecordDecl *BaseDecl =
2248 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
2249 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
2250 // Handle forced alignment.
2251 if (Layout.getAlignAfterVBases())
2252 AlignAfterVBases = true;
2253 // Handle virtual bases.
2254 if (i->isVirtual()) {
2255 VirtualAlignment = std::max(VirtualAlignment, Layout.getAlignment());
2256 HasVBPtr = true;
2257 continue;
2258 }
2259 // We located a primary base class!
Warren Hunt486e7142013-11-13 22:16:13 +00002260 if (!PrimaryBase && Layout.hasExtendableVFPtr()) {
Warren Hunt8f8bad72013-10-11 20:19:00 +00002261 PrimaryBase = BaseDecl;
Warren Hunt486e7142013-11-13 22:16:13 +00002262 HasExtendableVFPtr = true;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002263 }
2264 // We located a base to share a VBPtr with!
2265 if (!SharedVBPtrBase && Layout.hasVBPtr()) {
2266 SharedVBPtrBase = BaseDecl;
2267 HasVBPtr = true;
2268 }
2269 updateAlignment(Layout.getAlignment());
2270 }
2271
2272 // Use LayoutFields to compute the alignment of the fields. The layout
2273 // is discarded. This is the simplest way to get all of the bit-field
2274 // behavior correct and is not actually very expensive.
2275 layoutFields(RD);
2276 Size = CharUnits::Zero();
Warren Hunt55d8e822013-10-23 23:53:07 +00002277 BasesAndFieldsAlignment = Alignment;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002278 FieldOffsets.clear();
2279}
2280
2281void MicrosoftRecordLayoutBuilder::layoutVFPtr(const CXXRecordDecl *RD) {
2282 // If we have a primary base then our VFPtr was already laid out
2283 if (PrimaryBase)
2284 return;
2285
2286 // Look at all of our methods to determine if we need a VFPtr. We need a
2287 // vfptr if we define a new virtual function.
Warren Hunt486e7142013-11-13 22:16:13 +00002288 if (!HasExtendableVFPtr && RD->isDynamicClass())
Warren Hunt8f8bad72013-10-11 20:19:00 +00002289 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
2290 e = RD->method_end();
Warren Hunt486e7142013-11-13 22:16:13 +00002291 !HasExtendableVFPtr && i != e; ++i)
2292 HasExtendableVFPtr = i->isVirtual() && i->size_overridden_methods() == 0;
2293 if (!HasExtendableVFPtr)
Warren Hunt8f8bad72013-10-11 20:19:00 +00002294 return;
2295
Warren Hunt55d8e822013-10-23 23:53:07 +00002296 // MSVC 32 (but not 64) potentially over-aligns the vf-table pointer by giving
2297 // it the max alignment of all the non-virtual data in the class. The
2298 // resulting layout is essentially { vftbl, { nvdata } }. This is completely
Warren Hunt8f8bad72013-10-11 20:19:00 +00002299 // unnecessary, but we're not here to pass judgment.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002300 updateAlignment(PointerAlignment);
Warren Hunt55d8e822013-10-23 23:53:07 +00002301 if (Is64BitMode)
2302 Size = Size.RoundUpToAlignment(PointerAlignment) + PointerSize;
2303 else
2304 Size = Size.RoundUpToAlignment(PointerAlignment) + Alignment;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002305}
2306
2307void
2308MicrosoftRecordLayoutBuilder::layoutNonVirtualBases(const CXXRecordDecl *RD) {
2309 LazyEmptyBase = 0;
Warren Hunt55d8e822013-10-23 23:53:07 +00002310 LastBaseWasEmpty = false;
Warren Huntc0df47d2013-11-19 22:11:09 +00002311 LastNonVirtualBaseHasVBPtr = false;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002312
2313 // Lay out the primary base first.
2314 if (PrimaryBase)
2315 layoutNonVirtualBase(PrimaryBase);
2316
2317 // Iterate through the bases and lay out the non-virtual ones.
2318 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
2319 e = RD->bases_end();
2320 i != e; ++i) {
2321 if (i->isVirtual())
2322 continue;
2323 const CXXRecordDecl *BaseDecl =
2324 cast<CXXRecordDecl>(i->getType()->castAs<RecordType>()->getDecl());
2325 if (BaseDecl != PrimaryBase)
2326 layoutNonVirtualBase(BaseDecl);
2327 }
2328}
2329
2330void
2331MicrosoftRecordLayoutBuilder::layoutNonVirtualBase(const CXXRecordDecl *RD) {
2332 const ASTRecordLayout *Layout = RD ? &Context.getASTRecordLayout(RD) : 0;
2333
2334 // If we have a lazy empty base we haven't laid out yet, do that now.
2335 if (LazyEmptyBase) {
2336 const ASTRecordLayout &LazyLayout =
2337 Context.getASTRecordLayout(LazyEmptyBase);
2338 Size = Size.RoundUpToAlignment(LazyLayout.getAlignment());
Warren Huntc0df47d2013-11-19 22:11:09 +00002339 // If the last non-virtual base has a vbptr we add a byte of padding for no
2340 // obvious reason.
2341 if (LastNonVirtualBaseHasVBPtr)
2342 Size++;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002343 Bases.insert(std::make_pair(LazyEmptyBase, Size));
2344 // Empty bases only consume space when followed by another empty base.
Warren Hunt55d8e822013-10-23 23:53:07 +00002345 if (RD && Layout->getNonVirtualSize().isZero()) {
2346 LastBaseWasEmpty = true;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002347 Size++;
Warren Hunt55d8e822013-10-23 23:53:07 +00002348 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002349 LazyEmptyBase = 0;
Warren Huntc0df47d2013-11-19 22:11:09 +00002350 LastNonVirtualBaseHasVBPtr = false;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002351 }
2352
2353 // RD is null when flushing the final lazy base.
2354 if (!RD)
2355 return;
2356
2357 if (Layout->getNonVirtualSize().isZero()) {
2358 LazyEmptyBase = RD;
2359 return;
2360 }
2361
2362 // Insert the base here.
2363 CharUnits BaseOffset = Size.RoundUpToAlignment(Layout->getAlignment());
2364 Bases.insert(std::make_pair(RD, BaseOffset));
2365 Size = BaseOffset + Layout->getDataSize();
2366 // Note: we don't update alignment here because it was accounted
2367 // for during initalization.
Warren Hunt55d8e822013-10-23 23:53:07 +00002368 LastBaseWasEmpty = false;
Warren Huntc0df47d2013-11-19 22:11:09 +00002369 LastNonVirtualBaseHasVBPtr = Layout->hasVBPtr();
Warren Hunt8f8bad72013-10-11 20:19:00 +00002370}
2371
2372void MicrosoftRecordLayoutBuilder::layoutVBPtr(const CXXRecordDecl *RD) {
2373 if (!HasVBPtr)
2374 VBPtrOffset = CharUnits::fromQuantity(-1);
2375 else if (SharedVBPtrBase) {
2376 const ASTRecordLayout &Layout = Context.getASTRecordLayout(SharedVBPtrBase);
2377 VBPtrOffset = Bases[SharedVBPtrBase] + Layout.getVBPtrOffset();
2378 } else {
Warren Hunt8f8bad72013-10-11 20:19:00 +00002379 VBPtrOffset = Size.RoundUpToAlignment(PointerAlignment);
Warren Hunt55d8e822013-10-23 23:53:07 +00002380 CharUnits OldSize = Size;
2381 Size = VBPtrOffset + PointerSize;
2382 if (BasesAndFieldsAlignment <= PointerAlignment) {
2383 // Handle strange padding rules for the lazily placed base. I have no
2384 // explanation for why the last virtual base is padded in such an odd way.
2385 // Two things to note about this padding are that the rules are different
2386 // if the alignment of the bases+fields is <= to the alignemnt of a
2387 // pointer and that the rule in 64-bit mode behaves differently depending
2388 // on if the second to last base was also zero sized.
2389 Size += OldSize % BasesAndFieldsAlignment.getQuantity();
2390 } else {
2391 if (Is64BitMode)
2392 Size += LastBaseWasEmpty ? CharUnits::One() : CharUnits::Zero();
2393 else
2394 Size = OldSize + BasesAndFieldsAlignment;
2395 }
2396 updateAlignment(PointerAlignment);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002397 }
2398
2399 // Flush the lazy empty base.
2400 layoutNonVirtualBase(0);
2401}
2402
2403void MicrosoftRecordLayoutBuilder::layoutFields(const RecordDecl *RD) {
2404 LastFieldIsNonZeroWidthBitfield = false;
2405 for (RecordDecl::field_iterator Field = RD->field_begin(),
2406 FieldEnd = RD->field_end();
2407 Field != FieldEnd; ++Field)
2408 layoutField(*Field);
2409 Size = Size.RoundUpToAlignment(Alignment);
2410}
2411
2412void MicrosoftRecordLayoutBuilder::layoutField(const FieldDecl *FD) {
2413 if (FD->isBitField()) {
2414 layoutBitField(FD);
2415 return;
2416 }
2417 LastFieldIsNonZeroWidthBitfield = false;
2418
2419 std::pair<CharUnits, CharUnits> FieldInfo = getAdjustedFieldInfo(FD);
2420 CharUnits FieldSize = FieldInfo.first;
2421 CharUnits FieldAlign = FieldInfo.second;
2422
2423 updateAlignment(FieldAlign);
2424 if (IsUnion) {
2425 placeFieldAtZero();
2426 Size = std::max(Size, FieldSize);
2427 } else {
2428 // Round up the current record size to the field's alignment boundary.
2429 CharUnits FieldOffset = Size.RoundUpToAlignment(FieldAlign);
2430 placeFieldAtOffset(FieldOffset);
2431 Size = FieldOffset + FieldSize;
2432 }
2433}
2434
2435void MicrosoftRecordLayoutBuilder::layoutBitField(const FieldDecl *FD) {
2436 unsigned Width = FD->getBitWidthValue(Context);
2437 if (Width == 0) {
2438 layoutZeroWidthBitField(FD);
2439 return;
2440 }
2441
2442 std::pair<CharUnits, CharUnits> FieldInfo = getAdjustedFieldInfo(FD);
2443 CharUnits FieldSize = FieldInfo.first;
2444 CharUnits FieldAlign = FieldInfo.second;
2445
2446 // Clamp the bitfield to a containable size for the sake of being able
2447 // to lay them out. Sema will throw an error.
2448 if (Width > Context.toBits(FieldSize))
2449 Width = Context.toBits(FieldSize);
2450
2451 // Check to see if this bitfield fits into an existing allocation. Note:
2452 // MSVC refuses to pack bitfields of formal types with different sizes
2453 // into the same allocation.
2454 if (!IsUnion && LastFieldIsNonZeroWidthBitfield &&
2455 CurrentBitfieldSize == FieldSize && Width <= RemainingBitsInField) {
2456 placeFieldAtBitOffset(Context.toBits(Size) - RemainingBitsInField);
2457 RemainingBitsInField -= Width;
2458 return;
2459 }
2460
2461 LastFieldIsNonZeroWidthBitfield = true;
2462 CurrentBitfieldSize = FieldSize;
2463 if (IsUnion) {
2464 placeFieldAtZero();
2465 Size = std::max(Size, FieldSize);
2466 // TODO: Add a Sema warning that MS ignores bitfield alignment in unions.
2467 } else {
2468 // Allocate a new block of memory and place the bitfield in it.
2469 CharUnits FieldOffset = Size.RoundUpToAlignment(FieldAlign);
2470 placeFieldAtOffset(FieldOffset);
2471 Size = FieldOffset + FieldSize;
2472 updateAlignment(FieldAlign);
2473 RemainingBitsInField = Context.toBits(FieldSize) - Width;
2474 }
2475}
2476
2477void
2478MicrosoftRecordLayoutBuilder::layoutZeroWidthBitField(const FieldDecl *FD) {
2479 // Zero-width bitfields are ignored unless they follow a non-zero-width
2480 // bitfield.
2481 std::pair<CharUnits, CharUnits> FieldInfo = getAdjustedFieldInfo(FD);
2482 CharUnits FieldSize = FieldInfo.first;
2483 CharUnits FieldAlign = FieldInfo.second;
2484
2485 if (!LastFieldIsNonZeroWidthBitfield) {
2486 placeFieldAtOffset(IsUnion ? CharUnits::Zero() : Size);
2487 // TODO: Add a Sema warning that MS ignores alignment for zero
2488 // sized bitfields that occur after zero-size bitfields or non bitfields.
2489 return;
2490 }
2491
2492 LastFieldIsNonZeroWidthBitfield = false;
2493 if (IsUnion) {
2494 placeFieldAtZero();
2495 Size = std::max(Size, FieldSize);
2496 } else {
2497 // Round up the current record size to the field's alignment boundary.
2498 CharUnits FieldOffset = Size.RoundUpToAlignment(FieldAlign);
2499 placeFieldAtOffset(FieldOffset);
2500 Size = FieldOffset;
2501 updateAlignment(FieldAlign);
2502 }
2503}
2504
2505void MicrosoftRecordLayoutBuilder::layoutVirtualBases(const CXXRecordDecl *RD) {
2506 if (!HasVBPtr)
2507 return;
2508
2509 updateAlignment(VirtualAlignment);
2510
2511 // Zero-sized v-bases obey the alignment attribute so apply it here. The
2512 // alignment attribute is normally accounted for in FinalizeLayout.
2513 if (unsigned MaxAlign = RD->getMaxAlignment())
2514 updateAlignment(Context.toCharUnitsFromBits(MaxAlign));
2515
2516 llvm::SmallPtrSet<const CXXRecordDecl *, 2> HasVtordisp =
2517 computeVtorDispSet(RD);
2518
Warren Hunt6b7048d2013-11-06 00:54:59 +00002519 // If the last field we laid out was a non-zero length bitfield then add some
2520 // extra padding for no obvious reason.
2521 if (LastFieldIsNonZeroWidthBitfield)
2522 Size += CurrentBitfieldSize;
2523
Warren Hunt8f8bad72013-10-11 20:19:00 +00002524 // Iterate through the virtual bases and lay them out.
2525 for (CXXRecordDecl::base_class_const_iterator i = RD->vbases_begin(),
2526 e = RD->vbases_end();
2527 i != e; ++i) {
2528 const CXXRecordDecl *BaseDecl =
2529 cast<CXXRecordDecl>(i->getType()->castAs<RecordType>()->getDecl());
2530 layoutVirtualBase(BaseDecl, HasVtordisp.count(BaseDecl));
2531 }
2532}
2533
2534void MicrosoftRecordLayoutBuilder::layoutVirtualBase(const CXXRecordDecl *RD,
2535 bool HasVtordisp) {
2536 if (LazyEmptyBase) {
2537 const ASTRecordLayout &LazyLayout =
2538 Context.getASTRecordLayout(LazyEmptyBase);
2539 Size = Size.RoundUpToAlignment(LazyLayout.getAlignment());
2540 VBases.insert(
2541 std::make_pair(LazyEmptyBase, ASTRecordLayout::VBaseInfo(Size, false)));
2542 // Empty bases only consume space when followed by another empty base.
2543 // The space consumed is in an Alignment sized/aligned block and the v-base
2544 // is placed at its alignment offset into the chunk, unless its alignment
Warren Hunt55d8e822013-10-23 23:53:07 +00002545 // is less than 4 bytes, at which it is placed at 4 byte offset in the
2546 // chunk. We have no idea why.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002547 if (RD && Context.getASTRecordLayout(RD).getNonVirtualSize().isZero())
Warren Hunt55d8e822013-10-23 23:53:07 +00002548 Size = Size.RoundUpToAlignment(Alignment) + CharUnits::fromQuantity(4);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002549 LazyEmptyBase = 0;
2550 }
2551
2552 // RD is null when flushing the final lazy virtual base.
2553 if (!RD)
2554 return;
2555
2556 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2557 if (Layout.getNonVirtualSize().isZero() && !HasVtordisp) {
2558 LazyEmptyBase = RD;
2559 return;
2560 }
2561
2562 CharUnits BaseNVSize = Layout.getNonVirtualSize();
2563 CharUnits BaseAlign = Layout.getAlignment();
2564
Warren Hunt55d8e822013-10-23 23:53:07 +00002565 // vtordisps are always 4 bytes (even in 64-bit mode)
Warren Hunt8f8bad72013-10-11 20:19:00 +00002566 if (HasVtordisp)
Warren Hunt55d8e822013-10-23 23:53:07 +00002567 Size = Size.RoundUpToAlignment(Alignment) + CharUnits::fromQuantity(4);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002568 Size = Size.RoundUpToAlignment(BaseAlign);
2569
2570 // Insert the base here.
2571 CharUnits BaseOffset = Size.RoundUpToAlignment(BaseAlign);
2572 VBases.insert(
2573 std::make_pair(RD, ASTRecordLayout::VBaseInfo(BaseOffset, HasVtordisp)));
2574 Size = BaseOffset + BaseNVSize;
2575 // Note: we don't update alignment here because it was accounted for in
2576 // InitializeLayout.
2577}
2578
2579void MicrosoftRecordLayoutBuilder::finalizeCXXLayout(const CXXRecordDecl *RD) {
2580 // Flush the lazy virtual base.
2581 layoutVirtualBase(0, false);
2582
2583 if (RD->vbases_begin() == RD->vbases_end() || AlignAfterVBases)
2584 Size = Size.RoundUpToAlignment(Alignment);
2585
2586 if (Size.isZero())
2587 Size = Alignment;
2588}
2589
2590void MicrosoftRecordLayoutBuilder::honorDeclspecAlign(const RecordDecl *RD) {
2591 if (unsigned MaxAlign = RD->getMaxAlignment()) {
2592 AlignAfterVBases = true;
2593 updateAlignment(Context.toCharUnitsFromBits(MaxAlign));
2594 Size = Size.RoundUpToAlignment(Alignment);
2595 }
2596}
2597
2598static bool
2599RequiresVtordisp(const llvm::SmallPtrSet<const CXXRecordDecl *, 2> &HasVtordisp,
2600 const CXXRecordDecl *RD) {
2601 if (HasVtordisp.count(RD))
2602 return true;
2603 // If any of a virtual bases non-virtual bases (recursively) requires a
2604 // vtordisp than so does this virtual base.
2605 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
2606 e = RD->bases_end();
2607 i != e; ++i)
2608 if (!i->isVirtual() &&
2609 RequiresVtordisp(
2610 HasVtordisp,
2611 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl())))
2612 return true;
2613 return false;
2614}
2615
2616llvm::SmallPtrSet<const CXXRecordDecl *, 2>
2617MicrosoftRecordLayoutBuilder::computeVtorDispSet(const CXXRecordDecl *RD) {
2618 llvm::SmallPtrSet<const CXXRecordDecl *, 2> HasVtordisp;
2619
2620 // If any of our bases need a vtordisp for this type, so do we. Check our
2621 // direct bases for vtordisp requirements.
2622 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
2623 e = RD->bases_end();
2624 i != e; ++i) {
2625 const CXXRecordDecl *BaseDecl =
2626 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
2627 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
2628 for (ASTRecordLayout::VBaseOffsetsMapTy::const_iterator
2629 bi = Layout.getVBaseOffsetsMap().begin(),
2630 be = Layout.getVBaseOffsetsMap().end();
2631 bi != be; ++bi)
2632 if (bi->second.hasVtorDisp())
2633 HasVtordisp.insert(bi->first);
2634 }
2635
2636 // If we define a constructor or destructor and override a function that is
2637 // defined in a virtual base's vtable, that virtual bases need a vtordisp.
2638 // Here we collect a list of classes with vtables for which our virtual bases
2639 // actually live. The virtual bases with this property will require
2640 // vtordisps. In addition, virtual bases that contain non-virtual bases that
2641 // define functions we override also require vtordisps, this case is checked
2642 // explicitly below.
2643 if (RD->hasUserDeclaredConstructor() || RD->hasUserDeclaredDestructor()) {
2644 llvm::SmallPtrSet<const CXXMethodDecl *, 8> Work;
2645 // Seed the working set with our non-destructor virtual methods.
2646 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
2647 e = RD->method_end();
2648 i != e; ++i)
Warren Hunt42be7762013-10-14 20:14:09 +00002649 if ((*i)->isVirtual() && !isa<CXXDestructorDecl>(*i))
Warren Hunt8f8bad72013-10-11 20:19:00 +00002650 Work.insert(*i);
2651 while (!Work.empty()) {
2652 const CXXMethodDecl *MD = *Work.begin();
2653 CXXMethodDecl::method_iterator i = MD->begin_overridden_methods(),
2654 e = MD->end_overridden_methods();
2655 if (i == e)
2656 // If a virtual method has no-overrides it lives in its parent's vtable.
2657 HasVtordisp.insert(MD->getParent());
2658 else
2659 Work.insert(i, e);
2660 // We've finished processing this element, remove it from the working set.
2661 Work.erase(MD);
2662 }
2663 }
2664
2665 // Re-check all of our vbases for vtordisp requirements (in case their
2666 // non-virtual bases have vtordisp requirements).
2667 for (CXXRecordDecl::base_class_const_iterator i = RD->vbases_begin(),
2668 e = RD->vbases_end();
2669 i != e; ++i) {
2670 const CXXRecordDecl *BaseDecl = i->getType()->getAsCXXRecordDecl();
2671 if (!HasVtordisp.count(BaseDecl) && RequiresVtordisp(HasVtordisp, BaseDecl))
2672 HasVtordisp.insert(BaseDecl);
2673 }
2674
2675 return HasVtordisp;
2676}
2677
2678/// \brief Get or compute information about the layout of the specified record
2679/// (struct/union/class), which indicates its size and field position
2680/// information.
2681const ASTRecordLayout *
2682ASTContext::BuildMicrosoftASTRecordLayout(const RecordDecl *D) const {
2683 MicrosoftRecordLayoutBuilder Builder(*this);
2684 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
2685 Builder.cxxLayout(RD);
2686 return new (*this) ASTRecordLayout(
2687 *this, Builder.Size, Builder.Alignment,
Warren Hunt486e7142013-11-13 22:16:13 +00002688 Builder.HasExtendableVFPtr && !Builder.PrimaryBase,
2689 Builder.HasExtendableVFPtr,
Timur Iskhodzhanov2c9341f2013-11-08 11:45:35 +00002690 Builder.VBPtrOffset, Builder.DataSize, Builder.FieldOffsets.data(),
Warren Hunt8f8bad72013-10-11 20:19:00 +00002691 Builder.FieldOffsets.size(), Builder.DataSize,
2692 Builder.NonVirtualAlignment, CharUnits::Zero(), Builder.PrimaryBase,
Timur Iskhodzhanov2c9341f2013-11-08 11:45:35 +00002693 false, Builder.SharedVBPtrBase, Builder.AlignAfterVBases, Builder.Bases,
2694 Builder.VBases);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002695 } else {
2696 Builder.layout(D);
2697 return new (*this) ASTRecordLayout(
2698 *this, Builder.Size, Builder.Alignment, Builder.Size,
2699 Builder.FieldOffsets.data(), Builder.FieldOffsets.size());
2700 }
2701}
2702
Anders Carlssondf291d82010-05-26 04:56:53 +00002703/// getASTRecordLayout - Get or compute information about the layout of the
2704/// specified record (struct/union/class), which indicates its size and field
2705/// position information.
Jay Foad39c79802011-01-12 09:06:06 +00002706const ASTRecordLayout &
2707ASTContext::getASTRecordLayout(const RecordDecl *D) const {
John McCall0710e552011-10-07 02:39:22 +00002708 // These asserts test different things. A record has a definition
2709 // as soon as we begin to parse the definition. That definition is
2710 // not a complete definition (which is what isDefinition() tests)
2711 // until we *finish* parsing the definition.
Sean Callanan56c19892012-02-08 00:04:52 +00002712
2713 if (D->hasExternalLexicalStorage() && !D->getDefinition())
2714 getExternalSource()->CompleteType(const_cast<RecordDecl*>(D));
2715
Anders Carlssondf291d82010-05-26 04:56:53 +00002716 D = D->getDefinition();
2717 assert(D && "Cannot get layout of forward declarations!");
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00002718 assert(!D->isInvalidDecl() && "Cannot get layout of invalid decl!");
John McCallf937c022011-10-07 06:10:15 +00002719 assert(D->isCompleteDefinition() && "Cannot layout type before complete!");
Anders Carlssondf291d82010-05-26 04:56:53 +00002720
2721 // Look up this layout, if already laid out, return what we have.
2722 // Note that we can't save a reference to the entry because this function
2723 // is recursive.
2724 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
2725 if (Entry) return *Entry;
2726
Warren Hunt8f8bad72013-10-11 20:19:00 +00002727 const ASTRecordLayout *NewEntry = 0;
Anders Carlssond2954862010-05-26 05:10:47 +00002728
Warren Hunt8f8bad72013-10-11 20:19:00 +00002729 if (isMsLayout(D) && !D->getASTContext().getExternalSource()) {
2730 NewEntry = BuildMicrosoftASTRecordLayout(D);
2731 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
Anders Carlssonc121b4e2010-05-27 00:07:01 +00002732 EmptySubobjectMap EmptySubobjects(*this, RD);
John McCall0153cd32011-11-08 04:01:03 +00002733 RecordLayoutBuilder Builder(*this, &EmptySubobjects);
2734 Builder.Layout(RD);
Anders Carlsson439edd12010-05-27 05:41:06 +00002735
John McCall5c1f1d02013-01-29 01:14:22 +00002736 // In certain situations, we are allowed to lay out objects in the
2737 // tail-padding of base classes. This is ABI-dependent.
2738 // FIXME: this should be stored in the record layout.
2739 bool skipTailPadding =
2740 mustSkipTailPadding(getTargetInfo().getCXXABI(), cast<CXXRecordDecl>(D));
Anders Carlssond2954862010-05-26 05:10:47 +00002741
2742 // FIXME: This should be done in FinalizeLayout.
Ken Dyck1b4420e2011-02-28 02:01:38 +00002743 CharUnits DataSize =
John McCall5c1f1d02013-01-29 01:14:22 +00002744 skipTailPadding ? Builder.getSize() : Builder.getDataSize();
Ken Dyck1b4420e2011-02-28 02:01:38 +00002745 CharUnits NonVirtualSize =
John McCall5c1f1d02013-01-29 01:14:22 +00002746 skipTailPadding ? DataSize : Builder.NonVirtualSize;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002747 NewEntry =
John McCall0153cd32011-11-08 04:01:03 +00002748 new (*this) ASTRecordLayout(*this, Builder.getSize(),
2749 Builder.Alignment,
John McCalle42a3362012-05-01 08:55:32 +00002750 Builder.HasOwnVFPtr,
Warren Hunt8f8bad72013-10-11 20:19:00 +00002751 RD->isDynamicClass(),
Warren Hunt55d8e822013-10-23 23:53:07 +00002752 CharUnits::fromQuantity(-1),
Ken Dyck1b4420e2011-02-28 02:01:38 +00002753 DataSize,
John McCall0153cd32011-11-08 04:01:03 +00002754 Builder.FieldOffsets.data(),
2755 Builder.FieldOffsets.size(),
Ken Dyckaf1c83f2011-02-16 01:52:01 +00002756 NonVirtualSize,
John McCall0153cd32011-11-08 04:01:03 +00002757 Builder.NonVirtualAlignment,
Anders Carlssonc121b4e2010-05-27 00:07:01 +00002758 EmptySubobjects.SizeOfLargestEmptySubobject,
John McCall0153cd32011-11-08 04:01:03 +00002759 Builder.PrimaryBase,
2760 Builder.PrimaryBaseIsVirtual,
Timur Iskhodzhanov2c9341f2013-11-08 11:45:35 +00002761 0, true,
John McCall0153cd32011-11-08 04:01:03 +00002762 Builder.Bases, Builder.VBases);
Anders Carlssond2954862010-05-26 05:10:47 +00002763 } else {
John McCall0153cd32011-11-08 04:01:03 +00002764 RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/0);
Anders Carlssond2954862010-05-26 05:10:47 +00002765 Builder.Layout(D);
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002766
Anders Carlssond2954862010-05-26 05:10:47 +00002767 NewEntry =
Ken Dyck1b4420e2011-02-28 02:01:38 +00002768 new (*this) ASTRecordLayout(*this, Builder.getSize(),
Ken Dyck4731d5b2011-02-16 02:05:21 +00002769 Builder.Alignment,
Ken Dyck1b4420e2011-02-28 02:01:38 +00002770 Builder.getSize(),
Anders Carlssond2954862010-05-26 05:10:47 +00002771 Builder.FieldOffsets.data(),
2772 Builder.FieldOffsets.size());
2773 }
2774
Anders Carlssondf291d82010-05-26 04:56:53 +00002775 ASTRecordLayouts[D] = NewEntry;
2776
David Blaikiebbafb8a2012-03-11 07:00:24 +00002777 if (getLangOpts().DumpRecordLayouts) {
Argyrios Kyrtzidis8ade08e2013-07-12 22:30:03 +00002778 llvm::outs() << "\n*** Dumping AST Record Layout\n";
2779 DumpRecordLayout(D, llvm::outs(), getLangOpts().DumpRecordLayoutsSimple);
Anders Carlssondf291d82010-05-26 04:56:53 +00002780 }
2781
2782 return *NewEntry;
2783}
2784
John McCall6bd2a892013-01-25 22:31:03 +00002785const CXXMethodDecl *ASTContext::getCurrentKeyFunction(const CXXRecordDecl *RD) {
Reid Kleckner5d7f2982013-05-29 16:18:30 +00002786 if (!getTargetInfo().getCXXABI().hasKeyFunctions())
2787 return 0;
2788
John McCall6bd2a892013-01-25 22:31:03 +00002789 assert(RD->getDefinition() && "Cannot get key function for forward decl!");
Anders Carlssondf291d82010-05-26 04:56:53 +00002790 RD = cast<CXXRecordDecl>(RD->getDefinition());
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002791
Richard Smith676c4042013-08-29 23:59:27 +00002792 LazyDeclPtr &Entry = KeyFunctions[RD];
2793 if (!Entry)
2794 Entry = const_cast<CXXMethodDecl*>(computeKeyFunction(*this, RD));
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002795
Richard Smith676c4042013-08-29 23:59:27 +00002796 return cast_or_null<CXXMethodDecl>(Entry.get(getExternalSource()));
John McCall6bd2a892013-01-25 22:31:03 +00002797}
2798
Richard Smith676c4042013-08-29 23:59:27 +00002799void ASTContext::setNonKeyFunction(const CXXMethodDecl *Method) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002800 assert(Method == Method->getFirstDecl() &&
John McCall6bd2a892013-01-25 22:31:03 +00002801 "not working with method declaration from class definition");
2802
2803 // Look up the cache entry. Since we're working with the first
2804 // declaration, its parent must be the class definition, which is
2805 // the correct key for the KeyFunctions hash.
Richard Smith676c4042013-08-29 23:59:27 +00002806 llvm::DenseMap<const CXXRecordDecl*, LazyDeclPtr>::iterator
2807 I = KeyFunctions.find(Method->getParent());
John McCall6bd2a892013-01-25 22:31:03 +00002808
2809 // If it's not cached, there's nothing to do.
Richard Smith676c4042013-08-29 23:59:27 +00002810 if (I == KeyFunctions.end()) return;
John McCall6bd2a892013-01-25 22:31:03 +00002811
2812 // If it is cached, check whether it's the target method, and if so,
2813 // remove it from the cache.
Richard Smith676c4042013-08-29 23:59:27 +00002814 if (I->second.get(getExternalSource()) == Method) {
John McCall6bd2a892013-01-25 22:31:03 +00002815 // FIXME: remember that we did this for module / chained PCH state?
Richard Smith676c4042013-08-29 23:59:27 +00002816 KeyFunctions.erase(I);
John McCall6bd2a892013-01-25 22:31:03 +00002817 }
Anders Carlssondf291d82010-05-26 04:56:53 +00002818}
2819
Richard Smithdafff942012-01-14 04:30:29 +00002820static uint64_t getFieldOffset(const ASTContext &C, const FieldDecl *FD) {
2821 const ASTRecordLayout &Layout = C.getASTRecordLayout(FD->getParent());
2822 return Layout.getFieldOffset(FD->getFieldIndex());
2823}
2824
2825uint64_t ASTContext::getFieldOffset(const ValueDecl *VD) const {
2826 uint64_t OffsetInBits;
2827 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
2828 OffsetInBits = ::getFieldOffset(*this, FD);
2829 } else {
2830 const IndirectFieldDecl *IFD = cast<IndirectFieldDecl>(VD);
2831
2832 OffsetInBits = 0;
2833 for (IndirectFieldDecl::chain_iterator CI = IFD->chain_begin(),
2834 CE = IFD->chain_end();
2835 CI != CE; ++CI)
2836 OffsetInBits += ::getFieldOffset(*this, cast<FieldDecl>(*CI));
2837 }
2838
2839 return OffsetInBits;
2840}
2841
Eric Christopher8a39a012011-10-05 06:00:51 +00002842/// getObjCLayout - Get or compute information about the layout of the
2843/// given interface.
Anders Carlssondf291d82010-05-26 04:56:53 +00002844///
2845/// \param Impl - If given, also include the layout of the interface's
2846/// implementation. This may differ by including synthesized ivars.
2847const ASTRecordLayout &
2848ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
Jay Foad39c79802011-01-12 09:06:06 +00002849 const ObjCImplementationDecl *Impl) const {
Douglas Gregor64d92572011-12-20 15:50:13 +00002850 // Retrieve the definition
Sean Callanand9a909c2012-03-15 16:33:08 +00002851 if (D->hasExternalLexicalStorage() && !D->getDefinition())
2852 getExternalSource()->CompleteType(const_cast<ObjCInterfaceDecl*>(D));
Douglas Gregor64d92572011-12-20 15:50:13 +00002853 D = D->getDefinition();
2854 assert(D && D->isThisDeclarationADefinition() && "Invalid interface decl!");
Anders Carlssondf291d82010-05-26 04:56:53 +00002855
2856 // Look up this layout, if already laid out, return what we have.
Roman Divackye6377112012-09-06 15:59:27 +00002857 const ObjCContainerDecl *Key =
2858 Impl ? (const ObjCContainerDecl*) Impl : (const ObjCContainerDecl*) D;
Anders Carlssondf291d82010-05-26 04:56:53 +00002859 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
2860 return *Entry;
2861
2862 // Add in synthesized ivar count if laying out an implementation.
2863 if (Impl) {
2864 unsigned SynthCount = CountNonClassIvars(D);
2865 // If there aren't any sythesized ivars then reuse the interface
2866 // entry. Note we can't cache this because we simply free all
2867 // entries later; however we shouldn't look up implementations
2868 // frequently.
2869 if (SynthCount == 0)
2870 return getObjCLayout(D, 0);
2871 }
2872
John McCall0153cd32011-11-08 04:01:03 +00002873 RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/0);
Anders Carlsson6ed3a9a2010-05-26 05:04:25 +00002874 Builder.Layout(D);
2875
Anders Carlssondf291d82010-05-26 04:56:53 +00002876 const ASTRecordLayout *NewEntry =
Ken Dyck1b4420e2011-02-28 02:01:38 +00002877 new (*this) ASTRecordLayout(*this, Builder.getSize(),
Ken Dyck4731d5b2011-02-16 02:05:21 +00002878 Builder.Alignment,
Ken Dyck1b4420e2011-02-28 02:01:38 +00002879 Builder.getDataSize(),
Anders Carlsson6ed3a9a2010-05-26 05:04:25 +00002880 Builder.FieldOffsets.data(),
2881 Builder.FieldOffsets.size());
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002882
Anders Carlssondf291d82010-05-26 04:56:53 +00002883 ObjCLayouts[Key] = NewEntry;
2884
2885 return *NewEntry;
2886}
2887
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002888static void PrintOffset(raw_ostream &OS,
Anders Carlsson3f018712010-10-31 23:45:59 +00002889 CharUnits Offset, unsigned IndentLevel) {
Benjamin Kramer96ad7172011-11-05 09:02:52 +00002890 OS << llvm::format("%4" PRId64 " | ", (int64_t)Offset.getQuantity());
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002891 OS.indent(IndentLevel * 2);
2892}
2893
Eli Benderskyf6f93ee2012-12-08 00:07:24 +00002894static void PrintIndentNoOffset(raw_ostream &OS, unsigned IndentLevel) {
2895 OS << " | ";
2896 OS.indent(IndentLevel * 2);
2897}
2898
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002899static void DumpCXXRecordLayout(raw_ostream &OS,
Jay Foad39c79802011-01-12 09:06:06 +00002900 const CXXRecordDecl *RD, const ASTContext &C,
Anders Carlsson3f018712010-10-31 23:45:59 +00002901 CharUnits Offset,
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002902 unsigned IndentLevel,
2903 const char* Description,
2904 bool IncludeVirtualBases) {
Anders Carlsson3f018712010-10-31 23:45:59 +00002905 const ASTRecordLayout &Layout = C.getASTRecordLayout(RD);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002906
2907 PrintOffset(OS, Offset, IndentLevel);
Dan Gohman145f3f12010-04-19 16:39:44 +00002908 OS << C.getTypeDeclType(const_cast<CXXRecordDecl *>(RD)).getAsString();
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002909 if (Description)
2910 OS << ' ' << Description;
2911 if (RD->isEmpty())
2912 OS << " (empty)";
2913 OS << '\n';
2914
2915 IndentLevel++;
2916
Anders Carlsson3f018712010-10-31 23:45:59 +00002917 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
Warren Hunt8f8bad72013-10-11 20:19:00 +00002918 bool HasOwnVFPtr = Layout.hasOwnVFPtr();
2919 bool HasOwnVBPtr = Layout.hasOwnVBPtr();
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002920
2921 // Vtable pointer.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002922 if (RD->isDynamicClass() && !PrimaryBase && !isMsLayout(RD)) {
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002923 PrintOffset(OS, Offset, IndentLevel);
Benjamin Kramerb89514a2011-10-14 18:45:37 +00002924 OS << '(' << *RD << " vtable pointer)\n";
Warren Hunt8f8bad72013-10-11 20:19:00 +00002925 } else if (HasOwnVFPtr) {
2926 PrintOffset(OS, Offset, IndentLevel);
2927 // vfptr (for Microsoft C++ ABI)
2928 OS << '(' << *RD << " vftable pointer)\n";
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002929 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002930
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002931 // Dump (non-virtual) bases
2932 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
2933 E = RD->bases_end(); I != E; ++I) {
2934 assert(!I->getType()->isDependentType() &&
2935 "Cannot layout class with dependent bases.");
2936 if (I->isVirtual())
2937 continue;
2938
2939 const CXXRecordDecl *Base =
2940 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
2941
Anders Carlsson3f018712010-10-31 23:45:59 +00002942 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002943
2944 DumpCXXRecordLayout(OS, Base, C, BaseOffset, IndentLevel,
2945 Base == PrimaryBase ? "(primary base)" : "(base)",
2946 /*IncludeVirtualBases=*/false);
2947 }
Eli Friedman43114f92011-10-21 22:49:56 +00002948
Warren Hunt8f8bad72013-10-11 20:19:00 +00002949 // vbptr (for Microsoft C++ ABI)
2950 if (HasOwnVBPtr) {
Eli Friedman84d2d3a2011-09-27 19:12:27 +00002951 PrintOffset(OS, Offset + Layout.getVBPtrOffset(), IndentLevel);
Benjamin Kramerb89514a2011-10-14 18:45:37 +00002952 OS << '(' << *RD << " vbtable pointer)\n";
Eli Friedman84d2d3a2011-09-27 19:12:27 +00002953 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002954
2955 // Dump fields.
2956 uint64_t FieldNo = 0;
2957 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2958 E = RD->field_end(); I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +00002959 const FieldDecl &Field = **I;
Anders Carlsson3f018712010-10-31 23:45:59 +00002960 CharUnits FieldOffset = Offset +
Ken Dyck86a7fcc2011-01-18 01:56:16 +00002961 C.toCharUnitsFromBits(Layout.getFieldOffset(FieldNo));
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002962
David Blaikie2d7c57e2012-04-30 02:36:29 +00002963 if (const RecordType *RT = Field.getType()->getAs<RecordType>()) {
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002964 if (const CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2965 DumpCXXRecordLayout(OS, D, C, FieldOffset, IndentLevel,
David Blaikie2d7c57e2012-04-30 02:36:29 +00002966 Field.getName().data(),
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002967 /*IncludeVirtualBases=*/true);
2968 continue;
2969 }
2970 }
2971
2972 PrintOffset(OS, FieldOffset, IndentLevel);
David Blaikie2d7c57e2012-04-30 02:36:29 +00002973 OS << Field.getType().getAsString() << ' ' << Field << '\n';
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002974 }
2975
2976 if (!IncludeVirtualBases)
2977 return;
2978
2979 // Dump virtual bases.
John McCalle42a3362012-05-01 08:55:32 +00002980 const ASTRecordLayout::VBaseOffsetsMapTy &vtordisps =
2981 Layout.getVBaseOffsetsMap();
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002982 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
2983 E = RD->vbases_end(); I != E; ++I) {
2984 assert(I->isVirtual() && "Found non-virtual class!");
2985 const CXXRecordDecl *VBase =
2986 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
2987
Anders Carlsson3f018712010-10-31 23:45:59 +00002988 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBase);
John McCalle42a3362012-05-01 08:55:32 +00002989
2990 if (vtordisps.find(VBase)->second.hasVtorDisp()) {
2991 PrintOffset(OS, VBaseOffset - CharUnits::fromQuantity(4), IndentLevel);
2992 OS << "(vtordisp for vbase " << *VBase << ")\n";
2993 }
2994
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002995 DumpCXXRecordLayout(OS, VBase, C, VBaseOffset, IndentLevel,
2996 VBase == PrimaryBase ?
2997 "(primary virtual base)" : "(virtual base)",
2998 /*IncludeVirtualBases=*/false);
2999 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003000
Eli Benderskyf6f93ee2012-12-08 00:07:24 +00003001 PrintIndentNoOffset(OS, IndentLevel - 1);
3002 OS << "[sizeof=" << Layout.getSize().getQuantity();
Warren Hunt8f8bad72013-10-11 20:19:00 +00003003 if (!isMsLayout(RD))
3004 OS << ", dsize=" << Layout.getDataSize().getQuantity();
Ken Dyck7ad11e72011-02-15 02:32:40 +00003005 OS << ", align=" << Layout.getAlignment().getQuantity() << '\n';
Eli Benderskyf6f93ee2012-12-08 00:07:24 +00003006
3007 PrintIndentNoOffset(OS, IndentLevel - 1);
3008 OS << " nvsize=" << Layout.getNonVirtualSize().getQuantity();
3009 OS << ", nvalign=" << Layout.getNonVirtualAlign().getQuantity() << "]\n";
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003010 OS << '\n';
3011}
Daniel Dunbarccabe482010-04-19 20:44:53 +00003012
3013void ASTContext::DumpRecordLayout(const RecordDecl *RD,
Douglas Gregore9fc3772012-01-26 07:55:45 +00003014 raw_ostream &OS,
3015 bool Simple) const {
Daniel Dunbarccabe482010-04-19 20:44:53 +00003016 const ASTRecordLayout &Info = getASTRecordLayout(RD);
3017
3018 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Douglas Gregore9fc3772012-01-26 07:55:45 +00003019 if (!Simple)
3020 return DumpCXXRecordLayout(OS, CXXRD, *this, CharUnits(), 0, 0,
3021 /*IncludeVirtualBases=*/true);
Daniel Dunbarccabe482010-04-19 20:44:53 +00003022
3023 OS << "Type: " << getTypeDeclType(RD).getAsString() << "\n";
Douglas Gregore9fc3772012-01-26 07:55:45 +00003024 if (!Simple) {
3025 OS << "Record: ";
3026 RD->dump();
3027 }
Daniel Dunbarccabe482010-04-19 20:44:53 +00003028 OS << "\nLayout: ";
3029 OS << "<ASTRecordLayout\n";
Ken Dyckb0fcc592011-02-11 01:54:29 +00003030 OS << " Size:" << toBits(Info.getSize()) << "\n";
Warren Hunt8f8bad72013-10-11 20:19:00 +00003031 if (!isMsLayout(RD))
3032 OS << " DataSize:" << toBits(Info.getDataSize()) << "\n";
Ken Dyck7ad11e72011-02-15 02:32:40 +00003033 OS << " Alignment:" << toBits(Info.getAlignment()) << "\n";
Daniel Dunbarccabe482010-04-19 20:44:53 +00003034 OS << " FieldOffsets: [";
3035 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i) {
3036 if (i) OS << ", ";
3037 OS << Info.getFieldOffset(i);
3038 }
3039 OS << "]>\n";
3040}