blob: 312d646c7a9530c108af86ce60c3c487524ed0e2 [file] [log] [blame]
Anders Carlsson9392fa62010-05-26 05:41:04 +00001//=== RecordLayoutBuilder.cpp - Helper class for building record layouts ---==//
Anders Carlssonbda4c102009-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
Anders Carlssonbda4c102009-07-18 20:20:21 +000010#include "clang/AST/Attr.h"
Anders Carlsson245656e2010-11-24 22:55:48 +000011#include "clang/AST/CXXInheritance.h"
Anders Carlssonbda4c102009-07-18 20:20:21 +000012#include "clang/AST/Decl.h"
Anders Carlsson74cbe222009-07-19 00:18:47 +000013#include "clang/AST/DeclCXX.h"
Anders Carlsson93fab9d2009-07-18 20:50:59 +000014#include "clang/AST/DeclObjC.h"
Anders Carlssonbda4c102009-07-18 20:20:21 +000015#include "clang/AST/Expr.h"
Anders Carlsson9392fa62010-05-26 05:41:04 +000016#include "clang/AST/RecordLayout.h"
Anders Carlssonbda4c102009-07-18 20:20:21 +000017#include "clang/Basic/TargetInfo.h"
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +000018#include "clang/Sema/SemaDiagnostic.h"
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +000019#include "llvm/Support/Format.h"
20#include "llvm/ADT/SmallSet.h"
21#include "llvm/Support/MathExtras.h"
Ted Kremenek4d96d9f2011-03-19 01:00:36 +000022#include "llvm/Support/CrashRecoveryContext.h"
Anders Carlssonbda4c102009-07-18 20:20:21 +000023
24using namespace clang;
25
Benjamin Kramer7e220282010-05-26 09:58:31 +000026namespace {
Anders Carlsson6a91c032010-05-26 15:32:58 +000027
Anders Carlssonea2f41c2010-05-28 21:24:37 +000028/// BaseSubobjectInfo - Represents a single base subobject in a complete class.
29/// For a class hierarchy like
30///
31/// class A { };
32/// class B : A { };
33/// class C : A, B { };
34///
35/// The BaseSubobjectInfo graph for C will have three BaseSubobjectInfo
36/// instances, one for B and two for A.
37///
38/// If a base is virtual, it will only have one BaseSubobjectInfo allocated.
39struct BaseSubobjectInfo {
40 /// Class - The class for this base info.
Anders Carlsson4a257992010-05-28 21:13:31 +000041 const CXXRecordDecl *Class;
Anders Carlssonea2f41c2010-05-28 21:24:37 +000042
43 /// IsVirtual - Whether the BaseInfo represents a virtual base or not.
Anders Carlsson4a257992010-05-28 21:13:31 +000044 bool IsVirtual;
45
Anders Carlssonea2f41c2010-05-28 21:24:37 +000046 /// Bases - Information about the base subobjects.
Chris Lattner5f9e2722011-07-23 10:55:15 +000047 SmallVector<BaseSubobjectInfo*, 4> Bases;
Anders Carlssonea2f41c2010-05-28 21:24:37 +000048
Anders Carlsson6e264542010-05-29 17:35:14 +000049 /// PrimaryVirtualBaseInfo - Holds the base info for the primary virtual base
50 /// of this base info (if one exists).
51 BaseSubobjectInfo *PrimaryVirtualBaseInfo;
Anders Carlssonea2f41c2010-05-28 21:24:37 +000052
53 // FIXME: Document.
54 const BaseSubobjectInfo *Derived;
Anders Carlsson4a257992010-05-28 21:13:31 +000055};
56
Anders Carlsson6a91c032010-05-26 15:32:58 +000057/// EmptySubobjectMap - Keeps track of which empty subobjects exist at different
58/// offsets while laying out a C++ class.
59class EmptySubobjectMap {
Jay Foad4ba2a172011-01-12 09:06:06 +000060 const ASTContext &Context;
Anders Carlsson8c6acc62010-10-31 21:54:55 +000061 uint64_t CharWidth;
62
Anders Carlsson6a91c032010-05-26 15:32:58 +000063 /// Class - The class whose empty entries we're keeping track of.
64 const CXXRecordDecl *Class;
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +000065
Anders Carlsson58b16b62010-05-27 05:41:06 +000066 /// EmptyClassOffsets - A map from offsets to empty record decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +000067 typedef SmallVector<const CXXRecordDecl *, 1> ClassVectorTy;
Anders Carlssond8da7632010-10-31 21:22:43 +000068 typedef llvm::DenseMap<CharUnits, ClassVectorTy> EmptyClassOffsetsMapTy;
Anders Carlsson58b16b62010-05-27 05:41:06 +000069 EmptyClassOffsetsMapTy EmptyClassOffsets;
70
Anders Carlssonc8cb4622010-06-08 15:56:03 +000071 /// MaxEmptyClassOffset - The highest offset known to contain an empty
72 /// base subobject.
Anders Carlssonfe5ef732010-10-31 21:39:24 +000073 CharUnits MaxEmptyClassOffset;
Anders Carlssonc8cb4622010-06-08 15:56:03 +000074
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +000075 /// ComputeEmptySubobjectSizes - Compute the size of the largest base or
Anders Carlsson0c54fc92010-05-26 15:54:25 +000076 /// member subobject that is empty.
77 void ComputeEmptySubobjectSizes();
Anders Carlsson58b16b62010-05-27 05:41:06 +000078
Anders Carlssonfe5ef732010-10-31 21:39:24 +000079 void AddSubobjectAtOffset(const CXXRecordDecl *RD, CharUnits Offset);
Anders Carlsson812a3452010-05-27 18:20:57 +000080
Anders Carlssonea2f41c2010-05-28 21:24:37 +000081 void UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info,
Anders Carlssona3d43802010-10-31 22:13:23 +000082 CharUnits Offset, bool PlacingEmptyBase);
Anders Carlsson58b16b62010-05-27 05:41:06 +000083
Anders Carlsson812a3452010-05-27 18:20:57 +000084 void UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD,
85 const CXXRecordDecl *Class,
Anders Carlssona3d43802010-10-31 22:13:23 +000086 CharUnits Offset);
87 void UpdateEmptyFieldSubobjects(const FieldDecl *FD, CharUnits Offset);
Anders Carlsson812a3452010-05-27 18:20:57 +000088
Anders Carlssonc8cb4622010-06-08 15:56:03 +000089 /// AnyEmptySubobjectsBeyondOffset - Returns whether there are any empty
90 /// subobjects beyond the given offset.
Anders Carlssonfe5ef732010-10-31 21:39:24 +000091 bool AnyEmptySubobjectsBeyondOffset(CharUnits Offset) const {
Anders Carlssonc8cb4622010-06-08 15:56:03 +000092 return Offset <= MaxEmptyClassOffset;
93 }
94
Anders Carlsson8c6acc62010-10-31 21:54:55 +000095 CharUnits
96 getFieldOffset(const ASTRecordLayout &Layout, unsigned FieldNo) const {
97 uint64_t FieldOffset = Layout.getFieldOffset(FieldNo);
98 assert(FieldOffset % CharWidth == 0 &&
99 "Field offset not at char boundary!");
100
Ken Dyckff3a5172011-01-24 01:28:50 +0000101 return Context.toCharUnitsFromBits(FieldOffset);
Anders Carlssond8da7632010-10-31 21:22:43 +0000102 }
Anders Carlssond8da7632010-10-31 21:22:43 +0000103
Charles Davisc9f8aec2010-08-19 00:55:19 +0000104protected:
Anders Carlssonfe5ef732010-10-31 21:39:24 +0000105 bool CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD,
106 CharUnits Offset) const;
Charles Davisc9f8aec2010-08-19 00:55:19 +0000107
108 bool CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info,
Anders Carlssona3d43802010-10-31 22:13:23 +0000109 CharUnits Offset);
Charles Davisc9f8aec2010-08-19 00:55:19 +0000110
111 bool CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD,
112 const CXXRecordDecl *Class,
Anders Carlssona3d43802010-10-31 22:13:23 +0000113 CharUnits Offset) const;
Charles Davisc9f8aec2010-08-19 00:55:19 +0000114 bool CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD,
Anders Carlsson8c6acc62010-10-31 21:54:55 +0000115 CharUnits Offset) const;
Charles Davisc9f8aec2010-08-19 00:55:19 +0000116
Anders Carlsson6a91c032010-05-26 15:32:58 +0000117public:
Anders Carlsson0c54fc92010-05-26 15:54:25 +0000118 /// This holds the size of the largest empty subobject (either a base
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000119 /// or a member). Will be zero if the record being built doesn't contain
Anders Carlsson0c54fc92010-05-26 15:54:25 +0000120 /// any empty classes.
Anders Carlssona3d43802010-10-31 22:13:23 +0000121 CharUnits SizeOfLargestEmptySubobject;
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000122
Jay Foad4ba2a172011-01-12 09:06:06 +0000123 EmptySubobjectMap(const ASTContext &Context, const CXXRecordDecl *Class)
Anders Carlssona3d43802010-10-31 22:13:23 +0000124 : Context(Context), CharWidth(Context.getCharWidth()), Class(Class) {
Anders Carlsson261febd2010-05-27 00:07:01 +0000125 ComputeEmptySubobjectSizes();
126 }
127
128 /// CanPlaceBaseAtOffset - Return whether the given base class can be placed
129 /// at the given offset.
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000130 /// Returns false if placing the record will result in two components
Anders Carlsson261febd2010-05-27 00:07:01 +0000131 /// (direct or indirect) of the same type having the same offset.
Anders Carlssonc8cb4622010-06-08 15:56:03 +0000132 bool CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info,
Anders Carlssona3d43802010-10-31 22:13:23 +0000133 CharUnits Offset);
Anders Carlsson812a3452010-05-27 18:20:57 +0000134
135 /// CanPlaceFieldAtOffset - Return whether a field can be placed at the given
136 /// offset.
Anders Carlssona3d43802010-10-31 22:13:23 +0000137 bool CanPlaceFieldAtOffset(const FieldDecl *FD, CharUnits Offset);
Anders Carlsson6a91c032010-05-26 15:32:58 +0000138};
Anders Carlsson0c54fc92010-05-26 15:54:25 +0000139
140void EmptySubobjectMap::ComputeEmptySubobjectSizes() {
141 // Check the bases.
142 for (CXXRecordDecl::base_class_const_iterator I = Class->bases_begin(),
143 E = Class->bases_end(); I != E; ++I) {
144 const CXXRecordDecl *BaseDecl =
145 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
146
Anders Carlssona3d43802010-10-31 22:13:23 +0000147 CharUnits EmptySize;
Anders Carlsson0c54fc92010-05-26 15:54:25 +0000148 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
149 if (BaseDecl->isEmpty()) {
150 // If the class decl is empty, get its size.
Ken Dyck5f022d82011-02-09 01:59:34 +0000151 EmptySize = Layout.getSize();
Anders Carlsson0c54fc92010-05-26 15:54:25 +0000152 } else {
153 // Otherwise, we get the largest empty subobject for the decl.
154 EmptySize = Layout.getSizeOfLargestEmptySubobject();
155 }
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000156
Anders Carlssona3d43802010-10-31 22:13:23 +0000157 if (EmptySize > SizeOfLargestEmptySubobject)
158 SizeOfLargestEmptySubobject = EmptySize;
Anders Carlsson0c54fc92010-05-26 15:54:25 +0000159 }
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000160
Anders Carlsson0c54fc92010-05-26 15:54:25 +0000161 // Check the fields.
162 for (CXXRecordDecl::field_iterator I = Class->field_begin(),
163 E = Class->field_end(); I != E; ++I) {
David Blaikie262bc182012-04-30 02:36:29 +0000164 const FieldDecl &FD = *I;
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000165
166 const RecordType *RT =
David Blaikie262bc182012-04-30 02:36:29 +0000167 Context.getBaseElementType(FD.getType())->getAs<RecordType>();
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000168
Anders Carlsson0c54fc92010-05-26 15:54:25 +0000169 // We only care about record types.
170 if (!RT)
171 continue;
172
Anders Carlssona3d43802010-10-31 22:13:23 +0000173 CharUnits EmptySize;
Anders Carlsson0c54fc92010-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 Dyck5f022d82011-02-09 01:59:34 +0000178 EmptySize = Layout.getSize();
Anders Carlsson0c54fc92010-05-26 15:54:25 +0000179 } else {
180 // Otherwise, we get the largest empty subobject for the decl.
181 EmptySize = Layout.getSizeOfLargestEmptySubobject();
182 }
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000183
Anders Carlssona3d43802010-10-31 22:13:23 +0000184 if (EmptySize > SizeOfLargestEmptySubobject)
185 SizeOfLargestEmptySubobject = EmptySize;
Anders Carlsson0c54fc92010-05-26 15:54:25 +0000186 }
187}
188
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000189bool
Anders Carlsson812a3452010-05-27 18:20:57 +0000190EmptySubobjectMap::CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD,
Anders Carlssonfe5ef732010-10-31 21:39:24 +0000191 CharUnits Offset) const {
Anders Carlsson812a3452010-05-27 18:20:57 +0000192 // We only need to check empty bases.
193 if (!RD->isEmpty())
194 return true;
195
Anders Carlssonfe5ef732010-10-31 21:39:24 +0000196 EmptyClassOffsetsMapTy::const_iterator I = EmptyClassOffsets.find(Offset);
Anders Carlsson812a3452010-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 Carlssonfe5ef732010-10-31 21:39:24 +0000209 CharUnits Offset) {
Anders Carlsson812a3452010-05-27 18:20:57 +0000210 // We only care about empty bases.
211 if (!RD->isEmpty())
212 return;
213
Rafael Espindola272324b2010-12-29 23:02:58 +0000214 // If we have empty structures inside an union, we can assign both
215 // the same offset. Just avoid pushing them twice in the list.
Anders Carlssonfe5ef732010-10-31 21:39:24 +0000216 ClassVectorTy& Classes = EmptyClassOffsets[Offset];
Rafael Espindola272324b2010-12-29 23:02:58 +0000217 if (std::find(Classes.begin(), Classes.end(), RD) != Classes.end())
218 return;
219
Anders Carlsson812a3452010-05-27 18:20:57 +0000220 Classes.push_back(RD);
Anders Carlssonc8cb4622010-06-08 15:56:03 +0000221
222 // Update the empty class offset.
Anders Carlssonfe5ef732010-10-31 21:39:24 +0000223 if (Offset > MaxEmptyClassOffset)
224 MaxEmptyClassOffset = Offset;
Anders Carlsson812a3452010-05-27 18:20:57 +0000225}
226
227bool
Anders Carlssona3d43802010-10-31 22:13:23 +0000228EmptySubobjectMap::CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info,
229 CharUnits Offset) {
Anders Carlsson2177ab72010-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 Carlssona3d43802010-10-31 22:13:23 +0000232 if (!AnyEmptySubobjectsBeyondOffset(Offset))
Anders Carlsson2177ab72010-06-08 16:20:35 +0000233 return true;
234
Anders Carlssona3d43802010-10-31 22:13:23 +0000235 if (!CanPlaceSubobjectAtOffset(Info->Class, Offset))
Anders Carlsson812a3452010-05-27 18:20:57 +0000236 return false;
237
Anders Carlsson58b16b62010-05-27 05:41:06 +0000238 // Traverse all non-virtual bases.
Anders Carlsson4137d512010-05-29 21:10:24 +0000239 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
Anders Carlsson58b16b62010-05-27 05:41:06 +0000240 for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) {
Anders Carlssonea2f41c2010-05-28 21:24:37 +0000241 BaseSubobjectInfo* Base = Info->Bases[I];
Anders Carlsson58b16b62010-05-27 05:41:06 +0000242 if (Base->IsVirtual)
243 continue;
244
Anders Carlsson6a356742010-11-01 00:21:58 +0000245 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
Anders Carlsson58b16b62010-05-27 05:41:06 +0000246
247 if (!CanPlaceBaseSubobjectAtOffset(Base, BaseOffset))
248 return false;
249 }
250
Anders Carlsson6e264542010-05-29 17:35:14 +0000251 if (Info->PrimaryVirtualBaseInfo) {
252 BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
Anders Carlsson58b16b62010-05-27 05:41:06 +0000253
254 if (Info == PrimaryVirtualBaseInfo->Derived) {
255 if (!CanPlaceBaseSubobjectAtOffset(PrimaryVirtualBaseInfo, Offset))
256 return false;
257 }
258 }
259
Anders Carlsson812a3452010-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 Blaikie262bc182012-04-30 02:36:29 +0000264 const FieldDecl *FD = &*I;
Anders Carlsson8c6acc62010-10-31 21:54:55 +0000265 if (FD->isBitField())
266 continue;
267
Anders Carlssona3d43802010-10-31 22:13:23 +0000268 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
Anders Carlsson812a3452010-05-27 18:20:57 +0000269 if (!CanPlaceFieldSubobjectAtOffset(FD, FieldOffset))
270 return false;
271 }
272
Anders Carlsson58b16b62010-05-27 05:41:06 +0000273 return true;
274}
275
Anders Carlssonea2f41c2010-05-28 21:24:37 +0000276void EmptySubobjectMap::UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info,
Anders Carlssona3d43802010-10-31 22:13:23 +0000277 CharUnits Offset,
Anders Carlssone3362bc2010-06-13 18:00:18 +0000278 bool PlacingEmptyBase) {
279 if (!PlacingEmptyBase && Offset >= SizeOfLargestEmptySubobject) {
280 // We know that the only empty subobjects that can conflict with empty
281 // subobject of non-empty bases, are empty bases that can be placed at
282 // offset zero. Because of this, we only need to keep track of empty base
283 // subobjects with offsets less than the size of the largest empty
284 // subobject for our class.
285 return;
286 }
287
Anders Carlssona3d43802010-10-31 22:13:23 +0000288 AddSubobjectAtOffset(Info->Class, Offset);
Anders Carlsson4137d512010-05-29 21:10:24 +0000289
Anders Carlsson58b16b62010-05-27 05:41:06 +0000290 // Traverse all non-virtual bases.
Anders Carlsson4137d512010-05-29 21:10:24 +0000291 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
Anders Carlsson58b16b62010-05-27 05:41:06 +0000292 for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) {
Anders Carlssonea2f41c2010-05-28 21:24:37 +0000293 BaseSubobjectInfo* Base = Info->Bases[I];
Anders Carlsson58b16b62010-05-27 05:41:06 +0000294 if (Base->IsVirtual)
295 continue;
Anders Carlsson4137d512010-05-29 21:10:24 +0000296
Anders Carlsson6a356742010-11-01 00:21:58 +0000297 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
Anders Carlssone3362bc2010-06-13 18:00:18 +0000298 UpdateEmptyBaseSubobjects(Base, BaseOffset, PlacingEmptyBase);
Anders Carlsson58b16b62010-05-27 05:41:06 +0000299 }
300
Anders Carlsson6e264542010-05-29 17:35:14 +0000301 if (Info->PrimaryVirtualBaseInfo) {
302 BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
Anders Carlsson58b16b62010-05-27 05:41:06 +0000303
304 if (Info == PrimaryVirtualBaseInfo->Derived)
Anders Carlssone3362bc2010-06-13 18:00:18 +0000305 UpdateEmptyBaseSubobjects(PrimaryVirtualBaseInfo, Offset,
306 PlacingEmptyBase);
Anders Carlsson58b16b62010-05-27 05:41:06 +0000307 }
Anders Carlsson812a3452010-05-27 18:20:57 +0000308
Anders Carlsson812a3452010-05-27 18:20:57 +0000309 // Traverse all member variables.
310 unsigned FieldNo = 0;
311 for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(),
312 E = Info->Class->field_end(); I != E; ++I, ++FieldNo) {
David Blaikie262bc182012-04-30 02:36:29 +0000313 const FieldDecl *FD = &*I;
Anders Carlsson8c6acc62010-10-31 21:54:55 +0000314 if (FD->isBitField())
315 continue;
Anders Carlsson4137d512010-05-29 21:10:24 +0000316
Anders Carlssona3d43802010-10-31 22:13:23 +0000317 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
318 UpdateEmptyFieldSubobjects(FD, FieldOffset);
Anders Carlsson812a3452010-05-27 18:20:57 +0000319 }
Anders Carlsson58b16b62010-05-27 05:41:06 +0000320}
321
Anders Carlsson5b1319c2010-05-29 20:49:49 +0000322bool EmptySubobjectMap::CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info,
Anders Carlssona3d43802010-10-31 22:13:23 +0000323 CharUnits Offset) {
Anders Carlsson261febd2010-05-27 00:07:01 +0000324 // If we know this class doesn't have any empty subobjects we don't need to
325 // bother checking.
Anders Carlssona3d43802010-10-31 22:13:23 +0000326 if (SizeOfLargestEmptySubobject.isZero())
Anders Carlsson261febd2010-05-27 00:07:01 +0000327 return true;
328
Anders Carlsson58b16b62010-05-27 05:41:06 +0000329 if (!CanPlaceBaseSubobjectAtOffset(Info, Offset))
330 return false;
Anders Carlsson812a3452010-05-27 18:20:57 +0000331
332 // We are able to place the base at this offset. Make sure to update the
333 // empty base subobject map.
Anders Carlssone3362bc2010-06-13 18:00:18 +0000334 UpdateEmptyBaseSubobjects(Info, Offset, Info->Class->isEmpty());
Anders Carlsson261febd2010-05-27 00:07:01 +0000335 return true;
336}
337
Anders Carlsson812a3452010-05-27 18:20:57 +0000338bool
339EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD,
340 const CXXRecordDecl *Class,
Anders Carlssona3d43802010-10-31 22:13:23 +0000341 CharUnits Offset) const {
Anders Carlsson2177ab72010-06-08 16:20:35 +0000342 // We don't have to keep looking past the maximum offset that's known to
343 // contain an empty class.
Anders Carlssona3d43802010-10-31 22:13:23 +0000344 if (!AnyEmptySubobjectsBeyondOffset(Offset))
Anders Carlsson2177ab72010-06-08 16:20:35 +0000345 return true;
346
Anders Carlssona3d43802010-10-31 22:13:23 +0000347 if (!CanPlaceSubobjectAtOffset(RD, Offset))
Anders Carlsson812a3452010-05-27 18:20:57 +0000348 return false;
349
350 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
351
352 // Traverse all non-virtual bases.
353 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
354 E = RD->bases_end(); I != E; ++I) {
355 if (I->isVirtual())
356 continue;
357
358 const CXXRecordDecl *BaseDecl =
359 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
360
Anders Carlsson6a356742010-11-01 00:21:58 +0000361 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson812a3452010-05-27 18:20:57 +0000362 if (!CanPlaceFieldSubobjectAtOffset(BaseDecl, Class, BaseOffset))
363 return false;
364 }
365
Anders Carlsson45f5b542010-06-08 19:09:24 +0000366 if (RD == Class) {
367 // This is the most derived class, traverse virtual bases as well.
368 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
369 E = RD->vbases_end(); I != E; ++I) {
370 const CXXRecordDecl *VBaseDecl =
371 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
372
Anders Carlsson3069a0d2010-10-31 23:45:59 +0000373 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
Anders Carlsson45f5b542010-06-08 19:09:24 +0000374 if (!CanPlaceFieldSubobjectAtOffset(VBaseDecl, Class, VBaseOffset))
375 return false;
376 }
377 }
378
Anders Carlsson812a3452010-05-27 18:20:57 +0000379 // Traverse all member variables.
380 unsigned FieldNo = 0;
381 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
382 I != E; ++I, ++FieldNo) {
David Blaikie262bc182012-04-30 02:36:29 +0000383 const FieldDecl *FD = &*I;
Anders Carlsson8c6acc62010-10-31 21:54:55 +0000384 if (FD->isBitField())
385 continue;
386
Anders Carlssona3d43802010-10-31 22:13:23 +0000387 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
Anders Carlsson812a3452010-05-27 18:20:57 +0000388
389 if (!CanPlaceFieldSubobjectAtOffset(FD, FieldOffset))
390 return false;
391 }
392
393 return true;
394}
395
Anders Carlsson8c6acc62010-10-31 21:54:55 +0000396bool
397EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD,
398 CharUnits Offset) const {
Anders Carlsson2177ab72010-06-08 16:20:35 +0000399 // We don't have to keep looking past the maximum offset that's known to
400 // contain an empty class.
Anders Carlsson8c6acc62010-10-31 21:54:55 +0000401 if (!AnyEmptySubobjectsBeyondOffset(Offset))
Anders Carlsson2177ab72010-06-08 16:20:35 +0000402 return true;
403
Anders Carlsson812a3452010-05-27 18:20:57 +0000404 QualType T = FD->getType();
405 if (const RecordType *RT = T->getAs<RecordType>()) {
406 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlssona3d43802010-10-31 22:13:23 +0000407 return CanPlaceFieldSubobjectAtOffset(RD, RD, Offset);
Anders Carlsson812a3452010-05-27 18:20:57 +0000408 }
409
410 // If we have an array type we need to look at every element.
411 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
412 QualType ElemTy = Context.getBaseElementType(AT);
413 const RecordType *RT = ElemTy->getAs<RecordType>();
414 if (!RT)
415 return true;
416
417 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
418 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
419
420 uint64_t NumElements = Context.getConstantArrayElementCount(AT);
Anders Carlsson8c6acc62010-10-31 21:54:55 +0000421 CharUnits ElementOffset = Offset;
Anders Carlsson812a3452010-05-27 18:20:57 +0000422 for (uint64_t I = 0; I != NumElements; ++I) {
Anders Carlsson2177ab72010-06-08 16:20:35 +0000423 // We don't have to keep looking past the maximum offset that's known to
424 // contain an empty class.
Anders Carlsson8c6acc62010-10-31 21:54:55 +0000425 if (!AnyEmptySubobjectsBeyondOffset(ElementOffset))
Anders Carlsson2177ab72010-06-08 16:20:35 +0000426 return true;
427
Anders Carlssona3d43802010-10-31 22:13:23 +0000428 if (!CanPlaceFieldSubobjectAtOffset(RD, RD, ElementOffset))
Anders Carlsson812a3452010-05-27 18:20:57 +0000429 return false;
430
Ken Dyck5f022d82011-02-09 01:59:34 +0000431 ElementOffset += Layout.getSize();
Anders Carlsson812a3452010-05-27 18:20:57 +0000432 }
433 }
434
435 return true;
436}
437
438bool
Anders Carlssona3d43802010-10-31 22:13:23 +0000439EmptySubobjectMap::CanPlaceFieldAtOffset(const FieldDecl *FD,
440 CharUnits Offset) {
441 if (!CanPlaceFieldSubobjectAtOffset(FD, Offset))
Anders Carlsson812a3452010-05-27 18:20:57 +0000442 return false;
443
444 // We are able to place the member variable at this offset.
445 // Make sure to update the empty base subobject map.
446 UpdateEmptyFieldSubobjects(FD, Offset);
447 return true;
448}
449
450void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD,
451 const CXXRecordDecl *Class,
Anders Carlssona3d43802010-10-31 22:13:23 +0000452 CharUnits Offset) {
Anders Carlsson5ccfdd82010-06-13 17:49:16 +0000453 // We know that the only empty subobjects that can conflict with empty
Anders Carlssone3362bc2010-06-13 18:00:18 +0000454 // field subobjects are subobjects of empty bases that can be placed at offset
Anders Carlsson5ccfdd82010-06-13 17:49:16 +0000455 // zero. Because of this, we only need to keep track of empty field
456 // subobjects with offsets less than the size of the largest empty
457 // subobject for our class.
458 if (Offset >= SizeOfLargestEmptySubobject)
459 return;
460
Anders Carlssona3d43802010-10-31 22:13:23 +0000461 AddSubobjectAtOffset(RD, Offset);
Anders Carlsson812a3452010-05-27 18:20:57 +0000462
463 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
464
465 // Traverse all non-virtual bases.
466 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
467 E = RD->bases_end(); I != E; ++I) {
468 if (I->isVirtual())
469 continue;
470
471 const CXXRecordDecl *BaseDecl =
472 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
473
Anders Carlsson6a356742010-11-01 00:21:58 +0000474 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson812a3452010-05-27 18:20:57 +0000475 UpdateEmptyFieldSubobjects(BaseDecl, Class, BaseOffset);
476 }
477
Anders Carlsson45f5b542010-06-08 19:09:24 +0000478 if (RD == Class) {
479 // This is the most derived class, traverse virtual bases as well.
480 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
481 E = RD->vbases_end(); I != E; ++I) {
482 const CXXRecordDecl *VBaseDecl =
483 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
484
Anders Carlsson3069a0d2010-10-31 23:45:59 +0000485 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
Anders Carlsson45f5b542010-06-08 19:09:24 +0000486 UpdateEmptyFieldSubobjects(VBaseDecl, Class, VBaseOffset);
487 }
488 }
489
Anders Carlsson812a3452010-05-27 18:20:57 +0000490 // Traverse all member variables.
491 unsigned FieldNo = 0;
492 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
493 I != E; ++I, ++FieldNo) {
David Blaikie262bc182012-04-30 02:36:29 +0000494 const FieldDecl *FD = &*I;
Anders Carlssonfa84fba2010-11-01 15:14:51 +0000495 if (FD->isBitField())
496 continue;
497
Anders Carlssona3d43802010-10-31 22:13:23 +0000498 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
Anders Carlsson812a3452010-05-27 18:20:57 +0000499
Anders Carlssona3d43802010-10-31 22:13:23 +0000500 UpdateEmptyFieldSubobjects(FD, FieldOffset);
Anders Carlsson812a3452010-05-27 18:20:57 +0000501 }
502}
503
504void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const FieldDecl *FD,
Anders Carlssona3d43802010-10-31 22:13:23 +0000505 CharUnits Offset) {
Anders Carlsson812a3452010-05-27 18:20:57 +0000506 QualType T = FD->getType();
507 if (const RecordType *RT = T->getAs<RecordType>()) {
508 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
509 UpdateEmptyFieldSubobjects(RD, RD, Offset);
510 return;
511 }
512
513 // If we have an array type we need to update every element.
514 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
515 QualType ElemTy = Context.getBaseElementType(AT);
516 const RecordType *RT = ElemTy->getAs<RecordType>();
517 if (!RT)
518 return;
519
520 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
521 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
522
523 uint64_t NumElements = Context.getConstantArrayElementCount(AT);
Anders Carlssona3d43802010-10-31 22:13:23 +0000524 CharUnits ElementOffset = Offset;
Anders Carlsson812a3452010-05-27 18:20:57 +0000525
526 for (uint64_t I = 0; I != NumElements; ++I) {
Anders Carlsson5ccfdd82010-06-13 17:49:16 +0000527 // We know that the only empty subobjects that can conflict with empty
Anders Carlssone3362bc2010-06-13 18:00:18 +0000528 // field subobjects are subobjects of empty bases that can be placed at
Anders Carlsson5ccfdd82010-06-13 17:49:16 +0000529 // offset zero. Because of this, we only need to keep track of empty field
530 // subobjects with offsets less than the size of the largest empty
531 // subobject for our class.
532 if (ElementOffset >= SizeOfLargestEmptySubobject)
533 return;
534
Anders Carlsson812a3452010-05-27 18:20:57 +0000535 UpdateEmptyFieldSubobjects(RD, RD, ElementOffset);
Ken Dyck5f022d82011-02-09 01:59:34 +0000536 ElementOffset += Layout.getSize();
Anders Carlsson812a3452010-05-27 18:20:57 +0000537 }
538 }
539}
540
John McCall441c6232012-05-01 08:55:32 +0000541typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> ClassSetTy;
542
Anders Carlsson7d0918a2010-05-26 05:58:59 +0000543class RecordLayoutBuilder {
Charles Davisc9f8aec2010-08-19 00:55:19 +0000544protected:
Anders Carlsson9392fa62010-05-26 05:41:04 +0000545 // FIXME: Remove this and make the appropriate fields public.
546 friend class clang::ASTContext;
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000547
Jay Foad4ba2a172011-01-12 09:06:06 +0000548 const ASTContext &Context;
Anders Carlsson9392fa62010-05-26 05:41:04 +0000549
Anders Carlsson6a91c032010-05-26 15:32:58 +0000550 EmptySubobjectMap *EmptySubobjects;
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000551
Anders Carlsson9392fa62010-05-26 05:41:04 +0000552 /// Size - The current size of the record layout.
553 uint64_t Size;
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000554
Anders Carlsson9392fa62010-05-26 05:41:04 +0000555 /// Alignment - The current alignment of the record layout.
Ken Dyckea7f6c22011-02-16 02:05:21 +0000556 CharUnits Alignment;
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000557
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000558 /// \brief The alignment if attribute packed is not used.
Ken Dyck6feb4bb2011-02-16 02:11:31 +0000559 CharUnits UnpackedAlignment;
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000560
Chris Lattner5f9e2722011-07-23 10:55:15 +0000561 SmallVector<uint64_t, 16> FieldOffsets;
Anders Carlsson9392fa62010-05-26 05:41:04 +0000562
Douglas Gregor453dbcb2012-01-26 07:55:45 +0000563 /// \brief Whether the external AST source has provided a layout for this
564 /// record.
565 unsigned ExternalLayout : 1;
Douglas Gregor394f7b62012-01-28 00:53:29 +0000566
567 /// \brief Whether we need to infer alignment, even when we have an
568 /// externally-provided layout.
569 unsigned InferAlignment : 1;
Douglas Gregor453dbcb2012-01-26 07:55:45 +0000570
Anders Carlsson9392fa62010-05-26 05:41:04 +0000571 /// Packed - Whether the record is packed or not.
Daniel Dunbarc6082fe2010-05-27 05:45:51 +0000572 unsigned Packed : 1;
573
574 unsigned IsUnion : 1;
575
576 unsigned IsMac68kAlign : 1;
Fariborz Jahanian62055b02011-04-26 23:52:16 +0000577
578 unsigned IsMsStruct : 1;
Anders Carlsson9392fa62010-05-26 05:41:04 +0000579
580 /// UnfilledBitsInLastByte - If the last field laid out was a bitfield,
581 /// this contains the number of bits in the last byte that can be used for
582 /// an adjacent bitfield if necessary.
583 unsigned char UnfilledBitsInLastByte;
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000584
Anders Carlsson9392fa62010-05-26 05:41:04 +0000585 /// MaxFieldAlignment - The maximum allowed field alignment. This is set by
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000586 /// #pragma pack.
Ken Dyck834945c2011-02-17 01:49:42 +0000587 CharUnits MaxFieldAlignment;
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000588
Anders Carlsson9392fa62010-05-26 05:41:04 +0000589 /// DataSize - The data size of the record being laid out.
590 uint64_t DataSize;
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000591
Ken Dycka1fdb0b2011-02-16 01:52:01 +0000592 CharUnits NonVirtualSize;
Ken Dyckdf205382011-02-16 01:43:15 +0000593 CharUnits NonVirtualAlignment;
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000594
Fariborz Jahanian855a8e72011-05-03 20:21:04 +0000595 FieldDecl *ZeroLengthBitfield;
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000596
Anders Carlsson9392fa62010-05-26 05:41:04 +0000597 /// PrimaryBase - the primary base class (if one exists) of the class
598 /// we're laying out.
599 const CXXRecordDecl *PrimaryBase;
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000600
Anders Carlsson9392fa62010-05-26 05:41:04 +0000601 /// PrimaryBaseIsVirtual - Whether the primary base of the class we're laying
602 /// out is virtual.
603 bool PrimaryBaseIsVirtual;
604
John McCall441c6232012-05-01 08:55:32 +0000605 /// HasOwnVFPtr - Whether the class provides its own vtable/vftbl
606 /// pointer, as opposed to inheriting one from a primary base class.
607 bool HasOwnVFPtr;
Eli Friedman227e4832011-10-21 22:49:56 +0000608
Eli Friedman2fe36362011-09-27 19:12:27 +0000609 /// VBPtrOffset - Virtual base table offset. Only for MS layout.
610 CharUnits VBPtrOffset;
611
Anders Carlsson376bda92010-10-31 21:01:46 +0000612 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000613
Anders Carlsson9392fa62010-05-26 05:41:04 +0000614 /// Bases - base classes and their offsets in the record.
615 BaseOffsetsMapTy Bases;
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000616
Anders Carlsson9392fa62010-05-26 05:41:04 +0000617 // VBases - virtual base classes and their offsets in the record.
John McCall441c6232012-05-01 08:55:32 +0000618 ASTRecordLayout::VBaseOffsetsMapTy VBases;
Anders Carlsson9392fa62010-05-26 05:41:04 +0000619
620 /// IndirectPrimaryBases - Virtual base classes, direct or indirect, that are
621 /// primary base classes for some other direct or indirect base class.
Anders Carlsson245656e2010-11-24 22:55:48 +0000622 CXXIndirectPrimaryBaseSet IndirectPrimaryBases;
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000623
Anders Carlsson9392fa62010-05-26 05:41:04 +0000624 /// FirstNearlyEmptyVBase - The first nearly empty virtual base class in
625 /// inheritance graph order. Used for determining the primary base class.
626 const CXXRecordDecl *FirstNearlyEmptyVBase;
627
628 /// VisitedVirtualBases - A set of all the visited virtual bases, used to
629 /// avoid visiting virtual bases more than once.
630 llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000631
Douglas Gregor453dbcb2012-01-26 07:55:45 +0000632 /// \brief Externally-provided size.
633 uint64_t ExternalSize;
634
635 /// \brief Externally-provided alignment.
636 uint64_t ExternalAlign;
637
638 /// \brief Externally-provided field offsets.
639 llvm::DenseMap<const FieldDecl *, uint64_t> ExternalFieldOffsets;
640
641 /// \brief Externally-provided direct, non-virtual base offsets.
642 llvm::DenseMap<const CXXRecordDecl *, CharUnits> ExternalBaseOffsets;
643
644 /// \brief Externally-provided virtual base offsets.
645 llvm::DenseMap<const CXXRecordDecl *, CharUnits> ExternalVirtualBaseOffsets;
646
John McCall9da23522011-11-08 04:01:03 +0000647 RecordLayoutBuilder(const ASTContext &Context,
648 EmptySubobjectMap *EmptySubobjects)
Ken Dyckea7f6c22011-02-16 02:05:21 +0000649 : Context(Context), EmptySubobjects(EmptySubobjects), Size(0),
John McCall9da23522011-11-08 04:01:03 +0000650 Alignment(CharUnits::One()), UnpackedAlignment(CharUnits::One()),
Douglas Gregor394f7b62012-01-28 00:53:29 +0000651 ExternalLayout(false), InferAlignment(false),
652 Packed(false), IsUnion(false), IsMac68kAlign(false), IsMsStruct(false),
Ken Dyck834945c2011-02-17 01:49:42 +0000653 UnfilledBitsInLastByte(0), MaxFieldAlignment(CharUnits::Zero()),
654 DataSize(0), NonVirtualSize(CharUnits::Zero()),
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000655 NonVirtualAlignment(CharUnits::One()),
Fariborz Jahanian855a8e72011-05-03 20:21:04 +0000656 ZeroLengthBitfield(0), PrimaryBase(0),
Eli Friedman227e4832011-10-21 22:49:56 +0000657 PrimaryBaseIsVirtual(false),
John McCall441c6232012-05-01 08:55:32 +0000658 HasOwnVFPtr(false),
Eli Friedman227e4832011-10-21 22:49:56 +0000659 VBPtrOffset(CharUnits::fromQuantity(-1)),
Eli Friedman2fe36362011-09-27 19:12:27 +0000660 FirstNearlyEmptyVBase(0) { }
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000661
John McCall9da23522011-11-08 04:01:03 +0000662 /// Reset this RecordLayoutBuilder to a fresh state, using the given
663 /// alignment as the initial alignment. This is used for the
664 /// correct layout of vb-table pointers in MSVC.
665 void resetWithTargetAlignment(CharUnits TargetAlignment) {
666 const ASTContext &Context = this->Context;
667 EmptySubobjectMap *EmptySubobjects = this->EmptySubobjects;
668 this->~RecordLayoutBuilder();
669 new (this) RecordLayoutBuilder(Context, EmptySubobjects);
670 Alignment = UnpackedAlignment = TargetAlignment;
671 }
672
Anders Carlsson9392fa62010-05-26 05:41:04 +0000673 void Layout(const RecordDecl *D);
Anders Carlssonc6cab682010-05-26 15:10:00 +0000674 void Layout(const CXXRecordDecl *D);
Anders Carlsson9392fa62010-05-26 05:41:04 +0000675 void Layout(const ObjCInterfaceDecl *D);
676
677 void LayoutFields(const RecordDecl *D);
678 void LayoutField(const FieldDecl *D);
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000679 void LayoutWideBitField(uint64_t FieldSize, uint64_t TypeSize,
680 bool FieldPacked, const FieldDecl *D);
Anders Carlsson9392fa62010-05-26 05:41:04 +0000681 void LayoutBitField(const FieldDecl *D);
John McCall9da23522011-11-08 04:01:03 +0000682
683 bool isMicrosoftCXXABI() const {
684 return Context.getTargetInfo().getCXXABI() == CXXABI_Microsoft;
685 }
686
Eli Friedman2fe36362011-09-27 19:12:27 +0000687 void MSLayoutVirtualBases(const CXXRecordDecl *RD);
Anders Carlsson9392fa62010-05-26 05:41:04 +0000688
Anders Carlsson6e264542010-05-29 17:35:14 +0000689 /// BaseSubobjectInfoAllocator - Allocator for BaseSubobjectInfo objects.
690 llvm::SpecificBumpPtrAllocator<BaseSubobjectInfo> BaseSubobjectInfoAllocator;
691
692 typedef llvm::DenseMap<const CXXRecordDecl *, BaseSubobjectInfo *>
693 BaseSubobjectInfoMapTy;
694
695 /// VirtualBaseInfo - Map from all the (direct or indirect) virtual bases
696 /// of the class we're laying out to their base subobject info.
697 BaseSubobjectInfoMapTy VirtualBaseInfo;
698
699 /// NonVirtualBaseInfo - Map from all the direct non-virtual bases of the
700 /// class we're laying out to their base subobject info.
701 BaseSubobjectInfoMapTy NonVirtualBaseInfo;
702
703 /// ComputeBaseSubobjectInfo - Compute the base subobject information for the
704 /// bases of the given class.
705 void ComputeBaseSubobjectInfo(const CXXRecordDecl *RD);
706
707 /// ComputeBaseSubobjectInfo - Compute the base subobject information for a
708 /// single class and all of its base classes.
709 BaseSubobjectInfo *ComputeBaseSubobjectInfo(const CXXRecordDecl *RD,
710 bool IsVirtual,
711 BaseSubobjectInfo *Derived);
Anders Carlsson9392fa62010-05-26 05:41:04 +0000712
713 /// DeterminePrimaryBase - Determine the primary base of the given class.
714 void DeterminePrimaryBase(const CXXRecordDecl *RD);
715
716 void SelectPrimaryVBase(const CXXRecordDecl *RD);
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000717
Eli Friedman227e4832011-10-21 22:49:56 +0000718 void EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign);
Charles Davisc9f8aec2010-08-19 00:55:19 +0000719
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000720 /// LayoutNonVirtualBases - Determines the primary base class (if any) and
Anders Carlsson9392fa62010-05-26 05:41:04 +0000721 /// lays it out. Will then proceed to lay out all non-virtual base clasess.
722 void LayoutNonVirtualBases(const CXXRecordDecl *RD);
723
724 /// LayoutNonVirtualBase - Lays out a single non-virtual base.
Anders Carlsson07cebc52010-05-29 17:42:25 +0000725 void LayoutNonVirtualBase(const BaseSubobjectInfo *Base);
Anders Carlsson9392fa62010-05-26 05:41:04 +0000726
Anders Carlssona2311512010-10-31 22:20:42 +0000727 void AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
728 CharUnits Offset);
Anders Carlsson9392fa62010-05-26 05:41:04 +0000729
John McCall9da23522011-11-08 04:01:03 +0000730 bool needsVFTable(const CXXRecordDecl *RD) const;
John McCall441c6232012-05-01 08:55:32 +0000731 bool hasNewVirtualFunction(const CXXRecordDecl *RD,
732 bool IgnoreDestructor = false) const;
John McCall9da23522011-11-08 04:01:03 +0000733 bool isPossiblePrimaryBase(const CXXRecordDecl *Base) const;
Eli Friedman97c0aef2011-10-18 00:55:28 +0000734
John McCall441c6232012-05-01 08:55:32 +0000735 void computeVtordisps(const CXXRecordDecl *RD,
736 ClassSetTy &VtordispVBases);
737
Anders Carlsson9392fa62010-05-26 05:41:04 +0000738 /// LayoutVirtualBases - Lays out all the virtual bases.
739 void LayoutVirtualBases(const CXXRecordDecl *RD,
740 const CXXRecordDecl *MostDerivedClass);
741
742 /// LayoutVirtualBase - Lays out a single virtual base.
John McCall441c6232012-05-01 08:55:32 +0000743 void LayoutVirtualBase(const BaseSubobjectInfo *Base,
744 bool IsVtordispNeed = false);
Anders Carlsson9392fa62010-05-26 05:41:04 +0000745
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000746 /// LayoutBase - Will lay out a base and return the offset where it was
Anders Carlssona2311512010-10-31 22:20:42 +0000747 /// placed, in chars.
748 CharUnits LayoutBase(const BaseSubobjectInfo *Base);
Anders Carlsson9392fa62010-05-26 05:41:04 +0000749
Anders Carlssonc6cab682010-05-26 15:10:00 +0000750 /// InitializeLayout - Initialize record layout for the given record decl.
Daniel Dunbarc6082fe2010-05-27 05:45:51 +0000751 void InitializeLayout(const Decl *D);
Anders Carlssonc6cab682010-05-26 15:10:00 +0000752
Anders Carlsson9392fa62010-05-26 05:41:04 +0000753 /// FinishLayout - Finalize record layout. Adjust record size based on the
754 /// alignment.
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000755 void FinishLayout(const NamedDecl *D);
Anders Carlsson9392fa62010-05-26 05:41:04 +0000756
Ken Dyck3263e092011-02-19 18:58:07 +0000757 void UpdateAlignment(CharUnits NewAlignment, CharUnits UnpackedNewAlignment);
758 void UpdateAlignment(CharUnits NewAlignment) {
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000759 UpdateAlignment(NewAlignment, NewAlignment);
760 }
761
Douglas Gregor394f7b62012-01-28 00:53:29 +0000762 /// \brief Retrieve the externally-supplied field offset for the given
763 /// field.
764 ///
765 /// \param Field The field whose offset is being queried.
766 /// \param ComputedOffset The offset that we've computed for this field.
767 uint64_t updateExternalFieldOffset(const FieldDecl *Field,
768 uint64_t ComputedOffset);
769
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000770 void CheckFieldPadding(uint64_t Offset, uint64_t UnpaddedOffset,
771 uint64_t UnpackedOffset, unsigned UnpackedAlign,
772 bool isPacked, const FieldDecl *D);
773
774 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
Anders Carlsson9392fa62010-05-26 05:41:04 +0000775
Ken Dycka0c21c42011-02-24 01:13:28 +0000776 CharUnits getSize() const {
Ken Dyck99113442011-02-24 01:33:05 +0000777 assert(Size % Context.getCharWidth() == 0);
Ken Dycka0c21c42011-02-24 01:13:28 +0000778 return Context.toCharUnitsFromBits(Size);
779 }
780 uint64_t getSizeInBits() const { return Size; }
781
782 void setSize(CharUnits NewSize) { Size = Context.toBits(NewSize); }
783 void setSize(uint64_t NewSize) { Size = NewSize; }
784
Eli Friedman2fe36362011-09-27 19:12:27 +0000785 CharUnits getAligment() const { return Alignment; }
786
Ken Dycka0c21c42011-02-24 01:13:28 +0000787 CharUnits getDataSize() const {
Ken Dyck99113442011-02-24 01:33:05 +0000788 assert(DataSize % Context.getCharWidth() == 0);
Ken Dycka0c21c42011-02-24 01:13:28 +0000789 return Context.toCharUnitsFromBits(DataSize);
790 }
791 uint64_t getDataSizeInBits() const { return DataSize; }
792
793 void setDataSize(CharUnits NewSize) { DataSize = Context.toBits(NewSize); }
794 void setDataSize(uint64_t NewSize) { DataSize = NewSize; }
795
Argyrios Kyrtzidisc83d2d72010-08-15 10:17:39 +0000796 RecordLayoutBuilder(const RecordLayoutBuilder&); // DO NOT IMPLEMENT
797 void operator=(const RecordLayoutBuilder&); // DO NOT IMPLEMENT
Anders Carlsson9392fa62010-05-26 05:41:04 +0000798public:
799 static const CXXMethodDecl *ComputeKeyFunction(const CXXRecordDecl *RD);
800};
Benjamin Kramer7e220282010-05-26 09:58:31 +0000801} // end anonymous namespace
Anders Carlsson9392fa62010-05-26 05:41:04 +0000802
Anders Carlsson3f066522009-09-22 03:02:06 +0000803void
Anders Carlsson7d0918a2010-05-26 05:58:59 +0000804RecordLayoutBuilder::SelectPrimaryVBase(const CXXRecordDecl *RD) {
Anders Carlsson584e1df2010-03-11 03:39:12 +0000805 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +0000806 E = RD->bases_end(); I != E; ++I) {
Anders Carlsson584e1df2010-03-11 03:39:12 +0000807 assert(!I->getType()->isDependentType() &&
Sebastian Redl9994a342009-10-25 17:03:50 +0000808 "Cannot layout class with dependent bases.");
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +0000809
Mike Stump1eb44332009-09-09 15:08:12 +0000810 const CXXRecordDecl *Base =
Anders Carlsson584e1df2010-03-11 03:39:12 +0000811 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson200c5c22010-03-11 00:15:35 +0000812
Anders Carlsson584e1df2010-03-11 03:39:12 +0000813 // Check if this is a nearly empty virtual base.
Anders Carlssondae0cb52010-11-25 01:51:53 +0000814 if (I->isVirtual() && Context.isNearlyEmpty(Base)) {
Anders Carlsson584e1df2010-03-11 03:39:12 +0000815 // If it's not an indirect primary base, then we've found our primary
816 // base.
Anders Carlsson3f066522009-09-22 03:02:06 +0000817 if (!IndirectPrimaryBases.count(Base)) {
Anders Carlsson28fdd0a2010-05-26 05:20:58 +0000818 PrimaryBase = Base;
819 PrimaryBaseIsVirtual = true;
Mike Stumpd76264e2009-08-12 21:50:08 +0000820 return;
821 }
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +0000822
Anders Carlsson584e1df2010-03-11 03:39:12 +0000823 // Is this the first nearly empty virtual base?
824 if (!FirstNearlyEmptyVBase)
825 FirstNearlyEmptyVBase = Base;
Mike Stumpd76264e2009-08-12 21:50:08 +0000826 }
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +0000827
Anders Carlsson200c5c22010-03-11 00:15:35 +0000828 SelectPrimaryVBase(Base);
Anders Carlsson28fdd0a2010-05-26 05:20:58 +0000829 if (PrimaryBase)
Zhongxing Xu94ba3802010-02-15 04:28:35 +0000830 return;
Mike Stumpd76264e2009-08-12 21:50:08 +0000831 }
832}
833
Anders Carlsson200c5c22010-03-11 00:15:35 +0000834/// DeterminePrimaryBase - Determine the primary base of the given class.
Anders Carlsson7d0918a2010-05-26 05:58:59 +0000835void RecordLayoutBuilder::DeterminePrimaryBase(const CXXRecordDecl *RD) {
Anders Carlsson200c5c22010-03-11 00:15:35 +0000836 // If the class isn't dynamic, it won't have a primary base.
837 if (!RD->isDynamicClass())
838 return;
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +0000839
Anders Carlsson3f066522009-09-22 03:02:06 +0000840 // Compute all the primary virtual bases for all of our direct and
Mike Stump0880e752009-08-13 23:26:06 +0000841 // indirect bases, and record all their primary virtual base classes.
Anders Carlsson245656e2010-11-24 22:55:48 +0000842 RD->getIndirectPrimaryBases(IndirectPrimaryBases);
Mike Stump0880e752009-08-13 23:26:06 +0000843
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +0000844 // If the record has a dynamic base class, attempt to choose a primary base
845 // class. It is the first (in direct base class order) non-virtual dynamic
Anders Carlsson3f066522009-09-22 03:02:06 +0000846 // base class, if one exists.
Mike Stump6f376332009-08-05 22:37:18 +0000847 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +0000848 e = RD->bases_end(); i != e; ++i) {
Anders Carlssonce2009a2009-11-27 22:05:05 +0000849 // Ignore virtual bases.
850 if (i->isVirtual())
851 continue;
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +0000852
Anders Carlssonce2009a2009-11-27 22:05:05 +0000853 const CXXRecordDecl *Base =
854 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
855
John McCall9da23522011-11-08 04:01:03 +0000856 if (isPossiblePrimaryBase(Base)) {
Anders Carlssonce2009a2009-11-27 22:05:05 +0000857 // We found it.
Anders Carlsson28fdd0a2010-05-26 05:20:58 +0000858 PrimaryBase = Base;
859 PrimaryBaseIsVirtual = false;
Anders Carlssonce2009a2009-11-27 22:05:05 +0000860 return;
Mike Stump6f376332009-08-05 22:37:18 +0000861 }
862 }
863
Eli Friedman97c0aef2011-10-18 00:55:28 +0000864 // The Microsoft ABI doesn't have primary virtual bases.
John McCall9da23522011-11-08 04:01:03 +0000865 if (isMicrosoftCXXABI()) {
Eli Friedman97c0aef2011-10-18 00:55:28 +0000866 assert(!PrimaryBase && "Should not get here with a primary base!");
867 return;
868 }
869
870 // Under the Itanium ABI, if there is no non-virtual primary base class,
871 // try to compute the primary virtual base. The primary virtual base is
872 // the first nearly empty virtual base that is not an indirect primary
873 // virtual base class, if one exists.
Anders Carlsson200c5c22010-03-11 00:15:35 +0000874 if (RD->getNumVBases() != 0) {
875 SelectPrimaryVBase(RD);
Anders Carlsson28fdd0a2010-05-26 05:20:58 +0000876 if (PrimaryBase)
Anders Carlsson200c5c22010-03-11 00:15:35 +0000877 return;
878 }
Mike Stump6f376332009-08-05 22:37:18 +0000879
Eli Friedman97c0aef2011-10-18 00:55:28 +0000880 // Otherwise, it is the first indirect primary base class, if one exists.
Anders Carlsson200c5c22010-03-11 00:15:35 +0000881 if (FirstNearlyEmptyVBase) {
Anders Carlsson28fdd0a2010-05-26 05:20:58 +0000882 PrimaryBase = FirstNearlyEmptyVBase;
883 PrimaryBaseIsVirtual = true;
Mike Stump6f376332009-08-05 22:37:18 +0000884 return;
Anders Carlsson200c5c22010-03-11 00:15:35 +0000885 }
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +0000886
Anders Carlsson28fdd0a2010-05-26 05:20:58 +0000887 assert(!PrimaryBase && "Should not get here with a primary base!");
Mike Stump6f376332009-08-05 22:37:18 +0000888}
889
Anders Carlsson6e264542010-05-29 17:35:14 +0000890BaseSubobjectInfo *
891RecordLayoutBuilder::ComputeBaseSubobjectInfo(const CXXRecordDecl *RD,
892 bool IsVirtual,
893 BaseSubobjectInfo *Derived) {
894 BaseSubobjectInfo *Info;
895
896 if (IsVirtual) {
897 // Check if we already have info about this virtual base.
898 BaseSubobjectInfo *&InfoSlot = VirtualBaseInfo[RD];
899 if (InfoSlot) {
900 assert(InfoSlot->Class == RD && "Wrong class for virtual base info!");
901 return InfoSlot;
902 }
903
904 // We don't, create it.
905 InfoSlot = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
906 Info = InfoSlot;
907 } else {
908 Info = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
909 }
910
911 Info->Class = RD;
912 Info->IsVirtual = IsVirtual;
913 Info->Derived = 0;
914 Info->PrimaryVirtualBaseInfo = 0;
915
916 const CXXRecordDecl *PrimaryVirtualBase = 0;
917 BaseSubobjectInfo *PrimaryVirtualBaseInfo = 0;
918
919 // Check if this base has a primary virtual base.
920 if (RD->getNumVBases()) {
921 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Anders Carlssonc9e814b2010-11-24 23:12:57 +0000922 if (Layout.isPrimaryBaseVirtual()) {
Anders Carlsson6e264542010-05-29 17:35:14 +0000923 // This base does have a primary virtual base.
924 PrimaryVirtualBase = Layout.getPrimaryBase();
925 assert(PrimaryVirtualBase && "Didn't have a primary virtual base!");
926
927 // Now check if we have base subobject info about this primary base.
928 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
929
930 if (PrimaryVirtualBaseInfo) {
931 if (PrimaryVirtualBaseInfo->Derived) {
932 // We did have info about this primary base, and it turns out that it
933 // has already been claimed as a primary virtual base for another
934 // base.
935 PrimaryVirtualBase = 0;
936 } else {
937 // We can claim this base as our primary base.
938 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
939 PrimaryVirtualBaseInfo->Derived = Info;
940 }
941 }
942 }
943 }
944
945 // Now go through all direct bases.
946 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
947 E = RD->bases_end(); I != E; ++I) {
948 bool IsVirtual = I->isVirtual();
949
950 const CXXRecordDecl *BaseDecl =
951 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
952
953 Info->Bases.push_back(ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, Info));
954 }
955
956 if (PrimaryVirtualBase && !PrimaryVirtualBaseInfo) {
957 // Traversing the bases must have created the base info for our primary
958 // virtual base.
959 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
960 assert(PrimaryVirtualBaseInfo &&
961 "Did not create a primary virtual base!");
962
963 // Claim the primary virtual base as our primary virtual base.
964 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
965 PrimaryVirtualBaseInfo->Derived = Info;
966 }
967
968 return Info;
969}
970
971void RecordLayoutBuilder::ComputeBaseSubobjectInfo(const CXXRecordDecl *RD) {
972 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
973 E = RD->bases_end(); I != E; ++I) {
974 bool IsVirtual = I->isVirtual();
975
976 const CXXRecordDecl *BaseDecl =
977 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
978
979 // Compute the base subobject info for this base.
980 BaseSubobjectInfo *Info = ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, 0);
981
982 if (IsVirtual) {
983 // ComputeBaseInfo has already added this base for us.
984 assert(VirtualBaseInfo.count(BaseDecl) &&
985 "Did not add virtual base!");
986 } else {
987 // Add the base info to the map of non-virtual bases.
988 assert(!NonVirtualBaseInfo.count(BaseDecl) &&
989 "Non-virtual base already exists!");
990 NonVirtualBaseInfo.insert(std::make_pair(BaseDecl, Info));
991 }
992 }
993}
994
Anders Carlssone239b9d2010-03-10 22:21:28 +0000995void
Eli Friedman227e4832011-10-21 22:49:56 +0000996RecordLayoutBuilder::EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign) {
Eli Friedman97c0aef2011-10-18 00:55:28 +0000997 CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
998
999 // The maximum field alignment overrides base align.
1000 if (!MaxFieldAlignment.isZero()) {
1001 BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
1002 UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
1003 }
1004
1005 // Round up the current record size to pointer alignment.
Eli Friedman227e4832011-10-21 22:49:56 +00001006 setSize(getSize().RoundUpToAlignment(BaseAlign));
1007 setDataSize(getSize());
Eli Friedman97c0aef2011-10-18 00:55:28 +00001008
1009 // Update the alignment.
1010 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
1011}
1012
1013void
Anders Carlsson7d0918a2010-05-26 05:58:59 +00001014RecordLayoutBuilder::LayoutNonVirtualBases(const CXXRecordDecl *RD) {
Anders Carlsson6e264542010-05-29 17:35:14 +00001015 // Then, determine the primary base class.
Anders Carlsson200c5c22010-03-11 00:15:35 +00001016 DeterminePrimaryBase(RD);
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00001017
Anders Carlsson6e264542010-05-29 17:35:14 +00001018 // Compute base subobject info.
1019 ComputeBaseSubobjectInfo(RD);
1020
Anders Carlsson200c5c22010-03-11 00:15:35 +00001021 // If we have a primary base class, lay it out.
Anders Carlsson28fdd0a2010-05-26 05:20:58 +00001022 if (PrimaryBase) {
1023 if (PrimaryBaseIsVirtual) {
Anders Carlsson6e264542010-05-29 17:35:14 +00001024 // If the primary virtual base was a primary virtual base of some other
1025 // base class we'll have to steal it.
1026 BaseSubobjectInfo *PrimaryBaseInfo = VirtualBaseInfo.lookup(PrimaryBase);
1027 PrimaryBaseInfo->Derived = 0;
1028
Anders Carlsson200c5c22010-03-11 00:15:35 +00001029 // We have a virtual primary base, insert it as an indirect primary base.
Anders Carlsson28fdd0a2010-05-26 05:20:58 +00001030 IndirectPrimaryBases.insert(PrimaryBase);
Anders Carlsson37147ea2010-03-11 05:42:17 +00001031
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00001032 assert(!VisitedVirtualBases.count(PrimaryBase) &&
Anders Carlsson28fdd0a2010-05-26 05:20:58 +00001033 "vbase already visited!");
1034 VisitedVirtualBases.insert(PrimaryBase);
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00001035
Anders Carlsson276b4912010-05-29 17:48:36 +00001036 LayoutVirtualBase(PrimaryBaseInfo);
Anders Carlsson07cebc52010-05-29 17:42:25 +00001037 } else {
1038 BaseSubobjectInfo *PrimaryBaseInfo =
1039 NonVirtualBaseInfo.lookup(PrimaryBase);
1040 assert(PrimaryBaseInfo &&
1041 "Did not find base info for non-virtual primary base!");
1042
1043 LayoutNonVirtualBase(PrimaryBaseInfo);
1044 }
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00001045
John McCall9da23522011-11-08 04:01:03 +00001046 // If this class needs a vtable/vf-table and didn't get one from a
1047 // primary base, add it in now.
1048 } else if (needsVFTable(RD)) {
Eli Friedman97c0aef2011-10-18 00:55:28 +00001049 assert(DataSize == 0 && "Vtable pointer must be at offset zero!");
Eli Friedman97c0aef2011-10-18 00:55:28 +00001050 CharUnits PtrWidth =
1051 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Eli Friedman227e4832011-10-21 22:49:56 +00001052 CharUnits PtrAlign =
1053 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0));
1054 EnsureVTablePointerAlignment(PtrAlign);
John McCall441c6232012-05-01 08:55:32 +00001055 HasOwnVFPtr = true;
Eli Friedman97c0aef2011-10-18 00:55:28 +00001056 setSize(getSize() + PtrWidth);
1057 setDataSize(getSize());
1058 }
1059
John McCall9da23522011-11-08 04:01:03 +00001060 bool HasDirectVirtualBases = false;
1061 bool HasNonVirtualBaseWithVBTable = false;
1062
Anders Carlsson200c5c22010-03-11 00:15:35 +00001063 // Now lay out the non-virtual bases.
1064 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00001065 E = RD->bases_end(); I != E; ++I) {
Anders Carlsson200c5c22010-03-11 00:15:35 +00001066
John McCall9da23522011-11-08 04:01:03 +00001067 // Ignore virtual bases, but remember that we saw one.
1068 if (I->isVirtual()) {
1069 HasDirectVirtualBases = true;
Anders Carlsson200c5c22010-03-11 00:15:35 +00001070 continue;
John McCall9da23522011-11-08 04:01:03 +00001071 }
Anders Carlsson200c5c22010-03-11 00:15:35 +00001072
Anders Carlsson07cebc52010-05-29 17:42:25 +00001073 const CXXRecordDecl *BaseDecl =
John McCall9da23522011-11-08 04:01:03 +00001074 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
Anders Carlsson200c5c22010-03-11 00:15:35 +00001075
John McCall9da23522011-11-08 04:01:03 +00001076 // Remember if this base has virtual bases itself.
1077 if (BaseDecl->getNumVBases())
1078 HasNonVirtualBaseWithVBTable = true;
1079
1080 // Skip the primary base, because we've already laid it out. The
1081 // !PrimaryBaseIsVirtual check is required because we might have a
1082 // non-virtual base of the same type as a primary virtual base.
Anders Carlsson07cebc52010-05-29 17:42:25 +00001083 if (BaseDecl == PrimaryBase && !PrimaryBaseIsVirtual)
Anders Carlsson200c5c22010-03-11 00:15:35 +00001084 continue;
1085
1086 // Lay out the base.
Anders Carlsson07cebc52010-05-29 17:42:25 +00001087 BaseSubobjectInfo *BaseInfo = NonVirtualBaseInfo.lookup(BaseDecl);
1088 assert(BaseInfo && "Did not find base info for non-virtual base!");
1089
1090 LayoutNonVirtualBase(BaseInfo);
Anders Carlssone239b9d2010-03-10 22:21:28 +00001091 }
Eli Friedman97c0aef2011-10-18 00:55:28 +00001092
John McCall9da23522011-11-08 04:01:03 +00001093 // In the MS ABI, add the vb-table pointer if we need one, which is
1094 // whenever we have a virtual base and we can't re-use a vb-table
1095 // pointer from a non-virtual base.
1096 if (isMicrosoftCXXABI() &&
1097 HasDirectVirtualBases && !HasNonVirtualBaseWithVBTable) {
Eli Friedman97c0aef2011-10-18 00:55:28 +00001098 CharUnits PtrWidth =
1099 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Eli Friedman227e4832011-10-21 22:49:56 +00001100 CharUnits PtrAlign =
1101 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0));
John McCall9da23522011-11-08 04:01:03 +00001102
1103 // MSVC potentially over-aligns the vb-table pointer by giving it
1104 // the max alignment of all the non-virtual objects in the class.
1105 // This is completely unnecessary, but we're not here to pass
1106 // judgment.
1107 //
1108 // Note that we've only laid out the non-virtual bases, so on the
1109 // first pass Alignment won't be set correctly here, but if the
1110 // vb-table doesn't end up aligned correctly we'll come through
1111 // and redo the layout from scratch with the right alignment.
1112 //
1113 // TODO: Instead of doing this, just lay out the fields as if the
1114 // vb-table were at offset zero, then retroactively bump the field
1115 // offsets up.
Eli Friedman227e4832011-10-21 22:49:56 +00001116 PtrAlign = std::max(PtrAlign, Alignment);
John McCall9da23522011-11-08 04:01:03 +00001117
1118 EnsureVTablePointerAlignment(PtrAlign);
1119 VBPtrOffset = getSize();
1120 setSize(getSize() + PtrWidth);
1121 setDataSize(getSize());
Eli Friedman97c0aef2011-10-18 00:55:28 +00001122 }
Anders Carlssone239b9d2010-03-10 22:21:28 +00001123}
1124
Anders Carlsson07cebc52010-05-29 17:42:25 +00001125void RecordLayoutBuilder::LayoutNonVirtualBase(const BaseSubobjectInfo *Base) {
Anders Carlssone3bdbee2010-03-10 22:26:24 +00001126 // Layout the base.
Anders Carlssona2311512010-10-31 22:20:42 +00001127 CharUnits Offset = LayoutBase(Base);
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00001128
Anders Carlssone3bdbee2010-03-10 22:26:24 +00001129 // Add its base class offset.
Anders Carlsson07cebc52010-05-29 17:42:25 +00001130 assert(!Bases.count(Base->Class) && "base offset already exists!");
Anders Carlssona2311512010-10-31 22:20:42 +00001131 Bases.insert(std::make_pair(Base->Class, Offset));
Anders Carlsson3cd09cc2010-05-29 19:44:50 +00001132
1133 AddPrimaryVirtualBaseOffsets(Base, Offset);
Anders Carlssone239b9d2010-03-10 22:21:28 +00001134}
Mike Stump968db332009-11-05 04:02:15 +00001135
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00001136void
Anders Carlsson3cd09cc2010-05-29 19:44:50 +00001137RecordLayoutBuilder::AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
Anders Carlssona2311512010-10-31 22:20:42 +00001138 CharUnits Offset) {
Anders Carlsson3cd09cc2010-05-29 19:44:50 +00001139 // This base isn't interesting, it has no virtual bases.
1140 if (!Info->Class->getNumVBases())
1141 return;
1142
1143 // First, check if we have a virtual primary base to add offsets for.
1144 if (Info->PrimaryVirtualBaseInfo) {
1145 assert(Info->PrimaryVirtualBaseInfo->IsVirtual &&
1146 "Primary virtual base is not virtual!");
1147 if (Info->PrimaryVirtualBaseInfo->Derived == Info) {
1148 // Add the offset.
1149 assert(!VBases.count(Info->PrimaryVirtualBaseInfo->Class) &&
1150 "primary vbase offset already exists!");
1151 VBases.insert(std::make_pair(Info->PrimaryVirtualBaseInfo->Class,
John McCall441c6232012-05-01 08:55:32 +00001152 ASTRecordLayout::VBaseInfo(Offset, false)));
Anders Carlsson97913572010-04-15 16:12:58 +00001153
Anders Carlsson3cd09cc2010-05-29 19:44:50 +00001154 // Traverse the primary virtual base.
1155 AddPrimaryVirtualBaseOffsets(Info->PrimaryVirtualBaseInfo, Offset);
1156 }
Anders Carlsson97913572010-04-15 16:12:58 +00001157 }
1158
Anders Carlsson3cd09cc2010-05-29 19:44:50 +00001159 // Now go through all direct non-virtual bases.
1160 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
1161 for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) {
1162 const BaseSubobjectInfo *Base = Info->Bases[I];
1163 if (Base->IsVirtual)
Anders Carlsson97913572010-04-15 16:12:58 +00001164 continue;
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00001165
Anders Carlsson6a356742010-11-01 00:21:58 +00001166 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
Anders Carlsson3cd09cc2010-05-29 19:44:50 +00001167 AddPrimaryVirtualBaseOffsets(Base, BaseOffset);
Anders Carlsson97913572010-04-15 16:12:58 +00001168 }
1169}
1170
John McCall9da23522011-11-08 04:01:03 +00001171/// needsVFTable - Return true if this class needs a vtable or vf-table
1172/// when laid out as a base class. These are treated the same because
1173/// they're both always laid out at offset zero.
1174///
1175/// This function assumes that the class has no primary base.
1176bool RecordLayoutBuilder::needsVFTable(const CXXRecordDecl *RD) const {
1177 assert(!PrimaryBase);
1178
1179 // In the Itanium ABI, every dynamic class needs a vtable: even if
1180 // this class has no virtual functions as a base class (i.e. it's
1181 // non-polymorphic or only has virtual functions from virtual
1182 // bases),x it still needs a vtable to locate its virtual bases.
1183 if (!isMicrosoftCXXABI())
1184 return RD->isDynamicClass();
1185
1186 // In the MS ABI, we need a vfptr if the class has virtual functions
1187 // other than those declared by its virtual bases. The AST doesn't
1188 // tell us that directly, and checking manually for virtual
1189 // functions that aren't overrides is expensive, but there are
1190 // some important shortcuts:
1191
1192 // - Non-polymorphic classes have no virtual functions at all.
1193 if (!RD->isPolymorphic()) return false;
1194
1195 // - Polymorphic classes with no virtual bases must either declare
1196 // virtual functions directly or inherit them, but in the latter
1197 // case we would have a primary base.
1198 if (RD->getNumVBases() == 0) return true;
1199
1200 return hasNewVirtualFunction(RD);
1201}
1202
John McCall441c6232012-05-01 08:55:32 +00001203/// Does the given class inherit non-virtually from any of the classes
1204/// in the given set?
1205static bool hasNonVirtualBaseInSet(const CXXRecordDecl *RD,
1206 const ClassSetTy &set) {
1207 for (CXXRecordDecl::base_class_const_iterator
1208 I = RD->bases_begin(), E = RD->bases_end(); I != E; ++I) {
1209 // Ignore virtual links.
1210 if (I->isVirtual()) continue;
1211
1212 // Check whether the set contains the base.
1213 const CXXRecordDecl *base = I->getType()->getAsCXXRecordDecl();
1214 if (set.count(base))
1215 return true;
1216
1217 // Otherwise, recurse and propagate.
1218 if (hasNonVirtualBaseInSet(base, set))
1219 return true;
1220 }
1221
1222 return false;
1223}
1224
1225/// Does the given method (B::foo()) already override a method (A::foo())
1226/// such that A requires a vtordisp in B? If so, we don't need to add a
1227/// new vtordisp for B in a yet-more-derived class C providing C::foo().
1228static bool overridesMethodRequiringVtorDisp(const ASTContext &Context,
1229 const CXXMethodDecl *M) {
1230 CXXMethodDecl::method_iterator
1231 I = M->begin_overridden_methods(), E = M->end_overridden_methods();
1232 if (I == E) return false;
1233
1234 const ASTRecordLayout::VBaseOffsetsMapTy &offsets =
1235 Context.getASTRecordLayout(M->getParent()).getVBaseOffsetsMap();
1236 do {
1237 const CXXMethodDecl *overridden = *I;
1238
1239 // If the overridden method's class isn't recognized as a virtual
1240 // base in the derived class, ignore it.
1241 ASTRecordLayout::VBaseOffsetsMapTy::const_iterator
1242 it = offsets.find(overridden->getParent());
1243 if (it == offsets.end()) continue;
1244
1245 // Otherwise, check if the overridden method's class needs a vtordisp.
1246 if (it->second.hasVtorDisp()) return true;
1247
1248 } while (++I != E);
1249 return false;
1250}
1251
1252/// In the Microsoft ABI, decide which of the virtual bases require a
1253/// vtordisp field.
1254void RecordLayoutBuilder::computeVtordisps(const CXXRecordDecl *RD,
1255 ClassSetTy &vtordispVBases) {
1256 // Bail out if we have no virtual bases.
1257 assert(RD->getNumVBases());
1258
1259 // Build up the set of virtual bases that we haven't decided yet.
1260 ClassSetTy undecidedVBases;
1261 for (CXXRecordDecl::base_class_const_iterator
1262 I = RD->vbases_begin(), E = RD->vbases_end(); I != E; ++I) {
1263 const CXXRecordDecl *vbase = I->getType()->getAsCXXRecordDecl();
1264 undecidedVBases.insert(vbase);
1265 }
1266 assert(!undecidedVBases.empty());
1267
1268 // A virtual base requires a vtordisp field in a derived class if it
1269 // requires a vtordisp field in a base class. Walk all the direct
1270 // bases and collect this information.
1271 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1272 E = RD->bases_end(); I != E; ++I) {
1273 const CXXRecordDecl *base = I->getType()->getAsCXXRecordDecl();
1274 const ASTRecordLayout &baseLayout = Context.getASTRecordLayout(base);
1275
1276 // Iterate over the set of virtual bases provided by this class.
1277 for (ASTRecordLayout::VBaseOffsetsMapTy::const_iterator
1278 VI = baseLayout.getVBaseOffsetsMap().begin(),
1279 VE = baseLayout.getVBaseOffsetsMap().end(); VI != VE; ++VI) {
1280 // If it doesn't need a vtordisp in this base, ignore it.
1281 if (!VI->second.hasVtorDisp()) continue;
1282
1283 // If we've already seen it and decided it needs a vtordisp, ignore it.
1284 if (!undecidedVBases.erase(VI->first))
1285 continue;
1286
1287 // Add it.
1288 vtordispVBases.insert(VI->first);
1289
1290 // Quit as soon as we've decided everything.
1291 if (undecidedVBases.empty())
1292 return;
1293 }
1294 }
1295
1296 // Okay, we have virtual bases that we haven't yet decided about. A
1297 // virtual base requires a vtordisp if any the non-destructor
1298 // virtual methods declared in this class directly override a method
1299 // provided by that virtual base. (If so, we need to emit a thunk
1300 // for that method, to be used in the construction vftable, which
1301 // applies an additional 'vtordisp' this-adjustment.)
1302
1303 // Collect the set of bases directly overridden by any method in this class.
1304 // It's possible that some of these classes won't be virtual bases, or won't be
1305 // provided by virtual bases, or won't be virtual bases in the overridden
1306 // instance but are virtual bases elsewhere. Only the last matters for what
1307 // we're doing, and we can ignore those: if we don't directly override
1308 // a method provided by a virtual copy of a base class, but we do directly
1309 // override a method provided by a non-virtual copy of that base class,
1310 // then we must indirectly override the method provided by the virtual base,
1311 // and so we should already have collected it in the loop above.
1312 ClassSetTy overriddenBases;
1313 for (CXXRecordDecl::method_iterator
1314 M = RD->method_begin(), E = RD->method_end(); M != E; ++M) {
1315 // Ignore non-virtual methods and destructors.
1316 if (isa<CXXDestructorDecl>(*M) || !M->isVirtual())
1317 continue;
1318
1319 for (CXXMethodDecl::method_iterator I = M->begin_overridden_methods(),
1320 E = M->end_overridden_methods(); I != E; ++I) {
1321 const CXXMethodDecl *overriddenMethod = (*I);
1322
1323 // Ignore methods that override methods from vbases that require
1324 // require vtordisps.
1325 if (overridesMethodRequiringVtorDisp(Context, overriddenMethod))
1326 continue;
1327
1328 // As an optimization, check immediately whether we're overriding
1329 // something from the undecided set.
1330 const CXXRecordDecl *overriddenBase = overriddenMethod->getParent();
1331 if (undecidedVBases.erase(overriddenBase)) {
1332 vtordispVBases.insert(overriddenBase);
1333 if (undecidedVBases.empty()) return;
1334
1335 // We can't 'continue;' here because one of our undecided
1336 // vbases might non-virtually inherit from this base.
1337 // Consider:
1338 // struct A { virtual void foo(); };
1339 // struct B : A {};
1340 // struct C : virtual A, virtual B { virtual void foo(); };
1341 // We need a vtordisp for B here.
1342 }
1343
1344 // Otherwise, just collect it.
1345 overriddenBases.insert(overriddenBase);
1346 }
1347 }
1348
1349 // Walk the undecided v-bases and check whether they (non-virtually)
1350 // provide any of the overridden bases. We don't need to consider
1351 // virtual links because the vtordisp inheres to the layout
1352 // subobject containing the base.
1353 for (ClassSetTy::const_iterator
1354 I = undecidedVBases.begin(), E = undecidedVBases.end(); I != E; ++I) {
1355 if (hasNonVirtualBaseInSet(*I, overriddenBases))
1356 vtordispVBases.insert(*I);
1357 }
1358}
1359
John McCall9da23522011-11-08 04:01:03 +00001360/// hasNewVirtualFunction - Does the given polymorphic class declare a
1361/// virtual function that does not override a method from any of its
1362/// base classes?
Eli Friedman2fe36362011-09-27 19:12:27 +00001363bool
John McCall441c6232012-05-01 08:55:32 +00001364RecordLayoutBuilder::hasNewVirtualFunction(const CXXRecordDecl *RD,
1365 bool IgnoreDestructor) const {
John McCall9da23522011-11-08 04:01:03 +00001366 if (!RD->getNumBases())
1367 return true;
1368
Eli Friedman2fe36362011-09-27 19:12:27 +00001369 for (CXXRecordDecl::method_iterator method = RD->method_begin();
1370 method != RD->method_end();
1371 ++method) {
John McCall441c6232012-05-01 08:55:32 +00001372 if (method->isVirtual() && !method->size_overridden_methods() &&
1373 !(IgnoreDestructor && method->getKind() == Decl::CXXDestructor)) {
Eli Friedman2fe36362011-09-27 19:12:27 +00001374 return true;
1375 }
1376 }
1377 return false;
1378}
1379
John McCall9da23522011-11-08 04:01:03 +00001380/// isPossiblePrimaryBase - Is the given base class an acceptable
1381/// primary base class?
Eli Friedman97c0aef2011-10-18 00:55:28 +00001382bool
John McCall441c6232012-05-01 08:55:32 +00001383RecordLayoutBuilder::isPossiblePrimaryBase(const CXXRecordDecl *base) const {
John McCall9da23522011-11-08 04:01:03 +00001384 // In the Itanium ABI, a class can be a primary base class if it has
1385 // a vtable for any reason.
1386 if (!isMicrosoftCXXABI())
John McCall441c6232012-05-01 08:55:32 +00001387 return base->isDynamicClass();
John McCall9da23522011-11-08 04:01:03 +00001388
1389 // In the MS ABI, a class can only be a primary base class if it
1390 // provides a vf-table at a static offset. That means it has to be
1391 // non-virtual base. The existence of a separate vb-table means
1392 // that it's possible to get virtual functions only from a virtual
1393 // base, which we have to guard against.
1394
1395 // First off, it has to have virtual functions.
John McCall441c6232012-05-01 08:55:32 +00001396 if (!base->isPolymorphic()) return false;
John McCall9da23522011-11-08 04:01:03 +00001397
John McCall441c6232012-05-01 08:55:32 +00001398 // If it has no virtual bases, then the vfptr must be at a static offset.
1399 if (!base->getNumVBases()) return true;
1400
1401 // Otherwise, the necessary information is cached in the layout.
1402 const ASTRecordLayout &layout = Context.getASTRecordLayout(base);
John McCall9da23522011-11-08 04:01:03 +00001403
John McCall441c6232012-05-01 08:55:32 +00001404 // If the base has its own vfptr, it can be a primary base.
1405 if (layout.hasOwnVFPtr()) return true;
1406
1407 // If the base has a primary base class, then it can be a primary base.
1408 if (layout.getPrimaryBase()) return true;
1409
1410 // Otherwise it can't.
1411 return false;
Eli Friedman2fe36362011-09-27 19:12:27 +00001412}
1413
Anders Carlsson97913572010-04-15 16:12:58 +00001414void
Anders Carlsson7d0918a2010-05-26 05:58:59 +00001415RecordLayoutBuilder::LayoutVirtualBases(const CXXRecordDecl *RD,
Anders Carlsson97913572010-04-15 16:12:58 +00001416 const CXXRecordDecl *MostDerivedClass) {
Anders Carlsson88f42962010-03-11 04:33:54 +00001417 const CXXRecordDecl *PrimaryBase;
Anders Carlssonbdda6c12010-04-10 18:42:27 +00001418 bool PrimaryBaseIsVirtual;
Anders Carlsson37147ea2010-03-11 05:42:17 +00001419
Anders Carlssonbdda6c12010-04-10 18:42:27 +00001420 if (MostDerivedClass == RD) {
Anders Carlsson28fdd0a2010-05-26 05:20:58 +00001421 PrimaryBase = this->PrimaryBase;
1422 PrimaryBaseIsVirtual = this->PrimaryBaseIsVirtual;
Anders Carlssonbdda6c12010-04-10 18:42:27 +00001423 } else {
Anders Carlsson0f0e9b02010-04-16 15:07:51 +00001424 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Anders Carlsson88f42962010-03-11 04:33:54 +00001425 PrimaryBase = Layout.getPrimaryBase();
Anders Carlssonc9e814b2010-11-24 23:12:57 +00001426 PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
Anders Carlssonbdda6c12010-04-10 18:42:27 +00001427 }
1428
Anders Carlsson622e2472010-03-11 04:24:02 +00001429 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1430 E = RD->bases_end(); I != E; ++I) {
1431 assert(!I->getType()->isDependentType() &&
Sebastian Redl9994a342009-10-25 17:03:50 +00001432 "Cannot layout class with dependent bases.");
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00001433
Anders Carlsson276b4912010-05-29 17:48:36 +00001434 const CXXRecordDecl *BaseDecl =
John McCall9da23522011-11-08 04:01:03 +00001435 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
Anders Carlsson622e2472010-03-11 04:24:02 +00001436
1437 if (I->isVirtual()) {
Anders Carlsson276b4912010-05-29 17:48:36 +00001438 if (PrimaryBase != BaseDecl || !PrimaryBaseIsVirtual) {
1439 bool IndirectPrimaryBase = IndirectPrimaryBases.count(BaseDecl);
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00001440
Anders Carlssonbdda6c12010-04-10 18:42:27 +00001441 // Only lay out the virtual base if it's not an indirect primary base.
1442 if (!IndirectPrimaryBase) {
1443 // Only visit virtual bases once.
Anders Carlsson276b4912010-05-29 17:48:36 +00001444 if (!VisitedVirtualBases.insert(BaseDecl))
Anders Carlssonbdda6c12010-04-10 18:42:27 +00001445 continue;
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00001446
Anders Carlsson276b4912010-05-29 17:48:36 +00001447 const BaseSubobjectInfo *BaseInfo = VirtualBaseInfo.lookup(BaseDecl);
1448 assert(BaseInfo && "Did not find virtual base info!");
1449 LayoutVirtualBase(BaseInfo);
Anders Carlsson147b5dd2010-03-11 04:10:39 +00001450 }
Mike Stump968db332009-11-05 04:02:15 +00001451 }
Mike Stump4ef98092009-08-13 22:53:07 +00001452 }
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00001453
Anders Carlsson276b4912010-05-29 17:48:36 +00001454 if (!BaseDecl->getNumVBases()) {
Anders Carlsson622e2472010-03-11 04:24:02 +00001455 // This base isn't interesting since it doesn't have any virtual bases.
1456 continue;
Mike Stumpfe3010d2009-08-16 19:04:13 +00001457 }
Anders Carlsson622e2472010-03-11 04:24:02 +00001458
Anders Carlsson276b4912010-05-29 17:48:36 +00001459 LayoutVirtualBases(BaseDecl, MostDerivedClass);
Mike Stumpeb19fa92009-08-06 13:41:24 +00001460 }
1461}
1462
John McCall9da23522011-11-08 04:01:03 +00001463void RecordLayoutBuilder::MSLayoutVirtualBases(const CXXRecordDecl *RD) {
John McCall9da23522011-11-08 04:01:03 +00001464 if (!RD->getNumVBases())
1465 return;
1466
John McCall441c6232012-05-01 08:55:32 +00001467 ClassSetTy VtordispVBases;
1468 computeVtordisps(RD, VtordispVBases);
1469
John McCall9da23522011-11-08 04:01:03 +00001470 // This is substantially simplified because there are no virtual
1471 // primary bases.
1472 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
1473 E = RD->vbases_end(); I != E; ++I) {
1474 const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
1475 const BaseSubobjectInfo *BaseInfo = VirtualBaseInfo.lookup(BaseDecl);
1476 assert(BaseInfo && "Did not find virtual base info!");
John McCall441c6232012-05-01 08:55:32 +00001477
1478 // If this base requires a vtordisp, add enough space for an int field.
1479 // This is apparently always 32-bits, even on x64.
1480 bool vtordispNeeded = false;
1481 if (VtordispVBases.count(BaseDecl)) {
1482 CharUnits IntSize =
1483 CharUnits::fromQuantity(Context.getTargetInfo().getIntWidth() / 8);
1484
1485 setSize(getSize() + IntSize);
1486 setDataSize(getSize());
1487 vtordispNeeded = true;
1488 }
1489
1490 LayoutVirtualBase(BaseInfo, vtordispNeeded);
John McCall9da23522011-11-08 04:01:03 +00001491 }
1492}
1493
John McCall441c6232012-05-01 08:55:32 +00001494void RecordLayoutBuilder::LayoutVirtualBase(const BaseSubobjectInfo *Base,
1495 bool IsVtordispNeed) {
Anders Carlsson3cd09cc2010-05-29 19:44:50 +00001496 assert(!Base->Derived && "Trying to lay out a primary virtual base!");
1497
Anders Carlssone3bdbee2010-03-10 22:26:24 +00001498 // Layout the base.
Anders Carlssona2311512010-10-31 22:20:42 +00001499 CharUnits Offset = LayoutBase(Base);
Anders Carlssone3bdbee2010-03-10 22:26:24 +00001500
1501 // Add its base class offset.
Anders Carlsson276b4912010-05-29 17:48:36 +00001502 assert(!VBases.count(Base->Class) && "vbase offset already exists!");
John McCall441c6232012-05-01 08:55:32 +00001503 VBases.insert(std::make_pair(Base->Class,
1504 ASTRecordLayout::VBaseInfo(Offset, IsVtordispNeed)));
1505
1506 if (!isMicrosoftCXXABI())
1507 AddPrimaryVirtualBaseOffsets(Base, Offset);
Anders Carlssone239b9d2010-03-10 22:21:28 +00001508}
1509
Anders Carlssona2311512010-10-31 22:20:42 +00001510CharUnits RecordLayoutBuilder::LayoutBase(const BaseSubobjectInfo *Base) {
Anders Carlssonb1d880b2010-05-29 20:47:33 +00001511 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base->Class);
Anders Carlssone239b9d2010-03-10 22:21:28 +00001512
Douglas Gregor453dbcb2012-01-26 07:55:45 +00001513
1514 CharUnits Offset;
1515
1516 // Query the external layout to see if it provides an offset.
1517 bool HasExternalLayout = false;
1518 if (ExternalLayout) {
1519 llvm::DenseMap<const CXXRecordDecl *, CharUnits>::iterator Known;
1520 if (Base->IsVirtual) {
1521 Known = ExternalVirtualBaseOffsets.find(Base->Class);
1522 if (Known != ExternalVirtualBaseOffsets.end()) {
1523 Offset = Known->second;
1524 HasExternalLayout = true;
1525 }
1526 } else {
1527 Known = ExternalBaseOffsets.find(Base->Class);
1528 if (Known != ExternalBaseOffsets.end()) {
1529 Offset = Known->second;
1530 HasExternalLayout = true;
1531 }
1532 }
1533 }
1534
Anders Carlssone239b9d2010-03-10 22:21:28 +00001535 // If we have an empty base class, try to place it at offset 0.
Anders Carlssonb1d880b2010-05-29 20:47:33 +00001536 if (Base->Class->isEmpty() &&
Douglas Gregor453dbcb2012-01-26 07:55:45 +00001537 (!HasExternalLayout || Offset == CharUnits::Zero()) &&
Anders Carlssona3d43802010-10-31 22:13:23 +00001538 EmptySubobjects->CanPlaceBaseAtOffset(Base, CharUnits::Zero())) {
Ken Dyckf079b732011-02-28 02:01:38 +00001539 setSize(std::max(getSize(), Layout.getSize()));
Anders Carlssone239b9d2010-03-10 22:21:28 +00001540
Anders Carlssona2311512010-10-31 22:20:42 +00001541 return CharUnits::Zero();
Anders Carlssone239b9d2010-03-10 22:21:28 +00001542 }
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00001543
Ken Dyck3263e092011-02-19 18:58:07 +00001544 CharUnits UnpackedBaseAlign = Layout.getNonVirtualAlign();
1545 CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
Argyrios Kyrtzidis43ddd9f2010-12-09 00:35:20 +00001546
1547 // The maximum field alignment overrides base align.
Ken Dyck834945c2011-02-17 01:49:42 +00001548 if (!MaxFieldAlignment.isZero()) {
Ken Dyck3263e092011-02-19 18:58:07 +00001549 BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
1550 UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
Argyrios Kyrtzidis43ddd9f2010-12-09 00:35:20 +00001551 }
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00001552
Douglas Gregor453dbcb2012-01-26 07:55:45 +00001553 if (!HasExternalLayout) {
1554 // Round up the current record size to the base's alignment boundary.
1555 Offset = getDataSize().RoundUpToAlignment(BaseAlign);
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00001556
Douglas Gregor453dbcb2012-01-26 07:55:45 +00001557 // Try to place the base.
1558 while (!EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset))
1559 Offset += BaseAlign;
1560 } else {
1561 bool Allowed = EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset);
1562 (void)Allowed;
1563 assert(Allowed && "Base subobject externally placed at overlapping offset");
1564 }
1565
Anders Carlssonb1d880b2010-05-29 20:47:33 +00001566 if (!Base->Class->isEmpty()) {
Anders Carlssone239b9d2010-03-10 22:21:28 +00001567 // Update the data size.
Ken Dyckf079b732011-02-28 02:01:38 +00001568 setDataSize(Offset + Layout.getNonVirtualSize());
Anders Carlssone239b9d2010-03-10 22:21:28 +00001569
Ken Dyckf079b732011-02-28 02:01:38 +00001570 setSize(std::max(getSize(), getDataSize()));
Anders Carlssone239b9d2010-03-10 22:21:28 +00001571 } else
Ken Dyckf079b732011-02-28 02:01:38 +00001572 setSize(std::max(getSize(), Offset + Layout.getSize()));
Anders Carlssone239b9d2010-03-10 22:21:28 +00001573
1574 // Remember max struct/class alignment.
Argyrios Kyrtzidis43ddd9f2010-12-09 00:35:20 +00001575 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
Anders Carlssone239b9d2010-03-10 22:21:28 +00001576
Ken Dyckf079b732011-02-28 02:01:38 +00001577 return Offset;
Anders Carlssone239b9d2010-03-10 22:21:28 +00001578}
1579
Daniel Dunbarc6082fe2010-05-27 05:45:51 +00001580void RecordLayoutBuilder::InitializeLayout(const Decl *D) {
1581 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
1582 IsUnion = RD->isUnion();
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00001583
Anders Carlssona5dd7222009-08-08 19:38:24 +00001584 Packed = D->hasAttr<PackedAttr>();
Fariborz Jahanian62055b02011-04-26 23:52:16 +00001585
1586 IsMsStruct = D->hasAttr<MsStructAttr>();
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00001587
Daniel Dunbar88934e82011-10-05 21:04:55 +00001588 // Honor the default struct packing maximum alignment flag.
David Blaikie4e4d0842012-03-11 07:00:24 +00001589 if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct) {
Daniel Dunbar88934e82011-10-05 21:04:55 +00001590 MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
1591 }
1592
Daniel Dunbarc6082fe2010-05-27 05:45:51 +00001593 // mac68k alignment supersedes maximum field alignment and attribute aligned,
1594 // and forces all structures to have 2-byte alignment. The IBM docs on it
1595 // allude to additional (more complicated) semantics, especially with regard
1596 // to bit-fields, but gcc appears not to follow that.
1597 if (D->hasAttr<AlignMac68kAttr>()) {
1598 IsMac68kAlign = true;
Ken Dyck834945c2011-02-17 01:49:42 +00001599 MaxFieldAlignment = CharUnits::fromQuantity(2);
Ken Dyckea7f6c22011-02-16 02:05:21 +00001600 Alignment = CharUnits::fromQuantity(2);
Daniel Dunbarc6082fe2010-05-27 05:45:51 +00001601 } else {
1602 if (const MaxFieldAlignmentAttr *MFAA = D->getAttr<MaxFieldAlignmentAttr>())
Ken Dyck834945c2011-02-17 01:49:42 +00001603 MaxFieldAlignment = Context.toCharUnitsFromBits(MFAA->getAlignment());
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00001604
Sean Huntcf807c42010-08-18 23:23:40 +00001605 if (unsigned MaxAlign = D->getMaxAlignment())
Ken Dyck3263e092011-02-19 18:58:07 +00001606 UpdateAlignment(Context.toCharUnitsFromBits(MaxAlign));
Daniel Dunbarc6082fe2010-05-27 05:45:51 +00001607 }
Douglas Gregor453dbcb2012-01-26 07:55:45 +00001608
1609 // If there is an external AST source, ask it for the various offsets.
1610 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
1611 if (ExternalASTSource *External = Context.getExternalSource()) {
1612 ExternalLayout = External->layoutRecordType(RD,
1613 ExternalSize,
1614 ExternalAlign,
1615 ExternalFieldOffsets,
1616 ExternalBaseOffsets,
1617 ExternalVirtualBaseOffsets);
1618
1619 // Update based on external alignment.
1620 if (ExternalLayout) {
Douglas Gregor394f7b62012-01-28 00:53:29 +00001621 if (ExternalAlign > 0) {
1622 Alignment = Context.toCharUnitsFromBits(ExternalAlign);
1623 UnpackedAlignment = Alignment;
1624 } else {
1625 // The external source didn't have alignment information; infer it.
1626 InferAlignment = true;
1627 }
Douglas Gregor453dbcb2012-01-26 07:55:45 +00001628 }
1629 }
Anders Carlssonc6cab682010-05-26 15:10:00 +00001630}
Anders Carlsson74cbe222009-07-19 00:18:47 +00001631
Anders Carlssonc6cab682010-05-26 15:10:00 +00001632void RecordLayoutBuilder::Layout(const RecordDecl *D) {
1633 InitializeLayout(D);
Anders Carlssona2df41c2009-07-18 21:48:39 +00001634 LayoutFields(D);
Mike Stump1eb44332009-09-09 15:08:12 +00001635
Anders Carlssonbda4c102009-07-18 20:20:21 +00001636 // Finally, round the size of the total struct up to the alignment of the
1637 // struct itself.
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00001638 FinishLayout(D);
Anders Carlssonc6cab682010-05-26 15:10:00 +00001639}
1640
1641void RecordLayoutBuilder::Layout(const CXXRecordDecl *RD) {
1642 InitializeLayout(RD);
1643
Anders Carlssonc6cab682010-05-26 15:10:00 +00001644 // Lay out the vtable and the non-virtual bases.
1645 LayoutNonVirtualBases(RD);
1646
1647 LayoutFields(RD);
1648
Ken Dyck90ce2db2011-03-10 01:53:59 +00001649 NonVirtualSize = Context.toCharUnitsFromBits(
1650 llvm::RoundUpToAlignment(getSizeInBits(),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001651 Context.getTargetInfo().getCharAlign()));
Ken Dyckea7f6c22011-02-16 02:05:21 +00001652 NonVirtualAlignment = Alignment;
Anders Carlssonc6cab682010-05-26 15:10:00 +00001653
John McCall441c6232012-05-01 08:55:32 +00001654 if (isMicrosoftCXXABI()) {
1655 if (NonVirtualSize != NonVirtualSize.RoundUpToAlignment(Alignment)) {
John McCall9da23522011-11-08 04:01:03 +00001656 CharUnits AlignMember =
1657 NonVirtualSize.RoundUpToAlignment(Alignment) - NonVirtualSize;
Anders Carlssonc6cab682010-05-26 15:10:00 +00001658
John McCall9da23522011-11-08 04:01:03 +00001659 setSize(getSize() + AlignMember);
1660 setDataSize(getSize());
Anders Carlssonc6cab682010-05-26 15:10:00 +00001661
John McCall9da23522011-11-08 04:01:03 +00001662 NonVirtualSize = Context.toCharUnitsFromBits(
1663 llvm::RoundUpToAlignment(getSizeInBits(),
1664 Context.getTargetInfo().getCharAlign()));
John McCall441c6232012-05-01 08:55:32 +00001665 }
John McCall9da23522011-11-08 04:01:03 +00001666
1667 MSLayoutVirtualBases(RD);
John McCall9da23522011-11-08 04:01:03 +00001668 } else {
1669 // Lay out the virtual bases and add the primary virtual base offsets.
1670 LayoutVirtualBases(RD, RD);
1671 }
1672
1673 // Finally, round the size of the total struct up to the alignment
Eli Friedman901dd662011-12-01 00:37:01 +00001674 // of the struct itself.
1675 FinishLayout(RD);
Anders Carlssonc6cab682010-05-26 15:10:00 +00001676
Anders Carlssona1e87162010-04-10 21:24:48 +00001677#ifndef NDEBUG
Anders Carlssonc6cab682010-05-26 15:10:00 +00001678 // Check that we have base offsets for all bases.
1679 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1680 E = RD->bases_end(); I != E; ++I) {
1681 if (I->isVirtual())
1682 continue;
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00001683
Anders Carlssonc6cab682010-05-26 15:10:00 +00001684 const CXXRecordDecl *BaseDecl =
1685 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1686
1687 assert(Bases.count(BaseDecl) && "Did not find base offset!");
1688 }
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00001689
Anders Carlssonc6cab682010-05-26 15:10:00 +00001690 // And all virtual bases.
1691 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
1692 E = RD->vbases_end(); I != E; ++I) {
1693 const CXXRecordDecl *BaseDecl =
1694 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00001695
Anders Carlssonc6cab682010-05-26 15:10:00 +00001696 assert(VBases.count(BaseDecl) && "Did not find base offset!");
Anders Carlssona1e87162010-04-10 21:24:48 +00001697 }
1698#endif
Anders Carlssonbda4c102009-07-18 20:20:21 +00001699}
1700
Anders Carlsson7d0918a2010-05-26 05:58:59 +00001701void RecordLayoutBuilder::Layout(const ObjCInterfaceDecl *D) {
Anders Carlsson93fab9d2009-07-18 20:50:59 +00001702 if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
Anders Carlsson0f0e9b02010-04-16 15:07:51 +00001703 const ASTRecordLayout &SL = Context.getASTObjCInterfaceLayout(SD);
Anders Carlsson93fab9d2009-07-18 20:50:59 +00001704
Ken Dyck3263e092011-02-19 18:58:07 +00001705 UpdateAlignment(SL.getAlignment());
Mike Stump1eb44332009-09-09 15:08:12 +00001706
Anders Carlsson93fab9d2009-07-18 20:50:59 +00001707 // We start laying out ivars not at the end of the superclass
1708 // structure, but at the next byte following the last field.
Ken Dycka0c21c42011-02-24 01:13:28 +00001709 setSize(SL.getDataSize());
Ken Dyckf079b732011-02-28 02:01:38 +00001710 setDataSize(getSize());
Anders Carlsson93fab9d2009-07-18 20:50:59 +00001711 }
Mike Stump1eb44332009-09-09 15:08:12 +00001712
Daniel Dunbarc6082fe2010-05-27 05:45:51 +00001713 InitializeLayout(D);
Anders Carlsson93fab9d2009-07-18 20:50:59 +00001714 // Layout each ivar sequentially.
Jordy Rosedb8264e2011-07-22 02:08:32 +00001715 for (const ObjCIvarDecl *IVD = D->all_declared_ivar_begin(); IVD;
1716 IVD = IVD->getNextIvar())
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001717 LayoutField(IVD);
Mike Stump1eb44332009-09-09 15:08:12 +00001718
Anders Carlsson93fab9d2009-07-18 20:50:59 +00001719 // Finally, round the size of the total struct up to the alignment of the
1720 // struct itself.
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00001721 FinishLayout(D);
Anders Carlsson93fab9d2009-07-18 20:50:59 +00001722}
1723
Anders Carlsson7d0918a2010-05-26 05:58:59 +00001724void RecordLayoutBuilder::LayoutFields(const RecordDecl *D) {
Anders Carlssona2df41c2009-07-18 21:48:39 +00001725 // Layout each field, for now, just sequentially, respecting alignment. In
1726 // the future, this will need to be tweakable by targets.
Fariborz Jahanian62055b02011-04-26 23:52:16 +00001727 const FieldDecl *LastFD = 0;
Fariborz Jahanian855a8e72011-05-03 20:21:04 +00001728 ZeroLengthBitfield = 0;
Fariborz Jahanian6ec50ad2011-05-11 16:58:31 +00001729 unsigned RemainingInAlignment = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001730 for (RecordDecl::field_iterator Field = D->field_begin(),
Fariborz Jahanian62055b02011-04-26 23:52:16 +00001731 FieldEnd = D->field_end(); Field != FieldEnd; ++Field) {
1732 if (IsMsStruct) {
David Blaikie262bc182012-04-30 02:36:29 +00001733 FieldDecl *FD = &*Field;
Fariborz Jahanian855a8e72011-05-03 20:21:04 +00001734 if (Context.ZeroBitfieldFollowsBitfield(FD, LastFD))
1735 ZeroLengthBitfield = FD;
Fariborz Jahanian62055b02011-04-26 23:52:16 +00001736 // Zero-length bitfields following non-bitfield members are
1737 // ignored:
Fariborz Jahanian855a8e72011-05-03 20:21:04 +00001738 else if (Context.ZeroBitfieldFollowsNonBitfield(FD, LastFD))
Fariborz Jahanian62055b02011-04-26 23:52:16 +00001739 continue;
Fariborz Jahanian31e7f222011-05-06 22:42:22 +00001740 // FIXME. streamline these conditions into a simple one.
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001741 else if (Context.BitfieldFollowsBitfield(FD, LastFD) ||
Chad Rosierdd7fddb2011-08-04 23:34:15 +00001742 Context.BitfieldFollowsNonBitfield(FD, LastFD) ||
1743 Context.NonBitfieldFollowsBitfield(FD, LastFD)) {
Fariborz Jahanian31e7f222011-05-06 22:42:22 +00001744 // 1) Adjacent bit fields are packed into the same 1-, 2-, or
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +00001745 // 4-byte allocation unit if the integral types are the same
1746 // size and if the next bit field fits into the current
1747 // allocation unit without crossing the boundary imposed by the
1748 // common alignment requirements of the bit fields.
Fariborz Jahanian31e7f222011-05-06 22:42:22 +00001749 // 2) Establish a new alignment for a bitfield following
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001750 // a non-bitfield if size of their types differ.
Fariborz Jahanian31e7f222011-05-06 22:42:22 +00001751 // 3) Establish a new alignment for a non-bitfield following
1752 // a bitfield if size of their types differ.
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +00001753 std::pair<uint64_t, unsigned> FieldInfo =
1754 Context.getTypeInfo(FD->getType());
1755 uint64_t TypeSize = FieldInfo.first;
1756 unsigned FieldAlign = FieldInfo.second;
Fariborz Jahanian30364d02011-05-09 22:03:17 +00001757 // This check is needed for 'long long' in -m32 mode.
Fariborz Jahanian364a59e2011-12-12 21:16:36 +00001758 if (TypeSize > FieldAlign &&
1759 (Context.hasSameType(FD->getType(),
1760 Context.UnsignedLongLongTy)
1761 ||Context.hasSameType(FD->getType(),
1762 Context.LongLongTy)))
Fariborz Jahanian30364d02011-05-09 22:03:17 +00001763 FieldAlign = TypeSize;
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +00001764 FieldInfo = Context.getTypeInfo(LastFD->getType());
1765 uint64_t TypeSizeLastFD = FieldInfo.first;
1766 unsigned FieldAlignLastFD = FieldInfo.second;
Fariborz Jahanian30364d02011-05-09 22:03:17 +00001767 // This check is needed for 'long long' in -m32 mode.
Fariborz Jahanian364a59e2011-12-12 21:16:36 +00001768 if (TypeSizeLastFD > FieldAlignLastFD &&
1769 (Context.hasSameType(LastFD->getType(),
1770 Context.UnsignedLongLongTy)
1771 || Context.hasSameType(LastFD->getType(),
1772 Context.LongLongTy)))
Fariborz Jahanian30364d02011-05-09 22:03:17 +00001773 FieldAlignLastFD = TypeSizeLastFD;
Fariborz Jahanian6ec50ad2011-05-11 16:58:31 +00001774
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +00001775 if (TypeSizeLastFD != TypeSize) {
Fariborz Jahanian6ec50ad2011-05-11 16:58:31 +00001776 if (RemainingInAlignment &&
1777 LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001778 LastFD->getBitWidthValue(Context)) {
Fariborz Jahanian6ec50ad2011-05-11 16:58:31 +00001779 // If previous field was a bitfield with some remaining unfilled
1780 // bits, pad the field so current field starts on its type boundary.
1781 uint64_t FieldOffset =
1782 getDataSizeInBits() - UnfilledBitsInLastByte;
1783 uint64_t NewSizeInBits = RemainingInAlignment + FieldOffset;
1784 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001785 Context.getTargetInfo().getCharAlign()));
Fariborz Jahanian6ec50ad2011-05-11 16:58:31 +00001786 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1787 RemainingInAlignment = 0;
1788 }
1789
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +00001790 uint64_t UnpaddedFieldOffset =
1791 getDataSizeInBits() - UnfilledBitsInLastByte;
1792 FieldAlign = std::max(FieldAlign, FieldAlignLastFD);
Fariborz Jahanian6ec50ad2011-05-11 16:58:31 +00001793
Fariborz Jahanianed63e032011-05-10 19:00:50 +00001794 // The maximum field alignment overrides the aligned attribute.
1795 if (!MaxFieldAlignment.isZero()) {
1796 unsigned MaxFieldAlignmentInBits =
1797 Context.toBits(MaxFieldAlignment);
1798 FieldAlign = std::min(FieldAlign, MaxFieldAlignmentInBits);
1799 }
Fariborz Jahanian6ec50ad2011-05-11 16:58:31 +00001800
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +00001801 uint64_t NewSizeInBits =
1802 llvm::RoundUpToAlignment(UnpaddedFieldOffset, FieldAlign);
1803 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001804 Context.getTargetInfo().getCharAlign()));
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +00001805 UnfilledBitsInLastByte = getDataSizeInBits() - NewSizeInBits;
1806 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1807 }
Fariborz Jahanian6ec50ad2011-05-11 16:58:31 +00001808 if (FD->isBitField()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001809 uint64_t FieldSize = FD->getBitWidthValue(Context);
Fariborz Jahanian6ec50ad2011-05-11 16:58:31 +00001810 assert (FieldSize > 0 && "LayoutFields - ms_struct layout");
1811 if (RemainingInAlignment < FieldSize)
1812 RemainingInAlignment = TypeSize - FieldSize;
1813 else
1814 RemainingInAlignment -= FieldSize;
1815 }
1816 }
1817 else if (FD->isBitField()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001818 uint64_t FieldSize = FD->getBitWidthValue(Context);
Fariborz Jahanian6ec50ad2011-05-11 16:58:31 +00001819 std::pair<uint64_t, unsigned> FieldInfo =
1820 Context.getTypeInfo(FD->getType());
1821 uint64_t TypeSize = FieldInfo.first;
1822 RemainingInAlignment = TypeSize - FieldSize;
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +00001823 }
Fariborz Jahanian62055b02011-04-26 23:52:16 +00001824 LastFD = FD;
1825 }
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001826 else if (!Context.getTargetInfo().useBitFieldTypeAlignment() &&
1827 Context.getTargetInfo().useZeroLengthBitfieldAlignment()) {
David Blaikie262bc182012-04-30 02:36:29 +00001828 FieldDecl *FD = &*Field;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001829 if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
Chad Rosier61a62212011-08-04 01:21:14 +00001830 ZeroLengthBitfield = FD;
Chad Rosier61a62212011-08-04 01:21:14 +00001831 }
David Blaikie262bc182012-04-30 02:36:29 +00001832 LayoutField(&*Field);
Fariborz Jahanian62055b02011-04-26 23:52:16 +00001833 }
Fariborz Jahanian6ec50ad2011-05-11 16:58:31 +00001834 if (IsMsStruct && RemainingInAlignment &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001835 LastFD && LastFD->isBitField() && LastFD->getBitWidthValue(Context)) {
Fariborz Jahanian6ec50ad2011-05-11 16:58:31 +00001836 // If we ended a bitfield before the full length of the type then
1837 // pad the struct out to the full length of the last type.
1838 uint64_t FieldOffset =
1839 getDataSizeInBits() - UnfilledBitsInLastByte;
1840 uint64_t NewSizeInBits = RemainingInAlignment + FieldOffset;
1841 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001842 Context.getTargetInfo().getCharAlign()));
Fariborz Jahanian6ec50ad2011-05-11 16:58:31 +00001843 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1844 }
Anders Carlssona2df41c2009-07-18 21:48:39 +00001845}
1846
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00001847void RecordLayoutBuilder::LayoutWideBitField(uint64_t FieldSize,
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00001848 uint64_t TypeSize,
1849 bool FieldPacked,
1850 const FieldDecl *D) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001851 assert(Context.getLangOpts().CPlusPlus &&
Anders Carlsson4cf6f5f2010-04-16 15:57:11 +00001852 "Can only have wide bit-fields in C++!");
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00001853
Anders Carlsson4cf6f5f2010-04-16 15:57:11 +00001854 // Itanium C++ ABI 2.4:
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00001855 // If sizeof(T)*8 < n, let T' be the largest integral POD type with
Anders Carlsson4cf6f5f2010-04-16 15:57:11 +00001856 // sizeof(T')*8 <= n.
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00001857
Anders Carlsson4cf6f5f2010-04-16 15:57:11 +00001858 QualType IntegralPODTypes[] = {
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00001859 Context.UnsignedCharTy, Context.UnsignedShortTy, Context.UnsignedIntTy,
Anders Carlsson4cf6f5f2010-04-16 15:57:11 +00001860 Context.UnsignedLongTy, Context.UnsignedLongLongTy
1861 };
1862
Anders Carlsson4cf6f5f2010-04-16 15:57:11 +00001863 QualType Type;
1864 for (unsigned I = 0, E = llvm::array_lengthof(IntegralPODTypes);
1865 I != E; ++I) {
1866 uint64_t Size = Context.getTypeSize(IntegralPODTypes[I]);
Anders Carlsson4cf6f5f2010-04-16 15:57:11 +00001867
1868 if (Size > FieldSize)
1869 break;
1870
1871 Type = IntegralPODTypes[I];
1872 }
1873 assert(!Type.isNull() && "Did not find a type!");
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00001874
Ken Dyck3b3e1a12011-03-01 01:36:00 +00001875 CharUnits TypeAlign = Context.getTypeAlignInChars(Type);
Anders Carlsson4cf6f5f2010-04-16 15:57:11 +00001876
1877 // We're not going to use any of the unfilled bits in the last byte.
1878 UnfilledBitsInLastByte = 0;
1879
Anders Carlssonde9f1532010-04-17 20:21:41 +00001880 uint64_t FieldOffset;
Ken Dycka0c21c42011-02-24 01:13:28 +00001881 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastByte;
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00001882
Anders Carlsson4cf6f5f2010-04-16 15:57:11 +00001883 if (IsUnion) {
Ken Dycka0c21c42011-02-24 01:13:28 +00001884 setDataSize(std::max(getDataSizeInBits(), FieldSize));
Anders Carlssonde9f1532010-04-17 20:21:41 +00001885 FieldOffset = 0;
Anders Carlsson4cf6f5f2010-04-16 15:57:11 +00001886 } else {
Chad Rosierb8fca902011-08-05 22:38:04 +00001887 // The bitfield is allocated starting at the next offset aligned
1888 // appropriately for T', with length n bits.
Ken Dyck3b3e1a12011-03-01 01:36:00 +00001889 FieldOffset = llvm::RoundUpToAlignment(getDataSizeInBits(),
1890 Context.toBits(TypeAlign));
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00001891
Anders Carlsson4cf6f5f2010-04-16 15:57:11 +00001892 uint64_t NewSizeInBits = FieldOffset + FieldSize;
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00001893
Ken Dyckd5e3ed02011-03-10 02:00:35 +00001894 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001895 Context.getTargetInfo().getCharAlign()));
Ken Dycka0c21c42011-02-24 01:13:28 +00001896 UnfilledBitsInLastByte = getDataSizeInBits() - NewSizeInBits;
Anders Carlsson4cf6f5f2010-04-16 15:57:11 +00001897 }
1898
1899 // Place this field at the current location.
1900 FieldOffsets.push_back(FieldOffset);
1901
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00001902 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, FieldOffset,
Ken Dyck3b3e1a12011-03-01 01:36:00 +00001903 Context.toBits(TypeAlign), FieldPacked, D);
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00001904
Anders Carlsson4cf6f5f2010-04-16 15:57:11 +00001905 // Update the size.
Ken Dycka0c21c42011-02-24 01:13:28 +00001906 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00001907
Anders Carlsson4cf6f5f2010-04-16 15:57:11 +00001908 // Remember max struct/class alignment.
Ken Dyck3b3e1a12011-03-01 01:36:00 +00001909 UpdateAlignment(TypeAlign);
Anders Carlsson4cf6f5f2010-04-16 15:57:11 +00001910}
1911
Anders Carlsson7d0918a2010-05-26 05:58:59 +00001912void RecordLayoutBuilder::LayoutBitField(const FieldDecl *D) {
Anders Carlsson42dbcc42009-11-22 17:37:31 +00001913 bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
Ken Dycka0c21c42011-02-24 01:13:28 +00001914 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastByte;
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00001915 uint64_t FieldOffset = IsUnion ? 0 : UnpaddedFieldOffset;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001916 uint64_t FieldSize = D->getBitWidthValue(Context);
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00001917
Anders Carlsson0f0e9b02010-04-16 15:07:51 +00001918 std::pair<uint64_t, unsigned> FieldInfo = Context.getTypeInfo(D->getType());
Anders Carlsson42dbcc42009-11-22 17:37:31 +00001919 uint64_t TypeSize = FieldInfo.first;
1920 unsigned FieldAlign = FieldInfo.second;
Fariborz Jahanian855a8e72011-05-03 20:21:04 +00001921
Fariborz Jahanian30364d02011-05-09 22:03:17 +00001922 // This check is needed for 'long long' in -m32 mode.
Fariborz Jahanian364a59e2011-12-12 21:16:36 +00001923 if (IsMsStruct && (TypeSize > FieldAlign) &&
1924 (Context.hasSameType(D->getType(),
1925 Context.UnsignedLongLongTy)
1926 || Context.hasSameType(D->getType(), Context.LongLongTy)))
Fariborz Jahanian30364d02011-05-09 22:03:17 +00001927 FieldAlign = TypeSize;
Chad Rosier61a62212011-08-04 01:21:14 +00001928
Fariborz Jahanian855a8e72011-05-03 20:21:04 +00001929 if (ZeroLengthBitfield) {
Chad Rosierb8fca902011-08-05 22:38:04 +00001930 std::pair<uint64_t, unsigned> FieldInfo;
1931 unsigned ZeroLengthBitfieldAlignment;
1932 if (IsMsStruct) {
1933 // If a zero-length bitfield is inserted after a bitfield,
1934 // and the alignment of the zero-length bitfield is
1935 // greater than the member that follows it, `bar', `bar'
1936 // will be aligned as the type of the zero-length bitfield.
1937 if (ZeroLengthBitfield != D) {
1938 FieldInfo = Context.getTypeInfo(ZeroLengthBitfield->getType());
1939 ZeroLengthBitfieldAlignment = FieldInfo.second;
1940 // Ignore alignment of subsequent zero-length bitfields.
1941 if ((ZeroLengthBitfieldAlignment > FieldAlign) || (FieldSize == 0))
1942 FieldAlign = ZeroLengthBitfieldAlignment;
1943 if (FieldSize)
1944 ZeroLengthBitfield = 0;
1945 }
1946 } else {
1947 // The alignment of a zero-length bitfield affects the alignment
1948 // of the next member. The alignment is the max of the zero
1949 // length bitfield's alignment and a target specific fixed value.
1950 unsigned ZeroLengthBitfieldBoundary =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001951 Context.getTargetInfo().getZeroLengthBitfieldBoundary();
Chad Rosierb8fca902011-08-05 22:38:04 +00001952 if (ZeroLengthBitfieldBoundary > FieldAlign)
1953 FieldAlign = ZeroLengthBitfieldBoundary;
Fariborz Jahanian855a8e72011-05-03 20:21:04 +00001954 }
1955 }
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00001956
Anders Carlsson4cf6f5f2010-04-16 15:57:11 +00001957 if (FieldSize > TypeSize) {
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00001958 LayoutWideBitField(FieldSize, TypeSize, FieldPacked, D);
Anders Carlsson4cf6f5f2010-04-16 15:57:11 +00001959 return;
1960 }
1961
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00001962 // The align if the field is not packed. This is to check if the attribute
1963 // was unnecessary (-Wpacked).
1964 unsigned UnpackedFieldAlign = FieldAlign;
1965 uint64_t UnpackedFieldOffset = FieldOffset;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001966 if (!Context.getTargetInfo().useBitFieldTypeAlignment() && !ZeroLengthBitfield)
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00001967 UnpackedFieldAlign = 1;
1968
Chad Rosierb8fca902011-08-05 22:38:04 +00001969 if (FieldPacked ||
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001970 (!Context.getTargetInfo().useBitFieldTypeAlignment() && !ZeroLengthBitfield))
Anders Carlsson42dbcc42009-11-22 17:37:31 +00001971 FieldAlign = 1;
Sean Huntcf807c42010-08-18 23:23:40 +00001972 FieldAlign = std::max(FieldAlign, D->getMaxAlignment());
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00001973 UnpackedFieldAlign = std::max(UnpackedFieldAlign, D->getMaxAlignment());
Anders Carlsson42dbcc42009-11-22 17:37:31 +00001974
1975 // The maximum field alignment overrides the aligned attribute.
Eli Friedmanbff22ac2011-12-02 02:38:48 +00001976 if (!MaxFieldAlignment.isZero() && FieldSize != 0) {
Ken Dyck834945c2011-02-17 01:49:42 +00001977 unsigned MaxFieldAlignmentInBits = Context.toBits(MaxFieldAlignment);
1978 FieldAlign = std::min(FieldAlign, MaxFieldAlignmentInBits);
1979 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignmentInBits);
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00001980 }
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00001981
Douglas Gregor394f7b62012-01-28 00:53:29 +00001982 // Check if we need to add padding to give the field the correct alignment.
1983 if (FieldSize == 0 ||
1984 (MaxFieldAlignment.isZero() &&
1985 (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize))
1986 FieldOffset = llvm::RoundUpToAlignment(FieldOffset, FieldAlign);
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00001987
Douglas Gregor394f7b62012-01-28 00:53:29 +00001988 if (FieldSize == 0 ||
1989 (MaxFieldAlignment.isZero() &&
1990 (UnpackedFieldOffset & (UnpackedFieldAlign-1)) + FieldSize > TypeSize))
1991 UnpackedFieldOffset = llvm::RoundUpToAlignment(UnpackedFieldOffset,
1992 UnpackedFieldAlign);
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00001993
Chad Rosierb8fca902011-08-05 22:38:04 +00001994 // Padding members don't affect overall alignment, unless zero length bitfield
1995 // alignment is enabled.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001996 if (!D->getIdentifier() && !Context.getTargetInfo().useZeroLengthBitfieldAlignment())
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00001997 FieldAlign = UnpackedFieldAlign = 1;
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00001998
Chad Rosierb8fca902011-08-05 22:38:04 +00001999 if (!IsMsStruct)
2000 ZeroLengthBitfield = 0;
2001
Douglas Gregor394f7b62012-01-28 00:53:29 +00002002 if (ExternalLayout)
2003 FieldOffset = updateExternalFieldOffset(D, FieldOffset);
2004
Anders Carlsson42dbcc42009-11-22 17:37:31 +00002005 // Place this field at the current location.
2006 FieldOffsets.push_back(FieldOffset);
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002007
Douglas Gregor453dbcb2012-01-26 07:55:45 +00002008 if (!ExternalLayout)
2009 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, UnpackedFieldOffset,
2010 UnpackedFieldAlign, FieldPacked, D);
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00002011
Anders Carlssone4fc0d92009-11-22 19:13:51 +00002012 // Update DataSize to include the last byte containing (part of) the bitfield.
2013 if (IsUnion) {
2014 // FIXME: I think FieldSize should be TypeSize here.
Ken Dycka0c21c42011-02-24 01:13:28 +00002015 setDataSize(std::max(getDataSizeInBits(), FieldSize));
Anders Carlssone4fc0d92009-11-22 19:13:51 +00002016 } else {
2017 uint64_t NewSizeInBits = FieldOffset + FieldSize;
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002018
Ken Dyckd5e3ed02011-03-10 02:00:35 +00002019 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002020 Context.getTargetInfo().getCharAlign()));
Ken Dycka0c21c42011-02-24 01:13:28 +00002021 UnfilledBitsInLastByte = getDataSizeInBits() - NewSizeInBits;
Anders Carlssone4fc0d92009-11-22 19:13:51 +00002022 }
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002023
Anders Carlssone4fc0d92009-11-22 19:13:51 +00002024 // Update the size.
Ken Dycka0c21c42011-02-24 01:13:28 +00002025 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002026
Anders Carlsson42dbcc42009-11-22 17:37:31 +00002027 // Remember max struct/class alignment.
Ken Dyck3263e092011-02-19 18:58:07 +00002028 UpdateAlignment(Context.toCharUnitsFromBits(FieldAlign),
2029 Context.toCharUnitsFromBits(UnpackedFieldAlign));
Anders Carlsson42dbcc42009-11-22 17:37:31 +00002030}
2031
Douglas Gregor453dbcb2012-01-26 07:55:45 +00002032void RecordLayoutBuilder::LayoutField(const FieldDecl *D) {
Anders Carlsson42dbcc42009-11-22 17:37:31 +00002033 if (D->isBitField()) {
2034 LayoutBitField(D);
2035 return;
2036 }
2037
Ken Dycka0c21c42011-02-24 01:13:28 +00002038 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastByte;
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00002039
Anders Carlssone4fc0d92009-11-22 19:13:51 +00002040 // Reset the unfilled bits.
2041 UnfilledBitsInLastByte = 0;
2042
Anders Carlsson42dbcc42009-11-22 17:37:31 +00002043 bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
Ken Dyck9ed9a252011-02-20 02:06:09 +00002044 CharUnits FieldOffset =
Ken Dycka0c21c42011-02-24 01:13:28 +00002045 IsUnion ? CharUnits::Zero() : getDataSize();
Ken Dyck9ed9a252011-02-20 02:06:09 +00002046 CharUnits FieldSize;
2047 CharUnits FieldAlign;
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002048
Anders Carlsson42dbcc42009-11-22 17:37:31 +00002049 if (D->getType()->isIncompleteArrayType()) {
2050 // This is a flexible array member; we can't directly
2051 // query getTypeInfo about these, so we figure it out here.
2052 // Flexible array members don't have any size, but they
2053 // have to be aligned appropriately for their element type.
Ken Dyck9ed9a252011-02-20 02:06:09 +00002054 FieldSize = CharUnits::Zero();
Anders Carlsson0f0e9b02010-04-16 15:07:51 +00002055 const ArrayType* ATy = Context.getAsArrayType(D->getType());
Ken Dyck9ed9a252011-02-20 02:06:09 +00002056 FieldAlign = Context.getTypeAlignInChars(ATy->getElementType());
Anders Carlsson42dbcc42009-11-22 17:37:31 +00002057 } else if (const ReferenceType *RT = D->getType()->getAs<ReferenceType>()) {
2058 unsigned AS = RT->getPointeeType().getAddressSpace();
Ken Dyck9ed9a252011-02-20 02:06:09 +00002059 FieldSize =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002060 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(AS));
Ken Dyck9ed9a252011-02-20 02:06:09 +00002061 FieldAlign =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002062 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(AS));
Anders Carlssonbda4c102009-07-18 20:20:21 +00002063 } else {
Ken Dyck9ed9a252011-02-20 02:06:09 +00002064 std::pair<CharUnits, CharUnits> FieldInfo =
2065 Context.getTypeInfoInChars(D->getType());
Anders Carlsson42dbcc42009-11-22 17:37:31 +00002066 FieldSize = FieldInfo.first;
2067 FieldAlign = FieldInfo.second;
Chad Rosier61a62212011-08-04 01:21:14 +00002068
Fariborz Jahanian855a8e72011-05-03 20:21:04 +00002069 if (ZeroLengthBitfield) {
Chad Rosier61a62212011-08-04 01:21:14 +00002070 CharUnits ZeroLengthBitfieldBoundary =
2071 Context.toCharUnitsFromBits(
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002072 Context.getTargetInfo().getZeroLengthBitfieldBoundary());
Chad Rosier61a62212011-08-04 01:21:14 +00002073 if (ZeroLengthBitfieldBoundary == CharUnits::Zero()) {
2074 // If a zero-length bitfield is inserted after a bitfield,
2075 // and the alignment of the zero-length bitfield is
2076 // greater than the member that follows it, `bar', `bar'
2077 // will be aligned as the type of the zero-length bitfield.
2078 std::pair<CharUnits, CharUnits> FieldInfo =
2079 Context.getTypeInfoInChars(ZeroLengthBitfield->getType());
2080 CharUnits ZeroLengthBitfieldAlignment = FieldInfo.second;
2081 if (ZeroLengthBitfieldAlignment > FieldAlign)
2082 FieldAlign = ZeroLengthBitfieldAlignment;
Chad Rosier0e7bf402011-08-04 19:25:14 +00002083 } else if (ZeroLengthBitfieldBoundary > FieldAlign) {
Chad Rosier61a62212011-08-04 01:21:14 +00002084 // Align 'bar' based on a fixed alignment specified by the target.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002085 assert(Context.getTargetInfo().useZeroLengthBitfieldAlignment() &&
Chad Rosier6e43f3f2011-08-04 17:52:43 +00002086 "ZeroLengthBitfieldBoundary should only be used in conjunction"
2087 " with useZeroLengthBitfieldAlignment.");
Chad Rosier61a62212011-08-04 01:21:14 +00002088 FieldAlign = ZeroLengthBitfieldBoundary;
2089 }
Fariborz Jahanian855a8e72011-05-03 20:21:04 +00002090 ZeroLengthBitfield = 0;
2091 }
Douglas Gregor6f755502011-02-01 15:15:22 +00002092
David Blaikie4e4d0842012-03-11 07:00:24 +00002093 if (Context.getLangOpts().MSBitfields || IsMsStruct) {
Douglas Gregor6f755502011-02-01 15:15:22 +00002094 // If MS bitfield layout is required, figure out what type is being
2095 // laid out and align the field to the width of that type.
2096
2097 // Resolve all typedefs down to their base type and round up the field
2098 // alignment if necessary.
2099 QualType T = Context.getBaseElementType(D->getType());
2100 if (const BuiltinType *BTy = T->getAs<BuiltinType>()) {
Ken Dyck9ed9a252011-02-20 02:06:09 +00002101 CharUnits TypeSize = Context.getTypeSizeInChars(BTy);
Douglas Gregor6f755502011-02-01 15:15:22 +00002102 if (TypeSize > FieldAlign)
2103 FieldAlign = TypeSize;
2104 }
2105 }
Anders Carlssonbda4c102009-07-18 20:20:21 +00002106 }
Mike Stump1eb44332009-09-09 15:08:12 +00002107
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00002108 // The align if the field is not packed. This is to check if the attribute
2109 // was unnecessary (-Wpacked).
Ken Dyck9ed9a252011-02-20 02:06:09 +00002110 CharUnits UnpackedFieldAlign = FieldAlign;
2111 CharUnits UnpackedFieldOffset = FieldOffset;
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00002112
Anders Carlsson42dbcc42009-11-22 17:37:31 +00002113 if (FieldPacked)
Ken Dyck9ed9a252011-02-20 02:06:09 +00002114 FieldAlign = CharUnits::One();
2115 CharUnits MaxAlignmentInChars =
2116 Context.toCharUnitsFromBits(D->getMaxAlignment());
2117 FieldAlign = std::max(FieldAlign, MaxAlignmentInChars);
2118 UnpackedFieldAlign = std::max(UnpackedFieldAlign, MaxAlignmentInChars);
Anders Carlsson42dbcc42009-11-22 17:37:31 +00002119
2120 // The maximum field alignment overrides the aligned attribute.
Ken Dyck834945c2011-02-17 01:49:42 +00002121 if (!MaxFieldAlignment.isZero()) {
Ken Dyck9ed9a252011-02-20 02:06:09 +00002122 FieldAlign = std::min(FieldAlign, MaxFieldAlignment);
2123 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignment);
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00002124 }
Anders Carlsson42dbcc42009-11-22 17:37:31 +00002125
Douglas Gregor394f7b62012-01-28 00:53:29 +00002126 // Round up the current record size to the field's alignment boundary.
2127 FieldOffset = FieldOffset.RoundUpToAlignment(FieldAlign);
2128 UnpackedFieldOffset =
2129 UnpackedFieldOffset.RoundUpToAlignment(UnpackedFieldAlign);
2130
2131 if (ExternalLayout) {
2132 FieldOffset = Context.toCharUnitsFromBits(
2133 updateExternalFieldOffset(D, Context.toBits(FieldOffset)));
2134
2135 if (!IsUnion && EmptySubobjects) {
2136 // Record the fact that we're placing a field at this offset.
2137 bool Allowed = EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset);
2138 (void)Allowed;
2139 assert(Allowed && "Externally-placed field cannot be placed here");
2140 }
2141 } else {
Douglas Gregor453dbcb2012-01-26 07:55:45 +00002142 if (!IsUnion && EmptySubobjects) {
2143 // Check if we can place the field at this offset.
2144 while (!EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset)) {
2145 // We couldn't place the field at the offset. Try again at a new offset.
2146 FieldOffset += FieldAlign;
2147 }
Anders Carlsson42dbcc42009-11-22 17:37:31 +00002148 }
Anders Carlsson42dbcc42009-11-22 17:37:31 +00002149 }
Douglas Gregor453dbcb2012-01-26 07:55:45 +00002150
Anders Carlssonbda4c102009-07-18 20:20:21 +00002151 // Place this field at the current location.
Ken Dyck9ed9a252011-02-20 02:06:09 +00002152 FieldOffsets.push_back(Context.toBits(FieldOffset));
Mike Stump1eb44332009-09-09 15:08:12 +00002153
Douglas Gregor453dbcb2012-01-26 07:55:45 +00002154 if (!ExternalLayout)
2155 CheckFieldPadding(Context.toBits(FieldOffset), UnpaddedFieldOffset,
2156 Context.toBits(UnpackedFieldOffset),
2157 Context.toBits(UnpackedFieldAlign), FieldPacked, D);
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00002158
Anders Carlssonbda4c102009-07-18 20:20:21 +00002159 // Reserve space for this field.
Eli Friedmancd7a21b2012-01-12 23:27:03 +00002160 uint64_t FieldSizeInBits = Context.toBits(FieldSize);
Anders Carlssonbda4c102009-07-18 20:20:21 +00002161 if (IsUnion)
Eli Friedman83be12c2012-01-12 23:48:56 +00002162 setDataSize(std::max(getDataSizeInBits(), FieldSizeInBits));
Anders Carlssonbda4c102009-07-18 20:20:21 +00002163 else
Eli Friedman83be12c2012-01-12 23:48:56 +00002164 setDataSize(FieldOffset + FieldSize);
Mike Stump1eb44332009-09-09 15:08:12 +00002165
Eli Friedman83be12c2012-01-12 23:48:56 +00002166 // Update the size.
2167 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
Mike Stump1eb44332009-09-09 15:08:12 +00002168
Anders Carlssonbda4c102009-07-18 20:20:21 +00002169 // Remember max struct/class alignment.
Ken Dyck9ed9a252011-02-20 02:06:09 +00002170 UpdateAlignment(FieldAlign, UnpackedFieldAlign);
Anders Carlssonbda4c102009-07-18 20:20:21 +00002171}
2172
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00002173void RecordLayoutBuilder::FinishLayout(const NamedDecl *D) {
Douglas Gregor394f7b62012-01-28 00:53:29 +00002174 if (ExternalLayout) {
2175 setSize(ExternalSize);
2176 return;
2177 }
2178
Anders Carlssonbda4c102009-07-18 20:20:21 +00002179 // In C++, records cannot be of size 0.
David Blaikie4e4d0842012-03-11 07:00:24 +00002180 if (Context.getLangOpts().CPlusPlus && getSizeInBits() == 0) {
Fariborz Jahanianadf082e2011-02-02 19:36:18 +00002181 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
2182 // Compatibility with gcc requires a class (pod or non-pod)
2183 // which is not empty but of size 0; such as having fields of
2184 // array of zero-length, remains of Size 0
2185 if (RD->isEmpty())
Ken Dyckf079b732011-02-28 02:01:38 +00002186 setSize(CharUnits::One());
Fariborz Jahanianadf082e2011-02-02 19:36:18 +00002187 }
2188 else
Ken Dyckf079b732011-02-28 02:01:38 +00002189 setSize(CharUnits::One());
Fariborz Jahanianadf082e2011-02-02 19:36:18 +00002190 }
Eli Friedman901dd662011-12-01 00:37:01 +00002191
2192 // MSVC doesn't round up to the alignment of the record with virtual bases.
2193 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
2194 if (isMicrosoftCXXABI() && RD->getNumVBases())
2195 return;
2196 }
2197
Anders Carlssonbda4c102009-07-18 20:20:21 +00002198 // Finally, round the size of the record up to the alignment of the
2199 // record itself.
Ken Dycka0c21c42011-02-24 01:13:28 +00002200 uint64_t UnpaddedSize = getSizeInBits() - UnfilledBitsInLastByte;
Ken Dyckf079b732011-02-28 02:01:38 +00002201 uint64_t UnpackedSizeInBits =
Ken Dycka0c21c42011-02-24 01:13:28 +00002202 llvm::RoundUpToAlignment(getSizeInBits(),
2203 Context.toBits(UnpackedAlignment));
Ken Dyckf079b732011-02-28 02:01:38 +00002204 CharUnits UnpackedSize = Context.toCharUnitsFromBits(UnpackedSizeInBits);
Ken Dycka0c21c42011-02-24 01:13:28 +00002205 setSize(llvm::RoundUpToAlignment(getSizeInBits(), Context.toBits(Alignment)));
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00002206
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002207 unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00002208 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
2209 // Warn if padding was introduced to the struct/class/union.
Ken Dycka0c21c42011-02-24 01:13:28 +00002210 if (getSizeInBits() > UnpaddedSize) {
2211 unsigned PadSize = getSizeInBits() - UnpaddedSize;
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00002212 bool InBits = true;
2213 if (PadSize % CharBitNum == 0) {
2214 PadSize = PadSize / CharBitNum;
2215 InBits = false;
2216 }
2217 Diag(RD->getLocation(), diag::warn_padded_struct_size)
2218 << Context.getTypeDeclType(RD)
2219 << PadSize
2220 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1); // plural or not
2221 }
2222
2223 // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
2224 // bother since there won't be alignment issues.
Ken Dycka0c21c42011-02-24 01:13:28 +00002225 if (Packed && UnpackedAlignment > CharUnits::One() &&
Ken Dyckf079b732011-02-28 02:01:38 +00002226 getSize() == UnpackedSize)
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00002227 Diag(D->getLocation(), diag::warn_unnecessary_packed)
2228 << Context.getTypeDeclType(RD);
2229 }
Anders Carlssonbda4c102009-07-18 20:20:21 +00002230}
2231
Ken Dyck3263e092011-02-19 18:58:07 +00002232void RecordLayoutBuilder::UpdateAlignment(CharUnits NewAlignment,
2233 CharUnits UnpackedNewAlignment) {
Douglas Gregor453dbcb2012-01-26 07:55:45 +00002234 // The alignment is not modified when using 'mac68k' alignment or when
Douglas Gregor394f7b62012-01-28 00:53:29 +00002235 // we have an externally-supplied layout that also provides overall alignment.
2236 if (IsMac68kAlign || (ExternalLayout && !InferAlignment))
Daniel Dunbarc6082fe2010-05-27 05:45:51 +00002237 return;
2238
Ken Dyck3263e092011-02-19 18:58:07 +00002239 if (NewAlignment > Alignment) {
2240 assert(llvm::isPowerOf2_32(NewAlignment.getQuantity() &&
2241 "Alignment not a power of 2"));
2242 Alignment = NewAlignment;
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00002243 }
2244
Ken Dyck3263e092011-02-19 18:58:07 +00002245 if (UnpackedNewAlignment > UnpackedAlignment) {
2246 assert(llvm::isPowerOf2_32(UnpackedNewAlignment.getQuantity() &&
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00002247 "Alignment not a power of 2"));
Ken Dyck3263e092011-02-19 18:58:07 +00002248 UnpackedAlignment = UnpackedNewAlignment;
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00002249 }
2250}
2251
Douglas Gregor394f7b62012-01-28 00:53:29 +00002252uint64_t
2253RecordLayoutBuilder::updateExternalFieldOffset(const FieldDecl *Field,
2254 uint64_t ComputedOffset) {
2255 assert(ExternalFieldOffsets.find(Field) != ExternalFieldOffsets.end() &&
2256 "Field does not have an external offset");
2257
2258 uint64_t ExternalFieldOffset = ExternalFieldOffsets[Field];
2259
2260 if (InferAlignment && ExternalFieldOffset < ComputedOffset) {
2261 // The externally-supplied field offset is before the field offset we
2262 // computed. Assume that the structure is packed.
2263 Alignment = CharUnits::fromQuantity(1);
2264 InferAlignment = false;
2265 }
2266
2267 // Use the externally-supplied field offset.
2268 return ExternalFieldOffset;
2269}
2270
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00002271void RecordLayoutBuilder::CheckFieldPadding(uint64_t Offset,
2272 uint64_t UnpaddedOffset,
2273 uint64_t UnpackedOffset,
2274 unsigned UnpackedAlign,
2275 bool isPacked,
2276 const FieldDecl *D) {
2277 // We let objc ivars without warning, objc interfaces generally are not used
2278 // for padding tricks.
2279 if (isa<ObjCIvarDecl>(D))
Anders Carlssonbda4c102009-07-18 20:20:21 +00002280 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002281
Ted Kremenekae5860e2011-09-06 19:40:45 +00002282 // Don't warn about structs created without a SourceLocation. This can
2283 // be done by clients of the AST, such as codegen.
2284 if (D->getLocation().isInvalid())
2285 return;
2286
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002287 unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
Mike Stump1eb44332009-09-09 15:08:12 +00002288
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00002289 // Warn if padding was introduced to the struct/class.
2290 if (!IsUnion && Offset > UnpaddedOffset) {
2291 unsigned PadSize = Offset - UnpaddedOffset;
2292 bool InBits = true;
2293 if (PadSize % CharBitNum == 0) {
2294 PadSize = PadSize / CharBitNum;
2295 InBits = false;
2296 }
2297 if (D->getIdentifier())
2298 Diag(D->getLocation(), diag::warn_padded_struct_field)
2299 << (D->getParent()->isStruct() ? 0 : 1) // struct|class
2300 << Context.getTypeDeclType(D->getParent())
2301 << PadSize
2302 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1) // plural or not
2303 << D->getIdentifier();
2304 else
2305 Diag(D->getLocation(), diag::warn_padded_struct_anon_field)
2306 << (D->getParent()->isStruct() ? 0 : 1) // struct|class
2307 << Context.getTypeDeclType(D->getParent())
2308 << PadSize
2309 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1); // plural or not
2310 }
2311
2312 // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
2313 // bother since there won't be alignment issues.
2314 if (isPacked && UnpackedAlign > CharBitNum && Offset == UnpackedOffset)
2315 Diag(D->getLocation(), diag::warn_unnecessary_packed)
2316 << D->getIdentifier();
Anders Carlssonbda4c102009-07-18 20:20:21 +00002317}
Mike Stump1eb44332009-09-09 15:08:12 +00002318
Anders Carlssonf53df232009-12-07 04:35:11 +00002319const CXXMethodDecl *
Anders Carlsson7d0918a2010-05-26 05:58:59 +00002320RecordLayoutBuilder::ComputeKeyFunction(const CXXRecordDecl *RD) {
Daniel Dunbar8d8ab742010-04-19 20:44:53 +00002321 // If a class isn't polymorphic it doesn't have a key function.
Anders Carlssonf53df232009-12-07 04:35:11 +00002322 if (!RD->isPolymorphic())
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00002323 return 0;
Eli Friedman61eab882009-12-08 03:56:49 +00002324
Eli Friedmancb5d2d02011-06-10 21:53:06 +00002325 // A class that is not externally visible doesn't have a key function. (Or
Eli Friedman61eab882009-12-08 03:56:49 +00002326 // at least, there's no point to assigning a key function to such a class;
2327 // this doesn't affect the ABI.)
Eli Friedmancb5d2d02011-06-10 21:53:06 +00002328 if (RD->getLinkage() != ExternalLinkage)
Eli Friedman61eab882009-12-08 03:56:49 +00002329 return 0;
2330
Argyrios Kyrtzidis3bd5b6c2010-10-13 02:39:41 +00002331 // Template instantiations don't have key functions,see Itanium C++ ABI 5.2.6.
2332 // Same behavior as GCC.
2333 TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
2334 if (TSK == TSK_ImplicitInstantiation ||
2335 TSK == TSK_ExplicitInstantiationDefinition)
2336 return 0;
2337
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002338 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
2339 E = RD->method_end(); I != E; ++I) {
David Blaikie262bc182012-04-30 02:36:29 +00002340 const CXXMethodDecl *MD = &*I;
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002341
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00002342 if (!MD->isVirtual())
2343 continue;
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002344
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00002345 if (MD->isPure())
2346 continue;
Eli Friedman61eab882009-12-08 03:56:49 +00002347
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002348 // Ignore implicit member functions, they are always marked as inline, but
2349 // they don't have a body until they're defined.
2350 if (MD->isImplicit())
2351 continue;
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002352
Douglas Gregorbd6d6192010-01-05 19:06:31 +00002353 if (MD->isInlineSpecified())
2354 continue;
Eli Friedmand7d7f672009-12-06 20:50:05 +00002355
2356 if (MD->hasInlineBody())
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00002357 continue;
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002358
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00002359 // We found it.
2360 return MD;
2361 }
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002362
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00002363 return 0;
2364}
2365
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00002366DiagnosticBuilder
2367RecordLayoutBuilder::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +00002368 return Context.getDiagnostics().Report(Loc, DiagID);
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00002369}
2370
Anders Carlsson1e641ce2010-05-26 04:56:53 +00002371/// getASTRecordLayout - Get or compute information about the layout of the
2372/// specified record (struct/union/class), which indicates its size and field
2373/// position information.
Jay Foad4ba2a172011-01-12 09:06:06 +00002374const ASTRecordLayout &
2375ASTContext::getASTRecordLayout(const RecordDecl *D) const {
John McCall65959352011-10-07 02:39:22 +00002376 // These asserts test different things. A record has a definition
2377 // as soon as we begin to parse the definition. That definition is
2378 // not a complete definition (which is what isDefinition() tests)
2379 // until we *finish* parsing the definition.
Sean Callananfd5a5f52012-02-08 00:04:52 +00002380
2381 if (D->hasExternalLexicalStorage() && !D->getDefinition())
2382 getExternalSource()->CompleteType(const_cast<RecordDecl*>(D));
2383
Anders Carlsson1e641ce2010-05-26 04:56:53 +00002384 D = D->getDefinition();
2385 assert(D && "Cannot get layout of forward declarations!");
John McCall5e1cdac2011-10-07 06:10:15 +00002386 assert(D->isCompleteDefinition() && "Cannot layout type before complete!");
Anders Carlsson1e641ce2010-05-26 04:56:53 +00002387
2388 // Look up this layout, if already laid out, return what we have.
2389 // Note that we can't save a reference to the entry because this function
2390 // is recursive.
2391 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
2392 if (Entry) return *Entry;
2393
Anders Carlsson2f64e372010-05-26 05:10:47 +00002394 const ASTRecordLayout *NewEntry;
2395
2396 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
Anders Carlsson261febd2010-05-27 00:07:01 +00002397 EmptySubobjectMap EmptySubobjects(*this, RD);
John McCall9da23522011-11-08 04:01:03 +00002398 RecordLayoutBuilder Builder(*this, &EmptySubobjects);
2399 Builder.Layout(RD);
Anders Carlsson58b16b62010-05-27 05:41:06 +00002400
John McCall9da23522011-11-08 04:01:03 +00002401 // MSVC gives the vb-table pointer an alignment equal to that of
2402 // the non-virtual part of the structure. That's an inherently
2403 // multi-pass operation. If our first pass doesn't give us
2404 // adequate alignment, try again with the specified minimum
2405 // alignment. This is *much* more maintainable than computing the
2406 // alignment in advance in a separately-coded pass; it's also
2407 // significantly more efficient in the common case where the
2408 // vb-table doesn't need extra padding.
2409 if (Builder.VBPtrOffset != CharUnits::fromQuantity(-1) &&
2410 (Builder.VBPtrOffset % Builder.NonVirtualAlignment) != 0) {
2411 Builder.resetWithTargetAlignment(Builder.NonVirtualAlignment);
2412 Builder.Layout(RD);
Eli Friedman2fe36362011-09-27 19:12:27 +00002413 }
2414
Anders Carlsson2f64e372010-05-26 05:10:47 +00002415 // FIXME: This is not always correct. See the part about bitfields at
2416 // http://www.codesourcery.com/public/cxx-abi/abi.html#POD for more info.
2417 // FIXME: IsPODForThePurposeOfLayout should be stored in the record layout.
Eli Friedman2fe36362011-09-27 19:12:27 +00002418 // This does not affect the calculations of MSVC layouts
2419 bool IsPODForThePurposeOfLayout =
John McCall9da23522011-11-08 04:01:03 +00002420 (!Builder.isMicrosoftCXXABI() && cast<CXXRecordDecl>(D)->isPOD());
Anders Carlsson2f64e372010-05-26 05:10:47 +00002421
2422 // FIXME: This should be done in FinalizeLayout.
Ken Dyckf079b732011-02-28 02:01:38 +00002423 CharUnits DataSize =
John McCall9da23522011-11-08 04:01:03 +00002424 IsPODForThePurposeOfLayout ? Builder.getSize() : Builder.getDataSize();
Ken Dyckf079b732011-02-28 02:01:38 +00002425 CharUnits NonVirtualSize =
John McCall9da23522011-11-08 04:01:03 +00002426 IsPODForThePurposeOfLayout ? DataSize : Builder.NonVirtualSize;
Anders Carlsson2f64e372010-05-26 05:10:47 +00002427
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00002428 NewEntry =
John McCall9da23522011-11-08 04:01:03 +00002429 new (*this) ASTRecordLayout(*this, Builder.getSize(),
2430 Builder.Alignment,
John McCall441c6232012-05-01 08:55:32 +00002431 Builder.HasOwnVFPtr,
John McCall9da23522011-11-08 04:01:03 +00002432 Builder.VBPtrOffset,
Ken Dyckf079b732011-02-28 02:01:38 +00002433 DataSize,
John McCall9da23522011-11-08 04:01:03 +00002434 Builder.FieldOffsets.data(),
2435 Builder.FieldOffsets.size(),
Ken Dycka1fdb0b2011-02-16 01:52:01 +00002436 NonVirtualSize,
John McCall9da23522011-11-08 04:01:03 +00002437 Builder.NonVirtualAlignment,
Anders Carlsson261febd2010-05-27 00:07:01 +00002438 EmptySubobjects.SizeOfLargestEmptySubobject,
John McCall9da23522011-11-08 04:01:03 +00002439 Builder.PrimaryBase,
2440 Builder.PrimaryBaseIsVirtual,
2441 Builder.Bases, Builder.VBases);
Anders Carlsson2f64e372010-05-26 05:10:47 +00002442 } else {
John McCall9da23522011-11-08 04:01:03 +00002443 RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/0);
Anders Carlsson2f64e372010-05-26 05:10:47 +00002444 Builder.Layout(D);
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00002445
Anders Carlsson2f64e372010-05-26 05:10:47 +00002446 NewEntry =
Ken Dyckf079b732011-02-28 02:01:38 +00002447 new (*this) ASTRecordLayout(*this, Builder.getSize(),
Ken Dyckea7f6c22011-02-16 02:05:21 +00002448 Builder.Alignment,
Ken Dyckf079b732011-02-28 02:01:38 +00002449 Builder.getSize(),
Anders Carlsson2f64e372010-05-26 05:10:47 +00002450 Builder.FieldOffsets.data(),
2451 Builder.FieldOffsets.size());
2452 }
2453
Anders Carlsson1e641ce2010-05-26 04:56:53 +00002454 ASTRecordLayouts[D] = NewEntry;
2455
David Blaikie4e4d0842012-03-11 07:00:24 +00002456 if (getLangOpts().DumpRecordLayouts) {
Anders Carlsson1e641ce2010-05-26 04:56:53 +00002457 llvm::errs() << "\n*** Dumping AST Record Layout\n";
David Blaikie4e4d0842012-03-11 07:00:24 +00002458 DumpRecordLayout(D, llvm::errs(), getLangOpts().DumpRecordLayoutsSimple);
Anders Carlsson1e641ce2010-05-26 04:56:53 +00002459 }
2460
2461 return *NewEntry;
2462}
2463
2464const CXXMethodDecl *ASTContext::getKeyFunction(const CXXRecordDecl *RD) {
2465 RD = cast<CXXRecordDecl>(RD->getDefinition());
2466 assert(RD && "Cannot get key function for forward declarations!");
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00002467
Anders Carlsson1e641ce2010-05-26 04:56:53 +00002468 const CXXMethodDecl *&Entry = KeyFunctions[RD];
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00002469 if (!Entry)
Anders Carlsson7d0918a2010-05-26 05:58:59 +00002470 Entry = RecordLayoutBuilder::ComputeKeyFunction(RD);
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00002471
Anders Carlsson1e641ce2010-05-26 04:56:53 +00002472 return Entry;
2473}
2474
Richard Smith2d6a5672012-01-14 04:30:29 +00002475static uint64_t getFieldOffset(const ASTContext &C, const FieldDecl *FD) {
2476 const ASTRecordLayout &Layout = C.getASTRecordLayout(FD->getParent());
2477 return Layout.getFieldOffset(FD->getFieldIndex());
2478}
2479
2480uint64_t ASTContext::getFieldOffset(const ValueDecl *VD) const {
2481 uint64_t OffsetInBits;
2482 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
2483 OffsetInBits = ::getFieldOffset(*this, FD);
2484 } else {
2485 const IndirectFieldDecl *IFD = cast<IndirectFieldDecl>(VD);
2486
2487 OffsetInBits = 0;
2488 for (IndirectFieldDecl::chain_iterator CI = IFD->chain_begin(),
2489 CE = IFD->chain_end();
2490 CI != CE; ++CI)
2491 OffsetInBits += ::getFieldOffset(*this, cast<FieldDecl>(*CI));
2492 }
2493
2494 return OffsetInBits;
2495}
2496
Eric Christopher68395a72011-10-05 06:00:51 +00002497/// getObjCLayout - Get or compute information about the layout of the
2498/// given interface.
Anders Carlsson1e641ce2010-05-26 04:56:53 +00002499///
2500/// \param Impl - If given, also include the layout of the interface's
2501/// implementation. This may differ by including synthesized ivars.
2502const ASTRecordLayout &
2503ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
Jay Foad4ba2a172011-01-12 09:06:06 +00002504 const ObjCImplementationDecl *Impl) const {
Douglas Gregore7aa27a2011-12-20 15:50:13 +00002505 // Retrieve the definition
Sean Callanancad313b2012-03-15 16:33:08 +00002506 if (D->hasExternalLexicalStorage() && !D->getDefinition())
2507 getExternalSource()->CompleteType(const_cast<ObjCInterfaceDecl*>(D));
Douglas Gregore7aa27a2011-12-20 15:50:13 +00002508 D = D->getDefinition();
2509 assert(D && D->isThisDeclarationADefinition() && "Invalid interface decl!");
Anders Carlsson1e641ce2010-05-26 04:56:53 +00002510
2511 // Look up this layout, if already laid out, return what we have.
2512 ObjCContainerDecl *Key =
2513 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
2514 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
2515 return *Entry;
2516
2517 // Add in synthesized ivar count if laying out an implementation.
2518 if (Impl) {
2519 unsigned SynthCount = CountNonClassIvars(D);
2520 // If there aren't any sythesized ivars then reuse the interface
2521 // entry. Note we can't cache this because we simply free all
2522 // entries later; however we shouldn't look up implementations
2523 // frequently.
2524 if (SynthCount == 0)
2525 return getObjCLayout(D, 0);
2526 }
2527
John McCall9da23522011-11-08 04:01:03 +00002528 RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/0);
Anders Carlsson36cdc612010-05-26 05:04:25 +00002529 Builder.Layout(D);
2530
Anders Carlsson1e641ce2010-05-26 04:56:53 +00002531 const ASTRecordLayout *NewEntry =
Ken Dyckf079b732011-02-28 02:01:38 +00002532 new (*this) ASTRecordLayout(*this, Builder.getSize(),
Ken Dyckea7f6c22011-02-16 02:05:21 +00002533 Builder.Alignment,
Ken Dyckf079b732011-02-28 02:01:38 +00002534 Builder.getDataSize(),
Anders Carlsson36cdc612010-05-26 05:04:25 +00002535 Builder.FieldOffsets.data(),
2536 Builder.FieldOffsets.size());
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00002537
Anders Carlsson1e641ce2010-05-26 04:56:53 +00002538 ObjCLayouts[Key] = NewEntry;
2539
2540 return *NewEntry;
2541}
2542
Chris Lattner5f9e2722011-07-23 10:55:15 +00002543static void PrintOffset(raw_ostream &OS,
Anders Carlsson3069a0d2010-10-31 23:45:59 +00002544 CharUnits Offset, unsigned IndentLevel) {
Benjamin Kramere4ebbf72011-11-05 09:02:52 +00002545 OS << llvm::format("%4" PRId64 " | ", (int64_t)Offset.getQuantity());
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002546 OS.indent(IndentLevel * 2);
2547}
2548
Chris Lattner5f9e2722011-07-23 10:55:15 +00002549static void DumpCXXRecordLayout(raw_ostream &OS,
Jay Foad4ba2a172011-01-12 09:06:06 +00002550 const CXXRecordDecl *RD, const ASTContext &C,
Anders Carlsson3069a0d2010-10-31 23:45:59 +00002551 CharUnits Offset,
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002552 unsigned IndentLevel,
2553 const char* Description,
2554 bool IncludeVirtualBases) {
Anders Carlsson3069a0d2010-10-31 23:45:59 +00002555 const ASTRecordLayout &Layout = C.getASTRecordLayout(RD);
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002556
2557 PrintOffset(OS, Offset, IndentLevel);
Dan Gohmancb421fa2010-04-19 16:39:44 +00002558 OS << C.getTypeDeclType(const_cast<CXXRecordDecl *>(RD)).getAsString();
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002559 if (Description)
2560 OS << ' ' << Description;
2561 if (RD->isEmpty())
2562 OS << " (empty)";
2563 OS << '\n';
2564
2565 IndentLevel++;
2566
Anders Carlsson3069a0d2010-10-31 23:45:59 +00002567 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
John McCall441c6232012-05-01 08:55:32 +00002568 bool HasVfptr = Layout.hasOwnVFPtr();
Eli Friedman2fe36362011-09-27 19:12:27 +00002569 bool HasVbptr = Layout.getVBPtrOffset() != CharUnits::fromQuantity(-1);
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002570
2571 // Vtable pointer.
Eli Friedman227e4832011-10-21 22:49:56 +00002572 if (RD->isDynamicClass() && !PrimaryBase &&
2573 C.getTargetInfo().getCXXABI() != CXXABI_Microsoft) {
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002574 PrintOffset(OS, Offset, IndentLevel);
Benjamin Kramerb8989f22011-10-14 18:45:37 +00002575 OS << '(' << *RD << " vtable pointer)\n";
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002576 }
Eli Friedman2fe36362011-09-27 19:12:27 +00002577
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002578 // Dump (non-virtual) bases
2579 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
2580 E = RD->bases_end(); I != E; ++I) {
2581 assert(!I->getType()->isDependentType() &&
2582 "Cannot layout class with dependent bases.");
2583 if (I->isVirtual())
2584 continue;
2585
2586 const CXXRecordDecl *Base =
2587 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
2588
Anders Carlsson3069a0d2010-10-31 23:45:59 +00002589 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base);
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002590
2591 DumpCXXRecordLayout(OS, Base, C, BaseOffset, IndentLevel,
2592 Base == PrimaryBase ? "(primary base)" : "(base)",
2593 /*IncludeVirtualBases=*/false);
2594 }
Eli Friedman227e4832011-10-21 22:49:56 +00002595
2596 // vfptr and vbptr (for Microsoft C++ ABI)
2597 if (HasVfptr) {
John McCall441c6232012-05-01 08:55:32 +00002598 PrintOffset(OS, Offset, IndentLevel);
Eli Friedman227e4832011-10-21 22:49:56 +00002599 OS << '(' << *RD << " vftable pointer)\n";
2600 }
Eli Friedman2fe36362011-09-27 19:12:27 +00002601 if (HasVbptr) {
2602 PrintOffset(OS, Offset + Layout.getVBPtrOffset(), IndentLevel);
Benjamin Kramerb8989f22011-10-14 18:45:37 +00002603 OS << '(' << *RD << " vbtable pointer)\n";
Eli Friedman2fe36362011-09-27 19:12:27 +00002604 }
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002605
2606 // Dump fields.
2607 uint64_t FieldNo = 0;
2608 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2609 E = RD->field_end(); I != E; ++I, ++FieldNo) {
David Blaikie262bc182012-04-30 02:36:29 +00002610 const FieldDecl &Field = *I;
Anders Carlsson3069a0d2010-10-31 23:45:59 +00002611 CharUnits FieldOffset = Offset +
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00002612 C.toCharUnitsFromBits(Layout.getFieldOffset(FieldNo));
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002613
David Blaikie262bc182012-04-30 02:36:29 +00002614 if (const RecordType *RT = Field.getType()->getAs<RecordType>()) {
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002615 if (const CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2616 DumpCXXRecordLayout(OS, D, C, FieldOffset, IndentLevel,
David Blaikie262bc182012-04-30 02:36:29 +00002617 Field.getName().data(),
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002618 /*IncludeVirtualBases=*/true);
2619 continue;
2620 }
2621 }
2622
2623 PrintOffset(OS, FieldOffset, IndentLevel);
David Blaikie262bc182012-04-30 02:36:29 +00002624 OS << Field.getType().getAsString() << ' ' << Field << '\n';
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002625 }
2626
2627 if (!IncludeVirtualBases)
2628 return;
2629
2630 // Dump virtual bases.
John McCall441c6232012-05-01 08:55:32 +00002631 const ASTRecordLayout::VBaseOffsetsMapTy &vtordisps =
2632 Layout.getVBaseOffsetsMap();
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002633 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
2634 E = RD->vbases_end(); I != E; ++I) {
2635 assert(I->isVirtual() && "Found non-virtual class!");
2636 const CXXRecordDecl *VBase =
2637 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
2638
Anders Carlsson3069a0d2010-10-31 23:45:59 +00002639 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBase);
John McCall441c6232012-05-01 08:55:32 +00002640
2641 if (vtordisps.find(VBase)->second.hasVtorDisp()) {
2642 PrintOffset(OS, VBaseOffset - CharUnits::fromQuantity(4), IndentLevel);
2643 OS << "(vtordisp for vbase " << *VBase << ")\n";
2644 }
2645
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002646 DumpCXXRecordLayout(OS, VBase, C, VBaseOffset, IndentLevel,
2647 VBase == PrimaryBase ?
2648 "(primary virtual base)" : "(virtual base)",
2649 /*IncludeVirtualBases=*/false);
2650 }
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002651
Ken Dyck5f022d82011-02-09 01:59:34 +00002652 OS << " sizeof=" << Layout.getSize().getQuantity();
Ken Dyckec299032011-02-11 02:20:09 +00002653 OS << ", dsize=" << Layout.getDataSize().getQuantity();
Ken Dyckdac54c12011-02-15 02:32:40 +00002654 OS << ", align=" << Layout.getAlignment().getQuantity() << '\n';
Ken Dyck5c3633f2011-02-01 01:52:10 +00002655 OS << " nvsize=" << Layout.getNonVirtualSize().getQuantity();
Ken Dyck68cf1a52011-02-08 02:02:47 +00002656 OS << ", nvalign=" << Layout.getNonVirtualAlign().getQuantity() << '\n';
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002657 OS << '\n';
2658}
Daniel Dunbar8d8ab742010-04-19 20:44:53 +00002659
2660void ASTContext::DumpRecordLayout(const RecordDecl *RD,
Douglas Gregor453dbcb2012-01-26 07:55:45 +00002661 raw_ostream &OS,
2662 bool Simple) const {
Daniel Dunbar8d8ab742010-04-19 20:44:53 +00002663 const ASTRecordLayout &Info = getASTRecordLayout(RD);
2664
2665 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Douglas Gregor453dbcb2012-01-26 07:55:45 +00002666 if (!Simple)
2667 return DumpCXXRecordLayout(OS, CXXRD, *this, CharUnits(), 0, 0,
2668 /*IncludeVirtualBases=*/true);
Daniel Dunbar8d8ab742010-04-19 20:44:53 +00002669
2670 OS << "Type: " << getTypeDeclType(RD).getAsString() << "\n";
Douglas Gregor453dbcb2012-01-26 07:55:45 +00002671 if (!Simple) {
2672 OS << "Record: ";
2673 RD->dump();
2674 }
Daniel Dunbar8d8ab742010-04-19 20:44:53 +00002675 OS << "\nLayout: ";
2676 OS << "<ASTRecordLayout\n";
Ken Dyckdd76a9a2011-02-11 01:54:29 +00002677 OS << " Size:" << toBits(Info.getSize()) << "\n";
Ken Dyckec299032011-02-11 02:20:09 +00002678 OS << " DataSize:" << toBits(Info.getDataSize()) << "\n";
Ken Dyckdac54c12011-02-15 02:32:40 +00002679 OS << " Alignment:" << toBits(Info.getAlignment()) << "\n";
Daniel Dunbar8d8ab742010-04-19 20:44:53 +00002680 OS << " FieldOffsets: [";
2681 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i) {
2682 if (i) OS << ", ";
2683 OS << Info.getFieldOffset(i);
2684 }
2685 OS << "]>\n";
2686}