clang-tools 23.0.0git
MisplacedWideningCastCheck.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10#include "clang/AST/ASTContext.h"
11#include "clang/ASTMatchers/ASTMatchFinder.h"
12
13using namespace clang::ast_matchers;
14
15namespace clang::tidy::bugprone {
16
18 StringRef Name, ClangTidyContext *Context)
19 : ClangTidyCheck(Name, Context),
20 CheckImplicitCasts(Options.get("CheckImplicitCasts", false)) {}
21
24 Options.store(Opts, "CheckImplicitCasts", CheckImplicitCasts);
25}
26
28 const auto Calc =
29 expr(anyOf(binaryOperator(hasAnyOperatorName("+", "-", "*", "<<")),
30 unaryOperator(hasOperatorName("~"))),
31 hasType(isInteger()))
32 .bind("Calc");
33
34 const auto ExplicitCast = explicitCastExpr(hasDestinationType(isInteger()),
35 has(ignoringParenImpCasts(Calc)));
36 const auto ImplicitCast =
37 implicitCastExpr(hasImplicitDestinationType(isInteger()),
38 has(ignoringParenImpCasts(Calc)));
39 const auto Cast =
40 traverse(TK_AsIs, expr(anyOf(ExplicitCast, ImplicitCast)).bind("Cast"));
41
42 Finder->addMatcher(varDecl(hasInitializer(Cast)), this);
43 Finder->addMatcher(returnStmt(hasReturnValue(Cast)), this);
44 Finder->addMatcher(callExpr(hasAnyArgument(Cast)), this);
45 // When assigning to a bit field, bind the FieldDecl so check() can use the
46 // actual bit width instead of the declared type width.
47 Finder->addMatcher(
48 binaryOperator(hasOperatorName("="),
49 hasLHS(expr(optionally(memberExpr(hasDeclaration(
50 fieldDecl(isBitField()).bind("BitField")))))),
51 hasRHS(Cast)),
52 this);
53 Finder->addMatcher(
54 binaryOperator(isComparisonOperator(), hasEitherOperand(Cast)), this);
55}
56
57static unsigned getMaxCalculationWidth(const ASTContext &Context,
58 const Expr *E) {
59 E = E->IgnoreParenImpCasts();
60
61 if (const auto *Bop = dyn_cast<BinaryOperator>(E)) {
62 const unsigned LHSWidth = getMaxCalculationWidth(Context, Bop->getLHS());
63 const unsigned RHSWidth = getMaxCalculationWidth(Context, Bop->getRHS());
64 if (Bop->getOpcode() == BO_Mul)
65 return LHSWidth + RHSWidth;
66 if (Bop->getOpcode() == BO_Add)
67 return std::max(LHSWidth, RHSWidth) + 1;
68 if (Bop->getOpcode() == BO_Rem) {
69 Expr::EvalResult Result;
70 if (Bop->getRHS()->EvaluateAsInt(Result, Context))
71 return Result.Val.getInt().getActiveBits();
72 } else if (Bop->getOpcode() == BO_Shl) {
73 Expr::EvalResult Result;
74 if (Bop->getRHS()->EvaluateAsInt(Result, Context)) {
75 // We don't handle negative values and large values well. It is assumed
76 // that compiler warnings are written for such values so the user will
77 // fix that.
78 return LHSWidth + Result.Val.getInt().getExtValue();
79 }
80
81 // Unknown bitcount, assume there is truncation.
82 return 1024U;
83 }
84 } else if (const auto *Uop = dyn_cast<UnaryOperator>(E)) {
85 // There is truncation when ~ is used.
86 if (Uop->getOpcode() == UO_Not)
87 return 1024U;
88
89 const QualType T = Uop->getType();
90 return T->isIntegerType() ? Context.getIntWidth(T) : 1024U;
91 } else if (const auto *I = dyn_cast<IntegerLiteral>(E)) {
92 return I->getValue().getActiveBits();
93 }
94
95 return Context.getIntWidth(E->getType());
96}
97
98static int relativeIntSizes(BuiltinType::Kind Kind) {
99 switch (Kind) {
100 case BuiltinType::UChar:
101 return 1;
102 case BuiltinType::SChar:
103 return 1;
104 case BuiltinType::Char_U:
105 return 1;
106 case BuiltinType::Char_S:
107 return 1;
108 case BuiltinType::UShort:
109 return 2;
110 case BuiltinType::Short:
111 return 2;
112 case BuiltinType::UInt:
113 return 3;
114 case BuiltinType::Int:
115 return 3;
116 case BuiltinType::ULong:
117 return 4;
118 case BuiltinType::Long:
119 return 4;
120 case BuiltinType::ULongLong:
121 return 5;
122 case BuiltinType::LongLong:
123 return 5;
124 case BuiltinType::UInt128:
125 return 6;
126 case BuiltinType::Int128:
127 return 6;
128 default:
129 return 0;
130 }
131}
132
133static int relativeCharSizes(BuiltinType::Kind Kind) {
134 switch (Kind) {
135 case BuiltinType::UChar:
136 return 1;
137 case BuiltinType::SChar:
138 return 1;
139 case BuiltinType::Char_U:
140 return 1;
141 case BuiltinType::Char_S:
142 return 1;
143 case BuiltinType::Char16:
144 return 2;
145 case BuiltinType::Char32:
146 return 3;
147 default:
148 return 0;
149 }
150}
151
152static int relativeCharSizesW(BuiltinType::Kind Kind) {
153 switch (Kind) {
154 case BuiltinType::UChar:
155 return 1;
156 case BuiltinType::SChar:
157 return 1;
158 case BuiltinType::Char_U:
159 return 1;
160 case BuiltinType::Char_S:
161 return 1;
162 case BuiltinType::WChar_U:
163 return 2;
164 case BuiltinType::WChar_S:
165 return 2;
166 default:
167 return 0;
168 }
169}
170
171static bool isFirstWider(BuiltinType::Kind First, BuiltinType::Kind Second) {
172 int FirstSize = 0, SecondSize = 0;
173 if ((FirstSize = relativeIntSizes(First)) != 0 &&
174 (SecondSize = relativeIntSizes(Second)) != 0)
175 return FirstSize > SecondSize;
176 if ((FirstSize = relativeCharSizes(First)) != 0 &&
177 (SecondSize = relativeCharSizes(Second)) != 0)
178 return FirstSize > SecondSize;
179 if ((FirstSize = relativeCharSizesW(First)) != 0 &&
180 (SecondSize = relativeCharSizesW(Second)) != 0)
181 return FirstSize > SecondSize;
182 return false;
183}
184
185void MisplacedWideningCastCheck::check(const MatchFinder::MatchResult &Result) {
186 const auto *Cast = Result.Nodes.getNodeAs<CastExpr>("Cast");
187 if (!CheckImplicitCasts && isa<ImplicitCastExpr>(Cast))
188 return;
189 if (Cast->getBeginLoc().isMacroID())
190 return;
191
192 const auto *Calc = Result.Nodes.getNodeAs<Expr>("Calc");
193 if (Calc->getBeginLoc().isMacroID())
194 return;
195
196 if (Cast->isTypeDependent() || Cast->isValueDependent() ||
197 Calc->isTypeDependent() || Calc->isValueDependent())
198 return;
199
200 const ASTContext &Context = *Result.Context;
201
202 const QualType CastType = Cast->getType();
203 const QualType CalcType = Calc->getType();
204
205 // If assigning to a bit field, use the bit field width as the effective
206 // target width. The declared type may be wider than the actual bit field
207 // storage.
208 unsigned TargetWidth = Context.getIntWidth(CastType);
209 bool IsBitfieldAssign = false;
210 if (const auto *FD = Result.Nodes.getNodeAs<FieldDecl>("BitField")) {
211 TargetWidth = FD->getBitWidthValue();
212 IsBitfieldAssign = true;
213 }
214
215 // Explicit truncation using cast.
216 if (TargetWidth < Context.getIntWidth(CalcType))
217 return;
218
219 // If CalcType and CastType have same size then there is no real danger, but
220 // there can be a portability problem.
221
222 if (TargetWidth == Context.getIntWidth(CalcType)) {
223 // Bit field width is fixed across platforms — no portability concern.
224 if (IsBitfieldAssign)
225 return;
226 const auto *CastBuiltinType =
227 dyn_cast<BuiltinType>(CastType->getUnqualifiedDesugaredType());
228 const auto *CalcBuiltinType =
229 dyn_cast<BuiltinType>(CalcType->getUnqualifiedDesugaredType());
230 if (!CastBuiltinType || !CalcBuiltinType)
231 return;
232 if (!isFirstWider(CastBuiltinType->getKind(), CalcBuiltinType->getKind()))
233 return;
234 }
235
236 // Don't write a warning if we can easily see that the result is not
237 // truncated.
238 if (Context.getIntWidth(CalcType) >= getMaxCalculationWidth(Context, Calc))
239 return;
240
241 diag(Cast->getBeginLoc(), "either cast from %0 to %1 is ineffective, or "
242 "there is loss of precision before the conversion")
243 << CalcType << CastType;
244}
245
246} // namespace clang::tidy::bugprone
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void registerMatchers(ast_matchers::MatchFinder *Finder) override
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
MisplacedWideningCastCheck(StringRef Name, ClangTidyContext *Context)
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
static bool isFirstWider(BuiltinType::Kind First, BuiltinType::Kind Second)
static int relativeIntSizes(BuiltinType::Kind Kind)
static int relativeCharSizesW(BuiltinType::Kind Kind)
static unsigned getMaxCalculationWidth(const ASTContext &Context, const Expr *E)
static int relativeCharSizes(BuiltinType::Kind Kind)
llvm::StringMap< ClangTidyValue > OptionMap