clang-tools  5.0.0
SuspiciousEnumUsageCheck.cpp
Go to the documentation of this file.
1 //===--- SuspiciousEnumUsageCheck.cpp - clang-tidy-------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
11 #include "clang/AST/ASTContext.h"
12 #include "clang/ASTMatchers/ASTMatchFinder.h"
13 #include <algorithm>
14 
15 using namespace clang::ast_matchers;
16 
17 namespace clang {
18 namespace tidy {
19 namespace misc {
20 
21 static const char DifferentEnumErrorMessage[] =
22  "enum values are from different enum types";
23 
24 static const char BitmaskErrorMessage[] =
25  "enum type seems like a bitmask (contains mostly "
26  "power-of-2 literals), but this literal is not a "
27  "power-of-2";
28 
29 static const char BitmaskVarErrorMessage[] =
30  "enum type seems like a bitmask (contains mostly "
31  "power-of-2 literals) but %plural{1:a literal is|:some literals are}0 not "
32  "power-of-2";
33 
34 static const char BitmaskNoteMessage[] = "used here as a bitmask";
35 
36 /// Stores a min and a max value which describe an interval.
37 struct ValueRange {
38  llvm::APSInt MinVal;
39  llvm::APSInt MaxVal;
40 
41  ValueRange(const EnumDecl *EnumDec) {
42  const auto MinMaxVal = std::minmax_element(
43  EnumDec->enumerator_begin(), EnumDec->enumerator_end(),
44  [](const EnumConstantDecl *E1, const EnumConstantDecl *E2) {
45  return E1->getInitVal() < E2->getInitVal();
46  });
47  MinVal = MinMaxVal.first->getInitVal();
48  MaxVal = MinMaxVal.second->getInitVal();
49  }
50 };
51 
52 /// Return the number of EnumConstantDecls in an EnumDecl.
53 static int enumLength(const EnumDecl *EnumDec) {
54  return std::distance(EnumDec->enumerator_begin(), EnumDec->enumerator_end());
55 }
56 
57 static bool hasDisjointValueRange(const EnumDecl *Enum1,
58  const EnumDecl *Enum2) {
59  ValueRange Range1(Enum1), Range2(Enum2);
60  return (Range1.MaxVal < Range2.MinVal) || (Range2.MaxVal < Range1.MinVal);
61 }
62 
63 static bool isNonPowerOf2NorNullLiteral(const EnumConstantDecl *EnumConst) {
64  llvm::APSInt Val = EnumConst->getInitVal();
65  if (Val.isPowerOf2() || !Val.getBoolValue())
66  return false;
67  const Expr *InitExpr = EnumConst->getInitExpr();
68  if (!InitExpr)
69  return true;
70  return isa<IntegerLiteral>(InitExpr->IgnoreImpCasts());
71 }
72 
73 static bool isMaxValAllBitSetLiteral(const EnumDecl *EnumDec) {
74  auto EnumConst = std::max_element(
75  EnumDec->enumerator_begin(), EnumDec->enumerator_end(),
76  [](const EnumConstantDecl *E1, const EnumConstantDecl *E2) {
77  return E1->getInitVal() < E2->getInitVal();
78  });
79 
80  if (const Expr *InitExpr = EnumConst->getInitExpr()) {
81  return EnumConst->getInitVal().countTrailingOnes() ==
82  EnumConst->getInitVal().getActiveBits() &&
83  isa<IntegerLiteral>(InitExpr->IgnoreImpCasts());
84  }
85  return false;
86 }
87 
88 static int countNonPowOfTwoLiteralNum(const EnumDecl *EnumDec) {
89  return std::count_if(
90  EnumDec->enumerator_begin(), EnumDec->enumerator_end(),
91  [](const EnumConstantDecl *E) { return isNonPowerOf2NorNullLiteral(E); });
92 }
93 
94 /// Check if there is one or two enumerators that are not a power of 2 and are
95 /// initialized by a literal in the enum type, and that the enumeration contains
96 /// enough elements to reasonably act as a bitmask. Exclude the case where the
97 /// last enumerator is the sum of the lesser values (and initialized by a
98 /// literal) or when it could contain consecutive values.
99 static bool isPossiblyBitMask(const EnumDecl *EnumDec) {
100  ValueRange VR(EnumDec);
101  int EnumLen = enumLength(EnumDec);
102  int NonPowOfTwoCounter = countNonPowOfTwoLiteralNum(EnumDec);
103  return NonPowOfTwoCounter >= 1 && NonPowOfTwoCounter <= 2 &&
104  NonPowOfTwoCounter < EnumLen / 2 &&
105  (VR.MaxVal - VR.MinVal != EnumLen - 1) &&
106  !(NonPowOfTwoCounter == 1 && isMaxValAllBitSetLiteral(EnumDec));
107 }
108 
109 SuspiciousEnumUsageCheck::SuspiciousEnumUsageCheck(StringRef Name,
111  : ClangTidyCheck(Name, Context),
112  StrictMode(Options.getLocalOrGlobal("StrictMode", 0)) {}
113 
115  Options.store(Opts, "StrictMode", StrictMode);
116 }
117 
119  const auto enumExpr = [](StringRef RefName, StringRef DeclName) {
120  return allOf(ignoringImpCasts(expr().bind(RefName)),
121  ignoringImpCasts(hasType(enumDecl().bind(DeclName))));
122  };
123 
124  Finder->addMatcher(
125  binaryOperator(hasOperatorName("|"), hasLHS(enumExpr("", "enumDecl")),
126  hasRHS(allOf(enumExpr("", "otherEnumDecl"),
127  ignoringImpCasts(hasType(enumDecl(
128  unless(equalsBoundNode("enumDecl"))))))))
129  .bind("diffEnumOp"),
130  this);
131 
132  Finder->addMatcher(
133  binaryOperator(anyOf(hasOperatorName("+"), hasOperatorName("|")),
134  hasLHS(enumExpr("lhsExpr", "enumDecl")),
135  hasRHS(allOf(enumExpr("rhsExpr", ""),
136  ignoringImpCasts(hasType(enumDecl(
137  equalsBoundNode("enumDecl"))))))),
138  this);
139 
140  Finder->addMatcher(
141  binaryOperator(anyOf(hasOperatorName("+"), hasOperatorName("|")),
142  hasEitherOperand(
143  allOf(hasType(isInteger()), unless(enumExpr("", "")))),
144  hasEitherOperand(enumExpr("enumExpr", "enumDecl"))),
145  this);
146 
147  Finder->addMatcher(
148  binaryOperator(anyOf(hasOperatorName("|="), hasOperatorName("+=")),
149  hasRHS(enumExpr("enumExpr", "enumDecl"))),
150  this);
151 }
152 
153 void SuspiciousEnumUsageCheck::checkSuspiciousBitmaskUsage(
154  const Expr *NodeExpr, const EnumDecl *EnumDec) {
155  const auto *EnumExpr = dyn_cast<DeclRefExpr>(NodeExpr);
156  const auto *EnumConst =
157  EnumExpr ? dyn_cast<EnumConstantDecl>(EnumExpr->getDecl()) : nullptr;
158 
159  // Report the parameter if neccessary.
160  if (!EnumConst) {
161  diag(EnumDec->getInnerLocStart(), BitmaskVarErrorMessage)
162  << countNonPowOfTwoLiteralNum(EnumDec);
163  diag(EnumExpr->getExprLoc(), BitmaskNoteMessage, DiagnosticIDs::Note);
164  } else if (isNonPowerOf2NorNullLiteral(EnumConst)) {
165  diag(EnumConst->getSourceRange().getBegin(), BitmaskErrorMessage);
166  diag(EnumExpr->getExprLoc(), BitmaskNoteMessage, DiagnosticIDs::Note);
167  }
168 }
169 
170 void SuspiciousEnumUsageCheck::check(const MatchFinder::MatchResult &Result) {
171  // Case 1: The two enum values come from different types.
172  if (const auto *DiffEnumOp =
173  Result.Nodes.getNodeAs<BinaryOperator>("diffEnumOp")) {
174  const auto *EnumDec = Result.Nodes.getNodeAs<EnumDecl>("enumDecl");
175  const auto *OtherEnumDec =
176  Result.Nodes.getNodeAs<EnumDecl>("otherEnumDecl");
177  // Skip when one of the parameters is an empty enum. The
178  // hasDisjointValueRange function could not decide the values properly in
179  // case of an empty enum.
180  if (EnumDec->enumerator_begin() == EnumDec->enumerator_end() ||
181  OtherEnumDec->enumerator_begin() == OtherEnumDec->enumerator_end())
182  return;
183 
184  if (!hasDisjointValueRange(EnumDec, OtherEnumDec))
185  diag(DiffEnumOp->getOperatorLoc(), DifferentEnumErrorMessage);
186  return;
187  }
188 
189  // Case 2 and 3 only checked in strict mode. The checker tries to detect
190  // suspicious bitmasks which contains values initialized by non power-of-2
191  // literals.
192  if (!StrictMode)
193  return;
194  const auto *EnumDec = Result.Nodes.getNodeAs<EnumDecl>("enumDecl");
195  if (!isPossiblyBitMask(EnumDec))
196  return;
197 
198  // Case 2:
199  // a. Investigating the right hand side of `+=` or `|=` operator.
200  // b. When the operator is `|` or `+` but only one of them is an EnumExpr
201  if (const auto *EnumExpr = Result.Nodes.getNodeAs<Expr>("enumExpr")) {
202  checkSuspiciousBitmaskUsage(EnumExpr, EnumDec);
203  return;
204  }
205 
206  // Case 3:
207  // '|' or '+' operator where both argument comes from the same enum type
208  const auto *LhsExpr = Result.Nodes.getNodeAs<Expr>("lhsExpr");
209  checkSuspiciousBitmaskUsage(LhsExpr, EnumDec);
210 
211  const auto *RhsExpr = Result.Nodes.getNodeAs<Expr>("rhsExpr");
212  checkSuspiciousBitmaskUsage(RhsExpr, EnumDec);
213 }
214 
215 } // namespace misc
216 } // namespace tidy
217 } // namespace clang
static int countNonPowOfTwoLiteralNum(const EnumDecl *EnumDec)
static const char DifferentEnumErrorMessage[]
static const char BitmaskVarErrorMessage[]
StringHandle Name
std::unique_ptr< ast_matchers::MatchFinder > Finder
Definition: ClangTidy.cpp:275
Base class for all clang-tidy checks.
Definition: ClangTidy.h:127
static bool isPossiblyBitMask(const EnumDecl *EnumDec)
Check if there is one or two enumerators that are not a power of 2 and are initialized by a literal i...
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Should store all options supported by this check with their current values or default values for opti...
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
static bool hasDisjointValueRange(const EnumDecl *Enum1, const EnumDecl *Enum2)
void store(ClangTidyOptions::OptionMap &Options, StringRef LocalName, StringRef Value) const
Stores an option with the check-local name LocalName with string value Value to Options.
Definition: ClangTidy.cpp:449
std::map< std::string, std::string > OptionMap
static bool isNonPowerOf2NorNullLiteral(const EnumConstantDecl *EnumConst)
static const char BitmaskNoteMessage[]
static const char BitmaskErrorMessage[]
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
Stores a min and a max value which describe an interval.
ClangTidyContext & Context
Definition: ClangTidy.cpp:87
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
static int enumLength(const EnumDecl *EnumDec)
Return the number of EnumConstantDecls in an EnumDecl.
static bool isMaxValAllBitSetLiteral(const EnumDecl *EnumDec)
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
Definition: ClangTidy.cpp:416