Bug Summary

File:build/source/clang-tools-extra/clang-tidy/utils/ExceptionAnalyzer.cpp
Warning:line 467, column 9
Value stored to 'ThrownType' is never read

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name ExceptionAnalyzer.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/source/build-llvm/tools/clang/stage2-bins -resource-dir /usr/lib/llvm-17/lib/clang/17 -D CLANG_REPOSITORY_STRING="++20230510111145+7df43bdb42ae-1~exp1~20230510111303.1288" -D _DEBUG -D _GLIBCXX_ASSERTIONS -D _GNU_SOURCE -D _LIBCPP_ENABLE_ASSERTIONS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/tools/extra/clang-tidy/utils -I /build/source/clang-tools-extra/clang-tidy/utils -I tools/clang/tools/extra/clang-tidy -I /build/source/clang/include -I tools/clang/include -I include -I /build/source/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-17/lib/clang/17/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/source/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fcoverage-prefix-map=/build/source/= -source-date-epoch 1683717183 -O2 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/source/build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/source/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/source/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2023-05-10-133810-16478-1 -x c++ /build/source/clang-tools-extra/clang-tidy/utils/ExceptionAnalyzer.cpp
1//===--- ExceptionAnalyzer.cpp - clang-tidy -------------------------------===//
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
9#include "ExceptionAnalyzer.h"
10
11namespace clang::tidy::utils {
12
13void ExceptionAnalyzer::ExceptionInfo::registerException(
14 const Type *ExceptionType) {
15 assert(ExceptionType != nullptr && "Only valid types are accepted")(static_cast <bool> (ExceptionType != nullptr &&
"Only valid types are accepted") ? void (0) : __assert_fail (
"ExceptionType != nullptr && \"Only valid types are accepted\""
, "clang-tools-extra/clang-tidy/utils/ExceptionAnalyzer.cpp",
15, __extension__ __PRETTY_FUNCTION__))
;
16 Behaviour = State::Throwing;
17 ThrownExceptions.insert(ExceptionType);
18}
19
20void ExceptionAnalyzer::ExceptionInfo::registerExceptions(
21 const Throwables &Exceptions) {
22 if (Exceptions.size() == 0)
23 return;
24 Behaviour = State::Throwing;
25 ThrownExceptions.insert(Exceptions.begin(), Exceptions.end());
26}
27
28ExceptionAnalyzer::ExceptionInfo &ExceptionAnalyzer::ExceptionInfo::merge(
29 const ExceptionAnalyzer::ExceptionInfo &Other) {
30 // Only the following two cases require an update to the local
31 // 'Behaviour'. If the local entity is already throwing there will be no
32 // change and if the other entity is throwing the merged entity will throw
33 // as well.
34 // If one of both entities is 'Unknown' and the other one does not throw
35 // the merged entity is 'Unknown' as well.
36 if (Other.Behaviour == State::Throwing)
37 Behaviour = State::Throwing;
38 else if (Other.Behaviour == State::Unknown && Behaviour == State::NotThrowing)
39 Behaviour = State::Unknown;
40
41 ContainsUnknown = ContainsUnknown || Other.ContainsUnknown;
42 ThrownExceptions.insert(Other.ThrownExceptions.begin(),
43 Other.ThrownExceptions.end());
44 return *this;
45}
46
47// FIXME: This could be ported to clang later.
48namespace {
49
50bool isUnambiguousPublicBaseClass(const Type *DerivedType,
51 const Type *BaseType) {
52 const auto *DerivedClass =
53 DerivedType->getCanonicalTypeUnqualified()->getAsCXXRecordDecl();
54 const auto *BaseClass =
55 BaseType->getCanonicalTypeUnqualified()->getAsCXXRecordDecl();
56 if (!DerivedClass || !BaseClass)
57 return false;
58
59 CXXBasePaths Paths;
60 Paths.setOrigin(DerivedClass);
61
62 bool IsPublicBaseClass = false;
63 DerivedClass->lookupInBases(
64 [&BaseClass, &IsPublicBaseClass](const CXXBaseSpecifier *BS,
65 CXXBasePath &) {
66 if (BS->getType()
67 ->getCanonicalTypeUnqualified()
68 ->getAsCXXRecordDecl() == BaseClass &&
69 BS->getAccessSpecifier() == AS_public) {
70 IsPublicBaseClass = true;
71 return true;
72 }
73
74 return false;
75 },
76 Paths);
77
78 return !Paths.isAmbiguous(BaseType->getCanonicalTypeUnqualified()) &&
79 IsPublicBaseClass;
80}
81
82inline bool isPointerOrPointerToMember(const Type *T) {
83 return T->isPointerType() || T->isMemberPointerType();
84}
85
86std::optional<QualType> getPointeeOrArrayElementQualType(QualType T) {
87 if (T->isAnyPointerType() || T->isMemberPointerType())
88 return T->getPointeeType();
89
90 if (T->isArrayType())
91 return T->getAsArrayTypeUnsafe()->getElementType();
92
93 return std::nullopt;
94}
95
96bool isBaseOf(const Type *DerivedType, const Type *BaseType) {
97 const auto *DerivedClass = DerivedType->getAsCXXRecordDecl();
98 const auto *BaseClass = BaseType->getAsCXXRecordDecl();
99 if (!DerivedClass || !BaseClass)
100 return false;
101
102 return !DerivedClass->forallBases(
103 [BaseClass](const CXXRecordDecl *Cur) { return Cur != BaseClass; });
104}
105
106// Check if T1 is more or Equally qualified than T2.
107bool moreOrEquallyQualified(QualType T1, QualType T2) {
108 return T1.getQualifiers().isStrictSupersetOf(T2.getQualifiers()) ||
109 T1.getQualifiers() == T2.getQualifiers();
110}
111
112bool isStandardPointerConvertible(QualType From, QualType To) {
113 assert((From->isPointerType() || From->isMemberPointerType()) &&(static_cast <bool> ((From->isPointerType() || From->
isMemberPointerType()) && (To->isPointerType() || To
->isMemberPointerType()) && "Pointer conversion should be performed on pointer types only."
) ? void (0) : __assert_fail ("(From->isPointerType() || From->isMemberPointerType()) && (To->isPointerType() || To->isMemberPointerType()) && \"Pointer conversion should be performed on pointer types only.\""
, "clang-tools-extra/clang-tidy/utils/ExceptionAnalyzer.cpp",
115, __extension__ __PRETTY_FUNCTION__))
114 (To->isPointerType() || To->isMemberPointerType()) &&(static_cast <bool> ((From->isPointerType() || From->
isMemberPointerType()) && (To->isPointerType() || To
->isMemberPointerType()) && "Pointer conversion should be performed on pointer types only."
) ? void (0) : __assert_fail ("(From->isPointerType() || From->isMemberPointerType()) && (To->isPointerType() || To->isMemberPointerType()) && \"Pointer conversion should be performed on pointer types only.\""
, "clang-tools-extra/clang-tidy/utils/ExceptionAnalyzer.cpp",
115, __extension__ __PRETTY_FUNCTION__))
115 "Pointer conversion should be performed on pointer types only.")(static_cast <bool> ((From->isPointerType() || From->
isMemberPointerType()) && (To->isPointerType() || To
->isMemberPointerType()) && "Pointer conversion should be performed on pointer types only."
) ? void (0) : __assert_fail ("(From->isPointerType() || From->isMemberPointerType()) && (To->isPointerType() || To->isMemberPointerType()) && \"Pointer conversion should be performed on pointer types only.\""
, "clang-tools-extra/clang-tidy/utils/ExceptionAnalyzer.cpp",
115, __extension__ __PRETTY_FUNCTION__))
;
116
117 if (!moreOrEquallyQualified(To->getPointeeType(), From->getPointeeType()))
118 return false;
119
120 // (1)
121 // A null pointer constant can be converted to a pointer type ...
122 // The conversion of a null pointer constant to a pointer to cv-qualified type
123 // is a single conversion, and not the sequence of a pointer conversion
124 // followed by a qualification conversion. A null pointer constant of integral
125 // type can be converted to a prvalue of type std::nullptr_t
126 if (To->isPointerType() && From->isNullPtrType())
127 return true;
128
129 // (2)
130 // A prvalue of type “pointer to cv T”, where T is an object type, can be
131 // converted to a prvalue of type “pointer to cv void”.
132 if (To->isVoidPointerType() && From->isObjectPointerType())
133 return true;
134
135 // (3)
136 // A prvalue of type “pointer to cv D”, where D is a complete class type, can
137 // be converted to a prvalue of type “pointer to cv B”, where B is a base
138 // class of D. If B is an inaccessible or ambiguous base class of D, a program
139 // that necessitates this conversion is ill-formed.
140 if (const auto *RD = From->getPointeeCXXRecordDecl()) {
141 if (RD->isCompleteDefinition() &&
142 isBaseOf(From->getPointeeType().getTypePtr(),
143 To->getPointeeType().getTypePtr())) {
144 return true;
145 }
146 }
147
148 return false;
149}
150
151bool isFunctionPointerConvertible(QualType From, QualType To) {
152 if (!From->isFunctionPointerType() && !From->isFunctionType() &&
153 !From->isMemberFunctionPointerType())
154 return false;
155
156 if (!To->isFunctionPointerType() && !To->isMemberFunctionPointerType())
157 return false;
158
159 if (To->isFunctionPointerType()) {
160 if (From->isFunctionPointerType())
161 return To->getPointeeType() == From->getPointeeType();
162
163 if (From->isFunctionType())
164 return To->getPointeeType() == From;
165
166 return false;
167 }
168
169 if (To->isMemberFunctionPointerType()) {
170 if (!From->isMemberFunctionPointerType())
171 return false;
172
173 const auto *FromMember = cast<MemberPointerType>(From);
174 const auto *ToMember = cast<MemberPointerType>(To);
175
176 // Note: converting Derived::* to Base::* is a different kind of conversion,
177 // called Pointer-to-member conversion.
178 return FromMember->getClass() == ToMember->getClass() &&
179 FromMember->getPointeeType() == ToMember->getPointeeType();
180 }
181
182 return false;
183}
184
185// Checks if From is qualification convertible to To based on the current
186// LangOpts. If From is any array, we perform the array to pointer conversion
187// first. The function only performs checks based on C++ rules, which can differ
188// from the C rules.
189//
190// The function should only be called in C++ mode.
191bool isQualificationConvertiblePointer(QualType From, QualType To,
192 LangOptions LangOpts) {
193
194 // [N4659 7.5 (1)]
195 // A cv-decomposition of a type T is a sequence of cv_i and P_i such that T is
196 // cv_0 P_0 cv_1 P_1 ... cv_n−1 P_n−1 cv_n U” for n > 0,
197 // where each cv_i is a set of cv-qualifiers, and each P_i is “pointer to”,
198 // “pointer to member of class C_i of type”, “array of N_i”, or
199 // “array of unknown bound of”.
200 //
201 // If P_i designates an array, the cv-qualifiers cv_i+1 on the element type
202 // are also taken as the cv-qualifiers cvi of the array.
203 //
204 // The n-tuple of cv-qualifiers after the first one in the longest
205 // cv-decomposition of T, that is, cv_1, cv_2, ... , cv_n, is called the
206 // cv-qualification signature of T.
207
208 auto isValidP_i = [](QualType P) {
209 return P->isPointerType() || P->isMemberPointerType() ||
210 P->isConstantArrayType() || P->isIncompleteArrayType();
211 };
212
213 auto isSameP_i = [](QualType P1, QualType P2) {
214 if (P1->isPointerType())
215 return P2->isPointerType();
216
217 if (P1->isMemberPointerType())
218 return P2->isMemberPointerType() &&
219 P1->getAs<MemberPointerType>()->getClass() ==
220 P2->getAs<MemberPointerType>()->getClass();
221
222 if (P1->isConstantArrayType())
223 return P2->isConstantArrayType() &&
224 cast<ConstantArrayType>(P1)->getSize() ==
225 cast<ConstantArrayType>(P2)->getSize();
226
227 if (P1->isIncompleteArrayType())
228 return P2->isIncompleteArrayType();
229
230 return false;
231 };
232
233 // (2)
234 // Two types From and To are similar if they have cv-decompositions with the
235 // same n such that corresponding P_i components are the same [(added by
236 // N4849 7.3.5) or one is “array of N_i” and the other is “array of unknown
237 // bound of”], and the types denoted by U are the same.
238 //
239 // (3)
240 // A prvalue expression of type From can be converted to type To if the
241 // following conditions are satisfied:
242 // - From and To are similar
243 // - For every i > 0, if const is in cv_i of From then const is in cv_i of
244 // To, and similarly for volatile.
245 // - [(derived from addition by N4849 7.3.5) If P_i of From is “array of
246 // unknown bound of”, P_i of To is “array of unknown bound of”.]
247 // - If the cv_i of From and cv_i of To are different, then const is in every
248 // cv_k of To for 0 < k < i.
249
250 int I = 0;
251 bool ConstUntilI = true;
252 auto SatisfiesCVRules = [&I, &ConstUntilI](const QualType &From,
253 const QualType &To) {
254 if (I > 1) {
255 if (From.getQualifiers() != To.getQualifiers() && !ConstUntilI)
256 return false;
257 }
258
259 if (I > 0) {
260 if (From.isConstQualified() && !To.isConstQualified())
261 return false;
262
263 if (From.isVolatileQualified() && !To.isVolatileQualified())
264 return false;
265
266 ConstUntilI = To.isConstQualified();
267 }
268
269 return true;
270 };
271
272 while (isValidP_i(From) && isValidP_i(To)) {
273 // Remove every sugar.
274 From = From.getCanonicalType();
275 To = To.getCanonicalType();
276
277 if (!SatisfiesCVRules(From, To))
278 return false;
279
280 if (!isSameP_i(From, To)) {
281 if (LangOpts.CPlusPlus20) {
282 if (From->isConstantArrayType() && !To->isIncompleteArrayType())
283 return false;
284
285 if (From->isIncompleteArrayType() && !To->isIncompleteArrayType())
286 return false;
287
288 } else {
289 return false;
290 }
291 }
292
293 ++I;
294 std::optional<QualType> FromPointeeOrElem =
295 getPointeeOrArrayElementQualType(From);
296 std::optional<QualType> ToPointeeOrElem =
297 getPointeeOrArrayElementQualType(To);
298
299 assert(FromPointeeOrElem &&(static_cast <bool> (FromPointeeOrElem && "From pointer or array has no pointee or element!"
) ? void (0) : __assert_fail ("FromPointeeOrElem && \"From pointer or array has no pointee or element!\""
, "clang-tools-extra/clang-tidy/utils/ExceptionAnalyzer.cpp",
300, __extension__ __PRETTY_FUNCTION__))
300 "From pointer or array has no pointee or element!")(static_cast <bool> (FromPointeeOrElem && "From pointer or array has no pointee or element!"
) ? void (0) : __assert_fail ("FromPointeeOrElem && \"From pointer or array has no pointee or element!\""
, "clang-tools-extra/clang-tidy/utils/ExceptionAnalyzer.cpp",
300, __extension__ __PRETTY_FUNCTION__))
;
301 assert(ToPointeeOrElem && "To pointer or array has no pointee or element!")(static_cast <bool> (ToPointeeOrElem && "To pointer or array has no pointee or element!"
) ? void (0) : __assert_fail ("ToPointeeOrElem && \"To pointer or array has no pointee or element!\""
, "clang-tools-extra/clang-tidy/utils/ExceptionAnalyzer.cpp",
301, __extension__ __PRETTY_FUNCTION__))
;
302
303 From = *FromPointeeOrElem;
304 To = *ToPointeeOrElem;
305 }
306
307 // In this case the length (n) of From and To are not the same.
308 if (isValidP_i(From) || isValidP_i(To))
309 return false;
310
311 // We hit U.
312 if (!SatisfiesCVRules(From, To))
313 return false;
314
315 return From.getTypePtr() == To.getTypePtr();
316}
317} // namespace
318
319bool ExceptionAnalyzer::ExceptionInfo::filterByCatch(
320 const Type *HandlerTy, const ASTContext &Context) {
321 llvm::SmallVector<const Type *, 8> TypesToDelete;
322 for (const Type *ExceptionTy : ThrownExceptions) {
323 CanQualType ExceptionCanTy = ExceptionTy->getCanonicalTypeUnqualified();
324 CanQualType HandlerCanTy = HandlerTy->getCanonicalTypeUnqualified();
325
326 // The handler is of type cv T or cv T& and E and T are the same type
327 // (ignoring the top-level cv-qualifiers) ...
328 if (ExceptionCanTy == HandlerCanTy) {
329 TypesToDelete.push_back(ExceptionTy);
330 }
331
332 // The handler is of type cv T or cv T& and T is an unambiguous public base
333 // class of E ...
334 else if (isUnambiguousPublicBaseClass(ExceptionCanTy->getTypePtr(),
335 HandlerCanTy->getTypePtr())) {
336 TypesToDelete.push_back(ExceptionTy);
337 }
338
339 if (HandlerCanTy->getTypeClass() == Type::RValueReference ||
340 (HandlerCanTy->getTypeClass() == Type::LValueReference &&
341 !HandlerCanTy->getTypePtr()->getPointeeType().isConstQualified()))
342 continue;
343 // The handler is of type cv T or const T& where T is a pointer or
344 // pointer-to-member type and E is a pointer or pointer-to-member type that
345 // can be converted to T by one or more of ...
346 if (isPointerOrPointerToMember(HandlerCanTy->getTypePtr()) &&
347 isPointerOrPointerToMember(ExceptionCanTy->getTypePtr())) {
348 // A standard pointer conversion not involving conversions to pointers to
349 // private or protected or ambiguous classes ...
350 if (isStandardPointerConvertible(ExceptionCanTy, HandlerCanTy) &&
351 isUnambiguousPublicBaseClass(
352 ExceptionCanTy->getTypePtr()->getPointeeType().getTypePtr(),
353 HandlerCanTy->getTypePtr()->getPointeeType().getTypePtr())) {
354 TypesToDelete.push_back(ExceptionTy);
355 }
356 // A function pointer conversion ...
357 else if (isFunctionPointerConvertible(ExceptionCanTy, HandlerCanTy)) {
358 TypesToDelete.push_back(ExceptionTy);
359 }
360 // A a qualification conversion ...
361 else if (isQualificationConvertiblePointer(ExceptionCanTy, HandlerCanTy,
362 Context.getLangOpts())) {
363 TypesToDelete.push_back(ExceptionTy);
364 }
365 }
366
367 // The handler is of type cv T or const T& where T is a pointer or
368 // pointer-to-member type and E is std::nullptr_t.
369 else if (isPointerOrPointerToMember(HandlerCanTy->getTypePtr()) &&
370 ExceptionCanTy->isNullPtrType()) {
371 TypesToDelete.push_back(ExceptionTy);
372 }
373 }
374
375 for (const Type *T : TypesToDelete)
376 ThrownExceptions.erase(T);
377
378 reevaluateBehaviour();
379 return TypesToDelete.size() > 0;
380}
381
382ExceptionAnalyzer::ExceptionInfo &
383ExceptionAnalyzer::ExceptionInfo::filterIgnoredExceptions(
384 const llvm::StringSet<> &IgnoredTypes, bool IgnoreBadAlloc) {
385 llvm::SmallVector<const Type *, 8> TypesToDelete;
386 // Note: Using a 'SmallSet' with 'llvm::remove_if()' is not possible.
387 // Therefore this slightly hacky implementation is required.
388 for (const Type *T : ThrownExceptions) {
389 if (const auto *TD = T->getAsTagDecl()) {
390 if (TD->getDeclName().isIdentifier()) {
391 if ((IgnoreBadAlloc &&
392 (TD->getName() == "bad_alloc" && TD->isInStdNamespace())) ||
393 (IgnoredTypes.count(TD->getName()) > 0))
394 TypesToDelete.push_back(T);
395 }
396 }
397 }
398 for (const Type *T : TypesToDelete)
399 ThrownExceptions.erase(T);
400
401 reevaluateBehaviour();
402 return *this;
403}
404
405void ExceptionAnalyzer::ExceptionInfo::clear() {
406 Behaviour = State::NotThrowing;
407 ContainsUnknown = false;
408 ThrownExceptions.clear();
409}
410
411void ExceptionAnalyzer::ExceptionInfo::reevaluateBehaviour() {
412 if (ThrownExceptions.size() == 0)
413 if (ContainsUnknown)
414 Behaviour = State::Unknown;
415 else
416 Behaviour = State::NotThrowing;
417 else
418 Behaviour = State::Throwing;
419}
420
421ExceptionAnalyzer::ExceptionInfo ExceptionAnalyzer::throwsException(
422 const FunctionDecl *Func,
423 llvm::SmallSet<const FunctionDecl *, 32> &CallStack) {
424 if (CallStack.count(Func))
425 return ExceptionInfo::createNonThrowing();
426
427 if (const Stmt *Body = Func->getBody()) {
428 CallStack.insert(Func);
429 ExceptionInfo Result =
430 throwsException(Body, ExceptionInfo::Throwables(), CallStack);
431
432 // For a constructor, we also have to check the initializers.
433 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Func)) {
434 for (const CXXCtorInitializer *Init : Ctor->inits()) {
435 ExceptionInfo Excs = throwsException(
436 Init->getInit(), ExceptionInfo::Throwables(), CallStack);
437 Result.merge(Excs);
438 }
439 }
440
441 CallStack.erase(Func);
442 return Result;
443 }
444
445 auto Result = ExceptionInfo::createUnknown();
446 if (const auto *FPT = Func->getType()->getAs<FunctionProtoType>()) {
447 for (const QualType &Ex : FPT->exceptions())
448 Result.registerException(Ex.getTypePtr());
449 }
450 return Result;
451}
452
453/// Analyzes a single statement on it's throwing behaviour. This is in principle
454/// possible except some 'Unknown' functions are called.
455ExceptionAnalyzer::ExceptionInfo ExceptionAnalyzer::throwsException(
456 const Stmt *St, const ExceptionInfo::Throwables &Caught,
457 llvm::SmallSet<const FunctionDecl *, 32> &CallStack) {
458 auto Results = ExceptionInfo::createNonThrowing();
459 if (!St)
460 return Results;
461
462 if (const auto *Throw = dyn_cast<CXXThrowExpr>(St)) {
463 if (const auto *ThrownExpr = Throw->getSubExpr()) {
464 const auto *ThrownType =
465 ThrownExpr->getType()->getUnqualifiedDesugaredType();
466 if (ThrownType->isReferenceType())
467 ThrownType = ThrownType->castAs<ReferenceType>()
Value stored to 'ThrownType' is never read
468 ->getPointeeType()
469 ->getUnqualifiedDesugaredType();
470 Results.registerException(
471 ThrownExpr->getType()->getUnqualifiedDesugaredType());
472 } else
473 // A rethrow of a caught exception happens which makes it possible
474 // to throw all exception that are caught in the 'catch' clause of
475 // the parent try-catch block.
476 Results.registerExceptions(Caught);
477 } else if (const auto *Try = dyn_cast<CXXTryStmt>(St)) {
478 ExceptionInfo Uncaught =
479 throwsException(Try->getTryBlock(), Caught, CallStack);
480 for (unsigned I = 0; I < Try->getNumHandlers(); ++I) {
481 const CXXCatchStmt *Catch = Try->getHandler(I);
482
483 // Everything is catched through 'catch(...)'.
484 if (!Catch->getExceptionDecl()) {
485 ExceptionInfo Rethrown = throwsException(
486 Catch->getHandlerBlock(), Uncaught.getExceptionTypes(), CallStack);
487 Results.merge(Rethrown);
488 Uncaught.clear();
489 } else {
490 const auto *CaughtType =
491 Catch->getCaughtType()->getUnqualifiedDesugaredType();
492 if (CaughtType->isReferenceType()) {
493 CaughtType = CaughtType->castAs<ReferenceType>()
494 ->getPointeeType()
495 ->getUnqualifiedDesugaredType();
496 }
497
498 // If the caught exception will catch multiple previously potential
499 // thrown types (because it's sensitive to inheritance) the throwing
500 // situation changes. First of all filter the exception types and
501 // analyze if the baseclass-exception is rethrown.
502 if (Uncaught.filterByCatch(
503 CaughtType, Catch->getExceptionDecl()->getASTContext())) {
504 ExceptionInfo::Throwables CaughtExceptions;
505 CaughtExceptions.insert(CaughtType);
506 ExceptionInfo Rethrown = throwsException(Catch->getHandlerBlock(),
507 CaughtExceptions, CallStack);
508 Results.merge(Rethrown);
509 }
510 }
511 }
512 Results.merge(Uncaught);
513 } else if (const auto *Call = dyn_cast<CallExpr>(St)) {
514 if (const FunctionDecl *Func = Call->getDirectCallee()) {
515 ExceptionInfo Excs = throwsException(Func, CallStack);
516 Results.merge(Excs);
517 }
518 } else if (const auto *Construct = dyn_cast<CXXConstructExpr>(St)) {
519 ExceptionInfo Excs =
520 throwsException(Construct->getConstructor(), CallStack);
521 Results.merge(Excs);
522 } else if (const auto *DefaultInit = dyn_cast<CXXDefaultInitExpr>(St)) {
523 ExceptionInfo Excs =
524 throwsException(DefaultInit->getExpr(), Caught, CallStack);
525 Results.merge(Excs);
526 } else {
527 for (const Stmt *Child : St->children()) {
528 ExceptionInfo Excs = throwsException(Child, Caught, CallStack);
529 Results.merge(Excs);
530 }
531 }
532 return Results;
533}
534
535ExceptionAnalyzer::ExceptionInfo
536ExceptionAnalyzer::analyzeImpl(const FunctionDecl *Func) {
537 ExceptionInfo ExceptionList;
538
539 // Check if the function has already been analyzed and reuse that result.
540 const auto CacheEntry = FunctionCache.find(Func);
541 if (CacheEntry == FunctionCache.end()) {
542 llvm::SmallSet<const FunctionDecl *, 32> CallStack;
543 ExceptionList = throwsException(Func, CallStack);
544
545 // Cache the result of the analysis. This is done prior to filtering
546 // because it is best to keep as much information as possible.
547 // The results here might be relevant to different analysis passes
548 // with different needs as well.
549 FunctionCache.try_emplace(Func, ExceptionList);
550 } else
551 ExceptionList = CacheEntry->getSecond();
552
553 return ExceptionList;
554}
555
556ExceptionAnalyzer::ExceptionInfo
557ExceptionAnalyzer::analyzeImpl(const Stmt *Stmt) {
558 llvm::SmallSet<const FunctionDecl *, 32> CallStack;
559 return throwsException(Stmt, ExceptionInfo::Throwables(), CallStack);
560}
561
562template <typename T>
563ExceptionAnalyzer::ExceptionInfo
564ExceptionAnalyzer::analyzeDispatch(const T *Node) {
565 ExceptionInfo ExceptionList = analyzeImpl(Node);
566
567 if (ExceptionList.getBehaviour() == State::NotThrowing ||
568 ExceptionList.getBehaviour() == State::Unknown)
569 return ExceptionList;
570
571 // Remove all ignored exceptions from the list of exceptions that can be
572 // thrown.
573 ExceptionList.filterIgnoredExceptions(IgnoredExceptions, IgnoreBadAlloc);
574
575 return ExceptionList;
576}
577
578ExceptionAnalyzer::ExceptionInfo
579ExceptionAnalyzer::analyze(const FunctionDecl *Func) {
580 return analyzeDispatch(Func);
581}
582
583ExceptionAnalyzer::ExceptionInfo ExceptionAnalyzer::analyze(const Stmt *Stmt) {
584 return analyzeDispatch(Stmt);
585}
586
587} // namespace clang::tidy::utils