blob: 73267f70a6a5ea1c61d25172f852da9e9bed50b9 [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.
Aaron Ballman574705e2014-03-13 15:41:46 +0000143 for (const auto &I : Class->bases()) {
Reid Klecknercd612ab2014-04-11 16:57:42 +0000144 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000145
Anders Carlsson28466ab2010-10-31 22:13:23 +0000146 CharUnits EmptySize;
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000147 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
148 if (BaseDecl->isEmpty()) {
149 // If the class decl is empty, get its size.
Ken Dyckc8ae5502011-02-09 01:59:34 +0000150 EmptySize = Layout.getSize();
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000151 } else {
152 // Otherwise, we get the largest empty subobject for the decl.
153 EmptySize = Layout.getSizeOfLargestEmptySubobject();
154 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000155
Anders Carlsson28466ab2010-10-31 22:13:23 +0000156 if (EmptySize > SizeOfLargestEmptySubobject)
157 SizeOfLargestEmptySubobject = EmptySize;
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000158 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000159
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000160 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000161 for (const auto *I : Class->fields()) {
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000162 const RecordType *RT =
David Blaikie40ed2972012-06-06 20:45:41 +0000163 Context.getBaseElementType(I->getType())->getAs<RecordType>();
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000164
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000165 // We only care about record types.
166 if (!RT)
167 continue;
168
Anders Carlsson28466ab2010-10-31 22:13:23 +0000169 CharUnits EmptySize;
Reid Klecknercd612ab2014-04-11 16:57:42 +0000170 const CXXRecordDecl *MemberDecl = RT->getAsCXXRecordDecl();
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000171 const ASTRecordLayout &Layout = Context.getASTRecordLayout(MemberDecl);
172 if (MemberDecl->isEmpty()) {
173 // If the class decl is empty, get its size.
Ken Dyckc8ae5502011-02-09 01:59:34 +0000174 EmptySize = Layout.getSize();
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000175 } else {
176 // Otherwise, we get the largest empty subobject for the decl.
177 EmptySize = Layout.getSizeOfLargestEmptySubobject();
178 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000179
Anders Carlsson28466ab2010-10-31 22:13:23 +0000180 if (EmptySize > SizeOfLargestEmptySubobject)
181 SizeOfLargestEmptySubobject = EmptySize;
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000182 }
183}
184
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000185bool
Anders Carlssondb319762010-05-27 18:20:57 +0000186EmptySubobjectMap::CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD,
Anders Carlsson725190f2010-10-31 21:39:24 +0000187 CharUnits Offset) const {
Anders Carlssondb319762010-05-27 18:20:57 +0000188 // We only need to check empty bases.
189 if (!RD->isEmpty())
190 return true;
191
Anders Carlsson725190f2010-10-31 21:39:24 +0000192 EmptyClassOffsetsMapTy::const_iterator I = EmptyClassOffsets.find(Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000193 if (I == EmptyClassOffsets.end())
194 return true;
195
196 const ClassVectorTy& Classes = I->second;
197 if (std::find(Classes.begin(), Classes.end(), RD) == Classes.end())
198 return true;
199
200 // There is already an empty class of the same type at this offset.
201 return false;
202}
203
204void EmptySubobjectMap::AddSubobjectAtOffset(const CXXRecordDecl *RD,
Anders Carlsson725190f2010-10-31 21:39:24 +0000205 CharUnits Offset) {
Anders Carlssondb319762010-05-27 18:20:57 +0000206 // We only care about empty bases.
207 if (!RD->isEmpty())
208 return;
209
Reid Kleckner369f3162013-05-14 20:30:42 +0000210 // If we have empty structures inside a union, we can assign both
Rafael Espindola7bcde192010-12-29 23:02:58 +0000211 // the same offset. Just avoid pushing them twice in the list.
Anders Carlsson725190f2010-10-31 21:39:24 +0000212 ClassVectorTy& Classes = EmptyClassOffsets[Offset];
Rafael Espindola7bcde192010-12-29 23:02:58 +0000213 if (std::find(Classes.begin(), Classes.end(), RD) != Classes.end())
214 return;
215
Anders Carlssondb319762010-05-27 18:20:57 +0000216 Classes.push_back(RD);
Anders Carlssoncc5de092010-06-08 15:56:03 +0000217
218 // Update the empty class offset.
Anders Carlsson725190f2010-10-31 21:39:24 +0000219 if (Offset > MaxEmptyClassOffset)
220 MaxEmptyClassOffset = Offset;
Anders Carlssondb319762010-05-27 18:20:57 +0000221}
222
223bool
Anders Carlsson28466ab2010-10-31 22:13:23 +0000224EmptySubobjectMap::CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info,
225 CharUnits Offset) {
Anders Carlsson45c1d282010-06-08 16:20:35 +0000226 // We don't have to keep looking past the maximum offset that's known to
227 // contain an empty class.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000228 if (!AnyEmptySubobjectsBeyondOffset(Offset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000229 return true;
230
Anders Carlsson28466ab2010-10-31 22:13:23 +0000231 if (!CanPlaceSubobjectAtOffset(Info->Class, Offset))
Anders Carlssondb319762010-05-27 18:20:57 +0000232 return false;
233
Anders Carlsson439edd12010-05-27 05:41:06 +0000234 // Traverse all non-virtual bases.
Anders Carlssona7774a62010-05-29 21:10:24 +0000235 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
Anders Carlsson439edd12010-05-27 05:41:06 +0000236 for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) {
Anders Carlssona7f3cdb2010-05-28 21:24:37 +0000237 BaseSubobjectInfo* Base = Info->Bases[I];
Anders Carlsson439edd12010-05-27 05:41:06 +0000238 if (Base->IsVirtual)
239 continue;
240
Anders Carlsson0a14ee92010-11-01 00:21:58 +0000241 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
Anders Carlsson439edd12010-05-27 05:41:06 +0000242
243 if (!CanPlaceBaseSubobjectAtOffset(Base, BaseOffset))
244 return false;
245 }
246
Anders Carlssone3c24c72010-05-29 17:35:14 +0000247 if (Info->PrimaryVirtualBaseInfo) {
248 BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
Anders Carlsson439edd12010-05-27 05:41:06 +0000249
250 if (Info == PrimaryVirtualBaseInfo->Derived) {
251 if (!CanPlaceBaseSubobjectAtOffset(PrimaryVirtualBaseInfo, Offset))
252 return false;
253 }
254 }
255
Anders Carlssondb319762010-05-27 18:20:57 +0000256 // Traverse all member variables.
257 unsigned FieldNo = 0;
258 for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(),
259 E = Info->Class->field_end(); I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +0000260 if (I->isBitField())
Anders Carlsson233e2722010-10-31 21:54:55 +0000261 continue;
262
Anders Carlsson28466ab2010-10-31 22:13:23 +0000263 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
David Blaikie40ed2972012-06-06 20:45:41 +0000264 if (!CanPlaceFieldSubobjectAtOffset(*I, FieldOffset))
Anders Carlssondb319762010-05-27 18:20:57 +0000265 return false;
266 }
267
Anders Carlsson439edd12010-05-27 05:41:06 +0000268 return true;
269}
270
Anders Carlssona7f3cdb2010-05-28 21:24:37 +0000271void EmptySubobjectMap::UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000272 CharUnits Offset,
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000273 bool PlacingEmptyBase) {
274 if (!PlacingEmptyBase && Offset >= SizeOfLargestEmptySubobject) {
275 // We know that the only empty subobjects that can conflict with empty
276 // subobject of non-empty bases, are empty bases that can be placed at
277 // offset zero. Because of this, we only need to keep track of empty base
278 // subobjects with offsets less than the size of the largest empty
279 // subobject for our class.
280 return;
281 }
282
Anders Carlsson28466ab2010-10-31 22:13:23 +0000283 AddSubobjectAtOffset(Info->Class, Offset);
Anders Carlssona7774a62010-05-29 21:10:24 +0000284
Anders Carlsson439edd12010-05-27 05:41:06 +0000285 // Traverse all non-virtual bases.
Anders Carlssona7774a62010-05-29 21:10:24 +0000286 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
Anders Carlsson439edd12010-05-27 05:41:06 +0000287 for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) {
Anders Carlssona7f3cdb2010-05-28 21:24:37 +0000288 BaseSubobjectInfo* Base = Info->Bases[I];
Anders Carlsson439edd12010-05-27 05:41:06 +0000289 if (Base->IsVirtual)
290 continue;
Anders Carlssona7774a62010-05-29 21:10:24 +0000291
Anders Carlsson0a14ee92010-11-01 00:21:58 +0000292 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000293 UpdateEmptyBaseSubobjects(Base, BaseOffset, PlacingEmptyBase);
Anders Carlsson439edd12010-05-27 05:41:06 +0000294 }
295
Anders Carlssone3c24c72010-05-29 17:35:14 +0000296 if (Info->PrimaryVirtualBaseInfo) {
297 BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
Anders Carlsson439edd12010-05-27 05:41:06 +0000298
299 if (Info == PrimaryVirtualBaseInfo->Derived)
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000300 UpdateEmptyBaseSubobjects(PrimaryVirtualBaseInfo, Offset,
301 PlacingEmptyBase);
Anders Carlsson439edd12010-05-27 05:41:06 +0000302 }
Anders Carlssondb319762010-05-27 18:20:57 +0000303
Anders Carlssondb319762010-05-27 18:20:57 +0000304 // Traverse all member variables.
305 unsigned FieldNo = 0;
306 for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(),
307 E = Info->Class->field_end(); I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +0000308 if (I->isBitField())
Anders Carlsson233e2722010-10-31 21:54:55 +0000309 continue;
Anders Carlssona7774a62010-05-29 21:10:24 +0000310
Anders Carlsson28466ab2010-10-31 22:13:23 +0000311 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
David Blaikie40ed2972012-06-06 20:45:41 +0000312 UpdateEmptyFieldSubobjects(*I, FieldOffset);
Anders Carlssondb319762010-05-27 18:20:57 +0000313 }
Anders Carlsson439edd12010-05-27 05:41:06 +0000314}
315
Anders Carlssona60b86a2010-05-29 20:49:49 +0000316bool EmptySubobjectMap::CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000317 CharUnits Offset) {
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000318 // If we know this class doesn't have any empty subobjects we don't need to
319 // bother checking.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000320 if (SizeOfLargestEmptySubobject.isZero())
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000321 return true;
322
Anders Carlsson439edd12010-05-27 05:41:06 +0000323 if (!CanPlaceBaseSubobjectAtOffset(Info, Offset))
324 return false;
Anders Carlssondb319762010-05-27 18:20:57 +0000325
326 // We are able to place the base at this offset. Make sure to update the
327 // empty base subobject map.
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000328 UpdateEmptyBaseSubobjects(Info, Offset, Info->Class->isEmpty());
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000329 return true;
330}
331
Anders Carlssondb319762010-05-27 18:20:57 +0000332bool
333EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD,
334 const CXXRecordDecl *Class,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000335 CharUnits Offset) const {
Anders Carlsson45c1d282010-06-08 16:20:35 +0000336 // We don't have to keep looking past the maximum offset that's known to
337 // contain an empty class.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000338 if (!AnyEmptySubobjectsBeyondOffset(Offset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000339 return true;
340
Anders Carlsson28466ab2010-10-31 22:13:23 +0000341 if (!CanPlaceSubobjectAtOffset(RD, Offset))
Anders Carlssondb319762010-05-27 18:20:57 +0000342 return false;
343
344 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
345
346 // Traverse all non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000347 for (const auto &I : RD->bases()) {
348 if (I.isVirtual())
Anders Carlssondb319762010-05-27 18:20:57 +0000349 continue;
350
Reid Klecknercd612ab2014-04-11 16:57:42 +0000351 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
Anders Carlssondb319762010-05-27 18:20:57 +0000352
Anders Carlsson0a14ee92010-11-01 00:21:58 +0000353 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
Anders Carlssondb319762010-05-27 18:20:57 +0000354 if (!CanPlaceFieldSubobjectAtOffset(BaseDecl, Class, BaseOffset))
355 return false;
356 }
357
Anders Carlsson44687202010-06-08 19:09:24 +0000358 if (RD == Class) {
359 // This is the most derived class, traverse virtual bases as well.
Aaron Ballman445a9392014-03-13 16:15:17 +0000360 for (const auto &I : RD->vbases()) {
Reid Klecknercd612ab2014-04-11 16:57:42 +0000361 const CXXRecordDecl *VBaseDecl = I.getType()->getAsCXXRecordDecl();
362
Anders Carlsson3f018712010-10-31 23:45:59 +0000363 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
Anders Carlsson44687202010-06-08 19:09:24 +0000364 if (!CanPlaceFieldSubobjectAtOffset(VBaseDecl, Class, VBaseOffset))
365 return false;
366 }
367 }
368
Anders Carlssondb319762010-05-27 18:20:57 +0000369 // Traverse all member variables.
370 unsigned FieldNo = 0;
371 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
372 I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +0000373 if (I->isBitField())
Anders Carlsson233e2722010-10-31 21:54:55 +0000374 continue;
375
Anders Carlsson28466ab2010-10-31 22:13:23 +0000376 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
Anders Carlssondb319762010-05-27 18:20:57 +0000377
David Blaikie40ed2972012-06-06 20:45:41 +0000378 if (!CanPlaceFieldSubobjectAtOffset(*I, FieldOffset))
Anders Carlssondb319762010-05-27 18:20:57 +0000379 return false;
380 }
381
382 return true;
383}
384
Anders Carlsson233e2722010-10-31 21:54:55 +0000385bool
386EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD,
387 CharUnits Offset) const {
Anders Carlsson45c1d282010-06-08 16:20:35 +0000388 // We don't have to keep looking past the maximum offset that's known to
389 // contain an empty class.
Anders Carlsson233e2722010-10-31 21:54:55 +0000390 if (!AnyEmptySubobjectsBeyondOffset(Offset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000391 return true;
392
Anders Carlssondb319762010-05-27 18:20:57 +0000393 QualType T = FD->getType();
Reid Klecknercd612ab2014-04-11 16:57:42 +0000394 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
Anders Carlsson28466ab2010-10-31 22:13:23 +0000395 return CanPlaceFieldSubobjectAtOffset(RD, RD, Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000396
397 // If we have an array type we need to look at every element.
398 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
399 QualType ElemTy = Context.getBaseElementType(AT);
400 const RecordType *RT = ElemTy->getAs<RecordType>();
401 if (!RT)
402 return true;
Reid Klecknercd612ab2014-04-11 16:57:42 +0000403
404 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
Anders Carlssondb319762010-05-27 18:20:57 +0000405 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
406
407 uint64_t NumElements = Context.getConstantArrayElementCount(AT);
Anders Carlsson233e2722010-10-31 21:54:55 +0000408 CharUnits ElementOffset = Offset;
Anders Carlssondb319762010-05-27 18:20:57 +0000409 for (uint64_t I = 0; I != NumElements; ++I) {
Anders Carlsson45c1d282010-06-08 16:20:35 +0000410 // We don't have to keep looking past the maximum offset that's known to
411 // contain an empty class.
Anders Carlsson233e2722010-10-31 21:54:55 +0000412 if (!AnyEmptySubobjectsBeyondOffset(ElementOffset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000413 return true;
414
Anders Carlsson28466ab2010-10-31 22:13:23 +0000415 if (!CanPlaceFieldSubobjectAtOffset(RD, RD, ElementOffset))
Anders Carlssondb319762010-05-27 18:20:57 +0000416 return false;
417
Ken Dyckc8ae5502011-02-09 01:59:34 +0000418 ElementOffset += Layout.getSize();
Anders Carlssondb319762010-05-27 18:20:57 +0000419 }
420 }
421
422 return true;
423}
424
425bool
Anders Carlsson28466ab2010-10-31 22:13:23 +0000426EmptySubobjectMap::CanPlaceFieldAtOffset(const FieldDecl *FD,
427 CharUnits Offset) {
428 if (!CanPlaceFieldSubobjectAtOffset(FD, Offset))
Anders Carlssondb319762010-05-27 18:20:57 +0000429 return false;
430
431 // We are able to place the member variable at this offset.
432 // Make sure to update the empty base subobject map.
433 UpdateEmptyFieldSubobjects(FD, Offset);
434 return true;
435}
436
437void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD,
438 const CXXRecordDecl *Class,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000439 CharUnits Offset) {
Anders Carlssonae111dc2010-06-13 17:49:16 +0000440 // We know that the only empty subobjects that can conflict with empty
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000441 // field subobjects are subobjects of empty bases that can be placed at offset
Anders Carlssonae111dc2010-06-13 17:49:16 +0000442 // zero. Because of this, we only need to keep track of empty field
443 // subobjects with offsets less than the size of the largest empty
444 // subobject for our class.
445 if (Offset >= SizeOfLargestEmptySubobject)
446 return;
447
Anders Carlsson28466ab2010-10-31 22:13:23 +0000448 AddSubobjectAtOffset(RD, Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000449
450 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
451
452 // Traverse all non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000453 for (const auto &I : RD->bases()) {
454 if (I.isVirtual())
Anders Carlssondb319762010-05-27 18:20:57 +0000455 continue;
456
Reid Klecknercd612ab2014-04-11 16:57:42 +0000457 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
Anders Carlssondb319762010-05-27 18:20:57 +0000458
Anders Carlsson0a14ee92010-11-01 00:21:58 +0000459 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
Anders Carlssondb319762010-05-27 18:20:57 +0000460 UpdateEmptyFieldSubobjects(BaseDecl, Class, BaseOffset);
461 }
462
Anders Carlsson44687202010-06-08 19:09:24 +0000463 if (RD == Class) {
464 // This is the most derived class, traverse virtual bases as well.
Aaron Ballman445a9392014-03-13 16:15:17 +0000465 for (const auto &I : RD->vbases()) {
Reid Klecknercd612ab2014-04-11 16:57:42 +0000466 const CXXRecordDecl *VBaseDecl = I.getType()->getAsCXXRecordDecl();
467
Anders Carlsson3f018712010-10-31 23:45:59 +0000468 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
Anders Carlsson44687202010-06-08 19:09:24 +0000469 UpdateEmptyFieldSubobjects(VBaseDecl, Class, VBaseOffset);
470 }
471 }
472
Anders Carlssondb319762010-05-27 18:20:57 +0000473 // Traverse all member variables.
474 unsigned FieldNo = 0;
475 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
476 I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +0000477 if (I->isBitField())
Anders Carlsson09814d32010-11-01 15:14:51 +0000478 continue;
479
Anders Carlsson28466ab2010-10-31 22:13:23 +0000480 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
Anders Carlssondb319762010-05-27 18:20:57 +0000481
David Blaikie40ed2972012-06-06 20:45:41 +0000482 UpdateEmptyFieldSubobjects(*I, FieldOffset);
Anders Carlssondb319762010-05-27 18:20:57 +0000483 }
484}
485
486void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const FieldDecl *FD,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000487 CharUnits Offset) {
Anders Carlssondb319762010-05-27 18:20:57 +0000488 QualType T = FD->getType();
Reid Klecknercd612ab2014-04-11 16:57:42 +0000489 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
Anders Carlssondb319762010-05-27 18:20:57 +0000490 UpdateEmptyFieldSubobjects(RD, RD, Offset);
491 return;
492 }
493
494 // If we have an array type we need to update every element.
495 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
496 QualType ElemTy = Context.getBaseElementType(AT);
497 const RecordType *RT = ElemTy->getAs<RecordType>();
498 if (!RT)
499 return;
Reid Klecknercd612ab2014-04-11 16:57:42 +0000500
501 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
Anders Carlssondb319762010-05-27 18:20:57 +0000502 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
503
504 uint64_t NumElements = Context.getConstantArrayElementCount(AT);
Anders Carlsson28466ab2010-10-31 22:13:23 +0000505 CharUnits ElementOffset = Offset;
Anders Carlssondb319762010-05-27 18:20:57 +0000506
507 for (uint64_t I = 0; I != NumElements; ++I) {
Anders Carlssonae111dc2010-06-13 17:49:16 +0000508 // We know that the only empty subobjects that can conflict with empty
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000509 // field subobjects are subobjects of empty bases that can be placed at
Anders Carlssonae111dc2010-06-13 17:49:16 +0000510 // offset zero. Because of this, we only need to keep track of empty field
511 // subobjects with offsets less than the size of the largest empty
512 // subobject for our class.
513 if (ElementOffset >= SizeOfLargestEmptySubobject)
514 return;
515
Anders Carlssondb319762010-05-27 18:20:57 +0000516 UpdateEmptyFieldSubobjects(RD, RD, ElementOffset);
Ken Dyckc8ae5502011-02-09 01:59:34 +0000517 ElementOffset += Layout.getSize();
Anders Carlssondb319762010-05-27 18:20:57 +0000518 }
519 }
520}
521
John McCalle42a3362012-05-01 08:55:32 +0000522typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> ClassSetTy;
523
Anders Carlssonc2226202010-05-26 05:58:59 +0000524class RecordLayoutBuilder {
Charles Davisc2c576a2010-08-19 00:55:19 +0000525protected:
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000526 // FIXME: Remove this and make the appropriate fields public.
527 friend class clang::ASTContext;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000528
Jay Foad39c79802011-01-12 09:06:06 +0000529 const ASTContext &Context;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000530
Anders Carlssonf58de112010-05-26 15:32:58 +0000531 EmptySubobjectMap *EmptySubobjects;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000532
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000533 /// Size - The current size of the record layout.
534 uint64_t Size;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000535
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000536 /// Alignment - The current alignment of the record layout.
Ken Dyck4731d5b2011-02-16 02:05:21 +0000537 CharUnits Alignment;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000538
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000539 /// \brief The alignment if attribute packed is not used.
Ken Dyck1300b3b2011-02-16 02:11:31 +0000540 CharUnits UnpackedAlignment;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000541
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000542 SmallVector<uint64_t, 16> FieldOffsets;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000543
Douglas Gregore9fc3772012-01-26 07:55:45 +0000544 /// \brief Whether the external AST source has provided a layout for this
545 /// record.
546 unsigned ExternalLayout : 1;
Douglas Gregor44ba7892012-01-28 00:53:29 +0000547
548 /// \brief Whether we need to infer alignment, even when we have an
549 /// externally-provided layout.
550 unsigned InferAlignment : 1;
Douglas Gregore9fc3772012-01-26 07:55:45 +0000551
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000552 /// Packed - Whether the record is packed or not.
Daniel Dunbar6da10982010-05-27 05:45:51 +0000553 unsigned Packed : 1;
554
555 unsigned IsUnion : 1;
556
557 unsigned IsMac68kAlign : 1;
Fariborz Jahanianbcb23a12011-04-26 23:52:16 +0000558
559 unsigned IsMsStruct : 1;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000560
Eli Friedman2782dac2013-06-26 20:50:34 +0000561 /// UnfilledBitsInLastUnit - If the last field laid out was a bitfield,
562 /// this contains the number of bits in the last unit that can be used for
563 /// an adjacent bitfield if necessary. The unit in question is usually
564 /// a byte, but larger units are used if IsMsStruct.
565 unsigned char UnfilledBitsInLastUnit;
566 /// LastBitfieldTypeSize - If IsMsStruct, represents the size of the type
567 /// of the previous field if it was a bitfield.
568 unsigned char LastBitfieldTypeSize;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000569
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000570 /// MaxFieldAlignment - The maximum allowed field alignment. This is set by
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000571 /// #pragma pack.
Ken Dyck02ced6f2011-02-17 01:49:42 +0000572 CharUnits MaxFieldAlignment;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000573
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000574 /// DataSize - The data size of the record being laid out.
575 uint64_t DataSize;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000576
Ken Dyckaf1c83f2011-02-16 01:52:01 +0000577 CharUnits NonVirtualSize;
Ken Dycka2d3dda2011-02-16 01:43:15 +0000578 CharUnits NonVirtualAlignment;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000579
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000580 /// PrimaryBase - the primary base class (if one exists) of the class
581 /// we're laying out.
582 const CXXRecordDecl *PrimaryBase;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000583
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000584 /// PrimaryBaseIsVirtual - Whether the primary base of the class we're laying
585 /// out is virtual.
586 bool PrimaryBaseIsVirtual;
587
John McCalle42a3362012-05-01 08:55:32 +0000588 /// HasOwnVFPtr - Whether the class provides its own vtable/vftbl
589 /// pointer, as opposed to inheriting one from a primary base class.
590 bool HasOwnVFPtr;
Eli Friedman43114f92011-10-21 22:49:56 +0000591
Anders Carlsson22f57202010-10-31 21:01:46 +0000592 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000593
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000594 /// Bases - base classes and their offsets in the record.
595 BaseOffsetsMapTy Bases;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000596
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000597 // VBases - virtual base classes and their offsets in the record.
John McCalle42a3362012-05-01 08:55:32 +0000598 ASTRecordLayout::VBaseOffsetsMapTy VBases;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000599
600 /// IndirectPrimaryBases - Virtual base classes, direct or indirect, that are
601 /// primary base classes for some other direct or indirect base class.
Anders Carlsson5adde292010-11-24 22:55:48 +0000602 CXXIndirectPrimaryBaseSet IndirectPrimaryBases;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000603
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000604 /// FirstNearlyEmptyVBase - The first nearly empty virtual base class in
605 /// inheritance graph order. Used for determining the primary base class.
606 const CXXRecordDecl *FirstNearlyEmptyVBase;
607
608 /// VisitedVirtualBases - A set of all the visited virtual bases, used to
609 /// avoid visiting virtual bases more than once.
610 llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000611
Douglas Gregore9fc3772012-01-26 07:55:45 +0000612 /// \brief Externally-provided size.
613 uint64_t ExternalSize;
614
615 /// \brief Externally-provided alignment.
616 uint64_t ExternalAlign;
617
618 /// \brief Externally-provided field offsets.
619 llvm::DenseMap<const FieldDecl *, uint64_t> ExternalFieldOffsets;
620
621 /// \brief Externally-provided direct, non-virtual base offsets.
622 llvm::DenseMap<const CXXRecordDecl *, CharUnits> ExternalBaseOffsets;
623
624 /// \brief Externally-provided virtual base offsets.
625 llvm::DenseMap<const CXXRecordDecl *, CharUnits> ExternalVirtualBaseOffsets;
626
John McCall0153cd32011-11-08 04:01:03 +0000627 RecordLayoutBuilder(const ASTContext &Context,
628 EmptySubobjectMap *EmptySubobjects)
Ken Dyck4731d5b2011-02-16 02:05:21 +0000629 : Context(Context), EmptySubobjects(EmptySubobjects), Size(0),
John McCall0153cd32011-11-08 04:01:03 +0000630 Alignment(CharUnits::One()), UnpackedAlignment(CharUnits::One()),
Douglas Gregor44ba7892012-01-28 00:53:29 +0000631 ExternalLayout(false), InferAlignment(false),
632 Packed(false), IsUnion(false), IsMac68kAlign(false), IsMsStruct(false),
Eli Friedman2782dac2013-06-26 20:50:34 +0000633 UnfilledBitsInLastUnit(0), LastBitfieldTypeSize(0),
634 MaxFieldAlignment(CharUnits::Zero()),
Ken Dyck02ced6f2011-02-17 01:49:42 +0000635 DataSize(0), NonVirtualSize(CharUnits::Zero()),
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000636 NonVirtualAlignment(CharUnits::One()),
Eli Friedman481673f2013-06-26 23:47:39 +0000637 PrimaryBase(0), PrimaryBaseIsVirtual(false),
John McCalle42a3362012-05-01 08:55:32 +0000638 HasOwnVFPtr(false),
Eli Friedman84d2d3a2011-09-27 19:12:27 +0000639 FirstNearlyEmptyVBase(0) { }
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000640
John McCall0153cd32011-11-08 04:01:03 +0000641 /// Reset this RecordLayoutBuilder to a fresh state, using the given
642 /// alignment as the initial alignment. This is used for the
643 /// correct layout of vb-table pointers in MSVC.
644 void resetWithTargetAlignment(CharUnits TargetAlignment) {
645 const ASTContext &Context = this->Context;
646 EmptySubobjectMap *EmptySubobjects = this->EmptySubobjects;
647 this->~RecordLayoutBuilder();
648 new (this) RecordLayoutBuilder(Context, EmptySubobjects);
649 Alignment = UnpackedAlignment = TargetAlignment;
650 }
651
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000652 void Layout(const RecordDecl *D);
Anders Carlssonc28a6c92010-05-26 15:10:00 +0000653 void Layout(const CXXRecordDecl *D);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000654 void Layout(const ObjCInterfaceDecl *D);
655
656 void LayoutFields(const RecordDecl *D);
657 void LayoutField(const FieldDecl *D);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000658 void LayoutWideBitField(uint64_t FieldSize, uint64_t TypeSize,
659 bool FieldPacked, const FieldDecl *D);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000660 void LayoutBitField(const FieldDecl *D);
John McCall0153cd32011-11-08 04:01:03 +0000661
John McCall359b8852013-01-25 22:30:49 +0000662 TargetCXXABI getCXXABI() const {
663 return Context.getTargetInfo().getCXXABI();
664 }
665
Anders Carlssone3c24c72010-05-29 17:35:14 +0000666 /// BaseSubobjectInfoAllocator - Allocator for BaseSubobjectInfo objects.
667 llvm::SpecificBumpPtrAllocator<BaseSubobjectInfo> BaseSubobjectInfoAllocator;
668
669 typedef llvm::DenseMap<const CXXRecordDecl *, BaseSubobjectInfo *>
670 BaseSubobjectInfoMapTy;
671
672 /// VirtualBaseInfo - Map from all the (direct or indirect) virtual bases
673 /// of the class we're laying out to their base subobject info.
674 BaseSubobjectInfoMapTy VirtualBaseInfo;
675
676 /// NonVirtualBaseInfo - Map from all the direct non-virtual bases of the
677 /// class we're laying out to their base subobject info.
678 BaseSubobjectInfoMapTy NonVirtualBaseInfo;
679
680 /// ComputeBaseSubobjectInfo - Compute the base subobject information for the
681 /// bases of the given class.
682 void ComputeBaseSubobjectInfo(const CXXRecordDecl *RD);
683
684 /// ComputeBaseSubobjectInfo - Compute the base subobject information for a
685 /// single class and all of its base classes.
686 BaseSubobjectInfo *ComputeBaseSubobjectInfo(const CXXRecordDecl *RD,
687 bool IsVirtual,
688 BaseSubobjectInfo *Derived);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000689
690 /// DeterminePrimaryBase - Determine the primary base of the given class.
691 void DeterminePrimaryBase(const CXXRecordDecl *RD);
692
693 void SelectPrimaryVBase(const CXXRecordDecl *RD);
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000694
Eli Friedman43114f92011-10-21 22:49:56 +0000695 void EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign);
Charles Davisc2c576a2010-08-19 00:55:19 +0000696
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000697 /// LayoutNonVirtualBases - Determines the primary base class (if any) and
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000698 /// lays it out. Will then proceed to lay out all non-virtual base clasess.
699 void LayoutNonVirtualBases(const CXXRecordDecl *RD);
700
701 /// LayoutNonVirtualBase - Lays out a single non-virtual base.
Anders Carlssonbb0e6782010-05-29 17:42:25 +0000702 void LayoutNonVirtualBase(const BaseSubobjectInfo *Base);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000703
Anders Carlssona2f8e412010-10-31 22:20:42 +0000704 void AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
705 CharUnits Offset);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000706
707 /// LayoutVirtualBases - Lays out all the virtual bases.
708 void LayoutVirtualBases(const CXXRecordDecl *RD,
709 const CXXRecordDecl *MostDerivedClass);
710
711 /// LayoutVirtualBase - Lays out a single virtual base.
Warren Hunt55d8e822013-10-23 23:53:07 +0000712 void LayoutVirtualBase(const BaseSubobjectInfo *Base);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000713
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000714 /// LayoutBase - Will lay out a base and return the offset where it was
Anders Carlssona2f8e412010-10-31 22:20:42 +0000715 /// placed, in chars.
716 CharUnits LayoutBase(const BaseSubobjectInfo *Base);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000717
Anders Carlssonc28a6c92010-05-26 15:10:00 +0000718 /// InitializeLayout - Initialize record layout for the given record decl.
Daniel Dunbar6da10982010-05-27 05:45:51 +0000719 void InitializeLayout(const Decl *D);
Anders Carlssonc28a6c92010-05-26 15:10:00 +0000720
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000721 /// FinishLayout - Finalize record layout. Adjust record size based on the
722 /// alignment.
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000723 void FinishLayout(const NamedDecl *D);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000724
Ken Dyck85ef0432011-02-19 18:58:07 +0000725 void UpdateAlignment(CharUnits NewAlignment, CharUnits UnpackedNewAlignment);
726 void UpdateAlignment(CharUnits NewAlignment) {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000727 UpdateAlignment(NewAlignment, NewAlignment);
728 }
729
Douglas Gregor44ba7892012-01-28 00:53:29 +0000730 /// \brief Retrieve the externally-supplied field offset for the given
731 /// field.
732 ///
733 /// \param Field The field whose offset is being queried.
734 /// \param ComputedOffset The offset that we've computed for this field.
735 uint64_t updateExternalFieldOffset(const FieldDecl *Field,
736 uint64_t ComputedOffset);
737
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000738 void CheckFieldPadding(uint64_t Offset, uint64_t UnpaddedOffset,
739 uint64_t UnpackedOffset, unsigned UnpackedAlign,
740 bool isPacked, const FieldDecl *D);
741
742 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000743
Ken Dyckecfc7552011-02-24 01:13:28 +0000744 CharUnits getSize() const {
Ken Dyck3c215f22011-02-24 01:33:05 +0000745 assert(Size % Context.getCharWidth() == 0);
Ken Dyckecfc7552011-02-24 01:13:28 +0000746 return Context.toCharUnitsFromBits(Size);
747 }
748 uint64_t getSizeInBits() const { return Size; }
749
750 void setSize(CharUnits NewSize) { Size = Context.toBits(NewSize); }
751 void setSize(uint64_t NewSize) { Size = NewSize; }
752
Eli Friedman84d2d3a2011-09-27 19:12:27 +0000753 CharUnits getAligment() const { return Alignment; }
754
Ken Dyckecfc7552011-02-24 01:13:28 +0000755 CharUnits getDataSize() const {
Ken Dyck3c215f22011-02-24 01:33:05 +0000756 assert(DataSize % Context.getCharWidth() == 0);
Ken Dyckecfc7552011-02-24 01:13:28 +0000757 return Context.toCharUnitsFromBits(DataSize);
758 }
759 uint64_t getDataSizeInBits() const { return DataSize; }
760
761 void setDataSize(CharUnits NewSize) { DataSize = Context.toBits(NewSize); }
762 void setDataSize(uint64_t NewSize) { DataSize = NewSize; }
763
Dmitri Gribenkoa664e5b2012-09-15 20:20:27 +0000764 RecordLayoutBuilder(const RecordLayoutBuilder &) LLVM_DELETED_FUNCTION;
765 void operator=(const RecordLayoutBuilder &) LLVM_DELETED_FUNCTION;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000766};
Benjamin Kramerc7656cd2010-05-26 09:58:31 +0000767} // end anonymous namespace
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000768
Anders Carlsson81430692009-09-22 03:02:06 +0000769void
Anders Carlssonc2226202010-05-26 05:58:59 +0000770RecordLayoutBuilder::SelectPrimaryVBase(const CXXRecordDecl *RD) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000771 for (const auto &I : RD->bases()) {
772 assert(!I.getType()->isDependentType() &&
Sebastian Redl1054fae2009-10-25 17:03:50 +0000773 "Cannot layout class with dependent bases.");
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000774
Reid Klecknercd612ab2014-04-11 16:57:42 +0000775 const CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000776
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000777 // Check if this is a nearly empty virtual base.
Aaron Ballman574705e2014-03-13 15:41:46 +0000778 if (I.isVirtual() && Context.isNearlyEmpty(Base)) {
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000779 // If it's not an indirect primary base, then we've found our primary
780 // base.
Anders Carlsson81430692009-09-22 03:02:06 +0000781 if (!IndirectPrimaryBases.count(Base)) {
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000782 PrimaryBase = Base;
783 PrimaryBaseIsVirtual = true;
Mike Stump6f3793b2009-08-12 21:50:08 +0000784 return;
785 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000786
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000787 // Is this the first nearly empty virtual base?
788 if (!FirstNearlyEmptyVBase)
789 FirstNearlyEmptyVBase = Base;
Mike Stump6f3793b2009-08-12 21:50:08 +0000790 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000791
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000792 SelectPrimaryVBase(Base);
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000793 if (PrimaryBase)
Zhongxing Xuec345b72010-02-15 04:28:35 +0000794 return;
Mike Stump6f3793b2009-08-12 21:50:08 +0000795 }
796}
797
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000798/// DeterminePrimaryBase - Determine the primary base of the given class.
Anders Carlssonc2226202010-05-26 05:58:59 +0000799void RecordLayoutBuilder::DeterminePrimaryBase(const CXXRecordDecl *RD) {
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000800 // If the class isn't dynamic, it won't have a primary base.
801 if (!RD->isDynamicClass())
802 return;
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000803
Anders Carlsson81430692009-09-22 03:02:06 +0000804 // Compute all the primary virtual bases for all of our direct and
Mike Stump590a7c72009-08-13 23:26:06 +0000805 // indirect bases, and record all their primary virtual base classes.
Anders Carlsson5adde292010-11-24 22:55:48 +0000806 RD->getIndirectPrimaryBases(IndirectPrimaryBases);
Mike Stump590a7c72009-08-13 23:26:06 +0000807
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000808 // If the record has a dynamic base class, attempt to choose a primary base
809 // class. It is the first (in direct base class order) non-virtual dynamic
Anders Carlsson81430692009-09-22 03:02:06 +0000810 // base class, if one exists.
Aaron Ballman574705e2014-03-13 15:41:46 +0000811 for (const auto &I : RD->bases()) {
Anders Carlsson03ff3792009-11-27 22:05:05 +0000812 // Ignore virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000813 if (I.isVirtual())
Anders Carlsson03ff3792009-11-27 22:05:05 +0000814 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000815
Reid Klecknercd612ab2014-04-11 16:57:42 +0000816 const CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
Anders Carlsson03ff3792009-11-27 22:05:05 +0000817
Warren Hunt55d8e822013-10-23 23:53:07 +0000818 if (Base->isDynamicClass()) {
Anders Carlsson03ff3792009-11-27 22:05:05 +0000819 // We found it.
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000820 PrimaryBase = Base;
821 PrimaryBaseIsVirtual = false;
Anders Carlsson03ff3792009-11-27 22:05:05 +0000822 return;
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000823 }
824 }
825
Eli Friedman5e9534b2011-10-18 00:55:28 +0000826 // Under the Itanium ABI, if there is no non-virtual primary base class,
827 // try to compute the primary virtual base. The primary virtual base is
828 // the first nearly empty virtual base that is not an indirect primary
829 // virtual base class, if one exists.
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000830 if (RD->getNumVBases() != 0) {
831 SelectPrimaryVBase(RD);
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000832 if (PrimaryBase)
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000833 return;
834 }
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000835
Eli Friedman5e9534b2011-10-18 00:55:28 +0000836 // Otherwise, it is the first indirect primary base class, if one exists.
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000837 if (FirstNearlyEmptyVBase) {
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000838 PrimaryBase = FirstNearlyEmptyVBase;
839 PrimaryBaseIsVirtual = true;
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000840 return;
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000841 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000842
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000843 assert(!PrimaryBase && "Should not get here with a primary base!");
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000844}
845
Anders Carlssone3c24c72010-05-29 17:35:14 +0000846BaseSubobjectInfo *
847RecordLayoutBuilder::ComputeBaseSubobjectInfo(const CXXRecordDecl *RD,
848 bool IsVirtual,
849 BaseSubobjectInfo *Derived) {
850 BaseSubobjectInfo *Info;
851
852 if (IsVirtual) {
853 // Check if we already have info about this virtual base.
854 BaseSubobjectInfo *&InfoSlot = VirtualBaseInfo[RD];
855 if (InfoSlot) {
856 assert(InfoSlot->Class == RD && "Wrong class for virtual base info!");
857 return InfoSlot;
858 }
859
860 // We don't, create it.
861 InfoSlot = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
862 Info = InfoSlot;
863 } else {
864 Info = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
865 }
866
867 Info->Class = RD;
868 Info->IsVirtual = IsVirtual;
869 Info->Derived = 0;
870 Info->PrimaryVirtualBaseInfo = 0;
871
872 const CXXRecordDecl *PrimaryVirtualBase = 0;
873 BaseSubobjectInfo *PrimaryVirtualBaseInfo = 0;
874
875 // Check if this base has a primary virtual base.
876 if (RD->getNumVBases()) {
877 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Anders Carlsson7f95cd12010-11-24 23:12:57 +0000878 if (Layout.isPrimaryBaseVirtual()) {
Anders Carlssone3c24c72010-05-29 17:35:14 +0000879 // This base does have a primary virtual base.
880 PrimaryVirtualBase = Layout.getPrimaryBase();
881 assert(PrimaryVirtualBase && "Didn't have a primary virtual base!");
882
883 // Now check if we have base subobject info about this primary base.
884 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
885
886 if (PrimaryVirtualBaseInfo) {
887 if (PrimaryVirtualBaseInfo->Derived) {
888 // We did have info about this primary base, and it turns out that it
889 // has already been claimed as a primary virtual base for another
890 // base.
891 PrimaryVirtualBase = 0;
892 } else {
893 // We can claim this base as our primary base.
894 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
895 PrimaryVirtualBaseInfo->Derived = Info;
896 }
897 }
898 }
899 }
900
901 // Now go through all direct bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000902 for (const auto &I : RD->bases()) {
903 bool IsVirtual = I.isVirtual();
Reid Klecknercd612ab2014-04-11 16:57:42 +0000904
905 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
906
Anders Carlssone3c24c72010-05-29 17:35:14 +0000907 Info->Bases.push_back(ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, Info));
908 }
909
910 if (PrimaryVirtualBase && !PrimaryVirtualBaseInfo) {
911 // Traversing the bases must have created the base info for our primary
912 // virtual base.
913 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
914 assert(PrimaryVirtualBaseInfo &&
915 "Did not create a primary virtual base!");
916
917 // Claim the primary virtual base as our primary virtual base.
918 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
919 PrimaryVirtualBaseInfo->Derived = Info;
920 }
921
922 return Info;
923}
924
925void RecordLayoutBuilder::ComputeBaseSubobjectInfo(const CXXRecordDecl *RD) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000926 for (const auto &I : RD->bases()) {
927 bool IsVirtual = I.isVirtual();
Anders Carlssone3c24c72010-05-29 17:35:14 +0000928
Reid Klecknercd612ab2014-04-11 16:57:42 +0000929 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
930
Anders Carlssone3c24c72010-05-29 17:35:14 +0000931 // Compute the base subobject info for this base.
932 BaseSubobjectInfo *Info = ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, 0);
933
934 if (IsVirtual) {
935 // ComputeBaseInfo has already added this base for us.
936 assert(VirtualBaseInfo.count(BaseDecl) &&
937 "Did not add virtual base!");
938 } else {
939 // Add the base info to the map of non-virtual bases.
940 assert(!NonVirtualBaseInfo.count(BaseDecl) &&
941 "Non-virtual base already exists!");
942 NonVirtualBaseInfo.insert(std::make_pair(BaseDecl, Info));
943 }
944 }
945}
946
Anders Carlsson09ffa322010-03-10 22:21:28 +0000947void
Eli Friedman43114f92011-10-21 22:49:56 +0000948RecordLayoutBuilder::EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign) {
Eli Friedman5e9534b2011-10-18 00:55:28 +0000949 CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
950
951 // The maximum field alignment overrides base align.
952 if (!MaxFieldAlignment.isZero()) {
953 BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
954 UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
955 }
956
957 // Round up the current record size to pointer alignment.
Eli Friedman43114f92011-10-21 22:49:56 +0000958 setSize(getSize().RoundUpToAlignment(BaseAlign));
959 setDataSize(getSize());
Eli Friedman5e9534b2011-10-18 00:55:28 +0000960
961 // Update the alignment.
962 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
963}
964
965void
Anders Carlssonc2226202010-05-26 05:58:59 +0000966RecordLayoutBuilder::LayoutNonVirtualBases(const CXXRecordDecl *RD) {
Anders Carlssone3c24c72010-05-29 17:35:14 +0000967 // Then, determine the primary base class.
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000968 DeterminePrimaryBase(RD);
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000969
Anders Carlssone3c24c72010-05-29 17:35:14 +0000970 // Compute base subobject info.
971 ComputeBaseSubobjectInfo(RD);
972
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000973 // If we have a primary base class, lay it out.
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000974 if (PrimaryBase) {
975 if (PrimaryBaseIsVirtual) {
Anders Carlssone3c24c72010-05-29 17:35:14 +0000976 // If the primary virtual base was a primary virtual base of some other
977 // base class we'll have to steal it.
978 BaseSubobjectInfo *PrimaryBaseInfo = VirtualBaseInfo.lookup(PrimaryBase);
979 PrimaryBaseInfo->Derived = 0;
980
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000981 // We have a virtual primary base, insert it as an indirect primary base.
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000982 IndirectPrimaryBases.insert(PrimaryBase);
Anders Carlssonfe900962010-03-11 05:42:17 +0000983
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000984 assert(!VisitedVirtualBases.count(PrimaryBase) &&
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000985 "vbase already visited!");
986 VisitedVirtualBases.insert(PrimaryBase);
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000987
Anders Carlssond6ff5d72010-05-29 17:48:36 +0000988 LayoutVirtualBase(PrimaryBaseInfo);
Anders Carlssonbb0e6782010-05-29 17:42:25 +0000989 } else {
990 BaseSubobjectInfo *PrimaryBaseInfo =
991 NonVirtualBaseInfo.lookup(PrimaryBase);
992 assert(PrimaryBaseInfo &&
993 "Did not find base info for non-virtual primary base!");
994
995 LayoutNonVirtualBase(PrimaryBaseInfo);
996 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000997
John McCall0153cd32011-11-08 04:01:03 +0000998 // If this class needs a vtable/vf-table and didn't get one from a
999 // primary base, add it in now.
Warren Hunt55d8e822013-10-23 23:53:07 +00001000 } else if (RD->isDynamicClass()) {
Eli Friedman5e9534b2011-10-18 00:55:28 +00001001 assert(DataSize == 0 && "Vtable pointer must be at offset zero!");
Eli Friedman5e9534b2011-10-18 00:55:28 +00001002 CharUnits PtrWidth =
1003 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Eli Friedman43114f92011-10-21 22:49:56 +00001004 CharUnits PtrAlign =
1005 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0));
1006 EnsureVTablePointerAlignment(PtrAlign);
John McCalle42a3362012-05-01 08:55:32 +00001007 HasOwnVFPtr = true;
Eli Friedman5e9534b2011-10-18 00:55:28 +00001008 setSize(getSize() + PtrWidth);
1009 setDataSize(getSize());
1010 }
1011
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001012 // Now lay out the non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001013 for (const auto &I : RD->bases()) {
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001014
Benjamin Kramer273670a2013-10-25 07:40:50 +00001015 // Ignore virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001016 if (I.isVirtual())
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001017 continue;
1018
Aaron Ballman574705e2014-03-13 15:41:46 +00001019 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001020
John McCall0153cd32011-11-08 04:01:03 +00001021 // Skip the primary base, because we've already laid it out. The
1022 // !PrimaryBaseIsVirtual check is required because we might have a
1023 // non-virtual base of the same type as a primary virtual base.
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001024 if (BaseDecl == PrimaryBase && !PrimaryBaseIsVirtual)
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001025 continue;
1026
1027 // Lay out the base.
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001028 BaseSubobjectInfo *BaseInfo = NonVirtualBaseInfo.lookup(BaseDecl);
1029 assert(BaseInfo && "Did not find base info for non-virtual base!");
1030
1031 LayoutNonVirtualBase(BaseInfo);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001032 }
1033}
1034
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001035void RecordLayoutBuilder::LayoutNonVirtualBase(const BaseSubobjectInfo *Base) {
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001036 // Layout the base.
Anders Carlssona2f8e412010-10-31 22:20:42 +00001037 CharUnits Offset = LayoutBase(Base);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001038
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001039 // Add its base class offset.
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001040 assert(!Bases.count(Base->Class) && "base offset already exists!");
Anders Carlssona2f8e412010-10-31 22:20:42 +00001041 Bases.insert(std::make_pair(Base->Class, Offset));
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001042
1043 AddPrimaryVirtualBaseOffsets(Base, Offset);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001044}
Mike Stump2b84dd32009-11-05 04:02:15 +00001045
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001046void
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001047RecordLayoutBuilder::AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
Anders Carlssona2f8e412010-10-31 22:20:42 +00001048 CharUnits Offset) {
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001049 // This base isn't interesting, it has no virtual bases.
1050 if (!Info->Class->getNumVBases())
1051 return;
1052
1053 // First, check if we have a virtual primary base to add offsets for.
1054 if (Info->PrimaryVirtualBaseInfo) {
1055 assert(Info->PrimaryVirtualBaseInfo->IsVirtual &&
1056 "Primary virtual base is not virtual!");
1057 if (Info->PrimaryVirtualBaseInfo->Derived == Info) {
1058 // Add the offset.
1059 assert(!VBases.count(Info->PrimaryVirtualBaseInfo->Class) &&
1060 "primary vbase offset already exists!");
1061 VBases.insert(std::make_pair(Info->PrimaryVirtualBaseInfo->Class,
John McCalle42a3362012-05-01 08:55:32 +00001062 ASTRecordLayout::VBaseInfo(Offset, false)));
Anders Carlssonea7b1822010-04-15 16:12:58 +00001063
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001064 // Traverse the primary virtual base.
1065 AddPrimaryVirtualBaseOffsets(Info->PrimaryVirtualBaseInfo, Offset);
1066 }
Anders Carlssonea7b1822010-04-15 16:12:58 +00001067 }
1068
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001069 // Now go through all direct non-virtual bases.
1070 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
1071 for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) {
1072 const BaseSubobjectInfo *Base = Info->Bases[I];
1073 if (Base->IsVirtual)
Anders Carlssonea7b1822010-04-15 16:12:58 +00001074 continue;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001075
Anders Carlsson0a14ee92010-11-01 00:21:58 +00001076 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001077 AddPrimaryVirtualBaseOffsets(Base, BaseOffset);
Anders Carlssonea7b1822010-04-15 16:12:58 +00001078 }
1079}
1080
1081void
Anders Carlssonc2226202010-05-26 05:58:59 +00001082RecordLayoutBuilder::LayoutVirtualBases(const CXXRecordDecl *RD,
Anders Carlssonea7b1822010-04-15 16:12:58 +00001083 const CXXRecordDecl *MostDerivedClass) {
Anders Carlssonde710c92010-03-11 04:33:54 +00001084 const CXXRecordDecl *PrimaryBase;
Anders Carlsson291279e2010-04-10 18:42:27 +00001085 bool PrimaryBaseIsVirtual;
Anders Carlssonfe900962010-03-11 05:42:17 +00001086
Anders Carlsson291279e2010-04-10 18:42:27 +00001087 if (MostDerivedClass == RD) {
Anders Carlssond20e7cd2010-05-26 05:20:58 +00001088 PrimaryBase = this->PrimaryBase;
1089 PrimaryBaseIsVirtual = this->PrimaryBaseIsVirtual;
Anders Carlsson291279e2010-04-10 18:42:27 +00001090 } else {
Anders Carlsson5efc56e2010-04-16 15:07:51 +00001091 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Anders Carlssonde710c92010-03-11 04:33:54 +00001092 PrimaryBase = Layout.getPrimaryBase();
Anders Carlsson7f95cd12010-11-24 23:12:57 +00001093 PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
Anders Carlsson291279e2010-04-10 18:42:27 +00001094 }
1095
Aaron Ballman574705e2014-03-13 15:41:46 +00001096 for (const auto &I : RD->bases()) {
1097 assert(!I.getType()->isDependentType() &&
Sebastian Redl1054fae2009-10-25 17:03:50 +00001098 "Cannot layout class with dependent bases.");
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001099
Aaron Ballman574705e2014-03-13 15:41:46 +00001100 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
Anders Carlssonf7b7a1e2010-03-11 04:24:02 +00001101
Aaron Ballman574705e2014-03-13 15:41:46 +00001102 if (I.isVirtual()) {
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001103 if (PrimaryBase != BaseDecl || !PrimaryBaseIsVirtual) {
1104 bool IndirectPrimaryBase = IndirectPrimaryBases.count(BaseDecl);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001105
Anders Carlsson291279e2010-04-10 18:42:27 +00001106 // Only lay out the virtual base if it's not an indirect primary base.
1107 if (!IndirectPrimaryBase) {
1108 // Only visit virtual bases once.
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001109 if (!VisitedVirtualBases.insert(BaseDecl))
Anders Carlsson291279e2010-04-10 18:42:27 +00001110 continue;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001111
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001112 const BaseSubobjectInfo *BaseInfo = VirtualBaseInfo.lookup(BaseDecl);
1113 assert(BaseInfo && "Did not find virtual base info!");
1114 LayoutVirtualBase(BaseInfo);
Anders Carlsson6a848892010-03-11 04:10:39 +00001115 }
Mike Stump2b84dd32009-11-05 04:02:15 +00001116 }
Mike Stumpc2f591b2009-08-13 22:53:07 +00001117 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001118
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001119 if (!BaseDecl->getNumVBases()) {
Anders Carlssonf7b7a1e2010-03-11 04:24:02 +00001120 // This base isn't interesting since it doesn't have any virtual bases.
1121 continue;
Mike Stump996576f32009-08-16 19:04:13 +00001122 }
Anders Carlssonf7b7a1e2010-03-11 04:24:02 +00001123
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001124 LayoutVirtualBases(BaseDecl, MostDerivedClass);
Mike Stump6b2556f2009-08-06 13:41:24 +00001125 }
1126}
1127
Warren Hunt55d8e822013-10-23 23:53:07 +00001128void RecordLayoutBuilder::LayoutVirtualBase(const BaseSubobjectInfo *Base) {
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001129 assert(!Base->Derived && "Trying to lay out a primary virtual base!");
1130
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001131 // Layout the base.
Anders Carlssona2f8e412010-10-31 22:20:42 +00001132 CharUnits Offset = LayoutBase(Base);
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001133
1134 // Add its base class offset.
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001135 assert(!VBases.count(Base->Class) && "vbase offset already exists!");
John McCalle42a3362012-05-01 08:55:32 +00001136 VBases.insert(std::make_pair(Base->Class,
Warren Hunt55d8e822013-10-23 23:53:07 +00001137 ASTRecordLayout::VBaseInfo(Offset, false)));
John McCalle42a3362012-05-01 08:55:32 +00001138
Warren Hunt55d8e822013-10-23 23:53:07 +00001139 AddPrimaryVirtualBaseOffsets(Base, Offset);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001140}
1141
Anders Carlssona2f8e412010-10-31 22:20:42 +00001142CharUnits RecordLayoutBuilder::LayoutBase(const BaseSubobjectInfo *Base) {
Anders Carlssond7f3fcf2010-05-29 20:47:33 +00001143 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base->Class);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001144
Douglas Gregore9fc3772012-01-26 07:55:45 +00001145
1146 CharUnits Offset;
1147
1148 // Query the external layout to see if it provides an offset.
1149 bool HasExternalLayout = false;
1150 if (ExternalLayout) {
1151 llvm::DenseMap<const CXXRecordDecl *, CharUnits>::iterator Known;
1152 if (Base->IsVirtual) {
1153 Known = ExternalVirtualBaseOffsets.find(Base->Class);
1154 if (Known != ExternalVirtualBaseOffsets.end()) {
1155 Offset = Known->second;
1156 HasExternalLayout = true;
1157 }
1158 } else {
1159 Known = ExternalBaseOffsets.find(Base->Class);
1160 if (Known != ExternalBaseOffsets.end()) {
1161 Offset = Known->second;
1162 HasExternalLayout = true;
1163 }
1164 }
1165 }
1166
Warren Huntd640d7d2014-01-09 00:30:56 +00001167 CharUnits UnpackedBaseAlign = Layout.getNonVirtualAlignment();
Eli Friedman69d27d22013-07-16 00:21:28 +00001168 CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
1169
Anders Carlsson09ffa322010-03-10 22:21:28 +00001170 // If we have an empty base class, try to place it at offset 0.
Anders Carlssond7f3fcf2010-05-29 20:47:33 +00001171 if (Base->Class->isEmpty() &&
Douglas Gregore9fc3772012-01-26 07:55:45 +00001172 (!HasExternalLayout || Offset == CharUnits::Zero()) &&
Anders Carlsson28466ab2010-10-31 22:13:23 +00001173 EmptySubobjects->CanPlaceBaseAtOffset(Base, CharUnits::Zero())) {
Ken Dyck1b4420e2011-02-28 02:01:38 +00001174 setSize(std::max(getSize(), Layout.getSize()));
Eli Friedman69d27d22013-07-16 00:21:28 +00001175 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001176
Anders Carlssona2f8e412010-10-31 22:20:42 +00001177 return CharUnits::Zero();
Anders Carlsson09ffa322010-03-10 22:21:28 +00001178 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001179
Argyrios Kyrtzidis8b542742010-12-09 00:35:20 +00001180 // The maximum field alignment overrides base align.
Ken Dyck02ced6f2011-02-17 01:49:42 +00001181 if (!MaxFieldAlignment.isZero()) {
Ken Dyck85ef0432011-02-19 18:58:07 +00001182 BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
1183 UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
Argyrios Kyrtzidis8b542742010-12-09 00:35:20 +00001184 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001185
Douglas Gregore9fc3772012-01-26 07:55:45 +00001186 if (!HasExternalLayout) {
1187 // Round up the current record size to the base's alignment boundary.
1188 Offset = getDataSize().RoundUpToAlignment(BaseAlign);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001189
Douglas Gregore9fc3772012-01-26 07:55:45 +00001190 // Try to place the base.
1191 while (!EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset))
1192 Offset += BaseAlign;
1193 } else {
1194 bool Allowed = EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset);
1195 (void)Allowed;
1196 assert(Allowed && "Base subobject externally placed at overlapping offset");
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001197
1198 if (InferAlignment && Offset < getDataSize().RoundUpToAlignment(BaseAlign)){
1199 // The externally-supplied base offset is before the base offset we
1200 // computed. Assume that the structure is packed.
1201 Alignment = CharUnits::One();
1202 InferAlignment = false;
1203 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00001204 }
1205
Anders Carlssond7f3fcf2010-05-29 20:47:33 +00001206 if (!Base->Class->isEmpty()) {
Anders Carlsson09ffa322010-03-10 22:21:28 +00001207 // Update the data size.
Ken Dyck1b4420e2011-02-28 02:01:38 +00001208 setDataSize(Offset + Layout.getNonVirtualSize());
Anders Carlsson09ffa322010-03-10 22:21:28 +00001209
Ken Dyck1b4420e2011-02-28 02:01:38 +00001210 setSize(std::max(getSize(), getDataSize()));
Anders Carlsson09ffa322010-03-10 22:21:28 +00001211 } else
Ken Dyck1b4420e2011-02-28 02:01:38 +00001212 setSize(std::max(getSize(), Offset + Layout.getSize()));
Anders Carlsson09ffa322010-03-10 22:21:28 +00001213
1214 // Remember max struct/class alignment.
Argyrios Kyrtzidis8b542742010-12-09 00:35:20 +00001215 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001216
Ken Dyck1b4420e2011-02-28 02:01:38 +00001217 return Offset;
Anders Carlsson09ffa322010-03-10 22:21:28 +00001218}
1219
Daniel Dunbar6da10982010-05-27 05:45:51 +00001220void RecordLayoutBuilder::InitializeLayout(const Decl *D) {
Eli Friedman9ee2d0472012-10-12 23:29:20 +00001221 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Daniel Dunbar6da10982010-05-27 05:45:51 +00001222 IsUnion = RD->isUnion();
Eli Friedman9ee2d0472012-10-12 23:29:20 +00001223 IsMsStruct = RD->isMsStruct(Context);
1224 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001225
Eli Friedman9ee2d0472012-10-12 23:29:20 +00001226 Packed = D->hasAttr<PackedAttr>();
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001227
Daniel Dunbar096ed292011-10-05 21:04:55 +00001228 // Honor the default struct packing maximum alignment flag.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001229 if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct) {
Daniel Dunbar096ed292011-10-05 21:04:55 +00001230 MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
1231 }
1232
Daniel Dunbar6da10982010-05-27 05:45:51 +00001233 // mac68k alignment supersedes maximum field alignment and attribute aligned,
1234 // and forces all structures to have 2-byte alignment. The IBM docs on it
1235 // allude to additional (more complicated) semantics, especially with regard
1236 // to bit-fields, but gcc appears not to follow that.
1237 if (D->hasAttr<AlignMac68kAttr>()) {
1238 IsMac68kAlign = true;
Ken Dyck02ced6f2011-02-17 01:49:42 +00001239 MaxFieldAlignment = CharUnits::fromQuantity(2);
Ken Dyck4731d5b2011-02-16 02:05:21 +00001240 Alignment = CharUnits::fromQuantity(2);
Daniel Dunbar6da10982010-05-27 05:45:51 +00001241 } else {
1242 if (const MaxFieldAlignmentAttr *MFAA = D->getAttr<MaxFieldAlignmentAttr>())
Ken Dyck02ced6f2011-02-17 01:49:42 +00001243 MaxFieldAlignment = Context.toCharUnitsFromBits(MFAA->getAlignment());
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001244
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001245 if (unsigned MaxAlign = D->getMaxAlignment())
Ken Dyck85ef0432011-02-19 18:58:07 +00001246 UpdateAlignment(Context.toCharUnitsFromBits(MaxAlign));
Daniel Dunbar6da10982010-05-27 05:45:51 +00001247 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00001248
1249 // If there is an external AST source, ask it for the various offsets.
1250 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
1251 if (ExternalASTSource *External = Context.getExternalSource()) {
1252 ExternalLayout = External->layoutRecordType(RD,
1253 ExternalSize,
1254 ExternalAlign,
1255 ExternalFieldOffsets,
1256 ExternalBaseOffsets,
1257 ExternalVirtualBaseOffsets);
1258
1259 // Update based on external alignment.
1260 if (ExternalLayout) {
Douglas Gregor44ba7892012-01-28 00:53:29 +00001261 if (ExternalAlign > 0) {
1262 Alignment = Context.toCharUnitsFromBits(ExternalAlign);
Douglas Gregor44ba7892012-01-28 00:53:29 +00001263 } else {
1264 // The external source didn't have alignment information; infer it.
1265 InferAlignment = true;
1266 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00001267 }
1268 }
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001269}
Anders Carlsson6d9f6f32009-07-19 00:18:47 +00001270
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001271void RecordLayoutBuilder::Layout(const RecordDecl *D) {
1272 InitializeLayout(D);
Anders Carlsson118ce162009-07-18 21:48:39 +00001273 LayoutFields(D);
Mike Stump11289f42009-09-09 15:08:12 +00001274
Anders Carlsson79474332009-07-18 20:20:21 +00001275 // Finally, round the size of the total struct up to the alignment of the
1276 // struct itself.
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001277 FinishLayout(D);
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001278}
1279
1280void RecordLayoutBuilder::Layout(const CXXRecordDecl *RD) {
1281 InitializeLayout(RD);
1282
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001283 // Lay out the vtable and the non-virtual bases.
1284 LayoutNonVirtualBases(RD);
1285
1286 LayoutFields(RD);
1287
Ken Dycke7380752011-03-10 01:53:59 +00001288 NonVirtualSize = Context.toCharUnitsFromBits(
1289 llvm::RoundUpToAlignment(getSizeInBits(),
Douglas Gregore8bbc122011-09-02 00:18:52 +00001290 Context.getTargetInfo().getCharAlign()));
Ken Dyck4731d5b2011-02-16 02:05:21 +00001291 NonVirtualAlignment = Alignment;
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001292
Warren Hunt55d8e822013-10-23 23:53:07 +00001293 // Lay out the virtual bases and add the primary virtual base offsets.
1294 LayoutVirtualBases(RD, RD);
John McCall0153cd32011-11-08 04:01:03 +00001295
1296 // Finally, round the size of the total struct up to the alignment
Eli Friedman83a12582011-12-01 00:37:01 +00001297 // of the struct itself.
1298 FinishLayout(RD);
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001299
Anders Carlsson5b441d72010-04-10 21:24:48 +00001300#ifndef NDEBUG
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001301 // Check that we have base offsets for all bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001302 for (const auto &I : RD->bases()) {
1303 if (I.isVirtual())
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001304 continue;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001305
Reid Klecknercd612ab2014-04-11 16:57:42 +00001306 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001307
1308 assert(Bases.count(BaseDecl) && "Did not find base offset!");
1309 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001310
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001311 // And all virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00001312 for (const auto &I : RD->vbases()) {
Reid Klecknercd612ab2014-04-11 16:57:42 +00001313 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001314
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001315 assert(VBases.count(BaseDecl) && "Did not find base offset!");
Anders Carlsson5b441d72010-04-10 21:24:48 +00001316 }
1317#endif
Anders Carlsson79474332009-07-18 20:20:21 +00001318}
1319
Anders Carlssonc2226202010-05-26 05:58:59 +00001320void RecordLayoutBuilder::Layout(const ObjCInterfaceDecl *D) {
Anders Carlsson4f516282009-07-18 20:50:59 +00001321 if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
Anders Carlsson5efc56e2010-04-16 15:07:51 +00001322 const ASTRecordLayout &SL = Context.getASTObjCInterfaceLayout(SD);
Anders Carlsson4f516282009-07-18 20:50:59 +00001323
Ken Dyck85ef0432011-02-19 18:58:07 +00001324 UpdateAlignment(SL.getAlignment());
Mike Stump11289f42009-09-09 15:08:12 +00001325
Anders Carlsson4f516282009-07-18 20:50:59 +00001326 // We start laying out ivars not at the end of the superclass
1327 // structure, but at the next byte following the last field.
Ken Dyckecfc7552011-02-24 01:13:28 +00001328 setSize(SL.getDataSize());
Ken Dyck1b4420e2011-02-28 02:01:38 +00001329 setDataSize(getSize());
Anders Carlsson4f516282009-07-18 20:50:59 +00001330 }
Mike Stump11289f42009-09-09 15:08:12 +00001331
Daniel Dunbar6da10982010-05-27 05:45:51 +00001332 InitializeLayout(D);
Anders Carlsson4f516282009-07-18 20:50:59 +00001333 // Layout each ivar sequentially.
Jordy Rosea91768e2011-07-22 02:08:32 +00001334 for (const ObjCIvarDecl *IVD = D->all_declared_ivar_begin(); IVD;
1335 IVD = IVD->getNextIvar())
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001336 LayoutField(IVD);
Mike Stump11289f42009-09-09 15:08:12 +00001337
Anders Carlsson4f516282009-07-18 20:50:59 +00001338 // Finally, round the size of the total struct up to the alignment of the
1339 // struct itself.
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001340 FinishLayout(D);
Anders Carlsson4f516282009-07-18 20:50:59 +00001341}
1342
Anders Carlssonc2226202010-05-26 05:58:59 +00001343void RecordLayoutBuilder::LayoutFields(const RecordDecl *D) {
Anders Carlsson118ce162009-07-18 21:48:39 +00001344 // Layout each field, for now, just sequentially, respecting alignment. In
1345 // the future, this will need to be tweakable by targets.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001346 for (const auto *Field : D->fields())
1347 LayoutField(Field);
Anders Carlsson118ce162009-07-18 21:48:39 +00001348}
1349
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001350void RecordLayoutBuilder::LayoutWideBitField(uint64_t FieldSize,
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001351 uint64_t TypeSize,
1352 bool FieldPacked,
1353 const FieldDecl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001354 assert(Context.getLangOpts().CPlusPlus &&
Anders Carlsson57235162010-04-16 15:57:11 +00001355 "Can only have wide bit-fields in C++!");
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001356
Anders Carlsson57235162010-04-16 15:57:11 +00001357 // Itanium C++ ABI 2.4:
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001358 // If sizeof(T)*8 < n, let T' be the largest integral POD type with
Anders Carlsson57235162010-04-16 15:57:11 +00001359 // sizeof(T')*8 <= n.
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001360
Anders Carlsson57235162010-04-16 15:57:11 +00001361 QualType IntegralPODTypes[] = {
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001362 Context.UnsignedCharTy, Context.UnsignedShortTy, Context.UnsignedIntTy,
Anders Carlsson57235162010-04-16 15:57:11 +00001363 Context.UnsignedLongTy, Context.UnsignedLongLongTy
1364 };
1365
Anders Carlsson57235162010-04-16 15:57:11 +00001366 QualType Type;
1367 for (unsigned I = 0, E = llvm::array_lengthof(IntegralPODTypes);
1368 I != E; ++I) {
1369 uint64_t Size = Context.getTypeSize(IntegralPODTypes[I]);
Anders Carlsson57235162010-04-16 15:57:11 +00001370
1371 if (Size > FieldSize)
1372 break;
1373
1374 Type = IntegralPODTypes[I];
1375 }
1376 assert(!Type.isNull() && "Did not find a type!");
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001377
Ken Dyckdbe37f32011-03-01 01:36:00 +00001378 CharUnits TypeAlign = Context.getTypeAlignInChars(Type);
Anders Carlsson57235162010-04-16 15:57:11 +00001379
1380 // We're not going to use any of the unfilled bits in the last byte.
Eli Friedman2782dac2013-06-26 20:50:34 +00001381 UnfilledBitsInLastUnit = 0;
1382 LastBitfieldTypeSize = 0;
Anders Carlsson57235162010-04-16 15:57:11 +00001383
Anders Carlssonaad5fa82010-04-17 20:21:41 +00001384 uint64_t FieldOffset;
Eli Friedman2782dac2013-06-26 20:50:34 +00001385 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001386
Anders Carlsson57235162010-04-16 15:57:11 +00001387 if (IsUnion) {
Ken Dyckecfc7552011-02-24 01:13:28 +00001388 setDataSize(std::max(getDataSizeInBits(), FieldSize));
Anders Carlssonaad5fa82010-04-17 20:21:41 +00001389 FieldOffset = 0;
Anders Carlsson57235162010-04-16 15:57:11 +00001390 } else {
Chad Rosiere1a6a0e2011-08-05 22:38:04 +00001391 // The bitfield is allocated starting at the next offset aligned
1392 // appropriately for T', with length n bits.
Ken Dyckdbe37f32011-03-01 01:36:00 +00001393 FieldOffset = llvm::RoundUpToAlignment(getDataSizeInBits(),
1394 Context.toBits(TypeAlign));
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001395
Anders Carlsson57235162010-04-16 15:57:11 +00001396 uint64_t NewSizeInBits = FieldOffset + FieldSize;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001397
Ken Dycka1a2e8d2011-03-10 02:00:35 +00001398 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits,
Douglas Gregore8bbc122011-09-02 00:18:52 +00001399 Context.getTargetInfo().getCharAlign()));
Eli Friedman2782dac2013-06-26 20:50:34 +00001400 UnfilledBitsInLastUnit = getDataSizeInBits() - NewSizeInBits;
Anders Carlsson57235162010-04-16 15:57:11 +00001401 }
1402
1403 // Place this field at the current location.
1404 FieldOffsets.push_back(FieldOffset);
1405
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001406 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, FieldOffset,
Ken Dyckdbe37f32011-03-01 01:36:00 +00001407 Context.toBits(TypeAlign), FieldPacked, D);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001408
Anders Carlsson57235162010-04-16 15:57:11 +00001409 // Update the size.
Ken Dyckecfc7552011-02-24 01:13:28 +00001410 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001411
Anders Carlsson57235162010-04-16 15:57:11 +00001412 // Remember max struct/class alignment.
Ken Dyckdbe37f32011-03-01 01:36:00 +00001413 UpdateAlignment(TypeAlign);
Anders Carlsson57235162010-04-16 15:57:11 +00001414}
1415
Anders Carlssonc2226202010-05-26 05:58:59 +00001416void RecordLayoutBuilder::LayoutBitField(const FieldDecl *D) {
Anders Carlsson07209442009-11-22 17:37:31 +00001417 bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
Richard Smithcaf33902011-10-10 18:28:20 +00001418 uint64_t FieldSize = D->getBitWidthValue(Context);
Anders Carlsson5efc56e2010-04-16 15:07:51 +00001419 std::pair<uint64_t, unsigned> FieldInfo = Context.getTypeInfo(D->getType());
Anders Carlsson07209442009-11-22 17:37:31 +00001420 uint64_t TypeSize = FieldInfo.first;
1421 unsigned FieldAlign = FieldInfo.second;
Eli Friedman2782dac2013-06-26 20:50:34 +00001422
John McCall30268ca2014-01-29 07:53:44 +00001423 // UnfilledBitsInLastUnit is the difference between the end of the
1424 // last allocated bitfield (i.e. the first bit offset available for
1425 // bitfields) and the end of the current data size in bits (i.e. the
1426 // first bit offset available for non-bitfields). The current data
1427 // size in bits is always a multiple of the char size; additionally,
1428 // for ms_struct records it's also a multiple of the
1429 // LastBitfieldTypeSize (if set).
1430
John McCall76e1818a2014-02-13 00:50:08 +00001431 // The struct-layout algorithm is dictated by the platform ABI,
1432 // which in principle could use almost any rules it likes. In
1433 // practice, UNIXy targets tend to inherit the algorithm described
1434 // in the System V generic ABI. The basic bitfield layout rule in
1435 // System V is to place bitfields at the next available bit offset
1436 // where the entire bitfield would fit in an aligned storage unit of
1437 // the declared type; it's okay if an earlier or later non-bitfield
1438 // is allocated in the same storage unit. However, some targets
1439 // (those that !useBitFieldTypeAlignment(), e.g. ARM APCS) don't
1440 // require this storage unit to be aligned, and therefore always put
1441 // the bitfield at the next available bit offset.
John McCall30268ca2014-01-29 07:53:44 +00001442
John McCall76e1818a2014-02-13 00:50:08 +00001443 // ms_struct basically requests a complete replacement of the
1444 // platform ABI's struct-layout algorithm, with the high-level goal
1445 // of duplicating MSVC's layout. For non-bitfields, this follows
1446 // the the standard algorithm. The basic bitfield layout rule is to
1447 // allocate an entire unit of the bitfield's declared type
1448 // (e.g. 'unsigned long'), then parcel it up among successive
1449 // bitfields whose declared types have the same size, making a new
1450 // unit as soon as the last can no longer store the whole value.
1451 // Since it completely replaces the platform ABI's algorithm,
1452 // settings like !useBitFieldTypeAlignment() do not apply.
1453
1454 // A zero-width bitfield forces the use of a new storage unit for
1455 // later bitfields. In general, this occurs by rounding up the
1456 // current size of the struct as if the algorithm were about to
1457 // place a non-bitfield of the field's formal type. Usually this
1458 // does not change the alignment of the struct itself, but it does
1459 // on some targets (those that useZeroLengthBitfieldAlignment(),
1460 // e.g. ARM). In ms_struct layout, zero-width bitfields are
1461 // ignored unless they follow a non-zero-width bitfield.
1462
1463 // A field alignment restriction (e.g. from #pragma pack) or
1464 // specification (e.g. from __attribute__((aligned))) changes the
1465 // formal alignment of the field. For System V, this alters the
1466 // required alignment of the notional storage unit that must contain
1467 // the bitfield. For ms_struct, this only affects the placement of
1468 // new storage units. In both cases, the effect of #pragma pack is
1469 // ignored on zero-width bitfields.
1470
1471 // On System V, a packed field (e.g. from #pragma pack or
1472 // __attribute__((packed))) always uses the next available bit
1473 // offset.
1474
John McCall95833f32014-02-27 20:30:49 +00001475 // In an ms_struct struct, the alignment of a fundamental type is
1476 // always equal to its size. This is necessary in order to mimic
1477 // the i386 alignment rules on targets which might not fully align
1478 // all types (e.g. Darwin PPC32, where alignof(long long) == 4).
John McCall30268ca2014-01-29 07:53:44 +00001479
1480 // First, some simple bookkeeping to perform for ms_struct structs.
Eli Friedman2782dac2013-06-26 20:50:34 +00001481 if (IsMsStruct) {
John McCall30268ca2014-01-29 07:53:44 +00001482 // The field alignment for integer types is always the size.
Fariborz Jahanian7adbed62011-05-09 22:03:17 +00001483 FieldAlign = TypeSize;
John McCall30268ca2014-01-29 07:53:44 +00001484
1485 // If the previous field was not a bitfield, or was a bitfield
1486 // with a different storage unit size, we're done with that
1487 // storage unit.
Eli Friedman2782dac2013-06-26 20:50:34 +00001488 if (LastBitfieldTypeSize != TypeSize) {
John McCall30268ca2014-01-29 07:53:44 +00001489 // Also, ignore zero-length bitfields after non-bitfields.
1490 if (!LastBitfieldTypeSize && !FieldSize)
1491 FieldAlign = 1;
1492
Eli Friedman2782dac2013-06-26 20:50:34 +00001493 UnfilledBitsInLastUnit = 0;
1494 LastBitfieldTypeSize = 0;
1495 }
1496 }
1497
John McCall30268ca2014-01-29 07:53:44 +00001498 // If the field is wider than its declared type, it follows
1499 // different rules in all cases.
Anders Carlsson57235162010-04-16 15:57:11 +00001500 if (FieldSize > TypeSize) {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001501 LayoutWideBitField(FieldSize, TypeSize, FieldPacked, D);
Anders Carlsson57235162010-04-16 15:57:11 +00001502 return;
1503 }
1504
John McCall30268ca2014-01-29 07:53:44 +00001505 // Compute the next available bit offset.
1506 uint64_t FieldOffset =
1507 IsUnion ? 0 : (getDataSizeInBits() - UnfilledBitsInLastUnit);
1508
1509 // Handle targets that don't honor bitfield type alignment.
John McCall76e1818a2014-02-13 00:50:08 +00001510 if (!IsMsStruct && !Context.getTargetInfo().useBitFieldTypeAlignment()) {
John McCall30268ca2014-01-29 07:53:44 +00001511 // Some such targets do honor it on zero-width bitfields.
1512 if (FieldSize == 0 &&
1513 Context.getTargetInfo().useZeroLengthBitfieldAlignment()) {
1514 // The alignment to round up to is the max of the field's natural
1515 // alignment and a target-specific fixed value (sometimes zero).
1516 unsigned ZeroLengthBitfieldBoundary =
1517 Context.getTargetInfo().getZeroLengthBitfieldBoundary();
1518 FieldAlign = std::max(FieldAlign, ZeroLengthBitfieldBoundary);
1519
1520 // If that doesn't apply, just ignore the field alignment.
1521 } else {
1522 FieldAlign = 1;
1523 }
1524 }
1525
1526 // Remember the alignment we would have used if the field were not packed.
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001527 unsigned UnpackedFieldAlign = FieldAlign;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001528
Yunzhong Gao5fd0c9d2014-02-13 02:45:10 +00001529 // Ignore the field alignment if the field is packed unless it has zero-size.
1530 if (!IsMsStruct && FieldPacked && FieldSize != 0)
Anders Carlsson07209442009-11-22 17:37:31 +00001531 FieldAlign = 1;
Anders Carlsson07209442009-11-22 17:37:31 +00001532
John McCall30268ca2014-01-29 07:53:44 +00001533 // But, if there's an 'aligned' attribute on the field, honor that.
1534 if (unsigned ExplicitFieldAlign = D->getMaxAlignment()) {
1535 FieldAlign = std::max(FieldAlign, ExplicitFieldAlign);
1536 UnpackedFieldAlign = std::max(UnpackedFieldAlign, ExplicitFieldAlign);
1537 }
1538
1539 // But, if there's a #pragma pack in play, that takes precedent over
1540 // even the 'aligned' attribute, for non-zero-width bitfields.
1541 if (!MaxFieldAlignment.isZero() && FieldSize) {
Ken Dyck02ced6f2011-02-17 01:49:42 +00001542 unsigned MaxFieldAlignmentInBits = Context.toBits(MaxFieldAlignment);
1543 FieldAlign = std::min(FieldAlign, MaxFieldAlignmentInBits);
1544 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignmentInBits);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001545 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001546
John McCall30268ca2014-01-29 07:53:44 +00001547 // For purposes of diagnostics, we're going to simultaneously
1548 // compute the field offsets that we would have used if we weren't
1549 // adding any alignment padding or if the field weren't packed.
1550 uint64_t UnpaddedFieldOffset = FieldOffset;
1551 uint64_t UnpackedFieldOffset = FieldOffset;
1552
1553 // Check if we need to add padding to fit the bitfield within an
1554 // allocation unit with the right size and alignment. The rules are
1555 // somewhat different here for ms_struct structs.
1556 if (IsMsStruct) {
1557 // If it's not a zero-width bitfield, and we can fit the bitfield
1558 // into the active storage unit (and we haven't already decided to
1559 // start a new storage unit), just do so, regardless of any other
1560 // other consideration. Otherwise, round up to the right alignment.
1561 if (FieldSize == 0 || FieldSize > UnfilledBitsInLastUnit) {
1562 FieldOffset = llvm::RoundUpToAlignment(FieldOffset, FieldAlign);
1563 UnpackedFieldOffset = llvm::RoundUpToAlignment(UnpackedFieldOffset,
1564 UnpackedFieldAlign);
1565 UnfilledBitsInLastUnit = 0;
1566 }
1567
1568 } else {
1569 // #pragma pack, with any value, suppresses the insertion of padding.
1570 bool AllowPadding = MaxFieldAlignment.isZero();
1571
1572 // Compute the real offset.
1573 if (FieldSize == 0 ||
1574 (AllowPadding &&
1575 (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize)) {
1576 FieldOffset = llvm::RoundUpToAlignment(FieldOffset, FieldAlign);
1577 }
1578
1579 // Repeat the computation for diagnostic purposes.
1580 if (FieldSize == 0 ||
1581 (AllowPadding &&
1582 (UnpackedFieldOffset & (UnpackedFieldAlign-1)) + FieldSize > TypeSize))
1583 UnpackedFieldOffset = llvm::RoundUpToAlignment(UnpackedFieldOffset,
1584 UnpackedFieldAlign);
Eli Friedman2782dac2013-06-26 20:50:34 +00001585 }
1586
John McCall30268ca2014-01-29 07:53:44 +00001587 // If we're using external layout, give the external layout a chance
1588 // to override this information.
Douglas Gregor44ba7892012-01-28 00:53:29 +00001589 if (ExternalLayout)
1590 FieldOffset = updateExternalFieldOffset(D, FieldOffset);
1591
John McCall30268ca2014-01-29 07:53:44 +00001592 // Okay, place the bitfield at the calculated offset.
Anders Carlsson07209442009-11-22 17:37:31 +00001593 FieldOffsets.push_back(FieldOffset);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001594
John McCall30268ca2014-01-29 07:53:44 +00001595 // Bookkeeping:
1596
1597 // Anonymous members don't affect the overall record alignment,
1598 // except on targets where they do.
1599 if (!IsMsStruct &&
1600 !Context.getTargetInfo().useZeroLengthBitfieldAlignment() &&
1601 !D->getIdentifier())
1602 FieldAlign = UnpackedFieldAlign = 1;
1603
1604 // Diagnose differences in layout due to padding or packing.
Douglas Gregore9fc3772012-01-26 07:55:45 +00001605 if (!ExternalLayout)
1606 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, UnpackedFieldOffset,
1607 UnpackedFieldAlign, FieldPacked, D);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001608
Anders Carlssonba958402009-11-22 19:13:51 +00001609 // Update DataSize to include the last byte containing (part of) the bitfield.
John McCall30268ca2014-01-29 07:53:44 +00001610
1611 // For unions, this is just a max operation, as usual.
Anders Carlssonba958402009-11-22 19:13:51 +00001612 if (IsUnion) {
1613 // FIXME: I think FieldSize should be TypeSize here.
Ken Dyckecfc7552011-02-24 01:13:28 +00001614 setDataSize(std::max(getDataSizeInBits(), FieldSize));
John McCall30268ca2014-01-29 07:53:44 +00001615
1616 // For non-zero-width bitfields in ms_struct structs, allocate a new
1617 // storage unit if necessary.
1618 } else if (IsMsStruct && FieldSize) {
1619 // We should have cleared UnfilledBitsInLastUnit in every case
1620 // where we changed storage units.
1621 if (!UnfilledBitsInLastUnit) {
1622 setDataSize(FieldOffset + TypeSize);
1623 UnfilledBitsInLastUnit = TypeSize;
Eli Friedman2782dac2013-06-26 20:50:34 +00001624 }
John McCall30268ca2014-01-29 07:53:44 +00001625 UnfilledBitsInLastUnit -= FieldSize;
1626 LastBitfieldTypeSize = TypeSize;
1627
1628 // Otherwise, bump the data size up to include the bitfield,
1629 // including padding up to char alignment, and then remember how
1630 // bits we didn't use.
1631 } else {
1632 uint64_t NewSizeInBits = FieldOffset + FieldSize;
1633 uint64_t CharAlignment = Context.getTargetInfo().getCharAlign();
1634 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits, CharAlignment));
1635 UnfilledBitsInLastUnit = getDataSizeInBits() - NewSizeInBits;
1636
1637 // The only time we can get here for an ms_struct is if this is a
1638 // zero-width bitfield, which doesn't count as anything for the
1639 // purposes of unfilled bits.
1640 LastBitfieldTypeSize = 0;
Anders Carlssonba958402009-11-22 19:13:51 +00001641 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001642
Anders Carlssonba958402009-11-22 19:13:51 +00001643 // Update the size.
Ken Dyckecfc7552011-02-24 01:13:28 +00001644 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001645
Anders Carlsson07209442009-11-22 17:37:31 +00001646 // Remember max struct/class alignment.
Ken Dyck85ef0432011-02-19 18:58:07 +00001647 UpdateAlignment(Context.toCharUnitsFromBits(FieldAlign),
1648 Context.toCharUnitsFromBits(UnpackedFieldAlign));
Anders Carlsson07209442009-11-22 17:37:31 +00001649}
1650
Douglas Gregore9fc3772012-01-26 07:55:45 +00001651void RecordLayoutBuilder::LayoutField(const FieldDecl *D) {
Anders Carlsson07209442009-11-22 17:37:31 +00001652 if (D->isBitField()) {
1653 LayoutBitField(D);
1654 return;
1655 }
1656
Eli Friedman2782dac2013-06-26 20:50:34 +00001657 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001658
Anders Carlssonba958402009-11-22 19:13:51 +00001659 // Reset the unfilled bits.
Eli Friedman2782dac2013-06-26 20:50:34 +00001660 UnfilledBitsInLastUnit = 0;
1661 LastBitfieldTypeSize = 0;
Anders Carlssonba958402009-11-22 19:13:51 +00001662
Anders Carlsson07209442009-11-22 17:37:31 +00001663 bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
Ken Dyck6d90e892011-02-20 02:06:09 +00001664 CharUnits FieldOffset =
Ken Dyckecfc7552011-02-24 01:13:28 +00001665 IsUnion ? CharUnits::Zero() : getDataSize();
Ken Dyck6d90e892011-02-20 02:06:09 +00001666 CharUnits FieldSize;
1667 CharUnits FieldAlign;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001668
Anders Carlsson07209442009-11-22 17:37:31 +00001669 if (D->getType()->isIncompleteArrayType()) {
1670 // This is a flexible array member; we can't directly
1671 // query getTypeInfo about these, so we figure it out here.
1672 // Flexible array members don't have any size, but they
1673 // have to be aligned appropriately for their element type.
Ken Dyck6d90e892011-02-20 02:06:09 +00001674 FieldSize = CharUnits::Zero();
Anders Carlsson5efc56e2010-04-16 15:07:51 +00001675 const ArrayType* ATy = Context.getAsArrayType(D->getType());
Ken Dyck6d90e892011-02-20 02:06:09 +00001676 FieldAlign = Context.getTypeAlignInChars(ATy->getElementType());
Anders Carlsson07209442009-11-22 17:37:31 +00001677 } else if (const ReferenceType *RT = D->getType()->getAs<ReferenceType>()) {
1678 unsigned AS = RT->getPointeeType().getAddressSpace();
Ken Dyck6d90e892011-02-20 02:06:09 +00001679 FieldSize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001680 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(AS));
Ken Dyck6d90e892011-02-20 02:06:09 +00001681 FieldAlign =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001682 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(AS));
Anders Carlsson79474332009-07-18 20:20:21 +00001683 } else {
Ken Dyck6d90e892011-02-20 02:06:09 +00001684 std::pair<CharUnits, CharUnits> FieldInfo =
1685 Context.getTypeInfoInChars(D->getType());
Anders Carlsson07209442009-11-22 17:37:31 +00001686 FieldSize = FieldInfo.first;
1687 FieldAlign = FieldInfo.second;
Chad Rosier18903ee2011-08-04 01:21:14 +00001688
Eli Friedman9ee2d0472012-10-12 23:29:20 +00001689 if (IsMsStruct) {
Douglas Gregordbe39272011-02-01 15:15:22 +00001690 // If MS bitfield layout is required, figure out what type is being
1691 // laid out and align the field to the width of that type.
1692
1693 // Resolve all typedefs down to their base type and round up the field
1694 // alignment if necessary.
1695 QualType T = Context.getBaseElementType(D->getType());
1696 if (const BuiltinType *BTy = T->getAs<BuiltinType>()) {
Ken Dyck6d90e892011-02-20 02:06:09 +00001697 CharUnits TypeSize = Context.getTypeSizeInChars(BTy);
Douglas Gregordbe39272011-02-01 15:15:22 +00001698 if (TypeSize > FieldAlign)
1699 FieldAlign = TypeSize;
1700 }
1701 }
Anders Carlsson79474332009-07-18 20:20:21 +00001702 }
Mike Stump11289f42009-09-09 15:08:12 +00001703
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001704 // The align if the field is not packed. This is to check if the attribute
1705 // was unnecessary (-Wpacked).
Ken Dyck6d90e892011-02-20 02:06:09 +00001706 CharUnits UnpackedFieldAlign = FieldAlign;
1707 CharUnits UnpackedFieldOffset = FieldOffset;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001708
Anders Carlsson07209442009-11-22 17:37:31 +00001709 if (FieldPacked)
Ken Dyck6d90e892011-02-20 02:06:09 +00001710 FieldAlign = CharUnits::One();
1711 CharUnits MaxAlignmentInChars =
1712 Context.toCharUnitsFromBits(D->getMaxAlignment());
1713 FieldAlign = std::max(FieldAlign, MaxAlignmentInChars);
1714 UnpackedFieldAlign = std::max(UnpackedFieldAlign, MaxAlignmentInChars);
Anders Carlsson07209442009-11-22 17:37:31 +00001715
1716 // The maximum field alignment overrides the aligned attribute.
Ken Dyck02ced6f2011-02-17 01:49:42 +00001717 if (!MaxFieldAlignment.isZero()) {
Ken Dyck6d90e892011-02-20 02:06:09 +00001718 FieldAlign = std::min(FieldAlign, MaxFieldAlignment);
1719 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignment);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001720 }
Anders Carlsson07209442009-11-22 17:37:31 +00001721
Douglas Gregor44ba7892012-01-28 00:53:29 +00001722 // Round up the current record size to the field's alignment boundary.
1723 FieldOffset = FieldOffset.RoundUpToAlignment(FieldAlign);
1724 UnpackedFieldOffset =
1725 UnpackedFieldOffset.RoundUpToAlignment(UnpackedFieldAlign);
1726
1727 if (ExternalLayout) {
1728 FieldOffset = Context.toCharUnitsFromBits(
1729 updateExternalFieldOffset(D, Context.toBits(FieldOffset)));
1730
1731 if (!IsUnion && EmptySubobjects) {
1732 // Record the fact that we're placing a field at this offset.
1733 bool Allowed = EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset);
1734 (void)Allowed;
1735 assert(Allowed && "Externally-placed field cannot be placed here");
1736 }
1737 } else {
Douglas Gregore9fc3772012-01-26 07:55:45 +00001738 if (!IsUnion && EmptySubobjects) {
1739 // Check if we can place the field at this offset.
1740 while (!EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset)) {
1741 // We couldn't place the field at the offset. Try again at a new offset.
1742 FieldOffset += FieldAlign;
1743 }
Anders Carlsson07209442009-11-22 17:37:31 +00001744 }
Anders Carlsson07209442009-11-22 17:37:31 +00001745 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00001746
Anders Carlsson79474332009-07-18 20:20:21 +00001747 // Place this field at the current location.
Ken Dyck6d90e892011-02-20 02:06:09 +00001748 FieldOffsets.push_back(Context.toBits(FieldOffset));
Mike Stump11289f42009-09-09 15:08:12 +00001749
Douglas Gregore9fc3772012-01-26 07:55:45 +00001750 if (!ExternalLayout)
1751 CheckFieldPadding(Context.toBits(FieldOffset), UnpaddedFieldOffset,
1752 Context.toBits(UnpackedFieldOffset),
1753 Context.toBits(UnpackedFieldAlign), FieldPacked, D);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001754
Anders Carlsson79474332009-07-18 20:20:21 +00001755 // Reserve space for this field.
Eli Friedman43f18342012-01-12 23:27:03 +00001756 uint64_t FieldSizeInBits = Context.toBits(FieldSize);
Anders Carlsson79474332009-07-18 20:20:21 +00001757 if (IsUnion)
Eli Friedman2e108372012-01-12 23:48:56 +00001758 setDataSize(std::max(getDataSizeInBits(), FieldSizeInBits));
Anders Carlsson79474332009-07-18 20:20:21 +00001759 else
Eli Friedman2e108372012-01-12 23:48:56 +00001760 setDataSize(FieldOffset + FieldSize);
Mike Stump11289f42009-09-09 15:08:12 +00001761
Eli Friedman2e108372012-01-12 23:48:56 +00001762 // Update the size.
1763 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
Mike Stump11289f42009-09-09 15:08:12 +00001764
Anders Carlsson79474332009-07-18 20:20:21 +00001765 // Remember max struct/class alignment.
Ken Dyck6d90e892011-02-20 02:06:09 +00001766 UpdateAlignment(FieldAlign, UnpackedFieldAlign);
Anders Carlsson79474332009-07-18 20:20:21 +00001767}
1768
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001769void RecordLayoutBuilder::FinishLayout(const NamedDecl *D) {
Anders Carlsson79474332009-07-18 20:20:21 +00001770 // In C++, records cannot be of size 0.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001771 if (Context.getLangOpts().CPlusPlus && getSizeInBits() == 0) {
Fariborz Jahanian09b23312011-02-02 19:36:18 +00001772 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
1773 // Compatibility with gcc requires a class (pod or non-pod)
1774 // which is not empty but of size 0; such as having fields of
1775 // array of zero-length, remains of Size 0
1776 if (RD->isEmpty())
Ken Dyck1b4420e2011-02-28 02:01:38 +00001777 setSize(CharUnits::One());
Fariborz Jahanian09b23312011-02-02 19:36:18 +00001778 }
1779 else
Ken Dyck1b4420e2011-02-28 02:01:38 +00001780 setSize(CharUnits::One());
Fariborz Jahanian09b23312011-02-02 19:36:18 +00001781 }
Eli Friedman83a12582011-12-01 00:37:01 +00001782
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001783 // Finally, round the size of the record up to the alignment of the
1784 // record itself.
Eli Friedman2782dac2013-06-26 20:50:34 +00001785 uint64_t UnpaddedSize = getSizeInBits() - UnfilledBitsInLastUnit;
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001786 uint64_t UnpackedSizeInBits =
1787 llvm::RoundUpToAlignment(getSizeInBits(),
1788 Context.toBits(UnpackedAlignment));
1789 CharUnits UnpackedSize = Context.toCharUnitsFromBits(UnpackedSizeInBits);
1790 uint64_t RoundedSize
1791 = llvm::RoundUpToAlignment(getSizeInBits(), Context.toBits(Alignment));
1792
1793 if (ExternalLayout) {
1794 // If we're inferring alignment, and the external size is smaller than
1795 // our size after we've rounded up to alignment, conservatively set the
1796 // alignment to 1.
1797 if (InferAlignment && ExternalSize < RoundedSize) {
1798 Alignment = CharUnits::One();
1799 InferAlignment = false;
1800 }
1801 setSize(ExternalSize);
1802 return;
1803 }
1804
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001805 // Set the size to the final size.
1806 setSize(RoundedSize);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001807
Douglas Gregore8bbc122011-09-02 00:18:52 +00001808 unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001809 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
1810 // Warn if padding was introduced to the struct/class/union.
Ken Dyckecfc7552011-02-24 01:13:28 +00001811 if (getSizeInBits() > UnpaddedSize) {
1812 unsigned PadSize = getSizeInBits() - UnpaddedSize;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001813 bool InBits = true;
1814 if (PadSize % CharBitNum == 0) {
1815 PadSize = PadSize / CharBitNum;
1816 InBits = false;
1817 }
1818 Diag(RD->getLocation(), diag::warn_padded_struct_size)
1819 << Context.getTypeDeclType(RD)
1820 << PadSize
1821 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1); // plural or not
1822 }
1823
1824 // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
1825 // bother since there won't be alignment issues.
Ken Dyckecfc7552011-02-24 01:13:28 +00001826 if (Packed && UnpackedAlignment > CharUnits::One() &&
Ken Dyck1b4420e2011-02-28 02:01:38 +00001827 getSize() == UnpackedSize)
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001828 Diag(D->getLocation(), diag::warn_unnecessary_packed)
1829 << Context.getTypeDeclType(RD);
1830 }
Anders Carlsson79474332009-07-18 20:20:21 +00001831}
1832
Ken Dyck85ef0432011-02-19 18:58:07 +00001833void RecordLayoutBuilder::UpdateAlignment(CharUnits NewAlignment,
1834 CharUnits UnpackedNewAlignment) {
Douglas Gregore9fc3772012-01-26 07:55:45 +00001835 // The alignment is not modified when using 'mac68k' alignment or when
Douglas Gregor44ba7892012-01-28 00:53:29 +00001836 // we have an externally-supplied layout that also provides overall alignment.
1837 if (IsMac68kAlign || (ExternalLayout && !InferAlignment))
Daniel Dunbar6da10982010-05-27 05:45:51 +00001838 return;
1839
Ken Dyck85ef0432011-02-19 18:58:07 +00001840 if (NewAlignment > Alignment) {
1841 assert(llvm::isPowerOf2_32(NewAlignment.getQuantity() &&
1842 "Alignment not a power of 2"));
1843 Alignment = NewAlignment;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001844 }
1845
Ken Dyck85ef0432011-02-19 18:58:07 +00001846 if (UnpackedNewAlignment > UnpackedAlignment) {
1847 assert(llvm::isPowerOf2_32(UnpackedNewAlignment.getQuantity() &&
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001848 "Alignment not a power of 2"));
Ken Dyck85ef0432011-02-19 18:58:07 +00001849 UnpackedAlignment = UnpackedNewAlignment;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001850 }
1851}
1852
Douglas Gregor44ba7892012-01-28 00:53:29 +00001853uint64_t
1854RecordLayoutBuilder::updateExternalFieldOffset(const FieldDecl *Field,
1855 uint64_t ComputedOffset) {
1856 assert(ExternalFieldOffsets.find(Field) != ExternalFieldOffsets.end() &&
1857 "Field does not have an external offset");
1858
1859 uint64_t ExternalFieldOffset = ExternalFieldOffsets[Field];
1860
1861 if (InferAlignment && ExternalFieldOffset < ComputedOffset) {
1862 // The externally-supplied field offset is before the field offset we
1863 // computed. Assume that the structure is packed.
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001864 Alignment = CharUnits::One();
Douglas Gregor44ba7892012-01-28 00:53:29 +00001865 InferAlignment = false;
1866 }
1867
1868 // Use the externally-supplied field offset.
Benjamin Kramer648e68b2012-08-31 22:14:25 +00001869 return ExternalFieldOffset;
1870}
1871
1872/// \brief Get diagnostic %select index for tag kind for
1873/// field padding diagnostic message.
1874/// WARNING: Indexes apply to particular diagnostics only!
1875///
1876/// \returns diagnostic %select index.
1877static unsigned getPaddingDiagFromTagKind(TagTypeKind Tag) {
1878 switch (Tag) {
1879 case TTK_Struct: return 0;
1880 case TTK_Interface: return 1;
1881 case TTK_Class: return 2;
1882 default: llvm_unreachable("Invalid tag kind for field padding diagnostic!");
1883 }
1884}
1885
1886void RecordLayoutBuilder::CheckFieldPadding(uint64_t Offset,
1887 uint64_t UnpaddedOffset,
1888 uint64_t UnpackedOffset,
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001889 unsigned UnpackedAlign,
1890 bool isPacked,
1891 const FieldDecl *D) {
1892 // We let objc ivars without warning, objc interfaces generally are not used
1893 // for padding tricks.
1894 if (isa<ObjCIvarDecl>(D))
Anders Carlsson79474332009-07-18 20:20:21 +00001895 return;
Mike Stump11289f42009-09-09 15:08:12 +00001896
Ted Kremenekfed48af2011-09-06 19:40:45 +00001897 // Don't warn about structs created without a SourceLocation. This can
1898 // be done by clients of the AST, such as codegen.
1899 if (D->getLocation().isInvalid())
1900 return;
1901
Douglas Gregore8bbc122011-09-02 00:18:52 +00001902 unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
Mike Stump11289f42009-09-09 15:08:12 +00001903
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001904 // Warn if padding was introduced to the struct/class.
1905 if (!IsUnion && Offset > UnpaddedOffset) {
1906 unsigned PadSize = Offset - UnpaddedOffset;
1907 bool InBits = true;
1908 if (PadSize % CharBitNum == 0) {
1909 PadSize = PadSize / CharBitNum;
1910 InBits = false;
Benjamin Kramer648e68b2012-08-31 22:14:25 +00001911 }
1912 if (D->getIdentifier())
1913 Diag(D->getLocation(), diag::warn_padded_struct_field)
1914 << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
1915 << Context.getTypeDeclType(D->getParent())
1916 << PadSize
1917 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1) // plural or not
1918 << D->getIdentifier();
1919 else
1920 Diag(D->getLocation(), diag::warn_padded_struct_anon_field)
1921 << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
1922 << Context.getTypeDeclType(D->getParent())
1923 << PadSize
1924 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1); // plural or not
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001925 }
1926
1927 // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
1928 // bother since there won't be alignment issues.
1929 if (isPacked && UnpackedAlign > CharBitNum && Offset == UnpackedOffset)
1930 Diag(D->getLocation(), diag::warn_unnecessary_packed)
1931 << D->getIdentifier();
Anders Carlsson79474332009-07-18 20:20:21 +00001932}
Mike Stump11289f42009-09-09 15:08:12 +00001933
John McCall6bd2a892013-01-25 22:31:03 +00001934static const CXXMethodDecl *computeKeyFunction(ASTContext &Context,
1935 const CXXRecordDecl *RD) {
Daniel Dunbarccabe482010-04-19 20:44:53 +00001936 // If a class isn't polymorphic it doesn't have a key function.
Anders Carlsson5ebf8b42009-12-07 04:35:11 +00001937 if (!RD->isPolymorphic())
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001938 return 0;
Eli Friedmanf2c79b62009-12-08 03:56:49 +00001939
Eli Friedman300f55d2011-06-10 21:53:06 +00001940 // A class that is not externally visible doesn't have a key function. (Or
Eli Friedmanf2c79b62009-12-08 03:56:49 +00001941 // at least, there's no point to assigning a key function to such a class;
1942 // this doesn't affect the ABI.)
Rafael Espindola3ae00052013-05-13 00:12:11 +00001943 if (!RD->isExternallyVisible())
Eli Friedmanf2c79b62009-12-08 03:56:49 +00001944 return 0;
1945
Richard Smith750f5112014-03-24 23:54:09 +00001946 // Template instantiations don't have key functions per Itanium C++ ABI 5.2.6.
Argyrios Kyrtzidis8c64bbe2010-10-13 02:39:41 +00001947 // Same behavior as GCC.
1948 TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
1949 if (TSK == TSK_ImplicitInstantiation ||
Richard Smith750f5112014-03-24 23:54:09 +00001950 TSK == TSK_ExplicitInstantiationDeclaration ||
Argyrios Kyrtzidis8c64bbe2010-10-13 02:39:41 +00001951 TSK == TSK_ExplicitInstantiationDefinition)
1952 return 0;
1953
John McCall6bd2a892013-01-25 22:31:03 +00001954 bool allowInlineFunctions =
1955 Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline();
1956
Aaron Ballman2b124d12014-03-13 16:36:16 +00001957 for (const auto *MD : RD->methods()) {
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001958 if (!MD->isVirtual())
1959 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001960
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001961 if (MD->isPure())
1962 continue;
Eli Friedmanf2c79b62009-12-08 03:56:49 +00001963
Anders Carlssonf98849e2009-12-02 17:15:43 +00001964 // Ignore implicit member functions, they are always marked as inline, but
1965 // they don't have a body until they're defined.
1966 if (MD->isImplicit())
1967 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001968
Douglas Gregora318efd2010-01-05 19:06:31 +00001969 if (MD->isInlineSpecified())
1970 continue;
Eli Friedman71a26d82009-12-06 20:50:05 +00001971
1972 if (MD->hasInlineBody())
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001973 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001974
Benjamin Kramer4a902082012-08-03 15:43:22 +00001975 // Ignore inline deleted or defaulted functions.
Benjamin Kramer73d1be72012-08-03 08:39:58 +00001976 if (!MD->isUserProvided())
1977 continue;
1978
John McCall6bd2a892013-01-25 22:31:03 +00001979 // In certain ABIs, ignore functions with out-of-line inline definitions.
1980 if (!allowInlineFunctions) {
1981 const FunctionDecl *Def;
1982 if (MD->hasBody(Def) && Def->isInlineSpecified())
1983 continue;
1984 }
1985
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001986 // We found it.
1987 return MD;
1988 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001989
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001990 return 0;
1991}
1992
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001993DiagnosticBuilder
1994RecordLayoutBuilder::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +00001995 return Context.getDiagnostics().Report(Loc, DiagID);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001996}
1997
John McCall5c1f1d02013-01-29 01:14:22 +00001998/// Does the target C++ ABI require us to skip over the tail-padding
1999/// of the given class (considering it as a base class) when allocating
2000/// objects?
2001static bool mustSkipTailPadding(TargetCXXABI ABI, const CXXRecordDecl *RD) {
2002 switch (ABI.getTailPaddingUseRules()) {
2003 case TargetCXXABI::AlwaysUseTailPadding:
2004 return false;
2005
2006 case TargetCXXABI::UseTailPaddingUnlessPOD03:
2007 // FIXME: To the extent that this is meant to cover the Itanium ABI
2008 // rules, we should implement the restrictions about over-sized
2009 // bitfields:
2010 //
2011 // http://mentorembedded.github.com/cxx-abi/abi.html#POD :
2012 // In general, a type is considered a POD for the purposes of
2013 // layout if it is a POD type (in the sense of ISO C++
2014 // [basic.types]). However, a POD-struct or POD-union (in the
2015 // sense of ISO C++ [class]) with a bitfield member whose
2016 // declared width is wider than the declared type of the
2017 // bitfield is not a POD for the purpose of layout. Similarly,
2018 // an array type is not a POD for the purpose of layout if the
2019 // element type of the array is not a POD for the purpose of
2020 // layout.
2021 //
2022 // Where references to the ISO C++ are made in this paragraph,
2023 // the Technical Corrigendum 1 version of the standard is
2024 // intended.
2025 return RD->isPOD();
2026
2027 case TargetCXXABI::UseTailPaddingUnlessPOD11:
2028 // This is equivalent to RD->getTypeForDecl().isCXX11PODType(),
2029 // but with a lot of abstraction penalty stripped off. This does
2030 // assume that these properties are set correctly even in C++98
2031 // mode; fortunately, that is true because we want to assign
2032 // consistently semantics to the type-traits intrinsics (or at
2033 // least as many of them as possible).
2034 return RD->isTrivial() && RD->isStandardLayout();
2035 }
2036
2037 llvm_unreachable("bad tail-padding use kind");
2038}
2039
Warren Hunt8f8bad72013-10-11 20:19:00 +00002040static bool isMsLayout(const RecordDecl* D) {
Warren Hunt55d8e822013-10-23 23:53:07 +00002041 return D->getASTContext().getTargetInfo().getCXXABI().isMicrosoft();
Warren Hunt8f8bad72013-10-11 20:19:00 +00002042}
2043
2044// This section contains an implementation of struct layout that is, up to the
Warren Hunt917f97f2014-04-11 00:54:15 +00002045// included tests, compatible with cl.exe (2013). The layout produced is
Warren Hunt8f8bad72013-10-11 20:19:00 +00002046// significantly different than those produced by the Itanium ABI. Here we note
2047// the most important differences.
2048//
2049// * The alignment of bitfields in unions is ignored when computing the
2050// alignment of the union.
Alp Tokerf6a24ce2013-12-05 16:25:25 +00002051// * The existence of zero-width bitfield that occurs after anything other than
Warren Hunt8f8bad72013-10-11 20:19:00 +00002052// a non-zero length bitfield is ignored.
Warren Hunt917f97f2014-04-11 00:54:15 +00002053// * There is no explicit primary base for the purposes of layout. All bases
2054// with vfptrs are laid out first, followed by all bases without vfptrs.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002055// * The Itanium equivalent vtable pointers are split into a vfptr (virtual
2056// function pointer) and a vbptr (virtual base pointer). They can each be
Warren Hunt55d8e822013-10-23 23:53:07 +00002057// shared with a, non-virtual bases. These bases need not be the same. vfptrs
Warren Hunt917f97f2014-04-11 00:54:15 +00002058// always occur at offset 0. vbptrs can occur at an arbitrary offset and are
2059// placed after the lexiographically last non-virtual base. This placement
2060// is always before fields but can be in the middle of the non-virtual bases
2061// due to the two-pass layout scheme for non-virtual-bases.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002062// * Virtual bases sometimes require a 'vtordisp' field that is laid out before
2063// the virtual base and is used in conjunction with virtual overrides during
Warren Hunt917f97f2014-04-11 00:54:15 +00002064// construction and destruction. This is always a 4 byte value and is used as
2065// an alternative to constructor vtables.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002066// * vtordisps are allocated in a block of memory with size and alignment equal
2067// to the alignment of the completed structure (before applying __declspec(
Warren Hunt55d8e822013-10-23 23:53:07 +00002068// align())). The vtordisp always occur at the end of the allocation block,
2069// immediately prior to the virtual base.
Warren Hunt917f97f2014-04-11 00:54:15 +00002070// * vfptrs are injected after all bases and fields have been laid out. In
2071// order to guarantee proper alignment of all fields, the vfptr injection
2072// pushes all bases and fields back by the alignment imposed by those bases
2073// and fields. This can potentially add a significant amount of padding.
2074// vfptrs are always injected at offset 0.
2075// * vbptrs are injected after all bases and fields have been laid out. In
2076// order to guarantee proper alignment of all fields, the vfptr injection
2077// pushes all bases and fields back by the alignment imposed by those bases
2078// and fields. This can potentially add a significant amount of padding.
2079// vbptrs are injected immediately after the last non-virtual base as
2080// lexiographically ordered in the code. If this site isn't pointer aligned
2081// the vbptr is placed at the next properly aligned location. Enough padding
2082// is added to guarantee a fit.
2083// * The last zero sized non-virtual base can be placed at the end of the
2084// struct (potentially aliasing another object), or may alias with the first
2085// field, even if they are of the same type.
2086// * The last zero size virtual base may be placed at the end of the struct
2087// potentially aliasing another object.
Warren Hunt049f6732013-12-06 19:54:25 +00002088// * The ABI attempts to avoid aliasing of zero sized bases by adding padding
2089// between bases or vbases with specific properties. The criteria for
2090// additional padding between two bases is that the first base is zero sized
Warren Hunt39a907b2014-04-09 21:57:24 +00002091// or ends with a zero sized subobject and the second base is zero sized or
Warren Hunt917f97f2014-04-11 00:54:15 +00002092// trails with a zero sized base or field (sharing of vfptrs can reorder the
2093// layout of the so the leading base is not always the first one declared).
2094// This rule does take into account fields that are not records, so padding
2095// will occur even if the last field is, e.g. an int. The padding added for
2096// bases is 1 byte. The padding added between vbases depends on the alignment
2097// of the object but is at least 4 bytes (in both 32 and 64 bit modes).
2098// * There is no concept of non-virtual alignment, non-virtual alignment and
2099// alignment are always identical.
2100// * There is a distinction between alignment and required alignment.
2101// __declspec(align) changes the required alignment of a struct. This
2102// alignment is _always_ obeyed, even in the presence of #pragma pack. A
2103// record inherites required alignment from all of its fields an bases.
Warren Huntf4518def2014-01-10 01:28:05 +00002104// * __declspec(align) on bitfields has the effect of changing the bitfield's
Warren Hunt917f97f2014-04-11 00:54:15 +00002105// alignment instead of its required alignment. This is the only known way
2106// to make the alignment of a struct bigger than 8. Interestingly enough
2107// this alignment is also immune to the effects of #pragma pack and can be
2108// used to create structures with large alignment under #pragma pack.
2109// However, because it does not impact required alignment, such a structure,
2110// when used as a field or base, will not be aligned if #pragma pack is
2111// still active at the time of use.
2112//
2113// Known incompatiblities:
2114// * all: #pragma pack between fields in a record
2115// * 2010 and back: If the last field in a record is a bitfield, every object
2116// laid out after the record will have extra padding inserted before it. The
2117// extra padding will have size equal to the size of the storage class of the
2118// bitfield. 0 sized bitfields don't exhibit this behavior and the extra
2119// padding can be avoided by adding a 0 sized bitfield after the non-zero-
2120// sized bitfield.
2121// * 2012 and back: In 64-bit mode, if the alignment of a record is 16 or
2122// greater due to __declspec(align()) then a second layout phase occurs after
2123// The locations of the vf and vb pointers are known. This layout phase
2124// suffers from the "last field is a bitfield" bug in 2010 and results in
2125// _every_ field getting padding put in front of it, potentially including the
2126// vfptr, leaving the vfprt at a non-zero location which results in a fault if
2127// anything tries to read the vftbl. The second layout phase also treats
2128// bitfields as seperate entities and gives them each storage rather than
2129// packing them. Additionally, because this phase appears to perform a
2130// (an unstable) sort on the members before laying them out and because merged
2131// bitfields have the same address, the bitfields end up in whatever order
2132// the sort left them in, a behavior we could never hope to replicate.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002133
2134namespace {
2135struct MicrosoftRecordLayoutBuilder {
Warren Huntd640d7d2014-01-09 00:30:56 +00002136 struct ElementInfo {
2137 CharUnits Size;
2138 CharUnits Alignment;
2139 };
Warren Hunt8f8bad72013-10-11 20:19:00 +00002140 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
2141 MicrosoftRecordLayoutBuilder(const ASTContext &Context) : Context(Context) {}
2142private:
2143 MicrosoftRecordLayoutBuilder(const MicrosoftRecordLayoutBuilder &)
2144 LLVM_DELETED_FUNCTION;
2145 void operator=(const MicrosoftRecordLayoutBuilder &) LLVM_DELETED_FUNCTION;
2146public:
Warren Hunt8f8bad72013-10-11 20:19:00 +00002147 void layout(const RecordDecl *RD);
2148 void cxxLayout(const CXXRecordDecl *RD);
2149 /// \brief Initializes size and alignment and honors some flags.
2150 void initializeLayout(const RecordDecl *RD);
2151 /// \brief Initialized C++ layout, compute alignment and virtual alignment and
Alp Tokerf6a24ce2013-12-05 16:25:25 +00002152 /// existence of vfptrs and vbptrs. Alignment is needed before the vfptr is
Warren Hunt8f8bad72013-10-11 20:19:00 +00002153 /// laid out.
2154 void initializeCXXLayout(const CXXRecordDecl *RD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002155 void layoutNonVirtualBases(const CXXRecordDecl *RD);
Warren Huntd640d7d2014-01-09 00:30:56 +00002156 void layoutNonVirtualBase(const CXXRecordDecl *BaseDecl,
2157 const ASTRecordLayout &BaseLayout,
2158 const ASTRecordLayout *&PreviousBaseLayout);
2159 void injectVFPtr(const CXXRecordDecl *RD);
2160 void injectVBPtr(const CXXRecordDecl *RD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002161 /// \brief Lays out the fields of the record. Also rounds size up to
2162 /// alignment.
2163 void layoutFields(const RecordDecl *RD);
2164 void layoutField(const FieldDecl *FD);
2165 void layoutBitField(const FieldDecl *FD);
2166 /// \brief Lays out a single zero-width bit-field in the record and handles
2167 /// special cases associated with zero-width bit-fields.
2168 void layoutZeroWidthBitField(const FieldDecl *FD);
2169 void layoutVirtualBases(const CXXRecordDecl *RD);
Warren Hunt1603e522013-12-10 01:44:39 +00002170 void finalizeLayout(const RecordDecl *RD);
Warren Huntd640d7d2014-01-09 00:30:56 +00002171 /// \brief Gets the size and alignment of a base taking pragma pack and
2172 /// __declspec(align) into account.
Warren Hunt5d9eebf2014-04-10 22:15:18 +00002173 ElementInfo getAdjustedElementInfo(const ASTRecordLayout &Layout);
Warren Huntd640d7d2014-01-09 00:30:56 +00002174 /// \brief Gets the size and alignment of a field taking pragma pack and
2175 /// __declspec(align) into account. It also updates RequiredAlignment as a
2176 /// side effect because it is most convenient to do so here.
2177 ElementInfo getAdjustedElementInfo(const FieldDecl *FD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002178 /// \brief Places a field at an offset in CharUnits.
2179 void placeFieldAtOffset(CharUnits FieldOffset) {
2180 FieldOffsets.push_back(Context.toBits(FieldOffset));
2181 }
2182 /// \brief Places a bitfield at a bit offset.
2183 void placeFieldAtBitOffset(uint64_t FieldOffset) {
2184 FieldOffsets.push_back(FieldOffset);
2185 }
2186 /// \brief Compute the set of virtual bases for which vtordisps are required.
2187 llvm::SmallPtrSet<const CXXRecordDecl *, 2>
2188 computeVtorDispSet(const CXXRecordDecl *RD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002189 const ASTContext &Context;
2190 /// \brief The size of the record being laid out.
2191 CharUnits Size;
Warren Huntf6ec7482014-02-21 01:40:35 +00002192 /// \brief The non-virtual size of the record layout.
2193 CharUnits NonVirtualSize;
2194 /// \brief The data size of the record layout.
Warren Huntd640d7d2014-01-09 00:30:56 +00002195 CharUnits DataSize;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002196 /// \brief The current alignment of the record layout.
2197 CharUnits Alignment;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002198 /// \brief The maximum allowed field alignment. This is set by #pragma pack.
2199 CharUnits MaxFieldAlignment;
Warren Hunt7b252d22013-12-06 00:01:17 +00002200 /// \brief The alignment that this record must obey. This is imposed by
2201 /// __declspec(align()) on the record itself or one of its fields or bases.
2202 CharUnits RequiredAlignment;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002203 /// \brief The size of the allocation of the currently active bitfield.
2204 /// This value isn't meaningful unless LastFieldIsNonZeroWidthBitfield
2205 /// is true.
2206 CharUnits CurrentBitfieldSize;
Warren Huntd640d7d2014-01-09 00:30:56 +00002207 /// \brief Offset to the virtual base table pointer (if one exists).
2208 CharUnits VBPtrOffset;
2209 /// \brief The size and alignment info of a pointer.
2210 ElementInfo PointerInfo;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002211 /// \brief The primary base class (if one exists).
2212 const CXXRecordDecl *PrimaryBase;
2213 /// \brief The class we share our vb-pointer with.
2214 const CXXRecordDecl *SharedVBPtrBase;
Warren Huntd640d7d2014-01-09 00:30:56 +00002215 /// \brief The collection of field offsets.
2216 SmallVector<uint64_t, 16> FieldOffsets;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002217 /// \brief Base classes and their offsets in the record.
2218 BaseOffsetsMapTy Bases;
2219 /// \brief virtual base classes and their offsets in the record.
2220 ASTRecordLayout::VBaseOffsetsMapTy VBases;
Warren Huntd640d7d2014-01-09 00:30:56 +00002221 /// \brief The number of remaining bits in our last bitfield allocation.
2222 /// This value isn't meaningful unless LastFieldIsNonZeroWidthBitfield is
2223 /// true.
2224 unsigned RemainingBitsInField;
2225 bool IsUnion : 1;
2226 /// \brief True if the last field laid out was a bitfield and was not 0
2227 /// width.
2228 bool LastFieldIsNonZeroWidthBitfield : 1;
2229 /// \brief True if the class has its own vftable pointer.
2230 bool HasOwnVFPtr : 1;
2231 /// \brief True if the class has a vbtable pointer.
2232 bool HasVBPtr : 1;
Warren Hunt39a907b2014-04-09 21:57:24 +00002233 /// \brief True if the last sub-object within the type is zero sized or the
2234 /// object itself is zero sized. This *does not* count members that are not
2235 /// records. Only used for MS-ABI.
2236 bool EndsWithZeroSizedObject : 1;
Warren Hunt049f6732013-12-06 19:54:25 +00002237 /// \brief True if this class is zero sized or first base is zero sized or
2238 /// has this property. Only used for MS-ABI.
2239 bool LeadsWithZeroSizedBase : 1;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002240};
2241} // namespace
2242
Warren Huntd640d7d2014-01-09 00:30:56 +00002243MicrosoftRecordLayoutBuilder::ElementInfo
2244MicrosoftRecordLayoutBuilder::getAdjustedElementInfo(
Warren Hunt5d9eebf2014-04-10 22:15:18 +00002245 const ASTRecordLayout &Layout) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002246 ElementInfo Info;
2247 Info.Alignment = Layout.getAlignment();
2248 // Respect pragma pack.
Warren Hunt7b252d22013-12-06 00:01:17 +00002249 if (!MaxFieldAlignment.isZero())
Warren Huntd640d7d2014-01-09 00:30:56 +00002250 Info.Alignment = std::min(Info.Alignment, MaxFieldAlignment);
2251 // Track zero-sized subobjects here where it's already available.
Warren Hunt39a907b2014-04-09 21:57:24 +00002252 EndsWithZeroSizedObject = Layout.hasZeroSizedSubObject();
Warren Huntd640d7d2014-01-09 00:30:56 +00002253 // Respect required alignment, this is necessary because we may have adjusted
Warren Hunt94258912014-01-11 01:16:40 +00002254 // the alignment in the case of pragam pack. Note that the required alignment
2255 // doesn't actually apply to the struct alignment at this point.
2256 Alignment = std::max(Alignment, Info.Alignment);
Warren Hunt5d9eebf2014-04-10 22:15:18 +00002257 RequiredAlignment = std::max(RequiredAlignment, Layout.getRequiredAlignment());
Warren Huntd640d7d2014-01-09 00:30:56 +00002258 Info.Alignment = std::max(Info.Alignment, Layout.getRequiredAlignment());
Warren Hunt5d9eebf2014-04-10 22:15:18 +00002259 Info.Size = Layout.getNonVirtualSize();
Warren Huntd640d7d2014-01-09 00:30:56 +00002260 return Info;
Warren Hunt7b252d22013-12-06 00:01:17 +00002261}
2262
Warren Huntd640d7d2014-01-09 00:30:56 +00002263MicrosoftRecordLayoutBuilder::ElementInfo
2264MicrosoftRecordLayoutBuilder::getAdjustedElementInfo(
2265 const FieldDecl *FD) {
2266 ElementInfo Info;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002267 std::tie(Info.Size, Info.Alignment) =
Reid Klecknerdb673ca2014-02-25 18:08:48 +00002268 Context.getTypeInfoInChars(FD->getType());
Warren Huntf4518def2014-01-10 01:28:05 +00002269 // Respect align attributes.
2270 CharUnits FieldRequiredAlignment =
2271 Context.toCharUnitsFromBits(FD->getMaxAlignment());
Warren Hunt049f6732013-12-06 19:54:25 +00002272 // Respect attributes applied to subobjects of the field.
Warren Hunt5d9eebf2014-04-10 22:15:18 +00002273 if (FD->isBitField())
2274 // For some reason __declspec align impacts alignment rather than required
2275 // alignment when it is applied to bitfields.
Warren Huntf4518def2014-01-10 01:28:05 +00002276 Info.Alignment = std::max(Info.Alignment, FieldRequiredAlignment);
Warren Hunt5d9eebf2014-04-10 22:15:18 +00002277 else {
2278 if (auto RT =
2279 FD->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
2280 auto const &Layout = Context.getASTRecordLayout(RT->getDecl());
2281 EndsWithZeroSizedObject = Layout.hasZeroSizedSubObject();
2282 FieldRequiredAlignment = std::max(FieldRequiredAlignment,
2283 Layout.getRequiredAlignment());
2284 }
Warren Huntf4518def2014-01-10 01:28:05 +00002285 // Capture required alignment as a side-effect.
2286 RequiredAlignment = std::max(RequiredAlignment, FieldRequiredAlignment);
2287 }
Warren Hunt5d9eebf2014-04-10 22:15:18 +00002288 // Respect pragma pack, attribute pack and declspec align
2289 if (!MaxFieldAlignment.isZero())
2290 Info.Alignment = std::min(Info.Alignment, MaxFieldAlignment);
2291 if (FD->hasAttr<PackedAttr>())
2292 Info.Alignment = CharUnits::One();
2293 Info.Alignment = std::max(Info.Alignment, FieldRequiredAlignment);
Warren Hunt94258912014-01-11 01:16:40 +00002294 // TODO: Add a Sema warning that MS ignores bitfield alignment in unions.
Warren Hunt5d9eebf2014-04-10 22:15:18 +00002295 if (!(FD->isBitField() && IsUnion))
Warren Hunt94258912014-01-11 01:16:40 +00002296 Alignment = std::max(Alignment, Info.Alignment);
Warren Huntd640d7d2014-01-09 00:30:56 +00002297 return Info;
2298}
2299
2300void MicrosoftRecordLayoutBuilder::layout(const RecordDecl *RD) {
2301 initializeLayout(RD);
2302 layoutFields(RD);
2303 DataSize = Size = Size.RoundUpToAlignment(Alignment);
David Majnemer79a1c892014-02-12 00:43:02 +00002304 RequiredAlignment = std::max(
2305 RequiredAlignment, Context.toCharUnitsFromBits(RD->getMaxAlignment()));
Warren Huntd640d7d2014-01-09 00:30:56 +00002306 finalizeLayout(RD);
2307}
2308
2309void MicrosoftRecordLayoutBuilder::cxxLayout(const CXXRecordDecl *RD) {
2310 initializeLayout(RD);
2311 initializeCXXLayout(RD);
2312 layoutNonVirtualBases(RD);
2313 layoutFields(RD);
Warren Huntc89450e2014-03-24 21:37:27 +00002314 injectVBPtr(RD);
2315 injectVFPtr(RD);
2316 if (HasOwnVFPtr || (HasVBPtr && !SharedVBPtrBase))
2317 Alignment = std::max(Alignment, PointerInfo.Alignment);
Warren Hunt5d9eebf2014-04-10 22:15:18 +00002318 auto RoundingAlignment = Alignment;
2319 if (!MaxFieldAlignment.isZero())
2320 RoundingAlignment = std::min(RoundingAlignment, MaxFieldAlignment);
2321 NonVirtualSize = Size = Size.RoundUpToAlignment(RoundingAlignment);
David Majnemer79a1c892014-02-12 00:43:02 +00002322 RequiredAlignment = std::max(
2323 RequiredAlignment, Context.toCharUnitsFromBits(RD->getMaxAlignment()));
Warren Huntd640d7d2014-01-09 00:30:56 +00002324 layoutVirtualBases(RD);
2325 finalizeLayout(RD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002326}
2327
2328void MicrosoftRecordLayoutBuilder::initializeLayout(const RecordDecl *RD) {
2329 IsUnion = RD->isUnion();
Warren Hunt8f8bad72013-10-11 20:19:00 +00002330 Size = CharUnits::Zero();
2331 Alignment = CharUnits::One();
Warren Hunt7b252d22013-12-06 00:01:17 +00002332 // In 64-bit mode we always perform an alignment step after laying out vbases.
2333 // In 32-bit mode we do not. The check to see if we need to perform alignment
2334 // checks the RequiredAlignment field and performs alignment if it isn't 0.
Warren Huntbb9c3c32014-04-10 23:23:34 +00002335 RequiredAlignment = Context.getTargetInfo().getPointerWidth(0) == 64 ?
2336 CharUnits::One() : CharUnits::Zero();
Warren Hunt8f8bad72013-10-11 20:19:00 +00002337 // Compute the maximum field alignment.
2338 MaxFieldAlignment = CharUnits::Zero();
2339 // Honor the default struct packing maximum alignment flag.
2340 if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct)
Warren Huntf4518def2014-01-10 01:28:05 +00002341 MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
2342 // Honor the packing attribute. The MS-ABI ignores pragma pack if its larger
2343 // than the pointer size.
2344 if (const MaxFieldAlignmentAttr *MFAA = RD->getAttr<MaxFieldAlignmentAttr>()){
2345 unsigned PackedAlignment = MFAA->getAlignment();
2346 if (PackedAlignment <= Context.getTargetInfo().getPointerWidth(0))
2347 MaxFieldAlignment = Context.toCharUnitsFromBits(PackedAlignment);
2348 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002349 // Packed attribute forces max field alignment to be 1.
2350 if (RD->hasAttr<PackedAttr>())
2351 MaxFieldAlignment = CharUnits::One();
2352}
2353
Warren Hunt8f8bad72013-10-11 20:19:00 +00002354void
2355MicrosoftRecordLayoutBuilder::initializeCXXLayout(const CXXRecordDecl *RD) {
Warren Hunt39a907b2014-04-09 21:57:24 +00002356 EndsWithZeroSizedObject = false;
Warren Hunt049f6732013-12-06 19:54:25 +00002357 LeadsWithZeroSizedBase = false;
Warren Huntd640d7d2014-01-09 00:30:56 +00002358 HasOwnVFPtr = false;
2359 HasVBPtr = false;
2360 PrimaryBase = 0;
2361 SharedVBPtrBase = 0;
2362 // Calculate pointer size and alignment. These are used for vfptr and vbprt
2363 // injection.
2364 PointerInfo.Size =
2365 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
2366 PointerInfo.Alignment = PointerInfo.Size;
2367 // Respect pragma pack.
2368 if (!MaxFieldAlignment.isZero())
2369 PointerInfo.Alignment = std::min(PointerInfo.Alignment, MaxFieldAlignment);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002370}
2371
2372void
2373MicrosoftRecordLayoutBuilder::layoutNonVirtualBases(const CXXRecordDecl *RD) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002374 // The MS-ABI lays out all bases that contain leading vfptrs before it lays
2375 // out any bases that do not contain vfptrs. We implement this as two passes
2376 // over the bases. This approach guarantees that the primary base is laid out
2377 // first. We use these passes to calculate some additional aggregated
2378 // information about the bases, such as reqruied alignment and the presence of
2379 // zero sized members.
2380 const ASTRecordLayout* PreviousBaseLayout = 0;
2381 // Iterate through the bases and lay out the non-virtual ones.
Aaron Ballman574705e2014-03-13 15:41:46 +00002382 for (const auto &I : RD->bases()) {
2383 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
Warren Huntd640d7d2014-01-09 00:30:56 +00002384 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
Warren Huntd640d7d2014-01-09 00:30:56 +00002385 // Mark and skip virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00002386 if (I.isVirtual()) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002387 HasVBPtr = true;
2388 continue;
2389 }
2390 // Check fo a base to share a VBPtr with.
2391 if (!SharedVBPtrBase && BaseLayout.hasVBPtr()) {
2392 SharedVBPtrBase = BaseDecl;
2393 HasVBPtr = true;
2394 }
2395 // Only lay out bases with extendable VFPtrs on the first pass.
2396 if (!BaseLayout.hasExtendableVFPtr())
2397 continue;
2398 // If we don't have a primary base, this one qualifies.
Warren Huntbadf9e02014-01-13 19:55:52 +00002399 if (!PrimaryBase) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002400 PrimaryBase = BaseDecl;
Warren Huntbadf9e02014-01-13 19:55:52 +00002401 LeadsWithZeroSizedBase = BaseLayout.leadsWithZeroSizedBase();
2402 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002403 // Lay out the base.
2404 layoutNonVirtualBase(BaseDecl, BaseLayout, PreviousBaseLayout);
2405 }
2406 // Figure out if we need a fresh VFPtr for this class.
2407 if (!PrimaryBase && RD->isDynamicClass())
2408 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
2409 e = RD->method_end();
2410 !HasOwnVFPtr && i != e; ++i)
2411 HasOwnVFPtr = i->isVirtual() && i->size_overridden_methods() == 0;
2412 // If we don't have a primary base then we have a leading object that could
2413 // itself lead with a zero-sized object, something we track.
2414 bool CheckLeadingLayout = !PrimaryBase;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002415 // Iterate through the bases and lay out the non-virtual ones.
Aaron Ballman574705e2014-03-13 15:41:46 +00002416 for (const auto &I : RD->bases()) {
2417 if (I.isVirtual())
Warren Hunt8f8bad72013-10-11 20:19:00 +00002418 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +00002419 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
Warren Huntd640d7d2014-01-09 00:30:56 +00002420 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
2421 // Only lay out bases without extendable VFPtrs on the second pass.
Warren Huntbb9c3c32014-04-10 23:23:34 +00002422 if (BaseLayout.hasExtendableVFPtr()) {
2423 VBPtrOffset = Bases[BaseDecl] + BaseLayout.getNonVirtualSize();
Warren Hunt4431fe62013-12-12 22:33:37 +00002424 continue;
Warren Huntbb9c3c32014-04-10 23:23:34 +00002425 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002426 // If this is the first layout, check to see if it leads with a zero sized
2427 // object. If it does, so do we.
2428 if (CheckLeadingLayout) {
2429 CheckLeadingLayout = false;
2430 LeadsWithZeroSizedBase = BaseLayout.leadsWithZeroSizedBase();
Warren Hunt049f6732013-12-06 19:54:25 +00002431 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002432 // Lay out the base.
2433 layoutNonVirtualBase(BaseDecl, BaseLayout, PreviousBaseLayout);
Warren Huntbb9c3c32014-04-10 23:23:34 +00002434 VBPtrOffset = Bases[BaseDecl] + BaseLayout.getNonVirtualSize();
Warren Hunt8f8bad72013-10-11 20:19:00 +00002435 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002436 // Set our VBPtroffset if we know it at this point.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002437 if (!HasVBPtr)
2438 VBPtrOffset = CharUnits::fromQuantity(-1);
Warren Hunt6eba9072014-01-14 00:31:30 +00002439 else if (SharedVBPtrBase) {
2440 const ASTRecordLayout &Layout = Context.getASTRecordLayout(SharedVBPtrBase);
2441 VBPtrOffset = Bases[SharedVBPtrBase] + Layout.getVBPtrOffset();
2442 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002443}
2444
2445void MicrosoftRecordLayoutBuilder::layoutNonVirtualBase(
2446 const CXXRecordDecl *BaseDecl,
2447 const ASTRecordLayout &BaseLayout,
2448 const ASTRecordLayout *&PreviousBaseLayout) {
Warren Huntf4518def2014-01-10 01:28:05 +00002449 // Insert padding between two bases if the left first one is zero sized or
2450 // contains a zero sized subobject and the right is zero sized or one leads
2451 // with a zero sized base.
2452 if (PreviousBaseLayout && PreviousBaseLayout->hasZeroSizedSubObject() &&
2453 BaseLayout.leadsWithZeroSizedBase())
2454 Size++;
2455 ElementInfo Info = getAdjustedElementInfo(BaseLayout);
2456 CharUnits BaseOffset = Size.RoundUpToAlignment(Info.Alignment);
2457 Bases.insert(std::make_pair(BaseDecl, BaseOffset));
Warren Huntf6ec7482014-02-21 01:40:35 +00002458 Size = BaseOffset + BaseLayout.getNonVirtualSize();
Warren Huntf4518def2014-01-10 01:28:05 +00002459 PreviousBaseLayout = &BaseLayout;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002460}
2461
2462void MicrosoftRecordLayoutBuilder::layoutFields(const RecordDecl *RD) {
2463 LastFieldIsNonZeroWidthBitfield = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002464 for (const auto *Field : RD->fields())
2465 layoutField(Field);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002466}
2467
2468void MicrosoftRecordLayoutBuilder::layoutField(const FieldDecl *FD) {
2469 if (FD->isBitField()) {
2470 layoutBitField(FD);
2471 return;
2472 }
2473 LastFieldIsNonZeroWidthBitfield = false;
Warren Huntd640d7d2014-01-09 00:30:56 +00002474 ElementInfo Info = getAdjustedElementInfo(FD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002475 if (IsUnion) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002476 placeFieldAtOffset(CharUnits::Zero());
2477 Size = std::max(Size, Info.Size);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002478 } else {
Warren Huntd640d7d2014-01-09 00:30:56 +00002479 CharUnits FieldOffset = Size.RoundUpToAlignment(Info.Alignment);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002480 placeFieldAtOffset(FieldOffset);
Warren Huntd640d7d2014-01-09 00:30:56 +00002481 Size = FieldOffset + Info.Size;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002482 }
2483}
2484
2485void MicrosoftRecordLayoutBuilder::layoutBitField(const FieldDecl *FD) {
2486 unsigned Width = FD->getBitWidthValue(Context);
2487 if (Width == 0) {
2488 layoutZeroWidthBitField(FD);
2489 return;
2490 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002491 ElementInfo Info = getAdjustedElementInfo(FD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002492 // Clamp the bitfield to a containable size for the sake of being able
2493 // to lay them out. Sema will throw an error.
Warren Huntd640d7d2014-01-09 00:30:56 +00002494 if (Width > Context.toBits(Info.Size))
2495 Width = Context.toBits(Info.Size);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002496 // Check to see if this bitfield fits into an existing allocation. Note:
2497 // MSVC refuses to pack bitfields of formal types with different sizes
2498 // into the same allocation.
2499 if (!IsUnion && LastFieldIsNonZeroWidthBitfield &&
Warren Huntd640d7d2014-01-09 00:30:56 +00002500 CurrentBitfieldSize == Info.Size && Width <= RemainingBitsInField) {
Warren Hunt8f8bad72013-10-11 20:19:00 +00002501 placeFieldAtBitOffset(Context.toBits(Size) - RemainingBitsInField);
2502 RemainingBitsInField -= Width;
2503 return;
2504 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002505 LastFieldIsNonZeroWidthBitfield = true;
Warren Huntd640d7d2014-01-09 00:30:56 +00002506 CurrentBitfieldSize = Info.Size;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002507 if (IsUnion) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002508 placeFieldAtOffset(CharUnits::Zero());
2509 Size = std::max(Size, Info.Size);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002510 } else {
2511 // Allocate a new block of memory and place the bitfield in it.
Warren Huntd640d7d2014-01-09 00:30:56 +00002512 CharUnits FieldOffset = Size.RoundUpToAlignment(Info.Alignment);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002513 placeFieldAtOffset(FieldOffset);
Warren Huntd640d7d2014-01-09 00:30:56 +00002514 Size = FieldOffset + Info.Size;
Warren Huntd640d7d2014-01-09 00:30:56 +00002515 RemainingBitsInField = Context.toBits(Info.Size) - Width;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002516 }
2517}
2518
2519void
2520MicrosoftRecordLayoutBuilder::layoutZeroWidthBitField(const FieldDecl *FD) {
2521 // Zero-width bitfields are ignored unless they follow a non-zero-width
2522 // bitfield.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002523 if (!LastFieldIsNonZeroWidthBitfield) {
2524 placeFieldAtOffset(IsUnion ? CharUnits::Zero() : Size);
2525 // TODO: Add a Sema warning that MS ignores alignment for zero
Alp Tokerd4733632013-12-05 04:47:09 +00002526 // sized bitfields that occur after zero-size bitfields or non-bitfields.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002527 return;
2528 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002529 LastFieldIsNonZeroWidthBitfield = false;
Warren Huntd640d7d2014-01-09 00:30:56 +00002530 ElementInfo Info = getAdjustedElementInfo(FD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002531 if (IsUnion) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002532 placeFieldAtOffset(CharUnits::Zero());
2533 Size = std::max(Size, Info.Size);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002534 } else {
2535 // Round up the current record size to the field's alignment boundary.
Warren Huntd640d7d2014-01-09 00:30:56 +00002536 CharUnits FieldOffset = Size.RoundUpToAlignment(Info.Alignment);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002537 placeFieldAtOffset(FieldOffset);
2538 Size = FieldOffset;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002539 }
2540}
2541
Warren Huntd640d7d2014-01-09 00:30:56 +00002542void MicrosoftRecordLayoutBuilder::injectVBPtr(const CXXRecordDecl *RD) {
Warren Hunt6eba9072014-01-14 00:31:30 +00002543 if (!HasVBPtr || SharedVBPtrBase)
Warren Huntd640d7d2014-01-09 00:30:56 +00002544 return;
Warren Huntd640d7d2014-01-09 00:30:56 +00002545 // Inject the VBPointer at the injection site.
2546 CharUnits InjectionSite = VBPtrOffset;
2547 // But before we do, make sure it's properly aligned.
2548 VBPtrOffset = VBPtrOffset.RoundUpToAlignment(PointerInfo.Alignment);
2549 // Determine where the first field should be laid out after the vbptr.
2550 CharUnits FieldStart = VBPtrOffset + PointerInfo.Size;
2551 // Make sure that the amount we push the fields back by is a multiple of the
2552 // alignment.
David Majnemer79a1c892014-02-12 00:43:02 +00002553 CharUnits Offset = (FieldStart - InjectionSite).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 by the offset
2556 // amount.
2557 Size += Offset;
2558 for (SmallVector<uint64_t, 16>::iterator i = FieldOffsets.begin(),
2559 e = FieldOffsets.end();
2560 i != e; ++i)
2561 *i += Context.toBits(Offset);
2562 for (BaseOffsetsMapTy::iterator i = Bases.begin(), e = Bases.end();
2563 i != e; ++i)
Warren Huntbb9c3c32014-04-10 23:23:34 +00002564 if (i->second >= InjectionSite)
2565 i->second += Offset;
Warren Huntd640d7d2014-01-09 00:30:56 +00002566}
2567
2568void MicrosoftRecordLayoutBuilder::injectVFPtr(const CXXRecordDecl *RD) {
2569 if (!HasOwnVFPtr)
2570 return;
2571 // Make sure that the amount we push the struct back by is a multiple of the
2572 // alignment.
David Majnemer79a1c892014-02-12 00:43:02 +00002573 CharUnits Offset = PointerInfo.Size.RoundUpToAlignment(
2574 std::max(RequiredAlignment, Alignment));
Warren Huntd640d7d2014-01-09 00:30:56 +00002575 // Increase the size of the object and push back all fields, the vbptr and all
2576 // bases by the offset amount.
2577 Size += Offset;
David Majnemer79a1c892014-02-12 00:43:02 +00002578 for (SmallVectorImpl<uint64_t>::iterator i = FieldOffsets.begin(),
Warren Huntd640d7d2014-01-09 00:30:56 +00002579 e = FieldOffsets.end();
2580 i != e; ++i)
2581 *i += Context.toBits(Offset);
2582 if (HasVBPtr)
2583 VBPtrOffset += Offset;
2584 for (BaseOffsetsMapTy::iterator i = Bases.begin(), e = Bases.end();
2585 i != e; ++i)
2586 i->second += Offset;
Warren Huntd640d7d2014-01-09 00:30:56 +00002587}
2588
Warren Hunt8f8bad72013-10-11 20:19:00 +00002589void MicrosoftRecordLayoutBuilder::layoutVirtualBases(const CXXRecordDecl *RD) {
2590 if (!HasVBPtr)
2591 return;
Warren Huntd640d7d2014-01-09 00:30:56 +00002592 // Vtordisps are always 4 bytes (even in 64-bit mode)
2593 CharUnits VtorDispSize = CharUnits::fromQuantity(4);
2594 CharUnits VtorDispAlignment = VtorDispSize;
2595 // vtordisps respect pragma pack.
2596 if (!MaxFieldAlignment.isZero())
2597 VtorDispAlignment = std::min(VtorDispAlignment, MaxFieldAlignment);
2598 // The alignment of the vtordisp is at least the required alignment of the
2599 // entire record. This requirement may be present to support vtordisp
2600 // injection.
Aaron Ballman445a9392014-03-13 16:15:17 +00002601 for (const auto &I : RD->vbases()) {
2602 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
David Majnemer79a1c892014-02-12 00:43:02 +00002603 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
2604 RequiredAlignment =
2605 std::max(RequiredAlignment, BaseLayout.getRequiredAlignment());
2606 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002607 VtorDispAlignment = std::max(VtorDispAlignment, RequiredAlignment);
2608 // Compute the vtordisp set.
2609 llvm::SmallPtrSet<const CXXRecordDecl *, 2> HasVtordispSet =
Warren Hunt8f8bad72013-10-11 20:19:00 +00002610 computeVtorDispSet(RD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002611 // Iterate through the virtual bases and lay them out.
Warren Huntd640d7d2014-01-09 00:30:56 +00002612 const ASTRecordLayout* PreviousBaseLayout = 0;
Aaron Ballman445a9392014-03-13 16:15:17 +00002613 for (const auto &I : RD->vbases()) {
2614 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
Warren Huntd640d7d2014-01-09 00:30:56 +00002615 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
2616 bool HasVtordisp = HasVtordispSet.count(BaseDecl);
Warren Huntd640d7d2014-01-09 00:30:56 +00002617 // Insert padding between two bases if the left first one is zero sized or
2618 // contains a zero sized subobject and the right is zero sized or one leads
2619 // with a zero sized base. The padding between virtual bases is 4
2620 // bytes (in both 32 and 64 bits modes) and always involves rounding up to
2621 // the required alignment, we don't know why.
2622 if (PreviousBaseLayout && PreviousBaseLayout->hasZeroSizedSubObject() &&
2623 BaseLayout.leadsWithZeroSizedBase())
2624 Size = Size.RoundUpToAlignment(VtorDispAlignment) + VtorDispSize;
2625 // Insert the vtordisp.
2626 if (HasVtordisp)
2627 Size = Size.RoundUpToAlignment(VtorDispAlignment) + VtorDispSize;
2628 // Insert the virtual base.
2629 ElementInfo Info = getAdjustedElementInfo(BaseLayout);
Warren Huntf4518def2014-01-10 01:28:05 +00002630 CharUnits BaseOffset = Size.RoundUpToAlignment(Info.Alignment);
Warren Huntd640d7d2014-01-09 00:30:56 +00002631 VBases.insert(std::make_pair(BaseDecl,
2632 ASTRecordLayout::VBaseInfo(BaseOffset, HasVtordisp)));
Warren Huntf6ec7482014-02-21 01:40:35 +00002633 Size = BaseOffset + BaseLayout.getNonVirtualSize();
Warren Huntd640d7d2014-01-09 00:30:56 +00002634 PreviousBaseLayout = &BaseLayout;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002635 }
2636}
2637
Warren Huntc3384312013-12-11 22:28:32 +00002638void MicrosoftRecordLayoutBuilder::finalizeLayout(const RecordDecl *RD) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002639 // Respect required alignment. Note that in 32-bit mode Required alignment
2640 // may be 0 nad cause size not to be updated.
Warren Huntf6ec7482014-02-21 01:40:35 +00002641 DataSize = Size;
Warren Huntd640d7d2014-01-09 00:30:56 +00002642 if (!RequiredAlignment.isZero()) {
2643 Alignment = std::max(Alignment, RequiredAlignment);
Warren Hunt5d9eebf2014-04-10 22:15:18 +00002644 auto RoundingAlignment = Alignment;
2645 if (!MaxFieldAlignment.isZero())
2646 RoundingAlignment = std::min(RoundingAlignment, MaxFieldAlignment);
2647 RoundingAlignment = std::max(RoundingAlignment, RequiredAlignment);
2648 Size = Size.RoundUpToAlignment(RoundingAlignment);
Warren Huntd640d7d2014-01-09 00:30:56 +00002649 }
2650 // Zero-sized structures have size equal to their alignment.
Warren Hunt049f6732013-12-06 19:54:25 +00002651 if (Size.isZero()) {
Warren Hunt39a907b2014-04-09 21:57:24 +00002652 EndsWithZeroSizedObject = true;
Warren Hunt049f6732013-12-06 19:54:25 +00002653 LeadsWithZeroSizedBase = true;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002654 Size = Alignment;
Warren Hunt049f6732013-12-06 19:54:25 +00002655 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002656}
2657
Warren Hunt73f43982014-04-11 22:05:28 +00002658// Recursively walks the non-virtual bases of a class and determines if any of
2659// them are in the bases with overridden methods set.
2660static bool RequiresVtordisp(
2661 const llvm::SmallPtrSet<const CXXRecordDecl *, 2> &
2662 BasesWithOverriddenMethods,
2663 const CXXRecordDecl *RD) {
2664 if (BasesWithOverriddenMethods.count(RD))
Warren Hunt8f8bad72013-10-11 20:19:00 +00002665 return true;
2666 // If any of a virtual bases non-virtual bases (recursively) requires a
2667 // vtordisp than so does this virtual base.
Aaron Ballman574705e2014-03-13 15:41:46 +00002668 for (const auto &I : RD->bases())
2669 if (!I.isVirtual() &&
Warren Hunt73f43982014-04-11 22:05:28 +00002670 RequiresVtordisp(BasesWithOverriddenMethods,
2671 I.getType()->getAsCXXRecordDecl()))
Warren Hunt8f8bad72013-10-11 20:19:00 +00002672 return true;
2673 return false;
2674}
2675
2676llvm::SmallPtrSet<const CXXRecordDecl *, 2>
2677MicrosoftRecordLayoutBuilder::computeVtorDispSet(const CXXRecordDecl *RD) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002678 llvm::SmallPtrSet<const CXXRecordDecl *, 2> HasVtordispSet;
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00002679
2680 // /vd0 or #pragma vtordisp(0): Never use vtordisps when used as a vbase.
2681 if (RD->getMSVtorDispMode() == MSVtorDispAttr::Never)
2682 return HasVtordispSet;
2683
2684 // /vd2 or #pragma vtordisp(2): Always use vtordisps for virtual bases with
2685 // vftables.
2686 if (RD->getMSVtorDispMode() == MSVtorDispAttr::ForVFTable) {
Aaron Ballman445a9392014-03-13 16:15:17 +00002687 for (const auto &I : RD->vbases()) {
2688 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00002689 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
2690 if (Layout.hasExtendableVFPtr())
2691 HasVtordispSet.insert(BaseDecl);
2692 }
2693 return HasVtordispSet;
2694 }
2695
2696 // /vd1 or #pragma vtordisp(1): Try to guess based on whether we think it's
2697 // possible for a partially constructed object with virtual base overrides to
2698 // escape a non-trivial constructor.
2699 assert(RD->getMSVtorDispMode() == MSVtorDispAttr::ForVBaseOverride);
2700
Warren Hunt8f8bad72013-10-11 20:19:00 +00002701 // If any of our bases need a vtordisp for this type, so do we. Check our
2702 // direct bases for vtordisp requirements.
Aaron Ballman574705e2014-03-13 15:41:46 +00002703 for (const auto &I : RD->bases()) {
Reid Klecknercd612ab2014-04-11 16:57:42 +00002704 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
Warren Hunt8f8bad72013-10-11 20:19:00 +00002705 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
Reid Klecknercd612ab2014-04-11 16:57:42 +00002706 for (const auto &bi : Layout.getVBaseOffsetsMap())
2707 if (bi.second.hasVtorDisp())
2708 HasVtordispSet.insert(bi.first);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002709 }
Warren Hunt73f43982014-04-11 22:05:28 +00002710 // If we do not have a user declared constructor or destructor then we don't
2711 // introduce any additional vtordisps.
2712 if (!RD->hasUserDeclaredConstructor() && !RD->hasUserDeclaredDestructor())
2713 return HasVtordispSet;
2714 // Compute a set of base classes which define methods we override. A virtual
2715 // base in this set will require a vtordisp. A virtual base that transitively
2716 // contains one of these bases as a non-virtual base will also require a
2717 // vtordisp.
2718 llvm::SmallPtrSet<const CXXMethodDecl *, 8> Work;
2719 llvm::SmallPtrSet<const CXXRecordDecl *, 2> BasesWithOverriddenMethods;
2720 // Seed the working set with our non-destructor virtual methods.
2721 for (const auto *I : RD->methods())
2722 if (I->isVirtual() && !isa<CXXDestructorDecl>(I))
2723 Work.insert(I);
2724 while (!Work.empty()) {
2725 const CXXMethodDecl *MD = *Work.begin();
2726 CXXMethodDecl::method_iterator i = MD->begin_overridden_methods(),
2727 e = MD->end_overridden_methods();
2728 // If a virtual method has no-overrides it lives in its parent's vtable.
2729 if (i == e)
2730 BasesWithOverriddenMethods.insert(MD->getParent());
2731 else
2732 Work.insert(i, e);
2733 // We've finished processing this element, remove it from the working set.
2734 Work.erase(MD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002735 }
Warren Hunt73f43982014-04-11 22:05:28 +00002736 // For each of our virtual bases, check if it is in the set of overridden
2737 // bases or if it transitively contains a non-virtual base that is.
Aaron Ballman445a9392014-03-13 16:15:17 +00002738 for (const auto &I : RD->vbases()) {
2739 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
Warren Huntd640d7d2014-01-09 00:30:56 +00002740 if (!HasVtordispSet.count(BaseDecl) &&
Warren Hunt73f43982014-04-11 22:05:28 +00002741 RequiresVtordisp(BasesWithOverriddenMethods, BaseDecl))
Warren Huntd640d7d2014-01-09 00:30:56 +00002742 HasVtordispSet.insert(BaseDecl);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002743 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002744 return HasVtordispSet;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002745}
2746
2747/// \brief Get or compute information about the layout of the specified record
2748/// (struct/union/class), which indicates its size and field position
2749/// information.
2750const ASTRecordLayout *
2751ASTContext::BuildMicrosoftASTRecordLayout(const RecordDecl *D) const {
2752 MicrosoftRecordLayoutBuilder Builder(*this);
2753 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
2754 Builder.cxxLayout(RD);
2755 return new (*this) ASTRecordLayout(
Warren Hunt7b252d22013-12-06 00:01:17 +00002756 *this, Builder.Size, Builder.Alignment, Builder.RequiredAlignment,
Warren Huntd640d7d2014-01-09 00:30:56 +00002757 Builder.HasOwnVFPtr,
2758 Builder.HasOwnVFPtr || Builder.PrimaryBase,
Warren Huntf6ec7482014-02-21 01:40:35 +00002759 Builder.VBPtrOffset, Builder.NonVirtualSize, Builder.FieldOffsets.data(),
2760 Builder.FieldOffsets.size(), Builder.NonVirtualSize,
Warren Huntd640d7d2014-01-09 00:30:56 +00002761 Builder.Alignment, CharUnits::Zero(), Builder.PrimaryBase,
Warren Hunt049f6732013-12-06 19:54:25 +00002762 false, Builder.SharedVBPtrBase,
Warren Hunt39a907b2014-04-09 21:57:24 +00002763 Builder.EndsWithZeroSizedObject, Builder.LeadsWithZeroSizedBase,
Warren Hunt049f6732013-12-06 19:54:25 +00002764 Builder.Bases, Builder.VBases);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002765 } else {
2766 Builder.layout(D);
2767 return new (*this) ASTRecordLayout(
Warren Hunt7b252d22013-12-06 00:01:17 +00002768 *this, Builder.Size, Builder.Alignment, Builder.RequiredAlignment,
2769 Builder.Size, Builder.FieldOffsets.data(), Builder.FieldOffsets.size());
Warren Hunt8f8bad72013-10-11 20:19:00 +00002770 }
2771}
2772
Anders Carlssondf291d82010-05-26 04:56:53 +00002773/// getASTRecordLayout - Get or compute information about the layout of the
2774/// specified record (struct/union/class), which indicates its size and field
2775/// position information.
Jay Foad39c79802011-01-12 09:06:06 +00002776const ASTRecordLayout &
2777ASTContext::getASTRecordLayout(const RecordDecl *D) const {
John McCall0710e552011-10-07 02:39:22 +00002778 // These asserts test different things. A record has a definition
2779 // as soon as we begin to parse the definition. That definition is
2780 // not a complete definition (which is what isDefinition() tests)
2781 // until we *finish* parsing the definition.
Sean Callanan56c19892012-02-08 00:04:52 +00002782
2783 if (D->hasExternalLexicalStorage() && !D->getDefinition())
2784 getExternalSource()->CompleteType(const_cast<RecordDecl*>(D));
2785
Anders Carlssondf291d82010-05-26 04:56:53 +00002786 D = D->getDefinition();
2787 assert(D && "Cannot get layout of forward declarations!");
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00002788 assert(!D->isInvalidDecl() && "Cannot get layout of invalid decl!");
John McCallf937c022011-10-07 06:10:15 +00002789 assert(D->isCompleteDefinition() && "Cannot layout type before complete!");
Anders Carlssondf291d82010-05-26 04:56:53 +00002790
2791 // Look up this layout, if already laid out, return what we have.
2792 // Note that we can't save a reference to the entry because this function
2793 // is recursive.
2794 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
2795 if (Entry) return *Entry;
2796
Warren Hunt8f8bad72013-10-11 20:19:00 +00002797 const ASTRecordLayout *NewEntry = 0;
Anders Carlssond2954862010-05-26 05:10:47 +00002798
Reid Kleckneraf1465c2014-02-20 23:07:29 +00002799 if (isMsLayout(D) && !D->getASTContext().getExternalSource()) {
Warren Hunt8f8bad72013-10-11 20:19:00 +00002800 NewEntry = BuildMicrosoftASTRecordLayout(D);
2801 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
Anders Carlssonc121b4e2010-05-27 00:07:01 +00002802 EmptySubobjectMap EmptySubobjects(*this, RD);
John McCall0153cd32011-11-08 04:01:03 +00002803 RecordLayoutBuilder Builder(*this, &EmptySubobjects);
2804 Builder.Layout(RD);
Anders Carlsson439edd12010-05-27 05:41:06 +00002805
John McCall5c1f1d02013-01-29 01:14:22 +00002806 // In certain situations, we are allowed to lay out objects in the
2807 // tail-padding of base classes. This is ABI-dependent.
2808 // FIXME: this should be stored in the record layout.
2809 bool skipTailPadding =
2810 mustSkipTailPadding(getTargetInfo().getCXXABI(), cast<CXXRecordDecl>(D));
Anders Carlssond2954862010-05-26 05:10:47 +00002811
2812 // FIXME: This should be done in FinalizeLayout.
Ken Dyck1b4420e2011-02-28 02:01:38 +00002813 CharUnits DataSize =
John McCall5c1f1d02013-01-29 01:14:22 +00002814 skipTailPadding ? Builder.getSize() : Builder.getDataSize();
Ken Dyck1b4420e2011-02-28 02:01:38 +00002815 CharUnits NonVirtualSize =
John McCall5c1f1d02013-01-29 01:14:22 +00002816 skipTailPadding ? DataSize : Builder.NonVirtualSize;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002817 NewEntry =
John McCall0153cd32011-11-08 04:01:03 +00002818 new (*this) ASTRecordLayout(*this, Builder.getSize(),
2819 Builder.Alignment,
Warren Hunt7b252d22013-12-06 00:01:17 +00002820 /*RequiredAlignment : used by MS-ABI)*/
2821 Builder.Alignment,
John McCalle42a3362012-05-01 08:55:32 +00002822 Builder.HasOwnVFPtr,
Warren Hunt8f8bad72013-10-11 20:19:00 +00002823 RD->isDynamicClass(),
Warren Hunt55d8e822013-10-23 23:53:07 +00002824 CharUnits::fromQuantity(-1),
Ken Dyck1b4420e2011-02-28 02:01:38 +00002825 DataSize,
John McCall0153cd32011-11-08 04:01:03 +00002826 Builder.FieldOffsets.data(),
2827 Builder.FieldOffsets.size(),
Ken Dyckaf1c83f2011-02-16 01:52:01 +00002828 NonVirtualSize,
John McCall0153cd32011-11-08 04:01:03 +00002829 Builder.NonVirtualAlignment,
Anders Carlssonc121b4e2010-05-27 00:07:01 +00002830 EmptySubobjects.SizeOfLargestEmptySubobject,
John McCall0153cd32011-11-08 04:01:03 +00002831 Builder.PrimaryBase,
2832 Builder.PrimaryBaseIsVirtual,
Warren Hunt049f6732013-12-06 19:54:25 +00002833 0, false, false,
John McCall0153cd32011-11-08 04:01:03 +00002834 Builder.Bases, Builder.VBases);
Anders Carlssond2954862010-05-26 05:10:47 +00002835 } else {
John McCall0153cd32011-11-08 04:01:03 +00002836 RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/0);
Anders Carlssond2954862010-05-26 05:10:47 +00002837 Builder.Layout(D);
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002838
Anders Carlssond2954862010-05-26 05:10:47 +00002839 NewEntry =
Ken Dyck1b4420e2011-02-28 02:01:38 +00002840 new (*this) ASTRecordLayout(*this, Builder.getSize(),
Ken Dyck4731d5b2011-02-16 02:05:21 +00002841 Builder.Alignment,
Warren Hunt7b252d22013-12-06 00:01:17 +00002842 /*RequiredAlignment : used by MS-ABI)*/
2843 Builder.Alignment,
Ken Dyck1b4420e2011-02-28 02:01:38 +00002844 Builder.getSize(),
Anders Carlssond2954862010-05-26 05:10:47 +00002845 Builder.FieldOffsets.data(),
2846 Builder.FieldOffsets.size());
2847 }
2848
Anders Carlssondf291d82010-05-26 04:56:53 +00002849 ASTRecordLayouts[D] = NewEntry;
2850
David Blaikiebbafb8a2012-03-11 07:00:24 +00002851 if (getLangOpts().DumpRecordLayouts) {
Argyrios Kyrtzidis8ade08e2013-07-12 22:30:03 +00002852 llvm::outs() << "\n*** Dumping AST Record Layout\n";
2853 DumpRecordLayout(D, llvm::outs(), getLangOpts().DumpRecordLayoutsSimple);
Anders Carlssondf291d82010-05-26 04:56:53 +00002854 }
2855
2856 return *NewEntry;
2857}
2858
John McCall6bd2a892013-01-25 22:31:03 +00002859const CXXMethodDecl *ASTContext::getCurrentKeyFunction(const CXXRecordDecl *RD) {
Reid Kleckner5d7f2982013-05-29 16:18:30 +00002860 if (!getTargetInfo().getCXXABI().hasKeyFunctions())
2861 return 0;
2862
John McCall6bd2a892013-01-25 22:31:03 +00002863 assert(RD->getDefinition() && "Cannot get key function for forward decl!");
Anders Carlssondf291d82010-05-26 04:56:53 +00002864 RD = cast<CXXRecordDecl>(RD->getDefinition());
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002865
Richard Smith676c4042013-08-29 23:59:27 +00002866 LazyDeclPtr &Entry = KeyFunctions[RD];
2867 if (!Entry)
2868 Entry = const_cast<CXXMethodDecl*>(computeKeyFunction(*this, RD));
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002869
Richard Smith676c4042013-08-29 23:59:27 +00002870 return cast_or_null<CXXMethodDecl>(Entry.get(getExternalSource()));
John McCall6bd2a892013-01-25 22:31:03 +00002871}
2872
Richard Smith676c4042013-08-29 23:59:27 +00002873void ASTContext::setNonKeyFunction(const CXXMethodDecl *Method) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002874 assert(Method == Method->getFirstDecl() &&
John McCall6bd2a892013-01-25 22:31:03 +00002875 "not working with method declaration from class definition");
2876
2877 // Look up the cache entry. Since we're working with the first
2878 // declaration, its parent must be the class definition, which is
2879 // the correct key for the KeyFunctions hash.
Richard Smith676c4042013-08-29 23:59:27 +00002880 llvm::DenseMap<const CXXRecordDecl*, LazyDeclPtr>::iterator
2881 I = KeyFunctions.find(Method->getParent());
John McCall6bd2a892013-01-25 22:31:03 +00002882
2883 // If it's not cached, there's nothing to do.
Richard Smith676c4042013-08-29 23:59:27 +00002884 if (I == KeyFunctions.end()) return;
John McCall6bd2a892013-01-25 22:31:03 +00002885
2886 // If it is cached, check whether it's the target method, and if so,
2887 // remove it from the cache.
Richard Smith676c4042013-08-29 23:59:27 +00002888 if (I->second.get(getExternalSource()) == Method) {
John McCall6bd2a892013-01-25 22:31:03 +00002889 // FIXME: remember that we did this for module / chained PCH state?
Richard Smith676c4042013-08-29 23:59:27 +00002890 KeyFunctions.erase(I);
John McCall6bd2a892013-01-25 22:31:03 +00002891 }
Anders Carlssondf291d82010-05-26 04:56:53 +00002892}
2893
Richard Smithdafff942012-01-14 04:30:29 +00002894static uint64_t getFieldOffset(const ASTContext &C, const FieldDecl *FD) {
2895 const ASTRecordLayout &Layout = C.getASTRecordLayout(FD->getParent());
2896 return Layout.getFieldOffset(FD->getFieldIndex());
2897}
2898
2899uint64_t ASTContext::getFieldOffset(const ValueDecl *VD) const {
2900 uint64_t OffsetInBits;
2901 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
2902 OffsetInBits = ::getFieldOffset(*this, FD);
2903 } else {
2904 const IndirectFieldDecl *IFD = cast<IndirectFieldDecl>(VD);
2905
2906 OffsetInBits = 0;
Aaron Ballman29c94602014-03-07 18:36:15 +00002907 for (const auto *CI : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002908 OffsetInBits += ::getFieldOffset(*this, cast<FieldDecl>(CI));
Richard Smithdafff942012-01-14 04:30:29 +00002909 }
2910
2911 return OffsetInBits;
2912}
2913
Eric Christopher8a39a012011-10-05 06:00:51 +00002914/// getObjCLayout - Get or compute information about the layout of the
2915/// given interface.
Anders Carlssondf291d82010-05-26 04:56:53 +00002916///
2917/// \param Impl - If given, also include the layout of the interface's
2918/// implementation. This may differ by including synthesized ivars.
2919const ASTRecordLayout &
2920ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
Jay Foad39c79802011-01-12 09:06:06 +00002921 const ObjCImplementationDecl *Impl) const {
Douglas Gregor64d92572011-12-20 15:50:13 +00002922 // Retrieve the definition
Sean Callanand9a909c2012-03-15 16:33:08 +00002923 if (D->hasExternalLexicalStorage() && !D->getDefinition())
2924 getExternalSource()->CompleteType(const_cast<ObjCInterfaceDecl*>(D));
Douglas Gregor64d92572011-12-20 15:50:13 +00002925 D = D->getDefinition();
2926 assert(D && D->isThisDeclarationADefinition() && "Invalid interface decl!");
Anders Carlssondf291d82010-05-26 04:56:53 +00002927
2928 // Look up this layout, if already laid out, return what we have.
Roman Divackye6377112012-09-06 15:59:27 +00002929 const ObjCContainerDecl *Key =
2930 Impl ? (const ObjCContainerDecl*) Impl : (const ObjCContainerDecl*) D;
Anders Carlssondf291d82010-05-26 04:56:53 +00002931 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
2932 return *Entry;
2933
2934 // Add in synthesized ivar count if laying out an implementation.
2935 if (Impl) {
2936 unsigned SynthCount = CountNonClassIvars(D);
2937 // If there aren't any sythesized ivars then reuse the interface
2938 // entry. Note we can't cache this because we simply free all
2939 // entries later; however we shouldn't look up implementations
2940 // frequently.
2941 if (SynthCount == 0)
2942 return getObjCLayout(D, 0);
2943 }
2944
John McCall0153cd32011-11-08 04:01:03 +00002945 RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/0);
Anders Carlsson6ed3a9a2010-05-26 05:04:25 +00002946 Builder.Layout(D);
2947
Anders Carlssondf291d82010-05-26 04:56:53 +00002948 const ASTRecordLayout *NewEntry =
Ken Dyck1b4420e2011-02-28 02:01:38 +00002949 new (*this) ASTRecordLayout(*this, Builder.getSize(),
Ken Dyck4731d5b2011-02-16 02:05:21 +00002950 Builder.Alignment,
Warren Hunt7b252d22013-12-06 00:01:17 +00002951 /*RequiredAlignment : used by MS-ABI)*/
2952 Builder.Alignment,
Ken Dyck1b4420e2011-02-28 02:01:38 +00002953 Builder.getDataSize(),
Anders Carlsson6ed3a9a2010-05-26 05:04:25 +00002954 Builder.FieldOffsets.data(),
2955 Builder.FieldOffsets.size());
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002956
Anders Carlssondf291d82010-05-26 04:56:53 +00002957 ObjCLayouts[Key] = NewEntry;
2958
2959 return *NewEntry;
2960}
2961
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002962static void PrintOffset(raw_ostream &OS,
Anders Carlsson3f018712010-10-31 23:45:59 +00002963 CharUnits Offset, unsigned IndentLevel) {
Benjamin Kramer96ad7172011-11-05 09:02:52 +00002964 OS << llvm::format("%4" PRId64 " | ", (int64_t)Offset.getQuantity());
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002965 OS.indent(IndentLevel * 2);
2966}
2967
Eli Benderskyf6f93ee2012-12-08 00:07:24 +00002968static void PrintIndentNoOffset(raw_ostream &OS, unsigned IndentLevel) {
2969 OS << " | ";
2970 OS.indent(IndentLevel * 2);
2971}
2972
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002973static void DumpCXXRecordLayout(raw_ostream &OS,
Jay Foad39c79802011-01-12 09:06:06 +00002974 const CXXRecordDecl *RD, const ASTContext &C,
Anders Carlsson3f018712010-10-31 23:45:59 +00002975 CharUnits Offset,
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002976 unsigned IndentLevel,
2977 const char* Description,
2978 bool IncludeVirtualBases) {
Anders Carlsson3f018712010-10-31 23:45:59 +00002979 const ASTRecordLayout &Layout = C.getASTRecordLayout(RD);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002980
2981 PrintOffset(OS, Offset, IndentLevel);
Dan Gohman145f3f12010-04-19 16:39:44 +00002982 OS << C.getTypeDeclType(const_cast<CXXRecordDecl *>(RD)).getAsString();
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002983 if (Description)
2984 OS << ' ' << Description;
2985 if (RD->isEmpty())
2986 OS << " (empty)";
2987 OS << '\n';
2988
2989 IndentLevel++;
2990
Anders Carlsson3f018712010-10-31 23:45:59 +00002991 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
Warren Hunt8f8bad72013-10-11 20:19:00 +00002992 bool HasOwnVFPtr = Layout.hasOwnVFPtr();
2993 bool HasOwnVBPtr = Layout.hasOwnVBPtr();
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002994
2995 // Vtable pointer.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002996 if (RD->isDynamicClass() && !PrimaryBase && !isMsLayout(RD)) {
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002997 PrintOffset(OS, Offset, IndentLevel);
Benjamin Kramerb89514a2011-10-14 18:45:37 +00002998 OS << '(' << *RD << " vtable pointer)\n";
Warren Hunt8f8bad72013-10-11 20:19:00 +00002999 } else if (HasOwnVFPtr) {
3000 PrintOffset(OS, Offset, IndentLevel);
3001 // vfptr (for Microsoft C++ ABI)
3002 OS << '(' << *RD << " vftable pointer)\n";
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003003 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00003004
Reid Klecknerad59deb2014-02-28 01:03:09 +00003005 // Collect nvbases.
3006 SmallVector<const CXXRecordDecl *, 4> Bases;
Aaron Ballman574705e2014-03-13 15:41:46 +00003007 for (const auto &I : RD->bases()) {
3008 assert(!I.getType()->isDependentType() &&
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003009 "Cannot layout class with dependent bases.");
Aaron Ballman574705e2014-03-13 15:41:46 +00003010 if (!I.isVirtual())
3011 Bases.push_back(I.getType()->getAsCXXRecordDecl());
Reid Klecknerad59deb2014-02-28 01:03:09 +00003012 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003013
Reid Klecknerad59deb2014-02-28 01:03:09 +00003014 // Sort nvbases by offset.
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00003015 std::stable_sort(Bases.begin(), Bases.end(),
3016 [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
3017 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
3018 });
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003019
Reid Klecknerad59deb2014-02-28 01:03:09 +00003020 // Dump (non-virtual) bases
3021 for (SmallVectorImpl<const CXXRecordDecl *>::iterator I = Bases.begin(),
3022 E = Bases.end();
3023 I != E; ++I) {
3024 const CXXRecordDecl *Base = *I;
Anders Carlsson3f018712010-10-31 23:45:59 +00003025 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003026 DumpCXXRecordLayout(OS, Base, C, BaseOffset, IndentLevel,
3027 Base == PrimaryBase ? "(primary base)" : "(base)",
3028 /*IncludeVirtualBases=*/false);
3029 }
Eli Friedman43114f92011-10-21 22:49:56 +00003030
Warren Hunt8f8bad72013-10-11 20:19:00 +00003031 // vbptr (for Microsoft C++ ABI)
3032 if (HasOwnVBPtr) {
Eli Friedman84d2d3a2011-09-27 19:12:27 +00003033 PrintOffset(OS, Offset + Layout.getVBPtrOffset(), IndentLevel);
Benjamin Kramerb89514a2011-10-14 18:45:37 +00003034 OS << '(' << *RD << " vbtable pointer)\n";
Eli Friedman84d2d3a2011-09-27 19:12:27 +00003035 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003036
3037 // Dump fields.
3038 uint64_t FieldNo = 0;
3039 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
3040 E = RD->field_end(); I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +00003041 const FieldDecl &Field = **I;
Anders Carlsson3f018712010-10-31 23:45:59 +00003042 CharUnits FieldOffset = Offset +
Ken Dyck86a7fcc2011-01-18 01:56:16 +00003043 C.toCharUnitsFromBits(Layout.getFieldOffset(FieldNo));
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003044
Reid Klecknercd612ab2014-04-11 16:57:42 +00003045 if (const CXXRecordDecl *D = Field.getType()->getAsCXXRecordDecl()) {
3046 DumpCXXRecordLayout(OS, D, C, FieldOffset, IndentLevel,
3047 Field.getName().data(),
3048 /*IncludeVirtualBases=*/true);
3049 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003050 }
3051
3052 PrintOffset(OS, FieldOffset, IndentLevel);
David Blaikie2d7c57e2012-04-30 02:36:29 +00003053 OS << Field.getType().getAsString() << ' ' << Field << '\n';
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003054 }
3055
3056 if (!IncludeVirtualBases)
3057 return;
3058
3059 // Dump virtual bases.
John McCalle42a3362012-05-01 08:55:32 +00003060 const ASTRecordLayout::VBaseOffsetsMapTy &vtordisps =
3061 Layout.getVBaseOffsetsMap();
Aaron Ballman445a9392014-03-13 16:15:17 +00003062 for (const auto &I : RD->vbases()) {
3063 assert(I.isVirtual() && "Found non-virtual class!");
Reid Klecknercd612ab2014-04-11 16:57:42 +00003064 const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl();
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003065
Anders Carlsson3f018712010-10-31 23:45:59 +00003066 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBase);
John McCalle42a3362012-05-01 08:55:32 +00003067
3068 if (vtordisps.find(VBase)->second.hasVtorDisp()) {
3069 PrintOffset(OS, VBaseOffset - CharUnits::fromQuantity(4), IndentLevel);
3070 OS << "(vtordisp for vbase " << *VBase << ")\n";
3071 }
3072
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003073 DumpCXXRecordLayout(OS, VBase, C, VBaseOffset, IndentLevel,
3074 VBase == PrimaryBase ?
3075 "(primary virtual base)" : "(virtual base)",
3076 /*IncludeVirtualBases=*/false);
3077 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003078
Eli Benderskyf6f93ee2012-12-08 00:07:24 +00003079 PrintIndentNoOffset(OS, IndentLevel - 1);
3080 OS << "[sizeof=" << Layout.getSize().getQuantity();
Warren Hunt8f8bad72013-10-11 20:19:00 +00003081 if (!isMsLayout(RD))
3082 OS << ", dsize=" << Layout.getDataSize().getQuantity();
Ken Dyck7ad11e72011-02-15 02:32:40 +00003083 OS << ", align=" << Layout.getAlignment().getQuantity() << '\n';
Eli Benderskyf6f93ee2012-12-08 00:07:24 +00003084
3085 PrintIndentNoOffset(OS, IndentLevel - 1);
3086 OS << " nvsize=" << Layout.getNonVirtualSize().getQuantity();
Warren Huntd640d7d2014-01-09 00:30:56 +00003087 OS << ", nvalign=" << Layout.getNonVirtualAlignment().getQuantity() << "]\n";
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003088}
Daniel Dunbarccabe482010-04-19 20:44:53 +00003089
3090void ASTContext::DumpRecordLayout(const RecordDecl *RD,
Douglas Gregore9fc3772012-01-26 07:55:45 +00003091 raw_ostream &OS,
3092 bool Simple) const {
Daniel Dunbarccabe482010-04-19 20:44:53 +00003093 const ASTRecordLayout &Info = getASTRecordLayout(RD);
3094
3095 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Douglas Gregore9fc3772012-01-26 07:55:45 +00003096 if (!Simple)
3097 return DumpCXXRecordLayout(OS, CXXRD, *this, CharUnits(), 0, 0,
3098 /*IncludeVirtualBases=*/true);
Daniel Dunbarccabe482010-04-19 20:44:53 +00003099
3100 OS << "Type: " << getTypeDeclType(RD).getAsString() << "\n";
Douglas Gregore9fc3772012-01-26 07:55:45 +00003101 if (!Simple) {
3102 OS << "Record: ";
3103 RD->dump();
3104 }
Daniel Dunbarccabe482010-04-19 20:44:53 +00003105 OS << "\nLayout: ";
3106 OS << "<ASTRecordLayout\n";
Ken Dyckb0fcc592011-02-11 01:54:29 +00003107 OS << " Size:" << toBits(Info.getSize()) << "\n";
Warren Hunt8f8bad72013-10-11 20:19:00 +00003108 if (!isMsLayout(RD))
3109 OS << " DataSize:" << toBits(Info.getDataSize()) << "\n";
Ken Dyck7ad11e72011-02-15 02:32:40 +00003110 OS << " Alignment:" << toBits(Info.getAlignment()) << "\n";
Daniel Dunbarccabe482010-04-19 20:44:53 +00003111 OS << " FieldOffsets: [";
3112 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i) {
3113 if (i) OS << ", ";
3114 OS << Info.getFieldOffset(i);
3115 }
3116 OS << "]>\n";
3117}