197c191c4SBen Craig //=======- PaddingChecker.cpp ------------------------------------*- C++ -*-==//
297c191c4SBen Craig //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
697c191c4SBen Craig //
797c191c4SBen Craig //===----------------------------------------------------------------------===//
897c191c4SBen Craig //
997c191c4SBen Craig //  This file defines a checker that checks for padding that could be
1097c191c4SBen Craig //  removed by re-ordering members.
1197c191c4SBen Craig //
1297c191c4SBen Craig //===----------------------------------------------------------------------===//
1397c191c4SBen Craig 
1476a21502SKristof Umann #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
1597c191c4SBen Craig #include "clang/AST/CharUnits.h"
1697c191c4SBen Craig #include "clang/AST/DeclTemplate.h"
1797c191c4SBen Craig #include "clang/AST/RecordLayout.h"
1897c191c4SBen Craig #include "clang/AST/RecursiveASTVisitor.h"
19748c139aSKristof Umann #include "clang/Driver/DriverDiagnostic.h"
2097c191c4SBen Craig #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
2197c191c4SBen Craig #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
2297c191c4SBen Craig #include "clang/StaticAnalyzer/Core/Checker.h"
2397c191c4SBen Craig #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
2497c191c4SBen Craig #include "llvm/ADT/SmallString.h"
2597c191c4SBen Craig #include "llvm/Support/MathExtras.h"
2697c191c4SBen Craig #include "llvm/Support/raw_ostream.h"
2797c191c4SBen Craig #include <numeric>
2897c191c4SBen Craig 
2997c191c4SBen Craig using namespace clang;
3097c191c4SBen Craig using namespace ento;
3197c191c4SBen Craig 
3297c191c4SBen Craig namespace {
3397c191c4SBen Craig class PaddingChecker : public Checker<check::ASTDecl<TranslationUnitDecl>> {
3497c191c4SBen Craig private:
3597c191c4SBen Craig   mutable std::unique_ptr<BugType> PaddingBug;
3697c191c4SBen Craig   mutable BugReporter *BR;
3797c191c4SBen Craig 
3897c191c4SBen Craig public:
39088b1c9cSKristof Umann   int64_t AllowedPad;
40088b1c9cSKristof Umann 
checkASTDecl(const TranslationUnitDecl * TUD,AnalysisManager & MGR,BugReporter & BRArg) const4197c191c4SBen Craig   void checkASTDecl(const TranslationUnitDecl *TUD, AnalysisManager &MGR,
4297c191c4SBen Craig                     BugReporter &BRArg) const {
4397c191c4SBen Craig     BR = &BRArg;
4497c191c4SBen Craig 
4597c191c4SBen Craig     // The calls to checkAST* from AnalysisConsumer don't
4697c191c4SBen Craig     // visit template instantiations or lambda classes. We
4797c191c4SBen Craig     // want to visit those, so we make our own RecursiveASTVisitor.
4897c191c4SBen Craig     struct LocalVisitor : public RecursiveASTVisitor<LocalVisitor> {
4997c191c4SBen Craig       const PaddingChecker *Checker;
5097c191c4SBen Craig       bool shouldVisitTemplateInstantiations() const { return true; }
5197c191c4SBen Craig       bool shouldVisitImplicitCode() const { return true; }
5297c191c4SBen Craig       explicit LocalVisitor(const PaddingChecker *Checker) : Checker(Checker) {}
5397c191c4SBen Craig       bool VisitRecordDecl(const RecordDecl *RD) {
5497c191c4SBen Craig         Checker->visitRecord(RD);
5597c191c4SBen Craig         return true;
5697c191c4SBen Craig       }
5797c191c4SBen Craig       bool VisitVarDecl(const VarDecl *VD) {
5897c191c4SBen Craig         Checker->visitVariable(VD);
5997c191c4SBen Craig         return true;
6097c191c4SBen Craig       }
6197c191c4SBen Craig       // TODO: Visit array new and mallocs for arrays.
6297c191c4SBen Craig     };
6397c191c4SBen Craig 
6497c191c4SBen Craig     LocalVisitor visitor(this);
6597c191c4SBen Craig     visitor.TraverseDecl(const_cast<TranslationUnitDecl *>(TUD));
6697c191c4SBen Craig   }
6797c191c4SBen Craig 
689fc8faf9SAdrian Prantl   /// Look for records of overly padded types. If padding *
6997c191c4SBen Craig   /// PadMultiplier exceeds AllowedPad, then generate a report.
7097c191c4SBen Craig   /// PadMultiplier is used to share code with the array padding
7197c191c4SBen Craig   /// checker.
visitRecord(const RecordDecl * RD,uint64_t PadMultiplier=1) const7297c191c4SBen Craig   void visitRecord(const RecordDecl *RD, uint64_t PadMultiplier = 1) const {
7397c191c4SBen Craig     if (shouldSkipDecl(RD))
7497c191c4SBen Craig       return;
7597c191c4SBen Craig 
76e2f07346SAlexander Shaposhnikov     // TODO: Figure out why we are going through declarations and not only
77e2f07346SAlexander Shaposhnikov     // definitions.
78e2f07346SAlexander Shaposhnikov     if (!(RD = RD->getDefinition()))
79e2f07346SAlexander Shaposhnikov       return;
80e2f07346SAlexander Shaposhnikov 
81e2f07346SAlexander Shaposhnikov     // This is the simplest correct case: a class with no fields and one base
82e2f07346SAlexander Shaposhnikov     // class. Other cases are more complicated because of how the base classes
83e2f07346SAlexander Shaposhnikov     // & fields might interact, so we don't bother dealing with them.
84e2f07346SAlexander Shaposhnikov     // TODO: Support other combinations of base classes and fields.
85e2f07346SAlexander Shaposhnikov     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
86e2f07346SAlexander Shaposhnikov       if (CXXRD->field_empty() && CXXRD->getNumBases() == 1)
87e2f07346SAlexander Shaposhnikov         return visitRecord(CXXRD->bases().begin()->getType()->getAsRecordDecl(),
88e2f07346SAlexander Shaposhnikov                            PadMultiplier);
89e2f07346SAlexander Shaposhnikov 
9097c191c4SBen Craig     auto &ASTContext = RD->getASTContext();
9197c191c4SBen Craig     const ASTRecordLayout &RL = ASTContext.getASTRecordLayout(RD);
9297c191c4SBen Craig     assert(llvm::isPowerOf2_64(RL.getAlignment().getQuantity()));
9397c191c4SBen Craig 
9497c191c4SBen Craig     CharUnits BaselinePad = calculateBaselinePad(RD, ASTContext, RL);
9597c191c4SBen Craig     if (BaselinePad.isZero())
9697c191c4SBen Craig       return;
97b9250475SSaleem Abdulrasool 
98b9250475SSaleem Abdulrasool     CharUnits OptimalPad;
99b9250475SSaleem Abdulrasool     SmallVector<const FieldDecl *, 20> OptimalFieldsOrder;
100b9250475SSaleem Abdulrasool     std::tie(OptimalPad, OptimalFieldsOrder) =
101b9250475SSaleem Abdulrasool         calculateOptimalPad(RD, ASTContext, RL);
10297c191c4SBen Craig 
10397c191c4SBen Craig     CharUnits DiffPad = PadMultiplier * (BaselinePad - OptimalPad);
10497c191c4SBen Craig     if (DiffPad.getQuantity() <= AllowedPad) {
10597c191c4SBen Craig       assert(!DiffPad.isNegative() && "DiffPad should not be negative");
10697c191c4SBen Craig       // There is not enough excess padding to trigger a warning.
10797c191c4SBen Craig       return;
10897c191c4SBen Craig     }
109b9250475SSaleem Abdulrasool     reportRecord(RD, BaselinePad, OptimalPad, OptimalFieldsOrder);
11097c191c4SBen Craig   }
11197c191c4SBen Craig 
1129fc8faf9SAdrian Prantl   /// Look for arrays of overly padded types. If the padding of the
11397c191c4SBen Craig   /// array type exceeds AllowedPad, then generate a report.
visitVariable(const VarDecl * VD) const11497c191c4SBen Craig   void visitVariable(const VarDecl *VD) const {
11597c191c4SBen Craig     const ArrayType *ArrTy = VD->getType()->getAsArrayTypeUnsafe();
11697c191c4SBen Craig     if (ArrTy == nullptr)
11797c191c4SBen Craig       return;
11897c191c4SBen Craig     uint64_t Elts = 0;
11997c191c4SBen Craig     if (const ConstantArrayType *CArrTy = dyn_cast<ConstantArrayType>(ArrTy))
12097c191c4SBen Craig       Elts = CArrTy->getSize().getZExtValue();
12197c191c4SBen Craig     if (Elts == 0)
12297c191c4SBen Craig       return;
12397c191c4SBen Craig     const RecordType *RT = ArrTy->getElementType()->getAs<RecordType>();
12497c191c4SBen Craig     if (RT == nullptr)
12597c191c4SBen Craig       return;
12697c191c4SBen Craig 
127e2f07346SAlexander Shaposhnikov     // TODO: Recurse into the fields to see if they have excess padding.
12897c191c4SBen Craig     visitRecord(RT->getDecl(), Elts);
12997c191c4SBen Craig   }
13097c191c4SBen Craig 
shouldSkipDecl(const RecordDecl * RD) const13197c191c4SBen Craig   bool shouldSkipDecl(const RecordDecl *RD) const {
132e2f07346SAlexander Shaposhnikov     // TODO: Figure out why we are going through declarations and not only
133e2f07346SAlexander Shaposhnikov     // definitions.
134e2f07346SAlexander Shaposhnikov     if (!(RD = RD->getDefinition()))
135e2f07346SAlexander Shaposhnikov       return true;
13697c191c4SBen Craig     auto Location = RD->getLocation();
13797c191c4SBen Craig     // If the construct doesn't have a source file, then it's not something
13897c191c4SBen Craig     // we want to diagnose.
13997c191c4SBen Craig     if (!Location.isValid())
14097c191c4SBen Craig       return true;
14197c191c4SBen Craig     SrcMgr::CharacteristicKind Kind =
14297c191c4SBen Craig         BR->getSourceManager().getFileCharacteristic(Location);
14397c191c4SBen Craig     // Throw out all records that come from system headers.
14497c191c4SBen Craig     if (Kind != SrcMgr::C_User)
14597c191c4SBen Craig       return true;
14697c191c4SBen Craig 
14797c191c4SBen Craig     // Not going to attempt to optimize unions.
14897c191c4SBen Craig     if (RD->isUnion())
14997c191c4SBen Craig       return true;
15097c191c4SBen Craig     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
15197c191c4SBen Craig       // Tail padding with base classes ends up being very complicated.
152e2f07346SAlexander Shaposhnikov       // We will skip objects with base classes for now, unless they do not
153e2f07346SAlexander Shaposhnikov       // have fields.
154e2f07346SAlexander Shaposhnikov       // TODO: Handle more base class scenarios.
155e2f07346SAlexander Shaposhnikov       if (!CXXRD->field_empty() && CXXRD->getNumBases() != 0)
156e2f07346SAlexander Shaposhnikov         return true;
157e2f07346SAlexander Shaposhnikov       if (CXXRD->field_empty() && CXXRD->getNumBases() != 1)
15897c191c4SBen Craig         return true;
15997c191c4SBen Craig       // Virtual bases are complicated, skipping those for now.
16097c191c4SBen Craig       if (CXXRD->getNumVBases() != 0)
16197c191c4SBen Craig         return true;
16297c191c4SBen Craig       // Can't layout a template, so skip it. We do still layout the
16397c191c4SBen Craig       // instantiations though.
16497c191c4SBen Craig       if (CXXRD->getTypeForDecl()->isDependentType())
16597c191c4SBen Craig         return true;
16697c191c4SBen Craig       if (CXXRD->getTypeForDecl()->isInstantiationDependentType())
16797c191c4SBen Craig         return true;
16897c191c4SBen Craig     }
169e2f07346SAlexander Shaposhnikov     // How do you reorder fields if you haven't got any?
170e2f07346SAlexander Shaposhnikov     else if (RD->field_empty())
171e2f07346SAlexander Shaposhnikov       return true;
172e2f07346SAlexander Shaposhnikov 
17397c191c4SBen Craig     auto IsTrickyField = [](const FieldDecl *FD) -> bool {
17497c191c4SBen Craig       // Bitfield layout is hard.
17597c191c4SBen Craig       if (FD->isBitField())
17697c191c4SBen Craig         return true;
17797c191c4SBen Craig 
17897c191c4SBen Craig       // Variable length arrays are tricky too.
17997c191c4SBen Craig       QualType Ty = FD->getType();
18097c191c4SBen Craig       if (Ty->isIncompleteArrayType())
18197c191c4SBen Craig         return true;
18297c191c4SBen Craig       return false;
18397c191c4SBen Craig     };
18497c191c4SBen Craig 
185*9e88cbccSKazu Hirata     if (llvm::any_of(RD->fields(), IsTrickyField))
18697c191c4SBen Craig       return true;
18797c191c4SBen Craig     return false;
18897c191c4SBen Craig   }
18997c191c4SBen Craig 
calculateBaselinePad(const RecordDecl * RD,const ASTContext & ASTContext,const ASTRecordLayout & RL)19097c191c4SBen Craig   static CharUnits calculateBaselinePad(const RecordDecl *RD,
19197c191c4SBen Craig                                         const ASTContext &ASTContext,
19297c191c4SBen Craig                                         const ASTRecordLayout &RL) {
19397c191c4SBen Craig     CharUnits PaddingSum;
19497c191c4SBen Craig     CharUnits Offset = ASTContext.toCharUnitsFromBits(RL.getFieldOffset(0));
1954d511909SJustin Bogner     for (const FieldDecl *FD : RD->fields()) {
196c558b1fcSGeorgy Komarov       // Skip field that is a subobject of zero size, marked with
197c558b1fcSGeorgy Komarov       // [[no_unique_address]] or an empty bitfield, because its address can be
198c558b1fcSGeorgy Komarov       // set the same as the other fields addresses.
199c558b1fcSGeorgy Komarov       if (FD->isZeroSize(ASTContext))
200c558b1fcSGeorgy Komarov         continue;
20197c191c4SBen Craig       // This checker only cares about the padded size of the
20297c191c4SBen Craig       // field, and not the data size. If the field is a record
20397c191c4SBen Craig       // with tail padding, then we won't put that number in our
20497c191c4SBen Craig       // total because reordering fields won't fix that problem.
20597c191c4SBen Craig       CharUnits FieldSize = ASTContext.getTypeSizeInChars(FD->getType());
20697c191c4SBen Craig       auto FieldOffsetBits = RL.getFieldOffset(FD->getFieldIndex());
20797c191c4SBen Craig       CharUnits FieldOffset = ASTContext.toCharUnitsFromBits(FieldOffsetBits);
20897c191c4SBen Craig       PaddingSum += (FieldOffset - Offset);
20997c191c4SBen Craig       Offset = FieldOffset + FieldSize;
21097c191c4SBen Craig     }
21197c191c4SBen Craig     PaddingSum += RL.getSize() - Offset;
21297c191c4SBen Craig     return PaddingSum;
21397c191c4SBen Craig   }
21497c191c4SBen Craig 
21597c191c4SBen Craig   /// Optimal padding overview:
21697c191c4SBen Craig   /// 1.  Find a close approximation to where we can place our first field.
21797c191c4SBen Craig   ///     This will usually be at offset 0.
21897c191c4SBen Craig   /// 2.  Try to find the best field that can legally be placed at the current
21997c191c4SBen Craig   ///     offset.
22097c191c4SBen Craig   ///   a.  "Best" is the largest alignment that is legal, but smallest size.
22197c191c4SBen Craig   ///       This is to account for overly aligned types.
22297c191c4SBen Craig   /// 3.  If no fields can fit, pad by rounding the current offset up to the
22397c191c4SBen Craig   ///     smallest alignment requirement of our fields. Measure and track the
22497c191c4SBen Craig   //      amount of padding added. Go back to 2.
22597c191c4SBen Craig   /// 4.  Increment the current offset by the size of the chosen field.
22697c191c4SBen Craig   /// 5.  Remove the chosen field from the set of future possibilities.
22797c191c4SBen Craig   /// 6.  Go back to 2 if there are still unplaced fields.
22897c191c4SBen Craig   /// 7.  Add tail padding by rounding the current offset up to the structure
22997c191c4SBen Craig   ///     alignment. Track the amount of padding added.
23097c191c4SBen Craig 
231b9250475SSaleem Abdulrasool   static std::pair<CharUnits, SmallVector<const FieldDecl *, 20>>
calculateOptimalPad(const RecordDecl * RD,const ASTContext & ASTContext,const ASTRecordLayout & RL)232b9250475SSaleem Abdulrasool   calculateOptimalPad(const RecordDecl *RD, const ASTContext &ASTContext,
23397c191c4SBen Craig                       const ASTRecordLayout &RL) {
234b9250475SSaleem Abdulrasool     struct FieldInfo {
23597c191c4SBen Craig       CharUnits Align;
23697c191c4SBen Craig       CharUnits Size;
237b9250475SSaleem Abdulrasool       const FieldDecl *Field;
238b9250475SSaleem Abdulrasool       bool operator<(const FieldInfo &RHS) const {
23997c191c4SBen Craig         // Order from small alignments to large alignments,
24097c191c4SBen Craig         // then large sizes to small sizes.
241b9250475SSaleem Abdulrasool         // then large field indices to small field indices
242b9250475SSaleem Abdulrasool         return std::make_tuple(Align, -Size,
243b9250475SSaleem Abdulrasool                                Field ? -static_cast<int>(Field->getFieldIndex())
244b9250475SSaleem Abdulrasool                                      : 0) <
245b9250475SSaleem Abdulrasool                std::make_tuple(
246b9250475SSaleem Abdulrasool                    RHS.Align, -RHS.Size,
247b9250475SSaleem Abdulrasool                    RHS.Field ? -static_cast<int>(RHS.Field->getFieldIndex())
248b9250475SSaleem Abdulrasool                              : 0);
24997c191c4SBen Craig       }
25097c191c4SBen Craig     };
251b9250475SSaleem Abdulrasool     SmallVector<FieldInfo, 20> Fields;
25297c191c4SBen Craig     auto GatherSizesAndAlignments = [](const FieldDecl *FD) {
253b9250475SSaleem Abdulrasool       FieldInfo RetVal;
254b9250475SSaleem Abdulrasool       RetVal.Field = FD;
25597c191c4SBen Craig       auto &Ctx = FD->getASTContext();
256101309feSBevin Hansson       auto Info = Ctx.getTypeInfoInChars(FD->getType());
257c558b1fcSGeorgy Komarov       RetVal.Size = FD->isZeroSize(Ctx) ? CharUnits::Zero() : Info.Width;
258101309feSBevin Hansson       RetVal.Align = Info.Align;
25997c191c4SBen Craig       assert(llvm::isPowerOf2_64(RetVal.Align.getQuantity()));
26097c191c4SBen Craig       if (auto Max = FD->getMaxAlignment())
26197c191c4SBen Craig         RetVal.Align = std::max(Ctx.toCharUnitsFromBits(Max), RetVal.Align);
26297c191c4SBen Craig       return RetVal;
26397c191c4SBen Craig     };
26497c191c4SBen Craig     std::transform(RD->field_begin(), RD->field_end(),
26597c191c4SBen Craig                    std::back_inserter(Fields), GatherSizesAndAlignments);
26655fab260SFangrui Song     llvm::sort(Fields);
26797c191c4SBen Craig     // This lets us skip over vptrs and non-virtual bases,
26897c191c4SBen Craig     // so that we can just worry about the fields in our object.
26997c191c4SBen Craig     // Note that this does cause us to miss some cases where we
27097c191c4SBen Craig     // could pack more bytes in to a base class's tail padding.
27197c191c4SBen Craig     CharUnits NewOffset = ASTContext.toCharUnitsFromBits(RL.getFieldOffset(0));
27297c191c4SBen Craig     CharUnits NewPad;
273b9250475SSaleem Abdulrasool     SmallVector<const FieldDecl *, 20> OptimalFieldsOrder;
27497c191c4SBen Craig     while (!Fields.empty()) {
27597c191c4SBen Craig       unsigned TrailingZeros =
27697c191c4SBen Craig           llvm::countTrailingZeros((unsigned long long)NewOffset.getQuantity());
27797c191c4SBen Craig       // If NewOffset is zero, then countTrailingZeros will be 64. Shifting
27897c191c4SBen Craig       // 64 will overflow our unsigned long long. Shifting 63 will turn
27997c191c4SBen Craig       // our long long (and CharUnits internal type) negative. So shift 62.
28097c191c4SBen Craig       long long CurAlignmentBits = 1ull << (std::min)(TrailingZeros, 62u);
28197c191c4SBen Craig       CharUnits CurAlignment = CharUnits::fromQuantity(CurAlignmentBits);
282b9250475SSaleem Abdulrasool       FieldInfo InsertPoint = {CurAlignment, CharUnits::Zero(), nullptr};
28397c191c4SBen Craig 
28497c191c4SBen Craig       // In the typical case, this will find the last element
28597c191c4SBen Craig       // of the vector. We won't find a middle element unless
28697c191c4SBen Craig       // we started on a poorly aligned address or have an overly
28797c191c4SBen Craig       // aligned field.
2887264a474SFangrui Song       auto Iter = llvm::upper_bound(Fields, InsertPoint);
2897264a474SFangrui Song       if (Iter != Fields.begin()) {
29097c191c4SBen Craig         // We found a field that we can layout with the current alignment.
29197c191c4SBen Craig         --Iter;
29297c191c4SBen Craig         NewOffset += Iter->Size;
293b9250475SSaleem Abdulrasool         OptimalFieldsOrder.push_back(Iter->Field);
29497c191c4SBen Craig         Fields.erase(Iter);
29597c191c4SBen Craig       } else {
29697c191c4SBen Craig         // We are poorly aligned, and we need to pad in order to layout another
29797c191c4SBen Craig         // field. Round up to at least the smallest field alignment that we
29897c191c4SBen Craig         // currently have.
29983aa9794SRui Ueyama         CharUnits NextOffset = NewOffset.alignTo(Fields[0].Align);
30097c191c4SBen Craig         NewPad += NextOffset - NewOffset;
30197c191c4SBen Craig         NewOffset = NextOffset;
30297c191c4SBen Craig       }
30397c191c4SBen Craig     }
30497c191c4SBen Craig     // Calculate tail padding.
30583aa9794SRui Ueyama     CharUnits NewSize = NewOffset.alignTo(RL.getAlignment());
30697c191c4SBen Craig     NewPad += NewSize - NewOffset;
307b9250475SSaleem Abdulrasool     return {NewPad, std::move(OptimalFieldsOrder)};
30897c191c4SBen Craig   }
30997c191c4SBen Craig 
reportRecord(const RecordDecl * RD,CharUnits BaselinePad,CharUnits OptimalPad,const SmallVector<const FieldDecl *,20> & OptimalFieldsOrder) const310b9250475SSaleem Abdulrasool   void reportRecord(
311b9250475SSaleem Abdulrasool       const RecordDecl *RD, CharUnits BaselinePad, CharUnits OptimalPad,
312b9250475SSaleem Abdulrasool       const SmallVector<const FieldDecl *, 20> &OptimalFieldsOrder) const {
31397c191c4SBen Craig     if (!PaddingBug)
31497c191c4SBen Craig       PaddingBug =
3152b3d49b6SJonas Devlieghere           std::make_unique<BugType>(this, "Excessive Padding", "Performance");
31697c191c4SBen Craig 
31797c191c4SBen Craig     SmallString<100> Buf;
31897c191c4SBen Craig     llvm::raw_svector_ostream Os(Buf);
31997c191c4SBen Craig     Os << "Excessive padding in '";
3208c20828bSAaron Ballman     Os << QualType::getAsString(RD->getTypeForDecl(), Qualifiers(),
3218c20828bSAaron Ballman                                 LangOptions())
3228c20828bSAaron Ballman        << "'";
32397c191c4SBen Craig 
32497c191c4SBen Craig     if (auto *TSD = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
32597c191c4SBen Craig       // TODO: make this show up better in the console output and in
32697c191c4SBen Craig       // the HTML. Maybe just make it show up in HTML like the path
32797c191c4SBen Craig       // diagnostics show.
32897c191c4SBen Craig       SourceLocation ILoc = TSD->getPointOfInstantiation();
32997c191c4SBen Craig       if (ILoc.isValid())
33097c191c4SBen Craig         Os << " instantiated here: "
33197c191c4SBen Craig            << ILoc.printToString(BR->getSourceManager());
33297c191c4SBen Craig     }
33397c191c4SBen Craig 
33497c191c4SBen Craig     Os << " (" << BaselinePad.getQuantity() << " padding bytes, where "
33564ab2b1dSCorentin Jabot        << OptimalPad.getQuantity() << " is optimal). "
33664ab2b1dSCorentin Jabot        << "Optimal fields order: ";
337b9250475SSaleem Abdulrasool     for (const auto *FD : OptimalFieldsOrder)
33864ab2b1dSCorentin Jabot       Os << FD->getName() << ", ";
339b9250475SSaleem Abdulrasool     Os << "consider reordering the fields or adding explicit padding "
340b9250475SSaleem Abdulrasool           "members.";
34197c191c4SBen Craig 
34297c191c4SBen Craig     PathDiagnosticLocation CELoc =
34397c191c4SBen Craig         PathDiagnosticLocation::create(RD, BR->getSourceManager());
3442f169e7cSArtem Dergachev     auto Report =
3452f169e7cSArtem Dergachev         std::make_unique<BasicBugReport>(*PaddingBug, Os.str(), CELoc);
34697c191c4SBen Craig     Report->setDeclWithIssue(RD);
34797c191c4SBen Craig     Report->addRange(RD->getSourceRange());
34897c191c4SBen Craig     BR->emitReport(std::move(Report));
34997c191c4SBen Craig   }
35097c191c4SBen Craig };
351e2f07346SAlexander Shaposhnikov } // namespace
35297c191c4SBen Craig 
registerPaddingChecker(CheckerManager & Mgr)35397c191c4SBen Craig void ento::registerPaddingChecker(CheckerManager &Mgr) {
354088b1c9cSKristof Umann   auto *Checker = Mgr.registerChecker<PaddingChecker>();
355088b1c9cSKristof Umann   Checker->AllowedPad = Mgr.getAnalyzerOptions()
35683cc1b35SKristof Umann           .getCheckerIntegerOption(Checker, "AllowedPad");
357748c139aSKristof Umann   if (Checker->AllowedPad < 0)
358748c139aSKristof Umann     Mgr.reportInvalidCheckerOptionValue(
359748c139aSKristof Umann         Checker, "AllowedPad", "a non-negative value");
36097c191c4SBen Craig }
361058a7a45SKristof Umann 
shouldRegisterPaddingChecker(const CheckerManager & mgr)362bda3dd0dSKirstóf Umann bool ento::shouldRegisterPaddingChecker(const CheckerManager &mgr) {
363058a7a45SKristof Umann   return true;
364058a7a45SKristof Umann }
365