51#include "llvm/ADT/ArrayRef.h"
52#include "llvm/ADT/BitVector.h"
53#include "llvm/ADT/DenseMap.h"
54#include "llvm/ADT/MapVector.h"
55#include "llvm/ADT/PostOrderIterator.h"
56#include "llvm/ADT/STLFunctionalExtras.h"
57#include "llvm/ADT/SmallVector.h"
58#include "llvm/ADT/StringExtras.h"
59#include "llvm/ADT/StringRef.h"
60#include "llvm/Support/Debug.h"
61#include "llvm/Support/TimeProfiler.h"
76 SourceRange PreviousSilenceableCondVal;
79 UnreachableCodeHandler(Sema &s) : S(s) {}
82 SourceRange SilenceableCondVal, SourceRange R1,
83 SourceRange R2,
bool HasFallThroughAttr)
override {
87 if (HasFallThroughAttr &&
88 !S.getDiagnostics().isIgnored(diag::warn_unreachable_fallthrough_attr,
94 if (PreviousSilenceableCondVal.isValid() &&
96 PreviousSilenceableCondVal == SilenceableCondVal)
98 PreviousSilenceableCondVal = SilenceableCondVal;
100 unsigned diag = diag::warn_unreachable;
103 diag = diag::warn_unreachable_break;
106 diag = diag::warn_unreachable_return;
109 diag = diag::warn_unreachable_loop_increment;
115 S.Diag(L, diag) << R1 << R2;
118 if (
Open.isValid()) {
119 SourceLocation Close = SilenceableCondVal.
getEnd();
120 Close = S.getLocForEndOfToken(Close);
122 S.Diag(
Open, diag::note_unreachable_silence)
143 UnreachableCodeHandler UC(S);
153 LogicalErrorHandler(Sema &S) : S(S) {}
155 static bool HasMacroID(
const Expr *E) {
160 for (
const Stmt *SubStmt : E->
children())
161 if (
const Expr *SubExpr = dyn_cast_or_null<Expr>(SubStmt))
162 if (HasMacroID(SubExpr))
168 void logicAlwaysTrue(
const BinaryOperator *B,
bool isAlwaysTrue)
override {
172 unsigned DiagID = isAlwaysTrue
173 ? diag::warn_tautological_negation_or_compare
174 : diag::warn_tautological_negation_and_compare;
179 void compareAlwaysTrue(
const BinaryOperator *B,
180 bool isAlwaysTrueOrFalse)
override {
185 S.Diag(B->
getExprLoc(), diag::warn_tautological_overlap_comparison)
186 << DiagRange << isAlwaysTrueOrFalse;
189 void compareBitwiseEquality(
const BinaryOperator *B,
190 bool isAlwaysTrue)
override {
195 S.Diag(B->
getExprLoc(), diag::warn_comparison_bitwise_always)
196 << DiagRange << isAlwaysTrue;
199 void compareBitwiseOr(
const BinaryOperator *B)
override {
204 S.Diag(B->
getExprLoc(), diag::warn_comparison_bitwise_or) << DiagRange;
207 static bool hasActiveDiagnostics(DiagnosticsEngine &Diags,
208 SourceLocation Loc) {
209 return !Diags.
isIgnored(diag::warn_tautological_overlap_comparison, Loc) ||
210 !Diags.
isIgnored(diag::warn_comparison_bitwise_or, Loc) ||
211 !Diags.
isIgnored(diag::warn_tautological_negation_and_compare, Loc);
225 for (
const auto &B :
Block) {
239 if (isa_and_nonnull<TemplateSpecializationType>(NNS.getAsType()))
255 bool foundRecursion =
false;
260 WorkList.push_back(&cfg->
getEntry());
262 while (!WorkList.empty()) {
265 for (
auto I =
Block->succ_begin(), E =
Block->succ_end(); I != E; ++I) {
267 if (!Visited.insert(SuccBlock).second)
271 if (ExitID == SuccBlock->getBlockID())
276 foundRecursion =
true;
280 WorkList.push_back(SuccBlock);
284 return foundRecursion;
320 Stack.push_back(&ThrowBlock);
323 while (!Stack.empty()) {
324 CFGBlock &UnwindBlock = *Stack.pop_back_val();
326 for (
auto &Succ : UnwindBlock.
succs()) {
327 if (!Succ.isReachable() || Queued[Succ->getBlockID()])
334 dyn_cast_or_null<CXXCatchStmt>(Succ->getLabel())) {
335 QualType Caught = Catch->getCaughtType();
342 Stack.push_back(Succ);
343 Queued[Succ->getBlockID()] =
true;
357 if (!Reachable[B->getBlockID()])
360 std::optional<CFGStmt> S = E.getAs<
CFGStmt>();
363 if (
auto *Throw = dyn_cast<CXXThrowExpr>(S->getStmt()))
373 S.
Diag(OpLoc, diag::warn_throw_in_noexcept_func) << FD;
379 getAs<FunctionProtoType>())
404 if (FPT->isNothrow() || FD->
hasAttr<NoThrowAttr>())
413 if (
auto *FD = dyn_cast<FunctionDecl>(DRef->getDecl()))
414 return FD->isNoReturn();
433struct TransferFunctions :
public StmtVisitor<TransferFunctions> {
435 std::optional<bool> AllValuesAreNoReturn;
437 TransferFunctions(
const VarDecl *VD) : Var(VD) {}
439 void reset() { AllValuesAreNoReturn = std::nullopt; }
441 void VisitDeclStmt(DeclStmt *DS) {
442 for (
auto *DI : DS->
decls())
443 if (
auto *VD = dyn_cast<VarDecl>(DI))
444 if (VarDecl *Def = VD->getDefinition())
449 void VisitUnaryOperator(UnaryOperator *UO) {
453 if (DRef->getDecl() == Var)
454 AllValuesAreNoReturn =
false;
458 void VisitBinaryOperator(BinaryOperator *BO) {
461 if (DRef->getDecl() == Var)
465 void VisitCallExpr(CallExpr *CE) {
468 const Expr *Arg = *I;
471 if (
auto VD = dyn_cast<VarDecl>(DRef->getDecl()))
472 if (VD->getDefinition() == Var)
473 AllValuesAreNoReturn =
false;
499 using MapTy = llvm::DenseMap<const CFGBlock *, std::optional<bool>>;
500 using ValueTy = MapTy::value_type;
502 BlocksToCheck[&VarBlk] = std::nullopt;
503 const auto BlockSatisfiesCondition = [](ValueTy Item) {
504 return Item.getSecond().value_or(
false);
507 TransferFunctions TF(VD);
509 llvm::DenseSet<const CFGBlock *> Visited;
512 if (Visited.contains(B))
518 if (std::optional<CFGStmt> cs = ri->getAs<
CFGStmt>()) {
519 const Stmt *S = cs->getStmt();
521 TF.Visit(
const_cast<Stmt *
>(S));
522 if (TF.AllValuesAreNoReturn) {
523 if (!TF.AllValuesAreNoReturn.value())
525 BlocksToCheck[B] =
true;
532 if (llvm::all_of(BlocksToCheck, BlockSatisfiesCondition))
537 if (!BlocksToCheck[B]) {
539 BlocksToCheck.erase(B);
540 for (
const auto &PredBlk : B->preds())
541 if (!BlocksToCheck.contains(PredBlk))
542 BlocksToCheck[PredBlk] = std::nullopt;
585 for (
const auto *B : *cfg) {
586 if (!live[B->getBlockID()]) {
587 if (B->preds().empty()) {
588 const Stmt *Term = B->getTerminatorStmt();
589 if (isa_and_nonnull<CXXTryStmt>(Term))
601 bool HasLiveReturn =
false;
602 bool HasFakeEdge =
false;
603 bool HasPlainEdge =
false;
604 bool HasAbnormalEdge =
false;
622 HasAbnormalEdge =
true;
631 for ( ; ri != re ; ++ri)
639 HasAbnormalEdge =
true;
650 HasLiveReturn =
true;
664 HasLiveReturn =
true;
668 HasAbnormalEdge =
true;
672 HasAbnormalEdge =
true;
675 if (
auto *
Call = dyn_cast<CallExpr>(S)) {
676 const Expr *Callee =
Call->getCallee();
677 if (Callee->getType()->isPointerType())
679 dyn_cast<DeclRefExpr>(Callee->IgnoreParenImpCasts()))
680 if (
auto *VD = dyn_cast<VarDecl>(DeclRef->getDecl()))
682 HasAbnormalEdge =
true;
694 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
704struct CheckFallThroughDiagnostics {
705 unsigned diag_FallThrough_HasNoReturn = 0;
706 unsigned diag_FallThrough_ReturnsNonVoid = 0;
707 unsigned diag_NeverFallThroughOrReturn = 0;
709 SourceLocation FuncLoc;
711 static CheckFallThroughDiagnostics MakeForFunction(Sema &S,
713 CheckFallThroughDiagnostics D;
714 D.FuncLoc =
Func->getLocation();
715 D.diag_FallThrough_HasNoReturn = diag::warn_noreturn_has_return_expr;
716 D.diag_FallThrough_ReturnsNonVoid = diag::warn_falloff_nonvoid;
720 bool isVirtualMethod =
false;
721 if (
const CXXMethodDecl *
Method = dyn_cast<CXXMethodDecl>(
Func))
722 isVirtualMethod =
Method->isVirtual();
726 if (
const FunctionDecl *
Function = dyn_cast<FunctionDecl>(
Func)) {
730 D.diag_FallThrough_ReturnsNonVoid = diag::ext_main_no_return;
735 D.diag_NeverFallThroughOrReturn = diag::warn_suggest_noreturn_function;
737 D.FunKind = diag::FalloffFunctionKind::Function;
741 static CheckFallThroughDiagnostics MakeForCoroutine(
const Decl *
Func) {
742 CheckFallThroughDiagnostics D;
743 D.FuncLoc =
Func->getLocation();
744 D.diag_FallThrough_ReturnsNonVoid = diag::warn_falloff_nonvoid;
745 D.FunKind = diag::FalloffFunctionKind::Coroutine;
749 static CheckFallThroughDiagnostics MakeForBlock() {
750 CheckFallThroughDiagnostics D;
751 D.diag_FallThrough_HasNoReturn = diag::err_noreturn_has_return_expr;
752 D.diag_FallThrough_ReturnsNonVoid = diag::err_falloff_nonvoid;
753 D.FunKind = diag::FalloffFunctionKind::Block;
757 static CheckFallThroughDiagnostics MakeForLambda() {
758 CheckFallThroughDiagnostics D;
759 D.diag_FallThrough_HasNoReturn = diag::err_noreturn_has_return_expr;
760 D.diag_FallThrough_ReturnsNonVoid = diag::warn_falloff_nonvoid;
761 D.FunKind = diag::FalloffFunctionKind::Lambda;
765 bool checkDiagnostics(DiagnosticsEngine &D,
bool ReturnsVoid,
766 bool HasNoReturn)
const {
767 if (FunKind == diag::FalloffFunctionKind::Function) {
768 return (ReturnsVoid ||
769 D.
isIgnored(diag::warn_falloff_nonvoid, FuncLoc)) &&
771 D.
isIgnored(diag::warn_noreturn_has_return_expr, FuncLoc)) &&
773 D.
isIgnored(diag::warn_suggest_noreturn_block, FuncLoc));
775 if (FunKind == diag::FalloffFunctionKind::Coroutine) {
776 return (ReturnsVoid ||
777 D.
isIgnored(diag::warn_falloff_nonvoid, FuncLoc)) &&
781 return ReturnsVoid && !HasNoReturn;
793 const CheckFallThroughDiagnostics &CD,
796 bool ReturnsVoid =
false;
797 bool HasNoReturn =
false;
799 if (
const auto *FD = dyn_cast<FunctionDecl>(D)) {
800 if (
const auto *CBody = dyn_cast<CoroutineBodyStmt>(Body))
801 ReturnsVoid = CBody->getFallthroughHandler() !=
nullptr;
803 ReturnsVoid = FD->getReturnType()->isVoidType();
804 HasNoReturn = FD->isNoReturn() || FD->hasAttr<InferredNoReturnAttr>();
806 else if (
const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
807 ReturnsVoid = MD->getReturnType()->isVoidType();
808 HasNoReturn = MD->hasAttr<NoReturnAttr>();
813 if (FT->getReturnType()->isVoidType())
815 if (FT->getNoReturnAttr())
823 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
839 if (CD.diag_FallThrough_HasNoReturn)
840 S.
Diag(RBrace, CD.diag_FallThrough_HasNoReturn) << CD.FunKind;
841 }
else if (!ReturnsVoid && CD.diag_FallThrough_ReturnsNonVoid) {
845 if (
const auto *CS = dyn_cast<CompoundStmt>(Body);
846 CS && !CS->body_empty()) {
847 const Stmt *LastStmt = CS->body_back();
849 if (
const auto *EWC = dyn_cast<ExprWithCleanups>(LastStmt)) {
850 LastStmt = EWC->getSubExpr();
852 if (
const auto *CE = dyn_cast<CallExpr>(LastStmt)) {
854 Callee && Callee->hasAttr<InferredNoReturnAttr>()) {
865 S.
Diag(RBrace, CD.diag_FallThrough_ReturnsNonVoid)
866 << CD.FunKind << NotInAllControlPaths;
870 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
871 if (
const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
872 S.
Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 0 << FD;
873 }
else if (
const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
874 S.
Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 1 << MD;
876 S.
Diag(LBrace, CD.diag_NeverFallThroughOrReturn);
895 const DeclRefExpr *Needle;
898 typedef ConstEvaluatedExprVisitor<ContainsReference> Inherited;
900 ContainsReference(ASTContext &Context,
const DeclRefExpr *Needle)
901 : Inherited(Context), FoundReference(
false), Needle(Needle) {}
903 void VisitExpr(
const Expr *E) {
908 Inherited::VisitExpr(E);
911 void VisitDeclRefExpr(
const DeclRefExpr *E) {
913 FoundReference =
true;
918 bool doesContainReference()
const {
return FoundReference; }
926 S.
Diag(VD->
getLocation(), diag::note_block_var_fixit_add_initialization)
947 S.
Diag(Loc, diag::note_var_fixit_add_initialization) << VD->
getDeclName()
955 const Stmt *Else,
bool CondVal,
979 bool IsCapturedByBlock) {
980 bool Diagnosed =
false;
1012 const Stmt *Term = I->Terminator;
1022 int RemoveDiagKind = -1;
1023 const char *FixitStr =
1024 S.
getLangOpts().CPlusPlus ? (I->Output ?
"true" :
"false")
1025 : (I->Output ?
"1" :
"0");
1028 switch (Term ? Term->
getStmtClass() : Stmt::DeclStmtClass) {
1035 case Stmt::IfStmtClass: {
1042 I->Output, Fixit1, Fixit2);
1045 case Stmt::ConditionalOperatorClass: {
1052 I->Output, Fixit1, Fixit2);
1055 case Stmt::BinaryOperatorClass: {
1063 if ((BO->
getOpcode() == BO_LAnd && I->Output) ||
1064 (BO->
getOpcode() == BO_LOr && !I->Output))
1075 case Stmt::WhileStmtClass:
1082 case Stmt::ForStmtClass:
1092 case Stmt::CXXForRangeStmtClass:
1093 if (I->Output == 1) {
1105 case Stmt::DoStmtClass:
1108 Range =
cast<DoStmt>(Term)->getCond()->getSourceRange();
1114 case Stmt::CaseStmtClass:
1119 case Stmt::DefaultStmtClass:
1126 S.
Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
1127 << VD->
getDeclName() << IsCapturedByBlock << DiagKind
1128 << Str << I->Output << Range;
1131 if (RemoveDiagKind != -1)
1133 << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
1167 bool alwaysReportSelfInit =
false) {
1181 if (!alwaysReportSelfInit && DRE ==
Initializer->IgnoreParenImpCasts())
1184 ContainsReference CR(S.
Context, DRE);
1186 if (CR.doesContainReference()) {
1187 S.
Diag(DRE->getBeginLoc(), diag::warn_uninit_self_reference_in_init)
1198 diag::warn_uninit_byref_blockvar_captured_by_block)
1218 FallthroughMapper(Sema &S) : FoundSwitchStatements(
false), S(S) {
1219 ShouldWalkTypesOfTypeLocs =
false;
1222 bool foundSwitchStatements()
const {
return FoundSwitchStatements; }
1224 void markFallthroughVisited(
const AttributedStmt *Stmt) {
1225 bool Found = FallthroughStmts.erase(Stmt);
1230 typedef llvm::SmallPtrSet<const AttributedStmt *, 8> AttrStmts;
1232 const AttrStmts &getFallthroughStmts()
const {
return FallthroughStmts; }
1234 void fillReachableBlocks(CFG *Cfg) {
1235 assert(ReachableBlocks.empty() &&
"ReachableBlocks already filled");
1236 std::deque<const CFGBlock *> BlockQueue;
1238 ReachableBlocks.insert(&Cfg->
getEntry());
1239 BlockQueue.push_back(&Cfg->
getEntry());
1244 for (
const auto *B : *Cfg) {
1245 const Stmt *L = B->getLabel();
1246 if (isa_and_nonnull<SwitchCase>(L) && ReachableBlocks.insert(B).second)
1247 BlockQueue.push_back(B);
1250 while (!BlockQueue.empty()) {
1251 const CFGBlock *P = BlockQueue.front();
1252 BlockQueue.pop_front();
1257 for (
const CFGBlock::AdjacentBlock &Succ : P->
succs()) {
1258 const CFGBlock *B = Succ.getReachableBlock();
1259 if (B && ReachableBlocks.insert(B).second)
1260 BlockQueue.push_back(B);
1261 if (!FollowAlternate)
1263 const CFGBlock *Alt = Succ.getPossiblyUnreachableBlock();
1264 if (Alt && ReachableBlocks.insert(Alt).second)
1265 BlockQueue.push_back(Alt);
1270 bool checkFallThroughIntoBlock(
const CFGBlock &B,
int &AnnotatedCnt,
1271 bool IsTemplateInstantiation) {
1272 assert(!ReachableBlocks.empty() &&
"ReachableBlocks empty");
1274 int UnannotatedCnt = 0;
1278 while (!BlockQueue.empty()) {
1279 const CFGBlock *P = BlockQueue.
front();
1280 BlockQueue.pop_front();
1285 if (isa_and_nonnull<SwitchStmt>(Term))
1288 const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->
getLabel());
1293 const LabelStmt *L = dyn_cast_or_null<LabelStmt>(P->
getLabel());
1298 if (!ReachableBlocks.count(P)) {
1299 for (
const CFGElement &Elem : llvm::reverse(*P)) {
1300 if (std::optional<CFGStmt> CS = Elem.getAs<CFGStmt>()) {
1301 if (
const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
1305 if (!IsTemplateInstantiation)
1306 S.Diag(AS->getBeginLoc(),
1307 diag::warn_unreachable_fallthrough_attr);
1308 markFallthroughVisited(AS);
1327 if (
const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
1328 markFallthroughVisited(AS);
1336 std::back_inserter(BlockQueue));
1342 return !!UnannotatedCnt;
1345 bool VisitAttributedStmt(AttributedStmt *S)
override {
1346 if (asFallThroughAttr(S))
1347 FallthroughStmts.insert(S);
1351 bool VisitSwitchStmt(SwitchStmt *S)
override {
1352 FoundSwitchStatements =
true;
1358 bool TraverseDecl(Decl *D)
override {
return true; }
1361 bool TraverseLambdaExpr(
LambdaExpr *LE)
override {
1363 for (
const auto C : zip(
LE->captures(),
LE->capture_inits()))
1364 TraverseLambdaCapture(LE, &std::get<0>(
C), std::get<1>(
C));
1369 static const Stmt *stripAttributedStmt(
const Stmt *S) {
1370 if (
const auto *AS = dyn_cast_or_null<AttributedStmt>(S)) {
1372 return AS->getSubStmt();
1377 static const AttributedStmt *asFallThroughAttr(
const Stmt *S) {
1378 if (
const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
1385 static const Stmt *
getLastStmt(
const CFGBlock &B) {
1388 for (
const CFGElement &Elem : llvm::reverse(B))
1389 if (std::optional<CFGStmt> CS = Elem.getAs<CFGStmt>())
1390 return CS->getStmt();
1394 if (
const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.
getLabel()))
1401 bool FoundSwitchStatements;
1402 AttrStmts FallthroughStmts;
1404 llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks;
1411 tok::l_square, tok::l_square,
1413 tok::r_square, tok::r_square
1419 tok::r_square, tok::r_square
1424 StringRef MacroName;
1425 if (PreferClangAttr)
1427 if (MacroName.empty())
1429 if (MacroName.empty() && !PreferClangAttr)
1431 if (MacroName.empty()) {
1432 if (!PreferClangAttr)
1433 MacroName =
"[[fallthrough]]";
1435 MacroName =
"[[clang::fallthrough]]";
1437 MacroName =
"__attribute__((fallthrough))";
1444 FallthroughMapper FM(S);
1445 FM.TraverseStmt(AC.
getBody());
1447 if (!FM.foundSwitchStatements())
1450 if (PerFunction && FM.getFallthroughStmts().empty())
1458 FM.fillReachableBlocks(Cfg);
1460 for (
const CFGBlock *B : llvm::reverse(*Cfg)) {
1463 if (!isa_and_nonnull<SwitchCase>(Label))
1468 bool IsTemplateInstantiation =
false;
1470 IsTemplateInstantiation = Function->isTemplateInstantiation();
1471 if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt,
1472 IsTemplateInstantiation))
1476 PerFunction ? diag::warn_unannotated_fallthrough_per_function
1477 : diag::warn_unannotated_fallthrough);
1479 if (!AnnotatedCnt) {
1490 if (!(B->
empty() && isa_and_nonnull<BreakStmt>(Term))) {
1494 TextToInsert +=
"; ";
1495 S.
Diag(L, diag::note_insert_fallthrough_fixit)
1496 << AnnotationSpelling
1499 S.
Diag(L, diag::note_insert_break_fixit)
1504 for (
const auto *F : FM.getFallthroughStmts())
1505 S.
Diag(F->getBeginLoc(), diag::err_fallthrough_attr_invalid_placement);
1514 case Stmt::ForStmtClass:
1515 case Stmt::WhileStmtClass:
1516 case Stmt::CXXForRangeStmtClass:
1517 case Stmt::ObjCForCollectionStmtClass:
1519 case Stmt::DoStmtClass: {
1523 return Result.Val.getInt().getBoolValue();
1540 typedef std::pair<const Stmt *, WeakObjectUseMap::const_iterator>
1549 for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
1551 const WeakUseVector &Uses = I->second;
1554 WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1555 for ( ; UI != UE; ++UI) {
1568 if (UI == Uses.begin()) {
1569 WeakUseVector::const_iterator UI2 = UI;
1570 for (++UI2; UI2 != UE; ++UI2)
1571 if (UI2->isUnsafe())
1575 if (!
isInLoop(Ctx, PM, UI->getUseExpr()))
1578 const WeakObjectProfileTy &Profile = I->first;
1579 if (!Profile.isExactProfile())
1584 Base = Profile.getProperty();
1585 assert(
Base &&
"A profile always has a base or property.");
1587 if (
const VarDecl *BaseVar = dyn_cast<VarDecl>(
Base))
1593 UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
1596 if (UsesByStmt.empty())
1601 llvm::sort(UsesByStmt,
1602 [&SM](
const StmtUsesPair &LHS,
const StmtUsesPair &RHS) {
1604 RHS.first->getBeginLoc());
1620 FunctionKind =
Block;
1622 FunctionKind = Lambda;
1624 FunctionKind = Method;
1626 FunctionKind = Function;
1629 for (
const auto &P : UsesByStmt) {
1630 const Stmt *FirstRead = P.first;
1631 const WeakObjectProfileTy &Key = P.second->first;
1632 const WeakUseVector &Uses = P.second->second;
1640 if (Key.isExactProfile())
1641 DiagKind = diag::warn_arc_repeated_use_of_weak;
1643 DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
1655 const NamedDecl *KeyProp = Key.getProperty();
1657 ObjectKind = Variable;
1659 ObjectKind = Property;
1661 ObjectKind = ImplicitProperty;
1665 llvm_unreachable(
"Unexpected weak object kind!");
1670 if (Prop->hasAttr<IBOutletAttr>())
1675 <<
int(ObjectKind) << KeyProp <<
int(FunctionKind)
1679 for (
const auto &Use : Uses) {
1680 if (Use.getUseExpr() == FirstRead)
1682 S.
Diag(Use.getUseExpr()->getBeginLoc(),
1683 diag::note_arc_weak_also_accessed_here)
1684 << Use.getUseExpr()->getSourceRange();
1692typedef std::pair<PartialDiagnosticAt, OptionalNotes>
DelayedDiag;
1693typedef std::list<DelayedDiag>
DiagList;
1695struct SortDiagBySourceLocation {
1697 SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
1699 bool operator()(
const DelayedDiag &left,
const DelayedDiag &right) {
1702 return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
1711 typedef SmallVector<UninitUse, 2> UsesVec;
1712 typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType;
1716 typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap;
1720 UninitValsDiagReporter(Sema &S) : S(S) {}
1723 MappedType &getUses(
const VarDecl *vd) {
1724 MappedType &
V = uses[vd];
1725 if (!
V.getPointer())
1726 V.setPointer(
new UsesVec());
1730 void handleUseOfUninitVariable(
const VarDecl *vd,
1731 const UninitUse &use)
override {
1732 getUses(vd).getPointer()->push_back(use);
1735 void handleSelfInit(
const VarDecl *vd)
override { getUses(vd).setInt(
true); }
1738 for (
const auto &P : uses) {
1739 const VarDecl *vd = P.first;
1740 const MappedType &
V = P.second;
1742 UsesVec *vec =
V.getPointer();
1743 bool hasSelfInit =
V.getInt();
1745 diagnoseUnitializedVar(vd, hasSelfInit, vec);
1755 static bool hasAlwaysUninitializedUse(
const UsesVec* vec) {
1756 return llvm::any_of(*vec, [](
const UninitUse &U) {
1766 void diagnoseUnitializedVar(
const VarDecl *vd,
bool hasSelfInit,
1771 if (hasSelfInit && hasAlwaysUninitializedUse(vec)) {
1782 llvm::sort(*vec, [](
const UninitUse &a,
const UninitUse &b) {
1793 for (
const auto &U : *vec) {
1802 UninitUse Use = hasSelfInit ? UninitUse(U.
getUser(),
false) : U;
1811class CalledOnceInterProceduralData {
1814 void addDelayedWarning(
const BlockDecl *
Block,
1816 DelayedBlockWarnings[
Block].emplace_back(std::move(
Warning));
1819 void flushWarnings(
const BlockDecl *
Block, Sema &S) {
1821 S.
Diag(Delayed.first, Delayed.second);
1823 discardWarnings(
Block);
1826 void discardWarnings(
const BlockDecl *
Block) {
1827 DelayedBlockWarnings.erase(
Block);
1831 using DelayedDiagnostics = SmallVector<PartialDiagnosticAt, 2>;
1832 llvm::DenseMap<const BlockDecl *, DelayedDiagnostics> DelayedBlockWarnings;
1837 CalledOnceCheckReporter(Sema &S, CalledOnceInterProceduralData &Data)
1838 : S(S), Data(Data) {}
1839 void handleDoubleCall(
const ParmVarDecl *
Parameter,
const Expr *
Call,
1840 const Expr *PrevCall,
bool IsCompletionHandler,
1841 bool Poised)
override {
1842 auto DiagToReport = IsCompletionHandler
1843 ? diag::warn_completion_handler_called_twice
1844 : diag::warn_called_once_gets_called_twice;
1846 S.Diag(PrevCall->
getBeginLoc(), diag::note_called_once_gets_called_twice)
1850 void handleNeverCalled(
const ParmVarDecl *
Parameter,
1851 bool IsCompletionHandler)
override {
1852 auto DiagToReport = IsCompletionHandler
1853 ? diag::warn_completion_handler_never_called
1854 : diag::warn_called_once_never_called;
1855 S.Diag(
Parameter->getBeginLoc(), DiagToReport)
1861 bool IsCalledDirectly,
1862 bool IsCompletionHandler)
override {
1863 auto DiagToReport = IsCompletionHandler
1864 ? diag::warn_completion_handler_never_called_when
1865 : diag::warn_called_once_never_called_when;
1869 << (
unsigned)Reason);
1879 void handleCapturedNeverCalled(
const ParmVarDecl *
Parameter,
1881 bool IsCompletionHandler)
override {
1882 auto DiagToReport = IsCompletionHandler
1883 ? diag::warn_completion_handler_never_called
1884 : diag::warn_called_once_never_called;
1890 handleBlockThatIsGuaranteedToBeCalledOnce(
const BlockDecl *
Block)
override {
1891 Data.flushWarnings(
Block, S);
1894 void handleBlockWithNoGuarantees(
const BlockDecl *
Block)
override {
1895 Data.discardWarnings(
Block);
1900 CalledOnceInterProceduralData &Data;
1903constexpr unsigned CalledOnceWarnings[] = {
1904 diag::warn_called_once_never_called,
1905 diag::warn_called_once_never_called_when,
1906 diag::warn_called_once_gets_called_twice};
1908constexpr unsigned CompletionHandlerWarnings[]{
1909 diag::warn_completion_handler_never_called,
1910 diag::warn_completion_handler_never_called_when,
1911 diag::warn_completion_handler_called_twice};
1916 return llvm::any_of(DiagIDs, [&Diags, At](
unsigned DiagID) {
1923 return shouldAnalyzeCalledOnceImpl(CompletionHandlerWarnings, Diags, At);
1928 return shouldAnalyzeCalledOnceImpl(CalledOnceWarnings, Diags, At) ||
1929 shouldAnalyzeCalledOnceConventions(Diags, At);
1939class ThreadSafetyReporter :
public clang::threadSafety::ThreadSafetyHandler {
1942 SourceLocation FunLocation, FunEndLocation;
1944 const FunctionDecl *CurrentFunction;
1948 if (Verbose && CurrentFunction) {
1950 S.PDiag(diag::note_thread_warning_in_fun)
1951 << CurrentFunction);
1959 if (Verbose && CurrentFunction) {
1961 S.PDiag(diag::note_thread_warning_in_fun)
1962 << CurrentFunction);
1963 ONS.push_back(std::move(FNote));
1971 ONS.push_back(Note1);
1972 ONS.push_back(Note2);
1973 if (Verbose && CurrentFunction) {
1975 S.PDiag(diag::note_thread_warning_in_fun)
1976 << CurrentFunction);
1977 ONS.push_back(std::move(FNote));
1982 OptionalNotes makeLockedHereNote(SourceLocation LocLocked, StringRef Kind) {
1985 LocLocked, S.PDiag(diag::note_locked_here) << Kind))
1989 OptionalNotes makeUnlockedHereNote(SourceLocation LocUnlocked,
1993 LocUnlocked, S.PDiag(diag::note_unlocked_here) << Kind))
1997 OptionalNotes makeManagedMismatchNoteForParam(SourceLocation DeclLoc) {
2001 S.PDiag(diag::note_managed_mismatch_here_for_param)))
2006 ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
2007 : S(S), FunLocation(FL), FunEndLocation(FEL),
2010 void setVerbose(
bool b) { Verbose = b; }
2017 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
2018 for (
const auto &
Diag : Warnings) {
2019 S.Diag(
Diag.first.first,
Diag.first.second);
2020 for (
const auto &
Note :
Diag.second)
2025 void handleUnmatchedUnderlyingMutexes(SourceLocation Loc, SourceLocation DLoc,
2026 Name scopeName, StringRef Kind,
2027 Name expected, Name actual)
override {
2029 S.PDiag(diag::warn_unmatched_underlying_mutexes)
2030 << Kind << scopeName << expected << actual);
2031 Warnings.emplace_back(std::move(
Warning),
2032 makeManagedMismatchNoteForParam(DLoc));
2035 void handleExpectMoreUnderlyingMutexes(SourceLocation Loc,
2036 SourceLocation DLoc, Name scopeName,
2038 Name expected)
override {
2040 Loc, S.PDiag(diag::warn_expect_more_underlying_mutexes)
2041 << Kind << scopeName << expected);
2042 Warnings.emplace_back(std::move(
Warning),
2043 makeManagedMismatchNoteForParam(DLoc));
2046 void handleExpectFewerUnderlyingMutexes(SourceLocation Loc,
2047 SourceLocation DLoc, Name scopeName,
2049 Name actual)
override {
2051 Loc, S.PDiag(diag::warn_expect_fewer_underlying_mutexes)
2052 << Kind << scopeName << actual);
2053 Warnings.emplace_back(std::move(
Warning),
2054 makeManagedMismatchNoteForParam(DLoc));
2057 void handleInvalidLockExp(SourceLocation Loc)
override {
2060 Warnings.emplace_back(std::move(
Warning), getNotes());
2063 void handleUnmatchedUnlock(StringRef Kind, Name LockName, SourceLocation Loc,
2064 SourceLocation LocPreviousUnlock)
override {
2068 << Kind << LockName);
2069 Warnings.emplace_back(std::move(
Warning),
2070 makeUnlockedHereNote(LocPreviousUnlock, Kind));
2073 void handleIncorrectUnlockKind(StringRef Kind, Name LockName,
2075 SourceLocation LocLocked,
2076 SourceLocation LocUnlock)
override {
2078 LocUnlock = FunLocation;
2080 LocUnlock, S.PDiag(diag::warn_unlock_kind_mismatch)
2081 << Kind << LockName << Received << Expected);
2082 Warnings.emplace_back(std::move(
Warning),
2083 makeLockedHereNote(LocLocked, Kind));
2086 void handleDoubleLock(StringRef Kind, Name LockName, SourceLocation LocLocked,
2087 SourceLocation LocDoubleLock)
override {
2089 LocDoubleLock = FunLocation;
2091 << Kind << LockName);
2092 Warnings.emplace_back(std::move(
Warning),
2093 makeLockedHereNote(LocLocked, Kind));
2096 void handleMutexHeldEndOfScope(StringRef Kind, Name LockName,
2097 SourceLocation LocLocked,
2098 SourceLocation LocEndOfScope,
2100 bool ReentrancyMismatch)
override {
2101 unsigned DiagID = 0;
2104 DiagID = diag::warn_lock_some_predecessors;
2107 DiagID = diag::warn_expecting_lock_held_on_loop;
2110 DiagID = diag::warn_no_unlock;
2113 DiagID = diag::warn_expecting_locked;
2117 LocEndOfScope = FunEndLocation;
2121 << ReentrancyMismatch);
2122 Warnings.emplace_back(std::move(
Warning),
2123 makeLockedHereNote(LocLocked, Kind));
2126 void handleExclusiveAndShared(StringRef Kind, Name LockName,
2127 SourceLocation Loc1,
2128 SourceLocation Loc2)
override {
2130 S.PDiag(diag::warn_lock_exclusive_and_shared)
2131 << Kind << LockName);
2133 << Kind << LockName);
2134 Warnings.emplace_back(std::move(
Warning), getNotes(
Note));
2138 AccessKind AK, SourceLocation Loc)
override {
2139 unsigned DiagID = 0;
2146 DiagID = diag::warn_variable_requires_any_lock;
2153 DiagID = diag::warn_var_deref_requires_any_lock;
2156 llvm_unreachable(
"Only works for variables");
2161 Warnings.emplace_back(std::move(
Warning), getNotes());
2164 void handleGuardedByAnyReadNotHeld(
const NamedDecl *D,
2166 ArrayRef<StringRef> LockNames,
2167 SourceLocation Loc)
override {
2185 llvm_unreachable(
"POK_FunctionCall not applicable here");
2188 llvm::raw_string_ostream
OS(Quoted);
2189 llvm::ListSeparator LS;
2190 for (StringRef Name : LockNames)
2191 OS << LS <<
"'" << Name <<
"'";
2193 << D << IsDeref << Quoted);
2194 Warnings.emplace_back(std::move(
Warning), getNotes());
2197 void handleMutexNotHeld(StringRef Kind,
const NamedDecl *D,
2200 Name *PossibleMatch)
override {
2201 unsigned DiagID = 0;
2202 if (PossibleMatch) {
2205 DiagID = diag::warn_variable_requires_lock_precise;
2208 DiagID = diag::warn_var_deref_requires_lock_precise;
2211 DiagID = diag::warn_fun_requires_lock_precise;
2214 DiagID = diag::warn_guarded_pass_by_reference;
2217 DiagID = diag::warn_pt_guarded_pass_by_reference;
2220 DiagID = diag::warn_guarded_return_by_reference;
2223 DiagID = diag::warn_pt_guarded_return_by_reference;
2226 DiagID = diag::warn_guarded_pass_pointer;
2229 DiagID = diag::warn_pt_guarded_pass_pointer;
2232 DiagID = diag::warn_guarded_return_pointer;
2235 DiagID = diag::warn_pt_guarded_return_pointer;
2245 S.PDiag(diag::note_guarded_by_declared_here)
2247 Warnings.emplace_back(std::move(
Warning), getNotes(
Note, VNote));
2249 Warnings.emplace_back(std::move(
Warning), getNotes(
Note));
2253 DiagID = diag::warn_variable_requires_lock;
2256 DiagID = diag::warn_var_deref_requires_lock;
2259 DiagID = diag::warn_fun_requires_lock;
2262 DiagID = diag::warn_guarded_pass_by_reference;
2265 DiagID = diag::warn_pt_guarded_pass_by_reference;
2268 DiagID = diag::warn_guarded_return_by_reference;
2271 DiagID = diag::warn_pt_guarded_return_by_reference;
2274 DiagID = diag::warn_guarded_pass_pointer;
2277 DiagID = diag::warn_pt_guarded_pass_pointer;
2280 DiagID = diag::warn_guarded_return_pointer;
2283 DiagID = diag::warn_pt_guarded_return_pointer;
2291 S.PDiag(diag::note_guarded_by_declared_here));
2292 Warnings.emplace_back(std::move(
Warning), getNotes(
Note));
2294 Warnings.emplace_back(std::move(
Warning), getNotes());
2298 void handleNegativeNotHeld(StringRef Kind, Name LockName, Name Neg,
2299 SourceLocation Loc)
override {
2301 S.PDiag(diag::warn_acquire_requires_negative_cap)
2302 << Kind << LockName << Neg);
2303 Warnings.emplace_back(std::move(
Warning), getNotes());
2306 void handleNegativeNotHeld(
const NamedDecl *D, Name LockName,
2307 SourceLocation Loc)
override {
2309 Loc, S.PDiag(diag::warn_fun_requires_negative_cap) << D << LockName);
2310 Warnings.emplace_back(std::move(
Warning), getNotes());
2313 void handleFunExcludesLock(StringRef Kind, Name FunName, Name LockName,
2314 SourceLocation Loc)
override {
2316 << Kind << FunName << LockName);
2317 Warnings.emplace_back(std::move(
Warning), getNotes());
2320 void handleLockAcquiredBefore(StringRef Kind, Name L1Name, Name L2Name,
2321 SourceLocation Loc)
override {
2323 S.PDiag(diag::warn_acquired_before) << Kind << L1Name << L2Name);
2324 Warnings.emplace_back(std::move(
Warning), getNotes());
2327 void handleBeforeAfterCycle(Name L1Name, SourceLocation Loc)
override {
2329 S.PDiag(diag::warn_acquired_before_after_cycle) << L1Name);
2330 Warnings.emplace_back(std::move(
Warning), getNotes());
2333 void enterFunction(
const FunctionDecl* FD)
override {
2334 CurrentFunction = FD;
2337 void leaveFunction(
const FunctionDecl* FD)
override {
2338 CurrentFunction =
nullptr;
2359 ConsumedWarningsHandler(Sema &S) : S(S) {}
2362 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
2363 for (
const auto &
Diag : Warnings) {
2364 S.Diag(
Diag.first.first,
Diag.first.second);
2365 for (
const auto &
Note :
Diag.second)
2370 void warnLoopStateMismatch(SourceLocation Loc,
2371 StringRef VariableName)
override {
2378 void warnParamReturnTypestateMismatch(SourceLocation Loc,
2379 StringRef VariableName,
2380 StringRef ExpectedState,
2381 StringRef ObservedState)
override {
2384 diag::warn_param_return_typestate_mismatch) << VariableName <<
2385 ExpectedState << ObservedState);
2390 void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
2391 StringRef ObservedState)
override {
2394 diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState);
2399 void warnReturnTypestateForUnconsumableType(SourceLocation Loc,
2400 StringRef TypeName)
override {
2402 diag::warn_return_typestate_for_unconsumable_type) << TypeName);
2407 void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
2408 StringRef ObservedState)
override {
2411 diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState);
2416 void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State,
2417 SourceLocation Loc)
override {
2420 diag::warn_use_of_temp_in_invalid_state) << MethodName << State);
2425 void warnUseInInvalidState(StringRef MethodName, StringRef VariableName,
2426 StringRef State, SourceLocation Loc)
override {
2429 MethodName << VariableName << State);
2444bool isMainParam(
const Decl *D) {
2445 if (
const auto *PVD = dyn_cast_or_null<ParmVarDecl>(D))
2446 if (
const auto *FD = dyn_cast<FunctionDecl>(PVD->getDeclContext()))
2447 return FD->isMain();
2451bool refersMainParam(
const Expr *E) {
2455 return isMainParam(DRE->getDecl());
2461static constexpr unsigned UnsafeLibcCallDiagIDs[] = {
2462 diag::warn_unsafe_buffer_libc_call,
2463 diag::warn_unsafe_buffer_libc_call_numeric_conversion,
2464 diag::warn_unsafe_buffer_libc_call_string_manipulation,
2465 diag::warn_unsafe_buffer_libc_call_string_examination,
2466 diag::warn_unsafe_buffer_libc_call_memory,
2467 diag::warn_unsafe_buffer_libc_call_io,
2468 diag::warn_unsafe_buffer_libc_call_printf,
2469 diag::warn_unsafe_buffer_libc_call_scanf,
2475 return diag::warn_unsafe_buffer_libc_call;
2477 return diag::warn_unsafe_buffer_libc_call_numeric_conversion;
2479 return diag::warn_unsafe_buffer_libc_call_string_manipulation;
2481 return diag::warn_unsafe_buffer_libc_call_string_examination;
2483 return diag::warn_unsafe_buffer_libc_call_memory;
2485 return diag::warn_unsafe_buffer_libc_call_io;
2487 return diag::warn_unsafe_buffer_libc_call_printf;
2489 return diag::warn_unsafe_buffer_libc_call_scanf;
2491 llvm_unreachable(
"unknown UnsafeLibcFunctionFamily");
2496 bool SuggestSuggestions;
2500 std::string listVariableGroupAsString(
2501 const VarDecl *VD,
const ArrayRef<const VarDecl *> &VarGroupForVD)
const {
2502 if (VarGroupForVD.size() <= 1)
2505 std::vector<StringRef> VarNames;
2506 auto PutInQuotes = [](StringRef S) -> std::string {
2507 return "'" + S.str() +
"'";
2510 for (
auto *
V : VarGroupForVD) {
2513 VarNames.push_back(
V->getName());
2515 if (VarNames.size() == 1) {
2516 return PutInQuotes(VarNames[0]);
2518 if (VarNames.size() == 2) {
2519 return PutInQuotes(VarNames[0]) +
" and " + PutInQuotes(VarNames[1]);
2521 assert(VarGroupForVD.size() > 3);
2522 const unsigned N = VarNames.size() -
2524 std::string AllVars =
"";
2526 for (
unsigned I = 0; I < N; ++I)
2527 AllVars.append(PutInQuotes(VarNames[I]) +
", ");
2528 AllVars.append(PutInQuotes(VarNames[N]) +
", and " +
2529 PutInQuotes(VarNames[N + 1]));
2534 UnsafeBufferUsageReporter(Sema &S,
bool SuggestSuggestions)
2535 : S(S), SuggestSuggestions(SuggestSuggestions) {}
2537 void handleUnsafeOperation(
const Stmt *Operation,
bool IsRelatedToDecl,
2538 ASTContext &Ctx)
override {
2541 unsigned MsgParam = 0;
2542 NamedDecl *D =
nullptr;
2543 const Expr *BufferOperand =
nullptr;
2544 if (
const auto *ASE = dyn_cast<ArraySubscriptExpr>(Operation)) {
2545 BufferOperand = ASE->getBase();
2549 }
else if (
const auto *BO = dyn_cast<BinaryOperator>(Operation)) {
2551 if (Op == BO_Add || Op == BO_AddAssign || Op == BO_Sub ||
2552 Op == BO_SubAssign) {
2554 BufferOperand = BO->
getLHS();
2558 BufferOperand = BO->
getRHS();
2564 }
else if (
const auto *UO = dyn_cast<UnaryOperator>(Operation)) {
2566 if (Op == UO_PreInc || Op == UO_PreDec || Op == UO_PostInc ||
2576 assert(!IsRelatedToDecl &&
"Not implemented yet!");
2580 assert(!IsRelatedToDecl &&
"Not implemented yet!");
2582 D = ME->getMemberDecl();
2584 }
else if (
const auto *ECE = dyn_cast<ExplicitCastExpr>(Operation)) {
2585 if (
const auto *CE = dyn_cast<CXXMemberCallExpr>(
2586 ECE->getSubExpr()->IgnoreParens())) {
2587 D = CE->getMethodDecl();
2598 if (IsRelatedToDecl) {
2599 assert(!SuggestSuggestions &&
2600 "Variables blamed for unsafe buffer usage without suggestions!");
2601 S.Diag(Loc, diag::note_unsafe_buffer_operation) << MsgParam <<
Range;
2603 unsigned DiagID = refersMainParam(BufferOperand)
2604 ? diag::warn_unsafe_buffer_operation_main_argv
2605 : diag::warn_unsafe_buffer_operation;
2608 S.Diag(Loc, DiagID) << MsgParam << D <<
Range;
2610 S.Diag(Loc, DiagID) << MsgParam <<
Range;
2611 if (SuggestSuggestions) {
2612 S.Diag(Loc, diag::note_safe_buffer_usage_suggestions_disabled);
2617 void handleUnsafeLibcCall(
const CallExpr *
Call,
unsigned PrintfInfo,
2619 const Expr *UnsafeArg =
nullptr)
override {
2620 unsigned DiagID = getUnsafeLibcCallDiagID(Family);
2621 if (PrintfInfo & 0x8) {
2625 DiagID = diag::warn_unsafe_buffer_format_attr_call;
2628 S.Diag(
Call->getBeginLoc(), DiagID)
2629 <<
Call->getDirectCallee()
2630 <<
Call->getSourceRange();
2631 if (PrintfInfo > 0) {
2633 UnsafeArg ? UnsafeArg->getSourceRange() :
Call->getSourceRange();
2634 S.Diag(
R.getBegin(), diag::note_unsafe_buffer_printf_call)
2639 void handleUnsafeOperationInContainer(
const Stmt *Operation,
2640 bool IsRelatedToDecl,
2641 ASTContext &Ctx)
override {
2644 unsigned MsgParam = 0;
2645 std::string ContainerName =
"container";
2647 if (
const auto *CtorExpr = dyn_cast<CXXConstructExpr>(Operation)) {
2648 Loc = CtorExpr->getLocation();
2649 Range = CtorExpr->getSourceRange();
2650 if (
auto *TD = CtorExpr->getConstructor()->getParent()) {
2651 ContainerName = TD->getQualifiedNameAsString();
2653 }
else if (
const auto *
Call = dyn_cast<CallExpr>(Operation)) {
2654 Loc =
Call->getExprLoc();
2656 if (
const auto *FD =
Call->getDirectCallee()) {
2657 ContainerName = FD->getQualifiedNameAsString();
2665 S.Diag(Loc, diag::warn_unsafe_buffer_usage_in_container) << ContainerName;
2667 if (IsRelatedToDecl) {
2668 assert(!SuggestSuggestions &&
2669 "Variables blamed for unsafe buffer usage without suggestions!");
2670 S.Diag(Loc, diag::note_unsafe_buffer_operation) << MsgParam <<
Range;
2674 void handleUnsafeOperationInStringView(
const Stmt *Operation,
2675 bool IsRelatedToDecl,
2676 ASTContext &Ctx)
override {
2681 if (
const auto *CtorExpr = dyn_cast<CXXConstructExpr>(Operation)) {
2682 Loc = CtorExpr->getLocation();
2686 S.Diag(Loc, diag::warn_unsafe_buffer_usage_in_container)
2687 <<
"std::string_view";
2690 if (IsRelatedToDecl) {
2693 S.Diag(Loc, diag::note_unsafe_buffer_operation) << 0 <<
Range;
2697 void handleUnsafeVariableGroup(
const VarDecl *Variable,
2698 const VariableGroupsManager &VarGrpMgr,
2699 FixItList &&Fixes,
const Decl *D,
2700 const FixitStrategy &VarTargetTypes)
override {
2701 assert(!SuggestSuggestions &&
2702 "Unsafe buffer usage fixits displayed without suggestions!");
2704 unsigned DiagID = isMainParam(Variable)
2705 ? diag::warn_unsafe_buffer_variable_main_argv
2706 : diag::warn_unsafe_buffer_variable;
2708 S.Diag(
Variable->getLocation(), DiagID)
2711 if (!Fixes.empty()) {
2713 "Fix-its are generated only for `NamedDecl`s");
2715 bool BriefMsg =
false;
2719 const auto VarGroupForVD = VarGrpMgr.
getGroupOfVar(Variable, &BriefMsg);
2720 unsigned FixItStrategy = 0;
2721 switch (VarTargetTypes.
lookup(Variable)) {
2729 assert(
false &&
"We support only std::span and std::array");
2734 BriefMsg ? diag::note_unsafe_buffer_variable_fixit_together
2735 : diag::note_unsafe_buffer_variable_fixit_group);
2738 FD << listVariableGroupAsString(Variable, VarGroupForVD)
2739 << (VarGroupForVD.size() > 1) << ND;
2740 for (
const auto &F : Fixes) {
2746 if (areDebugNotesRequested())
2747 for (
const DebugNote &
Note: DebugNotesByVar[Variable])
2748 S.Diag(
Note.first, diag::note_safe_buffer_debug_mode) <<
Note.second;
2752 void handleUnsafeUniquePtrArrayAccess(
const DynTypedNode &Node,
2753 bool IsRelatedToDecl,
2754 ASTContext &Ctx)
override {
2757 Loc = Node.
get<Stmt>()->getBeginLoc();
2758 S.Diag(Loc, diag::warn_unsafe_buffer_usage_unique_ptr_array_access)
2762 bool isSafeBufferOptOut(
const SourceLocation &Loc)
const override {
2763 return S.PP.isSafeBufferOptOut(S.getSourceManager(), Loc);
2767 return S.Diags.isIgnored(diag::warn_unsafe_buffer_usage_in_container, Loc);
2770 bool ignoreUnsafeBufferInLibcCall(
const SourceLocation &Loc)
const override {
2771 return llvm::all_of(UnsafeLibcCallDiagIDs, [&](
unsigned ID) {
2772 return S.Diags.isIgnored(ID, Loc);
2777 ignoreUnsafeBufferInFormatAttrCall(
const SourceLocation &Loc)
const override {
2778 return S.Diags.isIgnored(diag::warn_unsafe_buffer_format_attr_call, Loc);
2781 bool ignoreUnsafeBufferInStaticSizedArray(
2782 const SourceLocation &Loc)
const override {
2783 return S.Diags.isIgnored(
2784 diag::warn_unsafe_buffer_usage_in_static_sized_array, Loc);
2791 getUnsafeBufferUsageAttributeTextAt(SourceLocation Loc,
2792 StringRef WSSuffix =
"")
const override {
2793 Preprocessor &PP = S.getPreprocessor();
2794 TokenValue ClangUnsafeBufferUsageTokens[] = {
2803 StringRef MacroName;
2807 if (MacroName.empty())
2808 MacroName =
"[[clang::unsafe_buffer_usage]]";
2809 return MacroName.str() + WSSuffix.str();
2820 enableCheckFallThrough = 1;
2821 enableCheckUnreachable = 0;
2822 enableThreadSafetyAnalysis = 0;
2823 enableConsumedAnalysis = 0;
2844template <
typename... Ts>
2847 return (!D.
isIgnored(Diags, Loc) || ...);
2852 NumFunctionsAnalyzed(0), NumFunctionsWithBadCFGs(0), NumCFGBlocks(0),
2853 MaxCFGBlocksPerFunction(0), NumUninitAnalysisFunctions(0),
2854 NumUninitAnalysisVariables(0), MaxUninitAnalysisVariablesPerFunction(0),
2855 NumUninitAnalysisBlockVisits(0),
2856 MaxUninitAnalysisBlockVisitsPerFunction(0) {
2864 using namespace diag;
2873 const void *StateKey =
nullptr;
2874 unsigned SysIdx = 0;
2878 auto It = PolicyCache[SysIdx].find(StateKey);
2879 if (It != PolicyCache[SysIdx].end()) {
2881 P.enableCheckUnreachable |= PolicyOverrides.enableCheckUnreachable;
2882 P.enableThreadSafetyAnalysis |=
2883 PolicyOverrides.enableThreadSafetyAnalysis;
2884 P.enableConsumedAnalysis |= PolicyOverrides.enableConsumedAnalysis;
2893 P.enableCheckUnreachable =
2894 areAnyEnabled(D, Loc, warn_unreachable, warn_unreachable_break,
2895 warn_unreachable_return, warn_unreachable_loop_increment);
2897 P.enableThreadSafetyAnalysis =
areAnyEnabled(D, Loc, warn_double_lock);
2899 P.enableConsumedAnalysis =
areAnyEnabled(D, Loc, warn_use_in_invalid_state);
2902 PolicyCache[SysIdx][StateKey] = P;
2904 P.enableCheckUnreachable |= PolicyOverrides.enableCheckUnreachable;
2905 P.enableThreadSafetyAnalysis |= PolicyOverrides.enableThreadSafetyAnalysis;
2906 P.enableConsumedAnalysis |= PolicyOverrides.enableConsumedAnalysis;
2911 for (
auto &M : PolicyCache)
2915void sema::AnalysisBasedWarnings::clearOverrides() {
2916 PolicyOverrides.enableCheckUnreachable =
false;
2917 PolicyOverrides.enableConsumedAnalysis =
false;
2918 PolicyOverrides.enableThreadSafetyAnalysis =
false;
2923 S.
Diag(D.Loc, D.PD);
2926template <
typename Iterator>
2928 std::pair<Iterator, Iterator> PUDs) {
2930 if (PUDs.first == PUDs.second)
2933 for (
auto I = PUDs.first; I != PUDs.second; ++I) {
2934 for (
const Stmt *S : I->Stmts)
2942 for (
auto I = PUDs.first; I != PUDs.second; ++I) {
2944 if (llvm::all_of(D.Stmts, [&](
const Stmt *St) {
2945 const CFGBlock *Block = AC.getBlockForRegisteredExpression(St);
2949 if (Block && Analysis)
2950 if (!Analysis->isReachable(&AC.getCFG()->getEntry(), Block))
2954 S.
Diag(D.Loc, D.PD);
2958 for (
auto I = PUDs.first; I != PUDs.second; ++I)
2959 S.
Diag(I->Loc, I->PD);
2965 VarDeclPossiblyUnreachableDiags.emplace(VD, PUD);
2970 if (!llvm::is_contained(VarDeclPossiblyUnreachableDiags, VD))
2983 auto Range = VarDeclPossiblyUnreachableDiags.equal_range(VD);
2985 llvm::make_second_range(llvm::make_range(Range.first, Range.second));
2987 S, AC, std::make_pair(SecondRange.begin(), SecondRange.end()));
2994 llvm::function_ref<void(
const Decl *)> Callback;
2995 const Module *
const TUModule;
2999 const Module *
const TUModule)
3000 : Callback(Callback), TUModule(TUModule) {
3070 llvm::TimeTraceScope TimeProfile(
"LifetimeSafetyTUAnalysis");
3074 for (
auto *Node : llvm::post_order(&CG)) {
3076 dyn_cast_or_null<clang::FunctionDecl>(Node->getDecl());
3085 runLifetimeSafetyAnalysis(AC, &SemaHelper,
3094 return !Diags.
isIgnored(diag::warn_unsafe_buffer_operation, Loc) ||
3095 !Diags.
isIgnored(diag::warn_unsafe_buffer_variable, Loc) ||
3096 !Diags.
isIgnored(diag::warn_unsafe_buffer_usage_in_container, Loc) ||
3099 UnsafeLibcCallDiagIDs,
3100 [&](
unsigned ID) {
return !Diags.
isIgnored(ID, Loc); }) ||
3101 !Diags.
isIgnored(diag::warn_unsafe_buffer_format_attr_call, Loc)));
3109 .ShowSafeBufferUsageSuggestions;
3117 .ShowSafeBufferUsageSuggestions;
3136 UnsafeBufferUsageReporter R(S,
false);
3139 auto CallAnalyzers = [&](
const Decl *Node) ->
void {
3140 if (Node->hasAttr<UnsafeBufferUsageAttr>())
3156 .TraverseTranslationUnitDecl(TU);
3182 if (
const auto *Ctor = dyn_cast<CXXConstructorDecl>(D)) {
3183 bool HasInClassInit =
false;
3185 if (FD->hasInClassInitializer()) {
3186 HasInClassInit =
true;
3189 if (!HasInClassInit)
3200 LSStats, S.CollectStats);
3218 if (S.hasUncompilableErrorOccurred()) {
3249 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis ||
3250 P.enableConsumedAnalysis || EnableLifetimeSafetyAnalysis) {
3263 if (EnableLifetimeSafetyAnalysis)
3267 std::optional<LogicalErrorHandler> LEH;
3268 if (LogicalErrorHandler::hasActiveDiagnostics(Diags, D->
getBeginLoc())) {
3278 if (P.enableCheckFallThrough) {
3279 const CheckFallThroughDiagnostics &CD =
3284 ? CheckFallThroughDiagnostics::MakeForLambda()
3286 ? CheckFallThroughDiagnostics::MakeForCoroutine(D)
3287 : CheckFallThroughDiagnostics::MakeForFunction(S, D)));
3292 if (P.enableCheckUnreachable) {
3305 if (P.enableThreadSafetyAnalysis) {
3308 threadSafety::ThreadSafetyReporter Reporter(S, FL, FEL);
3310 Reporter.setIssueBetaWarnings(
true);
3312 Reporter.setVerbose(
true);
3315 &S.ThreadSafetyDeclCache);
3316 Reporter.emitDiagnostics();
3320 if (P.enableConsumedAnalysis) {
3321 consumed::ConsumedWarningsHandler WarningHandler(S);
3332 UninitValsDiagReporter reporter(S);
3339 ++NumUninitAnalysisFunctions;
3342 MaxUninitAnalysisVariablesPerFunction =
3343 std::max(MaxUninitAnalysisVariablesPerFunction,
3345 MaxUninitAnalysisBlockVisitsPerFunction =
3346 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
3352 if (EnableLifetimeSafetyAnalysis) {
3357 LSStats, S.CollectStats);
3361 if (S.getLangOpts().ObjC && !S.getLangOpts().CPlusPlus &&
3362 shouldAnalyzeCalledOnceParameters(Diags, D->
getBeginLoc())) {
3364 CalledOnceCheckReporter Reporter(S, IPData->CalledOnceData);
3367 shouldAnalyzeCalledOnceConventions(Diags, D->
getBeginLoc()));
3371 bool FallThroughDiagFull =
3373 bool FallThroughDiagPerFunction = !Diags.
isIgnored(
3374 diag::warn_unannotated_fallthrough_per_function, D->
getBeginLoc());
3375 if (FallThroughDiagFull || FallThroughDiagPerFunction ||
3380 if (S.getLangOpts().ObjCWeak &&
3386 if (!Diags.
isIgnored(diag::warn_infinite_recursive_function,
3388 if (
const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3395 if (
const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
3401 if (LogicalErrorHandler::hasActiveDiagnostics(Diags, D->
getBeginLoc())) {
3410 ++NumFunctionsAnalyzed;
3414 NumCFGBlocks += cfg->getNumBlockIDs();
3415 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
3416 cfg->getNumBlockIDs());
3418 ++NumFunctionsWithBadCFGs;
3428 !D->
hasAttr<UnsafeBufferUsageAttr>()) {
3429 UnsafeBufferUsageReporter R(S,
3441 llvm::errs() <<
"\n*** Analysis Based Warnings Stats:\n";
3443 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
3444 unsigned AvgCFGBlocksPerFunction =
3445 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
3446 llvm::errs() << NumFunctionsAnalyzed <<
" functions analyzed ("
3447 << NumFunctionsWithBadCFGs <<
" w/o CFGs).\n"
3448 <<
" " << NumCFGBlocks <<
" CFG blocks built.\n"
3449 <<
" " << AvgCFGBlocksPerFunction
3450 <<
" average CFG blocks per function.\n"
3451 <<
" " << MaxCFGBlocksPerFunction
3452 <<
" max CFG blocks per function.\n";
3454 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
3455 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
3456 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
3457 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
3458 llvm::errs() << NumUninitAnalysisFunctions
3459 <<
" functions analyzed for uninitialiazed variables\n"
3460 <<
" " << NumUninitAnalysisVariables <<
" variables analyzed.\n"
3461 <<
" " << AvgUninitVariablesPerFunction
3462 <<
" average variables per function.\n"
3463 <<
" " << MaxUninitAnalysisVariablesPerFunction
3464 <<
" max variables per function.\n"
3465 <<
" " << NumUninitAnalysisBlockVisits <<
" block visits.\n"
3466 <<
" " << AvgUninitBlockVisitsPerFunction
3467 <<
" average block visits per function.\n"
3468 <<
" " << MaxUninitAnalysisBlockVisitsPerFunction
3469 <<
" max block visits per function.\n";
static bool shouldRunUnsafeBufferUsageAnalysis(const Sema &S, SourceLocation Loc)
static void visitReachableThrows(CFG *BodyCFG, llvm::function_ref< void(const CXXThrowExpr *, CFGBlock &)> Visit)
static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD)
static bool shouldEmitUnsafeBufferUsageSuggestions(const Sema &S)
static bool isReferenceToNoReturn(const Expr *E)
Checks if the given expression is a reference to a function with 'noreturn' attribute.
static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM, const Stmt *S)
static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC)
CheckFallThrough - Check that we don't fall off the end of a Statement that should return a value.
static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body, QualType BlockType, const CheckFallThroughDiagnostics &CD, AnalysisDeclContext &AC)
CheckFallThroughForBody - Check that we don't fall off the end of a function that should return a val...
static void flushDiagnostics(Sema &S, const sema::FunctionScopeInfo *fscope)
static void diagnoseRepeatedUseOfWeak(Sema &S, const sema::FunctionScopeInfo *CurFn, const Decl *D, const ParentMap &PM)
static void EmitDiagForCXXThrowInNonThrowingFunc(Sema &S, SourceLocation OpLoc, const FunctionDecl *FD)
static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC, bool PerFunction)
static void LifetimeSafetyTUAnalysis(Sema &S, TranslationUnitDecl *TU, clang::lifetimes::LifetimeSafetyStats &LSStats)
static void checkThrowInNonThrowingFunc(Sema &S, const FunctionDecl *FD, AnalysisDeclContext &AC)
static bool shouldSuggestUnsafeBufferUsageSuggestions(const Sema &S)
static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then, const Stmt *Else, bool CondVal, FixItHint &Fixit1, FixItHint &Fixit2)
Create a fixit to remove an if-like statement, on the assumption that its condition is CondVal.
static StringRef getFallthroughAttrSpelling(Preprocessor &PP, SourceLocation Loc)
static void emitPossiblyUnreachableDiags(Sema &S, AnalysisDeclContext &AC, std::pair< Iterator, Iterator > PUDs)
static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD, const UninitUse &Use, bool alwaysReportSelfInit=false)
DiagnoseUninitializedUse – Helper function for diagnosing uses of an uninitialized variable.
static bool areAnyEnabled(DiagnosticsEngine &D, SourceLocation Loc, Ts... Diags)
static bool hasRecursiveCallInPath(const FunctionDecl *FD, CFGBlock &Block)
static bool throwEscapes(Sema &S, const CXXThrowExpr *E, CFGBlock &ThrowBlock, CFG *Body)
Determine whether an exception thrown by E, unwinding from ThrowBlock, can reach ExitBlock.
static bool areAllValuesNoReturn(const VarDecl *VD, const CFGBlock &VarBlk, AnalysisDeclContext &AC)
static bool shouldSkipAnalysisForDecl(Sema &S, const Decl *D)
static bool isNoexcept(const FunctionDecl *FD)
static void setLifetimeSafetyCFGBuildOptions(AnalysisDeclContext &AC)
static bool DiagnoseUninitializedConstRefUse(Sema &S, const VarDecl *VD, const UninitUse &Use)
Diagnose uninitialized const reference usages.
static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use, bool IsCapturedByBlock)
DiagUninitUse – Helper function to produce a diagnostic for an uninitialized use of a variable.
static bool DiagnoseUninitializedConstPtrUse(Sema &S, const VarDecl *VD, const UninitUse &Use)
Diagnose uninitialized const pointer usages.
static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC)
CheckUnreachable - Check for unreachable code.
@ NeverFallThroughOrReturn
static bool isInitializedWithNoReturn(const VarDecl *VD)
Checks if the given variable, which is assumed to be a function pointer, is initialized with a functi...
static void checkRecursiveFunction(Sema &S, const FunctionDecl *FD, const Stmt *Body, AnalysisDeclContext &AC)
static bool checkForRecursiveFunctionCall(const FunctionDecl *FD, CFG *cfg)
This file defines AnalysisDeclContext, a class that manages the analysis context data for context sen...
static bool ignoreUnsafeBufferInContainer(const Stmt &Node, const UnsafeBufferUsageHandler *Handler)
Defines the Diagnostic-related interfaces.
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, const ASTContext &Ctx, Expr::SideEffectsKind AllowSideEffects, EvalInfo &Info)
static std::pair< const Stmt *, const CFGBlock * > getLastStmt(const ExplodedNode *Node)
Result
Implement __builtin_bit_cast and related operations.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
static void emitDiagnostics(BoundNodes &Match, const Decl *D, BugReporter &BR, AnalysisManager &AM, const ObjCAutoreleaseWriteChecker *Checker)
llvm::DenseMap< Stmt *, Stmt * > MapTy
Defines the clang::Preprocessor interface.
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Defines the Objective-C statement AST node classes.
C Language Family Type Representation.
@ Open
The standard open() call: int open(const char *path, int oflag, ...);.
TextDiagnosticBuffer::DiagList DiagList
CallableVisitor(llvm::function_ref< void(const Decl *)> Callback, const Module *const TUModule)
bool VisitObjCMethodDecl(ObjCMethodDecl *Node) override
bool TraverseDecl(Decl *Node) override
bool VisitBlockDecl(BlockDecl *Node) override
bool VisitFunctionDecl(FunctionDecl *Node) override
bool VisitLambdaExpr(LambdaExpr *Node) override
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
AnalysisDeclContext contains the context data for the function, method or block under analysis.
void registerForcedBlockExpression(const Stmt *stmt)
ParentMap & getParentMap()
const Decl * getDecl() const
bool getAddEHEdges() const
CFGReverseBlockReachabilityAnalysis * getCFGReachablityAnalysis()
ASTContext & getASTContext() const
CFG::BuildOptions & getCFGBuildOptions()
A builtin binary operation expression such as "x + y" or "x <= y".
static bool isLogicalOp(Opcode Opc)
SourceLocation getBeginLoc() const LLVM_READONLY
SourceLocation getOperatorLoc() const
SourceLocation getExprLoc() const
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
BinaryOperatorKind Opcode
Represents a block literal declaration, which is like an unnamed FunctionDecl.
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
SourceLocation getBeginLoc() const LLVM_READONLY
unsigned IgnoreDefaultsWithCoveredEnums
Represents a single basic block in a source-level CFG.
filtered_pred_iterator filtered_pred_start_end(const FilterOptions &f) const
reverse_iterator rbegin()
bool hasOnlyAnalyzerNoReturnElement() const
Returns true if the block ends in an 'analyzer_noreturn' call (as opposed to a real 'noreturn' one).
bool hasNoReturnElement() const
Returns true if the block has a noreturn element, whether it is a real 'noreturn' or an 'analyzer_nor...
ElementList::const_reverse_iterator const_reverse_iterator
FilteredCFGBlockIterator< const_pred_iterator, true > filtered_pred_iterator
succ_iterator succ_begin()
Stmt * getTerminatorStmt()
pred_iterator pred_begin()
unsigned getBlockID() const
unsigned succ_size() const
CFGCallback defines methods that should be called when a logical operator error is found when buildin...
Represents a top-level expression in a basic block.
T castAs() const
Convert to the specified CFGElement type, asserting that this CFGElement is of the desired type.
std::optional< T > getAs() const
Convert to the specified CFGElement type, returning std::nullopt if this CFGElement is not of the des...
const Stmt * getStmt() const
bool PruneTriviallyFalseEdges
bool AddCXXDefaultInitExprInCtors
bool AddParameterLifetimes
BuildOptions & setAllAlwaysAdd()
BuildOptions & setAlwaysAdd(Stmt::StmtClass stmtClass, bool val=true)
Represents a source-level, intra-procedural CFG that represents the control-flow of a Stmt.
unsigned getNumBlockIDs() const
Returns the total number of BlockIDs allocated (which start at 0).
Represents a call to a member function that may be written either with member call syntax (e....
CXXMethodDecl * getMethodDecl() const
Retrieve the declaration of the called method.
Expr * getImplicitObjectArgument() const
Retrieve the implicit object argument for the member call.
A C++ throw-expression (C++ [except.throw]).
const Expr * getSubExpr() const
SourceLocation getThrowLoc() const
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
ExprIterator arg_iterator
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
The AST-based call graph.
void addToCallGraph(Decl *D)
Populate the call graph with the functions in the given declaration.
static CharSourceRange getCharRange(SourceRange R)
SourceLocation getBegin() const
ConditionalOperator - The ?
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
ConstEvaluatedExprVisitor - This class visits 'const Expr *'s.
void enqueueBlock(const CFGBlock *Block)
const CFGBlock * dequeue()
bool isFunctionOrMethod() const
Returns true if this DeclContext is a function, Objective-C method, or block, or a DeclContext that c...
A reference to a declared variable, function, enum, etc.
Decl - This represents one declaration (or definition), e.g.
SourceLocation getEndLoc() const LLVM_READONLY
virtual Stmt * getBody() const
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
SourceLocation getLocation() const
DeclContext * getDeclContext()
SourceLocation getBeginLoc() const LLVM_READONLY
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
SourceLocation getBeginLoc() const LLVM_READONLY
TypeSourceInfo * getTypeSourceInfo() const
Concrete class used by the front-end to report problems and issues.
bool hasDiagSuppressionMapping() const
True if an active diagnostic suppression mapping makes severity dependent on the file path.
bool isLastDiagnosticIgnored() const
Determine whether the previous diagnostic was ignored.
DiagStateSystemClass getDiagStateSystemClassForLoc(SourceLocation Loc) const
Returns whether Loc is in a system header and/or a system macro.
bool getIgnoreAllWarnings() const
DiagnosticOptions & getDiagnosticOptions() const
Retrieve the diagnostic options.
const void * getDiagStateKeyForLoc(SourceLocation Loc) const
Returns a cache key representing the diagnostic state at Loc.
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
bool getSuppressSystemWarnings() const
const T * get() const
Retrieve the stored node as type T.
SourceRange getSourceRange(bool IncludeQualifier=false) const
For nodes which represent textual entities in the source code, return their SourceRange.
virtual bool TraverseDecl(MaybeConst< Decl > *D)
bool ShouldVisitTemplateInstantiations
bool ShouldVisitImplicitCode
void VisitDeclRefExpr(PTR(DeclRefExpr) E)
This represents one expression.
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Represents a member of a struct/union/class.
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
CharSourceRange RemoveRange
Code that should be replaced to correct the error.
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Kind lookup(const VarDecl *VD) const
Represents a function declaration or definition.
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
SourceRange getExceptionSpecSourceRange() const
Attempt to compute an informative source range covering the function exception specification,...
@ TK_MemberSpecialization
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
FunctionDecl * getDefinition()
Get the definition for this declaration.
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
Represents a prototype with parameter type info, e.g.
FunctionType - C99 6.7.5.3 - Function Declarators.
IfStmt - This represents an if/then/else.
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
CXXMethodDecl * getCallOperator() const
Retrieve the function call operator associated with this lambda expression.
Describes a module or submodule.
This represents a decl that may have a name.
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
@ Type
A type, stored as a Type*.
ObjCMethodDecl - Represents an instance or class method declaration.
bool hasBody() const override
Determine whether this method has a body.
Represents one property declaration in an Objective-C interface.
Stmt * getParent(Stmt *) const
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
const LangOptions & getLangOpts() const
StringRef getLastMacroWithSpelling(SourceLocation Loc, ArrayRef< TokenValue > Tokens) const
Return the name of the macro defined before Loc that has spelling Tokens.
A (possibly-)qualified type.
bool isNull() const
Return true if this QualType doesn't point to a type yet.
bool isConstant(const ASTContext &Ctx) const
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
QualType getCanonicalType() const
bool isConstQualified() const
Determine whether this type is const-qualified.
bool hasObjCLifetime() const
field_range fields() const
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Sema - This implements semantic analysis and AST building for C.
Preprocessor & getPreprocessor() const
DiagnosticsEngine & getDiagnostics() const
ASTContext & getASTContext() const
std::string getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const
Get a string to suggest for zero-initialization of a type.
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
const LangOptions & getLangOpts() const
bool CollectStats
Flag indicating whether or not to collect detailed statistics.
SourceManager & getSourceManager() const
bool handlerCanCatch(QualType HandlerType, QualType ExceptionType)
SourceManager & SourceMgr
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
This class handles loading and caching of source files into memory.
bool isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
bool isBeforeInTranslationUnit(SourceLocation LHS, SourceLocation RHS) const
Determines the order of 2 source locations in the translation unit.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
Stmt - This represents one statement.
SourceLocation getEndLoc() const LLVM_READONLY
StmtClass getStmtClass() const
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
SourceLocation getBeginLoc() const LLVM_READONLY
Stores token information for comparing actual tokens with predefined values.
The top declaration context.
QualType getType() const
Return the type wrapped by this type source info.
bool isBlockPointerType() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
const T * castAs() const
Member-template castAs<specific type>.
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
const T * getAs() const
Member-template getAs<specific type>'.
Expr * getSubExpr() const
A use of a variable, which might be uninitialized.
const Expr * getUser() const
Get the expression containing the uninitialized use.
SmallVectorImpl< Branch >::const_iterator branch_iterator
branch_iterator branch_end() const
bool isConstPtrUse() const
bool isConstRefOrPtrUse() const
bool isConstRefUse() const
branch_iterator branch_begin() const
Branches which inevitably result in the variable being used uninitialized.
@ Always
The use is always uninitialized.
@ AfterDecl
The use is uninitialized the first time it is reached after we reach the variable's declaration.
@ Maybe
The use might be uninitialized.
@ AfterCall
The use is uninitialized the first time it is reached after the function is called.
@ Sometimes
The use is uninitialized whenever a certain branch is taken.
Kind getKind() const
Get the kind of uninitialized use.
The interface that lets the caller handle unsafe buffer usage analysis results by overriding this cla...
Represents a variable declaration or definition.
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
const Expr * getInit() const
virtual VarGrpRef getGroupOfVar(const VarDecl *Var, bool *HasParm=nullptr) const =0
Returns the set of variables (including Var) that need to be fixed together in one step.
A class that handles the analysis of uniqueness violations.
void clearPolicyCache()
Drop cached getPolicyInEffectAt() results (diagnostic state changed).
void issueWarningsForRegisteredVarDecl(VarDecl *VD)
void IssueWarnings(Policy P, FunctionScopeInfo *fscope, const Decl *D, QualType BlockType)
void registerVarDeclWarning(VarDecl *VD, PossiblyUnreachableDiag PUD)
AnalysisBasedWarnings(Sema &s)
Policy getPolicyInEffectAt(SourceLocation Loc)
void IssueWarningsForImplicitFunction(const Decl *D)
Represents a simple identification of a weak object.
Retains information about a function, method, or block that is currently being parsed.
bool HasFallthroughStmt
Whether there is a fallthrough statement in this function.
SmallVector< WeakUseTy, 4 > WeakUseVector
Used to collect uses of a particular weak object in a function body.
SmallVector< PossiblyUnreachableDiag, 4 > PossiblyUnreachableDiags
A list of PartialDiagnostics created but delayed within the current function scope.
llvm::SmallDenseMap< WeakObjectProfileTy, WeakUseVector, 8, WeakObjectProfileTy::DenseMapInfo > WeakObjectUseMap
Used to collect all uses of weak objects in a function body.
const WeakObjectUseMap & getWeakObjectUses() const
InterProceduralData aims to be a storage of whatever data should be passed between analyses of differ...
CalledOnceInterProceduralData CalledOnceData
std::list< DelayedDiag > DiagList
std::pair< PartialDiagnosticAt, OptionalNotes > DelayedDiag
SmallVector< PartialDiagnosticAt, 1 > OptionalNotes
uint32_t Variable
Boolean variables are represented as positive integers.
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
@ Quoted
'#include ""' paths, added by 'gcc -iquote'.
bool LE(InterpState &S, CodePtr OpPC)
void runLifetimeSafetyAnalysis(AnalysisDeclContext &AC, LifetimeSafetySemaHelper *SemaHelper, const LifetimeSafetyOpts &Opts, LifetimeSafetyStats &Stats, bool CollectStats)
The main entry point for the analysis.
void printStats(const LifetimeSafetyStats &Stats)
Utility function to print missing origin stats.
LifetimeSafetyOpts GetLifetimeSafetyOpts(Sema &S, const Decl *D)
bool IsLifetimeSafetyEnabled(Sema &S, const Decl *D)
void FindUnreachableCode(AnalysisDeclContext &AC, Preprocessor &PP, Callback &CB)
unsigned ScanReachableFromBlock(const CFGBlock *Start, llvm::BitVector &Reachable)
ScanReachableFromBlock - Mark all blocks reachable from Start.
UnreachableKind
Classifications of unreachable code.
LockKind getLockKindFromAccessKind(AccessKind AK)
Helper function that returns a LockKind required for the given level of access.
LockErrorKind
This enum distinguishes between different situations where we warn due to inconsistent locking.
@ LEK_NotLockedAtEndOfFunction
Expecting a capability to be held at the end of function.
@ LEK_LockedSomePredecessors
A capability is locked in some but not all predecessors of a CFGBlock.
@ LEK_LockedAtEndOfFunction
A capability is still locked at the end of a function.
@ LEK_LockedSomeLoopIterations
A capability is locked for some but not all loop iterations.
AccessKind
This enum distinguishes between different ways to access (read or write) a variable.
LockKind
This enum distinguishes between different kinds of lock actions.
void runThreadSafetyAnalysis(AnalysisDeclContext &AC, ThreadSafetyHandler &Handler, BeforeSet **Bset)
Check a function's CFG for thread-safety violations.
ProtectedOperationKind
This enum distinguishes between different kinds of operations that may need to be protected by locks.
@ POK_PtPassByRef
Passing a pt-guarded variable by reference.
@ POK_PassPointer
Passing pointer to a guarded variable.
@ POK_VarDereference
Dereferencing a variable (e.g. p in *p = 5;)
@ POK_PassByRef
Passing a guarded variable by reference.
@ POK_ReturnByRef
Returning a guarded variable by reference.
@ POK_PtPassPointer
Passing a pt-guarded pointer.
@ POK_PtReturnPointer
Returning a pt-guarded pointer.
@ POK_VarAccess
Reading or writing a variable (e.g. x in x = 5;)
@ POK_FunctionCall
Making a function call (e.g. fool())
@ POK_ReturnPointer
Returning pointer to a guarded variable.
@ POK_PtReturnByRef
Returning a pt-guarded variable by reference.
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
void checkUnsafeBufferUsage(const Decl *D, UnsafeBufferUsageHandler &Handler, bool EmitSuggestions)
bool hasSpecificAttr(const Container &container)
@ If
'if' clause, allowed on all the Compute Constructs, Data Constructs, Executable Constructs,...
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ Parameter
The parameter type of a method or function.
void runUninitializedVariablesAnalysis(const DeclContext &dc, const CFG &cfg, AnalysisDeclContext &ac, UninitVariablesHandler &handler, UninitVariablesAnalysisStats &stats)
void checkCalledOnceParameters(AnalysisDeclContext &AC, CalledOnceCheckHandler &Handler, bool CheckConventionalParameters)
Check given CFG for 'called once' parameter violations.
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
UnsafeLibcFunctionFamily
The family of an unsafe libc function.
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
U cast(CodeGen::Address addr)
A worklist implementation for backward dataflow analysis.
void enqueuePredecessors(const CFGBlock *Block)
EvalResult is a struct with detailed info about an evaluated expression.
unsigned NumVariablesAnalyzed
A structure to hold the statistics related to LifetimeAnalysis.