Bug Summary

File:tools/clang/lib/AST/RecordLayoutBuilder.cpp
Warning:line 3154, column 3
Returning null reference

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name RecordLayoutBuilder.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn325118/build-llvm/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn325118/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn325118/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn325118/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn325118/build-llvm/tools/clang/lib/AST -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-02-14-150435-17243-1 -x c++ /build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp
1//=== RecordLayoutBuilder.cpp - Helper class for building record layouts ---==//
2//
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
10#include "clang/AST/RecordLayout.h"
11#include "clang/AST/ASTContext.h"
12#include "clang/AST/Attr.h"
13#include "clang/AST/CXXInheritance.h"
14#include "clang/AST/Decl.h"
15#include "clang/AST/DeclCXX.h"
16#include "clang/AST/DeclObjC.h"
17#include "clang/AST/Expr.h"
18#include "clang/Basic/TargetInfo.h"
19#include "clang/Sema/SemaDiagnostic.h"
20#include "llvm/ADT/SmallSet.h"
21#include "llvm/Support/Format.h"
22#include "llvm/Support/MathExtras.h"
23
24using namespace clang;
25
26namespace {
27
28/// BaseSubobjectInfo - Represents a single base subobject in a complete class.
29/// For a class hierarchy like
30///
31/// class A { };
32/// class B : A { };
33/// class C : A, B { };
34///
35/// The BaseSubobjectInfo graph for C will have three BaseSubobjectInfo
36/// instances, one for B and two for A.
37///
38/// If a base is virtual, it will only have one BaseSubobjectInfo allocated.
39struct BaseSubobjectInfo {
40 /// Class - The class for this base info.
41 const CXXRecordDecl *Class;
42
43 /// IsVirtual - Whether the BaseInfo represents a virtual base or not.
44 bool IsVirtual;
45
46 /// Bases - Information about the base subobjects.
47 SmallVector<BaseSubobjectInfo*, 4> Bases;
48
49 /// PrimaryVirtualBaseInfo - Holds the base info for the primary virtual base
50 /// of this base info (if one exists).
51 BaseSubobjectInfo *PrimaryVirtualBaseInfo;
52
53 // FIXME: Document.
54 const BaseSubobjectInfo *Derived;
55};
56
57/// \brief Externally provided layout. Typically used when the AST source, such
58/// as DWARF, lacks all the information that was available at compile time, such
59/// as alignment attributes on fields and pragmas in effect.
60struct ExternalLayout {
61 ExternalLayout() : Size(0), Align(0) {}
62
63 /// \brief Overall record size in bits.
64 uint64_t Size;
65
66 /// \brief Overall record alignment in bits.
67 uint64_t Align;
68
69 /// \brief Record field offsets in bits.
70 llvm::DenseMap<const FieldDecl *, uint64_t> FieldOffsets;
71
72 /// \brief Direct, non-virtual base offsets.
73 llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsets;
74
75 /// \brief Virtual base offsets.
76 llvm::DenseMap<const CXXRecordDecl *, CharUnits> VirtualBaseOffsets;
77
78 /// Get the offset of the given field. The external source must provide
79 /// entries for all fields in the record.
80 uint64_t getExternalFieldOffset(const FieldDecl *FD) {
81 assert(FieldOffsets.count(FD) &&(static_cast <bool> (FieldOffsets.count(FD) && "Field does not have an external offset"
) ? void (0) : __assert_fail ("FieldOffsets.count(FD) && \"Field does not have an external offset\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 82, __extension__ __PRETTY_FUNCTION__))
82 "Field does not have an external offset")(static_cast <bool> (FieldOffsets.count(FD) && "Field does not have an external offset"
) ? void (0) : __assert_fail ("FieldOffsets.count(FD) && \"Field does not have an external offset\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 82, __extension__ __PRETTY_FUNCTION__))
;
83 return FieldOffsets[FD];
84 }
85
86 bool getExternalNVBaseOffset(const CXXRecordDecl *RD, CharUnits &BaseOffset) {
87 auto Known = BaseOffsets.find(RD);
88 if (Known == BaseOffsets.end())
89 return false;
90 BaseOffset = Known->second;
91 return true;
92 }
93
94 bool getExternalVBaseOffset(const CXXRecordDecl *RD, CharUnits &BaseOffset) {
95 auto Known = VirtualBaseOffsets.find(RD);
96 if (Known == VirtualBaseOffsets.end())
97 return false;
98 BaseOffset = Known->second;
99 return true;
100 }
101};
102
103/// EmptySubobjectMap - Keeps track of which empty subobjects exist at different
104/// offsets while laying out a C++ class.
105class EmptySubobjectMap {
106 const ASTContext &Context;
107 uint64_t CharWidth;
108
109 /// Class - The class whose empty entries we're keeping track of.
110 const CXXRecordDecl *Class;
111
112 /// EmptyClassOffsets - A map from offsets to empty record decls.
113 typedef llvm::TinyPtrVector<const CXXRecordDecl *> ClassVectorTy;
114 typedef llvm::DenseMap<CharUnits, ClassVectorTy> EmptyClassOffsetsMapTy;
115 EmptyClassOffsetsMapTy EmptyClassOffsets;
116
117 /// MaxEmptyClassOffset - The highest offset known to contain an empty
118 /// base subobject.
119 CharUnits MaxEmptyClassOffset;
120
121 /// ComputeEmptySubobjectSizes - Compute the size of the largest base or
122 /// member subobject that is empty.
123 void ComputeEmptySubobjectSizes();
124
125 void AddSubobjectAtOffset(const CXXRecordDecl *RD, CharUnits Offset);
126
127 void UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info,
128 CharUnits Offset, bool PlacingEmptyBase);
129
130 void UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD,
131 const CXXRecordDecl *Class,
132 CharUnits Offset);
133 void UpdateEmptyFieldSubobjects(const FieldDecl *FD, CharUnits Offset);
134
135 /// AnyEmptySubobjectsBeyondOffset - Returns whether there are any empty
136 /// subobjects beyond the given offset.
137 bool AnyEmptySubobjectsBeyondOffset(CharUnits Offset) const {
138 return Offset <= MaxEmptyClassOffset;
139 }
140
141 CharUnits
142 getFieldOffset(const ASTRecordLayout &Layout, unsigned FieldNo) const {
143 uint64_t FieldOffset = Layout.getFieldOffset(FieldNo);
144 assert(FieldOffset % CharWidth == 0 &&(static_cast <bool> (FieldOffset % CharWidth == 0 &&
"Field offset not at char boundary!") ? void (0) : __assert_fail
("FieldOffset % CharWidth == 0 && \"Field offset not at char boundary!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 145, __extension__ __PRETTY_FUNCTION__))
145 "Field offset not at char boundary!")(static_cast <bool> (FieldOffset % CharWidth == 0 &&
"Field offset not at char boundary!") ? void (0) : __assert_fail
("FieldOffset % CharWidth == 0 && \"Field offset not at char boundary!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 145, __extension__ __PRETTY_FUNCTION__))
;
146
147 return Context.toCharUnitsFromBits(FieldOffset);
148 }
149
150protected:
151 bool CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD,
152 CharUnits Offset) const;
153
154 bool CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info,
155 CharUnits Offset);
156
157 bool CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD,
158 const CXXRecordDecl *Class,
159 CharUnits Offset) const;
160 bool CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD,
161 CharUnits Offset) const;
162
163public:
164 /// This holds the size of the largest empty subobject (either a base
165 /// or a member). Will be zero if the record being built doesn't contain
166 /// any empty classes.
167 CharUnits SizeOfLargestEmptySubobject;
168
169 EmptySubobjectMap(const ASTContext &Context, const CXXRecordDecl *Class)
170 : Context(Context), CharWidth(Context.getCharWidth()), Class(Class) {
171 ComputeEmptySubobjectSizes();
172 }
173
174 /// CanPlaceBaseAtOffset - Return whether the given base class can be placed
175 /// at the given offset.
176 /// Returns false if placing the record will result in two components
177 /// (direct or indirect) of the same type having the same offset.
178 bool CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info,
179 CharUnits Offset);
180
181 /// CanPlaceFieldAtOffset - Return whether a field can be placed at the given
182 /// offset.
183 bool CanPlaceFieldAtOffset(const FieldDecl *FD, CharUnits Offset);
184};
185
186void EmptySubobjectMap::ComputeEmptySubobjectSizes() {
187 // Check the bases.
188 for (const CXXBaseSpecifier &Base : Class->bases()) {
189 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
190
191 CharUnits EmptySize;
192 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
193 if (BaseDecl->isEmpty()) {
194 // If the class decl is empty, get its size.
195 EmptySize = Layout.getSize();
196 } else {
197 // Otherwise, we get the largest empty subobject for the decl.
198 EmptySize = Layout.getSizeOfLargestEmptySubobject();
199 }
200
201 if (EmptySize > SizeOfLargestEmptySubobject)
202 SizeOfLargestEmptySubobject = EmptySize;
203 }
204
205 // Check the fields.
206 for (const FieldDecl *FD : Class->fields()) {
207 const RecordType *RT =
208 Context.getBaseElementType(FD->getType())->getAs<RecordType>();
209
210 // We only care about record types.
211 if (!RT)
212 continue;
213
214 CharUnits EmptySize;
215 const CXXRecordDecl *MemberDecl = RT->getAsCXXRecordDecl();
216 const ASTRecordLayout &Layout = Context.getASTRecordLayout(MemberDecl);
217 if (MemberDecl->isEmpty()) {
218 // If the class decl is empty, get its size.
219 EmptySize = Layout.getSize();
220 } else {
221 // Otherwise, we get the largest empty subobject for the decl.
222 EmptySize = Layout.getSizeOfLargestEmptySubobject();
223 }
224
225 if (EmptySize > SizeOfLargestEmptySubobject)
226 SizeOfLargestEmptySubobject = EmptySize;
227 }
228}
229
230bool
231EmptySubobjectMap::CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD,
232 CharUnits Offset) const {
233 // We only need to check empty bases.
234 if (!RD->isEmpty())
235 return true;
236
237 EmptyClassOffsetsMapTy::const_iterator I = EmptyClassOffsets.find(Offset);
238 if (I == EmptyClassOffsets.end())
239 return true;
240
241 const ClassVectorTy &Classes = I->second;
242 if (std::find(Classes.begin(), Classes.end(), RD) == Classes.end())
243 return true;
244
245 // There is already an empty class of the same type at this offset.
246 return false;
247}
248
249void EmptySubobjectMap::AddSubobjectAtOffset(const CXXRecordDecl *RD,
250 CharUnits Offset) {
251 // We only care about empty bases.
252 if (!RD->isEmpty())
253 return;
254
255 // If we have empty structures inside a union, we can assign both
256 // the same offset. Just avoid pushing them twice in the list.
257 ClassVectorTy &Classes = EmptyClassOffsets[Offset];
258 if (std::find(Classes.begin(), Classes.end(), RD) != Classes.end())
259 return;
260
261 Classes.push_back(RD);
262
263 // Update the empty class offset.
264 if (Offset > MaxEmptyClassOffset)
265 MaxEmptyClassOffset = Offset;
266}
267
268bool
269EmptySubobjectMap::CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info,
270 CharUnits Offset) {
271 // We don't have to keep looking past the maximum offset that's known to
272 // contain an empty class.
273 if (!AnyEmptySubobjectsBeyondOffset(Offset))
274 return true;
275
276 if (!CanPlaceSubobjectAtOffset(Info->Class, Offset))
277 return false;
278
279 // Traverse all non-virtual bases.
280 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
281 for (const BaseSubobjectInfo *Base : Info->Bases) {
282 if (Base->IsVirtual)
283 continue;
284
285 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
286
287 if (!CanPlaceBaseSubobjectAtOffset(Base, BaseOffset))
288 return false;
289 }
290
291 if (Info->PrimaryVirtualBaseInfo) {
292 BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
293
294 if (Info == PrimaryVirtualBaseInfo->Derived) {
295 if (!CanPlaceBaseSubobjectAtOffset(PrimaryVirtualBaseInfo, Offset))
296 return false;
297 }
298 }
299
300 // Traverse all member variables.
301 unsigned FieldNo = 0;
302 for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(),
303 E = Info->Class->field_end(); I != E; ++I, ++FieldNo) {
304 if (I->isBitField())
305 continue;
306
307 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
308 if (!CanPlaceFieldSubobjectAtOffset(*I, FieldOffset))
309 return false;
310 }
311
312 return true;
313}
314
315void EmptySubobjectMap::UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info,
316 CharUnits Offset,
317 bool PlacingEmptyBase) {
318 if (!PlacingEmptyBase && Offset >= SizeOfLargestEmptySubobject) {
319 // We know that the only empty subobjects that can conflict with empty
320 // subobject of non-empty bases, are empty bases that can be placed at
321 // offset zero. Because of this, we only need to keep track of empty base
322 // subobjects with offsets less than the size of the largest empty
323 // subobject for our class.
324 return;
325 }
326
327 AddSubobjectAtOffset(Info->Class, Offset);
328
329 // Traverse all non-virtual bases.
330 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
331 for (const BaseSubobjectInfo *Base : Info->Bases) {
332 if (Base->IsVirtual)
333 continue;
334
335 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
336 UpdateEmptyBaseSubobjects(Base, BaseOffset, PlacingEmptyBase);
337 }
338
339 if (Info->PrimaryVirtualBaseInfo) {
340 BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
341
342 if (Info == PrimaryVirtualBaseInfo->Derived)
343 UpdateEmptyBaseSubobjects(PrimaryVirtualBaseInfo, Offset,
344 PlacingEmptyBase);
345 }
346
347 // Traverse all member variables.
348 unsigned FieldNo = 0;
349 for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(),
350 E = Info->Class->field_end(); I != E; ++I, ++FieldNo) {
351 if (I->isBitField())
352 continue;
353
354 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
355 UpdateEmptyFieldSubobjects(*I, FieldOffset);
356 }
357}
358
359bool EmptySubobjectMap::CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info,
360 CharUnits Offset) {
361 // If we know this class doesn't have any empty subobjects we don't need to
362 // bother checking.
363 if (SizeOfLargestEmptySubobject.isZero())
364 return true;
365
366 if (!CanPlaceBaseSubobjectAtOffset(Info, Offset))
367 return false;
368
369 // We are able to place the base at this offset. Make sure to update the
370 // empty base subobject map.
371 UpdateEmptyBaseSubobjects(Info, Offset, Info->Class->isEmpty());
372 return true;
373}
374
375bool
376EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD,
377 const CXXRecordDecl *Class,
378 CharUnits Offset) const {
379 // We don't have to keep looking past the maximum offset that's known to
380 // contain an empty class.
381 if (!AnyEmptySubobjectsBeyondOffset(Offset))
382 return true;
383
384 if (!CanPlaceSubobjectAtOffset(RD, Offset))
385 return false;
386
387 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
388
389 // Traverse all non-virtual bases.
390 for (const CXXBaseSpecifier &Base : RD->bases()) {
391 if (Base.isVirtual())
392 continue;
393
394 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
395
396 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
397 if (!CanPlaceFieldSubobjectAtOffset(BaseDecl, Class, BaseOffset))
398 return false;
399 }
400
401 if (RD == Class) {
402 // This is the most derived class, traverse virtual bases as well.
403 for (const CXXBaseSpecifier &Base : RD->vbases()) {
404 const CXXRecordDecl *VBaseDecl = Base.getType()->getAsCXXRecordDecl();
405
406 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
407 if (!CanPlaceFieldSubobjectAtOffset(VBaseDecl, Class, VBaseOffset))
408 return false;
409 }
410 }
411
412 // Traverse all member variables.
413 unsigned FieldNo = 0;
414 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
415 I != E; ++I, ++FieldNo) {
416 if (I->isBitField())
417 continue;
418
419 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
420
421 if (!CanPlaceFieldSubobjectAtOffset(*I, FieldOffset))
422 return false;
423 }
424
425 return true;
426}
427
428bool
429EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD,
430 CharUnits Offset) const {
431 // We don't have to keep looking past the maximum offset that's known to
432 // contain an empty class.
433 if (!AnyEmptySubobjectsBeyondOffset(Offset))
434 return true;
435
436 QualType T = FD->getType();
437 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
438 return CanPlaceFieldSubobjectAtOffset(RD, RD, Offset);
439
440 // If we have an array type we need to look at every element.
441 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
442 QualType ElemTy = Context.getBaseElementType(AT);
443 const RecordType *RT = ElemTy->getAs<RecordType>();
444 if (!RT)
445 return true;
446
447 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
448 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
449
450 uint64_t NumElements = Context.getConstantArrayElementCount(AT);
451 CharUnits ElementOffset = Offset;
452 for (uint64_t I = 0; I != NumElements; ++I) {
453 // We don't have to keep looking past the maximum offset that's known to
454 // contain an empty class.
455 if (!AnyEmptySubobjectsBeyondOffset(ElementOffset))
456 return true;
457
458 if (!CanPlaceFieldSubobjectAtOffset(RD, RD, ElementOffset))
459 return false;
460
461 ElementOffset += Layout.getSize();
462 }
463 }
464
465 return true;
466}
467
468bool
469EmptySubobjectMap::CanPlaceFieldAtOffset(const FieldDecl *FD,
470 CharUnits Offset) {
471 if (!CanPlaceFieldSubobjectAtOffset(FD, Offset))
472 return false;
473
474 // We are able to place the member variable at this offset.
475 // Make sure to update the empty base subobject map.
476 UpdateEmptyFieldSubobjects(FD, Offset);
477 return true;
478}
479
480void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD,
481 const CXXRecordDecl *Class,
482 CharUnits Offset) {
483 // We know that the only empty subobjects that can conflict with empty
484 // field subobjects are subobjects of empty bases that can be placed at offset
485 // zero. Because of this, we only need to keep track of empty field
486 // subobjects with offsets less than the size of the largest empty
487 // subobject for our class.
488 if (Offset >= SizeOfLargestEmptySubobject)
489 return;
490
491 AddSubobjectAtOffset(RD, Offset);
492
493 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
494
495 // Traverse all non-virtual bases.
496 for (const CXXBaseSpecifier &Base : RD->bases()) {
497 if (Base.isVirtual())
498 continue;
499
500 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
501
502 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
503 UpdateEmptyFieldSubobjects(BaseDecl, Class, BaseOffset);
504 }
505
506 if (RD == Class) {
507 // This is the most derived class, traverse virtual bases as well.
508 for (const CXXBaseSpecifier &Base : RD->vbases()) {
509 const CXXRecordDecl *VBaseDecl = Base.getType()->getAsCXXRecordDecl();
510
511 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
512 UpdateEmptyFieldSubobjects(VBaseDecl, Class, VBaseOffset);
513 }
514 }
515
516 // Traverse all member variables.
517 unsigned FieldNo = 0;
518 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
519 I != E; ++I, ++FieldNo) {
520 if (I->isBitField())
521 continue;
522
523 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
524
525 UpdateEmptyFieldSubobjects(*I, FieldOffset);
526 }
527}
528
529void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const FieldDecl *FD,
530 CharUnits Offset) {
531 QualType T = FD->getType();
532 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
533 UpdateEmptyFieldSubobjects(RD, RD, Offset);
534 return;
535 }
536
537 // If we have an array type we need to update every element.
538 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
539 QualType ElemTy = Context.getBaseElementType(AT);
540 const RecordType *RT = ElemTy->getAs<RecordType>();
541 if (!RT)
542 return;
543
544 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
545 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
546
547 uint64_t NumElements = Context.getConstantArrayElementCount(AT);
548 CharUnits ElementOffset = Offset;
549
550 for (uint64_t I = 0; I != NumElements; ++I) {
551 // We know that the only empty subobjects that can conflict with empty
552 // field subobjects are subobjects of empty bases that can be placed at
553 // offset zero. Because of this, we only need to keep track of empty field
554 // subobjects with offsets less than the size of the largest empty
555 // subobject for our class.
556 if (ElementOffset >= SizeOfLargestEmptySubobject)
557 return;
558
559 UpdateEmptyFieldSubobjects(RD, RD, ElementOffset);
560 ElementOffset += Layout.getSize();
561 }
562 }
563}
564
565typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> ClassSetTy;
566
567class ItaniumRecordLayoutBuilder {
568protected:
569 // FIXME: Remove this and make the appropriate fields public.
570 friend class clang::ASTContext;
571
572 const ASTContext &Context;
573
574 EmptySubobjectMap *EmptySubobjects;
575
576 /// Size - The current size of the record layout.
577 uint64_t Size;
578
579 /// Alignment - The current alignment of the record layout.
580 CharUnits Alignment;
581
582 /// \brief The alignment if attribute packed is not used.
583 CharUnits UnpackedAlignment;
584
585 SmallVector<uint64_t, 16> FieldOffsets;
586
587 /// \brief Whether the external AST source has provided a layout for this
588 /// record.
589 unsigned UseExternalLayout : 1;
590
591 /// \brief Whether we need to infer alignment, even when we have an
592 /// externally-provided layout.
593 unsigned InferAlignment : 1;
594
595 /// Packed - Whether the record is packed or not.
596 unsigned Packed : 1;
597
598 unsigned IsUnion : 1;
599
600 unsigned IsMac68kAlign : 1;
601
602 unsigned IsMsStruct : 1;
603
604 /// UnfilledBitsInLastUnit - If the last field laid out was a bitfield,
605 /// this contains the number of bits in the last unit that can be used for
606 /// an adjacent bitfield if necessary. The unit in question is usually
607 /// a byte, but larger units are used if IsMsStruct.
608 unsigned char UnfilledBitsInLastUnit;
609 /// LastBitfieldTypeSize - If IsMsStruct, represents the size of the type
610 /// of the previous field if it was a bitfield.
611 unsigned char LastBitfieldTypeSize;
612
613 /// MaxFieldAlignment - The maximum allowed field alignment. This is set by
614 /// #pragma pack.
615 CharUnits MaxFieldAlignment;
616
617 /// DataSize - The data size of the record being laid out.
618 uint64_t DataSize;
619
620 CharUnits NonVirtualSize;
621 CharUnits NonVirtualAlignment;
622
623 /// PrimaryBase - the primary base class (if one exists) of the class
624 /// we're laying out.
625 const CXXRecordDecl *PrimaryBase;
626
627 /// PrimaryBaseIsVirtual - Whether the primary base of the class we're laying
628 /// out is virtual.
629 bool PrimaryBaseIsVirtual;
630
631 /// HasOwnVFPtr - Whether the class provides its own vtable/vftbl
632 /// pointer, as opposed to inheriting one from a primary base class.
633 bool HasOwnVFPtr;
634
635 /// \brief the flag of field offset changing due to packed attribute.
636 bool HasPackedField;
637
638 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
639
640 /// Bases - base classes and their offsets in the record.
641 BaseOffsetsMapTy Bases;
642
643 // VBases - virtual base classes and their offsets in the record.
644 ASTRecordLayout::VBaseOffsetsMapTy VBases;
645
646 /// IndirectPrimaryBases - Virtual base classes, direct or indirect, that are
647 /// primary base classes for some other direct or indirect base class.
648 CXXIndirectPrimaryBaseSet IndirectPrimaryBases;
649
650 /// FirstNearlyEmptyVBase - The first nearly empty virtual base class in
651 /// inheritance graph order. Used for determining the primary base class.
652 const CXXRecordDecl *FirstNearlyEmptyVBase;
653
654 /// VisitedVirtualBases - A set of all the visited virtual bases, used to
655 /// avoid visiting virtual bases more than once.
656 llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
657
658 /// Valid if UseExternalLayout is true.
659 ExternalLayout External;
660
661 ItaniumRecordLayoutBuilder(const ASTContext &Context,
662 EmptySubobjectMap *EmptySubobjects)
663 : Context(Context), EmptySubobjects(EmptySubobjects), Size(0),
664 Alignment(CharUnits::One()), UnpackedAlignment(CharUnits::One()),
665 UseExternalLayout(false), InferAlignment(false), Packed(false),
666 IsUnion(false), IsMac68kAlign(false), IsMsStruct(false),
667 UnfilledBitsInLastUnit(0), LastBitfieldTypeSize(0),
668 MaxFieldAlignment(CharUnits::Zero()), DataSize(0),
669 NonVirtualSize(CharUnits::Zero()),
670 NonVirtualAlignment(CharUnits::One()), PrimaryBase(nullptr),
671 PrimaryBaseIsVirtual(false), HasOwnVFPtr(false),
672 HasPackedField(false), FirstNearlyEmptyVBase(nullptr) {}
673
674 void Layout(const RecordDecl *D);
675 void Layout(const CXXRecordDecl *D);
676 void Layout(const ObjCInterfaceDecl *D);
677
678 void LayoutFields(const RecordDecl *D);
679 void LayoutField(const FieldDecl *D, bool InsertExtraPadding);
680 void LayoutWideBitField(uint64_t FieldSize, uint64_t TypeSize,
681 bool FieldPacked, const FieldDecl *D);
682 void LayoutBitField(const FieldDecl *D);
683
684 TargetCXXABI getCXXABI() const {
685 return Context.getTargetInfo().getCXXABI();
686 }
687
688 /// BaseSubobjectInfoAllocator - Allocator for BaseSubobjectInfo objects.
689 llvm::SpecificBumpPtrAllocator<BaseSubobjectInfo> BaseSubobjectInfoAllocator;
690
691 typedef llvm::DenseMap<const CXXRecordDecl *, BaseSubobjectInfo *>
692 BaseSubobjectInfoMapTy;
693
694 /// VirtualBaseInfo - Map from all the (direct or indirect) virtual bases
695 /// of the class we're laying out to their base subobject info.
696 BaseSubobjectInfoMapTy VirtualBaseInfo;
697
698 /// NonVirtualBaseInfo - Map from all the direct non-virtual bases of the
699 /// class we're laying out to their base subobject info.
700 BaseSubobjectInfoMapTy NonVirtualBaseInfo;
701
702 /// ComputeBaseSubobjectInfo - Compute the base subobject information for the
703 /// bases of the given class.
704 void ComputeBaseSubobjectInfo(const CXXRecordDecl *RD);
705
706 /// ComputeBaseSubobjectInfo - Compute the base subobject information for a
707 /// single class and all of its base classes.
708 BaseSubobjectInfo *ComputeBaseSubobjectInfo(const CXXRecordDecl *RD,
709 bool IsVirtual,
710 BaseSubobjectInfo *Derived);
711
712 /// DeterminePrimaryBase - Determine the primary base of the given class.
713 void DeterminePrimaryBase(const CXXRecordDecl *RD);
714
715 void SelectPrimaryVBase(const CXXRecordDecl *RD);
716
717 void EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign);
718
719 /// LayoutNonVirtualBases - Determines the primary base class (if any) and
720 /// lays it out. Will then proceed to lay out all non-virtual base clasess.
721 void LayoutNonVirtualBases(const CXXRecordDecl *RD);
722
723 /// LayoutNonVirtualBase - Lays out a single non-virtual base.
724 void LayoutNonVirtualBase(const BaseSubobjectInfo *Base);
725
726 void AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
727 CharUnits Offset);
728
729 /// LayoutVirtualBases - Lays out all the virtual bases.
730 void LayoutVirtualBases(const CXXRecordDecl *RD,
731 const CXXRecordDecl *MostDerivedClass);
732
733 /// LayoutVirtualBase - Lays out a single virtual base.
734 void LayoutVirtualBase(const BaseSubobjectInfo *Base);
735
736 /// LayoutBase - Will lay out a base and return the offset where it was
737 /// placed, in chars.
738 CharUnits LayoutBase(const BaseSubobjectInfo *Base);
739
740 /// InitializeLayout - Initialize record layout for the given record decl.
741 void InitializeLayout(const Decl *D);
742
743 /// FinishLayout - Finalize record layout. Adjust record size based on the
744 /// alignment.
745 void FinishLayout(const NamedDecl *D);
746
747 void UpdateAlignment(CharUnits NewAlignment, CharUnits UnpackedNewAlignment);
748 void UpdateAlignment(CharUnits NewAlignment) {
749 UpdateAlignment(NewAlignment, NewAlignment);
750 }
751
752 /// \brief Retrieve the externally-supplied field offset for the given
753 /// field.
754 ///
755 /// \param Field The field whose offset is being queried.
756 /// \param ComputedOffset The offset that we've computed for this field.
757 uint64_t updateExternalFieldOffset(const FieldDecl *Field,
758 uint64_t ComputedOffset);
759
760 void CheckFieldPadding(uint64_t Offset, uint64_t UnpaddedOffset,
761 uint64_t UnpackedOffset, unsigned UnpackedAlign,
762 bool isPacked, const FieldDecl *D);
763
764 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
765
766 CharUnits getSize() const {
767 assert(Size % Context.getCharWidth() == 0)(static_cast <bool> (Size % Context.getCharWidth() == 0
) ? void (0) : __assert_fail ("Size % Context.getCharWidth() == 0"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 767, __extension__ __PRETTY_FUNCTION__))
;
768 return Context.toCharUnitsFromBits(Size);
769 }
770 uint64_t getSizeInBits() const { return Size; }
771
772 void setSize(CharUnits NewSize) { Size = Context.toBits(NewSize); }
773 void setSize(uint64_t NewSize) { Size = NewSize; }
774
775 CharUnits getAligment() const { return Alignment; }
776
777 CharUnits getDataSize() const {
778 assert(DataSize % Context.getCharWidth() == 0)(static_cast <bool> (DataSize % Context.getCharWidth() ==
0) ? void (0) : __assert_fail ("DataSize % Context.getCharWidth() == 0"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 778, __extension__ __PRETTY_FUNCTION__))
;
779 return Context.toCharUnitsFromBits(DataSize);
780 }
781 uint64_t getDataSizeInBits() const { return DataSize; }
782
783 void setDataSize(CharUnits NewSize) { DataSize = Context.toBits(NewSize); }
784 void setDataSize(uint64_t NewSize) { DataSize = NewSize; }
785
786 ItaniumRecordLayoutBuilder(const ItaniumRecordLayoutBuilder &) = delete;
787 void operator=(const ItaniumRecordLayoutBuilder &) = delete;
788};
789} // end anonymous namespace
790
791void ItaniumRecordLayoutBuilder::SelectPrimaryVBase(const CXXRecordDecl *RD) {
792 for (const auto &I : RD->bases()) {
793 assert(!I.getType()->isDependentType() &&(static_cast <bool> (!I.getType()->isDependentType()
&& "Cannot layout class with dependent bases.") ? void
(0) : __assert_fail ("!I.getType()->isDependentType() && \"Cannot layout class with dependent bases.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 794, __extension__ __PRETTY_FUNCTION__))
794 "Cannot layout class with dependent bases.")(static_cast <bool> (!I.getType()->isDependentType()
&& "Cannot layout class with dependent bases.") ? void
(0) : __assert_fail ("!I.getType()->isDependentType() && \"Cannot layout class with dependent bases.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 794, __extension__ __PRETTY_FUNCTION__))
;
795
796 const CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
797
798 // Check if this is a nearly empty virtual base.
799 if (I.isVirtual() && Context.isNearlyEmpty(Base)) {
800 // If it's not an indirect primary base, then we've found our primary
801 // base.
802 if (!IndirectPrimaryBases.count(Base)) {
803 PrimaryBase = Base;
804 PrimaryBaseIsVirtual = true;
805 return;
806 }
807
808 // Is this the first nearly empty virtual base?
809 if (!FirstNearlyEmptyVBase)
810 FirstNearlyEmptyVBase = Base;
811 }
812
813 SelectPrimaryVBase(Base);
814 if (PrimaryBase)
815 return;
816 }
817}
818
819/// DeterminePrimaryBase - Determine the primary base of the given class.
820void ItaniumRecordLayoutBuilder::DeterminePrimaryBase(const CXXRecordDecl *RD) {
821 // If the class isn't dynamic, it won't have a primary base.
822 if (!RD->isDynamicClass())
823 return;
824
825 // Compute all the primary virtual bases for all of our direct and
826 // indirect bases, and record all their primary virtual base classes.
827 RD->getIndirectPrimaryBases(IndirectPrimaryBases);
828
829 // If the record has a dynamic base class, attempt to choose a primary base
830 // class. It is the first (in direct base class order) non-virtual dynamic
831 // base class, if one exists.
832 for (const auto &I : RD->bases()) {
833 // Ignore virtual bases.
834 if (I.isVirtual())
835 continue;
836
837 const CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
838
839 if (Base->isDynamicClass()) {
840 // We found it.
841 PrimaryBase = Base;
842 PrimaryBaseIsVirtual = false;
843 return;
844 }
845 }
846
847 // Under the Itanium ABI, if there is no non-virtual primary base class,
848 // try to compute the primary virtual base. The primary virtual base is
849 // the first nearly empty virtual base that is not an indirect primary
850 // virtual base class, if one exists.
851 if (RD->getNumVBases() != 0) {
852 SelectPrimaryVBase(RD);
853 if (PrimaryBase)
854 return;
855 }
856
857 // Otherwise, it is the first indirect primary base class, if one exists.
858 if (FirstNearlyEmptyVBase) {
859 PrimaryBase = FirstNearlyEmptyVBase;
860 PrimaryBaseIsVirtual = true;
861 return;
862 }
863
864 assert(!PrimaryBase && "Should not get here with a primary base!")(static_cast <bool> (!PrimaryBase && "Should not get here with a primary base!"
) ? void (0) : __assert_fail ("!PrimaryBase && \"Should not get here with a primary base!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 864, __extension__ __PRETTY_FUNCTION__))
;
865}
866
867BaseSubobjectInfo *ItaniumRecordLayoutBuilder::ComputeBaseSubobjectInfo(
868 const CXXRecordDecl *RD, bool IsVirtual, BaseSubobjectInfo *Derived) {
869 BaseSubobjectInfo *Info;
870
871 if (IsVirtual) {
872 // Check if we already have info about this virtual base.
873 BaseSubobjectInfo *&InfoSlot = VirtualBaseInfo[RD];
874 if (InfoSlot) {
875 assert(InfoSlot->Class == RD && "Wrong class for virtual base info!")(static_cast <bool> (InfoSlot->Class == RD &&
"Wrong class for virtual base info!") ? void (0) : __assert_fail
("InfoSlot->Class == RD && \"Wrong class for virtual base info!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 875, __extension__ __PRETTY_FUNCTION__))
;
876 return InfoSlot;
877 }
878
879 // We don't, create it.
880 InfoSlot = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
881 Info = InfoSlot;
882 } else {
883 Info = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
884 }
885
886 Info->Class = RD;
887 Info->IsVirtual = IsVirtual;
888 Info->Derived = nullptr;
889 Info->PrimaryVirtualBaseInfo = nullptr;
890
891 const CXXRecordDecl *PrimaryVirtualBase = nullptr;
892 BaseSubobjectInfo *PrimaryVirtualBaseInfo = nullptr;
893
894 // Check if this base has a primary virtual base.
895 if (RD->getNumVBases()) {
896 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
897 if (Layout.isPrimaryBaseVirtual()) {
898 // This base does have a primary virtual base.
899 PrimaryVirtualBase = Layout.getPrimaryBase();
900 assert(PrimaryVirtualBase && "Didn't have a primary virtual base!")(static_cast <bool> (PrimaryVirtualBase && "Didn't have a primary virtual base!"
) ? void (0) : __assert_fail ("PrimaryVirtualBase && \"Didn't have a primary virtual base!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 900, __extension__ __PRETTY_FUNCTION__))
;
901
902 // Now check if we have base subobject info about this primary base.
903 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
904
905 if (PrimaryVirtualBaseInfo) {
906 if (PrimaryVirtualBaseInfo->Derived) {
907 // We did have info about this primary base, and it turns out that it
908 // has already been claimed as a primary virtual base for another
909 // base.
910 PrimaryVirtualBase = nullptr;
911 } else {
912 // We can claim this base as our primary base.
913 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
914 PrimaryVirtualBaseInfo->Derived = Info;
915 }
916 }
917 }
918 }
919
920 // Now go through all direct bases.
921 for (const auto &I : RD->bases()) {
922 bool IsVirtual = I.isVirtual();
923
924 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
925
926 Info->Bases.push_back(ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, Info));
927 }
928
929 if (PrimaryVirtualBase && !PrimaryVirtualBaseInfo) {
930 // Traversing the bases must have created the base info for our primary
931 // virtual base.
932 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
933 assert(PrimaryVirtualBaseInfo &&(static_cast <bool> (PrimaryVirtualBaseInfo && "Did not create a primary virtual base!"
) ? void (0) : __assert_fail ("PrimaryVirtualBaseInfo && \"Did not create a primary virtual base!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 934, __extension__ __PRETTY_FUNCTION__))
934 "Did not create a primary virtual base!")(static_cast <bool> (PrimaryVirtualBaseInfo && "Did not create a primary virtual base!"
) ? void (0) : __assert_fail ("PrimaryVirtualBaseInfo && \"Did not create a primary virtual base!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 934, __extension__ __PRETTY_FUNCTION__))
;
935
936 // Claim the primary virtual base as our primary virtual base.
937 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
938 PrimaryVirtualBaseInfo->Derived = Info;
939 }
940
941 return Info;
942}
943
944void ItaniumRecordLayoutBuilder::ComputeBaseSubobjectInfo(
945 const CXXRecordDecl *RD) {
946 for (const auto &I : RD->bases()) {
947 bool IsVirtual = I.isVirtual();
948
949 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
950
951 // Compute the base subobject info for this base.
952 BaseSubobjectInfo *Info = ComputeBaseSubobjectInfo(BaseDecl, IsVirtual,
953 nullptr);
954
955 if (IsVirtual) {
956 // ComputeBaseInfo has already added this base for us.
957 assert(VirtualBaseInfo.count(BaseDecl) &&(static_cast <bool> (VirtualBaseInfo.count(BaseDecl) &&
"Did not add virtual base!") ? void (0) : __assert_fail ("VirtualBaseInfo.count(BaseDecl) && \"Did not add virtual base!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 958, __extension__ __PRETTY_FUNCTION__))
958 "Did not add virtual base!")(static_cast <bool> (VirtualBaseInfo.count(BaseDecl) &&
"Did not add virtual base!") ? void (0) : __assert_fail ("VirtualBaseInfo.count(BaseDecl) && \"Did not add virtual base!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 958, __extension__ __PRETTY_FUNCTION__))
;
959 } else {
960 // Add the base info to the map of non-virtual bases.
961 assert(!NonVirtualBaseInfo.count(BaseDecl) &&(static_cast <bool> (!NonVirtualBaseInfo.count(BaseDecl
) && "Non-virtual base already exists!") ? void (0) :
__assert_fail ("!NonVirtualBaseInfo.count(BaseDecl) && \"Non-virtual base already exists!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 962, __extension__ __PRETTY_FUNCTION__))
962 "Non-virtual base already exists!")(static_cast <bool> (!NonVirtualBaseInfo.count(BaseDecl
) && "Non-virtual base already exists!") ? void (0) :
__assert_fail ("!NonVirtualBaseInfo.count(BaseDecl) && \"Non-virtual base already exists!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 962, __extension__ __PRETTY_FUNCTION__))
;
963 NonVirtualBaseInfo.insert(std::make_pair(BaseDecl, Info));
964 }
965 }
966}
967
968void ItaniumRecordLayoutBuilder::EnsureVTablePointerAlignment(
969 CharUnits UnpackedBaseAlign) {
970 CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
971
972 // The maximum field alignment overrides base align.
973 if (!MaxFieldAlignment.isZero()) {
974 BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
975 UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
976 }
977
978 // Round up the current record size to pointer alignment.
979 setSize(getSize().alignTo(BaseAlign));
980 setDataSize(getSize());
981
982 // Update the alignment.
983 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
984}
985
986void ItaniumRecordLayoutBuilder::LayoutNonVirtualBases(
987 const CXXRecordDecl *RD) {
988 // Then, determine the primary base class.
989 DeterminePrimaryBase(RD);
990
991 // Compute base subobject info.
992 ComputeBaseSubobjectInfo(RD);
993
994 // If we have a primary base class, lay it out.
995 if (PrimaryBase) {
996 if (PrimaryBaseIsVirtual) {
997 // If the primary virtual base was a primary virtual base of some other
998 // base class we'll have to steal it.
999 BaseSubobjectInfo *PrimaryBaseInfo = VirtualBaseInfo.lookup(PrimaryBase);
1000 PrimaryBaseInfo->Derived = nullptr;
1001
1002 // We have a virtual primary base, insert it as an indirect primary base.
1003 IndirectPrimaryBases.insert(PrimaryBase);
1004
1005 assert(!VisitedVirtualBases.count(PrimaryBase) &&(static_cast <bool> (!VisitedVirtualBases.count(PrimaryBase
) && "vbase already visited!") ? void (0) : __assert_fail
("!VisitedVirtualBases.count(PrimaryBase) && \"vbase already visited!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1006, __extension__ __PRETTY_FUNCTION__))
1006 "vbase already visited!")(static_cast <bool> (!VisitedVirtualBases.count(PrimaryBase
) && "vbase already visited!") ? void (0) : __assert_fail
("!VisitedVirtualBases.count(PrimaryBase) && \"vbase already visited!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1006, __extension__ __PRETTY_FUNCTION__))
;
1007 VisitedVirtualBases.insert(PrimaryBase);
1008
1009 LayoutVirtualBase(PrimaryBaseInfo);
1010 } else {
1011 BaseSubobjectInfo *PrimaryBaseInfo =
1012 NonVirtualBaseInfo.lookup(PrimaryBase);
1013 assert(PrimaryBaseInfo &&(static_cast <bool> (PrimaryBaseInfo && "Did not find base info for non-virtual primary base!"
) ? void (0) : __assert_fail ("PrimaryBaseInfo && \"Did not find base info for non-virtual primary base!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1014, __extension__ __PRETTY_FUNCTION__))
1014 "Did not find base info for non-virtual primary base!")(static_cast <bool> (PrimaryBaseInfo && "Did not find base info for non-virtual primary base!"
) ? void (0) : __assert_fail ("PrimaryBaseInfo && \"Did not find base info for non-virtual primary base!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1014, __extension__ __PRETTY_FUNCTION__))
;
1015
1016 LayoutNonVirtualBase(PrimaryBaseInfo);
1017 }
1018
1019 // If this class needs a vtable/vf-table and didn't get one from a
1020 // primary base, add it in now.
1021 } else if (RD->isDynamicClass()) {
1022 assert(DataSize == 0 && "Vtable pointer must be at offset zero!")(static_cast <bool> (DataSize == 0 && "Vtable pointer must be at offset zero!"
) ? void (0) : __assert_fail ("DataSize == 0 && \"Vtable pointer must be at offset zero!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1022, __extension__ __PRETTY_FUNCTION__))
;
1023 CharUnits PtrWidth =
1024 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
1025 CharUnits PtrAlign =
1026 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0));
1027 EnsureVTablePointerAlignment(PtrAlign);
1028 HasOwnVFPtr = true;
1029 setSize(getSize() + PtrWidth);
1030 setDataSize(getSize());
1031 }
1032
1033 // Now lay out the non-virtual bases.
1034 for (const auto &I : RD->bases()) {
1035
1036 // Ignore virtual bases.
1037 if (I.isVirtual())
1038 continue;
1039
1040 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
1041
1042 // Skip the primary base, because we've already laid it out. The
1043 // !PrimaryBaseIsVirtual check is required because we might have a
1044 // non-virtual base of the same type as a primary virtual base.
1045 if (BaseDecl == PrimaryBase && !PrimaryBaseIsVirtual)
1046 continue;
1047
1048 // Lay out the base.
1049 BaseSubobjectInfo *BaseInfo = NonVirtualBaseInfo.lookup(BaseDecl);
1050 assert(BaseInfo && "Did not find base info for non-virtual base!")(static_cast <bool> (BaseInfo && "Did not find base info for non-virtual base!"
) ? void (0) : __assert_fail ("BaseInfo && \"Did not find base info for non-virtual base!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1050, __extension__ __PRETTY_FUNCTION__))
;
1051
1052 LayoutNonVirtualBase(BaseInfo);
1053 }
1054}
1055
1056void ItaniumRecordLayoutBuilder::LayoutNonVirtualBase(
1057 const BaseSubobjectInfo *Base) {
1058 // Layout the base.
1059 CharUnits Offset = LayoutBase(Base);
1060
1061 // Add its base class offset.
1062 assert(!Bases.count(Base->Class) && "base offset already exists!")(static_cast <bool> (!Bases.count(Base->Class) &&
"base offset already exists!") ? void (0) : __assert_fail ("!Bases.count(Base->Class) && \"base offset already exists!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1062, __extension__ __PRETTY_FUNCTION__))
;
1063 Bases.insert(std::make_pair(Base->Class, Offset));
1064
1065 AddPrimaryVirtualBaseOffsets(Base, Offset);
1066}
1067
1068void ItaniumRecordLayoutBuilder::AddPrimaryVirtualBaseOffsets(
1069 const BaseSubobjectInfo *Info, CharUnits Offset) {
1070 // This base isn't interesting, it has no virtual bases.
1071 if (!Info->Class->getNumVBases())
1072 return;
1073
1074 // First, check if we have a virtual primary base to add offsets for.
1075 if (Info->PrimaryVirtualBaseInfo) {
1076 assert(Info->PrimaryVirtualBaseInfo->IsVirtual &&(static_cast <bool> (Info->PrimaryVirtualBaseInfo->
IsVirtual && "Primary virtual base is not virtual!") ?
void (0) : __assert_fail ("Info->PrimaryVirtualBaseInfo->IsVirtual && \"Primary virtual base is not virtual!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1077, __extension__ __PRETTY_FUNCTION__))
1077 "Primary virtual base is not virtual!")(static_cast <bool> (Info->PrimaryVirtualBaseInfo->
IsVirtual && "Primary virtual base is not virtual!") ?
void (0) : __assert_fail ("Info->PrimaryVirtualBaseInfo->IsVirtual && \"Primary virtual base is not virtual!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1077, __extension__ __PRETTY_FUNCTION__))
;
1078 if (Info->PrimaryVirtualBaseInfo->Derived == Info) {
1079 // Add the offset.
1080 assert(!VBases.count(Info->PrimaryVirtualBaseInfo->Class) &&(static_cast <bool> (!VBases.count(Info->PrimaryVirtualBaseInfo
->Class) && "primary vbase offset already exists!"
) ? void (0) : __assert_fail ("!VBases.count(Info->PrimaryVirtualBaseInfo->Class) && \"primary vbase offset already exists!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1081, __extension__ __PRETTY_FUNCTION__))
1081 "primary vbase offset already exists!")(static_cast <bool> (!VBases.count(Info->PrimaryVirtualBaseInfo
->Class) && "primary vbase offset already exists!"
) ? void (0) : __assert_fail ("!VBases.count(Info->PrimaryVirtualBaseInfo->Class) && \"primary vbase offset already exists!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1081, __extension__ __PRETTY_FUNCTION__))
;
1082 VBases.insert(std::make_pair(Info->PrimaryVirtualBaseInfo->Class,
1083 ASTRecordLayout::VBaseInfo(Offset, false)));
1084
1085 // Traverse the primary virtual base.
1086 AddPrimaryVirtualBaseOffsets(Info->PrimaryVirtualBaseInfo, Offset);
1087 }
1088 }
1089
1090 // Now go through all direct non-virtual bases.
1091 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
1092 for (const BaseSubobjectInfo *Base : Info->Bases) {
1093 if (Base->IsVirtual)
1094 continue;
1095
1096 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
1097 AddPrimaryVirtualBaseOffsets(Base, BaseOffset);
1098 }
1099}
1100
1101void ItaniumRecordLayoutBuilder::LayoutVirtualBases(
1102 const CXXRecordDecl *RD, const CXXRecordDecl *MostDerivedClass) {
1103 const CXXRecordDecl *PrimaryBase;
1104 bool PrimaryBaseIsVirtual;
1105
1106 if (MostDerivedClass == RD) {
1107 PrimaryBase = this->PrimaryBase;
1108 PrimaryBaseIsVirtual = this->PrimaryBaseIsVirtual;
1109 } else {
1110 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1111 PrimaryBase = Layout.getPrimaryBase();
1112 PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
1113 }
1114
1115 for (const CXXBaseSpecifier &Base : RD->bases()) {
1116 assert(!Base.getType()->isDependentType() &&(static_cast <bool> (!Base.getType()->isDependentType
() && "Cannot layout class with dependent bases.") ? void
(0) : __assert_fail ("!Base.getType()->isDependentType() && \"Cannot layout class with dependent bases.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1117, __extension__ __PRETTY_FUNCTION__))
1117 "Cannot layout class with dependent bases.")(static_cast <bool> (!Base.getType()->isDependentType
() && "Cannot layout class with dependent bases.") ? void
(0) : __assert_fail ("!Base.getType()->isDependentType() && \"Cannot layout class with dependent bases.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1117, __extension__ __PRETTY_FUNCTION__))
;
1118
1119 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
1120
1121 if (Base.isVirtual()) {
1122 if (PrimaryBase != BaseDecl || !PrimaryBaseIsVirtual) {
1123 bool IndirectPrimaryBase = IndirectPrimaryBases.count(BaseDecl);
1124
1125 // Only lay out the virtual base if it's not an indirect primary base.
1126 if (!IndirectPrimaryBase) {
1127 // Only visit virtual bases once.
1128 if (!VisitedVirtualBases.insert(BaseDecl).second)
1129 continue;
1130
1131 const BaseSubobjectInfo *BaseInfo = VirtualBaseInfo.lookup(BaseDecl);
1132 assert(BaseInfo && "Did not find virtual base info!")(static_cast <bool> (BaseInfo && "Did not find virtual base info!"
) ? void (0) : __assert_fail ("BaseInfo && \"Did not find virtual base info!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1132, __extension__ __PRETTY_FUNCTION__))
;
1133 LayoutVirtualBase(BaseInfo);
1134 }
1135 }
1136 }
1137
1138 if (!BaseDecl->getNumVBases()) {
1139 // This base isn't interesting since it doesn't have any virtual bases.
1140 continue;
1141 }
1142
1143 LayoutVirtualBases(BaseDecl, MostDerivedClass);
1144 }
1145}
1146
1147void ItaniumRecordLayoutBuilder::LayoutVirtualBase(
1148 const BaseSubobjectInfo *Base) {
1149 assert(!Base->Derived && "Trying to lay out a primary virtual base!")(static_cast <bool> (!Base->Derived && "Trying to lay out a primary virtual base!"
) ? void (0) : __assert_fail ("!Base->Derived && \"Trying to lay out a primary virtual base!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1149, __extension__ __PRETTY_FUNCTION__))
;
1150
1151 // Layout the base.
1152 CharUnits Offset = LayoutBase(Base);
1153
1154 // Add its base class offset.
1155 assert(!VBases.count(Base->Class) && "vbase offset already exists!")(static_cast <bool> (!VBases.count(Base->Class) &&
"vbase offset already exists!") ? void (0) : __assert_fail (
"!VBases.count(Base->Class) && \"vbase offset already exists!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1155, __extension__ __PRETTY_FUNCTION__))
;
1156 VBases.insert(std::make_pair(Base->Class,
1157 ASTRecordLayout::VBaseInfo(Offset, false)));
1158
1159 AddPrimaryVirtualBaseOffsets(Base, Offset);
1160}
1161
1162CharUnits
1163ItaniumRecordLayoutBuilder::LayoutBase(const BaseSubobjectInfo *Base) {
1164 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base->Class);
1165
1166
1167 CharUnits Offset;
1168
1169 // Query the external layout to see if it provides an offset.
1170 bool HasExternalLayout = false;
1171 if (UseExternalLayout) {
1172 if (Base->IsVirtual)
1173 HasExternalLayout = External.getExternalNVBaseOffset(Base->Class, Offset);
1174 else
1175 HasExternalLayout = External.getExternalVBaseOffset(Base->Class, Offset);
1176 }
1177
1178 CharUnits UnpackedBaseAlign = Layout.getNonVirtualAlignment();
1179 CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
1180
1181 // If we have an empty base class, try to place it at offset 0.
1182 if (Base->Class->isEmpty() &&
1183 (!HasExternalLayout || Offset == CharUnits::Zero()) &&
1184 EmptySubobjects->CanPlaceBaseAtOffset(Base, CharUnits::Zero())) {
1185 setSize(std::max(getSize(), Layout.getSize()));
1186 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
1187
1188 return CharUnits::Zero();
1189 }
1190
1191 // The maximum field alignment overrides base align.
1192 if (!MaxFieldAlignment.isZero()) {
1193 BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
1194 UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
1195 }
1196
1197 if (!HasExternalLayout) {
1198 // Round up the current record size to the base's alignment boundary.
1199 Offset = getDataSize().alignTo(BaseAlign);
1200
1201 // Try to place the base.
1202 while (!EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset))
1203 Offset += BaseAlign;
1204 } else {
1205 bool Allowed = EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset);
1206 (void)Allowed;
1207 assert(Allowed && "Base subobject externally placed at overlapping offset")(static_cast <bool> (Allowed && "Base subobject externally placed at overlapping offset"
) ? void (0) : __assert_fail ("Allowed && \"Base subobject externally placed at overlapping offset\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1207, __extension__ __PRETTY_FUNCTION__))
;
1208
1209 if (InferAlignment && Offset < getDataSize().alignTo(BaseAlign)) {
1210 // The externally-supplied base offset is before the base offset we
1211 // computed. Assume that the structure is packed.
1212 Alignment = CharUnits::One();
1213 InferAlignment = false;
1214 }
1215 }
1216
1217 if (!Base->Class->isEmpty()) {
1218 // Update the data size.
1219 setDataSize(Offset + Layout.getNonVirtualSize());
1220
1221 setSize(std::max(getSize(), getDataSize()));
1222 } else
1223 setSize(std::max(getSize(), Offset + Layout.getSize()));
1224
1225 // Remember max struct/class alignment.
1226 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
1227
1228 return Offset;
1229}
1230
1231void ItaniumRecordLayoutBuilder::InitializeLayout(const Decl *D) {
1232 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
1233 IsUnion = RD->isUnion();
1234 IsMsStruct = RD->isMsStruct(Context);
1235 }
1236
1237 Packed = D->hasAttr<PackedAttr>();
1238
1239 // Honor the default struct packing maximum alignment flag.
1240 if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct) {
1241 MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
1242 }
1243
1244 // mac68k alignment supersedes maximum field alignment and attribute aligned,
1245 // and forces all structures to have 2-byte alignment. The IBM docs on it
1246 // allude to additional (more complicated) semantics, especially with regard
1247 // to bit-fields, but gcc appears not to follow that.
1248 if (D->hasAttr<AlignMac68kAttr>()) {
1249 IsMac68kAlign = true;
1250 MaxFieldAlignment = CharUnits::fromQuantity(2);
1251 Alignment = CharUnits::fromQuantity(2);
1252 } else {
1253 if (const MaxFieldAlignmentAttr *MFAA = D->getAttr<MaxFieldAlignmentAttr>())
1254 MaxFieldAlignment = Context.toCharUnitsFromBits(MFAA->getAlignment());
1255
1256 if (unsigned MaxAlign = D->getMaxAlignment())
1257 UpdateAlignment(Context.toCharUnitsFromBits(MaxAlign));
1258 }
1259
1260 // If there is an external AST source, ask it for the various offsets.
1261 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
1262 if (ExternalASTSource *Source = Context.getExternalSource()) {
1263 UseExternalLayout = Source->layoutRecordType(
1264 RD, External.Size, External.Align, External.FieldOffsets,
1265 External.BaseOffsets, External.VirtualBaseOffsets);
1266
1267 // Update based on external alignment.
1268 if (UseExternalLayout) {
1269 if (External.Align > 0) {
1270 Alignment = Context.toCharUnitsFromBits(External.Align);
1271 } else {
1272 // The external source didn't have alignment information; infer it.
1273 InferAlignment = true;
1274 }
1275 }
1276 }
1277}
1278
1279void ItaniumRecordLayoutBuilder::Layout(const RecordDecl *D) {
1280 InitializeLayout(D);
1281 LayoutFields(D);
1282
1283 // Finally, round the size of the total struct up to the alignment of the
1284 // struct itself.
1285 FinishLayout(D);
1286}
1287
1288void ItaniumRecordLayoutBuilder::Layout(const CXXRecordDecl *RD) {
1289 InitializeLayout(RD);
1290
1291 // Lay out the vtable and the non-virtual bases.
1292 LayoutNonVirtualBases(RD);
1293
1294 LayoutFields(RD);
1295
1296 NonVirtualSize = Context.toCharUnitsFromBits(
1297 llvm::alignTo(getSizeInBits(), Context.getTargetInfo().getCharAlign()));
1298 NonVirtualAlignment = Alignment;
1299
1300 // Lay out the virtual bases and add the primary virtual base offsets.
1301 LayoutVirtualBases(RD, RD);
1302
1303 // Finally, round the size of the total struct up to the alignment
1304 // of the struct itself.
1305 FinishLayout(RD);
1306
1307#ifndef NDEBUG
1308 // Check that we have base offsets for all bases.
1309 for (const CXXBaseSpecifier &Base : RD->bases()) {
1310 if (Base.isVirtual())
1311 continue;
1312
1313 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
1314
1315 assert(Bases.count(BaseDecl) && "Did not find base offset!")(static_cast <bool> (Bases.count(BaseDecl) && "Did not find base offset!"
) ? void (0) : __assert_fail ("Bases.count(BaseDecl) && \"Did not find base offset!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1315, __extension__ __PRETTY_FUNCTION__))
;
1316 }
1317
1318 // And all virtual bases.
1319 for (const CXXBaseSpecifier &Base : RD->vbases()) {
1320 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
1321
1322 assert(VBases.count(BaseDecl) && "Did not find base offset!")(static_cast <bool> (VBases.count(BaseDecl) && "Did not find base offset!"
) ? void (0) : __assert_fail ("VBases.count(BaseDecl) && \"Did not find base offset!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1322, __extension__ __PRETTY_FUNCTION__))
;
1323 }
1324#endif
1325}
1326
1327void ItaniumRecordLayoutBuilder::Layout(const ObjCInterfaceDecl *D) {
1328 if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
1329 const ASTRecordLayout &SL = Context.getASTObjCInterfaceLayout(SD);
1330
1331 UpdateAlignment(SL.getAlignment());
1332
1333 // We start laying out ivars not at the end of the superclass
1334 // structure, but at the next byte following the last field.
1335 setSize(SL.getDataSize());
1336 setDataSize(getSize());
1337 }
1338
1339 InitializeLayout(D);
1340 // Layout each ivar sequentially.
1341 for (const ObjCIvarDecl *IVD = D->all_declared_ivar_begin(); IVD;
1342 IVD = IVD->getNextIvar())
1343 LayoutField(IVD, false);
1344
1345 // Finally, round the size of the total struct up to the alignment of the
1346 // struct itself.
1347 FinishLayout(D);
1348}
1349
1350void ItaniumRecordLayoutBuilder::LayoutFields(const RecordDecl *D) {
1351 // Layout each field, for now, just sequentially, respecting alignment. In
1352 // the future, this will need to be tweakable by targets.
1353 bool InsertExtraPadding = D->mayInsertExtraPadding(/*EmitRemark=*/true);
1354 bool HasFlexibleArrayMember = D->hasFlexibleArrayMember();
1355 for (auto I = D->field_begin(), End = D->field_end(); I != End; ++I) {
1356 auto Next(I);
1357 ++Next;
1358 LayoutField(*I,
1359 InsertExtraPadding && (Next != End || !HasFlexibleArrayMember));
1360 }
1361}
1362
1363// Rounds the specified size to have it a multiple of the char size.
1364static uint64_t
1365roundUpSizeToCharAlignment(uint64_t Size,
1366 const ASTContext &Context) {
1367 uint64_t CharAlignment = Context.getTargetInfo().getCharAlign();
1368 return llvm::alignTo(Size, CharAlignment);
1369}
1370
1371void ItaniumRecordLayoutBuilder::LayoutWideBitField(uint64_t FieldSize,
1372 uint64_t TypeSize,
1373 bool FieldPacked,
1374 const FieldDecl *D) {
1375 assert(Context.getLangOpts().CPlusPlus &&(static_cast <bool> (Context.getLangOpts().CPlusPlus &&
"Can only have wide bit-fields in C++!") ? void (0) : __assert_fail
("Context.getLangOpts().CPlusPlus && \"Can only have wide bit-fields in C++!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1376, __extension__ __PRETTY_FUNCTION__))
1376 "Can only have wide bit-fields in C++!")(static_cast <bool> (Context.getLangOpts().CPlusPlus &&
"Can only have wide bit-fields in C++!") ? void (0) : __assert_fail
("Context.getLangOpts().CPlusPlus && \"Can only have wide bit-fields in C++!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1376, __extension__ __PRETTY_FUNCTION__))
;
1377
1378 // Itanium C++ ABI 2.4:
1379 // If sizeof(T)*8 < n, let T' be the largest integral POD type with
1380 // sizeof(T')*8 <= n.
1381
1382 QualType IntegralPODTypes[] = {
1383 Context.UnsignedCharTy, Context.UnsignedShortTy, Context.UnsignedIntTy,
1384 Context.UnsignedLongTy, Context.UnsignedLongLongTy
1385 };
1386
1387 QualType Type;
1388 for (const QualType &QT : IntegralPODTypes) {
1389 uint64_t Size = Context.getTypeSize(QT);
1390
1391 if (Size > FieldSize)
1392 break;
1393
1394 Type = QT;
1395 }
1396 assert(!Type.isNull() && "Did not find a type!")(static_cast <bool> (!Type.isNull() && "Did not find a type!"
) ? void (0) : __assert_fail ("!Type.isNull() && \"Did not find a type!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1396, __extension__ __PRETTY_FUNCTION__))
;
1397
1398 CharUnits TypeAlign = Context.getTypeAlignInChars(Type);
1399
1400 // We're not going to use any of the unfilled bits in the last byte.
1401 UnfilledBitsInLastUnit = 0;
1402 LastBitfieldTypeSize = 0;
1403
1404 uint64_t FieldOffset;
1405 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
1406
1407 if (IsUnion) {
1408 uint64_t RoundedFieldSize = roundUpSizeToCharAlignment(FieldSize,
1409 Context);
1410 setDataSize(std::max(getDataSizeInBits(), RoundedFieldSize));
1411 FieldOffset = 0;
1412 } else {
1413 // The bitfield is allocated starting at the next offset aligned
1414 // appropriately for T', with length n bits.
1415 FieldOffset = llvm::alignTo(getDataSizeInBits(), Context.toBits(TypeAlign));
1416
1417 uint64_t NewSizeInBits = FieldOffset + FieldSize;
1418
1419 setDataSize(
1420 llvm::alignTo(NewSizeInBits, Context.getTargetInfo().getCharAlign()));
1421 UnfilledBitsInLastUnit = getDataSizeInBits() - NewSizeInBits;
1422 }
1423
1424 // Place this field at the current location.
1425 FieldOffsets.push_back(FieldOffset);
1426
1427 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, FieldOffset,
1428 Context.toBits(TypeAlign), FieldPacked, D);
1429
1430 // Update the size.
1431 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1432
1433 // Remember max struct/class alignment.
1434 UpdateAlignment(TypeAlign);
1435}
1436
1437void ItaniumRecordLayoutBuilder::LayoutBitField(const FieldDecl *D) {
1438 bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
1439 uint64_t FieldSize = D->getBitWidthValue(Context);
1440 TypeInfo FieldInfo = Context.getTypeInfo(D->getType());
1441 uint64_t TypeSize = FieldInfo.Width;
1442 unsigned FieldAlign = FieldInfo.Align;
1443
1444 // UnfilledBitsInLastUnit is the difference between the end of the
1445 // last allocated bitfield (i.e. the first bit offset available for
1446 // bitfields) and the end of the current data size in bits (i.e. the
1447 // first bit offset available for non-bitfields). The current data
1448 // size in bits is always a multiple of the char size; additionally,
1449 // for ms_struct records it's also a multiple of the
1450 // LastBitfieldTypeSize (if set).
1451
1452 // The struct-layout algorithm is dictated by the platform ABI,
1453 // which in principle could use almost any rules it likes. In
1454 // practice, UNIXy targets tend to inherit the algorithm described
1455 // in the System V generic ABI. The basic bitfield layout rule in
1456 // System V is to place bitfields at the next available bit offset
1457 // where the entire bitfield would fit in an aligned storage unit of
1458 // the declared type; it's okay if an earlier or later non-bitfield
1459 // is allocated in the same storage unit. However, some targets
1460 // (those that !useBitFieldTypeAlignment(), e.g. ARM APCS) don't
1461 // require this storage unit to be aligned, and therefore always put
1462 // the bitfield at the next available bit offset.
1463
1464 // ms_struct basically requests a complete replacement of the
1465 // platform ABI's struct-layout algorithm, with the high-level goal
1466 // of duplicating MSVC's layout. For non-bitfields, this follows
1467 // the standard algorithm. The basic bitfield layout rule is to
1468 // allocate an entire unit of the bitfield's declared type
1469 // (e.g. 'unsigned long'), then parcel it up among successive
1470 // bitfields whose declared types have the same size, making a new
1471 // unit as soon as the last can no longer store the whole value.
1472 // Since it completely replaces the platform ABI's algorithm,
1473 // settings like !useBitFieldTypeAlignment() do not apply.
1474
1475 // A zero-width bitfield forces the use of a new storage unit for
1476 // later bitfields. In general, this occurs by rounding up the
1477 // current size of the struct as if the algorithm were about to
1478 // place a non-bitfield of the field's formal type. Usually this
1479 // does not change the alignment of the struct itself, but it does
1480 // on some targets (those that useZeroLengthBitfieldAlignment(),
1481 // e.g. ARM). In ms_struct layout, zero-width bitfields are
1482 // ignored unless they follow a non-zero-width bitfield.
1483
1484 // A field alignment restriction (e.g. from #pragma pack) or
1485 // specification (e.g. from __attribute__((aligned))) changes the
1486 // formal alignment of the field. For System V, this alters the
1487 // required alignment of the notional storage unit that must contain
1488 // the bitfield. For ms_struct, this only affects the placement of
1489 // new storage units. In both cases, the effect of #pragma pack is
1490 // ignored on zero-width bitfields.
1491
1492 // On System V, a packed field (e.g. from #pragma pack or
1493 // __attribute__((packed))) always uses the next available bit
1494 // offset.
1495
1496 // In an ms_struct struct, the alignment of a fundamental type is
1497 // always equal to its size. This is necessary in order to mimic
1498 // the i386 alignment rules on targets which might not fully align
1499 // all types (e.g. Darwin PPC32, where alignof(long long) == 4).
1500
1501 // First, some simple bookkeeping to perform for ms_struct structs.
1502 if (IsMsStruct) {
1503 // The field alignment for integer types is always the size.
1504 FieldAlign = TypeSize;
1505
1506 // If the previous field was not a bitfield, or was a bitfield
1507 // with a different storage unit size, or if this field doesn't fit into
1508 // the current storage unit, we're done with that storage unit.
1509 if (LastBitfieldTypeSize != TypeSize ||
1510 UnfilledBitsInLastUnit < FieldSize) {
1511 // Also, ignore zero-length bitfields after non-bitfields.
1512 if (!LastBitfieldTypeSize && !FieldSize)
1513 FieldAlign = 1;
1514
1515 UnfilledBitsInLastUnit = 0;
1516 LastBitfieldTypeSize = 0;
1517 }
1518 }
1519
1520 // If the field is wider than its declared type, it follows
1521 // different rules in all cases.
1522 if (FieldSize > TypeSize) {
1523 LayoutWideBitField(FieldSize, TypeSize, FieldPacked, D);
1524 return;
1525 }
1526
1527 // Compute the next available bit offset.
1528 uint64_t FieldOffset =
1529 IsUnion ? 0 : (getDataSizeInBits() - UnfilledBitsInLastUnit);
1530
1531 // Handle targets that don't honor bitfield type alignment.
1532 if (!IsMsStruct && !Context.getTargetInfo().useBitFieldTypeAlignment()) {
1533 // Some such targets do honor it on zero-width bitfields.
1534 if (FieldSize == 0 &&
1535 Context.getTargetInfo().useZeroLengthBitfieldAlignment()) {
1536 // The alignment to round up to is the max of the field's natural
1537 // alignment and a target-specific fixed value (sometimes zero).
1538 unsigned ZeroLengthBitfieldBoundary =
1539 Context.getTargetInfo().getZeroLengthBitfieldBoundary();
1540 FieldAlign = std::max(FieldAlign, ZeroLengthBitfieldBoundary);
1541
1542 // If that doesn't apply, just ignore the field alignment.
1543 } else {
1544 FieldAlign = 1;
1545 }
1546 }
1547
1548 // Remember the alignment we would have used if the field were not packed.
1549 unsigned UnpackedFieldAlign = FieldAlign;
1550
1551 // Ignore the field alignment if the field is packed unless it has zero-size.
1552 if (!IsMsStruct && FieldPacked && FieldSize != 0)
1553 FieldAlign = 1;
1554
1555 // But, if there's an 'aligned' attribute on the field, honor that.
1556 unsigned ExplicitFieldAlign = D->getMaxAlignment();
1557 if (ExplicitFieldAlign) {
1558 FieldAlign = std::max(FieldAlign, ExplicitFieldAlign);
1559 UnpackedFieldAlign = std::max(UnpackedFieldAlign, ExplicitFieldAlign);
1560 }
1561
1562 // But, if there's a #pragma pack in play, that takes precedent over
1563 // even the 'aligned' attribute, for non-zero-width bitfields.
1564 unsigned MaxFieldAlignmentInBits = Context.toBits(MaxFieldAlignment);
1565 if (!MaxFieldAlignment.isZero() && FieldSize) {
1566 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignmentInBits);
1567 if (FieldPacked)
1568 FieldAlign = UnpackedFieldAlign;
1569 else
1570 FieldAlign = std::min(FieldAlign, MaxFieldAlignmentInBits);
1571 }
1572
1573 // But, ms_struct just ignores all of that in unions, even explicit
1574 // alignment attributes.
1575 if (IsMsStruct && IsUnion) {
1576 FieldAlign = UnpackedFieldAlign = 1;
1577 }
1578
1579 // For purposes of diagnostics, we're going to simultaneously
1580 // compute the field offsets that we would have used if we weren't
1581 // adding any alignment padding or if the field weren't packed.
1582 uint64_t UnpaddedFieldOffset = FieldOffset;
1583 uint64_t UnpackedFieldOffset = FieldOffset;
1584
1585 // Check if we need to add padding to fit the bitfield within an
1586 // allocation unit with the right size and alignment. The rules are
1587 // somewhat different here for ms_struct structs.
1588 if (IsMsStruct) {
1589 // If it's not a zero-width bitfield, and we can fit the bitfield
1590 // into the active storage unit (and we haven't already decided to
1591 // start a new storage unit), just do so, regardless of any other
1592 // other consideration. Otherwise, round up to the right alignment.
1593 if (FieldSize == 0 || FieldSize > UnfilledBitsInLastUnit) {
1594 FieldOffset = llvm::alignTo(FieldOffset, FieldAlign);
1595 UnpackedFieldOffset =
1596 llvm::alignTo(UnpackedFieldOffset, UnpackedFieldAlign);
1597 UnfilledBitsInLastUnit = 0;
1598 }
1599
1600 } else {
1601 // #pragma pack, with any value, suppresses the insertion of padding.
1602 bool AllowPadding = MaxFieldAlignment.isZero();
1603
1604 // Compute the real offset.
1605 if (FieldSize == 0 ||
1606 (AllowPadding &&
1607 (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize)) {
1608 FieldOffset = llvm::alignTo(FieldOffset, FieldAlign);
1609 } else if (ExplicitFieldAlign &&
1610 (MaxFieldAlignmentInBits == 0 ||
1611 ExplicitFieldAlign <= MaxFieldAlignmentInBits) &&
1612 Context.getTargetInfo().useExplicitBitFieldAlignment()) {
1613 // TODO: figure it out what needs to be done on targets that don't honor
1614 // bit-field type alignment like ARM APCS ABI.
1615 FieldOffset = llvm::alignTo(FieldOffset, ExplicitFieldAlign);
1616 }
1617
1618 // Repeat the computation for diagnostic purposes.
1619 if (FieldSize == 0 ||
1620 (AllowPadding &&
1621 (UnpackedFieldOffset & (UnpackedFieldAlign-1)) + FieldSize > TypeSize))
1622 UnpackedFieldOffset =
1623 llvm::alignTo(UnpackedFieldOffset, UnpackedFieldAlign);
1624 else if (ExplicitFieldAlign &&
1625 (MaxFieldAlignmentInBits == 0 ||
1626 ExplicitFieldAlign <= MaxFieldAlignmentInBits) &&
1627 Context.getTargetInfo().useExplicitBitFieldAlignment())
1628 UnpackedFieldOffset =
1629 llvm::alignTo(UnpackedFieldOffset, ExplicitFieldAlign);
1630 }
1631
1632 // If we're using external layout, give the external layout a chance
1633 // to override this information.
1634 if (UseExternalLayout)
1635 FieldOffset = updateExternalFieldOffset(D, FieldOffset);
1636
1637 // Okay, place the bitfield at the calculated offset.
1638 FieldOffsets.push_back(FieldOffset);
1639
1640 // Bookkeeping:
1641
1642 // Anonymous members don't affect the overall record alignment,
1643 // except on targets where they do.
1644 if (!IsMsStruct &&
1645 !Context.getTargetInfo().useZeroLengthBitfieldAlignment() &&
1646 !D->getIdentifier())
1647 FieldAlign = UnpackedFieldAlign = 1;
1648
1649 // Diagnose differences in layout due to padding or packing.
1650 if (!UseExternalLayout)
1651 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, UnpackedFieldOffset,
1652 UnpackedFieldAlign, FieldPacked, D);
1653
1654 // Update DataSize to include the last byte containing (part of) the bitfield.
1655
1656 // For unions, this is just a max operation, as usual.
1657 if (IsUnion) {
1658 // For ms_struct, allocate the entire storage unit --- unless this
1659 // is a zero-width bitfield, in which case just use a size of 1.
1660 uint64_t RoundedFieldSize;
1661 if (IsMsStruct) {
1662 RoundedFieldSize =
1663 (FieldSize ? TypeSize : Context.getTargetInfo().getCharWidth());
1664
1665 // Otherwise, allocate just the number of bytes required to store
1666 // the bitfield.
1667 } else {
1668 RoundedFieldSize = roundUpSizeToCharAlignment(FieldSize, Context);
1669 }
1670 setDataSize(std::max(getDataSizeInBits(), RoundedFieldSize));
1671
1672 // For non-zero-width bitfields in ms_struct structs, allocate a new
1673 // storage unit if necessary.
1674 } else if (IsMsStruct && FieldSize) {
1675 // We should have cleared UnfilledBitsInLastUnit in every case
1676 // where we changed storage units.
1677 if (!UnfilledBitsInLastUnit) {
1678 setDataSize(FieldOffset + TypeSize);
1679 UnfilledBitsInLastUnit = TypeSize;
1680 }
1681 UnfilledBitsInLastUnit -= FieldSize;
1682 LastBitfieldTypeSize = TypeSize;
1683
1684 // Otherwise, bump the data size up to include the bitfield,
1685 // including padding up to char alignment, and then remember how
1686 // bits we didn't use.
1687 } else {
1688 uint64_t NewSizeInBits = FieldOffset + FieldSize;
1689 uint64_t CharAlignment = Context.getTargetInfo().getCharAlign();
1690 setDataSize(llvm::alignTo(NewSizeInBits, CharAlignment));
1691 UnfilledBitsInLastUnit = getDataSizeInBits() - NewSizeInBits;
1692
1693 // The only time we can get here for an ms_struct is if this is a
1694 // zero-width bitfield, which doesn't count as anything for the
1695 // purposes of unfilled bits.
1696 LastBitfieldTypeSize = 0;
1697 }
1698
1699 // Update the size.
1700 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1701
1702 // Remember max struct/class alignment.
1703 UpdateAlignment(Context.toCharUnitsFromBits(FieldAlign),
1704 Context.toCharUnitsFromBits(UnpackedFieldAlign));
1705}
1706
1707void ItaniumRecordLayoutBuilder::LayoutField(const FieldDecl *D,
1708 bool InsertExtraPadding) {
1709 if (D->isBitField()) {
1710 LayoutBitField(D);
1711 return;
1712 }
1713
1714 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
1715
1716 // Reset the unfilled bits.
1717 UnfilledBitsInLastUnit = 0;
1718 LastBitfieldTypeSize = 0;
1719
1720 bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
1721 CharUnits FieldOffset =
1722 IsUnion ? CharUnits::Zero() : getDataSize();
1723 CharUnits FieldSize;
1724 CharUnits FieldAlign;
1725
1726 if (D->getType()->isIncompleteArrayType()) {
1727 // This is a flexible array member; we can't directly
1728 // query getTypeInfo about these, so we figure it out here.
1729 // Flexible array members don't have any size, but they
1730 // have to be aligned appropriately for their element type.
1731 FieldSize = CharUnits::Zero();
1732 const ArrayType* ATy = Context.getAsArrayType(D->getType());
1733 FieldAlign = Context.getTypeAlignInChars(ATy->getElementType());
1734 } else if (const ReferenceType *RT = D->getType()->getAs<ReferenceType>()) {
1735 unsigned AS = Context.getTargetAddressSpace(RT->getPointeeType());
1736 FieldSize =
1737 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(AS));
1738 FieldAlign =
1739 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(AS));
1740 } else {
1741 std::pair<CharUnits, CharUnits> FieldInfo =
1742 Context.getTypeInfoInChars(D->getType());
1743 FieldSize = FieldInfo.first;
1744 FieldAlign = FieldInfo.second;
1745
1746 if (IsMsStruct) {
1747 // If MS bitfield layout is required, figure out what type is being
1748 // laid out and align the field to the width of that type.
1749
1750 // Resolve all typedefs down to their base type and round up the field
1751 // alignment if necessary.
1752 QualType T = Context.getBaseElementType(D->getType());
1753 if (const BuiltinType *BTy = T->getAs<BuiltinType>()) {
1754 CharUnits TypeSize = Context.getTypeSizeInChars(BTy);
1755 if (TypeSize > FieldAlign)
1756 FieldAlign = TypeSize;
1757 }
1758 }
1759 }
1760
1761 // The align if the field is not packed. This is to check if the attribute
1762 // was unnecessary (-Wpacked).
1763 CharUnits UnpackedFieldAlign = FieldAlign;
1764 CharUnits UnpackedFieldOffset = FieldOffset;
1765
1766 if (FieldPacked)
1767 FieldAlign = CharUnits::One();
1768 CharUnits MaxAlignmentInChars =
1769 Context.toCharUnitsFromBits(D->getMaxAlignment());
1770 FieldAlign = std::max(FieldAlign, MaxAlignmentInChars);
1771 UnpackedFieldAlign = std::max(UnpackedFieldAlign, MaxAlignmentInChars);
1772
1773 // The maximum field alignment overrides the aligned attribute.
1774 if (!MaxFieldAlignment.isZero()) {
1775 FieldAlign = std::min(FieldAlign, MaxFieldAlignment);
1776 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignment);
1777 }
1778
1779 // Round up the current record size to the field's alignment boundary.
1780 FieldOffset = FieldOffset.alignTo(FieldAlign);
1781 UnpackedFieldOffset = UnpackedFieldOffset.alignTo(UnpackedFieldAlign);
1782
1783 if (UseExternalLayout) {
1784 FieldOffset = Context.toCharUnitsFromBits(
1785 updateExternalFieldOffset(D, Context.toBits(FieldOffset)));
1786
1787 if (!IsUnion && EmptySubobjects) {
1788 // Record the fact that we're placing a field at this offset.
1789 bool Allowed = EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset);
1790 (void)Allowed;
1791 assert(Allowed && "Externally-placed field cannot be placed here")(static_cast <bool> (Allowed && "Externally-placed field cannot be placed here"
) ? void (0) : __assert_fail ("Allowed && \"Externally-placed field cannot be placed here\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1791, __extension__ __PRETTY_FUNCTION__))
;
1792 }
1793 } else {
1794 if (!IsUnion && EmptySubobjects) {
1795 // Check if we can place the field at this offset.
1796 while (!EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset)) {
1797 // We couldn't place the field at the offset. Try again at a new offset.
1798 FieldOffset += FieldAlign;
1799 }
1800 }
1801 }
1802
1803 // Place this field at the current location.
1804 FieldOffsets.push_back(Context.toBits(FieldOffset));
1805
1806 if (!UseExternalLayout)
1807 CheckFieldPadding(Context.toBits(FieldOffset), UnpaddedFieldOffset,
1808 Context.toBits(UnpackedFieldOffset),
1809 Context.toBits(UnpackedFieldAlign), FieldPacked, D);
1810
1811 if (InsertExtraPadding) {
1812 CharUnits ASanAlignment = CharUnits::fromQuantity(8);
1813 CharUnits ExtraSizeForAsan = ASanAlignment;
1814 if (FieldSize % ASanAlignment)
1815 ExtraSizeForAsan +=
1816 ASanAlignment - CharUnits::fromQuantity(FieldSize % ASanAlignment);
1817 FieldSize += ExtraSizeForAsan;
1818 }
1819
1820 // Reserve space for this field.
1821 uint64_t FieldSizeInBits = Context.toBits(FieldSize);
1822 if (IsUnion)
1823 setDataSize(std::max(getDataSizeInBits(), FieldSizeInBits));
1824 else
1825 setDataSize(FieldOffset + FieldSize);
1826
1827 // Update the size.
1828 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1829
1830 // Remember max struct/class alignment.
1831 UpdateAlignment(FieldAlign, UnpackedFieldAlign);
1832}
1833
1834void ItaniumRecordLayoutBuilder::FinishLayout(const NamedDecl *D) {
1835 // In C++, records cannot be of size 0.
1836 if (Context.getLangOpts().CPlusPlus && getSizeInBits() == 0) {
1837 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
1838 // Compatibility with gcc requires a class (pod or non-pod)
1839 // which is not empty but of size 0; such as having fields of
1840 // array of zero-length, remains of Size 0
1841 if (RD->isEmpty())
1842 setSize(CharUnits::One());
1843 }
1844 else
1845 setSize(CharUnits::One());
1846 }
1847
1848 // Finally, round the size of the record up to the alignment of the
1849 // record itself.
1850 uint64_t UnpaddedSize = getSizeInBits() - UnfilledBitsInLastUnit;
1851 uint64_t UnpackedSizeInBits =
1852 llvm::alignTo(getSizeInBits(), Context.toBits(UnpackedAlignment));
1853 uint64_t RoundedSize =
1854 llvm::alignTo(getSizeInBits(), Context.toBits(Alignment));
1855
1856 if (UseExternalLayout) {
1857 // If we're inferring alignment, and the external size is smaller than
1858 // our size after we've rounded up to alignment, conservatively set the
1859 // alignment to 1.
1860 if (InferAlignment && External.Size < RoundedSize) {
1861 Alignment = CharUnits::One();
1862 InferAlignment = false;
1863 }
1864 setSize(External.Size);
1865 return;
1866 }
1867
1868 // Set the size to the final size.
1869 setSize(RoundedSize);
1870
1871 unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
1872 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
1873 // Warn if padding was introduced to the struct/class/union.
1874 if (getSizeInBits() > UnpaddedSize) {
1875 unsigned PadSize = getSizeInBits() - UnpaddedSize;
1876 bool InBits = true;
1877 if (PadSize % CharBitNum == 0) {
1878 PadSize = PadSize / CharBitNum;
1879 InBits = false;
1880 }
1881 Diag(RD->getLocation(), diag::warn_padded_struct_size)
1882 << Context.getTypeDeclType(RD)
1883 << PadSize
1884 << (InBits ? 1 : 0); // (byte|bit)
1885 }
1886
1887 // Warn if we packed it unnecessarily, when the unpacked alignment is not
1888 // greater than the one after packing, the size in bits doesn't change and
1889 // the offset of each field is identical.
1890 if (Packed && UnpackedAlignment <= Alignment &&
1891 UnpackedSizeInBits == getSizeInBits() && !HasPackedField)
1892 Diag(D->getLocation(), diag::warn_unnecessary_packed)
1893 << Context.getTypeDeclType(RD);
1894 }
1895}
1896
1897void ItaniumRecordLayoutBuilder::UpdateAlignment(
1898 CharUnits NewAlignment, CharUnits UnpackedNewAlignment) {
1899 // The alignment is not modified when using 'mac68k' alignment or when
1900 // we have an externally-supplied layout that also provides overall alignment.
1901 if (IsMac68kAlign || (UseExternalLayout && !InferAlignment))
1902 return;
1903
1904 if (NewAlignment > Alignment) {
1905 assert(llvm::isPowerOf2_64(NewAlignment.getQuantity()) &&(static_cast <bool> (llvm::isPowerOf2_64(NewAlignment.getQuantity
()) && "Alignment not a power of 2") ? void (0) : __assert_fail
("llvm::isPowerOf2_64(NewAlignment.getQuantity()) && \"Alignment not a power of 2\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1906, __extension__ __PRETTY_FUNCTION__))
1906 "Alignment not a power of 2")(static_cast <bool> (llvm::isPowerOf2_64(NewAlignment.getQuantity
()) && "Alignment not a power of 2") ? void (0) : __assert_fail
("llvm::isPowerOf2_64(NewAlignment.getQuantity()) && \"Alignment not a power of 2\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1906, __extension__ __PRETTY_FUNCTION__))
;
1907 Alignment = NewAlignment;
1908 }
1909
1910 if (UnpackedNewAlignment > UnpackedAlignment) {
1911 assert(llvm::isPowerOf2_64(UnpackedNewAlignment.getQuantity()) &&(static_cast <bool> (llvm::isPowerOf2_64(UnpackedNewAlignment
.getQuantity()) && "Alignment not a power of 2") ? void
(0) : __assert_fail ("llvm::isPowerOf2_64(UnpackedNewAlignment.getQuantity()) && \"Alignment not a power of 2\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1912, __extension__ __PRETTY_FUNCTION__))
1912 "Alignment not a power of 2")(static_cast <bool> (llvm::isPowerOf2_64(UnpackedNewAlignment
.getQuantity()) && "Alignment not a power of 2") ? void
(0) : __assert_fail ("llvm::isPowerOf2_64(UnpackedNewAlignment.getQuantity()) && \"Alignment not a power of 2\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1912, __extension__ __PRETTY_FUNCTION__))
;
1913 UnpackedAlignment = UnpackedNewAlignment;
1914 }
1915}
1916
1917uint64_t
1918ItaniumRecordLayoutBuilder::updateExternalFieldOffset(const FieldDecl *Field,
1919 uint64_t ComputedOffset) {
1920 uint64_t ExternalFieldOffset = External.getExternalFieldOffset(Field);
1921
1922 if (InferAlignment && ExternalFieldOffset < ComputedOffset) {
1923 // The externally-supplied field offset is before the field offset we
1924 // computed. Assume that the structure is packed.
1925 Alignment = CharUnits::One();
1926 InferAlignment = false;
1927 }
1928
1929 // Use the externally-supplied field offset.
1930 return ExternalFieldOffset;
1931}
1932
1933/// \brief Get diagnostic %select index for tag kind for
1934/// field padding diagnostic message.
1935/// WARNING: Indexes apply to particular diagnostics only!
1936///
1937/// \returns diagnostic %select index.
1938static unsigned getPaddingDiagFromTagKind(TagTypeKind Tag) {
1939 switch (Tag) {
1940 case TTK_Struct: return 0;
1941 case TTK_Interface: return 1;
1942 case TTK_Class: return 2;
1943 default: llvm_unreachable("Invalid tag kind for field padding diagnostic!")::llvm::llvm_unreachable_internal("Invalid tag kind for field padding diagnostic!"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1943)
;
1944 }
1945}
1946
1947void ItaniumRecordLayoutBuilder::CheckFieldPadding(
1948 uint64_t Offset, uint64_t UnpaddedOffset, uint64_t UnpackedOffset,
1949 unsigned UnpackedAlign, bool isPacked, const FieldDecl *D) {
1950 // We let objc ivars without warning, objc interfaces generally are not used
1951 // for padding tricks.
1952 if (isa<ObjCIvarDecl>(D))
1953 return;
1954
1955 // Don't warn about structs created without a SourceLocation. This can
1956 // be done by clients of the AST, such as codegen.
1957 if (D->getLocation().isInvalid())
1958 return;
1959
1960 unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
1961
1962 // Warn if padding was introduced to the struct/class.
1963 if (!IsUnion && Offset > UnpaddedOffset) {
1964 unsigned PadSize = Offset - UnpaddedOffset;
1965 bool InBits = true;
1966 if (PadSize % CharBitNum == 0) {
1967 PadSize = PadSize / CharBitNum;
1968 InBits = false;
1969 }
1970 if (D->getIdentifier())
1971 Diag(D->getLocation(), diag::warn_padded_struct_field)
1972 << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
1973 << Context.getTypeDeclType(D->getParent())
1974 << PadSize
1975 << (InBits ? 1 : 0) // (byte|bit)
1976 << D->getIdentifier();
1977 else
1978 Diag(D->getLocation(), diag::warn_padded_struct_anon_field)
1979 << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
1980 << Context.getTypeDeclType(D->getParent())
1981 << PadSize
1982 << (InBits ? 1 : 0); // (byte|bit)
1983 }
1984 if (isPacked && Offset != UnpackedOffset) {
1985 HasPackedField = true;
1986 }
1987}
1988
1989static const CXXMethodDecl *computeKeyFunction(ASTContext &Context,
1990 const CXXRecordDecl *RD) {
1991 // If a class isn't polymorphic it doesn't have a key function.
1992 if (!RD->isPolymorphic())
1993 return nullptr;
1994
1995 // A class that is not externally visible doesn't have a key function. (Or
1996 // at least, there's no point to assigning a key function to such a class;
1997 // this doesn't affect the ABI.)
1998 if (!RD->isExternallyVisible())
1999 return nullptr;
2000
2001 // Template instantiations don't have key functions per Itanium C++ ABI 5.2.6.
2002 // Same behavior as GCC.
2003 TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
2004 if (TSK == TSK_ImplicitInstantiation ||
2005 TSK == TSK_ExplicitInstantiationDeclaration ||
2006 TSK == TSK_ExplicitInstantiationDefinition)
2007 return nullptr;
2008
2009 bool allowInlineFunctions =
2010 Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline();
2011
2012 for (const CXXMethodDecl *MD : RD->methods()) {
2013 if (!MD->isVirtual())
2014 continue;
2015
2016 if (MD->isPure())
2017 continue;
2018
2019 // Ignore implicit member functions, they are always marked as inline, but
2020 // they don't have a body until they're defined.
2021 if (MD->isImplicit())
2022 continue;
2023
2024 if (MD->isInlineSpecified())
2025 continue;
2026
2027 if (MD->hasInlineBody())
2028 continue;
2029
2030 // Ignore inline deleted or defaulted functions.
2031 if (!MD->isUserProvided())
2032 continue;
2033
2034 // In certain ABIs, ignore functions with out-of-line inline definitions.
2035 if (!allowInlineFunctions) {
2036 const FunctionDecl *Def;
2037 if (MD->hasBody(Def) && Def->isInlineSpecified())
2038 continue;
2039 }
2040
2041 if (Context.getLangOpts().CUDA) {
2042 // While compiler may see key method in this TU, during CUDA
2043 // compilation we should ignore methods that are not accessible
2044 // on this side of compilation.
2045 if (Context.getLangOpts().CUDAIsDevice) {
2046 // In device mode ignore methods without __device__ attribute.
2047 if (!MD->hasAttr<CUDADeviceAttr>())
2048 continue;
2049 } else {
2050 // In host mode ignore __device__-only methods.
2051 if (!MD->hasAttr<CUDAHostAttr>() && MD->hasAttr<CUDADeviceAttr>())
2052 continue;
2053 }
2054 }
2055
2056 // If the key function is dllimport but the class isn't, then the class has
2057 // no key function. The DLL that exports the key function won't export the
2058 // vtable in this case.
2059 if (MD->hasAttr<DLLImportAttr>() && !RD->hasAttr<DLLImportAttr>())
2060 return nullptr;
2061
2062 // We found it.
2063 return MD;
2064 }
2065
2066 return nullptr;
2067}
2068
2069DiagnosticBuilder ItaniumRecordLayoutBuilder::Diag(SourceLocation Loc,
2070 unsigned DiagID) {
2071 return Context.getDiagnostics().Report(Loc, DiagID);
2072}
2073
2074/// Does the target C++ ABI require us to skip over the tail-padding
2075/// of the given class (considering it as a base class) when allocating
2076/// objects?
2077static bool mustSkipTailPadding(TargetCXXABI ABI, const CXXRecordDecl *RD) {
2078 switch (ABI.getTailPaddingUseRules()) {
2079 case TargetCXXABI::AlwaysUseTailPadding:
2080 return false;
2081
2082 case TargetCXXABI::UseTailPaddingUnlessPOD03:
2083 // FIXME: To the extent that this is meant to cover the Itanium ABI
2084 // rules, we should implement the restrictions about over-sized
2085 // bitfields:
2086 //
2087 // http://itanium-cxx-abi.github.io/cxx-abi/abi.html#POD :
2088 // In general, a type is considered a POD for the purposes of
2089 // layout if it is a POD type (in the sense of ISO C++
2090 // [basic.types]). However, a POD-struct or POD-union (in the
2091 // sense of ISO C++ [class]) with a bitfield member whose
2092 // declared width is wider than the declared type of the
2093 // bitfield is not a POD for the purpose of layout. Similarly,
2094 // an array type is not a POD for the purpose of layout if the
2095 // element type of the array is not a POD for the purpose of
2096 // layout.
2097 //
2098 // Where references to the ISO C++ are made in this paragraph,
2099 // the Technical Corrigendum 1 version of the standard is
2100 // intended.
2101 return RD->isPOD();
2102
2103 case TargetCXXABI::UseTailPaddingUnlessPOD11:
2104 // This is equivalent to RD->getTypeForDecl().isCXX11PODType(),
2105 // but with a lot of abstraction penalty stripped off. This does
2106 // assume that these properties are set correctly even in C++98
2107 // mode; fortunately, that is true because we want to assign
2108 // consistently semantics to the type-traits intrinsics (or at
2109 // least as many of them as possible).
2110 return RD->isTrivial() && RD->isStandardLayout();
2111 }
2112
2113 llvm_unreachable("bad tail-padding use kind")::llvm::llvm_unreachable_internal("bad tail-padding use kind"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 2113)
;
2114}
2115
2116static bool isMsLayout(const ASTContext &Context) {
2117 return Context.getTargetInfo().getCXXABI().isMicrosoft();
2118}
2119
2120// This section contains an implementation of struct layout that is, up to the
2121// included tests, compatible with cl.exe (2013). The layout produced is
2122// significantly different than those produced by the Itanium ABI. Here we note
2123// the most important differences.
2124//
2125// * The alignment of bitfields in unions is ignored when computing the
2126// alignment of the union.
2127// * The existence of zero-width bitfield that occurs after anything other than
2128// a non-zero length bitfield is ignored.
2129// * There is no explicit primary base for the purposes of layout. All bases
2130// with vfptrs are laid out first, followed by all bases without vfptrs.
2131// * The Itanium equivalent vtable pointers are split into a vfptr (virtual
2132// function pointer) and a vbptr (virtual base pointer). They can each be
2133// shared with a, non-virtual bases. These bases need not be the same. vfptrs
2134// always occur at offset 0. vbptrs can occur at an arbitrary offset and are
2135// placed after the lexicographically last non-virtual base. This placement
2136// is always before fields but can be in the middle of the non-virtual bases
2137// due to the two-pass layout scheme for non-virtual-bases.
2138// * Virtual bases sometimes require a 'vtordisp' field that is laid out before
2139// the virtual base and is used in conjunction with virtual overrides during
2140// construction and destruction. This is always a 4 byte value and is used as
2141// an alternative to constructor vtables.
2142// * vtordisps are allocated in a block of memory with size and alignment equal
2143// to the alignment of the completed structure (before applying __declspec(
2144// align())). The vtordisp always occur at the end of the allocation block,
2145// immediately prior to the virtual base.
2146// * vfptrs are injected after all bases and fields have been laid out. In
2147// order to guarantee proper alignment of all fields, the vfptr injection
2148// pushes all bases and fields back by the alignment imposed by those bases
2149// and fields. This can potentially add a significant amount of padding.
2150// vfptrs are always injected at offset 0.
2151// * vbptrs are injected after all bases and fields have been laid out. In
2152// order to guarantee proper alignment of all fields, the vfptr injection
2153// pushes all bases and fields back by the alignment imposed by those bases
2154// and fields. This can potentially add a significant amount of padding.
2155// vbptrs are injected immediately after the last non-virtual base as
2156// lexicographically ordered in the code. If this site isn't pointer aligned
2157// the vbptr is placed at the next properly aligned location. Enough padding
2158// is added to guarantee a fit.
2159// * The last zero sized non-virtual base can be placed at the end of the
2160// struct (potentially aliasing another object), or may alias with the first
2161// field, even if they are of the same type.
2162// * The last zero size virtual base may be placed at the end of the struct
2163// potentially aliasing another object.
2164// * The ABI attempts to avoid aliasing of zero sized bases by adding padding
2165// between bases or vbases with specific properties. The criteria for
2166// additional padding between two bases is that the first base is zero sized
2167// or ends with a zero sized subobject and the second base is zero sized or
2168// trails with a zero sized base or field (sharing of vfptrs can reorder the
2169// layout of the so the leading base is not always the first one declared).
2170// This rule does take into account fields that are not records, so padding
2171// will occur even if the last field is, e.g. an int. The padding added for
2172// bases is 1 byte. The padding added between vbases depends on the alignment
2173// of the object but is at least 4 bytes (in both 32 and 64 bit modes).
2174// * There is no concept of non-virtual alignment, non-virtual alignment and
2175// alignment are always identical.
2176// * There is a distinction between alignment and required alignment.
2177// __declspec(align) changes the required alignment of a struct. This
2178// alignment is _always_ obeyed, even in the presence of #pragma pack. A
2179// record inherits required alignment from all of its fields and bases.
2180// * __declspec(align) on bitfields has the effect of changing the bitfield's
2181// alignment instead of its required alignment. This is the only known way
2182// to make the alignment of a struct bigger than 8. Interestingly enough
2183// this alignment is also immune to the effects of #pragma pack and can be
2184// used to create structures with large alignment under #pragma pack.
2185// However, because it does not impact required alignment, such a structure,
2186// when used as a field or base, will not be aligned if #pragma pack is
2187// still active at the time of use.
2188//
2189// Known incompatibilities:
2190// * all: #pragma pack between fields in a record
2191// * 2010 and back: If the last field in a record is a bitfield, every object
2192// laid out after the record will have extra padding inserted before it. The
2193// extra padding will have size equal to the size of the storage class of the
2194// bitfield. 0 sized bitfields don't exhibit this behavior and the extra
2195// padding can be avoided by adding a 0 sized bitfield after the non-zero-
2196// sized bitfield.
2197// * 2012 and back: In 64-bit mode, if the alignment of a record is 16 or
2198// greater due to __declspec(align()) then a second layout phase occurs after
2199// The locations of the vf and vb pointers are known. This layout phase
2200// suffers from the "last field is a bitfield" bug in 2010 and results in
2201// _every_ field getting padding put in front of it, potentially including the
2202// vfptr, leaving the vfprt at a non-zero location which results in a fault if
2203// anything tries to read the vftbl. The second layout phase also treats
2204// bitfields as separate entities and gives them each storage rather than
2205// packing them. Additionally, because this phase appears to perform a
2206// (an unstable) sort on the members before laying them out and because merged
2207// bitfields have the same address, the bitfields end up in whatever order
2208// the sort left them in, a behavior we could never hope to replicate.
2209
2210namespace {
2211struct MicrosoftRecordLayoutBuilder {
2212 struct ElementInfo {
2213 CharUnits Size;
2214 CharUnits Alignment;
2215 };
2216 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
2217 MicrosoftRecordLayoutBuilder(const ASTContext &Context) : Context(Context) {}
2218private:
2219 MicrosoftRecordLayoutBuilder(const MicrosoftRecordLayoutBuilder &) = delete;
2220 void operator=(const MicrosoftRecordLayoutBuilder &) = delete;
2221public:
2222 void layout(const RecordDecl *RD);
2223 void cxxLayout(const CXXRecordDecl *RD);
2224 /// \brief Initializes size and alignment and honors some flags.
2225 void initializeLayout(const RecordDecl *RD);
2226 /// \brief Initialized C++ layout, compute alignment and virtual alignment and
2227 /// existence of vfptrs and vbptrs. Alignment is needed before the vfptr is
2228 /// laid out.
2229 void initializeCXXLayout(const CXXRecordDecl *RD);
2230 void layoutNonVirtualBases(const CXXRecordDecl *RD);
2231 void layoutNonVirtualBase(const CXXRecordDecl *RD,
2232 const CXXRecordDecl *BaseDecl,
2233 const ASTRecordLayout &BaseLayout,
2234 const ASTRecordLayout *&PreviousBaseLayout);
2235 void injectVFPtr(const CXXRecordDecl *RD);
2236 void injectVBPtr(const CXXRecordDecl *RD);
2237 /// \brief Lays out the fields of the record. Also rounds size up to
2238 /// alignment.
2239 void layoutFields(const RecordDecl *RD);
2240 void layoutField(const FieldDecl *FD);
2241 void layoutBitField(const FieldDecl *FD);
2242 /// \brief Lays out a single zero-width bit-field in the record and handles
2243 /// special cases associated with zero-width bit-fields.
2244 void layoutZeroWidthBitField(const FieldDecl *FD);
2245 void layoutVirtualBases(const CXXRecordDecl *RD);
2246 void finalizeLayout(const RecordDecl *RD);
2247 /// \brief Gets the size and alignment of a base taking pragma pack and
2248 /// __declspec(align) into account.
2249 ElementInfo getAdjustedElementInfo(const ASTRecordLayout &Layout);
2250 /// \brief Gets the size and alignment of a field taking pragma pack and
2251 /// __declspec(align) into account. It also updates RequiredAlignment as a
2252 /// side effect because it is most convenient to do so here.
2253 ElementInfo getAdjustedElementInfo(const FieldDecl *FD);
2254 /// \brief Places a field at an offset in CharUnits.
2255 void placeFieldAtOffset(CharUnits FieldOffset) {
2256 FieldOffsets.push_back(Context.toBits(FieldOffset));
2257 }
2258 /// \brief Places a bitfield at a bit offset.
2259 void placeFieldAtBitOffset(uint64_t FieldOffset) {
2260 FieldOffsets.push_back(FieldOffset);
2261 }
2262 /// \brief Compute the set of virtual bases for which vtordisps are required.
2263 void computeVtorDispSet(
2264 llvm::SmallPtrSetImpl<const CXXRecordDecl *> &HasVtorDispSet,
2265 const CXXRecordDecl *RD) const;
2266 const ASTContext &Context;
2267 /// \brief The size of the record being laid out.
2268 CharUnits Size;
2269 /// \brief The non-virtual size of the record layout.
2270 CharUnits NonVirtualSize;
2271 /// \brief The data size of the record layout.
2272 CharUnits DataSize;
2273 /// \brief The current alignment of the record layout.
2274 CharUnits Alignment;
2275 /// \brief The maximum allowed field alignment. This is set by #pragma pack.
2276 CharUnits MaxFieldAlignment;
2277 /// \brief The alignment that this record must obey. This is imposed by
2278 /// __declspec(align()) on the record itself or one of its fields or bases.
2279 CharUnits RequiredAlignment;
2280 /// \brief The size of the allocation of the currently active bitfield.
2281 /// This value isn't meaningful unless LastFieldIsNonZeroWidthBitfield
2282 /// is true.
2283 CharUnits CurrentBitfieldSize;
2284 /// \brief Offset to the virtual base table pointer (if one exists).
2285 CharUnits VBPtrOffset;
2286 /// \brief Minimum record size possible.
2287 CharUnits MinEmptyStructSize;
2288 /// \brief The size and alignment info of a pointer.
2289 ElementInfo PointerInfo;
2290 /// \brief The primary base class (if one exists).
2291 const CXXRecordDecl *PrimaryBase;
2292 /// \brief The class we share our vb-pointer with.
2293 const CXXRecordDecl *SharedVBPtrBase;
2294 /// \brief The collection of field offsets.
2295 SmallVector<uint64_t, 16> FieldOffsets;
2296 /// \brief Base classes and their offsets in the record.
2297 BaseOffsetsMapTy Bases;
2298 /// \brief virtual base classes and their offsets in the record.
2299 ASTRecordLayout::VBaseOffsetsMapTy VBases;
2300 /// \brief The number of remaining bits in our last bitfield allocation.
2301 /// This value isn't meaningful unless LastFieldIsNonZeroWidthBitfield is
2302 /// true.
2303 unsigned RemainingBitsInField;
2304 bool IsUnion : 1;
2305 /// \brief True if the last field laid out was a bitfield and was not 0
2306 /// width.
2307 bool LastFieldIsNonZeroWidthBitfield : 1;
2308 /// \brief True if the class has its own vftable pointer.
2309 bool HasOwnVFPtr : 1;
2310 /// \brief True if the class has a vbtable pointer.
2311 bool HasVBPtr : 1;
2312 /// \brief True if the last sub-object within the type is zero sized or the
2313 /// object itself is zero sized. This *does not* count members that are not
2314 /// records. Only used for MS-ABI.
2315 bool EndsWithZeroSizedObject : 1;
2316 /// \brief True if this class is zero sized or first base is zero sized or
2317 /// has this property. Only used for MS-ABI.
2318 bool LeadsWithZeroSizedBase : 1;
2319
2320 /// \brief True if the external AST source provided a layout for this record.
2321 bool UseExternalLayout : 1;
2322
2323 /// \brief The layout provided by the external AST source. Only active if
2324 /// UseExternalLayout is true.
2325 ExternalLayout External;
2326};
2327} // namespace
2328
2329MicrosoftRecordLayoutBuilder::ElementInfo
2330MicrosoftRecordLayoutBuilder::getAdjustedElementInfo(
2331 const ASTRecordLayout &Layout) {
2332 ElementInfo Info;
2333 Info.Alignment = Layout.getAlignment();
2334 // Respect pragma pack.
2335 if (!MaxFieldAlignment.isZero())
2336 Info.Alignment = std::min(Info.Alignment, MaxFieldAlignment);
2337 // Track zero-sized subobjects here where it's already available.
2338 EndsWithZeroSizedObject = Layout.endsWithZeroSizedObject();
2339 // Respect required alignment, this is necessary because we may have adjusted
2340 // the alignment in the case of pragam pack. Note that the required alignment
2341 // doesn't actually apply to the struct alignment at this point.
2342 Alignment = std::max(Alignment, Info.Alignment);
2343 RequiredAlignment = std::max(RequiredAlignment, Layout.getRequiredAlignment());
2344 Info.Alignment = std::max(Info.Alignment, Layout.getRequiredAlignment());
2345 Info.Size = Layout.getNonVirtualSize();
2346 return Info;
2347}
2348
2349MicrosoftRecordLayoutBuilder::ElementInfo
2350MicrosoftRecordLayoutBuilder::getAdjustedElementInfo(
2351 const FieldDecl *FD) {
2352 // Get the alignment of the field type's natural alignment, ignore any
2353 // alignment attributes.
2354 ElementInfo Info;
2355 std::tie(Info.Size, Info.Alignment) =
2356 Context.getTypeInfoInChars(FD->getType()->getUnqualifiedDesugaredType());
2357 // Respect align attributes on the field.
2358 CharUnits FieldRequiredAlignment =
2359 Context.toCharUnitsFromBits(FD->getMaxAlignment());
2360 // Respect align attributes on the type.
2361 if (Context.isAlignmentRequired(FD->getType()))
2362 FieldRequiredAlignment = std::max(
2363 Context.getTypeAlignInChars(FD->getType()), FieldRequiredAlignment);
2364 // Respect attributes applied to subobjects of the field.
2365 if (FD->isBitField())
2366 // For some reason __declspec align impacts alignment rather than required
2367 // alignment when it is applied to bitfields.
2368 Info.Alignment = std::max(Info.Alignment, FieldRequiredAlignment);
2369 else {
2370 if (auto RT =
2371 FD->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
2372 auto const &Layout = Context.getASTRecordLayout(RT->getDecl());
2373 EndsWithZeroSizedObject = Layout.endsWithZeroSizedObject();
2374 FieldRequiredAlignment = std::max(FieldRequiredAlignment,
2375 Layout.getRequiredAlignment());
2376 }
2377 // Capture required alignment as a side-effect.
2378 RequiredAlignment = std::max(RequiredAlignment, FieldRequiredAlignment);
2379 }
2380 // Respect pragma pack, attribute pack and declspec align
2381 if (!MaxFieldAlignment.isZero())
2382 Info.Alignment = std::min(Info.Alignment, MaxFieldAlignment);
2383 if (FD->hasAttr<PackedAttr>())
2384 Info.Alignment = CharUnits::One();
2385 Info.Alignment = std::max(Info.Alignment, FieldRequiredAlignment);
2386 return Info;
2387}
2388
2389void MicrosoftRecordLayoutBuilder::layout(const RecordDecl *RD) {
2390 // For C record layout, zero-sized records always have size 4.
2391 MinEmptyStructSize = CharUnits::fromQuantity(4);
2392 initializeLayout(RD);
2393 layoutFields(RD);
2394 DataSize = Size = Size.alignTo(Alignment);
2395 RequiredAlignment = std::max(
2396 RequiredAlignment, Context.toCharUnitsFromBits(RD->getMaxAlignment()));
2397 finalizeLayout(RD);
2398}
2399
2400void MicrosoftRecordLayoutBuilder::cxxLayout(const CXXRecordDecl *RD) {
2401 // The C++ standard says that empty structs have size 1.
2402 MinEmptyStructSize = CharUnits::One();
2403 initializeLayout(RD);
2404 initializeCXXLayout(RD);
2405 layoutNonVirtualBases(RD);
2406 layoutFields(RD);
2407 injectVBPtr(RD);
2408 injectVFPtr(RD);
2409 if (HasOwnVFPtr || (HasVBPtr && !SharedVBPtrBase))
2410 Alignment = std::max(Alignment, PointerInfo.Alignment);
2411 auto RoundingAlignment = Alignment;
2412 if (!MaxFieldAlignment.isZero())
2413 RoundingAlignment = std::min(RoundingAlignment, MaxFieldAlignment);
2414 NonVirtualSize = Size = Size.alignTo(RoundingAlignment);
2415 RequiredAlignment = std::max(
2416 RequiredAlignment, Context.toCharUnitsFromBits(RD->getMaxAlignment()));
2417 layoutVirtualBases(RD);
2418 finalizeLayout(RD);
2419}
2420
2421void MicrosoftRecordLayoutBuilder::initializeLayout(const RecordDecl *RD) {
2422 IsUnion = RD->isUnion();
2423 Size = CharUnits::Zero();
2424 Alignment = CharUnits::One();
2425 // In 64-bit mode we always perform an alignment step after laying out vbases.
2426 // In 32-bit mode we do not. The check to see if we need to perform alignment
2427 // checks the RequiredAlignment field and performs alignment if it isn't 0.
2428 RequiredAlignment = Context.getTargetInfo().getTriple().isArch64Bit()
2429 ? CharUnits::One()
2430 : CharUnits::Zero();
2431 // Compute the maximum field alignment.
2432 MaxFieldAlignment = CharUnits::Zero();
2433 // Honor the default struct packing maximum alignment flag.
2434 if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct)
2435 MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
2436 // Honor the packing attribute. The MS-ABI ignores pragma pack if its larger
2437 // than the pointer size.
2438 if (const MaxFieldAlignmentAttr *MFAA = RD->getAttr<MaxFieldAlignmentAttr>()){
2439 unsigned PackedAlignment = MFAA->getAlignment();
2440 if (PackedAlignment <= Context.getTargetInfo().getPointerWidth(0))
2441 MaxFieldAlignment = Context.toCharUnitsFromBits(PackedAlignment);
2442 }
2443 // Packed attribute forces max field alignment to be 1.
2444 if (RD->hasAttr<PackedAttr>())
2445 MaxFieldAlignment = CharUnits::One();
2446
2447 // Try to respect the external layout if present.
2448 UseExternalLayout = false;
2449 if (ExternalASTSource *Source = Context.getExternalSource())
2450 UseExternalLayout = Source->layoutRecordType(
2451 RD, External.Size, External.Align, External.FieldOffsets,
2452 External.BaseOffsets, External.VirtualBaseOffsets);
2453}
2454
2455void
2456MicrosoftRecordLayoutBuilder::initializeCXXLayout(const CXXRecordDecl *RD) {
2457 EndsWithZeroSizedObject = false;
2458 LeadsWithZeroSizedBase = false;
2459 HasOwnVFPtr = false;
2460 HasVBPtr = false;
2461 PrimaryBase = nullptr;
2462 SharedVBPtrBase = nullptr;
2463 // Calculate pointer size and alignment. These are used for vfptr and vbprt
2464 // injection.
2465 PointerInfo.Size =
2466 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
2467 PointerInfo.Alignment =
2468 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0));
2469 // Respect pragma pack.
2470 if (!MaxFieldAlignment.isZero())
2471 PointerInfo.Alignment = std::min(PointerInfo.Alignment, MaxFieldAlignment);
2472}
2473
2474void
2475MicrosoftRecordLayoutBuilder::layoutNonVirtualBases(const CXXRecordDecl *RD) {
2476 // The MS-ABI lays out all bases that contain leading vfptrs before it lays
2477 // out any bases that do not contain vfptrs. We implement this as two passes
2478 // over the bases. This approach guarantees that the primary base is laid out
2479 // first. We use these passes to calculate some additional aggregated
2480 // information about the bases, such as required alignment and the presence of
2481 // zero sized members.
2482 const ASTRecordLayout *PreviousBaseLayout = nullptr;
2483 // Iterate through the bases and lay out the non-virtual ones.
2484 for (const CXXBaseSpecifier &Base : RD->bases()) {
2485 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
2486 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
2487 // Mark and skip virtual bases.
2488 if (Base.isVirtual()) {
2489 HasVBPtr = true;
2490 continue;
2491 }
2492 // Check for a base to share a VBPtr with.
2493 if (!SharedVBPtrBase && BaseLayout.hasVBPtr()) {
2494 SharedVBPtrBase = BaseDecl;
2495 HasVBPtr = true;
2496 }
2497 // Only lay out bases with extendable VFPtrs on the first pass.
2498 if (!BaseLayout.hasExtendableVFPtr())
2499 continue;
2500 // If we don't have a primary base, this one qualifies.
2501 if (!PrimaryBase) {
2502 PrimaryBase = BaseDecl;
2503 LeadsWithZeroSizedBase = BaseLayout.leadsWithZeroSizedBase();
2504 }
2505 // Lay out the base.
2506 layoutNonVirtualBase(RD, BaseDecl, BaseLayout, PreviousBaseLayout);
2507 }
2508 // Figure out if we need a fresh VFPtr for this class.
2509 if (!PrimaryBase && RD->isDynamicClass())
2510 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
2511 e = RD->method_end();
2512 !HasOwnVFPtr && i != e; ++i)
2513 HasOwnVFPtr = i->isVirtual() && i->size_overridden_methods() == 0;
2514 // If we don't have a primary base then we have a leading object that could
2515 // itself lead with a zero-sized object, something we track.
2516 bool CheckLeadingLayout = !PrimaryBase;
2517 // Iterate through the bases and lay out the non-virtual ones.
2518 for (const CXXBaseSpecifier &Base : RD->bases()) {
2519 if (Base.isVirtual())
2520 continue;
2521 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
2522 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
2523 // Only lay out bases without extendable VFPtrs on the second pass.
2524 if (BaseLayout.hasExtendableVFPtr()) {
2525 VBPtrOffset = Bases[BaseDecl] + BaseLayout.getNonVirtualSize();
2526 continue;
2527 }
2528 // If this is the first layout, check to see if it leads with a zero sized
2529 // object. If it does, so do we.
2530 if (CheckLeadingLayout) {
2531 CheckLeadingLayout = false;
2532 LeadsWithZeroSizedBase = BaseLayout.leadsWithZeroSizedBase();
2533 }
2534 // Lay out the base.
2535 layoutNonVirtualBase(RD, BaseDecl, BaseLayout, PreviousBaseLayout);
2536 VBPtrOffset = Bases[BaseDecl] + BaseLayout.getNonVirtualSize();
2537 }
2538 // Set our VBPtroffset if we know it at this point.
2539 if (!HasVBPtr)
2540 VBPtrOffset = CharUnits::fromQuantity(-1);
2541 else if (SharedVBPtrBase) {
2542 const ASTRecordLayout &Layout = Context.getASTRecordLayout(SharedVBPtrBase);
2543 VBPtrOffset = Bases[SharedVBPtrBase] + Layout.getVBPtrOffset();
2544 }
2545}
2546
2547static bool recordUsesEBO(const RecordDecl *RD) {
2548 if (!isa<CXXRecordDecl>(RD))
2549 return false;
2550 if (RD->hasAttr<EmptyBasesAttr>())
2551 return true;
2552 if (auto *LVA = RD->getAttr<LayoutVersionAttr>())
2553 // TODO: Double check with the next version of MSVC.
2554 if (LVA->getVersion() <= LangOptions::MSVC2015)
2555 return false;
2556 // TODO: Some later version of MSVC will change the default behavior of the
2557 // compiler to enable EBO by default. When this happens, we will need an
2558 // additional isCompatibleWithMSVC check.
2559 return false;
2560}
2561
2562void MicrosoftRecordLayoutBuilder::layoutNonVirtualBase(
2563 const CXXRecordDecl *RD,
2564 const CXXRecordDecl *BaseDecl,
2565 const ASTRecordLayout &BaseLayout,
2566 const ASTRecordLayout *&PreviousBaseLayout) {
2567 // Insert padding between two bases if the left first one is zero sized or
2568 // contains a zero sized subobject and the right is zero sized or one leads
2569 // with a zero sized base.
2570 bool MDCUsesEBO = recordUsesEBO(RD);
2571 if (PreviousBaseLayout && PreviousBaseLayout->endsWithZeroSizedObject() &&
2572 BaseLayout.leadsWithZeroSizedBase() && !MDCUsesEBO)
2573 Size++;
2574 ElementInfo Info = getAdjustedElementInfo(BaseLayout);
2575 CharUnits BaseOffset;
2576
2577 // Respect the external AST source base offset, if present.
2578 bool FoundBase = false;
2579 if (UseExternalLayout) {
2580 FoundBase = External.getExternalNVBaseOffset(BaseDecl, BaseOffset);
2581 if (FoundBase) {
2582 assert(BaseOffset >= Size && "base offset already allocated")(static_cast <bool> (BaseOffset >= Size && "base offset already allocated"
) ? void (0) : __assert_fail ("BaseOffset >= Size && \"base offset already allocated\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 2582, __extension__ __PRETTY_FUNCTION__))
;
2583 Size = BaseOffset;
2584 }
2585 }
2586
2587 if (!FoundBase) {
2588 if (MDCUsesEBO && BaseDecl->isEmpty() &&
2589 BaseLayout.getNonVirtualSize() == CharUnits::Zero()) {
2590 BaseOffset = CharUnits::Zero();
2591 } else {
2592 // Otherwise, lay the base out at the end of the MDC.
2593 BaseOffset = Size = Size.alignTo(Info.Alignment);
2594 }
2595 }
2596 Bases.insert(std::make_pair(BaseDecl, BaseOffset));
2597 Size += BaseLayout.getNonVirtualSize();
2598 PreviousBaseLayout = &BaseLayout;
2599}
2600
2601void MicrosoftRecordLayoutBuilder::layoutFields(const RecordDecl *RD) {
2602 LastFieldIsNonZeroWidthBitfield = false;
2603 for (const FieldDecl *Field : RD->fields())
2604 layoutField(Field);
2605}
2606
2607void MicrosoftRecordLayoutBuilder::layoutField(const FieldDecl *FD) {
2608 if (FD->isBitField()) {
2609 layoutBitField(FD);
2610 return;
2611 }
2612 LastFieldIsNonZeroWidthBitfield = false;
2613 ElementInfo Info = getAdjustedElementInfo(FD);
2614 Alignment = std::max(Alignment, Info.Alignment);
2615 if (IsUnion) {
2616 placeFieldAtOffset(CharUnits::Zero());
2617 Size = std::max(Size, Info.Size);
2618 } else {
2619 CharUnits FieldOffset;
2620 if (UseExternalLayout) {
2621 FieldOffset =
2622 Context.toCharUnitsFromBits(External.getExternalFieldOffset(FD));
2623 assert(FieldOffset >= Size && "field offset already allocated")(static_cast <bool> (FieldOffset >= Size && "field offset already allocated"
) ? void (0) : __assert_fail ("FieldOffset >= Size && \"field offset already allocated\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 2623, __extension__ __PRETTY_FUNCTION__))
;
2624 } else {
2625 FieldOffset = Size.alignTo(Info.Alignment);
2626 }
2627 placeFieldAtOffset(FieldOffset);
2628 Size = FieldOffset + Info.Size;
2629 }
2630}
2631
2632void MicrosoftRecordLayoutBuilder::layoutBitField(const FieldDecl *FD) {
2633 unsigned Width = FD->getBitWidthValue(Context);
2634 if (Width == 0) {
2635 layoutZeroWidthBitField(FD);
2636 return;
2637 }
2638 ElementInfo Info = getAdjustedElementInfo(FD);
2639 // Clamp the bitfield to a containable size for the sake of being able
2640 // to lay them out. Sema will throw an error.
2641 if (Width > Context.toBits(Info.Size))
2642 Width = Context.toBits(Info.Size);
2643 // Check to see if this bitfield fits into an existing allocation. Note:
2644 // MSVC refuses to pack bitfields of formal types with different sizes
2645 // into the same allocation.
2646 if (!IsUnion && LastFieldIsNonZeroWidthBitfield &&
2647 CurrentBitfieldSize == Info.Size && Width <= RemainingBitsInField) {
2648 placeFieldAtBitOffset(Context.toBits(Size) - RemainingBitsInField);
2649 RemainingBitsInField -= Width;
2650 return;
2651 }
2652 LastFieldIsNonZeroWidthBitfield = true;
2653 CurrentBitfieldSize = Info.Size;
2654 if (IsUnion) {
2655 placeFieldAtOffset(CharUnits::Zero());
2656 Size = std::max(Size, Info.Size);
2657 // TODO: Add a Sema warning that MS ignores bitfield alignment in unions.
2658 } else {
2659 // Allocate a new block of memory and place the bitfield in it.
2660 CharUnits FieldOffset = Size.alignTo(Info.Alignment);
2661 placeFieldAtOffset(FieldOffset);
2662 Size = FieldOffset + Info.Size;
2663 Alignment = std::max(Alignment, Info.Alignment);
2664 RemainingBitsInField = Context.toBits(Info.Size) - Width;
2665 }
2666}
2667
2668void
2669MicrosoftRecordLayoutBuilder::layoutZeroWidthBitField(const FieldDecl *FD) {
2670 // Zero-width bitfields are ignored unless they follow a non-zero-width
2671 // bitfield.
2672 if (!LastFieldIsNonZeroWidthBitfield) {
2673 placeFieldAtOffset(IsUnion ? CharUnits::Zero() : Size);
2674 // TODO: Add a Sema warning that MS ignores alignment for zero
2675 // sized bitfields that occur after zero-size bitfields or non-bitfields.
2676 return;
2677 }
2678 LastFieldIsNonZeroWidthBitfield = false;
2679 ElementInfo Info = getAdjustedElementInfo(FD);
2680 if (IsUnion) {
2681 placeFieldAtOffset(CharUnits::Zero());
2682 Size = std::max(Size, Info.Size);
2683 // TODO: Add a Sema warning that MS ignores bitfield alignment in unions.
2684 } else {
2685 // Round up the current record size to the field's alignment boundary.
2686 CharUnits FieldOffset = Size.alignTo(Info.Alignment);
2687 placeFieldAtOffset(FieldOffset);
2688 Size = FieldOffset;
2689 Alignment = std::max(Alignment, Info.Alignment);
2690 }
2691}
2692
2693void MicrosoftRecordLayoutBuilder::injectVBPtr(const CXXRecordDecl *RD) {
2694 if (!HasVBPtr || SharedVBPtrBase)
2695 return;
2696 // Inject the VBPointer at the injection site.
2697 CharUnits InjectionSite = VBPtrOffset;
2698 // But before we do, make sure it's properly aligned.
2699 VBPtrOffset = VBPtrOffset.alignTo(PointerInfo.Alignment);
2700 // Shift everything after the vbptr down, unless we're using an external
2701 // layout.
2702 if (UseExternalLayout)
2703 return;
2704 // Determine where the first field should be laid out after the vbptr.
2705 CharUnits FieldStart = VBPtrOffset + PointerInfo.Size;
2706 // Make sure that the amount we push the fields back by is a multiple of the
2707 // alignment.
2708 CharUnits Offset = (FieldStart - InjectionSite)
2709 .alignTo(std::max(RequiredAlignment, Alignment));
2710 Size += Offset;
2711 for (uint64_t &FieldOffset : FieldOffsets)
2712 FieldOffset += Context.toBits(Offset);
2713 for (BaseOffsetsMapTy::value_type &Base : Bases)
2714 if (Base.second >= InjectionSite)
2715 Base.second += Offset;
2716}
2717
2718void MicrosoftRecordLayoutBuilder::injectVFPtr(const CXXRecordDecl *RD) {
2719 if (!HasOwnVFPtr)
2720 return;
2721 // Make sure that the amount we push the struct back by is a multiple of the
2722 // alignment.
2723 CharUnits Offset =
2724 PointerInfo.Size.alignTo(std::max(RequiredAlignment, Alignment));
2725 // Push back the vbptr, but increase the size of the object and push back
2726 // regular fields by the offset only if not using external record layout.
2727 if (HasVBPtr)
2728 VBPtrOffset += Offset;
2729
2730 if (UseExternalLayout)
2731 return;
2732
2733 Size += Offset;
2734
2735 // If we're using an external layout, the fields offsets have already
2736 // accounted for this adjustment.
2737 for (uint64_t &FieldOffset : FieldOffsets)
2738 FieldOffset += Context.toBits(Offset);
2739 for (BaseOffsetsMapTy::value_type &Base : Bases)
2740 Base.second += Offset;
2741}
2742
2743void MicrosoftRecordLayoutBuilder::layoutVirtualBases(const CXXRecordDecl *RD) {
2744 if (!HasVBPtr)
2745 return;
2746 // Vtordisps are always 4 bytes (even in 64-bit mode)
2747 CharUnits VtorDispSize = CharUnits::fromQuantity(4);
2748 CharUnits VtorDispAlignment = VtorDispSize;
2749 // vtordisps respect pragma pack.
2750 if (!MaxFieldAlignment.isZero())
2751 VtorDispAlignment = std::min(VtorDispAlignment, MaxFieldAlignment);
2752 // The alignment of the vtordisp is at least the required alignment of the
2753 // entire record. This requirement may be present to support vtordisp
2754 // injection.
2755 for (const CXXBaseSpecifier &VBase : RD->vbases()) {
2756 const CXXRecordDecl *BaseDecl = VBase.getType()->getAsCXXRecordDecl();
2757 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
2758 RequiredAlignment =
2759 std::max(RequiredAlignment, BaseLayout.getRequiredAlignment());
2760 }
2761 VtorDispAlignment = std::max(VtorDispAlignment, RequiredAlignment);
2762 // Compute the vtordisp set.
2763 llvm::SmallPtrSet<const CXXRecordDecl *, 2> HasVtorDispSet;
2764 computeVtorDispSet(HasVtorDispSet, RD);
2765 // Iterate through the virtual bases and lay them out.
2766 const ASTRecordLayout *PreviousBaseLayout = nullptr;
2767 for (const CXXBaseSpecifier &VBase : RD->vbases()) {
2768 const CXXRecordDecl *BaseDecl = VBase.getType()->getAsCXXRecordDecl();
2769 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
2770 bool HasVtordisp = HasVtorDispSet.count(BaseDecl) > 0;
2771 // Insert padding between two bases if the left first one is zero sized or
2772 // contains a zero sized subobject and the right is zero sized or one leads
2773 // with a zero sized base. The padding between virtual bases is 4
2774 // bytes (in both 32 and 64 bits modes) and always involves rounding up to
2775 // the required alignment, we don't know why.
2776 if ((PreviousBaseLayout && PreviousBaseLayout->endsWithZeroSizedObject() &&
2777 BaseLayout.leadsWithZeroSizedBase() && !recordUsesEBO(RD)) ||
2778 HasVtordisp) {
2779 Size = Size.alignTo(VtorDispAlignment) + VtorDispSize;
2780 Alignment = std::max(VtorDispAlignment, Alignment);
2781 }
2782 // Insert the virtual base.
2783 ElementInfo Info = getAdjustedElementInfo(BaseLayout);
2784 CharUnits BaseOffset;
2785
2786 // Respect the external AST source base offset, if present.
2787 bool FoundBase = false;
2788 if (UseExternalLayout) {
2789 FoundBase = External.getExternalVBaseOffset(BaseDecl, BaseOffset);
2790 if (FoundBase)
2791 assert(BaseOffset >= Size && "base offset already allocated")(static_cast <bool> (BaseOffset >= Size && "base offset already allocated"
) ? void (0) : __assert_fail ("BaseOffset >= Size && \"base offset already allocated\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 2791, __extension__ __PRETTY_FUNCTION__))
;
2792 }
2793 if (!FoundBase)
2794 BaseOffset = Size.alignTo(Info.Alignment);
2795
2796 VBases.insert(std::make_pair(BaseDecl,
2797 ASTRecordLayout::VBaseInfo(BaseOffset, HasVtordisp)));
2798 Size = BaseOffset + BaseLayout.getNonVirtualSize();
2799 PreviousBaseLayout = &BaseLayout;
2800 }
2801}
2802
2803void MicrosoftRecordLayoutBuilder::finalizeLayout(const RecordDecl *RD) {
2804 // Respect required alignment. Note that in 32-bit mode Required alignment
2805 // may be 0 and cause size not to be updated.
2806 DataSize = Size;
2807 if (!RequiredAlignment.isZero()) {
2808 Alignment = std::max(Alignment, RequiredAlignment);
2809 auto RoundingAlignment = Alignment;
2810 if (!MaxFieldAlignment.isZero())
2811 RoundingAlignment = std::min(RoundingAlignment, MaxFieldAlignment);
2812 RoundingAlignment = std::max(RoundingAlignment, RequiredAlignment);
2813 Size = Size.alignTo(RoundingAlignment);
2814 }
2815 if (Size.isZero()) {
2816 if (!recordUsesEBO(RD) || !cast<CXXRecordDecl>(RD)->isEmpty()) {
2817 EndsWithZeroSizedObject = true;
2818 LeadsWithZeroSizedBase = true;
2819 }
2820 // Zero-sized structures have size equal to their alignment if a
2821 // __declspec(align) came into play.
2822 if (RequiredAlignment >= MinEmptyStructSize)
2823 Size = Alignment;
2824 else
2825 Size = MinEmptyStructSize;
2826 }
2827
2828 if (UseExternalLayout) {
2829 Size = Context.toCharUnitsFromBits(External.Size);
2830 if (External.Align)
2831 Alignment = Context.toCharUnitsFromBits(External.Align);
2832 }
2833}
2834
2835// Recursively walks the non-virtual bases of a class and determines if any of
2836// them are in the bases with overridden methods set.
2837static bool
2838RequiresVtordisp(const llvm::SmallPtrSetImpl<const CXXRecordDecl *> &
2839 BasesWithOverriddenMethods,
2840 const CXXRecordDecl *RD) {
2841 if (BasesWithOverriddenMethods.count(RD))
2842 return true;
2843 // If any of a virtual bases non-virtual bases (recursively) requires a
2844 // vtordisp than so does this virtual base.
2845 for (const CXXBaseSpecifier &Base : RD->bases())
2846 if (!Base.isVirtual() &&
2847 RequiresVtordisp(BasesWithOverriddenMethods,
2848 Base.getType()->getAsCXXRecordDecl()))
2849 return true;
2850 return false;
2851}
2852
2853void MicrosoftRecordLayoutBuilder::computeVtorDispSet(
2854 llvm::SmallPtrSetImpl<const CXXRecordDecl *> &HasVtordispSet,
2855 const CXXRecordDecl *RD) const {
2856 // /vd2 or #pragma vtordisp(2): Always use vtordisps for virtual bases with
2857 // vftables.
2858 if (RD->getMSVtorDispMode() == MSVtorDispAttr::ForVFTable) {
2859 for (const CXXBaseSpecifier &Base : RD->vbases()) {
2860 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
2861 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
2862 if (Layout.hasExtendableVFPtr())
2863 HasVtordispSet.insert(BaseDecl);
2864 }
2865 return;
2866 }
2867
2868 // If any of our bases need a vtordisp for this type, so do we. Check our
2869 // direct bases for vtordisp requirements.
2870 for (const CXXBaseSpecifier &Base : RD->bases()) {
2871 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
2872 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
2873 for (const auto &bi : Layout.getVBaseOffsetsMap())
2874 if (bi.second.hasVtorDisp())
2875 HasVtordispSet.insert(bi.first);
2876 }
2877 // We don't introduce any additional vtordisps if either:
2878 // * A user declared constructor or destructor aren't declared.
2879 // * #pragma vtordisp(0) or the /vd0 flag are in use.
2880 if ((!RD->hasUserDeclaredConstructor() && !RD->hasUserDeclaredDestructor()) ||
2881 RD->getMSVtorDispMode() == MSVtorDispAttr::Never)
2882 return;
2883 // /vd1 or #pragma vtordisp(1): Try to guess based on whether we think it's
2884 // possible for a partially constructed object with virtual base overrides to
2885 // escape a non-trivial constructor.
2886 assert(RD->getMSVtorDispMode() == MSVtorDispAttr::ForVBaseOverride)(static_cast <bool> (RD->getMSVtorDispMode() == MSVtorDispAttr
::ForVBaseOverride) ? void (0) : __assert_fail ("RD->getMSVtorDispMode() == MSVtorDispAttr::ForVBaseOverride"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 2886, __extension__ __PRETTY_FUNCTION__))
;
2887 // Compute a set of base classes which define methods we override. A virtual
2888 // base in this set will require a vtordisp. A virtual base that transitively
2889 // contains one of these bases as a non-virtual base will also require a
2890 // vtordisp.
2891 llvm::SmallPtrSet<const CXXMethodDecl *, 8> Work;
2892 llvm::SmallPtrSet<const CXXRecordDecl *, 2> BasesWithOverriddenMethods;
2893 // Seed the working set with our non-destructor, non-pure virtual methods.
2894 for (const CXXMethodDecl *MD : RD->methods())
2895 if (MD->isVirtual() && !isa<CXXDestructorDecl>(MD) && !MD->isPure())
2896 Work.insert(MD);
2897 while (!Work.empty()) {
2898 const CXXMethodDecl *MD = *Work.begin();
2899 auto MethodRange = MD->overridden_methods();
2900 // If a virtual method has no-overrides it lives in its parent's vtable.
2901 if (MethodRange.begin() == MethodRange.end())
2902 BasesWithOverriddenMethods.insert(MD->getParent());
2903 else
2904 Work.insert(MethodRange.begin(), MethodRange.end());
2905 // We've finished processing this element, remove it from the working set.
2906 Work.erase(MD);
2907 }
2908 // For each of our virtual bases, check if it is in the set of overridden
2909 // bases or if it transitively contains a non-virtual base that is.
2910 for (const CXXBaseSpecifier &Base : RD->vbases()) {
2911 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
2912 if (!HasVtordispSet.count(BaseDecl) &&
2913 RequiresVtordisp(BasesWithOverriddenMethods, BaseDecl))
2914 HasVtordispSet.insert(BaseDecl);
2915 }
2916}
2917
2918/// getASTRecordLayout - Get or compute information about the layout of the
2919/// specified record (struct/union/class), which indicates its size and field
2920/// position information.
2921const ASTRecordLayout &
2922ASTContext::getASTRecordLayout(const RecordDecl *D) const {
2923 // These asserts test different things. A record has a definition
2924 // as soon as we begin to parse the definition. That definition is
2925 // not a complete definition (which is what isDefinition() tests)
2926 // until we *finish* parsing the definition.
2927
2928 if (D->hasExternalLexicalStorage() && !D->getDefinition())
2929 getExternalSource()->CompleteType(const_cast<RecordDecl*>(D));
2930
2931 D = D->getDefinition();
2932 assert(D && "Cannot get layout of forward declarations!")(static_cast <bool> (D && "Cannot get layout of forward declarations!"
) ? void (0) : __assert_fail ("D && \"Cannot get layout of forward declarations!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 2932, __extension__ __PRETTY_FUNCTION__))
;
2933 assert(!D->isInvalidDecl() && "Cannot get layout of invalid decl!")(static_cast <bool> (!D->isInvalidDecl() && "Cannot get layout of invalid decl!"
) ? void (0) : __assert_fail ("!D->isInvalidDecl() && \"Cannot get layout of invalid decl!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 2933, __extension__ __PRETTY_FUNCTION__))
;
2934 assert(D->isCompleteDefinition() && "Cannot layout type before complete!")(static_cast <bool> (D->isCompleteDefinition() &&
"Cannot layout type before complete!") ? void (0) : __assert_fail
("D->isCompleteDefinition() && \"Cannot layout type before complete!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 2934, __extension__ __PRETTY_FUNCTION__))
;
2935
2936 // Look up this layout, if already laid out, return what we have.
2937 // Note that we can't save a reference to the entry because this function
2938 // is recursive.
2939 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
2940 if (Entry) return *Entry;
2941
2942 const ASTRecordLayout *NewEntry = nullptr;
2943
2944 if (isMsLayout(*this)) {
2945 MicrosoftRecordLayoutBuilder Builder(*this);
2946 if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
2947 Builder.cxxLayout(RD);
2948 NewEntry = new (*this) ASTRecordLayout(
2949 *this, Builder.Size, Builder.Alignment, Builder.RequiredAlignment,
2950 Builder.HasOwnVFPtr, Builder.HasOwnVFPtr || Builder.PrimaryBase,
2951 Builder.VBPtrOffset, Builder.DataSize, Builder.FieldOffsets,
2952 Builder.NonVirtualSize, Builder.Alignment, CharUnits::Zero(),
2953 Builder.PrimaryBase, false, Builder.SharedVBPtrBase,
2954 Builder.EndsWithZeroSizedObject, Builder.LeadsWithZeroSizedBase,
2955 Builder.Bases, Builder.VBases);
2956 } else {
2957 Builder.layout(D);
2958 NewEntry = new (*this) ASTRecordLayout(
2959 *this, Builder.Size, Builder.Alignment, Builder.RequiredAlignment,
2960 Builder.Size, Builder.FieldOffsets);
2961 }
2962 } else {
2963 if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
2964 EmptySubobjectMap EmptySubobjects(*this, RD);
2965 ItaniumRecordLayoutBuilder Builder(*this, &EmptySubobjects);
2966 Builder.Layout(RD);
2967
2968 // In certain situations, we are allowed to lay out objects in the
2969 // tail-padding of base classes. This is ABI-dependent.
2970 // FIXME: this should be stored in the record layout.
2971 bool skipTailPadding =
2972 mustSkipTailPadding(getTargetInfo().getCXXABI(), RD);
2973
2974 // FIXME: This should be done in FinalizeLayout.
2975 CharUnits DataSize =
2976 skipTailPadding ? Builder.getSize() : Builder.getDataSize();
2977 CharUnits NonVirtualSize =
2978 skipTailPadding ? DataSize : Builder.NonVirtualSize;
2979 NewEntry = new (*this) ASTRecordLayout(
2980 *this, Builder.getSize(), Builder.Alignment,
2981 /*RequiredAlignment : used by MS-ABI)*/
2982 Builder.Alignment, Builder.HasOwnVFPtr, RD->isDynamicClass(),
2983 CharUnits::fromQuantity(-1), DataSize, Builder.FieldOffsets,
2984 NonVirtualSize, Builder.NonVirtualAlignment,
2985 EmptySubobjects.SizeOfLargestEmptySubobject, Builder.PrimaryBase,
2986 Builder.PrimaryBaseIsVirtual, nullptr, false, false, Builder.Bases,
2987 Builder.VBases);
2988 } else {
2989 ItaniumRecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/nullptr);
2990 Builder.Layout(D);
2991
2992 NewEntry = new (*this) ASTRecordLayout(
2993 *this, Builder.getSize(), Builder.Alignment,
2994 /*RequiredAlignment : used by MS-ABI)*/
2995 Builder.Alignment, Builder.getSize(), Builder.FieldOffsets);
2996 }
2997 }
2998
2999 ASTRecordLayouts[D] = NewEntry;
3000
3001 if (getLangOpts().DumpRecordLayouts) {
3002 llvm::outs() << "\n*** Dumping AST Record Layout\n";
3003 DumpRecordLayout(D, llvm::outs(), getLangOpts().DumpRecordLayoutsSimple);
3004 }
3005
3006 return *NewEntry;
3007}
3008
3009const CXXMethodDecl *ASTContext::getCurrentKeyFunction(const CXXRecordDecl *RD) {
3010 if (!getTargetInfo().getCXXABI().hasKeyFunctions())
3011 return nullptr;
3012
3013 assert(RD->getDefinition() && "Cannot get key function for forward decl!")(static_cast <bool> (RD->getDefinition() && "Cannot get key function for forward decl!"
) ? void (0) : __assert_fail ("RD->getDefinition() && \"Cannot get key function for forward decl!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 3013, __extension__ __PRETTY_FUNCTION__))
;
3014 RD = cast<CXXRecordDecl>(RD->getDefinition());
3015
3016 // Beware:
3017 // 1) computing the key function might trigger deserialization, which might
3018 // invalidate iterators into KeyFunctions
3019 // 2) 'get' on the LazyDeclPtr might also trigger deserialization and
3020 // invalidate the LazyDeclPtr within the map itself
3021 LazyDeclPtr Entry = KeyFunctions[RD];
3022 const Decl *Result =
3023 Entry ? Entry.get(getExternalSource()) : computeKeyFunction(*this, RD);
3024
3025 // Store it back if it changed.
3026 if (Entry.isOffset() || Entry.isValid() != bool(Result))
3027 KeyFunctions[RD] = const_cast<Decl*>(Result);
3028
3029 return cast_or_null<CXXMethodDecl>(Result);
3030}
3031
3032void ASTContext::setNonKeyFunction(const CXXMethodDecl *Method) {
3033 assert(Method == Method->getFirstDecl() &&(static_cast <bool> (Method == Method->getFirstDecl(
) && "not working with method declaration from class definition"
) ? void (0) : __assert_fail ("Method == Method->getFirstDecl() && \"not working with method declaration from class definition\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 3034, __extension__ __PRETTY_FUNCTION__))
3034 "not working with method declaration from class definition")(static_cast <bool> (Method == Method->getFirstDecl(
) && "not working with method declaration from class definition"
) ? void (0) : __assert_fail ("Method == Method->getFirstDecl() && \"not working with method declaration from class definition\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 3034, __extension__ __PRETTY_FUNCTION__))
;
3035
3036 // Look up the cache entry. Since we're working with the first
3037 // declaration, its parent must be the class definition, which is
3038 // the correct key for the KeyFunctions hash.
3039 const auto &Map = KeyFunctions;
3040 auto I = Map.find(Method->getParent());
3041
3042 // If it's not cached, there's nothing to do.
3043 if (I == Map.end()) return;
3044
3045 // If it is cached, check whether it's the target method, and if so,
3046 // remove it from the cache. Note, the call to 'get' might invalidate
3047 // the iterator and the LazyDeclPtr object within the map.
3048 LazyDeclPtr Ptr = I->second;
3049 if (Ptr.get(getExternalSource()) == Method) {
3050 // FIXME: remember that we did this for module / chained PCH state?
3051 KeyFunctions.erase(Method->getParent());
3052 }
3053}
3054
3055static uint64_t getFieldOffset(const ASTContext &C, const FieldDecl *FD) {
3056 const ASTRecordLayout &Layout = C.getASTRecordLayout(FD->getParent());
3057 return Layout.getFieldOffset(FD->getFieldIndex());
3058}
3059
3060uint64_t ASTContext::getFieldOffset(const ValueDecl *VD) const {
3061 uint64_t OffsetInBits;
3062 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
3063 OffsetInBits = ::getFieldOffset(*this, FD);
3064 } else {
3065 const IndirectFieldDecl *IFD = cast<IndirectFieldDecl>(VD);
3066
3067 OffsetInBits = 0;
3068 for (const NamedDecl *ND : IFD->chain())
3069 OffsetInBits += ::getFieldOffset(*this, cast<FieldDecl>(ND));
3070 }
3071
3072 return OffsetInBits;
3073}
3074
3075uint64_t ASTContext::lookupFieldBitOffset(const ObjCInterfaceDecl *OID,
3076 const ObjCImplementationDecl *ID,
3077 const ObjCIvarDecl *Ivar) const {
3078 const ObjCInterfaceDecl *Container = Ivar->getContainingInterface();
3079
3080 // FIXME: We should eliminate the need to have ObjCImplementationDecl passed
3081 // in here; it should never be necessary because that should be the lexical
3082 // decl context for the ivar.
3083
3084 // If we know have an implementation (and the ivar is in it) then
3085 // look up in the implementation layout.
3086 const ASTRecordLayout *RL;
3087 if (ID && declaresSameEntity(ID->getClassInterface(), Container))
3088 RL = &getASTObjCImplementationLayout(ID);
3089 else
3090 RL = &getASTObjCInterfaceLayout(Container);
3091
3092 // Compute field index.
3093 //
3094 // FIXME: The index here is closely tied to how ASTContext::getObjCLayout is
3095 // implemented. This should be fixed to get the information from the layout
3096 // directly.
3097 unsigned Index = 0;
3098
3099 for (const ObjCIvarDecl *IVD = Container->all_declared_ivar_begin();
3100 IVD; IVD = IVD->getNextIvar()) {
3101 if (Ivar == IVD)
3102 break;
3103 ++Index;
3104 }
3105 assert(Index < RL->getFieldCount() && "Ivar is not inside record layout!")(static_cast <bool> (Index < RL->getFieldCount() &&
"Ivar is not inside record layout!") ? void (0) : __assert_fail
("Index < RL->getFieldCount() && \"Ivar is not inside record layout!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 3105, __extension__ __PRETTY_FUNCTION__))
;
3106
3107 return RL->getFieldOffset(Index);
3108}
3109
3110/// getObjCLayout - Get or compute information about the layout of the
3111/// given interface.
3112///
3113/// \param Impl - If given, also include the layout of the interface's
3114/// implementation. This may differ by including synthesized ivars.
3115const ASTRecordLayout &
3116ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
3117 const ObjCImplementationDecl *Impl) const {
3118 // Retrieve the definition
3119 if (D->hasExternalLexicalStorage() && !D->getDefinition())
1
Assuming the condition is false
3120 getExternalSource()->CompleteType(const_cast<ObjCInterfaceDecl*>(D));
3121 D = D->getDefinition();
3122 assert(D && D->isThisDeclarationADefinition() && "Invalid interface decl!")(static_cast <bool> (D && D->isThisDeclarationADefinition
() && "Invalid interface decl!") ? void (0) : __assert_fail
("D && D->isThisDeclarationADefinition() && \"Invalid interface decl!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 3122, __extension__ __PRETTY_FUNCTION__))
;
3123
3124 // Look up this layout, if already laid out, return what we have.
3125 const ObjCContainerDecl *Key =
3126 Impl ? (const ObjCContainerDecl*) Impl : (const ObjCContainerDecl*) D;
2
Assuming 'Impl' is null
3
'?' condition is false
3127 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
4
Assuming 'Entry' is null
5
Taking false branch
3128 return *Entry;
3129
3130 // Add in synthesized ivar count if laying out an implementation.
3131 if (Impl) {
6
Taking false branch
3132 unsigned SynthCount = CountNonClassIvars(D);
3133 // If there aren't any synthesized ivars then reuse the interface
3134 // entry. Note we can't cache this because we simply free all
3135 // entries later; however we shouldn't look up implementations
3136 // frequently.
3137 if (SynthCount == 0)
3138 return getObjCLayout(D, nullptr);
3139 }
3140
3141 ItaniumRecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/nullptr);
3142 Builder.Layout(D);
3143
3144 const ASTRecordLayout *NewEntry =
7
'NewEntry' initialized to a null pointer value
3145 new (*this) ASTRecordLayout(*this, Builder.getSize(),
3146 Builder.Alignment,
3147 /*RequiredAlignment : used by MS-ABI)*/
3148 Builder.Alignment,
3149 Builder.getDataSize(),
3150 Builder.FieldOffsets);
3151
3152 ObjCLayouts[Key] = NewEntry;
3153
3154 return *NewEntry;
8
Returning null reference
3155}
3156
3157static void PrintOffset(raw_ostream &OS,
3158 CharUnits Offset, unsigned IndentLevel) {
3159 OS << llvm::format("%10" PRId64"l" "d" " | ", (int64_t)Offset.getQuantity());
3160 OS.indent(IndentLevel * 2);
3161}
3162
3163static void PrintBitFieldOffset(raw_ostream &OS, CharUnits Offset,
3164 unsigned Begin, unsigned Width,
3165 unsigned IndentLevel) {
3166 llvm::SmallString<10> Buffer;
3167 {
3168 llvm::raw_svector_ostream BufferOS(Buffer);
3169 BufferOS << Offset.getQuantity() << ':';
3170 if (Width == 0) {
3171 BufferOS << '-';
3172 } else {
3173 BufferOS << Begin << '-' << (Begin + Width - 1);
3174 }
3175 }
3176
3177 OS << llvm::right_justify(Buffer, 10) << " | ";
3178 OS.indent(IndentLevel * 2);
3179}
3180
3181static void PrintIndentNoOffset(raw_ostream &OS, unsigned IndentLevel) {
3182 OS << " | ";
3183 OS.indent(IndentLevel * 2);
3184}
3185
3186static void DumpRecordLayout(raw_ostream &OS, const RecordDecl *RD,
3187 const ASTContext &C,
3188 CharUnits Offset,
3189 unsigned IndentLevel,
3190 const char* Description,
3191 bool PrintSizeInfo,
3192 bool IncludeVirtualBases) {
3193 const ASTRecordLayout &Layout = C.getASTRecordLayout(RD);
3194 auto CXXRD = dyn_cast<CXXRecordDecl>(RD);
3195
3196 PrintOffset(OS, Offset, IndentLevel);
3197 OS << C.getTypeDeclType(const_cast<RecordDecl*>(RD)).getAsString();
3198 if (Description)
3199 OS << ' ' << Description;
3200 if (CXXRD && CXXRD->isEmpty())
3201 OS << " (empty)";
3202 OS << '\n';
3203
3204 IndentLevel++;
3205
3206 // Dump bases.
3207 if (CXXRD) {
3208 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
3209 bool HasOwnVFPtr = Layout.hasOwnVFPtr();
3210 bool HasOwnVBPtr = Layout.hasOwnVBPtr();
3211
3212 // Vtable pointer.
3213 if (CXXRD->isDynamicClass() && !PrimaryBase && !isMsLayout(C)) {
3214 PrintOffset(OS, Offset, IndentLevel);
3215 OS << '(' << *RD << " vtable pointer)\n";
3216 } else if (HasOwnVFPtr) {
3217 PrintOffset(OS, Offset, IndentLevel);
3218 // vfptr (for Microsoft C++ ABI)
3219 OS << '(' << *RD << " vftable pointer)\n";
3220 }
3221
3222 // Collect nvbases.
3223 SmallVector<const CXXRecordDecl *, 4> Bases;
3224 for (const CXXBaseSpecifier &Base : CXXRD->bases()) {
3225 assert(!Base.getType()->isDependentType() &&(static_cast <bool> (!Base.getType()->isDependentType
() && "Cannot layout class with dependent bases.") ? void
(0) : __assert_fail ("!Base.getType()->isDependentType() && \"Cannot layout class with dependent bases.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 3226, __extension__ __PRETTY_FUNCTION__))
3226 "Cannot layout class with dependent bases.")(static_cast <bool> (!Base.getType()->isDependentType
() && "Cannot layout class with dependent bases.") ? void
(0) : __assert_fail ("!Base.getType()->isDependentType() && \"Cannot layout class with dependent bases.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 3226, __extension__ __PRETTY_FUNCTION__))
;
3227 if (!Base.isVirtual())
3228 Bases.push_back(Base.getType()->getAsCXXRecordDecl());
3229 }
3230
3231 // Sort nvbases by offset.
3232 std::stable_sort(Bases.begin(), Bases.end(),
3233 [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
3234 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
3235 });
3236
3237 // Dump (non-virtual) bases
3238 for (const CXXRecordDecl *Base : Bases) {
3239 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base);
3240 DumpRecordLayout(OS, Base, C, BaseOffset, IndentLevel,
3241 Base == PrimaryBase ? "(primary base)" : "(base)",
3242 /*PrintSizeInfo=*/false,
3243 /*IncludeVirtualBases=*/false);
3244 }
3245
3246 // vbptr (for Microsoft C++ ABI)
3247 if (HasOwnVBPtr) {
3248 PrintOffset(OS, Offset + Layout.getVBPtrOffset(), IndentLevel);
3249 OS << '(' << *RD << " vbtable pointer)\n";
3250 }
3251 }
3252
3253 // Dump fields.
3254 uint64_t FieldNo = 0;
3255 for (RecordDecl::field_iterator I = RD->field_begin(),
3256 E = RD->field_end(); I != E; ++I, ++FieldNo) {
3257 const FieldDecl &Field = **I;
3258 uint64_t LocalFieldOffsetInBits = Layout.getFieldOffset(FieldNo);
3259 CharUnits FieldOffset =
3260 Offset + C.toCharUnitsFromBits(LocalFieldOffsetInBits);
3261
3262 // Recursively dump fields of record type.
3263 if (auto RT = Field.getType()->getAs<RecordType>()) {
3264 DumpRecordLayout(OS, RT->getDecl(), C, FieldOffset, IndentLevel,
3265 Field.getName().data(),
3266 /*PrintSizeInfo=*/false,
3267 /*IncludeVirtualBases=*/true);
3268 continue;
3269 }
3270
3271 if (Field.isBitField()) {
3272 uint64_t LocalFieldByteOffsetInBits = C.toBits(FieldOffset - Offset);
3273 unsigned Begin = LocalFieldOffsetInBits - LocalFieldByteOffsetInBits;
3274 unsigned Width = Field.getBitWidthValue(C);
3275 PrintBitFieldOffset(OS, FieldOffset, Begin, Width, IndentLevel);
3276 } else {
3277 PrintOffset(OS, FieldOffset, IndentLevel);
3278 }
3279 OS << Field.getType().getAsString() << ' ' << Field << '\n';
3280 }
3281
3282 // Dump virtual bases.
3283 if (CXXRD && IncludeVirtualBases) {
3284 const ASTRecordLayout::VBaseOffsetsMapTy &VtorDisps =
3285 Layout.getVBaseOffsetsMap();
3286
3287 for (const CXXBaseSpecifier &Base : CXXRD->vbases()) {
3288 assert(Base.isVirtual() && "Found non-virtual class!")(static_cast <bool> (Base.isVirtual() && "Found non-virtual class!"
) ? void (0) : __assert_fail ("Base.isVirtual() && \"Found non-virtual class!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/RecordLayoutBuilder.cpp"
, 3288, __extension__ __PRETTY_FUNCTION__))
;
3289 const CXXRecordDecl *VBase = Base.getType()->getAsCXXRecordDecl();
3290
3291 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBase);
3292
3293 if (VtorDisps.find(VBase)->second.hasVtorDisp()) {
3294 PrintOffset(OS, VBaseOffset - CharUnits::fromQuantity(4), IndentLevel);
3295 OS << "(vtordisp for vbase " << *VBase << ")\n";
3296 }
3297
3298 DumpRecordLayout(OS, VBase, C, VBaseOffset, IndentLevel,
3299 VBase == Layout.getPrimaryBase() ?
3300 "(primary virtual base)" : "(virtual base)",
3301 /*PrintSizeInfo=*/false,
3302 /*IncludeVirtualBases=*/false);
3303 }
3304 }
3305
3306 if (!PrintSizeInfo) return;
3307
3308 PrintIndentNoOffset(OS, IndentLevel - 1);
3309 OS << "[sizeof=" << Layout.getSize().getQuantity();
3310 if (CXXRD && !isMsLayout(C))
3311 OS << ", dsize=" << Layout.getDataSize().getQuantity();
3312 OS << ", align=" << Layout.getAlignment().getQuantity();
3313
3314 if (CXXRD) {
3315 OS << ",\n";
3316 PrintIndentNoOffset(OS, IndentLevel - 1);
3317 OS << " nvsize=" << Layout.getNonVirtualSize().getQuantity();
3318 OS << ", nvalign=" << Layout.getNonVirtualAlignment().getQuantity();
3319 }
3320 OS << "]\n";
3321}
3322
3323void ASTContext::DumpRecordLayout(const RecordDecl *RD,
3324 raw_ostream &OS,
3325 bool Simple) const {
3326 if (!Simple) {
3327 ::DumpRecordLayout(OS, RD, *this, CharUnits(), 0, nullptr,
3328 /*PrintSizeInfo*/true,
3329 /*IncludeVirtualBases=*/true);
3330 return;
3331 }
3332
3333 // The "simple" format is designed to be parsed by the
3334 // layout-override testing code. There shouldn't be any external
3335 // uses of this format --- when LLDB overrides a layout, it sets up
3336 // the data structures directly --- so feel free to adjust this as
3337 // you like as long as you also update the rudimentary parser for it
3338 // in libFrontend.
3339
3340 const ASTRecordLayout &Info = getASTRecordLayout(RD);
3341 OS << "Type: " << getTypeDeclType(RD).getAsString() << "\n";
3342 OS << "\nLayout: ";
3343 OS << "<ASTRecordLayout\n";
3344 OS << " Size:" << toBits(Info.getSize()) << "\n";
3345 if (!isMsLayout(*this))
3346 OS << " DataSize:" << toBits(Info.getDataSize()) << "\n";
3347 OS << " Alignment:" << toBits(Info.getAlignment()) << "\n";
3348 OS << " FieldOffsets: [";
3349 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i) {
3350 if (i) OS << ", ";
3351 OS << Info.getFieldOffset(i);
3352 }
3353 OS << "]>\n";
3354}