clang-tools 22.0.0git
ExceptionAnalyzer.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
9#include "ExceptionAnalyzer.h"
10
11namespace clang::tidy::utils {
12
14 const Type *ExceptionType, const ThrowInfo &ThrowInfo) {
15 assert(ExceptionType != nullptr && "Only valid types are accepted");
16 Behaviour = State::Throwing;
17 ThrownExceptions.insert({ExceptionType, ThrowInfo});
18}
19
21 const Throwables &Exceptions) {
22 if (Exceptions.empty())
23 return;
24 Behaviour = State::Throwing;
25 ThrownExceptions.insert_range(Exceptions);
26}
27
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_range(Other.ThrownExceptions);
43 return *this;
44}
45
46// FIXME: This could be ported to clang later.
47namespace {
48
49bool isUnambiguousPublicBaseClass(const Type *DerivedType,
50 const Type *BaseType) {
51 const auto *DerivedClass =
52 DerivedType->getCanonicalTypeUnqualified()->getAsCXXRecordDecl();
53 const auto *BaseClass =
54 BaseType->getCanonicalTypeUnqualified()->getAsCXXRecordDecl();
55 if (!DerivedClass || !BaseClass)
56 return false;
57
58 CXXBasePaths Paths;
59 Paths.setOrigin(DerivedClass);
60
61 bool IsPublicBaseClass = false;
62 DerivedClass->lookupInBases(
63 [&BaseClass, &IsPublicBaseClass](const CXXBaseSpecifier *BS,
64 CXXBasePath &) {
65 if (BS->getType()
66 ->getCanonicalTypeUnqualified()
67 ->getAsCXXRecordDecl() == BaseClass &&
68 BS->getAccessSpecifier() == AS_public) {
69 IsPublicBaseClass = true;
70 return true;
71 }
72
73 return false;
74 },
75 Paths);
76
77 return !Paths.isAmbiguous(BaseType->getCanonicalTypeUnqualified()) &&
78 IsPublicBaseClass;
79}
80
81inline bool isPointerOrPointerToMember(const Type *T) {
82 return T->isPointerType() || T->isMemberPointerType();
83}
84
85std::optional<QualType> getPointeeOrArrayElementQualType(QualType T) {
86 if (T->isAnyPointerType() || T->isMemberPointerType())
87 return T->getPointeeType();
88
89 if (T->isArrayType())
90 return T->getAsArrayTypeUnsafe()->getElementType();
91
92 return std::nullopt;
93}
94
95bool isBaseOf(const Type *DerivedType, const Type *BaseType) {
96 const auto *DerivedClass = DerivedType->getAsCXXRecordDecl();
97 const auto *BaseClass = BaseType->getAsCXXRecordDecl();
98 if (!DerivedClass || !BaseClass)
99 return false;
100
101 return !DerivedClass->forallBases(
102 [BaseClass](const CXXRecordDecl *Cur) { return Cur != BaseClass; });
103}
104
105// Check if T1 is more or Equally qualified than T2.
106bool moreOrEquallyQualified(QualType T1, QualType T2) {
107 return T1.getQualifiers().isStrictSupersetOf(T2.getQualifiers()) ||
108 T1.getQualifiers() == T2.getQualifiers();
109}
110
111bool isStandardPointerConvertible(QualType From, QualType To) {
112 assert((From->isPointerType() || From->isMemberPointerType()) &&
113 (To->isPointerType() || To->isMemberPointerType()) &&
114 "Pointer conversion should be performed on pointer types only.");
115
116 if (!moreOrEquallyQualified(To->getPointeeType(), From->getPointeeType()))
117 return false;
118
119 // (1)
120 // A null pointer constant can be converted to a pointer type ...
121 // The conversion of a null pointer constant to a pointer to cv-qualified type
122 // is a single conversion, and not the sequence of a pointer conversion
123 // followed by a qualification conversion. A null pointer constant of integral
124 // type can be converted to a prvalue of type std::nullptr_t
125 if (To->isPointerType() && From->isNullPtrType())
126 return true;
127
128 // (2)
129 // A prvalue of type “pointer to cv T”, where T is an object type, can be
130 // converted to a prvalue of type “pointer to cv void”.
131 if (To->isVoidPointerType() && From->isObjectPointerType())
132 return true;
133
134 // (3)
135 // A prvalue of type “pointer to cv D”, where D is a complete class type, can
136 // be converted to a prvalue of type “pointer to cv B”, where B is a base
137 // class of D. If B is an inaccessible or ambiguous base class of D, a program
138 // that necessitates this conversion is ill-formed.
139 if (const auto *RD = From->getPointeeCXXRecordDecl()) {
140 if (RD->isCompleteDefinition() &&
141 isBaseOf(From->getPointeeType().getTypePtr(),
142 To->getPointeeType().getTypePtr())) {
143 // If B is an inaccessible or ambiguous base class of D, a program
144 // that necessitates this conversion is ill-formed
145 return isUnambiguousPublicBaseClass(From->getPointeeType().getTypePtr(),
146 To->getPointeeType().getTypePtr());
147 }
148 }
149
150 return false;
151}
152
153bool isFunctionPointerConvertible(QualType From, QualType To) {
154 if (!From->isFunctionPointerType() && !From->isFunctionType() &&
155 !From->isMemberFunctionPointerType())
156 return false;
157
158 if (!To->isFunctionPointerType() && !To->isMemberFunctionPointerType())
159 return false;
160
161 if (To->isFunctionPointerType()) {
162 if (From->isFunctionPointerType())
163 return To->getPointeeType() == From->getPointeeType();
164
165 if (From->isFunctionType())
166 return To->getPointeeType() == From;
167
168 return false;
169 }
170
171 if (To->isMemberFunctionPointerType()) {
172 if (!From->isMemberFunctionPointerType())
173 return false;
174
175 const auto *FromMember = cast<MemberPointerType>(From);
176 const auto *ToMember = cast<MemberPointerType>(To);
177
178 // Note: converting Derived::* to Base::* is a different kind of conversion,
179 // called Pointer-to-member conversion.
180 return FromMember->getQualifier() == ToMember->getQualifier() &&
181 FromMember->getMostRecentCXXRecordDecl() ==
182 ToMember->getMostRecentCXXRecordDecl() &&
183 FromMember->getPointeeType() == ToMember->getPointeeType();
184 }
185
186 return false;
187}
188
189// Checks if From is qualification convertible to To based on the current
190// LangOpts. If From is any array, we perform the array to pointer conversion
191// first. The function only performs checks based on C++ rules, which can differ
192// from the C rules.
193//
194// The function should only be called in C++ mode.
195bool isQualificationConvertiblePointer(QualType From, QualType To,
196 LangOptions LangOpts) {
197
198 // [N4659 7.5 (1)]
199 // A cv-decomposition of a type T is a sequence of cv_i and P_i such that T is
200 // cv_0 P_0 cv_1 P_1 ... cv_n−1 P_n−1 cv_n U” for n > 0,
201 // where each cv_i is a set of cv-qualifiers, and each P_i is “pointer to”,
202 // “pointer to member of class C_i of type”, “array of N_i”, or
203 // “array of unknown bound of”.
204 //
205 // If P_i designates an array, the cv-qualifiers cv_i+1 on the element type
206 // are also taken as the cv-qualifiers cvi of the array.
207 //
208 // The n-tuple of cv-qualifiers after the first one in the longest
209 // cv-decomposition of T, that is, cv_1, cv_2, ... , cv_n, is called the
210 // cv-qualification signature of T.
211
212 // NOLINTNEXTLINE (readability-identifier-naming): Preserve original notation
213 auto IsValidP_i = [](QualType P) {
214 return P->isPointerType() || P->isMemberPointerType() ||
215 P->isConstantArrayType() || P->isIncompleteArrayType();
216 };
217
218 // NOLINTNEXTLINE (readability-identifier-naming): Preserve original notation
219 auto IsSameP_i = [](QualType P1, QualType P2) {
220 if (P1->isPointerType())
221 return P2->isPointerType();
222
223 if (P1->isMemberPointerType())
224 return P2->isMemberPointerType() &&
225 P1->getAs<MemberPointerType>()->getMostRecentCXXRecordDecl() ==
226 P2->getAs<MemberPointerType>()->getMostRecentCXXRecordDecl();
227
228 if (P1->isConstantArrayType())
229 return P2->isConstantArrayType() &&
230 cast<ConstantArrayType>(P1)->getSize() ==
231 cast<ConstantArrayType>(P2)->getSize();
232
233 if (P1->isIncompleteArrayType())
234 return P2->isIncompleteArrayType();
235
236 return false;
237 };
238
239 // (2)
240 // Two types From and To are similar if they have cv-decompositions with the
241 // same n such that corresponding P_i components are the same [(added by
242 // N4849 7.3.5) or one is “array of N_i” and the other is “array of unknown
243 // bound of”], and the types denoted by U are the same.
244 //
245 // (3)
246 // A prvalue expression of type From can be converted to type To if the
247 // following conditions are satisfied:
248 // - From and To are similar
249 // - For every i > 0, if const is in cv_i of From then const is in cv_i of
250 // To, and similarly for volatile.
251 // - [(derived from addition by N4849 7.3.5) If P_i of From is “array of
252 // unknown bound of”, P_i of To is “array of unknown bound of”.]
253 // - If the cv_i of From and cv_i of To are different, then const is in every
254 // cv_k of To for 0 < k < i.
255
256 int I = 0;
257 bool ConstUntilI = true;
258 auto SatisfiesCVRules = [&I, &ConstUntilI](const QualType &From,
259 const QualType &To) {
260 if (I > 1) {
261 if (From.getQualifiers() != To.getQualifiers() && !ConstUntilI)
262 return false;
263 }
264
265 if (I > 0) {
266 if (From.isConstQualified() && !To.isConstQualified())
267 return false;
268
269 if (From.isVolatileQualified() && !To.isVolatileQualified())
270 return false;
271
272 ConstUntilI = To.isConstQualified();
273 }
274
275 return true;
276 };
277
278 while (IsValidP_i(From) && IsValidP_i(To)) {
279 // Remove every sugar.
280 From = From.getCanonicalType();
281 To = To.getCanonicalType();
282
283 if (!SatisfiesCVRules(From, To))
284 return false;
285
286 if (!IsSameP_i(From, To)) {
287 if (LangOpts.CPlusPlus20) {
288 if (From->isConstantArrayType() && !To->isIncompleteArrayType())
289 return false;
290
291 if (From->isIncompleteArrayType() && !To->isIncompleteArrayType())
292 return false;
293
294 } else {
295 return false;
296 }
297 }
298
299 ++I;
300 std::optional<QualType> FromPointeeOrElem =
301 getPointeeOrArrayElementQualType(From);
302 std::optional<QualType> ToPointeeOrElem =
303 getPointeeOrArrayElementQualType(To);
304
305 assert(FromPointeeOrElem &&
306 "From pointer or array has no pointee or element!");
307 assert(ToPointeeOrElem && "To pointer or array has no pointee or element!");
308
309 From = *FromPointeeOrElem;
310 To = *ToPointeeOrElem;
311 }
312
313 // In this case the length (n) of From and To are not the same.
314 if (IsValidP_i(From) || IsValidP_i(To))
315 return false;
316
317 // We hit U.
318 if (!SatisfiesCVRules(From, To))
319 return false;
320
321 return From.getTypePtr() == To.getTypePtr();
322}
323} // namespace
324
325static bool canThrow(const FunctionDecl *Func) {
326 // consteval specifies that every call to the function must produce a
327 // compile-time constant, which cannot evaluate a throw expression without
328 // producing a compilation error.
329 if (Func->isConsteval())
330 return false;
331
332 const auto *FunProto = Func->getType()->getAs<FunctionProtoType>();
333 if (!FunProto)
334 return true;
335
336 switch (FunProto->canThrow()) {
337 case CT_Cannot:
338 return false;
339 case CT_Dependent: {
340 const Expr *NoexceptExpr = FunProto->getNoexceptExpr();
341 if (!NoexceptExpr)
342 return true; // no noexcept - can throw
343
344 if (NoexceptExpr->isValueDependent())
345 return true; // depend on template - some instance can throw
346
347 bool Result = false;
348 if (!NoexceptExpr->EvaluateAsBooleanCondition(Result, Func->getASTContext(),
349 /*InConstantContext=*/true))
350 return true; // complex X condition in noexcept(X), cannot validate,
351 // assume that may throw
352 return !Result; // noexcept(false) - can throw
353 }
354 default:
355 return true;
356 };
357}
358
361 const ASTContext &Context) {
362 llvm::SmallVector<const Type *, 8> TypesToDelete;
363 for (const auto &ThrownException : ThrownExceptions) {
364 const Type *ExceptionTy = ThrownException.getFirst();
365 CanQualType ExceptionCanTy = ExceptionTy->getCanonicalTypeUnqualified();
366 CanQualType HandlerCanTy = HandlerTy->getCanonicalTypeUnqualified();
367
368 // The handler is of type cv T or cv T& and E and T are the same type
369 // (ignoring the top-level cv-qualifiers) ...
370 if (ExceptionCanTy == HandlerCanTy) {
371 TypesToDelete.push_back(ExceptionTy);
372 }
373
374 // The handler is of type cv T or cv T& and T is an unambiguous public base
375 // class of E ...
376 else if (isUnambiguousPublicBaseClass(ExceptionCanTy->getTypePtr(),
377 HandlerCanTy->getTypePtr())) {
378 TypesToDelete.push_back(ExceptionTy);
379 }
380
381 if (HandlerCanTy->getTypeClass() == Type::RValueReference ||
382 (HandlerCanTy->getTypeClass() == Type::LValueReference &&
383 !HandlerCanTy->getTypePtr()->getPointeeType().isConstQualified()))
384 continue;
385 // The handler is of type cv T or const T& where T is a pointer or
386 // pointer-to-member type and E is a pointer or pointer-to-member type that
387 // can be converted to T by one or more of ...
388 if (isPointerOrPointerToMember(HandlerCanTy->getTypePtr()) &&
389 isPointerOrPointerToMember(ExceptionCanTy->getTypePtr())) {
390 // A standard pointer conversion not involving conversions to pointers to
391 // private or protected or ambiguous classes ...
392 if (isStandardPointerConvertible(ExceptionCanTy, HandlerCanTy)) {
393 TypesToDelete.push_back(ExceptionTy);
394 }
395 // A function pointer conversion ...
396 else if (isFunctionPointerConvertible(ExceptionCanTy, HandlerCanTy)) {
397 TypesToDelete.push_back(ExceptionTy);
398 }
399 // A a qualification conversion ...
400 else if (isQualificationConvertiblePointer(ExceptionCanTy, HandlerCanTy,
401 Context.getLangOpts())) {
402 TypesToDelete.push_back(ExceptionTy);
403 }
404 }
405
406 // The handler is of type cv T or const T& where T is a pointer or
407 // pointer-to-member type and E is std::nullptr_t.
408 else if (isPointerOrPointerToMember(HandlerCanTy->getTypePtr()) &&
409 ExceptionCanTy->isNullPtrType()) {
410 TypesToDelete.push_back(ExceptionTy);
411 }
412 }
413
414 Throwables DeletedExceptions;
415
416 for (const Type *TypeToDelete : TypesToDelete) {
417 const auto DeleteIt = ThrownExceptions.find(TypeToDelete);
418 if (DeleteIt != ThrownExceptions.end()) {
419 DeletedExceptions.insert(*DeleteIt);
420 ThrownExceptions.erase(DeleteIt);
421 }
422 }
423
424 reevaluateBehaviour();
425 return DeletedExceptions;
426}
427
430 const llvm::StringSet<> &IgnoredTypes, bool IgnoreBadAlloc) {
431 llvm::SmallVector<const Type *, 8> TypesToDelete;
432 // Note: Using a 'SmallSet' with 'llvm::remove_if()' is not possible.
433 // Therefore this slightly hacky implementation is required.
434 for (const auto &ThrownException : ThrownExceptions) {
435 const Type *T = ThrownException.getFirst();
436 if (const auto *TD = T->getAsTagDecl()) {
437 if (TD->getDeclName().isIdentifier()) {
438 if ((IgnoreBadAlloc &&
439 (TD->getName() == "bad_alloc" && TD->isInStdNamespace())) ||
440 (IgnoredTypes.contains(TD->getName())))
441 TypesToDelete.push_back(T);
442 }
443 }
444 }
445 for (const Type *T : TypesToDelete)
446 ThrownExceptions.erase(T);
447
448 reevaluateBehaviour();
449 return *this;
450}
451
453 Behaviour = State::NotThrowing;
454 ContainsUnknown = false;
455 ThrownExceptions.clear();
456}
457
458void ExceptionAnalyzer::ExceptionInfo::reevaluateBehaviour() {
459 if (ThrownExceptions.empty())
460 if (ContainsUnknown)
461 Behaviour = State::Unknown;
462 else
463 Behaviour = State::NotThrowing;
464 else
465 Behaviour = State::Throwing;
466}
467ExceptionAnalyzer::ExceptionInfo ExceptionAnalyzer::throwsException(
468 const FunctionDecl *Func, const ExceptionInfo::Throwables &Caught,
469 CallStack &CallStack, SourceLocation CallLoc) {
470 if (!Func || CallStack.contains(Func) ||
471 (!CallStack.empty() && !canThrow(Func)))
473
474 if (const Stmt *Body = Func->getBody()) {
475 CallStack.insert({Func, CallLoc});
476 ExceptionInfo Result = throwsException(Body, Caught, CallStack);
477
478 // For a constructor, we also have to check the initializers.
479 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Func)) {
480 for (const CXXCtorInitializer *Init : Ctor->inits()) {
481 ExceptionInfo Excs =
482 throwsException(Init->getInit(), Caught, CallStack);
483 Result.merge(Excs);
484 }
485 }
486
487 CallStack.erase(Func);
488 return Result;
489 }
490
491 auto Result = ExceptionInfo::createUnknown();
492 if (const auto *FPT = Func->getType()->getAs<FunctionProtoType>()) {
493 for (const QualType &Ex : FPT->exceptions()) {
494 CallStack.insert({Func, CallLoc});
495 Result.registerException(
496 Ex.getTypePtr(),
497 {Func->getExceptionSpecSourceRange().getBegin(), CallStack});
498 CallStack.erase(Func);
499 }
500 }
501 return Result;
502}
503
504/// Analyzes a single statement on it's throwing behaviour. This is in principle
505/// possible except some 'Unknown' functions are called.
506ExceptionAnalyzer::ExceptionInfo
507ExceptionAnalyzer::throwsException(const Stmt *St,
508 const ExceptionInfo::Throwables &Caught,
510 auto Results = ExceptionInfo::createNonThrowing();
511 if (!St)
512 return Results;
513
514 if (const auto *Throw = dyn_cast<CXXThrowExpr>(St)) {
515 if (const auto *ThrownExpr = Throw->getSubExpr()) {
516 const auto *ThrownType =
517 ThrownExpr->getType()->getUnqualifiedDesugaredType();
518 if (ThrownType->isReferenceType())
519 ThrownType = ThrownType->castAs<ReferenceType>()
520 ->getPointeeType()
521 ->getUnqualifiedDesugaredType();
522 Results.registerException(
523 ThrownExpr->getType()->getUnqualifiedDesugaredType(),
524 {Throw->getBeginLoc(), CallStack});
525 } else
526 // A rethrow of a caught exception happens which makes it possible
527 // to throw all exception that are caught in the 'catch' clause of
528 // the parent try-catch block.
529 Results.registerExceptions(Caught);
530 } else if (const auto *Try = dyn_cast<CXXTryStmt>(St)) {
531 ExceptionInfo Uncaught =
532 throwsException(Try->getTryBlock(), Caught, CallStack);
533 for (unsigned I = 0; I < Try->getNumHandlers(); ++I) {
534 const CXXCatchStmt *Catch = Try->getHandler(I);
535
536 // Everything is caught through 'catch(...)'.
537 if (!Catch->getExceptionDecl()) {
538 ExceptionInfo Rethrown = throwsException(
539 Catch->getHandlerBlock(), Uncaught.getExceptions(), CallStack);
540 Results.merge(Rethrown);
541 Uncaught.clear();
542 } else {
543 const auto *CaughtType =
544 Catch->getCaughtType()->getUnqualifiedDesugaredType();
545 if (CaughtType->isReferenceType()) {
546 CaughtType = CaughtType->castAs<ReferenceType>()
547 ->getPointeeType()
548 ->getUnqualifiedDesugaredType();
549 }
550
551 // If the caught exception will catch multiple previously potential
552 // thrown types (because it's sensitive to inheritance) the throwing
553 // situation changes. First of all filter the exception types and
554 // analyze if the baseclass-exception is rethrown.
555 const ExceptionInfo::Throwables FilteredExceptions =
556 Uncaught.filterByCatch(CaughtType,
557 Catch->getExceptionDecl()->getASTContext());
558 if (!FilteredExceptions.empty()) {
559 ExceptionInfo Rethrown = throwsException(
560 Catch->getHandlerBlock(), FilteredExceptions, CallStack);
561 Results.merge(Rethrown);
562 }
563 }
564 }
565 Results.merge(Uncaught);
566 } else if (const auto *Call = dyn_cast<CallExpr>(St)) {
567 if (const FunctionDecl *Func = Call->getDirectCallee()) {
568 ExceptionInfo Excs =
569 throwsException(Func, Caught, CallStack, Call->getBeginLoc());
570 Results.merge(Excs);
571 }
572 } else if (const auto *Construct = dyn_cast<CXXConstructExpr>(St)) {
573 ExceptionInfo Excs = throwsException(Construct->getConstructor(), Caught,
574 CallStack, Construct->getBeginLoc());
575 Results.merge(Excs);
576 } else if (const auto *DefaultInit = dyn_cast<CXXDefaultInitExpr>(St)) {
577 ExceptionInfo Excs =
578 throwsException(DefaultInit->getExpr(), Caught, CallStack);
579 Results.merge(Excs);
580 } else if (const auto *Coro = dyn_cast<CoroutineBodyStmt>(St)) {
581 for (const Stmt *Child : Coro->childrenExclBody()) {
582 if (Child != Coro->getExceptionHandler()) {
583 ExceptionInfo Excs = throwsException(Child, Caught, CallStack);
584 Results.merge(Excs);
585 }
586 }
587 ExceptionInfo Excs = throwsException(Coro->getBody(), Caught, CallStack);
588 Results.merge(throwsException(Coro->getExceptionHandler(),
589 Excs.getExceptions(), CallStack));
590 for (const auto &Exception : Excs.getExceptions()) {
591 const Type *ExcType = Exception.getFirst();
592 if (const CXXRecordDecl *ThrowableRec = ExcType->getAsCXXRecordDecl()) {
593 ExceptionInfo DestructorExcs = throwsException(
594 ThrowableRec->getDestructor(), Caught, CallStack, SourceLocation{});
595 Results.merge(DestructorExcs);
596 }
597 }
598 } else if (const auto *Lambda = dyn_cast<LambdaExpr>(St)) {
599 for (const Stmt *Init : Lambda->capture_inits()) {
600 ExceptionInfo Excs = throwsException(Init, Caught, CallStack);
601 Results.merge(Excs);
602 }
603 } else {
604 for (const Stmt *Child : St->children()) {
605 ExceptionInfo Excs = throwsException(Child, Caught, CallStack);
606 Results.merge(Excs);
607 }
608 }
609 return Results;
610}
611
612ExceptionAnalyzer::ExceptionInfo
613ExceptionAnalyzer::analyzeImpl(const FunctionDecl *Func) {
614 ExceptionInfo ExceptionList;
615
616 // Check if the function has already been analyzed and reuse that result.
617 const auto CacheEntry = FunctionCache.find(Func);
618 if (CacheEntry == FunctionCache.end()) {
620 ExceptionList = throwsException(Func, ExceptionInfo::Throwables(),
621 CallStack, Func->getLocation());
622
623 // Cache the result of the analysis. This is done prior to filtering
624 // because it is best to keep as much information as possible.
625 // The results here might be relevant to different analysis passes
626 // with different needs as well.
627 FunctionCache.try_emplace(Func, ExceptionList);
628 } else
629 ExceptionList = CacheEntry->getSecond();
630
631 return ExceptionList;
632}
633
634ExceptionAnalyzer::ExceptionInfo
635ExceptionAnalyzer::analyzeImpl(const Stmt *Stmt) {
637 return throwsException(Stmt, ExceptionInfo::Throwables(), CallStack);
638}
639
640template <typename T>
641ExceptionAnalyzer::ExceptionInfo
642ExceptionAnalyzer::analyzeDispatch(const T *Node) {
643 ExceptionInfo ExceptionList = analyzeImpl(Node);
644
645 if (ExceptionList.getBehaviour() == State::NotThrowing ||
646 ExceptionList.getBehaviour() == State::Unknown)
647 return ExceptionList;
648
649 // Remove all ignored exceptions from the list of exceptions that can be
650 // thrown.
651 ExceptionList.filterIgnoredExceptions(IgnoredExceptions, IgnoreBadAlloc);
652
653 return ExceptionList;
654}
655
656ExceptionAnalyzer::ExceptionInfo
657ExceptionAnalyzer::analyze(const FunctionDecl *Func) {
658 return analyzeDispatch(Func);
659}
660
662 return analyzeDispatch(Stmt);
663}
664
665} // namespace clang::tidy::utils
Bundle the gathered information about an entity like a function regarding it's exception behaviour.
void clear()
Clear the state to 'NonThrowing' to make the corresponding entity neutral.
llvm::SmallDenseMap< const Type *, ThrowInfo, 2 > Throwables
ExceptionInfo & filterIgnoredExceptions(const llvm::StringSet<> &IgnoredTypes, bool IgnoreBadAlloc)
Filter the set of thrown exception type against a set of ignored types that shall not be considered i...
Throwables filterByCatch(const Type *HandlerTy, const ASTContext &Context)
This method is useful in case 'catch' clauses are analyzed as it is possible to catch multiple except...
void registerExceptions(const Throwables &Exceptions)
Registers a SmallVector of exception types as recognized potential exceptions to be thrown.
ExceptionInfo & merge(const ExceptionInfo &Other)
Updates the local state according to the other state.
void registerException(const Type *ExceptionType, const ThrowInfo &ThrowInfo)
Register a single exception type as recognized potential exception to be thrown.
@ Throwing
The function can definitely throw given an AST.
@ Unknown
This can happen for extern functions without available definition.
@ NotThrowing
This function can not throw, given an AST.
llvm::MapVector< const FunctionDecl *, SourceLocation > CallStack
We use a MapVector to preserve the order of the functions in the call stack as well as have fast look...
ExceptionInfo analyze(const FunctionDecl *Func)
@ Type
An inlay hint that for a type annotation.
Definition Protocol.h:1672
static bool canThrow(const FunctionDecl *Func)
cppcoreguidelines::ProBoundsAvoidUncheckedContainerAccess P
Holds information about where an exception is thrown.