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/Lexer.h"
38 #include "clang/Lex/Preprocessor.h"
39 #include "clang/Sema/ScopeInfo.h"
40 #include "clang/Sema/SemaInternal.h"
41 #include "llvm/ADT/ArrayRef.h"
42 #include "llvm/ADT/BitVector.h"
43 #include "llvm/ADT/FoldingSet.h"
44 #include "llvm/ADT/ImmutableMap.h"
45 #include "llvm/ADT/MapVector.h"
46 #include "llvm/ADT/PostOrderIterator.h"
47 #include "llvm/ADT/SmallString.h"
48 #include "llvm/ADT/SmallVector.h"
49 #include "llvm/ADT/StringRef.h"
50 #include "llvm/Support/Casting.h"
56 using namespace clang;
58 //===----------------------------------------------------------------------===//
59 // Unreachable code analysis.
60 //===----------------------------------------------------------------------===//
63 class UnreachableCodeHandler : public reachable_code::Callback {
66 UnreachableCodeHandler(Sema &s) : S(s) {}
68 void HandleUnreachable(reachable_code::UnreachableKind UK,
70 SourceRange SilenceableCondVal,
72 SourceRange R2) override {
73 unsigned diag = diag::warn_unreachable;
75 case reachable_code::UK_Break:
76 diag = diag::warn_unreachable_break;
78 case reachable_code::UK_Return:
79 diag = diag::warn_unreachable_return;
81 case reachable_code::UK_Loop_Increment:
82 diag = diag::warn_unreachable_loop_increment;
84 case reachable_code::UK_Other:
88 S.Diag(L, diag) << R1 << R2;
90 SourceLocation Open = SilenceableCondVal.getBegin();
92 SourceLocation Close = SilenceableCondVal.getEnd();
93 Close = S.getLocForEndOfToken(Close);
94 if (Close.isValid()) {
95 S.Diag(Open, diag::note_unreachable_silence)
96 << FixItHint::CreateInsertion(Open, "/* DISABLES CODE */ (")
97 << FixItHint::CreateInsertion(Close, ")");
104 /// CheckUnreachable - Check for unreachable code.
105 static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) {
106 // As a heuristic prune all diagnostics not in the main file. Currently
107 // the majority of warnings in headers are false positives. These
108 // are largely caused by configuration state, e.g. preprocessor
109 // defined code, etc.
111 // Note that this is also a performance optimization. Analyzing
112 // headers many times can be expensive.
113 if (!S.getSourceManager().isInMainFile(AC.getDecl()->getLocStart()))
116 UnreachableCodeHandler UC(S);
117 reachable_code::FindUnreachableCode(AC, S.getPreprocessor(), UC);
121 /// \brief Warn on logical operator errors in CFGBuilder
122 class LogicalErrorHandler : public CFGCallback {
126 LogicalErrorHandler(Sema &S) : CFGCallback(), S(S) {}
128 static bool HasMacroID(const Expr *E) {
129 if (E->getExprLoc().isMacroID())
132 // Recurse to children.
133 for (ConstStmtRange SubStmts = E->children(); SubStmts; ++SubStmts)
135 if (const Expr *SubExpr = dyn_cast<Expr>(*SubStmts))
136 if (HasMacroID(SubExpr))
142 void compareAlwaysTrue(const BinaryOperator *B, bool isAlwaysTrue) override {
146 SourceRange DiagRange = B->getSourceRange();
147 S.Diag(B->getExprLoc(), diag::warn_tautological_overlap_comparison)
148 << DiagRange << isAlwaysTrue;
151 void compareBitwiseEquality(const BinaryOperator *B,
152 bool isAlwaysTrue) override {
156 SourceRange DiagRange = B->getSourceRange();
157 S.Diag(B->getExprLoc(), diag::warn_comparison_bitwise_always)
158 << DiagRange << isAlwaysTrue;
163 //===----------------------------------------------------------------------===//
164 // Check for infinite self-recursion in functions
165 //===----------------------------------------------------------------------===//
167 // All blocks are in one of three states. States are ordered so that blocks
168 // can only move to higher states.
169 enum RecursiveState {
172 FoundPathWithNoRecursiveCall
175 static void checkForFunctionCall(Sema &S, const FunctionDecl *FD,
176 CFGBlock &Block, unsigned ExitID,
177 llvm::SmallVectorImpl<RecursiveState> &States,
178 RecursiveState State) {
179 unsigned ID = Block.getBlockID();
181 // A block's state can only move to a higher state.
182 if (States[ID] >= State)
187 // Found a path to the exit node without a recursive call.
188 if (ID == ExitID && State == FoundPathWithNoRecursiveCall)
191 if (State == FoundPathWithNoRecursiveCall) {
192 // If the current state is FoundPathWithNoRecursiveCall, the successors
193 // will be either FoundPathWithNoRecursiveCall or FoundPath. To determine
194 // which, process all the Stmt's in this block to find any recursive calls.
195 for (const auto &B : Block) {
196 if (B.getKind() != CFGElement::Statement)
199 const CallExpr *CE = dyn_cast<CallExpr>(B.getAs<CFGStmt>()->getStmt());
200 if (CE && CE->getCalleeDecl() &&
201 CE->getCalleeDecl()->getCanonicalDecl() == FD) {
203 // Skip function calls which are qualified with a templated class.
204 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(
205 CE->getCallee()->IgnoreParenImpCasts())) {
206 if (NestedNameSpecifier *NNS = DRE->getQualifier()) {
207 if (NNS->getKind() == NestedNameSpecifier::TypeSpec &&
208 isa<TemplateSpecializationType>(NNS->getAsType())) {
214 if (const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE)) {
215 if (isa<CXXThisExpr>(MCE->getImplicitObjectArgument()) ||
216 !MCE->getMethodDecl()->isVirtual()) {
228 for (CFGBlock::succ_iterator I = Block.succ_begin(), E = Block.succ_end();
231 checkForFunctionCall(S, FD, **I, ExitID, States, State);
234 static void checkRecursiveFunction(Sema &S, const FunctionDecl *FD,
236 AnalysisDeclContext &AC) {
237 FD = FD->getCanonicalDecl();
239 // Only run on non-templated functions and non-templated members of
240 // templated classes.
241 if (FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate &&
242 FD->getTemplatedKind() != FunctionDecl::TK_MemberSpecialization)
245 CFG *cfg = AC.getCFG();
248 // If the exit block is unreachable, skip processing the function.
249 if (cfg->getExit().pred_empty())
252 // Mark all nodes as FoundNoPath, then begin processing the entry block.
253 llvm::SmallVector<RecursiveState, 16> states(cfg->getNumBlockIDs(),
255 checkForFunctionCall(S, FD, cfg->getEntry(), cfg->getExit().getBlockID(),
256 states, FoundPathWithNoRecursiveCall);
258 // Check that the exit block is reachable. This prevents triggering the
259 // warning on functions that do not terminate.
260 if (states[cfg->getExit().getBlockID()] == FoundPath)
261 S.Diag(Body->getLocStart(), diag::warn_infinite_recursive_function);
264 //===----------------------------------------------------------------------===//
265 // Check for missing return value.
266 //===----------------------------------------------------------------------===//
268 enum ControlFlowKind {
273 NeverFallThroughOrReturn
276 /// CheckFallThrough - Check that we don't fall off the end of a
277 /// Statement that should return a value.
279 /// \returns AlwaysFallThrough iff we always fall off the end of the statement,
280 /// MaybeFallThrough iff we might or might not fall off the end,
281 /// NeverFallThroughOrReturn iff we never fall off the end of the statement or
282 /// return. We assume NeverFallThrough iff we never fall off the end of the
283 /// statement but we may return. We assume that functions not marked noreturn
285 static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
286 CFG *cfg = AC.getCFG();
287 if (!cfg) return UnknownFallThrough;
289 // The CFG leaves in dead things, and we don't want the dead code paths to
290 // confuse us, so we mark all live things first.
291 llvm::BitVector live(cfg->getNumBlockIDs());
292 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
295 bool AddEHEdges = AC.getAddEHEdges();
296 if (!AddEHEdges && count != cfg->getNumBlockIDs())
297 // When there are things remaining dead, and we didn't add EH edges
298 // from CallExprs to the catch clauses, we have to go back and
299 // mark them as live.
300 for (const auto *B : *cfg) {
301 if (!live[B->getBlockID()]) {
302 if (B->pred_begin() == B->pred_end()) {
303 if (B->getTerminator() && isa<CXXTryStmt>(B->getTerminator()))
304 // When not adding EH edges from calls, catch clauses
305 // can otherwise seem dead. Avoid noting them as dead.
306 count += reachable_code::ScanReachableFromBlock(B, live);
312 // Now we know what is live, we check the live precessors of the exit block
313 // and look for fall through paths, being careful to ignore normal returns,
314 // and exceptional paths.
315 bool HasLiveReturn = false;
316 bool HasFakeEdge = false;
317 bool HasPlainEdge = false;
318 bool HasAbnormalEdge = false;
320 // Ignore default cases that aren't likely to be reachable because all
321 // enums in a switch(X) have explicit case statements.
322 CFGBlock::FilterOptions FO;
323 FO.IgnoreDefaultsWithCoveredEnums = 1;
325 for (CFGBlock::filtered_pred_iterator
326 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
327 const CFGBlock& B = **I;
328 if (!live[B.getBlockID()])
331 // Skip blocks which contain an element marked as no-return. They don't
332 // represent actually viable edges into the exit block, so mark them as
334 if (B.hasNoReturnElement()) {
335 HasAbnormalEdge = true;
339 // Destructors can appear after the 'return' in the CFG. This is
340 // normal. We need to look pass the destructors for the return
341 // statement (if it exists).
342 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
344 for ( ; ri != re ; ++ri)
345 if (ri->getAs<CFGStmt>())
348 // No more CFGElements in the block?
350 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
351 HasAbnormalEdge = true;
354 // A labeled empty statement, or the entry block...
359 CFGStmt CS = ri->castAs<CFGStmt>();
360 const Stmt *S = CS.getStmt();
361 if (isa<ReturnStmt>(S)) {
362 HasLiveReturn = true;
365 if (isa<ObjCAtThrowStmt>(S)) {
369 if (isa<CXXThrowExpr>(S)) {
373 if (isa<MSAsmStmt>(S)) {
374 // TODO: Verify this is correct.
376 HasLiveReturn = true;
379 if (isa<CXXTryStmt>(S)) {
380 HasAbnormalEdge = true;
383 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
385 HasAbnormalEdge = true;
393 return NeverFallThrough;
394 return NeverFallThroughOrReturn;
396 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
397 return MaybeFallThrough;
398 // This says AlwaysFallThrough for calls to functions that are not marked
399 // noreturn, that don't return. If people would like this warning to be more
400 // accurate, such functions should be marked as noreturn.
401 return AlwaysFallThrough;
406 struct CheckFallThroughDiagnostics {
407 unsigned diag_MaybeFallThrough_HasNoReturn;
408 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
409 unsigned diag_AlwaysFallThrough_HasNoReturn;
410 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
411 unsigned diag_NeverFallThroughOrReturn;
412 enum { Function, Block, Lambda } funMode;
413 SourceLocation FuncLoc;
415 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
416 CheckFallThroughDiagnostics D;
417 D.FuncLoc = Func->getLocation();
418 D.diag_MaybeFallThrough_HasNoReturn =
419 diag::warn_falloff_noreturn_function;
420 D.diag_MaybeFallThrough_ReturnsNonVoid =
421 diag::warn_maybe_falloff_nonvoid_function;
422 D.diag_AlwaysFallThrough_HasNoReturn =
423 diag::warn_falloff_noreturn_function;
424 D.diag_AlwaysFallThrough_ReturnsNonVoid =
425 diag::warn_falloff_nonvoid_function;
427 // Don't suggest that virtual functions be marked "noreturn", since they
428 // might be overridden by non-noreturn functions.
429 bool isVirtualMethod = false;
430 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
431 isVirtualMethod = Method->isVirtual();
433 // Don't suggest that template instantiations be marked "noreturn"
434 bool isTemplateInstantiation = false;
435 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
436 isTemplateInstantiation = Function->isTemplateInstantiation();
438 if (!isVirtualMethod && !isTemplateInstantiation)
439 D.diag_NeverFallThroughOrReturn =
440 diag::warn_suggest_noreturn_function;
442 D.diag_NeverFallThroughOrReturn = 0;
444 D.funMode = Function;
448 static CheckFallThroughDiagnostics MakeForBlock() {
449 CheckFallThroughDiagnostics D;
450 D.diag_MaybeFallThrough_HasNoReturn =
451 diag::err_noreturn_block_has_return_expr;
452 D.diag_MaybeFallThrough_ReturnsNonVoid =
453 diag::err_maybe_falloff_nonvoid_block;
454 D.diag_AlwaysFallThrough_HasNoReturn =
455 diag::err_noreturn_block_has_return_expr;
456 D.diag_AlwaysFallThrough_ReturnsNonVoid =
457 diag::err_falloff_nonvoid_block;
458 D.diag_NeverFallThroughOrReturn = 0;
463 static CheckFallThroughDiagnostics MakeForLambda() {
464 CheckFallThroughDiagnostics D;
465 D.diag_MaybeFallThrough_HasNoReturn =
466 diag::err_noreturn_lambda_has_return_expr;
467 D.diag_MaybeFallThrough_ReturnsNonVoid =
468 diag::warn_maybe_falloff_nonvoid_lambda;
469 D.diag_AlwaysFallThrough_HasNoReturn =
470 diag::err_noreturn_lambda_has_return_expr;
471 D.diag_AlwaysFallThrough_ReturnsNonVoid =
472 diag::warn_falloff_nonvoid_lambda;
473 D.diag_NeverFallThroughOrReturn = 0;
478 bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
479 bool HasNoReturn) const {
480 if (funMode == Function) {
481 return (ReturnsVoid ||
482 D.isIgnored(diag::warn_maybe_falloff_nonvoid_function,
485 D.isIgnored(diag::warn_noreturn_function_has_return_expr,
488 D.isIgnored(diag::warn_suggest_noreturn_block, FuncLoc));
491 // For blocks / lambdas.
492 return ReturnsVoid && !HasNoReturn;
498 /// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
499 /// function that should return a value. Check that we don't fall off the end
500 /// of a noreturn function. We assume that functions and blocks not marked
501 /// noreturn will return.
502 static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
503 const BlockExpr *blkExpr,
504 const CheckFallThroughDiagnostics& CD,
505 AnalysisDeclContext &AC) {
507 bool ReturnsVoid = false;
508 bool HasNoReturn = false;
510 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
511 ReturnsVoid = FD->getReturnType()->isVoidType();
512 HasNoReturn = FD->isNoReturn();
514 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
515 ReturnsVoid = MD->getReturnType()->isVoidType();
516 HasNoReturn = MD->hasAttr<NoReturnAttr>();
518 else if (isa<BlockDecl>(D)) {
519 QualType BlockTy = blkExpr->getType();
520 if (const FunctionType *FT =
521 BlockTy->getPointeeType()->getAs<FunctionType>()) {
522 if (FT->getReturnType()->isVoidType())
524 if (FT->getNoReturnAttr())
529 DiagnosticsEngine &Diags = S.getDiagnostics();
531 // Short circuit for compilation speed.
532 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
535 SourceLocation LBrace = Body->getLocStart(), RBrace = Body->getLocEnd();
536 // Either in a function body compound statement, or a function-try-block.
537 switch (CheckFallThrough(AC)) {
538 case UnknownFallThrough:
541 case MaybeFallThrough:
543 S.Diag(RBrace, CD.diag_MaybeFallThrough_HasNoReturn);
544 else if (!ReturnsVoid)
545 S.Diag(RBrace, CD.diag_MaybeFallThrough_ReturnsNonVoid);
547 case AlwaysFallThrough:
549 S.Diag(RBrace, CD.diag_AlwaysFallThrough_HasNoReturn);
550 else if (!ReturnsVoid)
551 S.Diag(RBrace, CD.diag_AlwaysFallThrough_ReturnsNonVoid);
553 case NeverFallThroughOrReturn:
554 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
555 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
556 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 0 << FD;
557 } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
558 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 1 << MD;
560 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn);
564 case NeverFallThrough:
569 //===----------------------------------------------------------------------===//
571 //===----------------------------------------------------------------------===//
574 /// ContainsReference - A visitor class to search for references to
575 /// a particular declaration (the needle) within any evaluated component of an
576 /// expression (recursively).
577 class ContainsReference : public ConstEvaluatedExprVisitor<ContainsReference> {
579 const DeclRefExpr *Needle;
582 typedef ConstEvaluatedExprVisitor<ContainsReference> Inherited;
584 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
585 : Inherited(Context), FoundReference(false), Needle(Needle) {}
587 void VisitExpr(const Expr *E) {
588 // Stop evaluating if we already have a reference.
592 Inherited::VisitExpr(E);
595 void VisitDeclRefExpr(const DeclRefExpr *E) {
597 FoundReference = true;
599 Inherited::VisitDeclRefExpr(E);
602 bool doesContainReference() const { return FoundReference; }
606 static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
607 QualType VariableTy = VD->getType().getCanonicalType();
608 if (VariableTy->isBlockPointerType() &&
609 !VD->hasAttr<BlocksAttr>()) {
610 S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization)
612 << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
616 // Don't issue a fixit if there is already an initializer.
620 // Don't suggest a fixit inside macros.
621 if (VD->getLocEnd().isMacroID())
624 SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
626 // Suggest possible initialization (if any).
627 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
631 S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
632 << FixItHint::CreateInsertion(Loc, Init);
636 /// Create a fixit to remove an if-like statement, on the assumption that its
637 /// condition is CondVal.
638 static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
639 const Stmt *Else, bool CondVal,
640 FixItHint &Fixit1, FixItHint &Fixit2) {
642 // If condition is always true, remove all but the 'then'.
643 Fixit1 = FixItHint::CreateRemoval(
644 CharSourceRange::getCharRange(If->getLocStart(),
645 Then->getLocStart()));
647 SourceLocation ElseKwLoc = Lexer::getLocForEndOfToken(
648 Then->getLocEnd(), 0, S.getSourceManager(), S.getLangOpts());
649 Fixit2 = FixItHint::CreateRemoval(
650 SourceRange(ElseKwLoc, Else->getLocEnd()));
653 // If condition is always false, remove all but the 'else'.
655 Fixit1 = FixItHint::CreateRemoval(
656 CharSourceRange::getCharRange(If->getLocStart(),
657 Else->getLocStart()));
659 Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
663 /// DiagUninitUse -- Helper function to produce a diagnostic for an
664 /// uninitialized use of a variable.
665 static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
666 bool IsCapturedByBlock) {
667 bool Diagnosed = false;
669 switch (Use.getKind()) {
670 case UninitUse::Always:
671 S.Diag(Use.getUser()->getLocStart(), diag::warn_uninit_var)
672 << VD->getDeclName() << IsCapturedByBlock
673 << Use.getUser()->getSourceRange();
676 case UninitUse::AfterDecl:
677 case UninitUse::AfterCall:
678 S.Diag(VD->getLocation(), diag::warn_sometimes_uninit_var)
679 << VD->getDeclName() << IsCapturedByBlock
680 << (Use.getKind() == UninitUse::AfterDecl ? 4 : 5)
681 << const_cast<DeclContext*>(VD->getLexicalDeclContext())
682 << VD->getSourceRange();
683 S.Diag(Use.getUser()->getLocStart(), diag::note_uninit_var_use)
684 << IsCapturedByBlock << Use.getUser()->getSourceRange();
687 case UninitUse::Maybe:
688 case UninitUse::Sometimes:
689 // Carry on to report sometimes-uninitialized branches, if possible,
690 // or a 'may be used uninitialized' diagnostic otherwise.
694 // Diagnose each branch which leads to a sometimes-uninitialized use.
695 for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
697 assert(Use.getKind() == UninitUse::Sometimes);
699 const Expr *User = Use.getUser();
700 const Stmt *Term = I->Terminator;
702 // Information used when building the diagnostic.
707 // FixIts to suppress the diagnostic by removing the dead condition.
708 // For all binary terminators, branch 0 is taken if the condition is true,
709 // and branch 1 is taken if the condition is false.
710 int RemoveDiagKind = -1;
711 const char *FixitStr =
712 S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
713 : (I->Output ? "1" : "0");
714 FixItHint Fixit1, Fixit2;
716 switch (Term ? Term->getStmtClass() : Stmt::DeclStmtClass) {
718 // Don't know how to report this. Just fall back to 'may be used
719 // uninitialized'. FIXME: Can this happen?
722 // "condition is true / condition is false".
723 case Stmt::IfStmtClass: {
724 const IfStmt *IS = cast<IfStmt>(Term);
727 Range = IS->getCond()->getSourceRange();
729 CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
730 I->Output, Fixit1, Fixit2);
733 case Stmt::ConditionalOperatorClass: {
734 const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
737 Range = CO->getCond()->getSourceRange();
739 CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
740 I->Output, Fixit1, Fixit2);
743 case Stmt::BinaryOperatorClass: {
744 const BinaryOperator *BO = cast<BinaryOperator>(Term);
745 if (!BO->isLogicalOp())
748 Str = BO->getOpcodeStr();
749 Range = BO->getLHS()->getSourceRange();
751 if ((BO->getOpcode() == BO_LAnd && I->Output) ||
752 (BO->getOpcode() == BO_LOr && !I->Output))
753 // true && y -> y, false || y -> y.
754 Fixit1 = FixItHint::CreateRemoval(SourceRange(BO->getLocStart(),
755 BO->getOperatorLoc()));
757 // false && y -> false, true || y -> true.
758 Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
762 // "loop is entered / loop is exited".
763 case Stmt::WhileStmtClass:
766 Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
768 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
770 case Stmt::ForStmtClass:
773 Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
776 Fixit1 = FixItHint::CreateRemoval(Range);
778 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
780 case Stmt::CXXForRangeStmtClass:
781 if (I->Output == 1) {
782 // The use occurs if a range-based for loop's body never executes.
783 // That may be impossible, and there's no syntactic fix for this,
784 // so treat it as a 'may be uninitialized' case.
789 Range = cast<CXXForRangeStmt>(Term)->getRangeInit()->getSourceRange();
792 // "condition is true / loop is exited".
793 case Stmt::DoStmtClass:
796 Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
798 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
801 // "switch case is taken".
802 case Stmt::CaseStmtClass:
805 Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
807 case Stmt::DefaultStmtClass:
810 Range = cast<DefaultStmt>(Term)->getDefaultLoc();
814 S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
815 << VD->getDeclName() << IsCapturedByBlock << DiagKind
816 << Str << I->Output << Range;
817 S.Diag(User->getLocStart(), diag::note_uninit_var_use)
818 << IsCapturedByBlock << User->getSourceRange();
819 if (RemoveDiagKind != -1)
820 S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
821 << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
827 S.Diag(Use.getUser()->getLocStart(), diag::warn_maybe_uninit_var)
828 << VD->getDeclName() << IsCapturedByBlock
829 << Use.getUser()->getSourceRange();
832 /// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
833 /// uninitialized variable. This manages the different forms of diagnostic
834 /// emitted for particular types of uses. Returns true if the use was diagnosed
835 /// as a warning. If a particular use is one we omit warnings for, returns
837 static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
838 const UninitUse &Use,
839 bool alwaysReportSelfInit = false) {
841 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
842 // Inspect the initializer of the variable declaration which is
843 // being referenced prior to its initialization. We emit
844 // specialized diagnostics for self-initialization, and we
845 // specifically avoid warning about self references which take the
850 // This is used to indicate to GCC that 'x' is intentionally left
851 // uninitialized. Proven code paths which access 'x' in
852 // an uninitialized state after this will still warn.
853 if (const Expr *Initializer = VD->getInit()) {
854 if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
857 ContainsReference CR(S.Context, DRE);
858 CR.Visit(Initializer);
859 if (CR.doesContainReference()) {
860 S.Diag(DRE->getLocStart(),
861 diag::warn_uninit_self_reference_in_init)
862 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
867 DiagUninitUse(S, VD, Use, false);
869 const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
870 if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
871 S.Diag(BE->getLocStart(),
872 diag::warn_uninit_byref_blockvar_captured_by_block)
873 << VD->getDeclName();
875 DiagUninitUse(S, VD, Use, true);
878 // Report where the variable was declared when the use wasn't within
879 // the initializer of that declaration & we didn't already suggest
880 // an initialization fixit.
881 if (!SuggestInitializationFixit(S, VD))
882 S.Diag(VD->getLocStart(), diag::note_uninit_var_def)
883 << VD->getDeclName();
889 class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
891 FallthroughMapper(Sema &S)
892 : FoundSwitchStatements(false),
896 bool foundSwitchStatements() const { return FoundSwitchStatements; }
898 void markFallthroughVisited(const AttributedStmt *Stmt) {
899 bool Found = FallthroughStmts.erase(Stmt);
904 typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
906 const AttrStmts &getFallthroughStmts() const {
907 return FallthroughStmts;
910 void fillReachableBlocks(CFG *Cfg) {
911 assert(ReachableBlocks.empty() && "ReachableBlocks already filled");
912 std::deque<const CFGBlock *> BlockQueue;
914 ReachableBlocks.insert(&Cfg->getEntry());
915 BlockQueue.push_back(&Cfg->getEntry());
916 // Mark all case blocks reachable to avoid problems with switching on
917 // constants, covered enums, etc.
918 // These blocks can contain fall-through annotations, and we don't want to
919 // issue a warn_fallthrough_attr_unreachable for them.
920 for (const auto *B : *Cfg) {
921 const Stmt *L = B->getLabel();
922 if (L && isa<SwitchCase>(L) && ReachableBlocks.insert(B).second)
923 BlockQueue.push_back(B);
926 while (!BlockQueue.empty()) {
927 const CFGBlock *P = BlockQueue.front();
928 BlockQueue.pop_front();
929 for (CFGBlock::const_succ_iterator I = P->succ_begin(),
932 if (*I && ReachableBlocks.insert(*I).second)
933 BlockQueue.push_back(*I);
938 bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt) {
939 assert(!ReachableBlocks.empty() && "ReachableBlocks empty");
941 int UnannotatedCnt = 0;
944 std::deque<const CFGBlock*> BlockQueue(B.pred_begin(), B.pred_end());
945 while (!BlockQueue.empty()) {
946 const CFGBlock *P = BlockQueue.front();
947 BlockQueue.pop_front();
950 const Stmt *Term = P->getTerminator();
951 if (Term && isa<SwitchStmt>(Term))
952 continue; // Switch statement, good.
954 const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
955 if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
956 continue; // Previous case label has no statements, good.
958 const LabelStmt *L = dyn_cast_or_null<LabelStmt>(P->getLabel());
959 if (L && L->getSubStmt() == B.getLabel() && P->begin() == P->end())
960 continue; // Case label is preceded with a normal label, good.
962 if (!ReachableBlocks.count(P)) {
963 for (CFGBlock::const_reverse_iterator ElemIt = P->rbegin(),
965 ElemIt != ElemEnd; ++ElemIt) {
966 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>()) {
967 if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
968 S.Diag(AS->getLocStart(),
969 diag::warn_fallthrough_attr_unreachable);
970 markFallthroughVisited(AS);
974 // Don't care about other unreachable statements.
977 // If there are no unreachable statements, this may be a special
980 // A a; // A has a destructor.
983 // // <<<< This place is represented by a 'hanging' CFG block.
988 const Stmt *LastStmt = getLastStmt(*P);
989 if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
990 markFallthroughVisited(AS);
992 continue; // Fallthrough annotation, good.
995 if (!LastStmt) { // This block contains no executable statements.
996 // Traverse its predecessors.
997 std::copy(P->pred_begin(), P->pred_end(),
998 std::back_inserter(BlockQueue));
1004 return !!UnannotatedCnt;
1007 // RecursiveASTVisitor setup.
1008 bool shouldWalkTypesOfTypeLocs() const { return false; }
1010 bool VisitAttributedStmt(AttributedStmt *S) {
1011 if (asFallThroughAttr(S))
1012 FallthroughStmts.insert(S);
1016 bool VisitSwitchStmt(SwitchStmt *S) {
1017 FoundSwitchStatements = true;
1021 // We don't want to traverse local type declarations. We analyze their
1022 // methods separately.
1023 bool TraverseDecl(Decl *D) { return true; }
1025 // We analyze lambda bodies separately. Skip them here.
1026 bool TraverseLambdaBody(LambdaExpr *LE) { return true; }
1030 static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
1031 if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
1032 if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
1038 static const Stmt *getLastStmt(const CFGBlock &B) {
1039 if (const Stmt *Term = B.getTerminator())
1041 for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
1043 ElemIt != ElemEnd; ++ElemIt) {
1044 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>())
1045 return CS->getStmt();
1047 // Workaround to detect a statement thrown out by CFGBuilder:
1048 // case X: {} case Y:
1049 // case X: ; case Y:
1050 if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
1051 if (!isa<SwitchCase>(SW->getSubStmt()))
1052 return SW->getSubStmt();
1057 bool FoundSwitchStatements;
1058 AttrStmts FallthroughStmts;
1060 llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks;
1064 static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
1066 // Only perform this analysis when using C++11. There is no good workflow
1067 // for this warning when not using C++11. There is no good way to silence
1068 // the warning (no attribute is available) unless we are using C++11's support
1069 // for generalized attributes. Once could use pragmas to silence the warning,
1070 // but as a general solution that is gross and not in the spirit of this
1073 // NOTE: This an intermediate solution. There are on-going discussions on
1074 // how to properly support this warning outside of C++11 with an annotation.
1075 if (!AC.getASTContext().getLangOpts().CPlusPlus11)
1078 FallthroughMapper FM(S);
1079 FM.TraverseStmt(AC.getBody());
1081 if (!FM.foundSwitchStatements())
1084 if (PerFunction && FM.getFallthroughStmts().empty())
1087 CFG *Cfg = AC.getCFG();
1092 FM.fillReachableBlocks(Cfg);
1094 for (CFG::reverse_iterator I = Cfg->rbegin(), E = Cfg->rend(); I != E; ++I) {
1095 const CFGBlock *B = *I;
1096 const Stmt *Label = B->getLabel();
1098 if (!Label || !isa<SwitchCase>(Label))
1103 if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt))
1106 S.Diag(Label->getLocStart(),
1107 PerFunction ? diag::warn_unannotated_fallthrough_per_function
1108 : diag::warn_unannotated_fallthrough);
1110 if (!AnnotatedCnt) {
1111 SourceLocation L = Label->getLocStart();
1114 if (S.getLangOpts().CPlusPlus11) {
1115 const Stmt *Term = B->getTerminator();
1116 // Skip empty cases.
1117 while (B->empty() && !Term && B->succ_size() == 1) {
1118 B = *B->succ_begin();
1119 Term = B->getTerminator();
1121 if (!(B->empty() && Term && isa<BreakStmt>(Term))) {
1122 Preprocessor &PP = S.getPreprocessor();
1123 TokenValue Tokens[] = {
1124 tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
1125 tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
1126 tok::r_square, tok::r_square
1128 StringRef AnnotationSpelling = "[[clang::fallthrough]]";
1129 StringRef MacroName = PP.getLastMacroWithSpelling(L, Tokens);
1130 if (!MacroName.empty())
1131 AnnotationSpelling = MacroName;
1132 SmallString<64> TextToInsert(AnnotationSpelling);
1133 TextToInsert += "; ";
1134 S.Diag(L, diag::note_insert_fallthrough_fixit) <<
1135 AnnotationSpelling <<
1136 FixItHint::CreateInsertion(L, TextToInsert);
1139 S.Diag(L, diag::note_insert_break_fixit) <<
1140 FixItHint::CreateInsertion(L, "break; ");
1144 for (const auto *F : FM.getFallthroughStmts())
1145 S.Diag(F->getLocStart(), diag::warn_fallthrough_attr_invalid_placement);
1148 static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
1153 switch (S->getStmtClass()) {
1154 case Stmt::ForStmtClass:
1155 case Stmt::WhileStmtClass:
1156 case Stmt::CXXForRangeStmtClass:
1157 case Stmt::ObjCForCollectionStmtClass:
1159 case Stmt::DoStmtClass: {
1160 const Expr *Cond = cast<DoStmt>(S)->getCond();
1162 if (!Cond->EvaluateAsInt(Val, Ctx))
1164 return Val.getBoolValue();
1169 } while ((S = PM.getParent(S)));
1175 static void diagnoseRepeatedUseOfWeak(Sema &S,
1176 const sema::FunctionScopeInfo *CurFn,
1178 const ParentMap &PM) {
1179 typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
1180 typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
1181 typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
1182 typedef std::pair<const Stmt *, WeakObjectUseMap::const_iterator>
1185 ASTContext &Ctx = S.getASTContext();
1187 const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
1189 // Extract all weak objects that are referenced more than once.
1190 SmallVector<StmtUsesPair, 8> UsesByStmt;
1191 for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
1193 const WeakUseVector &Uses = I->second;
1195 // Find the first read of the weak object.
1196 WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1197 for ( ; UI != UE; ++UI) {
1202 // If there were only writes to this object, don't warn.
1206 // If there was only one read, followed by any number of writes, and the
1207 // read is not within a loop, don't warn. Additionally, don't warn in a
1208 // loop if the base object is a local variable -- local variables are often
1209 // changed in loops.
1210 if (UI == Uses.begin()) {
1211 WeakUseVector::const_iterator UI2 = UI;
1212 for (++UI2; UI2 != UE; ++UI2)
1213 if (UI2->isUnsafe())
1217 if (!isInLoop(Ctx, PM, UI->getUseExpr()))
1220 const WeakObjectProfileTy &Profile = I->first;
1221 if (!Profile.isExactProfile())
1224 const NamedDecl *Base = Profile.getBase();
1226 Base = Profile.getProperty();
1227 assert(Base && "A profile always has a base or property.");
1229 if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
1230 if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
1235 UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
1238 if (UsesByStmt.empty())
1241 // Sort by first use so that we emit the warnings in a deterministic order.
1242 SourceManager &SM = S.getSourceManager();
1243 std::sort(UsesByStmt.begin(), UsesByStmt.end(),
1244 [&SM](const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
1245 return SM.isBeforeInTranslationUnit(LHS.first->getLocStart(),
1246 RHS.first->getLocStart());
1249 // Classify the current code body for better warning text.
1250 // This enum should stay in sync with the cases in
1251 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1252 // FIXME: Should we use a common classification enum and the same set of
1253 // possibilities all throughout Sema?
1261 if (isa<sema::BlockScopeInfo>(CurFn))
1262 FunctionKind = Block;
1263 else if (isa<sema::LambdaScopeInfo>(CurFn))
1264 FunctionKind = Lambda;
1265 else if (isa<ObjCMethodDecl>(D))
1266 FunctionKind = Method;
1268 FunctionKind = Function;
1270 // Iterate through the sorted problems and emit warnings for each.
1271 for (const auto &P : UsesByStmt) {
1272 const Stmt *FirstRead = P.first;
1273 const WeakObjectProfileTy &Key = P.second->first;
1274 const WeakUseVector &Uses = P.second->second;
1276 // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
1277 // may not contain enough information to determine that these are different
1278 // properties. We can only be 100% sure of a repeated use in certain cases,
1279 // and we adjust the diagnostic kind accordingly so that the less certain
1280 // case can be turned off if it is too noisy.
1282 if (Key.isExactProfile())
1283 DiagKind = diag::warn_arc_repeated_use_of_weak;
1285 DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
1287 // Classify the weak object being accessed for better warning text.
1288 // This enum should stay in sync with the cases in
1289 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1297 const NamedDecl *D = Key.getProperty();
1298 if (isa<VarDecl>(D))
1299 ObjectKind = Variable;
1300 else if (isa<ObjCPropertyDecl>(D))
1301 ObjectKind = Property;
1302 else if (isa<ObjCMethodDecl>(D))
1303 ObjectKind = ImplicitProperty;
1304 else if (isa<ObjCIvarDecl>(D))
1307 llvm_unreachable("Unexpected weak object kind!");
1309 // Show the first time the object was read.
1310 S.Diag(FirstRead->getLocStart(), DiagKind)
1311 << int(ObjectKind) << D << int(FunctionKind)
1312 << FirstRead->getSourceRange();
1314 // Print all the other accesses as notes.
1315 for (const auto &Use : Uses) {
1316 if (Use.getUseExpr() == FirstRead)
1318 S.Diag(Use.getUseExpr()->getLocStart(),
1319 diag::note_arc_weak_also_accessed_here)
1320 << Use.getUseExpr()->getSourceRange();
1326 class UninitValsDiagReporter : public UninitVariablesHandler {
1328 typedef SmallVector<UninitUse, 2> UsesVec;
1329 typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType;
1330 // Prefer using MapVector to DenseMap, so that iteration order will be
1331 // the same as insertion order. This is needed to obtain a deterministic
1332 // order of diagnostics when calling flushDiagnostics().
1333 typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap;
1337 UninitValsDiagReporter(Sema &S) : S(S), uses(nullptr) {}
1338 ~UninitValsDiagReporter() override { flushDiagnostics(); }
1340 MappedType &getUses(const VarDecl *vd) {
1342 uses = new UsesMap();
1344 MappedType &V = (*uses)[vd];
1345 if (!V.getPointer())
1346 V.setPointer(new UsesVec());
1351 void handleUseOfUninitVariable(const VarDecl *vd,
1352 const UninitUse &use) override {
1353 getUses(vd).getPointer()->push_back(use);
1356 void handleSelfInit(const VarDecl *vd) override {
1357 getUses(vd).setInt(true);
1360 void flushDiagnostics() {
1364 for (const auto &P : *uses) {
1365 const VarDecl *vd = P.first;
1366 const MappedType &V = P.second;
1368 UsesVec *vec = V.getPointer();
1369 bool hasSelfInit = V.getInt();
1371 // Specially handle the case where we have uses of an uninitialized
1372 // variable, but the root cause is an idiomatic self-init. We want
1373 // to report the diagnostic at the self-init since that is the root cause.
1374 if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
1375 DiagnoseUninitializedUse(S, vd,
1376 UninitUse(vd->getInit()->IgnoreParenCasts(),
1377 /* isAlwaysUninit */ true),
1378 /* alwaysReportSelfInit */ true);
1380 // Sort the uses by their SourceLocations. While not strictly
1381 // guaranteed to produce them in line/column order, this will provide
1382 // a stable ordering.
1383 std::sort(vec->begin(), vec->end(),
1384 [](const UninitUse &a, const UninitUse &b) {
1385 // Prefer a more confident report over a less confident one.
1386 if (a.getKind() != b.getKind())
1387 return a.getKind() > b.getKind();
1388 return a.getUser()->getLocStart() < b.getUser()->getLocStart();
1391 for (const auto &U : *vec) {
1392 // If we have self-init, downgrade all uses to 'may be uninitialized'.
1393 UninitUse Use = hasSelfInit ? UninitUse(U.getUser(), false) : U;
1395 if (DiagnoseUninitializedUse(S, vd, Use))
1396 // Skip further diagnostics for this variable. We try to warn only
1397 // on the first point at which a variable is used uninitialized.
1402 // Release the uses vector.
1409 static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
1410 return std::any_of(vec->begin(), vec->end(), [](const UninitUse &U) {
1411 return U.getKind() == UninitUse::Always ||
1412 U.getKind() == UninitUse::AfterCall ||
1413 U.getKind() == UninitUse::AfterDecl;
1421 typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
1422 typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
1423 typedef std::list<DelayedDiag> DiagList;
1425 struct SortDiagBySourceLocation {
1427 SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
1429 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1430 // Although this call will be slow, this is only called when outputting
1431 // multiple warnings.
1432 return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
1437 //===----------------------------------------------------------------------===//
1439 //===----------------------------------------------------------------------===//
1441 namespace threadSafety {
1443 class ThreadSafetyReporter : public clang::threadSafety::ThreadSafetyHandler {
1446 SourceLocation FunLocation, FunEndLocation;
1448 const FunctionDecl *CurrentFunction;
1451 OptionalNotes getNotes() const {
1452 if (Verbose && CurrentFunction) {
1453 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
1454 S.PDiag(diag::note_thread_warning_in_fun)
1455 << CurrentFunction->getNameAsString());
1456 return OptionalNotes(1, FNote);
1458 return OptionalNotes();
1461 OptionalNotes getNotes(const PartialDiagnosticAt &Note) const {
1462 OptionalNotes ONS(1, Note);
1463 if (Verbose && CurrentFunction) {
1464 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
1465 S.PDiag(diag::note_thread_warning_in_fun)
1466 << CurrentFunction->getNameAsString());
1467 ONS.push_back(std::move(FNote));
1472 OptionalNotes getNotes(const PartialDiagnosticAt &Note1,
1473 const PartialDiagnosticAt &Note2) const {
1475 ONS.push_back(Note1);
1476 ONS.push_back(Note2);
1477 if (Verbose && CurrentFunction) {
1478 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
1479 S.PDiag(diag::note_thread_warning_in_fun)
1480 << CurrentFunction->getNameAsString());
1481 ONS.push_back(std::move(FNote));
1487 void warnLockMismatch(unsigned DiagID, StringRef Kind, Name LockName,
1488 SourceLocation Loc) {
1489 // Gracefully handle rare cases when the analysis can't get a more
1490 // precise source location.
1493 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind << LockName);
1494 Warnings.emplace_back(std::move(Warning), getNotes());
1498 ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
1499 : S(S), FunLocation(FL), FunEndLocation(FEL),
1500 CurrentFunction(nullptr), Verbose(false) {}
1502 void setVerbose(bool b) { Verbose = b; }
1504 /// \brief Emit all buffered diagnostics in order of sourcelocation.
1505 /// We need to output diagnostics produced while iterating through
1506 /// the lockset in deterministic order, so this function orders diagnostics
1507 /// and outputs them.
1508 void emitDiagnostics() {
1509 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
1510 for (const auto &Diag : Warnings) {
1511 S.Diag(Diag.first.first, Diag.first.second);
1512 for (const auto &Note : Diag.second)
1513 S.Diag(Note.first, Note.second);
1517 void handleInvalidLockExp(StringRef Kind, SourceLocation Loc) override {
1518 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_cannot_resolve_lock)
1520 Warnings.emplace_back(std::move(Warning), getNotes());
1523 void handleUnmatchedUnlock(StringRef Kind, Name LockName,
1524 SourceLocation Loc) override {
1525 warnLockMismatch(diag::warn_unlock_but_no_lock, Kind, LockName, Loc);
1528 void handleIncorrectUnlockKind(StringRef Kind, Name LockName,
1529 LockKind Expected, LockKind Received,
1530 SourceLocation Loc) override {
1531 if (Loc.isInvalid())
1533 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_unlock_kind_mismatch)
1534 << Kind << LockName << Received
1536 Warnings.emplace_back(std::move(Warning), getNotes());
1539 void handleDoubleLock(StringRef Kind, Name LockName, SourceLocation Loc) override {
1540 warnLockMismatch(diag::warn_double_lock, Kind, LockName, Loc);
1543 void handleMutexHeldEndOfScope(StringRef Kind, Name LockName,
1544 SourceLocation LocLocked,
1545 SourceLocation LocEndOfScope,
1546 LockErrorKind LEK) override {
1547 unsigned DiagID = 0;
1549 case LEK_LockedSomePredecessors:
1550 DiagID = diag::warn_lock_some_predecessors;
1552 case LEK_LockedSomeLoopIterations:
1553 DiagID = diag::warn_expecting_lock_held_on_loop;
1555 case LEK_LockedAtEndOfFunction:
1556 DiagID = diag::warn_no_unlock;
1558 case LEK_NotLockedAtEndOfFunction:
1559 DiagID = diag::warn_expecting_locked;
1562 if (LocEndOfScope.isInvalid())
1563 LocEndOfScope = FunEndLocation;
1565 PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << Kind
1567 if (LocLocked.isValid()) {
1568 PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here)
1570 Warnings.emplace_back(std::move(Warning), getNotes(Note));
1573 Warnings.emplace_back(std::move(Warning), getNotes());
1576 void handleExclusiveAndShared(StringRef Kind, Name LockName,
1577 SourceLocation Loc1,
1578 SourceLocation Loc2) override {
1579 PartialDiagnosticAt Warning(Loc1,
1580 S.PDiag(diag::warn_lock_exclusive_and_shared)
1581 << Kind << LockName);
1582 PartialDiagnosticAt Note(Loc2, S.PDiag(diag::note_lock_exclusive_and_shared)
1583 << Kind << LockName);
1584 Warnings.emplace_back(std::move(Warning), getNotes(Note));
1587 void handleNoMutexHeld(StringRef Kind, const NamedDecl *D,
1588 ProtectedOperationKind POK, AccessKind AK,
1589 SourceLocation Loc) override {
1590 assert((POK == POK_VarAccess || POK == POK_VarDereference) &&
1591 "Only works for variables");
1592 unsigned DiagID = POK == POK_VarAccess?
1593 diag::warn_variable_requires_any_lock:
1594 diag::warn_var_deref_requires_any_lock;
1595 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
1596 << D->getNameAsString() << getLockKindFromAccessKind(AK));
1597 Warnings.emplace_back(std::move(Warning), getNotes());
1600 void handleMutexNotHeld(StringRef Kind, const NamedDecl *D,
1601 ProtectedOperationKind POK, Name LockName,
1602 LockKind LK, SourceLocation Loc,
1603 Name *PossibleMatch) override {
1604 unsigned DiagID = 0;
1605 if (PossibleMatch) {
1608 DiagID = diag::warn_variable_requires_lock_precise;
1610 case POK_VarDereference:
1611 DiagID = diag::warn_var_deref_requires_lock_precise;
1613 case POK_FunctionCall:
1614 DiagID = diag::warn_fun_requires_lock_precise;
1617 DiagID = diag::warn_guarded_pass_by_reference;
1619 case POK_PtPassByRef:
1620 DiagID = diag::warn_pt_guarded_pass_by_reference;
1623 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1624 << D->getNameAsString()
1626 PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
1628 if (Verbose && POK == POK_VarAccess) {
1629 PartialDiagnosticAt VNote(D->getLocation(),
1630 S.PDiag(diag::note_guarded_by_declared_here)
1631 << D->getNameAsString());
1632 Warnings.emplace_back(std::move(Warning), getNotes(Note, VNote));
1634 Warnings.emplace_back(std::move(Warning), getNotes(Note));
1638 DiagID = diag::warn_variable_requires_lock;
1640 case POK_VarDereference:
1641 DiagID = diag::warn_var_deref_requires_lock;
1643 case POK_FunctionCall:
1644 DiagID = diag::warn_fun_requires_lock;
1647 DiagID = diag::warn_guarded_pass_by_reference;
1649 case POK_PtPassByRef:
1650 DiagID = diag::warn_pt_guarded_pass_by_reference;
1653 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1654 << D->getNameAsString()
1656 if (Verbose && POK == POK_VarAccess) {
1657 PartialDiagnosticAt Note(D->getLocation(),
1658 S.PDiag(diag::note_guarded_by_declared_here)
1659 << D->getNameAsString());
1660 Warnings.emplace_back(std::move(Warning), getNotes(Note));
1662 Warnings.emplace_back(std::move(Warning), getNotes());
1666 void handleNegativeNotHeld(StringRef Kind, Name LockName, Name Neg,
1667 SourceLocation Loc) override {
1668 PartialDiagnosticAt Warning(Loc,
1669 S.PDiag(diag::warn_acquire_requires_negative_cap)
1670 << Kind << LockName << Neg);
1671 Warnings.emplace_back(std::move(Warning), getNotes());
1675 void handleFunExcludesLock(StringRef Kind, Name FunName, Name LockName,
1676 SourceLocation Loc) override {
1677 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_fun_excludes_mutex)
1678 << Kind << FunName << LockName);
1679 Warnings.emplace_back(std::move(Warning), getNotes());
1682 void handleLockAcquiredBefore(StringRef Kind, Name L1Name, Name L2Name,
1683 SourceLocation Loc) override {
1684 PartialDiagnosticAt Warning(Loc,
1685 S.PDiag(diag::warn_acquired_before) << Kind << L1Name << L2Name);
1686 Warnings.emplace_back(std::move(Warning), getNotes());
1689 void handleBeforeAfterCycle(Name L1Name, SourceLocation Loc) override {
1690 PartialDiagnosticAt Warning(Loc,
1691 S.PDiag(diag::warn_acquired_before_after_cycle) << L1Name);
1692 Warnings.emplace_back(std::move(Warning), getNotes());
1695 void enterFunction(const FunctionDecl* FD) override {
1696 CurrentFunction = FD;
1699 void leaveFunction(const FunctionDecl* FD) override {
1700 CurrentFunction = 0;
1704 } // namespace threadSafety
1705 } // namespace clang
1707 //===----------------------------------------------------------------------===//
1709 //===----------------------------------------------------------------------===//
1712 namespace consumed {
1714 class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase {
1721 ConsumedWarningsHandler(Sema &S) : S(S) {}
1723 void emitDiagnostics() override {
1724 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
1725 for (const auto &Diag : Warnings) {
1726 S.Diag(Diag.first.first, Diag.first.second);
1727 for (const auto &Note : Diag.second)
1728 S.Diag(Note.first, Note.second);
1732 void warnLoopStateMismatch(SourceLocation Loc,
1733 StringRef VariableName) override {
1734 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_loop_state_mismatch) <<
1737 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1740 void warnParamReturnTypestateMismatch(SourceLocation Loc,
1741 StringRef VariableName,
1742 StringRef ExpectedState,
1743 StringRef ObservedState) override {
1745 PartialDiagnosticAt Warning(Loc, S.PDiag(
1746 diag::warn_param_return_typestate_mismatch) << VariableName <<
1747 ExpectedState << ObservedState);
1749 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1752 void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
1753 StringRef ObservedState) override {
1755 PartialDiagnosticAt Warning(Loc, S.PDiag(
1756 diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState);
1758 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1761 void warnReturnTypestateForUnconsumableType(SourceLocation Loc,
1762 StringRef TypeName) override {
1763 PartialDiagnosticAt Warning(Loc, S.PDiag(
1764 diag::warn_return_typestate_for_unconsumable_type) << TypeName);
1766 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1769 void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
1770 StringRef ObservedState) override {
1772 PartialDiagnosticAt Warning(Loc, S.PDiag(
1773 diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState);
1775 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1778 void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State,
1779 SourceLocation Loc) override {
1781 PartialDiagnosticAt Warning(Loc, S.PDiag(
1782 diag::warn_use_of_temp_in_invalid_state) << MethodName << State);
1784 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1787 void warnUseInInvalidState(StringRef MethodName, StringRef VariableName,
1788 StringRef State, SourceLocation Loc) override {
1790 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_invalid_state) <<
1791 MethodName << VariableName << State);
1793 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1798 //===----------------------------------------------------------------------===//
1799 // AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
1800 // warnings on a function, method, or block.
1801 //===----------------------------------------------------------------------===//
1803 clang::sema::AnalysisBasedWarnings::Policy::Policy() {
1804 enableCheckFallThrough = 1;
1805 enableCheckUnreachable = 0;
1806 enableThreadSafetyAnalysis = 0;
1807 enableConsumedAnalysis = 0;
1810 static unsigned isEnabled(DiagnosticsEngine &D, unsigned diag) {
1811 return (unsigned)!D.isIgnored(diag, SourceLocation());
1814 clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
1816 NumFunctionsAnalyzed(0),
1817 NumFunctionsWithBadCFGs(0),
1819 MaxCFGBlocksPerFunction(0),
1820 NumUninitAnalysisFunctions(0),
1821 NumUninitAnalysisVariables(0),
1822 MaxUninitAnalysisVariablesPerFunction(0),
1823 NumUninitAnalysisBlockVisits(0),
1824 MaxUninitAnalysisBlockVisitsPerFunction(0) {
1826 using namespace diag;
1827 DiagnosticsEngine &D = S.getDiagnostics();
1829 DefaultPolicy.enableCheckUnreachable =
1830 isEnabled(D, warn_unreachable) ||
1831 isEnabled(D, warn_unreachable_break) ||
1832 isEnabled(D, warn_unreachable_return) ||
1833 isEnabled(D, warn_unreachable_loop_increment);
1835 DefaultPolicy.enableThreadSafetyAnalysis =
1836 isEnabled(D, warn_double_lock);
1838 DefaultPolicy.enableConsumedAnalysis =
1839 isEnabled(D, warn_use_in_invalid_state);
1842 static void flushDiagnostics(Sema &S, const sema::FunctionScopeInfo *fscope) {
1843 for (const auto &D : fscope->PossiblyUnreachableDiags)
1844 S.Diag(D.Loc, D.PD);
1848 AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
1849 sema::FunctionScopeInfo *fscope,
1850 const Decl *D, const BlockExpr *blkExpr) {
1852 // We avoid doing analysis-based warnings when there are errors for
1854 // (1) The CFGs often can't be constructed (if the body is invalid), so
1855 // don't bother trying.
1856 // (2) The code already has problems; running the analysis just takes more
1858 DiagnosticsEngine &Diags = S.getDiagnostics();
1860 // Do not do any analysis for declarations in system headers if we are
1861 // going to just ignore them.
1862 if (Diags.getSuppressSystemWarnings() &&
1863 S.SourceMgr.isInSystemHeader(D->getLocation()))
1866 // For code in dependent contexts, we'll do this at instantiation time.
1867 if (cast<DeclContext>(D)->isDependentContext())
1870 if (Diags.hasUncompilableErrorOccurred() || Diags.hasFatalErrorOccurred()) {
1871 // Flush out any possibly unreachable diagnostics.
1872 flushDiagnostics(S, fscope);
1876 const Stmt *Body = D->getBody();
1879 // Construct the analysis context with the specified CFG build options.
1880 AnalysisDeclContext AC(/* AnalysisDeclContextManager */ nullptr, D);
1882 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
1883 // explosion for destructors that can result and the compile time hit.
1884 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
1885 AC.getCFGBuildOptions().AddEHEdges = false;
1886 AC.getCFGBuildOptions().AddInitializers = true;
1887 AC.getCFGBuildOptions().AddImplicitDtors = true;
1888 AC.getCFGBuildOptions().AddTemporaryDtors = true;
1889 AC.getCFGBuildOptions().AddCXXNewAllocator = false;
1890 AC.getCFGBuildOptions().AddCXXDefaultInitExprInCtors = true;
1892 // Force that certain expressions appear as CFGElements in the CFG. This
1893 // is used to speed up various analyses.
1894 // FIXME: This isn't the right factoring. This is here for initial
1895 // prototyping, but we need a way for analyses to say what expressions they
1896 // expect to always be CFGElements and then fill in the BuildOptions
1897 // appropriately. This is essentially a layering violation.
1898 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis ||
1899 P.enableConsumedAnalysis) {
1900 // Unreachable code analysis and thread safety require a linearized CFG.
1901 AC.getCFGBuildOptions().setAllAlwaysAdd();
1904 AC.getCFGBuildOptions()
1905 .setAlwaysAdd(Stmt::BinaryOperatorClass)
1906 .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
1907 .setAlwaysAdd(Stmt::BlockExprClass)
1908 .setAlwaysAdd(Stmt::CStyleCastExprClass)
1909 .setAlwaysAdd(Stmt::DeclRefExprClass)
1910 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
1911 .setAlwaysAdd(Stmt::UnaryOperatorClass)
1912 .setAlwaysAdd(Stmt::AttributedStmtClass);
1915 // Install the logical handler for -Wtautological-overlap-compare
1916 std::unique_ptr<LogicalErrorHandler> LEH;
1917 if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
1918 D->getLocStart())) {
1919 LEH.reset(new LogicalErrorHandler(S));
1920 AC.getCFGBuildOptions().Observer = LEH.get();
1923 // Emit delayed diagnostics.
1924 if (!fscope->PossiblyUnreachableDiags.empty()) {
1925 bool analyzed = false;
1927 // Register the expressions with the CFGBuilder.
1928 for (const auto &D : fscope->PossiblyUnreachableDiags) {
1930 AC.registerForcedBlockExpression(D.stmt);
1935 for (const auto &D : fscope->PossiblyUnreachableDiags) {
1936 bool processed = false;
1938 const CFGBlock *block = AC.getBlockForRegisteredExpression(D.stmt);
1939 CFGReverseBlockReachabilityAnalysis *cra =
1940 AC.getCFGReachablityAnalysis();
1941 // FIXME: We should be able to assert that block is non-null, but
1942 // the CFG analysis can skip potentially-evaluated expressions in
1943 // edge cases; see test/Sema/vla-2.c.
1945 // Can this block be reached from the entrance?
1946 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
1947 S.Diag(D.Loc, D.PD);
1952 // Emit the warning anyway if we cannot map to a basic block.
1953 S.Diag(D.Loc, D.PD);
1959 flushDiagnostics(S, fscope);
1963 // Warning: check missing 'return'
1964 if (P.enableCheckFallThrough) {
1965 const CheckFallThroughDiagnostics &CD =
1966 (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
1967 : (isa<CXXMethodDecl>(D) &&
1968 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
1969 cast<CXXMethodDecl>(D)->getParent()->isLambda())
1970 ? CheckFallThroughDiagnostics::MakeForLambda()
1971 : CheckFallThroughDiagnostics::MakeForFunction(D));
1972 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
1975 // Warning: check for unreachable code
1976 if (P.enableCheckUnreachable) {
1977 // Only check for unreachable code on non-template instantiations.
1978 // Different template instantiations can effectively change the control-flow
1979 // and it is very difficult to prove that a snippet of code in a template
1980 // is unreachable for all instantiations.
1981 bool isTemplateInstantiation = false;
1982 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
1983 isTemplateInstantiation = Function->isTemplateInstantiation();
1984 if (!isTemplateInstantiation)
1985 CheckUnreachable(S, AC);
1988 // Check for thread safety violations
1989 if (P.enableThreadSafetyAnalysis) {
1990 SourceLocation FL = AC.getDecl()->getLocation();
1991 SourceLocation FEL = AC.getDecl()->getLocEnd();
1992 threadSafety::ThreadSafetyReporter Reporter(S, FL, FEL);
1993 if (!Diags.isIgnored(diag::warn_thread_safety_beta, D->getLocStart()))
1994 Reporter.setIssueBetaWarnings(true);
1995 if (!Diags.isIgnored(diag::warn_thread_safety_verbose, D->getLocStart()))
1996 Reporter.setVerbose(true);
1998 threadSafety::runThreadSafetyAnalysis(AC, Reporter,
1999 &S.ThreadSafetyDeclCache);
2000 Reporter.emitDiagnostics();
2003 // Check for violations of consumed properties.
2004 if (P.enableConsumedAnalysis) {
2005 consumed::ConsumedWarningsHandler WarningHandler(S);
2006 consumed::ConsumedAnalyzer Analyzer(WarningHandler);
2010 if (!Diags.isIgnored(diag::warn_uninit_var, D->getLocStart()) ||
2011 !Diags.isIgnored(diag::warn_sometimes_uninit_var, D->getLocStart()) ||
2012 !Diags.isIgnored(diag::warn_maybe_uninit_var, D->getLocStart())) {
2013 if (CFG *cfg = AC.getCFG()) {
2014 UninitValsDiagReporter reporter(S);
2015 UninitVariablesAnalysisStats stats;
2016 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
2017 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
2020 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
2021 ++NumUninitAnalysisFunctions;
2022 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
2023 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
2024 MaxUninitAnalysisVariablesPerFunction =
2025 std::max(MaxUninitAnalysisVariablesPerFunction,
2026 stats.NumVariablesAnalyzed);
2027 MaxUninitAnalysisBlockVisitsPerFunction =
2028 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
2029 stats.NumBlockVisits);
2034 bool FallThroughDiagFull =
2035 !Diags.isIgnored(diag::warn_unannotated_fallthrough, D->getLocStart());
2036 bool FallThroughDiagPerFunction = !Diags.isIgnored(
2037 diag::warn_unannotated_fallthrough_per_function, D->getLocStart());
2038 if (FallThroughDiagFull || FallThroughDiagPerFunction) {
2039 DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
2042 if (S.getLangOpts().ObjCARCWeak &&
2043 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, D->getLocStart()))
2044 diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
2047 // Check for infinite self-recursion in functions
2048 if (!Diags.isIgnored(diag::warn_infinite_recursive_function,
2049 D->getLocStart())) {
2050 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2051 checkRecursiveFunction(S, FD, Body, AC);
2055 // If none of the previous checks caused a CFG build, trigger one here
2056 // for -Wtautological-overlap-compare
2057 if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
2058 D->getLocStart())) {
2062 // Collect statistics about the CFG if it was built.
2063 if (S.CollectStats && AC.isCFGBuilt()) {
2064 ++NumFunctionsAnalyzed;
2065 if (CFG *cfg = AC.getCFG()) {
2066 // If we successfully built a CFG for this context, record some more
2067 // detail information about it.
2068 NumCFGBlocks += cfg->getNumBlockIDs();
2069 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
2070 cfg->getNumBlockIDs());
2072 ++NumFunctionsWithBadCFGs;
2077 void clang::sema::AnalysisBasedWarnings::PrintStats() const {
2078 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
2080 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
2081 unsigned AvgCFGBlocksPerFunction =
2082 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
2083 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
2084 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
2085 << " " << NumCFGBlocks << " CFG blocks built.\n"
2086 << " " << AvgCFGBlocksPerFunction
2087 << " average CFG blocks per function.\n"
2088 << " " << MaxCFGBlocksPerFunction
2089 << " max CFG blocks per function.\n";
2091 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
2092 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
2093 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
2094 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
2095 llvm::errs() << NumUninitAnalysisFunctions
2096 << " functions analyzed for uninitialiazed variables\n"
2097 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
2098 << " " << AvgUninitVariablesPerFunction
2099 << " average variables per function.\n"
2100 << " " << MaxUninitAnalysisVariablesPerFunction
2101 << " max variables per function.\n"
2102 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
2103 << " " << AvgUninitBlockVisitsPerFunction
2104 << " average block visits per function.\n"
2105 << " " << MaxUninitAnalysisBlockVisitsPerFunction
2106 << " max block visits per function.\n";