Coverage Report

Created: 2022-05-14 11:35

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