clang 24.0.0git
CIRGenRecordLayoutBuilder.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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// This contains code to compute the layout of a record.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CIRGenBuilder.h"
14#include "CIRGenModule.h"
15#include "CIRGenTypes.h"
16#include "TargetInfo.h"
17
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclCXX.h"
26#include "llvm/Support/Casting.h"
27
28#include <memory>
29
30using namespace llvm;
31using namespace clang;
32using namespace clang::CIRGen;
33
34namespace {
35/// The CIRRecordLowering is responsible for lowering an ASTRecordLayout to an
36/// mlir::Type. Some of the lowering is straightforward, some is not.
37// TODO: Detail some of the complexities and weirdnesses?
38// (See CGRecordLayoutBuilder.cpp)
39struct CIRRecordLowering final {
40
41 // MemberInfo is a helper structure that contains information about a record
42 // member. In addition to the standard member types, there exists a sentinel
43 // member type that ensures correct rounding.
44 struct MemberInfo final {
45 CharUnits offset;
46 enum class InfoKind { VFPtr, Field, Base, VBase } kind;
47 mlir::Type data;
48 /// What this member holds, recorded on the CIR record type.
49 cir::RecordMemberKind memberKind;
50 union {
51 const FieldDecl *fieldDecl;
52 const CXXRecordDecl *cxxRecordDecl;
53 };
54 MemberInfo(CharUnits offset, InfoKind kind, mlir::Type data,
55 cir::RecordMemberKind memberKind,
56 const FieldDecl *fieldDecl = nullptr)
57 : offset{offset}, kind{kind}, data{data}, memberKind{memberKind},
59 MemberInfo(CharUnits offset, InfoKind kind, mlir::Type data,
60 cir::RecordMemberKind memberKind, const CXXRecordDecl *rd)
61 : offset{offset}, kind{kind}, data{data}, memberKind{memberKind},
62 cxxRecordDecl{rd} {}
63 // MemberInfos are sorted so we define a < operator.
64 bool operator<(const MemberInfo &other) const {
65 return offset < other.offset;
66 }
67 };
68
69 static bool ownsBytes(const MemberInfo &member) {
70 return member.data && cir::memberOwnsBytes(member.data);
71 }
72
73 cir::BitFieldDeclAttr getBitFieldDecl(const FieldDecl *field) {
74 return cir::BitFieldDeclAttr::get(
75 cirGenTypes.convertTypeForMem(field->getType()),
76 field->getBitWidthValue(), field->isUnnamedBitField());
77 }
78
79 MemberInfo makeAccessUnitInfo(CharUnits offset, mlir::Type storage,
80 llvm::ArrayRef<cir::BitFieldDeclAttr> fields) {
81 mlir::Type unitTy =
82 cir::BitFieldType::get(&cirGenTypes.getMLIRContext(), storage, fields);
83 // If the access unit doesn't hold any named fields, it's empty.
84 const bool holdsNamedField =
85 mlir::cast<cir::BitFieldType>(unitTy).holdsNamedField();
86 return makeStorageInfo(offset, unitTy,
87 holdsNamedField ? cir::RecordMemberKind::BitField
88 : cir::RecordMemberKind::Empty);
89 }
90
91 /// The member for a zero-width bit-field, which belongs to no access unit
92 /// and owns no bytes. It sits at its own offset, where the run it ended
93 /// stops.
94 MemberInfo makeZeroWidthBitFieldInfo(const FieldDecl *field) {
95 assert(field->isZeroLengthBitField() && "not a zero-width bit-field");
96 return makeAccessUnitInfo(bitsToCharUnits(getFieldBitOffset(field)),
97 /*storage=*/mlir::Type{}, getBitFieldDecl(field));
98 }
99
100 // The constructor.
101 CIRRecordLowering(CIRGenTypes &cirGenTypes, const RecordDecl *recordDecl,
102 bool packed);
103
104 /// Constructs a MemberInfo instance from an offset and mlir::Type.
105 MemberInfo makeStorageInfo(CharUnits offset, mlir::Type data,
106 cir::RecordMemberKind memberKind) {
107 return MemberInfo(offset, MemberInfo::InfoKind::Field, data, memberKind);
108 }
109
110 // Layout routines.
111 void setBitFieldInfo(const FieldDecl *fd, CharUnits startOffset,
112 mlir::Type storageType);
113
114 void lower(bool nonVirtualBaseType);
115 void lowerUnion(bool nonVirtualBaseType);
116
117 /// Determines if we need a packed llvm struct.
118 void determinePacked(bool nvBaseType);
119 /// Inserts padding everywhere it's needed.
120 void insertPadding();
121
122 void computeVolatileBitfields();
123 void accumulateBases();
124 void accumulateVPtrs();
125 void accumulateVBases();
126 void accumulateFields(bool nonVirtualBaseType);
128 accumulateBitFields(RecordDecl::field_iterator field,
130
131 mlir::Type getVFPtrType();
132
133 /// Helper function to check if the target machine is BigEndian.
134 bool isBigEndian() const { return astContext.getTargetInfo().isBigEndian(); }
135
136 // The Itanium base layout rule allows virtual bases to overlap
137 // other bases, which complicates layout in specific ways.
138 //
139 // Note specifically that the ms_struct attribute doesn't change this.
140 bool isOverlappingVBaseABI() {
141 return !astContext.getTargetInfo().getCXXABI().isMicrosoft();
142 }
143 // Recursively searches all of the bases to find out if a vbase is
144 // not the primary vbase of some base class.
145 bool hasOwnStorage(const CXXRecordDecl *decl, const CXXRecordDecl *query);
146
147 /// The Microsoft bitfield layout rule allocates discrete storage
148 /// units of the field's formal type and only combines adjacent
149 /// fields of the same formal type. We want to emit a layout with
150 /// these discrete storage units instead of combining them into a
151 /// continuous run.
152 bool isDiscreteBitFieldABI() {
153 return astContext.getTargetInfo().getCXXABI().isMicrosoft() ||
154 recordDecl->isMsStruct(astContext);
155 }
156
157 CharUnits bitsToCharUnits(uint64_t bitOffset) {
158 return astContext.toCharUnitsFromBits(bitOffset);
159 }
160
161 void calculateZeroInit();
162
163 CharUnits getSize(mlir::Type Ty) {
164 return CharUnits::fromQuantity(dataLayout.layout.getTypeSize(Ty));
165 }
166 CharUnits getSizeInBits(mlir::Type ty) {
167 return CharUnits::fromQuantity(dataLayout.layout.getTypeSizeInBits(ty));
168 }
169
170 CharUnits getMemberAlignment(mlir::Type Ty) {
171 // An access unit takes the alignment of its storage type. A zero-width
172 // bit-field has no storage and so imposes no alignment.
173 if (auto bitFieldTy = mlir::dyn_cast<cir::BitFieldType>(Ty)) {
174 if (mlir::Type storage = bitFieldTy.getStorageType())
175 return getMemberAlignment(storage);
176 return CharUnits::One();
177 }
178 // Recurse on Arrays, they have the member alignment of their element type.
179 if (auto arrayTy = mlir::dyn_cast<cir::ArrayType>(Ty))
180 return getMemberAlignment(arrayTy.getElementType());
181 // Int types (_BitInt in particular) share the alignment of their storage
182 // type.
183 if (auto intTy = mlir::dyn_cast<cir::IntType>(Ty))
185 intTy.getStorageTypeAlignment(dataLayout.layout));
186
187 return CharUnits::fromQuantity(dataLayout.layout.getTypeABIAlignment(Ty));
188 }
189
190 bool isZeroInitializable(const FieldDecl *fd) {
191 return cirGenTypes.isZeroInitializable(fd->getType());
192 }
193 bool isZeroInitializable(const RecordDecl *rd) {
194 return cirGenTypes.isZeroInitializable(rd);
195 }
196
197 /// The mark for a member, given whether it holds data for argument passing
198 /// and whether it is a bit-field. A run of bit-fields shares one access
199 /// unit whose width can be narrower than the declared type of the bit-field
200 /// it holds.
201 static cir::RecordMemberKind makeMemberKind(bool holdsData,
202 bool isNamedBitField) {
203 if (!holdsData)
204 return cir::RecordMemberKind::Empty;
205 return isNamedBitField ? cir::RecordMemberKind::BitField
206 : cir::RecordMemberKind::Data;
207 }
208
209 /// The mark for a field that is not a bit-field. A run of bit-fields is one
210 /// member per access unit rather than one per field, so a bit-field is
211 /// marked where its unit is built.
212 cir::RecordMemberKind getFieldMemberKind(const FieldDecl *fd) {
213 assert(!fd->isBitField() && "a bit-field is marked with its access unit");
214 return makeMemberKind(/*holdsData=*/!isEmptyFieldForABI(astContext, fd),
215 /*isNamedBitField=*/false);
216 }
217
218 /// The mark for a base subobject. A base contributes no ABI data when it is
219 /// empty for the ABI, which is not the same as CXXRecordDecl::isEmpty(): a
220 /// base holding only unnamed bit-fields is laid out but carries no data.
221 cir::RecordMemberKind getBaseMemberKind(const CXXRecordDecl *baseDecl) {
222 return isEmptyRecordForABI(astContext,
223 astContext.getCanonicalTagType(baseDecl))
224 ? cir::RecordMemberKind::Empty
225 : cir::RecordMemberKind::Data;
226 }
227
228 /// Wraps cir::IntType with some implicit arguments.
229 mlir::Type getUIntNType(uint64_t numBits) {
230 unsigned alignedBits = llvm::PowerOf2Ceil(numBits);
231 alignedBits = std::max(8u, alignedBits);
232 return cir::IntType::get(&cirGenTypes.getMLIRContext(), alignedBits,
233 /*isSigned=*/false);
234 }
235
236 mlir::Type getCharType() {
237 return cir::IntType::get(&cirGenTypes.getMLIRContext(),
238 astContext.getCharWidth(),
239 /*isSigned=*/false);
240 }
241
242 mlir::Type getByteArrayType(CharUnits numberOfChars) {
243 assert(!numberOfChars.isZero() && "Empty byte arrays aren't allowed.");
244 mlir::Type type = getCharType();
245 return numberOfChars == CharUnits::One()
246 ? type
247 : cir::ArrayType::get(type, numberOfChars.getQuantity());
248 }
249
250 // Gets the CIR BaseSubobject type from a CXXRecordDecl.
251 mlir::Type getStorageType(const CXXRecordDecl *RD) {
252 return cirGenTypes.getCIRGenRecordLayout(RD).getBaseSubobjectCIRType();
253 }
254 // This is different from LLVM traditional codegen because CIRGen uses arrays
255 // of bytes instead of arbitrary-sized integers. This is important for packed
256 // structures support.
257 mlir::Type getBitfieldStorageType(unsigned numBits) {
258 unsigned alignedBits = llvm::alignTo(numBits, astContext.getCharWidth());
259 if (cir::isValidFundamentalIntWidth(alignedBits))
260 return builder.getUIntNTy(alignedBits);
261
262 mlir::Type type = getCharType();
263 return cir::ArrayType::get(type, alignedBits / astContext.getCharWidth());
264 }
265
266 mlir::Type getStorageType(const FieldDecl *fieldDecl) {
267 mlir::Type type = cirGenTypes.convertTypeForMem(fieldDecl->getType());
268 if (fieldDecl->isBitField()) {
269 cirGenTypes.getCGModule().errorNYI(recordDecl->getSourceRange(),
270 "getStorageType for bitfields");
271 }
272 return type;
273 }
274
275 uint64_t getFieldBitOffset(const FieldDecl *fieldDecl) {
276 return astRecordLayout.getFieldOffset(fieldDecl->getFieldIndex());
277 }
278
279 /// Fills out the structures that are ultimately consumed.
280 void fillOutputFields();
281
282 void appendPaddingBytes(CharUnits size) {
283 if (size.isZero())
284 return;
285 mlir::Type padTy = getByteArrayType(size);
286 if (recordDecl->isUnion()) {
287 assert(!unionPadding && "at most one union tail-padding type");
288 unionPadding = padTy;
289 } else {
290 addField(padTy, cir::RecordMemberKind::Pad);
291 }
292 }
293
294 void addField(mlir::Type ty, cir::RecordMemberKind memberKind) {
295 fieldTypes.push_back(ty);
296 fieldKinds.push_back(memberKind);
297 }
298
299 void clearFields() {
300 fieldTypes.clear();
301 fieldKinds.clear();
302 }
303
304 llvm::ArrayRef<mlir::Type> getFieldTypes() const { return fieldTypes; }
305 llvm::ArrayRef<cir::RecordMemberKind> getFieldKinds() const {
306 return fieldKinds;
307 }
308
309 CIRGenTypes &cirGenTypes;
310 CIRGenBuilderTy &builder;
311 const ASTContext &astContext;
312 const RecordDecl *recordDecl;
313 const CXXRecordDecl *cxxRecordDecl;
314 const ASTRecordLayout &astRecordLayout;
315 // Helpful intermediate data-structures
316 std::vector<MemberInfo> members;
317 mlir::Type unionPadding;
318 llvm::DenseMap<const FieldDecl *, CIRGenBitFieldInfo> bitFields;
319 llvm::DenseMap<const FieldDecl *, unsigned> fieldIdxMap;
320 llvm::DenseMap<const CXXRecordDecl *, unsigned> nonVirtualBases;
321 llvm::DenseMap<const CXXRecordDecl *, unsigned> virtualBases;
322 cir::CIRDataLayout dataLayout;
323
324 LLVM_PREFERRED_TYPE(bool)
325 unsigned zeroInitializable : 1;
326 LLVM_PREFERRED_TYPE(bool)
327 unsigned zeroInitializableAsBase : 1;
328 LLVM_PREFERRED_TYPE(bool)
329 unsigned packed : 1;
330
331private:
332 // Output fields, consumed by CIRGenTypes::computeRecordLayout. Private so
333 // that every append goes through addField and fieldKinds stays parallel to
334 // fieldTypes.
335 llvm::SmallVector<mlir::Type, 16> fieldTypes;
336 llvm::SmallVector<cir::RecordMemberKind> fieldKinds;
337
338 CIRRecordLowering(const CIRRecordLowering &) = delete;
339 void operator=(const CIRRecordLowering &) = delete;
340}; // CIRRecordLowering
341} // namespace
342
343CIRRecordLowering::CIRRecordLowering(CIRGenTypes &cirGenTypes,
344 const RecordDecl *recordDecl, bool packed)
345 : cirGenTypes{cirGenTypes}, builder{cirGenTypes.getBuilder()},
346 astContext{cirGenTypes.getASTContext()}, recordDecl{recordDecl},
348 astRecordLayout{
349 cirGenTypes.getASTContext().getASTRecordLayout(recordDecl)},
350 dataLayout{cirGenTypes.getCGModule().getModule()},
351 zeroInitializable{true}, zeroInitializableAsBase{true}, packed{packed} {}
352
353void CIRRecordLowering::setBitFieldInfo(const FieldDecl *fd,
354 CharUnits startOffset,
355 mlir::Type storageType) {
356 CIRGenBitFieldInfo &info = bitFields[fd->getCanonicalDecl()];
358 info.offset =
359 (unsigned)(getFieldBitOffset(fd) - astContext.toBits(startOffset));
360 info.size = fd->getBitWidthValue();
361 info.storageSize = getSizeInBits(storageType).getQuantity();
362 info.storageOffset = startOffset;
363 info.storageType = storageType;
364 info.name = fd->getName();
365
366 if (info.size > info.storageSize)
367 info.size = info.storageSize;
368 // Reverse the bit offsets for big endian machines. Since bitfields are laid
369 // out as packed bits within an integer-sized unit, we can imagine the bits
370 // counting from the most-significant-bit instead of the
371 // least-significant-bit.
372 if (dataLayout.isBigEndian())
373 info.offset = info.storageSize - (info.offset + info.size);
374
375 info.volatileStorageSize = 0;
376 info.volatileOffset = 0;
377 info.volatileStorageOffset = CharUnits::Zero();
378}
379
380void CIRRecordLowering::lower(bool nonVirtualBaseType) {
381 if (recordDecl->isUnion()) {
382 lowerUnion(nonVirtualBaseType);
383 computeVolatileBitfields();
384 return;
385 }
386
387 CharUnits size = nonVirtualBaseType ? astRecordLayout.getNonVirtualSize()
388 : astRecordLayout.getSize();
389
390 accumulateFields(nonVirtualBaseType);
391
392 if (cxxRecordDecl) {
393 accumulateVPtrs();
394 accumulateBases();
395 if (members.empty()) {
396 appendPaddingBytes(size);
397 computeVolatileBitfields();
398 return;
399 }
400 if (!nonVirtualBaseType)
401 accumulateVBases();
402 }
403
404 llvm::stable_sort(members);
405 // TODO: Verify bitfield clipping
407
408 // The sentinel is popped before fillOutputFields, so its kind never reaches
409 // the type.
410 members.push_back(
411 makeStorageInfo(size, getUIntNType(8), cir::RecordMemberKind::Data));
412 determinePacked(nonVirtualBaseType);
413 insertPadding();
414 members.pop_back();
415
416 calculateZeroInit();
417 fillOutputFields();
418 computeVolatileBitfields();
419}
420
421void CIRRecordLowering::fillOutputFields() {
422 for (const MemberInfo &member : members) {
423 if (member.data)
424 addField(member.data, member.memberKind);
425 if (member.kind == MemberInfo::InfoKind::Field) {
426 if (member.fieldDecl)
427 fieldIdxMap[member.fieldDecl->getCanonicalDecl()] =
428 fieldTypes.size() - 1;
429 // A bit-field carries no member of its own. It is numbered as the access
430 // unit ahead of it, whose storage it is read and written through.
431 if (!member.data) {
432 assert(member.fieldDecl &&
433 "member.data is a nullptr so member.fieldDecl should not be");
434 setBitFieldInfo(member.fieldDecl, member.offset,
435 cir::memberStorageType(fieldTypes.back()));
436 }
437 } else if (member.kind == MemberInfo::InfoKind::Base) {
438 nonVirtualBases[member.cxxRecordDecl] = fieldTypes.size() - 1;
439 } else if (member.kind == MemberInfo::InfoKind::VBase) {
440 virtualBases[member.cxxRecordDecl] = fieldTypes.size() - 1;
441 }
442 }
443}
444
446CIRRecordLowering::accumulateBitFields(RecordDecl::field_iterator field,
448 if (isDiscreteBitFieldABI()) {
449 // run stores the first element of the current run of bitfields. fieldEnd is
450 // used as a special value to note that we don't have a current run. A
451 // bitfield run is a contiguous collection of bitfields that can be stored
452 // in the same storage block. Zero-sized bitfields and bitfields that would
453 // cross an alignment boundary break a run and start a new one.
455 // tail is the offset of the first bit off the end of the current run. It's
456 // used to determine if the ASTRecordLayout is treating these two bitfields
457 // as contiguous. StartBitOffset is offset of the beginning of the Run.
458 uint64_t startBitOffset, tail = 0;
459 // Where the current run's access unit sits in members, and the bit-fields
460 // it holds so far. The unit grows as new bit-fields are added.
461 size_t unitIdx = 0;
462 mlir::Type unitStorage;
463 llvm::SmallVector<cir::BitFieldDeclAttr> unitFields;
464 for (; field != fieldEnd && field->isBitField(); ++field) {
465 // Zero-width bitfields end runs.
466 if (field->isZeroLengthBitField()) {
467 members.push_back(makeZeroWidthBitFieldInfo(*field));
468 run = fieldEnd;
469 continue;
470 }
471 uint64_t bitOffset = getFieldBitOffset(*field);
472 mlir::Type type = cirGenTypes.convertTypeForMem(field->getType());
473 cir::BitFieldDeclAttr decl = getBitFieldDecl(*field);
474 // If we don't have a run yet, or don't live within the previous run's
475 // allocated storage then we allocate some storage and start a new run.
476 if (run == fieldEnd || bitOffset >= tail) {
477 run = field;
478 startBitOffset = bitOffset;
479 tail = startBitOffset + dataLayout.getTypeAllocSizeInBits(type);
480 // The access unit is added to the record before the bit-fields it
481 // holds so that it gets laid out ahead of them.
482 unitIdx = members.size();
483 unitStorage = type;
484 unitFields.assign(1, decl);
485 members.push_back(makeAccessUnitInfo(bitsToCharUnits(startBitOffset),
486 unitStorage, unitFields));
487 } else {
488 unitFields.push_back(decl);
489 members[unitIdx] = makeAccessUnitInfo(bitsToCharUnits(startBitOffset),
490 unitStorage, unitFields);
491 }
492 assert(members[unitIdx].offset == bitsToCharUnits(startBitOffset) &&
493 "unitIdx must name the current run's access unit");
494 // Bitfields get the offset of their access unit but come afterward and
495 // remain there after a stable sort.
496 members.push_back(MemberInfo(bitsToCharUnits(startBitOffset),
497 MemberInfo::InfoKind::Field, nullptr,
498 cir::RecordMemberKind::Data, *field));
499 }
500 return field;
501 }
502
503 CharUnits regSize =
504 bitsToCharUnits(astContext.getTargetInfo().getRegisterWidth());
505 unsigned charBits = astContext.getCharWidth();
506
507 // Data about the start of the span we're accumulating to create an access
508 // unit from. 'Begin' is the first bitfield of the span. If 'begin' is
509 // 'fieldEnd', we've not got a current span. The span starts at the
510 // 'beginOffset' character boundary. 'bitSizeSinceBegin' is the size (in bits)
511 // of the span -- this might include padding when we've advanced to a
512 // subsequent bitfield run.
513 RecordDecl::field_iterator begin = fieldEnd;
514 CharUnits beginOffset;
515 uint64_t bitSizeSinceBegin;
516
517 // The (non-inclusive) end of the largest acceptable access unit we've found
518 // since 'begin'. If this is 'begin', we're gathering the initial set of
519 // bitfields of a new span. 'bestEndOffset' is the end of that acceptable
520 // access unit -- it might extend beyond the last character of the bitfield
521 // run, using available padding characters.
522 RecordDecl::field_iterator bestEnd = begin;
523 CharUnits bestEndOffset;
524 bool bestClipped; // Whether the representation must be in a byte array.
525
526 for (;;) {
527 // atAlignedBoundary is true if 'field' is the (potential) start of a new
528 // span (or the end of the bitfields). When true, limitOffset is the
529 // character offset of that span and barrier indicates whether the new
530 // span cannot be merged into the current one.
531 bool atAlignedBoundary = false;
532 bool barrier = false; // a barrier can be a zero Bit Width or non bit member
533 if (field != fieldEnd && field->isBitField()) {
534 uint64_t bitOffset = getFieldBitOffset(*field);
535 if (begin == fieldEnd) {
536 // Beginning a new span.
537 begin = field;
538 bestEnd = begin;
539
540 assert((bitOffset % charBits) == 0 && "Not at start of char");
541 beginOffset = bitsToCharUnits(bitOffset);
542 bitSizeSinceBegin = 0;
543 } else if ((bitOffset % charBits) != 0) {
544 // Bitfield occupies the same character as previous bitfield, it must be
545 // part of the same span. This can include zero-length bitfields, should
546 // the target not align them to character boundaries. Such non-alignment
547 // is at variance with the standards, which require zero-length
548 // bitfields be a barrier between access units. But of course we can't
549 // achieve that in the middle of a character.
550 assert(bitOffset ==
551 astContext.toBits(beginOffset) + bitSizeSinceBegin &&
552 "Concatenating non-contiguous bitfields");
553 } else {
554 // Bitfield potentially begins a new span. This includes zero-length
555 // bitfields on non-aligning targets that lie at character boundaries
556 // (those are barriers to merging).
557 if (field->isZeroLengthBitField())
558 barrier = true;
559 atAlignedBoundary = true;
560 }
561 } else {
562 // We've reached the end of the bitfield run. Either we're done, or this
563 // is a barrier for the current span.
564 if (begin == fieldEnd)
565 break;
566
567 barrier = true;
568 atAlignedBoundary = true;
569 }
570
571 // 'installBest' indicates whether we should create an access unit for the
572 // current best span: fields ['begin', 'bestEnd') occupying characters
573 // ['beginOffset', 'bestEndOffset').
574 bool installBest = false;
575 if (atAlignedBoundary) {
576 // 'field' is the start of a new span or the end of the bitfields. The
577 // just-seen span now extends to 'bitSizeSinceBegin'.
578
579 // Determine if we can accumulate that just-seen span into the current
580 // accumulation.
581 CharUnits accessSize = bitsToCharUnits(bitSizeSinceBegin + charBits - 1);
582 if (bestEnd == begin) {
583 // This is the initial run at the start of a new span. By definition,
584 // this is the best seen so far.
585 bestEnd = field;
586 bestEndOffset = beginOffset + accessSize;
587 // Assume clipped until proven not below.
588 bestClipped = true;
589 if (!bitSizeSinceBegin)
590 // A zero-sized initial span -- this will install nothing and reset
591 // for another.
592 installBest = true;
593 } else if (accessSize > regSize) {
594 // Accumulating the just-seen span would create a multi-register access
595 // unit, which would increase register pressure.
596 installBest = true;
597 }
598
599 if (!installBest) {
600 // Determine if accumulating the just-seen span will create an expensive
601 // access unit or not.
602 mlir::Type type = getUIntNType(astContext.toBits(accessSize));
604 cirGenTypes.getCGModule().errorNYI(
605 field->getSourceRange(), "NYI CheapUnalignedBitFieldAccess");
606
607 if (!installBest) {
608 // Find the next used storage offset to determine what the limit of
609 // the current span is. That's either the offset of the next field
610 // with storage (which might be field itself) or the end of the
611 // non-reusable tail padding.
612 CharUnits limitOffset;
613 for (auto probe = field; probe != fieldEnd; ++probe)
614 if (!isEmptyFieldForLayout(astContext, *probe)) {
615 // A member with storage sets the limit.
616 assert((getFieldBitOffset(*probe) % charBits) == 0 &&
617 "Next storage is not byte-aligned");
618 limitOffset = bitsToCharUnits(getFieldBitOffset(*probe));
619 goto FoundLimit;
620 }
621 limitOffset = cxxRecordDecl ? astRecordLayout.getNonVirtualSize()
622 : astRecordLayout.getDataSize();
623
624 FoundLimit:
625 CharUnits typeSize = getSize(type);
626 if (beginOffset + typeSize <= limitOffset) {
627 // There is space before limitOffset to create a naturally-sized
628 // access unit.
629 bestEndOffset = beginOffset + typeSize;
630 bestEnd = field;
631 bestClipped = false;
632 }
633 if (barrier) {
634 // The next field is a barrier that we cannot merge across.
635 installBest = true;
636 } else if (cirGenTypes.getCGModule()
638 .FineGrainedBitfieldAccesses) {
639 installBest = true;
640 } else {
641 // Otherwise, we're not installing. Update the bit size
642 // of the current span to go all the way to limitOffset, which is
643 // the (aligned) offset of next bitfield to consider.
644 bitSizeSinceBegin = astContext.toBits(limitOffset - beginOffset);
645 }
646 }
647 }
648 }
649
650 if (installBest) {
651 assert((field == fieldEnd || !field->isBitField() ||
652 (getFieldBitOffset(*field) % charBits) == 0) &&
653 "Installing but not at an aligned bitfield or limit");
654 CharUnits accessSize = bestEndOffset - beginOffset;
655 if (!accessSize.isZero()) {
656 // Add the storage member for the access unit to the record. The
657 // bitfields get the offset of their storage but come afterward and
658 // remain there after a stable sort.
659 mlir::Type type;
660 if (bestClipped) {
661 assert(getSize(getUIntNType(astContext.toBits(accessSize))) >
662 accessSize &&
663 "Clipped access need not be clipped");
664 type = getByteArrayType(accessSize);
665 } else {
666 type = getUIntNType(astContext.toBits(accessSize));
667 assert(getSize(type) == accessSize &&
668 "Unclipped access must be clipped");
669 }
670 // A zero-length bit-field in the span was given a member of its own
671 // when it was accumulated, and belongs to no access unit, so it is not
672 // one of the fields this unit holds.
673 llvm::SmallVector<cir::BitFieldDeclAttr> unitFields;
674 for (auto occupant = begin; occupant != bestEnd; ++occupant)
675 if (!occupant->isZeroLengthBitField())
676 unitFields.push_back(getBitFieldDecl(*occupant));
677 assert(!unitFields.empty() && "an access unit holds a bit-field");
678 members.push_back(makeAccessUnitInfo(beginOffset, type, unitFields));
679
680 for (; begin != bestEnd; ++begin)
681 if (!begin->isZeroLengthBitField())
682 members.push_back(MemberInfo(beginOffset,
683 MemberInfo::InfoKind::Field, nullptr,
684 cir::RecordMemberKind::Data, *begin));
685 }
686 // Reset to start a new span.
687 field = bestEnd;
688 begin = fieldEnd;
689 } else {
690 assert(field != fieldEnd && field->isBitField() &&
691 "Accumulating past end of bitfields");
692 assert(!barrier && "Accumulating across barrier");
693 if (field->isZeroLengthBitField())
694 members.push_back(makeZeroWidthBitFieldInfo(*field));
695 // Accumulate this bitfield into the current (potential) span.
696 bitSizeSinceBegin += field->getBitWidthValue();
697 ++field;
698 }
699 }
700
701 return field;
702}
703
704void CIRRecordLowering::accumulateFields(bool nonVirtualBaseType) {
705 for (RecordDecl::field_iterator field = recordDecl->field_begin(),
706 fieldEnd = recordDecl->field_end();
707 field != fieldEnd;) {
708 if (field->isBitField()) {
709 field = accumulateBitFields(field, fieldEnd);
710 assert((field == fieldEnd || !field->isBitField()) &&
711 "Failed to accumulate all the bitfields");
712 } else if (isEmptyFieldForLayout(astContext, *field) &&
713 field->isPotentiallyOverlapping()) {
714 // We lay out normal empty fields, as they are required for GEPs/getting
715 // function pointers. However 'no-unique-address' lends some additional
716 // complexity. These fields take up no real space, but would also have to
717 // be the correct 'GEP' offset to work here, but then mess with the
718 // layout. We likely need to come up with a new 'type' to support these,
719 // then figure out some way to lower these to the correct offset, likely
720 // by calculating the correct offset into the struct, and forming a
721 // replacement by-byte GEP in LowerToLLVM. However, this is only a
722 // problem with taking the address of one of these, so it is in practice
723 // not a horrifyingly problematic issue.
725 // Dropping the field leaves no member to mark, so its bytes read as
726 // padding. That is only sound when the field carries no ABI data, so
727 // make sure we add a member for it. if it does.
728 if (!isEmptyFieldForABI(astContext, *field))
729 members.push_back(
730 MemberInfo(bitsToCharUnits(getFieldBitOffset(*field)),
731 MemberInfo::InfoKind::Field,
732 getStorageType(field->getType()->getAsCXXRecordDecl()),
733 getFieldMemberKind(*field), *field));
734 ++field;
735 } else {
736 // Use base subobject layout for potentially-overlapping fields,
737 // as it is done in RecordLayoutBuilder.
738 //
739 // The mark comes from isEmptyFieldForABI, not the isEmptyFieldForLayout
740 // above. Neither predicate subsumes the other.
741 members.push_back(MemberInfo(
742 bitsToCharUnits(getFieldBitOffset(*field)),
743 MemberInfo::InfoKind::Field,
744 field->isPotentiallyOverlapping()
745 ? getStorageType(field->getType()->getAsCXXRecordDecl())
746 : getStorageType(*field),
747 getFieldMemberKind(*field), *field));
748 ++field;
749 }
750 }
751}
752
753void CIRRecordLowering::calculateZeroInit() {
754 for (const MemberInfo &member : members) {
755 if (member.kind == MemberInfo::InfoKind::Field) {
756 if (!member.fieldDecl || isZeroInitializable(member.fieldDecl))
757 continue;
758 zeroInitializable = zeroInitializableAsBase = false;
759 return;
760 } else if (member.kind == MemberInfo::InfoKind::Base ||
761 member.kind == MemberInfo::InfoKind::VBase) {
762 if (isZeroInitializable(member.cxxRecordDecl))
763 continue;
764 zeroInitializable = false;
765 if (member.kind == MemberInfo::InfoKind::Base)
766 zeroInitializableAsBase = false;
767 }
768 }
769}
770
771void CIRRecordLowering::determinePacked(bool nvBaseType) {
772 if (packed)
773 return;
774 CharUnits alignment = CharUnits::One();
775 CharUnits nvAlignment = CharUnits::One();
776 CharUnits nvSize = !nvBaseType && cxxRecordDecl
777 ? astRecordLayout.getNonVirtualSize()
778 : CharUnits::Zero();
779
780 for (const MemberInfo &member : members) {
781 // A member that owns no bytes sits inside another member's storage, whose
782 // own offset and alignment are what decide packing.
783 if (!ownsBytes(member))
784 continue;
785 // If any member falls at an offset that it not a multiple of its alignment,
786 // then the entire record must be packed.
787 if (!member.offset.isMultipleOf(getMemberAlignment(member.data)))
788 packed = true;
789 if (member.offset < nvSize)
790 nvAlignment = std::max(nvAlignment, getMemberAlignment(member.data));
791 alignment = std::max(alignment, getMemberAlignment(member.data));
792 }
793 // If the size of the record (the capstone's offset) is not a multiple of the
794 // record's alignment, it must be packed.
795 if (!members.back().offset.isMultipleOf(alignment))
796 packed = true;
797 // If the non-virtual sub-object is not a multiple of the non-virtual
798 // sub-object's alignment, it must be packed. We cannot have a packed
799 // non-virtual sub-object and an unpacked complete object or vise versa.
800 if (!nvSize.isMultipleOf(nvAlignment))
801 packed = true;
802 // Update the alignment of the sentinel.
803 if (!packed)
804 members.back().data = getUIntNType(astContext.toBits(alignment));
805}
806
807void CIRRecordLowering::insertPadding() {
808 std::vector<std::pair<CharUnits, CharUnits>> padding;
809 CharUnits size = CharUnits::Zero();
810 for (const MemberInfo &member : members) {
811 if (!member.data)
812 continue;
813 // A consumer recovers a member's offset by accumulating the sizes of the
814 // members before it, so the padding a zero-width bit-field sits inside has
815 // to be split at its offset for that sum to come out right. The offset
816 // can sit behind the running size, since the access unit covering the bits
817 // around it may be wider than the offset it was declared at.
818 if (!ownsBytes(member)) {
819 if (member.offset > size) {
820 padding.push_back(std::make_pair(size, member.offset - size));
821 size = member.offset;
822 }
823 continue;
824 }
825 CharUnits offset = member.offset;
826 assert(offset >= size);
827 // Insert padding if we need to.
828 if (offset != size.alignTo(packed ? CharUnits::One()
829 : getMemberAlignment(member.data)))
830 padding.push_back(std::make_pair(size, offset - size));
831 size = offset + getSize(member.data);
832 }
833 if (padding.empty())
834 return;
835 // Add the padding to the Members list and sort it.
836 for (const std::pair<CharUnits, CharUnits> &paddingPair : padding)
837 members.push_back(makeStorageInfo(paddingPair.first,
838 getByteArrayType(paddingPair.second),
839 cir::RecordMemberKind::Pad));
840 llvm::stable_sort(members);
841}
842
843static cir::ArgPassingKind
845 switch (kind) {
847 return cir::ArgPassingKind::CanPassInRegs;
849 return cir::ArgPassingKind::CannotPassInRegs;
851 return cir::ArgPassingKind::CanNeverPassInRegs;
852 }
853 llvm_unreachable("unknown RecordArgPassingKind");
854}
855
856/// Whether the member kinds on \p recordTy answer the record's ABI emptiness
857/// the same way the AST predicate does.
858[[maybe_unused]] static bool
859marksMatchABIEmptiness(const ASTContext &astContext, const RecordDecl *rd,
860 cir::RecordType recordTy) {
861 return recordTy.isEmptyForABI() ==
862 isEmptyRecordForABI(astContext, astContext.getCanonicalTagType(rd));
863}
864
865std::unique_ptr<CIRGenRecordLayout>
867 CIRRecordLowering lowering(*this, rd, /*packed=*/false);
868 assert(ty->isIncomplete() && "recomputing record layout?");
869 lowering.lower(/*nonVirtualBaseType=*/false);
870
871 // If we're in C++, compute the base subobject type. For C++ records baseTy
872 // defaults to the complete object type and is replaced by a distinct,
873 // smaller record only when the record has tail padding an enclosing
874 // [[no_unique_address]] field can reuse. We must populate baseTy even when
875 // it equals ty because callers such as getStorageType(const CXXRecordDecl *)
876 // read it unconditionally when laying out potentially-overlapping
877 // ([[no_unique_address]]) fields; a null baseTy would otherwise propagate as
878 // a null mlir::Type into the members vector and trip the !empty() assertion
879 // in fillOutputFields.
880 cir::RecordType baseTy;
881 if (llvm::isa<CXXRecordDecl>(rd)) {
882 baseTy = *ty;
883 // A record needs a distinct base-subobject type when its tail padding can
884 // be reused by an enclosing [[no_unique_address]] field, i.e. when the
885 // non-virtual size differs from the complete size. This matches classic
886 // CodeGen and covers unions too: a union's non-virtual size already tracks
887 // its reusable tail padding (and stays at the minimum union size when the
888 // union is empty, so a zero-data union does not spuriously qualify).
889 if (lowering.astRecordLayout.getNonVirtualSize() !=
890 lowering.astRecordLayout.getSize()) {
891 CIRRecordLowering baseLowering(*this, rd, /*Packed=*/lowering.packed);
892 baseLowering.lower(/*nonVirtualBaseType=*/true);
893 std::string baseIdentifier = getRecordTypeName(rd, ".base");
894 baseTy = builder.getCompleteNamedRecordType(
895 baseLowering.getFieldTypes(), baseLowering.packed, baseIdentifier,
896 baseLowering.getFieldKinds());
897 // TODO(cir): add something like addRecordTypeName
898
899 // BaseTy and Ty must agree on their packedness for getCIRFieldNo to work
900 // on both of them with the same index. Unions are exempt: CIR derives a
901 // union's packedness from its layout size, which is the data size for the
902 // base subobject but the full size for the complete object, so the two
903 // can legitimately disagree. (Classic CodeGen derives both from the data
904 // size and so needs no such exemption.)
905 assert((rd->isUnion() || lowering.packed == baseLowering.packed) &&
906 "Non-virtual and complete types must agree on packedness");
907 // Emptiness is a property of the decl, so the base subobject must answer
908 // the same way the complete object does. The two are not comparable
909 // mark by mark: they see different sizes and so different tail padding.
910 assert((marksMatchABIEmptiness(astContext, rd, baseTy) ||
911 cgm.getDiags().hasErrorOccurred()) &&
912 "base subobject member kinds must reproduce its ABI emptiness");
913 }
914 }
915
916 // Fill in the record *after* computing the base type. Filling in the body
917 // signifies that the type is no longer opaque and record layout is complete,
918 // but we may need to recursively layout rd while laying D out as a base type.
920 ty->complete(lowering.getFieldTypes(), lowering.packed, lowering.unionPadding,
921 lowering.getFieldKinds());
922
923 // The marks exist so that emptiness can be read off the type, so check that
924 // answer against the AST predicate on every record CIRGen lays out. This
925 // does not check the individual marks, only what they add up to. The marks
926 // themselves are pinned by clang/test/CIR/CodeGen/record-member-kinds.*.
927 assert((marksMatchABIEmptiness(astContext, rd, *ty) ||
928 cgm.getDiags().hasErrorOccurred()) &&
929 "member kinds must reproduce the ABI emptiness of the record");
930
931 // Queue ABI metadata for the module-level cir.record_layouts attribute.
932 if (ty->getName()) {
933 mlir::MLIRContext *mlirCtx = ty->getContext();
934 cir::ArgPassingKind apk =
936
937 bool hasTrivialDestructor = true;
938 if (auto *cxxRD = dyn_cast<CXXRecordDecl>(rd))
939 hasTrivialDestructor = cxxRD->hasTrivialDestructor();
940 const auto &astLayout = astContext.getASTRecordLayout(rd);
941 uint64_t recordAlignInBytes = astLayout.getAlignment().getQuantity();
942
943 cgm.addRecordLayout(ty->getName(), cir::RecordLayoutAttr::get(
944 mlirCtx, apk, hasTrivialDestructor,
945 recordAlignInBytes));
946 }
947
948 auto rl = std::make_unique<CIRGenRecordLayout>(
949 ty ? *ty : cir::RecordType{}, baseTy ? baseTy : cir::RecordType{},
950 (bool)lowering.zeroInitializable, (bool)lowering.zeroInitializableAsBase);
951
952 rl->nonVirtualBases.swap(lowering.nonVirtualBases);
953 rl->completeObjectVirtualBases.swap(lowering.virtualBases);
954
955 // Add all the field numbers.
956 rl->fieldIdxMap.swap(lowering.fieldIdxMap);
957
958 rl->bitFields.swap(lowering.bitFields);
959
960 // Dump the layout, if requested.
961 if (getASTContext().getLangOpts().DumpRecordLayouts) {
962 llvm::outs() << "\n*** Dumping CIRgen Record Layout\n";
963 llvm::outs() << "Record: ";
964 rd->dump(llvm::outs());
965 llvm::outs() << "\nLayout: ";
966 rl->print(llvm::outs());
967 }
968
969 // TODO: implement verification
970 return rl;
971}
972
973void CIRGenRecordLayout::print(raw_ostream &os) const {
974 os << "<CIRecordLayout\n";
975 os << " CIR Type:" << completeObjectType << "\n";
976 if (baseSubobjectType)
977 os << " NonVirtualBaseCIRType:" << baseSubobjectType << "\n";
978 os << " IsZeroInitializable:" << zeroInitializable << "\n";
979 os << " BitFields:[\n";
980 std::vector<std::pair<unsigned, const CIRGenBitFieldInfo *>> bitInfo;
981 for (auto &[decl, info] : bitFields) {
982 const RecordDecl *rd = decl->getParent();
983 unsigned index = 0;
984 for (RecordDecl::field_iterator it = rd->field_begin(); *it != decl; ++it)
985 ++index;
986 bitInfo.push_back(std::make_pair(index, &info));
987 }
988 llvm::array_pod_sort(bitInfo.begin(), bitInfo.end());
989 for (std::pair<unsigned, const CIRGenBitFieldInfo *> &info : bitInfo) {
990 os.indent(4);
991 info.second->print(os);
992 os << "\n";
993 }
994 os << " ]>\n";
995}
996
997void CIRGenBitFieldInfo::print(raw_ostream &os) const {
998 os << "<CIRBitFieldInfo" << " name:" << name << " offset:" << offset
999 << " size:" << size << " isSigned:" << isSigned
1000 << " storageSize:" << storageSize
1001 << " storageOffset:" << storageOffset.getQuantity()
1002 << " volatileOffset:" << volatileOffset
1003 << " volatileStorageSize:" << volatileStorageSize
1004 << " volatileStorageOffset:" << volatileStorageOffset.getQuantity() << ">";
1005}
1006
1007void CIRGenRecordLayout::dump() const { print(llvm::errs()); }
1008
1009void CIRGenBitFieldInfo::dump() const { print(llvm::errs()); }
1010
1011void CIRRecordLowering::lowerUnion(bool nonVirtualBaseType) {
1012 // The base-subobject layout of a union is sized to its data size rather than
1013 // its full size. A union can have reusable tail padding when one of its
1014 // members is a [[no_unique_address]] field that itself has tail padding, so
1015 // an enclosing [[no_unique_address]] union field must use this smaller type.
1016 CharUnits layoutSize = nonVirtualBaseType ? astRecordLayout.getDataSize()
1017 : astRecordLayout.getSize();
1018 // Accumulate bitfields and fields, and figure out what our difference between
1019 // storage type and padding is.
1020
1021 // First, accumulate all the types.
1022 for (const FieldDecl *field : recordDecl->fields()) {
1023 mlir::Type fieldType;
1024 cir::RecordMemberKind fieldKind;
1025 if (field->isBitField()) {
1026 if (field->isZeroLengthBitField())
1027 continue;
1028 // Every variant starts at offset zero, so a bit-field variant is an
1029 // access unit of its own, holding that one field.
1030 mlir::Type unitStorage =
1031 getBitfieldStorageType(field->getBitWidthValue());
1032 setBitFieldInfo(field, CharUnits::Zero(), unitStorage);
1033 MemberInfo unit = makeAccessUnitInfo(CharUnits::Zero(), unitStorage,
1034 getBitFieldDecl(field));
1035 fieldType = unit.data;
1036 fieldKind = unit.memberKind;
1037 } else {
1038 fieldType = getStorageType(field);
1039 fieldKind = getFieldMemberKind(field);
1040 }
1041
1042 fieldIdxMap[field->getCanonicalDecl()] = 0;
1043 addField(fieldType, fieldKind);
1044 }
1045
1046 // Compute zero-initializable status.
1047 // This union might not be zero initialized: it may contain a pointer to
1048 // data member which might have some exotic initialization sequence.
1049 // This chooses the first 'named' member and is zero-initializable based on
1050 // that.
1051 auto hasNamedMember = [](const FieldDecl *curField) -> bool {
1052 const auto *rd = curField->getType()->getAsRecordDecl();
1053 return rd && rd->findFirstNamedDataMember();
1054 };
1055 // Whether this is usable for zero-init as a 'named member'. It is a field
1056 // with a name (or a record type with a named member itself), that isn't a
1057 // zero-width bitfield.
1058 auto isNamedMember = [hasNamedMember](const FieldDecl *curField) -> bool {
1059 if (curField->isZeroLengthBitField())
1060 return false;
1061 return curField->getIdentifier() || hasNamedMember(curField);
1062 };
1063 auto firstNamedMemberItr = llvm::find_if(recordDecl->fields(), isNamedMember);
1064
1065 if (firstNamedMemberItr != recordDecl->fields().end() &&
1066 !isZeroInitializable(*firstNamedMemberItr))
1067 zeroInitializable = zeroInitializableAsBase = false;
1068
1069 // If we have no candidates for storage, we are JUST padding.
1070 if (getFieldTypes().empty()) {
1071 appendPaddingBytes(layoutSize);
1072 return;
1073 }
1074
1075 mlir::Type storageType =
1076 cir::UnionType::getUnionStorageType(dataLayout.layout, getFieldTypes());
1077
1078 // If our storage size was bigger than our required size (can happen in the
1079 // case of packed bitfields on Itanium) then just use an I8 array.
1080 if (layoutSize < getSize(storageType))
1081 storageType = getByteArrayType(layoutSize);
1082
1083 // The base-subobject record is built as a struct from fieldTypes, so add
1084 // the storage type and any trailing padding as ordinary fields rather than
1085 // routing padding through the union's single tail-padding slot.
1086 if (nonVirtualBaseType) {
1087 // A bit-field mark here says the stand-in's extent is not a declared
1088 // extent, not that its storage came from a bit-field: UnionBitAndWide in
1089 // clang/test/CIR/CodeGen/no-unique-address.cpp takes its double as storage
1090 // and still marks bitfield. The stand-in describes every variant, so it
1091 // takes the storage type rather than any one variant's `!cir.bitfield`,
1092 // and is the one bit-field-marked member that is not one. Computed before
1093 // clearFields() drops the variant marks.
1094 const cir::RecordMemberKind storageKind = makeMemberKind(
1095 /*holdsData=*/cir::anyMemberHoldsDataForABI(getFieldKinds()),
1096 /*isNamedBitField=*/llvm::any_of(getFieldKinds(),
1098 clearFields();
1099 addField(storageType, storageKind);
1100 CharUnits padding = layoutSize - getSize(storageType);
1101 if (!padding.isZero())
1102 addField(getByteArrayType(padding), cir::RecordMemberKind::Pad);
1103 } else {
1104 // Else we just add padding normally.
1105 appendPaddingBytes(layoutSize - getSize(storageType));
1106 }
1107 packed = !layoutSize.isMultipleOf(getMemberAlignment(storageType));
1108}
1109
1110bool CIRRecordLowering::hasOwnStorage(const CXXRecordDecl *decl,
1111 const CXXRecordDecl *query) {
1112 const ASTRecordLayout &declLayout = astContext.getASTRecordLayout(decl);
1113 if (declLayout.isPrimaryBaseVirtual() && declLayout.getPrimaryBase() == query)
1114 return false;
1115 for (const auto &base : decl->bases())
1116 if (!hasOwnStorage(base.getType()->getAsCXXRecordDecl(), query))
1117 return false;
1118 return true;
1119}
1120
1121/// The AAPCS that defines that, when possible, bit-fields should
1122/// be accessed using containers of the declared type width:
1123/// When a volatile bit-field is read, and its container does not overlap with
1124/// any non-bit-field member or any zero length bit-field member, its container
1125/// must be read exactly once using the access width appropriate to the type of
1126/// the container. When a volatile bit-field is written, and its container does
1127/// not overlap with any non-bit-field member or any zero-length bit-field
1128/// member, its container must be read exactly once and written exactly once
1129/// using the access width appropriate to the type of the container. The two
1130/// accesses are not atomic.
1131///
1132/// Enforcing the width restriction can be disabled using
1133/// -fno-aapcs-bitfield-width.
1134void CIRRecordLowering::computeVolatileBitfields() {
1135 if (!CodeGenUtils::isAAPCS(astContext.getTargetInfo()) ||
1136 !cirGenTypes.getCGModule().getCodeGenOpts().AAPCSBitfieldWidth)
1137 return;
1138
1139 for (auto &[field, info] : bitFields) {
1140 mlir::Type resLTy = cirGenTypes.convertTypeForMem(field->getType());
1141
1142 if (astContext.toBits(astRecordLayout.getAlignment()) <
1143 getSizeInBits(resLTy).getQuantity())
1144 continue;
1145
1146 // CIRRecordLowering::setBitFieldInfo() pre-adjusts the bit-field offsets
1147 // for big-endian targets, but it assumes a container of width
1148 // info.storageSize. Since AAPCS uses a different container size (width
1149 // of the type), we first undo that calculation here and redo it once
1150 // the bit-field offset within the new container is calculated.
1151 const unsigned oldOffset =
1152 isBigEndian() ? info.storageSize - (info.offset + info.size)
1153 : info.offset;
1154 // Offset to the bit-field from the beginning of the struct.
1155 const unsigned absoluteOffset =
1156 astContext.toBits(info.storageOffset) + oldOffset;
1157
1158 // Container size is the width of the bit-field type.
1159 const unsigned storageSize = getSizeInBits(resLTy).getQuantity();
1160 // Nothing to do if the access uses the desired
1161 // container width and is naturally aligned.
1162 if (info.storageSize == storageSize && (oldOffset % storageSize == 0))
1163 continue;
1164
1165 // Offset within the container.
1166 unsigned offset = absoluteOffset & (storageSize - 1);
1167 // Bail out if an aligned load of the container cannot cover the entire
1168 // bit-field. This can happen for example, if the bit-field is part of a
1169 // packed struct. AAPCS does not define access rules for such cases, we let
1170 // clang to follow its own rules.
1171 if (offset + info.size > storageSize)
1172 continue;
1173
1174 // Re-adjust offsets for big-endian targets.
1175 if (isBigEndian())
1176 offset = storageSize - (offset + info.size);
1177
1178 const CharUnits storageOffset =
1179 astContext.toCharUnitsFromBits(absoluteOffset & ~(storageSize - 1));
1180 const CharUnits end = storageOffset +
1181 astContext.toCharUnitsFromBits(storageSize) -
1183
1184 const ASTRecordLayout &layout =
1185 astContext.getASTRecordLayout(field->getParent());
1186 // If we access outside memory outside the record, than bail out.
1187 const CharUnits recordSize = layout.getSize();
1188 if (end >= recordSize)
1189 continue;
1190
1191 // Bail out if performing this load would access non-bit-fields members.
1192 bool conflict = false;
1193 for (const auto *f : recordDecl->fields()) {
1194 // Allow sized bit-fields overlaps.
1195 if (f->isBitField() && !f->isZeroLengthBitField())
1196 continue;
1197
1198 const CharUnits fOffset = astContext.toCharUnitsFromBits(
1199 layout.getFieldOffset(f->getFieldIndex()));
1200
1201 // As C11 defines, a zero sized bit-field defines a barrier, so
1202 // fields after and before it should be race condition free.
1203 // The AAPCS acknowledges it and imposes no restritions when the
1204 // natural container overlaps a zero-length bit-field.
1205 if (f->isZeroLengthBitField()) {
1206 if (end > fOffset && storageOffset < fOffset) {
1207 conflict = true;
1208 break;
1209 }
1210 }
1211
1212 const CharUnits fEnd =
1213 fOffset +
1214 astContext.toCharUnitsFromBits(
1215 getSizeInBits(cirGenTypes.convertTypeForMem(f->getType()))
1216 .getQuantity()) -
1218 // If no overlap, continue.
1219 if (end < fOffset || fEnd < storageOffset)
1220 continue;
1221
1222 // The desired load overlaps a non-bit-field member, bail out.
1223 conflict = true;
1224 break;
1225 }
1226
1227 if (conflict)
1228 continue;
1229 // Write the new bit-field access parameters.
1230 // As the storage offset now is defined as the number of elements from the
1231 // start of the structure, we should divide the Offset by the element size.
1232 info.volatileStorageOffset =
1233 storageOffset /
1234 astContext.toCharUnitsFromBits(storageSize).getQuantity();
1235 info.volatileStorageSize = storageSize;
1236 info.volatileOffset = offset;
1237 }
1238}
1239
1240void CIRRecordLowering::accumulateBases() {
1241 // If we've got a primary virtual base, we need to add it with the bases.
1242 if (astRecordLayout.isPrimaryBaseVirtual()) {
1243 const CXXRecordDecl *baseDecl = astRecordLayout.getPrimaryBase();
1244 members.push_back(MemberInfo(CharUnits::Zero(), MemberInfo::InfoKind::Base,
1245 getStorageType(baseDecl),
1246 getBaseMemberKind(baseDecl), baseDecl));
1247 }
1248
1249 // Accumulate the non-virtual bases.
1250 for (const auto &base : cxxRecordDecl->bases()) {
1251 if (base.isVirtual())
1252 continue;
1253 // Bases can be zero-sized even if not technically empty if they
1254 // contain only a trailing array member.
1255 const CXXRecordDecl *baseDecl = base.getType()->getAsCXXRecordDecl();
1256 if (!baseDecl->isEmpty() &&
1257 !astContext.getASTRecordLayout(baseDecl).getNonVirtualSize().isZero()) {
1258 members.push_back(MemberInfo(astRecordLayout.getBaseClassOffset(baseDecl),
1259 MemberInfo::InfoKind::Base,
1260 getStorageType(baseDecl),
1261 getBaseMemberKind(baseDecl), baseDecl));
1262 }
1263 }
1264}
1265
1266void CIRRecordLowering::accumulateVBases() {
1267 for (const auto &base : cxxRecordDecl->vbases()) {
1268 const CXXRecordDecl *baseDecl = base.getType()->getAsCXXRecordDecl();
1269 if (isEmptyRecordForLayout(astContext, base.getType()))
1270 continue;
1271 CharUnits offset = astRecordLayout.getVBaseClassOffset(baseDecl);
1272 // If the vbase is a primary virtual base of some base, then it doesn't
1273 // get its own storage location but instead lives inside of that base.
1274 if (isOverlappingVBaseABI() && astContext.isNearlyEmpty(baseDecl) &&
1275 !hasOwnStorage(cxxRecordDecl, baseDecl)) {
1276 members.push_back(MemberInfo(offset, MemberInfo::InfoKind::VBase, nullptr,
1277 cir::RecordMemberKind::Data, baseDecl));
1278 continue;
1279 }
1280 // If we've got a vtordisp, add it as a storage type.
1281 if (astRecordLayout.getVBaseOffsetsMap()
1282 .find(baseDecl)
1283 ->second.hasVtorDisp())
1284 members.push_back(makeStorageInfo(offset - CharUnits::fromQuantity(4),
1285 getUIntNType(32),
1286 cir::RecordMemberKind::Data));
1287 members.push_back(MemberInfo(offset, MemberInfo::InfoKind::VBase,
1288 getStorageType(baseDecl),
1289 getBaseMemberKind(baseDecl), baseDecl));
1290 }
1291}
1292
1293void CIRRecordLowering::accumulateVPtrs() {
1294 if (astRecordLayout.hasOwnVFPtr())
1295 members.push_back(MemberInfo(CharUnits::Zero(), MemberInfo::InfoKind::VFPtr,
1296 getVFPtrType(), cir::RecordMemberKind::Data));
1297
1298 if (astRecordLayout.hasOwnVBPtr())
1299 cirGenTypes.getCGModule().errorNYI(recordDecl->getSourceRange(),
1300 "accumulateVPtrs: hasOwnVBPtr");
1301}
1302
1303mlir::Type CIRRecordLowering::getVFPtrType() {
1304 return cir::VPtrType::get(builder.getContext());
1305}
Defines the clang::ASTContext interface.
static bool marksMatchABIEmptiness(const ASTContext &astContext, const RecordDecl *rd, cir::RecordType recordTy)
Whether the member kinds on recordTy answer the record's ABI emptiness the same way the AST predicate...
static cir::ArgPassingKind convertRecordArgPassingKind(RecordArgPassingKind kind)
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)
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
mlir::DataLayout layout
bool isBigEndian() const
llvm::TypeSize getTypeAllocSizeInBits(mlir::Type ty) const
Returns the offset in bits between successive objects of the specified type, including alignment padd...
C++ view class that accepts both !cir.struct and !cir.union types.
Definition CIRTypes.h:149
bool isIncomplete() const
Definition CIRTypes.cpp:619
bool isEmptyForABI() const
Whether no member holds data.
Definition CIRTypes.cpp:702
mlir::StringAttr getName() const
Definition CIRTypes.cpp:614
void complete(llvm::ArrayRef< mlir::Type > members, bool packed, mlir::Type padding, llvm::ArrayRef< RecordMemberKind > memberKinds)
padding is union-only.
Definition CIRTypes.cpp:657
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
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:947
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
CanQualType getCanonicalTagType(const TagDecl *TD) const
uint64_t getCharWidth() const
Return the size of the character type, in bits.
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.
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
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...
DiagnosticBuilder errorNYI(SourceLocation, llvm::StringRef)
Helpers to emit "not yet implemented" error diagnostics.
const clang::CodeGenOptions & getCodeGenOpts() const
This class organizes the cross-module state that is used while lowering AST types to CIR types.
Definition CIRGenTypes.h:51
CIRGenModule & getCGModule() const
Definition CIRGenTypes.h:91
std::string getRecordTypeName(const clang::RecordDecl *, llvm::StringRef suffix)
clang::ASTContext & getASTContext() const
std::unique_ptr< CIRGenRecordLayout > computeRecordLayout(const clang::RecordDecl *rd, cir::RecordType *ty)
mlir::Type convertTypeForMem(clang::QualType, bool forBitField=false)
Convert type T into an mlir::Type.
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition DeclCXX.h:1195
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition CharUnits.h:122
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition CharUnits.h:58
bool isMultipleOf(CharUnits N) const
Test whether this is a multiple of the other value.
Definition CharUnits.h:143
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:63
CharUnits alignTo(const CharUnits &Align) const
alignTo - Returns the next integer (mod 2**64) that is greater than or equal to this quantity and is ...
Definition CharUnits.h:201
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition CharUnits.h:53
void dump() const
Represents a member of a struct/union/class.
Definition Decl.h:3295
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3398
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4816
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition Decl.h:3542
bool isUnnamedBitField() const
Determines whether this is an unnamed bitfield.
Definition Decl.h:3401
bool isZeroLengthBitField() const
Is this a zero-length bit-field?
Definition Decl.cpp:4825
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:302
Represents a struct/union/class.
Definition Decl.h:4460
RecordArgPassingKind getArgPassingRestrictions() const
Definition Decl.h:4601
const FieldDecl * findFirstNamedDataMember() const
Finds the first data member which has a name.
Definition Decl.cpp:5468
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4660
field_iterator field_begin() const
Definition Decl.cpp:5339
bool isUnion() const
Definition Decl.h:4063
virtual unsigned getRegisterWidth() const
Return the "preferred" register width on this target.
Definition TargetInfo.h:900
bool hasCheapUnalignedBitFieldAccess() const
Return true iff unaligned accesses are cheap.
Definition TargetInfo.h:914
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2319
QualType getType() const
Definition Decl.h:724
mlir::Type memberStorageType(mlir::Type memberTy)
The storage a member is stored as: the access unit for a bit-field member, and the member type itself...
Definition CIRTypes.h:134
bool memberOwnsBytes(mlir::Type memberTy)
Whether a record member occupies bytes of its record.
Definition CIRTypes.h:125
bool isValidFundamentalIntWidth(unsigned width)
bool anyMemberHoldsDataForABI(llvm::ArrayRef< RecordMemberKind > kinds)
Whether any member holds data for argument passing on its mark alone.
Definition CIRTypes.h:52
bool isNamedBitField(RecordMemberKind kind)
Whether a member of this kind is an access unit the source can read a bit-field of.
Definition CIRTypes.h:64
bool isEmptyRecordForABI(const ASTContext &context, QualType t)
isEmptyRecordForABI - Return true if a structure contains only empty base classes and fields.
bool isEmptyFieldForABI(const ASTContext &context, const FieldDecl *fd)
isEmptyFieldForABI - Return true if the field is "empty", that is, it is a zero-width bit-field or an...
bool isEmptyFieldForLayout(const ASTContext &context, const FieldDecl *fd)
isEmptyFieldForLayout - Return true if the field is "empty", that is, either a zero-width bit-field o...
bool isEmptyRecordForLayout(const ASTContext &context, QualType t)
isEmptyRecordForLayout - Return true if a structure contains only empty base classes (per isEmptyReco...
bool isAAPCS(const TargetInfo &TargetInfo)
Helper method to check if the underlying ABI is AAPCS.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::VariadicDynCastAllOfMatcher< Decl, FieldDecl > fieldDecl
Matches field declarations.
const internal::VariadicDynCastAllOfMatcher< Decl, CXXRecordDecl > cxxRecordDecl
Matches C++ class declarations.
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
const internal::VariadicDynCastAllOfMatcher< Decl, RecordDecl > recordDecl
Matches class, struct, and union declarations.
void info(bool Verbose, unsigned Level, const char *Fmt, Ts &&...Args)
Prints an indented note to stderr when Verbose is set.
Definition Utils.h:57
RangeSelector member(std::string ID)
Given a MemberExpr, selects the member token. ID is the node's binding in the match result.
Stencil run(MatchConsumer< std::string > C)
Wraps a MatchConsumer in a Stencil, so that it can be used in a Stencil.
Definition Stencil.cpp:489
Top level wrappers for InstallAPI frontend operations.
bool operator<(DeclarationName LHS, DeclarationName RHS)
Ordering on two declaration names.
RecordArgPassingKind
Enum that represents the different ways arguments are passed to and returned from function calls.
Definition Decl.h:4437
@ CanPassInRegs
The argument of this type can be passed directly in registers.
Definition Decl.h:4439
@ CanNeverPassInRegs
The argument of this type cannot be passed directly in registers.
Definition Decl.h:4453
@ CannotPassInRegs
The argument of this type cannot be passed directly in registers.
Definition Decl.h:4448
unsigned long uint64_t
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
void __ovld __conv barrier(cl_mem_fence_flags)
All work-items in a work-group executing the kernel on a processor must execute this function before ...
#define true
Definition stdbool.h:25
static bool noUniqueAddressLayout()
static bool checkBitfieldClipping()
static bool astRecordDeclAttr()
unsigned offset
The offset within a contiguous run of bitfields that are represented as a single "field" within the c...
void print(llvm::raw_ostream &os) const
unsigned storageSize
The storage size in bits which should be used when accessing this bitfield.
unsigned volatileStorageSize
The storage size in bits which should be used when accessing this bitfield.
clang::CharUnits storageOffset
The offset of the bitfield storage from the start of the record.
unsigned size
The total size of the bit-field, in bits.
unsigned isSigned
Whether the bit-field is signed.
clang::CharUnits volatileStorageOffset
The offset of the bitfield storage from the start of the record.
unsigned volatileOffset
The offset within a contiguous run of bitfields that are represented as a single "field" within the c...
llvm::StringRef name
The name of a bitfield.