45 const auto *Struct = Result.Nodes.getNodeAs<RecordDecl>(
"struct");
49 if (Struct->isTemplated())
53 if (Struct->isInvalidDecl())
57 llvm::SmallVector<std::pair<unsigned int, unsigned int>, 10> FieldSizes;
58 unsigned int TotalBitSize = 0;
59 for (
const FieldDecl *StructField : Struct->fields()) {
63 const QualType StructFieldTy = StructField->getType();
64 if (StructFieldTy->isIncompleteType())
66 const unsigned int StructFieldWidth =
static_cast<unsigned int>(
67 Result.Context->getTypeInfo(StructFieldTy.getTypePtr()).Width);
68 FieldSizes.emplace_back(StructFieldWidth, StructField->getFieldIndex());
71 TotalBitSize += StructFieldWidth;
74 const uint64_t CharSize = Result.Context->getCharWidth();
75 const CharUnits CurrSize =
76 Result.Context->getASTRecordLayout(Struct).getSize();
77 const CharUnits MinByteSize =
78 CharUnits::fromQuantity(std::max<clang::CharUnits::QuantityType>(
79 std::ceil(
static_cast<float>(TotalBitSize) / CharSize), 1));
80 const CharUnits MaxAlign = CharUnits::fromQuantity(
81 std::ceil(
static_cast<float>(Struct->getMaxAlignment()) / CharSize));
82 const CharUnits CurrAlign =
83 Result.Context->getASTRecordLayout(Struct).getAlignment();
84 const CharUnits NewAlign = computeRecommendedAlignment(MinByteSize);
86 const bool IsPacked = Struct->hasAttr<PackedAttr>();
87 const bool NeedsPacking = (MinByteSize < CurrSize) &&
88 (MaxAlign != NewAlign) && (CurrSize != NewAlign);
89 const bool NeedsAlignment = CurrAlign.getQuantity() != NewAlign.getQuantity();
91 if (!NeedsAlignment && !NeedsPacking)
97 if (NeedsPacking && !IsPacked) {
98 diag(Struct->getLocation(),
99 "accessing fields in struct %0 is inefficient due to padding; only "
100 "needs %1 bytes but is using %2 bytes")
101 << Struct << MinByteSize.getQuantity() << CurrSize.getQuantity()
102 << FixItHint::CreateInsertion(Struct->getEndLoc().getLocWithOffset(1),
103 " __attribute__((packed))");
104 diag(Struct->getLocation(),
105 "use \"__attribute__((packed))\" to reduce the amount of padding "
106 "applied to struct %0",
112 auto *Attribute = Struct->getAttr<AlignedAttr>();
113 const std::string NewAlignQuantity = std::to_string(NewAlign.getQuantity());
115 FixIt = FixItHint::CreateReplacement(
116 Attribute->getRange(),
117 (Twine(
"aligned(") + NewAlignQuantity +
")").str());
119 FixIt = FixItHint::CreateInsertion(
120 Struct->getEndLoc().getLocWithOffset(1),
121 (Twine(
" __attribute__((aligned(") + NewAlignQuantity +
")))").str());
126 if (NeedsAlignment) {
127 diag(Struct->getLocation(),
128 "accessing fields in struct %0 is inefficient due to poor alignment; "
129 "currently aligned to %1 bytes, but recommended alignment is %2 bytes")
130 << Struct << CurrAlign.getQuantity() << NewAlignQuantity << FixIt;
132 diag(Struct->getLocation(),
133 "use \"__attribute__((aligned(%0)))\" to align struct %1 to %0 bytes",
135 << NewAlignQuantity << Struct;