#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
#include "clang/AST/CharUnits.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/RecordLayout.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Driver/DriverDiagnostic.h"
#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
#include "clang/StaticAnalyzer/Core/Checker.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/raw_ostream.h"
#include <numeric>
using namespace clang;
using namespace ento;
namespace {
class PaddingChecker : public Checker<check::ASTDecl<TranslationUnitDecl>> {
private:
mutable std::unique_ptr<BugType> PaddingBug;
mutable BugReporter *BR;
public:
int64_t AllowedPad;
void checkASTDecl(const TranslationUnitDecl *TUD, AnalysisManager &MGR,
BugReporter &BRArg) const {
BR = &BRArg;
struct LocalVisitor : public RecursiveASTVisitor<LocalVisitor> {
const PaddingChecker *Checker;
bool shouldVisitTemplateInstantiations() const { return true; }
bool shouldVisitImplicitCode() const { return true; }
explicit LocalVisitor(const PaddingChecker *Checker) : Checker(Checker) {}
bool VisitRecordDecl(const RecordDecl *RD) {
Checker->visitRecord(RD);
return true;
}
bool VisitVarDecl(const VarDecl *VD) {
Checker->visitVariable(VD);
return true;
}
};
LocalVisitor visitor(this);
visitor.TraverseDecl(const_cast<TranslationUnitDecl *>(TUD));
}
void visitRecord(const RecordDecl *RD, uint64_t PadMultiplier = 1) const {
if (shouldSkipDecl(RD))
return;
if (!(RD = RD->getDefinition()))
return;
if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
if (CXXRD->field_empty() && CXXRD->getNumBases() == 1)
return visitRecord(CXXRD->bases().begin()->getType()->getAsRecordDecl(),
PadMultiplier);
auto &ASTContext = RD->getASTContext();
const ASTRecordLayout &RL = ASTContext.getASTRecordLayout(RD);
assert(llvm::isPowerOf2_64(RL.getAlignment().getQuantity()));
CharUnits BaselinePad = calculateBaselinePad(RD, ASTContext, RL);
if (BaselinePad.isZero())
return;
CharUnits OptimalPad;
SmallVector<const FieldDecl *, 20> OptimalFieldsOrder;
std::tie(OptimalPad, OptimalFieldsOrder) =
calculateOptimalPad(RD, ASTContext, RL);
CharUnits DiffPad = PadMultiplier * (BaselinePad - OptimalPad);
if (DiffPad.getQuantity() <= AllowedPad) {
assert(!DiffPad.isNegative() && "DiffPad should not be negative");
return;
}
reportRecord(RD, BaselinePad, OptimalPad, OptimalFieldsOrder);
}
void visitVariable(const VarDecl *VD) const {
const ArrayType *ArrTy = VD->getType()->getAsArrayTypeUnsafe();
if (ArrTy == nullptr)
return;
uint64_t Elts = 0;
if (const ConstantArrayType *CArrTy = dyn_cast<ConstantArrayType>(ArrTy))
Elts = CArrTy->getSize().getZExtValue();
if (Elts == 0)
return;
const RecordType *RT = ArrTy->getElementType()->getAs<RecordType>();
if (RT == nullptr)
return;
visitRecord(RT->getDecl(), Elts);
}
bool shouldSkipDecl(const RecordDecl *RD) const {
if (!(RD = RD->getDefinition()))
return true;
auto Location = RD->getLocation();
if (!Location.isValid())
return true;
SrcMgr::CharacteristicKind Kind =
BR->getSourceManager().getFileCharacteristic(Location);
if (Kind != SrcMgr::C_User)
return true;
if (RD->isUnion())
return true;
if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
if (!CXXRD->field_empty() && CXXRD->getNumBases() != 0)
return true;
if (CXXRD->field_empty() && CXXRD->getNumBases() != 1)
return true;
if (CXXRD->getNumVBases() != 0)
return true;
if (CXXRD->getTypeForDecl()->isDependentType())
return true;
if (CXXRD->getTypeForDecl()->isInstantiationDependentType())
return true;
}
else if (RD->field_empty())
return true;
auto IsTrickyField = [](const FieldDecl *FD) -> bool {
if (FD->isBitField())
return true;
QualType Ty = FD->getType();
if (Ty->isIncompleteArrayType())
return true;
return false;
};
if (llvm::any_of(RD->fields(), IsTrickyField))
return true;
return false;
}
static CharUnits calculateBaselinePad(const RecordDecl *RD,
const ASTContext &ASTContext,
const ASTRecordLayout &RL) {
CharUnits PaddingSum;
CharUnits Offset = ASTContext.toCharUnitsFromBits(RL.getFieldOffset(0));
for (const FieldDecl *FD : RD->fields()) {
if (FD->isZeroSize(ASTContext))
continue;
CharUnits FieldSize = ASTContext.getTypeSizeInChars(FD->getType());
auto FieldOffsetBits = RL.getFieldOffset(FD->getFieldIndex());
CharUnits FieldOffset = ASTContext.toCharUnitsFromBits(FieldOffsetBits);
PaddingSum += (FieldOffset - Offset);
Offset = FieldOffset + FieldSize;
}
PaddingSum += RL.getSize() - Offset;
return PaddingSum;
}
static std::pair<CharUnits, SmallVector<const FieldDecl *, 20>>
calculateOptimalPad(const RecordDecl *RD, const ASTContext &ASTContext,
const ASTRecordLayout &RL) {
struct FieldInfo {
CharUnits Align;
CharUnits Size;
const FieldDecl *Field;
bool operator<(const FieldInfo &RHS) const {
return std::make_tuple(Align, -Size,
Field ? -static_cast<int>(Field->getFieldIndex())
: 0) <
std::make_tuple(
RHS.Align, -RHS.Size,
RHS.Field ? -static_cast<int>(RHS.Field->getFieldIndex())
: 0);
}
};
SmallVector<FieldInfo, 20> Fields;
auto GatherSizesAndAlignments = [](const FieldDecl *FD) {
FieldInfo RetVal;
RetVal.Field = FD;
auto &Ctx = FD->getASTContext();
auto Info = Ctx.getTypeInfoInChars(FD->getType());
RetVal.Size = FD->isZeroSize(Ctx) ? CharUnits::Zero() : Info.Width;
RetVal.Align = Info.Align;
assert(llvm::isPowerOf2_64(RetVal.Align.getQuantity()));
if (auto Max = FD->getMaxAlignment())
RetVal.Align = std::max(Ctx.toCharUnitsFromBits(Max), RetVal.Align);
return RetVal;
};
std::transform(RD->field_begin(), RD->field_end(),
std::back_inserter(Fields), GatherSizesAndAlignments);
llvm::sort(Fields);
CharUnits NewOffset = ASTContext.toCharUnitsFromBits(RL.getFieldOffset(0));
CharUnits NewPad;
SmallVector<const FieldDecl *, 20> OptimalFieldsOrder;
while (!Fields.empty()) {
unsigned TrailingZeros =
llvm::countTrailingZeros((unsigned long long)NewOffset.getQuantity());
long long CurAlignmentBits = 1ull << (std::min)(TrailingZeros, 62u);
CharUnits CurAlignment = CharUnits::fromQuantity(CurAlignmentBits);
FieldInfo InsertPoint = {CurAlignment, CharUnits::Zero(), nullptr};
auto Iter = llvm::upper_bound(Fields, InsertPoint);
if (Iter != Fields.begin()) {
--Iter;
NewOffset += Iter->Size;
OptimalFieldsOrder.push_back(Iter->Field);
Fields.erase(Iter);
} else {
CharUnits NextOffset = NewOffset.alignTo(Fields[0].Align);
NewPad += NextOffset - NewOffset;
NewOffset = NextOffset;
}
}
CharUnits NewSize = NewOffset.alignTo(RL.getAlignment());
NewPad += NewSize - NewOffset;
return {NewPad, std::move(OptimalFieldsOrder)};
}
void reportRecord(
const RecordDecl *RD, CharUnits BaselinePad, CharUnits OptimalPad,
const SmallVector<const FieldDecl *, 20> &OptimalFieldsOrder) const {
if (!PaddingBug)
PaddingBug =
std::make_unique<BugType>(this, "Excessive Padding", "Performance");
SmallString<100> Buf;
llvm::raw_svector_ostream Os(Buf);
Os << "Excessive padding in '";
Os << QualType::getAsString(RD->getTypeForDecl(), Qualifiers(),
LangOptions())
<< "'";
if (auto *TSD = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
SourceLocation ILoc = TSD->getPointOfInstantiation();
if (ILoc.isValid())
Os << " instantiated here: "
<< ILoc.printToString(BR->getSourceManager());
}
Os << " (" << BaselinePad.getQuantity() << " padding bytes, where "
<< OptimalPad.getQuantity() << " is optimal). "
<< "Optimal fields order: ";
for (const auto *FD : OptimalFieldsOrder)
Os << FD->getName() << ", ";
Os << "consider reordering the fields or adding explicit padding "
"members.";
PathDiagnosticLocation CELoc =
PathDiagnosticLocation::create(RD, BR->getSourceManager());
auto Report =
std::make_unique<BasicBugReport>(*PaddingBug, Os.str(), CELoc);
Report->setDeclWithIssue(RD);
Report->addRange(RD->getSourceRange());
BR->emitReport(std::move(Report));
}
};
}
void ento::registerPaddingChecker(CheckerManager &Mgr) {
auto *Checker = Mgr.registerChecker<PaddingChecker>();
Checker->AllowedPad = Mgr.getAnalyzerOptions()
.getCheckerIntegerOption(Checker, "AllowedPad");
if (Checker->AllowedPad < 0)
Mgr.reportInvalidCheckerOptionValue(
Checker, "AllowedPad", "a non-negative value");
}
bool ento::shouldRegisterPaddingChecker(const CheckerManager &mgr) {
return true;
}