1 //===--- ExceptionAnalyzer.cpp - clang-tidy -------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "ExceptionAnalyzer.h"
11 namespace clang::tidy::utils
{
13 void ExceptionAnalyzer::ExceptionInfo::registerException(
14 const Type
*ExceptionType
) {
15 assert(ExceptionType
!= nullptr && "Only valid types are accepted");
16 Behaviour
= State::Throwing
;
17 ThrownExceptions
.insert(ExceptionType
);
20 void ExceptionAnalyzer::ExceptionInfo::registerExceptions(
21 const Throwables
&Exceptions
) {
22 if (Exceptions
.size() == 0)
24 Behaviour
= State::Throwing
;
25 ThrownExceptions
.insert(Exceptions
.begin(), Exceptions
.end());
28 ExceptionAnalyzer::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
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
;
41 ContainsUnknown
= ContainsUnknown
|| Other
.ContainsUnknown
;
42 ThrownExceptions
.insert(Other
.ThrownExceptions
.begin(),
43 Other
.ThrownExceptions
.end());
47 // FIXME: This could be ported to clang later.
50 bool 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
)
60 Paths
.setOrigin(DerivedClass
);
62 bool IsPublicBaseClass
= false;
63 DerivedClass
->lookupInBases(
64 [&BaseClass
, &IsPublicBaseClass
](const CXXBaseSpecifier
*BS
,
67 ->getCanonicalTypeUnqualified()
68 ->getAsCXXRecordDecl() == BaseClass
&&
69 BS
->getAccessSpecifier() == AS_public
) {
70 IsPublicBaseClass
= true;
78 return !Paths
.isAmbiguous(BaseType
->getCanonicalTypeUnqualified()) &&
82 inline bool isPointerOrPointerToMember(const Type
*T
) {
83 return T
->isPointerType() || T
->isMemberPointerType();
86 std::optional
<QualType
> getPointeeOrArrayElementQualType(QualType T
) {
87 if (T
->isAnyPointerType() || T
->isMemberPointerType())
88 return T
->getPointeeType();
91 return T
->getAsArrayTypeUnsafe()->getElementType();
96 bool isBaseOf(const Type
*DerivedType
, const Type
*BaseType
) {
97 const auto *DerivedClass
= DerivedType
->getAsCXXRecordDecl();
98 const auto *BaseClass
= BaseType
->getAsCXXRecordDecl();
99 if (!DerivedClass
|| !BaseClass
)
102 return !DerivedClass
->forallBases(
103 [BaseClass
](const CXXRecordDecl
*Cur
) { return Cur
!= BaseClass
; });
106 // Check if T1 is more or Equally qualified than T2.
107 bool moreOrEquallyQualified(QualType T1
, QualType T2
) {
108 return T1
.getQualifiers().isStrictSupersetOf(T2
.getQualifiers()) ||
109 T1
.getQualifiers() == T2
.getQualifiers();
112 bool isStandardPointerConvertible(QualType From
, QualType To
) {
113 assert((From
->isPointerType() || From
->isMemberPointerType()) &&
114 (To
->isPointerType() || To
->isMemberPointerType()) &&
115 "Pointer conversion should be performed on pointer types only.");
117 if (!moreOrEquallyQualified(To
->getPointeeType(), From
->getPointeeType()))
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())
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())
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())) {
151 bool isFunctionPointerConvertible(QualType From
, QualType To
) {
152 if (!From
->isFunctionPointerType() && !From
->isFunctionType() &&
153 !From
->isMemberFunctionPointerType())
156 if (!To
->isFunctionPointerType() && !To
->isMemberFunctionPointerType())
159 if (To
->isFunctionPointerType()) {
160 if (From
->isFunctionPointerType())
161 return To
->getPointeeType() == From
->getPointeeType();
163 if (From
->isFunctionType())
164 return To
->getPointeeType() == From
;
169 if (To
->isMemberFunctionPointerType()) {
170 if (!From
->isMemberFunctionPointerType())
173 const auto *FromMember
= cast
<MemberPointerType
>(From
);
174 const auto *ToMember
= cast
<MemberPointerType
>(To
);
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();
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
190 // The function should only be called in C++ mode.
191 bool isQualificationConvertiblePointer(QualType From
, QualType To
,
192 LangOptions LangOpts
) {
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”.
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.
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.
208 auto isValidP_i
= [](QualType P
) {
209 return P
->isPointerType() || P
->isMemberPointerType() ||
210 P
->isConstantArrayType() || P
->isIncompleteArrayType();
213 auto isSameP_i
= [](QualType P1
, QualType P2
) {
214 if (P1
->isPointerType())
215 return P2
->isPointerType();
217 if (P1
->isMemberPointerType())
218 return P2
->isMemberPointerType() &&
219 P1
->getAs
<MemberPointerType
>()->getClass() ==
220 P2
->getAs
<MemberPointerType
>()->getClass();
222 if (P1
->isConstantArrayType())
223 return P2
->isConstantArrayType() &&
224 cast
<ConstantArrayType
>(P1
)->getSize() ==
225 cast
<ConstantArrayType
>(P2
)->getSize();
227 if (P1
->isIncompleteArrayType())
228 return P2
->isIncompleteArrayType();
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.
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.
251 bool ConstUntilI
= true;
252 auto SatisfiesCVRules
= [&I
, &ConstUntilI
](const QualType
&From
,
253 const QualType
&To
) {
255 if (From
.getQualifiers() != To
.getQualifiers() && !ConstUntilI
)
260 if (From
.isConstQualified() && !To
.isConstQualified())
263 if (From
.isVolatileQualified() && !To
.isVolatileQualified())
266 ConstUntilI
= To
.isConstQualified();
272 while (isValidP_i(From
) && isValidP_i(To
)) {
273 // Remove every sugar.
274 From
= From
.getCanonicalType();
275 To
= To
.getCanonicalType();
277 if (!SatisfiesCVRules(From
, To
))
280 if (!isSameP_i(From
, To
)) {
281 if (LangOpts
.CPlusPlus20
) {
282 if (From
->isConstantArrayType() && !To
->isIncompleteArrayType())
285 if (From
->isIncompleteArrayType() && !To
->isIncompleteArrayType())
294 std::optional
<QualType
> FromPointeeOrElem
=
295 getPointeeOrArrayElementQualType(From
);
296 std::optional
<QualType
> ToPointeeOrElem
=
297 getPointeeOrArrayElementQualType(To
);
299 assert(FromPointeeOrElem
&&
300 "From pointer or array has no pointee or element!");
301 assert(ToPointeeOrElem
&& "To pointer or array has no pointee or element!");
303 From
= *FromPointeeOrElem
;
304 To
= *ToPointeeOrElem
;
307 // In this case the length (n) of From and To are not the same.
308 if (isValidP_i(From
) || isValidP_i(To
))
312 if (!SatisfiesCVRules(From
, To
))
315 return From
.getTypePtr() == To
.getTypePtr();
319 bool 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();
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
);
332 // The handler is of type cv T or cv T& and T is an unambiguous public base
334 else if (isUnambiguousPublicBaseClass(ExceptionCanTy
->getTypePtr(),
335 HandlerCanTy
->getTypePtr())) {
336 TypesToDelete
.push_back(ExceptionTy
);
339 if (HandlerCanTy
->getTypeClass() == Type::RValueReference
||
340 (HandlerCanTy
->getTypeClass() == Type::LValueReference
&&
341 !HandlerCanTy
->getTypePtr()->getPointeeType().isConstQualified()))
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
);
356 // A function pointer conversion ...
357 else if (isFunctionPointerConvertible(ExceptionCanTy
, HandlerCanTy
)) {
358 TypesToDelete
.push_back(ExceptionTy
);
360 // A a qualification conversion ...
361 else if (isQualificationConvertiblePointer(ExceptionCanTy
, HandlerCanTy
,
362 Context
.getLangOpts())) {
363 TypesToDelete
.push_back(ExceptionTy
);
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
);
375 for (const Type
*T
: TypesToDelete
)
376 ThrownExceptions
.erase(T
);
378 reevaluateBehaviour();
379 return TypesToDelete
.size() > 0;
382 ExceptionAnalyzer::ExceptionInfo
&
383 ExceptionAnalyzer::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
);
398 for (const Type
*T
: TypesToDelete
)
399 ThrownExceptions
.erase(T
);
401 reevaluateBehaviour();
405 void ExceptionAnalyzer::ExceptionInfo::clear() {
406 Behaviour
= State::NotThrowing
;
407 ContainsUnknown
= false;
408 ThrownExceptions
.clear();
411 void ExceptionAnalyzer::ExceptionInfo::reevaluateBehaviour() {
412 if (ThrownExceptions
.size() == 0)
414 Behaviour
= State::Unknown
;
416 Behaviour
= State::NotThrowing
;
418 Behaviour
= State::Throwing
;
421 ExceptionAnalyzer::ExceptionInfo
ExceptionAnalyzer::throwsException(
422 const FunctionDecl
*Func
, const ExceptionInfo::Throwables
&Caught
,
423 llvm::SmallSet
<const FunctionDecl
*, 32> &CallStack
) {
424 if (CallStack
.count(Func
))
425 return ExceptionInfo::createNonThrowing();
427 if (const Stmt
*Body
= Func
->getBody()) {
428 CallStack
.insert(Func
);
429 ExceptionInfo Result
= throwsException(Body
, Caught
, CallStack
);
431 // For a constructor, we also have to check the initializers.
432 if (const auto *Ctor
= dyn_cast
<CXXConstructorDecl
>(Func
)) {
433 for (const CXXCtorInitializer
*Init
: Ctor
->inits()) {
435 throwsException(Init
->getInit(), Caught
, CallStack
);
440 CallStack
.erase(Func
);
444 auto Result
= ExceptionInfo::createUnknown();
445 if (const auto *FPT
= Func
->getType()->getAs
<FunctionProtoType
>()) {
446 for (const QualType
&Ex
: FPT
->exceptions())
447 Result
.registerException(Ex
.getTypePtr());
452 /// Analyzes a single statement on it's throwing behaviour. This is in principle
453 /// possible except some 'Unknown' functions are called.
454 ExceptionAnalyzer::ExceptionInfo
ExceptionAnalyzer::throwsException(
455 const Stmt
*St
, const ExceptionInfo::Throwables
&Caught
,
456 llvm::SmallSet
<const FunctionDecl
*, 32> &CallStack
) {
457 auto Results
= ExceptionInfo::createNonThrowing();
461 if (const auto *Throw
= dyn_cast
<CXXThrowExpr
>(St
)) {
462 if (const auto *ThrownExpr
= Throw
->getSubExpr()) {
463 const auto *ThrownType
=
464 ThrownExpr
->getType()->getUnqualifiedDesugaredType();
465 if (ThrownType
->isReferenceType())
466 ThrownType
= ThrownType
->castAs
<ReferenceType
>()
468 ->getUnqualifiedDesugaredType();
469 Results
.registerException(
470 ThrownExpr
->getType()->getUnqualifiedDesugaredType());
472 // A rethrow of a caught exception happens which makes it possible
473 // to throw all exception that are caught in the 'catch' clause of
474 // the parent try-catch block.
475 Results
.registerExceptions(Caught
);
476 } else if (const auto *Try
= dyn_cast
<CXXTryStmt
>(St
)) {
477 ExceptionInfo Uncaught
=
478 throwsException(Try
->getTryBlock(), Caught
, CallStack
);
479 for (unsigned I
= 0; I
< Try
->getNumHandlers(); ++I
) {
480 const CXXCatchStmt
*Catch
= Try
->getHandler(I
);
482 // Everything is catched through 'catch(...)'.
483 if (!Catch
->getExceptionDecl()) {
484 ExceptionInfo Rethrown
= throwsException(
485 Catch
->getHandlerBlock(), Uncaught
.getExceptionTypes(), CallStack
);
486 Results
.merge(Rethrown
);
489 const auto *CaughtType
=
490 Catch
->getCaughtType()->getUnqualifiedDesugaredType();
491 if (CaughtType
->isReferenceType()) {
492 CaughtType
= CaughtType
->castAs
<ReferenceType
>()
494 ->getUnqualifiedDesugaredType();
497 // If the caught exception will catch multiple previously potential
498 // thrown types (because it's sensitive to inheritance) the throwing
499 // situation changes. First of all filter the exception types and
500 // analyze if the baseclass-exception is rethrown.
501 if (Uncaught
.filterByCatch(
502 CaughtType
, Catch
->getExceptionDecl()->getASTContext())) {
503 ExceptionInfo::Throwables CaughtExceptions
;
504 CaughtExceptions
.insert(CaughtType
);
505 ExceptionInfo Rethrown
= throwsException(Catch
->getHandlerBlock(),
506 CaughtExceptions
, CallStack
);
507 Results
.merge(Rethrown
);
511 Results
.merge(Uncaught
);
512 } else if (const auto *Call
= dyn_cast
<CallExpr
>(St
)) {
513 if (const FunctionDecl
*Func
= Call
->getDirectCallee()) {
514 ExceptionInfo Excs
= throwsException(Func
, Caught
, CallStack
);
517 } else if (const auto *Construct
= dyn_cast
<CXXConstructExpr
>(St
)) {
519 throwsException(Construct
->getConstructor(), Caught
, CallStack
);
521 } else if (const auto *DefaultInit
= dyn_cast
<CXXDefaultInitExpr
>(St
)) {
523 throwsException(DefaultInit
->getExpr(), Caught
, CallStack
);
525 } else if (const auto *Coro
= dyn_cast
<CoroutineBodyStmt
>(St
)) {
526 for (const Stmt
*Child
: Coro
->childrenExclBody()) {
527 if (Child
!= Coro
->getExceptionHandler()) {
528 ExceptionInfo Excs
= throwsException(Child
, Caught
, CallStack
);
532 ExceptionInfo Excs
= throwsException(Coro
->getBody(), Caught
, CallStack
);
533 Results
.merge(throwsException(Coro
->getExceptionHandler(),
534 Excs
.getExceptionTypes(), CallStack
));
535 for (const Type
*Throwable
: Excs
.getExceptionTypes()) {
536 if (const auto ThrowableRec
= Throwable
->getAsCXXRecordDecl()) {
537 ExceptionInfo DestructorExcs
=
538 throwsException(ThrowableRec
->getDestructor(), Caught
, CallStack
);
539 Results
.merge(DestructorExcs
);
543 for (const Stmt
*Child
: St
->children()) {
544 ExceptionInfo Excs
= throwsException(Child
, Caught
, CallStack
);
551 ExceptionAnalyzer::ExceptionInfo
552 ExceptionAnalyzer::analyzeImpl(const FunctionDecl
*Func
) {
553 ExceptionInfo ExceptionList
;
555 // Check if the function has already been analyzed and reuse that result.
556 const auto CacheEntry
= FunctionCache
.find(Func
);
557 if (CacheEntry
== FunctionCache
.end()) {
558 llvm::SmallSet
<const FunctionDecl
*, 32> CallStack
;
560 throwsException(Func
, ExceptionInfo::Throwables(), CallStack
);
562 // Cache the result of the analysis. This is done prior to filtering
563 // because it is best to keep as much information as possible.
564 // The results here might be relevant to different analysis passes
565 // with different needs as well.
566 FunctionCache
.try_emplace(Func
, ExceptionList
);
568 ExceptionList
= CacheEntry
->getSecond();
570 return ExceptionList
;
573 ExceptionAnalyzer::ExceptionInfo
574 ExceptionAnalyzer::analyzeImpl(const Stmt
*Stmt
) {
575 llvm::SmallSet
<const FunctionDecl
*, 32> CallStack
;
576 return throwsException(Stmt
, ExceptionInfo::Throwables(), CallStack
);
579 template <typename T
>
580 ExceptionAnalyzer::ExceptionInfo
581 ExceptionAnalyzer::analyzeDispatch(const T
*Node
) {
582 ExceptionInfo ExceptionList
= analyzeImpl(Node
);
584 if (ExceptionList
.getBehaviour() == State::NotThrowing
||
585 ExceptionList
.getBehaviour() == State::Unknown
)
586 return ExceptionList
;
588 // Remove all ignored exceptions from the list of exceptions that can be
590 ExceptionList
.filterIgnoredExceptions(IgnoredExceptions
, IgnoreBadAlloc
);
592 return ExceptionList
;
595 ExceptionAnalyzer::ExceptionInfo
596 ExceptionAnalyzer::analyze(const FunctionDecl
*Func
) {
597 return analyzeDispatch(Func
);
600 ExceptionAnalyzer::ExceptionInfo
ExceptionAnalyzer::analyze(const Stmt
*Stmt
) {
601 return analyzeDispatch(Stmt
);
604 } // namespace clang::tidy::utils