1 //=- AnalysisBasedWarnings.cpp - Sema warnings based on libAnalysis -*- C++ -*-=//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines analysis_warnings::[Policy,Executor].
11 // Together they are used by Sema to issue warnings based on inexpensive
12 // static analysis algorithms in libAnalysis.
14 //===----------------------------------------------------------------------===//
16 #include "clang/Sema/AnalysisBasedWarnings.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/EvaluatedExprVisitor.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/ExprObjC.h"
22 #include "clang/AST/ParentMap.h"
23 #include "clang/AST/RecursiveASTVisitor.h"
24 #include "clang/AST/StmtCXX.h"
25 #include "clang/AST/StmtObjC.h"
26 #include "clang/AST/StmtVisitor.h"
27 #include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h"
28 #include "clang/Analysis/Analyses/Consumed.h"
29 #include "clang/Analysis/Analyses/ReachableCode.h"
30 #include "clang/Analysis/Analyses/ThreadSafety.h"
31 #include "clang/Analysis/Analyses/UninitializedValues.h"
32 #include "clang/Analysis/AnalysisDeclContext.h"
33 #include "clang/Analysis/CFG.h"
34 #include "clang/Analysis/CFGStmtMap.h"
35 #include "clang/Basic/SourceLocation.h"
36 #include "clang/Basic/SourceManager.h"
37 #include "clang/Lex/Preprocessor.h"
38 #include "clang/Sema/ScopeInfo.h"
39 #include "clang/Sema/SemaInternal.h"
40 #include "llvm/ADT/BitVector.h"
41 #include "llvm/ADT/MapVector.h"
42 #include "llvm/ADT/SmallString.h"
43 #include "llvm/ADT/SmallVector.h"
44 #include "llvm/ADT/StringRef.h"
45 #include "llvm/Support/Casting.h"
50 using namespace clang;
52 //===----------------------------------------------------------------------===//
53 // Unreachable code analysis.
54 //===----------------------------------------------------------------------===//
57 class UnreachableCodeHandler : public reachable_code::Callback {
59 SourceRange PreviousSilenceableCondVal;
62 UnreachableCodeHandler(Sema &s) : S(s) {}
64 void HandleUnreachable(reachable_code::UnreachableKind UK,
66 SourceRange SilenceableCondVal,
68 SourceRange R2) override {
69 // Avoid reporting multiple unreachable code diagnostics that are
70 // triggered by the same conditional value.
71 if (PreviousSilenceableCondVal.isValid() &&
72 SilenceableCondVal.isValid() &&
73 PreviousSilenceableCondVal == SilenceableCondVal)
75 PreviousSilenceableCondVal = SilenceableCondVal;
77 unsigned diag = diag::warn_unreachable;
79 case reachable_code::UK_Break:
80 diag = diag::warn_unreachable_break;
82 case reachable_code::UK_Return:
83 diag = diag::warn_unreachable_return;
85 case reachable_code::UK_Loop_Increment:
86 diag = diag::warn_unreachable_loop_increment;
88 case reachable_code::UK_Other:
92 S.Diag(L, diag) << R1 << R2;
94 SourceLocation Open = SilenceableCondVal.getBegin();
96 SourceLocation Close = SilenceableCondVal.getEnd();
97 Close = S.getLocForEndOfToken(Close);
98 if (Close.isValid()) {
99 S.Diag(Open, diag::note_unreachable_silence)
100 << FixItHint::CreateInsertion(Open, "/* DISABLES CODE */ (")
101 << FixItHint::CreateInsertion(Close, ")");
106 } // anonymous namespace
108 /// CheckUnreachable - Check for unreachable code.
109 static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) {
110 // As a heuristic prune all diagnostics not in the main file. Currently
111 // the majority of warnings in headers are false positives. These
112 // are largely caused by configuration state, e.g. preprocessor
113 // defined code, etc.
115 // Note that this is also a performance optimization. Analyzing
116 // headers many times can be expensive.
117 if (!S.getSourceManager().isInMainFile(AC.getDecl()->getLocStart()))
120 UnreachableCodeHandler UC(S);
121 reachable_code::FindUnreachableCode(AC, S.getPreprocessor(), UC);
125 /// \brief Warn on logical operator errors in CFGBuilder
126 class LogicalErrorHandler : public CFGCallback {
130 LogicalErrorHandler(Sema &S) : CFGCallback(), S(S) {}
132 static bool HasMacroID(const Expr *E) {
133 if (E->getExprLoc().isMacroID())
136 // Recurse to children.
137 for (const Stmt *SubStmt : E->children())
138 if (const Expr *SubExpr = dyn_cast_or_null<Expr>(SubStmt))
139 if (HasMacroID(SubExpr))
145 void compareAlwaysTrue(const BinaryOperator *B, bool isAlwaysTrue) override {
149 SourceRange DiagRange = B->getSourceRange();
150 S.Diag(B->getExprLoc(), diag::warn_tautological_overlap_comparison)
151 << DiagRange << isAlwaysTrue;
154 void compareBitwiseEquality(const BinaryOperator *B,
155 bool isAlwaysTrue) override {
159 SourceRange DiagRange = B->getSourceRange();
160 S.Diag(B->getExprLoc(), diag::warn_comparison_bitwise_always)
161 << DiagRange << isAlwaysTrue;
164 } // anonymous namespace
166 //===----------------------------------------------------------------------===//
167 // Check for infinite self-recursion in functions
168 //===----------------------------------------------------------------------===//
170 // Returns true if the function is called anywhere within the CFGBlock.
171 // For member functions, the additional condition of being call from the
172 // this pointer is required.
173 static bool hasRecursiveCallInPath(const FunctionDecl *FD, CFGBlock &Block) {
174 // Process all the Stmt's in this block to find any calls to FD.
175 for (const auto &B : Block) {
176 if (B.getKind() != CFGElement::Statement)
179 const CallExpr *CE = dyn_cast<CallExpr>(B.getAs<CFGStmt>()->getStmt());
180 if (!CE || !CE->getCalleeDecl() ||
181 CE->getCalleeDecl()->getCanonicalDecl() != FD)
184 // Skip function calls which are qualified with a templated class.
185 if (const DeclRefExpr *DRE =
186 dyn_cast<DeclRefExpr>(CE->getCallee()->IgnoreParenImpCasts())) {
187 if (NestedNameSpecifier *NNS = DRE->getQualifier()) {
188 if (NNS->getKind() == NestedNameSpecifier::TypeSpec &&
189 isa<TemplateSpecializationType>(NNS->getAsType())) {
195 const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE);
196 if (!MCE || isa<CXXThisExpr>(MCE->getImplicitObjectArgument()) ||
197 !MCE->getMethodDecl()->isVirtual())
203 // All blocks are in one of three states. States are ordered so that blocks
204 // can only move to higher states.
205 enum RecursiveState {
208 FoundPathWithNoRecursiveCall
211 // Returns true if there exists a path to the exit block and every path
212 // to the exit block passes through a call to FD.
213 static bool checkForRecursiveFunctionCall(const FunctionDecl *FD, CFG *cfg) {
215 const unsigned ExitID = cfg->getExit().getBlockID();
217 // Mark all nodes as FoundNoPath, then set the status of the entry block.
218 SmallVector<RecursiveState, 16> States(cfg->getNumBlockIDs(), FoundNoPath);
219 States[cfg->getEntry().getBlockID()] = FoundPathWithNoRecursiveCall;
221 // Make the processing stack and seed it with the entry block.
222 SmallVector<CFGBlock *, 16> Stack;
223 Stack.push_back(&cfg->getEntry());
225 while (!Stack.empty()) {
226 CFGBlock *CurBlock = Stack.back();
229 unsigned ID = CurBlock->getBlockID();
230 RecursiveState CurState = States[ID];
232 if (CurState == FoundPathWithNoRecursiveCall) {
233 // Found a path to the exit node without a recursive call.
237 // Only change state if the block has a recursive call.
238 if (hasRecursiveCallInPath(FD, *CurBlock))
239 CurState = FoundPath;
242 // Loop over successor blocks and add them to the Stack if their state
244 for (auto I = CurBlock->succ_begin(), E = CurBlock->succ_end(); I != E; ++I)
246 unsigned next_ID = (*I)->getBlockID();
247 if (States[next_ID] < CurState) {
248 States[next_ID] = CurState;
254 // Return true if the exit node is reachable, and only reachable through
256 return States[ExitID] == FoundPath;
259 static void checkRecursiveFunction(Sema &S, const FunctionDecl *FD,
260 const Stmt *Body, AnalysisDeclContext &AC) {
261 FD = FD->getCanonicalDecl();
263 // Only run on non-templated functions and non-templated members of
264 // templated classes.
265 if (FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate &&
266 FD->getTemplatedKind() != FunctionDecl::TK_MemberSpecialization)
269 CFG *cfg = AC.getCFG();
272 // If the exit block is unreachable, skip processing the function.
273 if (cfg->getExit().pred_empty())
276 // Emit diagnostic if a recursive function call is detected for all paths.
277 if (checkForRecursiveFunctionCall(FD, cfg))
278 S.Diag(Body->getLocStart(), diag::warn_infinite_recursive_function);
281 //===----------------------------------------------------------------------===//
282 // Check for throw in a non-throwing function.
283 //===----------------------------------------------------------------------===//
287 FoundPathWithNoThrowOutFunction,
290 static bool isThrowCaught(const CXXThrowExpr *Throw,
291 const CXXCatchStmt *Catch) {
292 const Type *CaughtType = Catch->getCaughtType().getTypePtrOrNull();
295 const Type *ThrowType = nullptr;
296 if (Throw->getSubExpr())
297 ThrowType = Throw->getSubExpr()->getType().getTypePtrOrNull();
300 if (ThrowType->isReferenceType())
301 ThrowType = ThrowType->castAs<ReferenceType>()
303 ->getUnqualifiedDesugaredType();
304 if (CaughtType->isReferenceType())
305 CaughtType = CaughtType->castAs<ReferenceType>()
307 ->getUnqualifiedDesugaredType();
308 if (ThrowType->isPointerType() && CaughtType->isPointerType()) {
309 ThrowType = ThrowType->getPointeeType()->getUnqualifiedDesugaredType();
310 CaughtType = CaughtType->getPointeeType()->getUnqualifiedDesugaredType();
312 if (CaughtType == ThrowType)
314 const CXXRecordDecl *CaughtAsRecordType =
315 CaughtType->getAsCXXRecordDecl();
316 const CXXRecordDecl *ThrowTypeAsRecordType = ThrowType->getAsCXXRecordDecl();
317 if (CaughtAsRecordType && ThrowTypeAsRecordType)
318 return ThrowTypeAsRecordType->isDerivedFrom(CaughtAsRecordType);
322 static bool isThrowCaughtByHandlers(const CXXThrowExpr *CE,
323 const CXXTryStmt *TryStmt) {
324 for (unsigned H = 0, E = TryStmt->getNumHandlers(); H < E; ++H) {
325 if (isThrowCaught(CE, TryStmt->getHandler(H)))
331 static bool doesThrowEscapePath(CFGBlock Block, SourceLocation &OpLoc) {
332 for (const auto &B : Block) {
333 if (B.getKind() != CFGElement::Statement)
335 const auto *CE = dyn_cast<CXXThrowExpr>(B.getAs<CFGStmt>()->getStmt());
339 OpLoc = CE->getThrowLoc();
340 for (const auto &I : Block.succs()) {
341 if (!I.isReachable())
343 if (const auto *Terminator =
344 dyn_cast_or_null<CXXTryStmt>(I->getTerminator()))
345 if (isThrowCaughtByHandlers(CE, Terminator))
353 static bool hasThrowOutNonThrowingFunc(SourceLocation &OpLoc, CFG *BodyCFG) {
355 unsigned ExitID = BodyCFG->getExit().getBlockID();
357 SmallVector<ThrowState, 16> States(BodyCFG->getNumBlockIDs(),
358 FoundNoPathForThrow);
359 States[BodyCFG->getEntry().getBlockID()] = FoundPathWithNoThrowOutFunction;
361 SmallVector<CFGBlock *, 16> Stack;
362 Stack.push_back(&BodyCFG->getEntry());
363 while (!Stack.empty()) {
364 CFGBlock *CurBlock = Stack.pop_back_val();
366 unsigned ID = CurBlock->getBlockID();
367 ThrowState CurState = States[ID];
368 if (CurState == FoundPathWithNoThrowOutFunction) {
372 if (doesThrowEscapePath(*CurBlock, OpLoc))
373 CurState = FoundPathForThrow;
376 // Loop over successor blocks and add them to the Stack if their state
378 for (const auto &I : CurBlock->succs())
379 if (I.isReachable()) {
380 unsigned NextID = I->getBlockID();
381 if (NextID == ExitID && CurState == FoundPathForThrow) {
382 States[NextID] = CurState;
383 } else if (States[NextID] < CurState) {
384 States[NextID] = CurState;
389 // Return true if the exit node is reachable, and only reachable through
390 // a throw expression.
391 return States[ExitID] == FoundPathForThrow;
394 static void EmitDiagForCXXThrowInNonThrowingFunc(Sema &S, SourceLocation OpLoc,
395 const FunctionDecl *FD) {
396 if (!S.getSourceManager().isInSystemHeader(OpLoc) &&
397 FD->getTypeSourceInfo()) {
398 S.Diag(OpLoc, diag::warn_throw_in_noexcept_func) << FD;
399 if (S.getLangOpts().CPlusPlus11 &&
400 (isa<CXXDestructorDecl>(FD) ||
401 FD->getDeclName().getCXXOverloadedOperator() == OO_Delete ||
402 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_Delete)) {
403 if (const auto *Ty = FD->getTypeSourceInfo()->getType()->
404 getAs<FunctionProtoType>())
405 S.Diag(FD->getLocation(), diag::note_throw_in_dtor)
406 << !isa<CXXDestructorDecl>(FD) << !Ty->hasExceptionSpec()
407 << FD->getExceptionSpecSourceRange();
409 S.Diag(FD->getLocation(), diag::note_throw_in_function)
410 << FD->getExceptionSpecSourceRange();
414 static void checkThrowInNonThrowingFunc(Sema &S, const FunctionDecl *FD,
415 AnalysisDeclContext &AC) {
416 CFG *BodyCFG = AC.getCFG();
419 if (BodyCFG->getExit().pred_empty())
421 SourceLocation OpLoc;
422 if (hasThrowOutNonThrowingFunc(OpLoc, BodyCFG))
423 EmitDiagForCXXThrowInNonThrowingFunc(S, OpLoc, FD);
426 static bool isNoexcept(const FunctionDecl *FD) {
427 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
428 if (FPT->isNothrow(FD->getASTContext()) || FD->hasAttr<NoThrowAttr>())
433 //===----------------------------------------------------------------------===//
434 // Check for missing return value.
435 //===----------------------------------------------------------------------===//
437 enum ControlFlowKind {
442 NeverFallThroughOrReturn
445 /// CheckFallThrough - Check that we don't fall off the end of a
446 /// Statement that should return a value.
448 /// \returns AlwaysFallThrough iff we always fall off the end of the statement,
449 /// MaybeFallThrough iff we might or might not fall off the end,
450 /// NeverFallThroughOrReturn iff we never fall off the end of the statement or
451 /// return. We assume NeverFallThrough iff we never fall off the end of the
452 /// statement but we may return. We assume that functions not marked noreturn
454 static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
455 CFG *cfg = AC.getCFG();
456 if (!cfg) return UnknownFallThrough;
458 // The CFG leaves in dead things, and we don't want the dead code paths to
459 // confuse us, so we mark all live things first.
460 llvm::BitVector live(cfg->getNumBlockIDs());
461 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
464 bool AddEHEdges = AC.getAddEHEdges();
465 if (!AddEHEdges && count != cfg->getNumBlockIDs())
466 // When there are things remaining dead, and we didn't add EH edges
467 // from CallExprs to the catch clauses, we have to go back and
468 // mark them as live.
469 for (const auto *B : *cfg) {
470 if (!live[B->getBlockID()]) {
471 if (B->pred_begin() == B->pred_end()) {
472 if (B->getTerminator() && isa<CXXTryStmt>(B->getTerminator()))
473 // When not adding EH edges from calls, catch clauses
474 // can otherwise seem dead. Avoid noting them as dead.
475 count += reachable_code::ScanReachableFromBlock(B, live);
481 // Now we know what is live, we check the live precessors of the exit block
482 // and look for fall through paths, being careful to ignore normal returns,
483 // and exceptional paths.
484 bool HasLiveReturn = false;
485 bool HasFakeEdge = false;
486 bool HasPlainEdge = false;
487 bool HasAbnormalEdge = false;
489 // Ignore default cases that aren't likely to be reachable because all
490 // enums in a switch(X) have explicit case statements.
491 CFGBlock::FilterOptions FO;
492 FO.IgnoreDefaultsWithCoveredEnums = 1;
494 for (CFGBlock::filtered_pred_iterator
495 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
496 const CFGBlock& B = **I;
497 if (!live[B.getBlockID()])
500 // Skip blocks which contain an element marked as no-return. They don't
501 // represent actually viable edges into the exit block, so mark them as
503 if (B.hasNoReturnElement()) {
504 HasAbnormalEdge = true;
508 // Destructors can appear after the 'return' in the CFG. This is
509 // normal. We need to look pass the destructors for the return
510 // statement (if it exists).
511 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
513 for ( ; ri != re ; ++ri)
514 if (ri->getAs<CFGStmt>())
517 // No more CFGElements in the block?
519 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
520 HasAbnormalEdge = true;
523 // A labeled empty statement, or the entry block...
528 CFGStmt CS = ri->castAs<CFGStmt>();
529 const Stmt *S = CS.getStmt();
530 if (isa<ReturnStmt>(S) || isa<CoreturnStmt>(S)) {
531 HasLiveReturn = true;
534 if (isa<ObjCAtThrowStmt>(S)) {
538 if (isa<CXXThrowExpr>(S)) {
542 if (isa<MSAsmStmt>(S)) {
543 // TODO: Verify this is correct.
545 HasLiveReturn = true;
548 if (isa<CXXTryStmt>(S)) {
549 HasAbnormalEdge = true;
552 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
554 HasAbnormalEdge = true;
562 return NeverFallThrough;
563 return NeverFallThroughOrReturn;
565 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
566 return MaybeFallThrough;
567 // This says AlwaysFallThrough for calls to functions that are not marked
568 // noreturn, that don't return. If people would like this warning to be more
569 // accurate, such functions should be marked as noreturn.
570 return AlwaysFallThrough;
575 struct CheckFallThroughDiagnostics {
576 unsigned diag_MaybeFallThrough_HasNoReturn;
577 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
578 unsigned diag_AlwaysFallThrough_HasNoReturn;
579 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
580 unsigned diag_NeverFallThroughOrReturn;
581 enum { Function, Block, Lambda, Coroutine } funMode;
582 SourceLocation FuncLoc;
584 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
585 CheckFallThroughDiagnostics D;
586 D.FuncLoc = Func->getLocation();
587 D.diag_MaybeFallThrough_HasNoReturn =
588 diag::warn_falloff_noreturn_function;
589 D.diag_MaybeFallThrough_ReturnsNonVoid =
590 diag::warn_maybe_falloff_nonvoid_function;
591 D.diag_AlwaysFallThrough_HasNoReturn =
592 diag::warn_falloff_noreturn_function;
593 D.diag_AlwaysFallThrough_ReturnsNonVoid =
594 diag::warn_falloff_nonvoid_function;
596 // Don't suggest that virtual functions be marked "noreturn", since they
597 // might be overridden by non-noreturn functions.
598 bool isVirtualMethod = false;
599 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
600 isVirtualMethod = Method->isVirtual();
602 // Don't suggest that template instantiations be marked "noreturn"
603 bool isTemplateInstantiation = false;
604 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
605 isTemplateInstantiation = Function->isTemplateInstantiation();
607 if (!isVirtualMethod && !isTemplateInstantiation)
608 D.diag_NeverFallThroughOrReturn =
609 diag::warn_suggest_noreturn_function;
611 D.diag_NeverFallThroughOrReturn = 0;
613 D.funMode = Function;
617 static CheckFallThroughDiagnostics MakeForCoroutine(const Decl *Func) {
618 CheckFallThroughDiagnostics D;
619 D.FuncLoc = Func->getLocation();
620 D.diag_MaybeFallThrough_HasNoReturn = 0;
621 D.diag_MaybeFallThrough_ReturnsNonVoid =
622 diag::warn_maybe_falloff_nonvoid_coroutine;
623 D.diag_AlwaysFallThrough_HasNoReturn = 0;
624 D.diag_AlwaysFallThrough_ReturnsNonVoid =
625 diag::warn_falloff_nonvoid_coroutine;
626 D.funMode = Coroutine;
630 static CheckFallThroughDiagnostics MakeForBlock() {
631 CheckFallThroughDiagnostics D;
632 D.diag_MaybeFallThrough_HasNoReturn =
633 diag::err_noreturn_block_has_return_expr;
634 D.diag_MaybeFallThrough_ReturnsNonVoid =
635 diag::err_maybe_falloff_nonvoid_block;
636 D.diag_AlwaysFallThrough_HasNoReturn =
637 diag::err_noreturn_block_has_return_expr;
638 D.diag_AlwaysFallThrough_ReturnsNonVoid =
639 diag::err_falloff_nonvoid_block;
640 D.diag_NeverFallThroughOrReturn = 0;
645 static CheckFallThroughDiagnostics MakeForLambda() {
646 CheckFallThroughDiagnostics D;
647 D.diag_MaybeFallThrough_HasNoReturn =
648 diag::err_noreturn_lambda_has_return_expr;
649 D.diag_MaybeFallThrough_ReturnsNonVoid =
650 diag::warn_maybe_falloff_nonvoid_lambda;
651 D.diag_AlwaysFallThrough_HasNoReturn =
652 diag::err_noreturn_lambda_has_return_expr;
653 D.diag_AlwaysFallThrough_ReturnsNonVoid =
654 diag::warn_falloff_nonvoid_lambda;
655 D.diag_NeverFallThroughOrReturn = 0;
660 bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
661 bool HasNoReturn) const {
662 if (funMode == Function) {
663 return (ReturnsVoid ||
664 D.isIgnored(diag::warn_maybe_falloff_nonvoid_function,
667 D.isIgnored(diag::warn_noreturn_function_has_return_expr,
670 D.isIgnored(diag::warn_suggest_noreturn_block, FuncLoc));
672 if (funMode == Coroutine) {
673 return (ReturnsVoid ||
674 D.isIgnored(diag::warn_maybe_falloff_nonvoid_function, FuncLoc) ||
675 D.isIgnored(diag::warn_maybe_falloff_nonvoid_coroutine,
679 // For blocks / lambdas.
680 return ReturnsVoid && !HasNoReturn;
684 } // anonymous namespace
686 /// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
687 /// function that should return a value. Check that we don't fall off the end
688 /// of a noreturn function. We assume that functions and blocks not marked
689 /// noreturn will return.
690 static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
691 const BlockExpr *blkExpr,
692 const CheckFallThroughDiagnostics& CD,
693 AnalysisDeclContext &AC) {
695 bool ReturnsVoid = false;
696 bool HasNoReturn = false;
697 bool IsCoroutine = S.getCurFunction() && S.getCurFunction()->isCoroutine();
699 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
700 if (const auto *CBody = dyn_cast<CoroutineBodyStmt>(Body))
701 ReturnsVoid = CBody->getFallthroughHandler() != nullptr;
703 ReturnsVoid = FD->getReturnType()->isVoidType();
704 HasNoReturn = FD->isNoReturn();
706 else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
707 ReturnsVoid = MD->getReturnType()->isVoidType();
708 HasNoReturn = MD->hasAttr<NoReturnAttr>();
710 else if (isa<BlockDecl>(D)) {
711 QualType BlockTy = blkExpr->getType();
712 if (const FunctionType *FT =
713 BlockTy->getPointeeType()->getAs<FunctionType>()) {
714 if (FT->getReturnType()->isVoidType())
716 if (FT->getNoReturnAttr())
721 DiagnosticsEngine &Diags = S.getDiagnostics();
723 // Short circuit for compilation speed.
724 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
726 SourceLocation LBrace = Body->getLocStart(), RBrace = Body->getLocEnd();
727 auto EmitDiag = [&](SourceLocation Loc, unsigned DiagID) {
729 S.Diag(Loc, DiagID) << S.getCurFunction()->CoroutinePromise->getType();
733 // Either in a function body compound statement, or a function-try-block.
734 switch (CheckFallThrough(AC)) {
735 case UnknownFallThrough:
738 case MaybeFallThrough:
740 EmitDiag(RBrace, CD.diag_MaybeFallThrough_HasNoReturn);
741 else if (!ReturnsVoid)
742 EmitDiag(RBrace, CD.diag_MaybeFallThrough_ReturnsNonVoid);
744 case AlwaysFallThrough:
746 EmitDiag(RBrace, CD.diag_AlwaysFallThrough_HasNoReturn);
747 else if (!ReturnsVoid)
748 EmitDiag(RBrace, CD.diag_AlwaysFallThrough_ReturnsNonVoid);
750 case NeverFallThroughOrReturn:
751 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
752 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
753 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 0 << FD;
754 } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
755 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 1 << MD;
757 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn);
761 case NeverFallThrough:
766 //===----------------------------------------------------------------------===//
768 //===----------------------------------------------------------------------===//
771 /// ContainsReference - A visitor class to search for references to
772 /// a particular declaration (the needle) within any evaluated component of an
773 /// expression (recursively).
774 class ContainsReference : public ConstEvaluatedExprVisitor<ContainsReference> {
776 const DeclRefExpr *Needle;
779 typedef ConstEvaluatedExprVisitor<ContainsReference> Inherited;
781 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
782 : Inherited(Context), FoundReference(false), Needle(Needle) {}
784 void VisitExpr(const Expr *E) {
785 // Stop evaluating if we already have a reference.
789 Inherited::VisitExpr(E);
792 void VisitDeclRefExpr(const DeclRefExpr *E) {
794 FoundReference = true;
796 Inherited::VisitDeclRefExpr(E);
799 bool doesContainReference() const { return FoundReference; }
801 } // anonymous namespace
803 static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
804 QualType VariableTy = VD->getType().getCanonicalType();
805 if (VariableTy->isBlockPointerType() &&
806 !VD->hasAttr<BlocksAttr>()) {
807 S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization)
809 << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
813 // Don't issue a fixit if there is already an initializer.
817 // Don't suggest a fixit inside macros.
818 if (VD->getLocEnd().isMacroID())
821 SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
823 // Suggest possible initialization (if any).
824 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
828 S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
829 << FixItHint::CreateInsertion(Loc, Init);
833 /// Create a fixit to remove an if-like statement, on the assumption that its
834 /// condition is CondVal.
835 static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
836 const Stmt *Else, bool CondVal,
837 FixItHint &Fixit1, FixItHint &Fixit2) {
839 // If condition is always true, remove all but the 'then'.
840 Fixit1 = FixItHint::CreateRemoval(
841 CharSourceRange::getCharRange(If->getLocStart(),
842 Then->getLocStart()));
844 SourceLocation ElseKwLoc = S.getLocForEndOfToken(Then->getLocEnd());
845 Fixit2 = FixItHint::CreateRemoval(
846 SourceRange(ElseKwLoc, Else->getLocEnd()));
849 // If condition is always false, remove all but the 'else'.
851 Fixit1 = FixItHint::CreateRemoval(
852 CharSourceRange::getCharRange(If->getLocStart(),
853 Else->getLocStart()));
855 Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
859 /// DiagUninitUse -- Helper function to produce a diagnostic for an
860 /// uninitialized use of a variable.
861 static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
862 bool IsCapturedByBlock) {
863 bool Diagnosed = false;
865 switch (Use.getKind()) {
866 case UninitUse::Always:
867 S.Diag(Use.getUser()->getLocStart(), diag::warn_uninit_var)
868 << VD->getDeclName() << IsCapturedByBlock
869 << Use.getUser()->getSourceRange();
872 case UninitUse::AfterDecl:
873 case UninitUse::AfterCall:
874 S.Diag(VD->getLocation(), diag::warn_sometimes_uninit_var)
875 << VD->getDeclName() << IsCapturedByBlock
876 << (Use.getKind() == UninitUse::AfterDecl ? 4 : 5)
877 << const_cast<DeclContext*>(VD->getLexicalDeclContext())
878 << VD->getSourceRange();
879 S.Diag(Use.getUser()->getLocStart(), diag::note_uninit_var_use)
880 << IsCapturedByBlock << Use.getUser()->getSourceRange();
883 case UninitUse::Maybe:
884 case UninitUse::Sometimes:
885 // Carry on to report sometimes-uninitialized branches, if possible,
886 // or a 'may be used uninitialized' diagnostic otherwise.
890 // Diagnose each branch which leads to a sometimes-uninitialized use.
891 for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
893 assert(Use.getKind() == UninitUse::Sometimes);
895 const Expr *User = Use.getUser();
896 const Stmt *Term = I->Terminator;
898 // Information used when building the diagnostic.
903 // FixIts to suppress the diagnostic by removing the dead condition.
904 // For all binary terminators, branch 0 is taken if the condition is true,
905 // and branch 1 is taken if the condition is false.
906 int RemoveDiagKind = -1;
907 const char *FixitStr =
908 S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
909 : (I->Output ? "1" : "0");
910 FixItHint Fixit1, Fixit2;
912 switch (Term ? Term->getStmtClass() : Stmt::DeclStmtClass) {
914 // Don't know how to report this. Just fall back to 'may be used
915 // uninitialized'. FIXME: Can this happen?
918 // "condition is true / condition is false".
919 case Stmt::IfStmtClass: {
920 const IfStmt *IS = cast<IfStmt>(Term);
923 Range = IS->getCond()->getSourceRange();
925 CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
926 I->Output, Fixit1, Fixit2);
929 case Stmt::ConditionalOperatorClass: {
930 const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
933 Range = CO->getCond()->getSourceRange();
935 CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
936 I->Output, Fixit1, Fixit2);
939 case Stmt::BinaryOperatorClass: {
940 const BinaryOperator *BO = cast<BinaryOperator>(Term);
941 if (!BO->isLogicalOp())
944 Str = BO->getOpcodeStr();
945 Range = BO->getLHS()->getSourceRange();
947 if ((BO->getOpcode() == BO_LAnd && I->Output) ||
948 (BO->getOpcode() == BO_LOr && !I->Output))
949 // true && y -> y, false || y -> y.
950 Fixit1 = FixItHint::CreateRemoval(SourceRange(BO->getLocStart(),
951 BO->getOperatorLoc()));
953 // false && y -> false, true || y -> true.
954 Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
958 // "loop is entered / loop is exited".
959 case Stmt::WhileStmtClass:
962 Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
964 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
966 case Stmt::ForStmtClass:
969 Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
972 Fixit1 = FixItHint::CreateRemoval(Range);
974 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
976 case Stmt::CXXForRangeStmtClass:
977 if (I->Output == 1) {
978 // The use occurs if a range-based for loop's body never executes.
979 // That may be impossible, and there's no syntactic fix for this,
980 // so treat it as a 'may be uninitialized' case.
985 Range = cast<CXXForRangeStmt>(Term)->getRangeInit()->getSourceRange();
988 // "condition is true / loop is exited".
989 case Stmt::DoStmtClass:
992 Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
994 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
997 // "switch case is taken".
998 case Stmt::CaseStmtClass:
1001 Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
1003 case Stmt::DefaultStmtClass:
1006 Range = cast<DefaultStmt>(Term)->getDefaultLoc();
1010 S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
1011 << VD->getDeclName() << IsCapturedByBlock << DiagKind
1012 << Str << I->Output << Range;
1013 S.Diag(User->getLocStart(), diag::note_uninit_var_use)
1014 << IsCapturedByBlock << User->getSourceRange();
1015 if (RemoveDiagKind != -1)
1016 S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
1017 << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
1023 S.Diag(Use.getUser()->getLocStart(), diag::warn_maybe_uninit_var)
1024 << VD->getDeclName() << IsCapturedByBlock
1025 << Use.getUser()->getSourceRange();
1028 /// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
1029 /// uninitialized variable. This manages the different forms of diagnostic
1030 /// emitted for particular types of uses. Returns true if the use was diagnosed
1031 /// as a warning. If a particular use is one we omit warnings for, returns
1033 static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
1034 const UninitUse &Use,
1035 bool alwaysReportSelfInit = false) {
1036 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
1037 // Inspect the initializer of the variable declaration which is
1038 // being referenced prior to its initialization. We emit
1039 // specialized diagnostics for self-initialization, and we
1040 // specifically avoid warning about self references which take the
1045 // This is used to indicate to GCC that 'x' is intentionally left
1046 // uninitialized. Proven code paths which access 'x' in
1047 // an uninitialized state after this will still warn.
1048 if (const Expr *Initializer = VD->getInit()) {
1049 if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
1052 ContainsReference CR(S.Context, DRE);
1053 CR.Visit(Initializer);
1054 if (CR.doesContainReference()) {
1055 S.Diag(DRE->getLocStart(),
1056 diag::warn_uninit_self_reference_in_init)
1057 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
1062 DiagUninitUse(S, VD, Use, false);
1064 const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
1065 if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
1066 S.Diag(BE->getLocStart(),
1067 diag::warn_uninit_byref_blockvar_captured_by_block)
1068 << VD->getDeclName();
1070 DiagUninitUse(S, VD, Use, true);
1073 // Report where the variable was declared when the use wasn't within
1074 // the initializer of that declaration & we didn't already suggest
1075 // an initialization fixit.
1076 if (!SuggestInitializationFixit(S, VD))
1077 S.Diag(VD->getLocStart(), diag::note_var_declared_here)
1078 << VD->getDeclName();
1084 class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
1086 FallthroughMapper(Sema &S)
1087 : FoundSwitchStatements(false),
1091 bool foundSwitchStatements() const { return FoundSwitchStatements; }
1093 void markFallthroughVisited(const AttributedStmt *Stmt) {
1094 bool Found = FallthroughStmts.erase(Stmt);
1099 typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
1101 const AttrStmts &getFallthroughStmts() const {
1102 return FallthroughStmts;
1105 void fillReachableBlocks(CFG *Cfg) {
1106 assert(ReachableBlocks.empty() && "ReachableBlocks already filled");
1107 std::deque<const CFGBlock *> BlockQueue;
1109 ReachableBlocks.insert(&Cfg->getEntry());
1110 BlockQueue.push_back(&Cfg->getEntry());
1111 // Mark all case blocks reachable to avoid problems with switching on
1112 // constants, covered enums, etc.
1113 // These blocks can contain fall-through annotations, and we don't want to
1114 // issue a warn_fallthrough_attr_unreachable for them.
1115 for (const auto *B : *Cfg) {
1116 const Stmt *L = B->getLabel();
1117 if (L && isa<SwitchCase>(L) && ReachableBlocks.insert(B).second)
1118 BlockQueue.push_back(B);
1121 while (!BlockQueue.empty()) {
1122 const CFGBlock *P = BlockQueue.front();
1123 BlockQueue.pop_front();
1124 for (CFGBlock::const_succ_iterator I = P->succ_begin(),
1127 if (*I && ReachableBlocks.insert(*I).second)
1128 BlockQueue.push_back(*I);
1133 bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt,
1134 bool IsTemplateInstantiation) {
1135 assert(!ReachableBlocks.empty() && "ReachableBlocks empty");
1137 int UnannotatedCnt = 0;
1140 std::deque<const CFGBlock*> BlockQueue(B.pred_begin(), B.pred_end());
1141 while (!BlockQueue.empty()) {
1142 const CFGBlock *P = BlockQueue.front();
1143 BlockQueue.pop_front();
1146 const Stmt *Term = P->getTerminator();
1147 if (Term && isa<SwitchStmt>(Term))
1148 continue; // Switch statement, good.
1150 const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
1151 if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
1152 continue; // Previous case label has no statements, good.
1154 const LabelStmt *L = dyn_cast_or_null<LabelStmt>(P->getLabel());
1155 if (L && L->getSubStmt() == B.getLabel() && P->begin() == P->end())
1156 continue; // Case label is preceded with a normal label, good.
1158 if (!ReachableBlocks.count(P)) {
1159 for (CFGBlock::const_reverse_iterator ElemIt = P->rbegin(),
1160 ElemEnd = P->rend();
1161 ElemIt != ElemEnd; ++ElemIt) {
1162 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>()) {
1163 if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
1164 // Don't issue a warning for an unreachable fallthrough
1165 // attribute in template instantiations as it may not be
1166 // unreachable in all instantiations of the template.
1167 if (!IsTemplateInstantiation)
1168 S.Diag(AS->getLocStart(),
1169 diag::warn_fallthrough_attr_unreachable);
1170 markFallthroughVisited(AS);
1174 // Don't care about other unreachable statements.
1177 // If there are no unreachable statements, this may be a special
1180 // A a; // A has a destructor.
1183 // // <<<< This place is represented by a 'hanging' CFG block.
1188 const Stmt *LastStmt = getLastStmt(*P);
1189 if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
1190 markFallthroughVisited(AS);
1192 continue; // Fallthrough annotation, good.
1195 if (!LastStmt) { // This block contains no executable statements.
1196 // Traverse its predecessors.
1197 std::copy(P->pred_begin(), P->pred_end(),
1198 std::back_inserter(BlockQueue));
1204 return !!UnannotatedCnt;
1207 // RecursiveASTVisitor setup.
1208 bool shouldWalkTypesOfTypeLocs() const { return false; }
1210 bool VisitAttributedStmt(AttributedStmt *S) {
1211 if (asFallThroughAttr(S))
1212 FallthroughStmts.insert(S);
1216 bool VisitSwitchStmt(SwitchStmt *S) {
1217 FoundSwitchStatements = true;
1221 // We don't want to traverse local type declarations. We analyze their
1222 // methods separately.
1223 bool TraverseDecl(Decl *D) { return true; }
1225 // We analyze lambda bodies separately. Skip them here.
1226 bool TraverseLambdaBody(LambdaExpr *LE) { return true; }
1230 static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
1231 if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
1232 if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
1238 static const Stmt *getLastStmt(const CFGBlock &B) {
1239 if (const Stmt *Term = B.getTerminator())
1241 for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
1243 ElemIt != ElemEnd; ++ElemIt) {
1244 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>())
1245 return CS->getStmt();
1247 // Workaround to detect a statement thrown out by CFGBuilder:
1248 // case X: {} case Y:
1249 // case X: ; case Y:
1250 if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
1251 if (!isa<SwitchCase>(SW->getSubStmt()))
1252 return SW->getSubStmt();
1257 bool FoundSwitchStatements;
1258 AttrStmts FallthroughStmts;
1260 llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks;
1262 } // anonymous namespace
1264 static StringRef getFallthroughAttrSpelling(Preprocessor &PP,
1265 SourceLocation Loc) {
1266 TokenValue FallthroughTokens[] = {
1267 tok::l_square, tok::l_square,
1268 PP.getIdentifierInfo("fallthrough"),
1269 tok::r_square, tok::r_square
1272 TokenValue ClangFallthroughTokens[] = {
1273 tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
1274 tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
1275 tok::r_square, tok::r_square
1278 bool PreferClangAttr = !PP.getLangOpts().CPlusPlus17;
1280 StringRef MacroName;
1281 if (PreferClangAttr)
1282 MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens);
1283 if (MacroName.empty())
1284 MacroName = PP.getLastMacroWithSpelling(Loc, FallthroughTokens);
1285 if (MacroName.empty() && !PreferClangAttr)
1286 MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens);
1287 if (MacroName.empty())
1288 MacroName = PreferClangAttr ? "[[clang::fallthrough]]" : "[[fallthrough]]";
1292 static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
1294 // Only perform this analysis when using [[]] attributes. There is no good
1295 // workflow for this warning when not using C++11. There is no good way to
1296 // silence the warning (no attribute is available) unless we are using
1297 // [[]] attributes. One could use pragmas to silence the warning, but as a
1298 // general solution that is gross and not in the spirit of this warning.
1300 // NOTE: This an intermediate solution. There are on-going discussions on
1301 // how to properly support this warning outside of C++11 with an annotation.
1302 if (!AC.getASTContext().getLangOpts().DoubleSquareBracketAttributes)
1305 FallthroughMapper FM(S);
1306 FM.TraverseStmt(AC.getBody());
1308 if (!FM.foundSwitchStatements())
1311 if (PerFunction && FM.getFallthroughStmts().empty())
1314 CFG *Cfg = AC.getCFG();
1319 FM.fillReachableBlocks(Cfg);
1321 for (const CFGBlock *B : llvm::reverse(*Cfg)) {
1322 const Stmt *Label = B->getLabel();
1324 if (!Label || !isa<SwitchCase>(Label))
1329 bool IsTemplateInstantiation = false;
1330 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(AC.getDecl()))
1331 IsTemplateInstantiation = Function->isTemplateInstantiation();
1332 if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt,
1333 IsTemplateInstantiation))
1336 S.Diag(Label->getLocStart(),
1337 PerFunction ? diag::warn_unannotated_fallthrough_per_function
1338 : diag::warn_unannotated_fallthrough);
1340 if (!AnnotatedCnt) {
1341 SourceLocation L = Label->getLocStart();
1344 if (S.getLangOpts().CPlusPlus11) {
1345 const Stmt *Term = B->getTerminator();
1346 // Skip empty cases.
1347 while (B->empty() && !Term && B->succ_size() == 1) {
1348 B = *B->succ_begin();
1349 Term = B->getTerminator();
1351 if (!(B->empty() && Term && isa<BreakStmt>(Term))) {
1352 Preprocessor &PP = S.getPreprocessor();
1353 StringRef AnnotationSpelling = getFallthroughAttrSpelling(PP, L);
1354 SmallString<64> TextToInsert(AnnotationSpelling);
1355 TextToInsert += "; ";
1356 S.Diag(L, diag::note_insert_fallthrough_fixit) <<
1357 AnnotationSpelling <<
1358 FixItHint::CreateInsertion(L, TextToInsert);
1361 S.Diag(L, diag::note_insert_break_fixit) <<
1362 FixItHint::CreateInsertion(L, "break; ");
1366 for (const auto *F : FM.getFallthroughStmts())
1367 S.Diag(F->getLocStart(), diag::err_fallthrough_attr_invalid_placement);
1370 static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
1375 switch (S->getStmtClass()) {
1376 case Stmt::ForStmtClass:
1377 case Stmt::WhileStmtClass:
1378 case Stmt::CXXForRangeStmtClass:
1379 case Stmt::ObjCForCollectionStmtClass:
1381 case Stmt::DoStmtClass: {
1382 const Expr *Cond = cast<DoStmt>(S)->getCond();
1384 if (!Cond->EvaluateAsInt(Val, Ctx))
1386 return Val.getBoolValue();
1391 } while ((S = PM.getParent(S)));
1396 static void diagnoseRepeatedUseOfWeak(Sema &S,
1397 const sema::FunctionScopeInfo *CurFn,
1399 const ParentMap &PM) {
1400 typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
1401 typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
1402 typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
1403 typedef std::pair<const Stmt *, WeakObjectUseMap::const_iterator>
1406 ASTContext &Ctx = S.getASTContext();
1408 const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
1410 // Extract all weak objects that are referenced more than once.
1411 SmallVector<StmtUsesPair, 8> UsesByStmt;
1412 for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
1414 const WeakUseVector &Uses = I->second;
1416 // Find the first read of the weak object.
1417 WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1418 for ( ; UI != UE; ++UI) {
1423 // If there were only writes to this object, don't warn.
1427 // If there was only one read, followed by any number of writes, and the
1428 // read is not within a loop, don't warn. Additionally, don't warn in a
1429 // loop if the base object is a local variable -- local variables are often
1430 // changed in loops.
1431 if (UI == Uses.begin()) {
1432 WeakUseVector::const_iterator UI2 = UI;
1433 for (++UI2; UI2 != UE; ++UI2)
1434 if (UI2->isUnsafe())
1438 if (!isInLoop(Ctx, PM, UI->getUseExpr()))
1441 const WeakObjectProfileTy &Profile = I->first;
1442 if (!Profile.isExactProfile())
1445 const NamedDecl *Base = Profile.getBase();
1447 Base = Profile.getProperty();
1448 assert(Base && "A profile always has a base or property.");
1450 if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
1451 if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
1456 UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
1459 if (UsesByStmt.empty())
1462 // Sort by first use so that we emit the warnings in a deterministic order.
1463 SourceManager &SM = S.getSourceManager();
1464 std::sort(UsesByStmt.begin(), UsesByStmt.end(),
1465 [&SM](const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
1466 return SM.isBeforeInTranslationUnit(LHS.first->getLocStart(),
1467 RHS.first->getLocStart());
1470 // Classify the current code body for better warning text.
1471 // This enum should stay in sync with the cases in
1472 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1473 // FIXME: Should we use a common classification enum and the same set of
1474 // possibilities all throughout Sema?
1482 if (isa<sema::BlockScopeInfo>(CurFn))
1483 FunctionKind = Block;
1484 else if (isa<sema::LambdaScopeInfo>(CurFn))
1485 FunctionKind = Lambda;
1486 else if (isa<ObjCMethodDecl>(D))
1487 FunctionKind = Method;
1489 FunctionKind = Function;
1491 // Iterate through the sorted problems and emit warnings for each.
1492 for (const auto &P : UsesByStmt) {
1493 const Stmt *FirstRead = P.first;
1494 const WeakObjectProfileTy &Key = P.second->first;
1495 const WeakUseVector &Uses = P.second->second;
1497 // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
1498 // may not contain enough information to determine that these are different
1499 // properties. We can only be 100% sure of a repeated use in certain cases,
1500 // and we adjust the diagnostic kind accordingly so that the less certain
1501 // case can be turned off if it is too noisy.
1503 if (Key.isExactProfile())
1504 DiagKind = diag::warn_arc_repeated_use_of_weak;
1506 DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
1508 // Classify the weak object being accessed for better warning text.
1509 // This enum should stay in sync with the cases in
1510 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1518 const NamedDecl *KeyProp = Key.getProperty();
1519 if (isa<VarDecl>(KeyProp))
1520 ObjectKind = Variable;
1521 else if (isa<ObjCPropertyDecl>(KeyProp))
1522 ObjectKind = Property;
1523 else if (isa<ObjCMethodDecl>(KeyProp))
1524 ObjectKind = ImplicitProperty;
1525 else if (isa<ObjCIvarDecl>(KeyProp))
1528 llvm_unreachable("Unexpected weak object kind!");
1530 // Do not warn about IBOutlet weak property receivers being set to null
1531 // since they are typically only used from the main thread.
1532 if (const ObjCPropertyDecl *Prop = dyn_cast<ObjCPropertyDecl>(KeyProp))
1533 if (Prop->hasAttr<IBOutletAttr>())
1536 // Show the first time the object was read.
1537 S.Diag(FirstRead->getLocStart(), DiagKind)
1538 << int(ObjectKind) << KeyProp << int(FunctionKind)
1539 << FirstRead->getSourceRange();
1541 // Print all the other accesses as notes.
1542 for (const auto &Use : Uses) {
1543 if (Use.getUseExpr() == FirstRead)
1545 S.Diag(Use.getUseExpr()->getLocStart(),
1546 diag::note_arc_weak_also_accessed_here)
1547 << Use.getUseExpr()->getSourceRange();
1553 class UninitValsDiagReporter : public UninitVariablesHandler {
1555 typedef SmallVector<UninitUse, 2> UsesVec;
1556 typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType;
1557 // Prefer using MapVector to DenseMap, so that iteration order will be
1558 // the same as insertion order. This is needed to obtain a deterministic
1559 // order of diagnostics when calling flushDiagnostics().
1560 typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap;
1564 UninitValsDiagReporter(Sema &S) : S(S) {}
1565 ~UninitValsDiagReporter() override { flushDiagnostics(); }
1567 MappedType &getUses(const VarDecl *vd) {
1568 MappedType &V = uses[vd];
1569 if (!V.getPointer())
1570 V.setPointer(new UsesVec());
1574 void handleUseOfUninitVariable(const VarDecl *vd,
1575 const UninitUse &use) override {
1576 getUses(vd).getPointer()->push_back(use);
1579 void handleSelfInit(const VarDecl *vd) override {
1580 getUses(vd).setInt(true);
1583 void flushDiagnostics() {
1584 for (const auto &P : uses) {
1585 const VarDecl *vd = P.first;
1586 const MappedType &V = P.second;
1588 UsesVec *vec = V.getPointer();
1589 bool hasSelfInit = V.getInt();
1591 // Specially handle the case where we have uses of an uninitialized
1592 // variable, but the root cause is an idiomatic self-init. We want
1593 // to report the diagnostic at the self-init since that is the root cause.
1594 if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
1595 DiagnoseUninitializedUse(S, vd,
1596 UninitUse(vd->getInit()->IgnoreParenCasts(),
1597 /* isAlwaysUninit */ true),
1598 /* alwaysReportSelfInit */ true);
1600 // Sort the uses by their SourceLocations. While not strictly
1601 // guaranteed to produce them in line/column order, this will provide
1602 // a stable ordering.
1603 std::sort(vec->begin(), vec->end(),
1604 [](const UninitUse &a, const UninitUse &b) {
1605 // Prefer a more confident report over a less confident one.
1606 if (a.getKind() != b.getKind())
1607 return a.getKind() > b.getKind();
1608 return a.getUser()->getLocStart() < b.getUser()->getLocStart();
1611 for (const auto &U : *vec) {
1612 // If we have self-init, downgrade all uses to 'may be uninitialized'.
1613 UninitUse Use = hasSelfInit ? UninitUse(U.getUser(), false) : U;
1615 if (DiagnoseUninitializedUse(S, vd, Use))
1616 // Skip further diagnostics for this variable. We try to warn only
1617 // on the first point at which a variable is used uninitialized.
1622 // Release the uses vector.
1630 static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
1631 return std::any_of(vec->begin(), vec->end(), [](const UninitUse &U) {
1632 return U.getKind() == UninitUse::Always ||
1633 U.getKind() == UninitUse::AfterCall ||
1634 U.getKind() == UninitUse::AfterDecl;
1638 } // anonymous namespace
1642 typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
1643 typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
1644 typedef std::list<DelayedDiag> DiagList;
1646 struct SortDiagBySourceLocation {
1648 SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
1650 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1651 // Although this call will be slow, this is only called when outputting
1652 // multiple warnings.
1653 return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
1656 } // anonymous namespace
1657 } // namespace clang
1659 //===----------------------------------------------------------------------===//
1661 //===----------------------------------------------------------------------===//
1663 namespace threadSafety {
1665 class ThreadSafetyReporter : public clang::threadSafety::ThreadSafetyHandler {
1668 SourceLocation FunLocation, FunEndLocation;
1670 const FunctionDecl *CurrentFunction;
1673 OptionalNotes getNotes() const {
1674 if (Verbose && CurrentFunction) {
1675 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
1676 S.PDiag(diag::note_thread_warning_in_fun)
1677 << CurrentFunction->getNameAsString());
1678 return OptionalNotes(1, FNote);
1680 return OptionalNotes();
1683 OptionalNotes getNotes(const PartialDiagnosticAt &Note) const {
1684 OptionalNotes ONS(1, Note);
1685 if (Verbose && CurrentFunction) {
1686 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
1687 S.PDiag(diag::note_thread_warning_in_fun)
1688 << CurrentFunction->getNameAsString());
1689 ONS.push_back(std::move(FNote));
1694 OptionalNotes getNotes(const PartialDiagnosticAt &Note1,
1695 const PartialDiagnosticAt &Note2) const {
1697 ONS.push_back(Note1);
1698 ONS.push_back(Note2);
1699 if (Verbose && CurrentFunction) {
1700 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
1701 S.PDiag(diag::note_thread_warning_in_fun)
1702 << CurrentFunction->getNameAsString());
1703 ONS.push_back(std::move(FNote));
1709 void warnLockMismatch(unsigned DiagID, StringRef Kind, Name LockName,
1710 SourceLocation Loc) {
1711 // Gracefully handle rare cases when the analysis can't get a more
1712 // precise source location.
1715 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind << LockName);
1716 Warnings.emplace_back(std::move(Warning), getNotes());
1720 ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
1721 : S(S), FunLocation(FL), FunEndLocation(FEL),
1722 CurrentFunction(nullptr), Verbose(false) {}
1724 void setVerbose(bool b) { Verbose = b; }
1726 /// \brief Emit all buffered diagnostics in order of sourcelocation.
1727 /// We need to output diagnostics produced while iterating through
1728 /// the lockset in deterministic order, so this function orders diagnostics
1729 /// and outputs them.
1730 void emitDiagnostics() {
1731 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
1732 for (const auto &Diag : Warnings) {
1733 S.Diag(Diag.first.first, Diag.first.second);
1734 for (const auto &Note : Diag.second)
1735 S.Diag(Note.first, Note.second);
1739 void handleInvalidLockExp(StringRef Kind, SourceLocation Loc) override {
1740 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_cannot_resolve_lock)
1742 Warnings.emplace_back(std::move(Warning), getNotes());
1745 void handleUnmatchedUnlock(StringRef Kind, Name LockName,
1746 SourceLocation Loc) override {
1747 warnLockMismatch(diag::warn_unlock_but_no_lock, Kind, LockName, Loc);
1750 void handleIncorrectUnlockKind(StringRef Kind, Name LockName,
1751 LockKind Expected, LockKind Received,
1752 SourceLocation Loc) override {
1753 if (Loc.isInvalid())
1755 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_unlock_kind_mismatch)
1756 << Kind << LockName << Received
1758 Warnings.emplace_back(std::move(Warning), getNotes());
1761 void handleDoubleLock(StringRef Kind, Name LockName, SourceLocation Loc) override {
1762 warnLockMismatch(diag::warn_double_lock, Kind, LockName, Loc);
1765 void handleMutexHeldEndOfScope(StringRef Kind, Name LockName,
1766 SourceLocation LocLocked,
1767 SourceLocation LocEndOfScope,
1768 LockErrorKind LEK) override {
1769 unsigned DiagID = 0;
1771 case LEK_LockedSomePredecessors:
1772 DiagID = diag::warn_lock_some_predecessors;
1774 case LEK_LockedSomeLoopIterations:
1775 DiagID = diag::warn_expecting_lock_held_on_loop;
1777 case LEK_LockedAtEndOfFunction:
1778 DiagID = diag::warn_no_unlock;
1780 case LEK_NotLockedAtEndOfFunction:
1781 DiagID = diag::warn_expecting_locked;
1784 if (LocEndOfScope.isInvalid())
1785 LocEndOfScope = FunEndLocation;
1787 PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << Kind
1789 if (LocLocked.isValid()) {
1790 PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here)
1792 Warnings.emplace_back(std::move(Warning), getNotes(Note));
1795 Warnings.emplace_back(std::move(Warning), getNotes());
1798 void handleExclusiveAndShared(StringRef Kind, Name LockName,
1799 SourceLocation Loc1,
1800 SourceLocation Loc2) override {
1801 PartialDiagnosticAt Warning(Loc1,
1802 S.PDiag(diag::warn_lock_exclusive_and_shared)
1803 << Kind << LockName);
1804 PartialDiagnosticAt Note(Loc2, S.PDiag(diag::note_lock_exclusive_and_shared)
1805 << Kind << LockName);
1806 Warnings.emplace_back(std::move(Warning), getNotes(Note));
1809 void handleNoMutexHeld(StringRef Kind, const NamedDecl *D,
1810 ProtectedOperationKind POK, AccessKind AK,
1811 SourceLocation Loc) override {
1812 assert((POK == POK_VarAccess || POK == POK_VarDereference) &&
1813 "Only works for variables");
1814 unsigned DiagID = POK == POK_VarAccess?
1815 diag::warn_variable_requires_any_lock:
1816 diag::warn_var_deref_requires_any_lock;
1817 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
1818 << D->getNameAsString() << getLockKindFromAccessKind(AK));
1819 Warnings.emplace_back(std::move(Warning), getNotes());
1822 void handleMutexNotHeld(StringRef Kind, const NamedDecl *D,
1823 ProtectedOperationKind POK, Name LockName,
1824 LockKind LK, SourceLocation Loc,
1825 Name *PossibleMatch) override {
1826 unsigned DiagID = 0;
1827 if (PossibleMatch) {
1830 DiagID = diag::warn_variable_requires_lock_precise;
1832 case POK_VarDereference:
1833 DiagID = diag::warn_var_deref_requires_lock_precise;
1835 case POK_FunctionCall:
1836 DiagID = diag::warn_fun_requires_lock_precise;
1839 DiagID = diag::warn_guarded_pass_by_reference;
1841 case POK_PtPassByRef:
1842 DiagID = diag::warn_pt_guarded_pass_by_reference;
1845 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1846 << D->getNameAsString()
1848 PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
1850 if (Verbose && POK == POK_VarAccess) {
1851 PartialDiagnosticAt VNote(D->getLocation(),
1852 S.PDiag(diag::note_guarded_by_declared_here)
1853 << D->getNameAsString());
1854 Warnings.emplace_back(std::move(Warning), getNotes(Note, VNote));
1856 Warnings.emplace_back(std::move(Warning), getNotes(Note));
1860 DiagID = diag::warn_variable_requires_lock;
1862 case POK_VarDereference:
1863 DiagID = diag::warn_var_deref_requires_lock;
1865 case POK_FunctionCall:
1866 DiagID = diag::warn_fun_requires_lock;
1869 DiagID = diag::warn_guarded_pass_by_reference;
1871 case POK_PtPassByRef:
1872 DiagID = diag::warn_pt_guarded_pass_by_reference;
1875 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1876 << D->getNameAsString()
1878 if (Verbose && POK == POK_VarAccess) {
1879 PartialDiagnosticAt Note(D->getLocation(),
1880 S.PDiag(diag::note_guarded_by_declared_here)
1881 << D->getNameAsString());
1882 Warnings.emplace_back(std::move(Warning), getNotes(Note));
1884 Warnings.emplace_back(std::move(Warning), getNotes());
1888 void handleNegativeNotHeld(StringRef Kind, Name LockName, Name Neg,
1889 SourceLocation Loc) override {
1890 PartialDiagnosticAt Warning(Loc,
1891 S.PDiag(diag::warn_acquire_requires_negative_cap)
1892 << Kind << LockName << Neg);
1893 Warnings.emplace_back(std::move(Warning), getNotes());
1896 void handleFunExcludesLock(StringRef Kind, Name FunName, Name LockName,
1897 SourceLocation Loc) override {
1898 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_fun_excludes_mutex)
1899 << Kind << FunName << LockName);
1900 Warnings.emplace_back(std::move(Warning), getNotes());
1903 void handleLockAcquiredBefore(StringRef Kind, Name L1Name, Name L2Name,
1904 SourceLocation Loc) override {
1905 PartialDiagnosticAt Warning(Loc,
1906 S.PDiag(diag::warn_acquired_before) << Kind << L1Name << L2Name);
1907 Warnings.emplace_back(std::move(Warning), getNotes());
1910 void handleBeforeAfterCycle(Name L1Name, SourceLocation Loc) override {
1911 PartialDiagnosticAt Warning(Loc,
1912 S.PDiag(diag::warn_acquired_before_after_cycle) << L1Name);
1913 Warnings.emplace_back(std::move(Warning), getNotes());
1916 void enterFunction(const FunctionDecl* FD) override {
1917 CurrentFunction = FD;
1920 void leaveFunction(const FunctionDecl* FD) override {
1921 CurrentFunction = nullptr;
1924 } // anonymous namespace
1925 } // namespace threadSafety
1926 } // namespace clang
1928 //===----------------------------------------------------------------------===//
1930 //===----------------------------------------------------------------------===//
1933 namespace consumed {
1935 class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase {
1942 ConsumedWarningsHandler(Sema &S) : S(S) {}
1944 void emitDiagnostics() override {
1945 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
1946 for (const auto &Diag : Warnings) {
1947 S.Diag(Diag.first.first, Diag.first.second);
1948 for (const auto &Note : Diag.second)
1949 S.Diag(Note.first, Note.second);
1953 void warnLoopStateMismatch(SourceLocation Loc,
1954 StringRef VariableName) override {
1955 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_loop_state_mismatch) <<
1958 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1961 void warnParamReturnTypestateMismatch(SourceLocation Loc,
1962 StringRef VariableName,
1963 StringRef ExpectedState,
1964 StringRef ObservedState) override {
1966 PartialDiagnosticAt Warning(Loc, S.PDiag(
1967 diag::warn_param_return_typestate_mismatch) << VariableName <<
1968 ExpectedState << ObservedState);
1970 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1973 void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
1974 StringRef ObservedState) override {
1976 PartialDiagnosticAt Warning(Loc, S.PDiag(
1977 diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState);
1979 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1982 void warnReturnTypestateForUnconsumableType(SourceLocation Loc,
1983 StringRef TypeName) override {
1984 PartialDiagnosticAt Warning(Loc, S.PDiag(
1985 diag::warn_return_typestate_for_unconsumable_type) << TypeName);
1987 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1990 void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
1991 StringRef ObservedState) override {
1993 PartialDiagnosticAt Warning(Loc, S.PDiag(
1994 diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState);
1996 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1999 void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State,
2000 SourceLocation Loc) override {
2002 PartialDiagnosticAt Warning(Loc, S.PDiag(
2003 diag::warn_use_of_temp_in_invalid_state) << MethodName << State);
2005 Warnings.emplace_back(std::move(Warning), OptionalNotes());
2008 void warnUseInInvalidState(StringRef MethodName, StringRef VariableName,
2009 StringRef State, SourceLocation Loc) override {
2011 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_invalid_state) <<
2012 MethodName << VariableName << State);
2014 Warnings.emplace_back(std::move(Warning), OptionalNotes());
2017 } // anonymous namespace
2018 } // namespace consumed
2019 } // namespace clang
2021 //===----------------------------------------------------------------------===//
2022 // AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
2023 // warnings on a function, method, or block.
2024 //===----------------------------------------------------------------------===//
2026 clang::sema::AnalysisBasedWarnings::Policy::Policy() {
2027 enableCheckFallThrough = 1;
2028 enableCheckUnreachable = 0;
2029 enableThreadSafetyAnalysis = 0;
2030 enableConsumedAnalysis = 0;
2033 static unsigned isEnabled(DiagnosticsEngine &D, unsigned diag) {
2034 return (unsigned)!D.isIgnored(diag, SourceLocation());
2037 clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
2039 NumFunctionsAnalyzed(0),
2040 NumFunctionsWithBadCFGs(0),
2042 MaxCFGBlocksPerFunction(0),
2043 NumUninitAnalysisFunctions(0),
2044 NumUninitAnalysisVariables(0),
2045 MaxUninitAnalysisVariablesPerFunction(0),
2046 NumUninitAnalysisBlockVisits(0),
2047 MaxUninitAnalysisBlockVisitsPerFunction(0) {
2049 using namespace diag;
2050 DiagnosticsEngine &D = S.getDiagnostics();
2052 DefaultPolicy.enableCheckUnreachable =
2053 isEnabled(D, warn_unreachable) ||
2054 isEnabled(D, warn_unreachable_break) ||
2055 isEnabled(D, warn_unreachable_return) ||
2056 isEnabled(D, warn_unreachable_loop_increment);
2058 DefaultPolicy.enableThreadSafetyAnalysis =
2059 isEnabled(D, warn_double_lock);
2061 DefaultPolicy.enableConsumedAnalysis =
2062 isEnabled(D, warn_use_in_invalid_state);
2065 static void flushDiagnostics(Sema &S, const sema::FunctionScopeInfo *fscope) {
2066 for (const auto &D : fscope->PossiblyUnreachableDiags)
2067 S.Diag(D.Loc, D.PD);
2071 AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
2072 sema::FunctionScopeInfo *fscope,
2073 const Decl *D, const BlockExpr *blkExpr) {
2075 // We avoid doing analysis-based warnings when there are errors for
2077 // (1) The CFGs often can't be constructed (if the body is invalid), so
2078 // don't bother trying.
2079 // (2) The code already has problems; running the analysis just takes more
2081 DiagnosticsEngine &Diags = S.getDiagnostics();
2083 // Do not do any analysis if we are going to just ignore them.
2084 if (Diags.getIgnoreAllWarnings() ||
2085 (Diags.getSuppressSystemWarnings() &&
2086 S.SourceMgr.isInSystemHeader(D->getLocation())))
2089 // For code in dependent contexts, we'll do this at instantiation time.
2090 if (cast<DeclContext>(D)->isDependentContext())
2093 if (Diags.hasUncompilableErrorOccurred()) {
2094 // Flush out any possibly unreachable diagnostics.
2095 flushDiagnostics(S, fscope);
2099 const Stmt *Body = D->getBody();
2102 // Construct the analysis context with the specified CFG build options.
2103 AnalysisDeclContext AC(/* AnalysisDeclContextManager */ nullptr, D);
2105 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
2106 // explosion for destructors that can result and the compile time hit.
2107 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
2108 AC.getCFGBuildOptions().AddEHEdges = false;
2109 AC.getCFGBuildOptions().AddInitializers = true;
2110 AC.getCFGBuildOptions().AddImplicitDtors = true;
2111 AC.getCFGBuildOptions().AddTemporaryDtors = true;
2112 AC.getCFGBuildOptions().AddCXXNewAllocator = false;
2113 AC.getCFGBuildOptions().AddCXXDefaultInitExprInCtors = true;
2115 // Force that certain expressions appear as CFGElements in the CFG. This
2116 // is used to speed up various analyses.
2117 // FIXME: This isn't the right factoring. This is here for initial
2118 // prototyping, but we need a way for analyses to say what expressions they
2119 // expect to always be CFGElements and then fill in the BuildOptions
2120 // appropriately. This is essentially a layering violation.
2121 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis ||
2122 P.enableConsumedAnalysis) {
2123 // Unreachable code analysis and thread safety require a linearized CFG.
2124 AC.getCFGBuildOptions().setAllAlwaysAdd();
2127 AC.getCFGBuildOptions()
2128 .setAlwaysAdd(Stmt::BinaryOperatorClass)
2129 .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
2130 .setAlwaysAdd(Stmt::BlockExprClass)
2131 .setAlwaysAdd(Stmt::CStyleCastExprClass)
2132 .setAlwaysAdd(Stmt::DeclRefExprClass)
2133 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
2134 .setAlwaysAdd(Stmt::UnaryOperatorClass)
2135 .setAlwaysAdd(Stmt::AttributedStmtClass);
2138 // Install the logical handler for -Wtautological-overlap-compare
2139 std::unique_ptr<LogicalErrorHandler> LEH;
2140 if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
2141 D->getLocStart())) {
2142 LEH.reset(new LogicalErrorHandler(S));
2143 AC.getCFGBuildOptions().Observer = LEH.get();
2146 // Emit delayed diagnostics.
2147 if (!fscope->PossiblyUnreachableDiags.empty()) {
2148 bool analyzed = false;
2150 // Register the expressions with the CFGBuilder.
2151 for (const auto &D : fscope->PossiblyUnreachableDiags) {
2153 AC.registerForcedBlockExpression(D.stmt);
2158 for (const auto &D : fscope->PossiblyUnreachableDiags) {
2159 bool processed = false;
2161 const CFGBlock *block = AC.getBlockForRegisteredExpression(D.stmt);
2162 CFGReverseBlockReachabilityAnalysis *cra =
2163 AC.getCFGReachablityAnalysis();
2164 // FIXME: We should be able to assert that block is non-null, but
2165 // the CFG analysis can skip potentially-evaluated expressions in
2166 // edge cases; see test/Sema/vla-2.c.
2168 // Can this block be reached from the entrance?
2169 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
2170 S.Diag(D.Loc, D.PD);
2175 // Emit the warning anyway if we cannot map to a basic block.
2176 S.Diag(D.Loc, D.PD);
2182 flushDiagnostics(S, fscope);
2185 // Warning: check missing 'return'
2186 if (P.enableCheckFallThrough) {
2187 const CheckFallThroughDiagnostics &CD =
2189 ? CheckFallThroughDiagnostics::MakeForBlock()
2190 : (isa<CXXMethodDecl>(D) &&
2191 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
2192 cast<CXXMethodDecl>(D)->getParent()->isLambda())
2193 ? CheckFallThroughDiagnostics::MakeForLambda()
2194 : (fscope->isCoroutine()
2195 ? CheckFallThroughDiagnostics::MakeForCoroutine(D)
2196 : CheckFallThroughDiagnostics::MakeForFunction(D)));
2197 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
2200 // Warning: check for unreachable code
2201 if (P.enableCheckUnreachable) {
2202 // Only check for unreachable code on non-template instantiations.
2203 // Different template instantiations can effectively change the control-flow
2204 // and it is very difficult to prove that a snippet of code in a template
2205 // is unreachable for all instantiations.
2206 bool isTemplateInstantiation = false;
2207 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2208 isTemplateInstantiation = Function->isTemplateInstantiation();
2209 if (!isTemplateInstantiation)
2210 CheckUnreachable(S, AC);
2213 // Check for thread safety violations
2214 if (P.enableThreadSafetyAnalysis) {
2215 SourceLocation FL = AC.getDecl()->getLocation();
2216 SourceLocation FEL = AC.getDecl()->getLocEnd();
2217 threadSafety::ThreadSafetyReporter Reporter(S, FL, FEL);
2218 if (!Diags.isIgnored(diag::warn_thread_safety_beta, D->getLocStart()))
2219 Reporter.setIssueBetaWarnings(true);
2220 if (!Diags.isIgnored(diag::warn_thread_safety_verbose, D->getLocStart()))
2221 Reporter.setVerbose(true);
2223 threadSafety::runThreadSafetyAnalysis(AC, Reporter,
2224 &S.ThreadSafetyDeclCache);
2225 Reporter.emitDiagnostics();
2228 // Check for violations of consumed properties.
2229 if (P.enableConsumedAnalysis) {
2230 consumed::ConsumedWarningsHandler WarningHandler(S);
2231 consumed::ConsumedAnalyzer Analyzer(WarningHandler);
2235 if (!Diags.isIgnored(diag::warn_uninit_var, D->getLocStart()) ||
2236 !Diags.isIgnored(diag::warn_sometimes_uninit_var, D->getLocStart()) ||
2237 !Diags.isIgnored(diag::warn_maybe_uninit_var, D->getLocStart())) {
2238 if (CFG *cfg = AC.getCFG()) {
2239 UninitValsDiagReporter reporter(S);
2240 UninitVariablesAnalysisStats stats;
2241 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
2242 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
2245 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
2246 ++NumUninitAnalysisFunctions;
2247 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
2248 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
2249 MaxUninitAnalysisVariablesPerFunction =
2250 std::max(MaxUninitAnalysisVariablesPerFunction,
2251 stats.NumVariablesAnalyzed);
2252 MaxUninitAnalysisBlockVisitsPerFunction =
2253 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
2254 stats.NumBlockVisits);
2259 bool FallThroughDiagFull =
2260 !Diags.isIgnored(diag::warn_unannotated_fallthrough, D->getLocStart());
2261 bool FallThroughDiagPerFunction = !Diags.isIgnored(
2262 diag::warn_unannotated_fallthrough_per_function, D->getLocStart());
2263 if (FallThroughDiagFull || FallThroughDiagPerFunction ||
2264 fscope->HasFallthroughStmt) {
2265 DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
2268 if (S.getLangOpts().ObjCWeak &&
2269 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, D->getLocStart()))
2270 diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
2273 // Check for infinite self-recursion in functions
2274 if (!Diags.isIgnored(diag::warn_infinite_recursive_function,
2275 D->getLocStart())) {
2276 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2277 checkRecursiveFunction(S, FD, Body, AC);
2281 // Check for throw out of non-throwing function.
2282 if (!Diags.isIgnored(diag::warn_throw_in_noexcept_func, D->getLocStart()))
2283 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2284 if (S.getLangOpts().CPlusPlus && isNoexcept(FD))
2285 checkThrowInNonThrowingFunc(S, FD, AC);
2287 // If none of the previous checks caused a CFG build, trigger one here
2288 // for -Wtautological-overlap-compare
2289 if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
2290 D->getLocStart())) {
2294 // Collect statistics about the CFG if it was built.
2295 if (S.CollectStats && AC.isCFGBuilt()) {
2296 ++NumFunctionsAnalyzed;
2297 if (CFG *cfg = AC.getCFG()) {
2298 // If we successfully built a CFG for this context, record some more
2299 // detail information about it.
2300 NumCFGBlocks += cfg->getNumBlockIDs();
2301 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
2302 cfg->getNumBlockIDs());
2304 ++NumFunctionsWithBadCFGs;
2309 void clang::sema::AnalysisBasedWarnings::PrintStats() const {
2310 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
2312 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
2313 unsigned AvgCFGBlocksPerFunction =
2314 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
2315 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
2316 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
2317 << " " << NumCFGBlocks << " CFG blocks built.\n"
2318 << " " << AvgCFGBlocksPerFunction
2319 << " average CFG blocks per function.\n"
2320 << " " << MaxCFGBlocksPerFunction
2321 << " max CFG blocks per function.\n";
2323 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
2324 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
2325 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
2326 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
2327 llvm::errs() << NumUninitAnalysisFunctions
2328 << " functions analyzed for uninitialiazed variables\n"
2329 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
2330 << " " << AvgUninitVariablesPerFunction
2331 << " average variables per function.\n"
2332 << " " << MaxUninitAnalysisVariablesPerFunction
2333 << " max variables per function.\n"
2334 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
2335 << " " << AvgUninitBlockVisitsPerFunction
2336 << " average block visits per function.\n"
2337 << " " << MaxUninitAnalysisBlockVisitsPerFunction
2338 << " max block visits per function.\n";