24#include "llvm/ADT/SmallVectorExtras.h"
25#include "llvm/Support/MathExtras.h"
26#include "llvm/Support/raw_ostream.h"
32class PaddingChecker :
public Checker<check::ASTDecl<TranslationUnitDecl>> {
34 const BugType PaddingBug{
this,
"Excessive Padding",
"Performance"};
35 mutable BugReporter *BR;
40 void checkASTDecl(
const TranslationUnitDecl *TUD, AnalysisManager &MGR,
41 BugReporter &BRArg)
const {
48 const PaddingChecker *Checker;
49 explicit LocalVisitor(
const PaddingChecker *Checker) : Checker(Checker) {
50 ShouldVisitTemplateInstantiations =
true;
51 ShouldVisitImplicitCode =
true;
53 bool VisitRecordDecl(RecordDecl *RD)
override {
54 Checker->visitRecord(RD);
57 bool VisitVarDecl(VarDecl *VD)
override {
58 Checker->visitVariable(VD);
64 LocalVisitor visitor(
this);
65 visitor.TraverseDecl(
const_cast<TranslationUnitDecl *
>(TUD));
72 void visitRecord(
const RecordDecl *RD,
uint64_t PadMultiplier = 1)
const {
73 if (shouldSkipDecl(RD))
88 if (
auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
89 if (CXXRD->field_empty() && CXXRD->getNumBases() == 1)
90 return visitRecord(CXXRD->bases().begin()->getType()->getAsRecordDecl(),
97 CharUnits BaselinePad = calculateBaselinePad(RD, ASTContext, RL);
101 CharUnits OptimalPad;
102 SmallVector<const FieldDecl *, 20> OptimalFieldsOrder;
103 std::tie(OptimalPad, OptimalFieldsOrder) =
104 calculateOptimalPad(RD, ASTContext, RL);
106 CharUnits DiffPad = PadMultiplier * (BaselinePad - OptimalPad);
108 assert(!DiffPad.
isNegative() &&
"DiffPad should not be negative");
112 reportRecord(ASTContext, RD, BaselinePad, OptimalPad, OptimalFieldsOrder);
117 void visitVariable(
const VarDecl *VD)
const {
119 if (ArrTy ==
nullptr)
122 if (
const ConstantArrayType *CArrTy = dyn_cast<ConstantArrayType>(ArrTy))
123 Elts = CArrTy->getZExtSize();
131 visitRecord(RD, Elts);
134 bool shouldSkipDecl(
const RecordDecl *RD)
const {
142 if (!Location.isValid())
145 BR->getSourceManager().getFileCharacteristic(Location);
153 if (
auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
158 if (!CXXRD->field_empty() && CXXRD->getNumBases() != 0)
160 if (CXXRD->field_empty() && CXXRD->getNumBases() != 1)
163 if (CXXRD->getNumVBases() != 0)
167 if (CXXRD->isDependentType())
174 auto IsTrickyField = [](
const FieldDecl *FD) ->
bool {
176 if (FD->isBitField())
180 QualType Ty = FD->getType();
197 if (llvm::any_of(RD->
fields(), IsTrickyField))
202 static CharUnits calculateBaselinePad(
const RecordDecl *RD,
203 const ASTContext &ASTContext,
204 const ASTRecordLayout &RL) {
205 CharUnits PaddingSum;
207 for (
const FieldDecl *FD : RD->
fields()) {
211 if (FD->isZeroSize(ASTContext))
220 PaddingSum += (FieldOffset - Offset);
221 Offset = FieldOffset + FieldSize;
223 PaddingSum += RL.
getSize() - Offset;
243 static std::pair<CharUnits, SmallVector<const FieldDecl *, 20>>
244 calculateOptimalPad(
const RecordDecl *RD,
const ASTContext &ASTContext,
245 const ASTRecordLayout &RL) {
249 const FieldDecl *
Field;
250 bool operator<(
const FieldInfo &RHS)
const {
254 return std::make_tuple(Align, -Size,
255 Field ? -
static_cast<int>(
Field->getFieldIndex())
258 RHS.Align, -RHS.Size,
259 RHS.Field ? -
static_cast<int>(RHS.Field->getFieldIndex())
263 auto GatherSizesAndAlignments = [](
const FieldDecl *FD) {
266 auto &Ctx = FD->getASTContext();
267 auto Info = Ctx.getTypeInfoInChars(FD->getType());
269 RetVal.Align = Info.Align;
270 assert(llvm::isPowerOf2_64(RetVal.Align.getQuantity()));
271 if (
auto Max = FD->getMaxAlignment())
272 RetVal.Align = std::max(Ctx.toCharUnitsFromBits(
Max), RetVal.Align);
275 SmallVector<FieldInfo, 20> Fields =
276 llvm::map_to_vector<20>(RD->
fields(), GatherSizesAndAlignments);
284 SmallVector<const FieldDecl *, 20> OptimalFieldsOrder;
285 while (!Fields.empty()) {
286 unsigned TrailingZeros =
287 llvm::countr_zero((
unsigned long long)NewOffset.
getQuantity());
291 long long CurAlignmentBits = 1ull << (std::min)(TrailingZeros, 62u);
299 auto Iter = llvm::upper_bound(Fields, InsertPoint);
300 if (Iter != Fields.begin()) {
303 NewOffset += Iter->Size;
304 OptimalFieldsOrder.push_back(Iter->Field);
310 CharUnits NextOffset = NewOffset.
alignTo(Fields[0].Align);
311 NewPad += NextOffset - NewOffset;
312 NewOffset = NextOffset;
317 NewPad += NewSize - NewOffset;
318 return {NewPad, std::move(OptimalFieldsOrder)};
322 const ASTContext &Ctx,
const RecordDecl *RD, CharUnits BaselinePad,
323 CharUnits OptimalPad,
324 const SmallVector<const FieldDecl *, 20> &OptimalFieldsOrder)
const {
325 SmallString<100> Buf;
326 llvm::raw_svector_ostream Os(Buf);
327 Os <<
"Excessive padding in '";
331 if (
auto *TSD = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
335 SourceLocation ILoc = TSD->getPointOfInstantiation();
337 Os <<
" instantiated here: "
341 Os <<
" (" << BaselinePad.
getQuantity() <<
" padding bytes, where "
343 <<
"optimal fields order: ";
344 for (
const auto *FD : OptimalFieldsOrder)
345 Os << FD->getName() <<
", ";
346 Os <<
"consider reordering the fields or adding explicit padding "
349 PathDiagnosticLocation CELoc =
351 auto Report = std::make_unique<BasicBugReport>(PaddingBug, Os.str(), CELoc);
352 Report->setDeclWithIssue(RD);
354 BR->emitReport(std::move(
Report));
365 Checker,
"AllowedPad",
"a non-negative value");
368bool ento::shouldRegisterPaddingChecker(
const CheckerManager &mgr) {
Defines the C++ template declaration subclasses.
Defines the SourceManager interface.
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
CanQualType getCanonicalTagType(const TagDecl *TD) const
CharUnits getAlignment() const
getAlignment - Get the record alignment in characters.
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.
int getCheckerIntegerOption(StringRef CheckerName, StringRef OptionName, bool SearchInParents=false) const
Interprets an option's string value as a boolean.
QualType getElementType() const
bool isNegative() const
Test whether the quantity is less than zero.
bool isZero() const
Test whether the quantity equals zero.
CharUnits alignTo(CharUnits Align) const
Returns the next integer (mod 2**64) that is greater than or equal to this quantity and is a multiple...
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
static constexpr CharUnits fromQuantity(QuantityType Quantity)
Construct a CharUnits quantity from a raw integer type.
static CharUnits Zero()
Construct a CharUnits quantity of zero.
ASTContext & getASTContext() const LLVM_READONLY
bool isInvalidDecl() const
SourceLocation getLocation() const
field_range fields() const
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
std::string printToString(const SourceManager &SM) const
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
bool isIncompleteArrayType() const
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
const AnalyzerOptions & getAnalyzerOptions() const
CHECKER * registerChecker(AT &&...Args)
Register a single-part checker (derived from Checker): construct its singleton instance,...
void reportInvalidCheckerOptionValue(const CheckerFrontend *Checker, StringRef OptionName, StringRef ExpectedValueDesc) const
Emits an error through a DiagnosticsEngine about an invalid user supplied checker option value.
Simple checker classes that implement one frontend (i.e.
static PathDiagnosticLocation create(const Decl *D, const SourceManager &SM)
Create a location corresponding to the given declaration.
CharacteristicKind
Indicates whether a file or directory holds normal user code, system code, or system code which is im...
Top level wrappers for InstallAPI frontend operations.
bool operator<(DeclarationName LHS, DeclarationName RHS)
Ordering on two declaration names.
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t int64_t
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t