clang 24.0.0git
CGRecordLayoutBuilder.cpp
Go to the documentation of this file.
1//===--- CGRecordLayoutBuilder.cpp - CGRecordLayout builder ----*- C++ -*-===//
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// Builder implementation for CGRecordLayout objects.
10//
11//===----------------------------------------------------------------------===//
12
13#include "ABIInfoImpl.h"
14#include "CGCXXABI.h"
15#include "CGRecordLayout.h"
16#include "CodeGenTypes.h"
18#include "clang/AST/Attr.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/Expr.h"
26#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/DerivedTypes.h"
28#include "llvm/IR/Type.h"
29#include "llvm/Support/Debug.h"
30#include "llvm/Support/MathExtras.h"
31#include "llvm/Support/raw_ostream.h"
32using namespace clang;
33using namespace CodeGen;
34
35namespace {
36/// The CGRecordLowering is responsible for lowering an ASTRecordLayout to an
37/// llvm::Type. Some of the lowering is straightforward, some is not. Here we
38/// detail some of the complexities and weirdnesses here.
39/// * LLVM does not have unions - Unions can, in theory be represented by any
40/// llvm::Type with correct size. We choose a field via a specific heuristic
41/// and add padding if necessary.
42/// * LLVM does not have bitfields - Bitfields are collected into contiguous
43/// runs and allocated as a single storage type for the run. ASTRecordLayout
44/// contains enough information to determine where the runs break. Microsoft
45/// and Itanium follow different rules and use different codepaths.
46/// * It is desired that, when possible, bitfields use the appropriate iN type
47/// when lowered to llvm types. For example unsigned x : 24 gets lowered to
48/// i24. This isn't always possible because i24 has storage size of 32 bit
49/// and if it is possible to use that extra byte of padding we must use [i8 x
50/// 3] instead of i24. This is computed when accumulating bitfields in
51/// accumulateBitfields.
52/// C++ examples that require clipping:
53/// struct { int a : 24; char b; }; // a must be clipped, b goes at offset 3
54/// struct A { int a : 24; ~A(); }; // a must be clipped because:
55/// struct B : A { char b; }; // b goes at offset 3
56/// * The allocation of bitfield access units is described in more detail in
57/// CGRecordLowering::accumulateBitFields.
58/// * Clang ignores 0 sized bitfields and 0 sized bases but *not* zero sized
59/// fields. The existing asserts suggest that LLVM assumes that *every* field
60/// has an underlying storage type. Therefore empty structures containing
61/// zero sized subobjects such as empty records or zero sized arrays still get
62/// a zero sized (empty struct) storage type.
63/// * Clang reads the complete type rather than the base type when generating
64/// code to access fields. Bitfields in tail position with tail padding may
65/// be clipped in the base class but not the complete class (we may discover
66/// that the tail padding is not used in the complete class.) However,
67/// because LLVM reads from the complete type it can generate incorrect code
68/// if we do not clip the tail padding off of the bitfield in the complete
69/// layout.
70/// * Itanium allows nearly empty primary virtual bases. These bases don't get
71/// get their own storage because they're laid out as part of another base
72/// or at the beginning of the structure. Determining if a VBase actually
73/// gets storage awkwardly involves a walk of all bases.
74/// * VFPtrs and VBPtrs do *not* make a record NotZeroInitializable.
75struct CGRecordLowering {
76 // MemberInfo is a helper structure that contains information about a record
77 // member. In additional to the standard member types, there exists a
78 // sentinel member type that ensures correct rounding.
79 struct MemberInfo {
80 CharUnits Offset;
81 enum InfoKind { VFPtr, VBPtr, Field, Base, VBase } Kind;
82 llvm::Type *Data;
83 union {
84 const FieldDecl *FD;
85 const CXXRecordDecl *RD;
86 };
87 MemberInfo(CharUnits Offset, InfoKind Kind, llvm::Type *Data,
88 const FieldDecl *FD = nullptr)
89 : Offset(Offset), Kind(Kind), Data(Data), FD(FD) {}
90 MemberInfo(CharUnits Offset, InfoKind Kind, llvm::Type *Data,
91 const CXXRecordDecl *RD)
92 : Offset(Offset), Kind(Kind), Data(Data), RD(RD) {}
93 // MemberInfos are sorted so we define a < operator.
94 bool operator <(const MemberInfo& a) const { return Offset < a.Offset; }
95 };
96 // The constructor.
97 CGRecordLowering(CodeGenTypes &Types, const RecordDecl *D, bool Packed);
98 // Short helper routines.
99 /// Constructs a MemberInfo instance from an offset and llvm::Type *.
100 static MemberInfo StorageInfo(CharUnits Offset, llvm::Type *Data) {
101 return MemberInfo(Offset, MemberInfo::Field, Data);
102 }
103
104 /// Helper function to check if the target machine is BigEndian.
105 bool isBE() const { return Context.getTargetInfo().isBigEndian(); }
106
107 /// Wraps llvm::Type::getIntNTy with some implicit arguments.
108 llvm::Type *getIntNType(uint64_t NumBits) const {
109 unsigned AlignedBits = llvm::alignTo(NumBits, Context.getCharWidth());
110 return llvm::Type::getIntNTy(Types.getLLVMContext(), AlignedBits);
111 }
112 /// Get the LLVM type sized as one character unit.
113 llvm::Type *getCharType() const {
114 return llvm::Type::getIntNTy(Types.getLLVMContext(),
115 Context.getCharWidth());
116 }
117 /// Gets an llvm type of size NumChars and alignment 1.
118 llvm::Type *getByteArrayType(CharUnits NumChars) const {
119 assert(!NumChars.isZero() && "Empty byte arrays aren't allowed.");
120 llvm::Type *Type = getCharType();
121 return NumChars == CharUnits::One() ? Type :
122 (llvm::Type *)llvm::ArrayType::get(Type, NumChars.getQuantity());
123 }
124 /// Gets the storage type for a field decl and handles storage
125 /// for itanium bitfields that are smaller than their declared type.
126 llvm::Type *getStorageType(const FieldDecl *FD) const {
127 llvm::Type *Type = Types.ConvertTypeForMem(FD->getType());
128 if (!FD->isBitField()) return Type;
130 return Type;
131 return getIntNType(std::min(FD->getBitWidthValue(),
132 (unsigned)Context.toBits(getSize(Type))));
133 }
134 /// Gets the llvm Basesubobject type from a CXXRecordDecl.
135 llvm::Type *getStorageType(const CXXRecordDecl *RD) const {
136 return Types.getCGRecordLayout(RD).getBaseSubobjectLLVMType();
137 }
138 CharUnits bitsToCharUnits(uint64_t BitOffset) const {
139 return Context.toCharUnitsFromBits(BitOffset);
140 }
141 CharUnits getSize(llvm::Type *Type) const {
142 return CharUnits::fromQuantity(DataLayout.getTypeAllocSize(Type));
143 }
144 CharUnits getAlignment(llvm::Type *Type) const {
145 return CharUnits::fromQuantity(DataLayout.getABITypeAlign(Type));
146 }
147 bool isZeroInitializable(const FieldDecl *FD) const {
148 return Types.isZeroInitializable(FD->getType());
149 }
150 bool isZeroInitializable(const RecordDecl *RD) const {
151 return Types.isZeroInitializable(RD);
152 }
153 void appendPaddingBytes(CharUnits Size) {
154 if (!Size.isZero())
155 FieldTypes.push_back(getByteArrayType(Size));
156 }
157 uint64_t getFieldBitOffset(const FieldDecl *FD) const {
158 return Layout.getFieldOffset(FD->getFieldIndex());
159 }
160 // Layout routines.
161 void setBitFieldInfo(const FieldDecl *FD, CharUnits StartOffset,
162 llvm::Type *StorageType);
163 /// Lowers an ASTRecordLayout to a llvm type.
164 void lower(bool NonVirtualBaseType);
165 void lowerUnion(bool isNonVirtualBaseType);
166 void accumulateFields(bool isNonVirtualBaseType);
168 accumulateBitFields(bool isNonVirtualBaseType,
171 void computeVolatileBitfields();
172 void accumulateBases();
173 void accumulateVPtrs();
174 void accumulateVBases();
175 void calculateZeroInit();
176 CharUnits calculateTailClippingOffset(bool isNonVirtualBaseType) const;
177 void checkBitfieldClipping(bool isNonVirtualBaseType) const;
178 /// Determines if we need a packed llvm struct.
179 void determinePacked(bool NVBaseType);
180 /// Inserts padding everywhere it's needed.
181 void insertPadding();
182 /// Fills out the structures that are ultimately consumed.
183 void fillOutputFields();
184 // Input memoization fields.
185 CodeGenTypes &Types;
186 const ASTContext &Context;
187 const RecordDecl *D;
188 const CXXRecordDecl *RD;
189 const ASTRecordLayout &Layout;
190 const llvm::DataLayout &DataLayout;
191 // Helpful intermediate data-structures.
192 std::vector<MemberInfo> Members;
193 // Output fields, consumed by CodeGenTypes::ComputeRecordLayout.
194 SmallVector<llvm::Type *, 16> FieldTypes;
195 llvm::DenseMap<const FieldDecl *, unsigned> Fields;
196 llvm::DenseMap<const FieldDecl *, CGBitFieldInfo> BitFields;
197 llvm::DenseMap<const CXXRecordDecl *, unsigned> NonVirtualBases;
198 llvm::DenseMap<const CXXRecordDecl *, unsigned> VirtualBases;
199 bool IsZeroInitializable : 1;
200 bool IsZeroInitializableAsBase : 1;
201 bool Packed : 1;
202private:
203 CGRecordLowering(const CGRecordLowering &) = delete;
204 void operator =(const CGRecordLowering &) = delete;
205};
206} // namespace {
207
208CGRecordLowering::CGRecordLowering(CodeGenTypes &Types, const RecordDecl *D,
209 bool Packed)
210 : Types(Types), Context(Types.getContext()), D(D),
211 RD(dyn_cast<CXXRecordDecl>(D)),
212 Layout(Types.getContext().getASTRecordLayout(D)),
213 DataLayout(Types.getDataLayout()), IsZeroInitializable(true),
214 IsZeroInitializableAsBase(true), Packed(Packed) {}
215
216void CGRecordLowering::setBitFieldInfo(
217 const FieldDecl *FD, CharUnits StartOffset, llvm::Type *StorageType) {
218 uint64_t Offset = getFieldBitOffset(FD) - Context.toBits(StartOffset);
219 uint64_t StorageSize =
220 DataLayout.getTypeAllocSizeInBits(StorageType).getFixedValue();
221 // CGBitFieldInfo::MakeInfo does the same clamp
222 llvm::Type *FieldType = Types.ConvertTypeForMem(FD->getType());
223 uint64_t Size =
224 std::min({uint64_t(FD->getBitWidthValue()), StorageSize,
225 DataLayout.getTypeAllocSizeInBits(FieldType).getFixedValue()});
226 // Reverse the bit offsets for big endian machines. Because we represent
227 // a bitfield as a single large integer load, we can imagine the bits
228 // counting from the most-significant-bit instead of the
229 // least-significant-bit.
230 if (DataLayout.isBigEndian())
231 Offset = StorageSize - (Offset + Size);
232
233 BitFields[FD->getCanonicalDecl()] = CGBitFieldInfo(
234 Offset, Size, FD->getType()->isSignedIntegerOrEnumerationType(),
235 StorageSize, StartOffset);
236}
237
238void CGRecordLowering::lower(bool NVBaseType) {
239 // The lowering process implemented in this function takes a variety of
240 // carefully ordered phases.
241 // 1) Store all members (fields and bases) in a list and sort them by offset.
242 // 2) Add a 1-byte capstone member at the Size of the structure.
243 // 3) Clip bitfield storages members if their tail padding is or might be
244 // used by another field or base. The clipping process uses the capstone
245 // by treating it as another object that occurs after the record.
246 // 4) Determine if the llvm-struct requires packing. It's important that this
247 // phase occur after clipping, because clipping changes the llvm type.
248 // This phase reads the offset of the capstone when determining packedness
249 // and updates the alignment of the capstone to be equal of the alignment
250 // of the record after doing so.
251 // 5) Insert padding everywhere it is needed. This phase requires 'Packed' to
252 // have been computed and needs to know the alignment of the record in
253 // order to understand if explicit tail padding is needed.
254 // 6) Remove the capstone, we don't need it anymore.
255 // 7) Determine if this record can be zero-initialized. This phase could have
256 // been placed anywhere after phase 1.
257 // 8) Format the complete list of members in a way that can be consumed by
258 // CodeGenTypes::ComputeRecordLayout.
259 CharUnits Size = NVBaseType ? Layout.getNonVirtualSize() : Layout.getSize();
260 if (D->isUnion()) {
261 lowerUnion(NVBaseType);
262 computeVolatileBitfields();
263 return;
264 }
265 accumulateFields(NVBaseType);
266 // RD implies C++.
267 if (RD) {
268 accumulateVPtrs();
269 accumulateBases();
270 if (Members.empty()) {
271 appendPaddingBytes(Size);
272 computeVolatileBitfields();
273 return;
274 }
275 if (!NVBaseType)
276 accumulateVBases();
277 }
278 llvm::stable_sort(Members);
279 checkBitfieldClipping(NVBaseType);
280 Members.push_back(StorageInfo(Size, getIntNType(8)));
281 determinePacked(NVBaseType);
282 insertPadding();
283 Members.pop_back();
284 calculateZeroInit();
285 fillOutputFields();
286 computeVolatileBitfields();
287}
288
289void CGRecordLowering::lowerUnion(bool isNonVirtualBaseType) {
290 CharUnits LayoutSize =
291 isNonVirtualBaseType ? Layout.getDataSize() : Layout.getSize();
292 llvm::Type *StorageType = nullptr;
293 bool SeenNamedMember = false;
294 // Iterate through the fields setting bitFieldInfo and the Fields array. Also
295 // locate the "most appropriate" storage type. The heuristic for finding the
296 // storage type isn't necessary, the first (non-0-length-bitfield) field's
297 // type would work fine and be simpler but would be different than what we've
298 // been doing and cause lit tests to change.
299 for (const auto *Field : D->fields()) {
300 if (Field->isBitField()) {
301 if (Field->isZeroLengthBitField())
302 continue;
303 llvm::Type *FieldType = getStorageType(Field);
304 if (LayoutSize < getSize(FieldType))
305 FieldType = getByteArrayType(LayoutSize);
306 setBitFieldInfo(Field, CharUnits::Zero(), FieldType);
307 }
308 Fields[Field->getCanonicalDecl()] = 0;
309 llvm::Type *FieldType = getStorageType(Field);
310 // Compute zero-initializable status.
311 // This union might not be zero initialized: it may contain a pointer to
312 // data member which might have some exotic initialization sequence.
313 // If this is the case, then we aught not to try and come up with a "better"
314 // type, it might not be very easy to come up with a Constant which
315 // correctly initializes it.
316 if (!SeenNamedMember) {
317 SeenNamedMember = Field->getIdentifier();
318 if (!SeenNamedMember)
319 if (const auto *FieldRD = Field->getType()->getAsRecordDecl())
320 SeenNamedMember = FieldRD->findFirstNamedDataMember();
321 if (SeenNamedMember && !isZeroInitializable(Field)) {
322 IsZeroInitializable = IsZeroInitializableAsBase = false;
323 StorageType = FieldType;
324 }
325 }
326 // Because our union isn't zero initializable, we won't be getting a better
327 // storage type.
328 if (!IsZeroInitializable)
329 continue;
330 // Conditionally update our storage type if we've got a new "better" one.
331 if (!StorageType ||
332 getAlignment(FieldType) > getAlignment(StorageType) ||
333 (getAlignment(FieldType) == getAlignment(StorageType) &&
334 getSize(FieldType) > getSize(StorageType)))
335 StorageType = FieldType;
336 }
337 // If we have no storage type just pad to the appropriate size and return.
338 if (!StorageType)
339 return appendPaddingBytes(LayoutSize);
340 // If our storage size was bigger than our required size (can happen in the
341 // case of packed bitfields on Itanium) then just use an I8 array.
342 if (LayoutSize < getSize(StorageType))
343 StorageType = getByteArrayType(LayoutSize);
344 FieldTypes.push_back(StorageType);
345 appendPaddingBytes(LayoutSize - getSize(StorageType));
346 // Set packed if we need it.
347 const auto StorageAlignment = getAlignment(StorageType);
348 assert((Layout.getSize().isMultipleOf(StorageAlignment) ||
349 !Layout.getDataSize().isMultipleOf(StorageAlignment)) &&
350 "Union's standard layout and no_unique_address layout must agree on "
351 "packedness");
352 if (!Layout.getDataSize().isMultipleOf(StorageAlignment))
353 Packed = true;
354}
355
356void CGRecordLowering::accumulateFields(bool isNonVirtualBaseType) {
357 for (RecordDecl::field_iterator Field = D->field_begin(),
358 FieldEnd = D->field_end();
359 Field != FieldEnd;) {
360 if (Field->isBitField()) {
361 Field = accumulateBitFields(isNonVirtualBaseType, Field, FieldEnd);
362 assert((Field == FieldEnd || !Field->isBitField()) &&
363 "Failed to accumulate all the bitfields");
364 } else if (CodeGenUtils::isEmptyFieldForLayout(Context, *Field)) {
365 // Empty fields have no storage.
366 ++Field;
367 } else {
368 // Use base subobject layout for the potentially-overlapping field,
369 // as it is done in RecordLayoutBuilder
370 Members.push_back(MemberInfo(
371 bitsToCharUnits(getFieldBitOffset(*Field)), MemberInfo::Field,
372 Field->isPotentiallyOverlapping()
373 ? getStorageType(Field->getType()->getAsCXXRecordDecl())
374 : getStorageType(*Field),
375 *Field));
376 ++Field;
377 }
378 }
379}
380
381// Create members for bitfields. Field is a bitfield, and FieldEnd is the end
382// iterator of the record. Return the first non-bitfield encountered. We need
383// to know whether this is the base or complete layout, as virtual bases could
384// affect the upper bound of bitfield access unit allocation.
386CGRecordLowering::accumulateBitFields(bool isNonVirtualBaseType,
389 if (CodeGenUtils::isDiscreteBitFieldABI(Context, D)) {
390 // Run stores the first element of the current run of bitfields. FieldEnd is
391 // used as a special value to note that we don't have a current run. A
392 // bitfield run is a contiguous collection of bitfields that can be stored
393 // in the same storage block. Zero-sized bitfields and bitfields that would
394 // cross an alignment boundary break a run and start a new one.
395 RecordDecl::field_iterator Run = FieldEnd;
396 // Tail is the offset of the first bit off the end of the current run. It's
397 // used to determine if the ASTRecordLayout is treating these two bitfields
398 // as contiguous. StartBitOffset is offset of the beginning of the Run.
399 uint64_t StartBitOffset, Tail = 0;
400 for (; Field != FieldEnd && Field->isBitField(); ++Field) {
401 // Zero-width bitfields end runs.
402 if (Field->isZeroLengthBitField()) {
403 Run = FieldEnd;
404 continue;
405 }
406 uint64_t BitOffset = getFieldBitOffset(*Field);
407 llvm::Type *Type = Types.ConvertTypeForMem(Field->getType());
408 // If we don't have a run yet, or don't live within the previous run's
409 // allocated storage then we allocate some storage and start a new run.
410 if (Run == FieldEnd || BitOffset >= Tail) {
411 Run = Field;
412 StartBitOffset = BitOffset;
413 Tail = StartBitOffset + DataLayout.getTypeAllocSizeInBits(Type);
414 // Add the storage member to the record. This must be added to the
415 // record before the bitfield members so that it gets laid out before
416 // the bitfields it contains get laid out.
417 Members.push_back(StorageInfo(bitsToCharUnits(StartBitOffset), Type));
418 }
419 // Bitfields get the offset of their storage but come afterward and remain
420 // there after a stable sort.
421 Members.push_back(MemberInfo(bitsToCharUnits(StartBitOffset),
422 MemberInfo::Field, nullptr, *Field));
423 }
424 return Field;
425 }
426
427 // The SysV ABI can overlap bitfield storage units with both other bitfield
428 // storage units /and/ other non-bitfield data members. Accessing a sequence
429 // of bitfields mustn't interfere with adjacent non-bitfields -- they're
430 // permitted to be accessed in separate threads for instance.
431
432 // We split runs of bit-fields into a sequence of "access units". When we emit
433 // a load or store of a bit-field, we'll load/store the entire containing
434 // access unit. As mentioned, the standard requires that these loads and
435 // stores must not interfere with accesses to other memory locations, and it
436 // defines the bit-field's memory location as the current run of
437 // non-zero-width bit-fields. So an access unit must never overlap with
438 // non-bit-field storage or cross a zero-width bit-field. Otherwise, we're
439 // free to draw the lines as we see fit.
440
441 // Drawing these lines well can be complicated. LLVM generally can't modify a
442 // program to access memory that it didn't before, so using very narrow access
443 // units can prevent the compiler from using optimal access patterns. For
444 // example, suppose a run of bit-fields occupies four bytes in a struct. If we
445 // split that into four 1-byte access units, then a sequence of assignments
446 // that doesn't touch all four bytes may have to be emitted with multiple
447 // 8-bit stores instead of a single 32-bit store. On the other hand, if we use
448 // very wide access units, we may find ourselves emitting accesses to
449 // bit-fields we didn't really need to touch, just because LLVM was unable to
450 // clean up after us.
451
452 // It is desirable to have access units be aligned powers of 2 no larger than
453 // a register. (On non-strict alignment ISAs, the alignment requirement can be
454 // dropped.) A three byte access unit will be accessed using 2-byte and 1-byte
455 // accesses and bit manipulation. If no bitfield straddles across the two
456 // separate accesses, it is better to have separate 2-byte and 1-byte access
457 // units, as then LLVM will not generate unnecessary memory accesses, or bit
458 // manipulation. Similarly, on a strict-alignment architecture, it is better
459 // to keep access-units naturally aligned, to avoid similar bit
460 // manipulation synthesizing larger unaligned accesses.
461
462 // Bitfields that share parts of a single byte are, of necessity, placed in
463 // the same access unit. That unit will encompass a consecutive run where
464 // adjacent bitfields share parts of a byte. (The first bitfield of such an
465 // access unit will start at the beginning of a byte.)
466
467 // We then try and accumulate adjacent access units when the combined unit is
468 // naturally sized, no larger than a register, and (on a strict alignment
469 // ISA), naturally aligned. Note that this requires lookahead to one or more
470 // subsequent access units. For instance, consider a 2-byte access-unit
471 // followed by 2 1-byte units. We can merge that into a 4-byte access-unit,
472 // but we would not want to merge a 2-byte followed by a single 1-byte (and no
473 // available tail padding). We keep track of the best access unit seen so far,
474 // and use that when we determine we cannot accumulate any more. Then we start
475 // again at the bitfield following that best one.
476
477 // The accumulation is also prevented when:
478 // *) it would cross a character-aigned zero-width bitfield, or
479 // *) fine-grained bitfield access option is in effect.
480
481 CharUnits RegSize =
482 bitsToCharUnits(Context.getTargetInfo().getRegisterWidth());
483 unsigned CharBits = Context.getCharWidth();
484
485 // Limit of useable tail padding at end of the record. Computed lazily and
486 // cached here.
487 CharUnits ScissorOffset = CharUnits::Zero();
488
489 // Data about the start of the span we're accumulating to create an access
490 // unit from. Begin is the first bitfield of the span. If Begin is FieldEnd,
491 // we've not got a current span. The span starts at the BeginOffset character
492 // boundary. BitSizeSinceBegin is the size (in bits) of the span -- this might
493 // include padding when we've advanced to a subsequent bitfield run.
494 RecordDecl::field_iterator Begin = FieldEnd;
495 CharUnits BeginOffset;
496 uint64_t BitSizeSinceBegin;
497
498 // The (non-inclusive) end of the largest acceptable access unit we've found
499 // since Begin. If this is Begin, we're gathering the initial set of bitfields
500 // of a new span. BestEndOffset is the end of that acceptable access unit --
501 // it might extend beyond the last character of the bitfield run, using
502 // available padding characters.
503 RecordDecl::field_iterator BestEnd = Begin;
504 CharUnits BestEndOffset;
505 bool BestClipped; // Whether the representation must be in a byte array.
506
507 for (;;) {
508 // AtAlignedBoundary is true iff Field is the (potential) start of a new
509 // span (or the end of the bitfields). When true, LimitOffset is the
510 // character offset of that span and Barrier indicates whether the new
511 // span cannot be merged into the current one.
512 bool AtAlignedBoundary = false;
513 bool Barrier = false;
514
515 if (Field != FieldEnd && Field->isBitField()) {
516 uint64_t BitOffset = getFieldBitOffset(*Field);
517 if (Begin == FieldEnd) {
518 // Beginning a new span.
519 Begin = Field;
520 BestEnd = Begin;
521
522 assert((BitOffset % CharBits) == 0 && "Not at start of char");
523 BeginOffset = bitsToCharUnits(BitOffset);
524 BitSizeSinceBegin = 0;
525 } else if ((BitOffset % CharBits) != 0) {
526 // Bitfield occupies the same character as previous bitfield, it must be
527 // part of the same span. This can include zero-length bitfields, should
528 // the target not align them to character boundaries. Such non-alignment
529 // is at variance with the standards, which require zero-length
530 // bitfields be a barrier between access units. But of course we can't
531 // achieve that in the middle of a character.
532 assert(BitOffset == Context.toBits(BeginOffset) + BitSizeSinceBegin &&
533 "Concatenating non-contiguous bitfields");
534 } else {
535 // Bitfield potentially begins a new span. This includes zero-length
536 // bitfields on non-aligning targets that lie at character boundaries
537 // (those are barriers to merging).
538 if (Field->isZeroLengthBitField())
539 Barrier = true;
540 AtAlignedBoundary = true;
541 }
542 } else {
543 // We've reached the end of the bitfield run. Either we're done, or this
544 // is a barrier for the current span.
545 if (Begin == FieldEnd)
546 break;
547
548 Barrier = true;
549 AtAlignedBoundary = true;
550 }
551
552 // InstallBest indicates whether we should create an access unit for the
553 // current best span: fields [Begin, BestEnd) occupying characters
554 // [BeginOffset, BestEndOffset).
555 bool InstallBest = false;
556 if (AtAlignedBoundary) {
557 // Field is the start of a new span or the end of the bitfields. The
558 // just-seen span now extends to BitSizeSinceBegin.
559
560 // Determine if we can accumulate that just-seen span into the current
561 // accumulation.
562 CharUnits AccessSize = bitsToCharUnits(BitSizeSinceBegin + CharBits - 1);
563 if (BestEnd == Begin) {
564 // This is the initial run at the start of a new span. By definition,
565 // this is the best seen so far.
566 BestEnd = Field;
567 BestEndOffset = BeginOffset + AccessSize;
568 // Assume clipped until proven not below.
569 BestClipped = true;
570 if (!BitSizeSinceBegin)
571 // A zero-sized initial span -- this will install nothing and reset
572 // for another.
573 InstallBest = true;
574 } else if (AccessSize > RegSize)
575 // Accumulating the just-seen span would create a multi-register access
576 // unit, which would increase register pressure.
577 InstallBest = true;
578
579 if (!InstallBest) {
580 // Determine if accumulating the just-seen span will create an expensive
581 // access unit or not.
582 llvm::Type *Type = getIntNType(Context.toBits(AccessSize));
584 // Unaligned accesses are expensive. Only accumulate if the new unit
585 // is naturally aligned. Otherwise install the best we have, which is
586 // either the initial access unit (can't do better), or a naturally
587 // aligned accumulation (since we would have already installed it if
588 // it wasn't naturally aligned).
589 CharUnits Align = getAlignment(Type);
590 if (Align > Layout.getAlignment())
591 // The alignment required is greater than the containing structure
592 // itself.
593 InstallBest = true;
594 else if (!BeginOffset.isMultipleOf(Align))
595 // The access unit is not at a naturally aligned offset within the
596 // structure.
597 InstallBest = true;
598
599 if (InstallBest && BestEnd == Field)
600 // We're installing the first span, whose clipping was presumed
601 // above. Compute it correctly.
602 if (getSize(Type) == AccessSize)
603 BestClipped = false;
604 }
605
606 if (!InstallBest) {
607 // Find the next used storage offset to determine what the limit of
608 // the current span is. That's either the offset of the next field
609 // with storage (which might be Field itself) or the end of the
610 // non-reusable tail padding.
611 CharUnits LimitOffset;
612 for (auto Probe = Field; Probe != FieldEnd; ++Probe)
613 if (!CodeGenUtils::isEmptyFieldForLayout(Context, *Probe)) {
614 // A member with storage sets the limit.
615 assert((getFieldBitOffset(*Probe) % CharBits) == 0 &&
616 "Next storage is not byte-aligned");
617 LimitOffset = bitsToCharUnits(getFieldBitOffset(*Probe));
618 goto FoundLimit;
619 }
620 // We reached the end of the fields, determine the bounds of useable
621 // tail padding. As this can be complex for C++, we cache the result.
622 if (ScissorOffset.isZero()) {
623 ScissorOffset = calculateTailClippingOffset(isNonVirtualBaseType);
624 assert(!ScissorOffset.isZero() && "Tail clipping at zero");
625 }
626
627 LimitOffset = ScissorOffset;
628 FoundLimit:;
629
630 CharUnits TypeSize = getSize(Type);
631 if (BeginOffset + TypeSize <= LimitOffset) {
632 // There is space before LimitOffset to create a naturally-sized
633 // access unit.
634 BestEndOffset = BeginOffset + TypeSize;
635 BestEnd = Field;
636 BestClipped = false;
637 }
638
639 if (Barrier)
640 // The next field is a barrier that we cannot merge across.
641 InstallBest = true;
642 else if (Types.getCodeGenOpts().FineGrainedBitfieldAccesses)
643 // Fine-grained access, so no merging of spans.
644 InstallBest = true;
645 else
646 // Otherwise, we're not installing. Update the bit size
647 // of the current span to go all the way to LimitOffset, which is
648 // the (aligned) offset of next bitfield to consider.
649 BitSizeSinceBegin = Context.toBits(LimitOffset - BeginOffset);
650 }
651 }
652 }
653
654 if (InstallBest) {
655 assert((Field == FieldEnd || !Field->isBitField() ||
656 (getFieldBitOffset(*Field) % CharBits) == 0) &&
657 "Installing but not at an aligned bitfield or limit");
658 CharUnits AccessSize = BestEndOffset - BeginOffset;
659 if (!AccessSize.isZero()) {
660 // Add the storage member for the access unit to the record. The
661 // bitfields get the offset of their storage but come afterward and
662 // remain there after a stable sort.
663 llvm::Type *Type;
664 if (BestClipped) {
665 assert(getSize(getIntNType(Context.toBits(AccessSize))) >
666 AccessSize &&
667 "Clipped access need not be clipped");
668 Type = getByteArrayType(AccessSize);
669 } else {
670 Type = getIntNType(Context.toBits(AccessSize));
671 assert(getSize(Type) == AccessSize &&
672 "Unclipped access must be clipped");
673 }
674 Members.push_back(StorageInfo(BeginOffset, Type));
675 for (; Begin != BestEnd; ++Begin)
676 if (!Begin->isZeroLengthBitField())
677 Members.push_back(
678 MemberInfo(BeginOffset, MemberInfo::Field, nullptr, *Begin));
679 }
680 // Reset to start a new span.
681 Field = BestEnd;
682 Begin = FieldEnd;
683 } else {
684 assert(Field != FieldEnd && Field->isBitField() &&
685 "Accumulating past end of bitfields");
686 assert(!Barrier && "Accumulating across barrier");
687 // Accumulate this bitfield into the current (potential) span.
688 BitSizeSinceBegin += Field->getBitWidthValue();
689 ++Field;
690 }
691 }
692
693 return Field;
694}
695
696void CGRecordLowering::accumulateBases() {
697 // If we've got a primary virtual base, we need to add it with the bases.
698 if (Layout.isPrimaryBaseVirtual()) {
699 const CXXRecordDecl *BaseDecl = Layout.getPrimaryBase();
700 Members.push_back(MemberInfo(CharUnits::Zero(), MemberInfo::Base,
701 getStorageType(BaseDecl), BaseDecl));
702 }
703 // Accumulate the non-virtual bases.
704 for (const auto &Base : RD->bases()) {
705 if (Base.isVirtual())
706 continue;
707
708 // Bases can be zero-sized even if not technically empty if they
709 // contain only a trailing array member.
710 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
711 if (!CodeGenUtils::isEmptyRecordForLayout(Context, Base.getType()) &&
712 !Context.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
713 Members.push_back(MemberInfo(Layout.getBaseClassOffset(BaseDecl),
714 MemberInfo::Base, getStorageType(BaseDecl), BaseDecl));
715 }
716}
717
718/// The AAPCS that defines that, when possible, bit-fields should
719/// be accessed using containers of the declared type width:
720/// When a volatile bit-field is read, and its container does not overlap with
721/// any non-bit-field member or any zero length bit-field member, its container
722/// must be read exactly once using the access width appropriate to the type of
723/// the container. When a volatile bit-field is written, and its container does
724/// not overlap with any non-bit-field member or any zero-length bit-field
725/// member, its container must be read exactly once and written exactly once
726/// using the access width appropriate to the type of the container. The two
727/// accesses are not atomic.
728///
729/// Enforcing the width restriction can be disabled using
730/// -fno-aapcs-bitfield-width.
731void CGRecordLowering::computeVolatileBitfields() {
732 if (!CodeGenUtils::isAAPCS(Context.getTargetInfo()) ||
733 !Types.getCodeGenOpts().AAPCSBitfieldWidth)
734 return;
735
736 for (auto &I : BitFields) {
737 const FieldDecl *Field = I.first;
738 CGBitFieldInfo &Info = I.second;
739 llvm::Type *ResLTy = Types.ConvertTypeForMem(Field->getType());
740 // If the record alignment is less than the type width, we can't enforce a
741 // aligned load, bail out.
742 if ((uint64_t)(Context.toBits(Layout.getAlignment())) <
743 ResLTy->getPrimitiveSizeInBits())
744 continue;
745 // CGRecordLowering::setBitFieldInfo() pre-adjusts the bit-field offsets
746 // for big-endian targets, but it assumes a container of width
747 // Info.StorageSize. Since AAPCS uses a different container size (width
748 // of the type), we first undo that calculation here and redo it once
749 // the bit-field offset within the new container is calculated.
750 const unsigned OldOffset =
751 isBE() ? Info.StorageSize - (Info.Offset + Info.Size) : Info.Offset;
752 // Offset to the bit-field from the beginning of the struct.
753 const unsigned AbsoluteOffset =
754 Context.toBits(Info.StorageOffset) + OldOffset;
755
756 // Container size is the width of the bit-field type.
757 const unsigned StorageSize = ResLTy->getPrimitiveSizeInBits();
758 // Nothing to do if the access uses the desired
759 // container width and is naturally aligned.
760 if (Info.StorageSize == StorageSize && (OldOffset % StorageSize == 0))
761 continue;
762
763 // Offset within the container.
764 unsigned Offset = AbsoluteOffset & (StorageSize - 1);
765 // Bail out if an aligned load of the container cannot cover the entire
766 // bit-field. This can happen for example, if the bit-field is part of a
767 // packed struct. AAPCS does not define access rules for such cases, we let
768 // clang to follow its own rules.
769 if (Offset + Info.Size > StorageSize)
770 continue;
771
772 // Re-adjust offsets for big-endian targets.
773 if (isBE())
774 Offset = StorageSize - (Offset + Info.Size);
775
776 const CharUnits StorageOffset =
777 Context.toCharUnitsFromBits(AbsoluteOffset & ~(StorageSize - 1));
778 const CharUnits End = StorageOffset +
779 Context.toCharUnitsFromBits(StorageSize) -
781
782 const ASTRecordLayout &Layout =
783 Context.getASTRecordLayout(Field->getParent());
784 // If we access outside memory outside the record, than bail out.
785 const CharUnits RecordSize = Layout.getSize();
786 if (End >= RecordSize)
787 continue;
788
789 // Bail out if performing this load would access non-bit-fields members.
790 bool Conflict = false;
791 for (const auto *F : D->fields()) {
792 // Allow sized bit-fields overlaps.
793 if (F->isBitField() && !F->isZeroLengthBitField())
794 continue;
795
796 const CharUnits FOffset = Context.toCharUnitsFromBits(
797 Layout.getFieldOffset(F->getFieldIndex()));
798
799 // As C11 defines, a zero sized bit-field defines a barrier, so
800 // fields after and before it should be race condition free.
801 // The AAPCS acknowledges it and imposes no restritions when the
802 // natural container overlaps a zero-length bit-field.
803 if (F->isZeroLengthBitField()) {
804 if (End > FOffset && StorageOffset < FOffset) {
805 Conflict = true;
806 break;
807 }
808 }
809
810 const CharUnits FEnd =
811 FOffset +
812 Context.toCharUnitsFromBits(
813 Types.ConvertTypeForMem(F->getType())->getPrimitiveSizeInBits()) -
815 // If no overlap, continue.
816 if (End < FOffset || FEnd < StorageOffset)
817 continue;
818
819 // The desired load overlaps a non-bit-field member, bail out.
820 Conflict = true;
821 break;
822 }
823
824 if (Conflict)
825 continue;
826 // Write the new bit-field access parameters.
827 // As the storage offset now is defined as the number of elements from the
828 // start of the structure, we should divide the Offset by the element size.
830 StorageOffset / Context.toCharUnitsFromBits(StorageSize).getQuantity();
831 Info.VolatileStorageSize = StorageSize;
832 Info.VolatileOffset = Offset;
833 }
834}
835
836void CGRecordLowering::accumulateVPtrs() {
837 llvm::Type *VPtrTy = Types.getCGM().GlobalsInt8PtrTy;
838 if (Layout.hasOwnVFPtr())
839 Members.push_back(MemberInfo(CharUnits::Zero(), MemberInfo::VFPtr, VPtrTy));
840 if (Layout.hasOwnVBPtr())
841 Members.push_back(
842 MemberInfo(Layout.getVBPtrOffset(), MemberInfo::VBPtr, VPtrTy));
843}
844
845CharUnits
846CGRecordLowering::calculateTailClippingOffset(bool isNonVirtualBaseType) const {
847 if (!RD)
848 return Layout.getDataSize();
849
850 CharUnits ScissorOffset = Layout.getNonVirtualSize();
851 // In the itanium ABI, it's possible to place a vbase at a dsize that is
852 // smaller than the nvsize. Here we check to see if such a base is placed
853 // before the nvsize and set the scissor offset to that, instead of the
854 // nvsize.
855 if (!isNonVirtualBaseType && CodeGenUtils::isOverlappingVBaseABI(Context))
856 for (const auto &Base : RD->vbases()) {
857 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
858 if (CodeGenUtils::isEmptyRecordForLayout(Context, Base.getType()))
859 continue;
860 // If the vbase is a primary virtual base of some base, then it doesn't
861 // get its own storage location but instead lives inside of that base.
862 if (Context.isNearlyEmpty(BaseDecl) &&
863 !CodeGenUtils::hasOwnStorage(Context, RD, BaseDecl))
864 continue;
865 ScissorOffset = std::min(ScissorOffset,
866 Layout.getVBaseClassOffset(BaseDecl));
867 }
868
869 return ScissorOffset;
870}
871
872void CGRecordLowering::accumulateVBases() {
873 for (const auto &Base : RD->vbases()) {
874 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
875 if (CodeGenUtils::isEmptyRecordForLayout(Context, Base.getType()))
876 continue;
877 CharUnits Offset = Layout.getVBaseClassOffset(BaseDecl);
878 // If the vbase is a primary virtual base of some base, then it doesn't
879 // get its own storage location but instead lives inside of that base.
881 Context.isNearlyEmpty(BaseDecl) &&
882 !CodeGenUtils::hasOwnStorage(Context, RD, BaseDecl)) {
883 Members.push_back(MemberInfo(Offset, MemberInfo::VBase, nullptr,
884 BaseDecl));
885 continue;
886 }
887 // If we've got a vtordisp, add it as a storage type.
888 if (Layout.getVBaseOffsetsMap().find(BaseDecl)->second.hasVtorDisp())
889 Members.push_back(StorageInfo(Offset - CharUnits::fromQuantity(4),
890 getIntNType(32)));
891 Members.push_back(MemberInfo(Offset, MemberInfo::VBase,
892 getStorageType(BaseDecl), BaseDecl));
893 }
894}
895
896void CGRecordLowering::calculateZeroInit() {
897 for (std::vector<MemberInfo>::const_iterator Member = Members.begin(),
898 MemberEnd = Members.end();
899 IsZeroInitializableAsBase && Member != MemberEnd; ++Member) {
900 if (Member->Kind == MemberInfo::Field) {
901 if (!Member->FD || isZeroInitializable(Member->FD))
902 continue;
903 IsZeroInitializable = IsZeroInitializableAsBase = false;
904 } else if (Member->Kind == MemberInfo::Base ||
905 Member->Kind == MemberInfo::VBase) {
906 if (isZeroInitializable(Member->RD))
907 continue;
908 IsZeroInitializable = false;
909 if (Member->Kind == MemberInfo::Base)
910 IsZeroInitializableAsBase = false;
911 }
912 }
913}
914
915// Verify accumulateBitfields computed the correct storage representations.
916void CGRecordLowering::checkBitfieldClipping(bool IsNonVirtualBaseType) const {
917#ifndef NDEBUG
918 auto ScissorOffset = calculateTailClippingOffset(IsNonVirtualBaseType);
919 auto Tail = CharUnits::Zero();
920 for (const auto &M : Members) {
921 // Only members with data could possibly overlap.
922 if (!M.Data)
923 continue;
924
925 assert(M.Offset >= Tail && "Bitfield access unit is not clipped");
926 Tail = M.Offset + getSize(M.Data);
927 assert((Tail <= ScissorOffset || M.Offset >= ScissorOffset) &&
928 "Bitfield straddles scissor offset");
929 }
930#endif
931}
932
933void CGRecordLowering::determinePacked(bool NVBaseType) {
934 if (Packed)
935 return;
936 CharUnits Alignment = CharUnits::One();
937 CharUnits NVAlignment = CharUnits::One();
938 CharUnits NVSize =
939 !NVBaseType && RD ? Layout.getNonVirtualSize() : CharUnits::Zero();
940 for (const MemberInfo &Member : Members) {
941 if (!Member.Data)
942 continue;
943 // If any member falls at an offset that it not a multiple of its alignment,
944 // then the entire record must be packed.
945 if (!Member.Offset.isMultipleOf(getAlignment(Member.Data)))
946 Packed = true;
947 if (Member.Offset < NVSize)
948 NVAlignment = std::max(NVAlignment, getAlignment(Member.Data));
949 Alignment = std::max(Alignment, getAlignment(Member.Data));
950 }
951 // If the size of the record (the capstone's offset) is not a multiple of the
952 // record's alignment, it must be packed.
953 if (!Members.back().Offset.isMultipleOf(Alignment))
954 Packed = true;
955 // If the non-virtual sub-object is not a multiple of the non-virtual
956 // sub-object's alignment, it must be packed. We cannot have a packed
957 // non-virtual sub-object and an unpacked complete object or vise versa.
958 if (!NVSize.isMultipleOf(NVAlignment))
959 Packed = true;
960 // Update the alignment of the sentinel.
961 if (!Packed)
962 Members.back().Data = getIntNType(Context.toBits(Alignment));
963}
964
965void CGRecordLowering::insertPadding() {
966 std::vector<std::pair<CharUnits, CharUnits> > Padding;
967 CharUnits Size = CharUnits::Zero();
968 for (const MemberInfo &Member : Members) {
969 if (!Member.Data)
970 continue;
971 CharUnits Offset = Member.Offset;
972 assert(Offset >= Size);
973 // Insert padding if we need to.
974 if (Offset !=
975 Size.alignTo(Packed ? CharUnits::One() : getAlignment(Member.Data)))
976 Padding.push_back(std::make_pair(Size, Offset - Size));
977 Size = Offset + getSize(Member.Data);
978 }
979 if (Padding.empty())
980 return;
981 // Add the padding to the Members list and sort it.
982 for (const auto &Pad : Padding)
983 Members.push_back(StorageInfo(Pad.first, getByteArrayType(Pad.second)));
984 llvm::stable_sort(Members);
985}
986
987void CGRecordLowering::fillOutputFields() {
988 for (const MemberInfo &Member : Members) {
989 if (Member.Data)
990 FieldTypes.push_back(Member.Data);
991 if (Member.Kind == MemberInfo::Field) {
992 if (Member.FD)
993 Fields[Member.FD->getCanonicalDecl()] = FieldTypes.size() - 1;
994 // A field without storage must be a bitfield.
995 if (!Member.Data) {
996 assert(Member.FD &&
997 "Member.Data is a nullptr so Member.FD should not be");
998 setBitFieldInfo(Member.FD, Member.Offset, FieldTypes.back());
999 }
1000 } else if (Member.Kind == MemberInfo::Base)
1001 NonVirtualBases[Member.RD] = FieldTypes.size() - 1;
1002 else if (Member.Kind == MemberInfo::VBase)
1003 VirtualBases[Member.RD] = FieldTypes.size() - 1;
1004 }
1005}
1006
1008 const FieldDecl *FD,
1009 uint64_t Offset, uint64_t Size,
1010 uint64_t StorageSize,
1012 // This function is vestigial from CGRecordLayoutBuilder days but is still
1013 // used in GCObjCRuntime.cpp. That usage has a "fixme" attached to it that
1014 // when addressed will allow for the removal of this function.
1015 llvm::Type *Ty = Types.ConvertTypeForMem(FD->getType());
1016 CharUnits TypeSizeInBytes =
1017 CharUnits::fromQuantity(Types.getDataLayout().getTypeAllocSize(Ty));
1018 uint64_t TypeSizeInBits = Types.getContext().toBits(TypeSizeInBytes);
1019
1021
1022 if (Size > TypeSizeInBits) {
1023 // We have a wide bit-field. The extra bits are only used for padding, so
1024 // if we have a bitfield of type T, with size N:
1025 //
1026 // T t : N;
1027 //
1028 // We can just assume that it's:
1029 //
1030 // T t : sizeof(T);
1031 //
1032 Size = TypeSizeInBits;
1033 }
1034
1035 // Reverse the bit offsets for big endian machines. Because we represent
1036 // a bitfield as a single large integer load, we can imagine the bits
1037 // counting from the most-significant-bit instead of the
1038 // least-significant-bit.
1039 if (Types.getDataLayout().isBigEndian()) {
1040 Offset = StorageSize - (Offset + Size);
1041 }
1042
1044}
1045
1046std::unique_ptr<CGRecordLayout>
1047CodeGenTypes::ComputeRecordLayout(const RecordDecl *D, llvm::StructType *Ty) {
1048 CGRecordLowering Builder(*this, D, /*Packed=*/false);
1049
1050 Builder.lower(/*NonVirtualBaseType=*/false);
1051
1052 // If we're in C++, compute the base subobject type.
1053 llvm::StructType *BaseTy = nullptr;
1054 if (isa<CXXRecordDecl>(D)) {
1055 BaseTy = Ty;
1056 if (Builder.Layout.getNonVirtualSize() != Builder.Layout.getSize()) {
1057 CGRecordLowering BaseBuilder(*this, D, /*Packed=*/Builder.Packed);
1058 BaseBuilder.lower(/*NonVirtualBaseType=*/true);
1059 BaseTy = llvm::StructType::create(
1060 getLLVMContext(), BaseBuilder.FieldTypes, "", BaseBuilder.Packed);
1061 addRecordTypeName(D, BaseTy, ".base");
1062 // BaseTy and Ty must agree on their packedness for getLLVMFieldNo to work
1063 // on both of them with the same index.
1064 assert(Builder.Packed == BaseBuilder.Packed &&
1065 "Non-virtual and complete types must agree on packedness");
1066 }
1067 }
1068
1069 // Fill in the struct *after* computing the base type. Filling in the body
1070 // signifies that the type is no longer opaque and record layout is complete,
1071 // but we may need to recursively layout D while laying D out as a base type.
1072 Ty->setBody(Builder.FieldTypes, Builder.Packed);
1073
1074 auto RL = std::make_unique<CGRecordLayout>(
1075 Ty, BaseTy, (bool)Builder.IsZeroInitializable,
1076 (bool)Builder.IsZeroInitializableAsBase);
1077
1078 RL->NonVirtualBases.swap(Builder.NonVirtualBases);
1079 RL->CompleteObjectVirtualBases.swap(Builder.VirtualBases);
1080
1081 // Add all the field numbers.
1082 RL->FieldInfo.swap(Builder.Fields);
1083
1084 // Add bitfield info.
1085 RL->BitFields.swap(Builder.BitFields);
1086
1087 // Dump the layout, if requested.
1088 if (getContext().getLangOpts().DumpRecordLayouts) {
1089 llvm::outs() << "\n*** Dumping IRgen Record Layout\n";
1090 llvm::outs() << "Record: ";
1091 D->dump(llvm::outs());
1092 llvm::outs() << "\nLayout: ";
1093 RL->print(llvm::outs());
1094 }
1095
1096#ifndef NDEBUG
1097 // Verify that the computed LLVM struct size matches the AST layout size.
1098 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(D);
1099
1100 uint64_t TypeSizeInBits = getContext().toBits(Layout.getSize());
1101 assert(TypeSizeInBits == getDataLayout().getTypeAllocSizeInBits(Ty) &&
1102 "Type size mismatch!");
1103
1104 if (BaseTy) {
1105 CharUnits NonVirtualSize = Layout.getNonVirtualSize();
1106
1107 uint64_t AlignedNonVirtualTypeSizeInBits =
1108 getContext().toBits(NonVirtualSize);
1109
1110 assert(AlignedNonVirtualTypeSizeInBits ==
1111 getDataLayout().getTypeAllocSizeInBits(BaseTy) &&
1112 "Type size mismatch!");
1113 }
1114
1115 // Verify that the LLVM and AST field offsets agree.
1116 llvm::StructType *ST = RL->getLLVMType();
1117 const llvm::StructLayout *SL = getDataLayout().getStructLayout(ST);
1118
1119 const ASTRecordLayout &AST_RL = getContext().getASTRecordLayout(D);
1121 for (unsigned i = 0, e = AST_RL.getFieldCount(); i != e; ++i, ++it) {
1122 const FieldDecl *FD = *it;
1123
1124 // Ignore zero-sized fields.
1126 continue;
1127
1128 // For non-bit-fields, just check that the LLVM struct offset matches the
1129 // AST offset.
1130 if (!FD->isBitField()) {
1131 unsigned FieldNo = RL->getLLVMFieldNo(FD);
1132 assert(AST_RL.getFieldOffset(i) == SL->getElementOffsetInBits(FieldNo) &&
1133 "Invalid field offset!");
1134 continue;
1135 }
1136
1137 // Ignore unnamed bit-fields.
1138 if (!FD->getDeclName())
1139 continue;
1140
1141 const CGBitFieldInfo &Info = RL->getBitFieldInfo(FD);
1142 llvm::Type *ElementTy = ST->getTypeAtIndex(RL->getLLVMFieldNo(FD));
1143
1144 // Unions have overlapping elements dictating their layout, but for
1145 // non-unions we can verify that this section of the layout is the exact
1146 // expected size.
1147 if (D->isUnion()) {
1148 // For unions we verify that the start is zero and the size
1149 // is in-bounds. However, on BE systems, the offset may be non-zero, but
1150 // the size + offset should match the storage size in that case as it
1151 // "starts" at the back.
1152 if (getDataLayout().isBigEndian())
1153 assert(static_cast<unsigned>(Info.Offset + Info.Size) ==
1154 Info.StorageSize &&
1155 "Big endian union bitfield does not end at the back");
1156 else
1157 assert(Info.Offset == 0 &&
1158 "Little endian union bitfield with a non-zero offset");
1159 assert(Info.StorageSize <= SL->getSizeInBits() &&
1160 "Union not large enough for bitfield storage");
1161 } else {
1162 assert((Info.StorageSize ==
1163 getDataLayout().getTypeAllocSizeInBits(ElementTy) ||
1164 Info.VolatileStorageSize ==
1165 getDataLayout().getTypeAllocSizeInBits(ElementTy)) &&
1166 "Storage size does not match the element type size");
1167 }
1168 assert(Info.Size > 0 && "Empty bitfield!");
1169 assert(static_cast<unsigned>(Info.Offset) + Info.Size <= Info.StorageSize &&
1170 "Bitfield outside of its allocated storage");
1171 }
1172#endif
1173
1174 return RL;
1175}
1176
1177void CGRecordLayout::print(raw_ostream &OS) const {
1178 OS << "<CGRecordLayout\n";
1179 OS << " LLVMType:" << *CompleteObjectType << "\n";
1180 if (BaseSubobjectType)
1181 OS << " NonVirtualBaseLLVMType:" << *BaseSubobjectType << "\n";
1182 OS << " IsZeroInitializable:" << IsZeroInitializable << "\n";
1183 OS << " BitFields:[\n";
1184
1185 // Print bit-field infos in declaration order.
1186 std::vector<std::pair<unsigned, const CGBitFieldInfo*> > BFIs;
1187 for (const auto &BitField : BitFields) {
1188 const RecordDecl *RD = BitField.first->getParent();
1189 unsigned Index = 0;
1190 for (RecordDecl::field_iterator it2 = RD->field_begin();
1191 *it2 != BitField.first; ++it2)
1192 ++Index;
1193 BFIs.push_back(std::make_pair(Index, &BitField.second));
1194 }
1195 llvm::array_pod_sort(BFIs.begin(), BFIs.end());
1196 for (auto &BFI : BFIs) {
1197 OS.indent(4);
1198 BFI.second->print(OS);
1199 OS << "\n";
1200 }
1201
1202 OS << "]>\n";
1203}
1204
1205LLVM_DUMP_METHOD void CGRecordLayout::dump() const {
1206 print(llvm::errs());
1207}
1208
1209void CGBitFieldInfo::print(raw_ostream &OS) const {
1210 OS << "<CGBitFieldInfo"
1211 << " Offset:" << Offset << " Size:" << Size << " IsSigned:" << IsSigned
1212 << " StorageSize:" << StorageSize
1213 << " StorageOffset:" << StorageOffset.getQuantity()
1214 << " VolatileOffset:" << VolatileOffset
1215 << " VolatileStorageSize:" << VolatileStorageSize
1216 << " VolatileStorageOffset:" << VolatileStorageOffset.getQuantity() << ">";
1217}
1218
1219LLVM_DUMP_METHOD void CGBitFieldInfo::dump() const {
1220 print(llvm::errs());
1221}
Defines the clang::ASTContext interface.
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
static void print(llvm::raw_ostream &OS, const T &V, const Context &Ctx, QualType Ty)
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
bool isNearlyEmpty(const CXXRecordDecl *RD) const
int64_t toBits(CharUnits CharSize) const
Convert a size in characters to a size in bits.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:971
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
uint64_t getCharWidth() const
Return the size of the character type, in bits.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
bool hasOwnVFPtr() const
hasOwnVFPtr - Does this class provide its own virtual-function table pointer, rather than inheriting ...
CharUnits getAlignment() const
getAlignment - Get the record alignment in characters.
bool hasOwnVBPtr() const
hasOwnVBPtr - Does this class provide its own virtual-base table pointer, rather than inheriting one ...
CharUnits getSize() const
getSize - Get the record size in characters.
unsigned getFieldCount() const
getFieldCount - Get the number of fields in the layout.
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
CharUnits getVBPtrOffset() const
getVBPtrOffset - Get the offset for virtual base table pointer.
CharUnits getDataSize() const
getDataSize() - Get the record data size, which is the record size without tail padding,...
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const
getVBaseClassOffset - Get the offset, in chars, for the given base class.
const VBaseOffsetsMapTy & getVBaseOffsetsMap() const
const CXXRecordDecl * getPrimaryBase() const
getPrimaryBase - Get the primary base for this record.
bool isPrimaryBaseVirtual() const
isPrimaryBaseVirtual - Get whether the primary base for this record is virtual or not.
CharUnits getNonVirtualSize() const
getNonVirtualSize - Get the non-virtual size (in chars) of an object, which is the size of the object...
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
bool isZero() const
Test whether the quantity equals zero.
Definition CharUnits.h:101
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
Definition CharUnits.h:155
static CharUnits One()
Construct a CharUnits quantity of one.
Definition CharUnits.h:55
bool isMultipleOf(CharUnits N) const
Test whether this is a multiple of the other value.
Definition CharUnits.h:122
static CharUnits fromQuantity(QuantityType Quantity)
Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:58
static CharUnits Zero()
Construct a CharUnits quantity of zero.
Definition CharUnits.h:52
This class organizes the cross-module state that is used while lowering AST types to LLVM types.
const CodeGenOptions & getCodeGenOpts() const
ASTContext & getContext() const
std::unique_ptr< CGRecordLayout > ComputeRecordLayout(const RecordDecl *D, llvm::StructType *Ty)
Compute a new LLVM record layout object for the given record.
llvm::Type * ConvertTypeForMem(QualType T)
ConvertTypeForMem - Convert type T into a llvm::Type.
CodeGenModule & getCGM() const
llvm::LLVMContext & getLLVMContext()
const llvm::DataLayout & getDataLayout() const
void addRecordTypeName(const RecordDecl *RD, llvm::StructType *Ty, StringRef suffix)
addRecordTypeName - Compute a name from the given record decl with an optional suffix and name the gi...
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2108
void dump() const
Represents a member of a struct/union/class.
Definition Decl.h:3341
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3444
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4854
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3426
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition Decl.h:3588
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:342
Represents a struct/union/class.
Definition Decl.h:4506
field_iterator field_end() const
Definition Decl.h:4712
field_range fields() const
Definition Decl.h:4709
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4706
field_iterator field_begin() const
Definition Decl.cpp:5383
bool isUnion() const
Definition Decl.h:4109
virtual unsigned getRegisterWidth() const
Return the "preferred" register width on this target.
Definition TargetInfo.h:902
bool hasCheapUnalignedBitFieldAccess() const
Return true iff unaligned accesses are cheap.
Definition TargetInfo.h:916
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2415
QualType getType() const
Definition Decl.h:725
bool isAAPCS(const TargetInfo &TargetInfo)
Helper method to check if the underlying ABI is AAPCS.
bool isDiscreteBitFieldABI(const ASTContext &Ctx, const RecordDecl *RD)
The Microsoft bitfield layout rule allocates discrete storage units of the field's formal type and on...
bool hasOwnStorage(const ASTContext &Ctx, const CXXRecordDecl *Decl, const CXXRecordDecl *Query)
Recursively searches all of the bases of Decl to find out whether Query is not the primary vbase of s...
bool isOverlappingVBaseABI(const ASTContext &Ctx)
The Itanium base layout rule allows virtual bases to overlap other bases, which complicates layout in...
bool isEmptyFieldForLayout(const ASTContext &Ctx, const FieldDecl *FD)
Return true iff the field is "empty", that is, either a zero-width bit-field or an isEmptyRecordForLa...
bool isEmptyRecordForLayout(const ASTContext &Ctx, QualType T)
Return true iff a structure contains only empty base classes (per isEmptyRecordForLayout) and fields ...
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool operator<(DeclarationName LHS, DeclarationName RHS)
Ordering on two declaration names.
unsigned long uint64_t
#define true
Definition stdbool.h:25
Structure with information about how a bitfield should be accessed.
CharUnits StorageOffset
The offset of the bitfield storage from the start of the struct.
CharUnits VolatileStorageOffset
The offset of the bitfield storage from the start of the struct.
unsigned VolatileOffset
The offset within a contiguous run of bitfields that are represented as a single "field" within the L...
unsigned Offset
The offset within a contiguous run of bitfields that are represented as a single "field" within the L...
unsigned VolatileStorageSize
The storage size in bits which should be used when accessing this bitfield.
unsigned Size
The total size of the bit-field, in bits, not including padding.
unsigned StorageSize
The storage size in bits which should be used when accessing this bitfield.
unsigned IsSigned
Whether the bit-field is signed.
static CGBitFieldInfo MakeInfo(class CodeGenTypes &Types, const FieldDecl *FD, uint64_t Offset, uint64_t Size, uint64_t StorageSize, CharUnits StorageOffset)
Given a bit-field decl, build an appropriate helper object for accessing that field (which is expecte...