blob: 457a40a8f03d5128c18d2bac046abae502ac938c [file] [log] [blame]
Anders Carlsson35a36eb2010-05-26 05:41:04 +00001//=== RecordLayoutBuilder.cpp - Helper class for building record layouts ---==//
Anders Carlsson79474332009-07-18 20:20:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Chandler Carruth3a022472012-12-04 09:13:33 +000010#include "clang/AST/RecordLayout.h"
Benjamin Kramer2ef30312012-07-04 18:45:14 +000011#include "clang/AST/ASTContext.h"
Anders Carlsson79474332009-07-18 20:20:21 +000012#include "clang/AST/Attr.h"
Anders Carlsson5adde292010-11-24 22:55:48 +000013#include "clang/AST/CXXInheritance.h"
Anders Carlsson79474332009-07-18 20:20:21 +000014#include "clang/AST/Decl.h"
Anders Carlsson6d9f6f32009-07-19 00:18:47 +000015#include "clang/AST/DeclCXX.h"
Anders Carlsson4f516282009-07-18 20:50:59 +000016#include "clang/AST/DeclObjC.h"
Anders Carlsson79474332009-07-18 20:20:21 +000017#include "clang/AST/Expr.h"
Anders Carlsson79474332009-07-18 20:20:21 +000018#include "clang/Basic/TargetInfo.h"
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +000019#include "clang/Sema/SemaDiagnostic.h"
Daniel Dunbaraa423af2010-04-08 02:59:49 +000020#include "llvm/ADT/SmallSet.h"
Ted Kremenekf75d0892011-03-19 01:00:36 +000021#include "llvm/Support/CrashRecoveryContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "llvm/Support/Format.h"
23#include "llvm/Support/MathExtras.h"
Anders Carlsson79474332009-07-18 20:20:21 +000024
25using namespace clang;
26
Benjamin Kramerc7656cd2010-05-26 09:58:31 +000027namespace {
Anders Carlssonf58de112010-05-26 15:32:58 +000028
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000029/// BaseSubobjectInfo - Represents a single base subobject in a complete class.
30/// For a class hierarchy like
31///
32/// class A { };
33/// class B : A { };
34/// class C : A, B { };
35///
36/// The BaseSubobjectInfo graph for C will have three BaseSubobjectInfo
37/// instances, one for B and two for A.
38///
39/// If a base is virtual, it will only have one BaseSubobjectInfo allocated.
40struct BaseSubobjectInfo {
41 /// Class - The class for this base info.
Anders Carlsson056818f2010-05-28 21:13:31 +000042 const CXXRecordDecl *Class;
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000043
44 /// IsVirtual - Whether the BaseInfo represents a virtual base or not.
Anders Carlsson056818f2010-05-28 21:13:31 +000045 bool IsVirtual;
46
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000047 /// Bases - Information about the base subobjects.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000048 SmallVector<BaseSubobjectInfo*, 4> Bases;
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000049
Anders Carlssone3c24c72010-05-29 17:35:14 +000050 /// PrimaryVirtualBaseInfo - Holds the base info for the primary virtual base
51 /// of this base info (if one exists).
52 BaseSubobjectInfo *PrimaryVirtualBaseInfo;
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000053
54 // FIXME: Document.
55 const BaseSubobjectInfo *Derived;
Anders Carlsson056818f2010-05-28 21:13:31 +000056};
57
Anders Carlssonf58de112010-05-26 15:32:58 +000058/// EmptySubobjectMap - Keeps track of which empty subobjects exist at different
59/// offsets while laying out a C++ class.
60class EmptySubobjectMap {
Jay Foad39c79802011-01-12 09:06:06 +000061 const ASTContext &Context;
Anders Carlsson233e2722010-10-31 21:54:55 +000062 uint64_t CharWidth;
63
Anders Carlssonf58de112010-05-26 15:32:58 +000064 /// Class - The class whose empty entries we're keeping track of.
65 const CXXRecordDecl *Class;
Daniel Dunbar592a85c2010-05-27 02:25:46 +000066
Anders Carlsson439edd12010-05-27 05:41:06 +000067 /// EmptyClassOffsets - A map from offsets to empty record decls.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000068 typedef SmallVector<const CXXRecordDecl *, 1> ClassVectorTy;
Anders Carlssonf8f756d2010-10-31 21:22:43 +000069 typedef llvm::DenseMap<CharUnits, ClassVectorTy> EmptyClassOffsetsMapTy;
Anders Carlsson439edd12010-05-27 05:41:06 +000070 EmptyClassOffsetsMapTy EmptyClassOffsets;
71
Anders Carlssoncc5de092010-06-08 15:56:03 +000072 /// MaxEmptyClassOffset - The highest offset known to contain an empty
73 /// base subobject.
Anders Carlsson725190f2010-10-31 21:39:24 +000074 CharUnits MaxEmptyClassOffset;
Anders Carlssoncc5de092010-06-08 15:56:03 +000075
Daniel Dunbar592a85c2010-05-27 02:25:46 +000076 /// ComputeEmptySubobjectSizes - Compute the size of the largest base or
Anders Carlssonc5ca1f72010-05-26 15:54:25 +000077 /// member subobject that is empty.
78 void ComputeEmptySubobjectSizes();
Anders Carlsson439edd12010-05-27 05:41:06 +000079
Anders Carlsson725190f2010-10-31 21:39:24 +000080 void AddSubobjectAtOffset(const CXXRecordDecl *RD, CharUnits Offset);
Anders Carlssondb319762010-05-27 18:20:57 +000081
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000082 void UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +000083 CharUnits Offset, bool PlacingEmptyBase);
Anders Carlsson439edd12010-05-27 05:41:06 +000084
Anders Carlssondb319762010-05-27 18:20:57 +000085 void UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD,
86 const CXXRecordDecl *Class,
Anders Carlsson28466ab2010-10-31 22:13:23 +000087 CharUnits Offset);
88 void UpdateEmptyFieldSubobjects(const FieldDecl *FD, CharUnits Offset);
Anders Carlssondb319762010-05-27 18:20:57 +000089
Anders Carlssoncc5de092010-06-08 15:56:03 +000090 /// AnyEmptySubobjectsBeyondOffset - Returns whether there are any empty
91 /// subobjects beyond the given offset.
Anders Carlsson725190f2010-10-31 21:39:24 +000092 bool AnyEmptySubobjectsBeyondOffset(CharUnits Offset) const {
Anders Carlssoncc5de092010-06-08 15:56:03 +000093 return Offset <= MaxEmptyClassOffset;
94 }
95
Anders Carlsson233e2722010-10-31 21:54:55 +000096 CharUnits
97 getFieldOffset(const ASTRecordLayout &Layout, unsigned FieldNo) const {
98 uint64_t FieldOffset = Layout.getFieldOffset(FieldNo);
99 assert(FieldOffset % CharWidth == 0 &&
100 "Field offset not at char boundary!");
101
Ken Dyck7c4026b2011-01-24 01:28:50 +0000102 return Context.toCharUnitsFromBits(FieldOffset);
Anders Carlssonf8f756d2010-10-31 21:22:43 +0000103 }
Anders Carlssonf8f756d2010-10-31 21:22:43 +0000104
Charles Davisc2c576a2010-08-19 00:55:19 +0000105protected:
Anders Carlsson725190f2010-10-31 21:39:24 +0000106 bool CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD,
107 CharUnits Offset) const;
Charles Davisc2c576a2010-08-19 00:55:19 +0000108
109 bool CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000110 CharUnits Offset);
Charles Davisc2c576a2010-08-19 00:55:19 +0000111
112 bool CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD,
113 const CXXRecordDecl *Class,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000114 CharUnits Offset) const;
Charles Davisc2c576a2010-08-19 00:55:19 +0000115 bool CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD,
Anders Carlsson233e2722010-10-31 21:54:55 +0000116 CharUnits Offset) const;
Charles Davisc2c576a2010-08-19 00:55:19 +0000117
Anders Carlssonf58de112010-05-26 15:32:58 +0000118public:
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000119 /// This holds the size of the largest empty subobject (either a base
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000120 /// or a member). Will be zero if the record being built doesn't contain
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000121 /// any empty classes.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000122 CharUnits SizeOfLargestEmptySubobject;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000123
Jay Foad39c79802011-01-12 09:06:06 +0000124 EmptySubobjectMap(const ASTContext &Context, const CXXRecordDecl *Class)
Anders Carlsson28466ab2010-10-31 22:13:23 +0000125 : Context(Context), CharWidth(Context.getCharWidth()), Class(Class) {
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000126 ComputeEmptySubobjectSizes();
127 }
128
129 /// CanPlaceBaseAtOffset - Return whether the given base class can be placed
130 /// at the given offset.
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000131 /// Returns false if placing the record will result in two components
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000132 /// (direct or indirect) of the same type having the same offset.
Anders Carlssoncc5de092010-06-08 15:56:03 +0000133 bool CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000134 CharUnits Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000135
136 /// CanPlaceFieldAtOffset - Return whether a field can be placed at the given
137 /// offset.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000138 bool CanPlaceFieldAtOffset(const FieldDecl *FD, CharUnits Offset);
Anders Carlssonf58de112010-05-26 15:32:58 +0000139};
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000140
141void EmptySubobjectMap::ComputeEmptySubobjectSizes() {
142 // Check the bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000143 for (const auto &I : Class->bases()) {
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000144 const CXXRecordDecl *BaseDecl =
Aaron Ballman574705e2014-03-13 15:41:46 +0000145 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000146
Anders Carlsson28466ab2010-10-31 22:13:23 +0000147 CharUnits EmptySize;
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000148 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
149 if (BaseDecl->isEmpty()) {
150 // If the class decl is empty, get its size.
Ken Dyckc8ae5502011-02-09 01:59:34 +0000151 EmptySize = Layout.getSize();
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000152 } else {
153 // Otherwise, we get the largest empty subobject for the decl.
154 EmptySize = Layout.getSizeOfLargestEmptySubobject();
155 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000156
Anders Carlsson28466ab2010-10-31 22:13:23 +0000157 if (EmptySize > SizeOfLargestEmptySubobject)
158 SizeOfLargestEmptySubobject = EmptySize;
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000159 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000160
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000161 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000162 for (const auto *I : Class->fields()) {
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000163 const RecordType *RT =
David Blaikie40ed2972012-06-06 20:45:41 +0000164 Context.getBaseElementType(I->getType())->getAs<RecordType>();
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000165
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000166 // We only care about record types.
167 if (!RT)
168 continue;
169
Anders Carlsson28466ab2010-10-31 22:13:23 +0000170 CharUnits EmptySize;
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000171 const CXXRecordDecl *MemberDecl = cast<CXXRecordDecl>(RT->getDecl());
172 const ASTRecordLayout &Layout = Context.getASTRecordLayout(MemberDecl);
173 if (MemberDecl->isEmpty()) {
174 // If the class decl is empty, get its size.
Ken Dyckc8ae5502011-02-09 01:59:34 +0000175 EmptySize = Layout.getSize();
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000176 } else {
177 // Otherwise, we get the largest empty subobject for the decl.
178 EmptySize = Layout.getSizeOfLargestEmptySubobject();
179 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000180
Anders Carlsson28466ab2010-10-31 22:13:23 +0000181 if (EmptySize > SizeOfLargestEmptySubobject)
182 SizeOfLargestEmptySubobject = EmptySize;
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000183 }
184}
185
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000186bool
Anders Carlssondb319762010-05-27 18:20:57 +0000187EmptySubobjectMap::CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD,
Anders Carlsson725190f2010-10-31 21:39:24 +0000188 CharUnits Offset) const {
Anders Carlssondb319762010-05-27 18:20:57 +0000189 // We only need to check empty bases.
190 if (!RD->isEmpty())
191 return true;
192
Anders Carlsson725190f2010-10-31 21:39:24 +0000193 EmptyClassOffsetsMapTy::const_iterator I = EmptyClassOffsets.find(Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000194 if (I == EmptyClassOffsets.end())
195 return true;
196
197 const ClassVectorTy& Classes = I->second;
198 if (std::find(Classes.begin(), Classes.end(), RD) == Classes.end())
199 return true;
200
201 // There is already an empty class of the same type at this offset.
202 return false;
203}
204
205void EmptySubobjectMap::AddSubobjectAtOffset(const CXXRecordDecl *RD,
Anders Carlsson725190f2010-10-31 21:39:24 +0000206 CharUnits Offset) {
Anders Carlssondb319762010-05-27 18:20:57 +0000207 // We only care about empty bases.
208 if (!RD->isEmpty())
209 return;
210
Reid Kleckner369f3162013-05-14 20:30:42 +0000211 // If we have empty structures inside a union, we can assign both
Rafael Espindola7bcde192010-12-29 23:02:58 +0000212 // the same offset. Just avoid pushing them twice in the list.
Anders Carlsson725190f2010-10-31 21:39:24 +0000213 ClassVectorTy& Classes = EmptyClassOffsets[Offset];
Rafael Espindola7bcde192010-12-29 23:02:58 +0000214 if (std::find(Classes.begin(), Classes.end(), RD) != Classes.end())
215 return;
216
Anders Carlssondb319762010-05-27 18:20:57 +0000217 Classes.push_back(RD);
Anders Carlssoncc5de092010-06-08 15:56:03 +0000218
219 // Update the empty class offset.
Anders Carlsson725190f2010-10-31 21:39:24 +0000220 if (Offset > MaxEmptyClassOffset)
221 MaxEmptyClassOffset = Offset;
Anders Carlssondb319762010-05-27 18:20:57 +0000222}
223
224bool
Anders Carlsson28466ab2010-10-31 22:13:23 +0000225EmptySubobjectMap::CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info,
226 CharUnits Offset) {
Anders Carlsson45c1d282010-06-08 16:20:35 +0000227 // We don't have to keep looking past the maximum offset that's known to
228 // contain an empty class.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000229 if (!AnyEmptySubobjectsBeyondOffset(Offset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000230 return true;
231
Anders Carlsson28466ab2010-10-31 22:13:23 +0000232 if (!CanPlaceSubobjectAtOffset(Info->Class, Offset))
Anders Carlssondb319762010-05-27 18:20:57 +0000233 return false;
234
Anders Carlsson439edd12010-05-27 05:41:06 +0000235 // Traverse all non-virtual bases.
Anders Carlssona7774a62010-05-29 21:10:24 +0000236 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
Anders Carlsson439edd12010-05-27 05:41:06 +0000237 for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) {
Anders Carlssona7f3cdb2010-05-28 21:24:37 +0000238 BaseSubobjectInfo* Base = Info->Bases[I];
Anders Carlsson439edd12010-05-27 05:41:06 +0000239 if (Base->IsVirtual)
240 continue;
241
Anders Carlsson0a14ee92010-11-01 00:21:58 +0000242 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
Anders Carlsson439edd12010-05-27 05:41:06 +0000243
244 if (!CanPlaceBaseSubobjectAtOffset(Base, BaseOffset))
245 return false;
246 }
247
Anders Carlssone3c24c72010-05-29 17:35:14 +0000248 if (Info->PrimaryVirtualBaseInfo) {
249 BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
Anders Carlsson439edd12010-05-27 05:41:06 +0000250
251 if (Info == PrimaryVirtualBaseInfo->Derived) {
252 if (!CanPlaceBaseSubobjectAtOffset(PrimaryVirtualBaseInfo, Offset))
253 return false;
254 }
255 }
256
Anders Carlssondb319762010-05-27 18:20:57 +0000257 // Traverse all member variables.
258 unsigned FieldNo = 0;
259 for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(),
260 E = Info->Class->field_end(); I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +0000261 if (I->isBitField())
Anders Carlsson233e2722010-10-31 21:54:55 +0000262 continue;
263
Anders Carlsson28466ab2010-10-31 22:13:23 +0000264 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
David Blaikie40ed2972012-06-06 20:45:41 +0000265 if (!CanPlaceFieldSubobjectAtOffset(*I, FieldOffset))
Anders Carlssondb319762010-05-27 18:20:57 +0000266 return false;
267 }
268
Anders Carlsson439edd12010-05-27 05:41:06 +0000269 return true;
270}
271
Anders Carlssona7f3cdb2010-05-28 21:24:37 +0000272void EmptySubobjectMap::UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000273 CharUnits Offset,
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000274 bool PlacingEmptyBase) {
275 if (!PlacingEmptyBase && Offset >= SizeOfLargestEmptySubobject) {
276 // We know that the only empty subobjects that can conflict with empty
277 // subobject of non-empty bases, are empty bases that can be placed at
278 // offset zero. Because of this, we only need to keep track of empty base
279 // subobjects with offsets less than the size of the largest empty
280 // subobject for our class.
281 return;
282 }
283
Anders Carlsson28466ab2010-10-31 22:13:23 +0000284 AddSubobjectAtOffset(Info->Class, Offset);
Anders Carlssona7774a62010-05-29 21:10:24 +0000285
Anders Carlsson439edd12010-05-27 05:41:06 +0000286 // Traverse all non-virtual bases.
Anders Carlssona7774a62010-05-29 21:10:24 +0000287 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
Anders Carlsson439edd12010-05-27 05:41:06 +0000288 for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) {
Anders Carlssona7f3cdb2010-05-28 21:24:37 +0000289 BaseSubobjectInfo* Base = Info->Bases[I];
Anders Carlsson439edd12010-05-27 05:41:06 +0000290 if (Base->IsVirtual)
291 continue;
Anders Carlssona7774a62010-05-29 21:10:24 +0000292
Anders Carlsson0a14ee92010-11-01 00:21:58 +0000293 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000294 UpdateEmptyBaseSubobjects(Base, BaseOffset, PlacingEmptyBase);
Anders Carlsson439edd12010-05-27 05:41:06 +0000295 }
296
Anders Carlssone3c24c72010-05-29 17:35:14 +0000297 if (Info->PrimaryVirtualBaseInfo) {
298 BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
Anders Carlsson439edd12010-05-27 05:41:06 +0000299
300 if (Info == PrimaryVirtualBaseInfo->Derived)
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000301 UpdateEmptyBaseSubobjects(PrimaryVirtualBaseInfo, Offset,
302 PlacingEmptyBase);
Anders Carlsson439edd12010-05-27 05:41:06 +0000303 }
Anders Carlssondb319762010-05-27 18:20:57 +0000304
Anders Carlssondb319762010-05-27 18:20:57 +0000305 // Traverse all member variables.
306 unsigned FieldNo = 0;
307 for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(),
308 E = Info->Class->field_end(); I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +0000309 if (I->isBitField())
Anders Carlsson233e2722010-10-31 21:54:55 +0000310 continue;
Anders Carlssona7774a62010-05-29 21:10:24 +0000311
Anders Carlsson28466ab2010-10-31 22:13:23 +0000312 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
David Blaikie40ed2972012-06-06 20:45:41 +0000313 UpdateEmptyFieldSubobjects(*I, FieldOffset);
Anders Carlssondb319762010-05-27 18:20:57 +0000314 }
Anders Carlsson439edd12010-05-27 05:41:06 +0000315}
316
Anders Carlssona60b86a2010-05-29 20:49:49 +0000317bool EmptySubobjectMap::CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000318 CharUnits Offset) {
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000319 // If we know this class doesn't have any empty subobjects we don't need to
320 // bother checking.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000321 if (SizeOfLargestEmptySubobject.isZero())
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000322 return true;
323
Anders Carlsson439edd12010-05-27 05:41:06 +0000324 if (!CanPlaceBaseSubobjectAtOffset(Info, Offset))
325 return false;
Anders Carlssondb319762010-05-27 18:20:57 +0000326
327 // We are able to place the base at this offset. Make sure to update the
328 // empty base subobject map.
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000329 UpdateEmptyBaseSubobjects(Info, Offset, Info->Class->isEmpty());
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000330 return true;
331}
332
Anders Carlssondb319762010-05-27 18:20:57 +0000333bool
334EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD,
335 const CXXRecordDecl *Class,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000336 CharUnits Offset) const {
Anders Carlsson45c1d282010-06-08 16:20:35 +0000337 // We don't have to keep looking past the maximum offset that's known to
338 // contain an empty class.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000339 if (!AnyEmptySubobjectsBeyondOffset(Offset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000340 return true;
341
Anders Carlsson28466ab2010-10-31 22:13:23 +0000342 if (!CanPlaceSubobjectAtOffset(RD, Offset))
Anders Carlssondb319762010-05-27 18:20:57 +0000343 return false;
344
345 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
346
347 // Traverse all non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000348 for (const auto &I : RD->bases()) {
349 if (I.isVirtual())
Anders Carlssondb319762010-05-27 18:20:57 +0000350 continue;
351
352 const CXXRecordDecl *BaseDecl =
Aaron Ballman574705e2014-03-13 15:41:46 +0000353 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Anders Carlssondb319762010-05-27 18:20:57 +0000354
Anders Carlsson0a14ee92010-11-01 00:21:58 +0000355 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
Anders Carlssondb319762010-05-27 18:20:57 +0000356 if (!CanPlaceFieldSubobjectAtOffset(BaseDecl, Class, BaseOffset))
357 return false;
358 }
359
Anders Carlsson44687202010-06-08 19:09:24 +0000360 if (RD == Class) {
361 // This is the most derived class, traverse virtual bases as well.
362 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
363 E = RD->vbases_end(); I != E; ++I) {
364 const CXXRecordDecl *VBaseDecl =
365 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
366
Anders Carlsson3f018712010-10-31 23:45:59 +0000367 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
Anders Carlsson44687202010-06-08 19:09:24 +0000368 if (!CanPlaceFieldSubobjectAtOffset(VBaseDecl, Class, VBaseOffset))
369 return false;
370 }
371 }
372
Anders Carlssondb319762010-05-27 18:20:57 +0000373 // Traverse all member variables.
374 unsigned FieldNo = 0;
375 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
376 I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +0000377 if (I->isBitField())
Anders Carlsson233e2722010-10-31 21:54:55 +0000378 continue;
379
Anders Carlsson28466ab2010-10-31 22:13:23 +0000380 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
Anders Carlssondb319762010-05-27 18:20:57 +0000381
David Blaikie40ed2972012-06-06 20:45:41 +0000382 if (!CanPlaceFieldSubobjectAtOffset(*I, FieldOffset))
Anders Carlssondb319762010-05-27 18:20:57 +0000383 return false;
384 }
385
386 return true;
387}
388
Anders Carlsson233e2722010-10-31 21:54:55 +0000389bool
390EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD,
391 CharUnits Offset) const {
Anders Carlsson45c1d282010-06-08 16:20:35 +0000392 // We don't have to keep looking past the maximum offset that's known to
393 // contain an empty class.
Anders Carlsson233e2722010-10-31 21:54:55 +0000394 if (!AnyEmptySubobjectsBeyondOffset(Offset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000395 return true;
396
Anders Carlssondb319762010-05-27 18:20:57 +0000397 QualType T = FD->getType();
398 if (const RecordType *RT = T->getAs<RecordType>()) {
399 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson28466ab2010-10-31 22:13:23 +0000400 return CanPlaceFieldSubobjectAtOffset(RD, RD, Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000401 }
402
403 // If we have an array type we need to look at every element.
404 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
405 QualType ElemTy = Context.getBaseElementType(AT);
406 const RecordType *RT = ElemTy->getAs<RecordType>();
407 if (!RT)
408 return true;
409
410 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
411 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
412
413 uint64_t NumElements = Context.getConstantArrayElementCount(AT);
Anders Carlsson233e2722010-10-31 21:54:55 +0000414 CharUnits ElementOffset = Offset;
Anders Carlssondb319762010-05-27 18:20:57 +0000415 for (uint64_t I = 0; I != NumElements; ++I) {
Anders Carlsson45c1d282010-06-08 16:20:35 +0000416 // We don't have to keep looking past the maximum offset that's known to
417 // contain an empty class.
Anders Carlsson233e2722010-10-31 21:54:55 +0000418 if (!AnyEmptySubobjectsBeyondOffset(ElementOffset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000419 return true;
420
Anders Carlsson28466ab2010-10-31 22:13:23 +0000421 if (!CanPlaceFieldSubobjectAtOffset(RD, RD, ElementOffset))
Anders Carlssondb319762010-05-27 18:20:57 +0000422 return false;
423
Ken Dyckc8ae5502011-02-09 01:59:34 +0000424 ElementOffset += Layout.getSize();
Anders Carlssondb319762010-05-27 18:20:57 +0000425 }
426 }
427
428 return true;
429}
430
431bool
Anders Carlsson28466ab2010-10-31 22:13:23 +0000432EmptySubobjectMap::CanPlaceFieldAtOffset(const FieldDecl *FD,
433 CharUnits Offset) {
434 if (!CanPlaceFieldSubobjectAtOffset(FD, Offset))
Anders Carlssondb319762010-05-27 18:20:57 +0000435 return false;
436
437 // We are able to place the member variable at this offset.
438 // Make sure to update the empty base subobject map.
439 UpdateEmptyFieldSubobjects(FD, Offset);
440 return true;
441}
442
443void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD,
444 const CXXRecordDecl *Class,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000445 CharUnits Offset) {
Anders Carlssonae111dc2010-06-13 17:49:16 +0000446 // We know that the only empty subobjects that can conflict with empty
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000447 // field subobjects are subobjects of empty bases that can be placed at offset
Anders Carlssonae111dc2010-06-13 17:49:16 +0000448 // zero. Because of this, we only need to keep track of empty field
449 // subobjects with offsets less than the size of the largest empty
450 // subobject for our class.
451 if (Offset >= SizeOfLargestEmptySubobject)
452 return;
453
Anders Carlsson28466ab2010-10-31 22:13:23 +0000454 AddSubobjectAtOffset(RD, Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000455
456 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
457
458 // Traverse all non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000459 for (const auto &I : RD->bases()) {
460 if (I.isVirtual())
Anders Carlssondb319762010-05-27 18:20:57 +0000461 continue;
462
463 const CXXRecordDecl *BaseDecl =
Aaron Ballman574705e2014-03-13 15:41:46 +0000464 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Anders Carlssondb319762010-05-27 18:20:57 +0000465
Anders Carlsson0a14ee92010-11-01 00:21:58 +0000466 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
Anders Carlssondb319762010-05-27 18:20:57 +0000467 UpdateEmptyFieldSubobjects(BaseDecl, Class, BaseOffset);
468 }
469
Anders Carlsson44687202010-06-08 19:09:24 +0000470 if (RD == Class) {
471 // This is the most derived class, traverse virtual bases as well.
472 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
473 E = RD->vbases_end(); I != E; ++I) {
474 const CXXRecordDecl *VBaseDecl =
475 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
476
Anders Carlsson3f018712010-10-31 23:45:59 +0000477 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
Anders Carlsson44687202010-06-08 19:09:24 +0000478 UpdateEmptyFieldSubobjects(VBaseDecl, Class, VBaseOffset);
479 }
480 }
481
Anders Carlssondb319762010-05-27 18:20:57 +0000482 // Traverse all member variables.
483 unsigned FieldNo = 0;
484 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
485 I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +0000486 if (I->isBitField())
Anders Carlsson09814d32010-11-01 15:14:51 +0000487 continue;
488
Anders Carlsson28466ab2010-10-31 22:13:23 +0000489 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
Anders Carlssondb319762010-05-27 18:20:57 +0000490
David Blaikie40ed2972012-06-06 20:45:41 +0000491 UpdateEmptyFieldSubobjects(*I, FieldOffset);
Anders Carlssondb319762010-05-27 18:20:57 +0000492 }
493}
494
495void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const FieldDecl *FD,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000496 CharUnits Offset) {
Anders Carlssondb319762010-05-27 18:20:57 +0000497 QualType T = FD->getType();
498 if (const RecordType *RT = T->getAs<RecordType>()) {
499 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
500 UpdateEmptyFieldSubobjects(RD, RD, Offset);
501 return;
502 }
503
504 // If we have an array type we need to update every element.
505 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
506 QualType ElemTy = Context.getBaseElementType(AT);
507 const RecordType *RT = ElemTy->getAs<RecordType>();
508 if (!RT)
509 return;
510
511 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
512 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
513
514 uint64_t NumElements = Context.getConstantArrayElementCount(AT);
Anders Carlsson28466ab2010-10-31 22:13:23 +0000515 CharUnits ElementOffset = Offset;
Anders Carlssondb319762010-05-27 18:20:57 +0000516
517 for (uint64_t I = 0; I != NumElements; ++I) {
Anders Carlssonae111dc2010-06-13 17:49:16 +0000518 // We know that the only empty subobjects that can conflict with empty
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000519 // field subobjects are subobjects of empty bases that can be placed at
Anders Carlssonae111dc2010-06-13 17:49:16 +0000520 // offset zero. Because of this, we only need to keep track of empty field
521 // subobjects with offsets less than the size of the largest empty
522 // subobject for our class.
523 if (ElementOffset >= SizeOfLargestEmptySubobject)
524 return;
525
Anders Carlssondb319762010-05-27 18:20:57 +0000526 UpdateEmptyFieldSubobjects(RD, RD, ElementOffset);
Ken Dyckc8ae5502011-02-09 01:59:34 +0000527 ElementOffset += Layout.getSize();
Anders Carlssondb319762010-05-27 18:20:57 +0000528 }
529 }
530}
531
John McCalle42a3362012-05-01 08:55:32 +0000532typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> ClassSetTy;
533
Anders Carlssonc2226202010-05-26 05:58:59 +0000534class RecordLayoutBuilder {
Charles Davisc2c576a2010-08-19 00:55:19 +0000535protected:
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000536 // FIXME: Remove this and make the appropriate fields public.
537 friend class clang::ASTContext;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000538
Jay Foad39c79802011-01-12 09:06:06 +0000539 const ASTContext &Context;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000540
Anders Carlssonf58de112010-05-26 15:32:58 +0000541 EmptySubobjectMap *EmptySubobjects;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000542
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000543 /// Size - The current size of the record layout.
544 uint64_t Size;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000545
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000546 /// Alignment - The current alignment of the record layout.
Ken Dyck4731d5b2011-02-16 02:05:21 +0000547 CharUnits Alignment;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000548
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000549 /// \brief The alignment if attribute packed is not used.
Ken Dyck1300b3b2011-02-16 02:11:31 +0000550 CharUnits UnpackedAlignment;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000551
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000552 SmallVector<uint64_t, 16> FieldOffsets;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000553
Douglas Gregore9fc3772012-01-26 07:55:45 +0000554 /// \brief Whether the external AST source has provided a layout for this
555 /// record.
556 unsigned ExternalLayout : 1;
Douglas Gregor44ba7892012-01-28 00:53:29 +0000557
558 /// \brief Whether we need to infer alignment, even when we have an
559 /// externally-provided layout.
560 unsigned InferAlignment : 1;
Douglas Gregore9fc3772012-01-26 07:55:45 +0000561
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000562 /// Packed - Whether the record is packed or not.
Daniel Dunbar6da10982010-05-27 05:45:51 +0000563 unsigned Packed : 1;
564
565 unsigned IsUnion : 1;
566
567 unsigned IsMac68kAlign : 1;
Fariborz Jahanianbcb23a12011-04-26 23:52:16 +0000568
569 unsigned IsMsStruct : 1;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000570
Eli Friedman2782dac2013-06-26 20:50:34 +0000571 /// UnfilledBitsInLastUnit - If the last field laid out was a bitfield,
572 /// this contains the number of bits in the last unit that can be used for
573 /// an adjacent bitfield if necessary. The unit in question is usually
574 /// a byte, but larger units are used if IsMsStruct.
575 unsigned char UnfilledBitsInLastUnit;
576 /// LastBitfieldTypeSize - If IsMsStruct, represents the size of the type
577 /// of the previous field if it was a bitfield.
578 unsigned char LastBitfieldTypeSize;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000579
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000580 /// MaxFieldAlignment - The maximum allowed field alignment. This is set by
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000581 /// #pragma pack.
Ken Dyck02ced6f2011-02-17 01:49:42 +0000582 CharUnits MaxFieldAlignment;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000583
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000584 /// DataSize - The data size of the record being laid out.
585 uint64_t DataSize;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000586
Ken Dyckaf1c83f2011-02-16 01:52:01 +0000587 CharUnits NonVirtualSize;
Ken Dycka2d3dda2011-02-16 01:43:15 +0000588 CharUnits NonVirtualAlignment;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000589
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000590 /// PrimaryBase - the primary base class (if one exists) of the class
591 /// we're laying out.
592 const CXXRecordDecl *PrimaryBase;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000593
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000594 /// PrimaryBaseIsVirtual - Whether the primary base of the class we're laying
595 /// out is virtual.
596 bool PrimaryBaseIsVirtual;
597
John McCalle42a3362012-05-01 08:55:32 +0000598 /// HasOwnVFPtr - Whether the class provides its own vtable/vftbl
599 /// pointer, as opposed to inheriting one from a primary base class.
600 bool HasOwnVFPtr;
Eli Friedman43114f92011-10-21 22:49:56 +0000601
Anders Carlsson22f57202010-10-31 21:01:46 +0000602 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000603
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000604 /// Bases - base classes and their offsets in the record.
605 BaseOffsetsMapTy Bases;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000606
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000607 // VBases - virtual base classes and their offsets in the record.
John McCalle42a3362012-05-01 08:55:32 +0000608 ASTRecordLayout::VBaseOffsetsMapTy VBases;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000609
610 /// IndirectPrimaryBases - Virtual base classes, direct or indirect, that are
611 /// primary base classes for some other direct or indirect base class.
Anders Carlsson5adde292010-11-24 22:55:48 +0000612 CXXIndirectPrimaryBaseSet IndirectPrimaryBases;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000613
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000614 /// FirstNearlyEmptyVBase - The first nearly empty virtual base class in
615 /// inheritance graph order. Used for determining the primary base class.
616 const CXXRecordDecl *FirstNearlyEmptyVBase;
617
618 /// VisitedVirtualBases - A set of all the visited virtual bases, used to
619 /// avoid visiting virtual bases more than once.
620 llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000621
Douglas Gregore9fc3772012-01-26 07:55:45 +0000622 /// \brief Externally-provided size.
623 uint64_t ExternalSize;
624
625 /// \brief Externally-provided alignment.
626 uint64_t ExternalAlign;
627
628 /// \brief Externally-provided field offsets.
629 llvm::DenseMap<const FieldDecl *, uint64_t> ExternalFieldOffsets;
630
631 /// \brief Externally-provided direct, non-virtual base offsets.
632 llvm::DenseMap<const CXXRecordDecl *, CharUnits> ExternalBaseOffsets;
633
634 /// \brief Externally-provided virtual base offsets.
635 llvm::DenseMap<const CXXRecordDecl *, CharUnits> ExternalVirtualBaseOffsets;
636
John McCall0153cd32011-11-08 04:01:03 +0000637 RecordLayoutBuilder(const ASTContext &Context,
638 EmptySubobjectMap *EmptySubobjects)
Ken Dyck4731d5b2011-02-16 02:05:21 +0000639 : Context(Context), EmptySubobjects(EmptySubobjects), Size(0),
John McCall0153cd32011-11-08 04:01:03 +0000640 Alignment(CharUnits::One()), UnpackedAlignment(CharUnits::One()),
Douglas Gregor44ba7892012-01-28 00:53:29 +0000641 ExternalLayout(false), InferAlignment(false),
642 Packed(false), IsUnion(false), IsMac68kAlign(false), IsMsStruct(false),
Eli Friedman2782dac2013-06-26 20:50:34 +0000643 UnfilledBitsInLastUnit(0), LastBitfieldTypeSize(0),
644 MaxFieldAlignment(CharUnits::Zero()),
Ken Dyck02ced6f2011-02-17 01:49:42 +0000645 DataSize(0), NonVirtualSize(CharUnits::Zero()),
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000646 NonVirtualAlignment(CharUnits::One()),
Eli Friedman481673f2013-06-26 23:47:39 +0000647 PrimaryBase(0), PrimaryBaseIsVirtual(false),
John McCalle42a3362012-05-01 08:55:32 +0000648 HasOwnVFPtr(false),
Eli Friedman84d2d3a2011-09-27 19:12:27 +0000649 FirstNearlyEmptyVBase(0) { }
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000650
John McCall0153cd32011-11-08 04:01:03 +0000651 /// Reset this RecordLayoutBuilder to a fresh state, using the given
652 /// alignment as the initial alignment. This is used for the
653 /// correct layout of vb-table pointers in MSVC.
654 void resetWithTargetAlignment(CharUnits TargetAlignment) {
655 const ASTContext &Context = this->Context;
656 EmptySubobjectMap *EmptySubobjects = this->EmptySubobjects;
657 this->~RecordLayoutBuilder();
658 new (this) RecordLayoutBuilder(Context, EmptySubobjects);
659 Alignment = UnpackedAlignment = TargetAlignment;
660 }
661
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000662 void Layout(const RecordDecl *D);
Anders Carlssonc28a6c92010-05-26 15:10:00 +0000663 void Layout(const CXXRecordDecl *D);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000664 void Layout(const ObjCInterfaceDecl *D);
665
666 void LayoutFields(const RecordDecl *D);
667 void LayoutField(const FieldDecl *D);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000668 void LayoutWideBitField(uint64_t FieldSize, uint64_t TypeSize,
669 bool FieldPacked, const FieldDecl *D);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000670 void LayoutBitField(const FieldDecl *D);
John McCall0153cd32011-11-08 04:01:03 +0000671
John McCall359b8852013-01-25 22:30:49 +0000672 TargetCXXABI getCXXABI() const {
673 return Context.getTargetInfo().getCXXABI();
674 }
675
Anders Carlssone3c24c72010-05-29 17:35:14 +0000676 /// BaseSubobjectInfoAllocator - Allocator for BaseSubobjectInfo objects.
677 llvm::SpecificBumpPtrAllocator<BaseSubobjectInfo> BaseSubobjectInfoAllocator;
678
679 typedef llvm::DenseMap<const CXXRecordDecl *, BaseSubobjectInfo *>
680 BaseSubobjectInfoMapTy;
681
682 /// VirtualBaseInfo - Map from all the (direct or indirect) virtual bases
683 /// of the class we're laying out to their base subobject info.
684 BaseSubobjectInfoMapTy VirtualBaseInfo;
685
686 /// NonVirtualBaseInfo - Map from all the direct non-virtual bases of the
687 /// class we're laying out to their base subobject info.
688 BaseSubobjectInfoMapTy NonVirtualBaseInfo;
689
690 /// ComputeBaseSubobjectInfo - Compute the base subobject information for the
691 /// bases of the given class.
692 void ComputeBaseSubobjectInfo(const CXXRecordDecl *RD);
693
694 /// ComputeBaseSubobjectInfo - Compute the base subobject information for a
695 /// single class and all of its base classes.
696 BaseSubobjectInfo *ComputeBaseSubobjectInfo(const CXXRecordDecl *RD,
697 bool IsVirtual,
698 BaseSubobjectInfo *Derived);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000699
700 /// DeterminePrimaryBase - Determine the primary base of the given class.
701 void DeterminePrimaryBase(const CXXRecordDecl *RD);
702
703 void SelectPrimaryVBase(const CXXRecordDecl *RD);
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000704
Eli Friedman43114f92011-10-21 22:49:56 +0000705 void EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign);
Charles Davisc2c576a2010-08-19 00:55:19 +0000706
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000707 /// LayoutNonVirtualBases - Determines the primary base class (if any) and
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000708 /// lays it out. Will then proceed to lay out all non-virtual base clasess.
709 void LayoutNonVirtualBases(const CXXRecordDecl *RD);
710
711 /// LayoutNonVirtualBase - Lays out a single non-virtual base.
Anders Carlssonbb0e6782010-05-29 17:42:25 +0000712 void LayoutNonVirtualBase(const BaseSubobjectInfo *Base);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000713
Anders Carlssona2f8e412010-10-31 22:20:42 +0000714 void AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
715 CharUnits Offset);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000716
717 /// LayoutVirtualBases - Lays out all the virtual bases.
718 void LayoutVirtualBases(const CXXRecordDecl *RD,
719 const CXXRecordDecl *MostDerivedClass);
720
721 /// LayoutVirtualBase - Lays out a single virtual base.
Warren Hunt55d8e822013-10-23 23:53:07 +0000722 void LayoutVirtualBase(const BaseSubobjectInfo *Base);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000723
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000724 /// LayoutBase - Will lay out a base and return the offset where it was
Anders Carlssona2f8e412010-10-31 22:20:42 +0000725 /// placed, in chars.
726 CharUnits LayoutBase(const BaseSubobjectInfo *Base);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000727
Anders Carlssonc28a6c92010-05-26 15:10:00 +0000728 /// InitializeLayout - Initialize record layout for the given record decl.
Daniel Dunbar6da10982010-05-27 05:45:51 +0000729 void InitializeLayout(const Decl *D);
Anders Carlssonc28a6c92010-05-26 15:10:00 +0000730
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000731 /// FinishLayout - Finalize record layout. Adjust record size based on the
732 /// alignment.
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000733 void FinishLayout(const NamedDecl *D);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000734
Ken Dyck85ef0432011-02-19 18:58:07 +0000735 void UpdateAlignment(CharUnits NewAlignment, CharUnits UnpackedNewAlignment);
736 void UpdateAlignment(CharUnits NewAlignment) {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000737 UpdateAlignment(NewAlignment, NewAlignment);
738 }
739
Douglas Gregor44ba7892012-01-28 00:53:29 +0000740 /// \brief Retrieve the externally-supplied field offset for the given
741 /// field.
742 ///
743 /// \param Field The field whose offset is being queried.
744 /// \param ComputedOffset The offset that we've computed for this field.
745 uint64_t updateExternalFieldOffset(const FieldDecl *Field,
746 uint64_t ComputedOffset);
747
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000748 void CheckFieldPadding(uint64_t Offset, uint64_t UnpaddedOffset,
749 uint64_t UnpackedOffset, unsigned UnpackedAlign,
750 bool isPacked, const FieldDecl *D);
751
752 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000753
Ken Dyckecfc7552011-02-24 01:13:28 +0000754 CharUnits getSize() const {
Ken Dyck3c215f22011-02-24 01:33:05 +0000755 assert(Size % Context.getCharWidth() == 0);
Ken Dyckecfc7552011-02-24 01:13:28 +0000756 return Context.toCharUnitsFromBits(Size);
757 }
758 uint64_t getSizeInBits() const { return Size; }
759
760 void setSize(CharUnits NewSize) { Size = Context.toBits(NewSize); }
761 void setSize(uint64_t NewSize) { Size = NewSize; }
762
Eli Friedman84d2d3a2011-09-27 19:12:27 +0000763 CharUnits getAligment() const { return Alignment; }
764
Ken Dyckecfc7552011-02-24 01:13:28 +0000765 CharUnits getDataSize() const {
Ken Dyck3c215f22011-02-24 01:33:05 +0000766 assert(DataSize % Context.getCharWidth() == 0);
Ken Dyckecfc7552011-02-24 01:13:28 +0000767 return Context.toCharUnitsFromBits(DataSize);
768 }
769 uint64_t getDataSizeInBits() const { return DataSize; }
770
771 void setDataSize(CharUnits NewSize) { DataSize = Context.toBits(NewSize); }
772 void setDataSize(uint64_t NewSize) { DataSize = NewSize; }
773
Dmitri Gribenkoa664e5b2012-09-15 20:20:27 +0000774 RecordLayoutBuilder(const RecordLayoutBuilder &) LLVM_DELETED_FUNCTION;
775 void operator=(const RecordLayoutBuilder &) LLVM_DELETED_FUNCTION;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000776};
Benjamin Kramerc7656cd2010-05-26 09:58:31 +0000777} // end anonymous namespace
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000778
Anders Carlsson81430692009-09-22 03:02:06 +0000779void
Anders Carlssonc2226202010-05-26 05:58:59 +0000780RecordLayoutBuilder::SelectPrimaryVBase(const CXXRecordDecl *RD) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000781 for (const auto &I : RD->bases()) {
782 assert(!I.getType()->isDependentType() &&
Sebastian Redl1054fae2009-10-25 17:03:50 +0000783 "Cannot layout class with dependent bases.");
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000784
Mike Stump11289f42009-09-09 15:08:12 +0000785 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +0000786 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000787
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000788 // Check if this is a nearly empty virtual base.
Aaron Ballman574705e2014-03-13 15:41:46 +0000789 if (I.isVirtual() && Context.isNearlyEmpty(Base)) {
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000790 // If it's not an indirect primary base, then we've found our primary
791 // base.
Anders Carlsson81430692009-09-22 03:02:06 +0000792 if (!IndirectPrimaryBases.count(Base)) {
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000793 PrimaryBase = Base;
794 PrimaryBaseIsVirtual = true;
Mike Stump6f3793b2009-08-12 21:50:08 +0000795 return;
796 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000797
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000798 // Is this the first nearly empty virtual base?
799 if (!FirstNearlyEmptyVBase)
800 FirstNearlyEmptyVBase = Base;
Mike Stump6f3793b2009-08-12 21:50:08 +0000801 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000802
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000803 SelectPrimaryVBase(Base);
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000804 if (PrimaryBase)
Zhongxing Xuec345b72010-02-15 04:28:35 +0000805 return;
Mike Stump6f3793b2009-08-12 21:50:08 +0000806 }
807}
808
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000809/// DeterminePrimaryBase - Determine the primary base of the given class.
Anders Carlssonc2226202010-05-26 05:58:59 +0000810void RecordLayoutBuilder::DeterminePrimaryBase(const CXXRecordDecl *RD) {
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000811 // If the class isn't dynamic, it won't have a primary base.
812 if (!RD->isDynamicClass())
813 return;
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000814
Anders Carlsson81430692009-09-22 03:02:06 +0000815 // Compute all the primary virtual bases for all of our direct and
Mike Stump590a7c72009-08-13 23:26:06 +0000816 // indirect bases, and record all their primary virtual base classes.
Anders Carlsson5adde292010-11-24 22:55:48 +0000817 RD->getIndirectPrimaryBases(IndirectPrimaryBases);
Mike Stump590a7c72009-08-13 23:26:06 +0000818
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000819 // If the record has a dynamic base class, attempt to choose a primary base
820 // class. It is the first (in direct base class order) non-virtual dynamic
Anders Carlsson81430692009-09-22 03:02:06 +0000821 // base class, if one exists.
Aaron Ballman574705e2014-03-13 15:41:46 +0000822 for (const auto &I : RD->bases()) {
Anders Carlsson03ff3792009-11-27 22:05:05 +0000823 // Ignore virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000824 if (I.isVirtual())
Anders Carlsson03ff3792009-11-27 22:05:05 +0000825 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000826
Anders Carlsson03ff3792009-11-27 22:05:05 +0000827 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +0000828 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Anders Carlsson03ff3792009-11-27 22:05:05 +0000829
Warren Hunt55d8e822013-10-23 23:53:07 +0000830 if (Base->isDynamicClass()) {
Anders Carlsson03ff3792009-11-27 22:05:05 +0000831 // We found it.
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000832 PrimaryBase = Base;
833 PrimaryBaseIsVirtual = false;
Anders Carlsson03ff3792009-11-27 22:05:05 +0000834 return;
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000835 }
836 }
837
Eli Friedman5e9534b2011-10-18 00:55:28 +0000838 // Under the Itanium ABI, if there is no non-virtual primary base class,
839 // try to compute the primary virtual base. The primary virtual base is
840 // the first nearly empty virtual base that is not an indirect primary
841 // virtual base class, if one exists.
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000842 if (RD->getNumVBases() != 0) {
843 SelectPrimaryVBase(RD);
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000844 if (PrimaryBase)
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000845 return;
846 }
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000847
Eli Friedman5e9534b2011-10-18 00:55:28 +0000848 // Otherwise, it is the first indirect primary base class, if one exists.
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000849 if (FirstNearlyEmptyVBase) {
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000850 PrimaryBase = FirstNearlyEmptyVBase;
851 PrimaryBaseIsVirtual = true;
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000852 return;
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000853 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000854
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000855 assert(!PrimaryBase && "Should not get here with a primary base!");
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000856}
857
Anders Carlssone3c24c72010-05-29 17:35:14 +0000858BaseSubobjectInfo *
859RecordLayoutBuilder::ComputeBaseSubobjectInfo(const CXXRecordDecl *RD,
860 bool IsVirtual,
861 BaseSubobjectInfo *Derived) {
862 BaseSubobjectInfo *Info;
863
864 if (IsVirtual) {
865 // Check if we already have info about this virtual base.
866 BaseSubobjectInfo *&InfoSlot = VirtualBaseInfo[RD];
867 if (InfoSlot) {
868 assert(InfoSlot->Class == RD && "Wrong class for virtual base info!");
869 return InfoSlot;
870 }
871
872 // We don't, create it.
873 InfoSlot = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
874 Info = InfoSlot;
875 } else {
876 Info = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
877 }
878
879 Info->Class = RD;
880 Info->IsVirtual = IsVirtual;
881 Info->Derived = 0;
882 Info->PrimaryVirtualBaseInfo = 0;
883
884 const CXXRecordDecl *PrimaryVirtualBase = 0;
885 BaseSubobjectInfo *PrimaryVirtualBaseInfo = 0;
886
887 // Check if this base has a primary virtual base.
888 if (RD->getNumVBases()) {
889 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Anders Carlsson7f95cd12010-11-24 23:12:57 +0000890 if (Layout.isPrimaryBaseVirtual()) {
Anders Carlssone3c24c72010-05-29 17:35:14 +0000891 // This base does have a primary virtual base.
892 PrimaryVirtualBase = Layout.getPrimaryBase();
893 assert(PrimaryVirtualBase && "Didn't have a primary virtual base!");
894
895 // Now check if we have base subobject info about this primary base.
896 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
897
898 if (PrimaryVirtualBaseInfo) {
899 if (PrimaryVirtualBaseInfo->Derived) {
900 // We did have info about this primary base, and it turns out that it
901 // has already been claimed as a primary virtual base for another
902 // base.
903 PrimaryVirtualBase = 0;
904 } else {
905 // We can claim this base as our primary base.
906 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
907 PrimaryVirtualBaseInfo->Derived = Info;
908 }
909 }
910 }
911 }
912
913 // Now go through all direct bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000914 for (const auto &I : RD->bases()) {
915 bool IsVirtual = I.isVirtual();
Anders Carlssone3c24c72010-05-29 17:35:14 +0000916
917 const CXXRecordDecl *BaseDecl =
Aaron Ballman574705e2014-03-13 15:41:46 +0000918 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Anders Carlssone3c24c72010-05-29 17:35:14 +0000919
920 Info->Bases.push_back(ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, Info));
921 }
922
923 if (PrimaryVirtualBase && !PrimaryVirtualBaseInfo) {
924 // Traversing the bases must have created the base info for our primary
925 // virtual base.
926 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
927 assert(PrimaryVirtualBaseInfo &&
928 "Did not create a primary virtual base!");
929
930 // Claim the primary virtual base as our primary virtual base.
931 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
932 PrimaryVirtualBaseInfo->Derived = Info;
933 }
934
935 return Info;
936}
937
938void RecordLayoutBuilder::ComputeBaseSubobjectInfo(const CXXRecordDecl *RD) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000939 for (const auto &I : RD->bases()) {
940 bool IsVirtual = I.isVirtual();
Anders Carlssone3c24c72010-05-29 17:35:14 +0000941
942 const CXXRecordDecl *BaseDecl =
Aaron Ballman574705e2014-03-13 15:41:46 +0000943 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Anders Carlssone3c24c72010-05-29 17:35:14 +0000944
945 // Compute the base subobject info for this base.
946 BaseSubobjectInfo *Info = ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, 0);
947
948 if (IsVirtual) {
949 // ComputeBaseInfo has already added this base for us.
950 assert(VirtualBaseInfo.count(BaseDecl) &&
951 "Did not add virtual base!");
952 } else {
953 // Add the base info to the map of non-virtual bases.
954 assert(!NonVirtualBaseInfo.count(BaseDecl) &&
955 "Non-virtual base already exists!");
956 NonVirtualBaseInfo.insert(std::make_pair(BaseDecl, Info));
957 }
958 }
959}
960
Anders Carlsson09ffa322010-03-10 22:21:28 +0000961void
Eli Friedman43114f92011-10-21 22:49:56 +0000962RecordLayoutBuilder::EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign) {
Eli Friedman5e9534b2011-10-18 00:55:28 +0000963 CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
964
965 // The maximum field alignment overrides base align.
966 if (!MaxFieldAlignment.isZero()) {
967 BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
968 UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
969 }
970
971 // Round up the current record size to pointer alignment.
Eli Friedman43114f92011-10-21 22:49:56 +0000972 setSize(getSize().RoundUpToAlignment(BaseAlign));
973 setDataSize(getSize());
Eli Friedman5e9534b2011-10-18 00:55:28 +0000974
975 // Update the alignment.
976 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
977}
978
979void
Anders Carlssonc2226202010-05-26 05:58:59 +0000980RecordLayoutBuilder::LayoutNonVirtualBases(const CXXRecordDecl *RD) {
Anders Carlssone3c24c72010-05-29 17:35:14 +0000981 // Then, determine the primary base class.
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000982 DeterminePrimaryBase(RD);
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000983
Anders Carlssone3c24c72010-05-29 17:35:14 +0000984 // Compute base subobject info.
985 ComputeBaseSubobjectInfo(RD);
986
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000987 // If we have a primary base class, lay it out.
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000988 if (PrimaryBase) {
989 if (PrimaryBaseIsVirtual) {
Anders Carlssone3c24c72010-05-29 17:35:14 +0000990 // If the primary virtual base was a primary virtual base of some other
991 // base class we'll have to steal it.
992 BaseSubobjectInfo *PrimaryBaseInfo = VirtualBaseInfo.lookup(PrimaryBase);
993 PrimaryBaseInfo->Derived = 0;
994
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000995 // We have a virtual primary base, insert it as an indirect primary base.
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000996 IndirectPrimaryBases.insert(PrimaryBase);
Anders Carlssonfe900962010-03-11 05:42:17 +0000997
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000998 assert(!VisitedVirtualBases.count(PrimaryBase) &&
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000999 "vbase already visited!");
1000 VisitedVirtualBases.insert(PrimaryBase);
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001001
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001002 LayoutVirtualBase(PrimaryBaseInfo);
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001003 } else {
1004 BaseSubobjectInfo *PrimaryBaseInfo =
1005 NonVirtualBaseInfo.lookup(PrimaryBase);
1006 assert(PrimaryBaseInfo &&
1007 "Did not find base info for non-virtual primary base!");
1008
1009 LayoutNonVirtualBase(PrimaryBaseInfo);
1010 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001011
John McCall0153cd32011-11-08 04:01:03 +00001012 // If this class needs a vtable/vf-table and didn't get one from a
1013 // primary base, add it in now.
Warren Hunt55d8e822013-10-23 23:53:07 +00001014 } else if (RD->isDynamicClass()) {
Eli Friedman5e9534b2011-10-18 00:55:28 +00001015 assert(DataSize == 0 && "Vtable pointer must be at offset zero!");
Eli Friedman5e9534b2011-10-18 00:55:28 +00001016 CharUnits PtrWidth =
1017 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Eli Friedman43114f92011-10-21 22:49:56 +00001018 CharUnits PtrAlign =
1019 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0));
1020 EnsureVTablePointerAlignment(PtrAlign);
John McCalle42a3362012-05-01 08:55:32 +00001021 HasOwnVFPtr = true;
Eli Friedman5e9534b2011-10-18 00:55:28 +00001022 setSize(getSize() + PtrWidth);
1023 setDataSize(getSize());
1024 }
1025
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001026 // Now lay out the non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001027 for (const auto &I : RD->bases()) {
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001028
Benjamin Kramer273670a2013-10-25 07:40:50 +00001029 // Ignore virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001030 if (I.isVirtual())
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001031 continue;
1032
Aaron Ballman574705e2014-03-13 15:41:46 +00001033 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001034
John McCall0153cd32011-11-08 04:01:03 +00001035 // Skip the primary base, because we've already laid it out. The
1036 // !PrimaryBaseIsVirtual check is required because we might have a
1037 // non-virtual base of the same type as a primary virtual base.
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001038 if (BaseDecl == PrimaryBase && !PrimaryBaseIsVirtual)
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001039 continue;
1040
1041 // Lay out the base.
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001042 BaseSubobjectInfo *BaseInfo = NonVirtualBaseInfo.lookup(BaseDecl);
1043 assert(BaseInfo && "Did not find base info for non-virtual base!");
1044
1045 LayoutNonVirtualBase(BaseInfo);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001046 }
1047}
1048
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001049void RecordLayoutBuilder::LayoutNonVirtualBase(const BaseSubobjectInfo *Base) {
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001050 // Layout the base.
Anders Carlssona2f8e412010-10-31 22:20:42 +00001051 CharUnits Offset = LayoutBase(Base);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001052
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001053 // Add its base class offset.
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001054 assert(!Bases.count(Base->Class) && "base offset already exists!");
Anders Carlssona2f8e412010-10-31 22:20:42 +00001055 Bases.insert(std::make_pair(Base->Class, Offset));
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001056
1057 AddPrimaryVirtualBaseOffsets(Base, Offset);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001058}
Mike Stump2b84dd32009-11-05 04:02:15 +00001059
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001060void
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001061RecordLayoutBuilder::AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
Anders Carlssona2f8e412010-10-31 22:20:42 +00001062 CharUnits Offset) {
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001063 // This base isn't interesting, it has no virtual bases.
1064 if (!Info->Class->getNumVBases())
1065 return;
1066
1067 // First, check if we have a virtual primary base to add offsets for.
1068 if (Info->PrimaryVirtualBaseInfo) {
1069 assert(Info->PrimaryVirtualBaseInfo->IsVirtual &&
1070 "Primary virtual base is not virtual!");
1071 if (Info->PrimaryVirtualBaseInfo->Derived == Info) {
1072 // Add the offset.
1073 assert(!VBases.count(Info->PrimaryVirtualBaseInfo->Class) &&
1074 "primary vbase offset already exists!");
1075 VBases.insert(std::make_pair(Info->PrimaryVirtualBaseInfo->Class,
John McCalle42a3362012-05-01 08:55:32 +00001076 ASTRecordLayout::VBaseInfo(Offset, false)));
Anders Carlssonea7b1822010-04-15 16:12:58 +00001077
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001078 // Traverse the primary virtual base.
1079 AddPrimaryVirtualBaseOffsets(Info->PrimaryVirtualBaseInfo, Offset);
1080 }
Anders Carlssonea7b1822010-04-15 16:12:58 +00001081 }
1082
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001083 // Now go through all direct non-virtual bases.
1084 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
1085 for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) {
1086 const BaseSubobjectInfo *Base = Info->Bases[I];
1087 if (Base->IsVirtual)
Anders Carlssonea7b1822010-04-15 16:12:58 +00001088 continue;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001089
Anders Carlsson0a14ee92010-11-01 00:21:58 +00001090 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001091 AddPrimaryVirtualBaseOffsets(Base, BaseOffset);
Anders Carlssonea7b1822010-04-15 16:12:58 +00001092 }
1093}
1094
1095void
Anders Carlssonc2226202010-05-26 05:58:59 +00001096RecordLayoutBuilder::LayoutVirtualBases(const CXXRecordDecl *RD,
Anders Carlssonea7b1822010-04-15 16:12:58 +00001097 const CXXRecordDecl *MostDerivedClass) {
Anders Carlssonde710c92010-03-11 04:33:54 +00001098 const CXXRecordDecl *PrimaryBase;
Anders Carlsson291279e2010-04-10 18:42:27 +00001099 bool PrimaryBaseIsVirtual;
Anders Carlssonfe900962010-03-11 05:42:17 +00001100
Anders Carlsson291279e2010-04-10 18:42:27 +00001101 if (MostDerivedClass == RD) {
Anders Carlssond20e7cd2010-05-26 05:20:58 +00001102 PrimaryBase = this->PrimaryBase;
1103 PrimaryBaseIsVirtual = this->PrimaryBaseIsVirtual;
Anders Carlsson291279e2010-04-10 18:42:27 +00001104 } else {
Anders Carlsson5efc56e2010-04-16 15:07:51 +00001105 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Anders Carlssonde710c92010-03-11 04:33:54 +00001106 PrimaryBase = Layout.getPrimaryBase();
Anders Carlsson7f95cd12010-11-24 23:12:57 +00001107 PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
Anders Carlsson291279e2010-04-10 18:42:27 +00001108 }
1109
Aaron Ballman574705e2014-03-13 15:41:46 +00001110 for (const auto &I : RD->bases()) {
1111 assert(!I.getType()->isDependentType() &&
Sebastian Redl1054fae2009-10-25 17:03:50 +00001112 "Cannot layout class with dependent bases.");
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001113
Aaron Ballman574705e2014-03-13 15:41:46 +00001114 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
Anders Carlssonf7b7a1e2010-03-11 04:24:02 +00001115
Aaron Ballman574705e2014-03-13 15:41:46 +00001116 if (I.isVirtual()) {
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001117 if (PrimaryBase != BaseDecl || !PrimaryBaseIsVirtual) {
1118 bool IndirectPrimaryBase = IndirectPrimaryBases.count(BaseDecl);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001119
Anders Carlsson291279e2010-04-10 18:42:27 +00001120 // Only lay out the virtual base if it's not an indirect primary base.
1121 if (!IndirectPrimaryBase) {
1122 // Only visit virtual bases once.
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001123 if (!VisitedVirtualBases.insert(BaseDecl))
Anders Carlsson291279e2010-04-10 18:42:27 +00001124 continue;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001125
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001126 const BaseSubobjectInfo *BaseInfo = VirtualBaseInfo.lookup(BaseDecl);
1127 assert(BaseInfo && "Did not find virtual base info!");
1128 LayoutVirtualBase(BaseInfo);
Anders Carlsson6a848892010-03-11 04:10:39 +00001129 }
Mike Stump2b84dd32009-11-05 04:02:15 +00001130 }
Mike Stumpc2f591b2009-08-13 22:53:07 +00001131 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001132
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001133 if (!BaseDecl->getNumVBases()) {
Anders Carlssonf7b7a1e2010-03-11 04:24:02 +00001134 // This base isn't interesting since it doesn't have any virtual bases.
1135 continue;
Mike Stump996576f32009-08-16 19:04:13 +00001136 }
Anders Carlssonf7b7a1e2010-03-11 04:24:02 +00001137
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001138 LayoutVirtualBases(BaseDecl, MostDerivedClass);
Mike Stump6b2556f2009-08-06 13:41:24 +00001139 }
1140}
1141
Warren Hunt55d8e822013-10-23 23:53:07 +00001142void RecordLayoutBuilder::LayoutVirtualBase(const BaseSubobjectInfo *Base) {
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001143 assert(!Base->Derived && "Trying to lay out a primary virtual base!");
1144
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001145 // Layout the base.
Anders Carlssona2f8e412010-10-31 22:20:42 +00001146 CharUnits Offset = LayoutBase(Base);
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001147
1148 // Add its base class offset.
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001149 assert(!VBases.count(Base->Class) && "vbase offset already exists!");
John McCalle42a3362012-05-01 08:55:32 +00001150 VBases.insert(std::make_pair(Base->Class,
Warren Hunt55d8e822013-10-23 23:53:07 +00001151 ASTRecordLayout::VBaseInfo(Offset, false)));
John McCalle42a3362012-05-01 08:55:32 +00001152
Warren Hunt55d8e822013-10-23 23:53:07 +00001153 AddPrimaryVirtualBaseOffsets(Base, Offset);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001154}
1155
Anders Carlssona2f8e412010-10-31 22:20:42 +00001156CharUnits RecordLayoutBuilder::LayoutBase(const BaseSubobjectInfo *Base) {
Anders Carlssond7f3fcf2010-05-29 20:47:33 +00001157 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base->Class);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001158
Douglas Gregore9fc3772012-01-26 07:55:45 +00001159
1160 CharUnits Offset;
1161
1162 // Query the external layout to see if it provides an offset.
1163 bool HasExternalLayout = false;
1164 if (ExternalLayout) {
1165 llvm::DenseMap<const CXXRecordDecl *, CharUnits>::iterator Known;
1166 if (Base->IsVirtual) {
1167 Known = ExternalVirtualBaseOffsets.find(Base->Class);
1168 if (Known != ExternalVirtualBaseOffsets.end()) {
1169 Offset = Known->second;
1170 HasExternalLayout = true;
1171 }
1172 } else {
1173 Known = ExternalBaseOffsets.find(Base->Class);
1174 if (Known != ExternalBaseOffsets.end()) {
1175 Offset = Known->second;
1176 HasExternalLayout = true;
1177 }
1178 }
1179 }
1180
Warren Huntd640d7d2014-01-09 00:30:56 +00001181 CharUnits UnpackedBaseAlign = Layout.getNonVirtualAlignment();
Eli Friedman69d27d22013-07-16 00:21:28 +00001182 CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
1183
Anders Carlsson09ffa322010-03-10 22:21:28 +00001184 // If we have an empty base class, try to place it at offset 0.
Anders Carlssond7f3fcf2010-05-29 20:47:33 +00001185 if (Base->Class->isEmpty() &&
Douglas Gregore9fc3772012-01-26 07:55:45 +00001186 (!HasExternalLayout || Offset == CharUnits::Zero()) &&
Anders Carlsson28466ab2010-10-31 22:13:23 +00001187 EmptySubobjects->CanPlaceBaseAtOffset(Base, CharUnits::Zero())) {
Ken Dyck1b4420e2011-02-28 02:01:38 +00001188 setSize(std::max(getSize(), Layout.getSize()));
Eli Friedman69d27d22013-07-16 00:21:28 +00001189 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001190
Anders Carlssona2f8e412010-10-31 22:20:42 +00001191 return CharUnits::Zero();
Anders Carlsson09ffa322010-03-10 22:21:28 +00001192 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001193
Argyrios Kyrtzidis8b542742010-12-09 00:35:20 +00001194 // The maximum field alignment overrides base align.
Ken Dyck02ced6f2011-02-17 01:49:42 +00001195 if (!MaxFieldAlignment.isZero()) {
Ken Dyck85ef0432011-02-19 18:58:07 +00001196 BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
1197 UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
Argyrios Kyrtzidis8b542742010-12-09 00:35:20 +00001198 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001199
Douglas Gregore9fc3772012-01-26 07:55:45 +00001200 if (!HasExternalLayout) {
1201 // Round up the current record size to the base's alignment boundary.
1202 Offset = getDataSize().RoundUpToAlignment(BaseAlign);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001203
Douglas Gregore9fc3772012-01-26 07:55:45 +00001204 // Try to place the base.
1205 while (!EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset))
1206 Offset += BaseAlign;
1207 } else {
1208 bool Allowed = EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset);
1209 (void)Allowed;
1210 assert(Allowed && "Base subobject externally placed at overlapping offset");
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001211
1212 if (InferAlignment && Offset < getDataSize().RoundUpToAlignment(BaseAlign)){
1213 // The externally-supplied base offset is before the base offset we
1214 // computed. Assume that the structure is packed.
1215 Alignment = CharUnits::One();
1216 InferAlignment = false;
1217 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00001218 }
1219
Anders Carlssond7f3fcf2010-05-29 20:47:33 +00001220 if (!Base->Class->isEmpty()) {
Anders Carlsson09ffa322010-03-10 22:21:28 +00001221 // Update the data size.
Ken Dyck1b4420e2011-02-28 02:01:38 +00001222 setDataSize(Offset + Layout.getNonVirtualSize());
Anders Carlsson09ffa322010-03-10 22:21:28 +00001223
Ken Dyck1b4420e2011-02-28 02:01:38 +00001224 setSize(std::max(getSize(), getDataSize()));
Anders Carlsson09ffa322010-03-10 22:21:28 +00001225 } else
Ken Dyck1b4420e2011-02-28 02:01:38 +00001226 setSize(std::max(getSize(), Offset + Layout.getSize()));
Anders Carlsson09ffa322010-03-10 22:21:28 +00001227
1228 // Remember max struct/class alignment.
Argyrios Kyrtzidis8b542742010-12-09 00:35:20 +00001229 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001230
Ken Dyck1b4420e2011-02-28 02:01:38 +00001231 return Offset;
Anders Carlsson09ffa322010-03-10 22:21:28 +00001232}
1233
Daniel Dunbar6da10982010-05-27 05:45:51 +00001234void RecordLayoutBuilder::InitializeLayout(const Decl *D) {
Eli Friedman9ee2d0472012-10-12 23:29:20 +00001235 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Daniel Dunbar6da10982010-05-27 05:45:51 +00001236 IsUnion = RD->isUnion();
Eli Friedman9ee2d0472012-10-12 23:29:20 +00001237 IsMsStruct = RD->isMsStruct(Context);
1238 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001239
Eli Friedman9ee2d0472012-10-12 23:29:20 +00001240 Packed = D->hasAttr<PackedAttr>();
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001241
Daniel Dunbar096ed292011-10-05 21:04:55 +00001242 // Honor the default struct packing maximum alignment flag.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001243 if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct) {
Daniel Dunbar096ed292011-10-05 21:04:55 +00001244 MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
1245 }
1246
Daniel Dunbar6da10982010-05-27 05:45:51 +00001247 // mac68k alignment supersedes maximum field alignment and attribute aligned,
1248 // and forces all structures to have 2-byte alignment. The IBM docs on it
1249 // allude to additional (more complicated) semantics, especially with regard
1250 // to bit-fields, but gcc appears not to follow that.
1251 if (D->hasAttr<AlignMac68kAttr>()) {
1252 IsMac68kAlign = true;
Ken Dyck02ced6f2011-02-17 01:49:42 +00001253 MaxFieldAlignment = CharUnits::fromQuantity(2);
Ken Dyck4731d5b2011-02-16 02:05:21 +00001254 Alignment = CharUnits::fromQuantity(2);
Daniel Dunbar6da10982010-05-27 05:45:51 +00001255 } else {
1256 if (const MaxFieldAlignmentAttr *MFAA = D->getAttr<MaxFieldAlignmentAttr>())
Ken Dyck02ced6f2011-02-17 01:49:42 +00001257 MaxFieldAlignment = Context.toCharUnitsFromBits(MFAA->getAlignment());
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001258
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001259 if (unsigned MaxAlign = D->getMaxAlignment())
Ken Dyck85ef0432011-02-19 18:58:07 +00001260 UpdateAlignment(Context.toCharUnitsFromBits(MaxAlign));
Daniel Dunbar6da10982010-05-27 05:45:51 +00001261 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00001262
1263 // If there is an external AST source, ask it for the various offsets.
1264 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
1265 if (ExternalASTSource *External = Context.getExternalSource()) {
1266 ExternalLayout = External->layoutRecordType(RD,
1267 ExternalSize,
1268 ExternalAlign,
1269 ExternalFieldOffsets,
1270 ExternalBaseOffsets,
1271 ExternalVirtualBaseOffsets);
1272
1273 // Update based on external alignment.
1274 if (ExternalLayout) {
Douglas Gregor44ba7892012-01-28 00:53:29 +00001275 if (ExternalAlign > 0) {
1276 Alignment = Context.toCharUnitsFromBits(ExternalAlign);
Douglas Gregor44ba7892012-01-28 00:53:29 +00001277 } else {
1278 // The external source didn't have alignment information; infer it.
1279 InferAlignment = true;
1280 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00001281 }
1282 }
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001283}
Anders Carlsson6d9f6f32009-07-19 00:18:47 +00001284
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001285void RecordLayoutBuilder::Layout(const RecordDecl *D) {
1286 InitializeLayout(D);
Anders Carlsson118ce162009-07-18 21:48:39 +00001287 LayoutFields(D);
Mike Stump11289f42009-09-09 15:08:12 +00001288
Anders Carlsson79474332009-07-18 20:20:21 +00001289 // Finally, round the size of the total struct up to the alignment of the
1290 // struct itself.
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001291 FinishLayout(D);
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001292}
1293
1294void RecordLayoutBuilder::Layout(const CXXRecordDecl *RD) {
1295 InitializeLayout(RD);
1296
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001297 // Lay out the vtable and the non-virtual bases.
1298 LayoutNonVirtualBases(RD);
1299
1300 LayoutFields(RD);
1301
Ken Dycke7380752011-03-10 01:53:59 +00001302 NonVirtualSize = Context.toCharUnitsFromBits(
1303 llvm::RoundUpToAlignment(getSizeInBits(),
Douglas Gregore8bbc122011-09-02 00:18:52 +00001304 Context.getTargetInfo().getCharAlign()));
Ken Dyck4731d5b2011-02-16 02:05:21 +00001305 NonVirtualAlignment = Alignment;
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001306
Warren Hunt55d8e822013-10-23 23:53:07 +00001307 // Lay out the virtual bases and add the primary virtual base offsets.
1308 LayoutVirtualBases(RD, RD);
John McCall0153cd32011-11-08 04:01:03 +00001309
1310 // Finally, round the size of the total struct up to the alignment
Eli Friedman83a12582011-12-01 00:37:01 +00001311 // of the struct itself.
1312 FinishLayout(RD);
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001313
Anders Carlsson5b441d72010-04-10 21:24:48 +00001314#ifndef NDEBUG
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001315 // Check that we have base offsets for all bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001316 for (const auto &I : RD->bases()) {
1317 if (I.isVirtual())
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001318 continue;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001319
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001320 const CXXRecordDecl *BaseDecl =
Aaron Ballman574705e2014-03-13 15:41:46 +00001321 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001322
1323 assert(Bases.count(BaseDecl) && "Did not find base offset!");
1324 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001325
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001326 // And all virtual bases.
1327 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
1328 E = RD->vbases_end(); I != E; ++I) {
1329 const CXXRecordDecl *BaseDecl =
1330 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001331
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001332 assert(VBases.count(BaseDecl) && "Did not find base offset!");
Anders Carlsson5b441d72010-04-10 21:24:48 +00001333 }
1334#endif
Anders Carlsson79474332009-07-18 20:20:21 +00001335}
1336
Anders Carlssonc2226202010-05-26 05:58:59 +00001337void RecordLayoutBuilder::Layout(const ObjCInterfaceDecl *D) {
Anders Carlsson4f516282009-07-18 20:50:59 +00001338 if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
Anders Carlsson5efc56e2010-04-16 15:07:51 +00001339 const ASTRecordLayout &SL = Context.getASTObjCInterfaceLayout(SD);
Anders Carlsson4f516282009-07-18 20:50:59 +00001340
Ken Dyck85ef0432011-02-19 18:58:07 +00001341 UpdateAlignment(SL.getAlignment());
Mike Stump11289f42009-09-09 15:08:12 +00001342
Anders Carlsson4f516282009-07-18 20:50:59 +00001343 // We start laying out ivars not at the end of the superclass
1344 // structure, but at the next byte following the last field.
Ken Dyckecfc7552011-02-24 01:13:28 +00001345 setSize(SL.getDataSize());
Ken Dyck1b4420e2011-02-28 02:01:38 +00001346 setDataSize(getSize());
Anders Carlsson4f516282009-07-18 20:50:59 +00001347 }
Mike Stump11289f42009-09-09 15:08:12 +00001348
Daniel Dunbar6da10982010-05-27 05:45:51 +00001349 InitializeLayout(D);
Anders Carlsson4f516282009-07-18 20:50:59 +00001350 // Layout each ivar sequentially.
Jordy Rosea91768e2011-07-22 02:08:32 +00001351 for (const ObjCIvarDecl *IVD = D->all_declared_ivar_begin(); IVD;
1352 IVD = IVD->getNextIvar())
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001353 LayoutField(IVD);
Mike Stump11289f42009-09-09 15:08:12 +00001354
Anders Carlsson4f516282009-07-18 20:50:59 +00001355 // Finally, round the size of the total struct up to the alignment of the
1356 // struct itself.
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001357 FinishLayout(D);
Anders Carlsson4f516282009-07-18 20:50:59 +00001358}
1359
Anders Carlssonc2226202010-05-26 05:58:59 +00001360void RecordLayoutBuilder::LayoutFields(const RecordDecl *D) {
Anders Carlsson118ce162009-07-18 21:48:39 +00001361 // Layout each field, for now, just sequentially, respecting alignment. In
1362 // the future, this will need to be tweakable by targets.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001363 for (const auto *Field : D->fields())
1364 LayoutField(Field);
Anders Carlsson118ce162009-07-18 21:48:39 +00001365}
1366
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001367void RecordLayoutBuilder::LayoutWideBitField(uint64_t FieldSize,
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001368 uint64_t TypeSize,
1369 bool FieldPacked,
1370 const FieldDecl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001371 assert(Context.getLangOpts().CPlusPlus &&
Anders Carlsson57235162010-04-16 15:57:11 +00001372 "Can only have wide bit-fields in C++!");
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001373
Anders Carlsson57235162010-04-16 15:57:11 +00001374 // Itanium C++ ABI 2.4:
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001375 // If sizeof(T)*8 < n, let T' be the largest integral POD type with
Anders Carlsson57235162010-04-16 15:57:11 +00001376 // sizeof(T')*8 <= n.
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001377
Anders Carlsson57235162010-04-16 15:57:11 +00001378 QualType IntegralPODTypes[] = {
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001379 Context.UnsignedCharTy, Context.UnsignedShortTy, Context.UnsignedIntTy,
Anders Carlsson57235162010-04-16 15:57:11 +00001380 Context.UnsignedLongTy, Context.UnsignedLongLongTy
1381 };
1382
Anders Carlsson57235162010-04-16 15:57:11 +00001383 QualType Type;
1384 for (unsigned I = 0, E = llvm::array_lengthof(IntegralPODTypes);
1385 I != E; ++I) {
1386 uint64_t Size = Context.getTypeSize(IntegralPODTypes[I]);
Anders Carlsson57235162010-04-16 15:57:11 +00001387
1388 if (Size > FieldSize)
1389 break;
1390
1391 Type = IntegralPODTypes[I];
1392 }
1393 assert(!Type.isNull() && "Did not find a type!");
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001394
Ken Dyckdbe37f32011-03-01 01:36:00 +00001395 CharUnits TypeAlign = Context.getTypeAlignInChars(Type);
Anders Carlsson57235162010-04-16 15:57:11 +00001396
1397 // We're not going to use any of the unfilled bits in the last byte.
Eli Friedman2782dac2013-06-26 20:50:34 +00001398 UnfilledBitsInLastUnit = 0;
1399 LastBitfieldTypeSize = 0;
Anders Carlsson57235162010-04-16 15:57:11 +00001400
Anders Carlssonaad5fa82010-04-17 20:21:41 +00001401 uint64_t FieldOffset;
Eli Friedman2782dac2013-06-26 20:50:34 +00001402 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001403
Anders Carlsson57235162010-04-16 15:57:11 +00001404 if (IsUnion) {
Ken Dyckecfc7552011-02-24 01:13:28 +00001405 setDataSize(std::max(getDataSizeInBits(), FieldSize));
Anders Carlssonaad5fa82010-04-17 20:21:41 +00001406 FieldOffset = 0;
Anders Carlsson57235162010-04-16 15:57:11 +00001407 } else {
Chad Rosiere1a6a0e2011-08-05 22:38:04 +00001408 // The bitfield is allocated starting at the next offset aligned
1409 // appropriately for T', with length n bits.
Ken Dyckdbe37f32011-03-01 01:36:00 +00001410 FieldOffset = llvm::RoundUpToAlignment(getDataSizeInBits(),
1411 Context.toBits(TypeAlign));
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001412
Anders Carlsson57235162010-04-16 15:57:11 +00001413 uint64_t NewSizeInBits = FieldOffset + FieldSize;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001414
Ken Dycka1a2e8d2011-03-10 02:00:35 +00001415 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits,
Douglas Gregore8bbc122011-09-02 00:18:52 +00001416 Context.getTargetInfo().getCharAlign()));
Eli Friedman2782dac2013-06-26 20:50:34 +00001417 UnfilledBitsInLastUnit = getDataSizeInBits() - NewSizeInBits;
Anders Carlsson57235162010-04-16 15:57:11 +00001418 }
1419
1420 // Place this field at the current location.
1421 FieldOffsets.push_back(FieldOffset);
1422
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001423 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, FieldOffset,
Ken Dyckdbe37f32011-03-01 01:36:00 +00001424 Context.toBits(TypeAlign), FieldPacked, D);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001425
Anders Carlsson57235162010-04-16 15:57:11 +00001426 // Update the size.
Ken Dyckecfc7552011-02-24 01:13:28 +00001427 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001428
Anders Carlsson57235162010-04-16 15:57:11 +00001429 // Remember max struct/class alignment.
Ken Dyckdbe37f32011-03-01 01:36:00 +00001430 UpdateAlignment(TypeAlign);
Anders Carlsson57235162010-04-16 15:57:11 +00001431}
1432
Anders Carlssonc2226202010-05-26 05:58:59 +00001433void RecordLayoutBuilder::LayoutBitField(const FieldDecl *D) {
Anders Carlsson07209442009-11-22 17:37:31 +00001434 bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
Richard Smithcaf33902011-10-10 18:28:20 +00001435 uint64_t FieldSize = D->getBitWidthValue(Context);
Anders Carlsson5efc56e2010-04-16 15:07:51 +00001436 std::pair<uint64_t, unsigned> FieldInfo = Context.getTypeInfo(D->getType());
Anders Carlsson07209442009-11-22 17:37:31 +00001437 uint64_t TypeSize = FieldInfo.first;
1438 unsigned FieldAlign = FieldInfo.second;
Eli Friedman2782dac2013-06-26 20:50:34 +00001439
John McCall30268ca2014-01-29 07:53:44 +00001440 // UnfilledBitsInLastUnit is the difference between the end of the
1441 // last allocated bitfield (i.e. the first bit offset available for
1442 // bitfields) and the end of the current data size in bits (i.e. the
1443 // first bit offset available for non-bitfields). The current data
1444 // size in bits is always a multiple of the char size; additionally,
1445 // for ms_struct records it's also a multiple of the
1446 // LastBitfieldTypeSize (if set).
1447
John McCall76e1818a2014-02-13 00:50:08 +00001448 // The struct-layout algorithm is dictated by the platform ABI,
1449 // which in principle could use almost any rules it likes. In
1450 // practice, UNIXy targets tend to inherit the algorithm described
1451 // in the System V generic ABI. The basic bitfield layout rule in
1452 // System V is to place bitfields at the next available bit offset
1453 // where the entire bitfield would fit in an aligned storage unit of
1454 // the declared type; it's okay if an earlier or later non-bitfield
1455 // is allocated in the same storage unit. However, some targets
1456 // (those that !useBitFieldTypeAlignment(), e.g. ARM APCS) don't
1457 // require this storage unit to be aligned, and therefore always put
1458 // the bitfield at the next available bit offset.
John McCall30268ca2014-01-29 07:53:44 +00001459
John McCall76e1818a2014-02-13 00:50:08 +00001460 // ms_struct basically requests a complete replacement of the
1461 // platform ABI's struct-layout algorithm, with the high-level goal
1462 // of duplicating MSVC's layout. For non-bitfields, this follows
1463 // the the standard algorithm. The basic bitfield layout rule is to
1464 // allocate an entire unit of the bitfield's declared type
1465 // (e.g. 'unsigned long'), then parcel it up among successive
1466 // bitfields whose declared types have the same size, making a new
1467 // unit as soon as the last can no longer store the whole value.
1468 // Since it completely replaces the platform ABI's algorithm,
1469 // settings like !useBitFieldTypeAlignment() do not apply.
1470
1471 // A zero-width bitfield forces the use of a new storage unit for
1472 // later bitfields. In general, this occurs by rounding up the
1473 // current size of the struct as if the algorithm were about to
1474 // place a non-bitfield of the field's formal type. Usually this
1475 // does not change the alignment of the struct itself, but it does
1476 // on some targets (those that useZeroLengthBitfieldAlignment(),
1477 // e.g. ARM). In ms_struct layout, zero-width bitfields are
1478 // ignored unless they follow a non-zero-width bitfield.
1479
1480 // A field alignment restriction (e.g. from #pragma pack) or
1481 // specification (e.g. from __attribute__((aligned))) changes the
1482 // formal alignment of the field. For System V, this alters the
1483 // required alignment of the notional storage unit that must contain
1484 // the bitfield. For ms_struct, this only affects the placement of
1485 // new storage units. In both cases, the effect of #pragma pack is
1486 // ignored on zero-width bitfields.
1487
1488 // On System V, a packed field (e.g. from #pragma pack or
1489 // __attribute__((packed))) always uses the next available bit
1490 // offset.
1491
John McCall95833f32014-02-27 20:30:49 +00001492 // In an ms_struct struct, the alignment of a fundamental type is
1493 // always equal to its size. This is necessary in order to mimic
1494 // the i386 alignment rules on targets which might not fully align
1495 // all types (e.g. Darwin PPC32, where alignof(long long) == 4).
John McCall30268ca2014-01-29 07:53:44 +00001496
1497 // First, some simple bookkeeping to perform for ms_struct structs.
Eli Friedman2782dac2013-06-26 20:50:34 +00001498 if (IsMsStruct) {
John McCall30268ca2014-01-29 07:53:44 +00001499 // The field alignment for integer types is always the size.
Fariborz Jahanian7adbed62011-05-09 22:03:17 +00001500 FieldAlign = TypeSize;
John McCall30268ca2014-01-29 07:53:44 +00001501
1502 // If the previous field was not a bitfield, or was a bitfield
1503 // with a different storage unit size, we're done with that
1504 // storage unit.
Eli Friedman2782dac2013-06-26 20:50:34 +00001505 if (LastBitfieldTypeSize != TypeSize) {
John McCall30268ca2014-01-29 07:53:44 +00001506 // Also, ignore zero-length bitfields after non-bitfields.
1507 if (!LastBitfieldTypeSize && !FieldSize)
1508 FieldAlign = 1;
1509
Eli Friedman2782dac2013-06-26 20:50:34 +00001510 UnfilledBitsInLastUnit = 0;
1511 LastBitfieldTypeSize = 0;
1512 }
1513 }
1514
John McCall30268ca2014-01-29 07:53:44 +00001515 // If the field is wider than its declared type, it follows
1516 // different rules in all cases.
Anders Carlsson57235162010-04-16 15:57:11 +00001517 if (FieldSize > TypeSize) {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001518 LayoutWideBitField(FieldSize, TypeSize, FieldPacked, D);
Anders Carlsson57235162010-04-16 15:57:11 +00001519 return;
1520 }
1521
John McCall30268ca2014-01-29 07:53:44 +00001522 // Compute the next available bit offset.
1523 uint64_t FieldOffset =
1524 IsUnion ? 0 : (getDataSizeInBits() - UnfilledBitsInLastUnit);
1525
1526 // Handle targets that don't honor bitfield type alignment.
John McCall76e1818a2014-02-13 00:50:08 +00001527 if (!IsMsStruct && !Context.getTargetInfo().useBitFieldTypeAlignment()) {
John McCall30268ca2014-01-29 07:53:44 +00001528 // Some such targets do honor it on zero-width bitfields.
1529 if (FieldSize == 0 &&
1530 Context.getTargetInfo().useZeroLengthBitfieldAlignment()) {
1531 // The alignment to round up to is the max of the field's natural
1532 // alignment and a target-specific fixed value (sometimes zero).
1533 unsigned ZeroLengthBitfieldBoundary =
1534 Context.getTargetInfo().getZeroLengthBitfieldBoundary();
1535 FieldAlign = std::max(FieldAlign, ZeroLengthBitfieldBoundary);
1536
1537 // If that doesn't apply, just ignore the field alignment.
1538 } else {
1539 FieldAlign = 1;
1540 }
1541 }
1542
1543 // Remember the alignment we would have used if the field were not packed.
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001544 unsigned UnpackedFieldAlign = FieldAlign;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001545
Yunzhong Gao5fd0c9d2014-02-13 02:45:10 +00001546 // Ignore the field alignment if the field is packed unless it has zero-size.
1547 if (!IsMsStruct && FieldPacked && FieldSize != 0)
Anders Carlsson07209442009-11-22 17:37:31 +00001548 FieldAlign = 1;
Anders Carlsson07209442009-11-22 17:37:31 +00001549
John McCall30268ca2014-01-29 07:53:44 +00001550 // But, if there's an 'aligned' attribute on the field, honor that.
1551 if (unsigned ExplicitFieldAlign = D->getMaxAlignment()) {
1552 FieldAlign = std::max(FieldAlign, ExplicitFieldAlign);
1553 UnpackedFieldAlign = std::max(UnpackedFieldAlign, ExplicitFieldAlign);
1554 }
1555
1556 // But, if there's a #pragma pack in play, that takes precedent over
1557 // even the 'aligned' attribute, for non-zero-width bitfields.
1558 if (!MaxFieldAlignment.isZero() && FieldSize) {
Ken Dyck02ced6f2011-02-17 01:49:42 +00001559 unsigned MaxFieldAlignmentInBits = Context.toBits(MaxFieldAlignment);
1560 FieldAlign = std::min(FieldAlign, MaxFieldAlignmentInBits);
1561 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignmentInBits);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001562 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001563
John McCall30268ca2014-01-29 07:53:44 +00001564 // For purposes of diagnostics, we're going to simultaneously
1565 // compute the field offsets that we would have used if we weren't
1566 // adding any alignment padding or if the field weren't packed.
1567 uint64_t UnpaddedFieldOffset = FieldOffset;
1568 uint64_t UnpackedFieldOffset = FieldOffset;
1569
1570 // Check if we need to add padding to fit the bitfield within an
1571 // allocation unit with the right size and alignment. The rules are
1572 // somewhat different here for ms_struct structs.
1573 if (IsMsStruct) {
1574 // If it's not a zero-width bitfield, and we can fit the bitfield
1575 // into the active storage unit (and we haven't already decided to
1576 // start a new storage unit), just do so, regardless of any other
1577 // other consideration. Otherwise, round up to the right alignment.
1578 if (FieldSize == 0 || FieldSize > UnfilledBitsInLastUnit) {
1579 FieldOffset = llvm::RoundUpToAlignment(FieldOffset, FieldAlign);
1580 UnpackedFieldOffset = llvm::RoundUpToAlignment(UnpackedFieldOffset,
1581 UnpackedFieldAlign);
1582 UnfilledBitsInLastUnit = 0;
1583 }
1584
1585 } else {
1586 // #pragma pack, with any value, suppresses the insertion of padding.
1587 bool AllowPadding = MaxFieldAlignment.isZero();
1588
1589 // Compute the real offset.
1590 if (FieldSize == 0 ||
1591 (AllowPadding &&
1592 (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize)) {
1593 FieldOffset = llvm::RoundUpToAlignment(FieldOffset, FieldAlign);
1594 }
1595
1596 // Repeat the computation for diagnostic purposes.
1597 if (FieldSize == 0 ||
1598 (AllowPadding &&
1599 (UnpackedFieldOffset & (UnpackedFieldAlign-1)) + FieldSize > TypeSize))
1600 UnpackedFieldOffset = llvm::RoundUpToAlignment(UnpackedFieldOffset,
1601 UnpackedFieldAlign);
Eli Friedman2782dac2013-06-26 20:50:34 +00001602 }
1603
John McCall30268ca2014-01-29 07:53:44 +00001604 // If we're using external layout, give the external layout a chance
1605 // to override this information.
Douglas Gregor44ba7892012-01-28 00:53:29 +00001606 if (ExternalLayout)
1607 FieldOffset = updateExternalFieldOffset(D, FieldOffset);
1608
John McCall30268ca2014-01-29 07:53:44 +00001609 // Okay, place the bitfield at the calculated offset.
Anders Carlsson07209442009-11-22 17:37:31 +00001610 FieldOffsets.push_back(FieldOffset);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001611
John McCall30268ca2014-01-29 07:53:44 +00001612 // Bookkeeping:
1613
1614 // Anonymous members don't affect the overall record alignment,
1615 // except on targets where they do.
1616 if (!IsMsStruct &&
1617 !Context.getTargetInfo().useZeroLengthBitfieldAlignment() &&
1618 !D->getIdentifier())
1619 FieldAlign = UnpackedFieldAlign = 1;
1620
1621 // Diagnose differences in layout due to padding or packing.
Douglas Gregore9fc3772012-01-26 07:55:45 +00001622 if (!ExternalLayout)
1623 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, UnpackedFieldOffset,
1624 UnpackedFieldAlign, FieldPacked, D);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001625
Anders Carlssonba958402009-11-22 19:13:51 +00001626 // Update DataSize to include the last byte containing (part of) the bitfield.
John McCall30268ca2014-01-29 07:53:44 +00001627
1628 // For unions, this is just a max operation, as usual.
Anders Carlssonba958402009-11-22 19:13:51 +00001629 if (IsUnion) {
1630 // FIXME: I think FieldSize should be TypeSize here.
Ken Dyckecfc7552011-02-24 01:13:28 +00001631 setDataSize(std::max(getDataSizeInBits(), FieldSize));
John McCall30268ca2014-01-29 07:53:44 +00001632
1633 // For non-zero-width bitfields in ms_struct structs, allocate a new
1634 // storage unit if necessary.
1635 } else if (IsMsStruct && FieldSize) {
1636 // We should have cleared UnfilledBitsInLastUnit in every case
1637 // where we changed storage units.
1638 if (!UnfilledBitsInLastUnit) {
1639 setDataSize(FieldOffset + TypeSize);
1640 UnfilledBitsInLastUnit = TypeSize;
Eli Friedman2782dac2013-06-26 20:50:34 +00001641 }
John McCall30268ca2014-01-29 07:53:44 +00001642 UnfilledBitsInLastUnit -= FieldSize;
1643 LastBitfieldTypeSize = TypeSize;
1644
1645 // Otherwise, bump the data size up to include the bitfield,
1646 // including padding up to char alignment, and then remember how
1647 // bits we didn't use.
1648 } else {
1649 uint64_t NewSizeInBits = FieldOffset + FieldSize;
1650 uint64_t CharAlignment = Context.getTargetInfo().getCharAlign();
1651 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits, CharAlignment));
1652 UnfilledBitsInLastUnit = getDataSizeInBits() - NewSizeInBits;
1653
1654 // The only time we can get here for an ms_struct is if this is a
1655 // zero-width bitfield, which doesn't count as anything for the
1656 // purposes of unfilled bits.
1657 LastBitfieldTypeSize = 0;
Anders Carlssonba958402009-11-22 19:13:51 +00001658 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001659
Anders Carlssonba958402009-11-22 19:13:51 +00001660 // Update the size.
Ken Dyckecfc7552011-02-24 01:13:28 +00001661 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001662
Anders Carlsson07209442009-11-22 17:37:31 +00001663 // Remember max struct/class alignment.
Ken Dyck85ef0432011-02-19 18:58:07 +00001664 UpdateAlignment(Context.toCharUnitsFromBits(FieldAlign),
1665 Context.toCharUnitsFromBits(UnpackedFieldAlign));
Anders Carlsson07209442009-11-22 17:37:31 +00001666}
1667
Douglas Gregore9fc3772012-01-26 07:55:45 +00001668void RecordLayoutBuilder::LayoutField(const FieldDecl *D) {
Anders Carlsson07209442009-11-22 17:37:31 +00001669 if (D->isBitField()) {
1670 LayoutBitField(D);
1671 return;
1672 }
1673
Eli Friedman2782dac2013-06-26 20:50:34 +00001674 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001675
Anders Carlssonba958402009-11-22 19:13:51 +00001676 // Reset the unfilled bits.
Eli Friedman2782dac2013-06-26 20:50:34 +00001677 UnfilledBitsInLastUnit = 0;
1678 LastBitfieldTypeSize = 0;
Anders Carlssonba958402009-11-22 19:13:51 +00001679
Anders Carlsson07209442009-11-22 17:37:31 +00001680 bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
Ken Dyck6d90e892011-02-20 02:06:09 +00001681 CharUnits FieldOffset =
Ken Dyckecfc7552011-02-24 01:13:28 +00001682 IsUnion ? CharUnits::Zero() : getDataSize();
Ken Dyck6d90e892011-02-20 02:06:09 +00001683 CharUnits FieldSize;
1684 CharUnits FieldAlign;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001685
Anders Carlsson07209442009-11-22 17:37:31 +00001686 if (D->getType()->isIncompleteArrayType()) {
1687 // This is a flexible array member; we can't directly
1688 // query getTypeInfo about these, so we figure it out here.
1689 // Flexible array members don't have any size, but they
1690 // have to be aligned appropriately for their element type.
Ken Dyck6d90e892011-02-20 02:06:09 +00001691 FieldSize = CharUnits::Zero();
Anders Carlsson5efc56e2010-04-16 15:07:51 +00001692 const ArrayType* ATy = Context.getAsArrayType(D->getType());
Ken Dyck6d90e892011-02-20 02:06:09 +00001693 FieldAlign = Context.getTypeAlignInChars(ATy->getElementType());
Anders Carlsson07209442009-11-22 17:37:31 +00001694 } else if (const ReferenceType *RT = D->getType()->getAs<ReferenceType>()) {
1695 unsigned AS = RT->getPointeeType().getAddressSpace();
Ken Dyck6d90e892011-02-20 02:06:09 +00001696 FieldSize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001697 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(AS));
Ken Dyck6d90e892011-02-20 02:06:09 +00001698 FieldAlign =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001699 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(AS));
Anders Carlsson79474332009-07-18 20:20:21 +00001700 } else {
Ken Dyck6d90e892011-02-20 02:06:09 +00001701 std::pair<CharUnits, CharUnits> FieldInfo =
1702 Context.getTypeInfoInChars(D->getType());
Anders Carlsson07209442009-11-22 17:37:31 +00001703 FieldSize = FieldInfo.first;
1704 FieldAlign = FieldInfo.second;
Chad Rosier18903ee2011-08-04 01:21:14 +00001705
Eli Friedman9ee2d0472012-10-12 23:29:20 +00001706 if (IsMsStruct) {
Douglas Gregordbe39272011-02-01 15:15:22 +00001707 // If MS bitfield layout is required, figure out what type is being
1708 // laid out and align the field to the width of that type.
1709
1710 // Resolve all typedefs down to their base type and round up the field
1711 // alignment if necessary.
1712 QualType T = Context.getBaseElementType(D->getType());
1713 if (const BuiltinType *BTy = T->getAs<BuiltinType>()) {
Ken Dyck6d90e892011-02-20 02:06:09 +00001714 CharUnits TypeSize = Context.getTypeSizeInChars(BTy);
Douglas Gregordbe39272011-02-01 15:15:22 +00001715 if (TypeSize > FieldAlign)
1716 FieldAlign = TypeSize;
1717 }
1718 }
Anders Carlsson79474332009-07-18 20:20:21 +00001719 }
Mike Stump11289f42009-09-09 15:08:12 +00001720
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001721 // The align if the field is not packed. This is to check if the attribute
1722 // was unnecessary (-Wpacked).
Ken Dyck6d90e892011-02-20 02:06:09 +00001723 CharUnits UnpackedFieldAlign = FieldAlign;
1724 CharUnits UnpackedFieldOffset = FieldOffset;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001725
Anders Carlsson07209442009-11-22 17:37:31 +00001726 if (FieldPacked)
Ken Dyck6d90e892011-02-20 02:06:09 +00001727 FieldAlign = CharUnits::One();
1728 CharUnits MaxAlignmentInChars =
1729 Context.toCharUnitsFromBits(D->getMaxAlignment());
1730 FieldAlign = std::max(FieldAlign, MaxAlignmentInChars);
1731 UnpackedFieldAlign = std::max(UnpackedFieldAlign, MaxAlignmentInChars);
Anders Carlsson07209442009-11-22 17:37:31 +00001732
1733 // The maximum field alignment overrides the aligned attribute.
Ken Dyck02ced6f2011-02-17 01:49:42 +00001734 if (!MaxFieldAlignment.isZero()) {
Ken Dyck6d90e892011-02-20 02:06:09 +00001735 FieldAlign = std::min(FieldAlign, MaxFieldAlignment);
1736 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignment);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001737 }
Anders Carlsson07209442009-11-22 17:37:31 +00001738
Douglas Gregor44ba7892012-01-28 00:53:29 +00001739 // Round up the current record size to the field's alignment boundary.
1740 FieldOffset = FieldOffset.RoundUpToAlignment(FieldAlign);
1741 UnpackedFieldOffset =
1742 UnpackedFieldOffset.RoundUpToAlignment(UnpackedFieldAlign);
1743
1744 if (ExternalLayout) {
1745 FieldOffset = Context.toCharUnitsFromBits(
1746 updateExternalFieldOffset(D, Context.toBits(FieldOffset)));
1747
1748 if (!IsUnion && EmptySubobjects) {
1749 // Record the fact that we're placing a field at this offset.
1750 bool Allowed = EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset);
1751 (void)Allowed;
1752 assert(Allowed && "Externally-placed field cannot be placed here");
1753 }
1754 } else {
Douglas Gregore9fc3772012-01-26 07:55:45 +00001755 if (!IsUnion && EmptySubobjects) {
1756 // Check if we can place the field at this offset.
1757 while (!EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset)) {
1758 // We couldn't place the field at the offset. Try again at a new offset.
1759 FieldOffset += FieldAlign;
1760 }
Anders Carlsson07209442009-11-22 17:37:31 +00001761 }
Anders Carlsson07209442009-11-22 17:37:31 +00001762 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00001763
Anders Carlsson79474332009-07-18 20:20:21 +00001764 // Place this field at the current location.
Ken Dyck6d90e892011-02-20 02:06:09 +00001765 FieldOffsets.push_back(Context.toBits(FieldOffset));
Mike Stump11289f42009-09-09 15:08:12 +00001766
Douglas Gregore9fc3772012-01-26 07:55:45 +00001767 if (!ExternalLayout)
1768 CheckFieldPadding(Context.toBits(FieldOffset), UnpaddedFieldOffset,
1769 Context.toBits(UnpackedFieldOffset),
1770 Context.toBits(UnpackedFieldAlign), FieldPacked, D);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001771
Anders Carlsson79474332009-07-18 20:20:21 +00001772 // Reserve space for this field.
Eli Friedman43f18342012-01-12 23:27:03 +00001773 uint64_t FieldSizeInBits = Context.toBits(FieldSize);
Anders Carlsson79474332009-07-18 20:20:21 +00001774 if (IsUnion)
Eli Friedman2e108372012-01-12 23:48:56 +00001775 setDataSize(std::max(getDataSizeInBits(), FieldSizeInBits));
Anders Carlsson79474332009-07-18 20:20:21 +00001776 else
Eli Friedman2e108372012-01-12 23:48:56 +00001777 setDataSize(FieldOffset + FieldSize);
Mike Stump11289f42009-09-09 15:08:12 +00001778
Eli Friedman2e108372012-01-12 23:48:56 +00001779 // Update the size.
1780 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
Mike Stump11289f42009-09-09 15:08:12 +00001781
Anders Carlsson79474332009-07-18 20:20:21 +00001782 // Remember max struct/class alignment.
Ken Dyck6d90e892011-02-20 02:06:09 +00001783 UpdateAlignment(FieldAlign, UnpackedFieldAlign);
Anders Carlsson79474332009-07-18 20:20:21 +00001784}
1785
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001786void RecordLayoutBuilder::FinishLayout(const NamedDecl *D) {
Anders Carlsson79474332009-07-18 20:20:21 +00001787 // In C++, records cannot be of size 0.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001788 if (Context.getLangOpts().CPlusPlus && getSizeInBits() == 0) {
Fariborz Jahanian09b23312011-02-02 19:36:18 +00001789 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
1790 // Compatibility with gcc requires a class (pod or non-pod)
1791 // which is not empty but of size 0; such as having fields of
1792 // array of zero-length, remains of Size 0
1793 if (RD->isEmpty())
Ken Dyck1b4420e2011-02-28 02:01:38 +00001794 setSize(CharUnits::One());
Fariborz Jahanian09b23312011-02-02 19:36:18 +00001795 }
1796 else
Ken Dyck1b4420e2011-02-28 02:01:38 +00001797 setSize(CharUnits::One());
Fariborz Jahanian09b23312011-02-02 19:36:18 +00001798 }
Eli Friedman83a12582011-12-01 00:37:01 +00001799
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001800 // Finally, round the size of the record up to the alignment of the
1801 // record itself.
Eli Friedman2782dac2013-06-26 20:50:34 +00001802 uint64_t UnpaddedSize = getSizeInBits() - UnfilledBitsInLastUnit;
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001803 uint64_t UnpackedSizeInBits =
1804 llvm::RoundUpToAlignment(getSizeInBits(),
1805 Context.toBits(UnpackedAlignment));
1806 CharUnits UnpackedSize = Context.toCharUnitsFromBits(UnpackedSizeInBits);
1807 uint64_t RoundedSize
1808 = llvm::RoundUpToAlignment(getSizeInBits(), Context.toBits(Alignment));
1809
1810 if (ExternalLayout) {
1811 // If we're inferring alignment, and the external size is smaller than
1812 // our size after we've rounded up to alignment, conservatively set the
1813 // alignment to 1.
1814 if (InferAlignment && ExternalSize < RoundedSize) {
1815 Alignment = CharUnits::One();
1816 InferAlignment = false;
1817 }
1818 setSize(ExternalSize);
1819 return;
1820 }
1821
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001822 // Set the size to the final size.
1823 setSize(RoundedSize);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001824
Douglas Gregore8bbc122011-09-02 00:18:52 +00001825 unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001826 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
1827 // Warn if padding was introduced to the struct/class/union.
Ken Dyckecfc7552011-02-24 01:13:28 +00001828 if (getSizeInBits() > UnpaddedSize) {
1829 unsigned PadSize = getSizeInBits() - UnpaddedSize;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001830 bool InBits = true;
1831 if (PadSize % CharBitNum == 0) {
1832 PadSize = PadSize / CharBitNum;
1833 InBits = false;
1834 }
1835 Diag(RD->getLocation(), diag::warn_padded_struct_size)
1836 << Context.getTypeDeclType(RD)
1837 << PadSize
1838 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1); // plural or not
1839 }
1840
1841 // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
1842 // bother since there won't be alignment issues.
Ken Dyckecfc7552011-02-24 01:13:28 +00001843 if (Packed && UnpackedAlignment > CharUnits::One() &&
Ken Dyck1b4420e2011-02-28 02:01:38 +00001844 getSize() == UnpackedSize)
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001845 Diag(D->getLocation(), diag::warn_unnecessary_packed)
1846 << Context.getTypeDeclType(RD);
1847 }
Anders Carlsson79474332009-07-18 20:20:21 +00001848}
1849
Ken Dyck85ef0432011-02-19 18:58:07 +00001850void RecordLayoutBuilder::UpdateAlignment(CharUnits NewAlignment,
1851 CharUnits UnpackedNewAlignment) {
Douglas Gregore9fc3772012-01-26 07:55:45 +00001852 // The alignment is not modified when using 'mac68k' alignment or when
Douglas Gregor44ba7892012-01-28 00:53:29 +00001853 // we have an externally-supplied layout that also provides overall alignment.
1854 if (IsMac68kAlign || (ExternalLayout && !InferAlignment))
Daniel Dunbar6da10982010-05-27 05:45:51 +00001855 return;
1856
Ken Dyck85ef0432011-02-19 18:58:07 +00001857 if (NewAlignment > Alignment) {
1858 assert(llvm::isPowerOf2_32(NewAlignment.getQuantity() &&
1859 "Alignment not a power of 2"));
1860 Alignment = NewAlignment;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001861 }
1862
Ken Dyck85ef0432011-02-19 18:58:07 +00001863 if (UnpackedNewAlignment > UnpackedAlignment) {
1864 assert(llvm::isPowerOf2_32(UnpackedNewAlignment.getQuantity() &&
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001865 "Alignment not a power of 2"));
Ken Dyck85ef0432011-02-19 18:58:07 +00001866 UnpackedAlignment = UnpackedNewAlignment;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001867 }
1868}
1869
Douglas Gregor44ba7892012-01-28 00:53:29 +00001870uint64_t
1871RecordLayoutBuilder::updateExternalFieldOffset(const FieldDecl *Field,
1872 uint64_t ComputedOffset) {
1873 assert(ExternalFieldOffsets.find(Field) != ExternalFieldOffsets.end() &&
1874 "Field does not have an external offset");
1875
1876 uint64_t ExternalFieldOffset = ExternalFieldOffsets[Field];
1877
1878 if (InferAlignment && ExternalFieldOffset < ComputedOffset) {
1879 // The externally-supplied field offset is before the field offset we
1880 // computed. Assume that the structure is packed.
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001881 Alignment = CharUnits::One();
Douglas Gregor44ba7892012-01-28 00:53:29 +00001882 InferAlignment = false;
1883 }
1884
1885 // Use the externally-supplied field offset.
Benjamin Kramer648e68b2012-08-31 22:14:25 +00001886 return ExternalFieldOffset;
1887}
1888
1889/// \brief Get diagnostic %select index for tag kind for
1890/// field padding diagnostic message.
1891/// WARNING: Indexes apply to particular diagnostics only!
1892///
1893/// \returns diagnostic %select index.
1894static unsigned getPaddingDiagFromTagKind(TagTypeKind Tag) {
1895 switch (Tag) {
1896 case TTK_Struct: return 0;
1897 case TTK_Interface: return 1;
1898 case TTK_Class: return 2;
1899 default: llvm_unreachable("Invalid tag kind for field padding diagnostic!");
1900 }
1901}
1902
1903void RecordLayoutBuilder::CheckFieldPadding(uint64_t Offset,
1904 uint64_t UnpaddedOffset,
1905 uint64_t UnpackedOffset,
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001906 unsigned UnpackedAlign,
1907 bool isPacked,
1908 const FieldDecl *D) {
1909 // We let objc ivars without warning, objc interfaces generally are not used
1910 // for padding tricks.
1911 if (isa<ObjCIvarDecl>(D))
Anders Carlsson79474332009-07-18 20:20:21 +00001912 return;
Mike Stump11289f42009-09-09 15:08:12 +00001913
Ted Kremenekfed48af2011-09-06 19:40:45 +00001914 // Don't warn about structs created without a SourceLocation. This can
1915 // be done by clients of the AST, such as codegen.
1916 if (D->getLocation().isInvalid())
1917 return;
1918
Douglas Gregore8bbc122011-09-02 00:18:52 +00001919 unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
Mike Stump11289f42009-09-09 15:08:12 +00001920
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001921 // Warn if padding was introduced to the struct/class.
1922 if (!IsUnion && Offset > UnpaddedOffset) {
1923 unsigned PadSize = Offset - UnpaddedOffset;
1924 bool InBits = true;
1925 if (PadSize % CharBitNum == 0) {
1926 PadSize = PadSize / CharBitNum;
1927 InBits = false;
Benjamin Kramer648e68b2012-08-31 22:14:25 +00001928 }
1929 if (D->getIdentifier())
1930 Diag(D->getLocation(), diag::warn_padded_struct_field)
1931 << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
1932 << Context.getTypeDeclType(D->getParent())
1933 << PadSize
1934 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1) // plural or not
1935 << D->getIdentifier();
1936 else
1937 Diag(D->getLocation(), diag::warn_padded_struct_anon_field)
1938 << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
1939 << Context.getTypeDeclType(D->getParent())
1940 << PadSize
1941 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1); // plural or not
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001942 }
1943
1944 // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
1945 // bother since there won't be alignment issues.
1946 if (isPacked && UnpackedAlign > CharBitNum && Offset == UnpackedOffset)
1947 Diag(D->getLocation(), diag::warn_unnecessary_packed)
1948 << D->getIdentifier();
Anders Carlsson79474332009-07-18 20:20:21 +00001949}
Mike Stump11289f42009-09-09 15:08:12 +00001950
John McCall6bd2a892013-01-25 22:31:03 +00001951static const CXXMethodDecl *computeKeyFunction(ASTContext &Context,
1952 const CXXRecordDecl *RD) {
Daniel Dunbarccabe482010-04-19 20:44:53 +00001953 // If a class isn't polymorphic it doesn't have a key function.
Anders Carlsson5ebf8b42009-12-07 04:35:11 +00001954 if (!RD->isPolymorphic())
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001955 return 0;
Eli Friedmanf2c79b62009-12-08 03:56:49 +00001956
Eli Friedman300f55d2011-06-10 21:53:06 +00001957 // A class that is not externally visible doesn't have a key function. (Or
Eli Friedmanf2c79b62009-12-08 03:56:49 +00001958 // at least, there's no point to assigning a key function to such a class;
1959 // this doesn't affect the ABI.)
Rafael Espindola3ae00052013-05-13 00:12:11 +00001960 if (!RD->isExternallyVisible())
Eli Friedmanf2c79b62009-12-08 03:56:49 +00001961 return 0;
1962
Argyrios Kyrtzidis8c64bbe2010-10-13 02:39:41 +00001963 // Template instantiations don't have key functions,see Itanium C++ ABI 5.2.6.
1964 // Same behavior as GCC.
1965 TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
1966 if (TSK == TSK_ImplicitInstantiation ||
1967 TSK == TSK_ExplicitInstantiationDefinition)
1968 return 0;
1969
John McCall6bd2a892013-01-25 22:31:03 +00001970 bool allowInlineFunctions =
1971 Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline();
1972
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001973 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
1974 E = RD->method_end(); I != E; ++I) {
David Blaikie40ed2972012-06-06 20:45:41 +00001975 const CXXMethodDecl *MD = *I;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001976
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001977 if (!MD->isVirtual())
1978 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001979
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001980 if (MD->isPure())
1981 continue;
Eli Friedmanf2c79b62009-12-08 03:56:49 +00001982
Anders Carlssonf98849e2009-12-02 17:15:43 +00001983 // Ignore implicit member functions, they are always marked as inline, but
1984 // they don't have a body until they're defined.
1985 if (MD->isImplicit())
1986 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001987
Douglas Gregora318efd2010-01-05 19:06:31 +00001988 if (MD->isInlineSpecified())
1989 continue;
Eli Friedman71a26d82009-12-06 20:50:05 +00001990
1991 if (MD->hasInlineBody())
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001992 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001993
Benjamin Kramer4a902082012-08-03 15:43:22 +00001994 // Ignore inline deleted or defaulted functions.
Benjamin Kramer73d1be72012-08-03 08:39:58 +00001995 if (!MD->isUserProvided())
1996 continue;
1997
John McCall6bd2a892013-01-25 22:31:03 +00001998 // In certain ABIs, ignore functions with out-of-line inline definitions.
1999 if (!allowInlineFunctions) {
2000 const FunctionDecl *Def;
2001 if (MD->hasBody(Def) && Def->isInlineSpecified())
2002 continue;
2003 }
2004
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00002005 // We found it.
2006 return MD;
2007 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002008
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00002009 return 0;
2010}
2011
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002012DiagnosticBuilder
2013RecordLayoutBuilder::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +00002014 return Context.getDiagnostics().Report(Loc, DiagID);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002015}
2016
John McCall5c1f1d02013-01-29 01:14:22 +00002017/// Does the target C++ ABI require us to skip over the tail-padding
2018/// of the given class (considering it as a base class) when allocating
2019/// objects?
2020static bool mustSkipTailPadding(TargetCXXABI ABI, const CXXRecordDecl *RD) {
2021 switch (ABI.getTailPaddingUseRules()) {
2022 case TargetCXXABI::AlwaysUseTailPadding:
2023 return false;
2024
2025 case TargetCXXABI::UseTailPaddingUnlessPOD03:
2026 // FIXME: To the extent that this is meant to cover the Itanium ABI
2027 // rules, we should implement the restrictions about over-sized
2028 // bitfields:
2029 //
2030 // http://mentorembedded.github.com/cxx-abi/abi.html#POD :
2031 // In general, a type is considered a POD for the purposes of
2032 // layout if it is a POD type (in the sense of ISO C++
2033 // [basic.types]). However, a POD-struct or POD-union (in the
2034 // sense of ISO C++ [class]) with a bitfield member whose
2035 // declared width is wider than the declared type of the
2036 // bitfield is not a POD for the purpose of layout. Similarly,
2037 // an array type is not a POD for the purpose of layout if the
2038 // element type of the array is not a POD for the purpose of
2039 // layout.
2040 //
2041 // Where references to the ISO C++ are made in this paragraph,
2042 // the Technical Corrigendum 1 version of the standard is
2043 // intended.
2044 return RD->isPOD();
2045
2046 case TargetCXXABI::UseTailPaddingUnlessPOD11:
2047 // This is equivalent to RD->getTypeForDecl().isCXX11PODType(),
2048 // but with a lot of abstraction penalty stripped off. This does
2049 // assume that these properties are set correctly even in C++98
2050 // mode; fortunately, that is true because we want to assign
2051 // consistently semantics to the type-traits intrinsics (or at
2052 // least as many of them as possible).
2053 return RD->isTrivial() && RD->isStandardLayout();
2054 }
2055
2056 llvm_unreachable("bad tail-padding use kind");
2057}
2058
Warren Hunt8f8bad72013-10-11 20:19:00 +00002059static bool isMsLayout(const RecordDecl* D) {
Warren Hunt55d8e822013-10-23 23:53:07 +00002060 return D->getASTContext().getTargetInfo().getCXXABI().isMicrosoft();
Warren Hunt8f8bad72013-10-11 20:19:00 +00002061}
2062
2063// This section contains an implementation of struct layout that is, up to the
2064// included tests, compatible with cl.exe (2012). The layout produced is
2065// significantly different than those produced by the Itanium ABI. Here we note
2066// the most important differences.
2067//
2068// * The alignment of bitfields in unions is ignored when computing the
2069// alignment of the union.
Alp Tokerf6a24ce2013-12-05 16:25:25 +00002070// * The existence of zero-width bitfield that occurs after anything other than
Warren Hunt8f8bad72013-10-11 20:19:00 +00002071// a non-zero length bitfield is ignored.
2072// * The Itanium equivalent vtable pointers are split into a vfptr (virtual
2073// function pointer) and a vbptr (virtual base pointer). They can each be
Warren Hunt55d8e822013-10-23 23:53:07 +00002074// shared with a, non-virtual bases. These bases need not be the same. vfptrs
2075// always occur at offset 0. vbptrs can occur at an
Warren Hunt8f8bad72013-10-11 20:19:00 +00002076// arbitrary offset and are placed after non-virtual bases but before fields.
2077// * Virtual bases sometimes require a 'vtordisp' field that is laid out before
2078// the virtual base and is used in conjunction with virtual overrides during
2079// construction and destruction.
2080// * vfptrs are allocated in a block of memory equal to the alignment of the
Warren Hunt55d8e822013-10-23 23:53:07 +00002081// fields and non-virtual bases at offset 0 in 32 bit mode and in a pointer
2082// sized block of memory in 64 bit mode.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002083// * vbptrs are allocated in a block of memory equal to the alignment of the
Warren Hunt55d8e822013-10-23 23:53:07 +00002084// fields and non-virtual bases. This block is at a potentially unaligned
2085// offset. If the allocation slot is unaligned and the alignment is less than
2086// or equal to the pointer size, additional space is allocated so that the
2087// pointer can be aligned properly. This causes very strange effects on the
2088// placement of objects after the allocated block. (see the code).
Warren Hunt8f8bad72013-10-11 20:19:00 +00002089// * vtordisps are allocated in a block of memory with size and alignment equal
2090// to the alignment of the completed structure (before applying __declspec(
Warren Hunt55d8e822013-10-23 23:53:07 +00002091// align())). The vtordisp always occur at the end of the allocation block,
2092// immediately prior to the virtual base.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002093// * The last zero sized non-virtual base is allocated after the placement of
2094// vbptr if one exists and can be placed at the end of the struct, potentially
2095// aliasing either the first member or another struct allocated after this
2096// one.
2097// * The last zero size virtual base may be placed at the end of the struct.
2098// and can potentially alias a zero sized type in the next struct.
Warren Hunt71140d62013-12-06 20:16:49 +00002099// * If the last field is a non-zero length bitfield, all virtual bases will
2100// have extra padding added before them for no obvious reason. The padding
2101// has the same number of bits as the type of the bitfield.
Warren Huntc0df47d2013-11-19 22:11:09 +00002102// * When laying out empty non-virtual bases, an extra byte of padding is added
2103// if the non-virtual base before the empty non-virtual base has a vbptr.
Warren Hunt049f6732013-12-06 19:54:25 +00002104// * The ABI attempts to avoid aliasing of zero sized bases by adding padding
2105// between bases or vbases with specific properties. The criteria for
2106// additional padding between two bases is that the first base is zero sized
2107// or has a zero sized subobject and the second base is zero sized or leads
2108// with a zero sized base (sharing of vfptrs can reorder the layout of the
2109// so the leading base is not always the first one declared). The padding
2110// added for bases is 1 byte. The padding added for vbases depends on the
2111// alignment of the object but is at least 4 bytes (in both 32 and 64 bit
2112// modes).
Warren Huntd640d7d2014-01-09 00:30:56 +00002113// * There is no concept of non-virtual alignment or any distinction between
2114// data size and non-virtual size.
Warren Huntf4518def2014-01-10 01:28:05 +00002115// * __declspec(align) on bitfields has the effect of changing the bitfield's
2116// alignment instead of its required alignment. This has implications on how
2117// it interacts with pragam pack.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002118
2119namespace {
2120struct MicrosoftRecordLayoutBuilder {
Warren Huntd640d7d2014-01-09 00:30:56 +00002121 struct ElementInfo {
2122 CharUnits Size;
2123 CharUnits Alignment;
2124 };
Warren Hunt8f8bad72013-10-11 20:19:00 +00002125 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
2126 MicrosoftRecordLayoutBuilder(const ASTContext &Context) : Context(Context) {}
2127private:
2128 MicrosoftRecordLayoutBuilder(const MicrosoftRecordLayoutBuilder &)
2129 LLVM_DELETED_FUNCTION;
2130 void operator=(const MicrosoftRecordLayoutBuilder &) LLVM_DELETED_FUNCTION;
2131public:
Warren Hunt8f8bad72013-10-11 20:19:00 +00002132 void layout(const RecordDecl *RD);
2133 void cxxLayout(const CXXRecordDecl *RD);
2134 /// \brief Initializes size and alignment and honors some flags.
2135 void initializeLayout(const RecordDecl *RD);
2136 /// \brief Initialized C++ layout, compute alignment and virtual alignment and
Alp Tokerf6a24ce2013-12-05 16:25:25 +00002137 /// existence of vfptrs and vbptrs. Alignment is needed before the vfptr is
Warren Hunt8f8bad72013-10-11 20:19:00 +00002138 /// laid out.
2139 void initializeCXXLayout(const CXXRecordDecl *RD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002140 void layoutNonVirtualBases(const CXXRecordDecl *RD);
Warren Huntd640d7d2014-01-09 00:30:56 +00002141 void layoutNonVirtualBase(const CXXRecordDecl *BaseDecl,
2142 const ASTRecordLayout &BaseLayout,
2143 const ASTRecordLayout *&PreviousBaseLayout);
2144 void injectVFPtr(const CXXRecordDecl *RD);
2145 void injectVBPtr(const CXXRecordDecl *RD);
2146 void injectVPtrs(const CXXRecordDecl *RD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002147 /// \brief Lays out the fields of the record. Also rounds size up to
2148 /// alignment.
2149 void layoutFields(const RecordDecl *RD);
2150 void layoutField(const FieldDecl *FD);
2151 void layoutBitField(const FieldDecl *FD);
2152 /// \brief Lays out a single zero-width bit-field in the record and handles
2153 /// special cases associated with zero-width bit-fields.
2154 void layoutZeroWidthBitField(const FieldDecl *FD);
2155 void layoutVirtualBases(const CXXRecordDecl *RD);
Warren Hunt1603e522013-12-10 01:44:39 +00002156 void finalizeLayout(const RecordDecl *RD);
Warren Huntd640d7d2014-01-09 00:30:56 +00002157 /// \brief Gets the size and alignment of a base taking pragma pack and
2158 /// __declspec(align) into account.
Warren Huntf6ec7482014-02-21 01:40:35 +00002159 ElementInfo getAdjustedElementInfo(const ASTRecordLayout &Layout,
2160 bool AsBase = true);
Warren Huntd640d7d2014-01-09 00:30:56 +00002161 /// \brief Gets the size and alignment of a field taking pragma pack and
2162 /// __declspec(align) into account. It also updates RequiredAlignment as a
2163 /// side effect because it is most convenient to do so here.
2164 ElementInfo getAdjustedElementInfo(const FieldDecl *FD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002165 /// \brief Places a field at an offset in CharUnits.
2166 void placeFieldAtOffset(CharUnits FieldOffset) {
2167 FieldOffsets.push_back(Context.toBits(FieldOffset));
2168 }
2169 /// \brief Places a bitfield at a bit offset.
2170 void placeFieldAtBitOffset(uint64_t FieldOffset) {
2171 FieldOffsets.push_back(FieldOffset);
2172 }
2173 /// \brief Compute the set of virtual bases for which vtordisps are required.
2174 llvm::SmallPtrSet<const CXXRecordDecl *, 2>
2175 computeVtorDispSet(const CXXRecordDecl *RD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002176 const ASTContext &Context;
2177 /// \brief The size of the record being laid out.
2178 CharUnits Size;
Warren Huntf6ec7482014-02-21 01:40:35 +00002179 /// \brief The non-virtual size of the record layout.
2180 CharUnits NonVirtualSize;
2181 /// \brief The data size of the record layout.
Warren Huntd640d7d2014-01-09 00:30:56 +00002182 CharUnits DataSize;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002183 /// \brief The current alignment of the record layout.
2184 CharUnits Alignment;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002185 /// \brief The maximum allowed field alignment. This is set by #pragma pack.
2186 CharUnits MaxFieldAlignment;
Warren Hunt7b252d22013-12-06 00:01:17 +00002187 /// \brief The alignment that this record must obey. This is imposed by
2188 /// __declspec(align()) on the record itself or one of its fields or bases.
2189 CharUnits RequiredAlignment;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002190 /// \brief The size of the allocation of the currently active bitfield.
2191 /// This value isn't meaningful unless LastFieldIsNonZeroWidthBitfield
2192 /// is true.
2193 CharUnits CurrentBitfieldSize;
Warren Huntd640d7d2014-01-09 00:30:56 +00002194 /// \brief Offset to the virtual base table pointer (if one exists).
2195 CharUnits VBPtrOffset;
2196 /// \brief The size and alignment info of a pointer.
2197 ElementInfo PointerInfo;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002198 /// \brief The primary base class (if one exists).
2199 const CXXRecordDecl *PrimaryBase;
2200 /// \brief The class we share our vb-pointer with.
2201 const CXXRecordDecl *SharedVBPtrBase;
Warren Huntd640d7d2014-01-09 00:30:56 +00002202 /// \brief The collection of field offsets.
2203 SmallVector<uint64_t, 16> FieldOffsets;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002204 /// \brief Base classes and their offsets in the record.
2205 BaseOffsetsMapTy Bases;
2206 /// \brief virtual base classes and their offsets in the record.
2207 ASTRecordLayout::VBaseOffsetsMapTy VBases;
Warren Huntd640d7d2014-01-09 00:30:56 +00002208 /// \brief The number of remaining bits in our last bitfield allocation.
2209 /// This value isn't meaningful unless LastFieldIsNonZeroWidthBitfield is
2210 /// true.
2211 unsigned RemainingBitsInField;
2212 bool IsUnion : 1;
2213 /// \brief True if the last field laid out was a bitfield and was not 0
2214 /// width.
2215 bool LastFieldIsNonZeroWidthBitfield : 1;
2216 /// \brief True if the class has its own vftable pointer.
2217 bool HasOwnVFPtr : 1;
2218 /// \brief True if the class has a vbtable pointer.
2219 bool HasVBPtr : 1;
Warren Hunt55d8e822013-10-23 23:53:07 +00002220 /// \brief Lets us know if we're in 64-bit mode
Warren Hunt049f6732013-12-06 19:54:25 +00002221 bool Is64BitMode : 1;
2222 /// \brief True if this class contains a zero sized member or base or a base
2223 /// with a zero sized member or base. Only used for MS-ABI.
2224 bool HasZeroSizedSubObject : 1;
2225 /// \brief True if this class is zero sized or first base is zero sized or
2226 /// has this property. Only used for MS-ABI.
2227 bool LeadsWithZeroSizedBase : 1;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002228};
2229} // namespace
2230
Warren Huntd640d7d2014-01-09 00:30:56 +00002231MicrosoftRecordLayoutBuilder::ElementInfo
2232MicrosoftRecordLayoutBuilder::getAdjustedElementInfo(
Warren Huntf6ec7482014-02-21 01:40:35 +00002233 const ASTRecordLayout &Layout, bool AsBase) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002234 ElementInfo Info;
2235 Info.Alignment = Layout.getAlignment();
2236 // Respect pragma pack.
Warren Hunt7b252d22013-12-06 00:01:17 +00002237 if (!MaxFieldAlignment.isZero())
Warren Huntd640d7d2014-01-09 00:30:56 +00002238 Info.Alignment = std::min(Info.Alignment, MaxFieldAlignment);
2239 // Track zero-sized subobjects here where it's already available.
2240 if (Layout.hasZeroSizedSubObject())
2241 HasZeroSizedSubObject = true;
2242 // Respect required alignment, this is necessary because we may have adjusted
Warren Hunt94258912014-01-11 01:16:40 +00002243 // the alignment in the case of pragam pack. Note that the required alignment
2244 // doesn't actually apply to the struct alignment at this point.
2245 Alignment = std::max(Alignment, Info.Alignment);
Warren Huntd640d7d2014-01-09 00:30:56 +00002246 Info.Alignment = std::max(Info.Alignment, Layout.getRequiredAlignment());
Warren Huntf6ec7482014-02-21 01:40:35 +00002247 Info.Size = AsBase ? Layout.getNonVirtualSize() : Layout.getSize();
Warren Huntd640d7d2014-01-09 00:30:56 +00002248 return Info;
Warren Hunt7b252d22013-12-06 00:01:17 +00002249}
2250
Warren Huntd640d7d2014-01-09 00:30:56 +00002251MicrosoftRecordLayoutBuilder::ElementInfo
2252MicrosoftRecordLayoutBuilder::getAdjustedElementInfo(
2253 const FieldDecl *FD) {
2254 ElementInfo Info;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002255 std::tie(Info.Size, Info.Alignment) =
Reid Klecknerdb673ca2014-02-25 18:08:48 +00002256 Context.getTypeInfoInChars(FD->getType());
Warren Huntf4518def2014-01-10 01:28:05 +00002257 // Respect align attributes.
2258 CharUnits FieldRequiredAlignment =
2259 Context.toCharUnitsFromBits(FD->getMaxAlignment());
Warren Hunt049f6732013-12-06 19:54:25 +00002260 // Respect attributes applied to subobjects of the field.
Warren Hunt7b252d22013-12-06 00:01:17 +00002261 if (const RecordType *RT =
2262 FD->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
2263 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RT->getDecl());
Warren Huntd640d7d2014-01-09 00:30:56 +00002264 // Get the element info for a layout, respecting pack.
Reid Klecknerdb673ca2014-02-25 18:08:48 +00002265 Info.Alignment = getAdjustedElementInfo(Layout, false).Alignment;
Warren Huntd640d7d2014-01-09 00:30:56 +00002266 // Capture required alignment as a side-effect.
Warren Hunt7b252d22013-12-06 00:01:17 +00002267 RequiredAlignment = std::max(RequiredAlignment,
2268 Layout.getRequiredAlignment());
Reid Klecknerdb673ca2014-02-25 18:08:48 +00002269 } else {
Warren Huntf4518def2014-01-10 01:28:05 +00002270 if (FD->isBitField() && FD->getMaxAlignment() != 0)
2271 Info.Alignment = std::max(Info.Alignment, FieldRequiredAlignment);
Warren Hunt26b94422014-01-14 00:54:36 +00002272 // Respect pragma pack.
2273 if (!MaxFieldAlignment.isZero())
2274 Info.Alignment = std::min(Info.Alignment, MaxFieldAlignment);
Warren Huntd640d7d2014-01-09 00:30:56 +00002275 }
2276 // Respect packed field attribute.
2277 if (FD->hasAttr<PackedAttr>())
2278 Info.Alignment = CharUnits::One();
Warren Huntf4518def2014-01-10 01:28:05 +00002279 // Take required alignment into account. __declspec(align) on bitfields
2280 // impacts the alignment rather than the required alignment.
2281 if (!FD->isBitField()) {
2282 Info.Alignment = std::max(Info.Alignment, FieldRequiredAlignment);
2283 // Capture required alignment as a side-effect.
2284 RequiredAlignment = std::max(RequiredAlignment, FieldRequiredAlignment);
2285 }
Warren Hunt94258912014-01-11 01:16:40 +00002286 // TODO: Add a Sema warning that MS ignores bitfield alignment in unions.
Warren Hunt26b94422014-01-14 00:54:36 +00002287 if (!(FD->isBitField() && IsUnion)) {
Warren Hunt94258912014-01-11 01:16:40 +00002288 Alignment = std::max(Alignment, Info.Alignment);
Warren Hunt26b94422014-01-14 00:54:36 +00002289 if (!MaxFieldAlignment.isZero())
2290 Alignment = std::min(Alignment, MaxFieldAlignment);
2291 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002292 return Info;
2293}
2294
2295void MicrosoftRecordLayoutBuilder::layout(const RecordDecl *RD) {
2296 initializeLayout(RD);
2297 layoutFields(RD);
2298 DataSize = Size = Size.RoundUpToAlignment(Alignment);
David Majnemer79a1c892014-02-12 00:43:02 +00002299 RequiredAlignment = std::max(
2300 RequiredAlignment, Context.toCharUnitsFromBits(RD->getMaxAlignment()));
Warren Huntd640d7d2014-01-09 00:30:56 +00002301 finalizeLayout(RD);
2302}
2303
2304void MicrosoftRecordLayoutBuilder::cxxLayout(const CXXRecordDecl *RD) {
2305 initializeLayout(RD);
2306 initializeCXXLayout(RD);
2307 layoutNonVirtualBases(RD);
2308 layoutFields(RD);
2309 injectVPtrs(RD);
Warren Huntf6ec7482014-02-21 01:40:35 +00002310 NonVirtualSize = Size = Size.RoundUpToAlignment(Alignment);
David Majnemer79a1c892014-02-12 00:43:02 +00002311 RequiredAlignment = std::max(
2312 RequiredAlignment, Context.toCharUnitsFromBits(RD->getMaxAlignment()));
Warren Huntd640d7d2014-01-09 00:30:56 +00002313 layoutVirtualBases(RD);
2314 finalizeLayout(RD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002315}
2316
2317void MicrosoftRecordLayoutBuilder::initializeLayout(const RecordDecl *RD) {
2318 IsUnion = RD->isUnion();
Warren Hunt5ae586a2013-11-01 23:59:41 +00002319 Is64BitMode = Context.getTargetInfo().getPointerWidth(0) == 64;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002320 Size = CharUnits::Zero();
2321 Alignment = CharUnits::One();
Warren Hunt7b252d22013-12-06 00:01:17 +00002322 // In 64-bit mode we always perform an alignment step after laying out vbases.
2323 // In 32-bit mode we do not. The check to see if we need to perform alignment
2324 // checks the RequiredAlignment field and performs alignment if it isn't 0.
2325 RequiredAlignment = Is64BitMode ? CharUnits::One() : CharUnits::Zero();
Warren Hunt8f8bad72013-10-11 20:19:00 +00002326 // Compute the maximum field alignment.
2327 MaxFieldAlignment = CharUnits::Zero();
2328 // Honor the default struct packing maximum alignment flag.
2329 if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct)
Warren Huntf4518def2014-01-10 01:28:05 +00002330 MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
2331 // Honor the packing attribute. The MS-ABI ignores pragma pack if its larger
2332 // than the pointer size.
2333 if (const MaxFieldAlignmentAttr *MFAA = RD->getAttr<MaxFieldAlignmentAttr>()){
2334 unsigned PackedAlignment = MFAA->getAlignment();
2335 if (PackedAlignment <= Context.getTargetInfo().getPointerWidth(0))
2336 MaxFieldAlignment = Context.toCharUnitsFromBits(PackedAlignment);
2337 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002338 // Packed attribute forces max field alignment to be 1.
2339 if (RD->hasAttr<PackedAttr>())
2340 MaxFieldAlignment = CharUnits::One();
2341}
2342
Warren Hunt8f8bad72013-10-11 20:19:00 +00002343void
2344MicrosoftRecordLayoutBuilder::initializeCXXLayout(const CXXRecordDecl *RD) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002345 HasZeroSizedSubObject = false;
Warren Hunt049f6732013-12-06 19:54:25 +00002346 LeadsWithZeroSizedBase = false;
Warren Huntd640d7d2014-01-09 00:30:56 +00002347 HasOwnVFPtr = false;
2348 HasVBPtr = false;
2349 PrimaryBase = 0;
2350 SharedVBPtrBase = 0;
2351 // Calculate pointer size and alignment. These are used for vfptr and vbprt
2352 // injection.
2353 PointerInfo.Size =
2354 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
2355 PointerInfo.Alignment = PointerInfo.Size;
2356 // Respect pragma pack.
2357 if (!MaxFieldAlignment.isZero())
2358 PointerInfo.Alignment = std::min(PointerInfo.Alignment, MaxFieldAlignment);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002359}
2360
2361void
2362MicrosoftRecordLayoutBuilder::layoutNonVirtualBases(const CXXRecordDecl *RD) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002363 // The MS-ABI lays out all bases that contain leading vfptrs before it lays
2364 // out any bases that do not contain vfptrs. We implement this as two passes
2365 // over the bases. This approach guarantees that the primary base is laid out
2366 // first. We use these passes to calculate some additional aggregated
2367 // information about the bases, such as reqruied alignment and the presence of
2368 // zero sized members.
2369 const ASTRecordLayout* PreviousBaseLayout = 0;
2370 // Iterate through the bases and lay out the non-virtual ones.
Aaron Ballman574705e2014-03-13 15:41:46 +00002371 for (const auto &I : RD->bases()) {
2372 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
Warren Huntd640d7d2014-01-09 00:30:56 +00002373 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
Warren Huntd640d7d2014-01-09 00:30:56 +00002374 // Mark and skip virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00002375 if (I.isVirtual()) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002376 HasVBPtr = true;
2377 continue;
2378 }
David Majnemer79a1c892014-02-12 00:43:02 +00002379 // Track RequiredAlignment for all bases in this pass.
2380 RequiredAlignment = std::max(RequiredAlignment,
2381 BaseLayout.getRequiredAlignment());
Warren Huntd640d7d2014-01-09 00:30:56 +00002382 // Check fo a base to share a VBPtr with.
2383 if (!SharedVBPtrBase && BaseLayout.hasVBPtr()) {
2384 SharedVBPtrBase = BaseDecl;
2385 HasVBPtr = true;
2386 }
2387 // Only lay out bases with extendable VFPtrs on the first pass.
2388 if (!BaseLayout.hasExtendableVFPtr())
2389 continue;
2390 // If we don't have a primary base, this one qualifies.
Warren Huntbadf9e02014-01-13 19:55:52 +00002391 if (!PrimaryBase) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002392 PrimaryBase = BaseDecl;
Warren Huntbadf9e02014-01-13 19:55:52 +00002393 LeadsWithZeroSizedBase = BaseLayout.leadsWithZeroSizedBase();
2394 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002395 // Lay out the base.
2396 layoutNonVirtualBase(BaseDecl, BaseLayout, PreviousBaseLayout);
2397 }
2398 // Figure out if we need a fresh VFPtr for this class.
2399 if (!PrimaryBase && RD->isDynamicClass())
2400 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
2401 e = RD->method_end();
2402 !HasOwnVFPtr && i != e; ++i)
2403 HasOwnVFPtr = i->isVirtual() && i->size_overridden_methods() == 0;
2404 // If we don't have a primary base then we have a leading object that could
2405 // itself lead with a zero-sized object, something we track.
2406 bool CheckLeadingLayout = !PrimaryBase;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002407 // Iterate through the bases and lay out the non-virtual ones.
Aaron Ballman574705e2014-03-13 15:41:46 +00002408 for (const auto &I : RD->bases()) {
2409 if (I.isVirtual())
Warren Hunt8f8bad72013-10-11 20:19:00 +00002410 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +00002411 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
Warren Huntd640d7d2014-01-09 00:30:56 +00002412 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
2413 // Only lay out bases without extendable VFPtrs on the second pass.
2414 if (BaseLayout.hasExtendableVFPtr())
Warren Hunt4431fe62013-12-12 22:33:37 +00002415 continue;
Warren Huntd640d7d2014-01-09 00:30:56 +00002416 // If this is the first layout, check to see if it leads with a zero sized
2417 // object. If it does, so do we.
2418 if (CheckLeadingLayout) {
2419 CheckLeadingLayout = false;
2420 LeadsWithZeroSizedBase = BaseLayout.leadsWithZeroSizedBase();
Warren Hunt049f6732013-12-06 19:54:25 +00002421 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002422 // Lay out the base.
2423 layoutNonVirtualBase(BaseDecl, BaseLayout, PreviousBaseLayout);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002424 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002425 // Set our VBPtroffset if we know it at this point.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002426 if (!HasVBPtr)
2427 VBPtrOffset = CharUnits::fromQuantity(-1);
Warren Hunt6eba9072014-01-14 00:31:30 +00002428 else if (SharedVBPtrBase) {
2429 const ASTRecordLayout &Layout = Context.getASTRecordLayout(SharedVBPtrBase);
2430 VBPtrOffset = Bases[SharedVBPtrBase] + Layout.getVBPtrOffset();
2431 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002432}
2433
2434void MicrosoftRecordLayoutBuilder::layoutNonVirtualBase(
2435 const CXXRecordDecl *BaseDecl,
2436 const ASTRecordLayout &BaseLayout,
2437 const ASTRecordLayout *&PreviousBaseLayout) {
Warren Huntf4518def2014-01-10 01:28:05 +00002438 // Insert padding between two bases if the left first one is zero sized or
2439 // contains a zero sized subobject and the right is zero sized or one leads
2440 // with a zero sized base.
2441 if (PreviousBaseLayout && PreviousBaseLayout->hasZeroSizedSubObject() &&
2442 BaseLayout.leadsWithZeroSizedBase())
2443 Size++;
2444 ElementInfo Info = getAdjustedElementInfo(BaseLayout);
2445 CharUnits BaseOffset = Size.RoundUpToAlignment(Info.Alignment);
2446 Bases.insert(std::make_pair(BaseDecl, BaseOffset));
Warren Huntf6ec7482014-02-21 01:40:35 +00002447 Size = BaseOffset + BaseLayout.getNonVirtualSize();
Warren Huntf4518def2014-01-10 01:28:05 +00002448 PreviousBaseLayout = &BaseLayout;
Warren Huntd640d7d2014-01-09 00:30:56 +00002449 VBPtrOffset = Size;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002450}
2451
2452void MicrosoftRecordLayoutBuilder::layoutFields(const RecordDecl *RD) {
2453 LastFieldIsNonZeroWidthBitfield = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002454 for (const auto *Field : RD->fields())
2455 layoutField(Field);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002456}
2457
2458void MicrosoftRecordLayoutBuilder::layoutField(const FieldDecl *FD) {
2459 if (FD->isBitField()) {
2460 layoutBitField(FD);
2461 return;
2462 }
2463 LastFieldIsNonZeroWidthBitfield = false;
Warren Huntd640d7d2014-01-09 00:30:56 +00002464 ElementInfo Info = getAdjustedElementInfo(FD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002465 if (IsUnion) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002466 placeFieldAtOffset(CharUnits::Zero());
2467 Size = std::max(Size, Info.Size);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002468 } else {
Warren Huntd640d7d2014-01-09 00:30:56 +00002469 CharUnits FieldOffset = Size.RoundUpToAlignment(Info.Alignment);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002470 placeFieldAtOffset(FieldOffset);
Warren Huntd640d7d2014-01-09 00:30:56 +00002471 Size = FieldOffset + Info.Size;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002472 }
2473}
2474
2475void MicrosoftRecordLayoutBuilder::layoutBitField(const FieldDecl *FD) {
2476 unsigned Width = FD->getBitWidthValue(Context);
2477 if (Width == 0) {
2478 layoutZeroWidthBitField(FD);
2479 return;
2480 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002481 ElementInfo Info = getAdjustedElementInfo(FD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002482 // Clamp the bitfield to a containable size for the sake of being able
2483 // to lay them out. Sema will throw an error.
Warren Huntd640d7d2014-01-09 00:30:56 +00002484 if (Width > Context.toBits(Info.Size))
2485 Width = Context.toBits(Info.Size);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002486 // Check to see if this bitfield fits into an existing allocation. Note:
2487 // MSVC refuses to pack bitfields of formal types with different sizes
2488 // into the same allocation.
2489 if (!IsUnion && LastFieldIsNonZeroWidthBitfield &&
Warren Huntd640d7d2014-01-09 00:30:56 +00002490 CurrentBitfieldSize == Info.Size && Width <= RemainingBitsInField) {
Warren Hunt8f8bad72013-10-11 20:19:00 +00002491 placeFieldAtBitOffset(Context.toBits(Size) - RemainingBitsInField);
2492 RemainingBitsInField -= Width;
2493 return;
2494 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002495 LastFieldIsNonZeroWidthBitfield = true;
Warren Huntd640d7d2014-01-09 00:30:56 +00002496 CurrentBitfieldSize = Info.Size;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002497 if (IsUnion) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002498 placeFieldAtOffset(CharUnits::Zero());
2499 Size = std::max(Size, Info.Size);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002500 } else {
2501 // Allocate a new block of memory and place the bitfield in it.
Warren Huntd640d7d2014-01-09 00:30:56 +00002502 CharUnits FieldOffset = Size.RoundUpToAlignment(Info.Alignment);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002503 placeFieldAtOffset(FieldOffset);
Warren Huntd640d7d2014-01-09 00:30:56 +00002504 Size = FieldOffset + Info.Size;
Warren Huntd640d7d2014-01-09 00:30:56 +00002505 RemainingBitsInField = Context.toBits(Info.Size) - Width;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002506 }
2507}
2508
2509void
2510MicrosoftRecordLayoutBuilder::layoutZeroWidthBitField(const FieldDecl *FD) {
2511 // Zero-width bitfields are ignored unless they follow a non-zero-width
2512 // bitfield.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002513 if (!LastFieldIsNonZeroWidthBitfield) {
2514 placeFieldAtOffset(IsUnion ? CharUnits::Zero() : Size);
2515 // TODO: Add a Sema warning that MS ignores alignment for zero
Alp Tokerd4733632013-12-05 04:47:09 +00002516 // sized bitfields that occur after zero-size bitfields or non-bitfields.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002517 return;
2518 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002519 LastFieldIsNonZeroWidthBitfield = false;
Warren Huntd640d7d2014-01-09 00:30:56 +00002520 ElementInfo Info = getAdjustedElementInfo(FD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002521 if (IsUnion) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002522 placeFieldAtOffset(CharUnits::Zero());
2523 Size = std::max(Size, Info.Size);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002524 } else {
2525 // Round up the current record size to the field's alignment boundary.
Warren Huntd640d7d2014-01-09 00:30:56 +00002526 CharUnits FieldOffset = Size.RoundUpToAlignment(Info.Alignment);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002527 placeFieldAtOffset(FieldOffset);
2528 Size = FieldOffset;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002529 }
2530}
2531
Warren Huntd640d7d2014-01-09 00:30:56 +00002532void MicrosoftRecordLayoutBuilder::injectVBPtr(const CXXRecordDecl *RD) {
Warren Hunt6eba9072014-01-14 00:31:30 +00002533 if (!HasVBPtr || SharedVBPtrBase)
Warren Huntd640d7d2014-01-09 00:30:56 +00002534 return;
Warren Huntd640d7d2014-01-09 00:30:56 +00002535 // Inject the VBPointer at the injection site.
2536 CharUnits InjectionSite = VBPtrOffset;
2537 // But before we do, make sure it's properly aligned.
2538 VBPtrOffset = VBPtrOffset.RoundUpToAlignment(PointerInfo.Alignment);
2539 // Determine where the first field should be laid out after the vbptr.
2540 CharUnits FieldStart = VBPtrOffset + PointerInfo.Size;
2541 // Make sure that the amount we push the fields back by is a multiple of the
2542 // alignment.
David Majnemer79a1c892014-02-12 00:43:02 +00002543 CharUnits Offset = (FieldStart - InjectionSite).RoundUpToAlignment(
2544 std::max(RequiredAlignment, Alignment));
Warren Huntd640d7d2014-01-09 00:30:56 +00002545 // Increase the size of the object and push back all fields by the offset
2546 // amount.
2547 Size += Offset;
2548 for (SmallVector<uint64_t, 16>::iterator i = FieldOffsets.begin(),
2549 e = FieldOffsets.end();
2550 i != e; ++i)
2551 *i += Context.toBits(Offset);
2552 for (BaseOffsetsMapTy::iterator i = Bases.begin(), e = Bases.end();
2553 i != e; ++i)
2554 if (i->second >= InjectionSite)
2555 i->second += Offset;
Warren Huntd640d7d2014-01-09 00:30:56 +00002556}
2557
2558void MicrosoftRecordLayoutBuilder::injectVFPtr(const CXXRecordDecl *RD) {
2559 if (!HasOwnVFPtr)
2560 return;
2561 // Make sure that the amount we push the struct back by is a multiple of the
2562 // alignment.
David Majnemer79a1c892014-02-12 00:43:02 +00002563 CharUnits Offset = PointerInfo.Size.RoundUpToAlignment(
2564 std::max(RequiredAlignment, Alignment));
Warren Huntd640d7d2014-01-09 00:30:56 +00002565 // Increase the size of the object and push back all fields, the vbptr and all
2566 // bases by the offset amount.
2567 Size += Offset;
David Majnemer79a1c892014-02-12 00:43:02 +00002568 for (SmallVectorImpl<uint64_t>::iterator i = FieldOffsets.begin(),
Warren Huntd640d7d2014-01-09 00:30:56 +00002569 e = FieldOffsets.end();
2570 i != e; ++i)
2571 *i += Context.toBits(Offset);
2572 if (HasVBPtr)
2573 VBPtrOffset += Offset;
2574 for (BaseOffsetsMapTy::iterator i = Bases.begin(), e = Bases.end();
2575 i != e; ++i)
2576 i->second += Offset;
Warren Huntd640d7d2014-01-09 00:30:56 +00002577}
2578
2579void MicrosoftRecordLayoutBuilder::injectVPtrs(const CXXRecordDecl *RD) {
David Blaikie461f1ea2014-01-09 02:34:06 +00002580 if (!(HasOwnVFPtr || (HasVBPtr && !SharedVBPtrBase)))
Warren Huntd640d7d2014-01-09 00:30:56 +00002581 return;
2582 if (!Is64BitMode || RequiredAlignment <= CharUnits::fromQuantity(8)) {
2583 // Note that the VBPtr is injected first. It depends on the alignment of
2584 // the object *before* the alignment is updated by inserting a pointer into
2585 // the record.
2586 injectVBPtr(RD);
2587 injectVFPtr(RD);
Warren Hunt94258912014-01-11 01:16:40 +00002588 Alignment = std::max(Alignment, PointerInfo.Alignment);
Warren Huntd640d7d2014-01-09 00:30:56 +00002589 return;
2590 }
2591 // In 64-bit mode, structs with RequiredAlignment greater than 8 get special
2592 // layout rules. Likely this is to avoid excessive padding intruced around
2593 // the vfptrs and vbptrs. The special rules involve re-laying out the struct
2594 // and inserting the vfptr and vbptr as if they were fields/bases.
2595 FieldOffsets.clear();
2596 Bases.clear();
2597 Size = CharUnits::Zero();
Warren Hunt94258912014-01-11 01:16:40 +00002598 Alignment = std::max(Alignment, PointerInfo.Alignment);
Warren Huntd640d7d2014-01-09 00:30:56 +00002599 if (HasOwnVFPtr)
2600 Size = PointerInfo.Size;
2601 layoutNonVirtualBases(RD);
2602 if (HasVBPtr && !SharedVBPtrBase) {
2603 const CXXRecordDecl *PenultBaseDecl = 0;
2604 const CXXRecordDecl *LastBaseDecl = 0;
2605 // Iterate through the bases and find the last two non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00002606 for (const auto &I : RD->bases()) {
2607 if (I.isVirtual())
Warren Huntd640d7d2014-01-09 00:30:56 +00002608 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +00002609 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
Warren Huntd640d7d2014-01-09 00:30:56 +00002610 if (!LastBaseDecl || Bases[BaseDecl] > Bases[LastBaseDecl]) {
2611 PenultBaseDecl = LastBaseDecl;
2612 LastBaseDecl = BaseDecl;
2613 }
2614 }
2615 const ASTRecordLayout *PenultBaseLayout = PenultBaseDecl ?
2616 &Context.getASTRecordLayout(PenultBaseDecl) : 0;
2617 const ASTRecordLayout *LastBaseLayout = LastBaseDecl ?
2618 &Context.getASTRecordLayout(LastBaseDecl) : 0;
2619 // Calculate the vbptr offset. The rule is different than in the general
2620 // case layout. Particularly, if the last two non-virtual bases are both
2621 // zero sized, the site of the vbptr is *before* the padding that occurs
2622 // between the two zero sized bases and the vbptr potentially aliases with
2623 // the first of these two bases. We have no understanding of why this is
2624 // different from the general case layout but it may have to do with lazy
2625 // placement of zero sized bases.
2626 VBPtrOffset = Size;
Warren Huntf6ec7482014-02-21 01:40:35 +00002627 if (LastBaseLayout && LastBaseLayout->getNonVirtualSize().isZero()) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002628 VBPtrOffset = Bases[LastBaseDecl];
Warren Huntf6ec7482014-02-21 01:40:35 +00002629 if (PenultBaseLayout && PenultBaseLayout->getNonVirtualSize().isZero())
Warren Huntd640d7d2014-01-09 00:30:56 +00002630 VBPtrOffset = Bases[PenultBaseDecl];
2631 }
2632 // Once we've located a spot for the vbptr, place it.
2633 VBPtrOffset = VBPtrOffset.RoundUpToAlignment(PointerInfo.Alignment);
2634 Size = VBPtrOffset + PointerInfo.Size;
Warren Huntf6ec7482014-02-21 01:40:35 +00002635 if (LastBaseLayout && LastBaseLayout->getNonVirtualSize().isZero()) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002636 // Add the padding between zero sized bases after the vbptr.
Warren Huntf6ec7482014-02-21 01:40:35 +00002637 if (PenultBaseLayout && PenultBaseLayout->getNonVirtualSize().isZero())
Warren Huntd640d7d2014-01-09 00:30:56 +00002638 Size += CharUnits::One();
2639 Size = Size.RoundUpToAlignment(LastBaseLayout->getRequiredAlignment());
2640 Bases[LastBaseDecl] = Size;
2641 }
2642 }
2643 layoutFields(RD);
Warren Hunt87c2b042014-01-10 23:32:32 +00002644 // The presence of a vbptr suppresses zero sized objects that are not in
2645 // virtual bases.
2646 HasZeroSizedSubObject = false;
Warren Hunt1603e522013-12-10 01:44:39 +00002647}
2648
Warren Hunt8f8bad72013-10-11 20:19:00 +00002649void MicrosoftRecordLayoutBuilder::layoutVirtualBases(const CXXRecordDecl *RD) {
2650 if (!HasVBPtr)
2651 return;
Warren Huntd640d7d2014-01-09 00:30:56 +00002652 // Vtordisps are always 4 bytes (even in 64-bit mode)
2653 CharUnits VtorDispSize = CharUnits::fromQuantity(4);
2654 CharUnits VtorDispAlignment = VtorDispSize;
2655 // vtordisps respect pragma pack.
2656 if (!MaxFieldAlignment.isZero())
2657 VtorDispAlignment = std::min(VtorDispAlignment, MaxFieldAlignment);
2658 // The alignment of the vtordisp is at least the required alignment of the
2659 // entire record. This requirement may be present to support vtordisp
2660 // injection.
David Majnemer79a1c892014-02-12 00:43:02 +00002661 for (CXXRecordDecl::base_class_const_iterator i = RD->vbases_begin(),
2662 e = RD->vbases_end();
2663 i != e; ++i) {
2664 const CXXRecordDecl *BaseDecl = i->getType()->getAsCXXRecordDecl();
2665 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
2666 RequiredAlignment =
2667 std::max(RequiredAlignment, BaseLayout.getRequiredAlignment());
2668 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002669 VtorDispAlignment = std::max(VtorDispAlignment, RequiredAlignment);
2670 // Compute the vtordisp set.
2671 llvm::SmallPtrSet<const CXXRecordDecl *, 2> HasVtordispSet =
Warren Hunt8f8bad72013-10-11 20:19:00 +00002672 computeVtorDispSet(RD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002673 // Iterate through the virtual bases and lay them out.
Warren Huntd640d7d2014-01-09 00:30:56 +00002674 const ASTRecordLayout* PreviousBaseLayout = 0;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002675 for (CXXRecordDecl::base_class_const_iterator i = RD->vbases_begin(),
2676 e = RD->vbases_end();
2677 i != e; ++i) {
Reid Klecknere7106c92013-12-18 23:17:05 +00002678 const CXXRecordDecl *BaseDecl = i->getType()->getAsCXXRecordDecl();
Warren Huntd640d7d2014-01-09 00:30:56 +00002679 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
2680 bool HasVtordisp = HasVtordispSet.count(BaseDecl);
Warren Hunt71140d62013-12-06 20:16:49 +00002681 // If the last field we laid out was a non-zero length bitfield then add
2682 // some extra padding for no obvious reason.
2683 if (LastFieldIsNonZeroWidthBitfield)
2684 Size += CurrentBitfieldSize;
Warren Huntd640d7d2014-01-09 00:30:56 +00002685 // Insert padding between two bases if the left first one is zero sized or
2686 // contains a zero sized subobject and the right is zero sized or one leads
2687 // with a zero sized base. The padding between virtual bases is 4
2688 // bytes (in both 32 and 64 bits modes) and always involves rounding up to
2689 // the required alignment, we don't know why.
2690 if (PreviousBaseLayout && PreviousBaseLayout->hasZeroSizedSubObject() &&
2691 BaseLayout.leadsWithZeroSizedBase())
2692 Size = Size.RoundUpToAlignment(VtorDispAlignment) + VtorDispSize;
2693 // Insert the vtordisp.
2694 if (HasVtordisp)
2695 Size = Size.RoundUpToAlignment(VtorDispAlignment) + VtorDispSize;
2696 // Insert the virtual base.
Warren Huntf6ec7482014-02-21 01:40:35 +00002697 HasZeroSizedSubObject = false;
Warren Huntd640d7d2014-01-09 00:30:56 +00002698 ElementInfo Info = getAdjustedElementInfo(BaseLayout);
Warren Huntf4518def2014-01-10 01:28:05 +00002699 CharUnits BaseOffset = Size.RoundUpToAlignment(Info.Alignment);
Warren Huntd640d7d2014-01-09 00:30:56 +00002700 VBases.insert(std::make_pair(BaseDecl,
2701 ASTRecordLayout::VBaseInfo(BaseOffset, HasVtordisp)));
Warren Huntf6ec7482014-02-21 01:40:35 +00002702 Size = BaseOffset + BaseLayout.getNonVirtualSize();
Warren Huntd640d7d2014-01-09 00:30:56 +00002703 PreviousBaseLayout = &BaseLayout;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002704 }
2705}
2706
Warren Huntc3384312013-12-11 22:28:32 +00002707void MicrosoftRecordLayoutBuilder::finalizeLayout(const RecordDecl *RD) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002708 // Respect required alignment. Note that in 32-bit mode Required alignment
2709 // may be 0 nad cause size not to be updated.
Warren Huntf6ec7482014-02-21 01:40:35 +00002710 DataSize = Size;
Warren Huntd640d7d2014-01-09 00:30:56 +00002711 if (!RequiredAlignment.isZero()) {
2712 Alignment = std::max(Alignment, RequiredAlignment);
2713 Size = Size.RoundUpToAlignment(Alignment);
2714 }
2715 // Zero-sized structures have size equal to their alignment.
Warren Hunt049f6732013-12-06 19:54:25 +00002716 if (Size.isZero()) {
2717 HasZeroSizedSubObject = true;
2718 LeadsWithZeroSizedBase = true;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002719 Size = Alignment;
Warren Hunt049f6732013-12-06 19:54:25 +00002720 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002721}
2722
2723static bool
2724RequiresVtordisp(const llvm::SmallPtrSet<const CXXRecordDecl *, 2> &HasVtordisp,
2725 const CXXRecordDecl *RD) {
2726 if (HasVtordisp.count(RD))
2727 return true;
2728 // If any of a virtual bases non-virtual bases (recursively) requires a
2729 // vtordisp than so does this virtual base.
Aaron Ballman574705e2014-03-13 15:41:46 +00002730 for (const auto &I : RD->bases())
2731 if (!I.isVirtual() &&
Warren Hunt8f8bad72013-10-11 20:19:00 +00002732 RequiresVtordisp(
2733 HasVtordisp,
Aaron Ballman574705e2014-03-13 15:41:46 +00002734 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl())))
Warren Hunt8f8bad72013-10-11 20:19:00 +00002735 return true;
2736 return false;
2737}
2738
2739llvm::SmallPtrSet<const CXXRecordDecl *, 2>
2740MicrosoftRecordLayoutBuilder::computeVtorDispSet(const CXXRecordDecl *RD) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002741 llvm::SmallPtrSet<const CXXRecordDecl *, 2> HasVtordispSet;
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00002742
2743 // /vd0 or #pragma vtordisp(0): Never use vtordisps when used as a vbase.
2744 if (RD->getMSVtorDispMode() == MSVtorDispAttr::Never)
2745 return HasVtordispSet;
2746
2747 // /vd2 or #pragma vtordisp(2): Always use vtordisps for virtual bases with
2748 // vftables.
2749 if (RD->getMSVtorDispMode() == MSVtorDispAttr::ForVFTable) {
2750 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
2751 E = RD->vbases_end();
2752 I != E; ++I) {
2753 const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
2754 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
2755 if (Layout.hasExtendableVFPtr())
2756 HasVtordispSet.insert(BaseDecl);
2757 }
2758 return HasVtordispSet;
2759 }
2760
2761 // /vd1 or #pragma vtordisp(1): Try to guess based on whether we think it's
2762 // possible for a partially constructed object with virtual base overrides to
2763 // escape a non-trivial constructor.
2764 assert(RD->getMSVtorDispMode() == MSVtorDispAttr::ForVBaseOverride);
2765
Warren Hunt8f8bad72013-10-11 20:19:00 +00002766 // If any of our bases need a vtordisp for this type, so do we. Check our
2767 // direct bases for vtordisp requirements.
Aaron Ballman574705e2014-03-13 15:41:46 +00002768 for (const auto &I : RD->bases()) {
Warren Hunt8f8bad72013-10-11 20:19:00 +00002769 const CXXRecordDecl *BaseDecl =
Aaron Ballman574705e2014-03-13 15:41:46 +00002770 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Warren Hunt8f8bad72013-10-11 20:19:00 +00002771 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
2772 for (ASTRecordLayout::VBaseOffsetsMapTy::const_iterator
2773 bi = Layout.getVBaseOffsetsMap().begin(),
2774 be = Layout.getVBaseOffsetsMap().end();
2775 bi != be; ++bi)
2776 if (bi->second.hasVtorDisp())
Warren Huntd640d7d2014-01-09 00:30:56 +00002777 HasVtordispSet.insert(bi->first);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002778 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002779 // If we define a constructor or destructor and override a function that is
2780 // defined in a virtual base's vtable, that virtual bases need a vtordisp.
2781 // Here we collect a list of classes with vtables for which our virtual bases
2782 // actually live. The virtual bases with this property will require
2783 // vtordisps. In addition, virtual bases that contain non-virtual bases that
2784 // define functions we override also require vtordisps, this case is checked
2785 // explicitly below.
2786 if (RD->hasUserDeclaredConstructor() || RD->hasUserDeclaredDestructor()) {
2787 llvm::SmallPtrSet<const CXXMethodDecl *, 8> Work;
2788 // Seed the working set with our non-destructor virtual methods.
2789 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
2790 e = RD->method_end();
2791 i != e; ++i)
Warren Hunt42be7762013-10-14 20:14:09 +00002792 if ((*i)->isVirtual() && !isa<CXXDestructorDecl>(*i))
Warren Hunt8f8bad72013-10-11 20:19:00 +00002793 Work.insert(*i);
2794 while (!Work.empty()) {
2795 const CXXMethodDecl *MD = *Work.begin();
2796 CXXMethodDecl::method_iterator i = MD->begin_overridden_methods(),
2797 e = MD->end_overridden_methods();
2798 if (i == e)
2799 // If a virtual method has no-overrides it lives in its parent's vtable.
Warren Huntd640d7d2014-01-09 00:30:56 +00002800 HasVtordispSet.insert(MD->getParent());
Warren Hunt8f8bad72013-10-11 20:19:00 +00002801 else
2802 Work.insert(i, e);
2803 // We've finished processing this element, remove it from the working set.
2804 Work.erase(MD);
2805 }
2806 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002807 // Re-check all of our vbases for vtordisp requirements (in case their
2808 // non-virtual bases have vtordisp requirements).
2809 for (CXXRecordDecl::base_class_const_iterator i = RD->vbases_begin(),
2810 e = RD->vbases_end();
2811 i != e; ++i) {
2812 const CXXRecordDecl *BaseDecl = i->getType()->getAsCXXRecordDecl();
Warren Huntd640d7d2014-01-09 00:30:56 +00002813 if (!HasVtordispSet.count(BaseDecl) &&
2814 RequiresVtordisp(HasVtordispSet, BaseDecl))
2815 HasVtordispSet.insert(BaseDecl);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002816 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002817 return HasVtordispSet;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002818}
2819
2820/// \brief Get or compute information about the layout of the specified record
2821/// (struct/union/class), which indicates its size and field position
2822/// information.
2823const ASTRecordLayout *
2824ASTContext::BuildMicrosoftASTRecordLayout(const RecordDecl *D) const {
2825 MicrosoftRecordLayoutBuilder Builder(*this);
2826 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
2827 Builder.cxxLayout(RD);
2828 return new (*this) ASTRecordLayout(
Warren Hunt7b252d22013-12-06 00:01:17 +00002829 *this, Builder.Size, Builder.Alignment, Builder.RequiredAlignment,
Warren Huntd640d7d2014-01-09 00:30:56 +00002830 Builder.HasOwnVFPtr,
2831 Builder.HasOwnVFPtr || Builder.PrimaryBase,
Warren Huntf6ec7482014-02-21 01:40:35 +00002832 Builder.VBPtrOffset, Builder.NonVirtualSize, Builder.FieldOffsets.data(),
2833 Builder.FieldOffsets.size(), Builder.NonVirtualSize,
Warren Huntd640d7d2014-01-09 00:30:56 +00002834 Builder.Alignment, CharUnits::Zero(), Builder.PrimaryBase,
Warren Hunt049f6732013-12-06 19:54:25 +00002835 false, Builder.SharedVBPtrBase,
2836 Builder.HasZeroSizedSubObject, Builder.LeadsWithZeroSizedBase,
2837 Builder.Bases, Builder.VBases);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002838 } else {
2839 Builder.layout(D);
2840 return new (*this) ASTRecordLayout(
Warren Hunt7b252d22013-12-06 00:01:17 +00002841 *this, Builder.Size, Builder.Alignment, Builder.RequiredAlignment,
2842 Builder.Size, Builder.FieldOffsets.data(), Builder.FieldOffsets.size());
Warren Hunt8f8bad72013-10-11 20:19:00 +00002843 }
2844}
2845
Anders Carlssondf291d82010-05-26 04:56:53 +00002846/// getASTRecordLayout - Get or compute information about the layout of the
2847/// specified record (struct/union/class), which indicates its size and field
2848/// position information.
Jay Foad39c79802011-01-12 09:06:06 +00002849const ASTRecordLayout &
2850ASTContext::getASTRecordLayout(const RecordDecl *D) const {
John McCall0710e552011-10-07 02:39:22 +00002851 // These asserts test different things. A record has a definition
2852 // as soon as we begin to parse the definition. That definition is
2853 // not a complete definition (which is what isDefinition() tests)
2854 // until we *finish* parsing the definition.
Sean Callanan56c19892012-02-08 00:04:52 +00002855
2856 if (D->hasExternalLexicalStorage() && !D->getDefinition())
2857 getExternalSource()->CompleteType(const_cast<RecordDecl*>(D));
2858
Anders Carlssondf291d82010-05-26 04:56:53 +00002859 D = D->getDefinition();
2860 assert(D && "Cannot get layout of forward declarations!");
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00002861 assert(!D->isInvalidDecl() && "Cannot get layout of invalid decl!");
John McCallf937c022011-10-07 06:10:15 +00002862 assert(D->isCompleteDefinition() && "Cannot layout type before complete!");
Anders Carlssondf291d82010-05-26 04:56:53 +00002863
2864 // Look up this layout, if already laid out, return what we have.
2865 // Note that we can't save a reference to the entry because this function
2866 // is recursive.
2867 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
2868 if (Entry) return *Entry;
2869
Warren Hunt8f8bad72013-10-11 20:19:00 +00002870 const ASTRecordLayout *NewEntry = 0;
Anders Carlssond2954862010-05-26 05:10:47 +00002871
Reid Kleckneraf1465c2014-02-20 23:07:29 +00002872 if (isMsLayout(D) && !D->getASTContext().getExternalSource()) {
Warren Hunt8f8bad72013-10-11 20:19:00 +00002873 NewEntry = BuildMicrosoftASTRecordLayout(D);
2874 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
Anders Carlssonc121b4e2010-05-27 00:07:01 +00002875 EmptySubobjectMap EmptySubobjects(*this, RD);
John McCall0153cd32011-11-08 04:01:03 +00002876 RecordLayoutBuilder Builder(*this, &EmptySubobjects);
2877 Builder.Layout(RD);
Anders Carlsson439edd12010-05-27 05:41:06 +00002878
John McCall5c1f1d02013-01-29 01:14:22 +00002879 // In certain situations, we are allowed to lay out objects in the
2880 // tail-padding of base classes. This is ABI-dependent.
2881 // FIXME: this should be stored in the record layout.
2882 bool skipTailPadding =
2883 mustSkipTailPadding(getTargetInfo().getCXXABI(), cast<CXXRecordDecl>(D));
Anders Carlssond2954862010-05-26 05:10:47 +00002884
2885 // FIXME: This should be done in FinalizeLayout.
Ken Dyck1b4420e2011-02-28 02:01:38 +00002886 CharUnits DataSize =
John McCall5c1f1d02013-01-29 01:14:22 +00002887 skipTailPadding ? Builder.getSize() : Builder.getDataSize();
Ken Dyck1b4420e2011-02-28 02:01:38 +00002888 CharUnits NonVirtualSize =
John McCall5c1f1d02013-01-29 01:14:22 +00002889 skipTailPadding ? DataSize : Builder.NonVirtualSize;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002890 NewEntry =
John McCall0153cd32011-11-08 04:01:03 +00002891 new (*this) ASTRecordLayout(*this, Builder.getSize(),
2892 Builder.Alignment,
Warren Hunt7b252d22013-12-06 00:01:17 +00002893 /*RequiredAlignment : used by MS-ABI)*/
2894 Builder.Alignment,
John McCalle42a3362012-05-01 08:55:32 +00002895 Builder.HasOwnVFPtr,
Warren Hunt8f8bad72013-10-11 20:19:00 +00002896 RD->isDynamicClass(),
Warren Hunt55d8e822013-10-23 23:53:07 +00002897 CharUnits::fromQuantity(-1),
Ken Dyck1b4420e2011-02-28 02:01:38 +00002898 DataSize,
John McCall0153cd32011-11-08 04:01:03 +00002899 Builder.FieldOffsets.data(),
2900 Builder.FieldOffsets.size(),
Ken Dyckaf1c83f2011-02-16 01:52:01 +00002901 NonVirtualSize,
John McCall0153cd32011-11-08 04:01:03 +00002902 Builder.NonVirtualAlignment,
Anders Carlssonc121b4e2010-05-27 00:07:01 +00002903 EmptySubobjects.SizeOfLargestEmptySubobject,
John McCall0153cd32011-11-08 04:01:03 +00002904 Builder.PrimaryBase,
2905 Builder.PrimaryBaseIsVirtual,
Warren Hunt049f6732013-12-06 19:54:25 +00002906 0, false, false,
John McCall0153cd32011-11-08 04:01:03 +00002907 Builder.Bases, Builder.VBases);
Anders Carlssond2954862010-05-26 05:10:47 +00002908 } else {
John McCall0153cd32011-11-08 04:01:03 +00002909 RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/0);
Anders Carlssond2954862010-05-26 05:10:47 +00002910 Builder.Layout(D);
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002911
Anders Carlssond2954862010-05-26 05:10:47 +00002912 NewEntry =
Ken Dyck1b4420e2011-02-28 02:01:38 +00002913 new (*this) ASTRecordLayout(*this, Builder.getSize(),
Ken Dyck4731d5b2011-02-16 02:05:21 +00002914 Builder.Alignment,
Warren Hunt7b252d22013-12-06 00:01:17 +00002915 /*RequiredAlignment : used by MS-ABI)*/
2916 Builder.Alignment,
Ken Dyck1b4420e2011-02-28 02:01:38 +00002917 Builder.getSize(),
Anders Carlssond2954862010-05-26 05:10:47 +00002918 Builder.FieldOffsets.data(),
2919 Builder.FieldOffsets.size());
2920 }
2921
Anders Carlssondf291d82010-05-26 04:56:53 +00002922 ASTRecordLayouts[D] = NewEntry;
2923
David Blaikiebbafb8a2012-03-11 07:00:24 +00002924 if (getLangOpts().DumpRecordLayouts) {
Argyrios Kyrtzidis8ade08e2013-07-12 22:30:03 +00002925 llvm::outs() << "\n*** Dumping AST Record Layout\n";
2926 DumpRecordLayout(D, llvm::outs(), getLangOpts().DumpRecordLayoutsSimple);
Anders Carlssondf291d82010-05-26 04:56:53 +00002927 }
2928
2929 return *NewEntry;
2930}
2931
John McCall6bd2a892013-01-25 22:31:03 +00002932const CXXMethodDecl *ASTContext::getCurrentKeyFunction(const CXXRecordDecl *RD) {
Reid Kleckner5d7f2982013-05-29 16:18:30 +00002933 if (!getTargetInfo().getCXXABI().hasKeyFunctions())
2934 return 0;
2935
John McCall6bd2a892013-01-25 22:31:03 +00002936 assert(RD->getDefinition() && "Cannot get key function for forward decl!");
Anders Carlssondf291d82010-05-26 04:56:53 +00002937 RD = cast<CXXRecordDecl>(RD->getDefinition());
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002938
Richard Smith676c4042013-08-29 23:59:27 +00002939 LazyDeclPtr &Entry = KeyFunctions[RD];
2940 if (!Entry)
2941 Entry = const_cast<CXXMethodDecl*>(computeKeyFunction(*this, RD));
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002942
Richard Smith676c4042013-08-29 23:59:27 +00002943 return cast_or_null<CXXMethodDecl>(Entry.get(getExternalSource()));
John McCall6bd2a892013-01-25 22:31:03 +00002944}
2945
Richard Smith676c4042013-08-29 23:59:27 +00002946void ASTContext::setNonKeyFunction(const CXXMethodDecl *Method) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002947 assert(Method == Method->getFirstDecl() &&
John McCall6bd2a892013-01-25 22:31:03 +00002948 "not working with method declaration from class definition");
2949
2950 // Look up the cache entry. Since we're working with the first
2951 // declaration, its parent must be the class definition, which is
2952 // the correct key for the KeyFunctions hash.
Richard Smith676c4042013-08-29 23:59:27 +00002953 llvm::DenseMap<const CXXRecordDecl*, LazyDeclPtr>::iterator
2954 I = KeyFunctions.find(Method->getParent());
John McCall6bd2a892013-01-25 22:31:03 +00002955
2956 // If it's not cached, there's nothing to do.
Richard Smith676c4042013-08-29 23:59:27 +00002957 if (I == KeyFunctions.end()) return;
John McCall6bd2a892013-01-25 22:31:03 +00002958
2959 // If it is cached, check whether it's the target method, and if so,
2960 // remove it from the cache.
Richard Smith676c4042013-08-29 23:59:27 +00002961 if (I->second.get(getExternalSource()) == Method) {
John McCall6bd2a892013-01-25 22:31:03 +00002962 // FIXME: remember that we did this for module / chained PCH state?
Richard Smith676c4042013-08-29 23:59:27 +00002963 KeyFunctions.erase(I);
John McCall6bd2a892013-01-25 22:31:03 +00002964 }
Anders Carlssondf291d82010-05-26 04:56:53 +00002965}
2966
Richard Smithdafff942012-01-14 04:30:29 +00002967static uint64_t getFieldOffset(const ASTContext &C, const FieldDecl *FD) {
2968 const ASTRecordLayout &Layout = C.getASTRecordLayout(FD->getParent());
2969 return Layout.getFieldOffset(FD->getFieldIndex());
2970}
2971
2972uint64_t ASTContext::getFieldOffset(const ValueDecl *VD) const {
2973 uint64_t OffsetInBits;
2974 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
2975 OffsetInBits = ::getFieldOffset(*this, FD);
2976 } else {
2977 const IndirectFieldDecl *IFD = cast<IndirectFieldDecl>(VD);
2978
2979 OffsetInBits = 0;
Aaron Ballman29c94602014-03-07 18:36:15 +00002980 for (const auto *CI : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002981 OffsetInBits += ::getFieldOffset(*this, cast<FieldDecl>(CI));
Richard Smithdafff942012-01-14 04:30:29 +00002982 }
2983
2984 return OffsetInBits;
2985}
2986
Eric Christopher8a39a012011-10-05 06:00:51 +00002987/// getObjCLayout - Get or compute information about the layout of the
2988/// given interface.
Anders Carlssondf291d82010-05-26 04:56:53 +00002989///
2990/// \param Impl - If given, also include the layout of the interface's
2991/// implementation. This may differ by including synthesized ivars.
2992const ASTRecordLayout &
2993ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
Jay Foad39c79802011-01-12 09:06:06 +00002994 const ObjCImplementationDecl *Impl) const {
Douglas Gregor64d92572011-12-20 15:50:13 +00002995 // Retrieve the definition
Sean Callanand9a909c2012-03-15 16:33:08 +00002996 if (D->hasExternalLexicalStorage() && !D->getDefinition())
2997 getExternalSource()->CompleteType(const_cast<ObjCInterfaceDecl*>(D));
Douglas Gregor64d92572011-12-20 15:50:13 +00002998 D = D->getDefinition();
2999 assert(D && D->isThisDeclarationADefinition() && "Invalid interface decl!");
Anders Carlssondf291d82010-05-26 04:56:53 +00003000
3001 // Look up this layout, if already laid out, return what we have.
Roman Divackye6377112012-09-06 15:59:27 +00003002 const ObjCContainerDecl *Key =
3003 Impl ? (const ObjCContainerDecl*) Impl : (const ObjCContainerDecl*) D;
Anders Carlssondf291d82010-05-26 04:56:53 +00003004 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
3005 return *Entry;
3006
3007 // Add in synthesized ivar count if laying out an implementation.
3008 if (Impl) {
3009 unsigned SynthCount = CountNonClassIvars(D);
3010 // If there aren't any sythesized ivars then reuse the interface
3011 // entry. Note we can't cache this because we simply free all
3012 // entries later; however we shouldn't look up implementations
3013 // frequently.
3014 if (SynthCount == 0)
3015 return getObjCLayout(D, 0);
3016 }
3017
John McCall0153cd32011-11-08 04:01:03 +00003018 RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/0);
Anders Carlsson6ed3a9a2010-05-26 05:04:25 +00003019 Builder.Layout(D);
3020
Anders Carlssondf291d82010-05-26 04:56:53 +00003021 const ASTRecordLayout *NewEntry =
Ken Dyck1b4420e2011-02-28 02:01:38 +00003022 new (*this) ASTRecordLayout(*this, Builder.getSize(),
Ken Dyck4731d5b2011-02-16 02:05:21 +00003023 Builder.Alignment,
Warren Hunt7b252d22013-12-06 00:01:17 +00003024 /*RequiredAlignment : used by MS-ABI)*/
3025 Builder.Alignment,
Ken Dyck1b4420e2011-02-28 02:01:38 +00003026 Builder.getDataSize(),
Anders Carlsson6ed3a9a2010-05-26 05:04:25 +00003027 Builder.FieldOffsets.data(),
3028 Builder.FieldOffsets.size());
Daniel Dunbar592a85c2010-05-27 02:25:46 +00003029
Anders Carlssondf291d82010-05-26 04:56:53 +00003030 ObjCLayouts[Key] = NewEntry;
3031
3032 return *NewEntry;
3033}
3034
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003035static void PrintOffset(raw_ostream &OS,
Anders Carlsson3f018712010-10-31 23:45:59 +00003036 CharUnits Offset, unsigned IndentLevel) {
Benjamin Kramer96ad7172011-11-05 09:02:52 +00003037 OS << llvm::format("%4" PRId64 " | ", (int64_t)Offset.getQuantity());
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003038 OS.indent(IndentLevel * 2);
3039}
3040
Eli Benderskyf6f93ee2012-12-08 00:07:24 +00003041static void PrintIndentNoOffset(raw_ostream &OS, unsigned IndentLevel) {
3042 OS << " | ";
3043 OS.indent(IndentLevel * 2);
3044}
3045
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003046static void DumpCXXRecordLayout(raw_ostream &OS,
Jay Foad39c79802011-01-12 09:06:06 +00003047 const CXXRecordDecl *RD, const ASTContext &C,
Anders Carlsson3f018712010-10-31 23:45:59 +00003048 CharUnits Offset,
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003049 unsigned IndentLevel,
3050 const char* Description,
3051 bool IncludeVirtualBases) {
Anders Carlsson3f018712010-10-31 23:45:59 +00003052 const ASTRecordLayout &Layout = C.getASTRecordLayout(RD);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003053
3054 PrintOffset(OS, Offset, IndentLevel);
Dan Gohman145f3f12010-04-19 16:39:44 +00003055 OS << C.getTypeDeclType(const_cast<CXXRecordDecl *>(RD)).getAsString();
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003056 if (Description)
3057 OS << ' ' << Description;
3058 if (RD->isEmpty())
3059 OS << " (empty)";
3060 OS << '\n';
3061
3062 IndentLevel++;
3063
Anders Carlsson3f018712010-10-31 23:45:59 +00003064 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
Warren Hunt8f8bad72013-10-11 20:19:00 +00003065 bool HasOwnVFPtr = Layout.hasOwnVFPtr();
3066 bool HasOwnVBPtr = Layout.hasOwnVBPtr();
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003067
3068 // Vtable pointer.
Warren Hunt8f8bad72013-10-11 20:19:00 +00003069 if (RD->isDynamicClass() && !PrimaryBase && !isMsLayout(RD)) {
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003070 PrintOffset(OS, Offset, IndentLevel);
Benjamin Kramerb89514a2011-10-14 18:45:37 +00003071 OS << '(' << *RD << " vtable pointer)\n";
Warren Hunt8f8bad72013-10-11 20:19:00 +00003072 } else if (HasOwnVFPtr) {
3073 PrintOffset(OS, Offset, IndentLevel);
3074 // vfptr (for Microsoft C++ ABI)
3075 OS << '(' << *RD << " vftable pointer)\n";
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003076 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00003077
Reid Klecknerad59deb2014-02-28 01:03:09 +00003078 // Collect nvbases.
3079 SmallVector<const CXXRecordDecl *, 4> Bases;
Aaron Ballman574705e2014-03-13 15:41:46 +00003080 for (const auto &I : RD->bases()) {
3081 assert(!I.getType()->isDependentType() &&
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003082 "Cannot layout class with dependent bases.");
Aaron Ballman574705e2014-03-13 15:41:46 +00003083 if (!I.isVirtual())
3084 Bases.push_back(I.getType()->getAsCXXRecordDecl());
Reid Klecknerad59deb2014-02-28 01:03:09 +00003085 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003086
Reid Klecknerad59deb2014-02-28 01:03:09 +00003087 // Sort nvbases by offset.
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00003088 std::stable_sort(Bases.begin(), Bases.end(),
3089 [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
3090 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
3091 });
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003092
Reid Klecknerad59deb2014-02-28 01:03:09 +00003093 // Dump (non-virtual) bases
3094 for (SmallVectorImpl<const CXXRecordDecl *>::iterator I = Bases.begin(),
3095 E = Bases.end();
3096 I != E; ++I) {
3097 const CXXRecordDecl *Base = *I;
Anders Carlsson3f018712010-10-31 23:45:59 +00003098 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003099 DumpCXXRecordLayout(OS, Base, C, BaseOffset, IndentLevel,
3100 Base == PrimaryBase ? "(primary base)" : "(base)",
3101 /*IncludeVirtualBases=*/false);
3102 }
Eli Friedman43114f92011-10-21 22:49:56 +00003103
Warren Hunt8f8bad72013-10-11 20:19:00 +00003104 // vbptr (for Microsoft C++ ABI)
3105 if (HasOwnVBPtr) {
Eli Friedman84d2d3a2011-09-27 19:12:27 +00003106 PrintOffset(OS, Offset + Layout.getVBPtrOffset(), IndentLevel);
Benjamin Kramerb89514a2011-10-14 18:45:37 +00003107 OS << '(' << *RD << " vbtable pointer)\n";
Eli Friedman84d2d3a2011-09-27 19:12:27 +00003108 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003109
3110 // Dump fields.
3111 uint64_t FieldNo = 0;
3112 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
3113 E = RD->field_end(); I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +00003114 const FieldDecl &Field = **I;
Anders Carlsson3f018712010-10-31 23:45:59 +00003115 CharUnits FieldOffset = Offset +
Ken Dyck86a7fcc2011-01-18 01:56:16 +00003116 C.toCharUnitsFromBits(Layout.getFieldOffset(FieldNo));
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003117
David Blaikie2d7c57e2012-04-30 02:36:29 +00003118 if (const RecordType *RT = Field.getType()->getAs<RecordType>()) {
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003119 if (const CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3120 DumpCXXRecordLayout(OS, D, C, FieldOffset, IndentLevel,
David Blaikie2d7c57e2012-04-30 02:36:29 +00003121 Field.getName().data(),
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003122 /*IncludeVirtualBases=*/true);
3123 continue;
3124 }
3125 }
3126
3127 PrintOffset(OS, FieldOffset, IndentLevel);
David Blaikie2d7c57e2012-04-30 02:36:29 +00003128 OS << Field.getType().getAsString() << ' ' << Field << '\n';
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003129 }
3130
3131 if (!IncludeVirtualBases)
3132 return;
3133
3134 // Dump virtual bases.
John McCalle42a3362012-05-01 08:55:32 +00003135 const ASTRecordLayout::VBaseOffsetsMapTy &vtordisps =
3136 Layout.getVBaseOffsetsMap();
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003137 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
3138 E = RD->vbases_end(); I != E; ++I) {
3139 assert(I->isVirtual() && "Found non-virtual class!");
3140 const CXXRecordDecl *VBase =
3141 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
3142
Anders Carlsson3f018712010-10-31 23:45:59 +00003143 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBase);
John McCalle42a3362012-05-01 08:55:32 +00003144
3145 if (vtordisps.find(VBase)->second.hasVtorDisp()) {
3146 PrintOffset(OS, VBaseOffset - CharUnits::fromQuantity(4), IndentLevel);
3147 OS << "(vtordisp for vbase " << *VBase << ")\n";
3148 }
3149
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003150 DumpCXXRecordLayout(OS, VBase, C, VBaseOffset, IndentLevel,
3151 VBase == PrimaryBase ?
3152 "(primary virtual base)" : "(virtual base)",
3153 /*IncludeVirtualBases=*/false);
3154 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003155
Eli Benderskyf6f93ee2012-12-08 00:07:24 +00003156 PrintIndentNoOffset(OS, IndentLevel - 1);
3157 OS << "[sizeof=" << Layout.getSize().getQuantity();
Warren Hunt8f8bad72013-10-11 20:19:00 +00003158 if (!isMsLayout(RD))
3159 OS << ", dsize=" << Layout.getDataSize().getQuantity();
Ken Dyck7ad11e72011-02-15 02:32:40 +00003160 OS << ", align=" << Layout.getAlignment().getQuantity() << '\n';
Eli Benderskyf6f93ee2012-12-08 00:07:24 +00003161
3162 PrintIndentNoOffset(OS, IndentLevel - 1);
3163 OS << " nvsize=" << Layout.getNonVirtualSize().getQuantity();
Warren Huntd640d7d2014-01-09 00:30:56 +00003164 OS << ", nvalign=" << Layout.getNonVirtualAlignment().getQuantity() << "]\n";
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003165 OS << '\n';
3166}
Daniel Dunbarccabe482010-04-19 20:44:53 +00003167
3168void ASTContext::DumpRecordLayout(const RecordDecl *RD,
Douglas Gregore9fc3772012-01-26 07:55:45 +00003169 raw_ostream &OS,
3170 bool Simple) const {
Daniel Dunbarccabe482010-04-19 20:44:53 +00003171 const ASTRecordLayout &Info = getASTRecordLayout(RD);
3172
3173 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Douglas Gregore9fc3772012-01-26 07:55:45 +00003174 if (!Simple)
3175 return DumpCXXRecordLayout(OS, CXXRD, *this, CharUnits(), 0, 0,
3176 /*IncludeVirtualBases=*/true);
Daniel Dunbarccabe482010-04-19 20:44:53 +00003177
3178 OS << "Type: " << getTypeDeclType(RD).getAsString() << "\n";
Douglas Gregore9fc3772012-01-26 07:55:45 +00003179 if (!Simple) {
3180 OS << "Record: ";
3181 RD->dump();
3182 }
Daniel Dunbarccabe482010-04-19 20:44:53 +00003183 OS << "\nLayout: ";
3184 OS << "<ASTRecordLayout\n";
Ken Dyckb0fcc592011-02-11 01:54:29 +00003185 OS << " Size:" << toBits(Info.getSize()) << "\n";
Warren Hunt8f8bad72013-10-11 20:19:00 +00003186 if (!isMsLayout(RD))
3187 OS << " DataSize:" << toBits(Info.getDataSize()) << "\n";
Ken Dyck7ad11e72011-02-15 02:32:40 +00003188 OS << " Alignment:" << toBits(Info.getAlignment()) << "\n";
Daniel Dunbarccabe482010-04-19 20:44:53 +00003189 OS << " FieldOffsets: [";
3190 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i) {
3191 if (i) OS << ", ";
3192 OS << Info.getFieldOffset(i);
3193 }
3194 OS << "]>\n";
3195}