blob: 3a91c6be91de4e9fadb9a12ca1342192c29ca151 [file] [log] [blame]
Anders Carlsson35a36eb2010-05-26 05:41:04 +00001//=== RecordLayoutBuilder.cpp - Helper class for building record layouts ---==//
Anders Carlsson79474332009-07-18 20:20:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Chandler Carruth3a022472012-12-04 09:13:33 +000010#include "clang/AST/RecordLayout.h"
Benjamin Kramer2ef30312012-07-04 18:45:14 +000011#include "clang/AST/ASTContext.h"
Anders Carlsson79474332009-07-18 20:20:21 +000012#include "clang/AST/Attr.h"
Anders Carlsson5adde292010-11-24 22:55:48 +000013#include "clang/AST/CXXInheritance.h"
Anders Carlsson79474332009-07-18 20:20:21 +000014#include "clang/AST/Decl.h"
Anders Carlsson6d9f6f32009-07-19 00:18:47 +000015#include "clang/AST/DeclCXX.h"
Anders Carlsson4f516282009-07-18 20:50:59 +000016#include "clang/AST/DeclObjC.h"
Anders Carlsson79474332009-07-18 20:20:21 +000017#include "clang/AST/Expr.h"
Anders Carlsson79474332009-07-18 20:20:21 +000018#include "clang/Basic/TargetInfo.h"
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +000019#include "clang/Sema/SemaDiagnostic.h"
Daniel Dunbaraa423af2010-04-08 02:59:49 +000020#include "llvm/ADT/SmallSet.h"
Ted Kremenekf75d0892011-03-19 01:00:36 +000021#include "llvm/Support/CrashRecoveryContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "llvm/Support/Format.h"
23#include "llvm/Support/MathExtras.h"
Anders Carlsson79474332009-07-18 20:20:21 +000024
25using namespace clang;
26
Benjamin Kramerc7656cd2010-05-26 09:58:31 +000027namespace {
Anders Carlssonf58de112010-05-26 15:32:58 +000028
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000029/// BaseSubobjectInfo - Represents a single base subobject in a complete class.
30/// For a class hierarchy like
31///
32/// class A { };
33/// class B : A { };
34/// class C : A, B { };
35///
36/// The BaseSubobjectInfo graph for C will have three BaseSubobjectInfo
37/// instances, one for B and two for A.
38///
39/// If a base is virtual, it will only have one BaseSubobjectInfo allocated.
40struct BaseSubobjectInfo {
41 /// Class - The class for this base info.
Anders Carlsson056818f2010-05-28 21:13:31 +000042 const CXXRecordDecl *Class;
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000043
44 /// IsVirtual - Whether the BaseInfo represents a virtual base or not.
Anders Carlsson056818f2010-05-28 21:13:31 +000045 bool IsVirtual;
46
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000047 /// Bases - Information about the base subobjects.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000048 SmallVector<BaseSubobjectInfo*, 4> Bases;
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000049
Anders Carlssone3c24c72010-05-29 17:35:14 +000050 /// PrimaryVirtualBaseInfo - Holds the base info for the primary virtual base
51 /// of this base info (if one exists).
52 BaseSubobjectInfo *PrimaryVirtualBaseInfo;
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000053
54 // FIXME: Document.
55 const BaseSubobjectInfo *Derived;
Anders Carlsson056818f2010-05-28 21:13:31 +000056};
57
Anders Carlssonf58de112010-05-26 15:32:58 +000058/// EmptySubobjectMap - Keeps track of which empty subobjects exist at different
59/// offsets while laying out a C++ class.
60class EmptySubobjectMap {
Jay Foad39c79802011-01-12 09:06:06 +000061 const ASTContext &Context;
Anders Carlsson233e2722010-10-31 21:54:55 +000062 uint64_t CharWidth;
63
Anders Carlssonf58de112010-05-26 15:32:58 +000064 /// Class - The class whose empty entries we're keeping track of.
65 const CXXRecordDecl *Class;
Daniel Dunbar592a85c2010-05-27 02:25:46 +000066
Anders Carlsson439edd12010-05-27 05:41:06 +000067 /// EmptyClassOffsets - A map from offsets to empty record decls.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000068 typedef SmallVector<const CXXRecordDecl *, 1> ClassVectorTy;
Anders Carlssonf8f756d2010-10-31 21:22:43 +000069 typedef llvm::DenseMap<CharUnits, ClassVectorTy> EmptyClassOffsetsMapTy;
Anders Carlsson439edd12010-05-27 05:41:06 +000070 EmptyClassOffsetsMapTy EmptyClassOffsets;
71
Anders Carlssoncc5de092010-06-08 15:56:03 +000072 /// MaxEmptyClassOffset - The highest offset known to contain an empty
73 /// base subobject.
Anders Carlsson725190f2010-10-31 21:39:24 +000074 CharUnits MaxEmptyClassOffset;
Anders Carlssoncc5de092010-06-08 15:56:03 +000075
Daniel Dunbar592a85c2010-05-27 02:25:46 +000076 /// ComputeEmptySubobjectSizes - Compute the size of the largest base or
Anders Carlssonc5ca1f72010-05-26 15:54:25 +000077 /// member subobject that is empty.
78 void ComputeEmptySubobjectSizes();
Anders Carlsson439edd12010-05-27 05:41:06 +000079
Anders Carlsson725190f2010-10-31 21:39:24 +000080 void AddSubobjectAtOffset(const CXXRecordDecl *RD, CharUnits Offset);
Anders Carlssondb319762010-05-27 18:20:57 +000081
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000082 void UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +000083 CharUnits Offset, bool PlacingEmptyBase);
Anders Carlsson439edd12010-05-27 05:41:06 +000084
Anders Carlssondb319762010-05-27 18:20:57 +000085 void UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD,
86 const CXXRecordDecl *Class,
Anders Carlsson28466ab2010-10-31 22:13:23 +000087 CharUnits Offset);
88 void UpdateEmptyFieldSubobjects(const FieldDecl *FD, CharUnits Offset);
Anders Carlssondb319762010-05-27 18:20:57 +000089
Anders Carlssoncc5de092010-06-08 15:56:03 +000090 /// AnyEmptySubobjectsBeyondOffset - Returns whether there are any empty
91 /// subobjects beyond the given offset.
Anders Carlsson725190f2010-10-31 21:39:24 +000092 bool AnyEmptySubobjectsBeyondOffset(CharUnits Offset) const {
Anders Carlssoncc5de092010-06-08 15:56:03 +000093 return Offset <= MaxEmptyClassOffset;
94 }
95
Anders Carlsson233e2722010-10-31 21:54:55 +000096 CharUnits
97 getFieldOffset(const ASTRecordLayout &Layout, unsigned FieldNo) const {
98 uint64_t FieldOffset = Layout.getFieldOffset(FieldNo);
99 assert(FieldOffset % CharWidth == 0 &&
100 "Field offset not at char boundary!");
101
Ken Dyck7c4026b2011-01-24 01:28:50 +0000102 return Context.toCharUnitsFromBits(FieldOffset);
Anders Carlssonf8f756d2010-10-31 21:22:43 +0000103 }
Anders Carlssonf8f756d2010-10-31 21:22:43 +0000104
Charles Davisc2c576a2010-08-19 00:55:19 +0000105protected:
Anders Carlsson725190f2010-10-31 21:39:24 +0000106 bool CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD,
107 CharUnits Offset) const;
Charles Davisc2c576a2010-08-19 00:55:19 +0000108
109 bool CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000110 CharUnits Offset);
Charles Davisc2c576a2010-08-19 00:55:19 +0000111
112 bool CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD,
113 const CXXRecordDecl *Class,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000114 CharUnits Offset) const;
Charles Davisc2c576a2010-08-19 00:55:19 +0000115 bool CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD,
Anders Carlsson233e2722010-10-31 21:54:55 +0000116 CharUnits Offset) const;
Charles Davisc2c576a2010-08-19 00:55:19 +0000117
Anders Carlssonf58de112010-05-26 15:32:58 +0000118public:
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000119 /// This holds the size of the largest empty subobject (either a base
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000120 /// or a member). Will be zero if the record being built doesn't contain
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000121 /// any empty classes.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000122 CharUnits SizeOfLargestEmptySubobject;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000123
Jay Foad39c79802011-01-12 09:06:06 +0000124 EmptySubobjectMap(const ASTContext &Context, const CXXRecordDecl *Class)
Anders Carlsson28466ab2010-10-31 22:13:23 +0000125 : Context(Context), CharWidth(Context.getCharWidth()), Class(Class) {
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000126 ComputeEmptySubobjectSizes();
127 }
128
129 /// CanPlaceBaseAtOffset - Return whether the given base class can be placed
130 /// at the given offset.
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000131 /// Returns false if placing the record will result in two components
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000132 /// (direct or indirect) of the same type having the same offset.
Anders Carlssoncc5de092010-06-08 15:56:03 +0000133 bool CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000134 CharUnits Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000135
136 /// CanPlaceFieldAtOffset - Return whether a field can be placed at the given
137 /// offset.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000138 bool CanPlaceFieldAtOffset(const FieldDecl *FD, CharUnits Offset);
Anders Carlssonf58de112010-05-26 15:32:58 +0000139};
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000140
141void EmptySubobjectMap::ComputeEmptySubobjectSizes() {
142 // Check the bases.
143 for (CXXRecordDecl::base_class_const_iterator I = Class->bases_begin(),
144 E = Class->bases_end(); I != E; ++I) {
145 const CXXRecordDecl *BaseDecl =
146 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
147
Anders Carlsson28466ab2010-10-31 22:13:23 +0000148 CharUnits EmptySize;
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000149 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
150 if (BaseDecl->isEmpty()) {
151 // If the class decl is empty, get its size.
Ken Dyckc8ae5502011-02-09 01:59:34 +0000152 EmptySize = Layout.getSize();
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000153 } else {
154 // Otherwise, we get the largest empty subobject for the decl.
155 EmptySize = Layout.getSizeOfLargestEmptySubobject();
156 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000157
Anders Carlsson28466ab2010-10-31 22:13:23 +0000158 if (EmptySize > SizeOfLargestEmptySubobject)
159 SizeOfLargestEmptySubobject = EmptySize;
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000160 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000161
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000162 // Check the fields.
163 for (CXXRecordDecl::field_iterator I = Class->field_begin(),
164 E = Class->field_end(); I != E; ++I) {
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000165
166 const RecordType *RT =
David Blaikie40ed2972012-06-06 20:45:41 +0000167 Context.getBaseElementType(I->getType())->getAs<RecordType>();
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000168
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000169 // We only care about record types.
170 if (!RT)
171 continue;
172
Anders Carlsson28466ab2010-10-31 22:13:23 +0000173 CharUnits EmptySize;
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000174 const CXXRecordDecl *MemberDecl = cast<CXXRecordDecl>(RT->getDecl());
175 const ASTRecordLayout &Layout = Context.getASTRecordLayout(MemberDecl);
176 if (MemberDecl->isEmpty()) {
177 // If the class decl is empty, get its size.
Ken Dyckc8ae5502011-02-09 01:59:34 +0000178 EmptySize = Layout.getSize();
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000179 } else {
180 // Otherwise, we get the largest empty subobject for the decl.
181 EmptySize = Layout.getSizeOfLargestEmptySubobject();
182 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000183
Anders Carlsson28466ab2010-10-31 22:13:23 +0000184 if (EmptySize > SizeOfLargestEmptySubobject)
185 SizeOfLargestEmptySubobject = EmptySize;
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000186 }
187}
188
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000189bool
Anders Carlssondb319762010-05-27 18:20:57 +0000190EmptySubobjectMap::CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD,
Anders Carlsson725190f2010-10-31 21:39:24 +0000191 CharUnits Offset) const {
Anders Carlssondb319762010-05-27 18:20:57 +0000192 // We only need to check empty bases.
193 if (!RD->isEmpty())
194 return true;
195
Anders Carlsson725190f2010-10-31 21:39:24 +0000196 EmptyClassOffsetsMapTy::const_iterator I = EmptyClassOffsets.find(Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000197 if (I == EmptyClassOffsets.end())
198 return true;
199
200 const ClassVectorTy& Classes = I->second;
201 if (std::find(Classes.begin(), Classes.end(), RD) == Classes.end())
202 return true;
203
204 // There is already an empty class of the same type at this offset.
205 return false;
206}
207
208void EmptySubobjectMap::AddSubobjectAtOffset(const CXXRecordDecl *RD,
Anders Carlsson725190f2010-10-31 21:39:24 +0000209 CharUnits Offset) {
Anders Carlssondb319762010-05-27 18:20:57 +0000210 // We only care about empty bases.
211 if (!RD->isEmpty())
212 return;
213
Reid Kleckner369f3162013-05-14 20:30:42 +0000214 // If we have empty structures inside a union, we can assign both
Rafael Espindola7bcde192010-12-29 23:02:58 +0000215 // the same offset. Just avoid pushing them twice in the list.
Anders Carlsson725190f2010-10-31 21:39:24 +0000216 ClassVectorTy& Classes = EmptyClassOffsets[Offset];
Rafael Espindola7bcde192010-12-29 23:02:58 +0000217 if (std::find(Classes.begin(), Classes.end(), RD) != Classes.end())
218 return;
219
Anders Carlssondb319762010-05-27 18:20:57 +0000220 Classes.push_back(RD);
Anders Carlssoncc5de092010-06-08 15:56:03 +0000221
222 // Update the empty class offset.
Anders Carlsson725190f2010-10-31 21:39:24 +0000223 if (Offset > MaxEmptyClassOffset)
224 MaxEmptyClassOffset = Offset;
Anders Carlssondb319762010-05-27 18:20:57 +0000225}
226
227bool
Anders Carlsson28466ab2010-10-31 22:13:23 +0000228EmptySubobjectMap::CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info,
229 CharUnits Offset) {
Anders Carlsson45c1d282010-06-08 16:20:35 +0000230 // We don't have to keep looking past the maximum offset that's known to
231 // contain an empty class.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000232 if (!AnyEmptySubobjectsBeyondOffset(Offset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000233 return true;
234
Anders Carlsson28466ab2010-10-31 22:13:23 +0000235 if (!CanPlaceSubobjectAtOffset(Info->Class, Offset))
Anders Carlssondb319762010-05-27 18:20:57 +0000236 return false;
237
Anders Carlsson439edd12010-05-27 05:41:06 +0000238 // Traverse all non-virtual bases.
Anders Carlssona7774a62010-05-29 21:10:24 +0000239 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
Anders Carlsson439edd12010-05-27 05:41:06 +0000240 for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) {
Anders Carlssona7f3cdb2010-05-28 21:24:37 +0000241 BaseSubobjectInfo* Base = Info->Bases[I];
Anders Carlsson439edd12010-05-27 05:41:06 +0000242 if (Base->IsVirtual)
243 continue;
244
Anders Carlsson0a14ee92010-11-01 00:21:58 +0000245 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
Anders Carlsson439edd12010-05-27 05:41:06 +0000246
247 if (!CanPlaceBaseSubobjectAtOffset(Base, BaseOffset))
248 return false;
249 }
250
Anders Carlssone3c24c72010-05-29 17:35:14 +0000251 if (Info->PrimaryVirtualBaseInfo) {
252 BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
Anders Carlsson439edd12010-05-27 05:41:06 +0000253
254 if (Info == PrimaryVirtualBaseInfo->Derived) {
255 if (!CanPlaceBaseSubobjectAtOffset(PrimaryVirtualBaseInfo, Offset))
256 return false;
257 }
258 }
259
Anders Carlssondb319762010-05-27 18:20:57 +0000260 // Traverse all member variables.
261 unsigned FieldNo = 0;
262 for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(),
263 E = Info->Class->field_end(); I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +0000264 if (I->isBitField())
Anders Carlsson233e2722010-10-31 21:54:55 +0000265 continue;
266
Anders Carlsson28466ab2010-10-31 22:13:23 +0000267 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
David Blaikie40ed2972012-06-06 20:45:41 +0000268 if (!CanPlaceFieldSubobjectAtOffset(*I, FieldOffset))
Anders Carlssondb319762010-05-27 18:20:57 +0000269 return false;
270 }
271
Anders Carlsson439edd12010-05-27 05:41:06 +0000272 return true;
273}
274
Anders Carlssona7f3cdb2010-05-28 21:24:37 +0000275void EmptySubobjectMap::UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000276 CharUnits Offset,
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000277 bool PlacingEmptyBase) {
278 if (!PlacingEmptyBase && Offset >= SizeOfLargestEmptySubobject) {
279 // We know that the only empty subobjects that can conflict with empty
280 // subobject of non-empty bases, are empty bases that can be placed at
281 // offset zero. Because of this, we only need to keep track of empty base
282 // subobjects with offsets less than the size of the largest empty
283 // subobject for our class.
284 return;
285 }
286
Anders Carlsson28466ab2010-10-31 22:13:23 +0000287 AddSubobjectAtOffset(Info->Class, Offset);
Anders Carlssona7774a62010-05-29 21:10:24 +0000288
Anders Carlsson439edd12010-05-27 05:41:06 +0000289 // Traverse all non-virtual bases.
Anders Carlssona7774a62010-05-29 21:10:24 +0000290 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
Anders Carlsson439edd12010-05-27 05:41:06 +0000291 for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) {
Anders Carlssona7f3cdb2010-05-28 21:24:37 +0000292 BaseSubobjectInfo* Base = Info->Bases[I];
Anders Carlsson439edd12010-05-27 05:41:06 +0000293 if (Base->IsVirtual)
294 continue;
Anders Carlssona7774a62010-05-29 21:10:24 +0000295
Anders Carlsson0a14ee92010-11-01 00:21:58 +0000296 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000297 UpdateEmptyBaseSubobjects(Base, BaseOffset, PlacingEmptyBase);
Anders Carlsson439edd12010-05-27 05:41:06 +0000298 }
299
Anders Carlssone3c24c72010-05-29 17:35:14 +0000300 if (Info->PrimaryVirtualBaseInfo) {
301 BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
Anders Carlsson439edd12010-05-27 05:41:06 +0000302
303 if (Info == PrimaryVirtualBaseInfo->Derived)
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000304 UpdateEmptyBaseSubobjects(PrimaryVirtualBaseInfo, Offset,
305 PlacingEmptyBase);
Anders Carlsson439edd12010-05-27 05:41:06 +0000306 }
Anders Carlssondb319762010-05-27 18:20:57 +0000307
Anders Carlssondb319762010-05-27 18:20:57 +0000308 // Traverse all member variables.
309 unsigned FieldNo = 0;
310 for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(),
311 E = Info->Class->field_end(); I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +0000312 if (I->isBitField())
Anders Carlsson233e2722010-10-31 21:54:55 +0000313 continue;
Anders Carlssona7774a62010-05-29 21:10:24 +0000314
Anders Carlsson28466ab2010-10-31 22:13:23 +0000315 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
David Blaikie40ed2972012-06-06 20:45:41 +0000316 UpdateEmptyFieldSubobjects(*I, FieldOffset);
Anders Carlssondb319762010-05-27 18:20:57 +0000317 }
Anders Carlsson439edd12010-05-27 05:41:06 +0000318}
319
Anders Carlssona60b86a2010-05-29 20:49:49 +0000320bool EmptySubobjectMap::CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000321 CharUnits Offset) {
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000322 // If we know this class doesn't have any empty subobjects we don't need to
323 // bother checking.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000324 if (SizeOfLargestEmptySubobject.isZero())
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000325 return true;
326
Anders Carlsson439edd12010-05-27 05:41:06 +0000327 if (!CanPlaceBaseSubobjectAtOffset(Info, Offset))
328 return false;
Anders Carlssondb319762010-05-27 18:20:57 +0000329
330 // We are able to place the base at this offset. Make sure to update the
331 // empty base subobject map.
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000332 UpdateEmptyBaseSubobjects(Info, Offset, Info->Class->isEmpty());
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000333 return true;
334}
335
Anders Carlssondb319762010-05-27 18:20:57 +0000336bool
337EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD,
338 const CXXRecordDecl *Class,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000339 CharUnits Offset) const {
Anders Carlsson45c1d282010-06-08 16:20:35 +0000340 // We don't have to keep looking past the maximum offset that's known to
341 // contain an empty class.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000342 if (!AnyEmptySubobjectsBeyondOffset(Offset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000343 return true;
344
Anders Carlsson28466ab2010-10-31 22:13:23 +0000345 if (!CanPlaceSubobjectAtOffset(RD, Offset))
Anders Carlssondb319762010-05-27 18:20:57 +0000346 return false;
347
348 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
349
350 // Traverse all non-virtual bases.
351 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
352 E = RD->bases_end(); I != E; ++I) {
353 if (I->isVirtual())
354 continue;
355
356 const CXXRecordDecl *BaseDecl =
357 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
358
Anders Carlsson0a14ee92010-11-01 00:21:58 +0000359 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
Anders Carlssondb319762010-05-27 18:20:57 +0000360 if (!CanPlaceFieldSubobjectAtOffset(BaseDecl, Class, BaseOffset))
361 return false;
362 }
363
Anders Carlsson44687202010-06-08 19:09:24 +0000364 if (RD == Class) {
365 // This is the most derived class, traverse virtual bases as well.
366 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
367 E = RD->vbases_end(); I != E; ++I) {
368 const CXXRecordDecl *VBaseDecl =
369 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
370
Anders Carlsson3f018712010-10-31 23:45:59 +0000371 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
Anders Carlsson44687202010-06-08 19:09:24 +0000372 if (!CanPlaceFieldSubobjectAtOffset(VBaseDecl, Class, VBaseOffset))
373 return false;
374 }
375 }
376
Anders Carlssondb319762010-05-27 18:20:57 +0000377 // Traverse all member variables.
378 unsigned FieldNo = 0;
379 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
380 I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +0000381 if (I->isBitField())
Anders Carlsson233e2722010-10-31 21:54:55 +0000382 continue;
383
Anders Carlsson28466ab2010-10-31 22:13:23 +0000384 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
Anders Carlssondb319762010-05-27 18:20:57 +0000385
David Blaikie40ed2972012-06-06 20:45:41 +0000386 if (!CanPlaceFieldSubobjectAtOffset(*I, FieldOffset))
Anders Carlssondb319762010-05-27 18:20:57 +0000387 return false;
388 }
389
390 return true;
391}
392
Anders Carlsson233e2722010-10-31 21:54:55 +0000393bool
394EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD,
395 CharUnits Offset) const {
Anders Carlsson45c1d282010-06-08 16:20:35 +0000396 // We don't have to keep looking past the maximum offset that's known to
397 // contain an empty class.
Anders Carlsson233e2722010-10-31 21:54:55 +0000398 if (!AnyEmptySubobjectsBeyondOffset(Offset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000399 return true;
400
Anders Carlssondb319762010-05-27 18:20:57 +0000401 QualType T = FD->getType();
402 if (const RecordType *RT = T->getAs<RecordType>()) {
403 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson28466ab2010-10-31 22:13:23 +0000404 return CanPlaceFieldSubobjectAtOffset(RD, RD, Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000405 }
406
407 // If we have an array type we need to look at every element.
408 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
409 QualType ElemTy = Context.getBaseElementType(AT);
410 const RecordType *RT = ElemTy->getAs<RecordType>();
411 if (!RT)
412 return true;
413
414 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
415 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
416
417 uint64_t NumElements = Context.getConstantArrayElementCount(AT);
Anders Carlsson233e2722010-10-31 21:54:55 +0000418 CharUnits ElementOffset = Offset;
Anders Carlssondb319762010-05-27 18:20:57 +0000419 for (uint64_t I = 0; I != NumElements; ++I) {
Anders Carlsson45c1d282010-06-08 16:20:35 +0000420 // We don't have to keep looking past the maximum offset that's known to
421 // contain an empty class.
Anders Carlsson233e2722010-10-31 21:54:55 +0000422 if (!AnyEmptySubobjectsBeyondOffset(ElementOffset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000423 return true;
424
Anders Carlsson28466ab2010-10-31 22:13:23 +0000425 if (!CanPlaceFieldSubobjectAtOffset(RD, RD, ElementOffset))
Anders Carlssondb319762010-05-27 18:20:57 +0000426 return false;
427
Ken Dyckc8ae5502011-02-09 01:59:34 +0000428 ElementOffset += Layout.getSize();
Anders Carlssondb319762010-05-27 18:20:57 +0000429 }
430 }
431
432 return true;
433}
434
435bool
Anders Carlsson28466ab2010-10-31 22:13:23 +0000436EmptySubobjectMap::CanPlaceFieldAtOffset(const FieldDecl *FD,
437 CharUnits Offset) {
438 if (!CanPlaceFieldSubobjectAtOffset(FD, Offset))
Anders Carlssondb319762010-05-27 18:20:57 +0000439 return false;
440
441 // We are able to place the member variable at this offset.
442 // Make sure to update the empty base subobject map.
443 UpdateEmptyFieldSubobjects(FD, Offset);
444 return true;
445}
446
447void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD,
448 const CXXRecordDecl *Class,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000449 CharUnits Offset) {
Anders Carlssonae111dc2010-06-13 17:49:16 +0000450 // We know that the only empty subobjects that can conflict with empty
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000451 // field subobjects are subobjects of empty bases that can be placed at offset
Anders Carlssonae111dc2010-06-13 17:49:16 +0000452 // zero. Because of this, we only need to keep track of empty field
453 // subobjects with offsets less than the size of the largest empty
454 // subobject for our class.
455 if (Offset >= SizeOfLargestEmptySubobject)
456 return;
457
Anders Carlsson28466ab2010-10-31 22:13:23 +0000458 AddSubobjectAtOffset(RD, Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000459
460 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
461
462 // Traverse all non-virtual bases.
463 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
464 E = RD->bases_end(); I != E; ++I) {
465 if (I->isVirtual())
466 continue;
467
468 const CXXRecordDecl *BaseDecl =
469 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
470
Anders Carlsson0a14ee92010-11-01 00:21:58 +0000471 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
Anders Carlssondb319762010-05-27 18:20:57 +0000472 UpdateEmptyFieldSubobjects(BaseDecl, Class, BaseOffset);
473 }
474
Anders Carlsson44687202010-06-08 19:09:24 +0000475 if (RD == Class) {
476 // This is the most derived class, traverse virtual bases as well.
477 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
478 E = RD->vbases_end(); I != E; ++I) {
479 const CXXRecordDecl *VBaseDecl =
480 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
481
Anders Carlsson3f018712010-10-31 23:45:59 +0000482 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
Anders Carlsson44687202010-06-08 19:09:24 +0000483 UpdateEmptyFieldSubobjects(VBaseDecl, Class, VBaseOffset);
484 }
485 }
486
Anders Carlssondb319762010-05-27 18:20:57 +0000487 // Traverse all member variables.
488 unsigned FieldNo = 0;
489 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
490 I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +0000491 if (I->isBitField())
Anders Carlsson09814d32010-11-01 15:14:51 +0000492 continue;
493
Anders Carlsson28466ab2010-10-31 22:13:23 +0000494 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
Anders Carlssondb319762010-05-27 18:20:57 +0000495
David Blaikie40ed2972012-06-06 20:45:41 +0000496 UpdateEmptyFieldSubobjects(*I, FieldOffset);
Anders Carlssondb319762010-05-27 18:20:57 +0000497 }
498}
499
500void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const FieldDecl *FD,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000501 CharUnits Offset) {
Anders Carlssondb319762010-05-27 18:20:57 +0000502 QualType T = FD->getType();
503 if (const RecordType *RT = T->getAs<RecordType>()) {
504 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
505 UpdateEmptyFieldSubobjects(RD, RD, Offset);
506 return;
507 }
508
509 // If we have an array type we need to update every element.
510 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
511 QualType ElemTy = Context.getBaseElementType(AT);
512 const RecordType *RT = ElemTy->getAs<RecordType>();
513 if (!RT)
514 return;
515
516 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
517 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
518
519 uint64_t NumElements = Context.getConstantArrayElementCount(AT);
Anders Carlsson28466ab2010-10-31 22:13:23 +0000520 CharUnits ElementOffset = Offset;
Anders Carlssondb319762010-05-27 18:20:57 +0000521
522 for (uint64_t I = 0; I != NumElements; ++I) {
Anders Carlssonae111dc2010-06-13 17:49:16 +0000523 // We know that the only empty subobjects that can conflict with empty
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000524 // field subobjects are subobjects of empty bases that can be placed at
Anders Carlssonae111dc2010-06-13 17:49:16 +0000525 // offset zero. Because of this, we only need to keep track of empty field
526 // subobjects with offsets less than the size of the largest empty
527 // subobject for our class.
528 if (ElementOffset >= SizeOfLargestEmptySubobject)
529 return;
530
Anders Carlssondb319762010-05-27 18:20:57 +0000531 UpdateEmptyFieldSubobjects(RD, RD, ElementOffset);
Ken Dyckc8ae5502011-02-09 01:59:34 +0000532 ElementOffset += Layout.getSize();
Anders Carlssondb319762010-05-27 18:20:57 +0000533 }
534 }
535}
536
John McCalle42a3362012-05-01 08:55:32 +0000537typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> ClassSetTy;
538
Anders Carlssonc2226202010-05-26 05:58:59 +0000539class RecordLayoutBuilder {
Charles Davisc2c576a2010-08-19 00:55:19 +0000540protected:
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000541 // FIXME: Remove this and make the appropriate fields public.
542 friend class clang::ASTContext;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000543
Jay Foad39c79802011-01-12 09:06:06 +0000544 const ASTContext &Context;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000545
Anders Carlssonf58de112010-05-26 15:32:58 +0000546 EmptySubobjectMap *EmptySubobjects;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000547
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000548 /// Size - The current size of the record layout.
549 uint64_t Size;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000550
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000551 /// Alignment - The current alignment of the record layout.
Ken Dyck4731d5b2011-02-16 02:05:21 +0000552 CharUnits Alignment;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000553
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000554 /// \brief The alignment if attribute packed is not used.
Ken Dyck1300b3b2011-02-16 02:11:31 +0000555 CharUnits UnpackedAlignment;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000556
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000557 SmallVector<uint64_t, 16> FieldOffsets;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000558
Douglas Gregore9fc3772012-01-26 07:55:45 +0000559 /// \brief Whether the external AST source has provided a layout for this
560 /// record.
561 unsigned ExternalLayout : 1;
Douglas Gregor44ba7892012-01-28 00:53:29 +0000562
563 /// \brief Whether we need to infer alignment, even when we have an
564 /// externally-provided layout.
565 unsigned InferAlignment : 1;
Douglas Gregore9fc3772012-01-26 07:55:45 +0000566
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000567 /// Packed - Whether the record is packed or not.
Daniel Dunbar6da10982010-05-27 05:45:51 +0000568 unsigned Packed : 1;
569
570 unsigned IsUnion : 1;
571
572 unsigned IsMac68kAlign : 1;
Fariborz Jahanianbcb23a12011-04-26 23:52:16 +0000573
574 unsigned IsMsStruct : 1;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000575
Eli Friedman2782dac2013-06-26 20:50:34 +0000576 /// UnfilledBitsInLastUnit - If the last field laid out was a bitfield,
577 /// this contains the number of bits in the last unit that can be used for
578 /// an adjacent bitfield if necessary. The unit in question is usually
579 /// a byte, but larger units are used if IsMsStruct.
580 unsigned char UnfilledBitsInLastUnit;
581 /// LastBitfieldTypeSize - If IsMsStruct, represents the size of the type
582 /// of the previous field if it was a bitfield.
583 unsigned char LastBitfieldTypeSize;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000584
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000585 /// MaxFieldAlignment - The maximum allowed field alignment. This is set by
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000586 /// #pragma pack.
Ken Dyck02ced6f2011-02-17 01:49:42 +0000587 CharUnits MaxFieldAlignment;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000588
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000589 /// DataSize - The data size of the record being laid out.
590 uint64_t DataSize;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000591
Ken Dyckaf1c83f2011-02-16 01:52:01 +0000592 CharUnits NonVirtualSize;
Ken Dycka2d3dda2011-02-16 01:43:15 +0000593 CharUnits NonVirtualAlignment;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000594
Fariborz Jahanianfc0fe6e2011-05-03 20:21:04 +0000595 FieldDecl *ZeroLengthBitfield;
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000596
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000597 /// PrimaryBase - the primary base class (if one exists) of the class
598 /// we're laying out.
599 const CXXRecordDecl *PrimaryBase;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000600
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000601 /// PrimaryBaseIsVirtual - Whether the primary base of the class we're laying
602 /// out is virtual.
603 bool PrimaryBaseIsVirtual;
604
John McCalle42a3362012-05-01 08:55:32 +0000605 /// HasOwnVFPtr - Whether the class provides its own vtable/vftbl
606 /// pointer, as opposed to inheriting one from a primary base class.
607 bool HasOwnVFPtr;
Eli Friedman43114f92011-10-21 22:49:56 +0000608
Eli Friedman84d2d3a2011-09-27 19:12:27 +0000609 /// VBPtrOffset - Virtual base table offset. Only for MS layout.
610 CharUnits VBPtrOffset;
611
Anders Carlsson22f57202010-10-31 21:01:46 +0000612 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000613
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000614 /// Bases - base classes and their offsets in the record.
615 BaseOffsetsMapTy Bases;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000616
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000617 // VBases - virtual base classes and their offsets in the record.
John McCalle42a3362012-05-01 08:55:32 +0000618 ASTRecordLayout::VBaseOffsetsMapTy VBases;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000619
620 /// IndirectPrimaryBases - Virtual base classes, direct or indirect, that are
621 /// primary base classes for some other direct or indirect base class.
Anders Carlsson5adde292010-11-24 22:55:48 +0000622 CXXIndirectPrimaryBaseSet IndirectPrimaryBases;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000623
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000624 /// FirstNearlyEmptyVBase - The first nearly empty virtual base class in
625 /// inheritance graph order. Used for determining the primary base class.
626 const CXXRecordDecl *FirstNearlyEmptyVBase;
627
628 /// VisitedVirtualBases - A set of all the visited virtual bases, used to
629 /// avoid visiting virtual bases more than once.
630 llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000631
Douglas Gregore9fc3772012-01-26 07:55:45 +0000632 /// \brief Externally-provided size.
633 uint64_t ExternalSize;
634
635 /// \brief Externally-provided alignment.
636 uint64_t ExternalAlign;
637
638 /// \brief Externally-provided field offsets.
639 llvm::DenseMap<const FieldDecl *, uint64_t> ExternalFieldOffsets;
640
641 /// \brief Externally-provided direct, non-virtual base offsets.
642 llvm::DenseMap<const CXXRecordDecl *, CharUnits> ExternalBaseOffsets;
643
644 /// \brief Externally-provided virtual base offsets.
645 llvm::DenseMap<const CXXRecordDecl *, CharUnits> ExternalVirtualBaseOffsets;
646
John McCall0153cd32011-11-08 04:01:03 +0000647 RecordLayoutBuilder(const ASTContext &Context,
648 EmptySubobjectMap *EmptySubobjects)
Ken Dyck4731d5b2011-02-16 02:05:21 +0000649 : Context(Context), EmptySubobjects(EmptySubobjects), Size(0),
John McCall0153cd32011-11-08 04:01:03 +0000650 Alignment(CharUnits::One()), UnpackedAlignment(CharUnits::One()),
Douglas Gregor44ba7892012-01-28 00:53:29 +0000651 ExternalLayout(false), InferAlignment(false),
652 Packed(false), IsUnion(false), IsMac68kAlign(false), IsMsStruct(false),
Eli Friedman2782dac2013-06-26 20:50:34 +0000653 UnfilledBitsInLastUnit(0), LastBitfieldTypeSize(0),
654 MaxFieldAlignment(CharUnits::Zero()),
Ken Dyck02ced6f2011-02-17 01:49:42 +0000655 DataSize(0), NonVirtualSize(CharUnits::Zero()),
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000656 NonVirtualAlignment(CharUnits::One()),
Fariborz Jahanianfc0fe6e2011-05-03 20:21:04 +0000657 ZeroLengthBitfield(0), PrimaryBase(0),
Eli Friedman43114f92011-10-21 22:49:56 +0000658 PrimaryBaseIsVirtual(false),
John McCalle42a3362012-05-01 08:55:32 +0000659 HasOwnVFPtr(false),
Eli Friedman43114f92011-10-21 22:49:56 +0000660 VBPtrOffset(CharUnits::fromQuantity(-1)),
Eli Friedman84d2d3a2011-09-27 19:12:27 +0000661 FirstNearlyEmptyVBase(0) { }
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000662
John McCall0153cd32011-11-08 04:01:03 +0000663 /// Reset this RecordLayoutBuilder to a fresh state, using the given
664 /// alignment as the initial alignment. This is used for the
665 /// correct layout of vb-table pointers in MSVC.
666 void resetWithTargetAlignment(CharUnits TargetAlignment) {
667 const ASTContext &Context = this->Context;
668 EmptySubobjectMap *EmptySubobjects = this->EmptySubobjects;
669 this->~RecordLayoutBuilder();
670 new (this) RecordLayoutBuilder(Context, EmptySubobjects);
671 Alignment = UnpackedAlignment = TargetAlignment;
672 }
673
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000674 void Layout(const RecordDecl *D);
Anders Carlssonc28a6c92010-05-26 15:10:00 +0000675 void Layout(const CXXRecordDecl *D);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000676 void Layout(const ObjCInterfaceDecl *D);
677
678 void LayoutFields(const RecordDecl *D);
679 void LayoutField(const FieldDecl *D);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000680 void LayoutWideBitField(uint64_t FieldSize, uint64_t TypeSize,
681 bool FieldPacked, const FieldDecl *D);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000682 void LayoutBitField(const FieldDecl *D);
John McCall0153cd32011-11-08 04:01:03 +0000683
John McCall359b8852013-01-25 22:30:49 +0000684 TargetCXXABI getCXXABI() const {
685 return Context.getTargetInfo().getCXXABI();
686 }
687
John McCall0153cd32011-11-08 04:01:03 +0000688 bool isMicrosoftCXXABI() const {
John McCall359b8852013-01-25 22:30:49 +0000689 return getCXXABI().isMicrosoft();
John McCall0153cd32011-11-08 04:01:03 +0000690 }
691
Eli Friedman84d2d3a2011-09-27 19:12:27 +0000692 void MSLayoutVirtualBases(const CXXRecordDecl *RD);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000693
Anders Carlssone3c24c72010-05-29 17:35:14 +0000694 /// BaseSubobjectInfoAllocator - Allocator for BaseSubobjectInfo objects.
695 llvm::SpecificBumpPtrAllocator<BaseSubobjectInfo> BaseSubobjectInfoAllocator;
696
697 typedef llvm::DenseMap<const CXXRecordDecl *, BaseSubobjectInfo *>
698 BaseSubobjectInfoMapTy;
699
700 /// VirtualBaseInfo - Map from all the (direct or indirect) virtual bases
701 /// of the class we're laying out to their base subobject info.
702 BaseSubobjectInfoMapTy VirtualBaseInfo;
703
704 /// NonVirtualBaseInfo - Map from all the direct non-virtual bases of the
705 /// class we're laying out to their base subobject info.
706 BaseSubobjectInfoMapTy NonVirtualBaseInfo;
707
708 /// ComputeBaseSubobjectInfo - Compute the base subobject information for the
709 /// bases of the given class.
710 void ComputeBaseSubobjectInfo(const CXXRecordDecl *RD);
711
712 /// ComputeBaseSubobjectInfo - Compute the base subobject information for a
713 /// single class and all of its base classes.
714 BaseSubobjectInfo *ComputeBaseSubobjectInfo(const CXXRecordDecl *RD,
715 bool IsVirtual,
716 BaseSubobjectInfo *Derived);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000717
718 /// DeterminePrimaryBase - Determine the primary base of the given class.
719 void DeterminePrimaryBase(const CXXRecordDecl *RD);
720
721 void SelectPrimaryVBase(const CXXRecordDecl *RD);
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000722
Eli Friedman43114f92011-10-21 22:49:56 +0000723 void EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign);
Charles Davisc2c576a2010-08-19 00:55:19 +0000724
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000725 /// LayoutNonVirtualBases - Determines the primary base class (if any) and
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000726 /// lays it out. Will then proceed to lay out all non-virtual base clasess.
727 void LayoutNonVirtualBases(const CXXRecordDecl *RD);
728
729 /// LayoutNonVirtualBase - Lays out a single non-virtual base.
Anders Carlssonbb0e6782010-05-29 17:42:25 +0000730 void LayoutNonVirtualBase(const BaseSubobjectInfo *Base);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000731
Anders Carlssona2f8e412010-10-31 22:20:42 +0000732 void AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
733 CharUnits Offset);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000734
John McCall0153cd32011-11-08 04:01:03 +0000735 bool needsVFTable(const CXXRecordDecl *RD) const;
John McCalle42a3362012-05-01 08:55:32 +0000736 bool hasNewVirtualFunction(const CXXRecordDecl *RD,
737 bool IgnoreDestructor = false) const;
John McCall0153cd32011-11-08 04:01:03 +0000738 bool isPossiblePrimaryBase(const CXXRecordDecl *Base) const;
Eli Friedman5e9534b2011-10-18 00:55:28 +0000739
John McCalle42a3362012-05-01 08:55:32 +0000740 void computeVtordisps(const CXXRecordDecl *RD,
741 ClassSetTy &VtordispVBases);
742
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000743 /// LayoutVirtualBases - Lays out all the virtual bases.
744 void LayoutVirtualBases(const CXXRecordDecl *RD,
745 const CXXRecordDecl *MostDerivedClass);
746
747 /// LayoutVirtualBase - Lays out a single virtual base.
John McCalle42a3362012-05-01 08:55:32 +0000748 void LayoutVirtualBase(const BaseSubobjectInfo *Base,
749 bool IsVtordispNeed = false);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000750
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000751 /// LayoutBase - Will lay out a base and return the offset where it was
Anders Carlssona2f8e412010-10-31 22:20:42 +0000752 /// placed, in chars.
753 CharUnits LayoutBase(const BaseSubobjectInfo *Base);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000754
Anders Carlssonc28a6c92010-05-26 15:10:00 +0000755 /// InitializeLayout - Initialize record layout for the given record decl.
Daniel Dunbar6da10982010-05-27 05:45:51 +0000756 void InitializeLayout(const Decl *D);
Anders Carlssonc28a6c92010-05-26 15:10:00 +0000757
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000758 /// FinishLayout - Finalize record layout. Adjust record size based on the
759 /// alignment.
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000760 void FinishLayout(const NamedDecl *D);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000761
Ken Dyck85ef0432011-02-19 18:58:07 +0000762 void UpdateAlignment(CharUnits NewAlignment, CharUnits UnpackedNewAlignment);
763 void UpdateAlignment(CharUnits NewAlignment) {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000764 UpdateAlignment(NewAlignment, NewAlignment);
765 }
766
Douglas Gregor44ba7892012-01-28 00:53:29 +0000767 /// \brief Retrieve the externally-supplied field offset for the given
768 /// field.
769 ///
770 /// \param Field The field whose offset is being queried.
771 /// \param ComputedOffset The offset that we've computed for this field.
772 uint64_t updateExternalFieldOffset(const FieldDecl *Field,
773 uint64_t ComputedOffset);
774
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000775 void CheckFieldPadding(uint64_t Offset, uint64_t UnpaddedOffset,
776 uint64_t UnpackedOffset, unsigned UnpackedAlign,
777 bool isPacked, const FieldDecl *D);
778
779 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000780
Ken Dyckecfc7552011-02-24 01:13:28 +0000781 CharUnits getSize() const {
Ken Dyck3c215f22011-02-24 01:33:05 +0000782 assert(Size % Context.getCharWidth() == 0);
Ken Dyckecfc7552011-02-24 01:13:28 +0000783 return Context.toCharUnitsFromBits(Size);
784 }
785 uint64_t getSizeInBits() const { return Size; }
786
787 void setSize(CharUnits NewSize) { Size = Context.toBits(NewSize); }
788 void setSize(uint64_t NewSize) { Size = NewSize; }
789
Eli Friedman84d2d3a2011-09-27 19:12:27 +0000790 CharUnits getAligment() const { return Alignment; }
791
Ken Dyckecfc7552011-02-24 01:13:28 +0000792 CharUnits getDataSize() const {
Ken Dyck3c215f22011-02-24 01:33:05 +0000793 assert(DataSize % Context.getCharWidth() == 0);
Ken Dyckecfc7552011-02-24 01:13:28 +0000794 return Context.toCharUnitsFromBits(DataSize);
795 }
796 uint64_t getDataSizeInBits() const { return DataSize; }
797
798 void setDataSize(CharUnits NewSize) { DataSize = Context.toBits(NewSize); }
799 void setDataSize(uint64_t NewSize) { DataSize = NewSize; }
800
Dmitri Gribenkoa664e5b2012-09-15 20:20:27 +0000801 RecordLayoutBuilder(const RecordLayoutBuilder &) LLVM_DELETED_FUNCTION;
802 void operator=(const RecordLayoutBuilder &) LLVM_DELETED_FUNCTION;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000803};
Benjamin Kramerc7656cd2010-05-26 09:58:31 +0000804} // end anonymous namespace
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000805
Anders Carlsson81430692009-09-22 03:02:06 +0000806void
Anders Carlssonc2226202010-05-26 05:58:59 +0000807RecordLayoutBuilder::SelectPrimaryVBase(const CXXRecordDecl *RD) {
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000808 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000809 E = RD->bases_end(); I != E; ++I) {
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000810 assert(!I->getType()->isDependentType() &&
Sebastian Redl1054fae2009-10-25 17:03:50 +0000811 "Cannot layout class with dependent bases.");
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000812
Mike Stump11289f42009-09-09 15:08:12 +0000813 const CXXRecordDecl *Base =
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000814 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000815
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000816 // Check if this is a nearly empty virtual base.
Anders Carlsson60a62632010-11-25 01:51:53 +0000817 if (I->isVirtual() && Context.isNearlyEmpty(Base)) {
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000818 // If it's not an indirect primary base, then we've found our primary
819 // base.
Anders Carlsson81430692009-09-22 03:02:06 +0000820 if (!IndirectPrimaryBases.count(Base)) {
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000821 PrimaryBase = Base;
822 PrimaryBaseIsVirtual = true;
Mike Stump6f3793b2009-08-12 21:50:08 +0000823 return;
824 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000825
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000826 // Is this the first nearly empty virtual base?
827 if (!FirstNearlyEmptyVBase)
828 FirstNearlyEmptyVBase = Base;
Mike Stump6f3793b2009-08-12 21:50:08 +0000829 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000830
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000831 SelectPrimaryVBase(Base);
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000832 if (PrimaryBase)
Zhongxing Xuec345b72010-02-15 04:28:35 +0000833 return;
Mike Stump6f3793b2009-08-12 21:50:08 +0000834 }
835}
836
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000837/// DeterminePrimaryBase - Determine the primary base of the given class.
Anders Carlssonc2226202010-05-26 05:58:59 +0000838void RecordLayoutBuilder::DeterminePrimaryBase(const CXXRecordDecl *RD) {
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000839 // If the class isn't dynamic, it won't have a primary base.
840 if (!RD->isDynamicClass())
841 return;
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000842
Anders Carlsson81430692009-09-22 03:02:06 +0000843 // Compute all the primary virtual bases for all of our direct and
Mike Stump590a7c72009-08-13 23:26:06 +0000844 // indirect bases, and record all their primary virtual base classes.
Anders Carlsson5adde292010-11-24 22:55:48 +0000845 RD->getIndirectPrimaryBases(IndirectPrimaryBases);
Mike Stump590a7c72009-08-13 23:26:06 +0000846
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000847 // If the record has a dynamic base class, attempt to choose a primary base
848 // class. It is the first (in direct base class order) non-virtual dynamic
Anders Carlsson81430692009-09-22 03:02:06 +0000849 // base class, if one exists.
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000850 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000851 e = RD->bases_end(); i != e; ++i) {
Anders Carlsson03ff3792009-11-27 22:05:05 +0000852 // Ignore virtual bases.
853 if (i->isVirtual())
854 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000855
Anders Carlsson03ff3792009-11-27 22:05:05 +0000856 const CXXRecordDecl *Base =
857 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
858
John McCall0153cd32011-11-08 04:01:03 +0000859 if (isPossiblePrimaryBase(Base)) {
Anders Carlsson03ff3792009-11-27 22:05:05 +0000860 // We found it.
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000861 PrimaryBase = Base;
862 PrimaryBaseIsVirtual = false;
Anders Carlsson03ff3792009-11-27 22:05:05 +0000863 return;
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000864 }
865 }
866
Eli Friedman5e9534b2011-10-18 00:55:28 +0000867 // The Microsoft ABI doesn't have primary virtual bases.
John McCall0153cd32011-11-08 04:01:03 +0000868 if (isMicrosoftCXXABI()) {
Eli Friedman5e9534b2011-10-18 00:55:28 +0000869 assert(!PrimaryBase && "Should not get here with a primary base!");
870 return;
871 }
872
873 // Under the Itanium ABI, if there is no non-virtual primary base class,
874 // try to compute the primary virtual base. The primary virtual base is
875 // the first nearly empty virtual base that is not an indirect primary
876 // virtual base class, if one exists.
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000877 if (RD->getNumVBases() != 0) {
878 SelectPrimaryVBase(RD);
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000879 if (PrimaryBase)
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000880 return;
881 }
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000882
Eli Friedman5e9534b2011-10-18 00:55:28 +0000883 // Otherwise, it is the first indirect primary base class, if one exists.
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000884 if (FirstNearlyEmptyVBase) {
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000885 PrimaryBase = FirstNearlyEmptyVBase;
886 PrimaryBaseIsVirtual = true;
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000887 return;
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000888 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000889
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000890 assert(!PrimaryBase && "Should not get here with a primary base!");
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000891}
892
Anders Carlssone3c24c72010-05-29 17:35:14 +0000893BaseSubobjectInfo *
894RecordLayoutBuilder::ComputeBaseSubobjectInfo(const CXXRecordDecl *RD,
895 bool IsVirtual,
896 BaseSubobjectInfo *Derived) {
897 BaseSubobjectInfo *Info;
898
899 if (IsVirtual) {
900 // Check if we already have info about this virtual base.
901 BaseSubobjectInfo *&InfoSlot = VirtualBaseInfo[RD];
902 if (InfoSlot) {
903 assert(InfoSlot->Class == RD && "Wrong class for virtual base info!");
904 return InfoSlot;
905 }
906
907 // We don't, create it.
908 InfoSlot = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
909 Info = InfoSlot;
910 } else {
911 Info = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
912 }
913
914 Info->Class = RD;
915 Info->IsVirtual = IsVirtual;
916 Info->Derived = 0;
917 Info->PrimaryVirtualBaseInfo = 0;
918
919 const CXXRecordDecl *PrimaryVirtualBase = 0;
920 BaseSubobjectInfo *PrimaryVirtualBaseInfo = 0;
921
922 // Check if this base has a primary virtual base.
923 if (RD->getNumVBases()) {
924 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Anders Carlsson7f95cd12010-11-24 23:12:57 +0000925 if (Layout.isPrimaryBaseVirtual()) {
Anders Carlssone3c24c72010-05-29 17:35:14 +0000926 // This base does have a primary virtual base.
927 PrimaryVirtualBase = Layout.getPrimaryBase();
928 assert(PrimaryVirtualBase && "Didn't have a primary virtual base!");
929
930 // Now check if we have base subobject info about this primary base.
931 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
932
933 if (PrimaryVirtualBaseInfo) {
934 if (PrimaryVirtualBaseInfo->Derived) {
935 // We did have info about this primary base, and it turns out that it
936 // has already been claimed as a primary virtual base for another
937 // base.
938 PrimaryVirtualBase = 0;
939 } else {
940 // We can claim this base as our primary base.
941 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
942 PrimaryVirtualBaseInfo->Derived = Info;
943 }
944 }
945 }
946 }
947
948 // Now go through all direct bases.
949 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
950 E = RD->bases_end(); I != E; ++I) {
951 bool IsVirtual = I->isVirtual();
952
953 const CXXRecordDecl *BaseDecl =
954 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
955
956 Info->Bases.push_back(ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, Info));
957 }
958
959 if (PrimaryVirtualBase && !PrimaryVirtualBaseInfo) {
960 // Traversing the bases must have created the base info for our primary
961 // virtual base.
962 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
963 assert(PrimaryVirtualBaseInfo &&
964 "Did not create a primary virtual base!");
965
966 // Claim the primary virtual base as our primary virtual base.
967 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
968 PrimaryVirtualBaseInfo->Derived = Info;
969 }
970
971 return Info;
972}
973
974void RecordLayoutBuilder::ComputeBaseSubobjectInfo(const CXXRecordDecl *RD) {
975 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
976 E = RD->bases_end(); I != E; ++I) {
977 bool IsVirtual = I->isVirtual();
978
979 const CXXRecordDecl *BaseDecl =
980 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
981
982 // Compute the base subobject info for this base.
983 BaseSubobjectInfo *Info = ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, 0);
984
985 if (IsVirtual) {
986 // ComputeBaseInfo has already added this base for us.
987 assert(VirtualBaseInfo.count(BaseDecl) &&
988 "Did not add virtual base!");
989 } else {
990 // Add the base info to the map of non-virtual bases.
991 assert(!NonVirtualBaseInfo.count(BaseDecl) &&
992 "Non-virtual base already exists!");
993 NonVirtualBaseInfo.insert(std::make_pair(BaseDecl, Info));
994 }
995 }
996}
997
Anders Carlsson09ffa322010-03-10 22:21:28 +0000998void
Eli Friedman43114f92011-10-21 22:49:56 +0000999RecordLayoutBuilder::EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign) {
Eli Friedman5e9534b2011-10-18 00:55:28 +00001000 CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
1001
1002 // The maximum field alignment overrides base align.
1003 if (!MaxFieldAlignment.isZero()) {
1004 BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
1005 UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
1006 }
1007
1008 // Round up the current record size to pointer alignment.
Eli Friedman43114f92011-10-21 22:49:56 +00001009 setSize(getSize().RoundUpToAlignment(BaseAlign));
1010 setDataSize(getSize());
Eli Friedman5e9534b2011-10-18 00:55:28 +00001011
1012 // Update the alignment.
1013 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
1014}
1015
1016void
Anders Carlssonc2226202010-05-26 05:58:59 +00001017RecordLayoutBuilder::LayoutNonVirtualBases(const CXXRecordDecl *RD) {
Anders Carlssone3c24c72010-05-29 17:35:14 +00001018 // Then, determine the primary base class.
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001019 DeterminePrimaryBase(RD);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001020
Anders Carlssone3c24c72010-05-29 17:35:14 +00001021 // Compute base subobject info.
1022 ComputeBaseSubobjectInfo(RD);
1023
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001024 // If we have a primary base class, lay it out.
Anders Carlssond20e7cd2010-05-26 05:20:58 +00001025 if (PrimaryBase) {
1026 if (PrimaryBaseIsVirtual) {
Anders Carlssone3c24c72010-05-29 17:35:14 +00001027 // If the primary virtual base was a primary virtual base of some other
1028 // base class we'll have to steal it.
1029 BaseSubobjectInfo *PrimaryBaseInfo = VirtualBaseInfo.lookup(PrimaryBase);
1030 PrimaryBaseInfo->Derived = 0;
1031
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001032 // We have a virtual primary base, insert it as an indirect primary base.
Anders Carlssond20e7cd2010-05-26 05:20:58 +00001033 IndirectPrimaryBases.insert(PrimaryBase);
Anders Carlssonfe900962010-03-11 05:42:17 +00001034
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001035 assert(!VisitedVirtualBases.count(PrimaryBase) &&
Anders Carlssond20e7cd2010-05-26 05:20:58 +00001036 "vbase already visited!");
1037 VisitedVirtualBases.insert(PrimaryBase);
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001038
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001039 LayoutVirtualBase(PrimaryBaseInfo);
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001040 } else {
1041 BaseSubobjectInfo *PrimaryBaseInfo =
1042 NonVirtualBaseInfo.lookup(PrimaryBase);
1043 assert(PrimaryBaseInfo &&
1044 "Did not find base info for non-virtual primary base!");
1045
1046 LayoutNonVirtualBase(PrimaryBaseInfo);
1047 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001048
John McCall0153cd32011-11-08 04:01:03 +00001049 // If this class needs a vtable/vf-table and didn't get one from a
1050 // primary base, add it in now.
1051 } else if (needsVFTable(RD)) {
Eli Friedman5e9534b2011-10-18 00:55:28 +00001052 assert(DataSize == 0 && "Vtable pointer must be at offset zero!");
Eli Friedman5e9534b2011-10-18 00:55:28 +00001053 CharUnits PtrWidth =
1054 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Eli Friedman43114f92011-10-21 22:49:56 +00001055 CharUnits PtrAlign =
1056 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0));
1057 EnsureVTablePointerAlignment(PtrAlign);
John McCalle42a3362012-05-01 08:55:32 +00001058 HasOwnVFPtr = true;
Eli Friedman5e9534b2011-10-18 00:55:28 +00001059 setSize(getSize() + PtrWidth);
1060 setDataSize(getSize());
1061 }
1062
John McCall0153cd32011-11-08 04:01:03 +00001063 bool HasDirectVirtualBases = false;
1064 bool HasNonVirtualBaseWithVBTable = false;
1065
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001066 // Now lay out the non-virtual bases.
1067 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001068 E = RD->bases_end(); I != E; ++I) {
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001069
John McCall0153cd32011-11-08 04:01:03 +00001070 // Ignore virtual bases, but remember that we saw one.
1071 if (I->isVirtual()) {
1072 HasDirectVirtualBases = true;
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001073 continue;
John McCall0153cd32011-11-08 04:01:03 +00001074 }
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001075
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001076 const CXXRecordDecl *BaseDecl =
John McCall0153cd32011-11-08 04:01:03 +00001077 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001078
John McCall0153cd32011-11-08 04:01:03 +00001079 // Remember if this base has virtual bases itself.
1080 if (BaseDecl->getNumVBases())
1081 HasNonVirtualBaseWithVBTable = true;
1082
1083 // Skip the primary base, because we've already laid it out. The
1084 // !PrimaryBaseIsVirtual check is required because we might have a
1085 // non-virtual base of the same type as a primary virtual base.
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001086 if (BaseDecl == PrimaryBase && !PrimaryBaseIsVirtual)
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001087 continue;
1088
1089 // Lay out the base.
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001090 BaseSubobjectInfo *BaseInfo = NonVirtualBaseInfo.lookup(BaseDecl);
1091 assert(BaseInfo && "Did not find base info for non-virtual base!");
1092
1093 LayoutNonVirtualBase(BaseInfo);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001094 }
Eli Friedman5e9534b2011-10-18 00:55:28 +00001095
John McCall0153cd32011-11-08 04:01:03 +00001096 // In the MS ABI, add the vb-table pointer if we need one, which is
1097 // whenever we have a virtual base and we can't re-use a vb-table
1098 // pointer from a non-virtual base.
1099 if (isMicrosoftCXXABI() &&
1100 HasDirectVirtualBases && !HasNonVirtualBaseWithVBTable) {
Eli Friedman5e9534b2011-10-18 00:55:28 +00001101 CharUnits PtrWidth =
1102 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Eli Friedman43114f92011-10-21 22:49:56 +00001103 CharUnits PtrAlign =
1104 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0));
John McCall0153cd32011-11-08 04:01:03 +00001105
1106 // MSVC potentially over-aligns the vb-table pointer by giving it
1107 // the max alignment of all the non-virtual objects in the class.
1108 // This is completely unnecessary, but we're not here to pass
1109 // judgment.
1110 //
1111 // Note that we've only laid out the non-virtual bases, so on the
1112 // first pass Alignment won't be set correctly here, but if the
1113 // vb-table doesn't end up aligned correctly we'll come through
1114 // and redo the layout from scratch with the right alignment.
1115 //
1116 // TODO: Instead of doing this, just lay out the fields as if the
1117 // vb-table were at offset zero, then retroactively bump the field
1118 // offsets up.
Eli Friedman43114f92011-10-21 22:49:56 +00001119 PtrAlign = std::max(PtrAlign, Alignment);
John McCall0153cd32011-11-08 04:01:03 +00001120
1121 EnsureVTablePointerAlignment(PtrAlign);
1122 VBPtrOffset = getSize();
1123 setSize(getSize() + PtrWidth);
1124 setDataSize(getSize());
Eli Friedman5e9534b2011-10-18 00:55:28 +00001125 }
Anders Carlsson09ffa322010-03-10 22:21:28 +00001126}
1127
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001128void RecordLayoutBuilder::LayoutNonVirtualBase(const BaseSubobjectInfo *Base) {
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001129 // Layout the base.
Anders Carlssona2f8e412010-10-31 22:20:42 +00001130 CharUnits Offset = LayoutBase(Base);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001131
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001132 // Add its base class offset.
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001133 assert(!Bases.count(Base->Class) && "base offset already exists!");
Anders Carlssona2f8e412010-10-31 22:20:42 +00001134 Bases.insert(std::make_pair(Base->Class, Offset));
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001135
1136 AddPrimaryVirtualBaseOffsets(Base, Offset);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001137}
Mike Stump2b84dd32009-11-05 04:02:15 +00001138
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001139void
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001140RecordLayoutBuilder::AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
Anders Carlssona2f8e412010-10-31 22:20:42 +00001141 CharUnits Offset) {
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001142 // This base isn't interesting, it has no virtual bases.
1143 if (!Info->Class->getNumVBases())
1144 return;
1145
1146 // First, check if we have a virtual primary base to add offsets for.
1147 if (Info->PrimaryVirtualBaseInfo) {
1148 assert(Info->PrimaryVirtualBaseInfo->IsVirtual &&
1149 "Primary virtual base is not virtual!");
1150 if (Info->PrimaryVirtualBaseInfo->Derived == Info) {
1151 // Add the offset.
1152 assert(!VBases.count(Info->PrimaryVirtualBaseInfo->Class) &&
1153 "primary vbase offset already exists!");
1154 VBases.insert(std::make_pair(Info->PrimaryVirtualBaseInfo->Class,
John McCalle42a3362012-05-01 08:55:32 +00001155 ASTRecordLayout::VBaseInfo(Offset, false)));
Anders Carlssonea7b1822010-04-15 16:12:58 +00001156
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001157 // Traverse the primary virtual base.
1158 AddPrimaryVirtualBaseOffsets(Info->PrimaryVirtualBaseInfo, Offset);
1159 }
Anders Carlssonea7b1822010-04-15 16:12:58 +00001160 }
1161
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001162 // Now go through all direct non-virtual bases.
1163 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
1164 for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) {
1165 const BaseSubobjectInfo *Base = Info->Bases[I];
1166 if (Base->IsVirtual)
Anders Carlssonea7b1822010-04-15 16:12:58 +00001167 continue;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001168
Anders Carlsson0a14ee92010-11-01 00:21:58 +00001169 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001170 AddPrimaryVirtualBaseOffsets(Base, BaseOffset);
Anders Carlssonea7b1822010-04-15 16:12:58 +00001171 }
1172}
1173
John McCall0153cd32011-11-08 04:01:03 +00001174/// needsVFTable - Return true if this class needs a vtable or vf-table
1175/// when laid out as a base class. These are treated the same because
1176/// they're both always laid out at offset zero.
1177///
1178/// This function assumes that the class has no primary base.
1179bool RecordLayoutBuilder::needsVFTable(const CXXRecordDecl *RD) const {
1180 assert(!PrimaryBase);
1181
1182 // In the Itanium ABI, every dynamic class needs a vtable: even if
1183 // this class has no virtual functions as a base class (i.e. it's
1184 // non-polymorphic or only has virtual functions from virtual
1185 // bases),x it still needs a vtable to locate its virtual bases.
1186 if (!isMicrosoftCXXABI())
1187 return RD->isDynamicClass();
1188
1189 // In the MS ABI, we need a vfptr if the class has virtual functions
1190 // other than those declared by its virtual bases. The AST doesn't
1191 // tell us that directly, and checking manually for virtual
1192 // functions that aren't overrides is expensive, but there are
1193 // some important shortcuts:
1194
1195 // - Non-polymorphic classes have no virtual functions at all.
1196 if (!RD->isPolymorphic()) return false;
1197
1198 // - Polymorphic classes with no virtual bases must either declare
1199 // virtual functions directly or inherit them, but in the latter
1200 // case we would have a primary base.
1201 if (RD->getNumVBases() == 0) return true;
1202
1203 return hasNewVirtualFunction(RD);
1204}
1205
John McCalle42a3362012-05-01 08:55:32 +00001206/// Does the given class inherit non-virtually from any of the classes
1207/// in the given set?
1208static bool hasNonVirtualBaseInSet(const CXXRecordDecl *RD,
1209 const ClassSetTy &set) {
1210 for (CXXRecordDecl::base_class_const_iterator
1211 I = RD->bases_begin(), E = RD->bases_end(); I != E; ++I) {
1212 // Ignore virtual links.
1213 if (I->isVirtual()) continue;
1214
1215 // Check whether the set contains the base.
1216 const CXXRecordDecl *base = I->getType()->getAsCXXRecordDecl();
1217 if (set.count(base))
1218 return true;
1219
1220 // Otherwise, recurse and propagate.
1221 if (hasNonVirtualBaseInSet(base, set))
1222 return true;
1223 }
1224
1225 return false;
1226}
1227
1228/// Does the given method (B::foo()) already override a method (A::foo())
1229/// such that A requires a vtordisp in B? If so, we don't need to add a
1230/// new vtordisp for B in a yet-more-derived class C providing C::foo().
1231static bool overridesMethodRequiringVtorDisp(const ASTContext &Context,
1232 const CXXMethodDecl *M) {
1233 CXXMethodDecl::method_iterator
1234 I = M->begin_overridden_methods(), E = M->end_overridden_methods();
1235 if (I == E) return false;
1236
1237 const ASTRecordLayout::VBaseOffsetsMapTy &offsets =
1238 Context.getASTRecordLayout(M->getParent()).getVBaseOffsetsMap();
1239 do {
1240 const CXXMethodDecl *overridden = *I;
1241
1242 // If the overridden method's class isn't recognized as a virtual
1243 // base in the derived class, ignore it.
1244 ASTRecordLayout::VBaseOffsetsMapTy::const_iterator
1245 it = offsets.find(overridden->getParent());
1246 if (it == offsets.end()) continue;
1247
1248 // Otherwise, check if the overridden method's class needs a vtordisp.
1249 if (it->second.hasVtorDisp()) return true;
1250
1251 } while (++I != E);
1252 return false;
1253}
1254
1255/// In the Microsoft ABI, decide which of the virtual bases require a
1256/// vtordisp field.
1257void RecordLayoutBuilder::computeVtordisps(const CXXRecordDecl *RD,
1258 ClassSetTy &vtordispVBases) {
1259 // Bail out if we have no virtual bases.
1260 assert(RD->getNumVBases());
1261
1262 // Build up the set of virtual bases that we haven't decided yet.
1263 ClassSetTy undecidedVBases;
1264 for (CXXRecordDecl::base_class_const_iterator
1265 I = RD->vbases_begin(), E = RD->vbases_end(); I != E; ++I) {
1266 const CXXRecordDecl *vbase = I->getType()->getAsCXXRecordDecl();
1267 undecidedVBases.insert(vbase);
1268 }
1269 assert(!undecidedVBases.empty());
1270
1271 // A virtual base requires a vtordisp field in a derived class if it
1272 // requires a vtordisp field in a base class. Walk all the direct
1273 // bases and collect this information.
1274 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1275 E = RD->bases_end(); I != E; ++I) {
1276 const CXXRecordDecl *base = I->getType()->getAsCXXRecordDecl();
1277 const ASTRecordLayout &baseLayout = Context.getASTRecordLayout(base);
1278
1279 // Iterate over the set of virtual bases provided by this class.
1280 for (ASTRecordLayout::VBaseOffsetsMapTy::const_iterator
1281 VI = baseLayout.getVBaseOffsetsMap().begin(),
1282 VE = baseLayout.getVBaseOffsetsMap().end(); VI != VE; ++VI) {
1283 // If it doesn't need a vtordisp in this base, ignore it.
1284 if (!VI->second.hasVtorDisp()) continue;
1285
1286 // If we've already seen it and decided it needs a vtordisp, ignore it.
1287 if (!undecidedVBases.erase(VI->first))
1288 continue;
1289
1290 // Add it.
1291 vtordispVBases.insert(VI->first);
1292
1293 // Quit as soon as we've decided everything.
1294 if (undecidedVBases.empty())
1295 return;
1296 }
1297 }
1298
1299 // Okay, we have virtual bases that we haven't yet decided about. A
1300 // virtual base requires a vtordisp if any the non-destructor
1301 // virtual methods declared in this class directly override a method
1302 // provided by that virtual base. (If so, we need to emit a thunk
1303 // for that method, to be used in the construction vftable, which
1304 // applies an additional 'vtordisp' this-adjustment.)
1305
1306 // Collect the set of bases directly overridden by any method in this class.
1307 // It's possible that some of these classes won't be virtual bases, or won't be
1308 // provided by virtual bases, or won't be virtual bases in the overridden
1309 // instance but are virtual bases elsewhere. Only the last matters for what
1310 // we're doing, and we can ignore those: if we don't directly override
1311 // a method provided by a virtual copy of a base class, but we do directly
1312 // override a method provided by a non-virtual copy of that base class,
1313 // then we must indirectly override the method provided by the virtual base,
1314 // and so we should already have collected it in the loop above.
1315 ClassSetTy overriddenBases;
1316 for (CXXRecordDecl::method_iterator
1317 M = RD->method_begin(), E = RD->method_end(); M != E; ++M) {
1318 // Ignore non-virtual methods and destructors.
1319 if (isa<CXXDestructorDecl>(*M) || !M->isVirtual())
1320 continue;
1321
1322 for (CXXMethodDecl::method_iterator I = M->begin_overridden_methods(),
1323 E = M->end_overridden_methods(); I != E; ++I) {
1324 const CXXMethodDecl *overriddenMethod = (*I);
1325
1326 // Ignore methods that override methods from vbases that require
1327 // require vtordisps.
1328 if (overridesMethodRequiringVtorDisp(Context, overriddenMethod))
1329 continue;
1330
1331 // As an optimization, check immediately whether we're overriding
1332 // something from the undecided set.
1333 const CXXRecordDecl *overriddenBase = overriddenMethod->getParent();
1334 if (undecidedVBases.erase(overriddenBase)) {
1335 vtordispVBases.insert(overriddenBase);
1336 if (undecidedVBases.empty()) return;
1337
1338 // We can't 'continue;' here because one of our undecided
1339 // vbases might non-virtually inherit from this base.
1340 // Consider:
1341 // struct A { virtual void foo(); };
1342 // struct B : A {};
1343 // struct C : virtual A, virtual B { virtual void foo(); };
1344 // We need a vtordisp for B here.
1345 }
1346
1347 // Otherwise, just collect it.
1348 overriddenBases.insert(overriddenBase);
1349 }
1350 }
1351
1352 // Walk the undecided v-bases and check whether they (non-virtually)
1353 // provide any of the overridden bases. We don't need to consider
1354 // virtual links because the vtordisp inheres to the layout
1355 // subobject containing the base.
1356 for (ClassSetTy::const_iterator
1357 I = undecidedVBases.begin(), E = undecidedVBases.end(); I != E; ++I) {
1358 if (hasNonVirtualBaseInSet(*I, overriddenBases))
1359 vtordispVBases.insert(*I);
1360 }
1361}
1362
John McCall0153cd32011-11-08 04:01:03 +00001363/// hasNewVirtualFunction - Does the given polymorphic class declare a
1364/// virtual function that does not override a method from any of its
1365/// base classes?
Eli Friedman84d2d3a2011-09-27 19:12:27 +00001366bool
John McCalle42a3362012-05-01 08:55:32 +00001367RecordLayoutBuilder::hasNewVirtualFunction(const CXXRecordDecl *RD,
1368 bool IgnoreDestructor) const {
John McCall0153cd32011-11-08 04:01:03 +00001369 if (!RD->getNumBases())
1370 return true;
1371
Eli Friedman84d2d3a2011-09-27 19:12:27 +00001372 for (CXXRecordDecl::method_iterator method = RD->method_begin();
1373 method != RD->method_end();
1374 ++method) {
John McCalle42a3362012-05-01 08:55:32 +00001375 if (method->isVirtual() && !method->size_overridden_methods() &&
1376 !(IgnoreDestructor && method->getKind() == Decl::CXXDestructor)) {
Eli Friedman84d2d3a2011-09-27 19:12:27 +00001377 return true;
1378 }
1379 }
1380 return false;
1381}
1382
John McCall0153cd32011-11-08 04:01:03 +00001383/// isPossiblePrimaryBase - Is the given base class an acceptable
1384/// primary base class?
Eli Friedman5e9534b2011-10-18 00:55:28 +00001385bool
John McCalle42a3362012-05-01 08:55:32 +00001386RecordLayoutBuilder::isPossiblePrimaryBase(const CXXRecordDecl *base) const {
John McCall0153cd32011-11-08 04:01:03 +00001387 // In the Itanium ABI, a class can be a primary base class if it has
1388 // a vtable for any reason.
1389 if (!isMicrosoftCXXABI())
John McCalle42a3362012-05-01 08:55:32 +00001390 return base->isDynamicClass();
John McCall0153cd32011-11-08 04:01:03 +00001391
1392 // In the MS ABI, a class can only be a primary base class if it
1393 // provides a vf-table at a static offset. That means it has to be
1394 // non-virtual base. The existence of a separate vb-table means
1395 // that it's possible to get virtual functions only from a virtual
1396 // base, which we have to guard against.
1397
1398 // First off, it has to have virtual functions.
John McCalle42a3362012-05-01 08:55:32 +00001399 if (!base->isPolymorphic()) return false;
John McCall0153cd32011-11-08 04:01:03 +00001400
John McCalle42a3362012-05-01 08:55:32 +00001401 // If it has no virtual bases, then the vfptr must be at a static offset.
1402 if (!base->getNumVBases()) return true;
1403
1404 // Otherwise, the necessary information is cached in the layout.
1405 const ASTRecordLayout &layout = Context.getASTRecordLayout(base);
John McCall0153cd32011-11-08 04:01:03 +00001406
John McCalle42a3362012-05-01 08:55:32 +00001407 // If the base has its own vfptr, it can be a primary base.
1408 if (layout.hasOwnVFPtr()) return true;
1409
1410 // If the base has a primary base class, then it can be a primary base.
1411 if (layout.getPrimaryBase()) return true;
1412
1413 // Otherwise it can't.
1414 return false;
Eli Friedman84d2d3a2011-09-27 19:12:27 +00001415}
1416
Anders Carlssonea7b1822010-04-15 16:12:58 +00001417void
Anders Carlssonc2226202010-05-26 05:58:59 +00001418RecordLayoutBuilder::LayoutVirtualBases(const CXXRecordDecl *RD,
Anders Carlssonea7b1822010-04-15 16:12:58 +00001419 const CXXRecordDecl *MostDerivedClass) {
Anders Carlssonde710c92010-03-11 04:33:54 +00001420 const CXXRecordDecl *PrimaryBase;
Anders Carlsson291279e2010-04-10 18:42:27 +00001421 bool PrimaryBaseIsVirtual;
Anders Carlssonfe900962010-03-11 05:42:17 +00001422
Anders Carlsson291279e2010-04-10 18:42:27 +00001423 if (MostDerivedClass == RD) {
Anders Carlssond20e7cd2010-05-26 05:20:58 +00001424 PrimaryBase = this->PrimaryBase;
1425 PrimaryBaseIsVirtual = this->PrimaryBaseIsVirtual;
Anders Carlsson291279e2010-04-10 18:42:27 +00001426 } else {
Anders Carlsson5efc56e2010-04-16 15:07:51 +00001427 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Anders Carlssonde710c92010-03-11 04:33:54 +00001428 PrimaryBase = Layout.getPrimaryBase();
Anders Carlsson7f95cd12010-11-24 23:12:57 +00001429 PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
Anders Carlsson291279e2010-04-10 18:42:27 +00001430 }
1431
Anders Carlssonf7b7a1e2010-03-11 04:24:02 +00001432 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1433 E = RD->bases_end(); I != E; ++I) {
1434 assert(!I->getType()->isDependentType() &&
Sebastian Redl1054fae2009-10-25 17:03:50 +00001435 "Cannot layout class with dependent bases.");
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001436
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001437 const CXXRecordDecl *BaseDecl =
John McCall0153cd32011-11-08 04:01:03 +00001438 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
Anders Carlssonf7b7a1e2010-03-11 04:24:02 +00001439
1440 if (I->isVirtual()) {
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001441 if (PrimaryBase != BaseDecl || !PrimaryBaseIsVirtual) {
1442 bool IndirectPrimaryBase = IndirectPrimaryBases.count(BaseDecl);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001443
Anders Carlsson291279e2010-04-10 18:42:27 +00001444 // Only lay out the virtual base if it's not an indirect primary base.
1445 if (!IndirectPrimaryBase) {
1446 // Only visit virtual bases once.
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001447 if (!VisitedVirtualBases.insert(BaseDecl))
Anders Carlsson291279e2010-04-10 18:42:27 +00001448 continue;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001449
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001450 const BaseSubobjectInfo *BaseInfo = VirtualBaseInfo.lookup(BaseDecl);
1451 assert(BaseInfo && "Did not find virtual base info!");
1452 LayoutVirtualBase(BaseInfo);
Anders Carlsson6a848892010-03-11 04:10:39 +00001453 }
Mike Stump2b84dd32009-11-05 04:02:15 +00001454 }
Mike Stumpc2f591b2009-08-13 22:53:07 +00001455 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001456
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001457 if (!BaseDecl->getNumVBases()) {
Anders Carlssonf7b7a1e2010-03-11 04:24:02 +00001458 // This base isn't interesting since it doesn't have any virtual bases.
1459 continue;
Mike Stump996576f32009-08-16 19:04:13 +00001460 }
Anders Carlssonf7b7a1e2010-03-11 04:24:02 +00001461
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001462 LayoutVirtualBases(BaseDecl, MostDerivedClass);
Mike Stump6b2556f2009-08-06 13:41:24 +00001463 }
1464}
1465
John McCall0153cd32011-11-08 04:01:03 +00001466void RecordLayoutBuilder::MSLayoutVirtualBases(const CXXRecordDecl *RD) {
John McCall0153cd32011-11-08 04:01:03 +00001467 if (!RD->getNumVBases())
1468 return;
1469
John McCalle42a3362012-05-01 08:55:32 +00001470 ClassSetTy VtordispVBases;
1471 computeVtordisps(RD, VtordispVBases);
1472
John McCall0153cd32011-11-08 04:01:03 +00001473 // This is substantially simplified because there are no virtual
1474 // primary bases.
1475 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
1476 E = RD->vbases_end(); I != E; ++I) {
1477 const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
1478 const BaseSubobjectInfo *BaseInfo = VirtualBaseInfo.lookup(BaseDecl);
1479 assert(BaseInfo && "Did not find virtual base info!");
John McCalle42a3362012-05-01 08:55:32 +00001480
1481 // If this base requires a vtordisp, add enough space for an int field.
1482 // This is apparently always 32-bits, even on x64.
1483 bool vtordispNeeded = false;
1484 if (VtordispVBases.count(BaseDecl)) {
1485 CharUnits IntSize =
1486 CharUnits::fromQuantity(Context.getTargetInfo().getIntWidth() / 8);
1487
1488 setSize(getSize() + IntSize);
1489 setDataSize(getSize());
1490 vtordispNeeded = true;
1491 }
1492
1493 LayoutVirtualBase(BaseInfo, vtordispNeeded);
John McCall0153cd32011-11-08 04:01:03 +00001494 }
1495}
1496
John McCalle42a3362012-05-01 08:55:32 +00001497void RecordLayoutBuilder::LayoutVirtualBase(const BaseSubobjectInfo *Base,
1498 bool IsVtordispNeed) {
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001499 assert(!Base->Derived && "Trying to lay out a primary virtual base!");
1500
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001501 // Layout the base.
Anders Carlssona2f8e412010-10-31 22:20:42 +00001502 CharUnits Offset = LayoutBase(Base);
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001503
1504 // Add its base class offset.
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001505 assert(!VBases.count(Base->Class) && "vbase offset already exists!");
John McCalle42a3362012-05-01 08:55:32 +00001506 VBases.insert(std::make_pair(Base->Class,
1507 ASTRecordLayout::VBaseInfo(Offset, IsVtordispNeed)));
1508
1509 if (!isMicrosoftCXXABI())
1510 AddPrimaryVirtualBaseOffsets(Base, Offset);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001511}
1512
Anders Carlssona2f8e412010-10-31 22:20:42 +00001513CharUnits RecordLayoutBuilder::LayoutBase(const BaseSubobjectInfo *Base) {
Anders Carlssond7f3fcf2010-05-29 20:47:33 +00001514 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base->Class);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001515
Douglas Gregore9fc3772012-01-26 07:55:45 +00001516
1517 CharUnits Offset;
1518
1519 // Query the external layout to see if it provides an offset.
1520 bool HasExternalLayout = false;
1521 if (ExternalLayout) {
1522 llvm::DenseMap<const CXXRecordDecl *, CharUnits>::iterator Known;
1523 if (Base->IsVirtual) {
1524 Known = ExternalVirtualBaseOffsets.find(Base->Class);
1525 if (Known != ExternalVirtualBaseOffsets.end()) {
1526 Offset = Known->second;
1527 HasExternalLayout = true;
1528 }
1529 } else {
1530 Known = ExternalBaseOffsets.find(Base->Class);
1531 if (Known != ExternalBaseOffsets.end()) {
1532 Offset = Known->second;
1533 HasExternalLayout = true;
1534 }
1535 }
1536 }
1537
Anders Carlsson09ffa322010-03-10 22:21:28 +00001538 // If we have an empty base class, try to place it at offset 0.
Anders Carlssond7f3fcf2010-05-29 20:47:33 +00001539 if (Base->Class->isEmpty() &&
Douglas Gregore9fc3772012-01-26 07:55:45 +00001540 (!HasExternalLayout || Offset == CharUnits::Zero()) &&
Anders Carlsson28466ab2010-10-31 22:13:23 +00001541 EmptySubobjects->CanPlaceBaseAtOffset(Base, CharUnits::Zero())) {
Ken Dyck1b4420e2011-02-28 02:01:38 +00001542 setSize(std::max(getSize(), Layout.getSize()));
Anders Carlsson09ffa322010-03-10 22:21:28 +00001543
Anders Carlssona2f8e412010-10-31 22:20:42 +00001544 return CharUnits::Zero();
Anders Carlsson09ffa322010-03-10 22:21:28 +00001545 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001546
Ken Dyck85ef0432011-02-19 18:58:07 +00001547 CharUnits UnpackedBaseAlign = Layout.getNonVirtualAlign();
1548 CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
Argyrios Kyrtzidis8b542742010-12-09 00:35:20 +00001549
1550 // The maximum field alignment overrides base align.
Ken Dyck02ced6f2011-02-17 01:49:42 +00001551 if (!MaxFieldAlignment.isZero()) {
Ken Dyck85ef0432011-02-19 18:58:07 +00001552 BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
1553 UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
Argyrios Kyrtzidis8b542742010-12-09 00:35:20 +00001554 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001555
Douglas Gregore9fc3772012-01-26 07:55:45 +00001556 if (!HasExternalLayout) {
1557 // Round up the current record size to the base's alignment boundary.
1558 Offset = getDataSize().RoundUpToAlignment(BaseAlign);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001559
Douglas Gregore9fc3772012-01-26 07:55:45 +00001560 // Try to place the base.
1561 while (!EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset))
1562 Offset += BaseAlign;
1563 } else {
1564 bool Allowed = EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset);
1565 (void)Allowed;
1566 assert(Allowed && "Base subobject externally placed at overlapping offset");
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001567
1568 if (InferAlignment && Offset < getDataSize().RoundUpToAlignment(BaseAlign)){
1569 // The externally-supplied base offset is before the base offset we
1570 // computed. Assume that the structure is packed.
1571 Alignment = CharUnits::One();
1572 InferAlignment = false;
1573 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00001574 }
1575
Anders Carlssond7f3fcf2010-05-29 20:47:33 +00001576 if (!Base->Class->isEmpty()) {
Anders Carlsson09ffa322010-03-10 22:21:28 +00001577 // Update the data size.
Ken Dyck1b4420e2011-02-28 02:01:38 +00001578 setDataSize(Offset + Layout.getNonVirtualSize());
Anders Carlsson09ffa322010-03-10 22:21:28 +00001579
Ken Dyck1b4420e2011-02-28 02:01:38 +00001580 setSize(std::max(getSize(), getDataSize()));
Anders Carlsson09ffa322010-03-10 22:21:28 +00001581 } else
Ken Dyck1b4420e2011-02-28 02:01:38 +00001582 setSize(std::max(getSize(), Offset + Layout.getSize()));
Anders Carlsson09ffa322010-03-10 22:21:28 +00001583
1584 // Remember max struct/class alignment.
Argyrios Kyrtzidis8b542742010-12-09 00:35:20 +00001585 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001586
Ken Dyck1b4420e2011-02-28 02:01:38 +00001587 return Offset;
Anders Carlsson09ffa322010-03-10 22:21:28 +00001588}
1589
Daniel Dunbar6da10982010-05-27 05:45:51 +00001590void RecordLayoutBuilder::InitializeLayout(const Decl *D) {
Eli Friedman9ee2d0472012-10-12 23:29:20 +00001591 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Daniel Dunbar6da10982010-05-27 05:45:51 +00001592 IsUnion = RD->isUnion();
Eli Friedman9ee2d0472012-10-12 23:29:20 +00001593 IsMsStruct = RD->isMsStruct(Context);
1594 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001595
Eli Friedman9ee2d0472012-10-12 23:29:20 +00001596 Packed = D->hasAttr<PackedAttr>();
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001597
Daniel Dunbar096ed292011-10-05 21:04:55 +00001598 // Honor the default struct packing maximum alignment flag.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001599 if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct) {
Daniel Dunbar096ed292011-10-05 21:04:55 +00001600 MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
1601 }
1602
Daniel Dunbar6da10982010-05-27 05:45:51 +00001603 // mac68k alignment supersedes maximum field alignment and attribute aligned,
1604 // and forces all structures to have 2-byte alignment. The IBM docs on it
1605 // allude to additional (more complicated) semantics, especially with regard
1606 // to bit-fields, but gcc appears not to follow that.
1607 if (D->hasAttr<AlignMac68kAttr>()) {
1608 IsMac68kAlign = true;
Ken Dyck02ced6f2011-02-17 01:49:42 +00001609 MaxFieldAlignment = CharUnits::fromQuantity(2);
Ken Dyck4731d5b2011-02-16 02:05:21 +00001610 Alignment = CharUnits::fromQuantity(2);
Daniel Dunbar6da10982010-05-27 05:45:51 +00001611 } else {
1612 if (const MaxFieldAlignmentAttr *MFAA = D->getAttr<MaxFieldAlignmentAttr>())
Ken Dyck02ced6f2011-02-17 01:49:42 +00001613 MaxFieldAlignment = Context.toCharUnitsFromBits(MFAA->getAlignment());
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001614
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001615 if (unsigned MaxAlign = D->getMaxAlignment())
Ken Dyck85ef0432011-02-19 18:58:07 +00001616 UpdateAlignment(Context.toCharUnitsFromBits(MaxAlign));
Daniel Dunbar6da10982010-05-27 05:45:51 +00001617 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00001618
1619 // If there is an external AST source, ask it for the various offsets.
1620 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
1621 if (ExternalASTSource *External = Context.getExternalSource()) {
1622 ExternalLayout = External->layoutRecordType(RD,
1623 ExternalSize,
1624 ExternalAlign,
1625 ExternalFieldOffsets,
1626 ExternalBaseOffsets,
1627 ExternalVirtualBaseOffsets);
1628
1629 // Update based on external alignment.
1630 if (ExternalLayout) {
Douglas Gregor44ba7892012-01-28 00:53:29 +00001631 if (ExternalAlign > 0) {
1632 Alignment = Context.toCharUnitsFromBits(ExternalAlign);
Douglas Gregor44ba7892012-01-28 00:53:29 +00001633 } else {
1634 // The external source didn't have alignment information; infer it.
1635 InferAlignment = true;
1636 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00001637 }
1638 }
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001639}
Anders Carlsson6d9f6f32009-07-19 00:18:47 +00001640
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001641void RecordLayoutBuilder::Layout(const RecordDecl *D) {
1642 InitializeLayout(D);
Anders Carlsson118ce162009-07-18 21:48:39 +00001643 LayoutFields(D);
Mike Stump11289f42009-09-09 15:08:12 +00001644
Anders Carlsson79474332009-07-18 20:20:21 +00001645 // Finally, round the size of the total struct up to the alignment of the
1646 // struct itself.
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001647 FinishLayout(D);
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001648}
1649
1650void RecordLayoutBuilder::Layout(const CXXRecordDecl *RD) {
1651 InitializeLayout(RD);
1652
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001653 // Lay out the vtable and the non-virtual bases.
1654 LayoutNonVirtualBases(RD);
1655
1656 LayoutFields(RD);
1657
Ken Dycke7380752011-03-10 01:53:59 +00001658 NonVirtualSize = Context.toCharUnitsFromBits(
1659 llvm::RoundUpToAlignment(getSizeInBits(),
Douglas Gregore8bbc122011-09-02 00:18:52 +00001660 Context.getTargetInfo().getCharAlign()));
Ken Dyck4731d5b2011-02-16 02:05:21 +00001661 NonVirtualAlignment = Alignment;
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001662
John McCalle42a3362012-05-01 08:55:32 +00001663 if (isMicrosoftCXXABI()) {
1664 if (NonVirtualSize != NonVirtualSize.RoundUpToAlignment(Alignment)) {
John McCall0153cd32011-11-08 04:01:03 +00001665 CharUnits AlignMember =
1666 NonVirtualSize.RoundUpToAlignment(Alignment) - NonVirtualSize;
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001667
John McCall0153cd32011-11-08 04:01:03 +00001668 setSize(getSize() + AlignMember);
1669 setDataSize(getSize());
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001670
John McCall0153cd32011-11-08 04:01:03 +00001671 NonVirtualSize = Context.toCharUnitsFromBits(
1672 llvm::RoundUpToAlignment(getSizeInBits(),
1673 Context.getTargetInfo().getCharAlign()));
John McCalle42a3362012-05-01 08:55:32 +00001674 }
John McCall0153cd32011-11-08 04:01:03 +00001675
1676 MSLayoutVirtualBases(RD);
John McCall0153cd32011-11-08 04:01:03 +00001677 } else {
1678 // Lay out the virtual bases and add the primary virtual base offsets.
1679 LayoutVirtualBases(RD, RD);
1680 }
1681
1682 // Finally, round the size of the total struct up to the alignment
Eli Friedman83a12582011-12-01 00:37:01 +00001683 // of the struct itself.
1684 FinishLayout(RD);
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001685
Anders Carlsson5b441d72010-04-10 21:24:48 +00001686#ifndef NDEBUG
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001687 // Check that we have base offsets for all bases.
1688 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1689 E = RD->bases_end(); I != E; ++I) {
1690 if (I->isVirtual())
1691 continue;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001692
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001693 const CXXRecordDecl *BaseDecl =
1694 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1695
1696 assert(Bases.count(BaseDecl) && "Did not find base offset!");
1697 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001698
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001699 // And all virtual bases.
1700 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
1701 E = RD->vbases_end(); I != E; ++I) {
1702 const CXXRecordDecl *BaseDecl =
1703 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001704
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001705 assert(VBases.count(BaseDecl) && "Did not find base offset!");
Anders Carlsson5b441d72010-04-10 21:24:48 +00001706 }
1707#endif
Anders Carlsson79474332009-07-18 20:20:21 +00001708}
1709
Anders Carlssonc2226202010-05-26 05:58:59 +00001710void RecordLayoutBuilder::Layout(const ObjCInterfaceDecl *D) {
Anders Carlsson4f516282009-07-18 20:50:59 +00001711 if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
Anders Carlsson5efc56e2010-04-16 15:07:51 +00001712 const ASTRecordLayout &SL = Context.getASTObjCInterfaceLayout(SD);
Anders Carlsson4f516282009-07-18 20:50:59 +00001713
Ken Dyck85ef0432011-02-19 18:58:07 +00001714 UpdateAlignment(SL.getAlignment());
Mike Stump11289f42009-09-09 15:08:12 +00001715
Anders Carlsson4f516282009-07-18 20:50:59 +00001716 // We start laying out ivars not at the end of the superclass
1717 // structure, but at the next byte following the last field.
Ken Dyckecfc7552011-02-24 01:13:28 +00001718 setSize(SL.getDataSize());
Ken Dyck1b4420e2011-02-28 02:01:38 +00001719 setDataSize(getSize());
Anders Carlsson4f516282009-07-18 20:50:59 +00001720 }
Mike Stump11289f42009-09-09 15:08:12 +00001721
Daniel Dunbar6da10982010-05-27 05:45:51 +00001722 InitializeLayout(D);
Anders Carlsson4f516282009-07-18 20:50:59 +00001723 // Layout each ivar sequentially.
Jordy Rosea91768e2011-07-22 02:08:32 +00001724 for (const ObjCIvarDecl *IVD = D->all_declared_ivar_begin(); IVD;
1725 IVD = IVD->getNextIvar())
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001726 LayoutField(IVD);
Mike Stump11289f42009-09-09 15:08:12 +00001727
Anders Carlsson4f516282009-07-18 20:50:59 +00001728 // Finally, round the size of the total struct up to the alignment of the
1729 // struct itself.
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001730 FinishLayout(D);
Anders Carlsson4f516282009-07-18 20:50:59 +00001731}
1732
Anders Carlssonc2226202010-05-26 05:58:59 +00001733void RecordLayoutBuilder::LayoutFields(const RecordDecl *D) {
Anders Carlsson118ce162009-07-18 21:48:39 +00001734 // Layout each field, for now, just sequentially, respecting alignment. In
1735 // the future, this will need to be tweakable by targets.
Fariborz Jahanianfc0fe6e2011-05-03 20:21:04 +00001736 ZeroLengthBitfield = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001737 for (RecordDecl::field_iterator Field = D->field_begin(),
Fariborz Jahanianbcb23a12011-04-26 23:52:16 +00001738 FieldEnd = D->field_end(); Field != FieldEnd; ++Field) {
Eli Friedman2782dac2013-06-26 20:50:34 +00001739 if (!Context.getTargetInfo().useBitFieldTypeAlignment() &&
1740 Context.getTargetInfo().useZeroLengthBitfieldAlignment()) {
David Blaikie40ed2972012-06-06 20:45:41 +00001741 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
1742 ZeroLengthBitfield = *Field;
Chad Rosier18903ee2011-08-04 01:21:14 +00001743 }
David Blaikie40ed2972012-06-06 20:45:41 +00001744 LayoutField(*Field);
Fariborz Jahanianbcb23a12011-04-26 23:52:16 +00001745 }
Anders Carlsson118ce162009-07-18 21:48:39 +00001746}
1747
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001748void RecordLayoutBuilder::LayoutWideBitField(uint64_t FieldSize,
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001749 uint64_t TypeSize,
1750 bool FieldPacked,
1751 const FieldDecl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001752 assert(Context.getLangOpts().CPlusPlus &&
Anders Carlsson57235162010-04-16 15:57:11 +00001753 "Can only have wide bit-fields in C++!");
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001754
Anders Carlsson57235162010-04-16 15:57:11 +00001755 // Itanium C++ ABI 2.4:
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001756 // If sizeof(T)*8 < n, let T' be the largest integral POD type with
Anders Carlsson57235162010-04-16 15:57:11 +00001757 // sizeof(T')*8 <= n.
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001758
Anders Carlsson57235162010-04-16 15:57:11 +00001759 QualType IntegralPODTypes[] = {
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001760 Context.UnsignedCharTy, Context.UnsignedShortTy, Context.UnsignedIntTy,
Anders Carlsson57235162010-04-16 15:57:11 +00001761 Context.UnsignedLongTy, Context.UnsignedLongLongTy
1762 };
1763
Anders Carlsson57235162010-04-16 15:57:11 +00001764 QualType Type;
1765 for (unsigned I = 0, E = llvm::array_lengthof(IntegralPODTypes);
1766 I != E; ++I) {
1767 uint64_t Size = Context.getTypeSize(IntegralPODTypes[I]);
Anders Carlsson57235162010-04-16 15:57:11 +00001768
1769 if (Size > FieldSize)
1770 break;
1771
1772 Type = IntegralPODTypes[I];
1773 }
1774 assert(!Type.isNull() && "Did not find a type!");
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001775
Ken Dyckdbe37f32011-03-01 01:36:00 +00001776 CharUnits TypeAlign = Context.getTypeAlignInChars(Type);
Anders Carlsson57235162010-04-16 15:57:11 +00001777
1778 // We're not going to use any of the unfilled bits in the last byte.
Eli Friedman2782dac2013-06-26 20:50:34 +00001779 UnfilledBitsInLastUnit = 0;
1780 LastBitfieldTypeSize = 0;
Anders Carlsson57235162010-04-16 15:57:11 +00001781
Anders Carlssonaad5fa82010-04-17 20:21:41 +00001782 uint64_t FieldOffset;
Eli Friedman2782dac2013-06-26 20:50:34 +00001783 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001784
Anders Carlsson57235162010-04-16 15:57:11 +00001785 if (IsUnion) {
Ken Dyckecfc7552011-02-24 01:13:28 +00001786 setDataSize(std::max(getDataSizeInBits(), FieldSize));
Anders Carlssonaad5fa82010-04-17 20:21:41 +00001787 FieldOffset = 0;
Anders Carlsson57235162010-04-16 15:57:11 +00001788 } else {
Chad Rosiere1a6a0e2011-08-05 22:38:04 +00001789 // The bitfield is allocated starting at the next offset aligned
1790 // appropriately for T', with length n bits.
Ken Dyckdbe37f32011-03-01 01:36:00 +00001791 FieldOffset = llvm::RoundUpToAlignment(getDataSizeInBits(),
1792 Context.toBits(TypeAlign));
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001793
Anders Carlsson57235162010-04-16 15:57:11 +00001794 uint64_t NewSizeInBits = FieldOffset + FieldSize;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001795
Ken Dycka1a2e8d2011-03-10 02:00:35 +00001796 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits,
Douglas Gregore8bbc122011-09-02 00:18:52 +00001797 Context.getTargetInfo().getCharAlign()));
Eli Friedman2782dac2013-06-26 20:50:34 +00001798 UnfilledBitsInLastUnit = getDataSizeInBits() - NewSizeInBits;
Anders Carlsson57235162010-04-16 15:57:11 +00001799 }
1800
1801 // Place this field at the current location.
1802 FieldOffsets.push_back(FieldOffset);
1803
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001804 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, FieldOffset,
Ken Dyckdbe37f32011-03-01 01:36:00 +00001805 Context.toBits(TypeAlign), FieldPacked, D);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001806
Anders Carlsson57235162010-04-16 15:57:11 +00001807 // Update the size.
Ken Dyckecfc7552011-02-24 01:13:28 +00001808 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001809
Anders Carlsson57235162010-04-16 15:57:11 +00001810 // Remember max struct/class alignment.
Ken Dyckdbe37f32011-03-01 01:36:00 +00001811 UpdateAlignment(TypeAlign);
Anders Carlsson57235162010-04-16 15:57:11 +00001812}
1813
Anders Carlssonc2226202010-05-26 05:58:59 +00001814void RecordLayoutBuilder::LayoutBitField(const FieldDecl *D) {
Anders Carlsson07209442009-11-22 17:37:31 +00001815 bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
Richard Smithcaf33902011-10-10 18:28:20 +00001816 uint64_t FieldSize = D->getBitWidthValue(Context);
Anders Carlsson5efc56e2010-04-16 15:07:51 +00001817 std::pair<uint64_t, unsigned> FieldInfo = Context.getTypeInfo(D->getType());
Anders Carlsson07209442009-11-22 17:37:31 +00001818 uint64_t TypeSize = FieldInfo.first;
1819 unsigned FieldAlign = FieldInfo.second;
Eli Friedman2782dac2013-06-26 20:50:34 +00001820
1821 if (IsMsStruct) {
1822 // The field alignment for integer types in ms_struct structs is
1823 // always the size.
Fariborz Jahanian7adbed62011-05-09 22:03:17 +00001824 FieldAlign = TypeSize;
Eli Friedman2782dac2013-06-26 20:50:34 +00001825 // Ignore zero-length bitfields after non-bitfields in ms_struct structs.
1826 if (!FieldSize && !LastBitfieldTypeSize)
1827 FieldAlign = 1;
1828 // If a bitfield is followed by a bitfield of a different size, don't
1829 // pack the bits together in ms_struct structs.
1830 if (LastBitfieldTypeSize != TypeSize) {
1831 UnfilledBitsInLastUnit = 0;
1832 LastBitfieldTypeSize = 0;
1833 }
1834 }
1835
1836 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
1837 uint64_t FieldOffset = IsUnion ? 0 : UnpaddedFieldOffset;
Chad Rosier18903ee2011-08-04 01:21:14 +00001838
Fariborz Jahanianfc0fe6e2011-05-03 20:21:04 +00001839 if (ZeroLengthBitfield) {
Eli Friedman2782dac2013-06-26 20:50:34 +00001840 // The alignment of a zero-length bitfield affects the alignment
1841 // of the next member. The alignment is the max of the zero
1842 // length bitfield's alignment and a target specific fixed value.
1843 unsigned ZeroLengthBitfieldBoundary =
1844 Context.getTargetInfo().getZeroLengthBitfieldBoundary();
1845 if (ZeroLengthBitfieldBoundary > FieldAlign)
1846 FieldAlign = ZeroLengthBitfieldBoundary;
Fariborz Jahanianfc0fe6e2011-05-03 20:21:04 +00001847 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001848
Anders Carlsson57235162010-04-16 15:57:11 +00001849 if (FieldSize > TypeSize) {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001850 LayoutWideBitField(FieldSize, TypeSize, FieldPacked, D);
Anders Carlsson57235162010-04-16 15:57:11 +00001851 return;
1852 }
1853
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001854 // The align if the field is not packed. This is to check if the attribute
1855 // was unnecessary (-Wpacked).
1856 unsigned UnpackedFieldAlign = FieldAlign;
1857 uint64_t UnpackedFieldOffset = FieldOffset;
Douglas Gregore8bbc122011-09-02 00:18:52 +00001858 if (!Context.getTargetInfo().useBitFieldTypeAlignment() && !ZeroLengthBitfield)
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001859 UnpackedFieldAlign = 1;
1860
Chad Rosiere1a6a0e2011-08-05 22:38:04 +00001861 if (FieldPacked ||
Douglas Gregore8bbc122011-09-02 00:18:52 +00001862 (!Context.getTargetInfo().useBitFieldTypeAlignment() && !ZeroLengthBitfield))
Anders Carlsson07209442009-11-22 17:37:31 +00001863 FieldAlign = 1;
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001864 FieldAlign = std::max(FieldAlign, D->getMaxAlignment());
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001865 UnpackedFieldAlign = std::max(UnpackedFieldAlign, D->getMaxAlignment());
Anders Carlsson07209442009-11-22 17:37:31 +00001866
1867 // The maximum field alignment overrides the aligned attribute.
Eli Friedmana91d38a2011-12-02 02:38:48 +00001868 if (!MaxFieldAlignment.isZero() && FieldSize != 0) {
Ken Dyck02ced6f2011-02-17 01:49:42 +00001869 unsigned MaxFieldAlignmentInBits = Context.toBits(MaxFieldAlignment);
1870 FieldAlign = std::min(FieldAlign, MaxFieldAlignmentInBits);
1871 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignmentInBits);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001872 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001873
Eli Friedman2782dac2013-06-26 20:50:34 +00001874 // ms_struct bitfields always have to start at a round alignment.
1875 if (IsMsStruct && !LastBitfieldTypeSize) {
1876 FieldOffset = llvm::RoundUpToAlignment(FieldOffset, FieldAlign);
1877 UnpackedFieldOffset = llvm::RoundUpToAlignment(UnpackedFieldOffset,
1878 UnpackedFieldAlign);
1879 }
1880
Douglas Gregor44ba7892012-01-28 00:53:29 +00001881 // Check if we need to add padding to give the field the correct alignment.
1882 if (FieldSize == 0 ||
1883 (MaxFieldAlignment.isZero() &&
1884 (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize))
1885 FieldOffset = llvm::RoundUpToAlignment(FieldOffset, FieldAlign);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001886
Douglas Gregor44ba7892012-01-28 00:53:29 +00001887 if (FieldSize == 0 ||
1888 (MaxFieldAlignment.isZero() &&
1889 (UnpackedFieldOffset & (UnpackedFieldAlign-1)) + FieldSize > TypeSize))
1890 UnpackedFieldOffset = llvm::RoundUpToAlignment(UnpackedFieldOffset,
1891 UnpackedFieldAlign);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001892
Chad Rosiere1a6a0e2011-08-05 22:38:04 +00001893 // Padding members don't affect overall alignment, unless zero length bitfield
1894 // alignment is enabled.
Eli Friedman2782dac2013-06-26 20:50:34 +00001895 if (!D->getIdentifier() &&
1896 !Context.getTargetInfo().useZeroLengthBitfieldAlignment() &&
1897 !IsMsStruct)
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001898 FieldAlign = UnpackedFieldAlign = 1;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001899
Eli Friedman2782dac2013-06-26 20:50:34 +00001900 ZeroLengthBitfield = 0;
Chad Rosiere1a6a0e2011-08-05 22:38:04 +00001901
Douglas Gregor44ba7892012-01-28 00:53:29 +00001902 if (ExternalLayout)
1903 FieldOffset = updateExternalFieldOffset(D, FieldOffset);
1904
Anders Carlsson07209442009-11-22 17:37:31 +00001905 // Place this field at the current location.
1906 FieldOffsets.push_back(FieldOffset);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001907
Douglas Gregore9fc3772012-01-26 07:55:45 +00001908 if (!ExternalLayout)
1909 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, UnpackedFieldOffset,
1910 UnpackedFieldAlign, FieldPacked, D);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001911
Anders Carlssonba958402009-11-22 19:13:51 +00001912 // Update DataSize to include the last byte containing (part of) the bitfield.
1913 if (IsUnion) {
1914 // FIXME: I think FieldSize should be TypeSize here.
Ken Dyckecfc7552011-02-24 01:13:28 +00001915 setDataSize(std::max(getDataSizeInBits(), FieldSize));
Anders Carlssonba958402009-11-22 19:13:51 +00001916 } else {
Eli Friedman2782dac2013-06-26 20:50:34 +00001917 if (IsMsStruct && FieldSize) {
1918 // Under ms_struct, a bitfield always takes up space equal to the size
1919 // of the type. We can't just change the alignment computation on the
1920 // other codepath because of the way this interacts with #pragma pack:
1921 // in a packed struct, we need to allocate misaligned space in the
1922 // struct to hold the bitfield.
1923 if (!UnfilledBitsInLastUnit) {
1924 setDataSize(FieldOffset + TypeSize);
1925 UnfilledBitsInLastUnit = TypeSize - FieldSize;
1926 } else if (UnfilledBitsInLastUnit < FieldSize) {
1927 setDataSize(getDataSizeInBits() + TypeSize);
1928 UnfilledBitsInLastUnit = TypeSize - FieldSize;
1929 } else {
1930 UnfilledBitsInLastUnit -= FieldSize;
1931 }
1932 LastBitfieldTypeSize = TypeSize;
1933 } else {
1934 uint64_t NewSizeInBits = FieldOffset + FieldSize;
1935 uint64_t BitfieldAlignment = Context.getTargetInfo().getCharAlign();
1936 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits, BitfieldAlignment));
1937 UnfilledBitsInLastUnit = getDataSizeInBits() - NewSizeInBits;
1938 LastBitfieldTypeSize = 0;
1939 }
Anders Carlssonba958402009-11-22 19:13:51 +00001940 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001941
Anders Carlssonba958402009-11-22 19:13:51 +00001942 // Update the size.
Ken Dyckecfc7552011-02-24 01:13:28 +00001943 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001944
Anders Carlsson07209442009-11-22 17:37:31 +00001945 // Remember max struct/class alignment.
Ken Dyck85ef0432011-02-19 18:58:07 +00001946 UpdateAlignment(Context.toCharUnitsFromBits(FieldAlign),
1947 Context.toCharUnitsFromBits(UnpackedFieldAlign));
Anders Carlsson07209442009-11-22 17:37:31 +00001948}
1949
Douglas Gregore9fc3772012-01-26 07:55:45 +00001950void RecordLayoutBuilder::LayoutField(const FieldDecl *D) {
Anders Carlsson07209442009-11-22 17:37:31 +00001951 if (D->isBitField()) {
1952 LayoutBitField(D);
1953 return;
1954 }
1955
Eli Friedman2782dac2013-06-26 20:50:34 +00001956 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001957
Anders Carlssonba958402009-11-22 19:13:51 +00001958 // Reset the unfilled bits.
Eli Friedman2782dac2013-06-26 20:50:34 +00001959 UnfilledBitsInLastUnit = 0;
1960 LastBitfieldTypeSize = 0;
Anders Carlssonba958402009-11-22 19:13:51 +00001961
Anders Carlsson07209442009-11-22 17:37:31 +00001962 bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
Ken Dyck6d90e892011-02-20 02:06:09 +00001963 CharUnits FieldOffset =
Ken Dyckecfc7552011-02-24 01:13:28 +00001964 IsUnion ? CharUnits::Zero() : getDataSize();
Ken Dyck6d90e892011-02-20 02:06:09 +00001965 CharUnits FieldSize;
1966 CharUnits FieldAlign;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001967
Anders Carlsson07209442009-11-22 17:37:31 +00001968 if (D->getType()->isIncompleteArrayType()) {
1969 // This is a flexible array member; we can't directly
1970 // query getTypeInfo about these, so we figure it out here.
1971 // Flexible array members don't have any size, but they
1972 // have to be aligned appropriately for their element type.
Ken Dyck6d90e892011-02-20 02:06:09 +00001973 FieldSize = CharUnits::Zero();
Anders Carlsson5efc56e2010-04-16 15:07:51 +00001974 const ArrayType* ATy = Context.getAsArrayType(D->getType());
Ken Dyck6d90e892011-02-20 02:06:09 +00001975 FieldAlign = Context.getTypeAlignInChars(ATy->getElementType());
Anders Carlsson07209442009-11-22 17:37:31 +00001976 } else if (const ReferenceType *RT = D->getType()->getAs<ReferenceType>()) {
1977 unsigned AS = RT->getPointeeType().getAddressSpace();
Ken Dyck6d90e892011-02-20 02:06:09 +00001978 FieldSize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001979 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(AS));
Ken Dyck6d90e892011-02-20 02:06:09 +00001980 FieldAlign =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001981 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(AS));
Anders Carlsson79474332009-07-18 20:20:21 +00001982 } else {
Ken Dyck6d90e892011-02-20 02:06:09 +00001983 std::pair<CharUnits, CharUnits> FieldInfo =
1984 Context.getTypeInfoInChars(D->getType());
Anders Carlsson07209442009-11-22 17:37:31 +00001985 FieldSize = FieldInfo.first;
1986 FieldAlign = FieldInfo.second;
Chad Rosier18903ee2011-08-04 01:21:14 +00001987
Fariborz Jahanianfc0fe6e2011-05-03 20:21:04 +00001988 if (ZeroLengthBitfield) {
Chad Rosier18903ee2011-08-04 01:21:14 +00001989 CharUnits ZeroLengthBitfieldBoundary =
1990 Context.toCharUnitsFromBits(
Douglas Gregore8bbc122011-09-02 00:18:52 +00001991 Context.getTargetInfo().getZeroLengthBitfieldBoundary());
Chad Rosier18903ee2011-08-04 01:21:14 +00001992 if (ZeroLengthBitfieldBoundary == CharUnits::Zero()) {
1993 // If a zero-length bitfield is inserted after a bitfield,
1994 // and the alignment of the zero-length bitfield is
1995 // greater than the member that follows it, `bar', `bar'
1996 // will be aligned as the type of the zero-length bitfield.
1997 std::pair<CharUnits, CharUnits> FieldInfo =
1998 Context.getTypeInfoInChars(ZeroLengthBitfield->getType());
1999 CharUnits ZeroLengthBitfieldAlignment = FieldInfo.second;
2000 if (ZeroLengthBitfieldAlignment > FieldAlign)
2001 FieldAlign = ZeroLengthBitfieldAlignment;
Chad Rosier64b18ee2011-08-04 19:25:14 +00002002 } else if (ZeroLengthBitfieldBoundary > FieldAlign) {
Chad Rosier18903ee2011-08-04 01:21:14 +00002003 // Align 'bar' based on a fixed alignment specified by the target.
Douglas Gregore8bbc122011-09-02 00:18:52 +00002004 assert(Context.getTargetInfo().useZeroLengthBitfieldAlignment() &&
Chad Rosiera336c6f2011-08-04 17:52:43 +00002005 "ZeroLengthBitfieldBoundary should only be used in conjunction"
2006 " with useZeroLengthBitfieldAlignment.");
Chad Rosier18903ee2011-08-04 01:21:14 +00002007 FieldAlign = ZeroLengthBitfieldBoundary;
2008 }
Fariborz Jahanianfc0fe6e2011-05-03 20:21:04 +00002009 ZeroLengthBitfield = 0;
2010 }
Douglas Gregordbe39272011-02-01 15:15:22 +00002011
Eli Friedman9ee2d0472012-10-12 23:29:20 +00002012 if (IsMsStruct) {
Douglas Gregordbe39272011-02-01 15:15:22 +00002013 // If MS bitfield layout is required, figure out what type is being
2014 // laid out and align the field to the width of that type.
2015
2016 // Resolve all typedefs down to their base type and round up the field
2017 // alignment if necessary.
2018 QualType T = Context.getBaseElementType(D->getType());
2019 if (const BuiltinType *BTy = T->getAs<BuiltinType>()) {
Ken Dyck6d90e892011-02-20 02:06:09 +00002020 CharUnits TypeSize = Context.getTypeSizeInChars(BTy);
Douglas Gregordbe39272011-02-01 15:15:22 +00002021 if (TypeSize > FieldAlign)
2022 FieldAlign = TypeSize;
2023 }
2024 }
Anders Carlsson79474332009-07-18 20:20:21 +00002025 }
Mike Stump11289f42009-09-09 15:08:12 +00002026
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002027 // The align if the field is not packed. This is to check if the attribute
2028 // was unnecessary (-Wpacked).
Ken Dyck6d90e892011-02-20 02:06:09 +00002029 CharUnits UnpackedFieldAlign = FieldAlign;
2030 CharUnits UnpackedFieldOffset = FieldOffset;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002031
Anders Carlsson07209442009-11-22 17:37:31 +00002032 if (FieldPacked)
Ken Dyck6d90e892011-02-20 02:06:09 +00002033 FieldAlign = CharUnits::One();
2034 CharUnits MaxAlignmentInChars =
2035 Context.toCharUnitsFromBits(D->getMaxAlignment());
2036 FieldAlign = std::max(FieldAlign, MaxAlignmentInChars);
2037 UnpackedFieldAlign = std::max(UnpackedFieldAlign, MaxAlignmentInChars);
Anders Carlsson07209442009-11-22 17:37:31 +00002038
2039 // The maximum field alignment overrides the aligned attribute.
Ken Dyck02ced6f2011-02-17 01:49:42 +00002040 if (!MaxFieldAlignment.isZero()) {
Ken Dyck6d90e892011-02-20 02:06:09 +00002041 FieldAlign = std::min(FieldAlign, MaxFieldAlignment);
2042 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignment);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002043 }
Anders Carlsson07209442009-11-22 17:37:31 +00002044
Douglas Gregor44ba7892012-01-28 00:53:29 +00002045 // Round up the current record size to the field's alignment boundary.
2046 FieldOffset = FieldOffset.RoundUpToAlignment(FieldAlign);
2047 UnpackedFieldOffset =
2048 UnpackedFieldOffset.RoundUpToAlignment(UnpackedFieldAlign);
2049
2050 if (ExternalLayout) {
2051 FieldOffset = Context.toCharUnitsFromBits(
2052 updateExternalFieldOffset(D, Context.toBits(FieldOffset)));
2053
2054 if (!IsUnion && EmptySubobjects) {
2055 // Record the fact that we're placing a field at this offset.
2056 bool Allowed = EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset);
2057 (void)Allowed;
2058 assert(Allowed && "Externally-placed field cannot be placed here");
2059 }
2060 } else {
Douglas Gregore9fc3772012-01-26 07:55:45 +00002061 if (!IsUnion && EmptySubobjects) {
2062 // Check if we can place the field at this offset.
2063 while (!EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset)) {
2064 // We couldn't place the field at the offset. Try again at a new offset.
2065 FieldOffset += FieldAlign;
2066 }
Anders Carlsson07209442009-11-22 17:37:31 +00002067 }
Anders Carlsson07209442009-11-22 17:37:31 +00002068 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00002069
Anders Carlsson79474332009-07-18 20:20:21 +00002070 // Place this field at the current location.
Ken Dyck6d90e892011-02-20 02:06:09 +00002071 FieldOffsets.push_back(Context.toBits(FieldOffset));
Mike Stump11289f42009-09-09 15:08:12 +00002072
Douglas Gregore9fc3772012-01-26 07:55:45 +00002073 if (!ExternalLayout)
2074 CheckFieldPadding(Context.toBits(FieldOffset), UnpaddedFieldOffset,
2075 Context.toBits(UnpackedFieldOffset),
2076 Context.toBits(UnpackedFieldAlign), FieldPacked, D);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002077
Anders Carlsson79474332009-07-18 20:20:21 +00002078 // Reserve space for this field.
Eli Friedman43f18342012-01-12 23:27:03 +00002079 uint64_t FieldSizeInBits = Context.toBits(FieldSize);
Anders Carlsson79474332009-07-18 20:20:21 +00002080 if (IsUnion)
Eli Friedman2e108372012-01-12 23:48:56 +00002081 setDataSize(std::max(getDataSizeInBits(), FieldSizeInBits));
Anders Carlsson79474332009-07-18 20:20:21 +00002082 else
Eli Friedman2e108372012-01-12 23:48:56 +00002083 setDataSize(FieldOffset + FieldSize);
Mike Stump11289f42009-09-09 15:08:12 +00002084
Eli Friedman2e108372012-01-12 23:48:56 +00002085 // Update the size.
2086 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
Mike Stump11289f42009-09-09 15:08:12 +00002087
Anders Carlsson79474332009-07-18 20:20:21 +00002088 // Remember max struct/class alignment.
Ken Dyck6d90e892011-02-20 02:06:09 +00002089 UpdateAlignment(FieldAlign, UnpackedFieldAlign);
Anders Carlsson79474332009-07-18 20:20:21 +00002090}
2091
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002092void RecordLayoutBuilder::FinishLayout(const NamedDecl *D) {
Anders Carlsson79474332009-07-18 20:20:21 +00002093 // In C++, records cannot be of size 0.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002094 if (Context.getLangOpts().CPlusPlus && getSizeInBits() == 0) {
Fariborz Jahanian09b23312011-02-02 19:36:18 +00002095 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
2096 // Compatibility with gcc requires a class (pod or non-pod)
2097 // which is not empty but of size 0; such as having fields of
2098 // array of zero-length, remains of Size 0
2099 if (RD->isEmpty())
Ken Dyck1b4420e2011-02-28 02:01:38 +00002100 setSize(CharUnits::One());
Fariborz Jahanian09b23312011-02-02 19:36:18 +00002101 }
2102 else
Ken Dyck1b4420e2011-02-28 02:01:38 +00002103 setSize(CharUnits::One());
Fariborz Jahanian09b23312011-02-02 19:36:18 +00002104 }
Eli Friedman83a12582011-12-01 00:37:01 +00002105
Douglas Gregor1423a5c2012-10-26 22:31:14 +00002106 // Finally, round the size of the record up to the alignment of the
2107 // record itself.
Eli Friedman2782dac2013-06-26 20:50:34 +00002108 uint64_t UnpaddedSize = getSizeInBits() - UnfilledBitsInLastUnit;
Douglas Gregor1423a5c2012-10-26 22:31:14 +00002109 uint64_t UnpackedSizeInBits =
2110 llvm::RoundUpToAlignment(getSizeInBits(),
2111 Context.toBits(UnpackedAlignment));
2112 CharUnits UnpackedSize = Context.toCharUnitsFromBits(UnpackedSizeInBits);
2113 uint64_t RoundedSize
2114 = llvm::RoundUpToAlignment(getSizeInBits(), Context.toBits(Alignment));
2115
2116 if (ExternalLayout) {
2117 // If we're inferring alignment, and the external size is smaller than
2118 // our size after we've rounded up to alignment, conservatively set the
2119 // alignment to 1.
2120 if (InferAlignment && ExternalSize < RoundedSize) {
2121 Alignment = CharUnits::One();
2122 InferAlignment = false;
2123 }
2124 setSize(ExternalSize);
2125 return;
2126 }
2127
2128
Eli Friedman83a12582011-12-01 00:37:01 +00002129 // MSVC doesn't round up to the alignment of the record with virtual bases.
2130 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
2131 if (isMicrosoftCXXABI() && RD->getNumVBases())
2132 return;
2133 }
2134
Douglas Gregor1423a5c2012-10-26 22:31:14 +00002135 // Set the size to the final size.
2136 setSize(RoundedSize);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002137
Douglas Gregore8bbc122011-09-02 00:18:52 +00002138 unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002139 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
2140 // Warn if padding was introduced to the struct/class/union.
Ken Dyckecfc7552011-02-24 01:13:28 +00002141 if (getSizeInBits() > UnpaddedSize) {
2142 unsigned PadSize = getSizeInBits() - UnpaddedSize;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002143 bool InBits = true;
2144 if (PadSize % CharBitNum == 0) {
2145 PadSize = PadSize / CharBitNum;
2146 InBits = false;
2147 }
2148 Diag(RD->getLocation(), diag::warn_padded_struct_size)
2149 << Context.getTypeDeclType(RD)
2150 << PadSize
2151 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1); // plural or not
2152 }
2153
2154 // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
2155 // bother since there won't be alignment issues.
Ken Dyckecfc7552011-02-24 01:13:28 +00002156 if (Packed && UnpackedAlignment > CharUnits::One() &&
Ken Dyck1b4420e2011-02-28 02:01:38 +00002157 getSize() == UnpackedSize)
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002158 Diag(D->getLocation(), diag::warn_unnecessary_packed)
2159 << Context.getTypeDeclType(RD);
2160 }
Anders Carlsson79474332009-07-18 20:20:21 +00002161}
2162
Ken Dyck85ef0432011-02-19 18:58:07 +00002163void RecordLayoutBuilder::UpdateAlignment(CharUnits NewAlignment,
2164 CharUnits UnpackedNewAlignment) {
Douglas Gregore9fc3772012-01-26 07:55:45 +00002165 // The alignment is not modified when using 'mac68k' alignment or when
Douglas Gregor44ba7892012-01-28 00:53:29 +00002166 // we have an externally-supplied layout that also provides overall alignment.
2167 if (IsMac68kAlign || (ExternalLayout && !InferAlignment))
Daniel Dunbar6da10982010-05-27 05:45:51 +00002168 return;
2169
Ken Dyck85ef0432011-02-19 18:58:07 +00002170 if (NewAlignment > Alignment) {
2171 assert(llvm::isPowerOf2_32(NewAlignment.getQuantity() &&
2172 "Alignment not a power of 2"));
2173 Alignment = NewAlignment;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002174 }
2175
Ken Dyck85ef0432011-02-19 18:58:07 +00002176 if (UnpackedNewAlignment > UnpackedAlignment) {
2177 assert(llvm::isPowerOf2_32(UnpackedNewAlignment.getQuantity() &&
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002178 "Alignment not a power of 2"));
Ken Dyck85ef0432011-02-19 18:58:07 +00002179 UnpackedAlignment = UnpackedNewAlignment;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002180 }
2181}
2182
Douglas Gregor44ba7892012-01-28 00:53:29 +00002183uint64_t
2184RecordLayoutBuilder::updateExternalFieldOffset(const FieldDecl *Field,
2185 uint64_t ComputedOffset) {
2186 assert(ExternalFieldOffsets.find(Field) != ExternalFieldOffsets.end() &&
2187 "Field does not have an external offset");
2188
2189 uint64_t ExternalFieldOffset = ExternalFieldOffsets[Field];
2190
2191 if (InferAlignment && ExternalFieldOffset < ComputedOffset) {
2192 // The externally-supplied field offset is before the field offset we
2193 // computed. Assume that the structure is packed.
Douglas Gregor1423a5c2012-10-26 22:31:14 +00002194 Alignment = CharUnits::One();
Douglas Gregor44ba7892012-01-28 00:53:29 +00002195 InferAlignment = false;
2196 }
2197
2198 // Use the externally-supplied field offset.
Benjamin Kramer648e68b2012-08-31 22:14:25 +00002199 return ExternalFieldOffset;
2200}
2201
2202/// \brief Get diagnostic %select index for tag kind for
2203/// field padding diagnostic message.
2204/// WARNING: Indexes apply to particular diagnostics only!
2205///
2206/// \returns diagnostic %select index.
2207static unsigned getPaddingDiagFromTagKind(TagTypeKind Tag) {
2208 switch (Tag) {
2209 case TTK_Struct: return 0;
2210 case TTK_Interface: return 1;
2211 case TTK_Class: return 2;
2212 default: llvm_unreachable("Invalid tag kind for field padding diagnostic!");
2213 }
2214}
2215
2216void RecordLayoutBuilder::CheckFieldPadding(uint64_t Offset,
2217 uint64_t UnpaddedOffset,
2218 uint64_t UnpackedOffset,
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002219 unsigned UnpackedAlign,
2220 bool isPacked,
2221 const FieldDecl *D) {
2222 // We let objc ivars without warning, objc interfaces generally are not used
2223 // for padding tricks.
2224 if (isa<ObjCIvarDecl>(D))
Anders Carlsson79474332009-07-18 20:20:21 +00002225 return;
Mike Stump11289f42009-09-09 15:08:12 +00002226
Ted Kremenekfed48af2011-09-06 19:40:45 +00002227 // Don't warn about structs created without a SourceLocation. This can
2228 // be done by clients of the AST, such as codegen.
2229 if (D->getLocation().isInvalid())
2230 return;
2231
Douglas Gregore8bbc122011-09-02 00:18:52 +00002232 unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
Mike Stump11289f42009-09-09 15:08:12 +00002233
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002234 // Warn if padding was introduced to the struct/class.
2235 if (!IsUnion && Offset > UnpaddedOffset) {
2236 unsigned PadSize = Offset - UnpaddedOffset;
2237 bool InBits = true;
2238 if (PadSize % CharBitNum == 0) {
2239 PadSize = PadSize / CharBitNum;
2240 InBits = false;
Benjamin Kramer648e68b2012-08-31 22:14:25 +00002241 }
2242 if (D->getIdentifier())
2243 Diag(D->getLocation(), diag::warn_padded_struct_field)
2244 << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
2245 << Context.getTypeDeclType(D->getParent())
2246 << PadSize
2247 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1) // plural or not
2248 << D->getIdentifier();
2249 else
2250 Diag(D->getLocation(), diag::warn_padded_struct_anon_field)
2251 << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
2252 << Context.getTypeDeclType(D->getParent())
2253 << PadSize
2254 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1); // plural or not
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002255 }
2256
2257 // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
2258 // bother since there won't be alignment issues.
2259 if (isPacked && UnpackedAlign > CharBitNum && Offset == UnpackedOffset)
2260 Diag(D->getLocation(), diag::warn_unnecessary_packed)
2261 << D->getIdentifier();
Anders Carlsson79474332009-07-18 20:20:21 +00002262}
Mike Stump11289f42009-09-09 15:08:12 +00002263
John McCall6bd2a892013-01-25 22:31:03 +00002264static const CXXMethodDecl *computeKeyFunction(ASTContext &Context,
2265 const CXXRecordDecl *RD) {
Daniel Dunbarccabe482010-04-19 20:44:53 +00002266 // If a class isn't polymorphic it doesn't have a key function.
Anders Carlsson5ebf8b42009-12-07 04:35:11 +00002267 if (!RD->isPolymorphic())
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00002268 return 0;
Eli Friedmanf2c79b62009-12-08 03:56:49 +00002269
Eli Friedman300f55d2011-06-10 21:53:06 +00002270 // A class that is not externally visible doesn't have a key function. (Or
Eli Friedmanf2c79b62009-12-08 03:56:49 +00002271 // at least, there's no point to assigning a key function to such a class;
2272 // this doesn't affect the ABI.)
Rafael Espindola3ae00052013-05-13 00:12:11 +00002273 if (!RD->isExternallyVisible())
Eli Friedmanf2c79b62009-12-08 03:56:49 +00002274 return 0;
2275
Argyrios Kyrtzidis8c64bbe2010-10-13 02:39:41 +00002276 // Template instantiations don't have key functions,see Itanium C++ ABI 5.2.6.
2277 // Same behavior as GCC.
2278 TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
2279 if (TSK == TSK_ImplicitInstantiation ||
2280 TSK == TSK_ExplicitInstantiationDefinition)
2281 return 0;
2282
John McCall6bd2a892013-01-25 22:31:03 +00002283 bool allowInlineFunctions =
2284 Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline();
2285
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002286 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
2287 E = RD->method_end(); I != E; ++I) {
David Blaikie40ed2972012-06-06 20:45:41 +00002288 const CXXMethodDecl *MD = *I;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002289
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00002290 if (!MD->isVirtual())
2291 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002292
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00002293 if (MD->isPure())
2294 continue;
Eli Friedmanf2c79b62009-12-08 03:56:49 +00002295
Anders Carlssonf98849e2009-12-02 17:15:43 +00002296 // Ignore implicit member functions, they are always marked as inline, but
2297 // they don't have a body until they're defined.
2298 if (MD->isImplicit())
2299 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002300
Douglas Gregora318efd2010-01-05 19:06:31 +00002301 if (MD->isInlineSpecified())
2302 continue;
Eli Friedman71a26d82009-12-06 20:50:05 +00002303
2304 if (MD->hasInlineBody())
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00002305 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002306
Benjamin Kramer4a902082012-08-03 15:43:22 +00002307 // Ignore inline deleted or defaulted functions.
Benjamin Kramer73d1be72012-08-03 08:39:58 +00002308 if (!MD->isUserProvided())
2309 continue;
2310
John McCall6bd2a892013-01-25 22:31:03 +00002311 // In certain ABIs, ignore functions with out-of-line inline definitions.
2312 if (!allowInlineFunctions) {
2313 const FunctionDecl *Def;
2314 if (MD->hasBody(Def) && Def->isInlineSpecified())
2315 continue;
2316 }
2317
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00002318 // We found it.
2319 return MD;
2320 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002321
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00002322 return 0;
2323}
2324
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002325DiagnosticBuilder
2326RecordLayoutBuilder::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +00002327 return Context.getDiagnostics().Report(Loc, DiagID);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002328}
2329
John McCall5c1f1d02013-01-29 01:14:22 +00002330/// Does the target C++ ABI require us to skip over the tail-padding
2331/// of the given class (considering it as a base class) when allocating
2332/// objects?
2333static bool mustSkipTailPadding(TargetCXXABI ABI, const CXXRecordDecl *RD) {
2334 switch (ABI.getTailPaddingUseRules()) {
2335 case TargetCXXABI::AlwaysUseTailPadding:
2336 return false;
2337
2338 case TargetCXXABI::UseTailPaddingUnlessPOD03:
2339 // FIXME: To the extent that this is meant to cover the Itanium ABI
2340 // rules, we should implement the restrictions about over-sized
2341 // bitfields:
2342 //
2343 // http://mentorembedded.github.com/cxx-abi/abi.html#POD :
2344 // In general, a type is considered a POD for the purposes of
2345 // layout if it is a POD type (in the sense of ISO C++
2346 // [basic.types]). However, a POD-struct or POD-union (in the
2347 // sense of ISO C++ [class]) with a bitfield member whose
2348 // declared width is wider than the declared type of the
2349 // bitfield is not a POD for the purpose of layout. Similarly,
2350 // an array type is not a POD for the purpose of layout if the
2351 // element type of the array is not a POD for the purpose of
2352 // layout.
2353 //
2354 // Where references to the ISO C++ are made in this paragraph,
2355 // the Technical Corrigendum 1 version of the standard is
2356 // intended.
2357 return RD->isPOD();
2358
2359 case TargetCXXABI::UseTailPaddingUnlessPOD11:
2360 // This is equivalent to RD->getTypeForDecl().isCXX11PODType(),
2361 // but with a lot of abstraction penalty stripped off. This does
2362 // assume that these properties are set correctly even in C++98
2363 // mode; fortunately, that is true because we want to assign
2364 // consistently semantics to the type-traits intrinsics (or at
2365 // least as many of them as possible).
2366 return RD->isTrivial() && RD->isStandardLayout();
2367 }
2368
2369 llvm_unreachable("bad tail-padding use kind");
2370}
2371
Anders Carlssondf291d82010-05-26 04:56:53 +00002372/// getASTRecordLayout - Get or compute information about the layout of the
2373/// specified record (struct/union/class), which indicates its size and field
2374/// position information.
Jay Foad39c79802011-01-12 09:06:06 +00002375const ASTRecordLayout &
2376ASTContext::getASTRecordLayout(const RecordDecl *D) const {
John McCall0710e552011-10-07 02:39:22 +00002377 // These asserts test different things. A record has a definition
2378 // as soon as we begin to parse the definition. That definition is
2379 // not a complete definition (which is what isDefinition() tests)
2380 // until we *finish* parsing the definition.
Sean Callanan56c19892012-02-08 00:04:52 +00002381
2382 if (D->hasExternalLexicalStorage() && !D->getDefinition())
2383 getExternalSource()->CompleteType(const_cast<RecordDecl*>(D));
2384
Anders Carlssondf291d82010-05-26 04:56:53 +00002385 D = D->getDefinition();
2386 assert(D && "Cannot get layout of forward declarations!");
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00002387 assert(!D->isInvalidDecl() && "Cannot get layout of invalid decl!");
John McCallf937c022011-10-07 06:10:15 +00002388 assert(D->isCompleteDefinition() && "Cannot layout type before complete!");
Anders Carlssondf291d82010-05-26 04:56:53 +00002389
2390 // Look up this layout, if already laid out, return what we have.
2391 // Note that we can't save a reference to the entry because this function
2392 // is recursive.
2393 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
2394 if (Entry) return *Entry;
2395
Anders Carlssond2954862010-05-26 05:10:47 +00002396 const ASTRecordLayout *NewEntry;
2397
2398 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
Anders Carlssonc121b4e2010-05-27 00:07:01 +00002399 EmptySubobjectMap EmptySubobjects(*this, RD);
John McCall0153cd32011-11-08 04:01:03 +00002400 RecordLayoutBuilder Builder(*this, &EmptySubobjects);
2401 Builder.Layout(RD);
Anders Carlsson439edd12010-05-27 05:41:06 +00002402
John McCall0153cd32011-11-08 04:01:03 +00002403 // MSVC gives the vb-table pointer an alignment equal to that of
2404 // the non-virtual part of the structure. That's an inherently
2405 // multi-pass operation. If our first pass doesn't give us
2406 // adequate alignment, try again with the specified minimum
2407 // alignment. This is *much* more maintainable than computing the
2408 // alignment in advance in a separately-coded pass; it's also
2409 // significantly more efficient in the common case where the
2410 // vb-table doesn't need extra padding.
2411 if (Builder.VBPtrOffset != CharUnits::fromQuantity(-1) &&
2412 (Builder.VBPtrOffset % Builder.NonVirtualAlignment) != 0) {
2413 Builder.resetWithTargetAlignment(Builder.NonVirtualAlignment);
2414 Builder.Layout(RD);
Eli Friedman84d2d3a2011-09-27 19:12:27 +00002415 }
2416
John McCall5c1f1d02013-01-29 01:14:22 +00002417 // In certain situations, we are allowed to lay out objects in the
2418 // tail-padding of base classes. This is ABI-dependent.
2419 // FIXME: this should be stored in the record layout.
2420 bool skipTailPadding =
2421 mustSkipTailPadding(getTargetInfo().getCXXABI(), cast<CXXRecordDecl>(D));
Anders Carlssond2954862010-05-26 05:10:47 +00002422
2423 // FIXME: This should be done in FinalizeLayout.
Ken Dyck1b4420e2011-02-28 02:01:38 +00002424 CharUnits DataSize =
John McCall5c1f1d02013-01-29 01:14:22 +00002425 skipTailPadding ? Builder.getSize() : Builder.getDataSize();
Ken Dyck1b4420e2011-02-28 02:01:38 +00002426 CharUnits NonVirtualSize =
John McCall5c1f1d02013-01-29 01:14:22 +00002427 skipTailPadding ? DataSize : Builder.NonVirtualSize;
Anders Carlssond2954862010-05-26 05:10:47 +00002428
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002429 NewEntry =
John McCall0153cd32011-11-08 04:01:03 +00002430 new (*this) ASTRecordLayout(*this, Builder.getSize(),
2431 Builder.Alignment,
John McCalle42a3362012-05-01 08:55:32 +00002432 Builder.HasOwnVFPtr,
John McCall0153cd32011-11-08 04:01:03 +00002433 Builder.VBPtrOffset,
Ken Dyck1b4420e2011-02-28 02:01:38 +00002434 DataSize,
John McCall0153cd32011-11-08 04:01:03 +00002435 Builder.FieldOffsets.data(),
2436 Builder.FieldOffsets.size(),
Ken Dyckaf1c83f2011-02-16 01:52:01 +00002437 NonVirtualSize,
John McCall0153cd32011-11-08 04:01:03 +00002438 Builder.NonVirtualAlignment,
Anders Carlssonc121b4e2010-05-27 00:07:01 +00002439 EmptySubobjects.SizeOfLargestEmptySubobject,
John McCall0153cd32011-11-08 04:01:03 +00002440 Builder.PrimaryBase,
2441 Builder.PrimaryBaseIsVirtual,
2442 Builder.Bases, Builder.VBases);
Anders Carlssond2954862010-05-26 05:10:47 +00002443 } else {
John McCall0153cd32011-11-08 04:01:03 +00002444 RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/0);
Anders Carlssond2954862010-05-26 05:10:47 +00002445 Builder.Layout(D);
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002446
Anders Carlssond2954862010-05-26 05:10:47 +00002447 NewEntry =
Ken Dyck1b4420e2011-02-28 02:01:38 +00002448 new (*this) ASTRecordLayout(*this, Builder.getSize(),
Ken Dyck4731d5b2011-02-16 02:05:21 +00002449 Builder.Alignment,
Ken Dyck1b4420e2011-02-28 02:01:38 +00002450 Builder.getSize(),
Anders Carlssond2954862010-05-26 05:10:47 +00002451 Builder.FieldOffsets.data(),
2452 Builder.FieldOffsets.size());
2453 }
2454
Anders Carlssondf291d82010-05-26 04:56:53 +00002455 ASTRecordLayouts[D] = NewEntry;
2456
David Blaikiebbafb8a2012-03-11 07:00:24 +00002457 if (getLangOpts().DumpRecordLayouts) {
Anders Carlssondf291d82010-05-26 04:56:53 +00002458 llvm::errs() << "\n*** Dumping AST Record Layout\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +00002459 DumpRecordLayout(D, llvm::errs(), getLangOpts().DumpRecordLayoutsSimple);
Anders Carlssondf291d82010-05-26 04:56:53 +00002460 }
2461
2462 return *NewEntry;
2463}
2464
John McCall6bd2a892013-01-25 22:31:03 +00002465const CXXMethodDecl *ASTContext::getCurrentKeyFunction(const CXXRecordDecl *RD) {
Reid Kleckner5d7f2982013-05-29 16:18:30 +00002466 if (!getTargetInfo().getCXXABI().hasKeyFunctions())
2467 return 0;
2468
John McCall6bd2a892013-01-25 22:31:03 +00002469 assert(RD->getDefinition() && "Cannot get key function for forward decl!");
Anders Carlssondf291d82010-05-26 04:56:53 +00002470 RD = cast<CXXRecordDecl>(RD->getDefinition());
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002471
John McCall6bd2a892013-01-25 22:31:03 +00002472 const CXXMethodDecl *&entry = KeyFunctions[RD];
2473 if (!entry) {
2474 entry = computeKeyFunction(*this, RD);
2475 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002476
John McCall6bd2a892013-01-25 22:31:03 +00002477 return entry;
2478}
2479
2480void ASTContext::setNonKeyFunction(const CXXMethodDecl *method) {
2481 assert(method == method->getFirstDeclaration() &&
2482 "not working with method declaration from class definition");
2483
2484 // Look up the cache entry. Since we're working with the first
2485 // declaration, its parent must be the class definition, which is
2486 // the correct key for the KeyFunctions hash.
2487 llvm::DenseMap<const CXXRecordDecl*, const CXXMethodDecl*>::iterator
2488 i = KeyFunctions.find(method->getParent());
2489
2490 // If it's not cached, there's nothing to do.
2491 if (i == KeyFunctions.end()) return;
2492
2493 // If it is cached, check whether it's the target method, and if so,
2494 // remove it from the cache.
2495 if (i->second == method) {
2496 // FIXME: remember that we did this for module / chained PCH state?
2497 KeyFunctions.erase(i);
2498 }
Anders Carlssondf291d82010-05-26 04:56:53 +00002499}
2500
Richard Smithdafff942012-01-14 04:30:29 +00002501static uint64_t getFieldOffset(const ASTContext &C, const FieldDecl *FD) {
2502 const ASTRecordLayout &Layout = C.getASTRecordLayout(FD->getParent());
2503 return Layout.getFieldOffset(FD->getFieldIndex());
2504}
2505
2506uint64_t ASTContext::getFieldOffset(const ValueDecl *VD) const {
2507 uint64_t OffsetInBits;
2508 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
2509 OffsetInBits = ::getFieldOffset(*this, FD);
2510 } else {
2511 const IndirectFieldDecl *IFD = cast<IndirectFieldDecl>(VD);
2512
2513 OffsetInBits = 0;
2514 for (IndirectFieldDecl::chain_iterator CI = IFD->chain_begin(),
2515 CE = IFD->chain_end();
2516 CI != CE; ++CI)
2517 OffsetInBits += ::getFieldOffset(*this, cast<FieldDecl>(*CI));
2518 }
2519
2520 return OffsetInBits;
2521}
2522
Eric Christopher8a39a012011-10-05 06:00:51 +00002523/// getObjCLayout - Get or compute information about the layout of the
2524/// given interface.
Anders Carlssondf291d82010-05-26 04:56:53 +00002525///
2526/// \param Impl - If given, also include the layout of the interface's
2527/// implementation. This may differ by including synthesized ivars.
2528const ASTRecordLayout &
2529ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
Jay Foad39c79802011-01-12 09:06:06 +00002530 const ObjCImplementationDecl *Impl) const {
Douglas Gregor64d92572011-12-20 15:50:13 +00002531 // Retrieve the definition
Sean Callanand9a909c2012-03-15 16:33:08 +00002532 if (D->hasExternalLexicalStorage() && !D->getDefinition())
2533 getExternalSource()->CompleteType(const_cast<ObjCInterfaceDecl*>(D));
Douglas Gregor64d92572011-12-20 15:50:13 +00002534 D = D->getDefinition();
2535 assert(D && D->isThisDeclarationADefinition() && "Invalid interface decl!");
Anders Carlssondf291d82010-05-26 04:56:53 +00002536
2537 // Look up this layout, if already laid out, return what we have.
Roman Divackye6377112012-09-06 15:59:27 +00002538 const ObjCContainerDecl *Key =
2539 Impl ? (const ObjCContainerDecl*) Impl : (const ObjCContainerDecl*) D;
Anders Carlssondf291d82010-05-26 04:56:53 +00002540 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
2541 return *Entry;
2542
2543 // Add in synthesized ivar count if laying out an implementation.
2544 if (Impl) {
2545 unsigned SynthCount = CountNonClassIvars(D);
2546 // If there aren't any sythesized ivars then reuse the interface
2547 // entry. Note we can't cache this because we simply free all
2548 // entries later; however we shouldn't look up implementations
2549 // frequently.
2550 if (SynthCount == 0)
2551 return getObjCLayout(D, 0);
2552 }
2553
John McCall0153cd32011-11-08 04:01:03 +00002554 RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/0);
Anders Carlsson6ed3a9a2010-05-26 05:04:25 +00002555 Builder.Layout(D);
2556
Anders Carlssondf291d82010-05-26 04:56:53 +00002557 const ASTRecordLayout *NewEntry =
Ken Dyck1b4420e2011-02-28 02:01:38 +00002558 new (*this) ASTRecordLayout(*this, Builder.getSize(),
Ken Dyck4731d5b2011-02-16 02:05:21 +00002559 Builder.Alignment,
Ken Dyck1b4420e2011-02-28 02:01:38 +00002560 Builder.getDataSize(),
Anders Carlsson6ed3a9a2010-05-26 05:04:25 +00002561 Builder.FieldOffsets.data(),
2562 Builder.FieldOffsets.size());
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002563
Anders Carlssondf291d82010-05-26 04:56:53 +00002564 ObjCLayouts[Key] = NewEntry;
2565
2566 return *NewEntry;
2567}
2568
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002569static void PrintOffset(raw_ostream &OS,
Anders Carlsson3f018712010-10-31 23:45:59 +00002570 CharUnits Offset, unsigned IndentLevel) {
Benjamin Kramer96ad7172011-11-05 09:02:52 +00002571 OS << llvm::format("%4" PRId64 " | ", (int64_t)Offset.getQuantity());
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002572 OS.indent(IndentLevel * 2);
2573}
2574
Eli Benderskyf6f93ee2012-12-08 00:07:24 +00002575static void PrintIndentNoOffset(raw_ostream &OS, unsigned IndentLevel) {
2576 OS << " | ";
2577 OS.indent(IndentLevel * 2);
2578}
2579
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002580static void DumpCXXRecordLayout(raw_ostream &OS,
Jay Foad39c79802011-01-12 09:06:06 +00002581 const CXXRecordDecl *RD, const ASTContext &C,
Anders Carlsson3f018712010-10-31 23:45:59 +00002582 CharUnits Offset,
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002583 unsigned IndentLevel,
2584 const char* Description,
2585 bool IncludeVirtualBases) {
Anders Carlsson3f018712010-10-31 23:45:59 +00002586 const ASTRecordLayout &Layout = C.getASTRecordLayout(RD);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002587
2588 PrintOffset(OS, Offset, IndentLevel);
Dan Gohman145f3f12010-04-19 16:39:44 +00002589 OS << C.getTypeDeclType(const_cast<CXXRecordDecl *>(RD)).getAsString();
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002590 if (Description)
2591 OS << ' ' << Description;
2592 if (RD->isEmpty())
2593 OS << " (empty)";
2594 OS << '\n';
2595
2596 IndentLevel++;
2597
Anders Carlsson3f018712010-10-31 23:45:59 +00002598 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
John McCalle42a3362012-05-01 08:55:32 +00002599 bool HasVfptr = Layout.hasOwnVFPtr();
Eli Friedman84d2d3a2011-09-27 19:12:27 +00002600 bool HasVbptr = Layout.getVBPtrOffset() != CharUnits::fromQuantity(-1);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002601
2602 // Vtable pointer.
Eli Friedman43114f92011-10-21 22:49:56 +00002603 if (RD->isDynamicClass() && !PrimaryBase &&
John McCall359b8852013-01-25 22:30:49 +00002604 !C.getTargetInfo().getCXXABI().isMicrosoft()) {
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002605 PrintOffset(OS, Offset, IndentLevel);
Benjamin Kramerb89514a2011-10-14 18:45:37 +00002606 OS << '(' << *RD << " vtable pointer)\n";
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002607 }
Eli Friedman84d2d3a2011-09-27 19:12:27 +00002608
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002609 // Dump (non-virtual) bases
2610 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
2611 E = RD->bases_end(); I != E; ++I) {
2612 assert(!I->getType()->isDependentType() &&
2613 "Cannot layout class with dependent bases.");
2614 if (I->isVirtual())
2615 continue;
2616
2617 const CXXRecordDecl *Base =
2618 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
2619
Anders Carlsson3f018712010-10-31 23:45:59 +00002620 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002621
2622 DumpCXXRecordLayout(OS, Base, C, BaseOffset, IndentLevel,
2623 Base == PrimaryBase ? "(primary base)" : "(base)",
2624 /*IncludeVirtualBases=*/false);
2625 }
Eli Friedman43114f92011-10-21 22:49:56 +00002626
2627 // vfptr and vbptr (for Microsoft C++ ABI)
2628 if (HasVfptr) {
John McCalle42a3362012-05-01 08:55:32 +00002629 PrintOffset(OS, Offset, IndentLevel);
Eli Friedman43114f92011-10-21 22:49:56 +00002630 OS << '(' << *RD << " vftable pointer)\n";
2631 }
Eli Friedman84d2d3a2011-09-27 19:12:27 +00002632 if (HasVbptr) {
2633 PrintOffset(OS, Offset + Layout.getVBPtrOffset(), IndentLevel);
Benjamin Kramerb89514a2011-10-14 18:45:37 +00002634 OS << '(' << *RD << " vbtable pointer)\n";
Eli Friedman84d2d3a2011-09-27 19:12:27 +00002635 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002636
2637 // Dump fields.
2638 uint64_t FieldNo = 0;
2639 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2640 E = RD->field_end(); I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +00002641 const FieldDecl &Field = **I;
Anders Carlsson3f018712010-10-31 23:45:59 +00002642 CharUnits FieldOffset = Offset +
Ken Dyck86a7fcc2011-01-18 01:56:16 +00002643 C.toCharUnitsFromBits(Layout.getFieldOffset(FieldNo));
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002644
David Blaikie2d7c57e2012-04-30 02:36:29 +00002645 if (const RecordType *RT = Field.getType()->getAs<RecordType>()) {
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002646 if (const CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2647 DumpCXXRecordLayout(OS, D, C, FieldOffset, IndentLevel,
David Blaikie2d7c57e2012-04-30 02:36:29 +00002648 Field.getName().data(),
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002649 /*IncludeVirtualBases=*/true);
2650 continue;
2651 }
2652 }
2653
2654 PrintOffset(OS, FieldOffset, IndentLevel);
David Blaikie2d7c57e2012-04-30 02:36:29 +00002655 OS << Field.getType().getAsString() << ' ' << Field << '\n';
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002656 }
2657
2658 if (!IncludeVirtualBases)
2659 return;
2660
2661 // Dump virtual bases.
John McCalle42a3362012-05-01 08:55:32 +00002662 const ASTRecordLayout::VBaseOffsetsMapTy &vtordisps =
2663 Layout.getVBaseOffsetsMap();
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002664 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
2665 E = RD->vbases_end(); I != E; ++I) {
2666 assert(I->isVirtual() && "Found non-virtual class!");
2667 const CXXRecordDecl *VBase =
2668 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
2669
Anders Carlsson3f018712010-10-31 23:45:59 +00002670 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBase);
John McCalle42a3362012-05-01 08:55:32 +00002671
2672 if (vtordisps.find(VBase)->second.hasVtorDisp()) {
2673 PrintOffset(OS, VBaseOffset - CharUnits::fromQuantity(4), IndentLevel);
2674 OS << "(vtordisp for vbase " << *VBase << ")\n";
2675 }
2676
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002677 DumpCXXRecordLayout(OS, VBase, C, VBaseOffset, IndentLevel,
2678 VBase == PrimaryBase ?
2679 "(primary virtual base)" : "(virtual base)",
2680 /*IncludeVirtualBases=*/false);
2681 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002682
Eli Benderskyf6f93ee2012-12-08 00:07:24 +00002683 PrintIndentNoOffset(OS, IndentLevel - 1);
2684 OS << "[sizeof=" << Layout.getSize().getQuantity();
Ken Dyckd5090c12011-02-11 02:20:09 +00002685 OS << ", dsize=" << Layout.getDataSize().getQuantity();
Ken Dyck7ad11e72011-02-15 02:32:40 +00002686 OS << ", align=" << Layout.getAlignment().getQuantity() << '\n';
Eli Benderskyf6f93ee2012-12-08 00:07:24 +00002687
2688 PrintIndentNoOffset(OS, IndentLevel - 1);
2689 OS << " nvsize=" << Layout.getNonVirtualSize().getQuantity();
2690 OS << ", nvalign=" << Layout.getNonVirtualAlign().getQuantity() << "]\n";
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002691 OS << '\n';
2692}
Daniel Dunbarccabe482010-04-19 20:44:53 +00002693
2694void ASTContext::DumpRecordLayout(const RecordDecl *RD,
Douglas Gregore9fc3772012-01-26 07:55:45 +00002695 raw_ostream &OS,
2696 bool Simple) const {
Daniel Dunbarccabe482010-04-19 20:44:53 +00002697 const ASTRecordLayout &Info = getASTRecordLayout(RD);
2698
2699 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Douglas Gregore9fc3772012-01-26 07:55:45 +00002700 if (!Simple)
2701 return DumpCXXRecordLayout(OS, CXXRD, *this, CharUnits(), 0, 0,
2702 /*IncludeVirtualBases=*/true);
Daniel Dunbarccabe482010-04-19 20:44:53 +00002703
2704 OS << "Type: " << getTypeDeclType(RD).getAsString() << "\n";
Douglas Gregore9fc3772012-01-26 07:55:45 +00002705 if (!Simple) {
2706 OS << "Record: ";
2707 RD->dump();
2708 }
Daniel Dunbarccabe482010-04-19 20:44:53 +00002709 OS << "\nLayout: ";
2710 OS << "<ASTRecordLayout\n";
Ken Dyckb0fcc592011-02-11 01:54:29 +00002711 OS << " Size:" << toBits(Info.getSize()) << "\n";
Ken Dyckd5090c12011-02-11 02:20:09 +00002712 OS << " DataSize:" << toBits(Info.getDataSize()) << "\n";
Ken Dyck7ad11e72011-02-15 02:32:40 +00002713 OS << " Alignment:" << toBits(Info.getAlignment()) << "\n";
Daniel Dunbarccabe482010-04-19 20:44:53 +00002714 OS << " FieldOffsets: [";
2715 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i) {
2716 if (i) OS << ", ";
2717 OS << Info.getFieldOffset(i);
2718 }
2719 OS << "]>\n";
2720}