blob: 6a7d5144c8c676970b9ba451dc6b42be67160458 [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"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "llvm/Support/Format.h"
22#include "llvm/Support/MathExtras.h"
Anders Carlsson79474332009-07-18 20:20:21 +000023
24using namespace clang;
25
Benjamin Kramerc7656cd2010-05-26 09:58:31 +000026namespace {
Anders Carlssonf58de112010-05-26 15:32:58 +000027
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000028/// BaseSubobjectInfo - Represents a single base subobject in a complete class.
29/// For a class hierarchy like
30///
31/// class A { };
32/// class B : A { };
33/// class C : A, B { };
34///
35/// The BaseSubobjectInfo graph for C will have three BaseSubobjectInfo
36/// instances, one for B and two for A.
37///
38/// If a base is virtual, it will only have one BaseSubobjectInfo allocated.
39struct BaseSubobjectInfo {
40 /// Class - The class for this base info.
Anders Carlsson056818f2010-05-28 21:13:31 +000041 const CXXRecordDecl *Class;
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000042
43 /// IsVirtual - Whether the BaseInfo represents a virtual base or not.
Anders Carlsson056818f2010-05-28 21:13:31 +000044 bool IsVirtual;
45
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000046 /// Bases - Information about the base subobjects.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000047 SmallVector<BaseSubobjectInfo*, 4> Bases;
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000048
Anders Carlssone3c24c72010-05-29 17:35:14 +000049 /// PrimaryVirtualBaseInfo - Holds the base info for the primary virtual base
50 /// of this base info (if one exists).
51 BaseSubobjectInfo *PrimaryVirtualBaseInfo;
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000052
53 // FIXME: Document.
54 const BaseSubobjectInfo *Derived;
Anders Carlsson056818f2010-05-28 21:13:31 +000055};
56
Reid Kleckner8b6d0342015-02-25 19:17:45 +000057/// \brief Externally provided layout. Typically used when the AST source, such
58/// as DWARF, lacks all the information that was available at compile time, such
59/// as alignment attributes on fields and pragmas in effect.
60struct ExternalLayout {
61 ExternalLayout() : Size(0), Align(0) {}
62
63 /// \brief Overall record size in bits.
64 uint64_t Size;
65
66 /// \brief Overall record alignment in bits.
67 uint64_t Align;
68
69 /// \brief Record field offsets in bits.
70 llvm::DenseMap<const FieldDecl *, uint64_t> FieldOffsets;
71
72 /// \brief Direct, non-virtual base offsets.
73 llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsets;
74
75 /// \brief Virtual base offsets.
76 llvm::DenseMap<const CXXRecordDecl *, CharUnits> VirtualBaseOffsets;
77
78 /// Get the offset of the given field. The external source must provide
79 /// entries for all fields in the record.
80 uint64_t getExternalFieldOffset(const FieldDecl *FD) {
81 assert(FieldOffsets.count(FD) &&
82 "Field does not have an external offset");
83 return FieldOffsets[FD];
84 }
85
86 bool getExternalNVBaseOffset(const CXXRecordDecl *RD, CharUnits &BaseOffset) {
87 auto Known = BaseOffsets.find(RD);
88 if (Known == BaseOffsets.end())
89 return false;
90 BaseOffset = Known->second;
91 return true;
92 }
93
94 bool getExternalVBaseOffset(const CXXRecordDecl *RD, CharUnits &BaseOffset) {
95 auto Known = VirtualBaseOffsets.find(RD);
96 if (Known == VirtualBaseOffsets.end())
97 return false;
98 BaseOffset = Known->second;
99 return true;
100 }
101};
102
Anders Carlssonf58de112010-05-26 15:32:58 +0000103/// EmptySubobjectMap - Keeps track of which empty subobjects exist at different
104/// offsets while laying out a C++ class.
105class EmptySubobjectMap {
Jay Foad39c79802011-01-12 09:06:06 +0000106 const ASTContext &Context;
Anders Carlsson233e2722010-10-31 21:54:55 +0000107 uint64_t CharWidth;
108
Anders Carlssonf58de112010-05-26 15:32:58 +0000109 /// Class - The class whose empty entries we're keeping track of.
110 const CXXRecordDecl *Class;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000111
Anders Carlsson439edd12010-05-27 05:41:06 +0000112 /// EmptyClassOffsets - A map from offsets to empty record decls.
Benjamin Kramer834652a2014-05-03 18:44:26 +0000113 typedef llvm::TinyPtrVector<const CXXRecordDecl *> ClassVectorTy;
Anders Carlssonf8f756d2010-10-31 21:22:43 +0000114 typedef llvm::DenseMap<CharUnits, ClassVectorTy> EmptyClassOffsetsMapTy;
Anders Carlsson439edd12010-05-27 05:41:06 +0000115 EmptyClassOffsetsMapTy EmptyClassOffsets;
116
Anders Carlssoncc5de092010-06-08 15:56:03 +0000117 /// MaxEmptyClassOffset - The highest offset known to contain an empty
118 /// base subobject.
Anders Carlsson725190f2010-10-31 21:39:24 +0000119 CharUnits MaxEmptyClassOffset;
Anders Carlssoncc5de092010-06-08 15:56:03 +0000120
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000121 /// ComputeEmptySubobjectSizes - Compute the size of the largest base or
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000122 /// member subobject that is empty.
123 void ComputeEmptySubobjectSizes();
Anders Carlsson439edd12010-05-27 05:41:06 +0000124
Anders Carlsson725190f2010-10-31 21:39:24 +0000125 void AddSubobjectAtOffset(const CXXRecordDecl *RD, CharUnits Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000126
Anders Carlssona7f3cdb2010-05-28 21:24:37 +0000127 void UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000128 CharUnits Offset, bool PlacingEmptyBase);
Anders Carlsson439edd12010-05-27 05:41:06 +0000129
Anders Carlssondb319762010-05-27 18:20:57 +0000130 void UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD,
131 const CXXRecordDecl *Class,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000132 CharUnits Offset);
133 void UpdateEmptyFieldSubobjects(const FieldDecl *FD, CharUnits Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000134
Anders Carlssoncc5de092010-06-08 15:56:03 +0000135 /// AnyEmptySubobjectsBeyondOffset - Returns whether there are any empty
136 /// subobjects beyond the given offset.
Anders Carlsson725190f2010-10-31 21:39:24 +0000137 bool AnyEmptySubobjectsBeyondOffset(CharUnits Offset) const {
Anders Carlssoncc5de092010-06-08 15:56:03 +0000138 return Offset <= MaxEmptyClassOffset;
139 }
140
Anders Carlsson233e2722010-10-31 21:54:55 +0000141 CharUnits
142 getFieldOffset(const ASTRecordLayout &Layout, unsigned FieldNo) const {
143 uint64_t FieldOffset = Layout.getFieldOffset(FieldNo);
144 assert(FieldOffset % CharWidth == 0 &&
145 "Field offset not at char boundary!");
146
Ken Dyck7c4026b2011-01-24 01:28:50 +0000147 return Context.toCharUnitsFromBits(FieldOffset);
Anders Carlssonf8f756d2010-10-31 21:22:43 +0000148 }
Anders Carlssonf8f756d2010-10-31 21:22:43 +0000149
Charles Davisc2c576a2010-08-19 00:55:19 +0000150protected:
Anders Carlsson725190f2010-10-31 21:39:24 +0000151 bool CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD,
152 CharUnits Offset) const;
Charles Davisc2c576a2010-08-19 00:55:19 +0000153
154 bool CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000155 CharUnits Offset);
Charles Davisc2c576a2010-08-19 00:55:19 +0000156
157 bool CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD,
158 const CXXRecordDecl *Class,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000159 CharUnits Offset) const;
Charles Davisc2c576a2010-08-19 00:55:19 +0000160 bool CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD,
Anders Carlsson233e2722010-10-31 21:54:55 +0000161 CharUnits Offset) const;
Charles Davisc2c576a2010-08-19 00:55:19 +0000162
Anders Carlssonf58de112010-05-26 15:32:58 +0000163public:
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000164 /// This holds the size of the largest empty subobject (either a base
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000165 /// or a member). Will be zero if the record being built doesn't contain
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000166 /// any empty classes.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000167 CharUnits SizeOfLargestEmptySubobject;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000168
Jay Foad39c79802011-01-12 09:06:06 +0000169 EmptySubobjectMap(const ASTContext &Context, const CXXRecordDecl *Class)
Anders Carlsson28466ab2010-10-31 22:13:23 +0000170 : Context(Context), CharWidth(Context.getCharWidth()), Class(Class) {
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000171 ComputeEmptySubobjectSizes();
172 }
173
174 /// CanPlaceBaseAtOffset - Return whether the given base class can be placed
175 /// at the given offset.
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000176 /// Returns false if placing the record will result in two components
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000177 /// (direct or indirect) of the same type having the same offset.
Anders Carlssoncc5de092010-06-08 15:56:03 +0000178 bool CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000179 CharUnits Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000180
181 /// CanPlaceFieldAtOffset - Return whether a field can be placed at the given
182 /// offset.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000183 bool CanPlaceFieldAtOffset(const FieldDecl *FD, CharUnits Offset);
Anders Carlssonf58de112010-05-26 15:32:58 +0000184};
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000185
186void EmptySubobjectMap::ComputeEmptySubobjectSizes() {
187 // Check the bases.
David Majnemerc964b4b2014-07-16 06:04:00 +0000188 for (const CXXBaseSpecifier &Base : Class->bases()) {
189 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000190
Anders Carlsson28466ab2010-10-31 22:13:23 +0000191 CharUnits EmptySize;
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000192 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
193 if (BaseDecl->isEmpty()) {
194 // If the class decl is empty, get its size.
Ken Dyckc8ae5502011-02-09 01:59:34 +0000195 EmptySize = Layout.getSize();
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000196 } else {
197 // Otherwise, we get the largest empty subobject for the decl.
198 EmptySize = Layout.getSizeOfLargestEmptySubobject();
199 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000200
Anders Carlsson28466ab2010-10-31 22:13:23 +0000201 if (EmptySize > SizeOfLargestEmptySubobject)
202 SizeOfLargestEmptySubobject = EmptySize;
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000203 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000204
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000205 // Check the fields.
David Majnemerc964b4b2014-07-16 06:04:00 +0000206 for (const FieldDecl *FD : Class->fields()) {
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000207 const RecordType *RT =
David Majnemerc964b4b2014-07-16 06:04:00 +0000208 Context.getBaseElementType(FD->getType())->getAs<RecordType>();
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000209
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000210 // We only care about record types.
211 if (!RT)
212 continue;
213
Anders Carlsson28466ab2010-10-31 22:13:23 +0000214 CharUnits EmptySize;
Reid Klecknercd612ab2014-04-11 16:57:42 +0000215 const CXXRecordDecl *MemberDecl = RT->getAsCXXRecordDecl();
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000216 const ASTRecordLayout &Layout = Context.getASTRecordLayout(MemberDecl);
217 if (MemberDecl->isEmpty()) {
218 // If the class decl is empty, get its size.
Ken Dyckc8ae5502011-02-09 01:59:34 +0000219 EmptySize = Layout.getSize();
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000220 } else {
221 // Otherwise, we get the largest empty subobject for the decl.
222 EmptySize = Layout.getSizeOfLargestEmptySubobject();
223 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000224
Anders Carlsson28466ab2010-10-31 22:13:23 +0000225 if (EmptySize > SizeOfLargestEmptySubobject)
226 SizeOfLargestEmptySubobject = EmptySize;
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000227 }
228}
229
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000230bool
Anders Carlssondb319762010-05-27 18:20:57 +0000231EmptySubobjectMap::CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD,
Anders Carlsson725190f2010-10-31 21:39:24 +0000232 CharUnits Offset) const {
Anders Carlssondb319762010-05-27 18:20:57 +0000233 // We only need to check empty bases.
234 if (!RD->isEmpty())
235 return true;
236
Anders Carlsson725190f2010-10-31 21:39:24 +0000237 EmptyClassOffsetsMapTy::const_iterator I = EmptyClassOffsets.find(Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000238 if (I == EmptyClassOffsets.end())
239 return true;
David Majnemerc964b4b2014-07-16 06:04:00 +0000240
241 const ClassVectorTy &Classes = I->second;
Anders Carlssondb319762010-05-27 18:20:57 +0000242 if (std::find(Classes.begin(), Classes.end(), RD) == Classes.end())
243 return true;
244
245 // There is already an empty class of the same type at this offset.
246 return false;
247}
248
249void EmptySubobjectMap::AddSubobjectAtOffset(const CXXRecordDecl *RD,
Anders Carlsson725190f2010-10-31 21:39:24 +0000250 CharUnits Offset) {
Anders Carlssondb319762010-05-27 18:20:57 +0000251 // We only care about empty bases.
252 if (!RD->isEmpty())
253 return;
254
Reid Kleckner369f3162013-05-14 20:30:42 +0000255 // If we have empty structures inside a union, we can assign both
Rafael Espindola7bcde192010-12-29 23:02:58 +0000256 // the same offset. Just avoid pushing them twice in the list.
David Majnemerc964b4b2014-07-16 06:04:00 +0000257 ClassVectorTy &Classes = EmptyClassOffsets[Offset];
Rafael Espindola7bcde192010-12-29 23:02:58 +0000258 if (std::find(Classes.begin(), Classes.end(), RD) != Classes.end())
259 return;
260
Anders Carlssondb319762010-05-27 18:20:57 +0000261 Classes.push_back(RD);
Anders Carlssoncc5de092010-06-08 15:56:03 +0000262
263 // Update the empty class offset.
Anders Carlsson725190f2010-10-31 21:39:24 +0000264 if (Offset > MaxEmptyClassOffset)
265 MaxEmptyClassOffset = Offset;
Anders Carlssondb319762010-05-27 18:20:57 +0000266}
267
268bool
Anders Carlsson28466ab2010-10-31 22:13:23 +0000269EmptySubobjectMap::CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info,
270 CharUnits Offset) {
Anders Carlsson45c1d282010-06-08 16:20:35 +0000271 // We don't have to keep looking past the maximum offset that's known to
272 // contain an empty class.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000273 if (!AnyEmptySubobjectsBeyondOffset(Offset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000274 return true;
275
Anders Carlsson28466ab2010-10-31 22:13:23 +0000276 if (!CanPlaceSubobjectAtOffset(Info->Class, Offset))
Anders Carlssondb319762010-05-27 18:20:57 +0000277 return false;
278
Anders Carlsson439edd12010-05-27 05:41:06 +0000279 // Traverse all non-virtual bases.
Anders Carlssona7774a62010-05-29 21:10:24 +0000280 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
David Majnemerc964b4b2014-07-16 06:04:00 +0000281 for (const BaseSubobjectInfo *Base : Info->Bases) {
Anders Carlsson439edd12010-05-27 05:41:06 +0000282 if (Base->IsVirtual)
283 continue;
284
Anders Carlsson0a14ee92010-11-01 00:21:58 +0000285 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
Anders Carlsson439edd12010-05-27 05:41:06 +0000286
287 if (!CanPlaceBaseSubobjectAtOffset(Base, BaseOffset))
288 return false;
289 }
290
Anders Carlssone3c24c72010-05-29 17:35:14 +0000291 if (Info->PrimaryVirtualBaseInfo) {
292 BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
Anders Carlsson439edd12010-05-27 05:41:06 +0000293
294 if (Info == PrimaryVirtualBaseInfo->Derived) {
295 if (!CanPlaceBaseSubobjectAtOffset(PrimaryVirtualBaseInfo, Offset))
296 return false;
297 }
298 }
299
Anders Carlssondb319762010-05-27 18:20:57 +0000300 // Traverse all member variables.
301 unsigned FieldNo = 0;
302 for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(),
303 E = Info->Class->field_end(); I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +0000304 if (I->isBitField())
Anders Carlsson233e2722010-10-31 21:54:55 +0000305 continue;
David Majnemerc964b4b2014-07-16 06:04:00 +0000306
Anders Carlsson28466ab2010-10-31 22:13:23 +0000307 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
David Blaikie40ed2972012-06-06 20:45:41 +0000308 if (!CanPlaceFieldSubobjectAtOffset(*I, FieldOffset))
Anders Carlssondb319762010-05-27 18:20:57 +0000309 return false;
310 }
David Majnemerc964b4b2014-07-16 06:04:00 +0000311
Anders Carlsson439edd12010-05-27 05:41:06 +0000312 return true;
313}
314
Anders Carlssona7f3cdb2010-05-28 21:24:37 +0000315void EmptySubobjectMap::UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000316 CharUnits Offset,
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000317 bool PlacingEmptyBase) {
318 if (!PlacingEmptyBase && Offset >= SizeOfLargestEmptySubobject) {
319 // We know that the only empty subobjects that can conflict with empty
320 // subobject of non-empty bases, are empty bases that can be placed at
321 // offset zero. Because of this, we only need to keep track of empty base
322 // subobjects with offsets less than the size of the largest empty
323 // subobject for our class.
324 return;
325 }
326
Anders Carlsson28466ab2010-10-31 22:13:23 +0000327 AddSubobjectAtOffset(Info->Class, Offset);
Anders Carlssona7774a62010-05-29 21:10:24 +0000328
Anders Carlsson439edd12010-05-27 05:41:06 +0000329 // Traverse all non-virtual bases.
Anders Carlssona7774a62010-05-29 21:10:24 +0000330 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
David Majnemerc964b4b2014-07-16 06:04:00 +0000331 for (const BaseSubobjectInfo *Base : Info->Bases) {
Anders Carlsson439edd12010-05-27 05:41:06 +0000332 if (Base->IsVirtual)
333 continue;
Anders Carlssona7774a62010-05-29 21:10:24 +0000334
Anders Carlsson0a14ee92010-11-01 00:21:58 +0000335 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000336 UpdateEmptyBaseSubobjects(Base, BaseOffset, PlacingEmptyBase);
Anders Carlsson439edd12010-05-27 05:41:06 +0000337 }
338
Anders Carlssone3c24c72010-05-29 17:35:14 +0000339 if (Info->PrimaryVirtualBaseInfo) {
340 BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
Anders Carlsson439edd12010-05-27 05:41:06 +0000341
342 if (Info == PrimaryVirtualBaseInfo->Derived)
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000343 UpdateEmptyBaseSubobjects(PrimaryVirtualBaseInfo, Offset,
344 PlacingEmptyBase);
Anders Carlsson439edd12010-05-27 05:41:06 +0000345 }
Anders Carlssondb319762010-05-27 18:20:57 +0000346
Anders Carlssondb319762010-05-27 18:20:57 +0000347 // Traverse all member variables.
348 unsigned FieldNo = 0;
349 for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(),
350 E = Info->Class->field_end(); I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +0000351 if (I->isBitField())
Anders Carlsson233e2722010-10-31 21:54:55 +0000352 continue;
Anders Carlssona7774a62010-05-29 21:10:24 +0000353
Anders Carlsson28466ab2010-10-31 22:13:23 +0000354 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
David Blaikie40ed2972012-06-06 20:45:41 +0000355 UpdateEmptyFieldSubobjects(*I, FieldOffset);
Anders Carlssondb319762010-05-27 18:20:57 +0000356 }
Anders Carlsson439edd12010-05-27 05:41:06 +0000357}
358
Anders Carlssona60b86a2010-05-29 20:49:49 +0000359bool EmptySubobjectMap::CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000360 CharUnits Offset) {
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000361 // If we know this class doesn't have any empty subobjects we don't need to
362 // bother checking.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000363 if (SizeOfLargestEmptySubobject.isZero())
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000364 return true;
365
Anders Carlsson439edd12010-05-27 05:41:06 +0000366 if (!CanPlaceBaseSubobjectAtOffset(Info, Offset))
367 return false;
Anders Carlssondb319762010-05-27 18:20:57 +0000368
369 // We are able to place the base at this offset. Make sure to update the
370 // empty base subobject map.
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000371 UpdateEmptyBaseSubobjects(Info, Offset, Info->Class->isEmpty());
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000372 return true;
373}
374
Anders Carlssondb319762010-05-27 18:20:57 +0000375bool
376EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD,
377 const CXXRecordDecl *Class,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000378 CharUnits Offset) const {
Anders Carlsson45c1d282010-06-08 16:20:35 +0000379 // We don't have to keep looking past the maximum offset that's known to
380 // contain an empty class.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000381 if (!AnyEmptySubobjectsBeyondOffset(Offset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000382 return true;
383
Anders Carlsson28466ab2010-10-31 22:13:23 +0000384 if (!CanPlaceSubobjectAtOffset(RD, Offset))
Anders Carlssondb319762010-05-27 18:20:57 +0000385 return false;
386
387 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
388
389 // Traverse all non-virtual bases.
David Majnemerc964b4b2014-07-16 06:04:00 +0000390 for (const CXXBaseSpecifier &Base : RD->bases()) {
391 if (Base.isVirtual())
Anders Carlssondb319762010-05-27 18:20:57 +0000392 continue;
393
David Majnemerc964b4b2014-07-16 06:04:00 +0000394 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
Anders Carlssondb319762010-05-27 18:20:57 +0000395
Anders Carlsson0a14ee92010-11-01 00:21:58 +0000396 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
Anders Carlssondb319762010-05-27 18:20:57 +0000397 if (!CanPlaceFieldSubobjectAtOffset(BaseDecl, Class, BaseOffset))
398 return false;
399 }
400
Anders Carlsson44687202010-06-08 19:09:24 +0000401 if (RD == Class) {
402 // This is the most derived class, traverse virtual bases as well.
David Majnemerc964b4b2014-07-16 06:04:00 +0000403 for (const CXXBaseSpecifier &Base : RD->vbases()) {
404 const CXXRecordDecl *VBaseDecl = Base.getType()->getAsCXXRecordDecl();
Reid Klecknercd612ab2014-04-11 16:57:42 +0000405
Anders Carlsson3f018712010-10-31 23:45:59 +0000406 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
Anders Carlsson44687202010-06-08 19:09:24 +0000407 if (!CanPlaceFieldSubobjectAtOffset(VBaseDecl, Class, VBaseOffset))
408 return false;
409 }
410 }
411
Anders Carlssondb319762010-05-27 18:20:57 +0000412 // Traverse all member variables.
413 unsigned FieldNo = 0;
414 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
415 I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +0000416 if (I->isBitField())
Anders Carlsson233e2722010-10-31 21:54:55 +0000417 continue;
418
Anders Carlsson28466ab2010-10-31 22:13:23 +0000419 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
Anders Carlssondb319762010-05-27 18:20:57 +0000420
David Blaikie40ed2972012-06-06 20:45:41 +0000421 if (!CanPlaceFieldSubobjectAtOffset(*I, FieldOffset))
Anders Carlssondb319762010-05-27 18:20:57 +0000422 return false;
423 }
424
425 return true;
426}
427
Anders Carlsson233e2722010-10-31 21:54:55 +0000428bool
429EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD,
430 CharUnits Offset) const {
Anders Carlsson45c1d282010-06-08 16:20:35 +0000431 // We don't have to keep looking past the maximum offset that's known to
432 // contain an empty class.
Anders Carlsson233e2722010-10-31 21:54:55 +0000433 if (!AnyEmptySubobjectsBeyondOffset(Offset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000434 return true;
435
Anders Carlssondb319762010-05-27 18:20:57 +0000436 QualType T = FD->getType();
Reid Klecknercd612ab2014-04-11 16:57:42 +0000437 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
Anders Carlsson28466ab2010-10-31 22:13:23 +0000438 return CanPlaceFieldSubobjectAtOffset(RD, RD, Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000439
440 // If we have an array type we need to look at every element.
441 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
442 QualType ElemTy = Context.getBaseElementType(AT);
443 const RecordType *RT = ElemTy->getAs<RecordType>();
444 if (!RT)
445 return true;
Reid Klecknercd612ab2014-04-11 16:57:42 +0000446
447 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
Anders Carlssondb319762010-05-27 18:20:57 +0000448 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
449
450 uint64_t NumElements = Context.getConstantArrayElementCount(AT);
Anders Carlsson233e2722010-10-31 21:54:55 +0000451 CharUnits ElementOffset = Offset;
Anders Carlssondb319762010-05-27 18:20:57 +0000452 for (uint64_t I = 0; I != NumElements; ++I) {
Anders Carlsson45c1d282010-06-08 16:20:35 +0000453 // We don't have to keep looking past the maximum offset that's known to
454 // contain an empty class.
Anders Carlsson233e2722010-10-31 21:54:55 +0000455 if (!AnyEmptySubobjectsBeyondOffset(ElementOffset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000456 return true;
457
Anders Carlsson28466ab2010-10-31 22:13:23 +0000458 if (!CanPlaceFieldSubobjectAtOffset(RD, RD, ElementOffset))
Anders Carlssondb319762010-05-27 18:20:57 +0000459 return false;
460
Ken Dyckc8ae5502011-02-09 01:59:34 +0000461 ElementOffset += Layout.getSize();
Anders Carlssondb319762010-05-27 18:20:57 +0000462 }
463 }
464
465 return true;
466}
467
468bool
Anders Carlsson28466ab2010-10-31 22:13:23 +0000469EmptySubobjectMap::CanPlaceFieldAtOffset(const FieldDecl *FD,
470 CharUnits Offset) {
471 if (!CanPlaceFieldSubobjectAtOffset(FD, Offset))
Anders Carlssondb319762010-05-27 18:20:57 +0000472 return false;
473
474 // We are able to place the member variable at this offset.
475 // Make sure to update the empty base subobject map.
476 UpdateEmptyFieldSubobjects(FD, Offset);
477 return true;
478}
479
480void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD,
481 const CXXRecordDecl *Class,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000482 CharUnits Offset) {
Anders Carlssonae111dc2010-06-13 17:49:16 +0000483 // We know that the only empty subobjects that can conflict with empty
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000484 // field subobjects are subobjects of empty bases that can be placed at offset
Anders Carlssonae111dc2010-06-13 17:49:16 +0000485 // zero. Because of this, we only need to keep track of empty field
486 // subobjects with offsets less than the size of the largest empty
487 // subobject for our class.
488 if (Offset >= SizeOfLargestEmptySubobject)
489 return;
490
Anders Carlsson28466ab2010-10-31 22:13:23 +0000491 AddSubobjectAtOffset(RD, Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000492
493 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
494
495 // Traverse all non-virtual bases.
David Majnemerc964b4b2014-07-16 06:04:00 +0000496 for (const CXXBaseSpecifier &Base : RD->bases()) {
497 if (Base.isVirtual())
Anders Carlssondb319762010-05-27 18:20:57 +0000498 continue;
499
David Majnemerc964b4b2014-07-16 06:04:00 +0000500 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
Anders Carlssondb319762010-05-27 18:20:57 +0000501
Anders Carlsson0a14ee92010-11-01 00:21:58 +0000502 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
Anders Carlssondb319762010-05-27 18:20:57 +0000503 UpdateEmptyFieldSubobjects(BaseDecl, Class, BaseOffset);
504 }
505
Anders Carlsson44687202010-06-08 19:09:24 +0000506 if (RD == Class) {
507 // This is the most derived class, traverse virtual bases as well.
David Majnemerc964b4b2014-07-16 06:04:00 +0000508 for (const CXXBaseSpecifier &Base : RD->vbases()) {
509 const CXXRecordDecl *VBaseDecl = Base.getType()->getAsCXXRecordDecl();
Reid Klecknercd612ab2014-04-11 16:57:42 +0000510
Anders Carlsson3f018712010-10-31 23:45:59 +0000511 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
Anders Carlsson44687202010-06-08 19:09:24 +0000512 UpdateEmptyFieldSubobjects(VBaseDecl, Class, VBaseOffset);
513 }
514 }
515
Anders Carlssondb319762010-05-27 18:20:57 +0000516 // Traverse all member variables.
517 unsigned FieldNo = 0;
518 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
519 I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +0000520 if (I->isBitField())
Anders Carlsson09814d32010-11-01 15:14:51 +0000521 continue;
522
Anders Carlsson28466ab2010-10-31 22:13:23 +0000523 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
Anders Carlssondb319762010-05-27 18:20:57 +0000524
David Blaikie40ed2972012-06-06 20:45:41 +0000525 UpdateEmptyFieldSubobjects(*I, FieldOffset);
Anders Carlssondb319762010-05-27 18:20:57 +0000526 }
527}
528
529void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const FieldDecl *FD,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000530 CharUnits Offset) {
Anders Carlssondb319762010-05-27 18:20:57 +0000531 QualType T = FD->getType();
Reid Klecknercd612ab2014-04-11 16:57:42 +0000532 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
Anders Carlssondb319762010-05-27 18:20:57 +0000533 UpdateEmptyFieldSubobjects(RD, RD, Offset);
534 return;
535 }
536
537 // If we have an array type we need to update every element.
538 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
539 QualType ElemTy = Context.getBaseElementType(AT);
540 const RecordType *RT = ElemTy->getAs<RecordType>();
541 if (!RT)
542 return;
Reid Klecknercd612ab2014-04-11 16:57:42 +0000543
544 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
Anders Carlssondb319762010-05-27 18:20:57 +0000545 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
546
547 uint64_t NumElements = Context.getConstantArrayElementCount(AT);
Anders Carlsson28466ab2010-10-31 22:13:23 +0000548 CharUnits ElementOffset = Offset;
Anders Carlssondb319762010-05-27 18:20:57 +0000549
550 for (uint64_t I = 0; I != NumElements; ++I) {
Anders Carlssonae111dc2010-06-13 17:49:16 +0000551 // We know that the only empty subobjects that can conflict with empty
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000552 // field subobjects are subobjects of empty bases that can be placed at
Anders Carlssonae111dc2010-06-13 17:49:16 +0000553 // offset zero. Because of this, we only need to keep track of empty field
554 // subobjects with offsets less than the size of the largest empty
555 // subobject for our class.
556 if (ElementOffset >= SizeOfLargestEmptySubobject)
557 return;
558
Anders Carlssondb319762010-05-27 18:20:57 +0000559 UpdateEmptyFieldSubobjects(RD, RD, ElementOffset);
Ken Dyckc8ae5502011-02-09 01:59:34 +0000560 ElementOffset += Layout.getSize();
Anders Carlssondb319762010-05-27 18:20:57 +0000561 }
562 }
563}
564
John McCalle42a3362012-05-01 08:55:32 +0000565typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> ClassSetTy;
566
David Majnemer3b1c9902015-07-25 20:18:14 +0000567class ItaniumRecordLayoutBuilder {
Charles Davisc2c576a2010-08-19 00:55:19 +0000568protected:
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000569 // FIXME: Remove this and make the appropriate fields public.
570 friend class clang::ASTContext;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000571
Jay Foad39c79802011-01-12 09:06:06 +0000572 const ASTContext &Context;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000573
Anders Carlssonf58de112010-05-26 15:32:58 +0000574 EmptySubobjectMap *EmptySubobjects;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000575
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000576 /// Size - The current size of the record layout.
577 uint64_t Size;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000578
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000579 /// Alignment - The current alignment of the record layout.
Ken Dyck4731d5b2011-02-16 02:05:21 +0000580 CharUnits Alignment;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000581
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000582 /// \brief The alignment if attribute packed is not used.
Ken Dyck1300b3b2011-02-16 02:11:31 +0000583 CharUnits UnpackedAlignment;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000584
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000585 SmallVector<uint64_t, 16> FieldOffsets;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000586
Douglas Gregore9fc3772012-01-26 07:55:45 +0000587 /// \brief Whether the external AST source has provided a layout for this
588 /// record.
Reid Kleckner8b6d0342015-02-25 19:17:45 +0000589 unsigned UseExternalLayout : 1;
Douglas Gregor44ba7892012-01-28 00:53:29 +0000590
591 /// \brief Whether we need to infer alignment, even when we have an
592 /// externally-provided layout.
593 unsigned InferAlignment : 1;
Douglas Gregore9fc3772012-01-26 07:55:45 +0000594
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000595 /// Packed - Whether the record is packed or not.
Daniel Dunbar6da10982010-05-27 05:45:51 +0000596 unsigned Packed : 1;
597
598 unsigned IsUnion : 1;
599
600 unsigned IsMac68kAlign : 1;
Fariborz Jahanianbcb23a12011-04-26 23:52:16 +0000601
602 unsigned IsMsStruct : 1;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000603
Eli Friedman2782dac2013-06-26 20:50:34 +0000604 /// UnfilledBitsInLastUnit - If the last field laid out was a bitfield,
605 /// this contains the number of bits in the last unit that can be used for
606 /// an adjacent bitfield if necessary. The unit in question is usually
607 /// a byte, but larger units are used if IsMsStruct.
608 unsigned char UnfilledBitsInLastUnit;
609 /// LastBitfieldTypeSize - If IsMsStruct, represents the size of the type
610 /// of the previous field if it was a bitfield.
611 unsigned char LastBitfieldTypeSize;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000612
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000613 /// MaxFieldAlignment - The maximum allowed field alignment. This is set by
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000614 /// #pragma pack.
Ken Dyck02ced6f2011-02-17 01:49:42 +0000615 CharUnits MaxFieldAlignment;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000616
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000617 /// DataSize - The data size of the record being laid out.
618 uint64_t DataSize;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000619
Ken Dyckaf1c83f2011-02-16 01:52:01 +0000620 CharUnits NonVirtualSize;
Ken Dycka2d3dda2011-02-16 01:43:15 +0000621 CharUnits NonVirtualAlignment;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000622
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000623 /// PrimaryBase - the primary base class (if one exists) of the class
624 /// we're laying out.
625 const CXXRecordDecl *PrimaryBase;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000626
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000627 /// PrimaryBaseIsVirtual - Whether the primary base of the class we're laying
628 /// out is virtual.
629 bool PrimaryBaseIsVirtual;
630
John McCalle42a3362012-05-01 08:55:32 +0000631 /// HasOwnVFPtr - Whether the class provides its own vtable/vftbl
632 /// pointer, as opposed to inheriting one from a primary base class.
633 bool HasOwnVFPtr;
Eli Friedman43114f92011-10-21 22:49:56 +0000634
Anders Carlsson22f57202010-10-31 21:01:46 +0000635 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000636
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000637 /// Bases - base classes and their offsets in the record.
638 BaseOffsetsMapTy Bases;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000639
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000640 // VBases - virtual base classes and their offsets in the record.
John McCalle42a3362012-05-01 08:55:32 +0000641 ASTRecordLayout::VBaseOffsetsMapTy VBases;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000642
643 /// IndirectPrimaryBases - Virtual base classes, direct or indirect, that are
644 /// primary base classes for some other direct or indirect base class.
Anders Carlsson5adde292010-11-24 22:55:48 +0000645 CXXIndirectPrimaryBaseSet IndirectPrimaryBases;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000646
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000647 /// FirstNearlyEmptyVBase - The first nearly empty virtual base class in
648 /// inheritance graph order. Used for determining the primary base class.
649 const CXXRecordDecl *FirstNearlyEmptyVBase;
650
651 /// VisitedVirtualBases - A set of all the visited virtual bases, used to
652 /// avoid visiting virtual bases more than once.
653 llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000654
Reid Kleckner8b6d0342015-02-25 19:17:45 +0000655 /// Valid if UseExternalLayout is true.
656 ExternalLayout External;
Douglas Gregore9fc3772012-01-26 07:55:45 +0000657
David Majnemer3b1c9902015-07-25 20:18:14 +0000658 ItaniumRecordLayoutBuilder(const ASTContext &Context,
659 EmptySubobjectMap *EmptySubobjects)
660 : Context(Context), EmptySubobjects(EmptySubobjects), Size(0),
661 Alignment(CharUnits::One()), UnpackedAlignment(CharUnits::One()),
662 UseExternalLayout(false), InferAlignment(false), Packed(false),
663 IsUnion(false), IsMac68kAlign(false), IsMsStruct(false),
664 UnfilledBitsInLastUnit(0), LastBitfieldTypeSize(0),
665 MaxFieldAlignment(CharUnits::Zero()), DataSize(0),
666 NonVirtualSize(CharUnits::Zero()),
667 NonVirtualAlignment(CharUnits::One()), PrimaryBase(nullptr),
668 PrimaryBaseIsVirtual(false), HasOwnVFPtr(false),
669 FirstNearlyEmptyVBase(nullptr) {}
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000670
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000671 void Layout(const RecordDecl *D);
Anders Carlssonc28a6c92010-05-26 15:10:00 +0000672 void Layout(const CXXRecordDecl *D);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000673 void Layout(const ObjCInterfaceDecl *D);
674
675 void LayoutFields(const RecordDecl *D);
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000676 void LayoutField(const FieldDecl *D, bool InsertExtraPadding);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000677 void LayoutWideBitField(uint64_t FieldSize, uint64_t TypeSize,
678 bool FieldPacked, const FieldDecl *D);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000679 void LayoutBitField(const FieldDecl *D);
John McCall0153cd32011-11-08 04:01:03 +0000680
John McCall359b8852013-01-25 22:30:49 +0000681 TargetCXXABI getCXXABI() const {
682 return Context.getTargetInfo().getCXXABI();
683 }
684
Anders Carlssone3c24c72010-05-29 17:35:14 +0000685 /// BaseSubobjectInfoAllocator - Allocator for BaseSubobjectInfo objects.
686 llvm::SpecificBumpPtrAllocator<BaseSubobjectInfo> BaseSubobjectInfoAllocator;
687
688 typedef llvm::DenseMap<const CXXRecordDecl *, BaseSubobjectInfo *>
689 BaseSubobjectInfoMapTy;
690
691 /// VirtualBaseInfo - Map from all the (direct or indirect) virtual bases
692 /// of the class we're laying out to their base subobject info.
693 BaseSubobjectInfoMapTy VirtualBaseInfo;
694
695 /// NonVirtualBaseInfo - Map from all the direct non-virtual bases of the
696 /// class we're laying out to their base subobject info.
697 BaseSubobjectInfoMapTy NonVirtualBaseInfo;
698
699 /// ComputeBaseSubobjectInfo - Compute the base subobject information for the
700 /// bases of the given class.
701 void ComputeBaseSubobjectInfo(const CXXRecordDecl *RD);
702
703 /// ComputeBaseSubobjectInfo - Compute the base subobject information for a
704 /// single class and all of its base classes.
705 BaseSubobjectInfo *ComputeBaseSubobjectInfo(const CXXRecordDecl *RD,
706 bool IsVirtual,
707 BaseSubobjectInfo *Derived);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000708
709 /// DeterminePrimaryBase - Determine the primary base of the given class.
710 void DeterminePrimaryBase(const CXXRecordDecl *RD);
711
712 void SelectPrimaryVBase(const CXXRecordDecl *RD);
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000713
Eli Friedman43114f92011-10-21 22:49:56 +0000714 void EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign);
Charles Davisc2c576a2010-08-19 00:55:19 +0000715
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000716 /// LayoutNonVirtualBases - Determines the primary base class (if any) and
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000717 /// lays it out. Will then proceed to lay out all non-virtual base clasess.
718 void LayoutNonVirtualBases(const CXXRecordDecl *RD);
719
720 /// LayoutNonVirtualBase - Lays out a single non-virtual base.
Anders Carlssonbb0e6782010-05-29 17:42:25 +0000721 void LayoutNonVirtualBase(const BaseSubobjectInfo *Base);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000722
Anders Carlssona2f8e412010-10-31 22:20:42 +0000723 void AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
724 CharUnits Offset);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000725
726 /// LayoutVirtualBases - Lays out all the virtual bases.
727 void LayoutVirtualBases(const CXXRecordDecl *RD,
728 const CXXRecordDecl *MostDerivedClass);
729
730 /// LayoutVirtualBase - Lays out a single virtual base.
Warren Hunt55d8e822013-10-23 23:53:07 +0000731 void LayoutVirtualBase(const BaseSubobjectInfo *Base);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000732
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000733 /// LayoutBase - Will lay out a base and return the offset where it was
Anders Carlssona2f8e412010-10-31 22:20:42 +0000734 /// placed, in chars.
735 CharUnits LayoutBase(const BaseSubobjectInfo *Base);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000736
Anders Carlssonc28a6c92010-05-26 15:10:00 +0000737 /// InitializeLayout - Initialize record layout for the given record decl.
Daniel Dunbar6da10982010-05-27 05:45:51 +0000738 void InitializeLayout(const Decl *D);
Anders Carlssonc28a6c92010-05-26 15:10:00 +0000739
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000740 /// FinishLayout - Finalize record layout. Adjust record size based on the
741 /// alignment.
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000742 void FinishLayout(const NamedDecl *D);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000743
Ken Dyck85ef0432011-02-19 18:58:07 +0000744 void UpdateAlignment(CharUnits NewAlignment, CharUnits UnpackedNewAlignment);
745 void UpdateAlignment(CharUnits NewAlignment) {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000746 UpdateAlignment(NewAlignment, NewAlignment);
747 }
748
Douglas Gregor44ba7892012-01-28 00:53:29 +0000749 /// \brief Retrieve the externally-supplied field offset for the given
750 /// field.
751 ///
752 /// \param Field The field whose offset is being queried.
753 /// \param ComputedOffset The offset that we've computed for this field.
754 uint64_t updateExternalFieldOffset(const FieldDecl *Field,
755 uint64_t ComputedOffset);
756
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000757 void CheckFieldPadding(uint64_t Offset, uint64_t UnpaddedOffset,
758 uint64_t UnpackedOffset, unsigned UnpackedAlign,
759 bool isPacked, const FieldDecl *D);
760
761 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000762
Ken Dyckecfc7552011-02-24 01:13:28 +0000763 CharUnits getSize() const {
Ken Dyck3c215f22011-02-24 01:33:05 +0000764 assert(Size % Context.getCharWidth() == 0);
Ken Dyckecfc7552011-02-24 01:13:28 +0000765 return Context.toCharUnitsFromBits(Size);
766 }
767 uint64_t getSizeInBits() const { return Size; }
768
769 void setSize(CharUnits NewSize) { Size = Context.toBits(NewSize); }
770 void setSize(uint64_t NewSize) { Size = NewSize; }
771
Eli Friedman84d2d3a2011-09-27 19:12:27 +0000772 CharUnits getAligment() const { return Alignment; }
773
Ken Dyckecfc7552011-02-24 01:13:28 +0000774 CharUnits getDataSize() const {
Ken Dyck3c215f22011-02-24 01:33:05 +0000775 assert(DataSize % Context.getCharWidth() == 0);
Ken Dyckecfc7552011-02-24 01:13:28 +0000776 return Context.toCharUnitsFromBits(DataSize);
777 }
778 uint64_t getDataSizeInBits() const { return DataSize; }
779
780 void setDataSize(CharUnits NewSize) { DataSize = Context.toBits(NewSize); }
781 void setDataSize(uint64_t NewSize) { DataSize = NewSize; }
782
David Majnemer3b1c9902015-07-25 20:18:14 +0000783 ItaniumRecordLayoutBuilder(const ItaniumRecordLayoutBuilder &) = delete;
784 void operator=(const ItaniumRecordLayoutBuilder &) = delete;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000785};
Benjamin Kramerc7656cd2010-05-26 09:58:31 +0000786} // end anonymous namespace
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000787
David Majnemer3b1c9902015-07-25 20:18:14 +0000788void ItaniumRecordLayoutBuilder::SelectPrimaryVBase(const CXXRecordDecl *RD) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000789 for (const auto &I : RD->bases()) {
790 assert(!I.getType()->isDependentType() &&
Sebastian Redl1054fae2009-10-25 17:03:50 +0000791 "Cannot layout class with dependent bases.");
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000792
Reid Klecknercd612ab2014-04-11 16:57:42 +0000793 const CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000794
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000795 // Check if this is a nearly empty virtual base.
Aaron Ballman574705e2014-03-13 15:41:46 +0000796 if (I.isVirtual() && Context.isNearlyEmpty(Base)) {
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000797 // If it's not an indirect primary base, then we've found our primary
798 // base.
Anders Carlsson81430692009-09-22 03:02:06 +0000799 if (!IndirectPrimaryBases.count(Base)) {
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000800 PrimaryBase = Base;
801 PrimaryBaseIsVirtual = true;
Mike Stump6f3793b2009-08-12 21:50:08 +0000802 return;
803 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000804
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000805 // Is this the first nearly empty virtual base?
806 if (!FirstNearlyEmptyVBase)
807 FirstNearlyEmptyVBase = Base;
Mike Stump6f3793b2009-08-12 21:50:08 +0000808 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000809
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000810 SelectPrimaryVBase(Base);
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000811 if (PrimaryBase)
Zhongxing Xuec345b72010-02-15 04:28:35 +0000812 return;
Mike Stump6f3793b2009-08-12 21:50:08 +0000813 }
814}
815
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000816/// DeterminePrimaryBase - Determine the primary base of the given class.
David Majnemer3b1c9902015-07-25 20:18:14 +0000817void ItaniumRecordLayoutBuilder::DeterminePrimaryBase(const CXXRecordDecl *RD) {
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000818 // If the class isn't dynamic, it won't have a primary base.
819 if (!RD->isDynamicClass())
820 return;
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000821
Anders Carlsson81430692009-09-22 03:02:06 +0000822 // Compute all the primary virtual bases for all of our direct and
Mike Stump590a7c72009-08-13 23:26:06 +0000823 // indirect bases, and record all their primary virtual base classes.
Anders Carlsson5adde292010-11-24 22:55:48 +0000824 RD->getIndirectPrimaryBases(IndirectPrimaryBases);
Mike Stump590a7c72009-08-13 23:26:06 +0000825
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000826 // If the record has a dynamic base class, attempt to choose a primary base
827 // class. It is the first (in direct base class order) non-virtual dynamic
Anders Carlsson81430692009-09-22 03:02:06 +0000828 // base class, if one exists.
Aaron Ballman574705e2014-03-13 15:41:46 +0000829 for (const auto &I : RD->bases()) {
Anders Carlsson03ff3792009-11-27 22:05:05 +0000830 // Ignore virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000831 if (I.isVirtual())
Anders Carlsson03ff3792009-11-27 22:05:05 +0000832 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000833
Reid Klecknercd612ab2014-04-11 16:57:42 +0000834 const CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
Anders Carlsson03ff3792009-11-27 22:05:05 +0000835
Warren Hunt55d8e822013-10-23 23:53:07 +0000836 if (Base->isDynamicClass()) {
Anders Carlsson03ff3792009-11-27 22:05:05 +0000837 // We found it.
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000838 PrimaryBase = Base;
839 PrimaryBaseIsVirtual = false;
Anders Carlsson03ff3792009-11-27 22:05:05 +0000840 return;
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000841 }
842 }
843
Eli Friedman5e9534b2011-10-18 00:55:28 +0000844 // Under the Itanium ABI, if there is no non-virtual primary base class,
845 // try to compute the primary virtual base. The primary virtual base is
846 // the first nearly empty virtual base that is not an indirect primary
847 // virtual base class, if one exists.
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000848 if (RD->getNumVBases() != 0) {
849 SelectPrimaryVBase(RD);
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000850 if (PrimaryBase)
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000851 return;
852 }
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000853
Eli Friedman5e9534b2011-10-18 00:55:28 +0000854 // Otherwise, it is the first indirect primary base class, if one exists.
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000855 if (FirstNearlyEmptyVBase) {
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000856 PrimaryBase = FirstNearlyEmptyVBase;
857 PrimaryBaseIsVirtual = true;
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000858 return;
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000859 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000860
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000861 assert(!PrimaryBase && "Should not get here with a primary base!");
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000862}
863
David Majnemer3b1c9902015-07-25 20:18:14 +0000864BaseSubobjectInfo *ItaniumRecordLayoutBuilder::ComputeBaseSubobjectInfo(
865 const CXXRecordDecl *RD, bool IsVirtual, BaseSubobjectInfo *Derived) {
Anders Carlssone3c24c72010-05-29 17:35:14 +0000866 BaseSubobjectInfo *Info;
867
868 if (IsVirtual) {
869 // Check if we already have info about this virtual base.
870 BaseSubobjectInfo *&InfoSlot = VirtualBaseInfo[RD];
871 if (InfoSlot) {
872 assert(InfoSlot->Class == RD && "Wrong class for virtual base info!");
873 return InfoSlot;
874 }
875
876 // We don't, create it.
877 InfoSlot = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
878 Info = InfoSlot;
879 } else {
880 Info = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
881 }
882
883 Info->Class = RD;
884 Info->IsVirtual = IsVirtual;
Craig Topper36250ad2014-05-12 05:36:57 +0000885 Info->Derived = nullptr;
886 Info->PrimaryVirtualBaseInfo = nullptr;
887
888 const CXXRecordDecl *PrimaryVirtualBase = nullptr;
889 BaseSubobjectInfo *PrimaryVirtualBaseInfo = nullptr;
Anders Carlssone3c24c72010-05-29 17:35:14 +0000890
891 // Check if this base has a primary virtual base.
892 if (RD->getNumVBases()) {
893 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Anders Carlsson7f95cd12010-11-24 23:12:57 +0000894 if (Layout.isPrimaryBaseVirtual()) {
Anders Carlssone3c24c72010-05-29 17:35:14 +0000895 // This base does have a primary virtual base.
896 PrimaryVirtualBase = Layout.getPrimaryBase();
897 assert(PrimaryVirtualBase && "Didn't have a primary virtual base!");
898
899 // Now check if we have base subobject info about this primary base.
900 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
901
902 if (PrimaryVirtualBaseInfo) {
903 if (PrimaryVirtualBaseInfo->Derived) {
904 // We did have info about this primary base, and it turns out that it
905 // has already been claimed as a primary virtual base for another
Craig Topper36250ad2014-05-12 05:36:57 +0000906 // base.
907 PrimaryVirtualBase = nullptr;
Anders Carlssone3c24c72010-05-29 17:35:14 +0000908 } else {
909 // We can claim this base as our primary base.
910 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
911 PrimaryVirtualBaseInfo->Derived = Info;
912 }
913 }
914 }
915 }
916
917 // Now go through all direct bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000918 for (const auto &I : RD->bases()) {
919 bool IsVirtual = I.isVirtual();
Reid Klecknercd612ab2014-04-11 16:57:42 +0000920
921 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
922
Anders Carlssone3c24c72010-05-29 17:35:14 +0000923 Info->Bases.push_back(ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, Info));
924 }
925
926 if (PrimaryVirtualBase && !PrimaryVirtualBaseInfo) {
927 // Traversing the bases must have created the base info for our primary
928 // virtual base.
929 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
930 assert(PrimaryVirtualBaseInfo &&
931 "Did not create a primary virtual base!");
932
933 // Claim the primary virtual base as our primary virtual base.
934 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
935 PrimaryVirtualBaseInfo->Derived = Info;
936 }
937
938 return Info;
939}
940
David Majnemer3b1c9902015-07-25 20:18:14 +0000941void ItaniumRecordLayoutBuilder::ComputeBaseSubobjectInfo(
942 const CXXRecordDecl *RD) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000943 for (const auto &I : RD->bases()) {
944 bool IsVirtual = I.isVirtual();
Anders Carlssone3c24c72010-05-29 17:35:14 +0000945
Reid Klecknercd612ab2014-04-11 16:57:42 +0000946 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
947
Anders Carlssone3c24c72010-05-29 17:35:14 +0000948 // Compute the base subobject info for this base.
Craig Topper36250ad2014-05-12 05:36:57 +0000949 BaseSubobjectInfo *Info = ComputeBaseSubobjectInfo(BaseDecl, IsVirtual,
950 nullptr);
Anders Carlssone3c24c72010-05-29 17:35:14 +0000951
952 if (IsVirtual) {
953 // ComputeBaseInfo has already added this base for us.
954 assert(VirtualBaseInfo.count(BaseDecl) &&
955 "Did not add virtual base!");
956 } else {
957 // Add the base info to the map of non-virtual bases.
958 assert(!NonVirtualBaseInfo.count(BaseDecl) &&
959 "Non-virtual base already exists!");
960 NonVirtualBaseInfo.insert(std::make_pair(BaseDecl, Info));
961 }
962 }
963}
964
David Majnemer3b1c9902015-07-25 20:18:14 +0000965void ItaniumRecordLayoutBuilder::EnsureVTablePointerAlignment(
966 CharUnits UnpackedBaseAlign) {
Eli Friedman5e9534b2011-10-18 00:55:28 +0000967 CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
968
969 // The maximum field alignment overrides base align.
970 if (!MaxFieldAlignment.isZero()) {
971 BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
972 UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
973 }
974
975 // Round up the current record size to pointer alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +0000976 setSize(getSize().alignTo(BaseAlign));
Eli Friedman43114f92011-10-21 22:49:56 +0000977 setDataSize(getSize());
Eli Friedman5e9534b2011-10-18 00:55:28 +0000978
979 // Update the alignment.
980 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
981}
982
David Majnemer3b1c9902015-07-25 20:18:14 +0000983void ItaniumRecordLayoutBuilder::LayoutNonVirtualBases(
984 const CXXRecordDecl *RD) {
Anders Carlssone3c24c72010-05-29 17:35:14 +0000985 // Then, determine the primary base class.
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000986 DeterminePrimaryBase(RD);
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000987
Anders Carlssone3c24c72010-05-29 17:35:14 +0000988 // Compute base subobject info.
989 ComputeBaseSubobjectInfo(RD);
990
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000991 // If we have a primary base class, lay it out.
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000992 if (PrimaryBase) {
993 if (PrimaryBaseIsVirtual) {
Anders Carlssone3c24c72010-05-29 17:35:14 +0000994 // If the primary virtual base was a primary virtual base of some other
995 // base class we'll have to steal it.
996 BaseSubobjectInfo *PrimaryBaseInfo = VirtualBaseInfo.lookup(PrimaryBase);
Craig Topper36250ad2014-05-12 05:36:57 +0000997 PrimaryBaseInfo->Derived = nullptr;
998
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000999 // We have a virtual primary base, insert it as an indirect primary base.
Anders Carlssond20e7cd2010-05-26 05:20:58 +00001000 IndirectPrimaryBases.insert(PrimaryBase);
Anders Carlssonfe900962010-03-11 05:42:17 +00001001
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001002 assert(!VisitedVirtualBases.count(PrimaryBase) &&
Anders Carlssond20e7cd2010-05-26 05:20:58 +00001003 "vbase already visited!");
1004 VisitedVirtualBases.insert(PrimaryBase);
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001005
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001006 LayoutVirtualBase(PrimaryBaseInfo);
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001007 } else {
1008 BaseSubobjectInfo *PrimaryBaseInfo =
1009 NonVirtualBaseInfo.lookup(PrimaryBase);
1010 assert(PrimaryBaseInfo &&
1011 "Did not find base info for non-virtual primary base!");
1012
1013 LayoutNonVirtualBase(PrimaryBaseInfo);
1014 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001015
John McCall0153cd32011-11-08 04:01:03 +00001016 // If this class needs a vtable/vf-table and didn't get one from a
1017 // primary base, add it in now.
Warren Hunt55d8e822013-10-23 23:53:07 +00001018 } else if (RD->isDynamicClass()) {
Eli Friedman5e9534b2011-10-18 00:55:28 +00001019 assert(DataSize == 0 && "Vtable pointer must be at offset zero!");
Eli Friedman5e9534b2011-10-18 00:55:28 +00001020 CharUnits PtrWidth =
1021 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Eli Friedman43114f92011-10-21 22:49:56 +00001022 CharUnits PtrAlign =
1023 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0));
1024 EnsureVTablePointerAlignment(PtrAlign);
John McCalle42a3362012-05-01 08:55:32 +00001025 HasOwnVFPtr = true;
Eli Friedman5e9534b2011-10-18 00:55:28 +00001026 setSize(getSize() + PtrWidth);
1027 setDataSize(getSize());
1028 }
1029
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001030 // Now lay out the non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001031 for (const auto &I : RD->bases()) {
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001032
Benjamin Kramer273670a2013-10-25 07:40:50 +00001033 // Ignore virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001034 if (I.isVirtual())
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001035 continue;
1036
Aaron Ballman574705e2014-03-13 15:41:46 +00001037 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001038
John McCall0153cd32011-11-08 04:01:03 +00001039 // Skip the primary base, because we've already laid it out. The
1040 // !PrimaryBaseIsVirtual check is required because we might have a
1041 // non-virtual base of the same type as a primary virtual base.
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001042 if (BaseDecl == PrimaryBase && !PrimaryBaseIsVirtual)
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001043 continue;
1044
1045 // Lay out the base.
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001046 BaseSubobjectInfo *BaseInfo = NonVirtualBaseInfo.lookup(BaseDecl);
1047 assert(BaseInfo && "Did not find base info for non-virtual base!");
1048
1049 LayoutNonVirtualBase(BaseInfo);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001050 }
1051}
1052
David Majnemer3b1c9902015-07-25 20:18:14 +00001053void ItaniumRecordLayoutBuilder::LayoutNonVirtualBase(
1054 const BaseSubobjectInfo *Base) {
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001055 // Layout the base.
Anders Carlssona2f8e412010-10-31 22:20:42 +00001056 CharUnits Offset = LayoutBase(Base);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001057
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001058 // Add its base class offset.
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001059 assert(!Bases.count(Base->Class) && "base offset already exists!");
Anders Carlssona2f8e412010-10-31 22:20:42 +00001060 Bases.insert(std::make_pair(Base->Class, Offset));
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001061
1062 AddPrimaryVirtualBaseOffsets(Base, Offset);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001063}
Mike Stump2b84dd32009-11-05 04:02:15 +00001064
David Majnemer3b1c9902015-07-25 20:18:14 +00001065void ItaniumRecordLayoutBuilder::AddPrimaryVirtualBaseOffsets(
1066 const BaseSubobjectInfo *Info, CharUnits Offset) {
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001067 // This base isn't interesting, it has no virtual bases.
1068 if (!Info->Class->getNumVBases())
1069 return;
1070
1071 // First, check if we have a virtual primary base to add offsets for.
1072 if (Info->PrimaryVirtualBaseInfo) {
1073 assert(Info->PrimaryVirtualBaseInfo->IsVirtual &&
1074 "Primary virtual base is not virtual!");
1075 if (Info->PrimaryVirtualBaseInfo->Derived == Info) {
1076 // Add the offset.
1077 assert(!VBases.count(Info->PrimaryVirtualBaseInfo->Class) &&
1078 "primary vbase offset already exists!");
1079 VBases.insert(std::make_pair(Info->PrimaryVirtualBaseInfo->Class,
John McCalle42a3362012-05-01 08:55:32 +00001080 ASTRecordLayout::VBaseInfo(Offset, false)));
Anders Carlssonea7b1822010-04-15 16:12:58 +00001081
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001082 // Traverse the primary virtual base.
1083 AddPrimaryVirtualBaseOffsets(Info->PrimaryVirtualBaseInfo, Offset);
1084 }
Anders Carlssonea7b1822010-04-15 16:12:58 +00001085 }
1086
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001087 // Now go through all direct non-virtual bases.
1088 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
David Majnemerc964b4b2014-07-16 06:04:00 +00001089 for (const BaseSubobjectInfo *Base : Info->Bases) {
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001090 if (Base->IsVirtual)
Anders Carlssonea7b1822010-04-15 16:12:58 +00001091 continue;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001092
Anders Carlsson0a14ee92010-11-01 00:21:58 +00001093 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001094 AddPrimaryVirtualBaseOffsets(Base, BaseOffset);
Anders Carlssonea7b1822010-04-15 16:12:58 +00001095 }
1096}
1097
David Majnemer3b1c9902015-07-25 20:18:14 +00001098void ItaniumRecordLayoutBuilder::LayoutVirtualBases(
1099 const CXXRecordDecl *RD, const CXXRecordDecl *MostDerivedClass) {
Anders Carlssonde710c92010-03-11 04:33:54 +00001100 const CXXRecordDecl *PrimaryBase;
Anders Carlsson291279e2010-04-10 18:42:27 +00001101 bool PrimaryBaseIsVirtual;
Anders Carlssonfe900962010-03-11 05:42:17 +00001102
Anders Carlsson291279e2010-04-10 18:42:27 +00001103 if (MostDerivedClass == RD) {
Anders Carlssond20e7cd2010-05-26 05:20:58 +00001104 PrimaryBase = this->PrimaryBase;
1105 PrimaryBaseIsVirtual = this->PrimaryBaseIsVirtual;
Anders Carlsson291279e2010-04-10 18:42:27 +00001106 } else {
Anders Carlsson5efc56e2010-04-16 15:07:51 +00001107 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Anders Carlssonde710c92010-03-11 04:33:54 +00001108 PrimaryBase = Layout.getPrimaryBase();
Anders Carlsson7f95cd12010-11-24 23:12:57 +00001109 PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
Anders Carlsson291279e2010-04-10 18:42:27 +00001110 }
1111
David Majnemerc964b4b2014-07-16 06:04:00 +00001112 for (const CXXBaseSpecifier &Base : RD->bases()) {
1113 assert(!Base.getType()->isDependentType() &&
Sebastian Redl1054fae2009-10-25 17:03:50 +00001114 "Cannot layout class with dependent bases.");
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001115
David Majnemerc964b4b2014-07-16 06:04:00 +00001116 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
Anders Carlssonf7b7a1e2010-03-11 04:24:02 +00001117
David Majnemerc964b4b2014-07-16 06:04:00 +00001118 if (Base.isVirtual()) {
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001119 if (PrimaryBase != BaseDecl || !PrimaryBaseIsVirtual) {
1120 bool IndirectPrimaryBase = IndirectPrimaryBases.count(BaseDecl);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001121
Anders Carlsson291279e2010-04-10 18:42:27 +00001122 // Only lay out the virtual base if it's not an indirect primary base.
1123 if (!IndirectPrimaryBase) {
1124 // Only visit virtual bases once.
David Blaikie82e95a32014-11-19 07:49:47 +00001125 if (!VisitedVirtualBases.insert(BaseDecl).second)
Anders Carlsson291279e2010-04-10 18:42:27 +00001126 continue;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001127
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001128 const BaseSubobjectInfo *BaseInfo = VirtualBaseInfo.lookup(BaseDecl);
1129 assert(BaseInfo && "Did not find virtual base info!");
1130 LayoutVirtualBase(BaseInfo);
Anders Carlsson6a848892010-03-11 04:10:39 +00001131 }
Mike Stump2b84dd32009-11-05 04:02:15 +00001132 }
Mike Stumpc2f591b2009-08-13 22:53:07 +00001133 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001134
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001135 if (!BaseDecl->getNumVBases()) {
Anders Carlssonf7b7a1e2010-03-11 04:24:02 +00001136 // This base isn't interesting since it doesn't have any virtual bases.
1137 continue;
Mike Stump996576f32009-08-16 19:04:13 +00001138 }
Anders Carlssonf7b7a1e2010-03-11 04:24:02 +00001139
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001140 LayoutVirtualBases(BaseDecl, MostDerivedClass);
Mike Stump6b2556f2009-08-06 13:41:24 +00001141 }
1142}
1143
David Majnemer3b1c9902015-07-25 20:18:14 +00001144void ItaniumRecordLayoutBuilder::LayoutVirtualBase(
1145 const BaseSubobjectInfo *Base) {
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001146 assert(!Base->Derived && "Trying to lay out a primary virtual base!");
1147
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001148 // Layout the base.
Anders Carlssona2f8e412010-10-31 22:20:42 +00001149 CharUnits Offset = LayoutBase(Base);
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001150
1151 // Add its base class offset.
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001152 assert(!VBases.count(Base->Class) && "vbase offset already exists!");
John McCalle42a3362012-05-01 08:55:32 +00001153 VBases.insert(std::make_pair(Base->Class,
Warren Hunt55d8e822013-10-23 23:53:07 +00001154 ASTRecordLayout::VBaseInfo(Offset, false)));
John McCalle42a3362012-05-01 08:55:32 +00001155
Warren Hunt55d8e822013-10-23 23:53:07 +00001156 AddPrimaryVirtualBaseOffsets(Base, Offset);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001157}
1158
David Majnemer3b1c9902015-07-25 20:18:14 +00001159CharUnits
1160ItaniumRecordLayoutBuilder::LayoutBase(const BaseSubobjectInfo *Base) {
Anders Carlssond7f3fcf2010-05-29 20:47:33 +00001161 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base->Class);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001162
Douglas Gregore9fc3772012-01-26 07:55:45 +00001163
1164 CharUnits Offset;
1165
1166 // Query the external layout to see if it provides an offset.
1167 bool HasExternalLayout = false;
Reid Kleckner8b6d0342015-02-25 19:17:45 +00001168 if (UseExternalLayout) {
Douglas Gregore9fc3772012-01-26 07:55:45 +00001169 llvm::DenseMap<const CXXRecordDecl *, CharUnits>::iterator Known;
Reid Kleckner8b6d0342015-02-25 19:17:45 +00001170 if (Base->IsVirtual)
1171 HasExternalLayout = External.getExternalNVBaseOffset(Base->Class, Offset);
1172 else
1173 HasExternalLayout = External.getExternalVBaseOffset(Base->Class, Offset);
Douglas Gregore9fc3772012-01-26 07:55:45 +00001174 }
1175
Warren Huntd640d7d2014-01-09 00:30:56 +00001176 CharUnits UnpackedBaseAlign = Layout.getNonVirtualAlignment();
Eli Friedman69d27d22013-07-16 00:21:28 +00001177 CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
1178
Anders Carlsson09ffa322010-03-10 22:21:28 +00001179 // If we have an empty base class, try to place it at offset 0.
Anders Carlssond7f3fcf2010-05-29 20:47:33 +00001180 if (Base->Class->isEmpty() &&
Douglas Gregore9fc3772012-01-26 07:55:45 +00001181 (!HasExternalLayout || Offset == CharUnits::Zero()) &&
Anders Carlsson28466ab2010-10-31 22:13:23 +00001182 EmptySubobjects->CanPlaceBaseAtOffset(Base, CharUnits::Zero())) {
Ken Dyck1b4420e2011-02-28 02:01:38 +00001183 setSize(std::max(getSize(), Layout.getSize()));
Eli Friedman69d27d22013-07-16 00:21:28 +00001184 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001185
Anders Carlssona2f8e412010-10-31 22:20:42 +00001186 return CharUnits::Zero();
Anders Carlsson09ffa322010-03-10 22:21:28 +00001187 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001188
Argyrios Kyrtzidis8b542742010-12-09 00:35:20 +00001189 // The maximum field alignment overrides base align.
Ken Dyck02ced6f2011-02-17 01:49:42 +00001190 if (!MaxFieldAlignment.isZero()) {
Ken Dyck85ef0432011-02-19 18:58:07 +00001191 BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
1192 UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
Argyrios Kyrtzidis8b542742010-12-09 00:35:20 +00001193 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001194
Douglas Gregore9fc3772012-01-26 07:55:45 +00001195 if (!HasExternalLayout) {
1196 // Round up the current record size to the base's alignment boundary.
Rui Ueyama83aa9792016-01-14 21:00:27 +00001197 Offset = getDataSize().alignTo(BaseAlign);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001198
Douglas Gregore9fc3772012-01-26 07:55:45 +00001199 // Try to place the base.
1200 while (!EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset))
1201 Offset += BaseAlign;
1202 } else {
1203 bool Allowed = EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset);
1204 (void)Allowed;
1205 assert(Allowed && "Base subobject externally placed at overlapping offset");
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001206
Rui Ueyama83aa9792016-01-14 21:00:27 +00001207 if (InferAlignment && Offset < getDataSize().alignTo(BaseAlign)) {
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001208 // The externally-supplied base offset is before the base offset we
1209 // computed. Assume that the structure is packed.
1210 Alignment = CharUnits::One();
1211 InferAlignment = false;
1212 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00001213 }
1214
Anders Carlssond7f3fcf2010-05-29 20:47:33 +00001215 if (!Base->Class->isEmpty()) {
Anders Carlsson09ffa322010-03-10 22:21:28 +00001216 // Update the data size.
Ken Dyck1b4420e2011-02-28 02:01:38 +00001217 setDataSize(Offset + Layout.getNonVirtualSize());
Anders Carlsson09ffa322010-03-10 22:21:28 +00001218
Ken Dyck1b4420e2011-02-28 02:01:38 +00001219 setSize(std::max(getSize(), getDataSize()));
Anders Carlsson09ffa322010-03-10 22:21:28 +00001220 } else
Ken Dyck1b4420e2011-02-28 02:01:38 +00001221 setSize(std::max(getSize(), Offset + Layout.getSize()));
Anders Carlsson09ffa322010-03-10 22:21:28 +00001222
1223 // Remember max struct/class alignment.
Argyrios Kyrtzidis8b542742010-12-09 00:35:20 +00001224 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001225
Ken Dyck1b4420e2011-02-28 02:01:38 +00001226 return Offset;
Anders Carlsson09ffa322010-03-10 22:21:28 +00001227}
1228
David Majnemer3b1c9902015-07-25 20:18:14 +00001229void ItaniumRecordLayoutBuilder::InitializeLayout(const Decl *D) {
Eli Friedman9ee2d0472012-10-12 23:29:20 +00001230 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Daniel Dunbar6da10982010-05-27 05:45:51 +00001231 IsUnion = RD->isUnion();
Eli Friedman9ee2d0472012-10-12 23:29:20 +00001232 IsMsStruct = RD->isMsStruct(Context);
1233 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001234
Eli Friedman9ee2d0472012-10-12 23:29:20 +00001235 Packed = D->hasAttr<PackedAttr>();
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001236
Daniel Dunbar096ed292011-10-05 21:04:55 +00001237 // Honor the default struct packing maximum alignment flag.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001238 if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct) {
Daniel Dunbar096ed292011-10-05 21:04:55 +00001239 MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
1240 }
1241
Daniel Dunbar6da10982010-05-27 05:45:51 +00001242 // mac68k alignment supersedes maximum field alignment and attribute aligned,
1243 // and forces all structures to have 2-byte alignment. The IBM docs on it
1244 // allude to additional (more complicated) semantics, especially with regard
1245 // to bit-fields, but gcc appears not to follow that.
1246 if (D->hasAttr<AlignMac68kAttr>()) {
1247 IsMac68kAlign = true;
Ken Dyck02ced6f2011-02-17 01:49:42 +00001248 MaxFieldAlignment = CharUnits::fromQuantity(2);
Ken Dyck4731d5b2011-02-16 02:05:21 +00001249 Alignment = CharUnits::fromQuantity(2);
Daniel Dunbar6da10982010-05-27 05:45:51 +00001250 } else {
1251 if (const MaxFieldAlignmentAttr *MFAA = D->getAttr<MaxFieldAlignmentAttr>())
Ken Dyck02ced6f2011-02-17 01:49:42 +00001252 MaxFieldAlignment = Context.toCharUnitsFromBits(MFAA->getAlignment());
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001253
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001254 if (unsigned MaxAlign = D->getMaxAlignment())
Ken Dyck85ef0432011-02-19 18:58:07 +00001255 UpdateAlignment(Context.toCharUnitsFromBits(MaxAlign));
Daniel Dunbar6da10982010-05-27 05:45:51 +00001256 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00001257
1258 // If there is an external AST source, ask it for the various offsets.
1259 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
Reid Kleckner8b6d0342015-02-25 19:17:45 +00001260 if (ExternalASTSource *Source = Context.getExternalSource()) {
1261 UseExternalLayout = Source->layoutRecordType(
1262 RD, External.Size, External.Align, External.FieldOffsets,
1263 External.BaseOffsets, External.VirtualBaseOffsets);
NAKAMURA Takumi472041f2015-02-25 10:32:20 +00001264
Douglas Gregore9fc3772012-01-26 07:55:45 +00001265 // Update based on external alignment.
Reid Kleckner8b6d0342015-02-25 19:17:45 +00001266 if (UseExternalLayout) {
1267 if (External.Align > 0) {
1268 Alignment = Context.toCharUnitsFromBits(External.Align);
Douglas Gregor44ba7892012-01-28 00:53:29 +00001269 } else {
1270 // The external source didn't have alignment information; infer it.
1271 InferAlignment = true;
1272 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00001273 }
1274 }
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001275}
Anders Carlsson6d9f6f32009-07-19 00:18:47 +00001276
David Majnemer3b1c9902015-07-25 20:18:14 +00001277void ItaniumRecordLayoutBuilder::Layout(const RecordDecl *D) {
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001278 InitializeLayout(D);
Anders Carlsson118ce162009-07-18 21:48:39 +00001279 LayoutFields(D);
Mike Stump11289f42009-09-09 15:08:12 +00001280
Anders Carlsson79474332009-07-18 20:20:21 +00001281 // Finally, round the size of the total struct up to the alignment of the
1282 // struct itself.
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001283 FinishLayout(D);
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001284}
1285
David Majnemer3b1c9902015-07-25 20:18:14 +00001286void ItaniumRecordLayoutBuilder::Layout(const CXXRecordDecl *RD) {
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001287 InitializeLayout(RD);
1288
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001289 // Lay out the vtable and the non-virtual bases.
1290 LayoutNonVirtualBases(RD);
1291
1292 LayoutFields(RD);
1293
Ken Dycke7380752011-03-10 01:53:59 +00001294 NonVirtualSize = Context.toCharUnitsFromBits(
Rui Ueyama83aa9792016-01-14 21:00:27 +00001295 llvm::alignTo(getSizeInBits(), Context.getTargetInfo().getCharAlign()));
Ken Dyck4731d5b2011-02-16 02:05:21 +00001296 NonVirtualAlignment = Alignment;
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001297
Warren Hunt55d8e822013-10-23 23:53:07 +00001298 // Lay out the virtual bases and add the primary virtual base offsets.
1299 LayoutVirtualBases(RD, RD);
John McCall0153cd32011-11-08 04:01:03 +00001300
1301 // Finally, round the size of the total struct up to the alignment
Eli Friedman83a12582011-12-01 00:37:01 +00001302 // of the struct itself.
1303 FinishLayout(RD);
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001304
Anders Carlsson5b441d72010-04-10 21:24:48 +00001305#ifndef NDEBUG
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001306 // Check that we have base offsets for all bases.
David Majnemerc964b4b2014-07-16 06:04:00 +00001307 for (const CXXBaseSpecifier &Base : RD->bases()) {
1308 if (Base.isVirtual())
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001309 continue;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001310
David Majnemerc964b4b2014-07-16 06:04:00 +00001311 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001312
1313 assert(Bases.count(BaseDecl) && "Did not find base offset!");
1314 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001315
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001316 // And all virtual bases.
David Majnemerc964b4b2014-07-16 06:04:00 +00001317 for (const CXXBaseSpecifier &Base : RD->vbases()) {
1318 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001319
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001320 assert(VBases.count(BaseDecl) && "Did not find base offset!");
Anders Carlsson5b441d72010-04-10 21:24:48 +00001321 }
1322#endif
Anders Carlsson79474332009-07-18 20:20:21 +00001323}
1324
David Majnemer3b1c9902015-07-25 20:18:14 +00001325void ItaniumRecordLayoutBuilder::Layout(const ObjCInterfaceDecl *D) {
Anders Carlsson4f516282009-07-18 20:50:59 +00001326 if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
Anders Carlsson5efc56e2010-04-16 15:07:51 +00001327 const ASTRecordLayout &SL = Context.getASTObjCInterfaceLayout(SD);
Anders Carlsson4f516282009-07-18 20:50:59 +00001328
Ken Dyck85ef0432011-02-19 18:58:07 +00001329 UpdateAlignment(SL.getAlignment());
Mike Stump11289f42009-09-09 15:08:12 +00001330
Anders Carlsson4f516282009-07-18 20:50:59 +00001331 // We start laying out ivars not at the end of the superclass
1332 // structure, but at the next byte following the last field.
Ken Dyckecfc7552011-02-24 01:13:28 +00001333 setSize(SL.getDataSize());
Ken Dyck1b4420e2011-02-28 02:01:38 +00001334 setDataSize(getSize());
Anders Carlsson4f516282009-07-18 20:50:59 +00001335 }
Mike Stump11289f42009-09-09 15:08:12 +00001336
Daniel Dunbar6da10982010-05-27 05:45:51 +00001337 InitializeLayout(D);
Anders Carlsson4f516282009-07-18 20:50:59 +00001338 // Layout each ivar sequentially.
Jordy Rosea91768e2011-07-22 02:08:32 +00001339 for (const ObjCIvarDecl *IVD = D->all_declared_ivar_begin(); IVD;
1340 IVD = IVD->getNextIvar())
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00001341 LayoutField(IVD, false);
Mike Stump11289f42009-09-09 15:08:12 +00001342
Anders Carlsson4f516282009-07-18 20:50:59 +00001343 // Finally, round the size of the total struct up to the alignment of the
1344 // struct itself.
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001345 FinishLayout(D);
Anders Carlsson4f516282009-07-18 20:50:59 +00001346}
1347
David Majnemer3b1c9902015-07-25 20:18:14 +00001348void ItaniumRecordLayoutBuilder::LayoutFields(const RecordDecl *D) {
Anders Carlsson118ce162009-07-18 21:48:39 +00001349 // Layout each field, for now, just sequentially, respecting alignment. In
1350 // the future, this will need to be tweakable by targets.
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00001351 bool InsertExtraPadding = D->mayInsertExtraPadding(/*EmitRemark=*/true);
Kostya Serebryany68c29da2014-10-27 19:34:10 +00001352 bool HasFlexibleArrayMember = D->hasFlexibleArrayMember();
1353 for (auto I = D->field_begin(), End = D->field_end(); I != End; ++I) {
1354 auto Next(I);
1355 ++Next;
1356 LayoutField(*I,
1357 InsertExtraPadding && (Next != End || !HasFlexibleArrayMember));
1358 }
Anders Carlsson118ce162009-07-18 21:48:39 +00001359}
1360
Artyom Skrobov5e63acc2014-10-17 10:22:03 +00001361// Rounds the specified size to have it a multiple of the char size.
1362static uint64_t
1363roundUpSizeToCharAlignment(uint64_t Size,
1364 const ASTContext &Context) {
1365 uint64_t CharAlignment = Context.getTargetInfo().getCharAlign();
Rui Ueyama83aa9792016-01-14 21:00:27 +00001366 return llvm::alignTo(Size, CharAlignment);
Artyom Skrobov5e63acc2014-10-17 10:22:03 +00001367}
1368
David Majnemer3b1c9902015-07-25 20:18:14 +00001369void ItaniumRecordLayoutBuilder::LayoutWideBitField(uint64_t FieldSize,
1370 uint64_t TypeSize,
1371 bool FieldPacked,
1372 const FieldDecl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001373 assert(Context.getLangOpts().CPlusPlus &&
Anders Carlsson57235162010-04-16 15:57:11 +00001374 "Can only have wide bit-fields in C++!");
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001375
Anders Carlsson57235162010-04-16 15:57:11 +00001376 // Itanium C++ ABI 2.4:
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001377 // If sizeof(T)*8 < n, let T' be the largest integral POD type with
Anders Carlsson57235162010-04-16 15:57:11 +00001378 // sizeof(T')*8 <= n.
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001379
Anders Carlsson57235162010-04-16 15:57:11 +00001380 QualType IntegralPODTypes[] = {
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001381 Context.UnsignedCharTy, Context.UnsignedShortTy, Context.UnsignedIntTy,
Anders Carlsson57235162010-04-16 15:57:11 +00001382 Context.UnsignedLongTy, Context.UnsignedLongLongTy
1383 };
1384
Anders Carlsson57235162010-04-16 15:57:11 +00001385 QualType Type;
David Majnemerc964b4b2014-07-16 06:04:00 +00001386 for (const QualType &QT : IntegralPODTypes) {
1387 uint64_t Size = Context.getTypeSize(QT);
Anders Carlsson57235162010-04-16 15:57:11 +00001388
1389 if (Size > FieldSize)
1390 break;
1391
David Majnemerc964b4b2014-07-16 06:04:00 +00001392 Type = QT;
Anders Carlsson57235162010-04-16 15:57:11 +00001393 }
1394 assert(!Type.isNull() && "Did not find a type!");
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001395
Ken Dyckdbe37f32011-03-01 01:36:00 +00001396 CharUnits TypeAlign = Context.getTypeAlignInChars(Type);
Anders Carlsson57235162010-04-16 15:57:11 +00001397
1398 // We're not going to use any of the unfilled bits in the last byte.
Eli Friedman2782dac2013-06-26 20:50:34 +00001399 UnfilledBitsInLastUnit = 0;
1400 LastBitfieldTypeSize = 0;
Anders Carlsson57235162010-04-16 15:57:11 +00001401
Anders Carlssonaad5fa82010-04-17 20:21:41 +00001402 uint64_t FieldOffset;
Eli Friedman2782dac2013-06-26 20:50:34 +00001403 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001404
Anders Carlsson57235162010-04-16 15:57:11 +00001405 if (IsUnion) {
Artyom Skrobov5e63acc2014-10-17 10:22:03 +00001406 uint64_t RoundedFieldSize = roundUpSizeToCharAlignment(FieldSize,
1407 Context);
1408 setDataSize(std::max(getDataSizeInBits(), RoundedFieldSize));
Anders Carlssonaad5fa82010-04-17 20:21:41 +00001409 FieldOffset = 0;
Anders Carlsson57235162010-04-16 15:57:11 +00001410 } else {
Chad Rosiere1a6a0e2011-08-05 22:38:04 +00001411 // The bitfield is allocated starting at the next offset aligned
1412 // appropriately for T', with length n bits.
Rui Ueyama83aa9792016-01-14 21:00:27 +00001413 FieldOffset = llvm::alignTo(getDataSizeInBits(), Context.toBits(TypeAlign));
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001414
Anders Carlsson57235162010-04-16 15:57:11 +00001415 uint64_t NewSizeInBits = FieldOffset + FieldSize;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001416
Rui Ueyama83aa9792016-01-14 21:00:27 +00001417 setDataSize(
1418 llvm::alignTo(NewSizeInBits, Context.getTargetInfo().getCharAlign()));
Eli Friedman2782dac2013-06-26 20:50:34 +00001419 UnfilledBitsInLastUnit = getDataSizeInBits() - NewSizeInBits;
Anders Carlsson57235162010-04-16 15:57:11 +00001420 }
1421
1422 // Place this field at the current location.
1423 FieldOffsets.push_back(FieldOffset);
1424
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001425 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, FieldOffset,
Ken Dyckdbe37f32011-03-01 01:36:00 +00001426 Context.toBits(TypeAlign), FieldPacked, D);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001427
Anders Carlsson57235162010-04-16 15:57:11 +00001428 // Update the size.
Ken Dyckecfc7552011-02-24 01:13:28 +00001429 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001430
Anders Carlsson57235162010-04-16 15:57:11 +00001431 // Remember max struct/class alignment.
Ken Dyckdbe37f32011-03-01 01:36:00 +00001432 UpdateAlignment(TypeAlign);
Anders Carlsson57235162010-04-16 15:57:11 +00001433}
1434
David Majnemer3b1c9902015-07-25 20:18:14 +00001435void ItaniumRecordLayoutBuilder::LayoutBitField(const FieldDecl *D) {
Anders Carlsson07209442009-11-22 17:37:31 +00001436 bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
Richard Smithcaf33902011-10-10 18:28:20 +00001437 uint64_t FieldSize = D->getBitWidthValue(Context);
David Majnemer34b57492014-07-30 01:30:47 +00001438 TypeInfo FieldInfo = Context.getTypeInfo(D->getType());
1439 uint64_t TypeSize = FieldInfo.Width;
1440 unsigned FieldAlign = FieldInfo.Align;
Eli Friedman2782dac2013-06-26 20:50:34 +00001441
John McCall30268ca2014-01-29 07:53:44 +00001442 // UnfilledBitsInLastUnit is the difference between the end of the
1443 // last allocated bitfield (i.e. the first bit offset available for
1444 // bitfields) and the end of the current data size in bits (i.e. the
1445 // first bit offset available for non-bitfields). The current data
1446 // size in bits is always a multiple of the char size; additionally,
1447 // for ms_struct records it's also a multiple of the
1448 // LastBitfieldTypeSize (if set).
1449
John McCall76e1818a2014-02-13 00:50:08 +00001450 // The struct-layout algorithm is dictated by the platform ABI,
1451 // which in principle could use almost any rules it likes. In
1452 // practice, UNIXy targets tend to inherit the algorithm described
1453 // in the System V generic ABI. The basic bitfield layout rule in
1454 // System V is to place bitfields at the next available bit offset
1455 // where the entire bitfield would fit in an aligned storage unit of
1456 // the declared type; it's okay if an earlier or later non-bitfield
1457 // is allocated in the same storage unit. However, some targets
1458 // (those that !useBitFieldTypeAlignment(), e.g. ARM APCS) don't
1459 // require this storage unit to be aligned, and therefore always put
1460 // the bitfield at the next available bit offset.
John McCall30268ca2014-01-29 07:53:44 +00001461
John McCall76e1818a2014-02-13 00:50:08 +00001462 // ms_struct basically requests a complete replacement of the
1463 // platform ABI's struct-layout algorithm, with the high-level goal
1464 // of duplicating MSVC's layout. For non-bitfields, this follows
Eric Christopher2c4555a2015-06-19 01:52:53 +00001465 // the standard algorithm. The basic bitfield layout rule is to
John McCall76e1818a2014-02-13 00:50:08 +00001466 // allocate an entire unit of the bitfield's declared type
1467 // (e.g. 'unsigned long'), then parcel it up among successive
1468 // bitfields whose declared types have the same size, making a new
1469 // unit as soon as the last can no longer store the whole value.
1470 // Since it completely replaces the platform ABI's algorithm,
1471 // settings like !useBitFieldTypeAlignment() do not apply.
1472
1473 // A zero-width bitfield forces the use of a new storage unit for
1474 // later bitfields. In general, this occurs by rounding up the
1475 // current size of the struct as if the algorithm were about to
1476 // place a non-bitfield of the field's formal type. Usually this
1477 // does not change the alignment of the struct itself, but it does
1478 // on some targets (those that useZeroLengthBitfieldAlignment(),
1479 // e.g. ARM). In ms_struct layout, zero-width bitfields are
1480 // ignored unless they follow a non-zero-width bitfield.
1481
1482 // A field alignment restriction (e.g. from #pragma pack) or
1483 // specification (e.g. from __attribute__((aligned))) changes the
1484 // formal alignment of the field. For System V, this alters the
1485 // required alignment of the notional storage unit that must contain
1486 // the bitfield. For ms_struct, this only affects the placement of
1487 // new storage units. In both cases, the effect of #pragma pack is
1488 // ignored on zero-width bitfields.
1489
1490 // On System V, a packed field (e.g. from #pragma pack or
1491 // __attribute__((packed))) always uses the next available bit
1492 // offset.
1493
John McCall95833f32014-02-27 20:30:49 +00001494 // In an ms_struct struct, the alignment of a fundamental type is
1495 // always equal to its size. This is necessary in order to mimic
1496 // the i386 alignment rules on targets which might not fully align
1497 // all types (e.g. Darwin PPC32, where alignof(long long) == 4).
John McCall30268ca2014-01-29 07:53:44 +00001498
1499 // First, some simple bookkeeping to perform for ms_struct structs.
Eli Friedman2782dac2013-06-26 20:50:34 +00001500 if (IsMsStruct) {
John McCall30268ca2014-01-29 07:53:44 +00001501 // The field alignment for integer types is always the size.
Fariborz Jahanian7adbed62011-05-09 22:03:17 +00001502 FieldAlign = TypeSize;
John McCall30268ca2014-01-29 07:53:44 +00001503
1504 // If the previous field was not a bitfield, or was a bitfield
1505 // with a different storage unit size, we're done with that
1506 // storage unit.
Eli Friedman2782dac2013-06-26 20:50:34 +00001507 if (LastBitfieldTypeSize != TypeSize) {
John McCall30268ca2014-01-29 07:53:44 +00001508 // Also, ignore zero-length bitfields after non-bitfields.
1509 if (!LastBitfieldTypeSize && !FieldSize)
1510 FieldAlign = 1;
1511
Eli Friedman2782dac2013-06-26 20:50:34 +00001512 UnfilledBitsInLastUnit = 0;
1513 LastBitfieldTypeSize = 0;
1514 }
1515 }
1516
John McCall30268ca2014-01-29 07:53:44 +00001517 // If the field is wider than its declared type, it follows
1518 // different rules in all cases.
Anders Carlsson57235162010-04-16 15:57:11 +00001519 if (FieldSize > TypeSize) {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001520 LayoutWideBitField(FieldSize, TypeSize, FieldPacked, D);
Anders Carlsson57235162010-04-16 15:57:11 +00001521 return;
1522 }
1523
John McCall30268ca2014-01-29 07:53:44 +00001524 // Compute the next available bit offset.
1525 uint64_t FieldOffset =
1526 IsUnion ? 0 : (getDataSizeInBits() - UnfilledBitsInLastUnit);
1527
1528 // Handle targets that don't honor bitfield type alignment.
John McCall76e1818a2014-02-13 00:50:08 +00001529 if (!IsMsStruct && !Context.getTargetInfo().useBitFieldTypeAlignment()) {
John McCall30268ca2014-01-29 07:53:44 +00001530 // Some such targets do honor it on zero-width bitfields.
1531 if (FieldSize == 0 &&
1532 Context.getTargetInfo().useZeroLengthBitfieldAlignment()) {
1533 // The alignment to round up to is the max of the field's natural
1534 // alignment and a target-specific fixed value (sometimes zero).
1535 unsigned ZeroLengthBitfieldBoundary =
1536 Context.getTargetInfo().getZeroLengthBitfieldBoundary();
1537 FieldAlign = std::max(FieldAlign, ZeroLengthBitfieldBoundary);
1538
1539 // If that doesn't apply, just ignore the field alignment.
1540 } else {
1541 FieldAlign = 1;
1542 }
1543 }
1544
1545 // Remember the alignment we would have used if the field were not packed.
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001546 unsigned UnpackedFieldAlign = FieldAlign;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001547
Yunzhong Gao5fd0c9d2014-02-13 02:45:10 +00001548 // Ignore the field alignment if the field is packed unless it has zero-size.
1549 if (!IsMsStruct && FieldPacked && FieldSize != 0)
Anders Carlsson07209442009-11-22 17:37:31 +00001550 FieldAlign = 1;
Anders Carlsson07209442009-11-22 17:37:31 +00001551
John McCall30268ca2014-01-29 07:53:44 +00001552 // But, if there's an 'aligned' attribute on the field, honor that.
Alexey Bataev567e30f2016-01-12 09:12:20 +00001553 unsigned ExplicitFieldAlign = D->getMaxAlignment();
1554 if (ExplicitFieldAlign) {
John McCall30268ca2014-01-29 07:53:44 +00001555 FieldAlign = std::max(FieldAlign, ExplicitFieldAlign);
1556 UnpackedFieldAlign = std::max(UnpackedFieldAlign, ExplicitFieldAlign);
1557 }
1558
1559 // But, if there's a #pragma pack in play, that takes precedent over
1560 // even the 'aligned' attribute, for non-zero-width bitfields.
Alexey Bataev455bdd92016-02-19 11:23:28 +00001561 unsigned MaxFieldAlignmentInBits = Context.toBits(MaxFieldAlignment);
John McCall30268ca2014-01-29 07:53:44 +00001562 if (!MaxFieldAlignment.isZero() && FieldSize) {
Ken Dyck02ced6f2011-02-17 01:49:42 +00001563 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignmentInBits);
Alexey Bataev455bdd92016-02-19 11:23:28 +00001564 if (FieldPacked)
1565 FieldAlign = UnpackedFieldAlign;
1566 else
1567 FieldAlign = std::min(FieldAlign, MaxFieldAlignmentInBits);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001568 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001569
John McCall0d461692015-08-19 22:42:36 +00001570 // But, ms_struct just ignores all of that in unions, even explicit
1571 // alignment attributes.
1572 if (IsMsStruct && IsUnion) {
1573 FieldAlign = UnpackedFieldAlign = 1;
1574 }
1575
John McCall30268ca2014-01-29 07:53:44 +00001576 // For purposes of diagnostics, we're going to simultaneously
1577 // compute the field offsets that we would have used if we weren't
1578 // adding any alignment padding or if the field weren't packed.
1579 uint64_t UnpaddedFieldOffset = FieldOffset;
1580 uint64_t UnpackedFieldOffset = FieldOffset;
1581
1582 // Check if we need to add padding to fit the bitfield within an
1583 // allocation unit with the right size and alignment. The rules are
1584 // somewhat different here for ms_struct structs.
1585 if (IsMsStruct) {
1586 // If it's not a zero-width bitfield, and we can fit the bitfield
1587 // into the active storage unit (and we haven't already decided to
1588 // start a new storage unit), just do so, regardless of any other
1589 // other consideration. Otherwise, round up to the right alignment.
1590 if (FieldSize == 0 || FieldSize > UnfilledBitsInLastUnit) {
Rui Ueyama83aa9792016-01-14 21:00:27 +00001591 FieldOffset = llvm::alignTo(FieldOffset, FieldAlign);
1592 UnpackedFieldOffset =
1593 llvm::alignTo(UnpackedFieldOffset, UnpackedFieldAlign);
John McCall30268ca2014-01-29 07:53:44 +00001594 UnfilledBitsInLastUnit = 0;
1595 }
1596
1597 } else {
1598 // #pragma pack, with any value, suppresses the insertion of padding.
1599 bool AllowPadding = MaxFieldAlignment.isZero();
1600
1601 // Compute the real offset.
1602 if (FieldSize == 0 ||
1603 (AllowPadding &&
1604 (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize)) {
Rui Ueyama83aa9792016-01-14 21:00:27 +00001605 FieldOffset = llvm::alignTo(FieldOffset, FieldAlign);
Sunil Srivastava0ce2f222016-02-05 20:50:02 +00001606 } else if (ExplicitFieldAlign &&
Alexey Bataev455bdd92016-02-19 11:23:28 +00001607 (MaxFieldAlignmentInBits == 0 ||
1608 ExplicitFieldAlign <= MaxFieldAlignmentInBits) &&
Sunil Srivastava0ce2f222016-02-05 20:50:02 +00001609 Context.getTargetInfo().useExplicitBitFieldAlignment()) {
Alexey Bataev567e30f2016-01-12 09:12:20 +00001610 // TODO: figure it out what needs to be done on targets that don't honor
1611 // bit-field type alignment like ARM APCS ABI.
Rui Ueyama83aa9792016-01-14 21:00:27 +00001612 FieldOffset = llvm::alignTo(FieldOffset, ExplicitFieldAlign);
John McCall30268ca2014-01-29 07:53:44 +00001613 }
1614
1615 // Repeat the computation for diagnostic purposes.
1616 if (FieldSize == 0 ||
1617 (AllowPadding &&
1618 (UnpackedFieldOffset & (UnpackedFieldAlign-1)) + FieldSize > TypeSize))
Rui Ueyama83aa9792016-01-14 21:00:27 +00001619 UnpackedFieldOffset =
1620 llvm::alignTo(UnpackedFieldOffset, UnpackedFieldAlign);
Sunil Srivastava0ce2f222016-02-05 20:50:02 +00001621 else if (ExplicitFieldAlign &&
Alexey Bataev455bdd92016-02-19 11:23:28 +00001622 (MaxFieldAlignmentInBits == 0 ||
1623 ExplicitFieldAlign <= MaxFieldAlignmentInBits) &&
Sunil Srivastava0ce2f222016-02-05 20:50:02 +00001624 Context.getTargetInfo().useExplicitBitFieldAlignment())
Rui Ueyama83aa9792016-01-14 21:00:27 +00001625 UnpackedFieldOffset =
1626 llvm::alignTo(UnpackedFieldOffset, ExplicitFieldAlign);
Eli Friedman2782dac2013-06-26 20:50:34 +00001627 }
1628
John McCall30268ca2014-01-29 07:53:44 +00001629 // If we're using external layout, give the external layout a chance
1630 // to override this information.
Reid Kleckner8b6d0342015-02-25 19:17:45 +00001631 if (UseExternalLayout)
Douglas Gregor44ba7892012-01-28 00:53:29 +00001632 FieldOffset = updateExternalFieldOffset(D, FieldOffset);
1633
John McCall30268ca2014-01-29 07:53:44 +00001634 // Okay, place the bitfield at the calculated offset.
Anders Carlsson07209442009-11-22 17:37:31 +00001635 FieldOffsets.push_back(FieldOffset);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001636
John McCall30268ca2014-01-29 07:53:44 +00001637 // Bookkeeping:
1638
1639 // Anonymous members don't affect the overall record alignment,
1640 // except on targets where they do.
1641 if (!IsMsStruct &&
1642 !Context.getTargetInfo().useZeroLengthBitfieldAlignment() &&
1643 !D->getIdentifier())
1644 FieldAlign = UnpackedFieldAlign = 1;
1645
1646 // Diagnose differences in layout due to padding or packing.
Reid Kleckner8b6d0342015-02-25 19:17:45 +00001647 if (!UseExternalLayout)
Douglas Gregore9fc3772012-01-26 07:55:45 +00001648 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, UnpackedFieldOffset,
1649 UnpackedFieldAlign, FieldPacked, D);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001650
Anders Carlssonba958402009-11-22 19:13:51 +00001651 // Update DataSize to include the last byte containing (part of) the bitfield.
John McCall30268ca2014-01-29 07:53:44 +00001652
1653 // For unions, this is just a max operation, as usual.
Anders Carlssonba958402009-11-22 19:13:51 +00001654 if (IsUnion) {
John McCall0d461692015-08-19 22:42:36 +00001655 // For ms_struct, allocate the entire storage unit --- unless this
1656 // is a zero-width bitfield, in which case just use a size of 1.
1657 uint64_t RoundedFieldSize;
1658 if (IsMsStruct) {
1659 RoundedFieldSize =
1660 (FieldSize ? TypeSize : Context.getTargetInfo().getCharWidth());
1661
1662 // Otherwise, allocate just the number of bytes required to store
1663 // the bitfield.
1664 } else {
1665 RoundedFieldSize = roundUpSizeToCharAlignment(FieldSize, Context);
1666 }
Artyom Skrobov5e63acc2014-10-17 10:22:03 +00001667 setDataSize(std::max(getDataSizeInBits(), RoundedFieldSize));
John McCall0d461692015-08-19 22:42:36 +00001668
John McCall30268ca2014-01-29 07:53:44 +00001669 // For non-zero-width bitfields in ms_struct structs, allocate a new
1670 // storage unit if necessary.
1671 } else if (IsMsStruct && FieldSize) {
1672 // We should have cleared UnfilledBitsInLastUnit in every case
1673 // where we changed storage units.
1674 if (!UnfilledBitsInLastUnit) {
1675 setDataSize(FieldOffset + TypeSize);
1676 UnfilledBitsInLastUnit = TypeSize;
Eli Friedman2782dac2013-06-26 20:50:34 +00001677 }
John McCall30268ca2014-01-29 07:53:44 +00001678 UnfilledBitsInLastUnit -= FieldSize;
1679 LastBitfieldTypeSize = TypeSize;
1680
1681 // Otherwise, bump the data size up to include the bitfield,
1682 // including padding up to char alignment, and then remember how
1683 // bits we didn't use.
1684 } else {
1685 uint64_t NewSizeInBits = FieldOffset + FieldSize;
1686 uint64_t CharAlignment = Context.getTargetInfo().getCharAlign();
Rui Ueyama83aa9792016-01-14 21:00:27 +00001687 setDataSize(llvm::alignTo(NewSizeInBits, CharAlignment));
John McCall30268ca2014-01-29 07:53:44 +00001688 UnfilledBitsInLastUnit = getDataSizeInBits() - NewSizeInBits;
1689
1690 // The only time we can get here for an ms_struct is if this is a
1691 // zero-width bitfield, which doesn't count as anything for the
1692 // purposes of unfilled bits.
1693 LastBitfieldTypeSize = 0;
Anders Carlssonba958402009-11-22 19:13:51 +00001694 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001695
Anders Carlssonba958402009-11-22 19:13:51 +00001696 // Update the size.
Ken Dyckecfc7552011-02-24 01:13:28 +00001697 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001698
Anders Carlsson07209442009-11-22 17:37:31 +00001699 // Remember max struct/class alignment.
Ken Dyck85ef0432011-02-19 18:58:07 +00001700 UpdateAlignment(Context.toCharUnitsFromBits(FieldAlign),
1701 Context.toCharUnitsFromBits(UnpackedFieldAlign));
Anders Carlsson07209442009-11-22 17:37:31 +00001702}
1703
David Majnemer3b1c9902015-07-25 20:18:14 +00001704void ItaniumRecordLayoutBuilder::LayoutField(const FieldDecl *D,
1705 bool InsertExtraPadding) {
Anders Carlsson07209442009-11-22 17:37:31 +00001706 if (D->isBitField()) {
1707 LayoutBitField(D);
1708 return;
1709 }
1710
Eli Friedman2782dac2013-06-26 20:50:34 +00001711 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001712
Anders Carlssonba958402009-11-22 19:13:51 +00001713 // Reset the unfilled bits.
Eli Friedman2782dac2013-06-26 20:50:34 +00001714 UnfilledBitsInLastUnit = 0;
1715 LastBitfieldTypeSize = 0;
Anders Carlssonba958402009-11-22 19:13:51 +00001716
Anders Carlsson07209442009-11-22 17:37:31 +00001717 bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
Ken Dyck6d90e892011-02-20 02:06:09 +00001718 CharUnits FieldOffset =
Ken Dyckecfc7552011-02-24 01:13:28 +00001719 IsUnion ? CharUnits::Zero() : getDataSize();
Ken Dyck6d90e892011-02-20 02:06:09 +00001720 CharUnits FieldSize;
1721 CharUnits FieldAlign;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001722
Anders Carlsson07209442009-11-22 17:37:31 +00001723 if (D->getType()->isIncompleteArrayType()) {
1724 // This is a flexible array member; we can't directly
1725 // query getTypeInfo about these, so we figure it out here.
1726 // Flexible array members don't have any size, but they
1727 // have to be aligned appropriately for their element type.
Ken Dyck6d90e892011-02-20 02:06:09 +00001728 FieldSize = CharUnits::Zero();
Anders Carlsson5efc56e2010-04-16 15:07:51 +00001729 const ArrayType* ATy = Context.getAsArrayType(D->getType());
Ken Dyck6d90e892011-02-20 02:06:09 +00001730 FieldAlign = Context.getTypeAlignInChars(ATy->getElementType());
Anders Carlsson07209442009-11-22 17:37:31 +00001731 } else if (const ReferenceType *RT = D->getType()->getAs<ReferenceType>()) {
1732 unsigned AS = RT->getPointeeType().getAddressSpace();
Ken Dyck6d90e892011-02-20 02:06:09 +00001733 FieldSize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001734 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(AS));
Ken Dyck6d90e892011-02-20 02:06:09 +00001735 FieldAlign =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001736 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(AS));
Anders Carlsson79474332009-07-18 20:20:21 +00001737 } else {
Ken Dyck6d90e892011-02-20 02:06:09 +00001738 std::pair<CharUnits, CharUnits> FieldInfo =
1739 Context.getTypeInfoInChars(D->getType());
Anders Carlsson07209442009-11-22 17:37:31 +00001740 FieldSize = FieldInfo.first;
1741 FieldAlign = FieldInfo.second;
Chad Rosier18903ee2011-08-04 01:21:14 +00001742
Eli Friedman9ee2d0472012-10-12 23:29:20 +00001743 if (IsMsStruct) {
Douglas Gregordbe39272011-02-01 15:15:22 +00001744 // If MS bitfield layout is required, figure out what type is being
1745 // laid out and align the field to the width of that type.
1746
1747 // Resolve all typedefs down to their base type and round up the field
1748 // alignment if necessary.
1749 QualType T = Context.getBaseElementType(D->getType());
1750 if (const BuiltinType *BTy = T->getAs<BuiltinType>()) {
Ken Dyck6d90e892011-02-20 02:06:09 +00001751 CharUnits TypeSize = Context.getTypeSizeInChars(BTy);
Douglas Gregordbe39272011-02-01 15:15:22 +00001752 if (TypeSize > FieldAlign)
1753 FieldAlign = TypeSize;
1754 }
1755 }
Anders Carlsson79474332009-07-18 20:20:21 +00001756 }
Mike Stump11289f42009-09-09 15:08:12 +00001757
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001758 // The align if the field is not packed. This is to check if the attribute
1759 // was unnecessary (-Wpacked).
Ken Dyck6d90e892011-02-20 02:06:09 +00001760 CharUnits UnpackedFieldAlign = FieldAlign;
1761 CharUnits UnpackedFieldOffset = FieldOffset;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001762
Anders Carlsson07209442009-11-22 17:37:31 +00001763 if (FieldPacked)
Ken Dyck6d90e892011-02-20 02:06:09 +00001764 FieldAlign = CharUnits::One();
1765 CharUnits MaxAlignmentInChars =
1766 Context.toCharUnitsFromBits(D->getMaxAlignment());
1767 FieldAlign = std::max(FieldAlign, MaxAlignmentInChars);
1768 UnpackedFieldAlign = std::max(UnpackedFieldAlign, MaxAlignmentInChars);
Anders Carlsson07209442009-11-22 17:37:31 +00001769
1770 // The maximum field alignment overrides the aligned attribute.
Ken Dyck02ced6f2011-02-17 01:49:42 +00001771 if (!MaxFieldAlignment.isZero()) {
Ken Dyck6d90e892011-02-20 02:06:09 +00001772 FieldAlign = std::min(FieldAlign, MaxFieldAlignment);
1773 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignment);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001774 }
Anders Carlsson07209442009-11-22 17:37:31 +00001775
Douglas Gregor44ba7892012-01-28 00:53:29 +00001776 // Round up the current record size to the field's alignment boundary.
Rui Ueyama83aa9792016-01-14 21:00:27 +00001777 FieldOffset = FieldOffset.alignTo(FieldAlign);
1778 UnpackedFieldOffset = UnpackedFieldOffset.alignTo(UnpackedFieldAlign);
Douglas Gregor44ba7892012-01-28 00:53:29 +00001779
Reid Kleckner8b6d0342015-02-25 19:17:45 +00001780 if (UseExternalLayout) {
Douglas Gregor44ba7892012-01-28 00:53:29 +00001781 FieldOffset = Context.toCharUnitsFromBits(
1782 updateExternalFieldOffset(D, Context.toBits(FieldOffset)));
1783
1784 if (!IsUnion && EmptySubobjects) {
1785 // Record the fact that we're placing a field at this offset.
1786 bool Allowed = EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset);
1787 (void)Allowed;
1788 assert(Allowed && "Externally-placed field cannot be placed here");
1789 }
1790 } else {
Douglas Gregore9fc3772012-01-26 07:55:45 +00001791 if (!IsUnion && EmptySubobjects) {
1792 // Check if we can place the field at this offset.
1793 while (!EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset)) {
1794 // We couldn't place the field at the offset. Try again at a new offset.
1795 FieldOffset += FieldAlign;
1796 }
Anders Carlsson07209442009-11-22 17:37:31 +00001797 }
Anders Carlsson07209442009-11-22 17:37:31 +00001798 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00001799
Anders Carlsson79474332009-07-18 20:20:21 +00001800 // Place this field at the current location.
Ken Dyck6d90e892011-02-20 02:06:09 +00001801 FieldOffsets.push_back(Context.toBits(FieldOffset));
Mike Stump11289f42009-09-09 15:08:12 +00001802
Reid Kleckner8b6d0342015-02-25 19:17:45 +00001803 if (!UseExternalLayout)
1804 CheckFieldPadding(Context.toBits(FieldOffset), UnpaddedFieldOffset,
Douglas Gregore9fc3772012-01-26 07:55:45 +00001805 Context.toBits(UnpackedFieldOffset),
1806 Context.toBits(UnpackedFieldAlign), FieldPacked, D);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001807
Kostya Serebryany68c29da2014-10-27 19:34:10 +00001808 if (InsertExtraPadding) {
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00001809 CharUnits ASanAlignment = CharUnits::fromQuantity(8);
1810 CharUnits ExtraSizeForAsan = ASanAlignment;
1811 if (FieldSize % ASanAlignment)
1812 ExtraSizeForAsan +=
1813 ASanAlignment - CharUnits::fromQuantity(FieldSize % ASanAlignment);
1814 FieldSize += ExtraSizeForAsan;
1815 }
1816
Anders Carlsson79474332009-07-18 20:20:21 +00001817 // Reserve space for this field.
Eli Friedman43f18342012-01-12 23:27:03 +00001818 uint64_t FieldSizeInBits = Context.toBits(FieldSize);
Anders Carlsson79474332009-07-18 20:20:21 +00001819 if (IsUnion)
Eli Friedman2e108372012-01-12 23:48:56 +00001820 setDataSize(std::max(getDataSizeInBits(), FieldSizeInBits));
Anders Carlsson79474332009-07-18 20:20:21 +00001821 else
Eli Friedman2e108372012-01-12 23:48:56 +00001822 setDataSize(FieldOffset + FieldSize);
Mike Stump11289f42009-09-09 15:08:12 +00001823
Eli Friedman2e108372012-01-12 23:48:56 +00001824 // Update the size.
1825 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
Mike Stump11289f42009-09-09 15:08:12 +00001826
Anders Carlsson79474332009-07-18 20:20:21 +00001827 // Remember max struct/class alignment.
Ken Dyck6d90e892011-02-20 02:06:09 +00001828 UpdateAlignment(FieldAlign, UnpackedFieldAlign);
Anders Carlsson79474332009-07-18 20:20:21 +00001829}
1830
David Majnemer3b1c9902015-07-25 20:18:14 +00001831void ItaniumRecordLayoutBuilder::FinishLayout(const NamedDecl *D) {
Anders Carlsson79474332009-07-18 20:20:21 +00001832 // In C++, records cannot be of size 0.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001833 if (Context.getLangOpts().CPlusPlus && getSizeInBits() == 0) {
Fariborz Jahanian09b23312011-02-02 19:36:18 +00001834 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
1835 // Compatibility with gcc requires a class (pod or non-pod)
1836 // which is not empty but of size 0; such as having fields of
1837 // array of zero-length, remains of Size 0
1838 if (RD->isEmpty())
Ken Dyck1b4420e2011-02-28 02:01:38 +00001839 setSize(CharUnits::One());
Fariborz Jahanian09b23312011-02-02 19:36:18 +00001840 }
1841 else
Ken Dyck1b4420e2011-02-28 02:01:38 +00001842 setSize(CharUnits::One());
Fariborz Jahanian09b23312011-02-02 19:36:18 +00001843 }
Eli Friedman83a12582011-12-01 00:37:01 +00001844
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001845 // Finally, round the size of the record up to the alignment of the
1846 // record itself.
Eli Friedman2782dac2013-06-26 20:50:34 +00001847 uint64_t UnpaddedSize = getSizeInBits() - UnfilledBitsInLastUnit;
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001848 uint64_t UnpackedSizeInBits =
Rui Ueyama83aa9792016-01-14 21:00:27 +00001849 llvm::alignTo(getSizeInBits(), Context.toBits(UnpackedAlignment));
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001850 CharUnits UnpackedSize = Context.toCharUnitsFromBits(UnpackedSizeInBits);
Rui Ueyama83aa9792016-01-14 21:00:27 +00001851 uint64_t RoundedSize =
1852 llvm::alignTo(getSizeInBits(), Context.toBits(Alignment));
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001853
Reid Kleckner8b6d0342015-02-25 19:17:45 +00001854 if (UseExternalLayout) {
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001855 // If we're inferring alignment, and the external size is smaller than
1856 // our size after we've rounded up to alignment, conservatively set the
1857 // alignment to 1.
Reid Kleckner8b6d0342015-02-25 19:17:45 +00001858 if (InferAlignment && External.Size < RoundedSize) {
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001859 Alignment = CharUnits::One();
1860 InferAlignment = false;
1861 }
Reid Kleckner8b6d0342015-02-25 19:17:45 +00001862 setSize(External.Size);
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001863 return;
1864 }
1865
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001866 // Set the size to the final size.
1867 setSize(RoundedSize);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001868
Douglas Gregore8bbc122011-09-02 00:18:52 +00001869 unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001870 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
1871 // Warn if padding was introduced to the struct/class/union.
Ken Dyckecfc7552011-02-24 01:13:28 +00001872 if (getSizeInBits() > UnpaddedSize) {
1873 unsigned PadSize = getSizeInBits() - UnpaddedSize;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001874 bool InBits = true;
1875 if (PadSize % CharBitNum == 0) {
1876 PadSize = PadSize / CharBitNum;
1877 InBits = false;
1878 }
1879 Diag(RD->getLocation(), diag::warn_padded_struct_size)
1880 << Context.getTypeDeclType(RD)
1881 << PadSize
Benjamin Kramerc06b6bd2015-08-21 12:51:01 +00001882 << (InBits ? 1 : 0); // (byte|bit)
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001883 }
1884
1885 // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
1886 // bother since there won't be alignment issues.
Ken Dyckecfc7552011-02-24 01:13:28 +00001887 if (Packed && UnpackedAlignment > CharUnits::One() &&
Ken Dyck1b4420e2011-02-28 02:01:38 +00001888 getSize() == UnpackedSize)
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001889 Diag(D->getLocation(), diag::warn_unnecessary_packed)
1890 << Context.getTypeDeclType(RD);
1891 }
Anders Carlsson79474332009-07-18 20:20:21 +00001892}
1893
David Majnemer3b1c9902015-07-25 20:18:14 +00001894void ItaniumRecordLayoutBuilder::UpdateAlignment(
1895 CharUnits NewAlignment, CharUnits UnpackedNewAlignment) {
Douglas Gregore9fc3772012-01-26 07:55:45 +00001896 // The alignment is not modified when using 'mac68k' alignment or when
Douglas Gregor44ba7892012-01-28 00:53:29 +00001897 // we have an externally-supplied layout that also provides overall alignment.
Reid Kleckner8b6d0342015-02-25 19:17:45 +00001898 if (IsMac68kAlign || (UseExternalLayout && !InferAlignment))
Daniel Dunbar6da10982010-05-27 05:45:51 +00001899 return;
1900
Ken Dyck85ef0432011-02-19 18:58:07 +00001901 if (NewAlignment > Alignment) {
Reid Kleckner5a63d702015-03-24 23:46:25 +00001902 assert(llvm::isPowerOf2_64(NewAlignment.getQuantity()) &&
1903 "Alignment not a power of 2");
Ken Dyck85ef0432011-02-19 18:58:07 +00001904 Alignment = NewAlignment;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001905 }
1906
Ken Dyck85ef0432011-02-19 18:58:07 +00001907 if (UnpackedNewAlignment > UnpackedAlignment) {
Reid Kleckner5a63d702015-03-24 23:46:25 +00001908 assert(llvm::isPowerOf2_64(UnpackedNewAlignment.getQuantity()) &&
1909 "Alignment not a power of 2");
Ken Dyck85ef0432011-02-19 18:58:07 +00001910 UnpackedAlignment = UnpackedNewAlignment;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001911 }
1912}
1913
Douglas Gregor44ba7892012-01-28 00:53:29 +00001914uint64_t
David Majnemer3b1c9902015-07-25 20:18:14 +00001915ItaniumRecordLayoutBuilder::updateExternalFieldOffset(const FieldDecl *Field,
1916 uint64_t ComputedOffset) {
Reid Kleckner8b6d0342015-02-25 19:17:45 +00001917 uint64_t ExternalFieldOffset = External.getExternalFieldOffset(Field);
NAKAMURA Takumi472041f2015-02-25 10:32:20 +00001918
Douglas Gregor44ba7892012-01-28 00:53:29 +00001919 if (InferAlignment && ExternalFieldOffset < ComputedOffset) {
1920 // The externally-supplied field offset is before the field offset we
1921 // computed. Assume that the structure is packed.
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001922 Alignment = CharUnits::One();
Douglas Gregor44ba7892012-01-28 00:53:29 +00001923 InferAlignment = false;
1924 }
1925
1926 // Use the externally-supplied field offset.
Benjamin Kramer648e68b2012-08-31 22:14:25 +00001927 return ExternalFieldOffset;
1928}
1929
1930/// \brief Get diagnostic %select index for tag kind for
1931/// field padding diagnostic message.
1932/// WARNING: Indexes apply to particular diagnostics only!
1933///
1934/// \returns diagnostic %select index.
1935static unsigned getPaddingDiagFromTagKind(TagTypeKind Tag) {
1936 switch (Tag) {
1937 case TTK_Struct: return 0;
1938 case TTK_Interface: return 1;
1939 case TTK_Class: return 2;
1940 default: llvm_unreachable("Invalid tag kind for field padding diagnostic!");
1941 }
1942}
1943
David Majnemer3b1c9902015-07-25 20:18:14 +00001944void ItaniumRecordLayoutBuilder::CheckFieldPadding(
1945 uint64_t Offset, uint64_t UnpaddedOffset, uint64_t UnpackedOffset,
1946 unsigned UnpackedAlign, bool isPacked, const FieldDecl *D) {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001947 // We let objc ivars without warning, objc interfaces generally are not used
1948 // for padding tricks.
1949 if (isa<ObjCIvarDecl>(D))
Anders Carlsson79474332009-07-18 20:20:21 +00001950 return;
Mike Stump11289f42009-09-09 15:08:12 +00001951
Ted Kremenekfed48af2011-09-06 19:40:45 +00001952 // Don't warn about structs created without a SourceLocation. This can
1953 // be done by clients of the AST, such as codegen.
1954 if (D->getLocation().isInvalid())
1955 return;
1956
Douglas Gregore8bbc122011-09-02 00:18:52 +00001957 unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
Mike Stump11289f42009-09-09 15:08:12 +00001958
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001959 // Warn if padding was introduced to the struct/class.
1960 if (!IsUnion && Offset > UnpaddedOffset) {
1961 unsigned PadSize = Offset - UnpaddedOffset;
1962 bool InBits = true;
1963 if (PadSize % CharBitNum == 0) {
1964 PadSize = PadSize / CharBitNum;
1965 InBits = false;
Benjamin Kramer648e68b2012-08-31 22:14:25 +00001966 }
1967 if (D->getIdentifier())
1968 Diag(D->getLocation(), diag::warn_padded_struct_field)
1969 << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
1970 << Context.getTypeDeclType(D->getParent())
1971 << PadSize
Benjamin Kramerc06b6bd2015-08-21 12:51:01 +00001972 << (InBits ? 1 : 0) // (byte|bit)
Benjamin Kramer648e68b2012-08-31 22:14:25 +00001973 << D->getIdentifier();
1974 else
1975 Diag(D->getLocation(), diag::warn_padded_struct_anon_field)
1976 << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
1977 << Context.getTypeDeclType(D->getParent())
1978 << PadSize
Benjamin Kramerc06b6bd2015-08-21 12:51:01 +00001979 << (InBits ? 1 : 0); // (byte|bit)
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001980 }
1981
1982 // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
1983 // bother since there won't be alignment issues.
1984 if (isPacked && UnpackedAlign > CharBitNum && Offset == UnpackedOffset)
1985 Diag(D->getLocation(), diag::warn_unnecessary_packed)
1986 << D->getIdentifier();
Anders Carlsson79474332009-07-18 20:20:21 +00001987}
Mike Stump11289f42009-09-09 15:08:12 +00001988
John McCall6bd2a892013-01-25 22:31:03 +00001989static const CXXMethodDecl *computeKeyFunction(ASTContext &Context,
1990 const CXXRecordDecl *RD) {
Daniel Dunbarccabe482010-04-19 20:44:53 +00001991 // If a class isn't polymorphic it doesn't have a key function.
Anders Carlsson5ebf8b42009-12-07 04:35:11 +00001992 if (!RD->isPolymorphic())
Craig Topper36250ad2014-05-12 05:36:57 +00001993 return nullptr;
Eli Friedmanf2c79b62009-12-08 03:56:49 +00001994
Eli Friedman300f55d2011-06-10 21:53:06 +00001995 // A class that is not externally visible doesn't have a key function. (Or
Eli Friedmanf2c79b62009-12-08 03:56:49 +00001996 // at least, there's no point to assigning a key function to such a class;
1997 // this doesn't affect the ABI.)
Rafael Espindola3ae00052013-05-13 00:12:11 +00001998 if (!RD->isExternallyVisible())
Craig Topper36250ad2014-05-12 05:36:57 +00001999 return nullptr;
Eli Friedmanf2c79b62009-12-08 03:56:49 +00002000
Richard Smith750f5112014-03-24 23:54:09 +00002001 // Template instantiations don't have key functions per Itanium C++ ABI 5.2.6.
Argyrios Kyrtzidis8c64bbe2010-10-13 02:39:41 +00002002 // Same behavior as GCC.
2003 TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
2004 if (TSK == TSK_ImplicitInstantiation ||
Richard Smith750f5112014-03-24 23:54:09 +00002005 TSK == TSK_ExplicitInstantiationDeclaration ||
Argyrios Kyrtzidis8c64bbe2010-10-13 02:39:41 +00002006 TSK == TSK_ExplicitInstantiationDefinition)
Craig Topper36250ad2014-05-12 05:36:57 +00002007 return nullptr;
Argyrios Kyrtzidis8c64bbe2010-10-13 02:39:41 +00002008
John McCall6bd2a892013-01-25 22:31:03 +00002009 bool allowInlineFunctions =
2010 Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline();
2011
David Majnemerc964b4b2014-07-16 06:04:00 +00002012 for (const CXXMethodDecl *MD : RD->methods()) {
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00002013 if (!MD->isVirtual())
2014 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002015
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00002016 if (MD->isPure())
2017 continue;
Eli Friedmanf2c79b62009-12-08 03:56:49 +00002018
Anders Carlssonf98849e2009-12-02 17:15:43 +00002019 // Ignore implicit member functions, they are always marked as inline, but
2020 // they don't have a body until they're defined.
2021 if (MD->isImplicit())
2022 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002023
Douglas Gregora318efd2010-01-05 19:06:31 +00002024 if (MD->isInlineSpecified())
2025 continue;
Eli Friedman71a26d82009-12-06 20:50:05 +00002026
2027 if (MD->hasInlineBody())
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00002028 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002029
Benjamin Kramer4a902082012-08-03 15:43:22 +00002030 // Ignore inline deleted or defaulted functions.
Benjamin Kramer73d1be72012-08-03 08:39:58 +00002031 if (!MD->isUserProvided())
2032 continue;
2033
John McCall6bd2a892013-01-25 22:31:03 +00002034 // In certain ABIs, ignore functions with out-of-line inline definitions.
2035 if (!allowInlineFunctions) {
2036 const FunctionDecl *Def;
2037 if (MD->hasBody(Def) && Def->isInlineSpecified())
2038 continue;
2039 }
2040
Artem Belevich9b929462015-12-17 18:12:36 +00002041 if (Context.getLangOpts().CUDA) {
2042 // While compiler may see key method in this TU, during CUDA
2043 // compilation we should ignore methods that are not accessible
2044 // on this side of compilation.
2045 if (Context.getLangOpts().CUDAIsDevice) {
2046 // In device mode ignore methods without __device__ attribute.
2047 if (!MD->hasAttr<CUDADeviceAttr>())
2048 continue;
2049 } else {
2050 // In host mode ignore __device__-only methods.
2051 if (!MD->hasAttr<CUDAHostAttr>() && MD->hasAttr<CUDADeviceAttr>())
2052 continue;
2053 }
2054 }
2055
Reid Klecknerc2e3ba42015-08-10 19:39:01 +00002056 // If the key function is dllimport but the class isn't, then the class has
2057 // no key function. The DLL that exports the key function won't export the
2058 // vtable in this case.
2059 if (MD->hasAttr<DLLImportAttr>() && !RD->hasAttr<DLLImportAttr>())
2060 return nullptr;
2061
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00002062 // We found it.
2063 return MD;
2064 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002065
Craig Topper36250ad2014-05-12 05:36:57 +00002066 return nullptr;
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00002067}
2068
David Majnemer3b1c9902015-07-25 20:18:14 +00002069DiagnosticBuilder ItaniumRecordLayoutBuilder::Diag(SourceLocation Loc,
2070 unsigned DiagID) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +00002071 return Context.getDiagnostics().Report(Loc, DiagID);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002072}
2073
John McCall5c1f1d02013-01-29 01:14:22 +00002074/// Does the target C++ ABI require us to skip over the tail-padding
2075/// of the given class (considering it as a base class) when allocating
2076/// objects?
2077static bool mustSkipTailPadding(TargetCXXABI ABI, const CXXRecordDecl *RD) {
2078 switch (ABI.getTailPaddingUseRules()) {
2079 case TargetCXXABI::AlwaysUseTailPadding:
2080 return false;
2081
2082 case TargetCXXABI::UseTailPaddingUnlessPOD03:
2083 // FIXME: To the extent that this is meant to cover the Itanium ABI
2084 // rules, we should implement the restrictions about over-sized
2085 // bitfields:
2086 //
2087 // http://mentorembedded.github.com/cxx-abi/abi.html#POD :
2088 // In general, a type is considered a POD for the purposes of
2089 // layout if it is a POD type (in the sense of ISO C++
2090 // [basic.types]). However, a POD-struct or POD-union (in the
2091 // sense of ISO C++ [class]) with a bitfield member whose
2092 // declared width is wider than the declared type of the
2093 // bitfield is not a POD for the purpose of layout. Similarly,
2094 // an array type is not a POD for the purpose of layout if the
2095 // element type of the array is not a POD for the purpose of
2096 // layout.
2097 //
2098 // Where references to the ISO C++ are made in this paragraph,
2099 // the Technical Corrigendum 1 version of the standard is
2100 // intended.
2101 return RD->isPOD();
2102
2103 case TargetCXXABI::UseTailPaddingUnlessPOD11:
2104 // This is equivalent to RD->getTypeForDecl().isCXX11PODType(),
2105 // but with a lot of abstraction penalty stripped off. This does
2106 // assume that these properties are set correctly even in C++98
2107 // mode; fortunately, that is true because we want to assign
2108 // consistently semantics to the type-traits intrinsics (or at
2109 // least as many of them as possible).
2110 return RD->isTrivial() && RD->isStandardLayout();
2111 }
2112
2113 llvm_unreachable("bad tail-padding use kind");
2114}
2115
David Majnemer3b1c9902015-07-25 20:18:14 +00002116static bool isMsLayout(const ASTContext &Context) {
2117 return Context.getTargetInfo().getCXXABI().isMicrosoft();
Warren Hunt8f8bad72013-10-11 20:19:00 +00002118}
2119
2120// This section contains an implementation of struct layout that is, up to the
Warren Hunt917f97f2014-04-11 00:54:15 +00002121// included tests, compatible with cl.exe (2013). The layout produced is
Warren Hunt8f8bad72013-10-11 20:19:00 +00002122// significantly different than those produced by the Itanium ABI. Here we note
2123// the most important differences.
2124//
2125// * The alignment of bitfields in unions is ignored when computing the
2126// alignment of the union.
Alp Tokerf6a24ce2013-12-05 16:25:25 +00002127// * The existence of zero-width bitfield that occurs after anything other than
Warren Hunt8f8bad72013-10-11 20:19:00 +00002128// a non-zero length bitfield is ignored.
Warren Hunt917f97f2014-04-11 00:54:15 +00002129// * There is no explicit primary base for the purposes of layout. All bases
2130// with vfptrs are laid out first, followed by all bases without vfptrs.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002131// * The Itanium equivalent vtable pointers are split into a vfptr (virtual
2132// function pointer) and a vbptr (virtual base pointer). They can each be
Warren Hunt55d8e822013-10-23 23:53:07 +00002133// shared with a, non-virtual bases. These bases need not be the same. vfptrs
Warren Hunt917f97f2014-04-11 00:54:15 +00002134// always occur at offset 0. vbptrs can occur at an arbitrary offset and are
David Majnemer07639702016-02-12 19:21:02 +00002135// placed after the lexicographically last non-virtual base. This placement
Warren Hunt917f97f2014-04-11 00:54:15 +00002136// is always before fields but can be in the middle of the non-virtual bases
2137// due to the two-pass layout scheme for non-virtual-bases.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002138// * Virtual bases sometimes require a 'vtordisp' field that is laid out before
2139// the virtual base and is used in conjunction with virtual overrides during
Warren Hunt917f97f2014-04-11 00:54:15 +00002140// construction and destruction. This is always a 4 byte value and is used as
2141// an alternative to constructor vtables.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002142// * vtordisps are allocated in a block of memory with size and alignment equal
2143// to the alignment of the completed structure (before applying __declspec(
Warren Hunt55d8e822013-10-23 23:53:07 +00002144// align())). The vtordisp always occur at the end of the allocation block,
2145// immediately prior to the virtual base.
Warren Hunt917f97f2014-04-11 00:54:15 +00002146// * vfptrs are injected after all bases and fields have been laid out. In
2147// order to guarantee proper alignment of all fields, the vfptr injection
2148// pushes all bases and fields back by the alignment imposed by those bases
2149// and fields. This can potentially add a significant amount of padding.
2150// vfptrs are always injected at offset 0.
2151// * vbptrs are injected after all bases and fields have been laid out. In
2152// order to guarantee proper alignment of all fields, the vfptr injection
2153// pushes all bases and fields back by the alignment imposed by those bases
2154// and fields. This can potentially add a significant amount of padding.
2155// vbptrs are injected immediately after the last non-virtual base as
David Majnemer07639702016-02-12 19:21:02 +00002156// lexicographically ordered in the code. If this site isn't pointer aligned
Warren Hunt917f97f2014-04-11 00:54:15 +00002157// the vbptr is placed at the next properly aligned location. Enough padding
2158// is added to guarantee a fit.
2159// * The last zero sized non-virtual base can be placed at the end of the
2160// struct (potentially aliasing another object), or may alias with the first
2161// field, even if they are of the same type.
2162// * The last zero size virtual base may be placed at the end of the struct
2163// potentially aliasing another object.
Warren Hunt049f6732013-12-06 19:54:25 +00002164// * The ABI attempts to avoid aliasing of zero sized bases by adding padding
2165// between bases or vbases with specific properties. The criteria for
2166// additional padding between two bases is that the first base is zero sized
Warren Hunt39a907b2014-04-09 21:57:24 +00002167// or ends with a zero sized subobject and the second base is zero sized or
Warren Hunt917f97f2014-04-11 00:54:15 +00002168// trails with a zero sized base or field (sharing of vfptrs can reorder the
2169// layout of the so the leading base is not always the first one declared).
2170// This rule does take into account fields that are not records, so padding
2171// will occur even if the last field is, e.g. an int. The padding added for
2172// bases is 1 byte. The padding added between vbases depends on the alignment
2173// of the object but is at least 4 bytes (in both 32 and 64 bit modes).
2174// * There is no concept of non-virtual alignment, non-virtual alignment and
2175// alignment are always identical.
2176// * There is a distinction between alignment and required alignment.
2177// __declspec(align) changes the required alignment of a struct. This
2178// alignment is _always_ obeyed, even in the presence of #pragma pack. A
Justin Bogner2ca9a4a2014-10-08 05:45:39 +00002179// record inherits required alignment from all of its fields and bases.
Warren Huntf4518def2014-01-10 01:28:05 +00002180// * __declspec(align) on bitfields has the effect of changing the bitfield's
Warren Hunt917f97f2014-04-11 00:54:15 +00002181// alignment instead of its required alignment. This is the only known way
2182// to make the alignment of a struct bigger than 8. Interestingly enough
2183// this alignment is also immune to the effects of #pragma pack and can be
2184// used to create structures with large alignment under #pragma pack.
2185// However, because it does not impact required alignment, such a structure,
2186// when used as a field or base, will not be aligned if #pragma pack is
2187// still active at the time of use.
2188//
Alp Toker08f6e9e2014-05-05 19:53:42 +00002189// Known incompatibilities:
Warren Hunt917f97f2014-04-11 00:54:15 +00002190// * all: #pragma pack between fields in a record
2191// * 2010 and back: If the last field in a record is a bitfield, every object
2192// laid out after the record will have extra padding inserted before it. The
2193// extra padding will have size equal to the size of the storage class of the
2194// bitfield. 0 sized bitfields don't exhibit this behavior and the extra
2195// padding can be avoided by adding a 0 sized bitfield after the non-zero-
2196// sized bitfield.
2197// * 2012 and back: In 64-bit mode, if the alignment of a record is 16 or
2198// greater due to __declspec(align()) then a second layout phase occurs after
2199// The locations of the vf and vb pointers are known. This layout phase
2200// suffers from the "last field is a bitfield" bug in 2010 and results in
2201// _every_ field getting padding put in front of it, potentially including the
2202// vfptr, leaving the vfprt at a non-zero location which results in a fault if
2203// anything tries to read the vftbl. The second layout phase also treats
Alp Toker08f6e9e2014-05-05 19:53:42 +00002204// bitfields as separate entities and gives them each storage rather than
Warren Hunt917f97f2014-04-11 00:54:15 +00002205// packing them. Additionally, because this phase appears to perform a
2206// (an unstable) sort on the members before laying them out and because merged
2207// bitfields have the same address, the bitfields end up in whatever order
2208// the sort left them in, a behavior we could never hope to replicate.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002209
2210namespace {
2211struct MicrosoftRecordLayoutBuilder {
Warren Huntd640d7d2014-01-09 00:30:56 +00002212 struct ElementInfo {
2213 CharUnits Size;
2214 CharUnits Alignment;
2215 };
Warren Hunt8f8bad72013-10-11 20:19:00 +00002216 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
2217 MicrosoftRecordLayoutBuilder(const ASTContext &Context) : Context(Context) {}
2218private:
Aaron Ballmanabc18922015-02-15 22:54:08 +00002219 MicrosoftRecordLayoutBuilder(const MicrosoftRecordLayoutBuilder &) = delete;
2220 void operator=(const MicrosoftRecordLayoutBuilder &) = delete;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002221public:
Warren Hunt8f8bad72013-10-11 20:19:00 +00002222 void layout(const RecordDecl *RD);
2223 void cxxLayout(const CXXRecordDecl *RD);
2224 /// \brief Initializes size and alignment and honors some flags.
2225 void initializeLayout(const RecordDecl *RD);
2226 /// \brief Initialized C++ layout, compute alignment and virtual alignment and
Alp Tokerf6a24ce2013-12-05 16:25:25 +00002227 /// existence of vfptrs and vbptrs. Alignment is needed before the vfptr is
Warren Hunt8f8bad72013-10-11 20:19:00 +00002228 /// laid out.
2229 void initializeCXXLayout(const CXXRecordDecl *RD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002230 void layoutNonVirtualBases(const CXXRecordDecl *RD);
Warren Huntd640d7d2014-01-09 00:30:56 +00002231 void layoutNonVirtualBase(const CXXRecordDecl *BaseDecl,
2232 const ASTRecordLayout &BaseLayout,
2233 const ASTRecordLayout *&PreviousBaseLayout);
2234 void injectVFPtr(const CXXRecordDecl *RD);
2235 void injectVBPtr(const CXXRecordDecl *RD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002236 /// \brief Lays out the fields of the record. Also rounds size up to
2237 /// alignment.
2238 void layoutFields(const RecordDecl *RD);
2239 void layoutField(const FieldDecl *FD);
2240 void layoutBitField(const FieldDecl *FD);
2241 /// \brief Lays out a single zero-width bit-field in the record and handles
2242 /// special cases associated with zero-width bit-fields.
2243 void layoutZeroWidthBitField(const FieldDecl *FD);
2244 void layoutVirtualBases(const CXXRecordDecl *RD);
Warren Hunt1603e522013-12-10 01:44:39 +00002245 void finalizeLayout(const RecordDecl *RD);
Warren Huntd640d7d2014-01-09 00:30:56 +00002246 /// \brief Gets the size and alignment of a base taking pragma pack and
2247 /// __declspec(align) into account.
Warren Hunt5d9eebf2014-04-10 22:15:18 +00002248 ElementInfo getAdjustedElementInfo(const ASTRecordLayout &Layout);
Warren Huntd640d7d2014-01-09 00:30:56 +00002249 /// \brief Gets the size and alignment of a field taking pragma pack and
2250 /// __declspec(align) into account. It also updates RequiredAlignment as a
2251 /// side effect because it is most convenient to do so here.
2252 ElementInfo getAdjustedElementInfo(const FieldDecl *FD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002253 /// \brief Places a field at an offset in CharUnits.
2254 void placeFieldAtOffset(CharUnits FieldOffset) {
2255 FieldOffsets.push_back(Context.toBits(FieldOffset));
2256 }
2257 /// \brief Places a bitfield at a bit offset.
2258 void placeFieldAtBitOffset(uint64_t FieldOffset) {
2259 FieldOffsets.push_back(FieldOffset);
2260 }
2261 /// \brief Compute the set of virtual bases for which vtordisps are required.
David Majnemerc2e67532014-09-23 22:58:15 +00002262 void computeVtorDispSet(
2263 llvm::SmallPtrSetImpl<const CXXRecordDecl *> &HasVtorDispSet,
2264 const CXXRecordDecl *RD) const;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002265 const ASTContext &Context;
2266 /// \brief The size of the record being laid out.
2267 CharUnits Size;
Warren Huntf6ec7482014-02-21 01:40:35 +00002268 /// \brief The non-virtual size of the record layout.
2269 CharUnits NonVirtualSize;
2270 /// \brief The data size of the record layout.
Warren Huntd640d7d2014-01-09 00:30:56 +00002271 CharUnits DataSize;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002272 /// \brief The current alignment of the record layout.
2273 CharUnits Alignment;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002274 /// \brief The maximum allowed field alignment. This is set by #pragma pack.
2275 CharUnits MaxFieldAlignment;
Warren Hunt7b252d22013-12-06 00:01:17 +00002276 /// \brief The alignment that this record must obey. This is imposed by
2277 /// __declspec(align()) on the record itself or one of its fields or bases.
2278 CharUnits RequiredAlignment;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002279 /// \brief The size of the allocation of the currently active bitfield.
2280 /// This value isn't meaningful unless LastFieldIsNonZeroWidthBitfield
2281 /// is true.
2282 CharUnits CurrentBitfieldSize;
Warren Huntd640d7d2014-01-09 00:30:56 +00002283 /// \brief Offset to the virtual base table pointer (if one exists).
2284 CharUnits VBPtrOffset;
David Majnemer00a061d2014-09-30 06:45:43 +00002285 /// \brief Minimum record size possible.
2286 CharUnits MinEmptyStructSize;
Warren Huntd640d7d2014-01-09 00:30:56 +00002287 /// \brief The size and alignment info of a pointer.
2288 ElementInfo PointerInfo;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002289 /// \brief The primary base class (if one exists).
2290 const CXXRecordDecl *PrimaryBase;
2291 /// \brief The class we share our vb-pointer with.
2292 const CXXRecordDecl *SharedVBPtrBase;
Warren Huntd640d7d2014-01-09 00:30:56 +00002293 /// \brief The collection of field offsets.
2294 SmallVector<uint64_t, 16> FieldOffsets;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002295 /// \brief Base classes and their offsets in the record.
2296 BaseOffsetsMapTy Bases;
2297 /// \brief virtual base classes and their offsets in the record.
2298 ASTRecordLayout::VBaseOffsetsMapTy VBases;
Warren Huntd640d7d2014-01-09 00:30:56 +00002299 /// \brief The number of remaining bits in our last bitfield allocation.
2300 /// This value isn't meaningful unless LastFieldIsNonZeroWidthBitfield is
2301 /// true.
2302 unsigned RemainingBitsInField;
2303 bool IsUnion : 1;
2304 /// \brief True if the last field laid out was a bitfield and was not 0
2305 /// width.
2306 bool LastFieldIsNonZeroWidthBitfield : 1;
2307 /// \brief True if the class has its own vftable pointer.
2308 bool HasOwnVFPtr : 1;
2309 /// \brief True if the class has a vbtable pointer.
2310 bool HasVBPtr : 1;
Warren Hunt39a907b2014-04-09 21:57:24 +00002311 /// \brief True if the last sub-object within the type is zero sized or the
2312 /// object itself is zero sized. This *does not* count members that are not
2313 /// records. Only used for MS-ABI.
2314 bool EndsWithZeroSizedObject : 1;
Warren Hunt049f6732013-12-06 19:54:25 +00002315 /// \brief True if this class is zero sized or first base is zero sized or
2316 /// has this property. Only used for MS-ABI.
2317 bool LeadsWithZeroSizedBase : 1;
Reid Kleckner8b6d0342015-02-25 19:17:45 +00002318
2319 /// \brief True if the external AST source provided a layout for this record.
2320 bool UseExternalLayout : 1;
2321
2322 /// \brief The layout provided by the external AST source. Only active if
2323 /// UseExternalLayout is true.
2324 ExternalLayout External;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002325};
2326} // namespace
2327
Warren Huntd640d7d2014-01-09 00:30:56 +00002328MicrosoftRecordLayoutBuilder::ElementInfo
2329MicrosoftRecordLayoutBuilder::getAdjustedElementInfo(
Warren Hunt5d9eebf2014-04-10 22:15:18 +00002330 const ASTRecordLayout &Layout) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002331 ElementInfo Info;
2332 Info.Alignment = Layout.getAlignment();
2333 // Respect pragma pack.
Warren Hunt7b252d22013-12-06 00:01:17 +00002334 if (!MaxFieldAlignment.isZero())
Warren Huntd640d7d2014-01-09 00:30:56 +00002335 Info.Alignment = std::min(Info.Alignment, MaxFieldAlignment);
2336 // Track zero-sized subobjects here where it's already available.
Warren Hunt39a907b2014-04-09 21:57:24 +00002337 EndsWithZeroSizedObject = Layout.hasZeroSizedSubObject();
Warren Huntd640d7d2014-01-09 00:30:56 +00002338 // Respect required alignment, this is necessary because we may have adjusted
Warren Hunt94258912014-01-11 01:16:40 +00002339 // the alignment in the case of pragam pack. Note that the required alignment
2340 // doesn't actually apply to the struct alignment at this point.
2341 Alignment = std::max(Alignment, Info.Alignment);
Warren Hunt5d9eebf2014-04-10 22:15:18 +00002342 RequiredAlignment = std::max(RequiredAlignment, Layout.getRequiredAlignment());
Warren Huntd640d7d2014-01-09 00:30:56 +00002343 Info.Alignment = std::max(Info.Alignment, Layout.getRequiredAlignment());
Warren Hunt5d9eebf2014-04-10 22:15:18 +00002344 Info.Size = Layout.getNonVirtualSize();
Warren Huntd640d7d2014-01-09 00:30:56 +00002345 return Info;
Warren Hunt7b252d22013-12-06 00:01:17 +00002346}
2347
Warren Huntd640d7d2014-01-09 00:30:56 +00002348MicrosoftRecordLayoutBuilder::ElementInfo
2349MicrosoftRecordLayoutBuilder::getAdjustedElementInfo(
2350 const FieldDecl *FD) {
David Majnemer34b57492014-07-30 01:30:47 +00002351 // Get the alignment of the field type's natural alignment, ignore any
2352 // alignment attributes.
Warren Huntd640d7d2014-01-09 00:30:56 +00002353 ElementInfo Info;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002354 std::tie(Info.Size, Info.Alignment) =
David Majnemer34b57492014-07-30 01:30:47 +00002355 Context.getTypeInfoInChars(FD->getType()->getUnqualifiedDesugaredType());
2356 // Respect align attributes on the field.
2357 CharUnits FieldRequiredAlignment =
Warren Huntf4518def2014-01-10 01:28:05 +00002358 Context.toCharUnitsFromBits(FD->getMaxAlignment());
David Majnemer34b57492014-07-30 01:30:47 +00002359 // Respect align attributes on the type.
2360 if (Context.isAlignmentRequired(FD->getType()))
2361 FieldRequiredAlignment = std::max(
2362 Context.getTypeAlignInChars(FD->getType()), FieldRequiredAlignment);
Warren Hunt049f6732013-12-06 19:54:25 +00002363 // Respect attributes applied to subobjects of the field.
Warren Hunt5d9eebf2014-04-10 22:15:18 +00002364 if (FD->isBitField())
2365 // For some reason __declspec align impacts alignment rather than required
2366 // alignment when it is applied to bitfields.
Warren Huntf4518def2014-01-10 01:28:05 +00002367 Info.Alignment = std::max(Info.Alignment, FieldRequiredAlignment);
Warren Hunt5d9eebf2014-04-10 22:15:18 +00002368 else {
2369 if (auto RT =
2370 FD->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
2371 auto const &Layout = Context.getASTRecordLayout(RT->getDecl());
2372 EndsWithZeroSizedObject = Layout.hasZeroSizedSubObject();
2373 FieldRequiredAlignment = std::max(FieldRequiredAlignment,
2374 Layout.getRequiredAlignment());
2375 }
Warren Huntf4518def2014-01-10 01:28:05 +00002376 // Capture required alignment as a side-effect.
2377 RequiredAlignment = std::max(RequiredAlignment, FieldRequiredAlignment);
2378 }
Warren Hunt5d9eebf2014-04-10 22:15:18 +00002379 // Respect pragma pack, attribute pack and declspec align
2380 if (!MaxFieldAlignment.isZero())
2381 Info.Alignment = std::min(Info.Alignment, MaxFieldAlignment);
2382 if (FD->hasAttr<PackedAttr>())
2383 Info.Alignment = CharUnits::One();
2384 Info.Alignment = std::max(Info.Alignment, FieldRequiredAlignment);
Warren Huntd640d7d2014-01-09 00:30:56 +00002385 return Info;
2386}
2387
2388void MicrosoftRecordLayoutBuilder::layout(const RecordDecl *RD) {
David Majnemer00a061d2014-09-30 06:45:43 +00002389 // For C record layout, zero-sized records always have size 4.
2390 MinEmptyStructSize = CharUnits::fromQuantity(4);
Warren Huntd640d7d2014-01-09 00:30:56 +00002391 initializeLayout(RD);
2392 layoutFields(RD);
Rui Ueyama83aa9792016-01-14 21:00:27 +00002393 DataSize = Size = Size.alignTo(Alignment);
David Majnemer79a1c892014-02-12 00:43:02 +00002394 RequiredAlignment = std::max(
2395 RequiredAlignment, Context.toCharUnitsFromBits(RD->getMaxAlignment()));
Warren Huntd640d7d2014-01-09 00:30:56 +00002396 finalizeLayout(RD);
2397}
2398
2399void MicrosoftRecordLayoutBuilder::cxxLayout(const CXXRecordDecl *RD) {
David Majnemer00a061d2014-09-30 06:45:43 +00002400 // The C++ standard says that empty structs have size 1.
2401 MinEmptyStructSize = CharUnits::One();
Warren Huntd640d7d2014-01-09 00:30:56 +00002402 initializeLayout(RD);
2403 initializeCXXLayout(RD);
2404 layoutNonVirtualBases(RD);
2405 layoutFields(RD);
Warren Huntc89450e2014-03-24 21:37:27 +00002406 injectVBPtr(RD);
2407 injectVFPtr(RD);
2408 if (HasOwnVFPtr || (HasVBPtr && !SharedVBPtrBase))
2409 Alignment = std::max(Alignment, PointerInfo.Alignment);
Warren Hunt5d9eebf2014-04-10 22:15:18 +00002410 auto RoundingAlignment = Alignment;
2411 if (!MaxFieldAlignment.isZero())
2412 RoundingAlignment = std::min(RoundingAlignment, MaxFieldAlignment);
Rui Ueyama83aa9792016-01-14 21:00:27 +00002413 NonVirtualSize = Size = Size.alignTo(RoundingAlignment);
David Majnemer79a1c892014-02-12 00:43:02 +00002414 RequiredAlignment = std::max(
2415 RequiredAlignment, Context.toCharUnitsFromBits(RD->getMaxAlignment()));
Warren Huntd640d7d2014-01-09 00:30:56 +00002416 layoutVirtualBases(RD);
2417 finalizeLayout(RD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002418}
2419
2420void MicrosoftRecordLayoutBuilder::initializeLayout(const RecordDecl *RD) {
2421 IsUnion = RD->isUnion();
Warren Hunt8f8bad72013-10-11 20:19:00 +00002422 Size = CharUnits::Zero();
2423 Alignment = CharUnits::One();
Warren Hunt7b252d22013-12-06 00:01:17 +00002424 // In 64-bit mode we always perform an alignment step after laying out vbases.
2425 // In 32-bit mode we do not. The check to see if we need to perform alignment
2426 // checks the RequiredAlignment field and performs alignment if it isn't 0.
David Majnemer37ea5782015-04-24 01:24:59 +00002427 RequiredAlignment = Context.getTargetInfo().getTriple().isArch64Bit()
2428 ? CharUnits::One()
2429 : CharUnits::Zero();
Warren Hunt8f8bad72013-10-11 20:19:00 +00002430 // Compute the maximum field alignment.
2431 MaxFieldAlignment = CharUnits::Zero();
2432 // Honor the default struct packing maximum alignment flag.
2433 if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct)
Warren Huntf4518def2014-01-10 01:28:05 +00002434 MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
2435 // Honor the packing attribute. The MS-ABI ignores pragma pack if its larger
2436 // than the pointer size.
2437 if (const MaxFieldAlignmentAttr *MFAA = RD->getAttr<MaxFieldAlignmentAttr>()){
2438 unsigned PackedAlignment = MFAA->getAlignment();
2439 if (PackedAlignment <= Context.getTargetInfo().getPointerWidth(0))
2440 MaxFieldAlignment = Context.toCharUnitsFromBits(PackedAlignment);
2441 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002442 // Packed attribute forces max field alignment to be 1.
2443 if (RD->hasAttr<PackedAttr>())
2444 MaxFieldAlignment = CharUnits::One();
Reid Kleckner8b6d0342015-02-25 19:17:45 +00002445
2446 // Try to respect the external layout if present.
2447 UseExternalLayout = false;
2448 if (ExternalASTSource *Source = Context.getExternalSource())
2449 UseExternalLayout = Source->layoutRecordType(
2450 RD, External.Size, External.Align, External.FieldOffsets,
2451 External.BaseOffsets, External.VirtualBaseOffsets);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002452}
2453
Warren Hunt8f8bad72013-10-11 20:19:00 +00002454void
2455MicrosoftRecordLayoutBuilder::initializeCXXLayout(const CXXRecordDecl *RD) {
Warren Hunt39a907b2014-04-09 21:57:24 +00002456 EndsWithZeroSizedObject = false;
Warren Hunt049f6732013-12-06 19:54:25 +00002457 LeadsWithZeroSizedBase = false;
Warren Huntd640d7d2014-01-09 00:30:56 +00002458 HasOwnVFPtr = false;
2459 HasVBPtr = false;
Craig Topper36250ad2014-05-12 05:36:57 +00002460 PrimaryBase = nullptr;
2461 SharedVBPtrBase = nullptr;
Warren Huntd640d7d2014-01-09 00:30:56 +00002462 // Calculate pointer size and alignment. These are used for vfptr and vbprt
2463 // injection.
2464 PointerInfo.Size =
2465 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
David Majnemer37ea5782015-04-24 01:24:59 +00002466 PointerInfo.Alignment =
2467 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0));
Warren Huntd640d7d2014-01-09 00:30:56 +00002468 // Respect pragma pack.
2469 if (!MaxFieldAlignment.isZero())
2470 PointerInfo.Alignment = std::min(PointerInfo.Alignment, MaxFieldAlignment);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002471}
2472
2473void
2474MicrosoftRecordLayoutBuilder::layoutNonVirtualBases(const CXXRecordDecl *RD) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002475 // The MS-ABI lays out all bases that contain leading vfptrs before it lays
2476 // out any bases that do not contain vfptrs. We implement this as two passes
2477 // over the bases. This approach guarantees that the primary base is laid out
2478 // first. We use these passes to calculate some additional aggregated
David Majnemer07639702016-02-12 19:21:02 +00002479 // information about the bases, such as required alignment and the presence of
Warren Huntd640d7d2014-01-09 00:30:56 +00002480 // zero sized members.
Craig Topper36250ad2014-05-12 05:36:57 +00002481 const ASTRecordLayout *PreviousBaseLayout = nullptr;
Warren Huntd640d7d2014-01-09 00:30:56 +00002482 // Iterate through the bases and lay out the non-virtual ones.
David Majnemerc964b4b2014-07-16 06:04:00 +00002483 for (const CXXBaseSpecifier &Base : RD->bases()) {
2484 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
Warren Huntd640d7d2014-01-09 00:30:56 +00002485 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
Warren Huntd640d7d2014-01-09 00:30:56 +00002486 // Mark and skip virtual bases.
David Majnemerc964b4b2014-07-16 06:04:00 +00002487 if (Base.isVirtual()) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002488 HasVBPtr = true;
2489 continue;
2490 }
David Majnemer07639702016-02-12 19:21:02 +00002491 // Check for a base to share a VBPtr with.
Warren Huntd640d7d2014-01-09 00:30:56 +00002492 if (!SharedVBPtrBase && BaseLayout.hasVBPtr()) {
2493 SharedVBPtrBase = BaseDecl;
2494 HasVBPtr = true;
2495 }
2496 // Only lay out bases with extendable VFPtrs on the first pass.
2497 if (!BaseLayout.hasExtendableVFPtr())
2498 continue;
2499 // If we don't have a primary base, this one qualifies.
Warren Huntbadf9e02014-01-13 19:55:52 +00002500 if (!PrimaryBase) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002501 PrimaryBase = BaseDecl;
Warren Huntbadf9e02014-01-13 19:55:52 +00002502 LeadsWithZeroSizedBase = BaseLayout.leadsWithZeroSizedBase();
2503 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002504 // Lay out the base.
2505 layoutNonVirtualBase(BaseDecl, BaseLayout, PreviousBaseLayout);
2506 }
2507 // Figure out if we need a fresh VFPtr for this class.
2508 if (!PrimaryBase && RD->isDynamicClass())
2509 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
2510 e = RD->method_end();
2511 !HasOwnVFPtr && i != e; ++i)
2512 HasOwnVFPtr = i->isVirtual() && i->size_overridden_methods() == 0;
2513 // If we don't have a primary base then we have a leading object that could
2514 // itself lead with a zero-sized object, something we track.
2515 bool CheckLeadingLayout = !PrimaryBase;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002516 // Iterate through the bases and lay out the non-virtual ones.
David Majnemerc964b4b2014-07-16 06:04:00 +00002517 for (const CXXBaseSpecifier &Base : RD->bases()) {
2518 if (Base.isVirtual())
Warren Hunt8f8bad72013-10-11 20:19:00 +00002519 continue;
David Majnemerc964b4b2014-07-16 06:04:00 +00002520 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
Warren Huntd640d7d2014-01-09 00:30:56 +00002521 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
2522 // Only lay out bases without extendable VFPtrs on the second pass.
Warren Huntbb9c3c32014-04-10 23:23:34 +00002523 if (BaseLayout.hasExtendableVFPtr()) {
2524 VBPtrOffset = Bases[BaseDecl] + BaseLayout.getNonVirtualSize();
Warren Hunt4431fe62013-12-12 22:33:37 +00002525 continue;
Warren Huntbb9c3c32014-04-10 23:23:34 +00002526 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002527 // If this is the first layout, check to see if it leads with a zero sized
2528 // object. If it does, so do we.
2529 if (CheckLeadingLayout) {
2530 CheckLeadingLayout = false;
2531 LeadsWithZeroSizedBase = BaseLayout.leadsWithZeroSizedBase();
Warren Hunt049f6732013-12-06 19:54:25 +00002532 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002533 // Lay out the base.
2534 layoutNonVirtualBase(BaseDecl, BaseLayout, PreviousBaseLayout);
Warren Huntbb9c3c32014-04-10 23:23:34 +00002535 VBPtrOffset = Bases[BaseDecl] + BaseLayout.getNonVirtualSize();
Warren Hunt8f8bad72013-10-11 20:19:00 +00002536 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002537 // Set our VBPtroffset if we know it at this point.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002538 if (!HasVBPtr)
2539 VBPtrOffset = CharUnits::fromQuantity(-1);
Warren Hunt6eba9072014-01-14 00:31:30 +00002540 else if (SharedVBPtrBase) {
2541 const ASTRecordLayout &Layout = Context.getASTRecordLayout(SharedVBPtrBase);
2542 VBPtrOffset = Bases[SharedVBPtrBase] + Layout.getVBPtrOffset();
2543 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002544}
2545
2546void MicrosoftRecordLayoutBuilder::layoutNonVirtualBase(
2547 const CXXRecordDecl *BaseDecl,
2548 const ASTRecordLayout &BaseLayout,
2549 const ASTRecordLayout *&PreviousBaseLayout) {
Warren Huntf4518def2014-01-10 01:28:05 +00002550 // Insert padding between two bases if the left first one is zero sized or
2551 // contains a zero sized subobject and the right is zero sized or one leads
2552 // with a zero sized base.
2553 if (PreviousBaseLayout && PreviousBaseLayout->hasZeroSizedSubObject() &&
2554 BaseLayout.leadsWithZeroSizedBase())
2555 Size++;
2556 ElementInfo Info = getAdjustedElementInfo(BaseLayout);
Reid Kleckner8b6d0342015-02-25 19:17:45 +00002557 CharUnits BaseOffset;
2558
2559 // Respect the external AST source base offset, if present.
2560 bool FoundBase = false;
2561 if (UseExternalLayout) {
2562 FoundBase = External.getExternalNVBaseOffset(BaseDecl, BaseOffset);
2563 if (FoundBase)
2564 assert(BaseOffset >= Size && "base offset already allocated");
2565 }
2566
2567 if (!FoundBase)
Rui Ueyama83aa9792016-01-14 21:00:27 +00002568 BaseOffset = Size.alignTo(Info.Alignment);
Warren Huntf4518def2014-01-10 01:28:05 +00002569 Bases.insert(std::make_pair(BaseDecl, BaseOffset));
Warren Huntf6ec7482014-02-21 01:40:35 +00002570 Size = BaseOffset + BaseLayout.getNonVirtualSize();
Warren Huntf4518def2014-01-10 01:28:05 +00002571 PreviousBaseLayout = &BaseLayout;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002572}
2573
2574void MicrosoftRecordLayoutBuilder::layoutFields(const RecordDecl *RD) {
2575 LastFieldIsNonZeroWidthBitfield = false;
David Majnemerc964b4b2014-07-16 06:04:00 +00002576 for (const FieldDecl *Field : RD->fields())
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002577 layoutField(Field);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002578}
2579
2580void MicrosoftRecordLayoutBuilder::layoutField(const FieldDecl *FD) {
2581 if (FD->isBitField()) {
2582 layoutBitField(FD);
2583 return;
2584 }
2585 LastFieldIsNonZeroWidthBitfield = false;
Warren Huntd640d7d2014-01-09 00:30:56 +00002586 ElementInfo Info = getAdjustedElementInfo(FD);
David Majnemeradc45bb2014-04-13 08:15:50 +00002587 Alignment = std::max(Alignment, Info.Alignment);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002588 if (IsUnion) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002589 placeFieldAtOffset(CharUnits::Zero());
2590 Size = std::max(Size, Info.Size);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002591 } else {
Reid Kleckner8b6d0342015-02-25 19:17:45 +00002592 CharUnits FieldOffset;
2593 if (UseExternalLayout) {
2594 FieldOffset =
2595 Context.toCharUnitsFromBits(External.getExternalFieldOffset(FD));
2596 assert(FieldOffset >= Size && "field offset already allocated");
2597 } else {
Rui Ueyama83aa9792016-01-14 21:00:27 +00002598 FieldOffset = Size.alignTo(Info.Alignment);
Reid Kleckner8b6d0342015-02-25 19:17:45 +00002599 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002600 placeFieldAtOffset(FieldOffset);
Warren Huntd640d7d2014-01-09 00:30:56 +00002601 Size = FieldOffset + Info.Size;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002602 }
2603}
2604
2605void MicrosoftRecordLayoutBuilder::layoutBitField(const FieldDecl *FD) {
2606 unsigned Width = FD->getBitWidthValue(Context);
2607 if (Width == 0) {
2608 layoutZeroWidthBitField(FD);
2609 return;
2610 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002611 ElementInfo Info = getAdjustedElementInfo(FD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002612 // Clamp the bitfield to a containable size for the sake of being able
2613 // to lay them out. Sema will throw an error.
Warren Huntd640d7d2014-01-09 00:30:56 +00002614 if (Width > Context.toBits(Info.Size))
2615 Width = Context.toBits(Info.Size);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002616 // Check to see if this bitfield fits into an existing allocation. Note:
2617 // MSVC refuses to pack bitfields of formal types with different sizes
2618 // into the same allocation.
2619 if (!IsUnion && LastFieldIsNonZeroWidthBitfield &&
Warren Huntd640d7d2014-01-09 00:30:56 +00002620 CurrentBitfieldSize == Info.Size && Width <= RemainingBitsInField) {
Warren Hunt8f8bad72013-10-11 20:19:00 +00002621 placeFieldAtBitOffset(Context.toBits(Size) - RemainingBitsInField);
2622 RemainingBitsInField -= Width;
2623 return;
2624 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002625 LastFieldIsNonZeroWidthBitfield = true;
Warren Huntd640d7d2014-01-09 00:30:56 +00002626 CurrentBitfieldSize = Info.Size;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002627 if (IsUnion) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002628 placeFieldAtOffset(CharUnits::Zero());
2629 Size = std::max(Size, Info.Size);
David Majnemeradc45bb2014-04-13 08:15:50 +00002630 // TODO: Add a Sema warning that MS ignores bitfield alignment in unions.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002631 } else {
2632 // Allocate a new block of memory and place the bitfield in it.
Rui Ueyama83aa9792016-01-14 21:00:27 +00002633 CharUnits FieldOffset = Size.alignTo(Info.Alignment);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002634 placeFieldAtOffset(FieldOffset);
Warren Huntd640d7d2014-01-09 00:30:56 +00002635 Size = FieldOffset + Info.Size;
David Majnemeradc45bb2014-04-13 08:15:50 +00002636 Alignment = std::max(Alignment, Info.Alignment);
Warren Huntd640d7d2014-01-09 00:30:56 +00002637 RemainingBitsInField = Context.toBits(Info.Size) - Width;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002638 }
2639}
2640
2641void
2642MicrosoftRecordLayoutBuilder::layoutZeroWidthBitField(const FieldDecl *FD) {
2643 // Zero-width bitfields are ignored unless they follow a non-zero-width
2644 // bitfield.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002645 if (!LastFieldIsNonZeroWidthBitfield) {
2646 placeFieldAtOffset(IsUnion ? CharUnits::Zero() : Size);
2647 // TODO: Add a Sema warning that MS ignores alignment for zero
Alp Tokerd4733632013-12-05 04:47:09 +00002648 // sized bitfields that occur after zero-size bitfields or non-bitfields.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002649 return;
2650 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002651 LastFieldIsNonZeroWidthBitfield = false;
Warren Huntd640d7d2014-01-09 00:30:56 +00002652 ElementInfo Info = getAdjustedElementInfo(FD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002653 if (IsUnion) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002654 placeFieldAtOffset(CharUnits::Zero());
2655 Size = std::max(Size, Info.Size);
David Majnemeradc45bb2014-04-13 08:15:50 +00002656 // TODO: Add a Sema warning that MS ignores bitfield alignment in unions.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002657 } else {
2658 // Round up the current record size to the field's alignment boundary.
Rui Ueyama83aa9792016-01-14 21:00:27 +00002659 CharUnits FieldOffset = Size.alignTo(Info.Alignment);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002660 placeFieldAtOffset(FieldOffset);
2661 Size = FieldOffset;
David Majnemeradc45bb2014-04-13 08:15:50 +00002662 Alignment = std::max(Alignment, Info.Alignment);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002663 }
2664}
2665
Warren Huntd640d7d2014-01-09 00:30:56 +00002666void MicrosoftRecordLayoutBuilder::injectVBPtr(const CXXRecordDecl *RD) {
Warren Hunt6eba9072014-01-14 00:31:30 +00002667 if (!HasVBPtr || SharedVBPtrBase)
Warren Huntd640d7d2014-01-09 00:30:56 +00002668 return;
Warren Huntd640d7d2014-01-09 00:30:56 +00002669 // Inject the VBPointer at the injection site.
2670 CharUnits InjectionSite = VBPtrOffset;
2671 // But before we do, make sure it's properly aligned.
Rui Ueyama83aa9792016-01-14 21:00:27 +00002672 VBPtrOffset = VBPtrOffset.alignTo(PointerInfo.Alignment);
Reid Kleckner8b6d0342015-02-25 19:17:45 +00002673 // Shift everything after the vbptr down, unless we're using an external
2674 // layout.
2675 if (UseExternalLayout)
2676 return;
Warren Huntd640d7d2014-01-09 00:30:56 +00002677 // Determine where the first field should be laid out after the vbptr.
2678 CharUnits FieldStart = VBPtrOffset + PointerInfo.Size;
2679 // Make sure that the amount we push the fields back by is a multiple of the
2680 // alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00002681 CharUnits Offset = (FieldStart - InjectionSite)
2682 .alignTo(std::max(RequiredAlignment, Alignment));
Warren Huntd640d7d2014-01-09 00:30:56 +00002683 Size += Offset;
David Majnemerc964b4b2014-07-16 06:04:00 +00002684 for (uint64_t &FieldOffset : FieldOffsets)
2685 FieldOffset += Context.toBits(Offset);
2686 for (BaseOffsetsMapTy::value_type &Base : Bases)
2687 if (Base.second >= InjectionSite)
2688 Base.second += Offset;
Warren Huntd640d7d2014-01-09 00:30:56 +00002689}
2690
2691void MicrosoftRecordLayoutBuilder::injectVFPtr(const CXXRecordDecl *RD) {
2692 if (!HasOwnVFPtr)
2693 return;
2694 // Make sure that the amount we push the struct back by is a multiple of the
2695 // alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00002696 CharUnits Offset =
2697 PointerInfo.Size.alignTo(std::max(RequiredAlignment, Alignment));
Zachary Turnerf686a442015-10-01 22:08:02 +00002698 // Push back the vbptr, but increase the size of the object and push back
2699 // regular fields by the offset only if not using external record layout.
Warren Huntd640d7d2014-01-09 00:30:56 +00002700 if (HasVBPtr)
2701 VBPtrOffset += Offset;
Zachary Turnerf686a442015-10-01 22:08:02 +00002702
2703 if (UseExternalLayout)
2704 return;
2705
2706 Size += Offset;
2707
2708 // If we're using an external layout, the fields offsets have already
2709 // accounted for this adjustment.
2710 for (uint64_t &FieldOffset : FieldOffsets)
2711 FieldOffset += Context.toBits(Offset);
David Majnemerc964b4b2014-07-16 06:04:00 +00002712 for (BaseOffsetsMapTy::value_type &Base : Bases)
2713 Base.second += Offset;
Warren Huntd640d7d2014-01-09 00:30:56 +00002714}
2715
Warren Hunt8f8bad72013-10-11 20:19:00 +00002716void MicrosoftRecordLayoutBuilder::layoutVirtualBases(const CXXRecordDecl *RD) {
2717 if (!HasVBPtr)
2718 return;
Warren Huntd640d7d2014-01-09 00:30:56 +00002719 // Vtordisps are always 4 bytes (even in 64-bit mode)
2720 CharUnits VtorDispSize = CharUnits::fromQuantity(4);
2721 CharUnits VtorDispAlignment = VtorDispSize;
2722 // vtordisps respect pragma pack.
2723 if (!MaxFieldAlignment.isZero())
2724 VtorDispAlignment = std::min(VtorDispAlignment, MaxFieldAlignment);
2725 // The alignment of the vtordisp is at least the required alignment of the
2726 // entire record. This requirement may be present to support vtordisp
2727 // injection.
David Majnemerc964b4b2014-07-16 06:04:00 +00002728 for (const CXXBaseSpecifier &VBase : RD->vbases()) {
2729 const CXXRecordDecl *BaseDecl = VBase.getType()->getAsCXXRecordDecl();
David Majnemer79a1c892014-02-12 00:43:02 +00002730 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
2731 RequiredAlignment =
2732 std::max(RequiredAlignment, BaseLayout.getRequiredAlignment());
2733 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002734 VtorDispAlignment = std::max(VtorDispAlignment, RequiredAlignment);
2735 // Compute the vtordisp set.
David Majnemerc2e67532014-09-23 22:58:15 +00002736 llvm::SmallPtrSet<const CXXRecordDecl *, 2> HasVtorDispSet;
2737 computeVtorDispSet(HasVtorDispSet, RD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002738 // Iterate through the virtual bases and lay them out.
Craig Topper36250ad2014-05-12 05:36:57 +00002739 const ASTRecordLayout *PreviousBaseLayout = nullptr;
David Majnemerc964b4b2014-07-16 06:04:00 +00002740 for (const CXXBaseSpecifier &VBase : RD->vbases()) {
2741 const CXXRecordDecl *BaseDecl = VBase.getType()->getAsCXXRecordDecl();
Warren Huntd640d7d2014-01-09 00:30:56 +00002742 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
David Majnemerc2e67532014-09-23 22:58:15 +00002743 bool HasVtordisp = HasVtorDispSet.count(BaseDecl) > 0;
Warren Huntd640d7d2014-01-09 00:30:56 +00002744 // Insert padding between two bases if the left first one is zero sized or
2745 // contains a zero sized subobject and the right is zero sized or one leads
2746 // with a zero sized base. The padding between virtual bases is 4
2747 // bytes (in both 32 and 64 bits modes) and always involves rounding up to
2748 // the required alignment, we don't know why.
Warren Hunt4f7efb72014-04-12 00:20:50 +00002749 if ((PreviousBaseLayout && PreviousBaseLayout->hasZeroSizedSubObject() &&
David Majnemerbf3d4302014-07-16 07:16:58 +00002750 BaseLayout.leadsWithZeroSizedBase()) || HasVtordisp) {
Rui Ueyama83aa9792016-01-14 21:00:27 +00002751 Size = Size.alignTo(VtorDispAlignment) + VtorDispSize;
David Majnemera2464682014-07-17 00:55:19 +00002752 Alignment = std::max(VtorDispAlignment, Alignment);
David Majnemerbf3d4302014-07-16 07:16:58 +00002753 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002754 // Insert the virtual base.
2755 ElementInfo Info = getAdjustedElementInfo(BaseLayout);
Reid Kleckner8b6d0342015-02-25 19:17:45 +00002756 CharUnits BaseOffset;
2757
2758 // Respect the external AST source base offset, if present.
2759 bool FoundBase = false;
2760 if (UseExternalLayout) {
2761 FoundBase = External.getExternalVBaseOffset(BaseDecl, BaseOffset);
2762 if (FoundBase)
2763 assert(BaseOffset >= Size && "base offset already allocated");
2764 }
2765 if (!FoundBase)
Rui Ueyama83aa9792016-01-14 21:00:27 +00002766 BaseOffset = Size.alignTo(Info.Alignment);
Reid Kleckner8b6d0342015-02-25 19:17:45 +00002767
Warren Huntd640d7d2014-01-09 00:30:56 +00002768 VBases.insert(std::make_pair(BaseDecl,
2769 ASTRecordLayout::VBaseInfo(BaseOffset, HasVtordisp)));
Warren Huntf6ec7482014-02-21 01:40:35 +00002770 Size = BaseOffset + BaseLayout.getNonVirtualSize();
Warren Huntd640d7d2014-01-09 00:30:56 +00002771 PreviousBaseLayout = &BaseLayout;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002772 }
2773}
2774
Warren Huntc3384312013-12-11 22:28:32 +00002775void MicrosoftRecordLayoutBuilder::finalizeLayout(const RecordDecl *RD) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002776 // Respect required alignment. Note that in 32-bit mode Required alignment
David Majnemer00a061d2014-09-30 06:45:43 +00002777 // may be 0 and cause size not to be updated.
Warren Huntf6ec7482014-02-21 01:40:35 +00002778 DataSize = Size;
Warren Huntd640d7d2014-01-09 00:30:56 +00002779 if (!RequiredAlignment.isZero()) {
2780 Alignment = std::max(Alignment, RequiredAlignment);
Warren Hunt5d9eebf2014-04-10 22:15:18 +00002781 auto RoundingAlignment = Alignment;
2782 if (!MaxFieldAlignment.isZero())
2783 RoundingAlignment = std::min(RoundingAlignment, MaxFieldAlignment);
2784 RoundingAlignment = std::max(RoundingAlignment, RequiredAlignment);
Rui Ueyama83aa9792016-01-14 21:00:27 +00002785 Size = Size.alignTo(RoundingAlignment);
Warren Huntd640d7d2014-01-09 00:30:56 +00002786 }
Warren Hunt049f6732013-12-06 19:54:25 +00002787 if (Size.isZero()) {
Warren Hunt39a907b2014-04-09 21:57:24 +00002788 EndsWithZeroSizedObject = true;
Warren Hunt049f6732013-12-06 19:54:25 +00002789 LeadsWithZeroSizedBase = true;
David Majnemer00a061d2014-09-30 06:45:43 +00002790 // Zero-sized structures have size equal to their alignment if a
2791 // __declspec(align) came into play.
2792 if (RequiredAlignment >= MinEmptyStructSize)
2793 Size = Alignment;
2794 else
2795 Size = MinEmptyStructSize;
Warren Hunt049f6732013-12-06 19:54:25 +00002796 }
Reid Kleckner8b6d0342015-02-25 19:17:45 +00002797
2798 if (UseExternalLayout) {
2799 Size = Context.toCharUnitsFromBits(External.Size);
2800 if (External.Align)
2801 Alignment = Context.toCharUnitsFromBits(External.Align);
2802 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002803}
2804
Warren Hunt73f43982014-04-11 22:05:28 +00002805// Recursively walks the non-virtual bases of a class and determines if any of
2806// them are in the bases with overridden methods set.
David Majnemer12727642014-07-16 06:30:31 +00002807static bool
2808RequiresVtordisp(const llvm::SmallPtrSetImpl<const CXXRecordDecl *> &
2809 BasesWithOverriddenMethods,
2810 const CXXRecordDecl *RD) {
Warren Hunt73f43982014-04-11 22:05:28 +00002811 if (BasesWithOverriddenMethods.count(RD))
Warren Hunt8f8bad72013-10-11 20:19:00 +00002812 return true;
2813 // If any of a virtual bases non-virtual bases (recursively) requires a
2814 // vtordisp than so does this virtual base.
David Majnemerc964b4b2014-07-16 06:04:00 +00002815 for (const CXXBaseSpecifier &Base : RD->bases())
2816 if (!Base.isVirtual() &&
Warren Hunt73f43982014-04-11 22:05:28 +00002817 RequiresVtordisp(BasesWithOverriddenMethods,
David Majnemerc964b4b2014-07-16 06:04:00 +00002818 Base.getType()->getAsCXXRecordDecl()))
Warren Hunt8f8bad72013-10-11 20:19:00 +00002819 return true;
2820 return false;
2821}
2822
David Majnemerc2e67532014-09-23 22:58:15 +00002823void MicrosoftRecordLayoutBuilder::computeVtorDispSet(
2824 llvm::SmallPtrSetImpl<const CXXRecordDecl *> &HasVtordispSet,
2825 const CXXRecordDecl *RD) const {
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00002826 // /vd2 or #pragma vtordisp(2): Always use vtordisps for virtual bases with
2827 // vftables.
2828 if (RD->getMSVtorDispMode() == MSVtorDispAttr::ForVFTable) {
David Majnemerc964b4b2014-07-16 06:04:00 +00002829 for (const CXXBaseSpecifier &Base : RD->vbases()) {
2830 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00002831 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
2832 if (Layout.hasExtendableVFPtr())
2833 HasVtordispSet.insert(BaseDecl);
2834 }
David Majnemerc2e67532014-09-23 22:58:15 +00002835 return;
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00002836 }
2837
Warren Hunt8f8bad72013-10-11 20:19:00 +00002838 // If any of our bases need a vtordisp for this type, so do we. Check our
2839 // direct bases for vtordisp requirements.
David Majnemerc964b4b2014-07-16 06:04:00 +00002840 for (const CXXBaseSpecifier &Base : RD->bases()) {
2841 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
Warren Hunt8f8bad72013-10-11 20:19:00 +00002842 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
Reid Klecknercd612ab2014-04-11 16:57:42 +00002843 for (const auto &bi : Layout.getVBaseOffsetsMap())
2844 if (bi.second.hasVtorDisp())
2845 HasVtordispSet.insert(bi.first);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002846 }
David Majnemerd43388c2014-04-13 02:27:32 +00002847 // We don't introduce any additional vtordisps if either:
2848 // * A user declared constructor or destructor aren't declared.
2849 // * #pragma vtordisp(0) or the /vd0 flag are in use.
2850 if ((!RD->hasUserDeclaredConstructor() && !RD->hasUserDeclaredDestructor()) ||
2851 RD->getMSVtorDispMode() == MSVtorDispAttr::Never)
David Majnemerc2e67532014-09-23 22:58:15 +00002852 return;
David Majnemerd43388c2014-04-13 02:27:32 +00002853 // /vd1 or #pragma vtordisp(1): Try to guess based on whether we think it's
2854 // possible for a partially constructed object with virtual base overrides to
2855 // escape a non-trivial constructor.
2856 assert(RD->getMSVtorDispMode() == MSVtorDispAttr::ForVBaseOverride);
Warren Hunt73f43982014-04-11 22:05:28 +00002857 // Compute a set of base classes which define methods we override. A virtual
2858 // base in this set will require a vtordisp. A virtual base that transitively
2859 // contains one of these bases as a non-virtual base will also require a
2860 // vtordisp.
2861 llvm::SmallPtrSet<const CXXMethodDecl *, 8> Work;
2862 llvm::SmallPtrSet<const CXXRecordDecl *, 2> BasesWithOverriddenMethods;
David Majnemerc2e67532014-09-23 22:58:15 +00002863 // Seed the working set with our non-destructor, non-pure virtual methods.
David Majnemerc964b4b2014-07-16 06:04:00 +00002864 for (const CXXMethodDecl *MD : RD->methods())
David Majnemerc2e67532014-09-23 22:58:15 +00002865 if (MD->isVirtual() && !isa<CXXDestructorDecl>(MD) && !MD->isPure())
David Majnemerc964b4b2014-07-16 06:04:00 +00002866 Work.insert(MD);
Warren Hunt73f43982014-04-11 22:05:28 +00002867 while (!Work.empty()) {
2868 const CXXMethodDecl *MD = *Work.begin();
2869 CXXMethodDecl::method_iterator i = MD->begin_overridden_methods(),
2870 e = MD->end_overridden_methods();
2871 // If a virtual method has no-overrides it lives in its parent's vtable.
2872 if (i == e)
2873 BasesWithOverriddenMethods.insert(MD->getParent());
2874 else
2875 Work.insert(i, e);
2876 // We've finished processing this element, remove it from the working set.
2877 Work.erase(MD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002878 }
Warren Hunt73f43982014-04-11 22:05:28 +00002879 // For each of our virtual bases, check if it is in the set of overridden
2880 // bases or if it transitively contains a non-virtual base that is.
David Majnemerc964b4b2014-07-16 06:04:00 +00002881 for (const CXXBaseSpecifier &Base : RD->vbases()) {
2882 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
Warren Huntd640d7d2014-01-09 00:30:56 +00002883 if (!HasVtordispSet.count(BaseDecl) &&
Warren Hunt73f43982014-04-11 22:05:28 +00002884 RequiresVtordisp(BasesWithOverriddenMethods, BaseDecl))
Warren Huntd640d7d2014-01-09 00:30:56 +00002885 HasVtordispSet.insert(BaseDecl);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002886 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002887}
2888
Anders Carlssondf291d82010-05-26 04:56:53 +00002889/// getASTRecordLayout - Get or compute information about the layout of the
2890/// specified record (struct/union/class), which indicates its size and field
2891/// position information.
Jay Foad39c79802011-01-12 09:06:06 +00002892const ASTRecordLayout &
2893ASTContext::getASTRecordLayout(const RecordDecl *D) const {
John McCall0710e552011-10-07 02:39:22 +00002894 // These asserts test different things. A record has a definition
2895 // as soon as we begin to parse the definition. That definition is
2896 // not a complete definition (which is what isDefinition() tests)
2897 // until we *finish* parsing the definition.
Sean Callanan56c19892012-02-08 00:04:52 +00002898
2899 if (D->hasExternalLexicalStorage() && !D->getDefinition())
2900 getExternalSource()->CompleteType(const_cast<RecordDecl*>(D));
2901
Anders Carlssondf291d82010-05-26 04:56:53 +00002902 D = D->getDefinition();
2903 assert(D && "Cannot get layout of forward declarations!");
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00002904 assert(!D->isInvalidDecl() && "Cannot get layout of invalid decl!");
John McCallf937c022011-10-07 06:10:15 +00002905 assert(D->isCompleteDefinition() && "Cannot layout type before complete!");
Anders Carlssondf291d82010-05-26 04:56:53 +00002906
2907 // Look up this layout, if already laid out, return what we have.
2908 // Note that we can't save a reference to the entry because this function
2909 // is recursive.
2910 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
2911 if (Entry) return *Entry;
2912
Craig Topper36250ad2014-05-12 05:36:57 +00002913 const ASTRecordLayout *NewEntry = nullptr;
Anders Carlssond2954862010-05-26 05:10:47 +00002914
David Majnemer3b1c9902015-07-25 20:18:14 +00002915 if (isMsLayout(*this)) {
2916 MicrosoftRecordLayoutBuilder Builder(*this);
2917 if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
2918 Builder.cxxLayout(RD);
2919 NewEntry = new (*this) ASTRecordLayout(
2920 *this, Builder.Size, Builder.Alignment, Builder.RequiredAlignment,
2921 Builder.HasOwnVFPtr, Builder.HasOwnVFPtr || Builder.PrimaryBase,
2922 Builder.VBPtrOffset, Builder.NonVirtualSize,
2923 Builder.FieldOffsets.data(), Builder.FieldOffsets.size(),
2924 Builder.NonVirtualSize, Builder.Alignment, CharUnits::Zero(),
2925 Builder.PrimaryBase, false, Builder.SharedVBPtrBase,
2926 Builder.EndsWithZeroSizedObject, Builder.LeadsWithZeroSizedBase,
2927 Builder.Bases, Builder.VBases);
2928 } else {
2929 Builder.layout(D);
2930 NewEntry = new (*this) ASTRecordLayout(
2931 *this, Builder.Size, Builder.Alignment, Builder.RequiredAlignment,
2932 Builder.Size, Builder.FieldOffsets.data(),
2933 Builder.FieldOffsets.size());
2934 }
Anders Carlssond2954862010-05-26 05:10:47 +00002935 } else {
David Majnemer3b1c9902015-07-25 20:18:14 +00002936 if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
2937 EmptySubobjectMap EmptySubobjects(*this, RD);
2938 ItaniumRecordLayoutBuilder Builder(*this, &EmptySubobjects);
2939 Builder.Layout(RD);
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002940
David Majnemer3b1c9902015-07-25 20:18:14 +00002941 // In certain situations, we are allowed to lay out objects in the
2942 // tail-padding of base classes. This is ABI-dependent.
2943 // FIXME: this should be stored in the record layout.
2944 bool skipTailPadding =
2945 mustSkipTailPadding(getTargetInfo().getCXXABI(), RD);
2946
2947 // FIXME: This should be done in FinalizeLayout.
2948 CharUnits DataSize =
2949 skipTailPadding ? Builder.getSize() : Builder.getDataSize();
2950 CharUnits NonVirtualSize =
2951 skipTailPadding ? DataSize : Builder.NonVirtualSize;
2952 NewEntry = new (*this) ASTRecordLayout(
2953 *this, Builder.getSize(), Builder.Alignment,
2954 /*RequiredAlignment : used by MS-ABI)*/
2955 Builder.Alignment, Builder.HasOwnVFPtr, RD->isDynamicClass(),
2956 CharUnits::fromQuantity(-1), DataSize, Builder.FieldOffsets.data(),
2957 Builder.FieldOffsets.size(), NonVirtualSize,
2958 Builder.NonVirtualAlignment,
2959 EmptySubobjects.SizeOfLargestEmptySubobject, Builder.PrimaryBase,
2960 Builder.PrimaryBaseIsVirtual, nullptr, false, false, Builder.Bases,
2961 Builder.VBases);
2962 } else {
2963 ItaniumRecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/nullptr);
2964 Builder.Layout(D);
2965
2966 NewEntry = new (*this) ASTRecordLayout(
2967 *this, Builder.getSize(), Builder.Alignment,
2968 /*RequiredAlignment : used by MS-ABI)*/
2969 Builder.Alignment, Builder.getSize(), Builder.FieldOffsets.data(),
2970 Builder.FieldOffsets.size());
2971 }
Anders Carlssond2954862010-05-26 05:10:47 +00002972 }
2973
Anders Carlssondf291d82010-05-26 04:56:53 +00002974 ASTRecordLayouts[D] = NewEntry;
2975
David Blaikiebbafb8a2012-03-11 07:00:24 +00002976 if (getLangOpts().DumpRecordLayouts) {
Argyrios Kyrtzidis8ade08e2013-07-12 22:30:03 +00002977 llvm::outs() << "\n*** Dumping AST Record Layout\n";
2978 DumpRecordLayout(D, llvm::outs(), getLangOpts().DumpRecordLayoutsSimple);
Anders Carlssondf291d82010-05-26 04:56:53 +00002979 }
2980
2981 return *NewEntry;
2982}
2983
John McCall6bd2a892013-01-25 22:31:03 +00002984const CXXMethodDecl *ASTContext::getCurrentKeyFunction(const CXXRecordDecl *RD) {
Reid Kleckner5d7f2982013-05-29 16:18:30 +00002985 if (!getTargetInfo().getCXXABI().hasKeyFunctions())
Craig Topper36250ad2014-05-12 05:36:57 +00002986 return nullptr;
Reid Kleckner5d7f2982013-05-29 16:18:30 +00002987
John McCall6bd2a892013-01-25 22:31:03 +00002988 assert(RD->getDefinition() && "Cannot get key function for forward decl!");
Anders Carlssondf291d82010-05-26 04:56:53 +00002989 RD = cast<CXXRecordDecl>(RD->getDefinition());
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002990
Richard Smitha9a1c682014-07-07 06:38:20 +00002991 // Beware:
2992 // 1) computing the key function might trigger deserialization, which might
2993 // invalidate iterators into KeyFunctions
2994 // 2) 'get' on the LazyDeclPtr might also trigger deserialization and
2995 // invalidate the LazyDeclPtr within the map itself
2996 LazyDeclPtr Entry = KeyFunctions[RD];
2997 const Decl *Result =
2998 Entry ? Entry.get(getExternalSource()) : computeKeyFunction(*this, RD);
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002999
Richard Smitha9a1c682014-07-07 06:38:20 +00003000 // Store it back if it changed.
3001 if (Entry.isOffset() || Entry.isValid() != bool(Result))
3002 KeyFunctions[RD] = const_cast<Decl*>(Result);
3003
3004 return cast_or_null<CXXMethodDecl>(Result);
John McCall6bd2a892013-01-25 22:31:03 +00003005}
3006
Richard Smith676c4042013-08-29 23:59:27 +00003007void ASTContext::setNonKeyFunction(const CXXMethodDecl *Method) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00003008 assert(Method == Method->getFirstDecl() &&
John McCall6bd2a892013-01-25 22:31:03 +00003009 "not working with method declaration from class definition");
3010
3011 // Look up the cache entry. Since we're working with the first
3012 // declaration, its parent must be the class definition, which is
3013 // the correct key for the KeyFunctions hash.
Reid Klecknerb4a26ed2015-05-21 00:12:53 +00003014 const auto &Map = KeyFunctions;
3015 auto I = Map.find(Method->getParent());
John McCall6bd2a892013-01-25 22:31:03 +00003016
3017 // If it's not cached, there's nothing to do.
Reid Klecknerb4a26ed2015-05-21 00:12:53 +00003018 if (I == Map.end()) return;
John McCall6bd2a892013-01-25 22:31:03 +00003019
3020 // If it is cached, check whether it's the target method, and if so,
Richard Smitha9a1c682014-07-07 06:38:20 +00003021 // remove it from the cache. Note, the call to 'get' might invalidate
3022 // the iterator and the LazyDeclPtr object within the map.
3023 LazyDeclPtr Ptr = I->second;
3024 if (Ptr.get(getExternalSource()) == Method) {
John McCall6bd2a892013-01-25 22:31:03 +00003025 // FIXME: remember that we did this for module / chained PCH state?
Richard Smitha9a1c682014-07-07 06:38:20 +00003026 KeyFunctions.erase(Method->getParent());
John McCall6bd2a892013-01-25 22:31:03 +00003027 }
Anders Carlssondf291d82010-05-26 04:56:53 +00003028}
3029
Richard Smithdafff942012-01-14 04:30:29 +00003030static uint64_t getFieldOffset(const ASTContext &C, const FieldDecl *FD) {
3031 const ASTRecordLayout &Layout = C.getASTRecordLayout(FD->getParent());
3032 return Layout.getFieldOffset(FD->getFieldIndex());
3033}
3034
3035uint64_t ASTContext::getFieldOffset(const ValueDecl *VD) const {
3036 uint64_t OffsetInBits;
3037 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
3038 OffsetInBits = ::getFieldOffset(*this, FD);
3039 } else {
3040 const IndirectFieldDecl *IFD = cast<IndirectFieldDecl>(VD);
3041
3042 OffsetInBits = 0;
David Majnemerc964b4b2014-07-16 06:04:00 +00003043 for (const NamedDecl *ND : IFD->chain())
3044 OffsetInBits += ::getFieldOffset(*this, cast<FieldDecl>(ND));
Richard Smithdafff942012-01-14 04:30:29 +00003045 }
3046
3047 return OffsetInBits;
3048}
3049
Eric Christopher8a39a012011-10-05 06:00:51 +00003050/// getObjCLayout - Get or compute information about the layout of the
3051/// given interface.
Anders Carlssondf291d82010-05-26 04:56:53 +00003052///
3053/// \param Impl - If given, also include the layout of the interface's
3054/// implementation. This may differ by including synthesized ivars.
3055const ASTRecordLayout &
3056ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
Jay Foad39c79802011-01-12 09:06:06 +00003057 const ObjCImplementationDecl *Impl) const {
Douglas Gregor64d92572011-12-20 15:50:13 +00003058 // Retrieve the definition
Sean Callanand9a909c2012-03-15 16:33:08 +00003059 if (D->hasExternalLexicalStorage() && !D->getDefinition())
3060 getExternalSource()->CompleteType(const_cast<ObjCInterfaceDecl*>(D));
Douglas Gregor64d92572011-12-20 15:50:13 +00003061 D = D->getDefinition();
3062 assert(D && D->isThisDeclarationADefinition() && "Invalid interface decl!");
Anders Carlssondf291d82010-05-26 04:56:53 +00003063
3064 // Look up this layout, if already laid out, return what we have.
Roman Divackye6377112012-09-06 15:59:27 +00003065 const ObjCContainerDecl *Key =
3066 Impl ? (const ObjCContainerDecl*) Impl : (const ObjCContainerDecl*) D;
Anders Carlssondf291d82010-05-26 04:56:53 +00003067 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
3068 return *Entry;
3069
3070 // Add in synthesized ivar count if laying out an implementation.
3071 if (Impl) {
3072 unsigned SynthCount = CountNonClassIvars(D);
David Majnemer07639702016-02-12 19:21:02 +00003073 // If there aren't any synthesized ivars then reuse the interface
Anders Carlssondf291d82010-05-26 04:56:53 +00003074 // entry. Note we can't cache this because we simply free all
3075 // entries later; however we shouldn't look up implementations
3076 // frequently.
3077 if (SynthCount == 0)
Craig Topper36250ad2014-05-12 05:36:57 +00003078 return getObjCLayout(D, nullptr);
Anders Carlssondf291d82010-05-26 04:56:53 +00003079 }
3080
David Majnemer3b1c9902015-07-25 20:18:14 +00003081 ItaniumRecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/nullptr);
Anders Carlsson6ed3a9a2010-05-26 05:04:25 +00003082 Builder.Layout(D);
3083
Anders Carlssondf291d82010-05-26 04:56:53 +00003084 const ASTRecordLayout *NewEntry =
Ken Dyck1b4420e2011-02-28 02:01:38 +00003085 new (*this) ASTRecordLayout(*this, Builder.getSize(),
Ken Dyck4731d5b2011-02-16 02:05:21 +00003086 Builder.Alignment,
Warren Hunt7b252d22013-12-06 00:01:17 +00003087 /*RequiredAlignment : used by MS-ABI)*/
3088 Builder.Alignment,
Ken Dyck1b4420e2011-02-28 02:01:38 +00003089 Builder.getDataSize(),
Anders Carlsson6ed3a9a2010-05-26 05:04:25 +00003090 Builder.FieldOffsets.data(),
3091 Builder.FieldOffsets.size());
Daniel Dunbar592a85c2010-05-27 02:25:46 +00003092
Anders Carlssondf291d82010-05-26 04:56:53 +00003093 ObjCLayouts[Key] = NewEntry;
3094
3095 return *NewEntry;
3096}
3097
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003098static void PrintOffset(raw_ostream &OS,
Anders Carlsson3f018712010-10-31 23:45:59 +00003099 CharUnits Offset, unsigned IndentLevel) {
John McCall0d461692015-08-19 22:42:36 +00003100 OS << llvm::format("%10" PRId64 " | ", (int64_t)Offset.getQuantity());
3101 OS.indent(IndentLevel * 2);
3102}
3103
3104static void PrintBitFieldOffset(raw_ostream &OS, CharUnits Offset,
3105 unsigned Begin, unsigned Width,
3106 unsigned IndentLevel) {
3107 llvm::SmallString<10> Buffer;
3108 {
3109 llvm::raw_svector_ostream BufferOS(Buffer);
3110 BufferOS << Offset.getQuantity() << ':';
3111 if (Width == 0) {
3112 BufferOS << '-';
3113 } else {
3114 BufferOS << Begin << '-' << (Begin + Width - 1);
3115 }
3116 }
3117
3118 OS << llvm::right_justify(Buffer, 10) << " | ";
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003119 OS.indent(IndentLevel * 2);
3120}
3121
Eli Benderskyf6f93ee2012-12-08 00:07:24 +00003122static void PrintIndentNoOffset(raw_ostream &OS, unsigned IndentLevel) {
John McCall0d461692015-08-19 22:42:36 +00003123 OS << " | ";
Eli Benderskyf6f93ee2012-12-08 00:07:24 +00003124 OS.indent(IndentLevel * 2);
3125}
3126
John McCall0d461692015-08-19 22:42:36 +00003127static void DumpRecordLayout(raw_ostream &OS, const RecordDecl *RD,
3128 const ASTContext &C,
3129 CharUnits Offset,
3130 unsigned IndentLevel,
3131 const char* Description,
3132 bool PrintSizeInfo,
3133 bool IncludeVirtualBases) {
Anders Carlsson3f018712010-10-31 23:45:59 +00003134 const ASTRecordLayout &Layout = C.getASTRecordLayout(RD);
John McCall0d461692015-08-19 22:42:36 +00003135 auto CXXRD = dyn_cast<CXXRecordDecl>(RD);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003136
3137 PrintOffset(OS, Offset, IndentLevel);
John McCall0d461692015-08-19 22:42:36 +00003138 OS << C.getTypeDeclType(const_cast<RecordDecl*>(RD)).getAsString();
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003139 if (Description)
3140 OS << ' ' << Description;
John McCall0d461692015-08-19 22:42:36 +00003141 if (CXXRD && CXXRD->isEmpty())
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003142 OS << " (empty)";
3143 OS << '\n';
3144
3145 IndentLevel++;
3146
John McCall0d461692015-08-19 22:42:36 +00003147 // Dump bases.
3148 if (CXXRD) {
3149 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
3150 bool HasOwnVFPtr = Layout.hasOwnVFPtr();
3151 bool HasOwnVBPtr = Layout.hasOwnVBPtr();
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003152
John McCall0d461692015-08-19 22:42:36 +00003153 // Vtable pointer.
3154 if (CXXRD->isDynamicClass() && !PrimaryBase && !isMsLayout(C)) {
3155 PrintOffset(OS, Offset, IndentLevel);
3156 OS << '(' << *RD << " vtable pointer)\n";
3157 } else if (HasOwnVFPtr) {
3158 PrintOffset(OS, Offset, IndentLevel);
3159 // vfptr (for Microsoft C++ ABI)
3160 OS << '(' << *RD << " vftable pointer)\n";
3161 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00003162
John McCall0d461692015-08-19 22:42:36 +00003163 // Collect nvbases.
3164 SmallVector<const CXXRecordDecl *, 4> Bases;
3165 for (const CXXBaseSpecifier &Base : CXXRD->bases()) {
3166 assert(!Base.getType()->isDependentType() &&
3167 "Cannot layout class with dependent bases.");
3168 if (!Base.isVirtual())
3169 Bases.push_back(Base.getType()->getAsCXXRecordDecl());
3170 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003171
John McCall0d461692015-08-19 22:42:36 +00003172 // Sort nvbases by offset.
3173 std::stable_sort(Bases.begin(), Bases.end(),
3174 [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
3175 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
3176 });
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003177
John McCall0d461692015-08-19 22:42:36 +00003178 // Dump (non-virtual) bases
3179 for (const CXXRecordDecl *Base : Bases) {
3180 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base);
3181 DumpRecordLayout(OS, Base, C, BaseOffset, IndentLevel,
3182 Base == PrimaryBase ? "(primary base)" : "(base)",
3183 /*PrintSizeInfo=*/false,
3184 /*IncludeVirtualBases=*/false);
3185 }
Eli Friedman43114f92011-10-21 22:49:56 +00003186
John McCall0d461692015-08-19 22:42:36 +00003187 // vbptr (for Microsoft C++ ABI)
3188 if (HasOwnVBPtr) {
3189 PrintOffset(OS, Offset + Layout.getVBPtrOffset(), IndentLevel);
3190 OS << '(' << *RD << " vbtable pointer)\n";
3191 }
Eli Friedman84d2d3a2011-09-27 19:12:27 +00003192 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003193
3194 // Dump fields.
3195 uint64_t FieldNo = 0;
John McCall0d461692015-08-19 22:42:36 +00003196 for (RecordDecl::field_iterator I = RD->field_begin(),
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003197 E = RD->field_end(); I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +00003198 const FieldDecl &Field = **I;
John McCall0d461692015-08-19 22:42:36 +00003199 uint64_t LocalFieldOffsetInBits = Layout.getFieldOffset(FieldNo);
3200 CharUnits FieldOffset =
3201 Offset + C.toCharUnitsFromBits(LocalFieldOffsetInBits);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003202
John McCall0d461692015-08-19 22:42:36 +00003203 // Recursively dump fields of record type.
3204 if (auto RT = Field.getType()->getAs<RecordType>()) {
3205 DumpRecordLayout(OS, RT->getDecl(), C, FieldOffset, IndentLevel,
3206 Field.getName().data(),
3207 /*PrintSizeInfo=*/false,
3208 /*IncludeVirtualBases=*/true);
Reid Klecknercd612ab2014-04-11 16:57:42 +00003209 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003210 }
3211
John McCall0d461692015-08-19 22:42:36 +00003212 if (Field.isBitField()) {
3213 uint64_t LocalFieldByteOffsetInBits = C.toBits(FieldOffset - Offset);
3214 unsigned Begin = LocalFieldOffsetInBits - LocalFieldByteOffsetInBits;
3215 unsigned Width = Field.getBitWidthValue(C);
3216 PrintBitFieldOffset(OS, FieldOffset, Begin, Width, IndentLevel);
3217 } else {
3218 PrintOffset(OS, FieldOffset, IndentLevel);
3219 }
David Blaikie2d7c57e2012-04-30 02:36:29 +00003220 OS << Field.getType().getAsString() << ' ' << Field << '\n';
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003221 }
3222
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003223 // Dump virtual bases.
John McCall0d461692015-08-19 22:42:36 +00003224 if (CXXRD && IncludeVirtualBases) {
3225 const ASTRecordLayout::VBaseOffsetsMapTy &VtorDisps =
3226 Layout.getVBaseOffsetsMap();
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003227
John McCall0d461692015-08-19 22:42:36 +00003228 for (const CXXBaseSpecifier &Base : CXXRD->vbases()) {
3229 assert(Base.isVirtual() && "Found non-virtual class!");
3230 const CXXRecordDecl *VBase = Base.getType()->getAsCXXRecordDecl();
John McCalle42a3362012-05-01 08:55:32 +00003231
John McCall0d461692015-08-19 22:42:36 +00003232 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBase);
3233
3234 if (VtorDisps.find(VBase)->second.hasVtorDisp()) {
3235 PrintOffset(OS, VBaseOffset - CharUnits::fromQuantity(4), IndentLevel);
3236 OS << "(vtordisp for vbase " << *VBase << ")\n";
3237 }
3238
3239 DumpRecordLayout(OS, VBase, C, VBaseOffset, IndentLevel,
3240 VBase == Layout.getPrimaryBase() ?
3241 "(primary virtual base)" : "(virtual base)",
3242 /*PrintSizeInfo=*/false,
3243 /*IncludeVirtualBases=*/false);
John McCalle42a3362012-05-01 08:55:32 +00003244 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003245 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003246
John McCall0d461692015-08-19 22:42:36 +00003247 if (!PrintSizeInfo) return;
3248
Eli Benderskyf6f93ee2012-12-08 00:07:24 +00003249 PrintIndentNoOffset(OS, IndentLevel - 1);
3250 OS << "[sizeof=" << Layout.getSize().getQuantity();
John McCall0d461692015-08-19 22:42:36 +00003251 if (CXXRD && !isMsLayout(C))
Warren Hunt8f8bad72013-10-11 20:19:00 +00003252 OS << ", dsize=" << Layout.getDataSize().getQuantity();
John McCall0d461692015-08-19 22:42:36 +00003253 OS << ", align=" << Layout.getAlignment().getQuantity();
Eli Benderskyf6f93ee2012-12-08 00:07:24 +00003254
John McCall0d461692015-08-19 22:42:36 +00003255 if (CXXRD) {
3256 OS << ",\n";
3257 PrintIndentNoOffset(OS, IndentLevel - 1);
3258 OS << " nvsize=" << Layout.getNonVirtualSize().getQuantity();
3259 OS << ", nvalign=" << Layout.getNonVirtualAlignment().getQuantity();
3260 }
3261 OS << "]\n";
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003262}
Daniel Dunbarccabe482010-04-19 20:44:53 +00003263
3264void ASTContext::DumpRecordLayout(const RecordDecl *RD,
Douglas Gregore9fc3772012-01-26 07:55:45 +00003265 raw_ostream &OS,
3266 bool Simple) const {
Douglas Gregore9fc3772012-01-26 07:55:45 +00003267 if (!Simple) {
John McCall0d461692015-08-19 22:42:36 +00003268 ::DumpRecordLayout(OS, RD, *this, CharUnits(), 0, nullptr,
3269 /*PrintSizeInfo*/true,
3270 /*IncludeVirtualBases=*/true);
3271 return;
Douglas Gregore9fc3772012-01-26 07:55:45 +00003272 }
John McCall0d461692015-08-19 22:42:36 +00003273
3274 // The "simple" format is designed to be parsed by the
3275 // layout-override testing code. There shouldn't be any external
3276 // uses of this format --- when LLDB overrides a layout, it sets up
3277 // the data structures directly --- so feel free to adjust this as
3278 // you like as long as you also update the rudimentary parser for it
3279 // in libFrontend.
3280
3281 const ASTRecordLayout &Info = getASTRecordLayout(RD);
3282 OS << "Type: " << getTypeDeclType(RD).getAsString() << "\n";
Daniel Dunbarccabe482010-04-19 20:44:53 +00003283 OS << "\nLayout: ";
3284 OS << "<ASTRecordLayout\n";
Ken Dyckb0fcc592011-02-11 01:54:29 +00003285 OS << " Size:" << toBits(Info.getSize()) << "\n";
David Majnemer3b1c9902015-07-25 20:18:14 +00003286 if (!isMsLayout(*this))
Warren Hunt8f8bad72013-10-11 20:19:00 +00003287 OS << " DataSize:" << toBits(Info.getDataSize()) << "\n";
Ken Dyck7ad11e72011-02-15 02:32:40 +00003288 OS << " Alignment:" << toBits(Info.getAlignment()) << "\n";
Daniel Dunbarccabe482010-04-19 20:44:53 +00003289 OS << " FieldOffsets: [";
3290 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i) {
3291 if (i) OS << ", ";
3292 OS << Info.getFieldOffset(i);
3293 }
3294 OS << "]>\n";
3295}