blob: fa208acf4ed1fefac4ad35d6ae2d77aff89d3d47 [file] [log] [blame]
Anders Carlsson35a36eb2010-05-26 05:41:04 +00001//=== RecordLayoutBuilder.cpp - Helper class for building record layouts ---==//
Anders Carlsson79474332009-07-18 20:20:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Chandler Carruth3a022472012-12-04 09:13:33 +000010#include "clang/AST/RecordLayout.h"
Benjamin Kramer2ef30312012-07-04 18:45:14 +000011#include "clang/AST/ASTContext.h"
Anders Carlsson79474332009-07-18 20:20:21 +000012#include "clang/AST/Attr.h"
Anders Carlsson5adde292010-11-24 22:55:48 +000013#include "clang/AST/CXXInheritance.h"
Anders Carlsson79474332009-07-18 20:20:21 +000014#include "clang/AST/Decl.h"
Anders Carlsson6d9f6f32009-07-19 00:18:47 +000015#include "clang/AST/DeclCXX.h"
Anders Carlsson4f516282009-07-18 20:50:59 +000016#include "clang/AST/DeclObjC.h"
Anders Carlsson79474332009-07-18 20:20:21 +000017#include "clang/AST/Expr.h"
Anders Carlsson79474332009-07-18 20:20:21 +000018#include "clang/Basic/TargetInfo.h"
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +000019#include "clang/Sema/SemaDiagnostic.h"
Daniel Dunbaraa423af2010-04-08 02:59:49 +000020#include "llvm/ADT/SmallSet.h"
Ted Kremenekf75d0892011-03-19 01:00:36 +000021#include "llvm/Support/CrashRecoveryContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "llvm/Support/Format.h"
23#include "llvm/Support/MathExtras.h"
Anders Carlsson79474332009-07-18 20:20:21 +000024
25using namespace clang;
26
Benjamin Kramerc7656cd2010-05-26 09:58:31 +000027namespace {
Anders Carlssonf58de112010-05-26 15:32:58 +000028
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000029/// BaseSubobjectInfo - Represents a single base subobject in a complete class.
30/// For a class hierarchy like
31///
32/// class A { };
33/// class B : A { };
34/// class C : A, B { };
35///
36/// The BaseSubobjectInfo graph for C will have three BaseSubobjectInfo
37/// instances, one for B and two for A.
38///
39/// If a base is virtual, it will only have one BaseSubobjectInfo allocated.
40struct BaseSubobjectInfo {
41 /// Class - The class for this base info.
Anders Carlsson056818f2010-05-28 21:13:31 +000042 const CXXRecordDecl *Class;
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000043
44 /// IsVirtual - Whether the BaseInfo represents a virtual base or not.
Anders Carlsson056818f2010-05-28 21:13:31 +000045 bool IsVirtual;
46
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000047 /// Bases - Information about the base subobjects.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000048 SmallVector<BaseSubobjectInfo*, 4> Bases;
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000049
Anders Carlssone3c24c72010-05-29 17:35:14 +000050 /// PrimaryVirtualBaseInfo - Holds the base info for the primary virtual base
51 /// of this base info (if one exists).
52 BaseSubobjectInfo *PrimaryVirtualBaseInfo;
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000053
54 // FIXME: Document.
55 const BaseSubobjectInfo *Derived;
Anders Carlsson056818f2010-05-28 21:13:31 +000056};
57
Anders Carlssonf58de112010-05-26 15:32:58 +000058/// EmptySubobjectMap - Keeps track of which empty subobjects exist at different
59/// offsets while laying out a C++ class.
60class EmptySubobjectMap {
Jay Foad39c79802011-01-12 09:06:06 +000061 const ASTContext &Context;
Anders Carlsson233e2722010-10-31 21:54:55 +000062 uint64_t CharWidth;
63
Anders Carlssonf58de112010-05-26 15:32:58 +000064 /// Class - The class whose empty entries we're keeping track of.
65 const CXXRecordDecl *Class;
Daniel Dunbar592a85c2010-05-27 02:25:46 +000066
Anders Carlsson439edd12010-05-27 05:41:06 +000067 /// EmptyClassOffsets - A map from offsets to empty record decls.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000068 typedef SmallVector<const CXXRecordDecl *, 1> ClassVectorTy;
Anders Carlssonf8f756d2010-10-31 21:22:43 +000069 typedef llvm::DenseMap<CharUnits, ClassVectorTy> EmptyClassOffsetsMapTy;
Anders Carlsson439edd12010-05-27 05:41:06 +000070 EmptyClassOffsetsMapTy EmptyClassOffsets;
71
Anders Carlssoncc5de092010-06-08 15:56:03 +000072 /// MaxEmptyClassOffset - The highest offset known to contain an empty
73 /// base subobject.
Anders Carlsson725190f2010-10-31 21:39:24 +000074 CharUnits MaxEmptyClassOffset;
Anders Carlssoncc5de092010-06-08 15:56:03 +000075
Daniel Dunbar592a85c2010-05-27 02:25:46 +000076 /// ComputeEmptySubobjectSizes - Compute the size of the largest base or
Anders Carlssonc5ca1f72010-05-26 15:54:25 +000077 /// member subobject that is empty.
78 void ComputeEmptySubobjectSizes();
Anders Carlsson439edd12010-05-27 05:41:06 +000079
Anders Carlsson725190f2010-10-31 21:39:24 +000080 void AddSubobjectAtOffset(const CXXRecordDecl *RD, CharUnits Offset);
Anders Carlssondb319762010-05-27 18:20:57 +000081
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000082 void UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +000083 CharUnits Offset, bool PlacingEmptyBase);
Anders Carlsson439edd12010-05-27 05:41:06 +000084
Anders Carlssondb319762010-05-27 18:20:57 +000085 void UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD,
86 const CXXRecordDecl *Class,
Anders Carlsson28466ab2010-10-31 22:13:23 +000087 CharUnits Offset);
88 void UpdateEmptyFieldSubobjects(const FieldDecl *FD, CharUnits Offset);
Anders Carlssondb319762010-05-27 18:20:57 +000089
Anders Carlssoncc5de092010-06-08 15:56:03 +000090 /// AnyEmptySubobjectsBeyondOffset - Returns whether there are any empty
91 /// subobjects beyond the given offset.
Anders Carlsson725190f2010-10-31 21:39:24 +000092 bool AnyEmptySubobjectsBeyondOffset(CharUnits Offset) const {
Anders Carlssoncc5de092010-06-08 15:56:03 +000093 return Offset <= MaxEmptyClassOffset;
94 }
95
Anders Carlsson233e2722010-10-31 21:54:55 +000096 CharUnits
97 getFieldOffset(const ASTRecordLayout &Layout, unsigned FieldNo) const {
98 uint64_t FieldOffset = Layout.getFieldOffset(FieldNo);
99 assert(FieldOffset % CharWidth == 0 &&
100 "Field offset not at char boundary!");
101
Ken Dyck7c4026b2011-01-24 01:28:50 +0000102 return Context.toCharUnitsFromBits(FieldOffset);
Anders Carlssonf8f756d2010-10-31 21:22:43 +0000103 }
Anders Carlssonf8f756d2010-10-31 21:22:43 +0000104
Charles Davisc2c576a2010-08-19 00:55:19 +0000105protected:
Anders Carlsson725190f2010-10-31 21:39:24 +0000106 bool CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD,
107 CharUnits Offset) const;
Charles Davisc2c576a2010-08-19 00:55:19 +0000108
109 bool CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000110 CharUnits Offset);
Charles Davisc2c576a2010-08-19 00:55:19 +0000111
112 bool CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD,
113 const CXXRecordDecl *Class,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000114 CharUnits Offset) const;
Charles Davisc2c576a2010-08-19 00:55:19 +0000115 bool CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD,
Anders Carlsson233e2722010-10-31 21:54:55 +0000116 CharUnits Offset) const;
Charles Davisc2c576a2010-08-19 00:55:19 +0000117
Anders Carlssonf58de112010-05-26 15:32:58 +0000118public:
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000119 /// This holds the size of the largest empty subobject (either a base
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000120 /// or a member). Will be zero if the record being built doesn't contain
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000121 /// any empty classes.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000122 CharUnits SizeOfLargestEmptySubobject;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000123
Jay Foad39c79802011-01-12 09:06:06 +0000124 EmptySubobjectMap(const ASTContext &Context, const CXXRecordDecl *Class)
Anders Carlsson28466ab2010-10-31 22:13:23 +0000125 : Context(Context), CharWidth(Context.getCharWidth()), Class(Class) {
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000126 ComputeEmptySubobjectSizes();
127 }
128
129 /// CanPlaceBaseAtOffset - Return whether the given base class can be placed
130 /// at the given offset.
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000131 /// Returns false if placing the record will result in two components
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000132 /// (direct or indirect) of the same type having the same offset.
Anders Carlssoncc5de092010-06-08 15:56:03 +0000133 bool CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000134 CharUnits Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000135
136 /// CanPlaceFieldAtOffset - Return whether a field can be placed at the given
137 /// offset.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000138 bool CanPlaceFieldAtOffset(const FieldDecl *FD, CharUnits Offset);
Anders Carlssonf58de112010-05-26 15:32:58 +0000139};
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000140
141void EmptySubobjectMap::ComputeEmptySubobjectSizes() {
142 // Check the bases.
143 for (CXXRecordDecl::base_class_const_iterator I = Class->bases_begin(),
144 E = Class->bases_end(); I != E; ++I) {
145 const CXXRecordDecl *BaseDecl =
146 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
147
Anders Carlsson28466ab2010-10-31 22:13:23 +0000148 CharUnits EmptySize;
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000149 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
150 if (BaseDecl->isEmpty()) {
151 // If the class decl is empty, get its size.
Ken Dyckc8ae5502011-02-09 01:59:34 +0000152 EmptySize = Layout.getSize();
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000153 } else {
154 // Otherwise, we get the largest empty subobject for the decl.
155 EmptySize = Layout.getSizeOfLargestEmptySubobject();
156 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000157
Anders Carlsson28466ab2010-10-31 22:13:23 +0000158 if (EmptySize > SizeOfLargestEmptySubobject)
159 SizeOfLargestEmptySubobject = EmptySize;
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000160 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000161
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000162 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000163 for (const auto *I : Class->fields()) {
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000164 const RecordType *RT =
David Blaikie40ed2972012-06-06 20:45:41 +0000165 Context.getBaseElementType(I->getType())->getAs<RecordType>();
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000166
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000167 // We only care about record types.
168 if (!RT)
169 continue;
170
Anders Carlsson28466ab2010-10-31 22:13:23 +0000171 CharUnits EmptySize;
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000172 const CXXRecordDecl *MemberDecl = cast<CXXRecordDecl>(RT->getDecl());
173 const ASTRecordLayout &Layout = Context.getASTRecordLayout(MemberDecl);
174 if (MemberDecl->isEmpty()) {
175 // If the class decl is empty, get its size.
Ken Dyckc8ae5502011-02-09 01:59:34 +0000176 EmptySize = Layout.getSize();
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000177 } else {
178 // Otherwise, we get the largest empty subobject for the decl.
179 EmptySize = Layout.getSizeOfLargestEmptySubobject();
180 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000181
Anders Carlsson28466ab2010-10-31 22:13:23 +0000182 if (EmptySize > SizeOfLargestEmptySubobject)
183 SizeOfLargestEmptySubobject = EmptySize;
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000184 }
185}
186
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000187bool
Anders Carlssondb319762010-05-27 18:20:57 +0000188EmptySubobjectMap::CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD,
Anders Carlsson725190f2010-10-31 21:39:24 +0000189 CharUnits Offset) const {
Anders Carlssondb319762010-05-27 18:20:57 +0000190 // We only need to check empty bases.
191 if (!RD->isEmpty())
192 return true;
193
Anders Carlsson725190f2010-10-31 21:39:24 +0000194 EmptyClassOffsetsMapTy::const_iterator I = EmptyClassOffsets.find(Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000195 if (I == EmptyClassOffsets.end())
196 return true;
197
198 const ClassVectorTy& Classes = I->second;
199 if (std::find(Classes.begin(), Classes.end(), RD) == Classes.end())
200 return true;
201
202 // There is already an empty class of the same type at this offset.
203 return false;
204}
205
206void EmptySubobjectMap::AddSubobjectAtOffset(const CXXRecordDecl *RD,
Anders Carlsson725190f2010-10-31 21:39:24 +0000207 CharUnits Offset) {
Anders Carlssondb319762010-05-27 18:20:57 +0000208 // We only care about empty bases.
209 if (!RD->isEmpty())
210 return;
211
Reid Kleckner369f3162013-05-14 20:30:42 +0000212 // If we have empty structures inside a union, we can assign both
Rafael Espindola7bcde192010-12-29 23:02:58 +0000213 // the same offset. Just avoid pushing them twice in the list.
Anders Carlsson725190f2010-10-31 21:39:24 +0000214 ClassVectorTy& Classes = EmptyClassOffsets[Offset];
Rafael Espindola7bcde192010-12-29 23:02:58 +0000215 if (std::find(Classes.begin(), Classes.end(), RD) != Classes.end())
216 return;
217
Anders Carlssondb319762010-05-27 18:20:57 +0000218 Classes.push_back(RD);
Anders Carlssoncc5de092010-06-08 15:56:03 +0000219
220 // Update the empty class offset.
Anders Carlsson725190f2010-10-31 21:39:24 +0000221 if (Offset > MaxEmptyClassOffset)
222 MaxEmptyClassOffset = Offset;
Anders Carlssondb319762010-05-27 18:20:57 +0000223}
224
225bool
Anders Carlsson28466ab2010-10-31 22:13:23 +0000226EmptySubobjectMap::CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info,
227 CharUnits Offset) {
Anders Carlsson45c1d282010-06-08 16:20:35 +0000228 // We don't have to keep looking past the maximum offset that's known to
229 // contain an empty class.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000230 if (!AnyEmptySubobjectsBeyondOffset(Offset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000231 return true;
232
Anders Carlsson28466ab2010-10-31 22:13:23 +0000233 if (!CanPlaceSubobjectAtOffset(Info->Class, Offset))
Anders Carlssondb319762010-05-27 18:20:57 +0000234 return false;
235
Anders Carlsson439edd12010-05-27 05:41:06 +0000236 // Traverse all non-virtual bases.
Anders Carlssona7774a62010-05-29 21:10:24 +0000237 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
Anders Carlsson439edd12010-05-27 05:41:06 +0000238 for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) {
Anders Carlssona7f3cdb2010-05-28 21:24:37 +0000239 BaseSubobjectInfo* Base = Info->Bases[I];
Anders Carlsson439edd12010-05-27 05:41:06 +0000240 if (Base->IsVirtual)
241 continue;
242
Anders Carlsson0a14ee92010-11-01 00:21:58 +0000243 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
Anders Carlsson439edd12010-05-27 05:41:06 +0000244
245 if (!CanPlaceBaseSubobjectAtOffset(Base, BaseOffset))
246 return false;
247 }
248
Anders Carlssone3c24c72010-05-29 17:35:14 +0000249 if (Info->PrimaryVirtualBaseInfo) {
250 BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
Anders Carlsson439edd12010-05-27 05:41:06 +0000251
252 if (Info == PrimaryVirtualBaseInfo->Derived) {
253 if (!CanPlaceBaseSubobjectAtOffset(PrimaryVirtualBaseInfo, Offset))
254 return false;
255 }
256 }
257
Anders Carlssondb319762010-05-27 18:20:57 +0000258 // Traverse all member variables.
259 unsigned FieldNo = 0;
260 for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(),
261 E = Info->Class->field_end(); I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +0000262 if (I->isBitField())
Anders Carlsson233e2722010-10-31 21:54:55 +0000263 continue;
264
Anders Carlsson28466ab2010-10-31 22:13:23 +0000265 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
David Blaikie40ed2972012-06-06 20:45:41 +0000266 if (!CanPlaceFieldSubobjectAtOffset(*I, FieldOffset))
Anders Carlssondb319762010-05-27 18:20:57 +0000267 return false;
268 }
269
Anders Carlsson439edd12010-05-27 05:41:06 +0000270 return true;
271}
272
Anders Carlssona7f3cdb2010-05-28 21:24:37 +0000273void EmptySubobjectMap::UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000274 CharUnits Offset,
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000275 bool PlacingEmptyBase) {
276 if (!PlacingEmptyBase && Offset >= SizeOfLargestEmptySubobject) {
277 // We know that the only empty subobjects that can conflict with empty
278 // subobject of non-empty bases, are empty bases that can be placed at
279 // offset zero. Because of this, we only need to keep track of empty base
280 // subobjects with offsets less than the size of the largest empty
281 // subobject for our class.
282 return;
283 }
284
Anders Carlsson28466ab2010-10-31 22:13:23 +0000285 AddSubobjectAtOffset(Info->Class, Offset);
Anders Carlssona7774a62010-05-29 21:10:24 +0000286
Anders Carlsson439edd12010-05-27 05:41:06 +0000287 // Traverse all non-virtual bases.
Anders Carlssona7774a62010-05-29 21:10:24 +0000288 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
Anders Carlsson439edd12010-05-27 05:41:06 +0000289 for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) {
Anders Carlssona7f3cdb2010-05-28 21:24:37 +0000290 BaseSubobjectInfo* Base = Info->Bases[I];
Anders Carlsson439edd12010-05-27 05:41:06 +0000291 if (Base->IsVirtual)
292 continue;
Anders Carlssona7774a62010-05-29 21:10:24 +0000293
Anders Carlsson0a14ee92010-11-01 00:21:58 +0000294 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000295 UpdateEmptyBaseSubobjects(Base, BaseOffset, PlacingEmptyBase);
Anders Carlsson439edd12010-05-27 05:41:06 +0000296 }
297
Anders Carlssone3c24c72010-05-29 17:35:14 +0000298 if (Info->PrimaryVirtualBaseInfo) {
299 BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
Anders Carlsson439edd12010-05-27 05:41:06 +0000300
301 if (Info == PrimaryVirtualBaseInfo->Derived)
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000302 UpdateEmptyBaseSubobjects(PrimaryVirtualBaseInfo, Offset,
303 PlacingEmptyBase);
Anders Carlsson439edd12010-05-27 05:41:06 +0000304 }
Anders Carlssondb319762010-05-27 18:20:57 +0000305
Anders Carlssondb319762010-05-27 18:20:57 +0000306 // Traverse all member variables.
307 unsigned FieldNo = 0;
308 for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(),
309 E = Info->Class->field_end(); I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +0000310 if (I->isBitField())
Anders Carlsson233e2722010-10-31 21:54:55 +0000311 continue;
Anders Carlssona7774a62010-05-29 21:10:24 +0000312
Anders Carlsson28466ab2010-10-31 22:13:23 +0000313 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
David Blaikie40ed2972012-06-06 20:45:41 +0000314 UpdateEmptyFieldSubobjects(*I, FieldOffset);
Anders Carlssondb319762010-05-27 18:20:57 +0000315 }
Anders Carlsson439edd12010-05-27 05:41:06 +0000316}
317
Anders Carlssona60b86a2010-05-29 20:49:49 +0000318bool EmptySubobjectMap::CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000319 CharUnits Offset) {
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000320 // If we know this class doesn't have any empty subobjects we don't need to
321 // bother checking.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000322 if (SizeOfLargestEmptySubobject.isZero())
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000323 return true;
324
Anders Carlsson439edd12010-05-27 05:41:06 +0000325 if (!CanPlaceBaseSubobjectAtOffset(Info, Offset))
326 return false;
Anders Carlssondb319762010-05-27 18:20:57 +0000327
328 // We are able to place the base at this offset. Make sure to update the
329 // empty base subobject map.
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000330 UpdateEmptyBaseSubobjects(Info, Offset, Info->Class->isEmpty());
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000331 return true;
332}
333
Anders Carlssondb319762010-05-27 18:20:57 +0000334bool
335EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD,
336 const CXXRecordDecl *Class,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000337 CharUnits Offset) const {
Anders Carlsson45c1d282010-06-08 16:20:35 +0000338 // We don't have to keep looking past the maximum offset that's known to
339 // contain an empty class.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000340 if (!AnyEmptySubobjectsBeyondOffset(Offset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000341 return true;
342
Anders Carlsson28466ab2010-10-31 22:13:23 +0000343 if (!CanPlaceSubobjectAtOffset(RD, Offset))
Anders Carlssondb319762010-05-27 18:20:57 +0000344 return false;
345
346 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
347
348 // Traverse all non-virtual bases.
349 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
350 E = RD->bases_end(); I != E; ++I) {
351 if (I->isVirtual())
352 continue;
353
354 const CXXRecordDecl *BaseDecl =
355 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
356
Anders Carlsson0a14ee92010-11-01 00:21:58 +0000357 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
Anders Carlssondb319762010-05-27 18:20:57 +0000358 if (!CanPlaceFieldSubobjectAtOffset(BaseDecl, Class, BaseOffset))
359 return false;
360 }
361
Anders Carlsson44687202010-06-08 19:09:24 +0000362 if (RD == Class) {
363 // This is the most derived class, traverse virtual bases as well.
364 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
365 E = RD->vbases_end(); I != E; ++I) {
366 const CXXRecordDecl *VBaseDecl =
367 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
368
Anders Carlsson3f018712010-10-31 23:45:59 +0000369 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
Anders Carlsson44687202010-06-08 19:09:24 +0000370 if (!CanPlaceFieldSubobjectAtOffset(VBaseDecl, Class, VBaseOffset))
371 return false;
372 }
373 }
374
Anders Carlssondb319762010-05-27 18:20:57 +0000375 // Traverse all member variables.
376 unsigned FieldNo = 0;
377 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
378 I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +0000379 if (I->isBitField())
Anders Carlsson233e2722010-10-31 21:54:55 +0000380 continue;
381
Anders Carlsson28466ab2010-10-31 22:13:23 +0000382 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
Anders Carlssondb319762010-05-27 18:20:57 +0000383
David Blaikie40ed2972012-06-06 20:45:41 +0000384 if (!CanPlaceFieldSubobjectAtOffset(*I, FieldOffset))
Anders Carlssondb319762010-05-27 18:20:57 +0000385 return false;
386 }
387
388 return true;
389}
390
Anders Carlsson233e2722010-10-31 21:54:55 +0000391bool
392EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD,
393 CharUnits Offset) const {
Anders Carlsson45c1d282010-06-08 16:20:35 +0000394 // We don't have to keep looking past the maximum offset that's known to
395 // contain an empty class.
Anders Carlsson233e2722010-10-31 21:54:55 +0000396 if (!AnyEmptySubobjectsBeyondOffset(Offset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000397 return true;
398
Anders Carlssondb319762010-05-27 18:20:57 +0000399 QualType T = FD->getType();
400 if (const RecordType *RT = T->getAs<RecordType>()) {
401 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson28466ab2010-10-31 22:13:23 +0000402 return CanPlaceFieldSubobjectAtOffset(RD, RD, Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000403 }
404
405 // If we have an array type we need to look at every element.
406 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
407 QualType ElemTy = Context.getBaseElementType(AT);
408 const RecordType *RT = ElemTy->getAs<RecordType>();
409 if (!RT)
410 return true;
411
412 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
413 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
414
415 uint64_t NumElements = Context.getConstantArrayElementCount(AT);
Anders Carlsson233e2722010-10-31 21:54:55 +0000416 CharUnits ElementOffset = Offset;
Anders Carlssondb319762010-05-27 18:20:57 +0000417 for (uint64_t I = 0; I != NumElements; ++I) {
Anders Carlsson45c1d282010-06-08 16:20:35 +0000418 // We don't have to keep looking past the maximum offset that's known to
419 // contain an empty class.
Anders Carlsson233e2722010-10-31 21:54:55 +0000420 if (!AnyEmptySubobjectsBeyondOffset(ElementOffset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000421 return true;
422
Anders Carlsson28466ab2010-10-31 22:13:23 +0000423 if (!CanPlaceFieldSubobjectAtOffset(RD, RD, ElementOffset))
Anders Carlssondb319762010-05-27 18:20:57 +0000424 return false;
425
Ken Dyckc8ae5502011-02-09 01:59:34 +0000426 ElementOffset += Layout.getSize();
Anders Carlssondb319762010-05-27 18:20:57 +0000427 }
428 }
429
430 return true;
431}
432
433bool
Anders Carlsson28466ab2010-10-31 22:13:23 +0000434EmptySubobjectMap::CanPlaceFieldAtOffset(const FieldDecl *FD,
435 CharUnits Offset) {
436 if (!CanPlaceFieldSubobjectAtOffset(FD, Offset))
Anders Carlssondb319762010-05-27 18:20:57 +0000437 return false;
438
439 // We are able to place the member variable at this offset.
440 // Make sure to update the empty base subobject map.
441 UpdateEmptyFieldSubobjects(FD, Offset);
442 return true;
443}
444
445void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD,
446 const CXXRecordDecl *Class,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000447 CharUnits Offset) {
Anders Carlssonae111dc2010-06-13 17:49:16 +0000448 // We know that the only empty subobjects that can conflict with empty
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000449 // field subobjects are subobjects of empty bases that can be placed at offset
Anders Carlssonae111dc2010-06-13 17:49:16 +0000450 // zero. Because of this, we only need to keep track of empty field
451 // subobjects with offsets less than the size of the largest empty
452 // subobject for our class.
453 if (Offset >= SizeOfLargestEmptySubobject)
454 return;
455
Anders Carlsson28466ab2010-10-31 22:13:23 +0000456 AddSubobjectAtOffset(RD, Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000457
458 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
459
460 // Traverse all non-virtual bases.
461 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
462 E = RD->bases_end(); I != E; ++I) {
463 if (I->isVirtual())
464 continue;
465
466 const CXXRecordDecl *BaseDecl =
467 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
468
Anders Carlsson0a14ee92010-11-01 00:21:58 +0000469 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
Anders Carlssondb319762010-05-27 18:20:57 +0000470 UpdateEmptyFieldSubobjects(BaseDecl, Class, BaseOffset);
471 }
472
Anders Carlsson44687202010-06-08 19:09:24 +0000473 if (RD == Class) {
474 // This is the most derived class, traverse virtual bases as well.
475 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
476 E = RD->vbases_end(); I != E; ++I) {
477 const CXXRecordDecl *VBaseDecl =
478 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
479
Anders Carlsson3f018712010-10-31 23:45:59 +0000480 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
Anders Carlsson44687202010-06-08 19:09:24 +0000481 UpdateEmptyFieldSubobjects(VBaseDecl, Class, VBaseOffset);
482 }
483 }
484
Anders Carlssondb319762010-05-27 18:20:57 +0000485 // Traverse all member variables.
486 unsigned FieldNo = 0;
487 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
488 I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +0000489 if (I->isBitField())
Anders Carlsson09814d32010-11-01 15:14:51 +0000490 continue;
491
Anders Carlsson28466ab2010-10-31 22:13:23 +0000492 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
Anders Carlssondb319762010-05-27 18:20:57 +0000493
David Blaikie40ed2972012-06-06 20:45:41 +0000494 UpdateEmptyFieldSubobjects(*I, FieldOffset);
Anders Carlssondb319762010-05-27 18:20:57 +0000495 }
496}
497
498void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const FieldDecl *FD,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000499 CharUnits Offset) {
Anders Carlssondb319762010-05-27 18:20:57 +0000500 QualType T = FD->getType();
501 if (const RecordType *RT = T->getAs<RecordType>()) {
502 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
503 UpdateEmptyFieldSubobjects(RD, RD, Offset);
504 return;
505 }
506
507 // If we have an array type we need to update every element.
508 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
509 QualType ElemTy = Context.getBaseElementType(AT);
510 const RecordType *RT = ElemTy->getAs<RecordType>();
511 if (!RT)
512 return;
513
514 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
515 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
516
517 uint64_t NumElements = Context.getConstantArrayElementCount(AT);
Anders Carlsson28466ab2010-10-31 22:13:23 +0000518 CharUnits ElementOffset = Offset;
Anders Carlssondb319762010-05-27 18:20:57 +0000519
520 for (uint64_t I = 0; I != NumElements; ++I) {
Anders Carlssonae111dc2010-06-13 17:49:16 +0000521 // We know that the only empty subobjects that can conflict with empty
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000522 // field subobjects are subobjects of empty bases that can be placed at
Anders Carlssonae111dc2010-06-13 17:49:16 +0000523 // offset zero. Because of this, we only need to keep track of empty field
524 // subobjects with offsets less than the size of the largest empty
525 // subobject for our class.
526 if (ElementOffset >= SizeOfLargestEmptySubobject)
527 return;
528
Anders Carlssondb319762010-05-27 18:20:57 +0000529 UpdateEmptyFieldSubobjects(RD, RD, ElementOffset);
Ken Dyckc8ae5502011-02-09 01:59:34 +0000530 ElementOffset += Layout.getSize();
Anders Carlssondb319762010-05-27 18:20:57 +0000531 }
532 }
533}
534
John McCalle42a3362012-05-01 08:55:32 +0000535typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> ClassSetTy;
536
Anders Carlssonc2226202010-05-26 05:58:59 +0000537class RecordLayoutBuilder {
Charles Davisc2c576a2010-08-19 00:55:19 +0000538protected:
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000539 // FIXME: Remove this and make the appropriate fields public.
540 friend class clang::ASTContext;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000541
Jay Foad39c79802011-01-12 09:06:06 +0000542 const ASTContext &Context;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000543
Anders Carlssonf58de112010-05-26 15:32:58 +0000544 EmptySubobjectMap *EmptySubobjects;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000545
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000546 /// Size - The current size of the record layout.
547 uint64_t Size;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000548
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000549 /// Alignment - The current alignment of the record layout.
Ken Dyck4731d5b2011-02-16 02:05:21 +0000550 CharUnits Alignment;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000551
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000552 /// \brief The alignment if attribute packed is not used.
Ken Dyck1300b3b2011-02-16 02:11:31 +0000553 CharUnits UnpackedAlignment;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000554
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000555 SmallVector<uint64_t, 16> FieldOffsets;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000556
Douglas Gregore9fc3772012-01-26 07:55:45 +0000557 /// \brief Whether the external AST source has provided a layout for this
558 /// record.
559 unsigned ExternalLayout : 1;
Douglas Gregor44ba7892012-01-28 00:53:29 +0000560
561 /// \brief Whether we need to infer alignment, even when we have an
562 /// externally-provided layout.
563 unsigned InferAlignment : 1;
Douglas Gregore9fc3772012-01-26 07:55:45 +0000564
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000565 /// Packed - Whether the record is packed or not.
Daniel Dunbar6da10982010-05-27 05:45:51 +0000566 unsigned Packed : 1;
567
568 unsigned IsUnion : 1;
569
570 unsigned IsMac68kAlign : 1;
Fariborz Jahanianbcb23a12011-04-26 23:52:16 +0000571
572 unsigned IsMsStruct : 1;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000573
Eli Friedman2782dac2013-06-26 20:50:34 +0000574 /// UnfilledBitsInLastUnit - If the last field laid out was a bitfield,
575 /// this contains the number of bits in the last unit that can be used for
576 /// an adjacent bitfield if necessary. The unit in question is usually
577 /// a byte, but larger units are used if IsMsStruct.
578 unsigned char UnfilledBitsInLastUnit;
579 /// LastBitfieldTypeSize - If IsMsStruct, represents the size of the type
580 /// of the previous field if it was a bitfield.
581 unsigned char LastBitfieldTypeSize;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000582
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000583 /// MaxFieldAlignment - The maximum allowed field alignment. This is set by
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000584 /// #pragma pack.
Ken Dyck02ced6f2011-02-17 01:49:42 +0000585 CharUnits MaxFieldAlignment;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000586
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000587 /// DataSize - The data size of the record being laid out.
588 uint64_t DataSize;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000589
Ken Dyckaf1c83f2011-02-16 01:52:01 +0000590 CharUnits NonVirtualSize;
Ken Dycka2d3dda2011-02-16 01:43:15 +0000591 CharUnits NonVirtualAlignment;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000592
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000593 /// PrimaryBase - the primary base class (if one exists) of the class
594 /// we're laying out.
595 const CXXRecordDecl *PrimaryBase;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000596
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000597 /// PrimaryBaseIsVirtual - Whether the primary base of the class we're laying
598 /// out is virtual.
599 bool PrimaryBaseIsVirtual;
600
John McCalle42a3362012-05-01 08:55:32 +0000601 /// HasOwnVFPtr - Whether the class provides its own vtable/vftbl
602 /// pointer, as opposed to inheriting one from a primary base class.
603 bool HasOwnVFPtr;
Eli Friedman43114f92011-10-21 22:49:56 +0000604
Anders Carlsson22f57202010-10-31 21:01:46 +0000605 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000606
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000607 /// Bases - base classes and their offsets in the record.
608 BaseOffsetsMapTy Bases;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000609
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000610 // VBases - virtual base classes and their offsets in the record.
John McCalle42a3362012-05-01 08:55:32 +0000611 ASTRecordLayout::VBaseOffsetsMapTy VBases;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000612
613 /// IndirectPrimaryBases - Virtual base classes, direct or indirect, that are
614 /// primary base classes for some other direct or indirect base class.
Anders Carlsson5adde292010-11-24 22:55:48 +0000615 CXXIndirectPrimaryBaseSet IndirectPrimaryBases;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000616
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000617 /// FirstNearlyEmptyVBase - The first nearly empty virtual base class in
618 /// inheritance graph order. Used for determining the primary base class.
619 const CXXRecordDecl *FirstNearlyEmptyVBase;
620
621 /// VisitedVirtualBases - A set of all the visited virtual bases, used to
622 /// avoid visiting virtual bases more than once.
623 llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000624
Douglas Gregore9fc3772012-01-26 07:55:45 +0000625 /// \brief Externally-provided size.
626 uint64_t ExternalSize;
627
628 /// \brief Externally-provided alignment.
629 uint64_t ExternalAlign;
630
631 /// \brief Externally-provided field offsets.
632 llvm::DenseMap<const FieldDecl *, uint64_t> ExternalFieldOffsets;
633
634 /// \brief Externally-provided direct, non-virtual base offsets.
635 llvm::DenseMap<const CXXRecordDecl *, CharUnits> ExternalBaseOffsets;
636
637 /// \brief Externally-provided virtual base offsets.
638 llvm::DenseMap<const CXXRecordDecl *, CharUnits> ExternalVirtualBaseOffsets;
639
John McCall0153cd32011-11-08 04:01:03 +0000640 RecordLayoutBuilder(const ASTContext &Context,
641 EmptySubobjectMap *EmptySubobjects)
Ken Dyck4731d5b2011-02-16 02:05:21 +0000642 : Context(Context), EmptySubobjects(EmptySubobjects), Size(0),
John McCall0153cd32011-11-08 04:01:03 +0000643 Alignment(CharUnits::One()), UnpackedAlignment(CharUnits::One()),
Douglas Gregor44ba7892012-01-28 00:53:29 +0000644 ExternalLayout(false), InferAlignment(false),
645 Packed(false), IsUnion(false), IsMac68kAlign(false), IsMsStruct(false),
Eli Friedman2782dac2013-06-26 20:50:34 +0000646 UnfilledBitsInLastUnit(0), LastBitfieldTypeSize(0),
647 MaxFieldAlignment(CharUnits::Zero()),
Ken Dyck02ced6f2011-02-17 01:49:42 +0000648 DataSize(0), NonVirtualSize(CharUnits::Zero()),
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000649 NonVirtualAlignment(CharUnits::One()),
Eli Friedman481673f2013-06-26 23:47:39 +0000650 PrimaryBase(0), PrimaryBaseIsVirtual(false),
John McCalle42a3362012-05-01 08:55:32 +0000651 HasOwnVFPtr(false),
Eli Friedman84d2d3a2011-09-27 19:12:27 +0000652 FirstNearlyEmptyVBase(0) { }
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000653
John McCall0153cd32011-11-08 04:01:03 +0000654 /// Reset this RecordLayoutBuilder to a fresh state, using the given
655 /// alignment as the initial alignment. This is used for the
656 /// correct layout of vb-table pointers in MSVC.
657 void resetWithTargetAlignment(CharUnits TargetAlignment) {
658 const ASTContext &Context = this->Context;
659 EmptySubobjectMap *EmptySubobjects = this->EmptySubobjects;
660 this->~RecordLayoutBuilder();
661 new (this) RecordLayoutBuilder(Context, EmptySubobjects);
662 Alignment = UnpackedAlignment = TargetAlignment;
663 }
664
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000665 void Layout(const RecordDecl *D);
Anders Carlssonc28a6c92010-05-26 15:10:00 +0000666 void Layout(const CXXRecordDecl *D);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000667 void Layout(const ObjCInterfaceDecl *D);
668
669 void LayoutFields(const RecordDecl *D);
670 void LayoutField(const FieldDecl *D);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000671 void LayoutWideBitField(uint64_t FieldSize, uint64_t TypeSize,
672 bool FieldPacked, const FieldDecl *D);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000673 void LayoutBitField(const FieldDecl *D);
John McCall0153cd32011-11-08 04:01:03 +0000674
John McCall359b8852013-01-25 22:30:49 +0000675 TargetCXXABI getCXXABI() const {
676 return Context.getTargetInfo().getCXXABI();
677 }
678
Anders Carlssone3c24c72010-05-29 17:35:14 +0000679 /// BaseSubobjectInfoAllocator - Allocator for BaseSubobjectInfo objects.
680 llvm::SpecificBumpPtrAllocator<BaseSubobjectInfo> BaseSubobjectInfoAllocator;
681
682 typedef llvm::DenseMap<const CXXRecordDecl *, BaseSubobjectInfo *>
683 BaseSubobjectInfoMapTy;
684
685 /// VirtualBaseInfo - Map from all the (direct or indirect) virtual bases
686 /// of the class we're laying out to their base subobject info.
687 BaseSubobjectInfoMapTy VirtualBaseInfo;
688
689 /// NonVirtualBaseInfo - Map from all the direct non-virtual bases of the
690 /// class we're laying out to their base subobject info.
691 BaseSubobjectInfoMapTy NonVirtualBaseInfo;
692
693 /// ComputeBaseSubobjectInfo - Compute the base subobject information for the
694 /// bases of the given class.
695 void ComputeBaseSubobjectInfo(const CXXRecordDecl *RD);
696
697 /// ComputeBaseSubobjectInfo - Compute the base subobject information for a
698 /// single class and all of its base classes.
699 BaseSubobjectInfo *ComputeBaseSubobjectInfo(const CXXRecordDecl *RD,
700 bool IsVirtual,
701 BaseSubobjectInfo *Derived);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000702
703 /// DeterminePrimaryBase - Determine the primary base of the given class.
704 void DeterminePrimaryBase(const CXXRecordDecl *RD);
705
706 void SelectPrimaryVBase(const CXXRecordDecl *RD);
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000707
Eli Friedman43114f92011-10-21 22:49:56 +0000708 void EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign);
Charles Davisc2c576a2010-08-19 00:55:19 +0000709
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000710 /// LayoutNonVirtualBases - Determines the primary base class (if any) and
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000711 /// lays it out. Will then proceed to lay out all non-virtual base clasess.
712 void LayoutNonVirtualBases(const CXXRecordDecl *RD);
713
714 /// LayoutNonVirtualBase - Lays out a single non-virtual base.
Anders Carlssonbb0e6782010-05-29 17:42:25 +0000715 void LayoutNonVirtualBase(const BaseSubobjectInfo *Base);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000716
Anders Carlssona2f8e412010-10-31 22:20:42 +0000717 void AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
718 CharUnits Offset);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000719
720 /// LayoutVirtualBases - Lays out all the virtual bases.
721 void LayoutVirtualBases(const CXXRecordDecl *RD,
722 const CXXRecordDecl *MostDerivedClass);
723
724 /// LayoutVirtualBase - Lays out a single virtual base.
Warren Hunt55d8e822013-10-23 23:53:07 +0000725 void LayoutVirtualBase(const BaseSubobjectInfo *Base);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000726
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000727 /// LayoutBase - Will lay out a base and return the offset where it was
Anders Carlssona2f8e412010-10-31 22:20:42 +0000728 /// placed, in chars.
729 CharUnits LayoutBase(const BaseSubobjectInfo *Base);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000730
Anders Carlssonc28a6c92010-05-26 15:10:00 +0000731 /// InitializeLayout - Initialize record layout for the given record decl.
Daniel Dunbar6da10982010-05-27 05:45:51 +0000732 void InitializeLayout(const Decl *D);
Anders Carlssonc28a6c92010-05-26 15:10:00 +0000733
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000734 /// FinishLayout - Finalize record layout. Adjust record size based on the
735 /// alignment.
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000736 void FinishLayout(const NamedDecl *D);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000737
Ken Dyck85ef0432011-02-19 18:58:07 +0000738 void UpdateAlignment(CharUnits NewAlignment, CharUnits UnpackedNewAlignment);
739 void UpdateAlignment(CharUnits NewAlignment) {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000740 UpdateAlignment(NewAlignment, NewAlignment);
741 }
742
Douglas Gregor44ba7892012-01-28 00:53:29 +0000743 /// \brief Retrieve the externally-supplied field offset for the given
744 /// field.
745 ///
746 /// \param Field The field whose offset is being queried.
747 /// \param ComputedOffset The offset that we've computed for this field.
748 uint64_t updateExternalFieldOffset(const FieldDecl *Field,
749 uint64_t ComputedOffset);
750
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000751 void CheckFieldPadding(uint64_t Offset, uint64_t UnpaddedOffset,
752 uint64_t UnpackedOffset, unsigned UnpackedAlign,
753 bool isPacked, const FieldDecl *D);
754
755 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000756
Ken Dyckecfc7552011-02-24 01:13:28 +0000757 CharUnits getSize() const {
Ken Dyck3c215f22011-02-24 01:33:05 +0000758 assert(Size % Context.getCharWidth() == 0);
Ken Dyckecfc7552011-02-24 01:13:28 +0000759 return Context.toCharUnitsFromBits(Size);
760 }
761 uint64_t getSizeInBits() const { return Size; }
762
763 void setSize(CharUnits NewSize) { Size = Context.toBits(NewSize); }
764 void setSize(uint64_t NewSize) { Size = NewSize; }
765
Eli Friedman84d2d3a2011-09-27 19:12:27 +0000766 CharUnits getAligment() const { return Alignment; }
767
Ken Dyckecfc7552011-02-24 01:13:28 +0000768 CharUnits getDataSize() const {
Ken Dyck3c215f22011-02-24 01:33:05 +0000769 assert(DataSize % Context.getCharWidth() == 0);
Ken Dyckecfc7552011-02-24 01:13:28 +0000770 return Context.toCharUnitsFromBits(DataSize);
771 }
772 uint64_t getDataSizeInBits() const { return DataSize; }
773
774 void setDataSize(CharUnits NewSize) { DataSize = Context.toBits(NewSize); }
775 void setDataSize(uint64_t NewSize) { DataSize = NewSize; }
776
Dmitri Gribenkoa664e5b2012-09-15 20:20:27 +0000777 RecordLayoutBuilder(const RecordLayoutBuilder &) LLVM_DELETED_FUNCTION;
778 void operator=(const RecordLayoutBuilder &) LLVM_DELETED_FUNCTION;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000779};
Benjamin Kramerc7656cd2010-05-26 09:58:31 +0000780} // end anonymous namespace
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000781
Anders Carlsson81430692009-09-22 03:02:06 +0000782void
Anders Carlssonc2226202010-05-26 05:58:59 +0000783RecordLayoutBuilder::SelectPrimaryVBase(const CXXRecordDecl *RD) {
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000784 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000785 E = RD->bases_end(); I != E; ++I) {
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000786 assert(!I->getType()->isDependentType() &&
Sebastian Redl1054fae2009-10-25 17:03:50 +0000787 "Cannot layout class with dependent bases.");
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000788
Mike Stump11289f42009-09-09 15:08:12 +0000789 const CXXRecordDecl *Base =
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000790 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000791
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000792 // Check if this is a nearly empty virtual base.
Anders Carlsson60a62632010-11-25 01:51:53 +0000793 if (I->isVirtual() && Context.isNearlyEmpty(Base)) {
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000794 // If it's not an indirect primary base, then we've found our primary
795 // base.
Anders Carlsson81430692009-09-22 03:02:06 +0000796 if (!IndirectPrimaryBases.count(Base)) {
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000797 PrimaryBase = Base;
798 PrimaryBaseIsVirtual = true;
Mike Stump6f3793b2009-08-12 21:50:08 +0000799 return;
800 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000801
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000802 // Is this the first nearly empty virtual base?
803 if (!FirstNearlyEmptyVBase)
804 FirstNearlyEmptyVBase = Base;
Mike Stump6f3793b2009-08-12 21:50:08 +0000805 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000806
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000807 SelectPrimaryVBase(Base);
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000808 if (PrimaryBase)
Zhongxing Xuec345b72010-02-15 04:28:35 +0000809 return;
Mike Stump6f3793b2009-08-12 21:50:08 +0000810 }
811}
812
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000813/// DeterminePrimaryBase - Determine the primary base of the given class.
Anders Carlssonc2226202010-05-26 05:58:59 +0000814void RecordLayoutBuilder::DeterminePrimaryBase(const CXXRecordDecl *RD) {
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000815 // If the class isn't dynamic, it won't have a primary base.
816 if (!RD->isDynamicClass())
817 return;
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000818
Anders Carlsson81430692009-09-22 03:02:06 +0000819 // Compute all the primary virtual bases for all of our direct and
Mike Stump590a7c72009-08-13 23:26:06 +0000820 // indirect bases, and record all their primary virtual base classes.
Anders Carlsson5adde292010-11-24 22:55:48 +0000821 RD->getIndirectPrimaryBases(IndirectPrimaryBases);
Mike Stump590a7c72009-08-13 23:26:06 +0000822
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000823 // If the record has a dynamic base class, attempt to choose a primary base
824 // class. It is the first (in direct base class order) non-virtual dynamic
Anders Carlsson81430692009-09-22 03:02:06 +0000825 // base class, if one exists.
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000826 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000827 e = RD->bases_end(); i != e; ++i) {
Anders Carlsson03ff3792009-11-27 22:05:05 +0000828 // Ignore virtual bases.
829 if (i->isVirtual())
830 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000831
Anders Carlsson03ff3792009-11-27 22:05:05 +0000832 const CXXRecordDecl *Base =
833 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
834
Warren Hunt55d8e822013-10-23 23:53:07 +0000835 if (Base->isDynamicClass()) {
Anders Carlsson03ff3792009-11-27 22:05:05 +0000836 // We found it.
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000837 PrimaryBase = Base;
838 PrimaryBaseIsVirtual = false;
Anders Carlsson03ff3792009-11-27 22:05:05 +0000839 return;
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000840 }
841 }
842
Eli Friedman5e9534b2011-10-18 00:55:28 +0000843 // Under the Itanium ABI, if there is no non-virtual primary base class,
844 // try to compute the primary virtual base. The primary virtual base is
845 // the first nearly empty virtual base that is not an indirect primary
846 // virtual base class, if one exists.
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000847 if (RD->getNumVBases() != 0) {
848 SelectPrimaryVBase(RD);
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000849 if (PrimaryBase)
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000850 return;
851 }
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000852
Eli Friedman5e9534b2011-10-18 00:55:28 +0000853 // Otherwise, it is the first indirect primary base class, if one exists.
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000854 if (FirstNearlyEmptyVBase) {
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000855 PrimaryBase = FirstNearlyEmptyVBase;
856 PrimaryBaseIsVirtual = true;
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000857 return;
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000858 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000859
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000860 assert(!PrimaryBase && "Should not get here with a primary base!");
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000861}
862
Anders Carlssone3c24c72010-05-29 17:35:14 +0000863BaseSubobjectInfo *
864RecordLayoutBuilder::ComputeBaseSubobjectInfo(const CXXRecordDecl *RD,
865 bool IsVirtual,
866 BaseSubobjectInfo *Derived) {
867 BaseSubobjectInfo *Info;
868
869 if (IsVirtual) {
870 // Check if we already have info about this virtual base.
871 BaseSubobjectInfo *&InfoSlot = VirtualBaseInfo[RD];
872 if (InfoSlot) {
873 assert(InfoSlot->Class == RD && "Wrong class for virtual base info!");
874 return InfoSlot;
875 }
876
877 // We don't, create it.
878 InfoSlot = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
879 Info = InfoSlot;
880 } else {
881 Info = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
882 }
883
884 Info->Class = RD;
885 Info->IsVirtual = IsVirtual;
886 Info->Derived = 0;
887 Info->PrimaryVirtualBaseInfo = 0;
888
889 const CXXRecordDecl *PrimaryVirtualBase = 0;
890 BaseSubobjectInfo *PrimaryVirtualBaseInfo = 0;
891
892 // Check if this base has a primary virtual base.
893 if (RD->getNumVBases()) {
894 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Anders Carlsson7f95cd12010-11-24 23:12:57 +0000895 if (Layout.isPrimaryBaseVirtual()) {
Anders Carlssone3c24c72010-05-29 17:35:14 +0000896 // This base does have a primary virtual base.
897 PrimaryVirtualBase = Layout.getPrimaryBase();
898 assert(PrimaryVirtualBase && "Didn't have a primary virtual base!");
899
900 // Now check if we have base subobject info about this primary base.
901 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
902
903 if (PrimaryVirtualBaseInfo) {
904 if (PrimaryVirtualBaseInfo->Derived) {
905 // We did have info about this primary base, and it turns out that it
906 // has already been claimed as a primary virtual base for another
907 // base.
908 PrimaryVirtualBase = 0;
909 } else {
910 // We can claim this base as our primary base.
911 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
912 PrimaryVirtualBaseInfo->Derived = Info;
913 }
914 }
915 }
916 }
917
918 // Now go through all direct bases.
919 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
920 E = RD->bases_end(); I != E; ++I) {
921 bool IsVirtual = I->isVirtual();
922
923 const CXXRecordDecl *BaseDecl =
924 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
925
926 Info->Bases.push_back(ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, Info));
927 }
928
929 if (PrimaryVirtualBase && !PrimaryVirtualBaseInfo) {
930 // Traversing the bases must have created the base info for our primary
931 // virtual base.
932 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
933 assert(PrimaryVirtualBaseInfo &&
934 "Did not create a primary virtual base!");
935
936 // Claim the primary virtual base as our primary virtual base.
937 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
938 PrimaryVirtualBaseInfo->Derived = Info;
939 }
940
941 return Info;
942}
943
944void RecordLayoutBuilder::ComputeBaseSubobjectInfo(const CXXRecordDecl *RD) {
945 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
946 E = RD->bases_end(); I != E; ++I) {
947 bool IsVirtual = I->isVirtual();
948
949 const CXXRecordDecl *BaseDecl =
950 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
951
952 // Compute the base subobject info for this base.
953 BaseSubobjectInfo *Info = ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, 0);
954
955 if (IsVirtual) {
956 // ComputeBaseInfo has already added this base for us.
957 assert(VirtualBaseInfo.count(BaseDecl) &&
958 "Did not add virtual base!");
959 } else {
960 // Add the base info to the map of non-virtual bases.
961 assert(!NonVirtualBaseInfo.count(BaseDecl) &&
962 "Non-virtual base already exists!");
963 NonVirtualBaseInfo.insert(std::make_pair(BaseDecl, Info));
964 }
965 }
966}
967
Anders Carlsson09ffa322010-03-10 22:21:28 +0000968void
Eli Friedman43114f92011-10-21 22:49:56 +0000969RecordLayoutBuilder::EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign) {
Eli Friedman5e9534b2011-10-18 00:55:28 +0000970 CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
971
972 // The maximum field alignment overrides base align.
973 if (!MaxFieldAlignment.isZero()) {
974 BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
975 UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
976 }
977
978 // Round up the current record size to pointer alignment.
Eli Friedman43114f92011-10-21 22:49:56 +0000979 setSize(getSize().RoundUpToAlignment(BaseAlign));
980 setDataSize(getSize());
Eli Friedman5e9534b2011-10-18 00:55:28 +0000981
982 // Update the alignment.
983 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
984}
985
986void
Anders Carlssonc2226202010-05-26 05:58:59 +0000987RecordLayoutBuilder::LayoutNonVirtualBases(const CXXRecordDecl *RD) {
Anders Carlssone3c24c72010-05-29 17:35:14 +0000988 // Then, determine the primary base class.
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000989 DeterminePrimaryBase(RD);
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000990
Anders Carlssone3c24c72010-05-29 17:35:14 +0000991 // Compute base subobject info.
992 ComputeBaseSubobjectInfo(RD);
993
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000994 // If we have a primary base class, lay it out.
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000995 if (PrimaryBase) {
996 if (PrimaryBaseIsVirtual) {
Anders Carlssone3c24c72010-05-29 17:35:14 +0000997 // If the primary virtual base was a primary virtual base of some other
998 // base class we'll have to steal it.
999 BaseSubobjectInfo *PrimaryBaseInfo = VirtualBaseInfo.lookup(PrimaryBase);
1000 PrimaryBaseInfo->Derived = 0;
1001
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001002 // We have a virtual primary base, insert it as an indirect primary base.
Anders Carlssond20e7cd2010-05-26 05:20:58 +00001003 IndirectPrimaryBases.insert(PrimaryBase);
Anders Carlssonfe900962010-03-11 05:42:17 +00001004
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001005 assert(!VisitedVirtualBases.count(PrimaryBase) &&
Anders Carlssond20e7cd2010-05-26 05:20:58 +00001006 "vbase already visited!");
1007 VisitedVirtualBases.insert(PrimaryBase);
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001008
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001009 LayoutVirtualBase(PrimaryBaseInfo);
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001010 } else {
1011 BaseSubobjectInfo *PrimaryBaseInfo =
1012 NonVirtualBaseInfo.lookup(PrimaryBase);
1013 assert(PrimaryBaseInfo &&
1014 "Did not find base info for non-virtual primary base!");
1015
1016 LayoutNonVirtualBase(PrimaryBaseInfo);
1017 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001018
John McCall0153cd32011-11-08 04:01:03 +00001019 // If this class needs a vtable/vf-table and didn't get one from a
1020 // primary base, add it in now.
Warren Hunt55d8e822013-10-23 23:53:07 +00001021 } else if (RD->isDynamicClass()) {
Eli Friedman5e9534b2011-10-18 00:55:28 +00001022 assert(DataSize == 0 && "Vtable pointer must be at offset zero!");
Eli Friedman5e9534b2011-10-18 00:55:28 +00001023 CharUnits PtrWidth =
1024 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Eli Friedman43114f92011-10-21 22:49:56 +00001025 CharUnits PtrAlign =
1026 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0));
1027 EnsureVTablePointerAlignment(PtrAlign);
John McCalle42a3362012-05-01 08:55:32 +00001028 HasOwnVFPtr = true;
Eli Friedman5e9534b2011-10-18 00:55:28 +00001029 setSize(getSize() + PtrWidth);
1030 setDataSize(getSize());
1031 }
1032
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001033 // Now lay out the non-virtual bases.
1034 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001035 E = RD->bases_end(); I != E; ++I) {
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001036
Benjamin Kramer273670a2013-10-25 07:40:50 +00001037 // Ignore virtual bases.
1038 if (I->isVirtual())
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001039 continue;
1040
Reid Klecknere7106c92013-12-18 23:17:05 +00001041 const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001042
John McCall0153cd32011-11-08 04:01:03 +00001043 // Skip the primary base, because we've already laid it out. The
1044 // !PrimaryBaseIsVirtual check is required because we might have a
1045 // non-virtual base of the same type as a primary virtual base.
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001046 if (BaseDecl == PrimaryBase && !PrimaryBaseIsVirtual)
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001047 continue;
1048
1049 // Lay out the base.
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001050 BaseSubobjectInfo *BaseInfo = NonVirtualBaseInfo.lookup(BaseDecl);
1051 assert(BaseInfo && "Did not find base info for non-virtual base!");
1052
1053 LayoutNonVirtualBase(BaseInfo);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001054 }
1055}
1056
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001057void RecordLayoutBuilder::LayoutNonVirtualBase(const BaseSubobjectInfo *Base) {
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001058 // Layout the base.
Anders Carlssona2f8e412010-10-31 22:20:42 +00001059 CharUnits Offset = LayoutBase(Base);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001060
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001061 // Add its base class offset.
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001062 assert(!Bases.count(Base->Class) && "base offset already exists!");
Anders Carlssona2f8e412010-10-31 22:20:42 +00001063 Bases.insert(std::make_pair(Base->Class, Offset));
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001064
1065 AddPrimaryVirtualBaseOffsets(Base, Offset);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001066}
Mike Stump2b84dd32009-11-05 04:02:15 +00001067
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001068void
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001069RecordLayoutBuilder::AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
Anders Carlssona2f8e412010-10-31 22:20:42 +00001070 CharUnits Offset) {
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001071 // This base isn't interesting, it has no virtual bases.
1072 if (!Info->Class->getNumVBases())
1073 return;
1074
1075 // First, check if we have a virtual primary base to add offsets for.
1076 if (Info->PrimaryVirtualBaseInfo) {
1077 assert(Info->PrimaryVirtualBaseInfo->IsVirtual &&
1078 "Primary virtual base is not virtual!");
1079 if (Info->PrimaryVirtualBaseInfo->Derived == Info) {
1080 // Add the offset.
1081 assert(!VBases.count(Info->PrimaryVirtualBaseInfo->Class) &&
1082 "primary vbase offset already exists!");
1083 VBases.insert(std::make_pair(Info->PrimaryVirtualBaseInfo->Class,
John McCalle42a3362012-05-01 08:55:32 +00001084 ASTRecordLayout::VBaseInfo(Offset, false)));
Anders Carlssonea7b1822010-04-15 16:12:58 +00001085
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001086 // Traverse the primary virtual base.
1087 AddPrimaryVirtualBaseOffsets(Info->PrimaryVirtualBaseInfo, Offset);
1088 }
Anders Carlssonea7b1822010-04-15 16:12:58 +00001089 }
1090
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001091 // Now go through all direct non-virtual bases.
1092 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
1093 for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) {
1094 const BaseSubobjectInfo *Base = Info->Bases[I];
1095 if (Base->IsVirtual)
Anders Carlssonea7b1822010-04-15 16:12:58 +00001096 continue;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001097
Anders Carlsson0a14ee92010-11-01 00:21:58 +00001098 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001099 AddPrimaryVirtualBaseOffsets(Base, BaseOffset);
Anders Carlssonea7b1822010-04-15 16:12:58 +00001100 }
1101}
1102
1103void
Anders Carlssonc2226202010-05-26 05:58:59 +00001104RecordLayoutBuilder::LayoutVirtualBases(const CXXRecordDecl *RD,
Anders Carlssonea7b1822010-04-15 16:12:58 +00001105 const CXXRecordDecl *MostDerivedClass) {
Anders Carlssonde710c92010-03-11 04:33:54 +00001106 const CXXRecordDecl *PrimaryBase;
Anders Carlsson291279e2010-04-10 18:42:27 +00001107 bool PrimaryBaseIsVirtual;
Anders Carlssonfe900962010-03-11 05:42:17 +00001108
Anders Carlsson291279e2010-04-10 18:42:27 +00001109 if (MostDerivedClass == RD) {
Anders Carlssond20e7cd2010-05-26 05:20:58 +00001110 PrimaryBase = this->PrimaryBase;
1111 PrimaryBaseIsVirtual = this->PrimaryBaseIsVirtual;
Anders Carlsson291279e2010-04-10 18:42:27 +00001112 } else {
Anders Carlsson5efc56e2010-04-16 15:07:51 +00001113 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Anders Carlssonde710c92010-03-11 04:33:54 +00001114 PrimaryBase = Layout.getPrimaryBase();
Anders Carlsson7f95cd12010-11-24 23:12:57 +00001115 PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
Anders Carlsson291279e2010-04-10 18:42:27 +00001116 }
1117
Anders Carlssonf7b7a1e2010-03-11 04:24:02 +00001118 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1119 E = RD->bases_end(); I != E; ++I) {
1120 assert(!I->getType()->isDependentType() &&
Sebastian Redl1054fae2009-10-25 17:03:50 +00001121 "Cannot layout class with dependent bases.");
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001122
Reid Klecknere7106c92013-12-18 23:17:05 +00001123 const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
Anders Carlssonf7b7a1e2010-03-11 04:24:02 +00001124
1125 if (I->isVirtual()) {
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001126 if (PrimaryBase != BaseDecl || !PrimaryBaseIsVirtual) {
1127 bool IndirectPrimaryBase = IndirectPrimaryBases.count(BaseDecl);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001128
Anders Carlsson291279e2010-04-10 18:42:27 +00001129 // Only lay out the virtual base if it's not an indirect primary base.
1130 if (!IndirectPrimaryBase) {
1131 // Only visit virtual bases once.
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001132 if (!VisitedVirtualBases.insert(BaseDecl))
Anders Carlsson291279e2010-04-10 18:42:27 +00001133 continue;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001134
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001135 const BaseSubobjectInfo *BaseInfo = VirtualBaseInfo.lookup(BaseDecl);
1136 assert(BaseInfo && "Did not find virtual base info!");
1137 LayoutVirtualBase(BaseInfo);
Anders Carlsson6a848892010-03-11 04:10:39 +00001138 }
Mike Stump2b84dd32009-11-05 04:02:15 +00001139 }
Mike Stumpc2f591b2009-08-13 22:53:07 +00001140 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001141
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001142 if (!BaseDecl->getNumVBases()) {
Anders Carlssonf7b7a1e2010-03-11 04:24:02 +00001143 // This base isn't interesting since it doesn't have any virtual bases.
1144 continue;
Mike Stump996576f32009-08-16 19:04:13 +00001145 }
Anders Carlssonf7b7a1e2010-03-11 04:24:02 +00001146
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001147 LayoutVirtualBases(BaseDecl, MostDerivedClass);
Mike Stump6b2556f2009-08-06 13:41:24 +00001148 }
1149}
1150
Warren Hunt55d8e822013-10-23 23:53:07 +00001151void RecordLayoutBuilder::LayoutVirtualBase(const BaseSubobjectInfo *Base) {
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001152 assert(!Base->Derived && "Trying to lay out a primary virtual base!");
1153
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001154 // Layout the base.
Anders Carlssona2f8e412010-10-31 22:20:42 +00001155 CharUnits Offset = LayoutBase(Base);
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001156
1157 // Add its base class offset.
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001158 assert(!VBases.count(Base->Class) && "vbase offset already exists!");
John McCalle42a3362012-05-01 08:55:32 +00001159 VBases.insert(std::make_pair(Base->Class,
Warren Hunt55d8e822013-10-23 23:53:07 +00001160 ASTRecordLayout::VBaseInfo(Offset, false)));
John McCalle42a3362012-05-01 08:55:32 +00001161
Warren Hunt55d8e822013-10-23 23:53:07 +00001162 AddPrimaryVirtualBaseOffsets(Base, Offset);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001163}
1164
Anders Carlssona2f8e412010-10-31 22:20:42 +00001165CharUnits RecordLayoutBuilder::LayoutBase(const BaseSubobjectInfo *Base) {
Anders Carlssond7f3fcf2010-05-29 20:47:33 +00001166 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base->Class);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001167
Douglas Gregore9fc3772012-01-26 07:55:45 +00001168
1169 CharUnits Offset;
1170
1171 // Query the external layout to see if it provides an offset.
1172 bool HasExternalLayout = false;
1173 if (ExternalLayout) {
1174 llvm::DenseMap<const CXXRecordDecl *, CharUnits>::iterator Known;
1175 if (Base->IsVirtual) {
1176 Known = ExternalVirtualBaseOffsets.find(Base->Class);
1177 if (Known != ExternalVirtualBaseOffsets.end()) {
1178 Offset = Known->second;
1179 HasExternalLayout = true;
1180 }
1181 } else {
1182 Known = ExternalBaseOffsets.find(Base->Class);
1183 if (Known != ExternalBaseOffsets.end()) {
1184 Offset = Known->second;
1185 HasExternalLayout = true;
1186 }
1187 }
1188 }
1189
Warren Huntd640d7d2014-01-09 00:30:56 +00001190 CharUnits UnpackedBaseAlign = Layout.getNonVirtualAlignment();
Eli Friedman69d27d22013-07-16 00:21:28 +00001191 CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
1192
Anders Carlsson09ffa322010-03-10 22:21:28 +00001193 // If we have an empty base class, try to place it at offset 0.
Anders Carlssond7f3fcf2010-05-29 20:47:33 +00001194 if (Base->Class->isEmpty() &&
Douglas Gregore9fc3772012-01-26 07:55:45 +00001195 (!HasExternalLayout || Offset == CharUnits::Zero()) &&
Anders Carlsson28466ab2010-10-31 22:13:23 +00001196 EmptySubobjects->CanPlaceBaseAtOffset(Base, CharUnits::Zero())) {
Ken Dyck1b4420e2011-02-28 02:01:38 +00001197 setSize(std::max(getSize(), Layout.getSize()));
Eli Friedman69d27d22013-07-16 00:21:28 +00001198 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001199
Anders Carlssona2f8e412010-10-31 22:20:42 +00001200 return CharUnits::Zero();
Anders Carlsson09ffa322010-03-10 22:21:28 +00001201 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001202
Argyrios Kyrtzidis8b542742010-12-09 00:35:20 +00001203 // The maximum field alignment overrides base align.
Ken Dyck02ced6f2011-02-17 01:49:42 +00001204 if (!MaxFieldAlignment.isZero()) {
Ken Dyck85ef0432011-02-19 18:58:07 +00001205 BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
1206 UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
Argyrios Kyrtzidis8b542742010-12-09 00:35:20 +00001207 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001208
Douglas Gregore9fc3772012-01-26 07:55:45 +00001209 if (!HasExternalLayout) {
1210 // Round up the current record size to the base's alignment boundary.
1211 Offset = getDataSize().RoundUpToAlignment(BaseAlign);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001212
Douglas Gregore9fc3772012-01-26 07:55:45 +00001213 // Try to place the base.
1214 while (!EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset))
1215 Offset += BaseAlign;
1216 } else {
1217 bool Allowed = EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset);
1218 (void)Allowed;
1219 assert(Allowed && "Base subobject externally placed at overlapping offset");
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001220
1221 if (InferAlignment && Offset < getDataSize().RoundUpToAlignment(BaseAlign)){
1222 // The externally-supplied base offset is before the base offset we
1223 // computed. Assume that the structure is packed.
1224 Alignment = CharUnits::One();
1225 InferAlignment = false;
1226 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00001227 }
1228
Anders Carlssond7f3fcf2010-05-29 20:47:33 +00001229 if (!Base->Class->isEmpty()) {
Anders Carlsson09ffa322010-03-10 22:21:28 +00001230 // Update the data size.
Ken Dyck1b4420e2011-02-28 02:01:38 +00001231 setDataSize(Offset + Layout.getNonVirtualSize());
Anders Carlsson09ffa322010-03-10 22:21:28 +00001232
Ken Dyck1b4420e2011-02-28 02:01:38 +00001233 setSize(std::max(getSize(), getDataSize()));
Anders Carlsson09ffa322010-03-10 22:21:28 +00001234 } else
Ken Dyck1b4420e2011-02-28 02:01:38 +00001235 setSize(std::max(getSize(), Offset + Layout.getSize()));
Anders Carlsson09ffa322010-03-10 22:21:28 +00001236
1237 // Remember max struct/class alignment.
Argyrios Kyrtzidis8b542742010-12-09 00:35:20 +00001238 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001239
Ken Dyck1b4420e2011-02-28 02:01:38 +00001240 return Offset;
Anders Carlsson09ffa322010-03-10 22:21:28 +00001241}
1242
Daniel Dunbar6da10982010-05-27 05:45:51 +00001243void RecordLayoutBuilder::InitializeLayout(const Decl *D) {
Eli Friedman9ee2d0472012-10-12 23:29:20 +00001244 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Daniel Dunbar6da10982010-05-27 05:45:51 +00001245 IsUnion = RD->isUnion();
Eli Friedman9ee2d0472012-10-12 23:29:20 +00001246 IsMsStruct = RD->isMsStruct(Context);
1247 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001248
Eli Friedman9ee2d0472012-10-12 23:29:20 +00001249 Packed = D->hasAttr<PackedAttr>();
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001250
Daniel Dunbar096ed292011-10-05 21:04:55 +00001251 // Honor the default struct packing maximum alignment flag.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001252 if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct) {
Daniel Dunbar096ed292011-10-05 21:04:55 +00001253 MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
1254 }
1255
Daniel Dunbar6da10982010-05-27 05:45:51 +00001256 // mac68k alignment supersedes maximum field alignment and attribute aligned,
1257 // and forces all structures to have 2-byte alignment. The IBM docs on it
1258 // allude to additional (more complicated) semantics, especially with regard
1259 // to bit-fields, but gcc appears not to follow that.
1260 if (D->hasAttr<AlignMac68kAttr>()) {
1261 IsMac68kAlign = true;
Ken Dyck02ced6f2011-02-17 01:49:42 +00001262 MaxFieldAlignment = CharUnits::fromQuantity(2);
Ken Dyck4731d5b2011-02-16 02:05:21 +00001263 Alignment = CharUnits::fromQuantity(2);
Daniel Dunbar6da10982010-05-27 05:45:51 +00001264 } else {
1265 if (const MaxFieldAlignmentAttr *MFAA = D->getAttr<MaxFieldAlignmentAttr>())
Ken Dyck02ced6f2011-02-17 01:49:42 +00001266 MaxFieldAlignment = Context.toCharUnitsFromBits(MFAA->getAlignment());
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001267
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001268 if (unsigned MaxAlign = D->getMaxAlignment())
Ken Dyck85ef0432011-02-19 18:58:07 +00001269 UpdateAlignment(Context.toCharUnitsFromBits(MaxAlign));
Daniel Dunbar6da10982010-05-27 05:45:51 +00001270 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00001271
1272 // If there is an external AST source, ask it for the various offsets.
1273 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
1274 if (ExternalASTSource *External = Context.getExternalSource()) {
1275 ExternalLayout = External->layoutRecordType(RD,
1276 ExternalSize,
1277 ExternalAlign,
1278 ExternalFieldOffsets,
1279 ExternalBaseOffsets,
1280 ExternalVirtualBaseOffsets);
1281
1282 // Update based on external alignment.
1283 if (ExternalLayout) {
Douglas Gregor44ba7892012-01-28 00:53:29 +00001284 if (ExternalAlign > 0) {
1285 Alignment = Context.toCharUnitsFromBits(ExternalAlign);
Douglas Gregor44ba7892012-01-28 00:53:29 +00001286 } else {
1287 // The external source didn't have alignment information; infer it.
1288 InferAlignment = true;
1289 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00001290 }
1291 }
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001292}
Anders Carlsson6d9f6f32009-07-19 00:18:47 +00001293
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001294void RecordLayoutBuilder::Layout(const RecordDecl *D) {
1295 InitializeLayout(D);
Anders Carlsson118ce162009-07-18 21:48:39 +00001296 LayoutFields(D);
Mike Stump11289f42009-09-09 15:08:12 +00001297
Anders Carlsson79474332009-07-18 20:20:21 +00001298 // Finally, round the size of the total struct up to the alignment of the
1299 // struct itself.
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001300 FinishLayout(D);
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001301}
1302
1303void RecordLayoutBuilder::Layout(const CXXRecordDecl *RD) {
1304 InitializeLayout(RD);
1305
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001306 // Lay out the vtable and the non-virtual bases.
1307 LayoutNonVirtualBases(RD);
1308
1309 LayoutFields(RD);
1310
Ken Dycke7380752011-03-10 01:53:59 +00001311 NonVirtualSize = Context.toCharUnitsFromBits(
1312 llvm::RoundUpToAlignment(getSizeInBits(),
Douglas Gregore8bbc122011-09-02 00:18:52 +00001313 Context.getTargetInfo().getCharAlign()));
Ken Dyck4731d5b2011-02-16 02:05:21 +00001314 NonVirtualAlignment = Alignment;
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001315
Warren Hunt55d8e822013-10-23 23:53:07 +00001316 // Lay out the virtual bases and add the primary virtual base offsets.
1317 LayoutVirtualBases(RD, RD);
John McCall0153cd32011-11-08 04:01:03 +00001318
1319 // Finally, round the size of the total struct up to the alignment
Eli Friedman83a12582011-12-01 00:37:01 +00001320 // of the struct itself.
1321 FinishLayout(RD);
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001322
Anders Carlsson5b441d72010-04-10 21:24:48 +00001323#ifndef NDEBUG
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001324 // Check that we have base offsets for all bases.
1325 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1326 E = RD->bases_end(); I != E; ++I) {
1327 if (I->isVirtual())
1328 continue;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001329
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001330 const CXXRecordDecl *BaseDecl =
1331 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1332
1333 assert(Bases.count(BaseDecl) && "Did not find base offset!");
1334 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001335
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001336 // And all virtual bases.
1337 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
1338 E = RD->vbases_end(); I != E; ++I) {
1339 const CXXRecordDecl *BaseDecl =
1340 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001341
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001342 assert(VBases.count(BaseDecl) && "Did not find base offset!");
Anders Carlsson5b441d72010-04-10 21:24:48 +00001343 }
1344#endif
Anders Carlsson79474332009-07-18 20:20:21 +00001345}
1346
Anders Carlssonc2226202010-05-26 05:58:59 +00001347void RecordLayoutBuilder::Layout(const ObjCInterfaceDecl *D) {
Anders Carlsson4f516282009-07-18 20:50:59 +00001348 if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
Anders Carlsson5efc56e2010-04-16 15:07:51 +00001349 const ASTRecordLayout &SL = Context.getASTObjCInterfaceLayout(SD);
Anders Carlsson4f516282009-07-18 20:50:59 +00001350
Ken Dyck85ef0432011-02-19 18:58:07 +00001351 UpdateAlignment(SL.getAlignment());
Mike Stump11289f42009-09-09 15:08:12 +00001352
Anders Carlsson4f516282009-07-18 20:50:59 +00001353 // We start laying out ivars not at the end of the superclass
1354 // structure, but at the next byte following the last field.
Ken Dyckecfc7552011-02-24 01:13:28 +00001355 setSize(SL.getDataSize());
Ken Dyck1b4420e2011-02-28 02:01:38 +00001356 setDataSize(getSize());
Anders Carlsson4f516282009-07-18 20:50:59 +00001357 }
Mike Stump11289f42009-09-09 15:08:12 +00001358
Daniel Dunbar6da10982010-05-27 05:45:51 +00001359 InitializeLayout(D);
Anders Carlsson4f516282009-07-18 20:50:59 +00001360 // Layout each ivar sequentially.
Jordy Rosea91768e2011-07-22 02:08:32 +00001361 for (const ObjCIvarDecl *IVD = D->all_declared_ivar_begin(); IVD;
1362 IVD = IVD->getNextIvar())
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001363 LayoutField(IVD);
Mike Stump11289f42009-09-09 15:08:12 +00001364
Anders Carlsson4f516282009-07-18 20:50:59 +00001365 // Finally, round the size of the total struct up to the alignment of the
1366 // struct itself.
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001367 FinishLayout(D);
Anders Carlsson4f516282009-07-18 20:50:59 +00001368}
1369
Anders Carlssonc2226202010-05-26 05:58:59 +00001370void RecordLayoutBuilder::LayoutFields(const RecordDecl *D) {
Anders Carlsson118ce162009-07-18 21:48:39 +00001371 // Layout each field, for now, just sequentially, respecting alignment. In
1372 // the future, this will need to be tweakable by targets.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001373 for (const auto *Field : D->fields())
1374 LayoutField(Field);
Anders Carlsson118ce162009-07-18 21:48:39 +00001375}
1376
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001377void RecordLayoutBuilder::LayoutWideBitField(uint64_t FieldSize,
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001378 uint64_t TypeSize,
1379 bool FieldPacked,
1380 const FieldDecl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001381 assert(Context.getLangOpts().CPlusPlus &&
Anders Carlsson57235162010-04-16 15:57:11 +00001382 "Can only have wide bit-fields in C++!");
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001383
Anders Carlsson57235162010-04-16 15:57:11 +00001384 // Itanium C++ ABI 2.4:
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001385 // If sizeof(T)*8 < n, let T' be the largest integral POD type with
Anders Carlsson57235162010-04-16 15:57:11 +00001386 // sizeof(T')*8 <= n.
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001387
Anders Carlsson57235162010-04-16 15:57:11 +00001388 QualType IntegralPODTypes[] = {
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001389 Context.UnsignedCharTy, Context.UnsignedShortTy, Context.UnsignedIntTy,
Anders Carlsson57235162010-04-16 15:57:11 +00001390 Context.UnsignedLongTy, Context.UnsignedLongLongTy
1391 };
1392
Anders Carlsson57235162010-04-16 15:57:11 +00001393 QualType Type;
1394 for (unsigned I = 0, E = llvm::array_lengthof(IntegralPODTypes);
1395 I != E; ++I) {
1396 uint64_t Size = Context.getTypeSize(IntegralPODTypes[I]);
Anders Carlsson57235162010-04-16 15:57:11 +00001397
1398 if (Size > FieldSize)
1399 break;
1400
1401 Type = IntegralPODTypes[I];
1402 }
1403 assert(!Type.isNull() && "Did not find a type!");
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001404
Ken Dyckdbe37f32011-03-01 01:36:00 +00001405 CharUnits TypeAlign = Context.getTypeAlignInChars(Type);
Anders Carlsson57235162010-04-16 15:57:11 +00001406
1407 // We're not going to use any of the unfilled bits in the last byte.
Eli Friedman2782dac2013-06-26 20:50:34 +00001408 UnfilledBitsInLastUnit = 0;
1409 LastBitfieldTypeSize = 0;
Anders Carlsson57235162010-04-16 15:57:11 +00001410
Anders Carlssonaad5fa82010-04-17 20:21:41 +00001411 uint64_t FieldOffset;
Eli Friedman2782dac2013-06-26 20:50:34 +00001412 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001413
Anders Carlsson57235162010-04-16 15:57:11 +00001414 if (IsUnion) {
Ken Dyckecfc7552011-02-24 01:13:28 +00001415 setDataSize(std::max(getDataSizeInBits(), FieldSize));
Anders Carlssonaad5fa82010-04-17 20:21:41 +00001416 FieldOffset = 0;
Anders Carlsson57235162010-04-16 15:57:11 +00001417 } else {
Chad Rosiere1a6a0e2011-08-05 22:38:04 +00001418 // The bitfield is allocated starting at the next offset aligned
1419 // appropriately for T', with length n bits.
Ken Dyckdbe37f32011-03-01 01:36:00 +00001420 FieldOffset = llvm::RoundUpToAlignment(getDataSizeInBits(),
1421 Context.toBits(TypeAlign));
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001422
Anders Carlsson57235162010-04-16 15:57:11 +00001423 uint64_t NewSizeInBits = FieldOffset + FieldSize;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001424
Ken Dycka1a2e8d2011-03-10 02:00:35 +00001425 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits,
Douglas Gregore8bbc122011-09-02 00:18:52 +00001426 Context.getTargetInfo().getCharAlign()));
Eli Friedman2782dac2013-06-26 20:50:34 +00001427 UnfilledBitsInLastUnit = getDataSizeInBits() - NewSizeInBits;
Anders Carlsson57235162010-04-16 15:57:11 +00001428 }
1429
1430 // Place this field at the current location.
1431 FieldOffsets.push_back(FieldOffset);
1432
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001433 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, FieldOffset,
Ken Dyckdbe37f32011-03-01 01:36:00 +00001434 Context.toBits(TypeAlign), FieldPacked, D);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001435
Anders Carlsson57235162010-04-16 15:57:11 +00001436 // Update the size.
Ken Dyckecfc7552011-02-24 01:13:28 +00001437 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001438
Anders Carlsson57235162010-04-16 15:57:11 +00001439 // Remember max struct/class alignment.
Ken Dyckdbe37f32011-03-01 01:36:00 +00001440 UpdateAlignment(TypeAlign);
Anders Carlsson57235162010-04-16 15:57:11 +00001441}
1442
Anders Carlssonc2226202010-05-26 05:58:59 +00001443void RecordLayoutBuilder::LayoutBitField(const FieldDecl *D) {
Anders Carlsson07209442009-11-22 17:37:31 +00001444 bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
Richard Smithcaf33902011-10-10 18:28:20 +00001445 uint64_t FieldSize = D->getBitWidthValue(Context);
Anders Carlsson5efc56e2010-04-16 15:07:51 +00001446 std::pair<uint64_t, unsigned> FieldInfo = Context.getTypeInfo(D->getType());
Anders Carlsson07209442009-11-22 17:37:31 +00001447 uint64_t TypeSize = FieldInfo.first;
1448 unsigned FieldAlign = FieldInfo.second;
Eli Friedman2782dac2013-06-26 20:50:34 +00001449
John McCall30268ca2014-01-29 07:53:44 +00001450 // UnfilledBitsInLastUnit is the difference between the end of the
1451 // last allocated bitfield (i.e. the first bit offset available for
1452 // bitfields) and the end of the current data size in bits (i.e. the
1453 // first bit offset available for non-bitfields). The current data
1454 // size in bits is always a multiple of the char size; additionally,
1455 // for ms_struct records it's also a multiple of the
1456 // LastBitfieldTypeSize (if set).
1457
John McCall76e1818a2014-02-13 00:50:08 +00001458 // The struct-layout algorithm is dictated by the platform ABI,
1459 // which in principle could use almost any rules it likes. In
1460 // practice, UNIXy targets tend to inherit the algorithm described
1461 // in the System V generic ABI. The basic bitfield layout rule in
1462 // System V is to place bitfields at the next available bit offset
1463 // where the entire bitfield would fit in an aligned storage unit of
1464 // the declared type; it's okay if an earlier or later non-bitfield
1465 // is allocated in the same storage unit. However, some targets
1466 // (those that !useBitFieldTypeAlignment(), e.g. ARM APCS) don't
1467 // require this storage unit to be aligned, and therefore always put
1468 // the bitfield at the next available bit offset.
John McCall30268ca2014-01-29 07:53:44 +00001469
John McCall76e1818a2014-02-13 00:50:08 +00001470 // ms_struct basically requests a complete replacement of the
1471 // platform ABI's struct-layout algorithm, with the high-level goal
1472 // of duplicating MSVC's layout. For non-bitfields, this follows
1473 // the the standard algorithm. The basic bitfield layout rule is to
1474 // allocate an entire unit of the bitfield's declared type
1475 // (e.g. 'unsigned long'), then parcel it up among successive
1476 // bitfields whose declared types have the same size, making a new
1477 // unit as soon as the last can no longer store the whole value.
1478 // Since it completely replaces the platform ABI's algorithm,
1479 // settings like !useBitFieldTypeAlignment() do not apply.
1480
1481 // A zero-width bitfield forces the use of a new storage unit for
1482 // later bitfields. In general, this occurs by rounding up the
1483 // current size of the struct as if the algorithm were about to
1484 // place a non-bitfield of the field's formal type. Usually this
1485 // does not change the alignment of the struct itself, but it does
1486 // on some targets (those that useZeroLengthBitfieldAlignment(),
1487 // e.g. ARM). In ms_struct layout, zero-width bitfields are
1488 // ignored unless they follow a non-zero-width bitfield.
1489
1490 // A field alignment restriction (e.g. from #pragma pack) or
1491 // specification (e.g. from __attribute__((aligned))) changes the
1492 // formal alignment of the field. For System V, this alters the
1493 // required alignment of the notional storage unit that must contain
1494 // the bitfield. For ms_struct, this only affects the placement of
1495 // new storage units. In both cases, the effect of #pragma pack is
1496 // ignored on zero-width bitfields.
1497
1498 // On System V, a packed field (e.g. from #pragma pack or
1499 // __attribute__((packed))) always uses the next available bit
1500 // offset.
1501
John McCall95833f32014-02-27 20:30:49 +00001502 // In an ms_struct struct, the alignment of a fundamental type is
1503 // always equal to its size. This is necessary in order to mimic
1504 // the i386 alignment rules on targets which might not fully align
1505 // all types (e.g. Darwin PPC32, where alignof(long long) == 4).
John McCall30268ca2014-01-29 07:53:44 +00001506
1507 // First, some simple bookkeeping to perform for ms_struct structs.
Eli Friedman2782dac2013-06-26 20:50:34 +00001508 if (IsMsStruct) {
John McCall30268ca2014-01-29 07:53:44 +00001509 // The field alignment for integer types is always the size.
Fariborz Jahanian7adbed62011-05-09 22:03:17 +00001510 FieldAlign = TypeSize;
John McCall30268ca2014-01-29 07:53:44 +00001511
1512 // If the previous field was not a bitfield, or was a bitfield
1513 // with a different storage unit size, we're done with that
1514 // storage unit.
Eli Friedman2782dac2013-06-26 20:50:34 +00001515 if (LastBitfieldTypeSize != TypeSize) {
John McCall30268ca2014-01-29 07:53:44 +00001516 // Also, ignore zero-length bitfields after non-bitfields.
1517 if (!LastBitfieldTypeSize && !FieldSize)
1518 FieldAlign = 1;
1519
Eli Friedman2782dac2013-06-26 20:50:34 +00001520 UnfilledBitsInLastUnit = 0;
1521 LastBitfieldTypeSize = 0;
1522 }
1523 }
1524
John McCall30268ca2014-01-29 07:53:44 +00001525 // If the field is wider than its declared type, it follows
1526 // different rules in all cases.
Anders Carlsson57235162010-04-16 15:57:11 +00001527 if (FieldSize > TypeSize) {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001528 LayoutWideBitField(FieldSize, TypeSize, FieldPacked, D);
Anders Carlsson57235162010-04-16 15:57:11 +00001529 return;
1530 }
1531
John McCall30268ca2014-01-29 07:53:44 +00001532 // Compute the next available bit offset.
1533 uint64_t FieldOffset =
1534 IsUnion ? 0 : (getDataSizeInBits() - UnfilledBitsInLastUnit);
1535
1536 // Handle targets that don't honor bitfield type alignment.
John McCall76e1818a2014-02-13 00:50:08 +00001537 if (!IsMsStruct && !Context.getTargetInfo().useBitFieldTypeAlignment()) {
John McCall30268ca2014-01-29 07:53:44 +00001538 // Some such targets do honor it on zero-width bitfields.
1539 if (FieldSize == 0 &&
1540 Context.getTargetInfo().useZeroLengthBitfieldAlignment()) {
1541 // The alignment to round up to is the max of the field's natural
1542 // alignment and a target-specific fixed value (sometimes zero).
1543 unsigned ZeroLengthBitfieldBoundary =
1544 Context.getTargetInfo().getZeroLengthBitfieldBoundary();
1545 FieldAlign = std::max(FieldAlign, ZeroLengthBitfieldBoundary);
1546
1547 // If that doesn't apply, just ignore the field alignment.
1548 } else {
1549 FieldAlign = 1;
1550 }
1551 }
1552
1553 // Remember the alignment we would have used if the field were not packed.
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001554 unsigned UnpackedFieldAlign = FieldAlign;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001555
Yunzhong Gao5fd0c9d2014-02-13 02:45:10 +00001556 // Ignore the field alignment if the field is packed unless it has zero-size.
1557 if (!IsMsStruct && FieldPacked && FieldSize != 0)
Anders Carlsson07209442009-11-22 17:37:31 +00001558 FieldAlign = 1;
Anders Carlsson07209442009-11-22 17:37:31 +00001559
John McCall30268ca2014-01-29 07:53:44 +00001560 // But, if there's an 'aligned' attribute on the field, honor that.
1561 if (unsigned ExplicitFieldAlign = D->getMaxAlignment()) {
1562 FieldAlign = std::max(FieldAlign, ExplicitFieldAlign);
1563 UnpackedFieldAlign = std::max(UnpackedFieldAlign, ExplicitFieldAlign);
1564 }
1565
1566 // But, if there's a #pragma pack in play, that takes precedent over
1567 // even the 'aligned' attribute, for non-zero-width bitfields.
1568 if (!MaxFieldAlignment.isZero() && FieldSize) {
Ken Dyck02ced6f2011-02-17 01:49:42 +00001569 unsigned MaxFieldAlignmentInBits = Context.toBits(MaxFieldAlignment);
1570 FieldAlign = std::min(FieldAlign, MaxFieldAlignmentInBits);
1571 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignmentInBits);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001572 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001573
John McCall30268ca2014-01-29 07:53:44 +00001574 // For purposes of diagnostics, we're going to simultaneously
1575 // compute the field offsets that we would have used if we weren't
1576 // adding any alignment padding or if the field weren't packed.
1577 uint64_t UnpaddedFieldOffset = FieldOffset;
1578 uint64_t UnpackedFieldOffset = FieldOffset;
1579
1580 // Check if we need to add padding to fit the bitfield within an
1581 // allocation unit with the right size and alignment. The rules are
1582 // somewhat different here for ms_struct structs.
1583 if (IsMsStruct) {
1584 // If it's not a zero-width bitfield, and we can fit the bitfield
1585 // into the active storage unit (and we haven't already decided to
1586 // start a new storage unit), just do so, regardless of any other
1587 // other consideration. Otherwise, round up to the right alignment.
1588 if (FieldSize == 0 || FieldSize > UnfilledBitsInLastUnit) {
1589 FieldOffset = llvm::RoundUpToAlignment(FieldOffset, FieldAlign);
1590 UnpackedFieldOffset = llvm::RoundUpToAlignment(UnpackedFieldOffset,
1591 UnpackedFieldAlign);
1592 UnfilledBitsInLastUnit = 0;
1593 }
1594
1595 } else {
1596 // #pragma pack, with any value, suppresses the insertion of padding.
1597 bool AllowPadding = MaxFieldAlignment.isZero();
1598
1599 // Compute the real offset.
1600 if (FieldSize == 0 ||
1601 (AllowPadding &&
1602 (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize)) {
1603 FieldOffset = llvm::RoundUpToAlignment(FieldOffset, FieldAlign);
1604 }
1605
1606 // Repeat the computation for diagnostic purposes.
1607 if (FieldSize == 0 ||
1608 (AllowPadding &&
1609 (UnpackedFieldOffset & (UnpackedFieldAlign-1)) + FieldSize > TypeSize))
1610 UnpackedFieldOffset = llvm::RoundUpToAlignment(UnpackedFieldOffset,
1611 UnpackedFieldAlign);
Eli Friedman2782dac2013-06-26 20:50:34 +00001612 }
1613
John McCall30268ca2014-01-29 07:53:44 +00001614 // If we're using external layout, give the external layout a chance
1615 // to override this information.
Douglas Gregor44ba7892012-01-28 00:53:29 +00001616 if (ExternalLayout)
1617 FieldOffset = updateExternalFieldOffset(D, FieldOffset);
1618
John McCall30268ca2014-01-29 07:53:44 +00001619 // Okay, place the bitfield at the calculated offset.
Anders Carlsson07209442009-11-22 17:37:31 +00001620 FieldOffsets.push_back(FieldOffset);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001621
John McCall30268ca2014-01-29 07:53:44 +00001622 // Bookkeeping:
1623
1624 // Anonymous members don't affect the overall record alignment,
1625 // except on targets where they do.
1626 if (!IsMsStruct &&
1627 !Context.getTargetInfo().useZeroLengthBitfieldAlignment() &&
1628 !D->getIdentifier())
1629 FieldAlign = UnpackedFieldAlign = 1;
1630
1631 // Diagnose differences in layout due to padding or packing.
Douglas Gregore9fc3772012-01-26 07:55:45 +00001632 if (!ExternalLayout)
1633 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, UnpackedFieldOffset,
1634 UnpackedFieldAlign, FieldPacked, D);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001635
Anders Carlssonba958402009-11-22 19:13:51 +00001636 // Update DataSize to include the last byte containing (part of) the bitfield.
John McCall30268ca2014-01-29 07:53:44 +00001637
1638 // For unions, this is just a max operation, as usual.
Anders Carlssonba958402009-11-22 19:13:51 +00001639 if (IsUnion) {
1640 // FIXME: I think FieldSize should be TypeSize here.
Ken Dyckecfc7552011-02-24 01:13:28 +00001641 setDataSize(std::max(getDataSizeInBits(), FieldSize));
John McCall30268ca2014-01-29 07:53:44 +00001642
1643 // For non-zero-width bitfields in ms_struct structs, allocate a new
1644 // storage unit if necessary.
1645 } else if (IsMsStruct && FieldSize) {
1646 // We should have cleared UnfilledBitsInLastUnit in every case
1647 // where we changed storage units.
1648 if (!UnfilledBitsInLastUnit) {
1649 setDataSize(FieldOffset + TypeSize);
1650 UnfilledBitsInLastUnit = TypeSize;
Eli Friedman2782dac2013-06-26 20:50:34 +00001651 }
John McCall30268ca2014-01-29 07:53:44 +00001652 UnfilledBitsInLastUnit -= FieldSize;
1653 LastBitfieldTypeSize = TypeSize;
1654
1655 // Otherwise, bump the data size up to include the bitfield,
1656 // including padding up to char alignment, and then remember how
1657 // bits we didn't use.
1658 } else {
1659 uint64_t NewSizeInBits = FieldOffset + FieldSize;
1660 uint64_t CharAlignment = Context.getTargetInfo().getCharAlign();
1661 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits, CharAlignment));
1662 UnfilledBitsInLastUnit = getDataSizeInBits() - NewSizeInBits;
1663
1664 // The only time we can get here for an ms_struct is if this is a
1665 // zero-width bitfield, which doesn't count as anything for the
1666 // purposes of unfilled bits.
1667 LastBitfieldTypeSize = 0;
Anders Carlssonba958402009-11-22 19:13:51 +00001668 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001669
Anders Carlssonba958402009-11-22 19:13:51 +00001670 // Update the size.
Ken Dyckecfc7552011-02-24 01:13:28 +00001671 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001672
Anders Carlsson07209442009-11-22 17:37:31 +00001673 // Remember max struct/class alignment.
Ken Dyck85ef0432011-02-19 18:58:07 +00001674 UpdateAlignment(Context.toCharUnitsFromBits(FieldAlign),
1675 Context.toCharUnitsFromBits(UnpackedFieldAlign));
Anders Carlsson07209442009-11-22 17:37:31 +00001676}
1677
Douglas Gregore9fc3772012-01-26 07:55:45 +00001678void RecordLayoutBuilder::LayoutField(const FieldDecl *D) {
Anders Carlsson07209442009-11-22 17:37:31 +00001679 if (D->isBitField()) {
1680 LayoutBitField(D);
1681 return;
1682 }
1683
Eli Friedman2782dac2013-06-26 20:50:34 +00001684 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001685
Anders Carlssonba958402009-11-22 19:13:51 +00001686 // Reset the unfilled bits.
Eli Friedman2782dac2013-06-26 20:50:34 +00001687 UnfilledBitsInLastUnit = 0;
1688 LastBitfieldTypeSize = 0;
Anders Carlssonba958402009-11-22 19:13:51 +00001689
Anders Carlsson07209442009-11-22 17:37:31 +00001690 bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
Ken Dyck6d90e892011-02-20 02:06:09 +00001691 CharUnits FieldOffset =
Ken Dyckecfc7552011-02-24 01:13:28 +00001692 IsUnion ? CharUnits::Zero() : getDataSize();
Ken Dyck6d90e892011-02-20 02:06:09 +00001693 CharUnits FieldSize;
1694 CharUnits FieldAlign;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001695
Anders Carlsson07209442009-11-22 17:37:31 +00001696 if (D->getType()->isIncompleteArrayType()) {
1697 // This is a flexible array member; we can't directly
1698 // query getTypeInfo about these, so we figure it out here.
1699 // Flexible array members don't have any size, but they
1700 // have to be aligned appropriately for their element type.
Ken Dyck6d90e892011-02-20 02:06:09 +00001701 FieldSize = CharUnits::Zero();
Anders Carlsson5efc56e2010-04-16 15:07:51 +00001702 const ArrayType* ATy = Context.getAsArrayType(D->getType());
Ken Dyck6d90e892011-02-20 02:06:09 +00001703 FieldAlign = Context.getTypeAlignInChars(ATy->getElementType());
Anders Carlsson07209442009-11-22 17:37:31 +00001704 } else if (const ReferenceType *RT = D->getType()->getAs<ReferenceType>()) {
1705 unsigned AS = RT->getPointeeType().getAddressSpace();
Ken Dyck6d90e892011-02-20 02:06:09 +00001706 FieldSize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001707 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(AS));
Ken Dyck6d90e892011-02-20 02:06:09 +00001708 FieldAlign =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001709 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(AS));
Anders Carlsson79474332009-07-18 20:20:21 +00001710 } else {
Ken Dyck6d90e892011-02-20 02:06:09 +00001711 std::pair<CharUnits, CharUnits> FieldInfo =
1712 Context.getTypeInfoInChars(D->getType());
Anders Carlsson07209442009-11-22 17:37:31 +00001713 FieldSize = FieldInfo.first;
1714 FieldAlign = FieldInfo.second;
Chad Rosier18903ee2011-08-04 01:21:14 +00001715
Eli Friedman9ee2d0472012-10-12 23:29:20 +00001716 if (IsMsStruct) {
Douglas Gregordbe39272011-02-01 15:15:22 +00001717 // If MS bitfield layout is required, figure out what type is being
1718 // laid out and align the field to the width of that type.
1719
1720 // Resolve all typedefs down to their base type and round up the field
1721 // alignment if necessary.
1722 QualType T = Context.getBaseElementType(D->getType());
1723 if (const BuiltinType *BTy = T->getAs<BuiltinType>()) {
Ken Dyck6d90e892011-02-20 02:06:09 +00001724 CharUnits TypeSize = Context.getTypeSizeInChars(BTy);
Douglas Gregordbe39272011-02-01 15:15:22 +00001725 if (TypeSize > FieldAlign)
1726 FieldAlign = TypeSize;
1727 }
1728 }
Anders Carlsson79474332009-07-18 20:20:21 +00001729 }
Mike Stump11289f42009-09-09 15:08:12 +00001730
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001731 // The align if the field is not packed. This is to check if the attribute
1732 // was unnecessary (-Wpacked).
Ken Dyck6d90e892011-02-20 02:06:09 +00001733 CharUnits UnpackedFieldAlign = FieldAlign;
1734 CharUnits UnpackedFieldOffset = FieldOffset;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001735
Anders Carlsson07209442009-11-22 17:37:31 +00001736 if (FieldPacked)
Ken Dyck6d90e892011-02-20 02:06:09 +00001737 FieldAlign = CharUnits::One();
1738 CharUnits MaxAlignmentInChars =
1739 Context.toCharUnitsFromBits(D->getMaxAlignment());
1740 FieldAlign = std::max(FieldAlign, MaxAlignmentInChars);
1741 UnpackedFieldAlign = std::max(UnpackedFieldAlign, MaxAlignmentInChars);
Anders Carlsson07209442009-11-22 17:37:31 +00001742
1743 // The maximum field alignment overrides the aligned attribute.
Ken Dyck02ced6f2011-02-17 01:49:42 +00001744 if (!MaxFieldAlignment.isZero()) {
Ken Dyck6d90e892011-02-20 02:06:09 +00001745 FieldAlign = std::min(FieldAlign, MaxFieldAlignment);
1746 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignment);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001747 }
Anders Carlsson07209442009-11-22 17:37:31 +00001748
Douglas Gregor44ba7892012-01-28 00:53:29 +00001749 // Round up the current record size to the field's alignment boundary.
1750 FieldOffset = FieldOffset.RoundUpToAlignment(FieldAlign);
1751 UnpackedFieldOffset =
1752 UnpackedFieldOffset.RoundUpToAlignment(UnpackedFieldAlign);
1753
1754 if (ExternalLayout) {
1755 FieldOffset = Context.toCharUnitsFromBits(
1756 updateExternalFieldOffset(D, Context.toBits(FieldOffset)));
1757
1758 if (!IsUnion && EmptySubobjects) {
1759 // Record the fact that we're placing a field at this offset.
1760 bool Allowed = EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset);
1761 (void)Allowed;
1762 assert(Allowed && "Externally-placed field cannot be placed here");
1763 }
1764 } else {
Douglas Gregore9fc3772012-01-26 07:55:45 +00001765 if (!IsUnion && EmptySubobjects) {
1766 // Check if we can place the field at this offset.
1767 while (!EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset)) {
1768 // We couldn't place the field at the offset. Try again at a new offset.
1769 FieldOffset += FieldAlign;
1770 }
Anders Carlsson07209442009-11-22 17:37:31 +00001771 }
Anders Carlsson07209442009-11-22 17:37:31 +00001772 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00001773
Anders Carlsson79474332009-07-18 20:20:21 +00001774 // Place this field at the current location.
Ken Dyck6d90e892011-02-20 02:06:09 +00001775 FieldOffsets.push_back(Context.toBits(FieldOffset));
Mike Stump11289f42009-09-09 15:08:12 +00001776
Douglas Gregore9fc3772012-01-26 07:55:45 +00001777 if (!ExternalLayout)
1778 CheckFieldPadding(Context.toBits(FieldOffset), UnpaddedFieldOffset,
1779 Context.toBits(UnpackedFieldOffset),
1780 Context.toBits(UnpackedFieldAlign), FieldPacked, D);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001781
Anders Carlsson79474332009-07-18 20:20:21 +00001782 // Reserve space for this field.
Eli Friedman43f18342012-01-12 23:27:03 +00001783 uint64_t FieldSizeInBits = Context.toBits(FieldSize);
Anders Carlsson79474332009-07-18 20:20:21 +00001784 if (IsUnion)
Eli Friedman2e108372012-01-12 23:48:56 +00001785 setDataSize(std::max(getDataSizeInBits(), FieldSizeInBits));
Anders Carlsson79474332009-07-18 20:20:21 +00001786 else
Eli Friedman2e108372012-01-12 23:48:56 +00001787 setDataSize(FieldOffset + FieldSize);
Mike Stump11289f42009-09-09 15:08:12 +00001788
Eli Friedman2e108372012-01-12 23:48:56 +00001789 // Update the size.
1790 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
Mike Stump11289f42009-09-09 15:08:12 +00001791
Anders Carlsson79474332009-07-18 20:20:21 +00001792 // Remember max struct/class alignment.
Ken Dyck6d90e892011-02-20 02:06:09 +00001793 UpdateAlignment(FieldAlign, UnpackedFieldAlign);
Anders Carlsson79474332009-07-18 20:20:21 +00001794}
1795
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001796void RecordLayoutBuilder::FinishLayout(const NamedDecl *D) {
Anders Carlsson79474332009-07-18 20:20:21 +00001797 // In C++, records cannot be of size 0.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001798 if (Context.getLangOpts().CPlusPlus && getSizeInBits() == 0) {
Fariborz Jahanian09b23312011-02-02 19:36:18 +00001799 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
1800 // Compatibility with gcc requires a class (pod or non-pod)
1801 // which is not empty but of size 0; such as having fields of
1802 // array of zero-length, remains of Size 0
1803 if (RD->isEmpty())
Ken Dyck1b4420e2011-02-28 02:01:38 +00001804 setSize(CharUnits::One());
Fariborz Jahanian09b23312011-02-02 19:36:18 +00001805 }
1806 else
Ken Dyck1b4420e2011-02-28 02:01:38 +00001807 setSize(CharUnits::One());
Fariborz Jahanian09b23312011-02-02 19:36:18 +00001808 }
Eli Friedman83a12582011-12-01 00:37:01 +00001809
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001810 // Finally, round the size of the record up to the alignment of the
1811 // record itself.
Eli Friedman2782dac2013-06-26 20:50:34 +00001812 uint64_t UnpaddedSize = getSizeInBits() - UnfilledBitsInLastUnit;
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001813 uint64_t UnpackedSizeInBits =
1814 llvm::RoundUpToAlignment(getSizeInBits(),
1815 Context.toBits(UnpackedAlignment));
1816 CharUnits UnpackedSize = Context.toCharUnitsFromBits(UnpackedSizeInBits);
1817 uint64_t RoundedSize
1818 = llvm::RoundUpToAlignment(getSizeInBits(), Context.toBits(Alignment));
1819
1820 if (ExternalLayout) {
1821 // If we're inferring alignment, and the external size is smaller than
1822 // our size after we've rounded up to alignment, conservatively set the
1823 // alignment to 1.
1824 if (InferAlignment && ExternalSize < RoundedSize) {
1825 Alignment = CharUnits::One();
1826 InferAlignment = false;
1827 }
1828 setSize(ExternalSize);
1829 return;
1830 }
1831
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001832 // Set the size to the final size.
1833 setSize(RoundedSize);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001834
Douglas Gregore8bbc122011-09-02 00:18:52 +00001835 unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001836 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
1837 // Warn if padding was introduced to the struct/class/union.
Ken Dyckecfc7552011-02-24 01:13:28 +00001838 if (getSizeInBits() > UnpaddedSize) {
1839 unsigned PadSize = getSizeInBits() - UnpaddedSize;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001840 bool InBits = true;
1841 if (PadSize % CharBitNum == 0) {
1842 PadSize = PadSize / CharBitNum;
1843 InBits = false;
1844 }
1845 Diag(RD->getLocation(), diag::warn_padded_struct_size)
1846 << Context.getTypeDeclType(RD)
1847 << PadSize
1848 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1); // plural or not
1849 }
1850
1851 // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
1852 // bother since there won't be alignment issues.
Ken Dyckecfc7552011-02-24 01:13:28 +00001853 if (Packed && UnpackedAlignment > CharUnits::One() &&
Ken Dyck1b4420e2011-02-28 02:01:38 +00001854 getSize() == UnpackedSize)
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001855 Diag(D->getLocation(), diag::warn_unnecessary_packed)
1856 << Context.getTypeDeclType(RD);
1857 }
Anders Carlsson79474332009-07-18 20:20:21 +00001858}
1859
Ken Dyck85ef0432011-02-19 18:58:07 +00001860void RecordLayoutBuilder::UpdateAlignment(CharUnits NewAlignment,
1861 CharUnits UnpackedNewAlignment) {
Douglas Gregore9fc3772012-01-26 07:55:45 +00001862 // The alignment is not modified when using 'mac68k' alignment or when
Douglas Gregor44ba7892012-01-28 00:53:29 +00001863 // we have an externally-supplied layout that also provides overall alignment.
1864 if (IsMac68kAlign || (ExternalLayout && !InferAlignment))
Daniel Dunbar6da10982010-05-27 05:45:51 +00001865 return;
1866
Ken Dyck85ef0432011-02-19 18:58:07 +00001867 if (NewAlignment > Alignment) {
1868 assert(llvm::isPowerOf2_32(NewAlignment.getQuantity() &&
1869 "Alignment not a power of 2"));
1870 Alignment = NewAlignment;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001871 }
1872
Ken Dyck85ef0432011-02-19 18:58:07 +00001873 if (UnpackedNewAlignment > UnpackedAlignment) {
1874 assert(llvm::isPowerOf2_32(UnpackedNewAlignment.getQuantity() &&
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001875 "Alignment not a power of 2"));
Ken Dyck85ef0432011-02-19 18:58:07 +00001876 UnpackedAlignment = UnpackedNewAlignment;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001877 }
1878}
1879
Douglas Gregor44ba7892012-01-28 00:53:29 +00001880uint64_t
1881RecordLayoutBuilder::updateExternalFieldOffset(const FieldDecl *Field,
1882 uint64_t ComputedOffset) {
1883 assert(ExternalFieldOffsets.find(Field) != ExternalFieldOffsets.end() &&
1884 "Field does not have an external offset");
1885
1886 uint64_t ExternalFieldOffset = ExternalFieldOffsets[Field];
1887
1888 if (InferAlignment && ExternalFieldOffset < ComputedOffset) {
1889 // The externally-supplied field offset is before the field offset we
1890 // computed. Assume that the structure is packed.
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001891 Alignment = CharUnits::One();
Douglas Gregor44ba7892012-01-28 00:53:29 +00001892 InferAlignment = false;
1893 }
1894
1895 // Use the externally-supplied field offset.
Benjamin Kramer648e68b2012-08-31 22:14:25 +00001896 return ExternalFieldOffset;
1897}
1898
1899/// \brief Get diagnostic %select index for tag kind for
1900/// field padding diagnostic message.
1901/// WARNING: Indexes apply to particular diagnostics only!
1902///
1903/// \returns diagnostic %select index.
1904static unsigned getPaddingDiagFromTagKind(TagTypeKind Tag) {
1905 switch (Tag) {
1906 case TTK_Struct: return 0;
1907 case TTK_Interface: return 1;
1908 case TTK_Class: return 2;
1909 default: llvm_unreachable("Invalid tag kind for field padding diagnostic!");
1910 }
1911}
1912
1913void RecordLayoutBuilder::CheckFieldPadding(uint64_t Offset,
1914 uint64_t UnpaddedOffset,
1915 uint64_t UnpackedOffset,
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001916 unsigned UnpackedAlign,
1917 bool isPacked,
1918 const FieldDecl *D) {
1919 // We let objc ivars without warning, objc interfaces generally are not used
1920 // for padding tricks.
1921 if (isa<ObjCIvarDecl>(D))
Anders Carlsson79474332009-07-18 20:20:21 +00001922 return;
Mike Stump11289f42009-09-09 15:08:12 +00001923
Ted Kremenekfed48af2011-09-06 19:40:45 +00001924 // Don't warn about structs created without a SourceLocation. This can
1925 // be done by clients of the AST, such as codegen.
1926 if (D->getLocation().isInvalid())
1927 return;
1928
Douglas Gregore8bbc122011-09-02 00:18:52 +00001929 unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
Mike Stump11289f42009-09-09 15:08:12 +00001930
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001931 // Warn if padding was introduced to the struct/class.
1932 if (!IsUnion && Offset > UnpaddedOffset) {
1933 unsigned PadSize = Offset - UnpaddedOffset;
1934 bool InBits = true;
1935 if (PadSize % CharBitNum == 0) {
1936 PadSize = PadSize / CharBitNum;
1937 InBits = false;
Benjamin Kramer648e68b2012-08-31 22:14:25 +00001938 }
1939 if (D->getIdentifier())
1940 Diag(D->getLocation(), diag::warn_padded_struct_field)
1941 << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
1942 << Context.getTypeDeclType(D->getParent())
1943 << PadSize
1944 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1) // plural or not
1945 << D->getIdentifier();
1946 else
1947 Diag(D->getLocation(), diag::warn_padded_struct_anon_field)
1948 << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
1949 << Context.getTypeDeclType(D->getParent())
1950 << PadSize
1951 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1); // plural or not
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001952 }
1953
1954 // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
1955 // bother since there won't be alignment issues.
1956 if (isPacked && UnpackedAlign > CharBitNum && Offset == UnpackedOffset)
1957 Diag(D->getLocation(), diag::warn_unnecessary_packed)
1958 << D->getIdentifier();
Anders Carlsson79474332009-07-18 20:20:21 +00001959}
Mike Stump11289f42009-09-09 15:08:12 +00001960
John McCall6bd2a892013-01-25 22:31:03 +00001961static const CXXMethodDecl *computeKeyFunction(ASTContext &Context,
1962 const CXXRecordDecl *RD) {
Daniel Dunbarccabe482010-04-19 20:44:53 +00001963 // If a class isn't polymorphic it doesn't have a key function.
Anders Carlsson5ebf8b42009-12-07 04:35:11 +00001964 if (!RD->isPolymorphic())
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001965 return 0;
Eli Friedmanf2c79b62009-12-08 03:56:49 +00001966
Eli Friedman300f55d2011-06-10 21:53:06 +00001967 // A class that is not externally visible doesn't have a key function. (Or
Eli Friedmanf2c79b62009-12-08 03:56:49 +00001968 // at least, there's no point to assigning a key function to such a class;
1969 // this doesn't affect the ABI.)
Rafael Espindola3ae00052013-05-13 00:12:11 +00001970 if (!RD->isExternallyVisible())
Eli Friedmanf2c79b62009-12-08 03:56:49 +00001971 return 0;
1972
Argyrios Kyrtzidis8c64bbe2010-10-13 02:39:41 +00001973 // Template instantiations don't have key functions,see Itanium C++ ABI 5.2.6.
1974 // Same behavior as GCC.
1975 TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
1976 if (TSK == TSK_ImplicitInstantiation ||
1977 TSK == TSK_ExplicitInstantiationDefinition)
1978 return 0;
1979
John McCall6bd2a892013-01-25 22:31:03 +00001980 bool allowInlineFunctions =
1981 Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline();
1982
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001983 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
1984 E = RD->method_end(); I != E; ++I) {
David Blaikie40ed2972012-06-06 20:45:41 +00001985 const CXXMethodDecl *MD = *I;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001986
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001987 if (!MD->isVirtual())
1988 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001989
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001990 if (MD->isPure())
1991 continue;
Eli Friedmanf2c79b62009-12-08 03:56:49 +00001992
Anders Carlssonf98849e2009-12-02 17:15:43 +00001993 // Ignore implicit member functions, they are always marked as inline, but
1994 // they don't have a body until they're defined.
1995 if (MD->isImplicit())
1996 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001997
Douglas Gregora318efd2010-01-05 19:06:31 +00001998 if (MD->isInlineSpecified())
1999 continue;
Eli Friedman71a26d82009-12-06 20:50:05 +00002000
2001 if (MD->hasInlineBody())
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00002002 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002003
Benjamin Kramer4a902082012-08-03 15:43:22 +00002004 // Ignore inline deleted or defaulted functions.
Benjamin Kramer73d1be72012-08-03 08:39:58 +00002005 if (!MD->isUserProvided())
2006 continue;
2007
John McCall6bd2a892013-01-25 22:31:03 +00002008 // In certain ABIs, ignore functions with out-of-line inline definitions.
2009 if (!allowInlineFunctions) {
2010 const FunctionDecl *Def;
2011 if (MD->hasBody(Def) && Def->isInlineSpecified())
2012 continue;
2013 }
2014
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00002015 // We found it.
2016 return MD;
2017 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002018
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00002019 return 0;
2020}
2021
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002022DiagnosticBuilder
2023RecordLayoutBuilder::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +00002024 return Context.getDiagnostics().Report(Loc, DiagID);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002025}
2026
John McCall5c1f1d02013-01-29 01:14:22 +00002027/// Does the target C++ ABI require us to skip over the tail-padding
2028/// of the given class (considering it as a base class) when allocating
2029/// objects?
2030static bool mustSkipTailPadding(TargetCXXABI ABI, const CXXRecordDecl *RD) {
2031 switch (ABI.getTailPaddingUseRules()) {
2032 case TargetCXXABI::AlwaysUseTailPadding:
2033 return false;
2034
2035 case TargetCXXABI::UseTailPaddingUnlessPOD03:
2036 // FIXME: To the extent that this is meant to cover the Itanium ABI
2037 // rules, we should implement the restrictions about over-sized
2038 // bitfields:
2039 //
2040 // http://mentorembedded.github.com/cxx-abi/abi.html#POD :
2041 // In general, a type is considered a POD for the purposes of
2042 // layout if it is a POD type (in the sense of ISO C++
2043 // [basic.types]). However, a POD-struct or POD-union (in the
2044 // sense of ISO C++ [class]) with a bitfield member whose
2045 // declared width is wider than the declared type of the
2046 // bitfield is not a POD for the purpose of layout. Similarly,
2047 // an array type is not a POD for the purpose of layout if the
2048 // element type of the array is not a POD for the purpose of
2049 // layout.
2050 //
2051 // Where references to the ISO C++ are made in this paragraph,
2052 // the Technical Corrigendum 1 version of the standard is
2053 // intended.
2054 return RD->isPOD();
2055
2056 case TargetCXXABI::UseTailPaddingUnlessPOD11:
2057 // This is equivalent to RD->getTypeForDecl().isCXX11PODType(),
2058 // but with a lot of abstraction penalty stripped off. This does
2059 // assume that these properties are set correctly even in C++98
2060 // mode; fortunately, that is true because we want to assign
2061 // consistently semantics to the type-traits intrinsics (or at
2062 // least as many of them as possible).
2063 return RD->isTrivial() && RD->isStandardLayout();
2064 }
2065
2066 llvm_unreachable("bad tail-padding use kind");
2067}
2068
Warren Hunt8f8bad72013-10-11 20:19:00 +00002069static bool isMsLayout(const RecordDecl* D) {
Warren Hunt55d8e822013-10-23 23:53:07 +00002070 return D->getASTContext().getTargetInfo().getCXXABI().isMicrosoft();
Warren Hunt8f8bad72013-10-11 20:19:00 +00002071}
2072
2073// This section contains an implementation of struct layout that is, up to the
2074// included tests, compatible with cl.exe (2012). The layout produced is
2075// significantly different than those produced by the Itanium ABI. Here we note
2076// the most important differences.
2077//
2078// * The alignment of bitfields in unions is ignored when computing the
2079// alignment of the union.
Alp Tokerf6a24ce2013-12-05 16:25:25 +00002080// * The existence of zero-width bitfield that occurs after anything other than
Warren Hunt8f8bad72013-10-11 20:19:00 +00002081// a non-zero length bitfield is ignored.
2082// * The Itanium equivalent vtable pointers are split into a vfptr (virtual
2083// function pointer) and a vbptr (virtual base pointer). They can each be
Warren Hunt55d8e822013-10-23 23:53:07 +00002084// shared with a, non-virtual bases. These bases need not be the same. vfptrs
2085// always occur at offset 0. vbptrs can occur at an
Warren Hunt8f8bad72013-10-11 20:19:00 +00002086// arbitrary offset and are placed after non-virtual bases but before fields.
2087// * Virtual bases sometimes require a 'vtordisp' field that is laid out before
2088// the virtual base and is used in conjunction with virtual overrides during
2089// construction and destruction.
2090// * vfptrs are allocated in a block of memory equal to the alignment of the
Warren Hunt55d8e822013-10-23 23:53:07 +00002091// fields and non-virtual bases at offset 0 in 32 bit mode and in a pointer
2092// sized block of memory in 64 bit mode.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002093// * vbptrs are allocated in a block of memory equal to the alignment of the
Warren Hunt55d8e822013-10-23 23:53:07 +00002094// fields and non-virtual bases. This block is at a potentially unaligned
2095// offset. If the allocation slot is unaligned and the alignment is less than
2096// or equal to the pointer size, additional space is allocated so that the
2097// pointer can be aligned properly. This causes very strange effects on the
2098// placement of objects after the allocated block. (see the code).
Warren Hunt8f8bad72013-10-11 20:19:00 +00002099// * vtordisps are allocated in a block of memory with size and alignment equal
2100// to the alignment of the completed structure (before applying __declspec(
Warren Hunt55d8e822013-10-23 23:53:07 +00002101// align())). The vtordisp always occur at the end of the allocation block,
2102// immediately prior to the virtual base.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002103// * The last zero sized non-virtual base is allocated after the placement of
2104// vbptr if one exists and can be placed at the end of the struct, potentially
2105// aliasing either the first member or another struct allocated after this
2106// one.
2107// * The last zero size virtual base may be placed at the end of the struct.
2108// and can potentially alias a zero sized type in the next struct.
Warren Hunt71140d62013-12-06 20:16:49 +00002109// * If the last field is a non-zero length bitfield, all virtual bases will
2110// have extra padding added before them for no obvious reason. The padding
2111// has the same number of bits as the type of the bitfield.
Warren Huntc0df47d2013-11-19 22:11:09 +00002112// * When laying out empty non-virtual bases, an extra byte of padding is added
2113// if the non-virtual base before the empty non-virtual base has a vbptr.
Warren Hunt049f6732013-12-06 19:54:25 +00002114// * The ABI attempts to avoid aliasing of zero sized bases by adding padding
2115// between bases or vbases with specific properties. The criteria for
2116// additional padding between two bases is that the first base is zero sized
2117// or has a zero sized subobject and the second base is zero sized or leads
2118// with a zero sized base (sharing of vfptrs can reorder the layout of the
2119// so the leading base is not always the first one declared). The padding
2120// added for bases is 1 byte. The padding added for vbases depends on the
2121// alignment of the object but is at least 4 bytes (in both 32 and 64 bit
2122// modes).
Warren Huntd640d7d2014-01-09 00:30:56 +00002123// * There is no concept of non-virtual alignment or any distinction between
2124// data size and non-virtual size.
Warren Huntf4518def2014-01-10 01:28:05 +00002125// * __declspec(align) on bitfields has the effect of changing the bitfield's
2126// alignment instead of its required alignment. This has implications on how
2127// it interacts with pragam pack.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002128
2129namespace {
2130struct MicrosoftRecordLayoutBuilder {
Warren Huntd640d7d2014-01-09 00:30:56 +00002131 struct ElementInfo {
2132 CharUnits Size;
2133 CharUnits Alignment;
2134 };
Warren Hunt8f8bad72013-10-11 20:19:00 +00002135 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
2136 MicrosoftRecordLayoutBuilder(const ASTContext &Context) : Context(Context) {}
2137private:
2138 MicrosoftRecordLayoutBuilder(const MicrosoftRecordLayoutBuilder &)
2139 LLVM_DELETED_FUNCTION;
2140 void operator=(const MicrosoftRecordLayoutBuilder &) LLVM_DELETED_FUNCTION;
2141public:
Warren Hunt8f8bad72013-10-11 20:19:00 +00002142 void layout(const RecordDecl *RD);
2143 void cxxLayout(const CXXRecordDecl *RD);
2144 /// \brief Initializes size and alignment and honors some flags.
2145 void initializeLayout(const RecordDecl *RD);
2146 /// \brief Initialized C++ layout, compute alignment and virtual alignment and
Alp Tokerf6a24ce2013-12-05 16:25:25 +00002147 /// existence of vfptrs and vbptrs. Alignment is needed before the vfptr is
Warren Hunt8f8bad72013-10-11 20:19:00 +00002148 /// laid out.
2149 void initializeCXXLayout(const CXXRecordDecl *RD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002150 void layoutNonVirtualBases(const CXXRecordDecl *RD);
Warren Huntd640d7d2014-01-09 00:30:56 +00002151 void layoutNonVirtualBase(const CXXRecordDecl *BaseDecl,
2152 const ASTRecordLayout &BaseLayout,
2153 const ASTRecordLayout *&PreviousBaseLayout);
2154 void injectVFPtr(const CXXRecordDecl *RD);
2155 void injectVBPtr(const CXXRecordDecl *RD);
2156 void injectVPtrs(const CXXRecordDecl *RD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002157 /// \brief Lays out the fields of the record. Also rounds size up to
2158 /// alignment.
2159 void layoutFields(const RecordDecl *RD);
2160 void layoutField(const FieldDecl *FD);
2161 void layoutBitField(const FieldDecl *FD);
2162 /// \brief Lays out a single zero-width bit-field in the record and handles
2163 /// special cases associated with zero-width bit-fields.
2164 void layoutZeroWidthBitField(const FieldDecl *FD);
2165 void layoutVirtualBases(const CXXRecordDecl *RD);
Warren Hunt1603e522013-12-10 01:44:39 +00002166 void finalizeLayout(const RecordDecl *RD);
Warren Huntd640d7d2014-01-09 00:30:56 +00002167 /// \brief Gets the size and alignment of a base taking pragma pack and
2168 /// __declspec(align) into account.
Warren Huntf6ec7482014-02-21 01:40:35 +00002169 ElementInfo getAdjustedElementInfo(const ASTRecordLayout &Layout,
2170 bool AsBase = true);
Warren Huntd640d7d2014-01-09 00:30:56 +00002171 /// \brief Gets the size and alignment of a field taking pragma pack and
2172 /// __declspec(align) into account. It also updates RequiredAlignment as a
2173 /// side effect because it is most convenient to do so here.
2174 ElementInfo getAdjustedElementInfo(const FieldDecl *FD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002175 /// \brief Places a field at an offset in CharUnits.
2176 void placeFieldAtOffset(CharUnits FieldOffset) {
2177 FieldOffsets.push_back(Context.toBits(FieldOffset));
2178 }
2179 /// \brief Places a bitfield at a bit offset.
2180 void placeFieldAtBitOffset(uint64_t FieldOffset) {
2181 FieldOffsets.push_back(FieldOffset);
2182 }
2183 /// \brief Compute the set of virtual bases for which vtordisps are required.
2184 llvm::SmallPtrSet<const CXXRecordDecl *, 2>
2185 computeVtorDispSet(const CXXRecordDecl *RD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002186 const ASTContext &Context;
2187 /// \brief The size of the record being laid out.
2188 CharUnits Size;
Warren Huntf6ec7482014-02-21 01:40:35 +00002189 /// \brief The non-virtual size of the record layout.
2190 CharUnits NonVirtualSize;
2191 /// \brief The data size of the record layout.
Warren Huntd640d7d2014-01-09 00:30:56 +00002192 CharUnits DataSize;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002193 /// \brief The current alignment of the record layout.
2194 CharUnits Alignment;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002195 /// \brief The maximum allowed field alignment. This is set by #pragma pack.
2196 CharUnits MaxFieldAlignment;
Warren Hunt7b252d22013-12-06 00:01:17 +00002197 /// \brief The alignment that this record must obey. This is imposed by
2198 /// __declspec(align()) on the record itself or one of its fields or bases.
2199 CharUnits RequiredAlignment;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002200 /// \brief The size of the allocation of the currently active bitfield.
2201 /// This value isn't meaningful unless LastFieldIsNonZeroWidthBitfield
2202 /// is true.
2203 CharUnits CurrentBitfieldSize;
Warren Huntd640d7d2014-01-09 00:30:56 +00002204 /// \brief Offset to the virtual base table pointer (if one exists).
2205 CharUnits VBPtrOffset;
2206 /// \brief The size and alignment info of a pointer.
2207 ElementInfo PointerInfo;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002208 /// \brief The primary base class (if one exists).
2209 const CXXRecordDecl *PrimaryBase;
2210 /// \brief The class we share our vb-pointer with.
2211 const CXXRecordDecl *SharedVBPtrBase;
Warren Huntd640d7d2014-01-09 00:30:56 +00002212 /// \brief The collection of field offsets.
2213 SmallVector<uint64_t, 16> FieldOffsets;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002214 /// \brief Base classes and their offsets in the record.
2215 BaseOffsetsMapTy Bases;
2216 /// \brief virtual base classes and their offsets in the record.
2217 ASTRecordLayout::VBaseOffsetsMapTy VBases;
Warren Huntd640d7d2014-01-09 00:30:56 +00002218 /// \brief The number of remaining bits in our last bitfield allocation.
2219 /// This value isn't meaningful unless LastFieldIsNonZeroWidthBitfield is
2220 /// true.
2221 unsigned RemainingBitsInField;
2222 bool IsUnion : 1;
2223 /// \brief True if the last field laid out was a bitfield and was not 0
2224 /// width.
2225 bool LastFieldIsNonZeroWidthBitfield : 1;
2226 /// \brief True if the class has its own vftable pointer.
2227 bool HasOwnVFPtr : 1;
2228 /// \brief True if the class has a vbtable pointer.
2229 bool HasVBPtr : 1;
Warren Hunt55d8e822013-10-23 23:53:07 +00002230 /// \brief Lets us know if we're in 64-bit mode
Warren Hunt049f6732013-12-06 19:54:25 +00002231 bool Is64BitMode : 1;
2232 /// \brief True if this class contains a zero sized member or base or a base
2233 /// with a zero sized member or base. Only used for MS-ABI.
2234 bool HasZeroSizedSubObject : 1;
2235 /// \brief True if this class is zero sized or first base is zero sized or
2236 /// has this property. Only used for MS-ABI.
2237 bool LeadsWithZeroSizedBase : 1;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002238};
2239} // namespace
2240
Warren Huntd640d7d2014-01-09 00:30:56 +00002241MicrosoftRecordLayoutBuilder::ElementInfo
2242MicrosoftRecordLayoutBuilder::getAdjustedElementInfo(
Warren Huntf6ec7482014-02-21 01:40:35 +00002243 const ASTRecordLayout &Layout, bool AsBase) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002244 ElementInfo Info;
2245 Info.Alignment = Layout.getAlignment();
2246 // Respect pragma pack.
Warren Hunt7b252d22013-12-06 00:01:17 +00002247 if (!MaxFieldAlignment.isZero())
Warren Huntd640d7d2014-01-09 00:30:56 +00002248 Info.Alignment = std::min(Info.Alignment, MaxFieldAlignment);
2249 // Track zero-sized subobjects here where it's already available.
2250 if (Layout.hasZeroSizedSubObject())
2251 HasZeroSizedSubObject = true;
2252 // Respect required alignment, this is necessary because we may have adjusted
Warren Hunt94258912014-01-11 01:16:40 +00002253 // the alignment in the case of pragam pack. Note that the required alignment
2254 // doesn't actually apply to the struct alignment at this point.
2255 Alignment = std::max(Alignment, Info.Alignment);
Warren Huntd640d7d2014-01-09 00:30:56 +00002256 Info.Alignment = std::max(Info.Alignment, Layout.getRequiredAlignment());
Warren Huntf6ec7482014-02-21 01:40:35 +00002257 Info.Size = AsBase ? Layout.getNonVirtualSize() : Layout.getSize();
Warren Huntd640d7d2014-01-09 00:30:56 +00002258 return Info;
Warren Hunt7b252d22013-12-06 00:01:17 +00002259}
2260
Warren Huntd640d7d2014-01-09 00:30:56 +00002261MicrosoftRecordLayoutBuilder::ElementInfo
2262MicrosoftRecordLayoutBuilder::getAdjustedElementInfo(
2263 const FieldDecl *FD) {
2264 ElementInfo Info;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002265 std::tie(Info.Size, Info.Alignment) =
Reid Klecknerdb673ca2014-02-25 18:08:48 +00002266 Context.getTypeInfoInChars(FD->getType());
Warren Huntf4518def2014-01-10 01:28:05 +00002267 // Respect align attributes.
2268 CharUnits FieldRequiredAlignment =
2269 Context.toCharUnitsFromBits(FD->getMaxAlignment());
Warren Hunt049f6732013-12-06 19:54:25 +00002270 // Respect attributes applied to subobjects of the field.
Warren Hunt7b252d22013-12-06 00:01:17 +00002271 if (const RecordType *RT =
2272 FD->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
2273 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RT->getDecl());
Warren Huntd640d7d2014-01-09 00:30:56 +00002274 // Get the element info for a layout, respecting pack.
Reid Klecknerdb673ca2014-02-25 18:08:48 +00002275 Info.Alignment = getAdjustedElementInfo(Layout, false).Alignment;
Warren Huntd640d7d2014-01-09 00:30:56 +00002276 // Capture required alignment as a side-effect.
Warren Hunt7b252d22013-12-06 00:01:17 +00002277 RequiredAlignment = std::max(RequiredAlignment,
2278 Layout.getRequiredAlignment());
Reid Klecknerdb673ca2014-02-25 18:08:48 +00002279 } else {
Warren Huntf4518def2014-01-10 01:28:05 +00002280 if (FD->isBitField() && FD->getMaxAlignment() != 0)
2281 Info.Alignment = std::max(Info.Alignment, FieldRequiredAlignment);
Warren Hunt26b94422014-01-14 00:54:36 +00002282 // Respect pragma pack.
2283 if (!MaxFieldAlignment.isZero())
2284 Info.Alignment = std::min(Info.Alignment, MaxFieldAlignment);
Warren Huntd640d7d2014-01-09 00:30:56 +00002285 }
2286 // Respect packed field attribute.
2287 if (FD->hasAttr<PackedAttr>())
2288 Info.Alignment = CharUnits::One();
Warren Huntf4518def2014-01-10 01:28:05 +00002289 // Take required alignment into account. __declspec(align) on bitfields
2290 // impacts the alignment rather than the required alignment.
2291 if (!FD->isBitField()) {
2292 Info.Alignment = std::max(Info.Alignment, FieldRequiredAlignment);
2293 // Capture required alignment as a side-effect.
2294 RequiredAlignment = std::max(RequiredAlignment, FieldRequiredAlignment);
2295 }
Warren Hunt94258912014-01-11 01:16:40 +00002296 // TODO: Add a Sema warning that MS ignores bitfield alignment in unions.
Warren Hunt26b94422014-01-14 00:54:36 +00002297 if (!(FD->isBitField() && IsUnion)) {
Warren Hunt94258912014-01-11 01:16:40 +00002298 Alignment = std::max(Alignment, Info.Alignment);
Warren Hunt26b94422014-01-14 00:54:36 +00002299 if (!MaxFieldAlignment.isZero())
2300 Alignment = std::min(Alignment, MaxFieldAlignment);
2301 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002302 return Info;
2303}
2304
2305void MicrosoftRecordLayoutBuilder::layout(const RecordDecl *RD) {
2306 initializeLayout(RD);
2307 layoutFields(RD);
2308 DataSize = Size = Size.RoundUpToAlignment(Alignment);
David Majnemer79a1c892014-02-12 00:43:02 +00002309 RequiredAlignment = std::max(
2310 RequiredAlignment, Context.toCharUnitsFromBits(RD->getMaxAlignment()));
Warren Huntd640d7d2014-01-09 00:30:56 +00002311 finalizeLayout(RD);
2312}
2313
2314void MicrosoftRecordLayoutBuilder::cxxLayout(const CXXRecordDecl *RD) {
2315 initializeLayout(RD);
2316 initializeCXXLayout(RD);
2317 layoutNonVirtualBases(RD);
2318 layoutFields(RD);
2319 injectVPtrs(RD);
Warren Huntf6ec7482014-02-21 01:40:35 +00002320 NonVirtualSize = Size = Size.RoundUpToAlignment(Alignment);
David Majnemer79a1c892014-02-12 00:43:02 +00002321 RequiredAlignment = std::max(
2322 RequiredAlignment, Context.toCharUnitsFromBits(RD->getMaxAlignment()));
Warren Huntd640d7d2014-01-09 00:30:56 +00002323 layoutVirtualBases(RD);
2324 finalizeLayout(RD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002325}
2326
2327void MicrosoftRecordLayoutBuilder::initializeLayout(const RecordDecl *RD) {
2328 IsUnion = RD->isUnion();
Warren Hunt5ae586a2013-11-01 23:59:41 +00002329 Is64BitMode = Context.getTargetInfo().getPointerWidth(0) == 64;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002330 Size = CharUnits::Zero();
2331 Alignment = CharUnits::One();
Warren Hunt7b252d22013-12-06 00:01:17 +00002332 // In 64-bit mode we always perform an alignment step after laying out vbases.
2333 // In 32-bit mode we do not. The check to see if we need to perform alignment
2334 // checks the RequiredAlignment field and performs alignment if it isn't 0.
2335 RequiredAlignment = Is64BitMode ? CharUnits::One() : CharUnits::Zero();
Warren Hunt8f8bad72013-10-11 20:19:00 +00002336 // Compute the maximum field alignment.
2337 MaxFieldAlignment = CharUnits::Zero();
2338 // Honor the default struct packing maximum alignment flag.
2339 if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct)
Warren Huntf4518def2014-01-10 01:28:05 +00002340 MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
2341 // Honor the packing attribute. The MS-ABI ignores pragma pack if its larger
2342 // than the pointer size.
2343 if (const MaxFieldAlignmentAttr *MFAA = RD->getAttr<MaxFieldAlignmentAttr>()){
2344 unsigned PackedAlignment = MFAA->getAlignment();
2345 if (PackedAlignment <= Context.getTargetInfo().getPointerWidth(0))
2346 MaxFieldAlignment = Context.toCharUnitsFromBits(PackedAlignment);
2347 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002348 // Packed attribute forces max field alignment to be 1.
2349 if (RD->hasAttr<PackedAttr>())
2350 MaxFieldAlignment = CharUnits::One();
2351}
2352
Warren Hunt8f8bad72013-10-11 20:19:00 +00002353void
2354MicrosoftRecordLayoutBuilder::initializeCXXLayout(const CXXRecordDecl *RD) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002355 HasZeroSizedSubObject = false;
Warren Hunt049f6732013-12-06 19:54:25 +00002356 LeadsWithZeroSizedBase = false;
Warren Huntd640d7d2014-01-09 00:30:56 +00002357 HasOwnVFPtr = false;
2358 HasVBPtr = false;
2359 PrimaryBase = 0;
2360 SharedVBPtrBase = 0;
2361 // Calculate pointer size and alignment. These are used for vfptr and vbprt
2362 // injection.
2363 PointerInfo.Size =
2364 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
2365 PointerInfo.Alignment = PointerInfo.Size;
2366 // Respect pragma pack.
2367 if (!MaxFieldAlignment.isZero())
2368 PointerInfo.Alignment = std::min(PointerInfo.Alignment, MaxFieldAlignment);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002369}
2370
2371void
2372MicrosoftRecordLayoutBuilder::layoutNonVirtualBases(const CXXRecordDecl *RD) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002373 // The MS-ABI lays out all bases that contain leading vfptrs before it lays
2374 // out any bases that do not contain vfptrs. We implement this as two passes
2375 // over the bases. This approach guarantees that the primary base is laid out
2376 // first. We use these passes to calculate some additional aggregated
2377 // information about the bases, such as reqruied alignment and the presence of
2378 // zero sized members.
2379 const ASTRecordLayout* PreviousBaseLayout = 0;
2380 // Iterate through the bases and lay out the non-virtual ones.
2381 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
2382 e = RD->bases_end();
2383 i != e; ++i) {
2384 const CXXRecordDecl *BaseDecl = i->getType()->getAsCXXRecordDecl();
2385 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
Warren Huntd640d7d2014-01-09 00:30:56 +00002386 // Mark and skip virtual bases.
2387 if (i->isVirtual()) {
2388 HasVBPtr = true;
2389 continue;
2390 }
David Majnemer79a1c892014-02-12 00:43:02 +00002391 // Track RequiredAlignment for all bases in this pass.
2392 RequiredAlignment = std::max(RequiredAlignment,
2393 BaseLayout.getRequiredAlignment());
Warren Huntd640d7d2014-01-09 00:30:56 +00002394 // Check fo a base to share a VBPtr with.
2395 if (!SharedVBPtrBase && BaseLayout.hasVBPtr()) {
2396 SharedVBPtrBase = BaseDecl;
2397 HasVBPtr = true;
2398 }
2399 // Only lay out bases with extendable VFPtrs on the first pass.
2400 if (!BaseLayout.hasExtendableVFPtr())
2401 continue;
2402 // If we don't have a primary base, this one qualifies.
Warren Huntbadf9e02014-01-13 19:55:52 +00002403 if (!PrimaryBase) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002404 PrimaryBase = BaseDecl;
Warren Huntbadf9e02014-01-13 19:55:52 +00002405 LeadsWithZeroSizedBase = BaseLayout.leadsWithZeroSizedBase();
2406 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002407 // Lay out the base.
2408 layoutNonVirtualBase(BaseDecl, BaseLayout, PreviousBaseLayout);
2409 }
2410 // Figure out if we need a fresh VFPtr for this class.
2411 if (!PrimaryBase && RD->isDynamicClass())
2412 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
2413 e = RD->method_end();
2414 !HasOwnVFPtr && i != e; ++i)
2415 HasOwnVFPtr = i->isVirtual() && i->size_overridden_methods() == 0;
2416 // If we don't have a primary base then we have a leading object that could
2417 // itself lead with a zero-sized object, something we track.
2418 bool CheckLeadingLayout = !PrimaryBase;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002419 // Iterate through the bases and lay out the non-virtual ones.
2420 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
2421 e = RD->bases_end();
2422 i != e; ++i) {
2423 if (i->isVirtual())
2424 continue;
Reid Klecknere7106c92013-12-18 23:17:05 +00002425 const CXXRecordDecl *BaseDecl = i->getType()->getAsCXXRecordDecl();
Warren Huntd640d7d2014-01-09 00:30:56 +00002426 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
2427 // Only lay out bases without extendable VFPtrs on the second pass.
2428 if (BaseLayout.hasExtendableVFPtr())
Warren Hunt4431fe62013-12-12 22:33:37 +00002429 continue;
Warren Huntd640d7d2014-01-09 00:30:56 +00002430 // If this is the first layout, check to see if it leads with a zero sized
2431 // object. If it does, so do we.
2432 if (CheckLeadingLayout) {
2433 CheckLeadingLayout = false;
2434 LeadsWithZeroSizedBase = BaseLayout.leadsWithZeroSizedBase();
Warren Hunt049f6732013-12-06 19:54:25 +00002435 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002436 // Lay out the base.
2437 layoutNonVirtualBase(BaseDecl, BaseLayout, PreviousBaseLayout);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002438 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002439 // Set our VBPtroffset if we know it at this point.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002440 if (!HasVBPtr)
2441 VBPtrOffset = CharUnits::fromQuantity(-1);
Warren Hunt6eba9072014-01-14 00:31:30 +00002442 else if (SharedVBPtrBase) {
2443 const ASTRecordLayout &Layout = Context.getASTRecordLayout(SharedVBPtrBase);
2444 VBPtrOffset = Bases[SharedVBPtrBase] + Layout.getVBPtrOffset();
2445 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002446}
2447
2448void MicrosoftRecordLayoutBuilder::layoutNonVirtualBase(
2449 const CXXRecordDecl *BaseDecl,
2450 const ASTRecordLayout &BaseLayout,
2451 const ASTRecordLayout *&PreviousBaseLayout) {
Warren Huntf4518def2014-01-10 01:28:05 +00002452 // Insert padding between two bases if the left first one is zero sized or
2453 // contains a zero sized subobject and the right is zero sized or one leads
2454 // with a zero sized base.
2455 if (PreviousBaseLayout && PreviousBaseLayout->hasZeroSizedSubObject() &&
2456 BaseLayout.leadsWithZeroSizedBase())
2457 Size++;
2458 ElementInfo Info = getAdjustedElementInfo(BaseLayout);
2459 CharUnits BaseOffset = Size.RoundUpToAlignment(Info.Alignment);
2460 Bases.insert(std::make_pair(BaseDecl, BaseOffset));
Warren Huntf6ec7482014-02-21 01:40:35 +00002461 Size = BaseOffset + BaseLayout.getNonVirtualSize();
Warren Huntf4518def2014-01-10 01:28:05 +00002462 PreviousBaseLayout = &BaseLayout;
Warren Huntd640d7d2014-01-09 00:30:56 +00002463 VBPtrOffset = Size;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002464}
2465
2466void MicrosoftRecordLayoutBuilder::layoutFields(const RecordDecl *RD) {
2467 LastFieldIsNonZeroWidthBitfield = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002468 for (const auto *Field : RD->fields())
2469 layoutField(Field);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002470}
2471
2472void MicrosoftRecordLayoutBuilder::layoutField(const FieldDecl *FD) {
2473 if (FD->isBitField()) {
2474 layoutBitField(FD);
2475 return;
2476 }
2477 LastFieldIsNonZeroWidthBitfield = false;
Warren Huntd640d7d2014-01-09 00:30:56 +00002478 ElementInfo Info = getAdjustedElementInfo(FD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002479 if (IsUnion) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002480 placeFieldAtOffset(CharUnits::Zero());
2481 Size = std::max(Size, Info.Size);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002482 } else {
Warren Huntd640d7d2014-01-09 00:30:56 +00002483 CharUnits FieldOffset = Size.RoundUpToAlignment(Info.Alignment);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002484 placeFieldAtOffset(FieldOffset);
Warren Huntd640d7d2014-01-09 00:30:56 +00002485 Size = FieldOffset + Info.Size;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002486 }
2487}
2488
2489void MicrosoftRecordLayoutBuilder::layoutBitField(const FieldDecl *FD) {
2490 unsigned Width = FD->getBitWidthValue(Context);
2491 if (Width == 0) {
2492 layoutZeroWidthBitField(FD);
2493 return;
2494 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002495 ElementInfo Info = getAdjustedElementInfo(FD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002496 // Clamp the bitfield to a containable size for the sake of being able
2497 // to lay them out. Sema will throw an error.
Warren Huntd640d7d2014-01-09 00:30:56 +00002498 if (Width > Context.toBits(Info.Size))
2499 Width = Context.toBits(Info.Size);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002500 // Check to see if this bitfield fits into an existing allocation. Note:
2501 // MSVC refuses to pack bitfields of formal types with different sizes
2502 // into the same allocation.
2503 if (!IsUnion && LastFieldIsNonZeroWidthBitfield &&
Warren Huntd640d7d2014-01-09 00:30:56 +00002504 CurrentBitfieldSize == Info.Size && Width <= RemainingBitsInField) {
Warren Hunt8f8bad72013-10-11 20:19:00 +00002505 placeFieldAtBitOffset(Context.toBits(Size) - RemainingBitsInField);
2506 RemainingBitsInField -= Width;
2507 return;
2508 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002509 LastFieldIsNonZeroWidthBitfield = true;
Warren Huntd640d7d2014-01-09 00:30:56 +00002510 CurrentBitfieldSize = Info.Size;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002511 if (IsUnion) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002512 placeFieldAtOffset(CharUnits::Zero());
2513 Size = std::max(Size, Info.Size);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002514 } else {
2515 // Allocate a new block of memory and place the bitfield in it.
Warren Huntd640d7d2014-01-09 00:30:56 +00002516 CharUnits FieldOffset = Size.RoundUpToAlignment(Info.Alignment);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002517 placeFieldAtOffset(FieldOffset);
Warren Huntd640d7d2014-01-09 00:30:56 +00002518 Size = FieldOffset + Info.Size;
Warren Huntd640d7d2014-01-09 00:30:56 +00002519 RemainingBitsInField = Context.toBits(Info.Size) - Width;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002520 }
2521}
2522
2523void
2524MicrosoftRecordLayoutBuilder::layoutZeroWidthBitField(const FieldDecl *FD) {
2525 // Zero-width bitfields are ignored unless they follow a non-zero-width
2526 // bitfield.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002527 if (!LastFieldIsNonZeroWidthBitfield) {
2528 placeFieldAtOffset(IsUnion ? CharUnits::Zero() : Size);
2529 // TODO: Add a Sema warning that MS ignores alignment for zero
Alp Tokerd4733632013-12-05 04:47:09 +00002530 // sized bitfields that occur after zero-size bitfields or non-bitfields.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002531 return;
2532 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002533 LastFieldIsNonZeroWidthBitfield = false;
Warren Huntd640d7d2014-01-09 00:30:56 +00002534 ElementInfo Info = getAdjustedElementInfo(FD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002535 if (IsUnion) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002536 placeFieldAtOffset(CharUnits::Zero());
2537 Size = std::max(Size, Info.Size);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002538 } else {
2539 // Round up the current record size to the field's alignment boundary.
Warren Huntd640d7d2014-01-09 00:30:56 +00002540 CharUnits FieldOffset = Size.RoundUpToAlignment(Info.Alignment);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002541 placeFieldAtOffset(FieldOffset);
2542 Size = FieldOffset;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002543 }
2544}
2545
Warren Huntd640d7d2014-01-09 00:30:56 +00002546void MicrosoftRecordLayoutBuilder::injectVBPtr(const CXXRecordDecl *RD) {
Warren Hunt6eba9072014-01-14 00:31:30 +00002547 if (!HasVBPtr || SharedVBPtrBase)
Warren Huntd640d7d2014-01-09 00:30:56 +00002548 return;
Warren Huntd640d7d2014-01-09 00:30:56 +00002549 // Inject the VBPointer at the injection site.
2550 CharUnits InjectionSite = VBPtrOffset;
2551 // But before we do, make sure it's properly aligned.
2552 VBPtrOffset = VBPtrOffset.RoundUpToAlignment(PointerInfo.Alignment);
2553 // Determine where the first field should be laid out after the vbptr.
2554 CharUnits FieldStart = VBPtrOffset + PointerInfo.Size;
2555 // Make sure that the amount we push the fields back by is a multiple of the
2556 // alignment.
David Majnemer79a1c892014-02-12 00:43:02 +00002557 CharUnits Offset = (FieldStart - InjectionSite).RoundUpToAlignment(
2558 std::max(RequiredAlignment, Alignment));
Warren Huntd640d7d2014-01-09 00:30:56 +00002559 // Increase the size of the object and push back all fields by the offset
2560 // amount.
2561 Size += Offset;
2562 for (SmallVector<uint64_t, 16>::iterator i = FieldOffsets.begin(),
2563 e = FieldOffsets.end();
2564 i != e; ++i)
2565 *i += Context.toBits(Offset);
2566 for (BaseOffsetsMapTy::iterator i = Bases.begin(), e = Bases.end();
2567 i != e; ++i)
2568 if (i->second >= InjectionSite)
2569 i->second += Offset;
Warren Huntd640d7d2014-01-09 00:30:56 +00002570}
2571
2572void MicrosoftRecordLayoutBuilder::injectVFPtr(const CXXRecordDecl *RD) {
2573 if (!HasOwnVFPtr)
2574 return;
2575 // Make sure that the amount we push the struct back by is a multiple of the
2576 // alignment.
David Majnemer79a1c892014-02-12 00:43:02 +00002577 CharUnits Offset = PointerInfo.Size.RoundUpToAlignment(
2578 std::max(RequiredAlignment, Alignment));
Warren Huntd640d7d2014-01-09 00:30:56 +00002579 // Increase the size of the object and push back all fields, the vbptr and all
2580 // bases by the offset amount.
2581 Size += Offset;
David Majnemer79a1c892014-02-12 00:43:02 +00002582 for (SmallVectorImpl<uint64_t>::iterator i = FieldOffsets.begin(),
Warren Huntd640d7d2014-01-09 00:30:56 +00002583 e = FieldOffsets.end();
2584 i != e; ++i)
2585 *i += Context.toBits(Offset);
2586 if (HasVBPtr)
2587 VBPtrOffset += Offset;
2588 for (BaseOffsetsMapTy::iterator i = Bases.begin(), e = Bases.end();
2589 i != e; ++i)
2590 i->second += Offset;
Warren Huntd640d7d2014-01-09 00:30:56 +00002591}
2592
2593void MicrosoftRecordLayoutBuilder::injectVPtrs(const CXXRecordDecl *RD) {
David Blaikie461f1ea2014-01-09 02:34:06 +00002594 if (!(HasOwnVFPtr || (HasVBPtr && !SharedVBPtrBase)))
Warren Huntd640d7d2014-01-09 00:30:56 +00002595 return;
2596 if (!Is64BitMode || RequiredAlignment <= CharUnits::fromQuantity(8)) {
2597 // Note that the VBPtr is injected first. It depends on the alignment of
2598 // the object *before* the alignment is updated by inserting a pointer into
2599 // the record.
2600 injectVBPtr(RD);
2601 injectVFPtr(RD);
Warren Hunt94258912014-01-11 01:16:40 +00002602 Alignment = std::max(Alignment, PointerInfo.Alignment);
Warren Huntd640d7d2014-01-09 00:30:56 +00002603 return;
2604 }
2605 // In 64-bit mode, structs with RequiredAlignment greater than 8 get special
2606 // layout rules. Likely this is to avoid excessive padding intruced around
2607 // the vfptrs and vbptrs. The special rules involve re-laying out the struct
2608 // and inserting the vfptr and vbptr as if they were fields/bases.
2609 FieldOffsets.clear();
2610 Bases.clear();
2611 Size = CharUnits::Zero();
Warren Hunt94258912014-01-11 01:16:40 +00002612 Alignment = std::max(Alignment, PointerInfo.Alignment);
Warren Huntd640d7d2014-01-09 00:30:56 +00002613 if (HasOwnVFPtr)
2614 Size = PointerInfo.Size;
2615 layoutNonVirtualBases(RD);
2616 if (HasVBPtr && !SharedVBPtrBase) {
2617 const CXXRecordDecl *PenultBaseDecl = 0;
2618 const CXXRecordDecl *LastBaseDecl = 0;
2619 // Iterate through the bases and find the last two non-virtual bases.
2620 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
2621 e = RD->bases_end();
2622 i != e; ++i) {
2623 if (i->isVirtual())
2624 continue;
2625 const CXXRecordDecl *BaseDecl = i->getType()->getAsCXXRecordDecl();
2626 if (!LastBaseDecl || Bases[BaseDecl] > Bases[LastBaseDecl]) {
2627 PenultBaseDecl = LastBaseDecl;
2628 LastBaseDecl = BaseDecl;
2629 }
2630 }
2631 const ASTRecordLayout *PenultBaseLayout = PenultBaseDecl ?
2632 &Context.getASTRecordLayout(PenultBaseDecl) : 0;
2633 const ASTRecordLayout *LastBaseLayout = LastBaseDecl ?
2634 &Context.getASTRecordLayout(LastBaseDecl) : 0;
2635 // Calculate the vbptr offset. The rule is different than in the general
2636 // case layout. Particularly, if the last two non-virtual bases are both
2637 // zero sized, the site of the vbptr is *before* the padding that occurs
2638 // between the two zero sized bases and the vbptr potentially aliases with
2639 // the first of these two bases. We have no understanding of why this is
2640 // different from the general case layout but it may have to do with lazy
2641 // placement of zero sized bases.
2642 VBPtrOffset = Size;
Warren Huntf6ec7482014-02-21 01:40:35 +00002643 if (LastBaseLayout && LastBaseLayout->getNonVirtualSize().isZero()) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002644 VBPtrOffset = Bases[LastBaseDecl];
Warren Huntf6ec7482014-02-21 01:40:35 +00002645 if (PenultBaseLayout && PenultBaseLayout->getNonVirtualSize().isZero())
Warren Huntd640d7d2014-01-09 00:30:56 +00002646 VBPtrOffset = Bases[PenultBaseDecl];
2647 }
2648 // Once we've located a spot for the vbptr, place it.
2649 VBPtrOffset = VBPtrOffset.RoundUpToAlignment(PointerInfo.Alignment);
2650 Size = VBPtrOffset + PointerInfo.Size;
Warren Huntf6ec7482014-02-21 01:40:35 +00002651 if (LastBaseLayout && LastBaseLayout->getNonVirtualSize().isZero()) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002652 // Add the padding between zero sized bases after the vbptr.
Warren Huntf6ec7482014-02-21 01:40:35 +00002653 if (PenultBaseLayout && PenultBaseLayout->getNonVirtualSize().isZero())
Warren Huntd640d7d2014-01-09 00:30:56 +00002654 Size += CharUnits::One();
2655 Size = Size.RoundUpToAlignment(LastBaseLayout->getRequiredAlignment());
2656 Bases[LastBaseDecl] = Size;
2657 }
2658 }
2659 layoutFields(RD);
Warren Hunt87c2b042014-01-10 23:32:32 +00002660 // The presence of a vbptr suppresses zero sized objects that are not in
2661 // virtual bases.
2662 HasZeroSizedSubObject = false;
Warren Hunt1603e522013-12-10 01:44:39 +00002663}
2664
Warren Hunt8f8bad72013-10-11 20:19:00 +00002665void MicrosoftRecordLayoutBuilder::layoutVirtualBases(const CXXRecordDecl *RD) {
2666 if (!HasVBPtr)
2667 return;
Warren Huntd640d7d2014-01-09 00:30:56 +00002668 // Vtordisps are always 4 bytes (even in 64-bit mode)
2669 CharUnits VtorDispSize = CharUnits::fromQuantity(4);
2670 CharUnits VtorDispAlignment = VtorDispSize;
2671 // vtordisps respect pragma pack.
2672 if (!MaxFieldAlignment.isZero())
2673 VtorDispAlignment = std::min(VtorDispAlignment, MaxFieldAlignment);
2674 // The alignment of the vtordisp is at least the required alignment of the
2675 // entire record. This requirement may be present to support vtordisp
2676 // injection.
David Majnemer79a1c892014-02-12 00:43:02 +00002677 for (CXXRecordDecl::base_class_const_iterator i = RD->vbases_begin(),
2678 e = RD->vbases_end();
2679 i != e; ++i) {
2680 const CXXRecordDecl *BaseDecl = i->getType()->getAsCXXRecordDecl();
2681 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
2682 RequiredAlignment =
2683 std::max(RequiredAlignment, BaseLayout.getRequiredAlignment());
2684 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002685 VtorDispAlignment = std::max(VtorDispAlignment, RequiredAlignment);
2686 // Compute the vtordisp set.
2687 llvm::SmallPtrSet<const CXXRecordDecl *, 2> HasVtordispSet =
Warren Hunt8f8bad72013-10-11 20:19:00 +00002688 computeVtorDispSet(RD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002689 // Iterate through the virtual bases and lay them out.
Warren Huntd640d7d2014-01-09 00:30:56 +00002690 const ASTRecordLayout* PreviousBaseLayout = 0;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002691 for (CXXRecordDecl::base_class_const_iterator i = RD->vbases_begin(),
2692 e = RD->vbases_end();
2693 i != e; ++i) {
Reid Klecknere7106c92013-12-18 23:17:05 +00002694 const CXXRecordDecl *BaseDecl = i->getType()->getAsCXXRecordDecl();
Warren Huntd640d7d2014-01-09 00:30:56 +00002695 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
2696 bool HasVtordisp = HasVtordispSet.count(BaseDecl);
Warren Hunt71140d62013-12-06 20:16:49 +00002697 // If the last field we laid out was a non-zero length bitfield then add
2698 // some extra padding for no obvious reason.
2699 if (LastFieldIsNonZeroWidthBitfield)
2700 Size += CurrentBitfieldSize;
Warren Huntd640d7d2014-01-09 00:30:56 +00002701 // Insert padding between two bases if the left first one is zero sized or
2702 // contains a zero sized subobject and the right is zero sized or one leads
2703 // with a zero sized base. The padding between virtual bases is 4
2704 // bytes (in both 32 and 64 bits modes) and always involves rounding up to
2705 // the required alignment, we don't know why.
2706 if (PreviousBaseLayout && PreviousBaseLayout->hasZeroSizedSubObject() &&
2707 BaseLayout.leadsWithZeroSizedBase())
2708 Size = Size.RoundUpToAlignment(VtorDispAlignment) + VtorDispSize;
2709 // Insert the vtordisp.
2710 if (HasVtordisp)
2711 Size = Size.RoundUpToAlignment(VtorDispAlignment) + VtorDispSize;
2712 // Insert the virtual base.
Warren Huntf6ec7482014-02-21 01:40:35 +00002713 HasZeroSizedSubObject = false;
Warren Huntd640d7d2014-01-09 00:30:56 +00002714 ElementInfo Info = getAdjustedElementInfo(BaseLayout);
Warren Huntf4518def2014-01-10 01:28:05 +00002715 CharUnits BaseOffset = Size.RoundUpToAlignment(Info.Alignment);
Warren Huntd640d7d2014-01-09 00:30:56 +00002716 VBases.insert(std::make_pair(BaseDecl,
2717 ASTRecordLayout::VBaseInfo(BaseOffset, HasVtordisp)));
Warren Huntf6ec7482014-02-21 01:40:35 +00002718 Size = BaseOffset + BaseLayout.getNonVirtualSize();
Warren Huntd640d7d2014-01-09 00:30:56 +00002719 PreviousBaseLayout = &BaseLayout;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002720 }
2721}
2722
Warren Huntc3384312013-12-11 22:28:32 +00002723void MicrosoftRecordLayoutBuilder::finalizeLayout(const RecordDecl *RD) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002724 // Respect required alignment. Note that in 32-bit mode Required alignment
2725 // may be 0 nad cause size not to be updated.
Warren Huntf6ec7482014-02-21 01:40:35 +00002726 DataSize = Size;
Warren Huntd640d7d2014-01-09 00:30:56 +00002727 if (!RequiredAlignment.isZero()) {
2728 Alignment = std::max(Alignment, RequiredAlignment);
2729 Size = Size.RoundUpToAlignment(Alignment);
2730 }
2731 // Zero-sized structures have size equal to their alignment.
Warren Hunt049f6732013-12-06 19:54:25 +00002732 if (Size.isZero()) {
2733 HasZeroSizedSubObject = true;
2734 LeadsWithZeroSizedBase = true;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002735 Size = Alignment;
Warren Hunt049f6732013-12-06 19:54:25 +00002736 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002737}
2738
2739static bool
2740RequiresVtordisp(const llvm::SmallPtrSet<const CXXRecordDecl *, 2> &HasVtordisp,
2741 const CXXRecordDecl *RD) {
2742 if (HasVtordisp.count(RD))
2743 return true;
2744 // If any of a virtual bases non-virtual bases (recursively) requires a
2745 // vtordisp than so does this virtual base.
2746 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
2747 e = RD->bases_end();
2748 i != e; ++i)
2749 if (!i->isVirtual() &&
2750 RequiresVtordisp(
2751 HasVtordisp,
2752 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl())))
2753 return true;
2754 return false;
2755}
2756
2757llvm::SmallPtrSet<const CXXRecordDecl *, 2>
2758MicrosoftRecordLayoutBuilder::computeVtorDispSet(const CXXRecordDecl *RD) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002759 llvm::SmallPtrSet<const CXXRecordDecl *, 2> HasVtordispSet;
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00002760
2761 // /vd0 or #pragma vtordisp(0): Never use vtordisps when used as a vbase.
2762 if (RD->getMSVtorDispMode() == MSVtorDispAttr::Never)
2763 return HasVtordispSet;
2764
2765 // /vd2 or #pragma vtordisp(2): Always use vtordisps for virtual bases with
2766 // vftables.
2767 if (RD->getMSVtorDispMode() == MSVtorDispAttr::ForVFTable) {
2768 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
2769 E = RD->vbases_end();
2770 I != E; ++I) {
2771 const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
2772 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
2773 if (Layout.hasExtendableVFPtr())
2774 HasVtordispSet.insert(BaseDecl);
2775 }
2776 return HasVtordispSet;
2777 }
2778
2779 // /vd1 or #pragma vtordisp(1): Try to guess based on whether we think it's
2780 // possible for a partially constructed object with virtual base overrides to
2781 // escape a non-trivial constructor.
2782 assert(RD->getMSVtorDispMode() == MSVtorDispAttr::ForVBaseOverride);
2783
Warren Hunt8f8bad72013-10-11 20:19:00 +00002784 // If any of our bases need a vtordisp for this type, so do we. Check our
2785 // direct bases for vtordisp requirements.
2786 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
2787 e = RD->bases_end();
2788 i != e; ++i) {
2789 const CXXRecordDecl *BaseDecl =
2790 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
2791 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
2792 for (ASTRecordLayout::VBaseOffsetsMapTy::const_iterator
2793 bi = Layout.getVBaseOffsetsMap().begin(),
2794 be = Layout.getVBaseOffsetsMap().end();
2795 bi != be; ++bi)
2796 if (bi->second.hasVtorDisp())
Warren Huntd640d7d2014-01-09 00:30:56 +00002797 HasVtordispSet.insert(bi->first);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002798 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002799 // If we define a constructor or destructor and override a function that is
2800 // defined in a virtual base's vtable, that virtual bases need a vtordisp.
2801 // Here we collect a list of classes with vtables for which our virtual bases
2802 // actually live. The virtual bases with this property will require
2803 // vtordisps. In addition, virtual bases that contain non-virtual bases that
2804 // define functions we override also require vtordisps, this case is checked
2805 // explicitly below.
2806 if (RD->hasUserDeclaredConstructor() || RD->hasUserDeclaredDestructor()) {
2807 llvm::SmallPtrSet<const CXXMethodDecl *, 8> Work;
2808 // Seed the working set with our non-destructor virtual methods.
2809 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
2810 e = RD->method_end();
2811 i != e; ++i)
Warren Hunt42be7762013-10-14 20:14:09 +00002812 if ((*i)->isVirtual() && !isa<CXXDestructorDecl>(*i))
Warren Hunt8f8bad72013-10-11 20:19:00 +00002813 Work.insert(*i);
2814 while (!Work.empty()) {
2815 const CXXMethodDecl *MD = *Work.begin();
2816 CXXMethodDecl::method_iterator i = MD->begin_overridden_methods(),
2817 e = MD->end_overridden_methods();
2818 if (i == e)
2819 // If a virtual method has no-overrides it lives in its parent's vtable.
Warren Huntd640d7d2014-01-09 00:30:56 +00002820 HasVtordispSet.insert(MD->getParent());
Warren Hunt8f8bad72013-10-11 20:19:00 +00002821 else
2822 Work.insert(i, e);
2823 // We've finished processing this element, remove it from the working set.
2824 Work.erase(MD);
2825 }
2826 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002827 // Re-check all of our vbases for vtordisp requirements (in case their
2828 // non-virtual bases have vtordisp requirements).
2829 for (CXXRecordDecl::base_class_const_iterator i = RD->vbases_begin(),
2830 e = RD->vbases_end();
2831 i != e; ++i) {
2832 const CXXRecordDecl *BaseDecl = i->getType()->getAsCXXRecordDecl();
Warren Huntd640d7d2014-01-09 00:30:56 +00002833 if (!HasVtordispSet.count(BaseDecl) &&
2834 RequiresVtordisp(HasVtordispSet, BaseDecl))
2835 HasVtordispSet.insert(BaseDecl);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002836 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002837 return HasVtordispSet;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002838}
2839
2840/// \brief Get or compute information about the layout of the specified record
2841/// (struct/union/class), which indicates its size and field position
2842/// information.
2843const ASTRecordLayout *
2844ASTContext::BuildMicrosoftASTRecordLayout(const RecordDecl *D) const {
2845 MicrosoftRecordLayoutBuilder Builder(*this);
2846 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
2847 Builder.cxxLayout(RD);
2848 return new (*this) ASTRecordLayout(
Warren Hunt7b252d22013-12-06 00:01:17 +00002849 *this, Builder.Size, Builder.Alignment, Builder.RequiredAlignment,
Warren Huntd640d7d2014-01-09 00:30:56 +00002850 Builder.HasOwnVFPtr,
2851 Builder.HasOwnVFPtr || Builder.PrimaryBase,
Warren Huntf6ec7482014-02-21 01:40:35 +00002852 Builder.VBPtrOffset, Builder.NonVirtualSize, Builder.FieldOffsets.data(),
2853 Builder.FieldOffsets.size(), Builder.NonVirtualSize,
Warren Huntd640d7d2014-01-09 00:30:56 +00002854 Builder.Alignment, CharUnits::Zero(), Builder.PrimaryBase,
Warren Hunt049f6732013-12-06 19:54:25 +00002855 false, Builder.SharedVBPtrBase,
2856 Builder.HasZeroSizedSubObject, Builder.LeadsWithZeroSizedBase,
2857 Builder.Bases, Builder.VBases);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002858 } else {
2859 Builder.layout(D);
2860 return new (*this) ASTRecordLayout(
Warren Hunt7b252d22013-12-06 00:01:17 +00002861 *this, Builder.Size, Builder.Alignment, Builder.RequiredAlignment,
2862 Builder.Size, Builder.FieldOffsets.data(), Builder.FieldOffsets.size());
Warren Hunt8f8bad72013-10-11 20:19:00 +00002863 }
2864}
2865
Anders Carlssondf291d82010-05-26 04:56:53 +00002866/// getASTRecordLayout - Get or compute information about the layout of the
2867/// specified record (struct/union/class), which indicates its size and field
2868/// position information.
Jay Foad39c79802011-01-12 09:06:06 +00002869const ASTRecordLayout &
2870ASTContext::getASTRecordLayout(const RecordDecl *D) const {
John McCall0710e552011-10-07 02:39:22 +00002871 // These asserts test different things. A record has a definition
2872 // as soon as we begin to parse the definition. That definition is
2873 // not a complete definition (which is what isDefinition() tests)
2874 // until we *finish* parsing the definition.
Sean Callanan56c19892012-02-08 00:04:52 +00002875
2876 if (D->hasExternalLexicalStorage() && !D->getDefinition())
2877 getExternalSource()->CompleteType(const_cast<RecordDecl*>(D));
2878
Anders Carlssondf291d82010-05-26 04:56:53 +00002879 D = D->getDefinition();
2880 assert(D && "Cannot get layout of forward declarations!");
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00002881 assert(!D->isInvalidDecl() && "Cannot get layout of invalid decl!");
John McCallf937c022011-10-07 06:10:15 +00002882 assert(D->isCompleteDefinition() && "Cannot layout type before complete!");
Anders Carlssondf291d82010-05-26 04:56:53 +00002883
2884 // Look up this layout, if already laid out, return what we have.
2885 // Note that we can't save a reference to the entry because this function
2886 // is recursive.
2887 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
2888 if (Entry) return *Entry;
2889
Warren Hunt8f8bad72013-10-11 20:19:00 +00002890 const ASTRecordLayout *NewEntry = 0;
Anders Carlssond2954862010-05-26 05:10:47 +00002891
Reid Kleckneraf1465c2014-02-20 23:07:29 +00002892 if (isMsLayout(D) && !D->getASTContext().getExternalSource()) {
Warren Hunt8f8bad72013-10-11 20:19:00 +00002893 NewEntry = BuildMicrosoftASTRecordLayout(D);
2894 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
Anders Carlssonc121b4e2010-05-27 00:07:01 +00002895 EmptySubobjectMap EmptySubobjects(*this, RD);
John McCall0153cd32011-11-08 04:01:03 +00002896 RecordLayoutBuilder Builder(*this, &EmptySubobjects);
2897 Builder.Layout(RD);
Anders Carlsson439edd12010-05-27 05:41:06 +00002898
John McCall5c1f1d02013-01-29 01:14:22 +00002899 // In certain situations, we are allowed to lay out objects in the
2900 // tail-padding of base classes. This is ABI-dependent.
2901 // FIXME: this should be stored in the record layout.
2902 bool skipTailPadding =
2903 mustSkipTailPadding(getTargetInfo().getCXXABI(), cast<CXXRecordDecl>(D));
Anders Carlssond2954862010-05-26 05:10:47 +00002904
2905 // FIXME: This should be done in FinalizeLayout.
Ken Dyck1b4420e2011-02-28 02:01:38 +00002906 CharUnits DataSize =
John McCall5c1f1d02013-01-29 01:14:22 +00002907 skipTailPadding ? Builder.getSize() : Builder.getDataSize();
Ken Dyck1b4420e2011-02-28 02:01:38 +00002908 CharUnits NonVirtualSize =
John McCall5c1f1d02013-01-29 01:14:22 +00002909 skipTailPadding ? DataSize : Builder.NonVirtualSize;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002910 NewEntry =
John McCall0153cd32011-11-08 04:01:03 +00002911 new (*this) ASTRecordLayout(*this, Builder.getSize(),
2912 Builder.Alignment,
Warren Hunt7b252d22013-12-06 00:01:17 +00002913 /*RequiredAlignment : used by MS-ABI)*/
2914 Builder.Alignment,
John McCalle42a3362012-05-01 08:55:32 +00002915 Builder.HasOwnVFPtr,
Warren Hunt8f8bad72013-10-11 20:19:00 +00002916 RD->isDynamicClass(),
Warren Hunt55d8e822013-10-23 23:53:07 +00002917 CharUnits::fromQuantity(-1),
Ken Dyck1b4420e2011-02-28 02:01:38 +00002918 DataSize,
John McCall0153cd32011-11-08 04:01:03 +00002919 Builder.FieldOffsets.data(),
2920 Builder.FieldOffsets.size(),
Ken Dyckaf1c83f2011-02-16 01:52:01 +00002921 NonVirtualSize,
John McCall0153cd32011-11-08 04:01:03 +00002922 Builder.NonVirtualAlignment,
Anders Carlssonc121b4e2010-05-27 00:07:01 +00002923 EmptySubobjects.SizeOfLargestEmptySubobject,
John McCall0153cd32011-11-08 04:01:03 +00002924 Builder.PrimaryBase,
2925 Builder.PrimaryBaseIsVirtual,
Warren Hunt049f6732013-12-06 19:54:25 +00002926 0, false, false,
John McCall0153cd32011-11-08 04:01:03 +00002927 Builder.Bases, Builder.VBases);
Anders Carlssond2954862010-05-26 05:10:47 +00002928 } else {
John McCall0153cd32011-11-08 04:01:03 +00002929 RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/0);
Anders Carlssond2954862010-05-26 05:10:47 +00002930 Builder.Layout(D);
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002931
Anders Carlssond2954862010-05-26 05:10:47 +00002932 NewEntry =
Ken Dyck1b4420e2011-02-28 02:01:38 +00002933 new (*this) ASTRecordLayout(*this, Builder.getSize(),
Ken Dyck4731d5b2011-02-16 02:05:21 +00002934 Builder.Alignment,
Warren Hunt7b252d22013-12-06 00:01:17 +00002935 /*RequiredAlignment : used by MS-ABI)*/
2936 Builder.Alignment,
Ken Dyck1b4420e2011-02-28 02:01:38 +00002937 Builder.getSize(),
Anders Carlssond2954862010-05-26 05:10:47 +00002938 Builder.FieldOffsets.data(),
2939 Builder.FieldOffsets.size());
2940 }
2941
Anders Carlssondf291d82010-05-26 04:56:53 +00002942 ASTRecordLayouts[D] = NewEntry;
2943
David Blaikiebbafb8a2012-03-11 07:00:24 +00002944 if (getLangOpts().DumpRecordLayouts) {
Argyrios Kyrtzidis8ade08e2013-07-12 22:30:03 +00002945 llvm::outs() << "\n*** Dumping AST Record Layout\n";
2946 DumpRecordLayout(D, llvm::outs(), getLangOpts().DumpRecordLayoutsSimple);
Anders Carlssondf291d82010-05-26 04:56:53 +00002947 }
2948
2949 return *NewEntry;
2950}
2951
John McCall6bd2a892013-01-25 22:31:03 +00002952const CXXMethodDecl *ASTContext::getCurrentKeyFunction(const CXXRecordDecl *RD) {
Reid Kleckner5d7f2982013-05-29 16:18:30 +00002953 if (!getTargetInfo().getCXXABI().hasKeyFunctions())
2954 return 0;
2955
John McCall6bd2a892013-01-25 22:31:03 +00002956 assert(RD->getDefinition() && "Cannot get key function for forward decl!");
Anders Carlssondf291d82010-05-26 04:56:53 +00002957 RD = cast<CXXRecordDecl>(RD->getDefinition());
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002958
Richard Smith676c4042013-08-29 23:59:27 +00002959 LazyDeclPtr &Entry = KeyFunctions[RD];
2960 if (!Entry)
2961 Entry = const_cast<CXXMethodDecl*>(computeKeyFunction(*this, RD));
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002962
Richard Smith676c4042013-08-29 23:59:27 +00002963 return cast_or_null<CXXMethodDecl>(Entry.get(getExternalSource()));
John McCall6bd2a892013-01-25 22:31:03 +00002964}
2965
Richard Smith676c4042013-08-29 23:59:27 +00002966void ASTContext::setNonKeyFunction(const CXXMethodDecl *Method) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002967 assert(Method == Method->getFirstDecl() &&
John McCall6bd2a892013-01-25 22:31:03 +00002968 "not working with method declaration from class definition");
2969
2970 // Look up the cache entry. Since we're working with the first
2971 // declaration, its parent must be the class definition, which is
2972 // the correct key for the KeyFunctions hash.
Richard Smith676c4042013-08-29 23:59:27 +00002973 llvm::DenseMap<const CXXRecordDecl*, LazyDeclPtr>::iterator
2974 I = KeyFunctions.find(Method->getParent());
John McCall6bd2a892013-01-25 22:31:03 +00002975
2976 // If it's not cached, there's nothing to do.
Richard Smith676c4042013-08-29 23:59:27 +00002977 if (I == KeyFunctions.end()) return;
John McCall6bd2a892013-01-25 22:31:03 +00002978
2979 // If it is cached, check whether it's the target method, and if so,
2980 // remove it from the cache.
Richard Smith676c4042013-08-29 23:59:27 +00002981 if (I->second.get(getExternalSource()) == Method) {
John McCall6bd2a892013-01-25 22:31:03 +00002982 // FIXME: remember that we did this for module / chained PCH state?
Richard Smith676c4042013-08-29 23:59:27 +00002983 KeyFunctions.erase(I);
John McCall6bd2a892013-01-25 22:31:03 +00002984 }
Anders Carlssondf291d82010-05-26 04:56:53 +00002985}
2986
Richard Smithdafff942012-01-14 04:30:29 +00002987static uint64_t getFieldOffset(const ASTContext &C, const FieldDecl *FD) {
2988 const ASTRecordLayout &Layout = C.getASTRecordLayout(FD->getParent());
2989 return Layout.getFieldOffset(FD->getFieldIndex());
2990}
2991
2992uint64_t ASTContext::getFieldOffset(const ValueDecl *VD) const {
2993 uint64_t OffsetInBits;
2994 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
2995 OffsetInBits = ::getFieldOffset(*this, FD);
2996 } else {
2997 const IndirectFieldDecl *IFD = cast<IndirectFieldDecl>(VD);
2998
2999 OffsetInBits = 0;
Aaron Ballman29c94602014-03-07 18:36:15 +00003000 for (const auto *CI : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00003001 OffsetInBits += ::getFieldOffset(*this, cast<FieldDecl>(CI));
Richard Smithdafff942012-01-14 04:30:29 +00003002 }
3003
3004 return OffsetInBits;
3005}
3006
Eric Christopher8a39a012011-10-05 06:00:51 +00003007/// getObjCLayout - Get or compute information about the layout of the
3008/// given interface.
Anders Carlssondf291d82010-05-26 04:56:53 +00003009///
3010/// \param Impl - If given, also include the layout of the interface's
3011/// implementation. This may differ by including synthesized ivars.
3012const ASTRecordLayout &
3013ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
Jay Foad39c79802011-01-12 09:06:06 +00003014 const ObjCImplementationDecl *Impl) const {
Douglas Gregor64d92572011-12-20 15:50:13 +00003015 // Retrieve the definition
Sean Callanand9a909c2012-03-15 16:33:08 +00003016 if (D->hasExternalLexicalStorage() && !D->getDefinition())
3017 getExternalSource()->CompleteType(const_cast<ObjCInterfaceDecl*>(D));
Douglas Gregor64d92572011-12-20 15:50:13 +00003018 D = D->getDefinition();
3019 assert(D && D->isThisDeclarationADefinition() && "Invalid interface decl!");
Anders Carlssondf291d82010-05-26 04:56:53 +00003020
3021 // Look up this layout, if already laid out, return what we have.
Roman Divackye6377112012-09-06 15:59:27 +00003022 const ObjCContainerDecl *Key =
3023 Impl ? (const ObjCContainerDecl*) Impl : (const ObjCContainerDecl*) D;
Anders Carlssondf291d82010-05-26 04:56:53 +00003024 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
3025 return *Entry;
3026
3027 // Add in synthesized ivar count if laying out an implementation.
3028 if (Impl) {
3029 unsigned SynthCount = CountNonClassIvars(D);
3030 // If there aren't any sythesized ivars then reuse the interface
3031 // entry. Note we can't cache this because we simply free all
3032 // entries later; however we shouldn't look up implementations
3033 // frequently.
3034 if (SynthCount == 0)
3035 return getObjCLayout(D, 0);
3036 }
3037
John McCall0153cd32011-11-08 04:01:03 +00003038 RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/0);
Anders Carlsson6ed3a9a2010-05-26 05:04:25 +00003039 Builder.Layout(D);
3040
Anders Carlssondf291d82010-05-26 04:56:53 +00003041 const ASTRecordLayout *NewEntry =
Ken Dyck1b4420e2011-02-28 02:01:38 +00003042 new (*this) ASTRecordLayout(*this, Builder.getSize(),
Ken Dyck4731d5b2011-02-16 02:05:21 +00003043 Builder.Alignment,
Warren Hunt7b252d22013-12-06 00:01:17 +00003044 /*RequiredAlignment : used by MS-ABI)*/
3045 Builder.Alignment,
Ken Dyck1b4420e2011-02-28 02:01:38 +00003046 Builder.getDataSize(),
Anders Carlsson6ed3a9a2010-05-26 05:04:25 +00003047 Builder.FieldOffsets.data(),
3048 Builder.FieldOffsets.size());
Daniel Dunbar592a85c2010-05-27 02:25:46 +00003049
Anders Carlssondf291d82010-05-26 04:56:53 +00003050 ObjCLayouts[Key] = NewEntry;
3051
3052 return *NewEntry;
3053}
3054
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003055static void PrintOffset(raw_ostream &OS,
Anders Carlsson3f018712010-10-31 23:45:59 +00003056 CharUnits Offset, unsigned IndentLevel) {
Benjamin Kramer96ad7172011-11-05 09:02:52 +00003057 OS << llvm::format("%4" PRId64 " | ", (int64_t)Offset.getQuantity());
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003058 OS.indent(IndentLevel * 2);
3059}
3060
Eli Benderskyf6f93ee2012-12-08 00:07:24 +00003061static void PrintIndentNoOffset(raw_ostream &OS, unsigned IndentLevel) {
3062 OS << " | ";
3063 OS.indent(IndentLevel * 2);
3064}
3065
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003066static void DumpCXXRecordLayout(raw_ostream &OS,
Jay Foad39c79802011-01-12 09:06:06 +00003067 const CXXRecordDecl *RD, const ASTContext &C,
Anders Carlsson3f018712010-10-31 23:45:59 +00003068 CharUnits Offset,
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003069 unsigned IndentLevel,
3070 const char* Description,
3071 bool IncludeVirtualBases) {
Anders Carlsson3f018712010-10-31 23:45:59 +00003072 const ASTRecordLayout &Layout = C.getASTRecordLayout(RD);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003073
3074 PrintOffset(OS, Offset, IndentLevel);
Dan Gohman145f3f12010-04-19 16:39:44 +00003075 OS << C.getTypeDeclType(const_cast<CXXRecordDecl *>(RD)).getAsString();
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003076 if (Description)
3077 OS << ' ' << Description;
3078 if (RD->isEmpty())
3079 OS << " (empty)";
3080 OS << '\n';
3081
3082 IndentLevel++;
3083
Anders Carlsson3f018712010-10-31 23:45:59 +00003084 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
Warren Hunt8f8bad72013-10-11 20:19:00 +00003085 bool HasOwnVFPtr = Layout.hasOwnVFPtr();
3086 bool HasOwnVBPtr = Layout.hasOwnVBPtr();
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003087
3088 // Vtable pointer.
Warren Hunt8f8bad72013-10-11 20:19:00 +00003089 if (RD->isDynamicClass() && !PrimaryBase && !isMsLayout(RD)) {
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003090 PrintOffset(OS, Offset, IndentLevel);
Benjamin Kramerb89514a2011-10-14 18:45:37 +00003091 OS << '(' << *RD << " vtable pointer)\n";
Warren Hunt8f8bad72013-10-11 20:19:00 +00003092 } else if (HasOwnVFPtr) {
3093 PrintOffset(OS, Offset, IndentLevel);
3094 // vfptr (for Microsoft C++ ABI)
3095 OS << '(' << *RD << " vftable pointer)\n";
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003096 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00003097
Reid Klecknerad59deb2014-02-28 01:03:09 +00003098 // Collect nvbases.
3099 SmallVector<const CXXRecordDecl *, 4> Bases;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003100 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
Reid Klecknerad59deb2014-02-28 01:03:09 +00003101 E = RD->bases_end();
3102 I != E; ++I) {
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003103 assert(!I->getType()->isDependentType() &&
3104 "Cannot layout class with dependent bases.");
Reid Klecknerad59deb2014-02-28 01:03:09 +00003105 if (!I->isVirtual())
3106 Bases.push_back(I->getType()->getAsCXXRecordDecl());
3107 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003108
Reid Klecknerad59deb2014-02-28 01:03:09 +00003109 // Sort nvbases by offset.
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00003110 std::stable_sort(Bases.begin(), Bases.end(),
3111 [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
3112 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
3113 });
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003114
Reid Klecknerad59deb2014-02-28 01:03:09 +00003115 // Dump (non-virtual) bases
3116 for (SmallVectorImpl<const CXXRecordDecl *>::iterator I = Bases.begin(),
3117 E = Bases.end();
3118 I != E; ++I) {
3119 const CXXRecordDecl *Base = *I;
Anders Carlsson3f018712010-10-31 23:45:59 +00003120 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003121 DumpCXXRecordLayout(OS, Base, C, BaseOffset, IndentLevel,
3122 Base == PrimaryBase ? "(primary base)" : "(base)",
3123 /*IncludeVirtualBases=*/false);
3124 }
Eli Friedman43114f92011-10-21 22:49:56 +00003125
Warren Hunt8f8bad72013-10-11 20:19:00 +00003126 // vbptr (for Microsoft C++ ABI)
3127 if (HasOwnVBPtr) {
Eli Friedman84d2d3a2011-09-27 19:12:27 +00003128 PrintOffset(OS, Offset + Layout.getVBPtrOffset(), IndentLevel);
Benjamin Kramerb89514a2011-10-14 18:45:37 +00003129 OS << '(' << *RD << " vbtable pointer)\n";
Eli Friedman84d2d3a2011-09-27 19:12:27 +00003130 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003131
3132 // Dump fields.
3133 uint64_t FieldNo = 0;
3134 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
3135 E = RD->field_end(); I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +00003136 const FieldDecl &Field = **I;
Anders Carlsson3f018712010-10-31 23:45:59 +00003137 CharUnits FieldOffset = Offset +
Ken Dyck86a7fcc2011-01-18 01:56:16 +00003138 C.toCharUnitsFromBits(Layout.getFieldOffset(FieldNo));
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003139
David Blaikie2d7c57e2012-04-30 02:36:29 +00003140 if (const RecordType *RT = Field.getType()->getAs<RecordType>()) {
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003141 if (const CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3142 DumpCXXRecordLayout(OS, D, C, FieldOffset, IndentLevel,
David Blaikie2d7c57e2012-04-30 02:36:29 +00003143 Field.getName().data(),
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003144 /*IncludeVirtualBases=*/true);
3145 continue;
3146 }
3147 }
3148
3149 PrintOffset(OS, FieldOffset, IndentLevel);
David Blaikie2d7c57e2012-04-30 02:36:29 +00003150 OS << Field.getType().getAsString() << ' ' << Field << '\n';
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003151 }
3152
3153 if (!IncludeVirtualBases)
3154 return;
3155
3156 // Dump virtual bases.
John McCalle42a3362012-05-01 08:55:32 +00003157 const ASTRecordLayout::VBaseOffsetsMapTy &vtordisps =
3158 Layout.getVBaseOffsetsMap();
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003159 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
3160 E = RD->vbases_end(); I != E; ++I) {
3161 assert(I->isVirtual() && "Found non-virtual class!");
3162 const CXXRecordDecl *VBase =
3163 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
3164
Anders Carlsson3f018712010-10-31 23:45:59 +00003165 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBase);
John McCalle42a3362012-05-01 08:55:32 +00003166
3167 if (vtordisps.find(VBase)->second.hasVtorDisp()) {
3168 PrintOffset(OS, VBaseOffset - CharUnits::fromQuantity(4), IndentLevel);
3169 OS << "(vtordisp for vbase " << *VBase << ")\n";
3170 }
3171
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003172 DumpCXXRecordLayout(OS, VBase, C, VBaseOffset, IndentLevel,
3173 VBase == PrimaryBase ?
3174 "(primary virtual base)" : "(virtual base)",
3175 /*IncludeVirtualBases=*/false);
3176 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003177
Eli Benderskyf6f93ee2012-12-08 00:07:24 +00003178 PrintIndentNoOffset(OS, IndentLevel - 1);
3179 OS << "[sizeof=" << Layout.getSize().getQuantity();
Warren Hunt8f8bad72013-10-11 20:19:00 +00003180 if (!isMsLayout(RD))
3181 OS << ", dsize=" << Layout.getDataSize().getQuantity();
Ken Dyck7ad11e72011-02-15 02:32:40 +00003182 OS << ", align=" << Layout.getAlignment().getQuantity() << '\n';
Eli Benderskyf6f93ee2012-12-08 00:07:24 +00003183
3184 PrintIndentNoOffset(OS, IndentLevel - 1);
3185 OS << " nvsize=" << Layout.getNonVirtualSize().getQuantity();
Warren Huntd640d7d2014-01-09 00:30:56 +00003186 OS << ", nvalign=" << Layout.getNonVirtualAlignment().getQuantity() << "]\n";
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003187 OS << '\n';
3188}
Daniel Dunbarccabe482010-04-19 20:44:53 +00003189
3190void ASTContext::DumpRecordLayout(const RecordDecl *RD,
Douglas Gregore9fc3772012-01-26 07:55:45 +00003191 raw_ostream &OS,
3192 bool Simple) const {
Daniel Dunbarccabe482010-04-19 20:44:53 +00003193 const ASTRecordLayout &Info = getASTRecordLayout(RD);
3194
3195 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Douglas Gregore9fc3772012-01-26 07:55:45 +00003196 if (!Simple)
3197 return DumpCXXRecordLayout(OS, CXXRD, *this, CharUnits(), 0, 0,
3198 /*IncludeVirtualBases=*/true);
Daniel Dunbarccabe482010-04-19 20:44:53 +00003199
3200 OS << "Type: " << getTypeDeclType(RD).getAsString() << "\n";
Douglas Gregore9fc3772012-01-26 07:55:45 +00003201 if (!Simple) {
3202 OS << "Record: ";
3203 RD->dump();
3204 }
Daniel Dunbarccabe482010-04-19 20:44:53 +00003205 OS << "\nLayout: ";
3206 OS << "<ASTRecordLayout\n";
Ken Dyckb0fcc592011-02-11 01:54:29 +00003207 OS << " Size:" << toBits(Info.getSize()) << "\n";
Warren Hunt8f8bad72013-10-11 20:19:00 +00003208 if (!isMsLayout(RD))
3209 OS << " DataSize:" << toBits(Info.getDataSize()) << "\n";
Ken Dyck7ad11e72011-02-15 02:32:40 +00003210 OS << " Alignment:" << toBits(Info.getAlignment()) << "\n";
Daniel Dunbarccabe482010-04-19 20:44:53 +00003211 OS << " FieldOffsets: [";
3212 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i) {
3213 if (i) OS << ", ";
3214 OS << Info.getFieldOffset(i);
3215 }
3216 OS << "]>\n";
3217}