blob: 5624ce7836ffb5e081dbd96b327d323d4082bdfa [file] [log] [blame]
Anders Carlsson35a36eb2010-05-26 05:41:04 +00001//=== RecordLayoutBuilder.cpp - Helper class for building record layouts ---==//
Anders Carlsson79474332009-07-18 20:20:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Chandler Carruth3a022472012-12-04 09:13:33 +000010#include "clang/AST/RecordLayout.h"
Benjamin Kramer2ef30312012-07-04 18:45:14 +000011#include "clang/AST/ASTContext.h"
Anders Carlsson79474332009-07-18 20:20:21 +000012#include "clang/AST/Attr.h"
Anders Carlsson5adde292010-11-24 22:55:48 +000013#include "clang/AST/CXXInheritance.h"
Anders Carlsson79474332009-07-18 20:20:21 +000014#include "clang/AST/Decl.h"
Anders Carlsson6d9f6f32009-07-19 00:18:47 +000015#include "clang/AST/DeclCXX.h"
Anders Carlsson4f516282009-07-18 20:50:59 +000016#include "clang/AST/DeclObjC.h"
Anders Carlsson79474332009-07-18 20:20:21 +000017#include "clang/AST/Expr.h"
Anders Carlsson79474332009-07-18 20:20:21 +000018#include "clang/Basic/TargetInfo.h"
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +000019#include "clang/Sema/SemaDiagnostic.h"
Daniel Dunbaraa423af2010-04-08 02:59:49 +000020#include "llvm/ADT/SmallSet.h"
Ted Kremenekf75d0892011-03-19 01:00:36 +000021#include "llvm/Support/CrashRecoveryContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "llvm/Support/Format.h"
23#include "llvm/Support/MathExtras.h"
Anders Carlsson79474332009-07-18 20:20:21 +000024
25using namespace clang;
26
Benjamin Kramerc7656cd2010-05-26 09:58:31 +000027namespace {
Anders Carlssonf58de112010-05-26 15:32:58 +000028
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000029/// BaseSubobjectInfo - Represents a single base subobject in a complete class.
30/// For a class hierarchy like
31///
32/// class A { };
33/// class B : A { };
34/// class C : A, B { };
35///
36/// The BaseSubobjectInfo graph for C will have three BaseSubobjectInfo
37/// instances, one for B and two for A.
38///
39/// If a base is virtual, it will only have one BaseSubobjectInfo allocated.
40struct BaseSubobjectInfo {
41 /// Class - The class for this base info.
Anders Carlsson056818f2010-05-28 21:13:31 +000042 const CXXRecordDecl *Class;
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000043
44 /// IsVirtual - Whether the BaseInfo represents a virtual base or not.
Anders Carlsson056818f2010-05-28 21:13:31 +000045 bool IsVirtual;
46
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000047 /// Bases - Information about the base subobjects.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000048 SmallVector<BaseSubobjectInfo*, 4> Bases;
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000049
Anders Carlssone3c24c72010-05-29 17:35:14 +000050 /// PrimaryVirtualBaseInfo - Holds the base info for the primary virtual base
51 /// of this base info (if one exists).
52 BaseSubobjectInfo *PrimaryVirtualBaseInfo;
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000053
54 // FIXME: Document.
55 const BaseSubobjectInfo *Derived;
Anders Carlsson056818f2010-05-28 21:13:31 +000056};
57
Anders Carlssonf58de112010-05-26 15:32:58 +000058/// EmptySubobjectMap - Keeps track of which empty subobjects exist at different
59/// offsets while laying out a C++ class.
60class EmptySubobjectMap {
Jay Foad39c79802011-01-12 09:06:06 +000061 const ASTContext &Context;
Anders Carlsson233e2722010-10-31 21:54:55 +000062 uint64_t CharWidth;
63
Anders Carlssonf58de112010-05-26 15:32:58 +000064 /// Class - The class whose empty entries we're keeping track of.
65 const CXXRecordDecl *Class;
Daniel Dunbar592a85c2010-05-27 02:25:46 +000066
Anders Carlsson439edd12010-05-27 05:41:06 +000067 /// EmptyClassOffsets - A map from offsets to empty record decls.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000068 typedef SmallVector<const CXXRecordDecl *, 1> ClassVectorTy;
Anders Carlssonf8f756d2010-10-31 21:22:43 +000069 typedef llvm::DenseMap<CharUnits, ClassVectorTy> EmptyClassOffsetsMapTy;
Anders Carlsson439edd12010-05-27 05:41:06 +000070 EmptyClassOffsetsMapTy EmptyClassOffsets;
71
Anders Carlssoncc5de092010-06-08 15:56:03 +000072 /// MaxEmptyClassOffset - The highest offset known to contain an empty
73 /// base subobject.
Anders Carlsson725190f2010-10-31 21:39:24 +000074 CharUnits MaxEmptyClassOffset;
Anders Carlssoncc5de092010-06-08 15:56:03 +000075
Daniel Dunbar592a85c2010-05-27 02:25:46 +000076 /// ComputeEmptySubobjectSizes - Compute the size of the largest base or
Anders Carlssonc5ca1f72010-05-26 15:54:25 +000077 /// member subobject that is empty.
78 void ComputeEmptySubobjectSizes();
Anders Carlsson439edd12010-05-27 05:41:06 +000079
Anders Carlsson725190f2010-10-31 21:39:24 +000080 void AddSubobjectAtOffset(const CXXRecordDecl *RD, CharUnits Offset);
Anders Carlssondb319762010-05-27 18:20:57 +000081
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000082 void UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +000083 CharUnits Offset, bool PlacingEmptyBase);
Anders Carlsson439edd12010-05-27 05:41:06 +000084
Anders Carlssondb319762010-05-27 18:20:57 +000085 void UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD,
86 const CXXRecordDecl *Class,
Anders Carlsson28466ab2010-10-31 22:13:23 +000087 CharUnits Offset);
88 void UpdateEmptyFieldSubobjects(const FieldDecl *FD, CharUnits Offset);
Anders Carlssondb319762010-05-27 18:20:57 +000089
Anders Carlssoncc5de092010-06-08 15:56:03 +000090 /// AnyEmptySubobjectsBeyondOffset - Returns whether there are any empty
91 /// subobjects beyond the given offset.
Anders Carlsson725190f2010-10-31 21:39:24 +000092 bool AnyEmptySubobjectsBeyondOffset(CharUnits Offset) const {
Anders Carlssoncc5de092010-06-08 15:56:03 +000093 return Offset <= MaxEmptyClassOffset;
94 }
95
Anders Carlsson233e2722010-10-31 21:54:55 +000096 CharUnits
97 getFieldOffset(const ASTRecordLayout &Layout, unsigned FieldNo) const {
98 uint64_t FieldOffset = Layout.getFieldOffset(FieldNo);
99 assert(FieldOffset % CharWidth == 0 &&
100 "Field offset not at char boundary!");
101
Ken Dyck7c4026b2011-01-24 01:28:50 +0000102 return Context.toCharUnitsFromBits(FieldOffset);
Anders Carlssonf8f756d2010-10-31 21:22:43 +0000103 }
Anders Carlssonf8f756d2010-10-31 21:22:43 +0000104
Charles Davisc2c576a2010-08-19 00:55:19 +0000105protected:
Anders Carlsson725190f2010-10-31 21:39:24 +0000106 bool CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD,
107 CharUnits Offset) const;
Charles Davisc2c576a2010-08-19 00:55:19 +0000108
109 bool CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000110 CharUnits Offset);
Charles Davisc2c576a2010-08-19 00:55:19 +0000111
112 bool CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD,
113 const CXXRecordDecl *Class,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000114 CharUnits Offset) const;
Charles Davisc2c576a2010-08-19 00:55:19 +0000115 bool CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD,
Anders Carlsson233e2722010-10-31 21:54:55 +0000116 CharUnits Offset) const;
Charles Davisc2c576a2010-08-19 00:55:19 +0000117
Anders Carlssonf58de112010-05-26 15:32:58 +0000118public:
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000119 /// This holds the size of the largest empty subobject (either a base
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000120 /// or a member). Will be zero if the record being built doesn't contain
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000121 /// any empty classes.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000122 CharUnits SizeOfLargestEmptySubobject;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000123
Jay Foad39c79802011-01-12 09:06:06 +0000124 EmptySubobjectMap(const ASTContext &Context, const CXXRecordDecl *Class)
Anders Carlsson28466ab2010-10-31 22:13:23 +0000125 : Context(Context), CharWidth(Context.getCharWidth()), Class(Class) {
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000126 ComputeEmptySubobjectSizes();
127 }
128
129 /// CanPlaceBaseAtOffset - Return whether the given base class can be placed
130 /// at the given offset.
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000131 /// Returns false if placing the record will result in two components
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000132 /// (direct or indirect) of the same type having the same offset.
Anders Carlssoncc5de092010-06-08 15:56:03 +0000133 bool CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000134 CharUnits Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000135
136 /// CanPlaceFieldAtOffset - Return whether a field can be placed at the given
137 /// offset.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000138 bool CanPlaceFieldAtOffset(const FieldDecl *FD, CharUnits Offset);
Anders Carlssonf58de112010-05-26 15:32:58 +0000139};
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000140
141void EmptySubobjectMap::ComputeEmptySubobjectSizes() {
142 // Check the bases.
143 for (CXXRecordDecl::base_class_const_iterator I = Class->bases_begin(),
144 E = Class->bases_end(); I != E; ++I) {
145 const CXXRecordDecl *BaseDecl =
146 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
147
Anders Carlsson28466ab2010-10-31 22:13:23 +0000148 CharUnits EmptySize;
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000149 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
150 if (BaseDecl->isEmpty()) {
151 // If the class decl is empty, get its size.
Ken Dyckc8ae5502011-02-09 01:59:34 +0000152 EmptySize = Layout.getSize();
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000153 } else {
154 // Otherwise, we get the largest empty subobject for the decl.
155 EmptySize = Layout.getSizeOfLargestEmptySubobject();
156 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000157
Anders Carlsson28466ab2010-10-31 22:13:23 +0000158 if (EmptySize > SizeOfLargestEmptySubobject)
159 SizeOfLargestEmptySubobject = EmptySize;
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000160 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000161
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000162 // Check the fields.
163 for (CXXRecordDecl::field_iterator I = Class->field_begin(),
164 E = Class->field_end(); I != E; ++I) {
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000165
166 const RecordType *RT =
David Blaikie40ed2972012-06-06 20:45:41 +0000167 Context.getBaseElementType(I->getType())->getAs<RecordType>();
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000168
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000169 // We only care about record types.
170 if (!RT)
171 continue;
172
Anders Carlsson28466ab2010-10-31 22:13:23 +0000173 CharUnits EmptySize;
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000174 const CXXRecordDecl *MemberDecl = cast<CXXRecordDecl>(RT->getDecl());
175 const ASTRecordLayout &Layout = Context.getASTRecordLayout(MemberDecl);
176 if (MemberDecl->isEmpty()) {
177 // If the class decl is empty, get its size.
Ken Dyckc8ae5502011-02-09 01:59:34 +0000178 EmptySize = Layout.getSize();
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000179 } else {
180 // Otherwise, we get the largest empty subobject for the decl.
181 EmptySize = Layout.getSizeOfLargestEmptySubobject();
182 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000183
Anders Carlsson28466ab2010-10-31 22:13:23 +0000184 if (EmptySize > SizeOfLargestEmptySubobject)
185 SizeOfLargestEmptySubobject = EmptySize;
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000186 }
187}
188
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000189bool
Anders Carlssondb319762010-05-27 18:20:57 +0000190EmptySubobjectMap::CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD,
Anders Carlsson725190f2010-10-31 21:39:24 +0000191 CharUnits Offset) const {
Anders Carlssondb319762010-05-27 18:20:57 +0000192 // We only need to check empty bases.
193 if (!RD->isEmpty())
194 return true;
195
Anders Carlsson725190f2010-10-31 21:39:24 +0000196 EmptyClassOffsetsMapTy::const_iterator I = EmptyClassOffsets.find(Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000197 if (I == EmptyClassOffsets.end())
198 return true;
199
200 const ClassVectorTy& Classes = I->second;
201 if (std::find(Classes.begin(), Classes.end(), RD) == Classes.end())
202 return true;
203
204 // There is already an empty class of the same type at this offset.
205 return false;
206}
207
208void EmptySubobjectMap::AddSubobjectAtOffset(const CXXRecordDecl *RD,
Anders Carlsson725190f2010-10-31 21:39:24 +0000209 CharUnits Offset) {
Anders Carlssondb319762010-05-27 18:20:57 +0000210 // We only care about empty bases.
211 if (!RD->isEmpty())
212 return;
213
Reid Kleckner369f3162013-05-14 20:30:42 +0000214 // If we have empty structures inside a union, we can assign both
Rafael Espindola7bcde192010-12-29 23:02:58 +0000215 // the same offset. Just avoid pushing them twice in the list.
Anders Carlsson725190f2010-10-31 21:39:24 +0000216 ClassVectorTy& Classes = EmptyClassOffsets[Offset];
Rafael Espindola7bcde192010-12-29 23:02:58 +0000217 if (std::find(Classes.begin(), Classes.end(), RD) != Classes.end())
218 return;
219
Anders Carlssondb319762010-05-27 18:20:57 +0000220 Classes.push_back(RD);
Anders Carlssoncc5de092010-06-08 15:56:03 +0000221
222 // Update the empty class offset.
Anders Carlsson725190f2010-10-31 21:39:24 +0000223 if (Offset > MaxEmptyClassOffset)
224 MaxEmptyClassOffset = Offset;
Anders Carlssondb319762010-05-27 18:20:57 +0000225}
226
227bool
Anders Carlsson28466ab2010-10-31 22:13:23 +0000228EmptySubobjectMap::CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info,
229 CharUnits Offset) {
Anders Carlsson45c1d282010-06-08 16:20:35 +0000230 // We don't have to keep looking past the maximum offset that's known to
231 // contain an empty class.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000232 if (!AnyEmptySubobjectsBeyondOffset(Offset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000233 return true;
234
Anders Carlsson28466ab2010-10-31 22:13:23 +0000235 if (!CanPlaceSubobjectAtOffset(Info->Class, Offset))
Anders Carlssondb319762010-05-27 18:20:57 +0000236 return false;
237
Anders Carlsson439edd12010-05-27 05:41:06 +0000238 // Traverse all non-virtual bases.
Anders Carlssona7774a62010-05-29 21:10:24 +0000239 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
Anders Carlsson439edd12010-05-27 05:41:06 +0000240 for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) {
Anders Carlssona7f3cdb2010-05-28 21:24:37 +0000241 BaseSubobjectInfo* Base = Info->Bases[I];
Anders Carlsson439edd12010-05-27 05:41:06 +0000242 if (Base->IsVirtual)
243 continue;
244
Anders Carlsson0a14ee92010-11-01 00:21:58 +0000245 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
Anders Carlsson439edd12010-05-27 05:41:06 +0000246
247 if (!CanPlaceBaseSubobjectAtOffset(Base, BaseOffset))
248 return false;
249 }
250
Anders Carlssone3c24c72010-05-29 17:35:14 +0000251 if (Info->PrimaryVirtualBaseInfo) {
252 BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
Anders Carlsson439edd12010-05-27 05:41:06 +0000253
254 if (Info == PrimaryVirtualBaseInfo->Derived) {
255 if (!CanPlaceBaseSubobjectAtOffset(PrimaryVirtualBaseInfo, Offset))
256 return false;
257 }
258 }
259
Anders Carlssondb319762010-05-27 18:20:57 +0000260 // Traverse all member variables.
261 unsigned FieldNo = 0;
262 for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(),
263 E = Info->Class->field_end(); I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +0000264 if (I->isBitField())
Anders Carlsson233e2722010-10-31 21:54:55 +0000265 continue;
266
Anders Carlsson28466ab2010-10-31 22:13:23 +0000267 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
David Blaikie40ed2972012-06-06 20:45:41 +0000268 if (!CanPlaceFieldSubobjectAtOffset(*I, FieldOffset))
Anders Carlssondb319762010-05-27 18:20:57 +0000269 return false;
270 }
271
Anders Carlsson439edd12010-05-27 05:41:06 +0000272 return true;
273}
274
Anders Carlssona7f3cdb2010-05-28 21:24:37 +0000275void EmptySubobjectMap::UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000276 CharUnits Offset,
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000277 bool PlacingEmptyBase) {
278 if (!PlacingEmptyBase && Offset >= SizeOfLargestEmptySubobject) {
279 // We know that the only empty subobjects that can conflict with empty
280 // subobject of non-empty bases, are empty bases that can be placed at
281 // offset zero. Because of this, we only need to keep track of empty base
282 // subobjects with offsets less than the size of the largest empty
283 // subobject for our class.
284 return;
285 }
286
Anders Carlsson28466ab2010-10-31 22:13:23 +0000287 AddSubobjectAtOffset(Info->Class, Offset);
Anders Carlssona7774a62010-05-29 21:10:24 +0000288
Anders Carlsson439edd12010-05-27 05:41:06 +0000289 // Traverse all non-virtual bases.
Anders Carlssona7774a62010-05-29 21:10:24 +0000290 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
Anders Carlsson439edd12010-05-27 05:41:06 +0000291 for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) {
Anders Carlssona7f3cdb2010-05-28 21:24:37 +0000292 BaseSubobjectInfo* Base = Info->Bases[I];
Anders Carlsson439edd12010-05-27 05:41:06 +0000293 if (Base->IsVirtual)
294 continue;
Anders Carlssona7774a62010-05-29 21:10:24 +0000295
Anders Carlsson0a14ee92010-11-01 00:21:58 +0000296 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000297 UpdateEmptyBaseSubobjects(Base, BaseOffset, PlacingEmptyBase);
Anders Carlsson439edd12010-05-27 05:41:06 +0000298 }
299
Anders Carlssone3c24c72010-05-29 17:35:14 +0000300 if (Info->PrimaryVirtualBaseInfo) {
301 BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
Anders Carlsson439edd12010-05-27 05:41:06 +0000302
303 if (Info == PrimaryVirtualBaseInfo->Derived)
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000304 UpdateEmptyBaseSubobjects(PrimaryVirtualBaseInfo, Offset,
305 PlacingEmptyBase);
Anders Carlsson439edd12010-05-27 05:41:06 +0000306 }
Anders Carlssondb319762010-05-27 18:20:57 +0000307
Anders Carlssondb319762010-05-27 18:20:57 +0000308 // Traverse all member variables.
309 unsigned FieldNo = 0;
310 for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(),
311 E = Info->Class->field_end(); I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +0000312 if (I->isBitField())
Anders Carlsson233e2722010-10-31 21:54:55 +0000313 continue;
Anders Carlssona7774a62010-05-29 21:10:24 +0000314
Anders Carlsson28466ab2010-10-31 22:13:23 +0000315 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
David Blaikie40ed2972012-06-06 20:45:41 +0000316 UpdateEmptyFieldSubobjects(*I, FieldOffset);
Anders Carlssondb319762010-05-27 18:20:57 +0000317 }
Anders Carlsson439edd12010-05-27 05:41:06 +0000318}
319
Anders Carlssona60b86a2010-05-29 20:49:49 +0000320bool EmptySubobjectMap::CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000321 CharUnits Offset) {
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000322 // If we know this class doesn't have any empty subobjects we don't need to
323 // bother checking.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000324 if (SizeOfLargestEmptySubobject.isZero())
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000325 return true;
326
Anders Carlsson439edd12010-05-27 05:41:06 +0000327 if (!CanPlaceBaseSubobjectAtOffset(Info, Offset))
328 return false;
Anders Carlssondb319762010-05-27 18:20:57 +0000329
330 // We are able to place the base at this offset. Make sure to update the
331 // empty base subobject map.
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000332 UpdateEmptyBaseSubobjects(Info, Offset, Info->Class->isEmpty());
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000333 return true;
334}
335
Anders Carlssondb319762010-05-27 18:20:57 +0000336bool
337EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD,
338 const CXXRecordDecl *Class,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000339 CharUnits Offset) const {
Anders Carlsson45c1d282010-06-08 16:20:35 +0000340 // We don't have to keep looking past the maximum offset that's known to
341 // contain an empty class.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000342 if (!AnyEmptySubobjectsBeyondOffset(Offset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000343 return true;
344
Anders Carlsson28466ab2010-10-31 22:13:23 +0000345 if (!CanPlaceSubobjectAtOffset(RD, Offset))
Anders Carlssondb319762010-05-27 18:20:57 +0000346 return false;
347
348 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
349
350 // Traverse all non-virtual bases.
351 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
352 E = RD->bases_end(); I != E; ++I) {
353 if (I->isVirtual())
354 continue;
355
356 const CXXRecordDecl *BaseDecl =
357 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
358
Anders Carlsson0a14ee92010-11-01 00:21:58 +0000359 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
Anders Carlssondb319762010-05-27 18:20:57 +0000360 if (!CanPlaceFieldSubobjectAtOffset(BaseDecl, Class, BaseOffset))
361 return false;
362 }
363
Anders Carlsson44687202010-06-08 19:09:24 +0000364 if (RD == Class) {
365 // This is the most derived class, traverse virtual bases as well.
366 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
367 E = RD->vbases_end(); I != E; ++I) {
368 const CXXRecordDecl *VBaseDecl =
369 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
370
Anders Carlsson3f018712010-10-31 23:45:59 +0000371 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
Anders Carlsson44687202010-06-08 19:09:24 +0000372 if (!CanPlaceFieldSubobjectAtOffset(VBaseDecl, Class, VBaseOffset))
373 return false;
374 }
375 }
376
Anders Carlssondb319762010-05-27 18:20:57 +0000377 // Traverse all member variables.
378 unsigned FieldNo = 0;
379 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
380 I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +0000381 if (I->isBitField())
Anders Carlsson233e2722010-10-31 21:54:55 +0000382 continue;
383
Anders Carlsson28466ab2010-10-31 22:13:23 +0000384 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
Anders Carlssondb319762010-05-27 18:20:57 +0000385
David Blaikie40ed2972012-06-06 20:45:41 +0000386 if (!CanPlaceFieldSubobjectAtOffset(*I, FieldOffset))
Anders Carlssondb319762010-05-27 18:20:57 +0000387 return false;
388 }
389
390 return true;
391}
392
Anders Carlsson233e2722010-10-31 21:54:55 +0000393bool
394EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD,
395 CharUnits Offset) const {
Anders Carlsson45c1d282010-06-08 16:20:35 +0000396 // We don't have to keep looking past the maximum offset that's known to
397 // contain an empty class.
Anders Carlsson233e2722010-10-31 21:54:55 +0000398 if (!AnyEmptySubobjectsBeyondOffset(Offset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000399 return true;
400
Anders Carlssondb319762010-05-27 18:20:57 +0000401 QualType T = FD->getType();
402 if (const RecordType *RT = T->getAs<RecordType>()) {
403 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson28466ab2010-10-31 22:13:23 +0000404 return CanPlaceFieldSubobjectAtOffset(RD, RD, Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000405 }
406
407 // If we have an array type we need to look at every element.
408 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
409 QualType ElemTy = Context.getBaseElementType(AT);
410 const RecordType *RT = ElemTy->getAs<RecordType>();
411 if (!RT)
412 return true;
413
414 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
415 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
416
417 uint64_t NumElements = Context.getConstantArrayElementCount(AT);
Anders Carlsson233e2722010-10-31 21:54:55 +0000418 CharUnits ElementOffset = Offset;
Anders Carlssondb319762010-05-27 18:20:57 +0000419 for (uint64_t I = 0; I != NumElements; ++I) {
Anders Carlsson45c1d282010-06-08 16:20:35 +0000420 // We don't have to keep looking past the maximum offset that's known to
421 // contain an empty class.
Anders Carlsson233e2722010-10-31 21:54:55 +0000422 if (!AnyEmptySubobjectsBeyondOffset(ElementOffset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000423 return true;
424
Anders Carlsson28466ab2010-10-31 22:13:23 +0000425 if (!CanPlaceFieldSubobjectAtOffset(RD, RD, ElementOffset))
Anders Carlssondb319762010-05-27 18:20:57 +0000426 return false;
427
Ken Dyckc8ae5502011-02-09 01:59:34 +0000428 ElementOffset += Layout.getSize();
Anders Carlssondb319762010-05-27 18:20:57 +0000429 }
430 }
431
432 return true;
433}
434
435bool
Anders Carlsson28466ab2010-10-31 22:13:23 +0000436EmptySubobjectMap::CanPlaceFieldAtOffset(const FieldDecl *FD,
437 CharUnits Offset) {
438 if (!CanPlaceFieldSubobjectAtOffset(FD, Offset))
Anders Carlssondb319762010-05-27 18:20:57 +0000439 return false;
440
441 // We are able to place the member variable at this offset.
442 // Make sure to update the empty base subobject map.
443 UpdateEmptyFieldSubobjects(FD, Offset);
444 return true;
445}
446
447void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD,
448 const CXXRecordDecl *Class,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000449 CharUnits Offset) {
Anders Carlssonae111dc2010-06-13 17:49:16 +0000450 // We know that the only empty subobjects that can conflict with empty
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000451 // field subobjects are subobjects of empty bases that can be placed at offset
Anders Carlssonae111dc2010-06-13 17:49:16 +0000452 // zero. Because of this, we only need to keep track of empty field
453 // subobjects with offsets less than the size of the largest empty
454 // subobject for our class.
455 if (Offset >= SizeOfLargestEmptySubobject)
456 return;
457
Anders Carlsson28466ab2010-10-31 22:13:23 +0000458 AddSubobjectAtOffset(RD, Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000459
460 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
461
462 // Traverse all non-virtual bases.
463 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
464 E = RD->bases_end(); I != E; ++I) {
465 if (I->isVirtual())
466 continue;
467
468 const CXXRecordDecl *BaseDecl =
469 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
470
Anders Carlsson0a14ee92010-11-01 00:21:58 +0000471 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
Anders Carlssondb319762010-05-27 18:20:57 +0000472 UpdateEmptyFieldSubobjects(BaseDecl, Class, BaseOffset);
473 }
474
Anders Carlsson44687202010-06-08 19:09:24 +0000475 if (RD == Class) {
476 // This is the most derived class, traverse virtual bases as well.
477 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
478 E = RD->vbases_end(); I != E; ++I) {
479 const CXXRecordDecl *VBaseDecl =
480 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
481
Anders Carlsson3f018712010-10-31 23:45:59 +0000482 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
Anders Carlsson44687202010-06-08 19:09:24 +0000483 UpdateEmptyFieldSubobjects(VBaseDecl, Class, VBaseOffset);
484 }
485 }
486
Anders Carlssondb319762010-05-27 18:20:57 +0000487 // Traverse all member variables.
488 unsigned FieldNo = 0;
489 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
490 I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +0000491 if (I->isBitField())
Anders Carlsson09814d32010-11-01 15:14:51 +0000492 continue;
493
Anders Carlsson28466ab2010-10-31 22:13:23 +0000494 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
Anders Carlssondb319762010-05-27 18:20:57 +0000495
David Blaikie40ed2972012-06-06 20:45:41 +0000496 UpdateEmptyFieldSubobjects(*I, FieldOffset);
Anders Carlssondb319762010-05-27 18:20:57 +0000497 }
498}
499
500void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const FieldDecl *FD,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000501 CharUnits Offset) {
Anders Carlssondb319762010-05-27 18:20:57 +0000502 QualType T = FD->getType();
503 if (const RecordType *RT = T->getAs<RecordType>()) {
504 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
505 UpdateEmptyFieldSubobjects(RD, RD, Offset);
506 return;
507 }
508
509 // If we have an array type we need to update every element.
510 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
511 QualType ElemTy = Context.getBaseElementType(AT);
512 const RecordType *RT = ElemTy->getAs<RecordType>();
513 if (!RT)
514 return;
515
516 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
517 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
518
519 uint64_t NumElements = Context.getConstantArrayElementCount(AT);
Anders Carlsson28466ab2010-10-31 22:13:23 +0000520 CharUnits ElementOffset = Offset;
Anders Carlssondb319762010-05-27 18:20:57 +0000521
522 for (uint64_t I = 0; I != NumElements; ++I) {
Anders Carlssonae111dc2010-06-13 17:49:16 +0000523 // We know that the only empty subobjects that can conflict with empty
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000524 // field subobjects are subobjects of empty bases that can be placed at
Anders Carlssonae111dc2010-06-13 17:49:16 +0000525 // offset zero. Because of this, we only need to keep track of empty field
526 // subobjects with offsets less than the size of the largest empty
527 // subobject for our class.
528 if (ElementOffset >= SizeOfLargestEmptySubobject)
529 return;
530
Anders Carlssondb319762010-05-27 18:20:57 +0000531 UpdateEmptyFieldSubobjects(RD, RD, ElementOffset);
Ken Dyckc8ae5502011-02-09 01:59:34 +0000532 ElementOffset += Layout.getSize();
Anders Carlssondb319762010-05-27 18:20:57 +0000533 }
534 }
535}
536
John McCalle42a3362012-05-01 08:55:32 +0000537typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> ClassSetTy;
538
Anders Carlssonc2226202010-05-26 05:58:59 +0000539class RecordLayoutBuilder {
Charles Davisc2c576a2010-08-19 00:55:19 +0000540protected:
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000541 // FIXME: Remove this and make the appropriate fields public.
542 friend class clang::ASTContext;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000543
Jay Foad39c79802011-01-12 09:06:06 +0000544 const ASTContext &Context;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000545
Anders Carlssonf58de112010-05-26 15:32:58 +0000546 EmptySubobjectMap *EmptySubobjects;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000547
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000548 /// Size - The current size of the record layout.
549 uint64_t Size;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000550
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000551 /// Alignment - The current alignment of the record layout.
Ken Dyck4731d5b2011-02-16 02:05:21 +0000552 CharUnits Alignment;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000553
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000554 /// \brief The alignment if attribute packed is not used.
Ken Dyck1300b3b2011-02-16 02:11:31 +0000555 CharUnits UnpackedAlignment;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000556
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000557 SmallVector<uint64_t, 16> FieldOffsets;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000558
Douglas Gregore9fc3772012-01-26 07:55:45 +0000559 /// \brief Whether the external AST source has provided a layout for this
560 /// record.
561 unsigned ExternalLayout : 1;
Douglas Gregor44ba7892012-01-28 00:53:29 +0000562
563 /// \brief Whether we need to infer alignment, even when we have an
564 /// externally-provided layout.
565 unsigned InferAlignment : 1;
Douglas Gregore9fc3772012-01-26 07:55:45 +0000566
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000567 /// Packed - Whether the record is packed or not.
Daniel Dunbar6da10982010-05-27 05:45:51 +0000568 unsigned Packed : 1;
569
570 unsigned IsUnion : 1;
571
572 unsigned IsMac68kAlign : 1;
Fariborz Jahanianbcb23a12011-04-26 23:52:16 +0000573
574 unsigned IsMsStruct : 1;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000575
Eli Friedman2782dac2013-06-26 20:50:34 +0000576 /// UnfilledBitsInLastUnit - If the last field laid out was a bitfield,
577 /// this contains the number of bits in the last unit that can be used for
578 /// an adjacent bitfield if necessary. The unit in question is usually
579 /// a byte, but larger units are used if IsMsStruct.
580 unsigned char UnfilledBitsInLastUnit;
581 /// LastBitfieldTypeSize - If IsMsStruct, represents the size of the type
582 /// of the previous field if it was a bitfield.
583 unsigned char LastBitfieldTypeSize;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000584
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000585 /// MaxFieldAlignment - The maximum allowed field alignment. This is set by
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000586 /// #pragma pack.
Ken Dyck02ced6f2011-02-17 01:49:42 +0000587 CharUnits MaxFieldAlignment;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000588
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000589 /// DataSize - The data size of the record being laid out.
590 uint64_t DataSize;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000591
Ken Dyckaf1c83f2011-02-16 01:52:01 +0000592 CharUnits NonVirtualSize;
Ken Dycka2d3dda2011-02-16 01:43:15 +0000593 CharUnits NonVirtualAlignment;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000594
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000595 /// PrimaryBase - the primary base class (if one exists) of the class
596 /// we're laying out.
597 const CXXRecordDecl *PrimaryBase;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000598
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000599 /// PrimaryBaseIsVirtual - Whether the primary base of the class we're laying
600 /// out is virtual.
601 bool PrimaryBaseIsVirtual;
602
John McCalle42a3362012-05-01 08:55:32 +0000603 /// HasOwnVFPtr - Whether the class provides its own vtable/vftbl
604 /// pointer, as opposed to inheriting one from a primary base class.
605 bool HasOwnVFPtr;
Eli Friedman43114f92011-10-21 22:49:56 +0000606
Anders Carlsson22f57202010-10-31 21:01:46 +0000607 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000608
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000609 /// Bases - base classes and their offsets in the record.
610 BaseOffsetsMapTy Bases;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000611
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000612 // VBases - virtual base classes and their offsets in the record.
John McCalle42a3362012-05-01 08:55:32 +0000613 ASTRecordLayout::VBaseOffsetsMapTy VBases;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000614
615 /// IndirectPrimaryBases - Virtual base classes, direct or indirect, that are
616 /// primary base classes for some other direct or indirect base class.
Anders Carlsson5adde292010-11-24 22:55:48 +0000617 CXXIndirectPrimaryBaseSet IndirectPrimaryBases;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000618
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000619 /// FirstNearlyEmptyVBase - The first nearly empty virtual base class in
620 /// inheritance graph order. Used for determining the primary base class.
621 const CXXRecordDecl *FirstNearlyEmptyVBase;
622
623 /// VisitedVirtualBases - A set of all the visited virtual bases, used to
624 /// avoid visiting virtual bases more than once.
625 llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000626
Douglas Gregore9fc3772012-01-26 07:55:45 +0000627 /// \brief Externally-provided size.
628 uint64_t ExternalSize;
629
630 /// \brief Externally-provided alignment.
631 uint64_t ExternalAlign;
632
633 /// \brief Externally-provided field offsets.
634 llvm::DenseMap<const FieldDecl *, uint64_t> ExternalFieldOffsets;
635
636 /// \brief Externally-provided direct, non-virtual base offsets.
637 llvm::DenseMap<const CXXRecordDecl *, CharUnits> ExternalBaseOffsets;
638
639 /// \brief Externally-provided virtual base offsets.
640 llvm::DenseMap<const CXXRecordDecl *, CharUnits> ExternalVirtualBaseOffsets;
641
John McCall0153cd32011-11-08 04:01:03 +0000642 RecordLayoutBuilder(const ASTContext &Context,
643 EmptySubobjectMap *EmptySubobjects)
Ken Dyck4731d5b2011-02-16 02:05:21 +0000644 : Context(Context), EmptySubobjects(EmptySubobjects), Size(0),
John McCall0153cd32011-11-08 04:01:03 +0000645 Alignment(CharUnits::One()), UnpackedAlignment(CharUnits::One()),
Douglas Gregor44ba7892012-01-28 00:53:29 +0000646 ExternalLayout(false), InferAlignment(false),
647 Packed(false), IsUnion(false), IsMac68kAlign(false), IsMsStruct(false),
Eli Friedman2782dac2013-06-26 20:50:34 +0000648 UnfilledBitsInLastUnit(0), LastBitfieldTypeSize(0),
649 MaxFieldAlignment(CharUnits::Zero()),
Ken Dyck02ced6f2011-02-17 01:49:42 +0000650 DataSize(0), NonVirtualSize(CharUnits::Zero()),
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000651 NonVirtualAlignment(CharUnits::One()),
Eli Friedman481673f2013-06-26 23:47:39 +0000652 PrimaryBase(0), PrimaryBaseIsVirtual(false),
John McCalle42a3362012-05-01 08:55:32 +0000653 HasOwnVFPtr(false),
Eli Friedman84d2d3a2011-09-27 19:12:27 +0000654 FirstNearlyEmptyVBase(0) { }
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000655
John McCall0153cd32011-11-08 04:01:03 +0000656 /// Reset this RecordLayoutBuilder to a fresh state, using the given
657 /// alignment as the initial alignment. This is used for the
658 /// correct layout of vb-table pointers in MSVC.
659 void resetWithTargetAlignment(CharUnits TargetAlignment) {
660 const ASTContext &Context = this->Context;
661 EmptySubobjectMap *EmptySubobjects = this->EmptySubobjects;
662 this->~RecordLayoutBuilder();
663 new (this) RecordLayoutBuilder(Context, EmptySubobjects);
664 Alignment = UnpackedAlignment = TargetAlignment;
665 }
666
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000667 void Layout(const RecordDecl *D);
Anders Carlssonc28a6c92010-05-26 15:10:00 +0000668 void Layout(const CXXRecordDecl *D);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000669 void Layout(const ObjCInterfaceDecl *D);
670
671 void LayoutFields(const RecordDecl *D);
672 void LayoutField(const FieldDecl *D);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000673 void LayoutWideBitField(uint64_t FieldSize, uint64_t TypeSize,
674 bool FieldPacked, const FieldDecl *D);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000675 void LayoutBitField(const FieldDecl *D);
John McCall0153cd32011-11-08 04:01:03 +0000676
John McCall359b8852013-01-25 22:30:49 +0000677 TargetCXXABI getCXXABI() const {
678 return Context.getTargetInfo().getCXXABI();
679 }
680
Anders Carlssone3c24c72010-05-29 17:35:14 +0000681 /// BaseSubobjectInfoAllocator - Allocator for BaseSubobjectInfo objects.
682 llvm::SpecificBumpPtrAllocator<BaseSubobjectInfo> BaseSubobjectInfoAllocator;
683
684 typedef llvm::DenseMap<const CXXRecordDecl *, BaseSubobjectInfo *>
685 BaseSubobjectInfoMapTy;
686
687 /// VirtualBaseInfo - Map from all the (direct or indirect) virtual bases
688 /// of the class we're laying out to their base subobject info.
689 BaseSubobjectInfoMapTy VirtualBaseInfo;
690
691 /// NonVirtualBaseInfo - Map from all the direct non-virtual bases of the
692 /// class we're laying out to their base subobject info.
693 BaseSubobjectInfoMapTy NonVirtualBaseInfo;
694
695 /// ComputeBaseSubobjectInfo - Compute the base subobject information for the
696 /// bases of the given class.
697 void ComputeBaseSubobjectInfo(const CXXRecordDecl *RD);
698
699 /// ComputeBaseSubobjectInfo - Compute the base subobject information for a
700 /// single class and all of its base classes.
701 BaseSubobjectInfo *ComputeBaseSubobjectInfo(const CXXRecordDecl *RD,
702 bool IsVirtual,
703 BaseSubobjectInfo *Derived);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000704
705 /// DeterminePrimaryBase - Determine the primary base of the given class.
706 void DeterminePrimaryBase(const CXXRecordDecl *RD);
707
708 void SelectPrimaryVBase(const CXXRecordDecl *RD);
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000709
Eli Friedman43114f92011-10-21 22:49:56 +0000710 void EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign);
Charles Davisc2c576a2010-08-19 00:55:19 +0000711
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000712 /// LayoutNonVirtualBases - Determines the primary base class (if any) and
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000713 /// lays it out. Will then proceed to lay out all non-virtual base clasess.
714 void LayoutNonVirtualBases(const CXXRecordDecl *RD);
715
716 /// LayoutNonVirtualBase - Lays out a single non-virtual base.
Anders Carlssonbb0e6782010-05-29 17:42:25 +0000717 void LayoutNonVirtualBase(const BaseSubobjectInfo *Base);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000718
Anders Carlssona2f8e412010-10-31 22:20:42 +0000719 void AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
720 CharUnits Offset);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000721
722 /// LayoutVirtualBases - Lays out all the virtual bases.
723 void LayoutVirtualBases(const CXXRecordDecl *RD,
724 const CXXRecordDecl *MostDerivedClass);
725
726 /// LayoutVirtualBase - Lays out a single virtual base.
Warren Hunt55d8e822013-10-23 23:53:07 +0000727 void LayoutVirtualBase(const BaseSubobjectInfo *Base);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000728
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000729 /// LayoutBase - Will lay out a base and return the offset where it was
Anders Carlssona2f8e412010-10-31 22:20:42 +0000730 /// placed, in chars.
731 CharUnits LayoutBase(const BaseSubobjectInfo *Base);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000732
Anders Carlssonc28a6c92010-05-26 15:10:00 +0000733 /// InitializeLayout - Initialize record layout for the given record decl.
Daniel Dunbar6da10982010-05-27 05:45:51 +0000734 void InitializeLayout(const Decl *D);
Anders Carlssonc28a6c92010-05-26 15:10:00 +0000735
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000736 /// FinishLayout - Finalize record layout. Adjust record size based on the
737 /// alignment.
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000738 void FinishLayout(const NamedDecl *D);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000739
Ken Dyck85ef0432011-02-19 18:58:07 +0000740 void UpdateAlignment(CharUnits NewAlignment, CharUnits UnpackedNewAlignment);
741 void UpdateAlignment(CharUnits NewAlignment) {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000742 UpdateAlignment(NewAlignment, NewAlignment);
743 }
744
Douglas Gregor44ba7892012-01-28 00:53:29 +0000745 /// \brief Retrieve the externally-supplied field offset for the given
746 /// field.
747 ///
748 /// \param Field The field whose offset is being queried.
749 /// \param ComputedOffset The offset that we've computed for this field.
750 uint64_t updateExternalFieldOffset(const FieldDecl *Field,
751 uint64_t ComputedOffset);
752
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000753 void CheckFieldPadding(uint64_t Offset, uint64_t UnpaddedOffset,
754 uint64_t UnpackedOffset, unsigned UnpackedAlign,
755 bool isPacked, const FieldDecl *D);
756
757 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000758
Ken Dyckecfc7552011-02-24 01:13:28 +0000759 CharUnits getSize() const {
Ken Dyck3c215f22011-02-24 01:33:05 +0000760 assert(Size % Context.getCharWidth() == 0);
Ken Dyckecfc7552011-02-24 01:13:28 +0000761 return Context.toCharUnitsFromBits(Size);
762 }
763 uint64_t getSizeInBits() const { return Size; }
764
765 void setSize(CharUnits NewSize) { Size = Context.toBits(NewSize); }
766 void setSize(uint64_t NewSize) { Size = NewSize; }
767
Eli Friedman84d2d3a2011-09-27 19:12:27 +0000768 CharUnits getAligment() const { return Alignment; }
769
Ken Dyckecfc7552011-02-24 01:13:28 +0000770 CharUnits getDataSize() const {
Ken Dyck3c215f22011-02-24 01:33:05 +0000771 assert(DataSize % Context.getCharWidth() == 0);
Ken Dyckecfc7552011-02-24 01:13:28 +0000772 return Context.toCharUnitsFromBits(DataSize);
773 }
774 uint64_t getDataSizeInBits() const { return DataSize; }
775
776 void setDataSize(CharUnits NewSize) { DataSize = Context.toBits(NewSize); }
777 void setDataSize(uint64_t NewSize) { DataSize = NewSize; }
778
Dmitri Gribenkoa664e5b2012-09-15 20:20:27 +0000779 RecordLayoutBuilder(const RecordLayoutBuilder &) LLVM_DELETED_FUNCTION;
780 void operator=(const RecordLayoutBuilder &) LLVM_DELETED_FUNCTION;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000781};
Benjamin Kramerc7656cd2010-05-26 09:58:31 +0000782} // end anonymous namespace
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000783
Anders Carlsson81430692009-09-22 03:02:06 +0000784void
Anders Carlssonc2226202010-05-26 05:58:59 +0000785RecordLayoutBuilder::SelectPrimaryVBase(const CXXRecordDecl *RD) {
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000786 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000787 E = RD->bases_end(); I != E; ++I) {
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000788 assert(!I->getType()->isDependentType() &&
Sebastian Redl1054fae2009-10-25 17:03:50 +0000789 "Cannot layout class with dependent bases.");
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000790
Mike Stump11289f42009-09-09 15:08:12 +0000791 const CXXRecordDecl *Base =
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000792 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000793
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000794 // Check if this is a nearly empty virtual base.
Anders Carlsson60a62632010-11-25 01:51:53 +0000795 if (I->isVirtual() && Context.isNearlyEmpty(Base)) {
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000796 // If it's not an indirect primary base, then we've found our primary
797 // base.
Anders Carlsson81430692009-09-22 03:02:06 +0000798 if (!IndirectPrimaryBases.count(Base)) {
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000799 PrimaryBase = Base;
800 PrimaryBaseIsVirtual = true;
Mike Stump6f3793b2009-08-12 21:50:08 +0000801 return;
802 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000803
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000804 // Is this the first nearly empty virtual base?
805 if (!FirstNearlyEmptyVBase)
806 FirstNearlyEmptyVBase = Base;
Mike Stump6f3793b2009-08-12 21:50:08 +0000807 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000808
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000809 SelectPrimaryVBase(Base);
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000810 if (PrimaryBase)
Zhongxing Xuec345b72010-02-15 04:28:35 +0000811 return;
Mike Stump6f3793b2009-08-12 21:50:08 +0000812 }
813}
814
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000815/// DeterminePrimaryBase - Determine the primary base of the given class.
Anders Carlssonc2226202010-05-26 05:58:59 +0000816void RecordLayoutBuilder::DeterminePrimaryBase(const CXXRecordDecl *RD) {
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000817 // If the class isn't dynamic, it won't have a primary base.
818 if (!RD->isDynamicClass())
819 return;
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000820
Anders Carlsson81430692009-09-22 03:02:06 +0000821 // Compute all the primary virtual bases for all of our direct and
Mike Stump590a7c72009-08-13 23:26:06 +0000822 // indirect bases, and record all their primary virtual base classes.
Anders Carlsson5adde292010-11-24 22:55:48 +0000823 RD->getIndirectPrimaryBases(IndirectPrimaryBases);
Mike Stump590a7c72009-08-13 23:26:06 +0000824
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000825 // If the record has a dynamic base class, attempt to choose a primary base
826 // class. It is the first (in direct base class order) non-virtual dynamic
Anders Carlsson81430692009-09-22 03:02:06 +0000827 // base class, if one exists.
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000828 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000829 e = RD->bases_end(); i != e; ++i) {
Anders Carlsson03ff3792009-11-27 22:05:05 +0000830 // Ignore virtual bases.
831 if (i->isVirtual())
832 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000833
Anders Carlsson03ff3792009-11-27 22:05:05 +0000834 const CXXRecordDecl *Base =
835 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
836
Warren Hunt55d8e822013-10-23 23:53:07 +0000837 if (Base->isDynamicClass()) {
Anders Carlsson03ff3792009-11-27 22:05:05 +0000838 // We found it.
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000839 PrimaryBase = Base;
840 PrimaryBaseIsVirtual = false;
Anders Carlsson03ff3792009-11-27 22:05:05 +0000841 return;
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000842 }
843 }
844
Eli Friedman5e9534b2011-10-18 00:55:28 +0000845 // Under the Itanium ABI, if there is no non-virtual primary base class,
846 // try to compute the primary virtual base. The primary virtual base is
847 // the first nearly empty virtual base that is not an indirect primary
848 // virtual base class, if one exists.
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000849 if (RD->getNumVBases() != 0) {
850 SelectPrimaryVBase(RD);
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000851 if (PrimaryBase)
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000852 return;
853 }
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000854
Eli Friedman5e9534b2011-10-18 00:55:28 +0000855 // Otherwise, it is the first indirect primary base class, if one exists.
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000856 if (FirstNearlyEmptyVBase) {
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000857 PrimaryBase = FirstNearlyEmptyVBase;
858 PrimaryBaseIsVirtual = true;
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000859 return;
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000860 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000861
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000862 assert(!PrimaryBase && "Should not get here with a primary base!");
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000863}
864
Anders Carlssone3c24c72010-05-29 17:35:14 +0000865BaseSubobjectInfo *
866RecordLayoutBuilder::ComputeBaseSubobjectInfo(const CXXRecordDecl *RD,
867 bool IsVirtual,
868 BaseSubobjectInfo *Derived) {
869 BaseSubobjectInfo *Info;
870
871 if (IsVirtual) {
872 // Check if we already have info about this virtual base.
873 BaseSubobjectInfo *&InfoSlot = VirtualBaseInfo[RD];
874 if (InfoSlot) {
875 assert(InfoSlot->Class == RD && "Wrong class for virtual base info!");
876 return InfoSlot;
877 }
878
879 // We don't, create it.
880 InfoSlot = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
881 Info = InfoSlot;
882 } else {
883 Info = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
884 }
885
886 Info->Class = RD;
887 Info->IsVirtual = IsVirtual;
888 Info->Derived = 0;
889 Info->PrimaryVirtualBaseInfo = 0;
890
891 const CXXRecordDecl *PrimaryVirtualBase = 0;
892 BaseSubobjectInfo *PrimaryVirtualBaseInfo = 0;
893
894 // Check if this base has a primary virtual base.
895 if (RD->getNumVBases()) {
896 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Anders Carlsson7f95cd12010-11-24 23:12:57 +0000897 if (Layout.isPrimaryBaseVirtual()) {
Anders Carlssone3c24c72010-05-29 17:35:14 +0000898 // This base does have a primary virtual base.
899 PrimaryVirtualBase = Layout.getPrimaryBase();
900 assert(PrimaryVirtualBase && "Didn't have a primary virtual base!");
901
902 // Now check if we have base subobject info about this primary base.
903 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
904
905 if (PrimaryVirtualBaseInfo) {
906 if (PrimaryVirtualBaseInfo->Derived) {
907 // We did have info about this primary base, and it turns out that it
908 // has already been claimed as a primary virtual base for another
909 // base.
910 PrimaryVirtualBase = 0;
911 } else {
912 // We can claim this base as our primary base.
913 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
914 PrimaryVirtualBaseInfo->Derived = Info;
915 }
916 }
917 }
918 }
919
920 // Now go through all direct bases.
921 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
922 E = RD->bases_end(); I != E; ++I) {
923 bool IsVirtual = I->isVirtual();
924
925 const CXXRecordDecl *BaseDecl =
926 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
927
928 Info->Bases.push_back(ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, Info));
929 }
930
931 if (PrimaryVirtualBase && !PrimaryVirtualBaseInfo) {
932 // Traversing the bases must have created the base info for our primary
933 // virtual base.
934 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
935 assert(PrimaryVirtualBaseInfo &&
936 "Did not create a primary virtual base!");
937
938 // Claim the primary virtual base as our primary virtual base.
939 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
940 PrimaryVirtualBaseInfo->Derived = Info;
941 }
942
943 return Info;
944}
945
946void RecordLayoutBuilder::ComputeBaseSubobjectInfo(const CXXRecordDecl *RD) {
947 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
948 E = RD->bases_end(); I != E; ++I) {
949 bool IsVirtual = I->isVirtual();
950
951 const CXXRecordDecl *BaseDecl =
952 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
953
954 // Compute the base subobject info for this base.
955 BaseSubobjectInfo *Info = ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, 0);
956
957 if (IsVirtual) {
958 // ComputeBaseInfo has already added this base for us.
959 assert(VirtualBaseInfo.count(BaseDecl) &&
960 "Did not add virtual base!");
961 } else {
962 // Add the base info to the map of non-virtual bases.
963 assert(!NonVirtualBaseInfo.count(BaseDecl) &&
964 "Non-virtual base already exists!");
965 NonVirtualBaseInfo.insert(std::make_pair(BaseDecl, Info));
966 }
967 }
968}
969
Anders Carlsson09ffa322010-03-10 22:21:28 +0000970void
Eli Friedman43114f92011-10-21 22:49:56 +0000971RecordLayoutBuilder::EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign) {
Eli Friedman5e9534b2011-10-18 00:55:28 +0000972 CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
973
974 // The maximum field alignment overrides base align.
975 if (!MaxFieldAlignment.isZero()) {
976 BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
977 UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
978 }
979
980 // Round up the current record size to pointer alignment.
Eli Friedman43114f92011-10-21 22:49:56 +0000981 setSize(getSize().RoundUpToAlignment(BaseAlign));
982 setDataSize(getSize());
Eli Friedman5e9534b2011-10-18 00:55:28 +0000983
984 // Update the alignment.
985 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
986}
987
988void
Anders Carlssonc2226202010-05-26 05:58:59 +0000989RecordLayoutBuilder::LayoutNonVirtualBases(const CXXRecordDecl *RD) {
Anders Carlssone3c24c72010-05-29 17:35:14 +0000990 // Then, determine the primary base class.
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000991 DeterminePrimaryBase(RD);
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000992
Anders Carlssone3c24c72010-05-29 17:35:14 +0000993 // Compute base subobject info.
994 ComputeBaseSubobjectInfo(RD);
995
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000996 // If we have a primary base class, lay it out.
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000997 if (PrimaryBase) {
998 if (PrimaryBaseIsVirtual) {
Anders Carlssone3c24c72010-05-29 17:35:14 +0000999 // If the primary virtual base was a primary virtual base of some other
1000 // base class we'll have to steal it.
1001 BaseSubobjectInfo *PrimaryBaseInfo = VirtualBaseInfo.lookup(PrimaryBase);
1002 PrimaryBaseInfo->Derived = 0;
1003
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001004 // We have a virtual primary base, insert it as an indirect primary base.
Anders Carlssond20e7cd2010-05-26 05:20:58 +00001005 IndirectPrimaryBases.insert(PrimaryBase);
Anders Carlssonfe900962010-03-11 05:42:17 +00001006
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001007 assert(!VisitedVirtualBases.count(PrimaryBase) &&
Anders Carlssond20e7cd2010-05-26 05:20:58 +00001008 "vbase already visited!");
1009 VisitedVirtualBases.insert(PrimaryBase);
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001010
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001011 LayoutVirtualBase(PrimaryBaseInfo);
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001012 } else {
1013 BaseSubobjectInfo *PrimaryBaseInfo =
1014 NonVirtualBaseInfo.lookup(PrimaryBase);
1015 assert(PrimaryBaseInfo &&
1016 "Did not find base info for non-virtual primary base!");
1017
1018 LayoutNonVirtualBase(PrimaryBaseInfo);
1019 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001020
John McCall0153cd32011-11-08 04:01:03 +00001021 // If this class needs a vtable/vf-table and didn't get one from a
1022 // primary base, add it in now.
Warren Hunt55d8e822013-10-23 23:53:07 +00001023 } else if (RD->isDynamicClass()) {
Eli Friedman5e9534b2011-10-18 00:55:28 +00001024 assert(DataSize == 0 && "Vtable pointer must be at offset zero!");
Eli Friedman5e9534b2011-10-18 00:55:28 +00001025 CharUnits PtrWidth =
1026 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Eli Friedman43114f92011-10-21 22:49:56 +00001027 CharUnits PtrAlign =
1028 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0));
1029 EnsureVTablePointerAlignment(PtrAlign);
John McCalle42a3362012-05-01 08:55:32 +00001030 HasOwnVFPtr = true;
Eli Friedman5e9534b2011-10-18 00:55:28 +00001031 setSize(getSize() + PtrWidth);
1032 setDataSize(getSize());
1033 }
1034
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001035 // Now lay out the non-virtual bases.
1036 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001037 E = RD->bases_end(); I != E; ++I) {
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001038
Benjamin Kramer273670a2013-10-25 07:40:50 +00001039 // Ignore virtual bases.
1040 if (I->isVirtual())
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001041 continue;
1042
Reid Klecknere7106c92013-12-18 23:17:05 +00001043 const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001044
John McCall0153cd32011-11-08 04:01:03 +00001045 // Skip the primary base, because we've already laid it out. The
1046 // !PrimaryBaseIsVirtual check is required because we might have a
1047 // non-virtual base of the same type as a primary virtual base.
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001048 if (BaseDecl == PrimaryBase && !PrimaryBaseIsVirtual)
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001049 continue;
1050
1051 // Lay out the base.
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001052 BaseSubobjectInfo *BaseInfo = NonVirtualBaseInfo.lookup(BaseDecl);
1053 assert(BaseInfo && "Did not find base info for non-virtual base!");
1054
1055 LayoutNonVirtualBase(BaseInfo);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001056 }
1057}
1058
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001059void RecordLayoutBuilder::LayoutNonVirtualBase(const BaseSubobjectInfo *Base) {
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001060 // Layout the base.
Anders Carlssona2f8e412010-10-31 22:20:42 +00001061 CharUnits Offset = LayoutBase(Base);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001062
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001063 // Add its base class offset.
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001064 assert(!Bases.count(Base->Class) && "base offset already exists!");
Anders Carlssona2f8e412010-10-31 22:20:42 +00001065 Bases.insert(std::make_pair(Base->Class, Offset));
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001066
1067 AddPrimaryVirtualBaseOffsets(Base, Offset);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001068}
Mike Stump2b84dd32009-11-05 04:02:15 +00001069
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001070void
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001071RecordLayoutBuilder::AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
Anders Carlssona2f8e412010-10-31 22:20:42 +00001072 CharUnits Offset) {
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001073 // This base isn't interesting, it has no virtual bases.
1074 if (!Info->Class->getNumVBases())
1075 return;
1076
1077 // First, check if we have a virtual primary base to add offsets for.
1078 if (Info->PrimaryVirtualBaseInfo) {
1079 assert(Info->PrimaryVirtualBaseInfo->IsVirtual &&
1080 "Primary virtual base is not virtual!");
1081 if (Info->PrimaryVirtualBaseInfo->Derived == Info) {
1082 // Add the offset.
1083 assert(!VBases.count(Info->PrimaryVirtualBaseInfo->Class) &&
1084 "primary vbase offset already exists!");
1085 VBases.insert(std::make_pair(Info->PrimaryVirtualBaseInfo->Class,
John McCalle42a3362012-05-01 08:55:32 +00001086 ASTRecordLayout::VBaseInfo(Offset, false)));
Anders Carlssonea7b1822010-04-15 16:12:58 +00001087
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001088 // Traverse the primary virtual base.
1089 AddPrimaryVirtualBaseOffsets(Info->PrimaryVirtualBaseInfo, Offset);
1090 }
Anders Carlssonea7b1822010-04-15 16:12:58 +00001091 }
1092
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001093 // Now go through all direct non-virtual bases.
1094 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
1095 for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) {
1096 const BaseSubobjectInfo *Base = Info->Bases[I];
1097 if (Base->IsVirtual)
Anders Carlssonea7b1822010-04-15 16:12:58 +00001098 continue;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001099
Anders Carlsson0a14ee92010-11-01 00:21:58 +00001100 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001101 AddPrimaryVirtualBaseOffsets(Base, BaseOffset);
Anders Carlssonea7b1822010-04-15 16:12:58 +00001102 }
1103}
1104
1105void
Anders Carlssonc2226202010-05-26 05:58:59 +00001106RecordLayoutBuilder::LayoutVirtualBases(const CXXRecordDecl *RD,
Anders Carlssonea7b1822010-04-15 16:12:58 +00001107 const CXXRecordDecl *MostDerivedClass) {
Anders Carlssonde710c92010-03-11 04:33:54 +00001108 const CXXRecordDecl *PrimaryBase;
Anders Carlsson291279e2010-04-10 18:42:27 +00001109 bool PrimaryBaseIsVirtual;
Anders Carlssonfe900962010-03-11 05:42:17 +00001110
Anders Carlsson291279e2010-04-10 18:42:27 +00001111 if (MostDerivedClass == RD) {
Anders Carlssond20e7cd2010-05-26 05:20:58 +00001112 PrimaryBase = this->PrimaryBase;
1113 PrimaryBaseIsVirtual = this->PrimaryBaseIsVirtual;
Anders Carlsson291279e2010-04-10 18:42:27 +00001114 } else {
Anders Carlsson5efc56e2010-04-16 15:07:51 +00001115 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Anders Carlssonde710c92010-03-11 04:33:54 +00001116 PrimaryBase = Layout.getPrimaryBase();
Anders Carlsson7f95cd12010-11-24 23:12:57 +00001117 PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
Anders Carlsson291279e2010-04-10 18:42:27 +00001118 }
1119
Anders Carlssonf7b7a1e2010-03-11 04:24:02 +00001120 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1121 E = RD->bases_end(); I != E; ++I) {
1122 assert(!I->getType()->isDependentType() &&
Sebastian Redl1054fae2009-10-25 17:03:50 +00001123 "Cannot layout class with dependent bases.");
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001124
Reid Klecknere7106c92013-12-18 23:17:05 +00001125 const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
Anders Carlssonf7b7a1e2010-03-11 04:24:02 +00001126
1127 if (I->isVirtual()) {
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001128 if (PrimaryBase != BaseDecl || !PrimaryBaseIsVirtual) {
1129 bool IndirectPrimaryBase = IndirectPrimaryBases.count(BaseDecl);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001130
Anders Carlsson291279e2010-04-10 18:42:27 +00001131 // Only lay out the virtual base if it's not an indirect primary base.
1132 if (!IndirectPrimaryBase) {
1133 // Only visit virtual bases once.
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001134 if (!VisitedVirtualBases.insert(BaseDecl))
Anders Carlsson291279e2010-04-10 18:42:27 +00001135 continue;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001136
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001137 const BaseSubobjectInfo *BaseInfo = VirtualBaseInfo.lookup(BaseDecl);
1138 assert(BaseInfo && "Did not find virtual base info!");
1139 LayoutVirtualBase(BaseInfo);
Anders Carlsson6a848892010-03-11 04:10:39 +00001140 }
Mike Stump2b84dd32009-11-05 04:02:15 +00001141 }
Mike Stumpc2f591b2009-08-13 22:53:07 +00001142 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001143
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001144 if (!BaseDecl->getNumVBases()) {
Anders Carlssonf7b7a1e2010-03-11 04:24:02 +00001145 // This base isn't interesting since it doesn't have any virtual bases.
1146 continue;
Mike Stump996576f32009-08-16 19:04:13 +00001147 }
Anders Carlssonf7b7a1e2010-03-11 04:24:02 +00001148
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001149 LayoutVirtualBases(BaseDecl, MostDerivedClass);
Mike Stump6b2556f2009-08-06 13:41:24 +00001150 }
1151}
1152
Warren Hunt55d8e822013-10-23 23:53:07 +00001153void RecordLayoutBuilder::LayoutVirtualBase(const BaseSubobjectInfo *Base) {
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001154 assert(!Base->Derived && "Trying to lay out a primary virtual base!");
1155
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001156 // Layout the base.
Anders Carlssona2f8e412010-10-31 22:20:42 +00001157 CharUnits Offset = LayoutBase(Base);
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001158
1159 // Add its base class offset.
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001160 assert(!VBases.count(Base->Class) && "vbase offset already exists!");
John McCalle42a3362012-05-01 08:55:32 +00001161 VBases.insert(std::make_pair(Base->Class,
Warren Hunt55d8e822013-10-23 23:53:07 +00001162 ASTRecordLayout::VBaseInfo(Offset, false)));
John McCalle42a3362012-05-01 08:55:32 +00001163
Warren Hunt55d8e822013-10-23 23:53:07 +00001164 AddPrimaryVirtualBaseOffsets(Base, Offset);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001165}
1166
Anders Carlssona2f8e412010-10-31 22:20:42 +00001167CharUnits RecordLayoutBuilder::LayoutBase(const BaseSubobjectInfo *Base) {
Anders Carlssond7f3fcf2010-05-29 20:47:33 +00001168 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base->Class);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001169
Douglas Gregore9fc3772012-01-26 07:55:45 +00001170
1171 CharUnits Offset;
1172
1173 // Query the external layout to see if it provides an offset.
1174 bool HasExternalLayout = false;
1175 if (ExternalLayout) {
1176 llvm::DenseMap<const CXXRecordDecl *, CharUnits>::iterator Known;
1177 if (Base->IsVirtual) {
1178 Known = ExternalVirtualBaseOffsets.find(Base->Class);
1179 if (Known != ExternalVirtualBaseOffsets.end()) {
1180 Offset = Known->second;
1181 HasExternalLayout = true;
1182 }
1183 } else {
1184 Known = ExternalBaseOffsets.find(Base->Class);
1185 if (Known != ExternalBaseOffsets.end()) {
1186 Offset = Known->second;
1187 HasExternalLayout = true;
1188 }
1189 }
1190 }
1191
Warren Huntd640d7d2014-01-09 00:30:56 +00001192 CharUnits UnpackedBaseAlign = Layout.getNonVirtualAlignment();
Eli Friedman69d27d22013-07-16 00:21:28 +00001193 CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
1194
Anders Carlsson09ffa322010-03-10 22:21:28 +00001195 // If we have an empty base class, try to place it at offset 0.
Anders Carlssond7f3fcf2010-05-29 20:47:33 +00001196 if (Base->Class->isEmpty() &&
Douglas Gregore9fc3772012-01-26 07:55:45 +00001197 (!HasExternalLayout || Offset == CharUnits::Zero()) &&
Anders Carlsson28466ab2010-10-31 22:13:23 +00001198 EmptySubobjects->CanPlaceBaseAtOffset(Base, CharUnits::Zero())) {
Ken Dyck1b4420e2011-02-28 02:01:38 +00001199 setSize(std::max(getSize(), Layout.getSize()));
Eli Friedman69d27d22013-07-16 00:21:28 +00001200 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001201
Anders Carlssona2f8e412010-10-31 22:20:42 +00001202 return CharUnits::Zero();
Anders Carlsson09ffa322010-03-10 22:21:28 +00001203 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001204
Argyrios Kyrtzidis8b542742010-12-09 00:35:20 +00001205 // The maximum field alignment overrides base align.
Ken Dyck02ced6f2011-02-17 01:49:42 +00001206 if (!MaxFieldAlignment.isZero()) {
Ken Dyck85ef0432011-02-19 18:58:07 +00001207 BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
1208 UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
Argyrios Kyrtzidis8b542742010-12-09 00:35:20 +00001209 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001210
Douglas Gregore9fc3772012-01-26 07:55:45 +00001211 if (!HasExternalLayout) {
1212 // Round up the current record size to the base's alignment boundary.
1213 Offset = getDataSize().RoundUpToAlignment(BaseAlign);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001214
Douglas Gregore9fc3772012-01-26 07:55:45 +00001215 // Try to place the base.
1216 while (!EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset))
1217 Offset += BaseAlign;
1218 } else {
1219 bool Allowed = EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset);
1220 (void)Allowed;
1221 assert(Allowed && "Base subobject externally placed at overlapping offset");
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001222
1223 if (InferAlignment && Offset < getDataSize().RoundUpToAlignment(BaseAlign)){
1224 // The externally-supplied base offset is before the base offset we
1225 // computed. Assume that the structure is packed.
1226 Alignment = CharUnits::One();
1227 InferAlignment = false;
1228 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00001229 }
1230
Anders Carlssond7f3fcf2010-05-29 20:47:33 +00001231 if (!Base->Class->isEmpty()) {
Anders Carlsson09ffa322010-03-10 22:21:28 +00001232 // Update the data size.
Ken Dyck1b4420e2011-02-28 02:01:38 +00001233 setDataSize(Offset + Layout.getNonVirtualSize());
Anders Carlsson09ffa322010-03-10 22:21:28 +00001234
Ken Dyck1b4420e2011-02-28 02:01:38 +00001235 setSize(std::max(getSize(), getDataSize()));
Anders Carlsson09ffa322010-03-10 22:21:28 +00001236 } else
Ken Dyck1b4420e2011-02-28 02:01:38 +00001237 setSize(std::max(getSize(), Offset + Layout.getSize()));
Anders Carlsson09ffa322010-03-10 22:21:28 +00001238
1239 // Remember max struct/class alignment.
Argyrios Kyrtzidis8b542742010-12-09 00:35:20 +00001240 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001241
Ken Dyck1b4420e2011-02-28 02:01:38 +00001242 return Offset;
Anders Carlsson09ffa322010-03-10 22:21:28 +00001243}
1244
Daniel Dunbar6da10982010-05-27 05:45:51 +00001245void RecordLayoutBuilder::InitializeLayout(const Decl *D) {
Eli Friedman9ee2d0472012-10-12 23:29:20 +00001246 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Daniel Dunbar6da10982010-05-27 05:45:51 +00001247 IsUnion = RD->isUnion();
Eli Friedman9ee2d0472012-10-12 23:29:20 +00001248 IsMsStruct = RD->isMsStruct(Context);
1249 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001250
Eli Friedman9ee2d0472012-10-12 23:29:20 +00001251 Packed = D->hasAttr<PackedAttr>();
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001252
Daniel Dunbar096ed292011-10-05 21:04:55 +00001253 // Honor the default struct packing maximum alignment flag.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001254 if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct) {
Daniel Dunbar096ed292011-10-05 21:04:55 +00001255 MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
1256 }
1257
Daniel Dunbar6da10982010-05-27 05:45:51 +00001258 // mac68k alignment supersedes maximum field alignment and attribute aligned,
1259 // and forces all structures to have 2-byte alignment. The IBM docs on it
1260 // allude to additional (more complicated) semantics, especially with regard
1261 // to bit-fields, but gcc appears not to follow that.
1262 if (D->hasAttr<AlignMac68kAttr>()) {
1263 IsMac68kAlign = true;
Ken Dyck02ced6f2011-02-17 01:49:42 +00001264 MaxFieldAlignment = CharUnits::fromQuantity(2);
Ken Dyck4731d5b2011-02-16 02:05:21 +00001265 Alignment = CharUnits::fromQuantity(2);
Daniel Dunbar6da10982010-05-27 05:45:51 +00001266 } else {
1267 if (const MaxFieldAlignmentAttr *MFAA = D->getAttr<MaxFieldAlignmentAttr>())
Ken Dyck02ced6f2011-02-17 01:49:42 +00001268 MaxFieldAlignment = Context.toCharUnitsFromBits(MFAA->getAlignment());
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001269
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001270 if (unsigned MaxAlign = D->getMaxAlignment())
Ken Dyck85ef0432011-02-19 18:58:07 +00001271 UpdateAlignment(Context.toCharUnitsFromBits(MaxAlign));
Daniel Dunbar6da10982010-05-27 05:45:51 +00001272 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00001273
1274 // If there is an external AST source, ask it for the various offsets.
1275 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
1276 if (ExternalASTSource *External = Context.getExternalSource()) {
1277 ExternalLayout = External->layoutRecordType(RD,
1278 ExternalSize,
1279 ExternalAlign,
1280 ExternalFieldOffsets,
1281 ExternalBaseOffsets,
1282 ExternalVirtualBaseOffsets);
1283
1284 // Update based on external alignment.
1285 if (ExternalLayout) {
Douglas Gregor44ba7892012-01-28 00:53:29 +00001286 if (ExternalAlign > 0) {
1287 Alignment = Context.toCharUnitsFromBits(ExternalAlign);
Douglas Gregor44ba7892012-01-28 00:53:29 +00001288 } else {
1289 // The external source didn't have alignment information; infer it.
1290 InferAlignment = true;
1291 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00001292 }
1293 }
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001294}
Anders Carlsson6d9f6f32009-07-19 00:18:47 +00001295
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001296void RecordLayoutBuilder::Layout(const RecordDecl *D) {
1297 InitializeLayout(D);
Anders Carlsson118ce162009-07-18 21:48:39 +00001298 LayoutFields(D);
Mike Stump11289f42009-09-09 15:08:12 +00001299
Anders Carlsson79474332009-07-18 20:20:21 +00001300 // Finally, round the size of the total struct up to the alignment of the
1301 // struct itself.
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001302 FinishLayout(D);
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001303}
1304
1305void RecordLayoutBuilder::Layout(const CXXRecordDecl *RD) {
1306 InitializeLayout(RD);
1307
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001308 // Lay out the vtable and the non-virtual bases.
1309 LayoutNonVirtualBases(RD);
1310
1311 LayoutFields(RD);
1312
Ken Dycke7380752011-03-10 01:53:59 +00001313 NonVirtualSize = Context.toCharUnitsFromBits(
1314 llvm::RoundUpToAlignment(getSizeInBits(),
Douglas Gregore8bbc122011-09-02 00:18:52 +00001315 Context.getTargetInfo().getCharAlign()));
Ken Dyck4731d5b2011-02-16 02:05:21 +00001316 NonVirtualAlignment = Alignment;
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001317
Warren Hunt55d8e822013-10-23 23:53:07 +00001318 // Lay out the virtual bases and add the primary virtual base offsets.
1319 LayoutVirtualBases(RD, RD);
John McCall0153cd32011-11-08 04:01:03 +00001320
1321 // Finally, round the size of the total struct up to the alignment
Eli Friedman83a12582011-12-01 00:37:01 +00001322 // of the struct itself.
1323 FinishLayout(RD);
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001324
Anders Carlsson5b441d72010-04-10 21:24:48 +00001325#ifndef NDEBUG
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001326 // Check that we have base offsets for all bases.
1327 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1328 E = RD->bases_end(); I != E; ++I) {
1329 if (I->isVirtual())
1330 continue;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001331
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001332 const CXXRecordDecl *BaseDecl =
1333 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1334
1335 assert(Bases.count(BaseDecl) && "Did not find base offset!");
1336 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001337
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001338 // And all virtual bases.
1339 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
1340 E = RD->vbases_end(); I != E; ++I) {
1341 const CXXRecordDecl *BaseDecl =
1342 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001343
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001344 assert(VBases.count(BaseDecl) && "Did not find base offset!");
Anders Carlsson5b441d72010-04-10 21:24:48 +00001345 }
1346#endif
Anders Carlsson79474332009-07-18 20:20:21 +00001347}
1348
Anders Carlssonc2226202010-05-26 05:58:59 +00001349void RecordLayoutBuilder::Layout(const ObjCInterfaceDecl *D) {
Anders Carlsson4f516282009-07-18 20:50:59 +00001350 if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
Anders Carlsson5efc56e2010-04-16 15:07:51 +00001351 const ASTRecordLayout &SL = Context.getASTObjCInterfaceLayout(SD);
Anders Carlsson4f516282009-07-18 20:50:59 +00001352
Ken Dyck85ef0432011-02-19 18:58:07 +00001353 UpdateAlignment(SL.getAlignment());
Mike Stump11289f42009-09-09 15:08:12 +00001354
Anders Carlsson4f516282009-07-18 20:50:59 +00001355 // We start laying out ivars not at the end of the superclass
1356 // structure, but at the next byte following the last field.
Ken Dyckecfc7552011-02-24 01:13:28 +00001357 setSize(SL.getDataSize());
Ken Dyck1b4420e2011-02-28 02:01:38 +00001358 setDataSize(getSize());
Anders Carlsson4f516282009-07-18 20:50:59 +00001359 }
Mike Stump11289f42009-09-09 15:08:12 +00001360
Daniel Dunbar6da10982010-05-27 05:45:51 +00001361 InitializeLayout(D);
Anders Carlsson4f516282009-07-18 20:50:59 +00001362 // Layout each ivar sequentially.
Jordy Rosea91768e2011-07-22 02:08:32 +00001363 for (const ObjCIvarDecl *IVD = D->all_declared_ivar_begin(); IVD;
1364 IVD = IVD->getNextIvar())
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001365 LayoutField(IVD);
Mike Stump11289f42009-09-09 15:08:12 +00001366
Anders Carlsson4f516282009-07-18 20:50:59 +00001367 // Finally, round the size of the total struct up to the alignment of the
1368 // struct itself.
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001369 FinishLayout(D);
Anders Carlsson4f516282009-07-18 20:50:59 +00001370}
1371
Anders Carlssonc2226202010-05-26 05:58:59 +00001372void RecordLayoutBuilder::LayoutFields(const RecordDecl *D) {
Anders Carlsson118ce162009-07-18 21:48:39 +00001373 // Layout each field, for now, just sequentially, respecting alignment. In
1374 // the future, this will need to be tweakable by targets.
Mike Stump11289f42009-09-09 15:08:12 +00001375 for (RecordDecl::field_iterator Field = D->field_begin(),
Eli Friedman481673f2013-06-26 23:47:39 +00001376 FieldEnd = D->field_end(); Field != FieldEnd; ++Field)
David Blaikie40ed2972012-06-06 20:45:41 +00001377 LayoutField(*Field);
Anders Carlsson118ce162009-07-18 21:48:39 +00001378}
1379
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001380void RecordLayoutBuilder::LayoutWideBitField(uint64_t FieldSize,
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001381 uint64_t TypeSize,
1382 bool FieldPacked,
1383 const FieldDecl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001384 assert(Context.getLangOpts().CPlusPlus &&
Anders Carlsson57235162010-04-16 15:57:11 +00001385 "Can only have wide bit-fields in C++!");
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001386
Anders Carlsson57235162010-04-16 15:57:11 +00001387 // Itanium C++ ABI 2.4:
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001388 // If sizeof(T)*8 < n, let T' be the largest integral POD type with
Anders Carlsson57235162010-04-16 15:57:11 +00001389 // sizeof(T')*8 <= n.
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001390
Anders Carlsson57235162010-04-16 15:57:11 +00001391 QualType IntegralPODTypes[] = {
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001392 Context.UnsignedCharTy, Context.UnsignedShortTy, Context.UnsignedIntTy,
Anders Carlsson57235162010-04-16 15:57:11 +00001393 Context.UnsignedLongTy, Context.UnsignedLongLongTy
1394 };
1395
Anders Carlsson57235162010-04-16 15:57:11 +00001396 QualType Type;
1397 for (unsigned I = 0, E = llvm::array_lengthof(IntegralPODTypes);
1398 I != E; ++I) {
1399 uint64_t Size = Context.getTypeSize(IntegralPODTypes[I]);
Anders Carlsson57235162010-04-16 15:57:11 +00001400
1401 if (Size > FieldSize)
1402 break;
1403
1404 Type = IntegralPODTypes[I];
1405 }
1406 assert(!Type.isNull() && "Did not find a type!");
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001407
Ken Dyckdbe37f32011-03-01 01:36:00 +00001408 CharUnits TypeAlign = Context.getTypeAlignInChars(Type);
Anders Carlsson57235162010-04-16 15:57:11 +00001409
1410 // We're not going to use any of the unfilled bits in the last byte.
Eli Friedman2782dac2013-06-26 20:50:34 +00001411 UnfilledBitsInLastUnit = 0;
1412 LastBitfieldTypeSize = 0;
Anders Carlsson57235162010-04-16 15:57:11 +00001413
Anders Carlssonaad5fa82010-04-17 20:21:41 +00001414 uint64_t FieldOffset;
Eli Friedman2782dac2013-06-26 20:50:34 +00001415 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001416
Anders Carlsson57235162010-04-16 15:57:11 +00001417 if (IsUnion) {
Ken Dyckecfc7552011-02-24 01:13:28 +00001418 setDataSize(std::max(getDataSizeInBits(), FieldSize));
Anders Carlssonaad5fa82010-04-17 20:21:41 +00001419 FieldOffset = 0;
Anders Carlsson57235162010-04-16 15:57:11 +00001420 } else {
Chad Rosiere1a6a0e2011-08-05 22:38:04 +00001421 // The bitfield is allocated starting at the next offset aligned
1422 // appropriately for T', with length n bits.
Ken Dyckdbe37f32011-03-01 01:36:00 +00001423 FieldOffset = llvm::RoundUpToAlignment(getDataSizeInBits(),
1424 Context.toBits(TypeAlign));
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001425
Anders Carlsson57235162010-04-16 15:57:11 +00001426 uint64_t NewSizeInBits = FieldOffset + FieldSize;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001427
Ken Dycka1a2e8d2011-03-10 02:00:35 +00001428 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits,
Douglas Gregore8bbc122011-09-02 00:18:52 +00001429 Context.getTargetInfo().getCharAlign()));
Eli Friedman2782dac2013-06-26 20:50:34 +00001430 UnfilledBitsInLastUnit = getDataSizeInBits() - NewSizeInBits;
Anders Carlsson57235162010-04-16 15:57:11 +00001431 }
1432
1433 // Place this field at the current location.
1434 FieldOffsets.push_back(FieldOffset);
1435
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001436 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, FieldOffset,
Ken Dyckdbe37f32011-03-01 01:36:00 +00001437 Context.toBits(TypeAlign), FieldPacked, D);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001438
Anders Carlsson57235162010-04-16 15:57:11 +00001439 // Update the size.
Ken Dyckecfc7552011-02-24 01:13:28 +00001440 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001441
Anders Carlsson57235162010-04-16 15:57:11 +00001442 // Remember max struct/class alignment.
Ken Dyckdbe37f32011-03-01 01:36:00 +00001443 UpdateAlignment(TypeAlign);
Anders Carlsson57235162010-04-16 15:57:11 +00001444}
1445
Anders Carlssonc2226202010-05-26 05:58:59 +00001446void RecordLayoutBuilder::LayoutBitField(const FieldDecl *D) {
Anders Carlsson07209442009-11-22 17:37:31 +00001447 bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
Richard Smithcaf33902011-10-10 18:28:20 +00001448 uint64_t FieldSize = D->getBitWidthValue(Context);
Anders Carlsson5efc56e2010-04-16 15:07:51 +00001449 std::pair<uint64_t, unsigned> FieldInfo = Context.getTypeInfo(D->getType());
Anders Carlsson07209442009-11-22 17:37:31 +00001450 uint64_t TypeSize = FieldInfo.first;
1451 unsigned FieldAlign = FieldInfo.second;
Eli Friedman2782dac2013-06-26 20:50:34 +00001452
John McCall30268ca2014-01-29 07:53:44 +00001453 // UnfilledBitsInLastUnit is the difference between the end of the
1454 // last allocated bitfield (i.e. the first bit offset available for
1455 // bitfields) and the end of the current data size in bits (i.e. the
1456 // first bit offset available for non-bitfields). The current data
1457 // size in bits is always a multiple of the char size; additionally,
1458 // for ms_struct records it's also a multiple of the
1459 // LastBitfieldTypeSize (if set).
1460
1461 // The basic bitfield layout rule for ms_struct is to allocate an
1462 // entire unit of the bitfield's declared type (e.g. 'unsigned
1463 // long'), then parcel it up among successive bitfields whose
1464 // declared types have the same size, making a new unit as soon as
1465 // the last can no longer store the whole value.
1466
1467 // The standard bitfield layout rule for non-ms_struct is to place
1468 // bitfields at the next available bit offset where the entire
1469 // bitfield would fit in an aligned storage unit of the declared
1470 // type (even if there are also non-bitfields within that same
1471 // unit). However, some targets (those that !useBitFieldTypeAlignment())
1472 // don't require this storage unit to be aligned, and therefore
1473 // always put the bit-field at the next available bit offset.
1474 // Such targets generally do interpret zero-width bitfields as
1475 // forcing the use of a new storage unit.
1476
1477 // First, some simple bookkeeping to perform for ms_struct structs.
Eli Friedman2782dac2013-06-26 20:50:34 +00001478 if (IsMsStruct) {
John McCall30268ca2014-01-29 07:53:44 +00001479 // The field alignment for integer types is always the size.
Fariborz Jahanian7adbed62011-05-09 22:03:17 +00001480 FieldAlign = TypeSize;
John McCall30268ca2014-01-29 07:53:44 +00001481
1482 // If the previous field was not a bitfield, or was a bitfield
1483 // with a different storage unit size, we're done with that
1484 // storage unit.
Eli Friedman2782dac2013-06-26 20:50:34 +00001485 if (LastBitfieldTypeSize != TypeSize) {
John McCall30268ca2014-01-29 07:53:44 +00001486 // Also, ignore zero-length bitfields after non-bitfields.
1487 if (!LastBitfieldTypeSize && !FieldSize)
1488 FieldAlign = 1;
1489
Eli Friedman2782dac2013-06-26 20:50:34 +00001490 UnfilledBitsInLastUnit = 0;
1491 LastBitfieldTypeSize = 0;
1492 }
1493 }
1494
John McCall30268ca2014-01-29 07:53:44 +00001495 // If the field is wider than its declared type, it follows
1496 // different rules in all cases.
Anders Carlsson57235162010-04-16 15:57:11 +00001497 if (FieldSize > TypeSize) {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001498 LayoutWideBitField(FieldSize, TypeSize, FieldPacked, D);
Anders Carlsson57235162010-04-16 15:57:11 +00001499 return;
1500 }
1501
John McCall30268ca2014-01-29 07:53:44 +00001502 // Compute the next available bit offset.
1503 uint64_t FieldOffset =
1504 IsUnion ? 0 : (getDataSizeInBits() - UnfilledBitsInLastUnit);
1505
1506 // Handle targets that don't honor bitfield type alignment.
1507 if (!Context.getTargetInfo().useBitFieldTypeAlignment()) {
1508 // Some such targets do honor it on zero-width bitfields.
1509 if (FieldSize == 0 &&
1510 Context.getTargetInfo().useZeroLengthBitfieldAlignment()) {
1511 // The alignment to round up to is the max of the field's natural
1512 // alignment and a target-specific fixed value (sometimes zero).
1513 unsigned ZeroLengthBitfieldBoundary =
1514 Context.getTargetInfo().getZeroLengthBitfieldBoundary();
1515 FieldAlign = std::max(FieldAlign, ZeroLengthBitfieldBoundary);
1516
1517 // If that doesn't apply, just ignore the field alignment.
1518 } else {
1519 FieldAlign = 1;
1520 }
1521 }
1522
1523 // Remember the alignment we would have used if the field were not packed.
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001524 unsigned UnpackedFieldAlign = FieldAlign;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001525
John McCall30268ca2014-01-29 07:53:44 +00001526 // Ignore the field alignment if the field is packed.
1527 if (FieldPacked)
Anders Carlsson07209442009-11-22 17:37:31 +00001528 FieldAlign = 1;
Anders Carlsson07209442009-11-22 17:37:31 +00001529
John McCall30268ca2014-01-29 07:53:44 +00001530 // But, if there's an 'aligned' attribute on the field, honor that.
1531 if (unsigned ExplicitFieldAlign = D->getMaxAlignment()) {
1532 FieldAlign = std::max(FieldAlign, ExplicitFieldAlign);
1533 UnpackedFieldAlign = std::max(UnpackedFieldAlign, ExplicitFieldAlign);
1534 }
1535
1536 // But, if there's a #pragma pack in play, that takes precedent over
1537 // even the 'aligned' attribute, for non-zero-width bitfields.
1538 if (!MaxFieldAlignment.isZero() && FieldSize) {
Ken Dyck02ced6f2011-02-17 01:49:42 +00001539 unsigned MaxFieldAlignmentInBits = Context.toBits(MaxFieldAlignment);
1540 FieldAlign = std::min(FieldAlign, MaxFieldAlignmentInBits);
1541 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignmentInBits);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001542 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001543
John McCall30268ca2014-01-29 07:53:44 +00001544 // For purposes of diagnostics, we're going to simultaneously
1545 // compute the field offsets that we would have used if we weren't
1546 // adding any alignment padding or if the field weren't packed.
1547 uint64_t UnpaddedFieldOffset = FieldOffset;
1548 uint64_t UnpackedFieldOffset = FieldOffset;
1549
1550 // Check if we need to add padding to fit the bitfield within an
1551 // allocation unit with the right size and alignment. The rules are
1552 // somewhat different here for ms_struct structs.
1553 if (IsMsStruct) {
1554 // If it's not a zero-width bitfield, and we can fit the bitfield
1555 // into the active storage unit (and we haven't already decided to
1556 // start a new storage unit), just do so, regardless of any other
1557 // other consideration. Otherwise, round up to the right alignment.
1558 if (FieldSize == 0 || FieldSize > UnfilledBitsInLastUnit) {
1559 FieldOffset = llvm::RoundUpToAlignment(FieldOffset, FieldAlign);
1560 UnpackedFieldOffset = llvm::RoundUpToAlignment(UnpackedFieldOffset,
1561 UnpackedFieldAlign);
1562 UnfilledBitsInLastUnit = 0;
1563 }
1564
1565 } else {
1566 // #pragma pack, with any value, suppresses the insertion of padding.
1567 bool AllowPadding = MaxFieldAlignment.isZero();
1568
1569 // Compute the real offset.
1570 if (FieldSize == 0 ||
1571 (AllowPadding &&
1572 (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize)) {
1573 FieldOffset = llvm::RoundUpToAlignment(FieldOffset, FieldAlign);
1574 }
1575
1576 // Repeat the computation for diagnostic purposes.
1577 if (FieldSize == 0 ||
1578 (AllowPadding &&
1579 (UnpackedFieldOffset & (UnpackedFieldAlign-1)) + FieldSize > TypeSize))
1580 UnpackedFieldOffset = llvm::RoundUpToAlignment(UnpackedFieldOffset,
1581 UnpackedFieldAlign);
Eli Friedman2782dac2013-06-26 20:50:34 +00001582 }
1583
John McCall30268ca2014-01-29 07:53:44 +00001584 // If we're using external layout, give the external layout a chance
1585 // to override this information.
Douglas Gregor44ba7892012-01-28 00:53:29 +00001586 if (ExternalLayout)
1587 FieldOffset = updateExternalFieldOffset(D, FieldOffset);
1588
John McCall30268ca2014-01-29 07:53:44 +00001589 // Okay, place the bitfield at the calculated offset.
Anders Carlsson07209442009-11-22 17:37:31 +00001590 FieldOffsets.push_back(FieldOffset);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001591
John McCall30268ca2014-01-29 07:53:44 +00001592 // Bookkeeping:
1593
1594 // Anonymous members don't affect the overall record alignment,
1595 // except on targets where they do.
1596 if (!IsMsStruct &&
1597 !Context.getTargetInfo().useZeroLengthBitfieldAlignment() &&
1598 !D->getIdentifier())
1599 FieldAlign = UnpackedFieldAlign = 1;
1600
1601 // Diagnose differences in layout due to padding or packing.
Douglas Gregore9fc3772012-01-26 07:55:45 +00001602 if (!ExternalLayout)
1603 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, UnpackedFieldOffset,
1604 UnpackedFieldAlign, FieldPacked, D);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001605
Anders Carlssonba958402009-11-22 19:13:51 +00001606 // Update DataSize to include the last byte containing (part of) the bitfield.
John McCall30268ca2014-01-29 07:53:44 +00001607
1608 // For unions, this is just a max operation, as usual.
Anders Carlssonba958402009-11-22 19:13:51 +00001609 if (IsUnion) {
1610 // FIXME: I think FieldSize should be TypeSize here.
Ken Dyckecfc7552011-02-24 01:13:28 +00001611 setDataSize(std::max(getDataSizeInBits(), FieldSize));
John McCall30268ca2014-01-29 07:53:44 +00001612
1613 // For non-zero-width bitfields in ms_struct structs, allocate a new
1614 // storage unit if necessary.
1615 } else if (IsMsStruct && FieldSize) {
1616 // We should have cleared UnfilledBitsInLastUnit in every case
1617 // where we changed storage units.
1618 if (!UnfilledBitsInLastUnit) {
1619 setDataSize(FieldOffset + TypeSize);
1620 UnfilledBitsInLastUnit = TypeSize;
Eli Friedman2782dac2013-06-26 20:50:34 +00001621 }
John McCall30268ca2014-01-29 07:53:44 +00001622 UnfilledBitsInLastUnit -= FieldSize;
1623 LastBitfieldTypeSize = TypeSize;
1624
1625 // Otherwise, bump the data size up to include the bitfield,
1626 // including padding up to char alignment, and then remember how
1627 // bits we didn't use.
1628 } else {
1629 uint64_t NewSizeInBits = FieldOffset + FieldSize;
1630 uint64_t CharAlignment = Context.getTargetInfo().getCharAlign();
1631 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits, CharAlignment));
1632 UnfilledBitsInLastUnit = getDataSizeInBits() - NewSizeInBits;
1633
1634 // The only time we can get here for an ms_struct is if this is a
1635 // zero-width bitfield, which doesn't count as anything for the
1636 // purposes of unfilled bits.
1637 LastBitfieldTypeSize = 0;
Anders Carlssonba958402009-11-22 19:13:51 +00001638 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001639
Anders Carlssonba958402009-11-22 19:13:51 +00001640 // Update the size.
Ken Dyckecfc7552011-02-24 01:13:28 +00001641 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001642
Anders Carlsson07209442009-11-22 17:37:31 +00001643 // Remember max struct/class alignment.
Ken Dyck85ef0432011-02-19 18:58:07 +00001644 UpdateAlignment(Context.toCharUnitsFromBits(FieldAlign),
1645 Context.toCharUnitsFromBits(UnpackedFieldAlign));
Anders Carlsson07209442009-11-22 17:37:31 +00001646}
1647
Douglas Gregore9fc3772012-01-26 07:55:45 +00001648void RecordLayoutBuilder::LayoutField(const FieldDecl *D) {
Anders Carlsson07209442009-11-22 17:37:31 +00001649 if (D->isBitField()) {
1650 LayoutBitField(D);
1651 return;
1652 }
1653
Eli Friedman2782dac2013-06-26 20:50:34 +00001654 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001655
Anders Carlssonba958402009-11-22 19:13:51 +00001656 // Reset the unfilled bits.
Eli Friedman2782dac2013-06-26 20:50:34 +00001657 UnfilledBitsInLastUnit = 0;
1658 LastBitfieldTypeSize = 0;
Anders Carlssonba958402009-11-22 19:13:51 +00001659
Anders Carlsson07209442009-11-22 17:37:31 +00001660 bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
Ken Dyck6d90e892011-02-20 02:06:09 +00001661 CharUnits FieldOffset =
Ken Dyckecfc7552011-02-24 01:13:28 +00001662 IsUnion ? CharUnits::Zero() : getDataSize();
Ken Dyck6d90e892011-02-20 02:06:09 +00001663 CharUnits FieldSize;
1664 CharUnits FieldAlign;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001665
Anders Carlsson07209442009-11-22 17:37:31 +00001666 if (D->getType()->isIncompleteArrayType()) {
1667 // This is a flexible array member; we can't directly
1668 // query getTypeInfo about these, so we figure it out here.
1669 // Flexible array members don't have any size, but they
1670 // have to be aligned appropriately for their element type.
Ken Dyck6d90e892011-02-20 02:06:09 +00001671 FieldSize = CharUnits::Zero();
Anders Carlsson5efc56e2010-04-16 15:07:51 +00001672 const ArrayType* ATy = Context.getAsArrayType(D->getType());
Ken Dyck6d90e892011-02-20 02:06:09 +00001673 FieldAlign = Context.getTypeAlignInChars(ATy->getElementType());
Anders Carlsson07209442009-11-22 17:37:31 +00001674 } else if (const ReferenceType *RT = D->getType()->getAs<ReferenceType>()) {
1675 unsigned AS = RT->getPointeeType().getAddressSpace();
Ken Dyck6d90e892011-02-20 02:06:09 +00001676 FieldSize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001677 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(AS));
Ken Dyck6d90e892011-02-20 02:06:09 +00001678 FieldAlign =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001679 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(AS));
Anders Carlsson79474332009-07-18 20:20:21 +00001680 } else {
Ken Dyck6d90e892011-02-20 02:06:09 +00001681 std::pair<CharUnits, CharUnits> FieldInfo =
1682 Context.getTypeInfoInChars(D->getType());
Anders Carlsson07209442009-11-22 17:37:31 +00001683 FieldSize = FieldInfo.first;
1684 FieldAlign = FieldInfo.second;
Chad Rosier18903ee2011-08-04 01:21:14 +00001685
Eli Friedman9ee2d0472012-10-12 23:29:20 +00001686 if (IsMsStruct) {
Douglas Gregordbe39272011-02-01 15:15:22 +00001687 // If MS bitfield layout is required, figure out what type is being
1688 // laid out and align the field to the width of that type.
1689
1690 // Resolve all typedefs down to their base type and round up the field
1691 // alignment if necessary.
1692 QualType T = Context.getBaseElementType(D->getType());
1693 if (const BuiltinType *BTy = T->getAs<BuiltinType>()) {
Ken Dyck6d90e892011-02-20 02:06:09 +00001694 CharUnits TypeSize = Context.getTypeSizeInChars(BTy);
Douglas Gregordbe39272011-02-01 15:15:22 +00001695 if (TypeSize > FieldAlign)
1696 FieldAlign = TypeSize;
1697 }
1698 }
Anders Carlsson79474332009-07-18 20:20:21 +00001699 }
Mike Stump11289f42009-09-09 15:08:12 +00001700
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001701 // The align if the field is not packed. This is to check if the attribute
1702 // was unnecessary (-Wpacked).
Ken Dyck6d90e892011-02-20 02:06:09 +00001703 CharUnits UnpackedFieldAlign = FieldAlign;
1704 CharUnits UnpackedFieldOffset = FieldOffset;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001705
Anders Carlsson07209442009-11-22 17:37:31 +00001706 if (FieldPacked)
Ken Dyck6d90e892011-02-20 02:06:09 +00001707 FieldAlign = CharUnits::One();
1708 CharUnits MaxAlignmentInChars =
1709 Context.toCharUnitsFromBits(D->getMaxAlignment());
1710 FieldAlign = std::max(FieldAlign, MaxAlignmentInChars);
1711 UnpackedFieldAlign = std::max(UnpackedFieldAlign, MaxAlignmentInChars);
Anders Carlsson07209442009-11-22 17:37:31 +00001712
1713 // The maximum field alignment overrides the aligned attribute.
Ken Dyck02ced6f2011-02-17 01:49:42 +00001714 if (!MaxFieldAlignment.isZero()) {
Ken Dyck6d90e892011-02-20 02:06:09 +00001715 FieldAlign = std::min(FieldAlign, MaxFieldAlignment);
1716 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignment);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001717 }
Anders Carlsson07209442009-11-22 17:37:31 +00001718
Douglas Gregor44ba7892012-01-28 00:53:29 +00001719 // Round up the current record size to the field's alignment boundary.
1720 FieldOffset = FieldOffset.RoundUpToAlignment(FieldAlign);
1721 UnpackedFieldOffset =
1722 UnpackedFieldOffset.RoundUpToAlignment(UnpackedFieldAlign);
1723
1724 if (ExternalLayout) {
1725 FieldOffset = Context.toCharUnitsFromBits(
1726 updateExternalFieldOffset(D, Context.toBits(FieldOffset)));
1727
1728 if (!IsUnion && EmptySubobjects) {
1729 // Record the fact that we're placing a field at this offset.
1730 bool Allowed = EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset);
1731 (void)Allowed;
1732 assert(Allowed && "Externally-placed field cannot be placed here");
1733 }
1734 } else {
Douglas Gregore9fc3772012-01-26 07:55:45 +00001735 if (!IsUnion && EmptySubobjects) {
1736 // Check if we can place the field at this offset.
1737 while (!EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset)) {
1738 // We couldn't place the field at the offset. Try again at a new offset.
1739 FieldOffset += FieldAlign;
1740 }
Anders Carlsson07209442009-11-22 17:37:31 +00001741 }
Anders Carlsson07209442009-11-22 17:37:31 +00001742 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00001743
Anders Carlsson79474332009-07-18 20:20:21 +00001744 // Place this field at the current location.
Ken Dyck6d90e892011-02-20 02:06:09 +00001745 FieldOffsets.push_back(Context.toBits(FieldOffset));
Mike Stump11289f42009-09-09 15:08:12 +00001746
Douglas Gregore9fc3772012-01-26 07:55:45 +00001747 if (!ExternalLayout)
1748 CheckFieldPadding(Context.toBits(FieldOffset), UnpaddedFieldOffset,
1749 Context.toBits(UnpackedFieldOffset),
1750 Context.toBits(UnpackedFieldAlign), FieldPacked, D);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001751
Anders Carlsson79474332009-07-18 20:20:21 +00001752 // Reserve space for this field.
Eli Friedman43f18342012-01-12 23:27:03 +00001753 uint64_t FieldSizeInBits = Context.toBits(FieldSize);
Anders Carlsson79474332009-07-18 20:20:21 +00001754 if (IsUnion)
Eli Friedman2e108372012-01-12 23:48:56 +00001755 setDataSize(std::max(getDataSizeInBits(), FieldSizeInBits));
Anders Carlsson79474332009-07-18 20:20:21 +00001756 else
Eli Friedman2e108372012-01-12 23:48:56 +00001757 setDataSize(FieldOffset + FieldSize);
Mike Stump11289f42009-09-09 15:08:12 +00001758
Eli Friedman2e108372012-01-12 23:48:56 +00001759 // Update the size.
1760 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
Mike Stump11289f42009-09-09 15:08:12 +00001761
Anders Carlsson79474332009-07-18 20:20:21 +00001762 // Remember max struct/class alignment.
Ken Dyck6d90e892011-02-20 02:06:09 +00001763 UpdateAlignment(FieldAlign, UnpackedFieldAlign);
Anders Carlsson79474332009-07-18 20:20:21 +00001764}
1765
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001766void RecordLayoutBuilder::FinishLayout(const NamedDecl *D) {
Anders Carlsson79474332009-07-18 20:20:21 +00001767 // In C++, records cannot be of size 0.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001768 if (Context.getLangOpts().CPlusPlus && getSizeInBits() == 0) {
Fariborz Jahanian09b23312011-02-02 19:36:18 +00001769 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
1770 // Compatibility with gcc requires a class (pod or non-pod)
1771 // which is not empty but of size 0; such as having fields of
1772 // array of zero-length, remains of Size 0
1773 if (RD->isEmpty())
Ken Dyck1b4420e2011-02-28 02:01:38 +00001774 setSize(CharUnits::One());
Fariborz Jahanian09b23312011-02-02 19:36:18 +00001775 }
1776 else
Ken Dyck1b4420e2011-02-28 02:01:38 +00001777 setSize(CharUnits::One());
Fariborz Jahanian09b23312011-02-02 19:36:18 +00001778 }
Eli Friedman83a12582011-12-01 00:37:01 +00001779
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001780 // Finally, round the size of the record up to the alignment of the
1781 // record itself.
Eli Friedman2782dac2013-06-26 20:50:34 +00001782 uint64_t UnpaddedSize = getSizeInBits() - UnfilledBitsInLastUnit;
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001783 uint64_t UnpackedSizeInBits =
1784 llvm::RoundUpToAlignment(getSizeInBits(),
1785 Context.toBits(UnpackedAlignment));
1786 CharUnits UnpackedSize = Context.toCharUnitsFromBits(UnpackedSizeInBits);
1787 uint64_t RoundedSize
1788 = llvm::RoundUpToAlignment(getSizeInBits(), Context.toBits(Alignment));
1789
1790 if (ExternalLayout) {
1791 // If we're inferring alignment, and the external size is smaller than
1792 // our size after we've rounded up to alignment, conservatively set the
1793 // alignment to 1.
1794 if (InferAlignment && ExternalSize < RoundedSize) {
1795 Alignment = CharUnits::One();
1796 InferAlignment = false;
1797 }
1798 setSize(ExternalSize);
1799 return;
1800 }
1801
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001802 // Set the size to the final size.
1803 setSize(RoundedSize);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001804
Douglas Gregore8bbc122011-09-02 00:18:52 +00001805 unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001806 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
1807 // Warn if padding was introduced to the struct/class/union.
Ken Dyckecfc7552011-02-24 01:13:28 +00001808 if (getSizeInBits() > UnpaddedSize) {
1809 unsigned PadSize = getSizeInBits() - UnpaddedSize;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001810 bool InBits = true;
1811 if (PadSize % CharBitNum == 0) {
1812 PadSize = PadSize / CharBitNum;
1813 InBits = false;
1814 }
1815 Diag(RD->getLocation(), diag::warn_padded_struct_size)
1816 << Context.getTypeDeclType(RD)
1817 << PadSize
1818 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1); // plural or not
1819 }
1820
1821 // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
1822 // bother since there won't be alignment issues.
Ken Dyckecfc7552011-02-24 01:13:28 +00001823 if (Packed && UnpackedAlignment > CharUnits::One() &&
Ken Dyck1b4420e2011-02-28 02:01:38 +00001824 getSize() == UnpackedSize)
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001825 Diag(D->getLocation(), diag::warn_unnecessary_packed)
1826 << Context.getTypeDeclType(RD);
1827 }
Anders Carlsson79474332009-07-18 20:20:21 +00001828}
1829
Ken Dyck85ef0432011-02-19 18:58:07 +00001830void RecordLayoutBuilder::UpdateAlignment(CharUnits NewAlignment,
1831 CharUnits UnpackedNewAlignment) {
Douglas Gregore9fc3772012-01-26 07:55:45 +00001832 // The alignment is not modified when using 'mac68k' alignment or when
Douglas Gregor44ba7892012-01-28 00:53:29 +00001833 // we have an externally-supplied layout that also provides overall alignment.
1834 if (IsMac68kAlign || (ExternalLayout && !InferAlignment))
Daniel Dunbar6da10982010-05-27 05:45:51 +00001835 return;
1836
Ken Dyck85ef0432011-02-19 18:58:07 +00001837 if (NewAlignment > Alignment) {
1838 assert(llvm::isPowerOf2_32(NewAlignment.getQuantity() &&
1839 "Alignment not a power of 2"));
1840 Alignment = NewAlignment;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001841 }
1842
Ken Dyck85ef0432011-02-19 18:58:07 +00001843 if (UnpackedNewAlignment > UnpackedAlignment) {
1844 assert(llvm::isPowerOf2_32(UnpackedNewAlignment.getQuantity() &&
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001845 "Alignment not a power of 2"));
Ken Dyck85ef0432011-02-19 18:58:07 +00001846 UnpackedAlignment = UnpackedNewAlignment;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001847 }
1848}
1849
Douglas Gregor44ba7892012-01-28 00:53:29 +00001850uint64_t
1851RecordLayoutBuilder::updateExternalFieldOffset(const FieldDecl *Field,
1852 uint64_t ComputedOffset) {
1853 assert(ExternalFieldOffsets.find(Field) != ExternalFieldOffsets.end() &&
1854 "Field does not have an external offset");
1855
1856 uint64_t ExternalFieldOffset = ExternalFieldOffsets[Field];
1857
1858 if (InferAlignment && ExternalFieldOffset < ComputedOffset) {
1859 // The externally-supplied field offset is before the field offset we
1860 // computed. Assume that the structure is packed.
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001861 Alignment = CharUnits::One();
Douglas Gregor44ba7892012-01-28 00:53:29 +00001862 InferAlignment = false;
1863 }
1864
1865 // Use the externally-supplied field offset.
Benjamin Kramer648e68b2012-08-31 22:14:25 +00001866 return ExternalFieldOffset;
1867}
1868
1869/// \brief Get diagnostic %select index for tag kind for
1870/// field padding diagnostic message.
1871/// WARNING: Indexes apply to particular diagnostics only!
1872///
1873/// \returns diagnostic %select index.
1874static unsigned getPaddingDiagFromTagKind(TagTypeKind Tag) {
1875 switch (Tag) {
1876 case TTK_Struct: return 0;
1877 case TTK_Interface: return 1;
1878 case TTK_Class: return 2;
1879 default: llvm_unreachable("Invalid tag kind for field padding diagnostic!");
1880 }
1881}
1882
1883void RecordLayoutBuilder::CheckFieldPadding(uint64_t Offset,
1884 uint64_t UnpaddedOffset,
1885 uint64_t UnpackedOffset,
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001886 unsigned UnpackedAlign,
1887 bool isPacked,
1888 const FieldDecl *D) {
1889 // We let objc ivars without warning, objc interfaces generally are not used
1890 // for padding tricks.
1891 if (isa<ObjCIvarDecl>(D))
Anders Carlsson79474332009-07-18 20:20:21 +00001892 return;
Mike Stump11289f42009-09-09 15:08:12 +00001893
Ted Kremenekfed48af2011-09-06 19:40:45 +00001894 // Don't warn about structs created without a SourceLocation. This can
1895 // be done by clients of the AST, such as codegen.
1896 if (D->getLocation().isInvalid())
1897 return;
1898
Douglas Gregore8bbc122011-09-02 00:18:52 +00001899 unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
Mike Stump11289f42009-09-09 15:08:12 +00001900
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001901 // Warn if padding was introduced to the struct/class.
1902 if (!IsUnion && Offset > UnpaddedOffset) {
1903 unsigned PadSize = Offset - UnpaddedOffset;
1904 bool InBits = true;
1905 if (PadSize % CharBitNum == 0) {
1906 PadSize = PadSize / CharBitNum;
1907 InBits = false;
Benjamin Kramer648e68b2012-08-31 22:14:25 +00001908 }
1909 if (D->getIdentifier())
1910 Diag(D->getLocation(), diag::warn_padded_struct_field)
1911 << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
1912 << Context.getTypeDeclType(D->getParent())
1913 << PadSize
1914 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1) // plural or not
1915 << D->getIdentifier();
1916 else
1917 Diag(D->getLocation(), diag::warn_padded_struct_anon_field)
1918 << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
1919 << Context.getTypeDeclType(D->getParent())
1920 << PadSize
1921 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1); // plural or not
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001922 }
1923
1924 // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
1925 // bother since there won't be alignment issues.
1926 if (isPacked && UnpackedAlign > CharBitNum && Offset == UnpackedOffset)
1927 Diag(D->getLocation(), diag::warn_unnecessary_packed)
1928 << D->getIdentifier();
Anders Carlsson79474332009-07-18 20:20:21 +00001929}
Mike Stump11289f42009-09-09 15:08:12 +00001930
John McCall6bd2a892013-01-25 22:31:03 +00001931static const CXXMethodDecl *computeKeyFunction(ASTContext &Context,
1932 const CXXRecordDecl *RD) {
Daniel Dunbarccabe482010-04-19 20:44:53 +00001933 // If a class isn't polymorphic it doesn't have a key function.
Anders Carlsson5ebf8b42009-12-07 04:35:11 +00001934 if (!RD->isPolymorphic())
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001935 return 0;
Eli Friedmanf2c79b62009-12-08 03:56:49 +00001936
Eli Friedman300f55d2011-06-10 21:53:06 +00001937 // A class that is not externally visible doesn't have a key function. (Or
Eli Friedmanf2c79b62009-12-08 03:56:49 +00001938 // at least, there's no point to assigning a key function to such a class;
1939 // this doesn't affect the ABI.)
Rafael Espindola3ae00052013-05-13 00:12:11 +00001940 if (!RD->isExternallyVisible())
Eli Friedmanf2c79b62009-12-08 03:56:49 +00001941 return 0;
1942
Argyrios Kyrtzidis8c64bbe2010-10-13 02:39:41 +00001943 // Template instantiations don't have key functions,see Itanium C++ ABI 5.2.6.
1944 // Same behavior as GCC.
1945 TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
1946 if (TSK == TSK_ImplicitInstantiation ||
1947 TSK == TSK_ExplicitInstantiationDefinition)
1948 return 0;
1949
John McCall6bd2a892013-01-25 22:31:03 +00001950 bool allowInlineFunctions =
1951 Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline();
1952
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001953 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
1954 E = RD->method_end(); I != E; ++I) {
David Blaikie40ed2972012-06-06 20:45:41 +00001955 const CXXMethodDecl *MD = *I;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001956
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001957 if (!MD->isVirtual())
1958 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001959
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001960 if (MD->isPure())
1961 continue;
Eli Friedmanf2c79b62009-12-08 03:56:49 +00001962
Anders Carlssonf98849e2009-12-02 17:15:43 +00001963 // Ignore implicit member functions, they are always marked as inline, but
1964 // they don't have a body until they're defined.
1965 if (MD->isImplicit())
1966 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001967
Douglas Gregora318efd2010-01-05 19:06:31 +00001968 if (MD->isInlineSpecified())
1969 continue;
Eli Friedman71a26d82009-12-06 20:50:05 +00001970
1971 if (MD->hasInlineBody())
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001972 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001973
Benjamin Kramer4a902082012-08-03 15:43:22 +00001974 // Ignore inline deleted or defaulted functions.
Benjamin Kramer73d1be72012-08-03 08:39:58 +00001975 if (!MD->isUserProvided())
1976 continue;
1977
John McCall6bd2a892013-01-25 22:31:03 +00001978 // In certain ABIs, ignore functions with out-of-line inline definitions.
1979 if (!allowInlineFunctions) {
1980 const FunctionDecl *Def;
1981 if (MD->hasBody(Def) && Def->isInlineSpecified())
1982 continue;
1983 }
1984
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001985 // We found it.
1986 return MD;
1987 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001988
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001989 return 0;
1990}
1991
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001992DiagnosticBuilder
1993RecordLayoutBuilder::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +00001994 return Context.getDiagnostics().Report(Loc, DiagID);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001995}
1996
John McCall5c1f1d02013-01-29 01:14:22 +00001997/// Does the target C++ ABI require us to skip over the tail-padding
1998/// of the given class (considering it as a base class) when allocating
1999/// objects?
2000static bool mustSkipTailPadding(TargetCXXABI ABI, const CXXRecordDecl *RD) {
2001 switch (ABI.getTailPaddingUseRules()) {
2002 case TargetCXXABI::AlwaysUseTailPadding:
2003 return false;
2004
2005 case TargetCXXABI::UseTailPaddingUnlessPOD03:
2006 // FIXME: To the extent that this is meant to cover the Itanium ABI
2007 // rules, we should implement the restrictions about over-sized
2008 // bitfields:
2009 //
2010 // http://mentorembedded.github.com/cxx-abi/abi.html#POD :
2011 // In general, a type is considered a POD for the purposes of
2012 // layout if it is a POD type (in the sense of ISO C++
2013 // [basic.types]). However, a POD-struct or POD-union (in the
2014 // sense of ISO C++ [class]) with a bitfield member whose
2015 // declared width is wider than the declared type of the
2016 // bitfield is not a POD for the purpose of layout. Similarly,
2017 // an array type is not a POD for the purpose of layout if the
2018 // element type of the array is not a POD for the purpose of
2019 // layout.
2020 //
2021 // Where references to the ISO C++ are made in this paragraph,
2022 // the Technical Corrigendum 1 version of the standard is
2023 // intended.
2024 return RD->isPOD();
2025
2026 case TargetCXXABI::UseTailPaddingUnlessPOD11:
2027 // This is equivalent to RD->getTypeForDecl().isCXX11PODType(),
2028 // but with a lot of abstraction penalty stripped off. This does
2029 // assume that these properties are set correctly even in C++98
2030 // mode; fortunately, that is true because we want to assign
2031 // consistently semantics to the type-traits intrinsics (or at
2032 // least as many of them as possible).
2033 return RD->isTrivial() && RD->isStandardLayout();
2034 }
2035
2036 llvm_unreachable("bad tail-padding use kind");
2037}
2038
Warren Hunt8f8bad72013-10-11 20:19:00 +00002039static bool isMsLayout(const RecordDecl* D) {
Warren Hunt55d8e822013-10-23 23:53:07 +00002040 return D->getASTContext().getTargetInfo().getCXXABI().isMicrosoft();
Warren Hunt8f8bad72013-10-11 20:19:00 +00002041}
2042
2043// This section contains an implementation of struct layout that is, up to the
2044// included tests, compatible with cl.exe (2012). The layout produced is
2045// significantly different than those produced by the Itanium ABI. Here we note
2046// the most important differences.
2047//
2048// * The alignment of bitfields in unions is ignored when computing the
2049// alignment of the union.
Alp Tokerf6a24ce2013-12-05 16:25:25 +00002050// * The existence of zero-width bitfield that occurs after anything other than
Warren Hunt8f8bad72013-10-11 20:19:00 +00002051// a non-zero length bitfield is ignored.
2052// * The Itanium equivalent vtable pointers are split into a vfptr (virtual
2053// function pointer) and a vbptr (virtual base pointer). They can each be
Warren Hunt55d8e822013-10-23 23:53:07 +00002054// shared with a, non-virtual bases. These bases need not be the same. vfptrs
2055// always occur at offset 0. vbptrs can occur at an
Warren Hunt8f8bad72013-10-11 20:19:00 +00002056// arbitrary offset and are placed after non-virtual bases but before fields.
2057// * Virtual bases sometimes require a 'vtordisp' field that is laid out before
2058// the virtual base and is used in conjunction with virtual overrides during
2059// construction and destruction.
2060// * vfptrs are allocated in a block of memory equal to the alignment of the
Warren Hunt55d8e822013-10-23 23:53:07 +00002061// fields and non-virtual bases at offset 0 in 32 bit mode and in a pointer
2062// sized block of memory in 64 bit mode.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002063// * vbptrs are allocated in a block of memory equal to the alignment of the
Warren Hunt55d8e822013-10-23 23:53:07 +00002064// fields and non-virtual bases. This block is at a potentially unaligned
2065// offset. If the allocation slot is unaligned and the alignment is less than
2066// or equal to the pointer size, additional space is allocated so that the
2067// pointer can be aligned properly. This causes very strange effects on the
2068// placement of objects after the allocated block. (see the code).
Warren Hunt8f8bad72013-10-11 20:19:00 +00002069// * vtordisps are allocated in a block of memory with size and alignment equal
2070// to the alignment of the completed structure (before applying __declspec(
Warren Hunt55d8e822013-10-23 23:53:07 +00002071// align())). The vtordisp always occur at the end of the allocation block,
2072// immediately prior to the virtual base.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002073// * The last zero sized non-virtual base is allocated after the placement of
2074// vbptr if one exists and can be placed at the end of the struct, potentially
2075// aliasing either the first member or another struct allocated after this
2076// one.
2077// * The last zero size virtual base may be placed at the end of the struct.
2078// and can potentially alias a zero sized type in the next struct.
Warren Hunt71140d62013-12-06 20:16:49 +00002079// * If the last field is a non-zero length bitfield, all virtual bases will
2080// have extra padding added before them for no obvious reason. The padding
2081// has the same number of bits as the type of the bitfield.
Warren Huntc0df47d2013-11-19 22:11:09 +00002082// * When laying out empty non-virtual bases, an extra byte of padding is added
2083// if the non-virtual base before the empty non-virtual base has a vbptr.
Warren Hunt049f6732013-12-06 19:54:25 +00002084// * The ABI attempts to avoid aliasing of zero sized bases by adding padding
2085// between bases or vbases with specific properties. The criteria for
2086// additional padding between two bases is that the first base is zero sized
2087// or has a zero sized subobject and the second base is zero sized or leads
2088// with a zero sized base (sharing of vfptrs can reorder the layout of the
2089// so the leading base is not always the first one declared). The padding
2090// added for bases is 1 byte. The padding added for vbases depends on the
2091// alignment of the object but is at least 4 bytes (in both 32 and 64 bit
2092// modes).
Warren Huntd640d7d2014-01-09 00:30:56 +00002093// * There is no concept of non-virtual alignment or any distinction between
2094// data size and non-virtual size.
Warren Huntf4518def2014-01-10 01:28:05 +00002095// * __declspec(align) on bitfields has the effect of changing the bitfield's
2096// alignment instead of its required alignment. This has implications on how
2097// it interacts with pragam pack.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002098
2099namespace {
2100struct MicrosoftRecordLayoutBuilder {
Warren Huntd640d7d2014-01-09 00:30:56 +00002101 struct ElementInfo {
2102 CharUnits Size;
2103 CharUnits Alignment;
2104 };
Warren Hunt8f8bad72013-10-11 20:19:00 +00002105 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
2106 MicrosoftRecordLayoutBuilder(const ASTContext &Context) : Context(Context) {}
2107private:
2108 MicrosoftRecordLayoutBuilder(const MicrosoftRecordLayoutBuilder &)
2109 LLVM_DELETED_FUNCTION;
2110 void operator=(const MicrosoftRecordLayoutBuilder &) LLVM_DELETED_FUNCTION;
2111public:
Warren Hunt8f8bad72013-10-11 20:19:00 +00002112 void layout(const RecordDecl *RD);
2113 void cxxLayout(const CXXRecordDecl *RD);
2114 /// \brief Initializes size and alignment and honors some flags.
2115 void initializeLayout(const RecordDecl *RD);
2116 /// \brief Initialized C++ layout, compute alignment and virtual alignment and
Alp Tokerf6a24ce2013-12-05 16:25:25 +00002117 /// existence of vfptrs and vbptrs. Alignment is needed before the vfptr is
Warren Hunt8f8bad72013-10-11 20:19:00 +00002118 /// laid out.
2119 void initializeCXXLayout(const CXXRecordDecl *RD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002120 void layoutNonVirtualBases(const CXXRecordDecl *RD);
Warren Huntd640d7d2014-01-09 00:30:56 +00002121 void layoutNonVirtualBase(const CXXRecordDecl *BaseDecl,
2122 const ASTRecordLayout &BaseLayout,
2123 const ASTRecordLayout *&PreviousBaseLayout);
2124 void injectVFPtr(const CXXRecordDecl *RD);
2125 void injectVBPtr(const CXXRecordDecl *RD);
2126 void injectVPtrs(const CXXRecordDecl *RD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002127 /// \brief Lays out the fields of the record. Also rounds size up to
2128 /// alignment.
2129 void layoutFields(const RecordDecl *RD);
2130 void layoutField(const FieldDecl *FD);
2131 void layoutBitField(const FieldDecl *FD);
2132 /// \brief Lays out a single zero-width bit-field in the record and handles
2133 /// special cases associated with zero-width bit-fields.
2134 void layoutZeroWidthBitField(const FieldDecl *FD);
2135 void layoutVirtualBases(const CXXRecordDecl *RD);
Warren Hunt1603e522013-12-10 01:44:39 +00002136 void finalizeLayout(const RecordDecl *RD);
Warren Huntd640d7d2014-01-09 00:30:56 +00002137 /// \brief Gets the size and alignment of a base taking pragma pack and
2138 /// __declspec(align) into account.
2139 ElementInfo getAdjustedElementInfo(const ASTRecordLayout &Layout);
2140 /// \brief Gets the size and alignment of a field taking pragma pack and
2141 /// __declspec(align) into account. It also updates RequiredAlignment as a
2142 /// side effect because it is most convenient to do so here.
2143 ElementInfo getAdjustedElementInfo(const FieldDecl *FD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002144 /// \brief Places a field at an offset in CharUnits.
2145 void placeFieldAtOffset(CharUnits FieldOffset) {
2146 FieldOffsets.push_back(Context.toBits(FieldOffset));
2147 }
2148 /// \brief Places a bitfield at a bit offset.
2149 void placeFieldAtBitOffset(uint64_t FieldOffset) {
2150 FieldOffsets.push_back(FieldOffset);
2151 }
2152 /// \brief Compute the set of virtual bases for which vtordisps are required.
2153 llvm::SmallPtrSet<const CXXRecordDecl *, 2>
2154 computeVtorDispSet(const CXXRecordDecl *RD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002155 const ASTContext &Context;
2156 /// \brief The size of the record being laid out.
2157 CharUnits Size;
Warren Huntd640d7d2014-01-09 00:30:56 +00002158 /// \brief The data alignment of the record layout.
2159 CharUnits DataSize;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002160 /// \brief The current alignment of the record layout.
2161 CharUnits Alignment;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002162 /// \brief The maximum allowed field alignment. This is set by #pragma pack.
2163 CharUnits MaxFieldAlignment;
Warren Hunt7b252d22013-12-06 00:01:17 +00002164 /// \brief The alignment that this record must obey. This is imposed by
2165 /// __declspec(align()) on the record itself or one of its fields or bases.
2166 CharUnits RequiredAlignment;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002167 /// \brief The size of the allocation of the currently active bitfield.
2168 /// This value isn't meaningful unless LastFieldIsNonZeroWidthBitfield
2169 /// is true.
2170 CharUnits CurrentBitfieldSize;
Warren Huntd640d7d2014-01-09 00:30:56 +00002171 /// \brief Offset to the virtual base table pointer (if one exists).
2172 CharUnits VBPtrOffset;
2173 /// \brief The size and alignment info of a pointer.
2174 ElementInfo PointerInfo;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002175 /// \brief The primary base class (if one exists).
2176 const CXXRecordDecl *PrimaryBase;
2177 /// \brief The class we share our vb-pointer with.
2178 const CXXRecordDecl *SharedVBPtrBase;
Warren Huntd640d7d2014-01-09 00:30:56 +00002179 /// \brief The collection of field offsets.
2180 SmallVector<uint64_t, 16> FieldOffsets;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002181 /// \brief Base classes and their offsets in the record.
2182 BaseOffsetsMapTy Bases;
2183 /// \brief virtual base classes and their offsets in the record.
2184 ASTRecordLayout::VBaseOffsetsMapTy VBases;
Warren Huntd640d7d2014-01-09 00:30:56 +00002185 /// \brief The number of remaining bits in our last bitfield allocation.
2186 /// This value isn't meaningful unless LastFieldIsNonZeroWidthBitfield is
2187 /// true.
2188 unsigned RemainingBitsInField;
2189 bool IsUnion : 1;
2190 /// \brief True if the last field laid out was a bitfield and was not 0
2191 /// width.
2192 bool LastFieldIsNonZeroWidthBitfield : 1;
2193 /// \brief True if the class has its own vftable pointer.
2194 bool HasOwnVFPtr : 1;
2195 /// \brief True if the class has a vbtable pointer.
2196 bool HasVBPtr : 1;
Warren Hunt55d8e822013-10-23 23:53:07 +00002197 /// \brief Lets us know if we're in 64-bit mode
Warren Hunt049f6732013-12-06 19:54:25 +00002198 bool Is64BitMode : 1;
2199 /// \brief True if this class contains a zero sized member or base or a base
2200 /// with a zero sized member or base. Only used for MS-ABI.
2201 bool HasZeroSizedSubObject : 1;
2202 /// \brief True if this class is zero sized or first base is zero sized or
2203 /// has this property. Only used for MS-ABI.
2204 bool LeadsWithZeroSizedBase : 1;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002205};
2206} // namespace
2207
Warren Huntd640d7d2014-01-09 00:30:56 +00002208MicrosoftRecordLayoutBuilder::ElementInfo
2209MicrosoftRecordLayoutBuilder::getAdjustedElementInfo(
2210 const ASTRecordLayout &Layout) {
2211 ElementInfo Info;
2212 Info.Alignment = Layout.getAlignment();
2213 // Respect pragma pack.
Warren Hunt7b252d22013-12-06 00:01:17 +00002214 if (!MaxFieldAlignment.isZero())
Warren Huntd640d7d2014-01-09 00:30:56 +00002215 Info.Alignment = std::min(Info.Alignment, MaxFieldAlignment);
2216 // Track zero-sized subobjects here where it's already available.
2217 if (Layout.hasZeroSizedSubObject())
2218 HasZeroSizedSubObject = true;
2219 // Respect required alignment, this is necessary because we may have adjusted
Warren Hunt94258912014-01-11 01:16:40 +00002220 // the alignment in the case of pragam pack. Note that the required alignment
2221 // doesn't actually apply to the struct alignment at this point.
2222 Alignment = std::max(Alignment, Info.Alignment);
Warren Huntd640d7d2014-01-09 00:30:56 +00002223 Info.Alignment = std::max(Info.Alignment, Layout.getRequiredAlignment());
Warren Hunt640015cb2014-01-09 23:51:31 +00002224 Info.Size = Layout.getDataSize();
Warren Huntd640d7d2014-01-09 00:30:56 +00002225 return Info;
Warren Hunt7b252d22013-12-06 00:01:17 +00002226}
2227
Warren Huntd640d7d2014-01-09 00:30:56 +00002228MicrosoftRecordLayoutBuilder::ElementInfo
2229MicrosoftRecordLayoutBuilder::getAdjustedElementInfo(
2230 const FieldDecl *FD) {
2231 ElementInfo Info;
Warren Huntf4518def2014-01-10 01:28:05 +00002232 // Respect align attributes.
2233 CharUnits FieldRequiredAlignment =
2234 Context.toCharUnitsFromBits(FD->getMaxAlignment());
Warren Hunt049f6732013-12-06 19:54:25 +00002235 // Respect attributes applied to subobjects of the field.
Warren Hunt7b252d22013-12-06 00:01:17 +00002236 if (const RecordType *RT =
2237 FD->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
2238 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RT->getDecl());
Warren Huntd640d7d2014-01-09 00:30:56 +00002239 // Get the element info for a layout, respecting pack.
2240 Info = getAdjustedElementInfo(Layout);
2241 // Nomally getAdjustedElementInfo returns the non-virtual size, which is
2242 // correct for bases but not for fields.
Reid Kleckner4f017ce2014-01-13 19:25:00 +00002243 Info.Size = Context.getTypeInfoInChars(FD->getType()).first;
Warren Huntd640d7d2014-01-09 00:30:56 +00002244 // Capture required alignment as a side-effect.
Warren Hunt7b252d22013-12-06 00:01:17 +00002245 RequiredAlignment = std::max(RequiredAlignment,
2246 Layout.getRequiredAlignment());
Warren Hunt7b252d22013-12-06 00:01:17 +00002247 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002248 else {
Reid Kleckner4f017ce2014-01-13 19:25:00 +00002249 llvm::tie(Info.Size, Info.Alignment) =
Warren Huntd640d7d2014-01-09 00:30:56 +00002250 Context.getTypeInfoInChars(FD->getType());
Warren Huntf4518def2014-01-10 01:28:05 +00002251 if (FD->isBitField() && FD->getMaxAlignment() != 0)
2252 Info.Alignment = std::max(Info.Alignment, FieldRequiredAlignment);
Warren Hunt26b94422014-01-14 00:54:36 +00002253 // Respect pragma pack.
2254 if (!MaxFieldAlignment.isZero())
2255 Info.Alignment = std::min(Info.Alignment, MaxFieldAlignment);
Warren Huntd640d7d2014-01-09 00:30:56 +00002256 }
2257 // Respect packed field attribute.
2258 if (FD->hasAttr<PackedAttr>())
2259 Info.Alignment = CharUnits::One();
Warren Huntf4518def2014-01-10 01:28:05 +00002260 // Take required alignment into account. __declspec(align) on bitfields
2261 // impacts the alignment rather than the required alignment.
2262 if (!FD->isBitField()) {
2263 Info.Alignment = std::max(Info.Alignment, FieldRequiredAlignment);
2264 // Capture required alignment as a side-effect.
2265 RequiredAlignment = std::max(RequiredAlignment, FieldRequiredAlignment);
2266 }
Warren Hunt94258912014-01-11 01:16:40 +00002267 // TODO: Add a Sema warning that MS ignores bitfield alignment in unions.
Warren Hunt26b94422014-01-14 00:54:36 +00002268 if (!(FD->isBitField() && IsUnion)) {
Warren Hunt94258912014-01-11 01:16:40 +00002269 Alignment = std::max(Alignment, Info.Alignment);
Warren Hunt26b94422014-01-14 00:54:36 +00002270 if (!MaxFieldAlignment.isZero())
2271 Alignment = std::min(Alignment, MaxFieldAlignment);
2272 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002273 return Info;
2274}
2275
2276void MicrosoftRecordLayoutBuilder::layout(const RecordDecl *RD) {
2277 initializeLayout(RD);
2278 layoutFields(RD);
2279 DataSize = Size = Size.RoundUpToAlignment(Alignment);
David Majnemer79a1c892014-02-12 00:43:02 +00002280 RequiredAlignment = std::max(
2281 RequiredAlignment, Context.toCharUnitsFromBits(RD->getMaxAlignment()));
Warren Huntd640d7d2014-01-09 00:30:56 +00002282 finalizeLayout(RD);
2283}
2284
2285void MicrosoftRecordLayoutBuilder::cxxLayout(const CXXRecordDecl *RD) {
2286 initializeLayout(RD);
2287 initializeCXXLayout(RD);
2288 layoutNonVirtualBases(RD);
2289 layoutFields(RD);
2290 injectVPtrs(RD);
2291 DataSize = Size = Size.RoundUpToAlignment(Alignment);
David Majnemer79a1c892014-02-12 00:43:02 +00002292 RequiredAlignment = std::max(
2293 RequiredAlignment, Context.toCharUnitsFromBits(RD->getMaxAlignment()));
Warren Huntd640d7d2014-01-09 00:30:56 +00002294 layoutVirtualBases(RD);
2295 finalizeLayout(RD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002296}
2297
2298void MicrosoftRecordLayoutBuilder::initializeLayout(const RecordDecl *RD) {
2299 IsUnion = RD->isUnion();
Warren Hunt5ae586a2013-11-01 23:59:41 +00002300 Is64BitMode = Context.getTargetInfo().getPointerWidth(0) == 64;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002301 Size = CharUnits::Zero();
2302 Alignment = CharUnits::One();
Warren Hunt7b252d22013-12-06 00:01:17 +00002303 // In 64-bit mode we always perform an alignment step after laying out vbases.
2304 // In 32-bit mode we do not. The check to see if we need to perform alignment
2305 // checks the RequiredAlignment field and performs alignment if it isn't 0.
2306 RequiredAlignment = Is64BitMode ? CharUnits::One() : CharUnits::Zero();
Warren Hunt8f8bad72013-10-11 20:19:00 +00002307 // Compute the maximum field alignment.
2308 MaxFieldAlignment = CharUnits::Zero();
2309 // Honor the default struct packing maximum alignment flag.
2310 if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct)
Warren Huntf4518def2014-01-10 01:28:05 +00002311 MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
2312 // Honor the packing attribute. The MS-ABI ignores pragma pack if its larger
2313 // than the pointer size.
2314 if (const MaxFieldAlignmentAttr *MFAA = RD->getAttr<MaxFieldAlignmentAttr>()){
2315 unsigned PackedAlignment = MFAA->getAlignment();
2316 if (PackedAlignment <= Context.getTargetInfo().getPointerWidth(0))
2317 MaxFieldAlignment = Context.toCharUnitsFromBits(PackedAlignment);
2318 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002319 // Packed attribute forces max field alignment to be 1.
2320 if (RD->hasAttr<PackedAttr>())
2321 MaxFieldAlignment = CharUnits::One();
2322}
2323
Warren Hunt8f8bad72013-10-11 20:19:00 +00002324void
2325MicrosoftRecordLayoutBuilder::initializeCXXLayout(const CXXRecordDecl *RD) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002326 HasZeroSizedSubObject = false;
Warren Hunt049f6732013-12-06 19:54:25 +00002327 LeadsWithZeroSizedBase = false;
Warren Huntd640d7d2014-01-09 00:30:56 +00002328 HasOwnVFPtr = false;
2329 HasVBPtr = false;
2330 PrimaryBase = 0;
2331 SharedVBPtrBase = 0;
2332 // Calculate pointer size and alignment. These are used for vfptr and vbprt
2333 // injection.
2334 PointerInfo.Size =
2335 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
2336 PointerInfo.Alignment = PointerInfo.Size;
2337 // Respect pragma pack.
2338 if (!MaxFieldAlignment.isZero())
2339 PointerInfo.Alignment = std::min(PointerInfo.Alignment, MaxFieldAlignment);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002340}
2341
2342void
2343MicrosoftRecordLayoutBuilder::layoutNonVirtualBases(const CXXRecordDecl *RD) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002344 // The MS-ABI lays out all bases that contain leading vfptrs before it lays
2345 // out any bases that do not contain vfptrs. We implement this as two passes
2346 // over the bases. This approach guarantees that the primary base is laid out
2347 // first. We use these passes to calculate some additional aggregated
2348 // information about the bases, such as reqruied alignment and the presence of
2349 // zero sized members.
2350 const ASTRecordLayout* PreviousBaseLayout = 0;
2351 // Iterate through the bases and lay out the non-virtual ones.
2352 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
2353 e = RD->bases_end();
2354 i != e; ++i) {
2355 const CXXRecordDecl *BaseDecl = i->getType()->getAsCXXRecordDecl();
2356 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
Warren Huntd640d7d2014-01-09 00:30:56 +00002357 // Mark and skip virtual bases.
2358 if (i->isVirtual()) {
2359 HasVBPtr = true;
2360 continue;
2361 }
David Majnemer79a1c892014-02-12 00:43:02 +00002362 // Track RequiredAlignment for all bases in this pass.
2363 RequiredAlignment = std::max(RequiredAlignment,
2364 BaseLayout.getRequiredAlignment());
Warren Huntd640d7d2014-01-09 00:30:56 +00002365 // Check fo a base to share a VBPtr with.
2366 if (!SharedVBPtrBase && BaseLayout.hasVBPtr()) {
2367 SharedVBPtrBase = BaseDecl;
2368 HasVBPtr = true;
2369 }
2370 // Only lay out bases with extendable VFPtrs on the first pass.
2371 if (!BaseLayout.hasExtendableVFPtr())
2372 continue;
2373 // If we don't have a primary base, this one qualifies.
Warren Huntbadf9e02014-01-13 19:55:52 +00002374 if (!PrimaryBase) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002375 PrimaryBase = BaseDecl;
Warren Huntbadf9e02014-01-13 19:55:52 +00002376 LeadsWithZeroSizedBase = BaseLayout.leadsWithZeroSizedBase();
2377 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002378 // Lay out the base.
2379 layoutNonVirtualBase(BaseDecl, BaseLayout, PreviousBaseLayout);
2380 }
2381 // Figure out if we need a fresh VFPtr for this class.
2382 if (!PrimaryBase && RD->isDynamicClass())
2383 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
2384 e = RD->method_end();
2385 !HasOwnVFPtr && i != e; ++i)
2386 HasOwnVFPtr = i->isVirtual() && i->size_overridden_methods() == 0;
2387 // If we don't have a primary base then we have a leading object that could
2388 // itself lead with a zero-sized object, something we track.
2389 bool CheckLeadingLayout = !PrimaryBase;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002390 // Iterate through the bases and lay out the non-virtual ones.
2391 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
2392 e = RD->bases_end();
2393 i != e; ++i) {
2394 if (i->isVirtual())
2395 continue;
Reid Klecknere7106c92013-12-18 23:17:05 +00002396 const CXXRecordDecl *BaseDecl = i->getType()->getAsCXXRecordDecl();
Warren Huntd640d7d2014-01-09 00:30:56 +00002397 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
2398 // Only lay out bases without extendable VFPtrs on the second pass.
2399 if (BaseLayout.hasExtendableVFPtr())
Warren Hunt4431fe62013-12-12 22:33:37 +00002400 continue;
Warren Huntd640d7d2014-01-09 00:30:56 +00002401 // If this is the first layout, check to see if it leads with a zero sized
2402 // object. If it does, so do we.
2403 if (CheckLeadingLayout) {
2404 CheckLeadingLayout = false;
2405 LeadsWithZeroSizedBase = BaseLayout.leadsWithZeroSizedBase();
Warren Hunt049f6732013-12-06 19:54:25 +00002406 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002407 // Lay out the base.
2408 layoutNonVirtualBase(BaseDecl, BaseLayout, PreviousBaseLayout);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002409 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002410 // Set our VBPtroffset if we know it at this point.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002411 if (!HasVBPtr)
2412 VBPtrOffset = CharUnits::fromQuantity(-1);
Warren Hunt6eba9072014-01-14 00:31:30 +00002413 else if (SharedVBPtrBase) {
2414 const ASTRecordLayout &Layout = Context.getASTRecordLayout(SharedVBPtrBase);
2415 VBPtrOffset = Bases[SharedVBPtrBase] + Layout.getVBPtrOffset();
2416 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002417}
2418
2419void MicrosoftRecordLayoutBuilder::layoutNonVirtualBase(
2420 const CXXRecordDecl *BaseDecl,
2421 const ASTRecordLayout &BaseLayout,
2422 const ASTRecordLayout *&PreviousBaseLayout) {
Warren Huntf4518def2014-01-10 01:28:05 +00002423 // Insert padding between two bases if the left first one is zero sized or
2424 // contains a zero sized subobject and the right is zero sized or one leads
2425 // with a zero sized base.
2426 if (PreviousBaseLayout && PreviousBaseLayout->hasZeroSizedSubObject() &&
2427 BaseLayout.leadsWithZeroSizedBase())
2428 Size++;
2429 ElementInfo Info = getAdjustedElementInfo(BaseLayout);
2430 CharUnits BaseOffset = Size.RoundUpToAlignment(Info.Alignment);
2431 Bases.insert(std::make_pair(BaseDecl, BaseOffset));
2432 Size = BaseOffset + BaseLayout.getDataSize();
Warren Huntf4518def2014-01-10 01:28:05 +00002433 PreviousBaseLayout = &BaseLayout;
Warren Huntd640d7d2014-01-09 00:30:56 +00002434 VBPtrOffset = Size;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002435}
2436
2437void MicrosoftRecordLayoutBuilder::layoutFields(const RecordDecl *RD) {
2438 LastFieldIsNonZeroWidthBitfield = false;
2439 for (RecordDecl::field_iterator Field = RD->field_begin(),
2440 FieldEnd = RD->field_end();
2441 Field != FieldEnd; ++Field)
2442 layoutField(*Field);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002443}
2444
2445void MicrosoftRecordLayoutBuilder::layoutField(const FieldDecl *FD) {
2446 if (FD->isBitField()) {
2447 layoutBitField(FD);
2448 return;
2449 }
2450 LastFieldIsNonZeroWidthBitfield = false;
Warren Huntd640d7d2014-01-09 00:30:56 +00002451 ElementInfo Info = getAdjustedElementInfo(FD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002452 if (IsUnion) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002453 placeFieldAtOffset(CharUnits::Zero());
2454 Size = std::max(Size, Info.Size);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002455 } else {
Warren Huntd640d7d2014-01-09 00:30:56 +00002456 CharUnits FieldOffset = Size.RoundUpToAlignment(Info.Alignment);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002457 placeFieldAtOffset(FieldOffset);
Warren Huntd640d7d2014-01-09 00:30:56 +00002458 Size = FieldOffset + Info.Size;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002459 }
2460}
2461
2462void MicrosoftRecordLayoutBuilder::layoutBitField(const FieldDecl *FD) {
2463 unsigned Width = FD->getBitWidthValue(Context);
2464 if (Width == 0) {
2465 layoutZeroWidthBitField(FD);
2466 return;
2467 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002468 ElementInfo Info = getAdjustedElementInfo(FD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002469 // Clamp the bitfield to a containable size for the sake of being able
2470 // to lay them out. Sema will throw an error.
Warren Huntd640d7d2014-01-09 00:30:56 +00002471 if (Width > Context.toBits(Info.Size))
2472 Width = Context.toBits(Info.Size);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002473 // Check to see if this bitfield fits into an existing allocation. Note:
2474 // MSVC refuses to pack bitfields of formal types with different sizes
2475 // into the same allocation.
2476 if (!IsUnion && LastFieldIsNonZeroWidthBitfield &&
Warren Huntd640d7d2014-01-09 00:30:56 +00002477 CurrentBitfieldSize == Info.Size && Width <= RemainingBitsInField) {
Warren Hunt8f8bad72013-10-11 20:19:00 +00002478 placeFieldAtBitOffset(Context.toBits(Size) - RemainingBitsInField);
2479 RemainingBitsInField -= Width;
2480 return;
2481 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002482 LastFieldIsNonZeroWidthBitfield = true;
Warren Huntd640d7d2014-01-09 00:30:56 +00002483 CurrentBitfieldSize = Info.Size;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002484 if (IsUnion) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002485 placeFieldAtOffset(CharUnits::Zero());
2486 Size = std::max(Size, Info.Size);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002487 } else {
2488 // Allocate a new block of memory and place the bitfield in it.
Warren Huntd640d7d2014-01-09 00:30:56 +00002489 CharUnits FieldOffset = Size.RoundUpToAlignment(Info.Alignment);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002490 placeFieldAtOffset(FieldOffset);
Warren Huntd640d7d2014-01-09 00:30:56 +00002491 Size = FieldOffset + Info.Size;
Warren Huntd640d7d2014-01-09 00:30:56 +00002492 RemainingBitsInField = Context.toBits(Info.Size) - Width;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002493 }
2494}
2495
2496void
2497MicrosoftRecordLayoutBuilder::layoutZeroWidthBitField(const FieldDecl *FD) {
2498 // Zero-width bitfields are ignored unless they follow a non-zero-width
2499 // bitfield.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002500 if (!LastFieldIsNonZeroWidthBitfield) {
2501 placeFieldAtOffset(IsUnion ? CharUnits::Zero() : Size);
2502 // TODO: Add a Sema warning that MS ignores alignment for zero
Alp Tokerd4733632013-12-05 04:47:09 +00002503 // sized bitfields that occur after zero-size bitfields or non-bitfields.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002504 return;
2505 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002506 LastFieldIsNonZeroWidthBitfield = false;
Warren Huntd640d7d2014-01-09 00:30:56 +00002507 ElementInfo Info = getAdjustedElementInfo(FD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002508 if (IsUnion) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002509 placeFieldAtOffset(CharUnits::Zero());
2510 Size = std::max(Size, Info.Size);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002511 } else {
2512 // Round up the current record size to the field's alignment boundary.
Warren Huntd640d7d2014-01-09 00:30:56 +00002513 CharUnits FieldOffset = Size.RoundUpToAlignment(Info.Alignment);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002514 placeFieldAtOffset(FieldOffset);
2515 Size = FieldOffset;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002516 }
2517}
2518
Warren Huntd640d7d2014-01-09 00:30:56 +00002519void MicrosoftRecordLayoutBuilder::injectVBPtr(const CXXRecordDecl *RD) {
Warren Hunt6eba9072014-01-14 00:31:30 +00002520 if (!HasVBPtr || SharedVBPtrBase)
Warren Huntd640d7d2014-01-09 00:30:56 +00002521 return;
Warren Huntd640d7d2014-01-09 00:30:56 +00002522 // Inject the VBPointer at the injection site.
2523 CharUnits InjectionSite = VBPtrOffset;
2524 // But before we do, make sure it's properly aligned.
2525 VBPtrOffset = VBPtrOffset.RoundUpToAlignment(PointerInfo.Alignment);
2526 // Determine where the first field should be laid out after the vbptr.
2527 CharUnits FieldStart = VBPtrOffset + PointerInfo.Size;
2528 // Make sure that the amount we push the fields back by is a multiple of the
2529 // alignment.
David Majnemer79a1c892014-02-12 00:43:02 +00002530 CharUnits Offset = (FieldStart - InjectionSite).RoundUpToAlignment(
2531 std::max(RequiredAlignment, Alignment));
Warren Huntd640d7d2014-01-09 00:30:56 +00002532 // Increase the size of the object and push back all fields by the offset
2533 // amount.
2534 Size += Offset;
2535 for (SmallVector<uint64_t, 16>::iterator i = FieldOffsets.begin(),
2536 e = FieldOffsets.end();
2537 i != e; ++i)
2538 *i += Context.toBits(Offset);
2539 for (BaseOffsetsMapTy::iterator i = Bases.begin(), e = Bases.end();
2540 i != e; ++i)
2541 if (i->second >= InjectionSite)
2542 i->second += Offset;
Warren Hunt87c2b042014-01-10 23:32:32 +00002543 // The presence of a vbptr suppresses zero sized objects that are not in
2544 // virtual bases.
2545 HasZeroSizedSubObject = false;
Warren Huntd640d7d2014-01-09 00:30:56 +00002546}
2547
2548void MicrosoftRecordLayoutBuilder::injectVFPtr(const CXXRecordDecl *RD) {
2549 if (!HasOwnVFPtr)
2550 return;
2551 // Make sure that the amount we push the struct back by is a multiple of the
2552 // alignment.
David Majnemer79a1c892014-02-12 00:43:02 +00002553 CharUnits Offset = PointerInfo.Size.RoundUpToAlignment(
2554 std::max(RequiredAlignment, Alignment));
Warren Huntd640d7d2014-01-09 00:30:56 +00002555 // Increase the size of the object and push back all fields, the vbptr and all
2556 // bases by the offset amount.
2557 Size += Offset;
David Majnemer79a1c892014-02-12 00:43:02 +00002558 for (SmallVectorImpl<uint64_t>::iterator i = FieldOffsets.begin(),
Warren Huntd640d7d2014-01-09 00:30:56 +00002559 e = FieldOffsets.end();
2560 i != e; ++i)
2561 *i += Context.toBits(Offset);
2562 if (HasVBPtr)
2563 VBPtrOffset += Offset;
2564 for (BaseOffsetsMapTy::iterator i = Bases.begin(), e = Bases.end();
2565 i != e; ++i)
2566 i->second += Offset;
Warren Huntd640d7d2014-01-09 00:30:56 +00002567}
2568
2569void MicrosoftRecordLayoutBuilder::injectVPtrs(const CXXRecordDecl *RD) {
David Blaikie461f1ea2014-01-09 02:34:06 +00002570 if (!(HasOwnVFPtr || (HasVBPtr && !SharedVBPtrBase)))
Warren Huntd640d7d2014-01-09 00:30:56 +00002571 return;
2572 if (!Is64BitMode || RequiredAlignment <= CharUnits::fromQuantity(8)) {
2573 // Note that the VBPtr is injected first. It depends on the alignment of
2574 // the object *before* the alignment is updated by inserting a pointer into
2575 // the record.
2576 injectVBPtr(RD);
2577 injectVFPtr(RD);
Warren Hunt94258912014-01-11 01:16:40 +00002578 Alignment = std::max(Alignment, PointerInfo.Alignment);
Warren Huntd640d7d2014-01-09 00:30:56 +00002579 return;
2580 }
2581 // In 64-bit mode, structs with RequiredAlignment greater than 8 get special
2582 // layout rules. Likely this is to avoid excessive padding intruced around
2583 // the vfptrs and vbptrs. The special rules involve re-laying out the struct
2584 // and inserting the vfptr and vbptr as if they were fields/bases.
2585 FieldOffsets.clear();
2586 Bases.clear();
2587 Size = CharUnits::Zero();
Warren Hunt94258912014-01-11 01:16:40 +00002588 Alignment = std::max(Alignment, PointerInfo.Alignment);
Warren Huntd640d7d2014-01-09 00:30:56 +00002589 if (HasOwnVFPtr)
2590 Size = PointerInfo.Size;
2591 layoutNonVirtualBases(RD);
2592 if (HasVBPtr && !SharedVBPtrBase) {
2593 const CXXRecordDecl *PenultBaseDecl = 0;
2594 const CXXRecordDecl *LastBaseDecl = 0;
2595 // Iterate through the bases and find the last two non-virtual bases.
2596 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
2597 e = RD->bases_end();
2598 i != e; ++i) {
2599 if (i->isVirtual())
2600 continue;
2601 const CXXRecordDecl *BaseDecl = i->getType()->getAsCXXRecordDecl();
2602 if (!LastBaseDecl || Bases[BaseDecl] > Bases[LastBaseDecl]) {
2603 PenultBaseDecl = LastBaseDecl;
2604 LastBaseDecl = BaseDecl;
2605 }
2606 }
2607 const ASTRecordLayout *PenultBaseLayout = PenultBaseDecl ?
2608 &Context.getASTRecordLayout(PenultBaseDecl) : 0;
2609 const ASTRecordLayout *LastBaseLayout = LastBaseDecl ?
2610 &Context.getASTRecordLayout(LastBaseDecl) : 0;
2611 // Calculate the vbptr offset. The rule is different than in the general
2612 // case layout. Particularly, if the last two non-virtual bases are both
2613 // zero sized, the site of the vbptr is *before* the padding that occurs
2614 // between the two zero sized bases and the vbptr potentially aliases with
2615 // the first of these two bases. We have no understanding of why this is
2616 // different from the general case layout but it may have to do with lazy
2617 // placement of zero sized bases.
2618 VBPtrOffset = Size;
Warren Hunt640015cb2014-01-09 23:51:31 +00002619 if (LastBaseLayout && LastBaseLayout->getDataSize().isZero()) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002620 VBPtrOffset = Bases[LastBaseDecl];
Warren Hunt640015cb2014-01-09 23:51:31 +00002621 if (PenultBaseLayout && PenultBaseLayout->getDataSize().isZero())
Warren Huntd640d7d2014-01-09 00:30:56 +00002622 VBPtrOffset = Bases[PenultBaseDecl];
2623 }
2624 // Once we've located a spot for the vbptr, place it.
2625 VBPtrOffset = VBPtrOffset.RoundUpToAlignment(PointerInfo.Alignment);
2626 Size = VBPtrOffset + PointerInfo.Size;
Warren Hunt640015cb2014-01-09 23:51:31 +00002627 if (LastBaseLayout && LastBaseLayout->getDataSize().isZero()) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002628 // Add the padding between zero sized bases after the vbptr.
Warren Hunt640015cb2014-01-09 23:51:31 +00002629 if (PenultBaseLayout && PenultBaseLayout->getDataSize().isZero())
Warren Huntd640d7d2014-01-09 00:30:56 +00002630 Size += CharUnits::One();
2631 Size = Size.RoundUpToAlignment(LastBaseLayout->getRequiredAlignment());
2632 Bases[LastBaseDecl] = Size;
2633 }
2634 }
2635 layoutFields(RD);
Warren Hunt87c2b042014-01-10 23:32:32 +00002636 // The presence of a vbptr suppresses zero sized objects that are not in
2637 // virtual bases.
2638 HasZeroSizedSubObject = false;
Warren Hunt1603e522013-12-10 01:44:39 +00002639}
2640
Warren Hunt8f8bad72013-10-11 20:19:00 +00002641void MicrosoftRecordLayoutBuilder::layoutVirtualBases(const CXXRecordDecl *RD) {
2642 if (!HasVBPtr)
2643 return;
Warren Huntd640d7d2014-01-09 00:30:56 +00002644 // Vtordisps are always 4 bytes (even in 64-bit mode)
2645 CharUnits VtorDispSize = CharUnits::fromQuantity(4);
2646 CharUnits VtorDispAlignment = VtorDispSize;
2647 // vtordisps respect pragma pack.
2648 if (!MaxFieldAlignment.isZero())
2649 VtorDispAlignment = std::min(VtorDispAlignment, MaxFieldAlignment);
2650 // The alignment of the vtordisp is at least the required alignment of the
2651 // entire record. This requirement may be present to support vtordisp
2652 // injection.
David Majnemer79a1c892014-02-12 00:43:02 +00002653 for (CXXRecordDecl::base_class_const_iterator i = RD->vbases_begin(),
2654 e = RD->vbases_end();
2655 i != e; ++i) {
2656 const CXXRecordDecl *BaseDecl = i->getType()->getAsCXXRecordDecl();
2657 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
2658 RequiredAlignment =
2659 std::max(RequiredAlignment, BaseLayout.getRequiredAlignment());
2660 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002661 VtorDispAlignment = std::max(VtorDispAlignment, RequiredAlignment);
2662 // Compute the vtordisp set.
2663 llvm::SmallPtrSet<const CXXRecordDecl *, 2> HasVtordispSet =
Warren Hunt8f8bad72013-10-11 20:19:00 +00002664 computeVtorDispSet(RD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002665 // Iterate through the virtual bases and lay them out.
Warren Huntd640d7d2014-01-09 00:30:56 +00002666 const ASTRecordLayout* PreviousBaseLayout = 0;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002667 for (CXXRecordDecl::base_class_const_iterator i = RD->vbases_begin(),
2668 e = RD->vbases_end();
2669 i != e; ++i) {
Reid Klecknere7106c92013-12-18 23:17:05 +00002670 const CXXRecordDecl *BaseDecl = i->getType()->getAsCXXRecordDecl();
Warren Huntd640d7d2014-01-09 00:30:56 +00002671 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
2672 bool HasVtordisp = HasVtordispSet.count(BaseDecl);
Warren Hunt71140d62013-12-06 20:16:49 +00002673 // If the last field we laid out was a non-zero length bitfield then add
2674 // some extra padding for no obvious reason.
2675 if (LastFieldIsNonZeroWidthBitfield)
2676 Size += CurrentBitfieldSize;
Warren Huntd640d7d2014-01-09 00:30:56 +00002677 // Insert padding between two bases if the left first one is zero sized or
2678 // contains a zero sized subobject and the right is zero sized or one leads
2679 // with a zero sized base. The padding between virtual bases is 4
2680 // bytes (in both 32 and 64 bits modes) and always involves rounding up to
2681 // the required alignment, we don't know why.
2682 if (PreviousBaseLayout && PreviousBaseLayout->hasZeroSizedSubObject() &&
2683 BaseLayout.leadsWithZeroSizedBase())
2684 Size = Size.RoundUpToAlignment(VtorDispAlignment) + VtorDispSize;
2685 // Insert the vtordisp.
2686 if (HasVtordisp)
2687 Size = Size.RoundUpToAlignment(VtorDispAlignment) + VtorDispSize;
2688 // Insert the virtual base.
2689 ElementInfo Info = getAdjustedElementInfo(BaseLayout);
Warren Huntf4518def2014-01-10 01:28:05 +00002690 CharUnits BaseOffset = Size.RoundUpToAlignment(Info.Alignment);
Warren Huntd640d7d2014-01-09 00:30:56 +00002691 VBases.insert(std::make_pair(BaseDecl,
2692 ASTRecordLayout::VBaseInfo(BaseOffset, HasVtordisp)));
Warren Hunt640015cb2014-01-09 23:51:31 +00002693 Size = BaseOffset + BaseLayout.getDataSize();
Warren Huntd640d7d2014-01-09 00:30:56 +00002694 PreviousBaseLayout = &BaseLayout;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002695 }
2696}
2697
Warren Huntc3384312013-12-11 22:28:32 +00002698void MicrosoftRecordLayoutBuilder::finalizeLayout(const RecordDecl *RD) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002699 // Respect required alignment. Note that in 32-bit mode Required alignment
2700 // may be 0 nad cause size not to be updated.
2701 if (!RequiredAlignment.isZero()) {
2702 Alignment = std::max(Alignment, RequiredAlignment);
2703 Size = Size.RoundUpToAlignment(Alignment);
2704 }
2705 // Zero-sized structures have size equal to their alignment.
Warren Hunt049f6732013-12-06 19:54:25 +00002706 if (Size.isZero()) {
2707 HasZeroSizedSubObject = true;
2708 LeadsWithZeroSizedBase = true;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002709 Size = Alignment;
Warren Hunt049f6732013-12-06 19:54:25 +00002710 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002711}
2712
2713static bool
2714RequiresVtordisp(const llvm::SmallPtrSet<const CXXRecordDecl *, 2> &HasVtordisp,
2715 const CXXRecordDecl *RD) {
2716 if (HasVtordisp.count(RD))
2717 return true;
2718 // If any of a virtual bases non-virtual bases (recursively) requires a
2719 // vtordisp than so does this virtual base.
2720 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
2721 e = RD->bases_end();
2722 i != e; ++i)
2723 if (!i->isVirtual() &&
2724 RequiresVtordisp(
2725 HasVtordisp,
2726 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl())))
2727 return true;
2728 return false;
2729}
2730
2731llvm::SmallPtrSet<const CXXRecordDecl *, 2>
2732MicrosoftRecordLayoutBuilder::computeVtorDispSet(const CXXRecordDecl *RD) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002733 llvm::SmallPtrSet<const CXXRecordDecl *, 2> HasVtordispSet;
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00002734
2735 // /vd0 or #pragma vtordisp(0): Never use vtordisps when used as a vbase.
2736 if (RD->getMSVtorDispMode() == MSVtorDispAttr::Never)
2737 return HasVtordispSet;
2738
2739 // /vd2 or #pragma vtordisp(2): Always use vtordisps for virtual bases with
2740 // vftables.
2741 if (RD->getMSVtorDispMode() == MSVtorDispAttr::ForVFTable) {
2742 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
2743 E = RD->vbases_end();
2744 I != E; ++I) {
2745 const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
2746 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
2747 if (Layout.hasExtendableVFPtr())
2748 HasVtordispSet.insert(BaseDecl);
2749 }
2750 return HasVtordispSet;
2751 }
2752
2753 // /vd1 or #pragma vtordisp(1): Try to guess based on whether we think it's
2754 // possible for a partially constructed object with virtual base overrides to
2755 // escape a non-trivial constructor.
2756 assert(RD->getMSVtorDispMode() == MSVtorDispAttr::ForVBaseOverride);
2757
Warren Hunt8f8bad72013-10-11 20:19:00 +00002758 // If any of our bases need a vtordisp for this type, so do we. Check our
2759 // direct bases for vtordisp requirements.
2760 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
2761 e = RD->bases_end();
2762 i != e; ++i) {
2763 const CXXRecordDecl *BaseDecl =
2764 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
2765 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
2766 for (ASTRecordLayout::VBaseOffsetsMapTy::const_iterator
2767 bi = Layout.getVBaseOffsetsMap().begin(),
2768 be = Layout.getVBaseOffsetsMap().end();
2769 bi != be; ++bi)
2770 if (bi->second.hasVtorDisp())
Warren Huntd640d7d2014-01-09 00:30:56 +00002771 HasVtordispSet.insert(bi->first);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002772 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002773 // If we define a constructor or destructor and override a function that is
2774 // defined in a virtual base's vtable, that virtual bases need a vtordisp.
2775 // Here we collect a list of classes with vtables for which our virtual bases
2776 // actually live. The virtual bases with this property will require
2777 // vtordisps. In addition, virtual bases that contain non-virtual bases that
2778 // define functions we override also require vtordisps, this case is checked
2779 // explicitly below.
2780 if (RD->hasUserDeclaredConstructor() || RD->hasUserDeclaredDestructor()) {
2781 llvm::SmallPtrSet<const CXXMethodDecl *, 8> Work;
2782 // Seed the working set with our non-destructor virtual methods.
2783 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
2784 e = RD->method_end();
2785 i != e; ++i)
Warren Hunt42be7762013-10-14 20:14:09 +00002786 if ((*i)->isVirtual() && !isa<CXXDestructorDecl>(*i))
Warren Hunt8f8bad72013-10-11 20:19:00 +00002787 Work.insert(*i);
2788 while (!Work.empty()) {
2789 const CXXMethodDecl *MD = *Work.begin();
2790 CXXMethodDecl::method_iterator i = MD->begin_overridden_methods(),
2791 e = MD->end_overridden_methods();
2792 if (i == e)
2793 // If a virtual method has no-overrides it lives in its parent's vtable.
Warren Huntd640d7d2014-01-09 00:30:56 +00002794 HasVtordispSet.insert(MD->getParent());
Warren Hunt8f8bad72013-10-11 20:19:00 +00002795 else
2796 Work.insert(i, e);
2797 // We've finished processing this element, remove it from the working set.
2798 Work.erase(MD);
2799 }
2800 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002801 // Re-check all of our vbases for vtordisp requirements (in case their
2802 // non-virtual bases have vtordisp requirements).
2803 for (CXXRecordDecl::base_class_const_iterator i = RD->vbases_begin(),
2804 e = RD->vbases_end();
2805 i != e; ++i) {
2806 const CXXRecordDecl *BaseDecl = i->getType()->getAsCXXRecordDecl();
Warren Huntd640d7d2014-01-09 00:30:56 +00002807 if (!HasVtordispSet.count(BaseDecl) &&
2808 RequiresVtordisp(HasVtordispSet, BaseDecl))
2809 HasVtordispSet.insert(BaseDecl);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002810 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002811 return HasVtordispSet;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002812}
2813
2814/// \brief Get or compute information about the layout of the specified record
2815/// (struct/union/class), which indicates its size and field position
2816/// information.
2817const ASTRecordLayout *
2818ASTContext::BuildMicrosoftASTRecordLayout(const RecordDecl *D) const {
2819 MicrosoftRecordLayoutBuilder Builder(*this);
2820 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
2821 Builder.cxxLayout(RD);
2822 return new (*this) ASTRecordLayout(
Warren Hunt7b252d22013-12-06 00:01:17 +00002823 *this, Builder.Size, Builder.Alignment, Builder.RequiredAlignment,
Warren Huntd640d7d2014-01-09 00:30:56 +00002824 Builder.HasOwnVFPtr,
2825 Builder.HasOwnVFPtr || Builder.PrimaryBase,
Timur Iskhodzhanov2c9341f2013-11-08 11:45:35 +00002826 Builder.VBPtrOffset, Builder.DataSize, Builder.FieldOffsets.data(),
Warren Hunt8f8bad72013-10-11 20:19:00 +00002827 Builder.FieldOffsets.size(), Builder.DataSize,
Warren Huntd640d7d2014-01-09 00:30:56 +00002828 Builder.Alignment, CharUnits::Zero(), Builder.PrimaryBase,
Warren Hunt049f6732013-12-06 19:54:25 +00002829 false, Builder.SharedVBPtrBase,
2830 Builder.HasZeroSizedSubObject, Builder.LeadsWithZeroSizedBase,
2831 Builder.Bases, Builder.VBases);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002832 } else {
2833 Builder.layout(D);
2834 return new (*this) ASTRecordLayout(
Warren Hunt7b252d22013-12-06 00:01:17 +00002835 *this, Builder.Size, Builder.Alignment, Builder.RequiredAlignment,
2836 Builder.Size, Builder.FieldOffsets.data(), Builder.FieldOffsets.size());
Warren Hunt8f8bad72013-10-11 20:19:00 +00002837 }
2838}
2839
Anders Carlssondf291d82010-05-26 04:56:53 +00002840/// getASTRecordLayout - Get or compute information about the layout of the
2841/// specified record (struct/union/class), which indicates its size and field
2842/// position information.
Jay Foad39c79802011-01-12 09:06:06 +00002843const ASTRecordLayout &
2844ASTContext::getASTRecordLayout(const RecordDecl *D) const {
John McCall0710e552011-10-07 02:39:22 +00002845 // These asserts test different things. A record has a definition
2846 // as soon as we begin to parse the definition. That definition is
2847 // not a complete definition (which is what isDefinition() tests)
2848 // until we *finish* parsing the definition.
Sean Callanan56c19892012-02-08 00:04:52 +00002849
2850 if (D->hasExternalLexicalStorage() && !D->getDefinition())
2851 getExternalSource()->CompleteType(const_cast<RecordDecl*>(D));
2852
Anders Carlssondf291d82010-05-26 04:56:53 +00002853 D = D->getDefinition();
2854 assert(D && "Cannot get layout of forward declarations!");
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00002855 assert(!D->isInvalidDecl() && "Cannot get layout of invalid decl!");
John McCallf937c022011-10-07 06:10:15 +00002856 assert(D->isCompleteDefinition() && "Cannot layout type before complete!");
Anders Carlssondf291d82010-05-26 04:56:53 +00002857
2858 // Look up this layout, if already laid out, return what we have.
2859 // Note that we can't save a reference to the entry because this function
2860 // is recursive.
2861 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
2862 if (Entry) return *Entry;
2863
Warren Hunt8f8bad72013-10-11 20:19:00 +00002864 const ASTRecordLayout *NewEntry = 0;
Anders Carlssond2954862010-05-26 05:10:47 +00002865
Warren Hunt8f8bad72013-10-11 20:19:00 +00002866 if (isMsLayout(D) && !D->getASTContext().getExternalSource()) {
2867 NewEntry = BuildMicrosoftASTRecordLayout(D);
2868 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
Anders Carlssonc121b4e2010-05-27 00:07:01 +00002869 EmptySubobjectMap EmptySubobjects(*this, RD);
John McCall0153cd32011-11-08 04:01:03 +00002870 RecordLayoutBuilder Builder(*this, &EmptySubobjects);
2871 Builder.Layout(RD);
Anders Carlsson439edd12010-05-27 05:41:06 +00002872
John McCall5c1f1d02013-01-29 01:14:22 +00002873 // In certain situations, we are allowed to lay out objects in the
2874 // tail-padding of base classes. This is ABI-dependent.
2875 // FIXME: this should be stored in the record layout.
2876 bool skipTailPadding =
2877 mustSkipTailPadding(getTargetInfo().getCXXABI(), cast<CXXRecordDecl>(D));
Anders Carlssond2954862010-05-26 05:10:47 +00002878
2879 // FIXME: This should be done in FinalizeLayout.
Ken Dyck1b4420e2011-02-28 02:01:38 +00002880 CharUnits DataSize =
John McCall5c1f1d02013-01-29 01:14:22 +00002881 skipTailPadding ? Builder.getSize() : Builder.getDataSize();
Ken Dyck1b4420e2011-02-28 02:01:38 +00002882 CharUnits NonVirtualSize =
John McCall5c1f1d02013-01-29 01:14:22 +00002883 skipTailPadding ? DataSize : Builder.NonVirtualSize;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002884 NewEntry =
John McCall0153cd32011-11-08 04:01:03 +00002885 new (*this) ASTRecordLayout(*this, Builder.getSize(),
2886 Builder.Alignment,
Warren Hunt7b252d22013-12-06 00:01:17 +00002887 /*RequiredAlignment : used by MS-ABI)*/
2888 Builder.Alignment,
John McCalle42a3362012-05-01 08:55:32 +00002889 Builder.HasOwnVFPtr,
Warren Hunt8f8bad72013-10-11 20:19:00 +00002890 RD->isDynamicClass(),
Warren Hunt55d8e822013-10-23 23:53:07 +00002891 CharUnits::fromQuantity(-1),
Ken Dyck1b4420e2011-02-28 02:01:38 +00002892 DataSize,
John McCall0153cd32011-11-08 04:01:03 +00002893 Builder.FieldOffsets.data(),
2894 Builder.FieldOffsets.size(),
Ken Dyckaf1c83f2011-02-16 01:52:01 +00002895 NonVirtualSize,
John McCall0153cd32011-11-08 04:01:03 +00002896 Builder.NonVirtualAlignment,
Anders Carlssonc121b4e2010-05-27 00:07:01 +00002897 EmptySubobjects.SizeOfLargestEmptySubobject,
John McCall0153cd32011-11-08 04:01:03 +00002898 Builder.PrimaryBase,
2899 Builder.PrimaryBaseIsVirtual,
Warren Hunt049f6732013-12-06 19:54:25 +00002900 0, false, false,
John McCall0153cd32011-11-08 04:01:03 +00002901 Builder.Bases, Builder.VBases);
Anders Carlssond2954862010-05-26 05:10:47 +00002902 } else {
John McCall0153cd32011-11-08 04:01:03 +00002903 RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/0);
Anders Carlssond2954862010-05-26 05:10:47 +00002904 Builder.Layout(D);
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002905
Anders Carlssond2954862010-05-26 05:10:47 +00002906 NewEntry =
Ken Dyck1b4420e2011-02-28 02:01:38 +00002907 new (*this) ASTRecordLayout(*this, Builder.getSize(),
Ken Dyck4731d5b2011-02-16 02:05:21 +00002908 Builder.Alignment,
Warren Hunt7b252d22013-12-06 00:01:17 +00002909 /*RequiredAlignment : used by MS-ABI)*/
2910 Builder.Alignment,
Ken Dyck1b4420e2011-02-28 02:01:38 +00002911 Builder.getSize(),
Anders Carlssond2954862010-05-26 05:10:47 +00002912 Builder.FieldOffsets.data(),
2913 Builder.FieldOffsets.size());
2914 }
2915
Anders Carlssondf291d82010-05-26 04:56:53 +00002916 ASTRecordLayouts[D] = NewEntry;
2917
David Blaikiebbafb8a2012-03-11 07:00:24 +00002918 if (getLangOpts().DumpRecordLayouts) {
Argyrios Kyrtzidis8ade08e2013-07-12 22:30:03 +00002919 llvm::outs() << "\n*** Dumping AST Record Layout\n";
2920 DumpRecordLayout(D, llvm::outs(), getLangOpts().DumpRecordLayoutsSimple);
Anders Carlssondf291d82010-05-26 04:56:53 +00002921 }
2922
2923 return *NewEntry;
2924}
2925
John McCall6bd2a892013-01-25 22:31:03 +00002926const CXXMethodDecl *ASTContext::getCurrentKeyFunction(const CXXRecordDecl *RD) {
Reid Kleckner5d7f2982013-05-29 16:18:30 +00002927 if (!getTargetInfo().getCXXABI().hasKeyFunctions())
2928 return 0;
2929
John McCall6bd2a892013-01-25 22:31:03 +00002930 assert(RD->getDefinition() && "Cannot get key function for forward decl!");
Anders Carlssondf291d82010-05-26 04:56:53 +00002931 RD = cast<CXXRecordDecl>(RD->getDefinition());
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002932
Richard Smith676c4042013-08-29 23:59:27 +00002933 LazyDeclPtr &Entry = KeyFunctions[RD];
2934 if (!Entry)
2935 Entry = const_cast<CXXMethodDecl*>(computeKeyFunction(*this, RD));
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002936
Richard Smith676c4042013-08-29 23:59:27 +00002937 return cast_or_null<CXXMethodDecl>(Entry.get(getExternalSource()));
John McCall6bd2a892013-01-25 22:31:03 +00002938}
2939
Richard Smith676c4042013-08-29 23:59:27 +00002940void ASTContext::setNonKeyFunction(const CXXMethodDecl *Method) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002941 assert(Method == Method->getFirstDecl() &&
John McCall6bd2a892013-01-25 22:31:03 +00002942 "not working with method declaration from class definition");
2943
2944 // Look up the cache entry. Since we're working with the first
2945 // declaration, its parent must be the class definition, which is
2946 // the correct key for the KeyFunctions hash.
Richard Smith676c4042013-08-29 23:59:27 +00002947 llvm::DenseMap<const CXXRecordDecl*, LazyDeclPtr>::iterator
2948 I = KeyFunctions.find(Method->getParent());
John McCall6bd2a892013-01-25 22:31:03 +00002949
2950 // If it's not cached, there's nothing to do.
Richard Smith676c4042013-08-29 23:59:27 +00002951 if (I == KeyFunctions.end()) return;
John McCall6bd2a892013-01-25 22:31:03 +00002952
2953 // If it is cached, check whether it's the target method, and if so,
2954 // remove it from the cache.
Richard Smith676c4042013-08-29 23:59:27 +00002955 if (I->second.get(getExternalSource()) == Method) {
John McCall6bd2a892013-01-25 22:31:03 +00002956 // FIXME: remember that we did this for module / chained PCH state?
Richard Smith676c4042013-08-29 23:59:27 +00002957 KeyFunctions.erase(I);
John McCall6bd2a892013-01-25 22:31:03 +00002958 }
Anders Carlssondf291d82010-05-26 04:56:53 +00002959}
2960
Richard Smithdafff942012-01-14 04:30:29 +00002961static uint64_t getFieldOffset(const ASTContext &C, const FieldDecl *FD) {
2962 const ASTRecordLayout &Layout = C.getASTRecordLayout(FD->getParent());
2963 return Layout.getFieldOffset(FD->getFieldIndex());
2964}
2965
2966uint64_t ASTContext::getFieldOffset(const ValueDecl *VD) const {
2967 uint64_t OffsetInBits;
2968 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
2969 OffsetInBits = ::getFieldOffset(*this, FD);
2970 } else {
2971 const IndirectFieldDecl *IFD = cast<IndirectFieldDecl>(VD);
2972
2973 OffsetInBits = 0;
2974 for (IndirectFieldDecl::chain_iterator CI = IFD->chain_begin(),
2975 CE = IFD->chain_end();
2976 CI != CE; ++CI)
2977 OffsetInBits += ::getFieldOffset(*this, cast<FieldDecl>(*CI));
2978 }
2979
2980 return OffsetInBits;
2981}
2982
Eric Christopher8a39a012011-10-05 06:00:51 +00002983/// getObjCLayout - Get or compute information about the layout of the
2984/// given interface.
Anders Carlssondf291d82010-05-26 04:56:53 +00002985///
2986/// \param Impl - If given, also include the layout of the interface's
2987/// implementation. This may differ by including synthesized ivars.
2988const ASTRecordLayout &
2989ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
Jay Foad39c79802011-01-12 09:06:06 +00002990 const ObjCImplementationDecl *Impl) const {
Douglas Gregor64d92572011-12-20 15:50:13 +00002991 // Retrieve the definition
Sean Callanand9a909c2012-03-15 16:33:08 +00002992 if (D->hasExternalLexicalStorage() && !D->getDefinition())
2993 getExternalSource()->CompleteType(const_cast<ObjCInterfaceDecl*>(D));
Douglas Gregor64d92572011-12-20 15:50:13 +00002994 D = D->getDefinition();
2995 assert(D && D->isThisDeclarationADefinition() && "Invalid interface decl!");
Anders Carlssondf291d82010-05-26 04:56:53 +00002996
2997 // Look up this layout, if already laid out, return what we have.
Roman Divackye6377112012-09-06 15:59:27 +00002998 const ObjCContainerDecl *Key =
2999 Impl ? (const ObjCContainerDecl*) Impl : (const ObjCContainerDecl*) D;
Anders Carlssondf291d82010-05-26 04:56:53 +00003000 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
3001 return *Entry;
3002
3003 // Add in synthesized ivar count if laying out an implementation.
3004 if (Impl) {
3005 unsigned SynthCount = CountNonClassIvars(D);
3006 // If there aren't any sythesized ivars then reuse the interface
3007 // entry. Note we can't cache this because we simply free all
3008 // entries later; however we shouldn't look up implementations
3009 // frequently.
3010 if (SynthCount == 0)
3011 return getObjCLayout(D, 0);
3012 }
3013
John McCall0153cd32011-11-08 04:01:03 +00003014 RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/0);
Anders Carlsson6ed3a9a2010-05-26 05:04:25 +00003015 Builder.Layout(D);
3016
Anders Carlssondf291d82010-05-26 04:56:53 +00003017 const ASTRecordLayout *NewEntry =
Ken Dyck1b4420e2011-02-28 02:01:38 +00003018 new (*this) ASTRecordLayout(*this, Builder.getSize(),
Ken Dyck4731d5b2011-02-16 02:05:21 +00003019 Builder.Alignment,
Warren Hunt7b252d22013-12-06 00:01:17 +00003020 /*RequiredAlignment : used by MS-ABI)*/
3021 Builder.Alignment,
Ken Dyck1b4420e2011-02-28 02:01:38 +00003022 Builder.getDataSize(),
Anders Carlsson6ed3a9a2010-05-26 05:04:25 +00003023 Builder.FieldOffsets.data(),
3024 Builder.FieldOffsets.size());
Daniel Dunbar592a85c2010-05-27 02:25:46 +00003025
Anders Carlssondf291d82010-05-26 04:56:53 +00003026 ObjCLayouts[Key] = NewEntry;
3027
3028 return *NewEntry;
3029}
3030
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003031static void PrintOffset(raw_ostream &OS,
Anders Carlsson3f018712010-10-31 23:45:59 +00003032 CharUnits Offset, unsigned IndentLevel) {
Benjamin Kramer96ad7172011-11-05 09:02:52 +00003033 OS << llvm::format("%4" PRId64 " | ", (int64_t)Offset.getQuantity());
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003034 OS.indent(IndentLevel * 2);
3035}
3036
Eli Benderskyf6f93ee2012-12-08 00:07:24 +00003037static void PrintIndentNoOffset(raw_ostream &OS, unsigned IndentLevel) {
3038 OS << " | ";
3039 OS.indent(IndentLevel * 2);
3040}
3041
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003042static void DumpCXXRecordLayout(raw_ostream &OS,
Jay Foad39c79802011-01-12 09:06:06 +00003043 const CXXRecordDecl *RD, const ASTContext &C,
Anders Carlsson3f018712010-10-31 23:45:59 +00003044 CharUnits Offset,
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003045 unsigned IndentLevel,
3046 const char* Description,
3047 bool IncludeVirtualBases) {
Anders Carlsson3f018712010-10-31 23:45:59 +00003048 const ASTRecordLayout &Layout = C.getASTRecordLayout(RD);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003049
3050 PrintOffset(OS, Offset, IndentLevel);
Dan Gohman145f3f12010-04-19 16:39:44 +00003051 OS << C.getTypeDeclType(const_cast<CXXRecordDecl *>(RD)).getAsString();
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003052 if (Description)
3053 OS << ' ' << Description;
3054 if (RD->isEmpty())
3055 OS << " (empty)";
3056 OS << '\n';
3057
3058 IndentLevel++;
3059
Anders Carlsson3f018712010-10-31 23:45:59 +00003060 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
Warren Hunt8f8bad72013-10-11 20:19:00 +00003061 bool HasOwnVFPtr = Layout.hasOwnVFPtr();
3062 bool HasOwnVBPtr = Layout.hasOwnVBPtr();
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003063
3064 // Vtable pointer.
Warren Hunt8f8bad72013-10-11 20:19:00 +00003065 if (RD->isDynamicClass() && !PrimaryBase && !isMsLayout(RD)) {
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003066 PrintOffset(OS, Offset, IndentLevel);
Benjamin Kramerb89514a2011-10-14 18:45:37 +00003067 OS << '(' << *RD << " vtable pointer)\n";
Warren Hunt8f8bad72013-10-11 20:19:00 +00003068 } else if (HasOwnVFPtr) {
3069 PrintOffset(OS, Offset, IndentLevel);
3070 // vfptr (for Microsoft C++ ABI)
3071 OS << '(' << *RD << " vftable pointer)\n";
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003072 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00003073
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003074 // Dump (non-virtual) bases
3075 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
3076 E = RD->bases_end(); I != E; ++I) {
3077 assert(!I->getType()->isDependentType() &&
3078 "Cannot layout class with dependent bases.");
3079 if (I->isVirtual())
3080 continue;
3081
3082 const CXXRecordDecl *Base =
3083 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
3084
Anders Carlsson3f018712010-10-31 23:45:59 +00003085 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003086
3087 DumpCXXRecordLayout(OS, Base, C, BaseOffset, IndentLevel,
3088 Base == PrimaryBase ? "(primary base)" : "(base)",
3089 /*IncludeVirtualBases=*/false);
3090 }
Eli Friedman43114f92011-10-21 22:49:56 +00003091
Warren Hunt8f8bad72013-10-11 20:19:00 +00003092 // vbptr (for Microsoft C++ ABI)
3093 if (HasOwnVBPtr) {
Eli Friedman84d2d3a2011-09-27 19:12:27 +00003094 PrintOffset(OS, Offset + Layout.getVBPtrOffset(), IndentLevel);
Benjamin Kramerb89514a2011-10-14 18:45:37 +00003095 OS << '(' << *RD << " vbtable pointer)\n";
Eli Friedman84d2d3a2011-09-27 19:12:27 +00003096 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003097
3098 // Dump fields.
3099 uint64_t FieldNo = 0;
3100 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
3101 E = RD->field_end(); I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +00003102 const FieldDecl &Field = **I;
Anders Carlsson3f018712010-10-31 23:45:59 +00003103 CharUnits FieldOffset = Offset +
Ken Dyck86a7fcc2011-01-18 01:56:16 +00003104 C.toCharUnitsFromBits(Layout.getFieldOffset(FieldNo));
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003105
David Blaikie2d7c57e2012-04-30 02:36:29 +00003106 if (const RecordType *RT = Field.getType()->getAs<RecordType>()) {
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003107 if (const CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3108 DumpCXXRecordLayout(OS, D, C, FieldOffset, IndentLevel,
David Blaikie2d7c57e2012-04-30 02:36:29 +00003109 Field.getName().data(),
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003110 /*IncludeVirtualBases=*/true);
3111 continue;
3112 }
3113 }
3114
3115 PrintOffset(OS, FieldOffset, IndentLevel);
David Blaikie2d7c57e2012-04-30 02:36:29 +00003116 OS << Field.getType().getAsString() << ' ' << Field << '\n';
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003117 }
3118
3119 if (!IncludeVirtualBases)
3120 return;
3121
3122 // Dump virtual bases.
John McCalle42a3362012-05-01 08:55:32 +00003123 const ASTRecordLayout::VBaseOffsetsMapTy &vtordisps =
3124 Layout.getVBaseOffsetsMap();
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003125 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
3126 E = RD->vbases_end(); I != E; ++I) {
3127 assert(I->isVirtual() && "Found non-virtual class!");
3128 const CXXRecordDecl *VBase =
3129 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
3130
Anders Carlsson3f018712010-10-31 23:45:59 +00003131 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBase);
John McCalle42a3362012-05-01 08:55:32 +00003132
3133 if (vtordisps.find(VBase)->second.hasVtorDisp()) {
3134 PrintOffset(OS, VBaseOffset - CharUnits::fromQuantity(4), IndentLevel);
3135 OS << "(vtordisp for vbase " << *VBase << ")\n";
3136 }
3137
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003138 DumpCXXRecordLayout(OS, VBase, C, VBaseOffset, IndentLevel,
3139 VBase == PrimaryBase ?
3140 "(primary virtual base)" : "(virtual base)",
3141 /*IncludeVirtualBases=*/false);
3142 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003143
Eli Benderskyf6f93ee2012-12-08 00:07:24 +00003144 PrintIndentNoOffset(OS, IndentLevel - 1);
3145 OS << "[sizeof=" << Layout.getSize().getQuantity();
Warren Hunt8f8bad72013-10-11 20:19:00 +00003146 if (!isMsLayout(RD))
3147 OS << ", dsize=" << Layout.getDataSize().getQuantity();
Ken Dyck7ad11e72011-02-15 02:32:40 +00003148 OS << ", align=" << Layout.getAlignment().getQuantity() << '\n';
Eli Benderskyf6f93ee2012-12-08 00:07:24 +00003149
3150 PrintIndentNoOffset(OS, IndentLevel - 1);
3151 OS << " nvsize=" << Layout.getNonVirtualSize().getQuantity();
Warren Huntd640d7d2014-01-09 00:30:56 +00003152 OS << ", nvalign=" << Layout.getNonVirtualAlignment().getQuantity() << "]\n";
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003153 OS << '\n';
3154}
Daniel Dunbarccabe482010-04-19 20:44:53 +00003155
3156void ASTContext::DumpRecordLayout(const RecordDecl *RD,
Douglas Gregore9fc3772012-01-26 07:55:45 +00003157 raw_ostream &OS,
3158 bool Simple) const {
Daniel Dunbarccabe482010-04-19 20:44:53 +00003159 const ASTRecordLayout &Info = getASTRecordLayout(RD);
3160
3161 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Douglas Gregore9fc3772012-01-26 07:55:45 +00003162 if (!Simple)
3163 return DumpCXXRecordLayout(OS, CXXRD, *this, CharUnits(), 0, 0,
3164 /*IncludeVirtualBases=*/true);
Daniel Dunbarccabe482010-04-19 20:44:53 +00003165
3166 OS << "Type: " << getTypeDeclType(RD).getAsString() << "\n";
Douglas Gregore9fc3772012-01-26 07:55:45 +00003167 if (!Simple) {
3168 OS << "Record: ";
3169 RD->dump();
3170 }
Daniel Dunbarccabe482010-04-19 20:44:53 +00003171 OS << "\nLayout: ";
3172 OS << "<ASTRecordLayout\n";
Ken Dyckb0fcc592011-02-11 01:54:29 +00003173 OS << " Size:" << toBits(Info.getSize()) << "\n";
Warren Hunt8f8bad72013-10-11 20:19:00 +00003174 if (!isMsLayout(RD))
3175 OS << " DataSize:" << toBits(Info.getDataSize()) << "\n";
Ken Dyck7ad11e72011-02-15 02:32:40 +00003176 OS << " Alignment:" << toBits(Info.getAlignment()) << "\n";
Daniel Dunbarccabe482010-04-19 20:44:53 +00003177 OS << " FieldOffsets: [";
3178 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i) {
3179 if (i) OS << ", ";
3180 OS << Info.getFieldOffset(i);
3181 }
3182 OS << "]>\n";
3183}