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 // Unaligned accesses are expensive. Only accumulate if the new unit
605 // is naturally aligned. Otherwise install the best we have, which is
606 // either the initial access unit (can't do better), or a naturally
607 // aligned accumulation (since we would have already installed it if
608 // it wasn't naturally aligned).
609 CharUnits align = getMemberAlignment(type);
610 if (align > astRecordLayout.getAlignment()) {
611 // The alignment required is greater than the containing structure
612 // itself.
613 installBest = true;
614 } else if (!beginOffset.isMultipleOf(align)) {
615 // The access unit is not at a naturally aligned offset within the
616 // structure.
617 installBest = true;
618 }
619
620 if (installBest && bestEnd == field) {
621 // We're installing the first span, whose clipping was presumed
622 // above. Compute it correctly.
623 if (getSize(type) == accessSize)
624 bestClipped = false;
625 }
626 }
627
628 if (!installBest) {
629 // Find the next used storage offset to determine what the limit of
630 // the current span is. That's either the offset of the next field
631 // with storage (which might be field itself) or the end of the
632 // non-reusable tail padding.
633 CharUnits limitOffset;
634 for (auto probe = field; probe != fieldEnd; ++probe)
635 if (!isEmptyFieldForLayout(astContext, *probe)) {
636 // A member with storage sets the limit.
637 assert((getFieldBitOffset(*probe) % charBits) == 0 &&
638 "Next storage is not byte-aligned");
639 limitOffset = bitsToCharUnits(getFieldBitOffset(*probe));
640 goto FoundLimit;
641 }
642 limitOffset = cxxRecordDecl ? astRecordLayout.getNonVirtualSize()
643 : astRecordLayout.getDataSize();
644
645 FoundLimit:
646 CharUnits typeSize = getSize(type);
647 if (beginOffset + typeSize <= limitOffset) {
648 // There is space before limitOffset to create a naturally-sized
649 // access unit.
650 bestEndOffset = beginOffset + typeSize;
651 bestEnd = field;
652 bestClipped = false;
653 }
654 if (barrier) {
655 // The next field is a barrier that we cannot merge across.
656 installBest = true;
657 } else if (cirGenTypes.getCGModule()
659 .FineGrainedBitfieldAccesses) {
660 installBest = true;
661 } else {
662 // Otherwise, we're not installing. Update the bit size
663 // of the current span to go all the way to limitOffset, which is
664 // the (aligned) offset of next bitfield to consider.
665 bitSizeSinceBegin = astContext.toBits(limitOffset - beginOffset);
666 }
667 }
668 }
669 }
670
671 if (installBest) {
672 assert((field == fieldEnd || !field->isBitField() ||
673 (getFieldBitOffset(*field) % charBits) == 0) &&
674 "Installing but not at an aligned bitfield or limit");
675 CharUnits accessSize = bestEndOffset - beginOffset;
676 if (!accessSize.isZero()) {
677 // Add the storage member for the access unit to the record. The
678 // bitfields get the offset of their storage but come afterward and
679 // remain there after a stable sort.
680 mlir::Type type;
681 if (bestClipped) {
682 assert(getSize(getUIntNType(astContext.toBits(accessSize))) >
683 accessSize &&
684 "Clipped access need not be clipped");
685 type = getByteArrayType(accessSize);
686 } else {
687 type = getUIntNType(astContext.toBits(accessSize));
688 assert(getSize(type) == accessSize &&
689 "Unclipped access must be clipped");
690 }
691 // A zero-length bit-field in the span was given a member of its own
692 // when it was accumulated, and belongs to no access unit, so it is not
693 // one of the fields this unit holds.
694 llvm::SmallVector<cir::BitFieldDeclAttr> unitFields;
695 for (auto occupant = begin; occupant != bestEnd; ++occupant)
696 if (!occupant->isZeroLengthBitField())
697 unitFields.push_back(getBitFieldDecl(*occupant));
698 assert(!unitFields.empty() && "an access unit holds a bit-field");
699 members.push_back(makeAccessUnitInfo(beginOffset, type, unitFields));
700
701 for (; begin != bestEnd; ++begin)
702 if (!begin->isZeroLengthBitField())
703 members.push_back(MemberInfo(beginOffset,
704 MemberInfo::InfoKind::Field, nullptr,
705 cir::RecordMemberKind::Data, *begin));
706 }
707 // Reset to start a new span.
708 field = bestEnd;
709 begin = fieldEnd;
710 } else {
711 assert(field != fieldEnd && field->isBitField() &&
712 "Accumulating past end of bitfields");
713 assert(!barrier && "Accumulating across barrier");
714 if (field->isZeroLengthBitField())
715 members.push_back(makeZeroWidthBitFieldInfo(*field));
716 // Accumulate this bitfield into the current (potential) span.
717 bitSizeSinceBegin += field->getBitWidthValue();
718 ++field;
719 }
720 }
721
722 return field;
723}
724
725void CIRRecordLowering::accumulateFields(bool nonVirtualBaseType) {
726 for (RecordDecl::field_iterator field = recordDecl->field_begin(),
727 fieldEnd = recordDecl->field_end();
728 field != fieldEnd;) {
729 if (field->isBitField()) {
730 field = accumulateBitFields(field, fieldEnd);
731 assert((field == fieldEnd || !field->isBitField()) &&
732 "Failed to accumulate all the bitfields");
733 } else if (isEmptyFieldForLayout(astContext, *field) &&
734 field->isPotentiallyOverlapping()) {
735 // We lay out normal empty fields, as they are required for GEPs/getting
736 // function pointers. However 'no-unique-address' lends some additional
737 // complexity. These fields take up no real space, but would also have to
738 // be the correct 'GEP' offset to work here, but then mess with the
739 // layout. We likely need to come up with a new 'type' to support these,
740 // then figure out some way to lower these to the correct offset, likely
741 // by calculating the correct offset into the struct, and forming a
742 // replacement by-byte GEP in LowerToLLVM. However, this is only a
743 // problem with taking the address of one of these, so it is in practice
744 // not a horrifyingly problematic issue.
746 // Dropping the field leaves no member to mark, so its bytes read as
747 // padding. That is only sound when the field carries no ABI data, so
748 // make sure we add a member for it. if it does.
749 if (!isEmptyFieldForABI(astContext, *field))
750 members.push_back(
751 MemberInfo(bitsToCharUnits(getFieldBitOffset(*field)),
752 MemberInfo::InfoKind::Field,
753 getStorageType(field->getType()->getAsCXXRecordDecl()),
754 getFieldMemberKind(*field), *field));
755 ++field;
756 } else {
757 // Use base subobject layout for potentially-overlapping fields,
758 // as it is done in RecordLayoutBuilder.
759 //
760 // The mark comes from isEmptyFieldForABI, not the isEmptyFieldForLayout
761 // above. Neither predicate subsumes the other.
762 members.push_back(MemberInfo(
763 bitsToCharUnits(getFieldBitOffset(*field)),
764 MemberInfo::InfoKind::Field,
765 field->isPotentiallyOverlapping()
766 ? getStorageType(field->getType()->getAsCXXRecordDecl())
767 : getStorageType(*field),
768 getFieldMemberKind(*field), *field));
769 ++field;
770 }
771 }
772}
773
774void CIRRecordLowering::calculateZeroInit() {
775 for (const MemberInfo &member : members) {
776 if (member.kind == MemberInfo::InfoKind::Field) {
777 if (!member.fieldDecl || isZeroInitializable(member.fieldDecl))
778 continue;
779 zeroInitializable = zeroInitializableAsBase = false;
780 return;
781 } else if (member.kind == MemberInfo::InfoKind::Base ||
782 member.kind == MemberInfo::InfoKind::VBase) {
783 if (isZeroInitializable(member.cxxRecordDecl))
784 continue;
785 zeroInitializable = false;
786 if (member.kind == MemberInfo::InfoKind::Base)
787 zeroInitializableAsBase = false;
788 }
789 }
790}
791
792void CIRRecordLowering::determinePacked(bool nvBaseType) {
793 if (packed)
794 return;
795 CharUnits alignment = CharUnits::One();
796 CharUnits nvAlignment = CharUnits::One();
797 CharUnits nvSize = !nvBaseType && cxxRecordDecl
798 ? astRecordLayout.getNonVirtualSize()
799 : CharUnits::Zero();
800
801 for (const MemberInfo &member : members) {
802 // A member that owns no bytes sits inside another member's storage, whose
803 // own offset and alignment are what decide packing.
804 if (!ownsBytes(member))
805 continue;
806 // If any member falls at an offset that it not a multiple of its alignment,
807 // then the entire record must be packed.
808 if (!member.offset.isMultipleOf(getMemberAlignment(member.data)))
809 packed = true;
810 if (member.offset < nvSize)
811 nvAlignment = std::max(nvAlignment, getMemberAlignment(member.data));
812 alignment = std::max(alignment, getMemberAlignment(member.data));
813 }
814 // If the size of the record (the capstone's offset) is not a multiple of the
815 // record's alignment, it must be packed.
816 if (!members.back().offset.isMultipleOf(alignment))
817 packed = true;
818 // If the non-virtual sub-object is not a multiple of the non-virtual
819 // sub-object's alignment, it must be packed. We cannot have a packed
820 // non-virtual sub-object and an unpacked complete object or vise versa.
821 if (!nvSize.isMultipleOf(nvAlignment))
822 packed = true;
823 // Update the alignment of the sentinel.
824 if (!packed)
825 members.back().data = getUIntNType(astContext.toBits(alignment));
826}
827
828void CIRRecordLowering::insertPadding() {
829 std::vector<std::pair<CharUnits, CharUnits>> padding;
830 CharUnits size = CharUnits::Zero();
831 for (const MemberInfo &member : members) {
832 if (!member.data)
833 continue;
834 // A consumer recovers a member's offset by accumulating the sizes of the
835 // members before it, so the padding a zero-width bit-field sits inside has
836 // to be split at its offset for that sum to come out right. The offset
837 // can sit behind the running size, since the access unit covering the bits
838 // around it may be wider than the offset it was declared at.
839 if (!ownsBytes(member)) {
840 if (member.offset > size) {
841 padding.push_back(std::make_pair(size, member.offset - size));
842 size = member.offset;
843 }
844 continue;
845 }
846 CharUnits offset = member.offset;
847 assert(offset >= size);
848 // Insert padding if we need to.
849 if (offset != size.alignTo(packed ? CharUnits::One()
850 : getMemberAlignment(member.data)))
851 padding.push_back(std::make_pair(size, offset - size));
852 size = offset + getSize(member.data);
853 }
854 if (padding.empty())
855 return;
856 // Add the padding to the Members list and sort it.
857 for (const std::pair<CharUnits, CharUnits> &paddingPair : padding)
858 members.push_back(makeStorageInfo(paddingPair.first,
859 getByteArrayType(paddingPair.second),
860 cir::RecordMemberKind::Pad));
861 llvm::stable_sort(members);
862}
863
864static cir::ArgPassingKind
866 switch (kind) {
868 return cir::ArgPassingKind::CanPassInRegs;
870 return cir::ArgPassingKind::CannotPassInRegs;
872 return cir::ArgPassingKind::CanNeverPassInRegs;
873 }
874 llvm_unreachable("unknown RecordArgPassingKind");
875}
876
877/// Whether the member kinds on \p recordTy answer the record's ABI emptiness
878/// the same way the AST predicate does.
879[[maybe_unused]] static bool
880marksMatchABIEmptiness(const ASTContext &astContext, const RecordDecl *rd,
881 cir::RecordType recordTy) {
882 return recordTy.isEmptyForABI() ==
883 isEmptyRecordForABI(astContext, astContext.getCanonicalTagType(rd));
884}
885
886std::unique_ptr<CIRGenRecordLayout>
888 CIRRecordLowering lowering(*this, rd, /*packed=*/false);
889 assert(ty->isIncomplete() && "recomputing record layout?");
890 lowering.lower(/*nonVirtualBaseType=*/false);
891
892 // If we're in C++, compute the base subobject type. For C++ records baseTy
893 // defaults to the complete object type and is replaced by a distinct,
894 // smaller record only when the record has tail padding an enclosing
895 // [[no_unique_address]] field can reuse. We must populate baseTy even when
896 // it equals ty because callers such as getStorageType(const CXXRecordDecl *)
897 // read it unconditionally when laying out potentially-overlapping
898 // ([[no_unique_address]]) fields; a null baseTy would otherwise propagate as
899 // a null mlir::Type into the members vector and trip the !empty() assertion
900 // in fillOutputFields.
901 cir::RecordType baseTy;
902 if (llvm::isa<CXXRecordDecl>(rd)) {
903 baseTy = *ty;
904 // A record needs a distinct base-subobject type when its tail padding can
905 // be reused by an enclosing [[no_unique_address]] field, i.e. when the
906 // non-virtual size differs from the complete size. This matches classic
907 // CodeGen and covers unions too: a union's non-virtual size already tracks
908 // its reusable tail padding (and stays at the minimum union size when the
909 // union is empty, so a zero-data union does not spuriously qualify).
910 if (lowering.astRecordLayout.getNonVirtualSize() !=
911 lowering.astRecordLayout.getSize()) {
912 CIRRecordLowering baseLowering(*this, rd, /*Packed=*/lowering.packed);
913 baseLowering.lower(/*nonVirtualBaseType=*/true);
914 std::string baseIdentifier = getRecordTypeName(rd, ".base");
915 baseTy = builder.getCompleteNamedRecordType(
916 baseLowering.getFieldTypes(), baseLowering.packed, baseIdentifier,
917 baseLowering.getFieldKinds());
918 // TODO(cir): add something like addRecordTypeName
919
920 // BaseTy and Ty must agree on their packedness for getCIRFieldNo to work
921 // on both of them with the same index. Unions are exempt: CIR derives a
922 // union's packedness from its layout size, which is the data size for the
923 // base subobject but the full size for the complete object, so the two
924 // can legitimately disagree. (Classic CodeGen derives both from the data
925 // size and so needs no such exemption.)
926 assert((rd->isUnion() || lowering.packed == baseLowering.packed) &&
927 "Non-virtual and complete types must agree on packedness");
928 // Emptiness is a property of the decl, so the base subobject must answer
929 // the same way the complete object does. The two are not comparable
930 // mark by mark: they see different sizes and so different tail padding.
931 assert((marksMatchABIEmptiness(astContext, rd, baseTy) ||
932 cgm.getDiags().hasErrorOccurred()) &&
933 "base subobject member kinds must reproduce its ABI emptiness");
934 }
935 }
936
937 // Fill in the record *after* computing the base type. Filling in the body
938 // signifies that the type is no longer opaque and record layout is complete,
939 // but we may need to recursively layout rd while laying D out as a base type.
941 ty->complete(lowering.getFieldTypes(), lowering.packed, lowering.unionPadding,
942 lowering.getFieldKinds());
943
944 // The marks exist so that emptiness can be read off the type, so check that
945 // answer against the AST predicate on every record CIRGen lays out. This
946 // does not check the individual marks, only what they add up to. The marks
947 // themselves are pinned by clang/test/CIR/CodeGen/record-member-kinds.*.
948 assert((marksMatchABIEmptiness(astContext, rd, *ty) ||
949 cgm.getDiags().hasErrorOccurred()) &&
950 "member kinds must reproduce the ABI emptiness of the record");
951
952 // Queue ABI metadata for the module-level cir.record_layouts attribute.
953 if (ty->getName()) {
954 mlir::MLIRContext *mlirCtx = ty->getContext();
955 cir::ArgPassingKind apk =
957
958 bool hasTrivialDestructor = true;
959 if (auto *cxxRD = dyn_cast<CXXRecordDecl>(rd))
960 hasTrivialDestructor = cxxRD->hasTrivialDestructor();
961 const auto &astLayout = astContext.getASTRecordLayout(rd);
962 uint64_t recordAlignInBytes = astLayout.getAlignment().getQuantity();
963
964 cgm.addRecordLayout(ty->getName(), cir::RecordLayoutAttr::get(
965 mlirCtx, apk, hasTrivialDestructor,
966 recordAlignInBytes));
967 }
968
969 auto rl = std::make_unique<CIRGenRecordLayout>(
970 ty ? *ty : cir::RecordType{}, baseTy ? baseTy : cir::RecordType{},
971 (bool)lowering.zeroInitializable, (bool)lowering.zeroInitializableAsBase);
972
973 rl->nonVirtualBases.swap(lowering.nonVirtualBases);
974 rl->completeObjectVirtualBases.swap(lowering.virtualBases);
975
976 // Add all the field numbers.
977 rl->fieldIdxMap.swap(lowering.fieldIdxMap);
978
979 rl->bitFields.swap(lowering.bitFields);
980
981 // Dump the layout, if requested.
982 if (getASTContext().getLangOpts().DumpRecordLayouts) {
983 llvm::outs() << "\n*** Dumping CIRgen Record Layout\n";
984 llvm::outs() << "Record: ";
985 rd->dump(llvm::outs());
986 llvm::outs() << "\nLayout: ";
987 rl->print(llvm::outs());
988 }
989
990 // TODO: implement verification
991 return rl;
992}
993
994void CIRGenRecordLayout::print(raw_ostream &os) const {
995 os << "<CIRecordLayout\n";
996 os << " CIR Type:" << completeObjectType << "\n";
997 if (baseSubobjectType)
998 os << " NonVirtualBaseCIRType:" << baseSubobjectType << "\n";
999 os << " IsZeroInitializable:" << zeroInitializable << "\n";
1000 os << " BitFields:[\n";
1001 std::vector<std::pair<unsigned, const CIRGenBitFieldInfo *>> bitInfo;
1002 for (auto &[decl, info] : bitFields) {
1003 const RecordDecl *rd = decl->getParent();
1004 unsigned index = 0;
1005 for (RecordDecl::field_iterator it = rd->field_begin(); *it != decl; ++it)
1006 ++index;
1007 bitInfo.push_back(std::make_pair(index, &info));
1008 }
1009 llvm::array_pod_sort(bitInfo.begin(), bitInfo.end());
1010 for (std::pair<unsigned, const CIRGenBitFieldInfo *> &info : bitInfo) {
1011 os.indent(4);
1012 info.second->print(os);
1013 os << "\n";
1014 }
1015 os << " ]>\n";
1016}
1017
1018void CIRGenBitFieldInfo::print(raw_ostream &os) const {
1019 os << "<CIRBitFieldInfo" << " name:" << name << " offset:" << offset
1020 << " size:" << size << " isSigned:" << isSigned
1021 << " storageSize:" << storageSize
1022 << " storageOffset:" << storageOffset.getQuantity()
1023 << " volatileOffset:" << volatileOffset
1024 << " volatileStorageSize:" << volatileStorageSize
1025 << " volatileStorageOffset:" << volatileStorageOffset.getQuantity() << ">";
1026}
1027
1028void CIRGenRecordLayout::dump() const { print(llvm::errs()); }
1029
1030void CIRGenBitFieldInfo::dump() const { print(llvm::errs()); }
1031
1032void CIRRecordLowering::lowerUnion(bool nonVirtualBaseType) {
1033 // The base-subobject layout of a union is sized to its data size rather than
1034 // its full size. A union can have reusable tail padding when one of its
1035 // members is a [[no_unique_address]] field that itself has tail padding, so
1036 // an enclosing [[no_unique_address]] union field must use this smaller type.
1037 CharUnits layoutSize = nonVirtualBaseType ? astRecordLayout.getDataSize()
1038 : astRecordLayout.getSize();
1039 // Accumulate bitfields and fields, and figure out what our difference between
1040 // storage type and padding is.
1041
1042 // First, accumulate all the types.
1043 for (const FieldDecl *field : recordDecl->fields()) {
1044 mlir::Type fieldType;
1045 cir::RecordMemberKind fieldKind;
1046 if (field->isBitField()) {
1047 if (field->isZeroLengthBitField())
1048 continue;
1049 // Every variant starts at offset zero, so a bit-field variant is an
1050 // access unit of its own, holding that one field.
1051 mlir::Type unitStorage =
1052 getBitfieldStorageType(field->getBitWidthValue());
1053 setBitFieldInfo(field, CharUnits::Zero(), unitStorage);
1054 MemberInfo unit = makeAccessUnitInfo(CharUnits::Zero(), unitStorage,
1055 getBitFieldDecl(field));
1056 fieldType = unit.data;
1057 fieldKind = unit.memberKind;
1058 } else {
1059 fieldType = getStorageType(field);
1060 fieldKind = getFieldMemberKind(field);
1061 }
1062
1063 fieldIdxMap[field->getCanonicalDecl()] = 0;
1064 addField(fieldType, fieldKind);
1065 }
1066
1067 // Compute zero-initializable status.
1068 // This union might not be zero initialized: it may contain a pointer to
1069 // data member which might have some exotic initialization sequence.
1070 // This chooses the first 'named' member and is zero-initializable based on
1071 // that.
1072 auto hasNamedMember = [](const FieldDecl *curField) -> bool {
1073 const auto *rd = curField->getType()->getAsRecordDecl();
1074 return rd && rd->findFirstNamedDataMember();
1075 };
1076 // Whether this is usable for zero-init as a 'named member'. It is a field
1077 // with a name (or a record type with a named member itself), that isn't a
1078 // zero-width bitfield.
1079 auto isNamedMember = [hasNamedMember](const FieldDecl *curField) -> bool {
1080 if (curField->isZeroLengthBitField())
1081 return false;
1082 return curField->getIdentifier() || hasNamedMember(curField);
1083 };
1084 auto firstNamedMemberItr = llvm::find_if(recordDecl->fields(), isNamedMember);
1085
1086 if (firstNamedMemberItr != recordDecl->fields().end() &&
1087 !isZeroInitializable(*firstNamedMemberItr))
1088 zeroInitializable = zeroInitializableAsBase = false;
1089
1090 // If we have no candidates for storage, we are JUST padding.
1091 if (getFieldTypes().empty()) {
1092 appendPaddingBytes(layoutSize);
1093 return;
1094 }
1095
1096 mlir::Type storageType =
1097 cir::UnionType::getUnionStorageType(dataLayout.layout, getFieldTypes());
1098
1099 // If our storage size was bigger than our required size (can happen in the
1100 // case of packed bitfields on Itanium) then just use an I8 array.
1101 if (layoutSize < getSize(storageType))
1102 storageType = getByteArrayType(layoutSize);
1103
1104 // The base-subobject record is built as a struct from fieldTypes, so add
1105 // the storage type and any trailing padding as ordinary fields rather than
1106 // routing padding through the union's single tail-padding slot.
1107 if (nonVirtualBaseType) {
1108 // A bit-field mark here says the stand-in's extent is not a declared
1109 // extent, not that its storage came from a bit-field: UnionBitAndWide in
1110 // clang/test/CIR/CodeGen/no-unique-address.cpp takes its double as storage
1111 // and still marks bitfield. The stand-in describes every variant, so it
1112 // takes the storage type rather than any one variant's `!cir.bitfield`,
1113 // and is the one bit-field-marked member that is not one. Computed before
1114 // clearFields() drops the variant marks.
1115 const cir::RecordMemberKind storageKind = makeMemberKind(
1116 /*holdsData=*/cir::anyMemberHoldsDataForABI(getFieldKinds()),
1117 /*isNamedBitField=*/llvm::any_of(getFieldKinds(),
1119 clearFields();
1120 addField(storageType, storageKind);
1121 CharUnits padding = layoutSize - getSize(storageType);
1122 if (!padding.isZero())
1123 addField(getByteArrayType(padding), cir::RecordMemberKind::Pad);
1124 } else {
1125 // Else we just add padding normally.
1126 appendPaddingBytes(layoutSize - getSize(storageType));
1127 }
1128 packed = !layoutSize.isMultipleOf(getMemberAlignment(storageType));
1129}
1130
1131bool CIRRecordLowering::hasOwnStorage(const CXXRecordDecl *decl,
1132 const CXXRecordDecl *query) {
1133 const ASTRecordLayout &declLayout = astContext.getASTRecordLayout(decl);
1134 if (declLayout.isPrimaryBaseVirtual() && declLayout.getPrimaryBase() == query)
1135 return false;
1136 for (const auto &base : decl->bases())
1137 if (!hasOwnStorage(base.getType()->getAsCXXRecordDecl(), query))
1138 return false;
1139 return true;
1140}
1141
1142/// The AAPCS that defines that, when possible, bit-fields should
1143/// be accessed using containers of the declared type width:
1144/// When a volatile bit-field is read, and its container does not overlap with
1145/// any non-bit-field member or any zero length bit-field member, its container
1146/// must be read exactly once using the access width appropriate to the type of
1147/// the container. When a volatile bit-field is written, and its container does
1148/// not overlap with any non-bit-field member or any zero-length bit-field
1149/// member, its container must be read exactly once and written exactly once
1150/// using the access width appropriate to the type of the container. The two
1151/// accesses are not atomic.
1152///
1153/// Enforcing the width restriction can be disabled using
1154/// -fno-aapcs-bitfield-width.
1155void CIRRecordLowering::computeVolatileBitfields() {
1156 if (!CodeGenUtils::isAAPCS(astContext.getTargetInfo()) ||
1157 !cirGenTypes.getCGModule().getCodeGenOpts().AAPCSBitfieldWidth)
1158 return;
1159
1160 for (auto &[field, info] : bitFields) {
1161 mlir::Type resLTy = cirGenTypes.convertTypeForMem(field->getType());
1162
1163 if (astContext.toBits(astRecordLayout.getAlignment()) <
1164 getSizeInBits(resLTy).getQuantity())
1165 continue;
1166
1167 // CIRRecordLowering::setBitFieldInfo() pre-adjusts the bit-field offsets
1168 // for big-endian targets, but it assumes a container of width
1169 // info.storageSize. Since AAPCS uses a different container size (width
1170 // of the type), we first undo that calculation here and redo it once
1171 // the bit-field offset within the new container is calculated.
1172 const unsigned oldOffset =
1173 isBigEndian() ? info.storageSize - (info.offset + info.size)
1174 : info.offset;
1175 // Offset to the bit-field from the beginning of the struct.
1176 const unsigned absoluteOffset =
1177 astContext.toBits(info.storageOffset) + oldOffset;
1178
1179 // Container size is the width of the bit-field type.
1180 const unsigned storageSize = getSizeInBits(resLTy).getQuantity();
1181 // Nothing to do if the access uses the desired
1182 // container width and is naturally aligned.
1183 if (info.storageSize == storageSize && (oldOffset % storageSize == 0))
1184 continue;
1185
1186 // Offset within the container.
1187 unsigned offset = absoluteOffset & (storageSize - 1);
1188 // Bail out if an aligned load of the container cannot cover the entire
1189 // bit-field. This can happen for example, if the bit-field is part of a
1190 // packed struct. AAPCS does not define access rules for such cases, we let
1191 // clang to follow its own rules.
1192 if (offset + info.size > storageSize)
1193 continue;
1194
1195 // Re-adjust offsets for big-endian targets.
1196 if (isBigEndian())
1197 offset = storageSize - (offset + info.size);
1198
1199 const CharUnits storageOffset =
1200 astContext.toCharUnitsFromBits(absoluteOffset & ~(storageSize - 1));
1201 const CharUnits end = storageOffset +
1202 astContext.toCharUnitsFromBits(storageSize) -
1204
1205 const ASTRecordLayout &layout =
1206 astContext.getASTRecordLayout(field->getParent());
1207 // If we access outside memory outside the record, than bail out.
1208 const CharUnits recordSize = layout.getSize();
1209 if (end >= recordSize)
1210 continue;
1211
1212 // Bail out if performing this load would access non-bit-fields members.
1213 bool conflict = false;
1214 for (const auto *f : recordDecl->fields()) {
1215 // Allow sized bit-fields overlaps.
1216 if (f->isBitField() && !f->isZeroLengthBitField())
1217 continue;
1218
1219 const CharUnits fOffset = astContext.toCharUnitsFromBits(
1220 layout.getFieldOffset(f->getFieldIndex()));
1221
1222 // As C11 defines, a zero sized bit-field defines a barrier, so
1223 // fields after and before it should be race condition free.
1224 // The AAPCS acknowledges it and imposes no restritions when the
1225 // natural container overlaps a zero-length bit-field.
1226 if (f->isZeroLengthBitField()) {
1227 if (end > fOffset && storageOffset < fOffset) {
1228 conflict = true;
1229 break;
1230 }
1231 }
1232
1233 const CharUnits fEnd =
1234 fOffset +
1235 astContext.toCharUnitsFromBits(
1236 getSizeInBits(cirGenTypes.convertTypeForMem(f->getType()))
1237 .getQuantity()) -
1239 // If no overlap, continue.
1240 if (end < fOffset || fEnd < storageOffset)
1241 continue;
1242
1243 // The desired load overlaps a non-bit-field member, bail out.
1244 conflict = true;
1245 break;
1246 }
1247
1248 if (conflict)
1249 continue;
1250 // Write the new bit-field access parameters.
1251 // As the storage offset now is defined as the number of elements from the
1252 // start of the structure, we should divide the Offset by the element size.
1253 info.volatileStorageOffset =
1254 storageOffset /
1255 astContext.toCharUnitsFromBits(storageSize).getQuantity();
1256 info.volatileStorageSize = storageSize;
1257 info.volatileOffset = offset;
1258 }
1259}
1260
1261void CIRRecordLowering::accumulateBases() {
1262 // If we've got a primary virtual base, we need to add it with the bases.
1263 if (astRecordLayout.isPrimaryBaseVirtual()) {
1264 const CXXRecordDecl *baseDecl = astRecordLayout.getPrimaryBase();
1265 members.push_back(MemberInfo(CharUnits::Zero(), MemberInfo::InfoKind::Base,
1266 getStorageType(baseDecl),
1267 getBaseMemberKind(baseDecl), baseDecl));
1268 }
1269
1270 // Accumulate the non-virtual bases.
1271 for (const auto &base : cxxRecordDecl->bases()) {
1272 if (base.isVirtual())
1273 continue;
1274 // Bases can be zero-sized even if not technically empty if they
1275 // contain only a trailing array member.
1276 const CXXRecordDecl *baseDecl = base.getType()->getAsCXXRecordDecl();
1277 if (!baseDecl->isEmpty() &&
1278 !astContext.getASTRecordLayout(baseDecl).getNonVirtualSize().isZero()) {
1279 members.push_back(MemberInfo(astRecordLayout.getBaseClassOffset(baseDecl),
1280 MemberInfo::InfoKind::Base,
1281 getStorageType(baseDecl),
1282 getBaseMemberKind(baseDecl), baseDecl));
1283 }
1284 }
1285}
1286
1287void CIRRecordLowering::accumulateVBases() {
1288 for (const auto &base : cxxRecordDecl->vbases()) {
1289 const CXXRecordDecl *baseDecl = base.getType()->getAsCXXRecordDecl();
1290 if (isEmptyRecordForLayout(astContext, base.getType()))
1291 continue;
1292 CharUnits offset = astRecordLayout.getVBaseClassOffset(baseDecl);
1293 // If the vbase is a primary virtual base of some base, then it doesn't
1294 // get its own storage location but instead lives inside of that base.
1295 if (isOverlappingVBaseABI() && astContext.isNearlyEmpty(baseDecl) &&
1296 !hasOwnStorage(cxxRecordDecl, baseDecl)) {
1297 members.push_back(MemberInfo(offset, MemberInfo::InfoKind::VBase, nullptr,
1298 cir::RecordMemberKind::Data, baseDecl));
1299 continue;
1300 }
1301 // If we've got a vtordisp, add it as a storage type.
1302 if (astRecordLayout.getVBaseOffsetsMap()
1303 .find(baseDecl)
1304 ->second.hasVtorDisp())
1305 members.push_back(makeStorageInfo(offset - CharUnits::fromQuantity(4),
1306 getUIntNType(32),
1307 cir::RecordMemberKind::Data));
1308 members.push_back(MemberInfo(offset, MemberInfo::InfoKind::VBase,
1309 getStorageType(baseDecl),
1310 getBaseMemberKind(baseDecl), baseDecl));
1311 }
1312}
1313
1314void CIRRecordLowering::accumulateVPtrs() {
1315 if (astRecordLayout.hasOwnVFPtr())
1316 members.push_back(MemberInfo(CharUnits::Zero(), MemberInfo::InfoKind::VFPtr,
1317 getVFPtrType(), cir::RecordMemberKind::Data));
1318
1319 if (astRecordLayout.hasOwnVBPtr())
1320 cirGenTypes.getCGModule().errorNYI(recordDecl->getSourceRange(),
1321 "accumulateVPtrs: hasOwnVBPtr");
1322}
1323
1324mlir::Type CIRRecordLowering::getVFPtrType() {
1325 return cir::VPtrType::get(builder.getContext());
1326}
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:239
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:965
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:1196
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:4817
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:4826
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:5469
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4660
field_iterator field_begin() const
Definition Decl.cpp:5340
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:2411
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.
constexpr size_t align(size_t Size)
Aligns a size to the pointer alignment.
Definition PrimType.h:213
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.