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 {
60 UnreachableCodeHandler(Sema &s) : S(s) {}
62 void HandleUnreachable(reachable_code::UnreachableKind UK,
64 SourceRange SilenceableCondVal,
66 SourceRange R2) override {
67 unsigned diag = diag::warn_unreachable;
69 case reachable_code::UK_Break:
70 diag = diag::warn_unreachable_break;
72 case reachable_code::UK_Return:
73 diag = diag::warn_unreachable_return;
75 case reachable_code::UK_Loop_Increment:
76 diag = diag::warn_unreachable_loop_increment;
78 case reachable_code::UK_Other:
82 S.Diag(L, diag) << R1 << R2;
84 SourceLocation Open = SilenceableCondVal.getBegin();
86 SourceLocation Close = SilenceableCondVal.getEnd();
87 Close = S.getLocForEndOfToken(Close);
88 if (Close.isValid()) {
89 S.Diag(Open, diag::note_unreachable_silence)
90 << FixItHint::CreateInsertion(Open, "/* DISABLES CODE */ (")
91 << FixItHint::CreateInsertion(Close, ")");
96 } // anonymous namespace
98 /// CheckUnreachable - Check for unreachable code.
99 static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) {
100 // As a heuristic prune all diagnostics not in the main file. Currently
101 // the majority of warnings in headers are false positives. These
102 // are largely caused by configuration state, e.g. preprocessor
103 // defined code, etc.
105 // Note that this is also a performance optimization. Analyzing
106 // headers many times can be expensive.
107 if (!S.getSourceManager().isInMainFile(AC.getDecl()->getLocStart()))
110 UnreachableCodeHandler UC(S);
111 reachable_code::FindUnreachableCode(AC, S.getPreprocessor(), UC);
115 /// \brief Warn on logical operator errors in CFGBuilder
116 class LogicalErrorHandler : public CFGCallback {
120 LogicalErrorHandler(Sema &S) : CFGCallback(), S(S) {}
122 static bool HasMacroID(const Expr *E) {
123 if (E->getExprLoc().isMacroID())
126 // Recurse to children.
127 for (const Stmt *SubStmt : E->children())
128 if (const Expr *SubExpr = dyn_cast_or_null<Expr>(SubStmt))
129 if (HasMacroID(SubExpr))
135 void compareAlwaysTrue(const BinaryOperator *B, bool isAlwaysTrue) override {
139 SourceRange DiagRange = B->getSourceRange();
140 S.Diag(B->getExprLoc(), diag::warn_tautological_overlap_comparison)
141 << DiagRange << isAlwaysTrue;
144 void compareBitwiseEquality(const BinaryOperator *B,
145 bool isAlwaysTrue) override {
149 SourceRange DiagRange = B->getSourceRange();
150 S.Diag(B->getExprLoc(), diag::warn_comparison_bitwise_always)
151 << DiagRange << isAlwaysTrue;
154 } // anonymous namespace
156 //===----------------------------------------------------------------------===//
157 // Check for infinite self-recursion in functions
158 //===----------------------------------------------------------------------===//
160 // Returns true if the function is called anywhere within the CFGBlock.
161 // For member functions, the additional condition of being call from the
162 // this pointer is required.
163 static bool hasRecursiveCallInPath(const FunctionDecl *FD, CFGBlock &Block) {
164 // Process all the Stmt's in this block to find any calls to FD.
165 for (const auto &B : Block) {
166 if (B.getKind() != CFGElement::Statement)
169 const CallExpr *CE = dyn_cast<CallExpr>(B.getAs<CFGStmt>()->getStmt());
170 if (!CE || !CE->getCalleeDecl() ||
171 CE->getCalleeDecl()->getCanonicalDecl() != FD)
174 // Skip function calls which are qualified with a templated class.
175 if (const DeclRefExpr *DRE =
176 dyn_cast<DeclRefExpr>(CE->getCallee()->IgnoreParenImpCasts())) {
177 if (NestedNameSpecifier *NNS = DRE->getQualifier()) {
178 if (NNS->getKind() == NestedNameSpecifier::TypeSpec &&
179 isa<TemplateSpecializationType>(NNS->getAsType())) {
185 const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE);
186 if (!MCE || isa<CXXThisExpr>(MCE->getImplicitObjectArgument()) ||
187 !MCE->getMethodDecl()->isVirtual())
193 // All blocks are in one of three states. States are ordered so that blocks
194 // can only move to higher states.
195 enum RecursiveState {
198 FoundPathWithNoRecursiveCall
201 // Returns true if there exists a path to the exit block and every path
202 // to the exit block passes through a call to FD.
203 static bool checkForRecursiveFunctionCall(const FunctionDecl *FD, CFG *cfg) {
205 const unsigned ExitID = cfg->getExit().getBlockID();
207 // Mark all nodes as FoundNoPath, then set the status of the entry block.
208 SmallVector<RecursiveState, 16> States(cfg->getNumBlockIDs(), FoundNoPath);
209 States[cfg->getEntry().getBlockID()] = FoundPathWithNoRecursiveCall;
211 // Make the processing stack and seed it with the entry block.
212 SmallVector<CFGBlock *, 16> Stack;
213 Stack.push_back(&cfg->getEntry());
215 while (!Stack.empty()) {
216 CFGBlock *CurBlock = Stack.back();
219 unsigned ID = CurBlock->getBlockID();
220 RecursiveState CurState = States[ID];
222 if (CurState == FoundPathWithNoRecursiveCall) {
223 // Found a path to the exit node without a recursive call.
227 // Only change state if the block has a recursive call.
228 if (hasRecursiveCallInPath(FD, *CurBlock))
229 CurState = FoundPath;
232 // Loop over successor blocks and add them to the Stack if their state
234 for (auto I = CurBlock->succ_begin(), E = CurBlock->succ_end(); I != E; ++I)
236 unsigned next_ID = (*I)->getBlockID();
237 if (States[next_ID] < CurState) {
238 States[next_ID] = CurState;
244 // Return true if the exit node is reachable, and only reachable through
246 return States[ExitID] == FoundPath;
249 static void checkRecursiveFunction(Sema &S, const FunctionDecl *FD,
250 const Stmt *Body, AnalysisDeclContext &AC) {
251 FD = FD->getCanonicalDecl();
253 // Only run on non-templated functions and non-templated members of
254 // templated classes.
255 if (FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate &&
256 FD->getTemplatedKind() != FunctionDecl::TK_MemberSpecialization)
259 CFG *cfg = AC.getCFG();
262 // If the exit block is unreachable, skip processing the function.
263 if (cfg->getExit().pred_empty())
266 // Emit diagnostic if a recursive function call is detected for all paths.
267 if (checkForRecursiveFunctionCall(FD, cfg))
268 S.Diag(Body->getLocStart(), diag::warn_infinite_recursive_function);
271 //===----------------------------------------------------------------------===//
272 // Check for missing return value.
273 //===----------------------------------------------------------------------===//
275 enum ControlFlowKind {
280 NeverFallThroughOrReturn
283 /// CheckFallThrough - Check that we don't fall off the end of a
284 /// Statement that should return a value.
286 /// \returns AlwaysFallThrough iff we always fall off the end of the statement,
287 /// MaybeFallThrough iff we might or might not fall off the end,
288 /// NeverFallThroughOrReturn iff we never fall off the end of the statement or
289 /// return. We assume NeverFallThrough iff we never fall off the end of the
290 /// statement but we may return. We assume that functions not marked noreturn
292 static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
293 CFG *cfg = AC.getCFG();
294 if (!cfg) return UnknownFallThrough;
296 // The CFG leaves in dead things, and we don't want the dead code paths to
297 // confuse us, so we mark all live things first.
298 llvm::BitVector live(cfg->getNumBlockIDs());
299 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
302 bool AddEHEdges = AC.getAddEHEdges();
303 if (!AddEHEdges && count != cfg->getNumBlockIDs())
304 // When there are things remaining dead, and we didn't add EH edges
305 // from CallExprs to the catch clauses, we have to go back and
306 // mark them as live.
307 for (const auto *B : *cfg) {
308 if (!live[B->getBlockID()]) {
309 if (B->pred_begin() == B->pred_end()) {
310 if (B->getTerminator() && isa<CXXTryStmt>(B->getTerminator()))
311 // When not adding EH edges from calls, catch clauses
312 // can otherwise seem dead. Avoid noting them as dead.
313 count += reachable_code::ScanReachableFromBlock(B, live);
319 // Now we know what is live, we check the live precessors of the exit block
320 // and look for fall through paths, being careful to ignore normal returns,
321 // and exceptional paths.
322 bool HasLiveReturn = false;
323 bool HasFakeEdge = false;
324 bool HasPlainEdge = false;
325 bool HasAbnormalEdge = false;
327 // Ignore default cases that aren't likely to be reachable because all
328 // enums in a switch(X) have explicit case statements.
329 CFGBlock::FilterOptions FO;
330 FO.IgnoreDefaultsWithCoveredEnums = 1;
332 for (CFGBlock::filtered_pred_iterator
333 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
334 const CFGBlock& B = **I;
335 if (!live[B.getBlockID()])
338 // Skip blocks which contain an element marked as no-return. They don't
339 // represent actually viable edges into the exit block, so mark them as
341 if (B.hasNoReturnElement()) {
342 HasAbnormalEdge = true;
346 // Destructors can appear after the 'return' in the CFG. This is
347 // normal. We need to look pass the destructors for the return
348 // statement (if it exists).
349 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
351 for ( ; ri != re ; ++ri)
352 if (ri->getAs<CFGStmt>())
355 // No more CFGElements in the block?
357 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
358 HasAbnormalEdge = true;
361 // A labeled empty statement, or the entry block...
366 CFGStmt CS = ri->castAs<CFGStmt>();
367 const Stmt *S = CS.getStmt();
368 if (isa<ReturnStmt>(S) || isa<CoreturnStmt>(S)) {
369 HasLiveReturn = true;
372 if (isa<ObjCAtThrowStmt>(S)) {
376 if (isa<CXXThrowExpr>(S)) {
380 if (isa<MSAsmStmt>(S)) {
381 // TODO: Verify this is correct.
383 HasLiveReturn = true;
386 if (isa<CXXTryStmt>(S)) {
387 HasAbnormalEdge = true;
390 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
392 HasAbnormalEdge = true;
400 return NeverFallThrough;
401 return NeverFallThroughOrReturn;
403 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
404 return MaybeFallThrough;
405 // This says AlwaysFallThrough for calls to functions that are not marked
406 // noreturn, that don't return. If people would like this warning to be more
407 // accurate, such functions should be marked as noreturn.
408 return AlwaysFallThrough;
413 struct CheckFallThroughDiagnostics {
414 unsigned diag_MaybeFallThrough_HasNoReturn;
415 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
416 unsigned diag_AlwaysFallThrough_HasNoReturn;
417 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
418 unsigned diag_NeverFallThroughOrReturn;
419 enum { Function, Block, Lambda, Coroutine } funMode;
420 SourceLocation FuncLoc;
422 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
423 CheckFallThroughDiagnostics D;
424 D.FuncLoc = Func->getLocation();
425 D.diag_MaybeFallThrough_HasNoReturn =
426 diag::warn_falloff_noreturn_function;
427 D.diag_MaybeFallThrough_ReturnsNonVoid =
428 diag::warn_maybe_falloff_nonvoid_function;
429 D.diag_AlwaysFallThrough_HasNoReturn =
430 diag::warn_falloff_noreturn_function;
431 D.diag_AlwaysFallThrough_ReturnsNonVoid =
432 diag::warn_falloff_nonvoid_function;
434 // Don't suggest that virtual functions be marked "noreturn", since they
435 // might be overridden by non-noreturn functions.
436 bool isVirtualMethod = false;
437 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
438 isVirtualMethod = Method->isVirtual();
440 // Don't suggest that template instantiations be marked "noreturn"
441 bool isTemplateInstantiation = false;
442 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
443 isTemplateInstantiation = Function->isTemplateInstantiation();
445 if (!isVirtualMethod && !isTemplateInstantiation)
446 D.diag_NeverFallThroughOrReturn =
447 diag::warn_suggest_noreturn_function;
449 D.diag_NeverFallThroughOrReturn = 0;
451 D.funMode = Function;
455 static CheckFallThroughDiagnostics MakeForCoroutine(const Decl *Func) {
456 CheckFallThroughDiagnostics D;
457 D.FuncLoc = Func->getLocation();
458 D.diag_MaybeFallThrough_HasNoReturn = 0;
459 D.diag_MaybeFallThrough_ReturnsNonVoid =
460 diag::warn_maybe_falloff_nonvoid_coroutine;
461 D.diag_AlwaysFallThrough_HasNoReturn = 0;
462 D.diag_AlwaysFallThrough_ReturnsNonVoid =
463 diag::warn_falloff_nonvoid_coroutine;
464 D.funMode = Coroutine;
468 static CheckFallThroughDiagnostics MakeForBlock() {
469 CheckFallThroughDiagnostics D;
470 D.diag_MaybeFallThrough_HasNoReturn =
471 diag::err_noreturn_block_has_return_expr;
472 D.diag_MaybeFallThrough_ReturnsNonVoid =
473 diag::err_maybe_falloff_nonvoid_block;
474 D.diag_AlwaysFallThrough_HasNoReturn =
475 diag::err_noreturn_block_has_return_expr;
476 D.diag_AlwaysFallThrough_ReturnsNonVoid =
477 diag::err_falloff_nonvoid_block;
478 D.diag_NeverFallThroughOrReturn = 0;
483 static CheckFallThroughDiagnostics MakeForLambda() {
484 CheckFallThroughDiagnostics D;
485 D.diag_MaybeFallThrough_HasNoReturn =
486 diag::err_noreturn_lambda_has_return_expr;
487 D.diag_MaybeFallThrough_ReturnsNonVoid =
488 diag::warn_maybe_falloff_nonvoid_lambda;
489 D.diag_AlwaysFallThrough_HasNoReturn =
490 diag::err_noreturn_lambda_has_return_expr;
491 D.diag_AlwaysFallThrough_ReturnsNonVoid =
492 diag::warn_falloff_nonvoid_lambda;
493 D.diag_NeverFallThroughOrReturn = 0;
498 bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
499 bool HasNoReturn) const {
500 if (funMode == Function) {
501 return (ReturnsVoid ||
502 D.isIgnored(diag::warn_maybe_falloff_nonvoid_function,
505 D.isIgnored(diag::warn_noreturn_function_has_return_expr,
508 D.isIgnored(diag::warn_suggest_noreturn_block, FuncLoc));
510 if (funMode == Coroutine) {
511 return (ReturnsVoid ||
512 D.isIgnored(diag::warn_maybe_falloff_nonvoid_function, FuncLoc) ||
513 D.isIgnored(diag::warn_maybe_falloff_nonvoid_coroutine,
517 // For blocks / lambdas.
518 return ReturnsVoid && !HasNoReturn;
522 } // anonymous namespace
524 /// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
525 /// function that should return a value. Check that we don't fall off the end
526 /// of a noreturn function. We assume that functions and blocks not marked
527 /// noreturn will return.
528 static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
529 const BlockExpr *blkExpr,
530 const CheckFallThroughDiagnostics& CD,
531 AnalysisDeclContext &AC) {
533 bool ReturnsVoid = false;
534 bool HasNoReturn = false;
536 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
537 if (const auto *CBody = dyn_cast<CoroutineBodyStmt>(Body))
538 ReturnsVoid = CBody->getFallthroughHandler() != nullptr;
540 ReturnsVoid = FD->getReturnType()->isVoidType();
541 HasNoReturn = FD->isNoReturn();
543 else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
544 ReturnsVoid = MD->getReturnType()->isVoidType();
545 HasNoReturn = MD->hasAttr<NoReturnAttr>();
547 else if (isa<BlockDecl>(D)) {
548 QualType BlockTy = blkExpr->getType();
549 if (const FunctionType *FT =
550 BlockTy->getPointeeType()->getAs<FunctionType>()) {
551 if (FT->getReturnType()->isVoidType())
553 if (FT->getNoReturnAttr())
558 DiagnosticsEngine &Diags = S.getDiagnostics();
560 // Short circuit for compilation speed.
561 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
564 SourceLocation LBrace = Body->getLocStart(), RBrace = Body->getLocEnd();
565 // Either in a function body compound statement, or a function-try-block.
566 switch (CheckFallThrough(AC)) {
567 case UnknownFallThrough:
570 case MaybeFallThrough:
572 S.Diag(RBrace, CD.diag_MaybeFallThrough_HasNoReturn);
573 else if (!ReturnsVoid)
574 S.Diag(RBrace, CD.diag_MaybeFallThrough_ReturnsNonVoid);
576 case AlwaysFallThrough:
578 S.Diag(RBrace, CD.diag_AlwaysFallThrough_HasNoReturn);
579 else if (!ReturnsVoid)
580 S.Diag(RBrace, CD.diag_AlwaysFallThrough_ReturnsNonVoid);
582 case NeverFallThroughOrReturn:
583 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
584 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
585 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 0 << FD;
586 } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
587 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 1 << MD;
589 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn);
593 case NeverFallThrough:
598 //===----------------------------------------------------------------------===//
600 //===----------------------------------------------------------------------===//
603 /// ContainsReference - A visitor class to search for references to
604 /// a particular declaration (the needle) within any evaluated component of an
605 /// expression (recursively).
606 class ContainsReference : public ConstEvaluatedExprVisitor<ContainsReference> {
608 const DeclRefExpr *Needle;
611 typedef ConstEvaluatedExprVisitor<ContainsReference> Inherited;
613 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
614 : Inherited(Context), FoundReference(false), Needle(Needle) {}
616 void VisitExpr(const Expr *E) {
617 // Stop evaluating if we already have a reference.
621 Inherited::VisitExpr(E);
624 void VisitDeclRefExpr(const DeclRefExpr *E) {
626 FoundReference = true;
628 Inherited::VisitDeclRefExpr(E);
631 bool doesContainReference() const { return FoundReference; }
633 } // anonymous namespace
635 static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
636 QualType VariableTy = VD->getType().getCanonicalType();
637 if (VariableTy->isBlockPointerType() &&
638 !VD->hasAttr<BlocksAttr>()) {
639 S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization)
641 << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
645 // Don't issue a fixit if there is already an initializer.
649 // Don't suggest a fixit inside macros.
650 if (VD->getLocEnd().isMacroID())
653 SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
655 // Suggest possible initialization (if any).
656 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
660 S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
661 << FixItHint::CreateInsertion(Loc, Init);
665 /// Create a fixit to remove an if-like statement, on the assumption that its
666 /// condition is CondVal.
667 static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
668 const Stmt *Else, bool CondVal,
669 FixItHint &Fixit1, FixItHint &Fixit2) {
671 // If condition is always true, remove all but the 'then'.
672 Fixit1 = FixItHint::CreateRemoval(
673 CharSourceRange::getCharRange(If->getLocStart(),
674 Then->getLocStart()));
676 SourceLocation ElseKwLoc = S.getLocForEndOfToken(Then->getLocEnd());
677 Fixit2 = FixItHint::CreateRemoval(
678 SourceRange(ElseKwLoc, Else->getLocEnd()));
681 // If condition is always false, remove all but the 'else'.
683 Fixit1 = FixItHint::CreateRemoval(
684 CharSourceRange::getCharRange(If->getLocStart(),
685 Else->getLocStart()));
687 Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
691 /// DiagUninitUse -- Helper function to produce a diagnostic for an
692 /// uninitialized use of a variable.
693 static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
694 bool IsCapturedByBlock) {
695 bool Diagnosed = false;
697 switch (Use.getKind()) {
698 case UninitUse::Always:
699 S.Diag(Use.getUser()->getLocStart(), diag::warn_uninit_var)
700 << VD->getDeclName() << IsCapturedByBlock
701 << Use.getUser()->getSourceRange();
704 case UninitUse::AfterDecl:
705 case UninitUse::AfterCall:
706 S.Diag(VD->getLocation(), diag::warn_sometimes_uninit_var)
707 << VD->getDeclName() << IsCapturedByBlock
708 << (Use.getKind() == UninitUse::AfterDecl ? 4 : 5)
709 << const_cast<DeclContext*>(VD->getLexicalDeclContext())
710 << VD->getSourceRange();
711 S.Diag(Use.getUser()->getLocStart(), diag::note_uninit_var_use)
712 << IsCapturedByBlock << Use.getUser()->getSourceRange();
715 case UninitUse::Maybe:
716 case UninitUse::Sometimes:
717 // Carry on to report sometimes-uninitialized branches, if possible,
718 // or a 'may be used uninitialized' diagnostic otherwise.
722 // Diagnose each branch which leads to a sometimes-uninitialized use.
723 for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
725 assert(Use.getKind() == UninitUse::Sometimes);
727 const Expr *User = Use.getUser();
728 const Stmt *Term = I->Terminator;
730 // Information used when building the diagnostic.
735 // FixIts to suppress the diagnostic by removing the dead condition.
736 // For all binary terminators, branch 0 is taken if the condition is true,
737 // and branch 1 is taken if the condition is false.
738 int RemoveDiagKind = -1;
739 const char *FixitStr =
740 S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
741 : (I->Output ? "1" : "0");
742 FixItHint Fixit1, Fixit2;
744 switch (Term ? Term->getStmtClass() : Stmt::DeclStmtClass) {
746 // Don't know how to report this. Just fall back to 'may be used
747 // uninitialized'. FIXME: Can this happen?
750 // "condition is true / condition is false".
751 case Stmt::IfStmtClass: {
752 const IfStmt *IS = cast<IfStmt>(Term);
755 Range = IS->getCond()->getSourceRange();
757 CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
758 I->Output, Fixit1, Fixit2);
761 case Stmt::ConditionalOperatorClass: {
762 const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
765 Range = CO->getCond()->getSourceRange();
767 CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
768 I->Output, Fixit1, Fixit2);
771 case Stmt::BinaryOperatorClass: {
772 const BinaryOperator *BO = cast<BinaryOperator>(Term);
773 if (!BO->isLogicalOp())
776 Str = BO->getOpcodeStr();
777 Range = BO->getLHS()->getSourceRange();
779 if ((BO->getOpcode() == BO_LAnd && I->Output) ||
780 (BO->getOpcode() == BO_LOr && !I->Output))
781 // true && y -> y, false || y -> y.
782 Fixit1 = FixItHint::CreateRemoval(SourceRange(BO->getLocStart(),
783 BO->getOperatorLoc()));
785 // false && y -> false, true || y -> true.
786 Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
790 // "loop is entered / loop is exited".
791 case Stmt::WhileStmtClass:
794 Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
796 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
798 case Stmt::ForStmtClass:
801 Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
804 Fixit1 = FixItHint::CreateRemoval(Range);
806 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
808 case Stmt::CXXForRangeStmtClass:
809 if (I->Output == 1) {
810 // The use occurs if a range-based for loop's body never executes.
811 // That may be impossible, and there's no syntactic fix for this,
812 // so treat it as a 'may be uninitialized' case.
817 Range = cast<CXXForRangeStmt>(Term)->getRangeInit()->getSourceRange();
820 // "condition is true / loop is exited".
821 case Stmt::DoStmtClass:
824 Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
826 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
829 // "switch case is taken".
830 case Stmt::CaseStmtClass:
833 Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
835 case Stmt::DefaultStmtClass:
838 Range = cast<DefaultStmt>(Term)->getDefaultLoc();
842 S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
843 << VD->getDeclName() << IsCapturedByBlock << DiagKind
844 << Str << I->Output << Range;
845 S.Diag(User->getLocStart(), diag::note_uninit_var_use)
846 << IsCapturedByBlock << User->getSourceRange();
847 if (RemoveDiagKind != -1)
848 S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
849 << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
855 S.Diag(Use.getUser()->getLocStart(), diag::warn_maybe_uninit_var)
856 << VD->getDeclName() << IsCapturedByBlock
857 << Use.getUser()->getSourceRange();
860 /// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
861 /// uninitialized variable. This manages the different forms of diagnostic
862 /// emitted for particular types of uses. Returns true if the use was diagnosed
863 /// as a warning. If a particular use is one we omit warnings for, returns
865 static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
866 const UninitUse &Use,
867 bool alwaysReportSelfInit = false) {
868 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
869 // Inspect the initializer of the variable declaration which is
870 // being referenced prior to its initialization. We emit
871 // specialized diagnostics for self-initialization, and we
872 // specifically avoid warning about self references which take the
877 // This is used to indicate to GCC that 'x' is intentionally left
878 // uninitialized. Proven code paths which access 'x' in
879 // an uninitialized state after this will still warn.
880 if (const Expr *Initializer = VD->getInit()) {
881 if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
884 ContainsReference CR(S.Context, DRE);
885 CR.Visit(Initializer);
886 if (CR.doesContainReference()) {
887 S.Diag(DRE->getLocStart(),
888 diag::warn_uninit_self_reference_in_init)
889 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
894 DiagUninitUse(S, VD, Use, false);
896 const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
897 if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
898 S.Diag(BE->getLocStart(),
899 diag::warn_uninit_byref_blockvar_captured_by_block)
900 << VD->getDeclName();
902 DiagUninitUse(S, VD, Use, true);
905 // Report where the variable was declared when the use wasn't within
906 // the initializer of that declaration & we didn't already suggest
907 // an initialization fixit.
908 if (!SuggestInitializationFixit(S, VD))
909 S.Diag(VD->getLocStart(), diag::note_var_declared_here)
910 << VD->getDeclName();
916 class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
918 FallthroughMapper(Sema &S)
919 : FoundSwitchStatements(false),
923 bool foundSwitchStatements() const { return FoundSwitchStatements; }
925 void markFallthroughVisited(const AttributedStmt *Stmt) {
926 bool Found = FallthroughStmts.erase(Stmt);
931 typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
933 const AttrStmts &getFallthroughStmts() const {
934 return FallthroughStmts;
937 void fillReachableBlocks(CFG *Cfg) {
938 assert(ReachableBlocks.empty() && "ReachableBlocks already filled");
939 std::deque<const CFGBlock *> BlockQueue;
941 ReachableBlocks.insert(&Cfg->getEntry());
942 BlockQueue.push_back(&Cfg->getEntry());
943 // Mark all case blocks reachable to avoid problems with switching on
944 // constants, covered enums, etc.
945 // These blocks can contain fall-through annotations, and we don't want to
946 // issue a warn_fallthrough_attr_unreachable for them.
947 for (const auto *B : *Cfg) {
948 const Stmt *L = B->getLabel();
949 if (L && isa<SwitchCase>(L) && ReachableBlocks.insert(B).second)
950 BlockQueue.push_back(B);
953 while (!BlockQueue.empty()) {
954 const CFGBlock *P = BlockQueue.front();
955 BlockQueue.pop_front();
956 for (CFGBlock::const_succ_iterator I = P->succ_begin(),
959 if (*I && ReachableBlocks.insert(*I).second)
960 BlockQueue.push_back(*I);
965 bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt) {
966 assert(!ReachableBlocks.empty() && "ReachableBlocks empty");
968 int UnannotatedCnt = 0;
971 std::deque<const CFGBlock*> BlockQueue(B.pred_begin(), B.pred_end());
972 while (!BlockQueue.empty()) {
973 const CFGBlock *P = BlockQueue.front();
974 BlockQueue.pop_front();
977 const Stmt *Term = P->getTerminator();
978 if (Term && isa<SwitchStmt>(Term))
979 continue; // Switch statement, good.
981 const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
982 if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
983 continue; // Previous case label has no statements, good.
985 const LabelStmt *L = dyn_cast_or_null<LabelStmt>(P->getLabel());
986 if (L && L->getSubStmt() == B.getLabel() && P->begin() == P->end())
987 continue; // Case label is preceded with a normal label, good.
989 if (!ReachableBlocks.count(P)) {
990 for (CFGBlock::const_reverse_iterator ElemIt = P->rbegin(),
992 ElemIt != ElemEnd; ++ElemIt) {
993 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>()) {
994 if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
995 S.Diag(AS->getLocStart(),
996 diag::warn_fallthrough_attr_unreachable);
997 markFallthroughVisited(AS);
1001 // Don't care about other unreachable statements.
1004 // If there are no unreachable statements, this may be a special
1007 // A a; // A has a destructor.
1010 // // <<<< This place is represented by a 'hanging' CFG block.
1015 const Stmt *LastStmt = getLastStmt(*P);
1016 if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
1017 markFallthroughVisited(AS);
1019 continue; // Fallthrough annotation, good.
1022 if (!LastStmt) { // This block contains no executable statements.
1023 // Traverse its predecessors.
1024 std::copy(P->pred_begin(), P->pred_end(),
1025 std::back_inserter(BlockQueue));
1031 return !!UnannotatedCnt;
1034 // RecursiveASTVisitor setup.
1035 bool shouldWalkTypesOfTypeLocs() const { return false; }
1037 bool VisitAttributedStmt(AttributedStmt *S) {
1038 if (asFallThroughAttr(S))
1039 FallthroughStmts.insert(S);
1043 bool VisitSwitchStmt(SwitchStmt *S) {
1044 FoundSwitchStatements = true;
1048 // We don't want to traverse local type declarations. We analyze their
1049 // methods separately.
1050 bool TraverseDecl(Decl *D) { return true; }
1052 // We analyze lambda bodies separately. Skip them here.
1053 bool TraverseLambdaBody(LambdaExpr *LE) { return true; }
1057 static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
1058 if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
1059 if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
1065 static const Stmt *getLastStmt(const CFGBlock &B) {
1066 if (const Stmt *Term = B.getTerminator())
1068 for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
1070 ElemIt != ElemEnd; ++ElemIt) {
1071 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>())
1072 return CS->getStmt();
1074 // Workaround to detect a statement thrown out by CFGBuilder:
1075 // case X: {} case Y:
1076 // case X: ; case Y:
1077 if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
1078 if (!isa<SwitchCase>(SW->getSubStmt()))
1079 return SW->getSubStmt();
1084 bool FoundSwitchStatements;
1085 AttrStmts FallthroughStmts;
1087 llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks;
1089 } // anonymous namespace
1091 static StringRef getFallthroughAttrSpelling(Preprocessor &PP,
1092 SourceLocation Loc) {
1093 TokenValue FallthroughTokens[] = {
1094 tok::l_square, tok::l_square,
1095 PP.getIdentifierInfo("fallthrough"),
1096 tok::r_square, tok::r_square
1099 TokenValue ClangFallthroughTokens[] = {
1100 tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
1101 tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
1102 tok::r_square, tok::r_square
1105 bool PreferClangAttr = !PP.getLangOpts().CPlusPlus1z;
1107 StringRef MacroName;
1108 if (PreferClangAttr)
1109 MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens);
1110 if (MacroName.empty())
1111 MacroName = PP.getLastMacroWithSpelling(Loc, FallthroughTokens);
1112 if (MacroName.empty() && !PreferClangAttr)
1113 MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens);
1114 if (MacroName.empty())
1115 MacroName = PreferClangAttr ? "[[clang::fallthrough]]" : "[[fallthrough]]";
1119 static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
1121 // Only perform this analysis when using C++11. There is no good workflow
1122 // for this warning when not using C++11. There is no good way to silence
1123 // the warning (no attribute is available) unless we are using C++11's support
1124 // for generalized attributes. Once could use pragmas to silence the warning,
1125 // but as a general solution that is gross and not in the spirit of this
1128 // NOTE: This an intermediate solution. There are on-going discussions on
1129 // how to properly support this warning outside of C++11 with an annotation.
1130 if (!AC.getASTContext().getLangOpts().CPlusPlus11)
1133 FallthroughMapper FM(S);
1134 FM.TraverseStmt(AC.getBody());
1136 if (!FM.foundSwitchStatements())
1139 if (PerFunction && FM.getFallthroughStmts().empty())
1142 CFG *Cfg = AC.getCFG();
1147 FM.fillReachableBlocks(Cfg);
1149 for (const CFGBlock *B : llvm::reverse(*Cfg)) {
1150 const Stmt *Label = B->getLabel();
1152 if (!Label || !isa<SwitchCase>(Label))
1157 if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt))
1160 S.Diag(Label->getLocStart(),
1161 PerFunction ? diag::warn_unannotated_fallthrough_per_function
1162 : diag::warn_unannotated_fallthrough);
1164 if (!AnnotatedCnt) {
1165 SourceLocation L = Label->getLocStart();
1168 if (S.getLangOpts().CPlusPlus11) {
1169 const Stmt *Term = B->getTerminator();
1170 // Skip empty cases.
1171 while (B->empty() && !Term && B->succ_size() == 1) {
1172 B = *B->succ_begin();
1173 Term = B->getTerminator();
1175 if (!(B->empty() && Term && isa<BreakStmt>(Term))) {
1176 Preprocessor &PP = S.getPreprocessor();
1177 StringRef AnnotationSpelling = getFallthroughAttrSpelling(PP, L);
1178 SmallString<64> TextToInsert(AnnotationSpelling);
1179 TextToInsert += "; ";
1180 S.Diag(L, diag::note_insert_fallthrough_fixit) <<
1181 AnnotationSpelling <<
1182 FixItHint::CreateInsertion(L, TextToInsert);
1185 S.Diag(L, diag::note_insert_break_fixit) <<
1186 FixItHint::CreateInsertion(L, "break; ");
1190 for (const auto *F : FM.getFallthroughStmts())
1191 S.Diag(F->getLocStart(), diag::err_fallthrough_attr_invalid_placement);
1194 static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
1199 switch (S->getStmtClass()) {
1200 case Stmt::ForStmtClass:
1201 case Stmt::WhileStmtClass:
1202 case Stmt::CXXForRangeStmtClass:
1203 case Stmt::ObjCForCollectionStmtClass:
1205 case Stmt::DoStmtClass: {
1206 const Expr *Cond = cast<DoStmt>(S)->getCond();
1208 if (!Cond->EvaluateAsInt(Val, Ctx))
1210 return Val.getBoolValue();
1215 } while ((S = PM.getParent(S)));
1220 static void diagnoseRepeatedUseOfWeak(Sema &S,
1221 const sema::FunctionScopeInfo *CurFn,
1223 const ParentMap &PM) {
1224 typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
1225 typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
1226 typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
1227 typedef std::pair<const Stmt *, WeakObjectUseMap::const_iterator>
1230 ASTContext &Ctx = S.getASTContext();
1232 const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
1234 // Extract all weak objects that are referenced more than once.
1235 SmallVector<StmtUsesPair, 8> UsesByStmt;
1236 for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
1238 const WeakUseVector &Uses = I->second;
1240 // Find the first read of the weak object.
1241 WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1242 for ( ; UI != UE; ++UI) {
1247 // If there were only writes to this object, don't warn.
1251 // If there was only one read, followed by any number of writes, and the
1252 // read is not within a loop, don't warn. Additionally, don't warn in a
1253 // loop if the base object is a local variable -- local variables are often
1254 // changed in loops.
1255 if (UI == Uses.begin()) {
1256 WeakUseVector::const_iterator UI2 = UI;
1257 for (++UI2; UI2 != UE; ++UI2)
1258 if (UI2->isUnsafe())
1262 if (!isInLoop(Ctx, PM, UI->getUseExpr()))
1265 const WeakObjectProfileTy &Profile = I->first;
1266 if (!Profile.isExactProfile())
1269 const NamedDecl *Base = Profile.getBase();
1271 Base = Profile.getProperty();
1272 assert(Base && "A profile always has a base or property.");
1274 if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
1275 if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
1280 UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
1283 if (UsesByStmt.empty())
1286 // Sort by first use so that we emit the warnings in a deterministic order.
1287 SourceManager &SM = S.getSourceManager();
1288 std::sort(UsesByStmt.begin(), UsesByStmt.end(),
1289 [&SM](const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
1290 return SM.isBeforeInTranslationUnit(LHS.first->getLocStart(),
1291 RHS.first->getLocStart());
1294 // Classify the current code body for better warning text.
1295 // This enum should stay in sync with the cases in
1296 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1297 // FIXME: Should we use a common classification enum and the same set of
1298 // possibilities all throughout Sema?
1306 if (isa<sema::BlockScopeInfo>(CurFn))
1307 FunctionKind = Block;
1308 else if (isa<sema::LambdaScopeInfo>(CurFn))
1309 FunctionKind = Lambda;
1310 else if (isa<ObjCMethodDecl>(D))
1311 FunctionKind = Method;
1313 FunctionKind = Function;
1315 // Iterate through the sorted problems and emit warnings for each.
1316 for (const auto &P : UsesByStmt) {
1317 const Stmt *FirstRead = P.first;
1318 const WeakObjectProfileTy &Key = P.second->first;
1319 const WeakUseVector &Uses = P.second->second;
1321 // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
1322 // may not contain enough information to determine that these are different
1323 // properties. We can only be 100% sure of a repeated use in certain cases,
1324 // and we adjust the diagnostic kind accordingly so that the less certain
1325 // case can be turned off if it is too noisy.
1327 if (Key.isExactProfile())
1328 DiagKind = diag::warn_arc_repeated_use_of_weak;
1330 DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
1332 // Classify the weak object being accessed for better warning text.
1333 // This enum should stay in sync with the cases in
1334 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1342 const NamedDecl *KeyProp = Key.getProperty();
1343 if (isa<VarDecl>(KeyProp))
1344 ObjectKind = Variable;
1345 else if (isa<ObjCPropertyDecl>(KeyProp))
1346 ObjectKind = Property;
1347 else if (isa<ObjCMethodDecl>(KeyProp))
1348 ObjectKind = ImplicitProperty;
1349 else if (isa<ObjCIvarDecl>(KeyProp))
1352 llvm_unreachable("Unexpected weak object kind!");
1354 // Do not warn about IBOutlet weak property receivers being set to null
1355 // since they are typically only used from the main thread.
1356 if (const ObjCPropertyDecl *Prop = dyn_cast<ObjCPropertyDecl>(KeyProp))
1357 if (Prop->hasAttr<IBOutletAttr>())
1360 // Show the first time the object was read.
1361 S.Diag(FirstRead->getLocStart(), DiagKind)
1362 << int(ObjectKind) << KeyProp << int(FunctionKind)
1363 << FirstRead->getSourceRange();
1365 // Print all the other accesses as notes.
1366 for (const auto &Use : Uses) {
1367 if (Use.getUseExpr() == FirstRead)
1369 S.Diag(Use.getUseExpr()->getLocStart(),
1370 diag::note_arc_weak_also_accessed_here)
1371 << Use.getUseExpr()->getSourceRange();
1377 class UninitValsDiagReporter : public UninitVariablesHandler {
1379 typedef SmallVector<UninitUse, 2> UsesVec;
1380 typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType;
1381 // Prefer using MapVector to DenseMap, so that iteration order will be
1382 // the same as insertion order. This is needed to obtain a deterministic
1383 // order of diagnostics when calling flushDiagnostics().
1384 typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap;
1388 UninitValsDiagReporter(Sema &S) : S(S) {}
1389 ~UninitValsDiagReporter() override { flushDiagnostics(); }
1391 MappedType &getUses(const VarDecl *vd) {
1392 MappedType &V = uses[vd];
1393 if (!V.getPointer())
1394 V.setPointer(new UsesVec());
1398 void handleUseOfUninitVariable(const VarDecl *vd,
1399 const UninitUse &use) override {
1400 getUses(vd).getPointer()->push_back(use);
1403 void handleSelfInit(const VarDecl *vd) override {
1404 getUses(vd).setInt(true);
1407 void flushDiagnostics() {
1408 for (const auto &P : uses) {
1409 const VarDecl *vd = P.first;
1410 const MappedType &V = P.second;
1412 UsesVec *vec = V.getPointer();
1413 bool hasSelfInit = V.getInt();
1415 // Specially handle the case where we have uses of an uninitialized
1416 // variable, but the root cause is an idiomatic self-init. We want
1417 // to report the diagnostic at the self-init since that is the root cause.
1418 if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
1419 DiagnoseUninitializedUse(S, vd,
1420 UninitUse(vd->getInit()->IgnoreParenCasts(),
1421 /* isAlwaysUninit */ true),
1422 /* alwaysReportSelfInit */ true);
1424 // Sort the uses by their SourceLocations. While not strictly
1425 // guaranteed to produce them in line/column order, this will provide
1426 // a stable ordering.
1427 std::sort(vec->begin(), vec->end(),
1428 [](const UninitUse &a, const UninitUse &b) {
1429 // Prefer a more confident report over a less confident one.
1430 if (a.getKind() != b.getKind())
1431 return a.getKind() > b.getKind();
1432 return a.getUser()->getLocStart() < b.getUser()->getLocStart();
1435 for (const auto &U : *vec) {
1436 // If we have self-init, downgrade all uses to 'may be uninitialized'.
1437 UninitUse Use = hasSelfInit ? UninitUse(U.getUser(), false) : U;
1439 if (DiagnoseUninitializedUse(S, vd, Use))
1440 // Skip further diagnostics for this variable. We try to warn only
1441 // on the first point at which a variable is used uninitialized.
1446 // Release the uses vector.
1454 static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
1455 return std::any_of(vec->begin(), vec->end(), [](const UninitUse &U) {
1456 return U.getKind() == UninitUse::Always ||
1457 U.getKind() == UninitUse::AfterCall ||
1458 U.getKind() == UninitUse::AfterDecl;
1462 } // anonymous namespace
1466 typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
1467 typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
1468 typedef std::list<DelayedDiag> DiagList;
1470 struct SortDiagBySourceLocation {
1472 SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
1474 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1475 // Although this call will be slow, this is only called when outputting
1476 // multiple warnings.
1477 return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
1480 } // anonymous namespace
1481 } // namespace clang
1483 //===----------------------------------------------------------------------===//
1485 //===----------------------------------------------------------------------===//
1487 namespace threadSafety {
1489 class ThreadSafetyReporter : public clang::threadSafety::ThreadSafetyHandler {
1492 SourceLocation FunLocation, FunEndLocation;
1494 const FunctionDecl *CurrentFunction;
1497 OptionalNotes getNotes() const {
1498 if (Verbose && CurrentFunction) {
1499 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
1500 S.PDiag(diag::note_thread_warning_in_fun)
1501 << CurrentFunction->getNameAsString());
1502 return OptionalNotes(1, FNote);
1504 return OptionalNotes();
1507 OptionalNotes getNotes(const PartialDiagnosticAt &Note) const {
1508 OptionalNotes ONS(1, Note);
1509 if (Verbose && CurrentFunction) {
1510 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
1511 S.PDiag(diag::note_thread_warning_in_fun)
1512 << CurrentFunction->getNameAsString());
1513 ONS.push_back(std::move(FNote));
1518 OptionalNotes getNotes(const PartialDiagnosticAt &Note1,
1519 const PartialDiagnosticAt &Note2) const {
1521 ONS.push_back(Note1);
1522 ONS.push_back(Note2);
1523 if (Verbose && CurrentFunction) {
1524 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
1525 S.PDiag(diag::note_thread_warning_in_fun)
1526 << CurrentFunction->getNameAsString());
1527 ONS.push_back(std::move(FNote));
1533 void warnLockMismatch(unsigned DiagID, StringRef Kind, Name LockName,
1534 SourceLocation Loc) {
1535 // Gracefully handle rare cases when the analysis can't get a more
1536 // precise source location.
1539 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind << LockName);
1540 Warnings.emplace_back(std::move(Warning), getNotes());
1544 ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
1545 : S(S), FunLocation(FL), FunEndLocation(FEL),
1546 CurrentFunction(nullptr), Verbose(false) {}
1548 void setVerbose(bool b) { Verbose = b; }
1550 /// \brief Emit all buffered diagnostics in order of sourcelocation.
1551 /// We need to output diagnostics produced while iterating through
1552 /// the lockset in deterministic order, so this function orders diagnostics
1553 /// and outputs them.
1554 void emitDiagnostics() {
1555 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
1556 for (const auto &Diag : Warnings) {
1557 S.Diag(Diag.first.first, Diag.first.second);
1558 for (const auto &Note : Diag.second)
1559 S.Diag(Note.first, Note.second);
1563 void handleInvalidLockExp(StringRef Kind, SourceLocation Loc) override {
1564 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_cannot_resolve_lock)
1566 Warnings.emplace_back(std::move(Warning), getNotes());
1569 void handleUnmatchedUnlock(StringRef Kind, Name LockName,
1570 SourceLocation Loc) override {
1571 warnLockMismatch(diag::warn_unlock_but_no_lock, Kind, LockName, Loc);
1574 void handleIncorrectUnlockKind(StringRef Kind, Name LockName,
1575 LockKind Expected, LockKind Received,
1576 SourceLocation Loc) override {
1577 if (Loc.isInvalid())
1579 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_unlock_kind_mismatch)
1580 << Kind << LockName << Received
1582 Warnings.emplace_back(std::move(Warning), getNotes());
1585 void handleDoubleLock(StringRef Kind, Name LockName, SourceLocation Loc) override {
1586 warnLockMismatch(diag::warn_double_lock, Kind, LockName, Loc);
1589 void handleMutexHeldEndOfScope(StringRef Kind, Name LockName,
1590 SourceLocation LocLocked,
1591 SourceLocation LocEndOfScope,
1592 LockErrorKind LEK) override {
1593 unsigned DiagID = 0;
1595 case LEK_LockedSomePredecessors:
1596 DiagID = diag::warn_lock_some_predecessors;
1598 case LEK_LockedSomeLoopIterations:
1599 DiagID = diag::warn_expecting_lock_held_on_loop;
1601 case LEK_LockedAtEndOfFunction:
1602 DiagID = diag::warn_no_unlock;
1604 case LEK_NotLockedAtEndOfFunction:
1605 DiagID = diag::warn_expecting_locked;
1608 if (LocEndOfScope.isInvalid())
1609 LocEndOfScope = FunEndLocation;
1611 PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << Kind
1613 if (LocLocked.isValid()) {
1614 PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here)
1616 Warnings.emplace_back(std::move(Warning), getNotes(Note));
1619 Warnings.emplace_back(std::move(Warning), getNotes());
1622 void handleExclusiveAndShared(StringRef Kind, Name LockName,
1623 SourceLocation Loc1,
1624 SourceLocation Loc2) override {
1625 PartialDiagnosticAt Warning(Loc1,
1626 S.PDiag(diag::warn_lock_exclusive_and_shared)
1627 << Kind << LockName);
1628 PartialDiagnosticAt Note(Loc2, S.PDiag(diag::note_lock_exclusive_and_shared)
1629 << Kind << LockName);
1630 Warnings.emplace_back(std::move(Warning), getNotes(Note));
1633 void handleNoMutexHeld(StringRef Kind, const NamedDecl *D,
1634 ProtectedOperationKind POK, AccessKind AK,
1635 SourceLocation Loc) override {
1636 assert((POK == POK_VarAccess || POK == POK_VarDereference) &&
1637 "Only works for variables");
1638 unsigned DiagID = POK == POK_VarAccess?
1639 diag::warn_variable_requires_any_lock:
1640 diag::warn_var_deref_requires_any_lock;
1641 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
1642 << D->getNameAsString() << getLockKindFromAccessKind(AK));
1643 Warnings.emplace_back(std::move(Warning), getNotes());
1646 void handleMutexNotHeld(StringRef Kind, const NamedDecl *D,
1647 ProtectedOperationKind POK, Name LockName,
1648 LockKind LK, SourceLocation Loc,
1649 Name *PossibleMatch) override {
1650 unsigned DiagID = 0;
1651 if (PossibleMatch) {
1654 DiagID = diag::warn_variable_requires_lock_precise;
1656 case POK_VarDereference:
1657 DiagID = diag::warn_var_deref_requires_lock_precise;
1659 case POK_FunctionCall:
1660 DiagID = diag::warn_fun_requires_lock_precise;
1663 DiagID = diag::warn_guarded_pass_by_reference;
1665 case POK_PtPassByRef:
1666 DiagID = diag::warn_pt_guarded_pass_by_reference;
1669 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1670 << D->getNameAsString()
1672 PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
1674 if (Verbose && POK == POK_VarAccess) {
1675 PartialDiagnosticAt VNote(D->getLocation(),
1676 S.PDiag(diag::note_guarded_by_declared_here)
1677 << D->getNameAsString());
1678 Warnings.emplace_back(std::move(Warning), getNotes(Note, VNote));
1680 Warnings.emplace_back(std::move(Warning), getNotes(Note));
1684 DiagID = diag::warn_variable_requires_lock;
1686 case POK_VarDereference:
1687 DiagID = diag::warn_var_deref_requires_lock;
1689 case POK_FunctionCall:
1690 DiagID = diag::warn_fun_requires_lock;
1693 DiagID = diag::warn_guarded_pass_by_reference;
1695 case POK_PtPassByRef:
1696 DiagID = diag::warn_pt_guarded_pass_by_reference;
1699 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1700 << D->getNameAsString()
1702 if (Verbose && POK == POK_VarAccess) {
1703 PartialDiagnosticAt Note(D->getLocation(),
1704 S.PDiag(diag::note_guarded_by_declared_here)
1705 << D->getNameAsString());
1706 Warnings.emplace_back(std::move(Warning), getNotes(Note));
1708 Warnings.emplace_back(std::move(Warning), getNotes());
1712 void handleNegativeNotHeld(StringRef Kind, Name LockName, Name Neg,
1713 SourceLocation Loc) override {
1714 PartialDiagnosticAt Warning(Loc,
1715 S.PDiag(diag::warn_acquire_requires_negative_cap)
1716 << Kind << LockName << Neg);
1717 Warnings.emplace_back(std::move(Warning), getNotes());
1720 void handleFunExcludesLock(StringRef Kind, Name FunName, Name LockName,
1721 SourceLocation Loc) override {
1722 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_fun_excludes_mutex)
1723 << Kind << FunName << LockName);
1724 Warnings.emplace_back(std::move(Warning), getNotes());
1727 void handleLockAcquiredBefore(StringRef Kind, Name L1Name, Name L2Name,
1728 SourceLocation Loc) override {
1729 PartialDiagnosticAt Warning(Loc,
1730 S.PDiag(diag::warn_acquired_before) << Kind << L1Name << L2Name);
1731 Warnings.emplace_back(std::move(Warning), getNotes());
1734 void handleBeforeAfterCycle(Name L1Name, SourceLocation Loc) override {
1735 PartialDiagnosticAt Warning(Loc,
1736 S.PDiag(diag::warn_acquired_before_after_cycle) << L1Name);
1737 Warnings.emplace_back(std::move(Warning), getNotes());
1740 void enterFunction(const FunctionDecl* FD) override {
1741 CurrentFunction = FD;
1744 void leaveFunction(const FunctionDecl* FD) override {
1745 CurrentFunction = nullptr;
1748 } // anonymous namespace
1749 } // namespace threadSafety
1750 } // namespace clang
1752 //===----------------------------------------------------------------------===//
1754 //===----------------------------------------------------------------------===//
1757 namespace consumed {
1759 class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase {
1766 ConsumedWarningsHandler(Sema &S) : S(S) {}
1768 void emitDiagnostics() override {
1769 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
1770 for (const auto &Diag : Warnings) {
1771 S.Diag(Diag.first.first, Diag.first.second);
1772 for (const auto &Note : Diag.second)
1773 S.Diag(Note.first, Note.second);
1777 void warnLoopStateMismatch(SourceLocation Loc,
1778 StringRef VariableName) override {
1779 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_loop_state_mismatch) <<
1782 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1785 void warnParamReturnTypestateMismatch(SourceLocation Loc,
1786 StringRef VariableName,
1787 StringRef ExpectedState,
1788 StringRef ObservedState) override {
1790 PartialDiagnosticAt Warning(Loc, S.PDiag(
1791 diag::warn_param_return_typestate_mismatch) << VariableName <<
1792 ExpectedState << ObservedState);
1794 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1797 void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
1798 StringRef ObservedState) override {
1800 PartialDiagnosticAt Warning(Loc, S.PDiag(
1801 diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState);
1803 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1806 void warnReturnTypestateForUnconsumableType(SourceLocation Loc,
1807 StringRef TypeName) override {
1808 PartialDiagnosticAt Warning(Loc, S.PDiag(
1809 diag::warn_return_typestate_for_unconsumable_type) << TypeName);
1811 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1814 void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
1815 StringRef ObservedState) override {
1817 PartialDiagnosticAt Warning(Loc, S.PDiag(
1818 diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState);
1820 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1823 void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State,
1824 SourceLocation Loc) override {
1826 PartialDiagnosticAt Warning(Loc, S.PDiag(
1827 diag::warn_use_of_temp_in_invalid_state) << MethodName << State);
1829 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1832 void warnUseInInvalidState(StringRef MethodName, StringRef VariableName,
1833 StringRef State, SourceLocation Loc) override {
1835 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_invalid_state) <<
1836 MethodName << VariableName << State);
1838 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1841 } // anonymous namespace
1842 } // namespace consumed
1843 } // namespace clang
1845 //===----------------------------------------------------------------------===//
1846 // AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
1847 // warnings on a function, method, or block.
1848 //===----------------------------------------------------------------------===//
1850 clang::sema::AnalysisBasedWarnings::Policy::Policy() {
1851 enableCheckFallThrough = 1;
1852 enableCheckUnreachable = 0;
1853 enableThreadSafetyAnalysis = 0;
1854 enableConsumedAnalysis = 0;
1857 static unsigned isEnabled(DiagnosticsEngine &D, unsigned diag) {
1858 return (unsigned)!D.isIgnored(diag, SourceLocation());
1861 clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
1863 NumFunctionsAnalyzed(0),
1864 NumFunctionsWithBadCFGs(0),
1866 MaxCFGBlocksPerFunction(0),
1867 NumUninitAnalysisFunctions(0),
1868 NumUninitAnalysisVariables(0),
1869 MaxUninitAnalysisVariablesPerFunction(0),
1870 NumUninitAnalysisBlockVisits(0),
1871 MaxUninitAnalysisBlockVisitsPerFunction(0) {
1873 using namespace diag;
1874 DiagnosticsEngine &D = S.getDiagnostics();
1876 DefaultPolicy.enableCheckUnreachable =
1877 isEnabled(D, warn_unreachable) ||
1878 isEnabled(D, warn_unreachable_break) ||
1879 isEnabled(D, warn_unreachable_return) ||
1880 isEnabled(D, warn_unreachable_loop_increment);
1882 DefaultPolicy.enableThreadSafetyAnalysis =
1883 isEnabled(D, warn_double_lock);
1885 DefaultPolicy.enableConsumedAnalysis =
1886 isEnabled(D, warn_use_in_invalid_state);
1889 static void flushDiagnostics(Sema &S, const sema::FunctionScopeInfo *fscope) {
1890 for (const auto &D : fscope->PossiblyUnreachableDiags)
1891 S.Diag(D.Loc, D.PD);
1895 AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
1896 sema::FunctionScopeInfo *fscope,
1897 const Decl *D, const BlockExpr *blkExpr) {
1899 // We avoid doing analysis-based warnings when there are errors for
1901 // (1) The CFGs often can't be constructed (if the body is invalid), so
1902 // don't bother trying.
1903 // (2) The code already has problems; running the analysis just takes more
1905 DiagnosticsEngine &Diags = S.getDiagnostics();
1907 // Do not do any analysis for declarations in system headers if we are
1908 // going to just ignore them.
1909 if (Diags.getSuppressSystemWarnings() &&
1910 S.SourceMgr.isInSystemHeader(D->getLocation()))
1913 // For code in dependent contexts, we'll do this at instantiation time.
1914 if (cast<DeclContext>(D)->isDependentContext())
1917 if (Diags.hasUncompilableErrorOccurred()) {
1918 // Flush out any possibly unreachable diagnostics.
1919 flushDiagnostics(S, fscope);
1923 const Stmt *Body = D->getBody();
1926 // Construct the analysis context with the specified CFG build options.
1927 AnalysisDeclContext AC(/* AnalysisDeclContextManager */ nullptr, D);
1929 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
1930 // explosion for destructors that can result and the compile time hit.
1931 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
1932 AC.getCFGBuildOptions().AddEHEdges = false;
1933 AC.getCFGBuildOptions().AddInitializers = true;
1934 AC.getCFGBuildOptions().AddImplicitDtors = true;
1935 AC.getCFGBuildOptions().AddTemporaryDtors = true;
1936 AC.getCFGBuildOptions().AddCXXNewAllocator = false;
1937 AC.getCFGBuildOptions().AddCXXDefaultInitExprInCtors = true;
1939 // Force that certain expressions appear as CFGElements in the CFG. This
1940 // is used to speed up various analyses.
1941 // FIXME: This isn't the right factoring. This is here for initial
1942 // prototyping, but we need a way for analyses to say what expressions they
1943 // expect to always be CFGElements and then fill in the BuildOptions
1944 // appropriately. This is essentially a layering violation.
1945 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis ||
1946 P.enableConsumedAnalysis) {
1947 // Unreachable code analysis and thread safety require a linearized CFG.
1948 AC.getCFGBuildOptions().setAllAlwaysAdd();
1951 AC.getCFGBuildOptions()
1952 .setAlwaysAdd(Stmt::BinaryOperatorClass)
1953 .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
1954 .setAlwaysAdd(Stmt::BlockExprClass)
1955 .setAlwaysAdd(Stmt::CStyleCastExprClass)
1956 .setAlwaysAdd(Stmt::DeclRefExprClass)
1957 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
1958 .setAlwaysAdd(Stmt::UnaryOperatorClass)
1959 .setAlwaysAdd(Stmt::AttributedStmtClass);
1962 // Install the logical handler for -Wtautological-overlap-compare
1963 std::unique_ptr<LogicalErrorHandler> LEH;
1964 if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
1965 D->getLocStart())) {
1966 LEH.reset(new LogicalErrorHandler(S));
1967 AC.getCFGBuildOptions().Observer = LEH.get();
1970 // Emit delayed diagnostics.
1971 if (!fscope->PossiblyUnreachableDiags.empty()) {
1972 bool analyzed = false;
1974 // Register the expressions with the CFGBuilder.
1975 for (const auto &D : fscope->PossiblyUnreachableDiags) {
1977 AC.registerForcedBlockExpression(D.stmt);
1982 for (const auto &D : fscope->PossiblyUnreachableDiags) {
1983 bool processed = false;
1985 const CFGBlock *block = AC.getBlockForRegisteredExpression(D.stmt);
1986 CFGReverseBlockReachabilityAnalysis *cra =
1987 AC.getCFGReachablityAnalysis();
1988 // FIXME: We should be able to assert that block is non-null, but
1989 // the CFG analysis can skip potentially-evaluated expressions in
1990 // edge cases; see test/Sema/vla-2.c.
1992 // Can this block be reached from the entrance?
1993 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
1994 S.Diag(D.Loc, D.PD);
1999 // Emit the warning anyway if we cannot map to a basic block.
2000 S.Diag(D.Loc, D.PD);
2006 flushDiagnostics(S, fscope);
2009 // Warning: check missing 'return'
2010 if (P.enableCheckFallThrough) {
2011 auto IsCoro = [&]() {
2012 if (auto *FD = dyn_cast<FunctionDecl>(D))
2013 if (FD->getBody() && isa<CoroutineBodyStmt>(FD->getBody()))
2017 const CheckFallThroughDiagnostics &CD =
2019 ? CheckFallThroughDiagnostics::MakeForBlock()
2020 : (isa<CXXMethodDecl>(D) &&
2021 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
2022 cast<CXXMethodDecl>(D)->getParent()->isLambda())
2023 ? CheckFallThroughDiagnostics::MakeForLambda()
2025 ? CheckFallThroughDiagnostics::MakeForCoroutine(D)
2026 : CheckFallThroughDiagnostics::MakeForFunction(D)));
2027 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
2030 // Warning: check for unreachable code
2031 if (P.enableCheckUnreachable) {
2032 // Only check for unreachable code on non-template instantiations.
2033 // Different template instantiations can effectively change the control-flow
2034 // and it is very difficult to prove that a snippet of code in a template
2035 // is unreachable for all instantiations.
2036 bool isTemplateInstantiation = false;
2037 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2038 isTemplateInstantiation = Function->isTemplateInstantiation();
2039 if (!isTemplateInstantiation)
2040 CheckUnreachable(S, AC);
2043 // Check for thread safety violations
2044 if (P.enableThreadSafetyAnalysis) {
2045 SourceLocation FL = AC.getDecl()->getLocation();
2046 SourceLocation FEL = AC.getDecl()->getLocEnd();
2047 threadSafety::ThreadSafetyReporter Reporter(S, FL, FEL);
2048 if (!Diags.isIgnored(diag::warn_thread_safety_beta, D->getLocStart()))
2049 Reporter.setIssueBetaWarnings(true);
2050 if (!Diags.isIgnored(diag::warn_thread_safety_verbose, D->getLocStart()))
2051 Reporter.setVerbose(true);
2053 threadSafety::runThreadSafetyAnalysis(AC, Reporter,
2054 &S.ThreadSafetyDeclCache);
2055 Reporter.emitDiagnostics();
2058 // Check for violations of consumed properties.
2059 if (P.enableConsumedAnalysis) {
2060 consumed::ConsumedWarningsHandler WarningHandler(S);
2061 consumed::ConsumedAnalyzer Analyzer(WarningHandler);
2065 if (!Diags.isIgnored(diag::warn_uninit_var, D->getLocStart()) ||
2066 !Diags.isIgnored(diag::warn_sometimes_uninit_var, D->getLocStart()) ||
2067 !Diags.isIgnored(diag::warn_maybe_uninit_var, D->getLocStart())) {
2068 if (CFG *cfg = AC.getCFG()) {
2069 UninitValsDiagReporter reporter(S);
2070 UninitVariablesAnalysisStats stats;
2071 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
2072 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
2075 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
2076 ++NumUninitAnalysisFunctions;
2077 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
2078 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
2079 MaxUninitAnalysisVariablesPerFunction =
2080 std::max(MaxUninitAnalysisVariablesPerFunction,
2081 stats.NumVariablesAnalyzed);
2082 MaxUninitAnalysisBlockVisitsPerFunction =
2083 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
2084 stats.NumBlockVisits);
2089 bool FallThroughDiagFull =
2090 !Diags.isIgnored(diag::warn_unannotated_fallthrough, D->getLocStart());
2091 bool FallThroughDiagPerFunction = !Diags.isIgnored(
2092 diag::warn_unannotated_fallthrough_per_function, D->getLocStart());
2093 if (FallThroughDiagFull || FallThroughDiagPerFunction ||
2094 fscope->HasFallthroughStmt) {
2095 DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
2098 if (S.getLangOpts().ObjCWeak &&
2099 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, D->getLocStart()))
2100 diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
2103 // Check for infinite self-recursion in functions
2104 if (!Diags.isIgnored(diag::warn_infinite_recursive_function,
2105 D->getLocStart())) {
2106 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2107 checkRecursiveFunction(S, FD, Body, AC);
2111 // If none of the previous checks caused a CFG build, trigger one here
2112 // for -Wtautological-overlap-compare
2113 if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
2114 D->getLocStart())) {
2118 // Collect statistics about the CFG if it was built.
2119 if (S.CollectStats && AC.isCFGBuilt()) {
2120 ++NumFunctionsAnalyzed;
2121 if (CFG *cfg = AC.getCFG()) {
2122 // If we successfully built a CFG for this context, record some more
2123 // detail information about it.
2124 NumCFGBlocks += cfg->getNumBlockIDs();
2125 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
2126 cfg->getNumBlockIDs());
2128 ++NumFunctionsWithBadCFGs;
2133 void clang::sema::AnalysisBasedWarnings::PrintStats() const {
2134 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
2136 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
2137 unsigned AvgCFGBlocksPerFunction =
2138 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
2139 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
2140 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
2141 << " " << NumCFGBlocks << " CFG blocks built.\n"
2142 << " " << AvgCFGBlocksPerFunction
2143 << " average CFG blocks per function.\n"
2144 << " " << MaxCFGBlocksPerFunction
2145 << " max CFG blocks per function.\n";
2147 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
2148 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
2149 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
2150 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
2151 llvm::errs() << NumUninitAnalysisFunctions
2152 << " functions analyzed for uninitialiazed variables\n"
2153 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
2154 << " " << AvgUninitVariablesPerFunction
2155 << " average variables per function.\n"
2156 << " " << MaxUninitAnalysisVariablesPerFunction
2157 << " max variables per function.\n"
2158 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
2159 << " " << AvgUninitBlockVisitsPerFunction
2160 << " average block visits per function.\n"
2161 << " " << MaxUninitAnalysisBlockVisitsPerFunction
2162 << " max block visits per function.\n";