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/AnalysisContext.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 *ThrowType = nullptr;
293 if (Throw->getSubExpr())
294 ThrowType = Throw->getSubExpr()->getType().getTypePtrOrNull();
297 const Type *CaughtType = Catch->getCaughtType().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.back();
367 unsigned ID = CurBlock->getBlockID();
368 ThrowState CurState = States[ID];
369 if (CurState == FoundPathWithNoThrowOutFunction) {
373 if (doesThrowEscapePath(*CurBlock, OpLoc))
374 CurState = FoundPathForThrow;
377 // Loop over successor blocks and add them to the Stack if their state
379 for (const auto &I : CurBlock->succs())
380 if (I.isReachable()) {
381 unsigned NextID = I->getBlockID();
382 if (NextID == ExitID && CurState == FoundPathForThrow) {
383 States[NextID] = CurState;
384 } else if (States[NextID] < CurState) {
385 States[NextID] = CurState;
390 // Return true if the exit node is reachable, and only reachable through
391 // a throw expression.
392 return States[ExitID] == FoundPathForThrow;
395 static void EmitDiagForCXXThrowInNonThrowingFunc(Sema &S, SourceLocation OpLoc,
396 const FunctionDecl *FD) {
397 if (!S.getSourceManager().isInSystemHeader(OpLoc) &&
398 FD->getTypeSourceInfo()) {
399 S.Diag(OpLoc, diag::warn_throw_in_noexcept_func) << FD;
400 if (S.getLangOpts().CPlusPlus11 &&
401 (isa<CXXDestructorDecl>(FD) ||
402 FD->getDeclName().getCXXOverloadedOperator() == OO_Delete ||
403 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_Delete)) {
404 if (const auto *Ty = FD->getTypeSourceInfo()->getType()->
405 getAs<FunctionProtoType>())
406 S.Diag(FD->getLocation(), diag::note_throw_in_dtor)
407 << !isa<CXXDestructorDecl>(FD) << !Ty->hasExceptionSpec()
408 << FD->getExceptionSpecSourceRange();
410 S.Diag(FD->getLocation(), diag::note_throw_in_function)
411 << FD->getExceptionSpecSourceRange();
415 static void checkThrowInNonThrowingFunc(Sema &S, const FunctionDecl *FD,
416 AnalysisDeclContext &AC) {
417 CFG *BodyCFG = AC.getCFG();
420 if (BodyCFG->getExit().pred_empty())
422 SourceLocation OpLoc;
423 if (hasThrowOutNonThrowingFunc(OpLoc, BodyCFG))
424 EmitDiagForCXXThrowInNonThrowingFunc(S, OpLoc, FD);
427 static bool isNoexcept(const FunctionDecl *FD) {
428 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
429 if (FPT->isNothrow(FD->getASTContext()))
434 //===----------------------------------------------------------------------===//
435 // Check for missing return value.
436 //===----------------------------------------------------------------------===//
438 enum ControlFlowKind {
443 NeverFallThroughOrReturn
446 /// CheckFallThrough - Check that we don't fall off the end of a
447 /// Statement that should return a value.
449 /// \returns AlwaysFallThrough iff we always fall off the end of the statement,
450 /// MaybeFallThrough iff we might or might not fall off the end,
451 /// NeverFallThroughOrReturn iff we never fall off the end of the statement or
452 /// return. We assume NeverFallThrough iff we never fall off the end of the
453 /// statement but we may return. We assume that functions not marked noreturn
455 static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
456 CFG *cfg = AC.getCFG();
457 if (!cfg) return UnknownFallThrough;
459 // The CFG leaves in dead things, and we don't want the dead code paths to
460 // confuse us, so we mark all live things first.
461 llvm::BitVector live(cfg->getNumBlockIDs());
462 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
465 bool AddEHEdges = AC.getAddEHEdges();
466 if (!AddEHEdges && count != cfg->getNumBlockIDs())
467 // When there are things remaining dead, and we didn't add EH edges
468 // from CallExprs to the catch clauses, we have to go back and
469 // mark them as live.
470 for (const auto *B : *cfg) {
471 if (!live[B->getBlockID()]) {
472 if (B->pred_begin() == B->pred_end()) {
473 if (B->getTerminator() && isa<CXXTryStmt>(B->getTerminator()))
474 // When not adding EH edges from calls, catch clauses
475 // can otherwise seem dead. Avoid noting them as dead.
476 count += reachable_code::ScanReachableFromBlock(B, live);
482 // Now we know what is live, we check the live precessors of the exit block
483 // and look for fall through paths, being careful to ignore normal returns,
484 // and exceptional paths.
485 bool HasLiveReturn = false;
486 bool HasFakeEdge = false;
487 bool HasPlainEdge = false;
488 bool HasAbnormalEdge = false;
490 // Ignore default cases that aren't likely to be reachable because all
491 // enums in a switch(X) have explicit case statements.
492 CFGBlock::FilterOptions FO;
493 FO.IgnoreDefaultsWithCoveredEnums = 1;
495 for (CFGBlock::filtered_pred_iterator
496 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
497 const CFGBlock& B = **I;
498 if (!live[B.getBlockID()])
501 // Skip blocks which contain an element marked as no-return. They don't
502 // represent actually viable edges into the exit block, so mark them as
504 if (B.hasNoReturnElement()) {
505 HasAbnormalEdge = true;
509 // Destructors can appear after the 'return' in the CFG. This is
510 // normal. We need to look pass the destructors for the return
511 // statement (if it exists).
512 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
514 for ( ; ri != re ; ++ri)
515 if (ri->getAs<CFGStmt>())
518 // No more CFGElements in the block?
520 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
521 HasAbnormalEdge = true;
524 // A labeled empty statement, or the entry block...
529 CFGStmt CS = ri->castAs<CFGStmt>();
530 const Stmt *S = CS.getStmt();
531 if (isa<ReturnStmt>(S) || isa<CoreturnStmt>(S)) {
532 HasLiveReturn = true;
535 if (isa<ObjCAtThrowStmt>(S)) {
539 if (isa<CXXThrowExpr>(S)) {
543 if (isa<MSAsmStmt>(S)) {
544 // TODO: Verify this is correct.
546 HasLiveReturn = true;
549 if (isa<CXXTryStmt>(S)) {
550 HasAbnormalEdge = true;
553 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
555 HasAbnormalEdge = true;
563 return NeverFallThrough;
564 return NeverFallThroughOrReturn;
566 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
567 return MaybeFallThrough;
568 // This says AlwaysFallThrough for calls to functions that are not marked
569 // noreturn, that don't return. If people would like this warning to be more
570 // accurate, such functions should be marked as noreturn.
571 return AlwaysFallThrough;
576 struct CheckFallThroughDiagnostics {
577 unsigned diag_MaybeFallThrough_HasNoReturn;
578 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
579 unsigned diag_AlwaysFallThrough_HasNoReturn;
580 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
581 unsigned diag_NeverFallThroughOrReturn;
582 enum { Function, Block, Lambda, Coroutine } funMode;
583 SourceLocation FuncLoc;
585 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
586 CheckFallThroughDiagnostics D;
587 D.FuncLoc = Func->getLocation();
588 D.diag_MaybeFallThrough_HasNoReturn =
589 diag::warn_falloff_noreturn_function;
590 D.diag_MaybeFallThrough_ReturnsNonVoid =
591 diag::warn_maybe_falloff_nonvoid_function;
592 D.diag_AlwaysFallThrough_HasNoReturn =
593 diag::warn_falloff_noreturn_function;
594 D.diag_AlwaysFallThrough_ReturnsNonVoid =
595 diag::warn_falloff_nonvoid_function;
597 // Don't suggest that virtual functions be marked "noreturn", since they
598 // might be overridden by non-noreturn functions.
599 bool isVirtualMethod = false;
600 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
601 isVirtualMethod = Method->isVirtual();
603 // Don't suggest that template instantiations be marked "noreturn"
604 bool isTemplateInstantiation = false;
605 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
606 isTemplateInstantiation = Function->isTemplateInstantiation();
608 if (!isVirtualMethod && !isTemplateInstantiation)
609 D.diag_NeverFallThroughOrReturn =
610 diag::warn_suggest_noreturn_function;
612 D.diag_NeverFallThroughOrReturn = 0;
614 D.funMode = Function;
618 static CheckFallThroughDiagnostics MakeForCoroutine(const Decl *Func) {
619 CheckFallThroughDiagnostics D;
620 D.FuncLoc = Func->getLocation();
621 D.diag_MaybeFallThrough_HasNoReturn = 0;
622 D.diag_MaybeFallThrough_ReturnsNonVoid =
623 diag::warn_maybe_falloff_nonvoid_coroutine;
624 D.diag_AlwaysFallThrough_HasNoReturn = 0;
625 D.diag_AlwaysFallThrough_ReturnsNonVoid =
626 diag::warn_falloff_nonvoid_coroutine;
627 D.funMode = Coroutine;
631 static CheckFallThroughDiagnostics MakeForBlock() {
632 CheckFallThroughDiagnostics D;
633 D.diag_MaybeFallThrough_HasNoReturn =
634 diag::err_noreturn_block_has_return_expr;
635 D.diag_MaybeFallThrough_ReturnsNonVoid =
636 diag::err_maybe_falloff_nonvoid_block;
637 D.diag_AlwaysFallThrough_HasNoReturn =
638 diag::err_noreturn_block_has_return_expr;
639 D.diag_AlwaysFallThrough_ReturnsNonVoid =
640 diag::err_falloff_nonvoid_block;
641 D.diag_NeverFallThroughOrReturn = 0;
646 static CheckFallThroughDiagnostics MakeForLambda() {
647 CheckFallThroughDiagnostics D;
648 D.diag_MaybeFallThrough_HasNoReturn =
649 diag::err_noreturn_lambda_has_return_expr;
650 D.diag_MaybeFallThrough_ReturnsNonVoid =
651 diag::warn_maybe_falloff_nonvoid_lambda;
652 D.diag_AlwaysFallThrough_HasNoReturn =
653 diag::err_noreturn_lambda_has_return_expr;
654 D.diag_AlwaysFallThrough_ReturnsNonVoid =
655 diag::warn_falloff_nonvoid_lambda;
656 D.diag_NeverFallThroughOrReturn = 0;
661 bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
662 bool HasNoReturn) const {
663 if (funMode == Function) {
664 return (ReturnsVoid ||
665 D.isIgnored(diag::warn_maybe_falloff_nonvoid_function,
668 D.isIgnored(diag::warn_noreturn_function_has_return_expr,
671 D.isIgnored(diag::warn_suggest_noreturn_block, FuncLoc));
673 if (funMode == Coroutine) {
674 return (ReturnsVoid ||
675 D.isIgnored(diag::warn_maybe_falloff_nonvoid_function, FuncLoc) ||
676 D.isIgnored(diag::warn_maybe_falloff_nonvoid_coroutine,
680 // For blocks / lambdas.
681 return ReturnsVoid && !HasNoReturn;
685 } // anonymous namespace
687 /// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
688 /// function that should return a value. Check that we don't fall off the end
689 /// of a noreturn function. We assume that functions and blocks not marked
690 /// noreturn will return.
691 static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
692 const BlockExpr *blkExpr,
693 const CheckFallThroughDiagnostics& CD,
694 AnalysisDeclContext &AC) {
696 bool ReturnsVoid = false;
697 bool HasNoReturn = false;
698 bool IsCoroutine = S.getCurFunction() && S.getCurFunction()->isCoroutine();
700 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
701 if (const auto *CBody = dyn_cast<CoroutineBodyStmt>(Body))
702 ReturnsVoid = CBody->getFallthroughHandler() != nullptr;
704 ReturnsVoid = FD->getReturnType()->isVoidType();
705 HasNoReturn = FD->isNoReturn();
707 else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
708 ReturnsVoid = MD->getReturnType()->isVoidType();
709 HasNoReturn = MD->hasAttr<NoReturnAttr>();
711 else if (isa<BlockDecl>(D)) {
712 QualType BlockTy = blkExpr->getType();
713 if (const FunctionType *FT =
714 BlockTy->getPointeeType()->getAs<FunctionType>()) {
715 if (FT->getReturnType()->isVoidType())
717 if (FT->getNoReturnAttr())
722 DiagnosticsEngine &Diags = S.getDiagnostics();
724 // Short circuit for compilation speed.
725 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
727 SourceLocation LBrace = Body->getLocStart(), RBrace = Body->getLocEnd();
728 auto EmitDiag = [&](SourceLocation Loc, unsigned DiagID) {
730 S.Diag(Loc, DiagID) << S.getCurFunction()->CoroutinePromise->getType();
734 // Either in a function body compound statement, or a function-try-block.
735 switch (CheckFallThrough(AC)) {
736 case UnknownFallThrough:
739 case MaybeFallThrough:
741 EmitDiag(RBrace, CD.diag_MaybeFallThrough_HasNoReturn);
742 else if (!ReturnsVoid)
743 EmitDiag(RBrace, CD.diag_MaybeFallThrough_ReturnsNonVoid);
745 case AlwaysFallThrough:
747 EmitDiag(RBrace, CD.diag_AlwaysFallThrough_HasNoReturn);
748 else if (!ReturnsVoid)
749 EmitDiag(RBrace, CD.diag_AlwaysFallThrough_ReturnsNonVoid);
751 case NeverFallThroughOrReturn:
752 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
753 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
754 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 0 << FD;
755 } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
756 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 1 << MD;
758 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn);
762 case NeverFallThrough:
767 //===----------------------------------------------------------------------===//
769 //===----------------------------------------------------------------------===//
772 /// ContainsReference - A visitor class to search for references to
773 /// a particular declaration (the needle) within any evaluated component of an
774 /// expression (recursively).
775 class ContainsReference : public ConstEvaluatedExprVisitor<ContainsReference> {
777 const DeclRefExpr *Needle;
780 typedef ConstEvaluatedExprVisitor<ContainsReference> Inherited;
782 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
783 : Inherited(Context), FoundReference(false), Needle(Needle) {}
785 void VisitExpr(const Expr *E) {
786 // Stop evaluating if we already have a reference.
790 Inherited::VisitExpr(E);
793 void VisitDeclRefExpr(const DeclRefExpr *E) {
795 FoundReference = true;
797 Inherited::VisitDeclRefExpr(E);
800 bool doesContainReference() const { return FoundReference; }
802 } // anonymous namespace
804 static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
805 QualType VariableTy = VD->getType().getCanonicalType();
806 if (VariableTy->isBlockPointerType() &&
807 !VD->hasAttr<BlocksAttr>()) {
808 S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization)
810 << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
814 // Don't issue a fixit if there is already an initializer.
818 // Don't suggest a fixit inside macros.
819 if (VD->getLocEnd().isMacroID())
822 SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
824 // Suggest possible initialization (if any).
825 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
829 S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
830 << FixItHint::CreateInsertion(Loc, Init);
834 /// Create a fixit to remove an if-like statement, on the assumption that its
835 /// condition is CondVal.
836 static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
837 const Stmt *Else, bool CondVal,
838 FixItHint &Fixit1, FixItHint &Fixit2) {
840 // If condition is always true, remove all but the 'then'.
841 Fixit1 = FixItHint::CreateRemoval(
842 CharSourceRange::getCharRange(If->getLocStart(),
843 Then->getLocStart()));
845 SourceLocation ElseKwLoc = S.getLocForEndOfToken(Then->getLocEnd());
846 Fixit2 = FixItHint::CreateRemoval(
847 SourceRange(ElseKwLoc, Else->getLocEnd()));
850 // If condition is always false, remove all but the 'else'.
852 Fixit1 = FixItHint::CreateRemoval(
853 CharSourceRange::getCharRange(If->getLocStart(),
854 Else->getLocStart()));
856 Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
860 /// DiagUninitUse -- Helper function to produce a diagnostic for an
861 /// uninitialized use of a variable.
862 static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
863 bool IsCapturedByBlock) {
864 bool Diagnosed = false;
866 switch (Use.getKind()) {
867 case UninitUse::Always:
868 S.Diag(Use.getUser()->getLocStart(), diag::warn_uninit_var)
869 << VD->getDeclName() << IsCapturedByBlock
870 << Use.getUser()->getSourceRange();
873 case UninitUse::AfterDecl:
874 case UninitUse::AfterCall:
875 S.Diag(VD->getLocation(), diag::warn_sometimes_uninit_var)
876 << VD->getDeclName() << IsCapturedByBlock
877 << (Use.getKind() == UninitUse::AfterDecl ? 4 : 5)
878 << const_cast<DeclContext*>(VD->getLexicalDeclContext())
879 << VD->getSourceRange();
880 S.Diag(Use.getUser()->getLocStart(), diag::note_uninit_var_use)
881 << IsCapturedByBlock << Use.getUser()->getSourceRange();
884 case UninitUse::Maybe:
885 case UninitUse::Sometimes:
886 // Carry on to report sometimes-uninitialized branches, if possible,
887 // or a 'may be used uninitialized' diagnostic otherwise.
891 // Diagnose each branch which leads to a sometimes-uninitialized use.
892 for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
894 assert(Use.getKind() == UninitUse::Sometimes);
896 const Expr *User = Use.getUser();
897 const Stmt *Term = I->Terminator;
899 // Information used when building the diagnostic.
904 // FixIts to suppress the diagnostic by removing the dead condition.
905 // For all binary terminators, branch 0 is taken if the condition is true,
906 // and branch 1 is taken if the condition is false.
907 int RemoveDiagKind = -1;
908 const char *FixitStr =
909 S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
910 : (I->Output ? "1" : "0");
911 FixItHint Fixit1, Fixit2;
913 switch (Term ? Term->getStmtClass() : Stmt::DeclStmtClass) {
915 // Don't know how to report this. Just fall back to 'may be used
916 // uninitialized'. FIXME: Can this happen?
919 // "condition is true / condition is false".
920 case Stmt::IfStmtClass: {
921 const IfStmt *IS = cast<IfStmt>(Term);
924 Range = IS->getCond()->getSourceRange();
926 CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
927 I->Output, Fixit1, Fixit2);
930 case Stmt::ConditionalOperatorClass: {
931 const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
934 Range = CO->getCond()->getSourceRange();
936 CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
937 I->Output, Fixit1, Fixit2);
940 case Stmt::BinaryOperatorClass: {
941 const BinaryOperator *BO = cast<BinaryOperator>(Term);
942 if (!BO->isLogicalOp())
945 Str = BO->getOpcodeStr();
946 Range = BO->getLHS()->getSourceRange();
948 if ((BO->getOpcode() == BO_LAnd && I->Output) ||
949 (BO->getOpcode() == BO_LOr && !I->Output))
950 // true && y -> y, false || y -> y.
951 Fixit1 = FixItHint::CreateRemoval(SourceRange(BO->getLocStart(),
952 BO->getOperatorLoc()));
954 // false && y -> false, true || y -> true.
955 Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
959 // "loop is entered / loop is exited".
960 case Stmt::WhileStmtClass:
963 Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
965 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
967 case Stmt::ForStmtClass:
970 Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
973 Fixit1 = FixItHint::CreateRemoval(Range);
975 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
977 case Stmt::CXXForRangeStmtClass:
978 if (I->Output == 1) {
979 // The use occurs if a range-based for loop's body never executes.
980 // That may be impossible, and there's no syntactic fix for this,
981 // so treat it as a 'may be uninitialized' case.
986 Range = cast<CXXForRangeStmt>(Term)->getRangeInit()->getSourceRange();
989 // "condition is true / loop is exited".
990 case Stmt::DoStmtClass:
993 Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
995 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
998 // "switch case is taken".
999 case Stmt::CaseStmtClass:
1002 Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
1004 case Stmt::DefaultStmtClass:
1007 Range = cast<DefaultStmt>(Term)->getDefaultLoc();
1011 S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
1012 << VD->getDeclName() << IsCapturedByBlock << DiagKind
1013 << Str << I->Output << Range;
1014 S.Diag(User->getLocStart(), diag::note_uninit_var_use)
1015 << IsCapturedByBlock << User->getSourceRange();
1016 if (RemoveDiagKind != -1)
1017 S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
1018 << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
1024 S.Diag(Use.getUser()->getLocStart(), diag::warn_maybe_uninit_var)
1025 << VD->getDeclName() << IsCapturedByBlock
1026 << Use.getUser()->getSourceRange();
1029 /// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
1030 /// uninitialized variable. This manages the different forms of diagnostic
1031 /// emitted for particular types of uses. Returns true if the use was diagnosed
1032 /// as a warning. If a particular use is one we omit warnings for, returns
1034 static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
1035 const UninitUse &Use,
1036 bool alwaysReportSelfInit = false) {
1037 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
1038 // Inspect the initializer of the variable declaration which is
1039 // being referenced prior to its initialization. We emit
1040 // specialized diagnostics for self-initialization, and we
1041 // specifically avoid warning about self references which take the
1046 // This is used to indicate to GCC that 'x' is intentionally left
1047 // uninitialized. Proven code paths which access 'x' in
1048 // an uninitialized state after this will still warn.
1049 if (const Expr *Initializer = VD->getInit()) {
1050 if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
1053 ContainsReference CR(S.Context, DRE);
1054 CR.Visit(Initializer);
1055 if (CR.doesContainReference()) {
1056 S.Diag(DRE->getLocStart(),
1057 diag::warn_uninit_self_reference_in_init)
1058 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
1063 DiagUninitUse(S, VD, Use, false);
1065 const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
1066 if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
1067 S.Diag(BE->getLocStart(),
1068 diag::warn_uninit_byref_blockvar_captured_by_block)
1069 << VD->getDeclName();
1071 DiagUninitUse(S, VD, Use, true);
1074 // Report where the variable was declared when the use wasn't within
1075 // the initializer of that declaration & we didn't already suggest
1076 // an initialization fixit.
1077 if (!SuggestInitializationFixit(S, VD))
1078 S.Diag(VD->getLocStart(), diag::note_var_declared_here)
1079 << VD->getDeclName();
1085 class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
1087 FallthroughMapper(Sema &S)
1088 : FoundSwitchStatements(false),
1092 bool foundSwitchStatements() const { return FoundSwitchStatements; }
1094 void markFallthroughVisited(const AttributedStmt *Stmt) {
1095 bool Found = FallthroughStmts.erase(Stmt);
1100 typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
1102 const AttrStmts &getFallthroughStmts() const {
1103 return FallthroughStmts;
1106 void fillReachableBlocks(CFG *Cfg) {
1107 assert(ReachableBlocks.empty() && "ReachableBlocks already filled");
1108 std::deque<const CFGBlock *> BlockQueue;
1110 ReachableBlocks.insert(&Cfg->getEntry());
1111 BlockQueue.push_back(&Cfg->getEntry());
1112 // Mark all case blocks reachable to avoid problems with switching on
1113 // constants, covered enums, etc.
1114 // These blocks can contain fall-through annotations, and we don't want to
1115 // issue a warn_fallthrough_attr_unreachable for them.
1116 for (const auto *B : *Cfg) {
1117 const Stmt *L = B->getLabel();
1118 if (L && isa<SwitchCase>(L) && ReachableBlocks.insert(B).second)
1119 BlockQueue.push_back(B);
1122 while (!BlockQueue.empty()) {
1123 const CFGBlock *P = BlockQueue.front();
1124 BlockQueue.pop_front();
1125 for (CFGBlock::const_succ_iterator I = P->succ_begin(),
1128 if (*I && ReachableBlocks.insert(*I).second)
1129 BlockQueue.push_back(*I);
1134 bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt,
1135 bool IsTemplateInstantiation) {
1136 assert(!ReachableBlocks.empty() && "ReachableBlocks empty");
1138 int UnannotatedCnt = 0;
1141 std::deque<const CFGBlock*> BlockQueue(B.pred_begin(), B.pred_end());
1142 while (!BlockQueue.empty()) {
1143 const CFGBlock *P = BlockQueue.front();
1144 BlockQueue.pop_front();
1147 const Stmt *Term = P->getTerminator();
1148 if (Term && isa<SwitchStmt>(Term))
1149 continue; // Switch statement, good.
1151 const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
1152 if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
1153 continue; // Previous case label has no statements, good.
1155 const LabelStmt *L = dyn_cast_or_null<LabelStmt>(P->getLabel());
1156 if (L && L->getSubStmt() == B.getLabel() && P->begin() == P->end())
1157 continue; // Case label is preceded with a normal label, good.
1159 if (!ReachableBlocks.count(P)) {
1160 for (CFGBlock::const_reverse_iterator ElemIt = P->rbegin(),
1161 ElemEnd = P->rend();
1162 ElemIt != ElemEnd; ++ElemIt) {
1163 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>()) {
1164 if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
1165 // Don't issue a warning for an unreachable fallthrough
1166 // attribute in template instantiations as it may not be
1167 // unreachable in all instantiations of the template.
1168 if (!IsTemplateInstantiation)
1169 S.Diag(AS->getLocStart(),
1170 diag::warn_fallthrough_attr_unreachable);
1171 markFallthroughVisited(AS);
1175 // Don't care about other unreachable statements.
1178 // If there are no unreachable statements, this may be a special
1181 // A a; // A has a destructor.
1184 // // <<<< This place is represented by a 'hanging' CFG block.
1189 const Stmt *LastStmt = getLastStmt(*P);
1190 if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
1191 markFallthroughVisited(AS);
1193 continue; // Fallthrough annotation, good.
1196 if (!LastStmt) { // This block contains no executable statements.
1197 // Traverse its predecessors.
1198 std::copy(P->pred_begin(), P->pred_end(),
1199 std::back_inserter(BlockQueue));
1205 return !!UnannotatedCnt;
1208 // RecursiveASTVisitor setup.
1209 bool shouldWalkTypesOfTypeLocs() const { return false; }
1211 bool VisitAttributedStmt(AttributedStmt *S) {
1212 if (asFallThroughAttr(S))
1213 FallthroughStmts.insert(S);
1217 bool VisitSwitchStmt(SwitchStmt *S) {
1218 FoundSwitchStatements = true;
1222 // We don't want to traverse local type declarations. We analyze their
1223 // methods separately.
1224 bool TraverseDecl(Decl *D) { return true; }
1226 // We analyze lambda bodies separately. Skip them here.
1227 bool TraverseLambdaBody(LambdaExpr *LE) { return true; }
1231 static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
1232 if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
1233 if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
1239 static const Stmt *getLastStmt(const CFGBlock &B) {
1240 if (const Stmt *Term = B.getTerminator())
1242 for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
1244 ElemIt != ElemEnd; ++ElemIt) {
1245 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>())
1246 return CS->getStmt();
1248 // Workaround to detect a statement thrown out by CFGBuilder:
1249 // case X: {} case Y:
1250 // case X: ; case Y:
1251 if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
1252 if (!isa<SwitchCase>(SW->getSubStmt()))
1253 return SW->getSubStmt();
1258 bool FoundSwitchStatements;
1259 AttrStmts FallthroughStmts;
1261 llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks;
1263 } // anonymous namespace
1265 static StringRef getFallthroughAttrSpelling(Preprocessor &PP,
1266 SourceLocation Loc) {
1267 TokenValue FallthroughTokens[] = {
1268 tok::l_square, tok::l_square,
1269 PP.getIdentifierInfo("fallthrough"),
1270 tok::r_square, tok::r_square
1273 TokenValue ClangFallthroughTokens[] = {
1274 tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
1275 tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
1276 tok::r_square, tok::r_square
1279 bool PreferClangAttr = !PP.getLangOpts().CPlusPlus1z;
1281 StringRef MacroName;
1282 if (PreferClangAttr)
1283 MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens);
1284 if (MacroName.empty())
1285 MacroName = PP.getLastMacroWithSpelling(Loc, FallthroughTokens);
1286 if (MacroName.empty() && !PreferClangAttr)
1287 MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens);
1288 if (MacroName.empty())
1289 MacroName = PreferClangAttr ? "[[clang::fallthrough]]" : "[[fallthrough]]";
1293 static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
1295 // Only perform this analysis when using C++11. There is no good workflow
1296 // for this warning when not using C++11. There is no good way to silence
1297 // the warning (no attribute is available) unless we are using C++11's support
1298 // for generalized attributes. Once could use pragmas to silence the warning,
1299 // but as a general solution that is gross and not in the spirit of this
1302 // NOTE: This an intermediate solution. There are on-going discussions on
1303 // how to properly support this warning outside of C++11 with an annotation.
1304 if (!AC.getASTContext().getLangOpts().CPlusPlus11)
1307 FallthroughMapper FM(S);
1308 FM.TraverseStmt(AC.getBody());
1310 if (!FM.foundSwitchStatements())
1313 if (PerFunction && FM.getFallthroughStmts().empty())
1316 CFG *Cfg = AC.getCFG();
1321 FM.fillReachableBlocks(Cfg);
1323 for (const CFGBlock *B : llvm::reverse(*Cfg)) {
1324 const Stmt *Label = B->getLabel();
1326 if (!Label || !isa<SwitchCase>(Label))
1331 bool IsTemplateInstantiation = false;
1332 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(AC.getDecl()))
1333 IsTemplateInstantiation = Function->isTemplateInstantiation();
1334 if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt,
1335 IsTemplateInstantiation))
1338 S.Diag(Label->getLocStart(),
1339 PerFunction ? diag::warn_unannotated_fallthrough_per_function
1340 : diag::warn_unannotated_fallthrough);
1342 if (!AnnotatedCnt) {
1343 SourceLocation L = Label->getLocStart();
1346 if (S.getLangOpts().CPlusPlus11) {
1347 const Stmt *Term = B->getTerminator();
1348 // Skip empty cases.
1349 while (B->empty() && !Term && B->succ_size() == 1) {
1350 B = *B->succ_begin();
1351 Term = B->getTerminator();
1353 if (!(B->empty() && Term && isa<BreakStmt>(Term))) {
1354 Preprocessor &PP = S.getPreprocessor();
1355 StringRef AnnotationSpelling = getFallthroughAttrSpelling(PP, L);
1356 SmallString<64> TextToInsert(AnnotationSpelling);
1357 TextToInsert += "; ";
1358 S.Diag(L, diag::note_insert_fallthrough_fixit) <<
1359 AnnotationSpelling <<
1360 FixItHint::CreateInsertion(L, TextToInsert);
1363 S.Diag(L, diag::note_insert_break_fixit) <<
1364 FixItHint::CreateInsertion(L, "break; ");
1368 for (const auto *F : FM.getFallthroughStmts())
1369 S.Diag(F->getLocStart(), diag::err_fallthrough_attr_invalid_placement);
1372 static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
1377 switch (S->getStmtClass()) {
1378 case Stmt::ForStmtClass:
1379 case Stmt::WhileStmtClass:
1380 case Stmt::CXXForRangeStmtClass:
1381 case Stmt::ObjCForCollectionStmtClass:
1383 case Stmt::DoStmtClass: {
1384 const Expr *Cond = cast<DoStmt>(S)->getCond();
1386 if (!Cond->EvaluateAsInt(Val, Ctx))
1388 return Val.getBoolValue();
1393 } while ((S = PM.getParent(S)));
1398 static void diagnoseRepeatedUseOfWeak(Sema &S,
1399 const sema::FunctionScopeInfo *CurFn,
1401 const ParentMap &PM) {
1402 typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
1403 typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
1404 typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
1405 typedef std::pair<const Stmt *, WeakObjectUseMap::const_iterator>
1408 ASTContext &Ctx = S.getASTContext();
1410 const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
1412 // Extract all weak objects that are referenced more than once.
1413 SmallVector<StmtUsesPair, 8> UsesByStmt;
1414 for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
1416 const WeakUseVector &Uses = I->second;
1418 // Find the first read of the weak object.
1419 WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1420 for ( ; UI != UE; ++UI) {
1425 // If there were only writes to this object, don't warn.
1429 // If there was only one read, followed by any number of writes, and the
1430 // read is not within a loop, don't warn. Additionally, don't warn in a
1431 // loop if the base object is a local variable -- local variables are often
1432 // changed in loops.
1433 if (UI == Uses.begin()) {
1434 WeakUseVector::const_iterator UI2 = UI;
1435 for (++UI2; UI2 != UE; ++UI2)
1436 if (UI2->isUnsafe())
1440 if (!isInLoop(Ctx, PM, UI->getUseExpr()))
1443 const WeakObjectProfileTy &Profile = I->first;
1444 if (!Profile.isExactProfile())
1447 const NamedDecl *Base = Profile.getBase();
1449 Base = Profile.getProperty();
1450 assert(Base && "A profile always has a base or property.");
1452 if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
1453 if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
1458 UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
1461 if (UsesByStmt.empty())
1464 // Sort by first use so that we emit the warnings in a deterministic order.
1465 SourceManager &SM = S.getSourceManager();
1466 std::sort(UsesByStmt.begin(), UsesByStmt.end(),
1467 [&SM](const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
1468 return SM.isBeforeInTranslationUnit(LHS.first->getLocStart(),
1469 RHS.first->getLocStart());
1472 // Classify the current code body for better warning text.
1473 // This enum should stay in sync with the cases in
1474 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1475 // FIXME: Should we use a common classification enum and the same set of
1476 // possibilities all throughout Sema?
1484 if (isa<sema::BlockScopeInfo>(CurFn))
1485 FunctionKind = Block;
1486 else if (isa<sema::LambdaScopeInfo>(CurFn))
1487 FunctionKind = Lambda;
1488 else if (isa<ObjCMethodDecl>(D))
1489 FunctionKind = Method;
1491 FunctionKind = Function;
1493 // Iterate through the sorted problems and emit warnings for each.
1494 for (const auto &P : UsesByStmt) {
1495 const Stmt *FirstRead = P.first;
1496 const WeakObjectProfileTy &Key = P.second->first;
1497 const WeakUseVector &Uses = P.second->second;
1499 // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
1500 // may not contain enough information to determine that these are different
1501 // properties. We can only be 100% sure of a repeated use in certain cases,
1502 // and we adjust the diagnostic kind accordingly so that the less certain
1503 // case can be turned off if it is too noisy.
1505 if (Key.isExactProfile())
1506 DiagKind = diag::warn_arc_repeated_use_of_weak;
1508 DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
1510 // Classify the weak object being accessed for better warning text.
1511 // This enum should stay in sync with the cases in
1512 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1520 const NamedDecl *KeyProp = Key.getProperty();
1521 if (isa<VarDecl>(KeyProp))
1522 ObjectKind = Variable;
1523 else if (isa<ObjCPropertyDecl>(KeyProp))
1524 ObjectKind = Property;
1525 else if (isa<ObjCMethodDecl>(KeyProp))
1526 ObjectKind = ImplicitProperty;
1527 else if (isa<ObjCIvarDecl>(KeyProp))
1530 llvm_unreachable("Unexpected weak object kind!");
1532 // Do not warn about IBOutlet weak property receivers being set to null
1533 // since they are typically only used from the main thread.
1534 if (const ObjCPropertyDecl *Prop = dyn_cast<ObjCPropertyDecl>(KeyProp))
1535 if (Prop->hasAttr<IBOutletAttr>())
1538 // Show the first time the object was read.
1539 S.Diag(FirstRead->getLocStart(), DiagKind)
1540 << int(ObjectKind) << KeyProp << int(FunctionKind)
1541 << FirstRead->getSourceRange();
1543 // Print all the other accesses as notes.
1544 for (const auto &Use : Uses) {
1545 if (Use.getUseExpr() == FirstRead)
1547 S.Diag(Use.getUseExpr()->getLocStart(),
1548 diag::note_arc_weak_also_accessed_here)
1549 << Use.getUseExpr()->getSourceRange();
1555 class UninitValsDiagReporter : public UninitVariablesHandler {
1557 typedef SmallVector<UninitUse, 2> UsesVec;
1558 typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType;
1559 // Prefer using MapVector to DenseMap, so that iteration order will be
1560 // the same as insertion order. This is needed to obtain a deterministic
1561 // order of diagnostics when calling flushDiagnostics().
1562 typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap;
1566 UninitValsDiagReporter(Sema &S) : S(S) {}
1567 ~UninitValsDiagReporter() override { flushDiagnostics(); }
1569 MappedType &getUses(const VarDecl *vd) {
1570 MappedType &V = uses[vd];
1571 if (!V.getPointer())
1572 V.setPointer(new UsesVec());
1576 void handleUseOfUninitVariable(const VarDecl *vd,
1577 const UninitUse &use) override {
1578 getUses(vd).getPointer()->push_back(use);
1581 void handleSelfInit(const VarDecl *vd) override {
1582 getUses(vd).setInt(true);
1585 void flushDiagnostics() {
1586 for (const auto &P : uses) {
1587 const VarDecl *vd = P.first;
1588 const MappedType &V = P.second;
1590 UsesVec *vec = V.getPointer();
1591 bool hasSelfInit = V.getInt();
1593 // Specially handle the case where we have uses of an uninitialized
1594 // variable, but the root cause is an idiomatic self-init. We want
1595 // to report the diagnostic at the self-init since that is the root cause.
1596 if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
1597 DiagnoseUninitializedUse(S, vd,
1598 UninitUse(vd->getInit()->IgnoreParenCasts(),
1599 /* isAlwaysUninit */ true),
1600 /* alwaysReportSelfInit */ true);
1602 // Sort the uses by their SourceLocations. While not strictly
1603 // guaranteed to produce them in line/column order, this will provide
1604 // a stable ordering.
1605 std::sort(vec->begin(), vec->end(),
1606 [](const UninitUse &a, const UninitUse &b) {
1607 // Prefer a more confident report over a less confident one.
1608 if (a.getKind() != b.getKind())
1609 return a.getKind() > b.getKind();
1610 return a.getUser()->getLocStart() < b.getUser()->getLocStart();
1613 for (const auto &U : *vec) {
1614 // If we have self-init, downgrade all uses to 'may be uninitialized'.
1615 UninitUse Use = hasSelfInit ? UninitUse(U.getUser(), false) : U;
1617 if (DiagnoseUninitializedUse(S, vd, Use))
1618 // Skip further diagnostics for this variable. We try to warn only
1619 // on the first point at which a variable is used uninitialized.
1624 // Release the uses vector.
1632 static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
1633 return std::any_of(vec->begin(), vec->end(), [](const UninitUse &U) {
1634 return U.getKind() == UninitUse::Always ||
1635 U.getKind() == UninitUse::AfterCall ||
1636 U.getKind() == UninitUse::AfterDecl;
1640 } // anonymous namespace
1644 typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
1645 typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
1646 typedef std::list<DelayedDiag> DiagList;
1648 struct SortDiagBySourceLocation {
1650 SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
1652 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1653 // Although this call will be slow, this is only called when outputting
1654 // multiple warnings.
1655 return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
1658 } // anonymous namespace
1659 } // namespace clang
1661 //===----------------------------------------------------------------------===//
1663 //===----------------------------------------------------------------------===//
1665 namespace threadSafety {
1667 class ThreadSafetyReporter : public clang::threadSafety::ThreadSafetyHandler {
1670 SourceLocation FunLocation, FunEndLocation;
1672 const FunctionDecl *CurrentFunction;
1675 OptionalNotes getNotes() const {
1676 if (Verbose && CurrentFunction) {
1677 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
1678 S.PDiag(diag::note_thread_warning_in_fun)
1679 << CurrentFunction->getNameAsString());
1680 return OptionalNotes(1, FNote);
1682 return OptionalNotes();
1685 OptionalNotes getNotes(const PartialDiagnosticAt &Note) const {
1686 OptionalNotes ONS(1, Note);
1687 if (Verbose && CurrentFunction) {
1688 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
1689 S.PDiag(diag::note_thread_warning_in_fun)
1690 << CurrentFunction->getNameAsString());
1691 ONS.push_back(std::move(FNote));
1696 OptionalNotes getNotes(const PartialDiagnosticAt &Note1,
1697 const PartialDiagnosticAt &Note2) const {
1699 ONS.push_back(Note1);
1700 ONS.push_back(Note2);
1701 if (Verbose && CurrentFunction) {
1702 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
1703 S.PDiag(diag::note_thread_warning_in_fun)
1704 << CurrentFunction->getNameAsString());
1705 ONS.push_back(std::move(FNote));
1711 void warnLockMismatch(unsigned DiagID, StringRef Kind, Name LockName,
1712 SourceLocation Loc) {
1713 // Gracefully handle rare cases when the analysis can't get a more
1714 // precise source location.
1717 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind << LockName);
1718 Warnings.emplace_back(std::move(Warning), getNotes());
1722 ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
1723 : S(S), FunLocation(FL), FunEndLocation(FEL),
1724 CurrentFunction(nullptr), Verbose(false) {}
1726 void setVerbose(bool b) { Verbose = b; }
1728 /// \brief Emit all buffered diagnostics in order of sourcelocation.
1729 /// We need to output diagnostics produced while iterating through
1730 /// the lockset in deterministic order, so this function orders diagnostics
1731 /// and outputs them.
1732 void emitDiagnostics() {
1733 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
1734 for (const auto &Diag : Warnings) {
1735 S.Diag(Diag.first.first, Diag.first.second);
1736 for (const auto &Note : Diag.second)
1737 S.Diag(Note.first, Note.second);
1741 void handleInvalidLockExp(StringRef Kind, SourceLocation Loc) override {
1742 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_cannot_resolve_lock)
1744 Warnings.emplace_back(std::move(Warning), getNotes());
1747 void handleUnmatchedUnlock(StringRef Kind, Name LockName,
1748 SourceLocation Loc) override {
1749 warnLockMismatch(diag::warn_unlock_but_no_lock, Kind, LockName, Loc);
1752 void handleIncorrectUnlockKind(StringRef Kind, Name LockName,
1753 LockKind Expected, LockKind Received,
1754 SourceLocation Loc) override {
1755 if (Loc.isInvalid())
1757 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_unlock_kind_mismatch)
1758 << Kind << LockName << Received
1760 Warnings.emplace_back(std::move(Warning), getNotes());
1763 void handleDoubleLock(StringRef Kind, Name LockName, SourceLocation Loc) override {
1764 warnLockMismatch(diag::warn_double_lock, Kind, LockName, Loc);
1767 void handleMutexHeldEndOfScope(StringRef Kind, Name LockName,
1768 SourceLocation LocLocked,
1769 SourceLocation LocEndOfScope,
1770 LockErrorKind LEK) override {
1771 unsigned DiagID = 0;
1773 case LEK_LockedSomePredecessors:
1774 DiagID = diag::warn_lock_some_predecessors;
1776 case LEK_LockedSomeLoopIterations:
1777 DiagID = diag::warn_expecting_lock_held_on_loop;
1779 case LEK_LockedAtEndOfFunction:
1780 DiagID = diag::warn_no_unlock;
1782 case LEK_NotLockedAtEndOfFunction:
1783 DiagID = diag::warn_expecting_locked;
1786 if (LocEndOfScope.isInvalid())
1787 LocEndOfScope = FunEndLocation;
1789 PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << Kind
1791 if (LocLocked.isValid()) {
1792 PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here)
1794 Warnings.emplace_back(std::move(Warning), getNotes(Note));
1797 Warnings.emplace_back(std::move(Warning), getNotes());
1800 void handleExclusiveAndShared(StringRef Kind, Name LockName,
1801 SourceLocation Loc1,
1802 SourceLocation Loc2) override {
1803 PartialDiagnosticAt Warning(Loc1,
1804 S.PDiag(diag::warn_lock_exclusive_and_shared)
1805 << Kind << LockName);
1806 PartialDiagnosticAt Note(Loc2, S.PDiag(diag::note_lock_exclusive_and_shared)
1807 << Kind << LockName);
1808 Warnings.emplace_back(std::move(Warning), getNotes(Note));
1811 void handleNoMutexHeld(StringRef Kind, const NamedDecl *D,
1812 ProtectedOperationKind POK, AccessKind AK,
1813 SourceLocation Loc) override {
1814 assert((POK == POK_VarAccess || POK == POK_VarDereference) &&
1815 "Only works for variables");
1816 unsigned DiagID = POK == POK_VarAccess?
1817 diag::warn_variable_requires_any_lock:
1818 diag::warn_var_deref_requires_any_lock;
1819 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
1820 << D->getNameAsString() << getLockKindFromAccessKind(AK));
1821 Warnings.emplace_back(std::move(Warning), getNotes());
1824 void handleMutexNotHeld(StringRef Kind, const NamedDecl *D,
1825 ProtectedOperationKind POK, Name LockName,
1826 LockKind LK, SourceLocation Loc,
1827 Name *PossibleMatch) override {
1828 unsigned DiagID = 0;
1829 if (PossibleMatch) {
1832 DiagID = diag::warn_variable_requires_lock_precise;
1834 case POK_VarDereference:
1835 DiagID = diag::warn_var_deref_requires_lock_precise;
1837 case POK_FunctionCall:
1838 DiagID = diag::warn_fun_requires_lock_precise;
1841 DiagID = diag::warn_guarded_pass_by_reference;
1843 case POK_PtPassByRef:
1844 DiagID = diag::warn_pt_guarded_pass_by_reference;
1847 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1848 << D->getNameAsString()
1850 PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
1852 if (Verbose && POK == POK_VarAccess) {
1853 PartialDiagnosticAt VNote(D->getLocation(),
1854 S.PDiag(diag::note_guarded_by_declared_here)
1855 << D->getNameAsString());
1856 Warnings.emplace_back(std::move(Warning), getNotes(Note, VNote));
1858 Warnings.emplace_back(std::move(Warning), getNotes(Note));
1862 DiagID = diag::warn_variable_requires_lock;
1864 case POK_VarDereference:
1865 DiagID = diag::warn_var_deref_requires_lock;
1867 case POK_FunctionCall:
1868 DiagID = diag::warn_fun_requires_lock;
1871 DiagID = diag::warn_guarded_pass_by_reference;
1873 case POK_PtPassByRef:
1874 DiagID = diag::warn_pt_guarded_pass_by_reference;
1877 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1878 << D->getNameAsString()
1880 if (Verbose && POK == POK_VarAccess) {
1881 PartialDiagnosticAt Note(D->getLocation(),
1882 S.PDiag(diag::note_guarded_by_declared_here)
1883 << D->getNameAsString());
1884 Warnings.emplace_back(std::move(Warning), getNotes(Note));
1886 Warnings.emplace_back(std::move(Warning), getNotes());
1890 void handleNegativeNotHeld(StringRef Kind, Name LockName, Name Neg,
1891 SourceLocation Loc) override {
1892 PartialDiagnosticAt Warning(Loc,
1893 S.PDiag(diag::warn_acquire_requires_negative_cap)
1894 << Kind << LockName << Neg);
1895 Warnings.emplace_back(std::move(Warning), getNotes());
1898 void handleFunExcludesLock(StringRef Kind, Name FunName, Name LockName,
1899 SourceLocation Loc) override {
1900 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_fun_excludes_mutex)
1901 << Kind << FunName << LockName);
1902 Warnings.emplace_back(std::move(Warning), getNotes());
1905 void handleLockAcquiredBefore(StringRef Kind, Name L1Name, Name L2Name,
1906 SourceLocation Loc) override {
1907 PartialDiagnosticAt Warning(Loc,
1908 S.PDiag(diag::warn_acquired_before) << Kind << L1Name << L2Name);
1909 Warnings.emplace_back(std::move(Warning), getNotes());
1912 void handleBeforeAfterCycle(Name L1Name, SourceLocation Loc) override {
1913 PartialDiagnosticAt Warning(Loc,
1914 S.PDiag(diag::warn_acquired_before_after_cycle) << L1Name);
1915 Warnings.emplace_back(std::move(Warning), getNotes());
1918 void enterFunction(const FunctionDecl* FD) override {
1919 CurrentFunction = FD;
1922 void leaveFunction(const FunctionDecl* FD) override {
1923 CurrentFunction = nullptr;
1926 } // anonymous namespace
1927 } // namespace threadSafety
1928 } // namespace clang
1930 //===----------------------------------------------------------------------===//
1932 //===----------------------------------------------------------------------===//
1935 namespace consumed {
1937 class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase {
1944 ConsumedWarningsHandler(Sema &S) : S(S) {}
1946 void emitDiagnostics() override {
1947 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
1948 for (const auto &Diag : Warnings) {
1949 S.Diag(Diag.first.first, Diag.first.second);
1950 for (const auto &Note : Diag.second)
1951 S.Diag(Note.first, Note.second);
1955 void warnLoopStateMismatch(SourceLocation Loc,
1956 StringRef VariableName) override {
1957 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_loop_state_mismatch) <<
1960 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1963 void warnParamReturnTypestateMismatch(SourceLocation Loc,
1964 StringRef VariableName,
1965 StringRef ExpectedState,
1966 StringRef ObservedState) override {
1968 PartialDiagnosticAt Warning(Loc, S.PDiag(
1969 diag::warn_param_return_typestate_mismatch) << VariableName <<
1970 ExpectedState << ObservedState);
1972 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1975 void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
1976 StringRef ObservedState) override {
1978 PartialDiagnosticAt Warning(Loc, S.PDiag(
1979 diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState);
1981 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1984 void warnReturnTypestateForUnconsumableType(SourceLocation Loc,
1985 StringRef TypeName) override {
1986 PartialDiagnosticAt Warning(Loc, S.PDiag(
1987 diag::warn_return_typestate_for_unconsumable_type) << TypeName);
1989 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1992 void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
1993 StringRef ObservedState) override {
1995 PartialDiagnosticAt Warning(Loc, S.PDiag(
1996 diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState);
1998 Warnings.emplace_back(std::move(Warning), OptionalNotes());
2001 void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State,
2002 SourceLocation Loc) override {
2004 PartialDiagnosticAt Warning(Loc, S.PDiag(
2005 diag::warn_use_of_temp_in_invalid_state) << MethodName << State);
2007 Warnings.emplace_back(std::move(Warning), OptionalNotes());
2010 void warnUseInInvalidState(StringRef MethodName, StringRef VariableName,
2011 StringRef State, SourceLocation Loc) override {
2013 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_invalid_state) <<
2014 MethodName << VariableName << State);
2016 Warnings.emplace_back(std::move(Warning), OptionalNotes());
2019 } // anonymous namespace
2020 } // namespace consumed
2021 } // namespace clang
2023 //===----------------------------------------------------------------------===//
2024 // AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
2025 // warnings on a function, method, or block.
2026 //===----------------------------------------------------------------------===//
2028 clang::sema::AnalysisBasedWarnings::Policy::Policy() {
2029 enableCheckFallThrough = 1;
2030 enableCheckUnreachable = 0;
2031 enableThreadSafetyAnalysis = 0;
2032 enableConsumedAnalysis = 0;
2035 static unsigned isEnabled(DiagnosticsEngine &D, unsigned diag) {
2036 return (unsigned)!D.isIgnored(diag, SourceLocation());
2039 clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
2041 NumFunctionsAnalyzed(0),
2042 NumFunctionsWithBadCFGs(0),
2044 MaxCFGBlocksPerFunction(0),
2045 NumUninitAnalysisFunctions(0),
2046 NumUninitAnalysisVariables(0),
2047 MaxUninitAnalysisVariablesPerFunction(0),
2048 NumUninitAnalysisBlockVisits(0),
2049 MaxUninitAnalysisBlockVisitsPerFunction(0) {
2051 using namespace diag;
2052 DiagnosticsEngine &D = S.getDiagnostics();
2054 DefaultPolicy.enableCheckUnreachable =
2055 isEnabled(D, warn_unreachable) ||
2056 isEnabled(D, warn_unreachable_break) ||
2057 isEnabled(D, warn_unreachable_return) ||
2058 isEnabled(D, warn_unreachable_loop_increment);
2060 DefaultPolicy.enableThreadSafetyAnalysis =
2061 isEnabled(D, warn_double_lock);
2063 DefaultPolicy.enableConsumedAnalysis =
2064 isEnabled(D, warn_use_in_invalid_state);
2067 static void flushDiagnostics(Sema &S, const sema::FunctionScopeInfo *fscope) {
2068 for (const auto &D : fscope->PossiblyUnreachableDiags)
2069 S.Diag(D.Loc, D.PD);
2073 AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
2074 sema::FunctionScopeInfo *fscope,
2075 const Decl *D, const BlockExpr *blkExpr) {
2077 // We avoid doing analysis-based warnings when there are errors for
2079 // (1) The CFGs often can't be constructed (if the body is invalid), so
2080 // don't bother trying.
2081 // (2) The code already has problems; running the analysis just takes more
2083 DiagnosticsEngine &Diags = S.getDiagnostics();
2085 // Do not do any analysis for declarations in system headers if we are
2086 // going to just ignore them.
2087 if (Diags.getSuppressSystemWarnings() &&
2088 S.SourceMgr.isInSystemHeader(D->getLocation()))
2091 // For code in dependent contexts, we'll do this at instantiation time.
2092 if (cast<DeclContext>(D)->isDependentContext())
2095 if (Diags.hasUncompilableErrorOccurred()) {
2096 // Flush out any possibly unreachable diagnostics.
2097 flushDiagnostics(S, fscope);
2101 const Stmt *Body = D->getBody();
2104 // Construct the analysis context with the specified CFG build options.
2105 AnalysisDeclContext AC(/* AnalysisDeclContextManager */ nullptr, D);
2107 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
2108 // explosion for destructors that can result and the compile time hit.
2109 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
2110 AC.getCFGBuildOptions().AddEHEdges = false;
2111 AC.getCFGBuildOptions().AddInitializers = true;
2112 AC.getCFGBuildOptions().AddImplicitDtors = true;
2113 AC.getCFGBuildOptions().AddTemporaryDtors = true;
2114 AC.getCFGBuildOptions().AddCXXNewAllocator = false;
2115 AC.getCFGBuildOptions().AddCXXDefaultInitExprInCtors = true;
2117 // Force that certain expressions appear as CFGElements in the CFG. This
2118 // is used to speed up various analyses.
2119 // FIXME: This isn't the right factoring. This is here for initial
2120 // prototyping, but we need a way for analyses to say what expressions they
2121 // expect to always be CFGElements and then fill in the BuildOptions
2122 // appropriately. This is essentially a layering violation.
2123 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis ||
2124 P.enableConsumedAnalysis) {
2125 // Unreachable code analysis and thread safety require a linearized CFG.
2126 AC.getCFGBuildOptions().setAllAlwaysAdd();
2129 AC.getCFGBuildOptions()
2130 .setAlwaysAdd(Stmt::BinaryOperatorClass)
2131 .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
2132 .setAlwaysAdd(Stmt::BlockExprClass)
2133 .setAlwaysAdd(Stmt::CStyleCastExprClass)
2134 .setAlwaysAdd(Stmt::DeclRefExprClass)
2135 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
2136 .setAlwaysAdd(Stmt::UnaryOperatorClass)
2137 .setAlwaysAdd(Stmt::AttributedStmtClass);
2140 // Install the logical handler for -Wtautological-overlap-compare
2141 std::unique_ptr<LogicalErrorHandler> LEH;
2142 if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
2143 D->getLocStart())) {
2144 LEH.reset(new LogicalErrorHandler(S));
2145 AC.getCFGBuildOptions().Observer = LEH.get();
2148 // Emit delayed diagnostics.
2149 if (!fscope->PossiblyUnreachableDiags.empty()) {
2150 bool analyzed = false;
2152 // Register the expressions with the CFGBuilder.
2153 for (const auto &D : fscope->PossiblyUnreachableDiags) {
2155 AC.registerForcedBlockExpression(D.stmt);
2160 for (const auto &D : fscope->PossiblyUnreachableDiags) {
2161 bool processed = false;
2163 const CFGBlock *block = AC.getBlockForRegisteredExpression(D.stmt);
2164 CFGReverseBlockReachabilityAnalysis *cra =
2165 AC.getCFGReachablityAnalysis();
2166 // FIXME: We should be able to assert that block is non-null, but
2167 // the CFG analysis can skip potentially-evaluated expressions in
2168 // edge cases; see test/Sema/vla-2.c.
2170 // Can this block be reached from the entrance?
2171 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
2172 S.Diag(D.Loc, D.PD);
2177 // Emit the warning anyway if we cannot map to a basic block.
2178 S.Diag(D.Loc, D.PD);
2184 flushDiagnostics(S, fscope);
2187 // Warning: check missing 'return'
2188 if (P.enableCheckFallThrough) {
2189 const CheckFallThroughDiagnostics &CD =
2191 ? CheckFallThroughDiagnostics::MakeForBlock()
2192 : (isa<CXXMethodDecl>(D) &&
2193 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
2194 cast<CXXMethodDecl>(D)->getParent()->isLambda())
2195 ? CheckFallThroughDiagnostics::MakeForLambda()
2196 : (fscope->isCoroutine()
2197 ? CheckFallThroughDiagnostics::MakeForCoroutine(D)
2198 : CheckFallThroughDiagnostics::MakeForFunction(D)));
2199 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
2202 // Warning: check for unreachable code
2203 if (P.enableCheckUnreachable) {
2204 // Only check for unreachable code on non-template instantiations.
2205 // Different template instantiations can effectively change the control-flow
2206 // and it is very difficult to prove that a snippet of code in a template
2207 // is unreachable for all instantiations.
2208 bool isTemplateInstantiation = false;
2209 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2210 isTemplateInstantiation = Function->isTemplateInstantiation();
2211 if (!isTemplateInstantiation)
2212 CheckUnreachable(S, AC);
2215 // Check for thread safety violations
2216 if (P.enableThreadSafetyAnalysis) {
2217 SourceLocation FL = AC.getDecl()->getLocation();
2218 SourceLocation FEL = AC.getDecl()->getLocEnd();
2219 threadSafety::ThreadSafetyReporter Reporter(S, FL, FEL);
2220 if (!Diags.isIgnored(diag::warn_thread_safety_beta, D->getLocStart()))
2221 Reporter.setIssueBetaWarnings(true);
2222 if (!Diags.isIgnored(diag::warn_thread_safety_verbose, D->getLocStart()))
2223 Reporter.setVerbose(true);
2225 threadSafety::runThreadSafetyAnalysis(AC, Reporter,
2226 &S.ThreadSafetyDeclCache);
2227 Reporter.emitDiagnostics();
2230 // Check for violations of consumed properties.
2231 if (P.enableConsumedAnalysis) {
2232 consumed::ConsumedWarningsHandler WarningHandler(S);
2233 consumed::ConsumedAnalyzer Analyzer(WarningHandler);
2237 if (!Diags.isIgnored(diag::warn_uninit_var, D->getLocStart()) ||
2238 !Diags.isIgnored(diag::warn_sometimes_uninit_var, D->getLocStart()) ||
2239 !Diags.isIgnored(diag::warn_maybe_uninit_var, D->getLocStart())) {
2240 if (CFG *cfg = AC.getCFG()) {
2241 UninitValsDiagReporter reporter(S);
2242 UninitVariablesAnalysisStats stats;
2243 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
2244 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
2247 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
2248 ++NumUninitAnalysisFunctions;
2249 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
2250 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
2251 MaxUninitAnalysisVariablesPerFunction =
2252 std::max(MaxUninitAnalysisVariablesPerFunction,
2253 stats.NumVariablesAnalyzed);
2254 MaxUninitAnalysisBlockVisitsPerFunction =
2255 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
2256 stats.NumBlockVisits);
2261 bool FallThroughDiagFull =
2262 !Diags.isIgnored(diag::warn_unannotated_fallthrough, D->getLocStart());
2263 bool FallThroughDiagPerFunction = !Diags.isIgnored(
2264 diag::warn_unannotated_fallthrough_per_function, D->getLocStart());
2265 if (FallThroughDiagFull || FallThroughDiagPerFunction ||
2266 fscope->HasFallthroughStmt) {
2267 DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
2270 if (S.getLangOpts().ObjCWeak &&
2271 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, D->getLocStart()))
2272 diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
2275 // Check for infinite self-recursion in functions
2276 if (!Diags.isIgnored(diag::warn_infinite_recursive_function,
2277 D->getLocStart())) {
2278 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2279 checkRecursiveFunction(S, FD, Body, AC);
2283 // Check for throw out of non-throwing function.
2284 if (!Diags.isIgnored(diag::warn_throw_in_noexcept_func, D->getLocStart()))
2285 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2286 if (S.getLangOpts().CPlusPlus && isNoexcept(FD))
2287 checkThrowInNonThrowingFunc(S, FD, AC);
2289 // If none of the previous checks caused a CFG build, trigger one here
2290 // for -Wtautological-overlap-compare
2291 if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
2292 D->getLocStart())) {
2296 // Collect statistics about the CFG if it was built.
2297 if (S.CollectStats && AC.isCFGBuilt()) {
2298 ++NumFunctionsAnalyzed;
2299 if (CFG *cfg = AC.getCFG()) {
2300 // If we successfully built a CFG for this context, record some more
2301 // detail information about it.
2302 NumCFGBlocks += cfg->getNumBlockIDs();
2303 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
2304 cfg->getNumBlockIDs());
2306 ++NumFunctionsWithBadCFGs;
2311 void clang::sema::AnalysisBasedWarnings::PrintStats() const {
2312 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
2314 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
2315 unsigned AvgCFGBlocksPerFunction =
2316 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
2317 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
2318 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
2319 << " " << NumCFGBlocks << " CFG blocks built.\n"
2320 << " " << AvgCFGBlocksPerFunction
2321 << " average CFG blocks per function.\n"
2322 << " " << MaxCFGBlocksPerFunction
2323 << " max CFG blocks per function.\n";
2325 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
2326 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
2327 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
2328 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
2329 llvm::errs() << NumUninitAnalysisFunctions
2330 << " functions analyzed for uninitialiazed variables\n"
2331 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
2332 << " " << AvgUninitVariablesPerFunction
2333 << " average variables per function.\n"
2334 << " " << MaxUninitAnalysisVariablesPerFunction
2335 << " max variables per function.\n"
2336 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
2337 << " " << AvgUninitBlockVisitsPerFunction
2338 << " average block visits per function.\n"
2339 << " " << MaxUninitAnalysisBlockVisitsPerFunction
2340 << " max block visits per function.\n";