1 //=- AnalysisBasedWarnings.cpp - Sema warnings based on libAnalysis -*- C++ -*-=//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines analysis_warnings::[Policy,Executor].
11 // Together they are used by Sema to issue warnings based on inexpensive
12 // static analysis algorithms in libAnalysis.
14 //===----------------------------------------------------------------------===//
16 #include "clang/Sema/AnalysisBasedWarnings.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/EvaluatedExprVisitor.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/ExprObjC.h"
22 #include "clang/AST/ParentMap.h"
23 #include "clang/AST/RecursiveASTVisitor.h"
24 #include "clang/AST/StmtCXX.h"
25 #include "clang/AST/StmtObjC.h"
26 #include "clang/AST/StmtVisitor.h"
27 #include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h"
28 #include "clang/Analysis/Analyses/Consumed.h"
29 #include "clang/Analysis/Analyses/ReachableCode.h"
30 #include "clang/Analysis/Analyses/ThreadSafety.h"
31 #include "clang/Analysis/Analyses/UninitializedValues.h"
32 #include "clang/Analysis/AnalysisContext.h"
33 #include "clang/Analysis/CFG.h"
34 #include "clang/Analysis/CFGStmtMap.h"
35 #include "clang/Basic/SourceLocation.h"
36 #include "clang/Basic/SourceManager.h"
37 #include "clang/Lex/Preprocessor.h"
38 #include "clang/Sema/ScopeInfo.h"
39 #include "clang/Sema/SemaInternal.h"
40 #include "llvm/ADT/BitVector.h"
41 #include "llvm/ADT/MapVector.h"
42 #include "llvm/ADT/SmallString.h"
43 #include "llvm/ADT/SmallVector.h"
44 #include "llvm/ADT/StringRef.h"
45 #include "llvm/Support/Casting.h"
50 using namespace clang;
52 //===----------------------------------------------------------------------===//
53 // Unreachable code analysis.
54 //===----------------------------------------------------------------------===//
57 class UnreachableCodeHandler : public reachable_code::Callback {
59 SourceRange PreviousSilenceableCondVal;
62 UnreachableCodeHandler(Sema &s) : S(s) {}
64 void HandleUnreachable(reachable_code::UnreachableKind UK,
66 SourceRange SilenceableCondVal,
68 SourceRange R2) override {
69 // Avoid reporting multiple unreachable code diagnostics that are
70 // triggered by the same conditional value.
71 if (PreviousSilenceableCondVal.isValid() &&
72 SilenceableCondVal.isValid() &&
73 PreviousSilenceableCondVal == SilenceableCondVal)
75 PreviousSilenceableCondVal = SilenceableCondVal;
77 unsigned diag = diag::warn_unreachable;
79 case reachable_code::UK_Break:
80 diag = diag::warn_unreachable_break;
82 case reachable_code::UK_Return:
83 diag = diag::warn_unreachable_return;
85 case reachable_code::UK_Loop_Increment:
86 diag = diag::warn_unreachable_loop_increment;
88 case reachable_code::UK_Other:
92 S.Diag(L, diag) << R1 << R2;
94 SourceLocation Open = SilenceableCondVal.getBegin();
96 SourceLocation Close = SilenceableCondVal.getEnd();
97 Close = S.getLocForEndOfToken(Close);
98 if (Close.isValid()) {
99 S.Diag(Open, diag::note_unreachable_silence)
100 << FixItHint::CreateInsertion(Open, "/* DISABLES CODE */ (")
101 << FixItHint::CreateInsertion(Close, ")");
106 } // anonymous namespace
108 /// CheckUnreachable - Check for unreachable code.
109 static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) {
110 // As a heuristic prune all diagnostics not in the main file. Currently
111 // the majority of warnings in headers are false positives. These
112 // are largely caused by configuration state, e.g. preprocessor
113 // defined code, etc.
115 // Note that this is also a performance optimization. Analyzing
116 // headers many times can be expensive.
117 if (!S.getSourceManager().isInMainFile(AC.getDecl()->getLocStart()))
120 UnreachableCodeHandler UC(S);
121 reachable_code::FindUnreachableCode(AC, S.getPreprocessor(), UC);
125 /// \brief Warn on logical operator errors in CFGBuilder
126 class LogicalErrorHandler : public CFGCallback {
130 LogicalErrorHandler(Sema &S) : CFGCallback(), S(S) {}
132 static bool HasMacroID(const Expr *E) {
133 if (E->getExprLoc().isMacroID())
136 // Recurse to children.
137 for (const Stmt *SubStmt : E->children())
138 if (const Expr *SubExpr = dyn_cast_or_null<Expr>(SubStmt))
139 if (HasMacroID(SubExpr))
145 void compareAlwaysTrue(const BinaryOperator *B, bool isAlwaysTrue) override {
149 SourceRange DiagRange = B->getSourceRange();
150 S.Diag(B->getExprLoc(), diag::warn_tautological_overlap_comparison)
151 << DiagRange << isAlwaysTrue;
154 void compareBitwiseEquality(const BinaryOperator *B,
155 bool isAlwaysTrue) override {
159 SourceRange DiagRange = B->getSourceRange();
160 S.Diag(B->getExprLoc(), diag::warn_comparison_bitwise_always)
161 << DiagRange << isAlwaysTrue;
164 } // anonymous namespace
166 //===----------------------------------------------------------------------===//
167 // Check for infinite self-recursion in functions
168 //===----------------------------------------------------------------------===//
170 // Returns true if the function is called anywhere within the CFGBlock.
171 // For member functions, the additional condition of being call from the
172 // this pointer is required.
173 static bool hasRecursiveCallInPath(const FunctionDecl *FD, CFGBlock &Block) {
174 // Process all the Stmt's in this block to find any calls to FD.
175 for (const auto &B : Block) {
176 if (B.getKind() != CFGElement::Statement)
179 const CallExpr *CE = dyn_cast<CallExpr>(B.getAs<CFGStmt>()->getStmt());
180 if (!CE || !CE->getCalleeDecl() ||
181 CE->getCalleeDecl()->getCanonicalDecl() != FD)
184 // Skip function calls which are qualified with a templated class.
185 if (const DeclRefExpr *DRE =
186 dyn_cast<DeclRefExpr>(CE->getCallee()->IgnoreParenImpCasts())) {
187 if (NestedNameSpecifier *NNS = DRE->getQualifier()) {
188 if (NNS->getKind() == NestedNameSpecifier::TypeSpec &&
189 isa<TemplateSpecializationType>(NNS->getAsType())) {
195 const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE);
196 if (!MCE || isa<CXXThisExpr>(MCE->getImplicitObjectArgument()) ||
197 !MCE->getMethodDecl()->isVirtual())
203 // All blocks are in one of three states. States are ordered so that blocks
204 // can only move to higher states.
205 enum RecursiveState {
208 FoundPathWithNoRecursiveCall
211 // Returns true if there exists a path to the exit block and every path
212 // to the exit block passes through a call to FD.
213 static bool checkForRecursiveFunctionCall(const FunctionDecl *FD, CFG *cfg) {
215 const unsigned ExitID = cfg->getExit().getBlockID();
217 // Mark all nodes as FoundNoPath, then set the status of the entry block.
218 SmallVector<RecursiveState, 16> States(cfg->getNumBlockIDs(), FoundNoPath);
219 States[cfg->getEntry().getBlockID()] = FoundPathWithNoRecursiveCall;
221 // Make the processing stack and seed it with the entry block.
222 SmallVector<CFGBlock *, 16> Stack;
223 Stack.push_back(&cfg->getEntry());
225 while (!Stack.empty()) {
226 CFGBlock *CurBlock = Stack.back();
229 unsigned ID = CurBlock->getBlockID();
230 RecursiveState CurState = States[ID];
232 if (CurState == FoundPathWithNoRecursiveCall) {
233 // Found a path to the exit node without a recursive call.
237 // Only change state if the block has a recursive call.
238 if (hasRecursiveCallInPath(FD, *CurBlock))
239 CurState = FoundPath;
242 // Loop over successor blocks and add them to the Stack if their state
244 for (auto I = CurBlock->succ_begin(), E = CurBlock->succ_end(); I != E; ++I)
246 unsigned next_ID = (*I)->getBlockID();
247 if (States[next_ID] < CurState) {
248 States[next_ID] = CurState;
254 // Return true if the exit node is reachable, and only reachable through
256 return States[ExitID] == FoundPath;
259 static void checkRecursiveFunction(Sema &S, const FunctionDecl *FD,
260 const Stmt *Body, AnalysisDeclContext &AC) {
261 FD = FD->getCanonicalDecl();
263 // Only run on non-templated functions and non-templated members of
264 // templated classes.
265 if (FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate &&
266 FD->getTemplatedKind() != FunctionDecl::TK_MemberSpecialization)
269 CFG *cfg = AC.getCFG();
272 // If the exit block is unreachable, skip processing the function.
273 if (cfg->getExit().pred_empty())
276 // Emit diagnostic if a recursive function call is detected for all paths.
277 if (checkForRecursiveFunctionCall(FD, cfg))
278 S.Diag(Body->getLocStart(), diag::warn_infinite_recursive_function);
281 //===----------------------------------------------------------------------===//
282 // Check for missing return value.
283 //===----------------------------------------------------------------------===//
285 enum ControlFlowKind {
290 NeverFallThroughOrReturn
293 /// CheckFallThrough - Check that we don't fall off the end of a
294 /// Statement that should return a value.
296 /// \returns AlwaysFallThrough iff we always fall off the end of the statement,
297 /// MaybeFallThrough iff we might or might not fall off the end,
298 /// NeverFallThroughOrReturn iff we never fall off the end of the statement or
299 /// return. We assume NeverFallThrough iff we never fall off the end of the
300 /// statement but we may return. We assume that functions not marked noreturn
302 static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
303 CFG *cfg = AC.getCFG();
304 if (!cfg) return UnknownFallThrough;
306 // The CFG leaves in dead things, and we don't want the dead code paths to
307 // confuse us, so we mark all live things first.
308 llvm::BitVector live(cfg->getNumBlockIDs());
309 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
312 bool AddEHEdges = AC.getAddEHEdges();
313 if (!AddEHEdges && count != cfg->getNumBlockIDs())
314 // When there are things remaining dead, and we didn't add EH edges
315 // from CallExprs to the catch clauses, we have to go back and
316 // mark them as live.
317 for (const auto *B : *cfg) {
318 if (!live[B->getBlockID()]) {
319 if (B->pred_begin() == B->pred_end()) {
320 if (B->getTerminator() && isa<CXXTryStmt>(B->getTerminator()))
321 // When not adding EH edges from calls, catch clauses
322 // can otherwise seem dead. Avoid noting them as dead.
323 count += reachable_code::ScanReachableFromBlock(B, live);
329 // Now we know what is live, we check the live precessors of the exit block
330 // and look for fall through paths, being careful to ignore normal returns,
331 // and exceptional paths.
332 bool HasLiveReturn = false;
333 bool HasFakeEdge = false;
334 bool HasPlainEdge = false;
335 bool HasAbnormalEdge = false;
337 // Ignore default cases that aren't likely to be reachable because all
338 // enums in a switch(X) have explicit case statements.
339 CFGBlock::FilterOptions FO;
340 FO.IgnoreDefaultsWithCoveredEnums = 1;
342 for (CFGBlock::filtered_pred_iterator
343 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
344 const CFGBlock& B = **I;
345 if (!live[B.getBlockID()])
348 // Skip blocks which contain an element marked as no-return. They don't
349 // represent actually viable edges into the exit block, so mark them as
351 if (B.hasNoReturnElement()) {
352 HasAbnormalEdge = true;
356 // Destructors can appear after the 'return' in the CFG. This is
357 // normal. We need to look pass the destructors for the return
358 // statement (if it exists).
359 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
361 for ( ; ri != re ; ++ri)
362 if (ri->getAs<CFGStmt>())
365 // No more CFGElements in the block?
367 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
368 HasAbnormalEdge = true;
371 // A labeled empty statement, or the entry block...
376 CFGStmt CS = ri->castAs<CFGStmt>();
377 const Stmt *S = CS.getStmt();
378 if (isa<ReturnStmt>(S) || isa<CoreturnStmt>(S)) {
379 HasLiveReturn = true;
382 if (isa<ObjCAtThrowStmt>(S)) {
386 if (isa<CXXThrowExpr>(S)) {
390 if (isa<MSAsmStmt>(S)) {
391 // TODO: Verify this is correct.
393 HasLiveReturn = true;
396 if (isa<CXXTryStmt>(S)) {
397 HasAbnormalEdge = true;
400 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
402 HasAbnormalEdge = true;
410 return NeverFallThrough;
411 return NeverFallThroughOrReturn;
413 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
414 return MaybeFallThrough;
415 // This says AlwaysFallThrough for calls to functions that are not marked
416 // noreturn, that don't return. If people would like this warning to be more
417 // accurate, such functions should be marked as noreturn.
418 return AlwaysFallThrough;
423 struct CheckFallThroughDiagnostics {
424 unsigned diag_MaybeFallThrough_HasNoReturn;
425 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
426 unsigned diag_AlwaysFallThrough_HasNoReturn;
427 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
428 unsigned diag_NeverFallThroughOrReturn;
429 enum { Function, Block, Lambda, Coroutine } funMode;
430 SourceLocation FuncLoc;
432 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
433 CheckFallThroughDiagnostics D;
434 D.FuncLoc = Func->getLocation();
435 D.diag_MaybeFallThrough_HasNoReturn =
436 diag::warn_falloff_noreturn_function;
437 D.diag_MaybeFallThrough_ReturnsNonVoid =
438 diag::warn_maybe_falloff_nonvoid_function;
439 D.diag_AlwaysFallThrough_HasNoReturn =
440 diag::warn_falloff_noreturn_function;
441 D.diag_AlwaysFallThrough_ReturnsNonVoid =
442 diag::warn_falloff_nonvoid_function;
444 // Don't suggest that virtual functions be marked "noreturn", since they
445 // might be overridden by non-noreturn functions.
446 bool isVirtualMethod = false;
447 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
448 isVirtualMethod = Method->isVirtual();
450 // Don't suggest that template instantiations be marked "noreturn"
451 bool isTemplateInstantiation = false;
452 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
453 isTemplateInstantiation = Function->isTemplateInstantiation();
455 if (!isVirtualMethod && !isTemplateInstantiation)
456 D.diag_NeverFallThroughOrReturn =
457 diag::warn_suggest_noreturn_function;
459 D.diag_NeverFallThroughOrReturn = 0;
461 D.funMode = Function;
465 static CheckFallThroughDiagnostics MakeForCoroutine(const Decl *Func) {
466 CheckFallThroughDiagnostics D;
467 D.FuncLoc = Func->getLocation();
468 D.diag_MaybeFallThrough_HasNoReturn = 0;
469 D.diag_MaybeFallThrough_ReturnsNonVoid =
470 diag::warn_maybe_falloff_nonvoid_coroutine;
471 D.diag_AlwaysFallThrough_HasNoReturn = 0;
472 D.diag_AlwaysFallThrough_ReturnsNonVoid =
473 diag::warn_falloff_nonvoid_coroutine;
474 D.funMode = Coroutine;
478 static CheckFallThroughDiagnostics MakeForBlock() {
479 CheckFallThroughDiagnostics D;
480 D.diag_MaybeFallThrough_HasNoReturn =
481 diag::err_noreturn_block_has_return_expr;
482 D.diag_MaybeFallThrough_ReturnsNonVoid =
483 diag::err_maybe_falloff_nonvoid_block;
484 D.diag_AlwaysFallThrough_HasNoReturn =
485 diag::err_noreturn_block_has_return_expr;
486 D.diag_AlwaysFallThrough_ReturnsNonVoid =
487 diag::err_falloff_nonvoid_block;
488 D.diag_NeverFallThroughOrReturn = 0;
493 static CheckFallThroughDiagnostics MakeForLambda() {
494 CheckFallThroughDiagnostics D;
495 D.diag_MaybeFallThrough_HasNoReturn =
496 diag::err_noreturn_lambda_has_return_expr;
497 D.diag_MaybeFallThrough_ReturnsNonVoid =
498 diag::warn_maybe_falloff_nonvoid_lambda;
499 D.diag_AlwaysFallThrough_HasNoReturn =
500 diag::err_noreturn_lambda_has_return_expr;
501 D.diag_AlwaysFallThrough_ReturnsNonVoid =
502 diag::warn_falloff_nonvoid_lambda;
503 D.diag_NeverFallThroughOrReturn = 0;
508 bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
509 bool HasNoReturn) const {
510 if (funMode == Function) {
511 return (ReturnsVoid ||
512 D.isIgnored(diag::warn_maybe_falloff_nonvoid_function,
515 D.isIgnored(diag::warn_noreturn_function_has_return_expr,
518 D.isIgnored(diag::warn_suggest_noreturn_block, FuncLoc));
520 if (funMode == Coroutine) {
521 return (ReturnsVoid ||
522 D.isIgnored(diag::warn_maybe_falloff_nonvoid_function, FuncLoc) ||
523 D.isIgnored(diag::warn_maybe_falloff_nonvoid_coroutine,
527 // For blocks / lambdas.
528 return ReturnsVoid && !HasNoReturn;
532 } // anonymous namespace
534 /// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
535 /// function that should return a value. Check that we don't fall off the end
536 /// of a noreturn function. We assume that functions and blocks not marked
537 /// noreturn will return.
538 static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
539 const BlockExpr *blkExpr,
540 const CheckFallThroughDiagnostics& CD,
541 AnalysisDeclContext &AC) {
543 bool ReturnsVoid = false;
544 bool HasNoReturn = false;
546 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
547 if (const auto *CBody = dyn_cast<CoroutineBodyStmt>(Body))
548 ReturnsVoid = CBody->getFallthroughHandler() != nullptr;
550 ReturnsVoid = FD->getReturnType()->isVoidType();
551 HasNoReturn = FD->isNoReturn();
553 else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
554 ReturnsVoid = MD->getReturnType()->isVoidType();
555 HasNoReturn = MD->hasAttr<NoReturnAttr>();
557 else if (isa<BlockDecl>(D)) {
558 QualType BlockTy = blkExpr->getType();
559 if (const FunctionType *FT =
560 BlockTy->getPointeeType()->getAs<FunctionType>()) {
561 if (FT->getReturnType()->isVoidType())
563 if (FT->getNoReturnAttr())
568 DiagnosticsEngine &Diags = S.getDiagnostics();
570 // Short circuit for compilation speed.
571 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
574 SourceLocation LBrace = Body->getLocStart(), RBrace = Body->getLocEnd();
575 // Either in a function body compound statement, or a function-try-block.
576 switch (CheckFallThrough(AC)) {
577 case UnknownFallThrough:
580 case MaybeFallThrough:
582 S.Diag(RBrace, CD.diag_MaybeFallThrough_HasNoReturn);
583 else if (!ReturnsVoid)
584 S.Diag(RBrace, CD.diag_MaybeFallThrough_ReturnsNonVoid);
586 case AlwaysFallThrough:
588 S.Diag(RBrace, CD.diag_AlwaysFallThrough_HasNoReturn);
589 else if (!ReturnsVoid)
590 S.Diag(RBrace, CD.diag_AlwaysFallThrough_ReturnsNonVoid);
592 case NeverFallThroughOrReturn:
593 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
594 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
595 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 0 << FD;
596 } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
597 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 1 << MD;
599 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn);
603 case NeverFallThrough:
608 //===----------------------------------------------------------------------===//
610 //===----------------------------------------------------------------------===//
613 /// ContainsReference - A visitor class to search for references to
614 /// a particular declaration (the needle) within any evaluated component of an
615 /// expression (recursively).
616 class ContainsReference : public ConstEvaluatedExprVisitor<ContainsReference> {
618 const DeclRefExpr *Needle;
621 typedef ConstEvaluatedExprVisitor<ContainsReference> Inherited;
623 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
624 : Inherited(Context), FoundReference(false), Needle(Needle) {}
626 void VisitExpr(const Expr *E) {
627 // Stop evaluating if we already have a reference.
631 Inherited::VisitExpr(E);
634 void VisitDeclRefExpr(const DeclRefExpr *E) {
636 FoundReference = true;
638 Inherited::VisitDeclRefExpr(E);
641 bool doesContainReference() const { return FoundReference; }
643 } // anonymous namespace
645 static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
646 QualType VariableTy = VD->getType().getCanonicalType();
647 if (VariableTy->isBlockPointerType() &&
648 !VD->hasAttr<BlocksAttr>()) {
649 S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization)
651 << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
655 // Don't issue a fixit if there is already an initializer.
659 // Don't suggest a fixit inside macros.
660 if (VD->getLocEnd().isMacroID())
663 SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
665 // Suggest possible initialization (if any).
666 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
670 S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
671 << FixItHint::CreateInsertion(Loc, Init);
675 /// Create a fixit to remove an if-like statement, on the assumption that its
676 /// condition is CondVal.
677 static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
678 const Stmt *Else, bool CondVal,
679 FixItHint &Fixit1, FixItHint &Fixit2) {
681 // If condition is always true, remove all but the 'then'.
682 Fixit1 = FixItHint::CreateRemoval(
683 CharSourceRange::getCharRange(If->getLocStart(),
684 Then->getLocStart()));
686 SourceLocation ElseKwLoc = S.getLocForEndOfToken(Then->getLocEnd());
687 Fixit2 = FixItHint::CreateRemoval(
688 SourceRange(ElseKwLoc, Else->getLocEnd()));
691 // If condition is always false, remove all but the 'else'.
693 Fixit1 = FixItHint::CreateRemoval(
694 CharSourceRange::getCharRange(If->getLocStart(),
695 Else->getLocStart()));
697 Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
701 /// DiagUninitUse -- Helper function to produce a diagnostic for an
702 /// uninitialized use of a variable.
703 static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
704 bool IsCapturedByBlock) {
705 bool Diagnosed = false;
707 switch (Use.getKind()) {
708 case UninitUse::Always:
709 S.Diag(Use.getUser()->getLocStart(), diag::warn_uninit_var)
710 << VD->getDeclName() << IsCapturedByBlock
711 << Use.getUser()->getSourceRange();
714 case UninitUse::AfterDecl:
715 case UninitUse::AfterCall:
716 S.Diag(VD->getLocation(), diag::warn_sometimes_uninit_var)
717 << VD->getDeclName() << IsCapturedByBlock
718 << (Use.getKind() == UninitUse::AfterDecl ? 4 : 5)
719 << const_cast<DeclContext*>(VD->getLexicalDeclContext())
720 << VD->getSourceRange();
721 S.Diag(Use.getUser()->getLocStart(), diag::note_uninit_var_use)
722 << IsCapturedByBlock << Use.getUser()->getSourceRange();
725 case UninitUse::Maybe:
726 case UninitUse::Sometimes:
727 // Carry on to report sometimes-uninitialized branches, if possible,
728 // or a 'may be used uninitialized' diagnostic otherwise.
732 // Diagnose each branch which leads to a sometimes-uninitialized use.
733 for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
735 assert(Use.getKind() == UninitUse::Sometimes);
737 const Expr *User = Use.getUser();
738 const Stmt *Term = I->Terminator;
740 // Information used when building the diagnostic.
745 // FixIts to suppress the diagnostic by removing the dead condition.
746 // For all binary terminators, branch 0 is taken if the condition is true,
747 // and branch 1 is taken if the condition is false.
748 int RemoveDiagKind = -1;
749 const char *FixitStr =
750 S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
751 : (I->Output ? "1" : "0");
752 FixItHint Fixit1, Fixit2;
754 switch (Term ? Term->getStmtClass() : Stmt::DeclStmtClass) {
756 // Don't know how to report this. Just fall back to 'may be used
757 // uninitialized'. FIXME: Can this happen?
760 // "condition is true / condition is false".
761 case Stmt::IfStmtClass: {
762 const IfStmt *IS = cast<IfStmt>(Term);
765 Range = IS->getCond()->getSourceRange();
767 CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
768 I->Output, Fixit1, Fixit2);
771 case Stmt::ConditionalOperatorClass: {
772 const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
775 Range = CO->getCond()->getSourceRange();
777 CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
778 I->Output, Fixit1, Fixit2);
781 case Stmt::BinaryOperatorClass: {
782 const BinaryOperator *BO = cast<BinaryOperator>(Term);
783 if (!BO->isLogicalOp())
786 Str = BO->getOpcodeStr();
787 Range = BO->getLHS()->getSourceRange();
789 if ((BO->getOpcode() == BO_LAnd && I->Output) ||
790 (BO->getOpcode() == BO_LOr && !I->Output))
791 // true && y -> y, false || y -> y.
792 Fixit1 = FixItHint::CreateRemoval(SourceRange(BO->getLocStart(),
793 BO->getOperatorLoc()));
795 // false && y -> false, true || y -> true.
796 Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
800 // "loop is entered / loop is exited".
801 case Stmt::WhileStmtClass:
804 Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
806 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
808 case Stmt::ForStmtClass:
811 Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
814 Fixit1 = FixItHint::CreateRemoval(Range);
816 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
818 case Stmt::CXXForRangeStmtClass:
819 if (I->Output == 1) {
820 // The use occurs if a range-based for loop's body never executes.
821 // That may be impossible, and there's no syntactic fix for this,
822 // so treat it as a 'may be uninitialized' case.
827 Range = cast<CXXForRangeStmt>(Term)->getRangeInit()->getSourceRange();
830 // "condition is true / loop is exited".
831 case Stmt::DoStmtClass:
834 Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
836 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
839 // "switch case is taken".
840 case Stmt::CaseStmtClass:
843 Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
845 case Stmt::DefaultStmtClass:
848 Range = cast<DefaultStmt>(Term)->getDefaultLoc();
852 S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
853 << VD->getDeclName() << IsCapturedByBlock << DiagKind
854 << Str << I->Output << Range;
855 S.Diag(User->getLocStart(), diag::note_uninit_var_use)
856 << IsCapturedByBlock << User->getSourceRange();
857 if (RemoveDiagKind != -1)
858 S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
859 << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
865 S.Diag(Use.getUser()->getLocStart(), diag::warn_maybe_uninit_var)
866 << VD->getDeclName() << IsCapturedByBlock
867 << Use.getUser()->getSourceRange();
870 /// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
871 /// uninitialized variable. This manages the different forms of diagnostic
872 /// emitted for particular types of uses. Returns true if the use was diagnosed
873 /// as a warning. If a particular use is one we omit warnings for, returns
875 static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
876 const UninitUse &Use,
877 bool alwaysReportSelfInit = false) {
878 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
879 // Inspect the initializer of the variable declaration which is
880 // being referenced prior to its initialization. We emit
881 // specialized diagnostics for self-initialization, and we
882 // specifically avoid warning about self references which take the
887 // This is used to indicate to GCC that 'x' is intentionally left
888 // uninitialized. Proven code paths which access 'x' in
889 // an uninitialized state after this will still warn.
890 if (const Expr *Initializer = VD->getInit()) {
891 if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
894 ContainsReference CR(S.Context, DRE);
895 CR.Visit(Initializer);
896 if (CR.doesContainReference()) {
897 S.Diag(DRE->getLocStart(),
898 diag::warn_uninit_self_reference_in_init)
899 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
904 DiagUninitUse(S, VD, Use, false);
906 const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
907 if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
908 S.Diag(BE->getLocStart(),
909 diag::warn_uninit_byref_blockvar_captured_by_block)
910 << VD->getDeclName();
912 DiagUninitUse(S, VD, Use, true);
915 // Report where the variable was declared when the use wasn't within
916 // the initializer of that declaration & we didn't already suggest
917 // an initialization fixit.
918 if (!SuggestInitializationFixit(S, VD))
919 S.Diag(VD->getLocStart(), diag::note_var_declared_here)
920 << VD->getDeclName();
926 class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
928 FallthroughMapper(Sema &S)
929 : FoundSwitchStatements(false),
933 bool foundSwitchStatements() const { return FoundSwitchStatements; }
935 void markFallthroughVisited(const AttributedStmt *Stmt) {
936 bool Found = FallthroughStmts.erase(Stmt);
941 typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
943 const AttrStmts &getFallthroughStmts() const {
944 return FallthroughStmts;
947 void fillReachableBlocks(CFG *Cfg) {
948 assert(ReachableBlocks.empty() && "ReachableBlocks already filled");
949 std::deque<const CFGBlock *> BlockQueue;
951 ReachableBlocks.insert(&Cfg->getEntry());
952 BlockQueue.push_back(&Cfg->getEntry());
953 // Mark all case blocks reachable to avoid problems with switching on
954 // constants, covered enums, etc.
955 // These blocks can contain fall-through annotations, and we don't want to
956 // issue a warn_fallthrough_attr_unreachable for them.
957 for (const auto *B : *Cfg) {
958 const Stmt *L = B->getLabel();
959 if (L && isa<SwitchCase>(L) && ReachableBlocks.insert(B).second)
960 BlockQueue.push_back(B);
963 while (!BlockQueue.empty()) {
964 const CFGBlock *P = BlockQueue.front();
965 BlockQueue.pop_front();
966 for (CFGBlock::const_succ_iterator I = P->succ_begin(),
969 if (*I && ReachableBlocks.insert(*I).second)
970 BlockQueue.push_back(*I);
975 bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt) {
976 assert(!ReachableBlocks.empty() && "ReachableBlocks empty");
978 int UnannotatedCnt = 0;
981 std::deque<const CFGBlock*> BlockQueue(B.pred_begin(), B.pred_end());
982 while (!BlockQueue.empty()) {
983 const CFGBlock *P = BlockQueue.front();
984 BlockQueue.pop_front();
987 const Stmt *Term = P->getTerminator();
988 if (Term && isa<SwitchStmt>(Term))
989 continue; // Switch statement, good.
991 const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
992 if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
993 continue; // Previous case label has no statements, good.
995 const LabelStmt *L = dyn_cast_or_null<LabelStmt>(P->getLabel());
996 if (L && L->getSubStmt() == B.getLabel() && P->begin() == P->end())
997 continue; // Case label is preceded with a normal label, good.
999 if (!ReachableBlocks.count(P)) {
1000 for (CFGBlock::const_reverse_iterator ElemIt = P->rbegin(),
1001 ElemEnd = P->rend();
1002 ElemIt != ElemEnd; ++ElemIt) {
1003 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>()) {
1004 if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
1005 S.Diag(AS->getLocStart(),
1006 diag::warn_fallthrough_attr_unreachable);
1007 markFallthroughVisited(AS);
1011 // Don't care about other unreachable statements.
1014 // If there are no unreachable statements, this may be a special
1017 // A a; // A has a destructor.
1020 // // <<<< This place is represented by a 'hanging' CFG block.
1025 const Stmt *LastStmt = getLastStmt(*P);
1026 if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
1027 markFallthroughVisited(AS);
1029 continue; // Fallthrough annotation, good.
1032 if (!LastStmt) { // This block contains no executable statements.
1033 // Traverse its predecessors.
1034 std::copy(P->pred_begin(), P->pred_end(),
1035 std::back_inserter(BlockQueue));
1041 return !!UnannotatedCnt;
1044 // RecursiveASTVisitor setup.
1045 bool shouldWalkTypesOfTypeLocs() const { return false; }
1047 bool VisitAttributedStmt(AttributedStmt *S) {
1048 if (asFallThroughAttr(S))
1049 FallthroughStmts.insert(S);
1053 bool VisitSwitchStmt(SwitchStmt *S) {
1054 FoundSwitchStatements = true;
1058 // We don't want to traverse local type declarations. We analyze their
1059 // methods separately.
1060 bool TraverseDecl(Decl *D) { return true; }
1062 // We analyze lambda bodies separately. Skip them here.
1063 bool TraverseLambdaBody(LambdaExpr *LE) { return true; }
1067 static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
1068 if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
1069 if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
1075 static const Stmt *getLastStmt(const CFGBlock &B) {
1076 if (const Stmt *Term = B.getTerminator())
1078 for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
1080 ElemIt != ElemEnd; ++ElemIt) {
1081 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>())
1082 return CS->getStmt();
1084 // Workaround to detect a statement thrown out by CFGBuilder:
1085 // case X: {} case Y:
1086 // case X: ; case Y:
1087 if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
1088 if (!isa<SwitchCase>(SW->getSubStmt()))
1089 return SW->getSubStmt();
1094 bool FoundSwitchStatements;
1095 AttrStmts FallthroughStmts;
1097 llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks;
1099 } // anonymous namespace
1101 static StringRef getFallthroughAttrSpelling(Preprocessor &PP,
1102 SourceLocation Loc) {
1103 TokenValue FallthroughTokens[] = {
1104 tok::l_square, tok::l_square,
1105 PP.getIdentifierInfo("fallthrough"),
1106 tok::r_square, tok::r_square
1109 TokenValue ClangFallthroughTokens[] = {
1110 tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
1111 tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
1112 tok::r_square, tok::r_square
1115 bool PreferClangAttr = !PP.getLangOpts().CPlusPlus1z;
1117 StringRef MacroName;
1118 if (PreferClangAttr)
1119 MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens);
1120 if (MacroName.empty())
1121 MacroName = PP.getLastMacroWithSpelling(Loc, FallthroughTokens);
1122 if (MacroName.empty() && !PreferClangAttr)
1123 MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens);
1124 if (MacroName.empty())
1125 MacroName = PreferClangAttr ? "[[clang::fallthrough]]" : "[[fallthrough]]";
1129 static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
1131 // Only perform this analysis when using C++11. There is no good workflow
1132 // for this warning when not using C++11. There is no good way to silence
1133 // the warning (no attribute is available) unless we are using C++11's support
1134 // for generalized attributes. Once could use pragmas to silence the warning,
1135 // but as a general solution that is gross and not in the spirit of this
1138 // NOTE: This an intermediate solution. There are on-going discussions on
1139 // how to properly support this warning outside of C++11 with an annotation.
1140 if (!AC.getASTContext().getLangOpts().CPlusPlus11)
1143 FallthroughMapper FM(S);
1144 FM.TraverseStmt(AC.getBody());
1146 if (!FM.foundSwitchStatements())
1149 if (PerFunction && FM.getFallthroughStmts().empty())
1152 CFG *Cfg = AC.getCFG();
1157 FM.fillReachableBlocks(Cfg);
1159 for (const CFGBlock *B : llvm::reverse(*Cfg)) {
1160 const Stmt *Label = B->getLabel();
1162 if (!Label || !isa<SwitchCase>(Label))
1167 if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt))
1170 S.Diag(Label->getLocStart(),
1171 PerFunction ? diag::warn_unannotated_fallthrough_per_function
1172 : diag::warn_unannotated_fallthrough);
1174 if (!AnnotatedCnt) {
1175 SourceLocation L = Label->getLocStart();
1178 if (S.getLangOpts().CPlusPlus11) {
1179 const Stmt *Term = B->getTerminator();
1180 // Skip empty cases.
1181 while (B->empty() && !Term && B->succ_size() == 1) {
1182 B = *B->succ_begin();
1183 Term = B->getTerminator();
1185 if (!(B->empty() && Term && isa<BreakStmt>(Term))) {
1186 Preprocessor &PP = S.getPreprocessor();
1187 StringRef AnnotationSpelling = getFallthroughAttrSpelling(PP, L);
1188 SmallString<64> TextToInsert(AnnotationSpelling);
1189 TextToInsert += "; ";
1190 S.Diag(L, diag::note_insert_fallthrough_fixit) <<
1191 AnnotationSpelling <<
1192 FixItHint::CreateInsertion(L, TextToInsert);
1195 S.Diag(L, diag::note_insert_break_fixit) <<
1196 FixItHint::CreateInsertion(L, "break; ");
1200 for (const auto *F : FM.getFallthroughStmts())
1201 S.Diag(F->getLocStart(), diag::err_fallthrough_attr_invalid_placement);
1204 static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
1209 switch (S->getStmtClass()) {
1210 case Stmt::ForStmtClass:
1211 case Stmt::WhileStmtClass:
1212 case Stmt::CXXForRangeStmtClass:
1213 case Stmt::ObjCForCollectionStmtClass:
1215 case Stmt::DoStmtClass: {
1216 const Expr *Cond = cast<DoStmt>(S)->getCond();
1218 if (!Cond->EvaluateAsInt(Val, Ctx))
1220 return Val.getBoolValue();
1225 } while ((S = PM.getParent(S)));
1230 static void diagnoseRepeatedUseOfWeak(Sema &S,
1231 const sema::FunctionScopeInfo *CurFn,
1233 const ParentMap &PM) {
1234 typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
1235 typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
1236 typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
1237 typedef std::pair<const Stmt *, WeakObjectUseMap::const_iterator>
1240 ASTContext &Ctx = S.getASTContext();
1242 const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
1244 // Extract all weak objects that are referenced more than once.
1245 SmallVector<StmtUsesPair, 8> UsesByStmt;
1246 for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
1248 const WeakUseVector &Uses = I->second;
1250 // Find the first read of the weak object.
1251 WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1252 for ( ; UI != UE; ++UI) {
1257 // If there were only writes to this object, don't warn.
1261 // If there was only one read, followed by any number of writes, and the
1262 // read is not within a loop, don't warn. Additionally, don't warn in a
1263 // loop if the base object is a local variable -- local variables are often
1264 // changed in loops.
1265 if (UI == Uses.begin()) {
1266 WeakUseVector::const_iterator UI2 = UI;
1267 for (++UI2; UI2 != UE; ++UI2)
1268 if (UI2->isUnsafe())
1272 if (!isInLoop(Ctx, PM, UI->getUseExpr()))
1275 const WeakObjectProfileTy &Profile = I->first;
1276 if (!Profile.isExactProfile())
1279 const NamedDecl *Base = Profile.getBase();
1281 Base = Profile.getProperty();
1282 assert(Base && "A profile always has a base or property.");
1284 if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
1285 if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
1290 UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
1293 if (UsesByStmt.empty())
1296 // Sort by first use so that we emit the warnings in a deterministic order.
1297 SourceManager &SM = S.getSourceManager();
1298 std::sort(UsesByStmt.begin(), UsesByStmt.end(),
1299 [&SM](const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
1300 return SM.isBeforeInTranslationUnit(LHS.first->getLocStart(),
1301 RHS.first->getLocStart());
1304 // Classify the current code body for better warning text.
1305 // This enum should stay in sync with the cases in
1306 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1307 // FIXME: Should we use a common classification enum and the same set of
1308 // possibilities all throughout Sema?
1316 if (isa<sema::BlockScopeInfo>(CurFn))
1317 FunctionKind = Block;
1318 else if (isa<sema::LambdaScopeInfo>(CurFn))
1319 FunctionKind = Lambda;
1320 else if (isa<ObjCMethodDecl>(D))
1321 FunctionKind = Method;
1323 FunctionKind = Function;
1325 // Iterate through the sorted problems and emit warnings for each.
1326 for (const auto &P : UsesByStmt) {
1327 const Stmt *FirstRead = P.first;
1328 const WeakObjectProfileTy &Key = P.second->first;
1329 const WeakUseVector &Uses = P.second->second;
1331 // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
1332 // may not contain enough information to determine that these are different
1333 // properties. We can only be 100% sure of a repeated use in certain cases,
1334 // and we adjust the diagnostic kind accordingly so that the less certain
1335 // case can be turned off if it is too noisy.
1337 if (Key.isExactProfile())
1338 DiagKind = diag::warn_arc_repeated_use_of_weak;
1340 DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
1342 // Classify the weak object being accessed for better warning text.
1343 // This enum should stay in sync with the cases in
1344 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1352 const NamedDecl *KeyProp = Key.getProperty();
1353 if (isa<VarDecl>(KeyProp))
1354 ObjectKind = Variable;
1355 else if (isa<ObjCPropertyDecl>(KeyProp))
1356 ObjectKind = Property;
1357 else if (isa<ObjCMethodDecl>(KeyProp))
1358 ObjectKind = ImplicitProperty;
1359 else if (isa<ObjCIvarDecl>(KeyProp))
1362 llvm_unreachable("Unexpected weak object kind!");
1364 // Do not warn about IBOutlet weak property receivers being set to null
1365 // since they are typically only used from the main thread.
1366 if (const ObjCPropertyDecl *Prop = dyn_cast<ObjCPropertyDecl>(KeyProp))
1367 if (Prop->hasAttr<IBOutletAttr>())
1370 // Show the first time the object was read.
1371 S.Diag(FirstRead->getLocStart(), DiagKind)
1372 << int(ObjectKind) << KeyProp << int(FunctionKind)
1373 << FirstRead->getSourceRange();
1375 // Print all the other accesses as notes.
1376 for (const auto &Use : Uses) {
1377 if (Use.getUseExpr() == FirstRead)
1379 S.Diag(Use.getUseExpr()->getLocStart(),
1380 diag::note_arc_weak_also_accessed_here)
1381 << Use.getUseExpr()->getSourceRange();
1387 class UninitValsDiagReporter : public UninitVariablesHandler {
1389 typedef SmallVector<UninitUse, 2> UsesVec;
1390 typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType;
1391 // Prefer using MapVector to DenseMap, so that iteration order will be
1392 // the same as insertion order. This is needed to obtain a deterministic
1393 // order of diagnostics when calling flushDiagnostics().
1394 typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap;
1398 UninitValsDiagReporter(Sema &S) : S(S) {}
1399 ~UninitValsDiagReporter() override { flushDiagnostics(); }
1401 MappedType &getUses(const VarDecl *vd) {
1402 MappedType &V = uses[vd];
1403 if (!V.getPointer())
1404 V.setPointer(new UsesVec());
1408 void handleUseOfUninitVariable(const VarDecl *vd,
1409 const UninitUse &use) override {
1410 getUses(vd).getPointer()->push_back(use);
1413 void handleSelfInit(const VarDecl *vd) override {
1414 getUses(vd).setInt(true);
1417 void flushDiagnostics() {
1418 for (const auto &P : uses) {
1419 const VarDecl *vd = P.first;
1420 const MappedType &V = P.second;
1422 UsesVec *vec = V.getPointer();
1423 bool hasSelfInit = V.getInt();
1425 // Specially handle the case where we have uses of an uninitialized
1426 // variable, but the root cause is an idiomatic self-init. We want
1427 // to report the diagnostic at the self-init since that is the root cause.
1428 if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
1429 DiagnoseUninitializedUse(S, vd,
1430 UninitUse(vd->getInit()->IgnoreParenCasts(),
1431 /* isAlwaysUninit */ true),
1432 /* alwaysReportSelfInit */ true);
1434 // Sort the uses by their SourceLocations. While not strictly
1435 // guaranteed to produce them in line/column order, this will provide
1436 // a stable ordering.
1437 std::sort(vec->begin(), vec->end(),
1438 [](const UninitUse &a, const UninitUse &b) {
1439 // Prefer a more confident report over a less confident one.
1440 if (a.getKind() != b.getKind())
1441 return a.getKind() > b.getKind();
1442 return a.getUser()->getLocStart() < b.getUser()->getLocStart();
1445 for (const auto &U : *vec) {
1446 // If we have self-init, downgrade all uses to 'may be uninitialized'.
1447 UninitUse Use = hasSelfInit ? UninitUse(U.getUser(), false) : U;
1449 if (DiagnoseUninitializedUse(S, vd, Use))
1450 // Skip further diagnostics for this variable. We try to warn only
1451 // on the first point at which a variable is used uninitialized.
1456 // Release the uses vector.
1464 static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
1465 return std::any_of(vec->begin(), vec->end(), [](const UninitUse &U) {
1466 return U.getKind() == UninitUse::Always ||
1467 U.getKind() == UninitUse::AfterCall ||
1468 U.getKind() == UninitUse::AfterDecl;
1472 } // anonymous namespace
1476 typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
1477 typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
1478 typedef std::list<DelayedDiag> DiagList;
1480 struct SortDiagBySourceLocation {
1482 SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
1484 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1485 // Although this call will be slow, this is only called when outputting
1486 // multiple warnings.
1487 return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
1490 } // anonymous namespace
1491 } // namespace clang
1493 //===----------------------------------------------------------------------===//
1495 //===----------------------------------------------------------------------===//
1497 namespace threadSafety {
1499 class ThreadSafetyReporter : public clang::threadSafety::ThreadSafetyHandler {
1502 SourceLocation FunLocation, FunEndLocation;
1504 const FunctionDecl *CurrentFunction;
1507 OptionalNotes getNotes() const {
1508 if (Verbose && CurrentFunction) {
1509 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
1510 S.PDiag(diag::note_thread_warning_in_fun)
1511 << CurrentFunction->getNameAsString());
1512 return OptionalNotes(1, FNote);
1514 return OptionalNotes();
1517 OptionalNotes getNotes(const PartialDiagnosticAt &Note) const {
1518 OptionalNotes ONS(1, Note);
1519 if (Verbose && CurrentFunction) {
1520 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
1521 S.PDiag(diag::note_thread_warning_in_fun)
1522 << CurrentFunction->getNameAsString());
1523 ONS.push_back(std::move(FNote));
1528 OptionalNotes getNotes(const PartialDiagnosticAt &Note1,
1529 const PartialDiagnosticAt &Note2) const {
1531 ONS.push_back(Note1);
1532 ONS.push_back(Note2);
1533 if (Verbose && CurrentFunction) {
1534 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
1535 S.PDiag(diag::note_thread_warning_in_fun)
1536 << CurrentFunction->getNameAsString());
1537 ONS.push_back(std::move(FNote));
1543 void warnLockMismatch(unsigned DiagID, StringRef Kind, Name LockName,
1544 SourceLocation Loc) {
1545 // Gracefully handle rare cases when the analysis can't get a more
1546 // precise source location.
1549 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind << LockName);
1550 Warnings.emplace_back(std::move(Warning), getNotes());
1554 ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
1555 : S(S), FunLocation(FL), FunEndLocation(FEL),
1556 CurrentFunction(nullptr), Verbose(false) {}
1558 void setVerbose(bool b) { Verbose = b; }
1560 /// \brief Emit all buffered diagnostics in order of sourcelocation.
1561 /// We need to output diagnostics produced while iterating through
1562 /// the lockset in deterministic order, so this function orders diagnostics
1563 /// and outputs them.
1564 void emitDiagnostics() {
1565 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
1566 for (const auto &Diag : Warnings) {
1567 S.Diag(Diag.first.first, Diag.first.second);
1568 for (const auto &Note : Diag.second)
1569 S.Diag(Note.first, Note.second);
1573 void handleInvalidLockExp(StringRef Kind, SourceLocation Loc) override {
1574 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_cannot_resolve_lock)
1576 Warnings.emplace_back(std::move(Warning), getNotes());
1579 void handleUnmatchedUnlock(StringRef Kind, Name LockName,
1580 SourceLocation Loc) override {
1581 warnLockMismatch(diag::warn_unlock_but_no_lock, Kind, LockName, Loc);
1584 void handleIncorrectUnlockKind(StringRef Kind, Name LockName,
1585 LockKind Expected, LockKind Received,
1586 SourceLocation Loc) override {
1587 if (Loc.isInvalid())
1589 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_unlock_kind_mismatch)
1590 << Kind << LockName << Received
1592 Warnings.emplace_back(std::move(Warning), getNotes());
1595 void handleDoubleLock(StringRef Kind, Name LockName, SourceLocation Loc) override {
1596 warnLockMismatch(diag::warn_double_lock, Kind, LockName, Loc);
1599 void handleMutexHeldEndOfScope(StringRef Kind, Name LockName,
1600 SourceLocation LocLocked,
1601 SourceLocation LocEndOfScope,
1602 LockErrorKind LEK) override {
1603 unsigned DiagID = 0;
1605 case LEK_LockedSomePredecessors:
1606 DiagID = diag::warn_lock_some_predecessors;
1608 case LEK_LockedSomeLoopIterations:
1609 DiagID = diag::warn_expecting_lock_held_on_loop;
1611 case LEK_LockedAtEndOfFunction:
1612 DiagID = diag::warn_no_unlock;
1614 case LEK_NotLockedAtEndOfFunction:
1615 DiagID = diag::warn_expecting_locked;
1618 if (LocEndOfScope.isInvalid())
1619 LocEndOfScope = FunEndLocation;
1621 PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << Kind
1623 if (LocLocked.isValid()) {
1624 PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here)
1626 Warnings.emplace_back(std::move(Warning), getNotes(Note));
1629 Warnings.emplace_back(std::move(Warning), getNotes());
1632 void handleExclusiveAndShared(StringRef Kind, Name LockName,
1633 SourceLocation Loc1,
1634 SourceLocation Loc2) override {
1635 PartialDiagnosticAt Warning(Loc1,
1636 S.PDiag(diag::warn_lock_exclusive_and_shared)
1637 << Kind << LockName);
1638 PartialDiagnosticAt Note(Loc2, S.PDiag(diag::note_lock_exclusive_and_shared)
1639 << Kind << LockName);
1640 Warnings.emplace_back(std::move(Warning), getNotes(Note));
1643 void handleNoMutexHeld(StringRef Kind, const NamedDecl *D,
1644 ProtectedOperationKind POK, AccessKind AK,
1645 SourceLocation Loc) override {
1646 assert((POK == POK_VarAccess || POK == POK_VarDereference) &&
1647 "Only works for variables");
1648 unsigned DiagID = POK == POK_VarAccess?
1649 diag::warn_variable_requires_any_lock:
1650 diag::warn_var_deref_requires_any_lock;
1651 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
1652 << D->getNameAsString() << getLockKindFromAccessKind(AK));
1653 Warnings.emplace_back(std::move(Warning), getNotes());
1656 void handleMutexNotHeld(StringRef Kind, const NamedDecl *D,
1657 ProtectedOperationKind POK, Name LockName,
1658 LockKind LK, SourceLocation Loc,
1659 Name *PossibleMatch) override {
1660 unsigned DiagID = 0;
1661 if (PossibleMatch) {
1664 DiagID = diag::warn_variable_requires_lock_precise;
1666 case POK_VarDereference:
1667 DiagID = diag::warn_var_deref_requires_lock_precise;
1669 case POK_FunctionCall:
1670 DiagID = diag::warn_fun_requires_lock_precise;
1673 DiagID = diag::warn_guarded_pass_by_reference;
1675 case POK_PtPassByRef:
1676 DiagID = diag::warn_pt_guarded_pass_by_reference;
1679 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1680 << D->getNameAsString()
1682 PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
1684 if (Verbose && POK == POK_VarAccess) {
1685 PartialDiagnosticAt VNote(D->getLocation(),
1686 S.PDiag(diag::note_guarded_by_declared_here)
1687 << D->getNameAsString());
1688 Warnings.emplace_back(std::move(Warning), getNotes(Note, VNote));
1690 Warnings.emplace_back(std::move(Warning), getNotes(Note));
1694 DiagID = diag::warn_variable_requires_lock;
1696 case POK_VarDereference:
1697 DiagID = diag::warn_var_deref_requires_lock;
1699 case POK_FunctionCall:
1700 DiagID = diag::warn_fun_requires_lock;
1703 DiagID = diag::warn_guarded_pass_by_reference;
1705 case POK_PtPassByRef:
1706 DiagID = diag::warn_pt_guarded_pass_by_reference;
1709 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1710 << D->getNameAsString()
1712 if (Verbose && POK == POK_VarAccess) {
1713 PartialDiagnosticAt Note(D->getLocation(),
1714 S.PDiag(diag::note_guarded_by_declared_here)
1715 << D->getNameAsString());
1716 Warnings.emplace_back(std::move(Warning), getNotes(Note));
1718 Warnings.emplace_back(std::move(Warning), getNotes());
1722 void handleNegativeNotHeld(StringRef Kind, Name LockName, Name Neg,
1723 SourceLocation Loc) override {
1724 PartialDiagnosticAt Warning(Loc,
1725 S.PDiag(diag::warn_acquire_requires_negative_cap)
1726 << Kind << LockName << Neg);
1727 Warnings.emplace_back(std::move(Warning), getNotes());
1730 void handleFunExcludesLock(StringRef Kind, Name FunName, Name LockName,
1731 SourceLocation Loc) override {
1732 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_fun_excludes_mutex)
1733 << Kind << FunName << LockName);
1734 Warnings.emplace_back(std::move(Warning), getNotes());
1737 void handleLockAcquiredBefore(StringRef Kind, Name L1Name, Name L2Name,
1738 SourceLocation Loc) override {
1739 PartialDiagnosticAt Warning(Loc,
1740 S.PDiag(diag::warn_acquired_before) << Kind << L1Name << L2Name);
1741 Warnings.emplace_back(std::move(Warning), getNotes());
1744 void handleBeforeAfterCycle(Name L1Name, SourceLocation Loc) override {
1745 PartialDiagnosticAt Warning(Loc,
1746 S.PDiag(diag::warn_acquired_before_after_cycle) << L1Name);
1747 Warnings.emplace_back(std::move(Warning), getNotes());
1750 void enterFunction(const FunctionDecl* FD) override {
1751 CurrentFunction = FD;
1754 void leaveFunction(const FunctionDecl* FD) override {
1755 CurrentFunction = nullptr;
1758 } // anonymous namespace
1759 } // namespace threadSafety
1760 } // namespace clang
1762 //===----------------------------------------------------------------------===//
1764 //===----------------------------------------------------------------------===//
1767 namespace consumed {
1769 class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase {
1776 ConsumedWarningsHandler(Sema &S) : S(S) {}
1778 void emitDiagnostics() override {
1779 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
1780 for (const auto &Diag : Warnings) {
1781 S.Diag(Diag.first.first, Diag.first.second);
1782 for (const auto &Note : Diag.second)
1783 S.Diag(Note.first, Note.second);
1787 void warnLoopStateMismatch(SourceLocation Loc,
1788 StringRef VariableName) override {
1789 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_loop_state_mismatch) <<
1792 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1795 void warnParamReturnTypestateMismatch(SourceLocation Loc,
1796 StringRef VariableName,
1797 StringRef ExpectedState,
1798 StringRef ObservedState) override {
1800 PartialDiagnosticAt Warning(Loc, S.PDiag(
1801 diag::warn_param_return_typestate_mismatch) << VariableName <<
1802 ExpectedState << ObservedState);
1804 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1807 void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
1808 StringRef ObservedState) override {
1810 PartialDiagnosticAt Warning(Loc, S.PDiag(
1811 diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState);
1813 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1816 void warnReturnTypestateForUnconsumableType(SourceLocation Loc,
1817 StringRef TypeName) override {
1818 PartialDiagnosticAt Warning(Loc, S.PDiag(
1819 diag::warn_return_typestate_for_unconsumable_type) << TypeName);
1821 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1824 void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
1825 StringRef ObservedState) override {
1827 PartialDiagnosticAt Warning(Loc, S.PDiag(
1828 diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState);
1830 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1833 void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State,
1834 SourceLocation Loc) override {
1836 PartialDiagnosticAt Warning(Loc, S.PDiag(
1837 diag::warn_use_of_temp_in_invalid_state) << MethodName << State);
1839 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1842 void warnUseInInvalidState(StringRef MethodName, StringRef VariableName,
1843 StringRef State, SourceLocation Loc) override {
1845 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_invalid_state) <<
1846 MethodName << VariableName << State);
1848 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1851 } // anonymous namespace
1852 } // namespace consumed
1853 } // namespace clang
1855 //===----------------------------------------------------------------------===//
1856 // AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
1857 // warnings on a function, method, or block.
1858 //===----------------------------------------------------------------------===//
1860 clang::sema::AnalysisBasedWarnings::Policy::Policy() {
1861 enableCheckFallThrough = 1;
1862 enableCheckUnreachable = 0;
1863 enableThreadSafetyAnalysis = 0;
1864 enableConsumedAnalysis = 0;
1867 static unsigned isEnabled(DiagnosticsEngine &D, unsigned diag) {
1868 return (unsigned)!D.isIgnored(diag, SourceLocation());
1871 clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
1873 NumFunctionsAnalyzed(0),
1874 NumFunctionsWithBadCFGs(0),
1876 MaxCFGBlocksPerFunction(0),
1877 NumUninitAnalysisFunctions(0),
1878 NumUninitAnalysisVariables(0),
1879 MaxUninitAnalysisVariablesPerFunction(0),
1880 NumUninitAnalysisBlockVisits(0),
1881 MaxUninitAnalysisBlockVisitsPerFunction(0) {
1883 using namespace diag;
1884 DiagnosticsEngine &D = S.getDiagnostics();
1886 DefaultPolicy.enableCheckUnreachable =
1887 isEnabled(D, warn_unreachable) ||
1888 isEnabled(D, warn_unreachable_break) ||
1889 isEnabled(D, warn_unreachable_return) ||
1890 isEnabled(D, warn_unreachable_loop_increment);
1892 DefaultPolicy.enableThreadSafetyAnalysis =
1893 isEnabled(D, warn_double_lock);
1895 DefaultPolicy.enableConsumedAnalysis =
1896 isEnabled(D, warn_use_in_invalid_state);
1899 static void flushDiagnostics(Sema &S, const sema::FunctionScopeInfo *fscope) {
1900 for (const auto &D : fscope->PossiblyUnreachableDiags)
1901 S.Diag(D.Loc, D.PD);
1905 AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
1906 sema::FunctionScopeInfo *fscope,
1907 const Decl *D, const BlockExpr *blkExpr) {
1909 // We avoid doing analysis-based warnings when there are errors for
1911 // (1) The CFGs often can't be constructed (if the body is invalid), so
1912 // don't bother trying.
1913 // (2) The code already has problems; running the analysis just takes more
1915 DiagnosticsEngine &Diags = S.getDiagnostics();
1917 // Do not do any analysis for declarations in system headers if we are
1918 // going to just ignore them.
1919 if (Diags.getSuppressSystemWarnings() &&
1920 S.SourceMgr.isInSystemHeader(D->getLocation()))
1923 // For code in dependent contexts, we'll do this at instantiation time.
1924 if (cast<DeclContext>(D)->isDependentContext())
1927 if (Diags.hasUncompilableErrorOccurred()) {
1928 // Flush out any possibly unreachable diagnostics.
1929 flushDiagnostics(S, fscope);
1933 const Stmt *Body = D->getBody();
1936 // Construct the analysis context with the specified CFG build options.
1937 AnalysisDeclContext AC(/* AnalysisDeclContextManager */ nullptr, D);
1939 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
1940 // explosion for destructors that can result and the compile time hit.
1941 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
1942 AC.getCFGBuildOptions().AddEHEdges = false;
1943 AC.getCFGBuildOptions().AddInitializers = true;
1944 AC.getCFGBuildOptions().AddImplicitDtors = true;
1945 AC.getCFGBuildOptions().AddTemporaryDtors = true;
1946 AC.getCFGBuildOptions().AddCXXNewAllocator = false;
1947 AC.getCFGBuildOptions().AddCXXDefaultInitExprInCtors = true;
1949 // Force that certain expressions appear as CFGElements in the CFG. This
1950 // is used to speed up various analyses.
1951 // FIXME: This isn't the right factoring. This is here for initial
1952 // prototyping, but we need a way for analyses to say what expressions they
1953 // expect to always be CFGElements and then fill in the BuildOptions
1954 // appropriately. This is essentially a layering violation.
1955 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis ||
1956 P.enableConsumedAnalysis) {
1957 // Unreachable code analysis and thread safety require a linearized CFG.
1958 AC.getCFGBuildOptions().setAllAlwaysAdd();
1961 AC.getCFGBuildOptions()
1962 .setAlwaysAdd(Stmt::BinaryOperatorClass)
1963 .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
1964 .setAlwaysAdd(Stmt::BlockExprClass)
1965 .setAlwaysAdd(Stmt::CStyleCastExprClass)
1966 .setAlwaysAdd(Stmt::DeclRefExprClass)
1967 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
1968 .setAlwaysAdd(Stmt::UnaryOperatorClass)
1969 .setAlwaysAdd(Stmt::AttributedStmtClass);
1972 // Install the logical handler for -Wtautological-overlap-compare
1973 std::unique_ptr<LogicalErrorHandler> LEH;
1974 if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
1975 D->getLocStart())) {
1976 LEH.reset(new LogicalErrorHandler(S));
1977 AC.getCFGBuildOptions().Observer = LEH.get();
1980 // Emit delayed diagnostics.
1981 if (!fscope->PossiblyUnreachableDiags.empty()) {
1982 bool analyzed = false;
1984 // Register the expressions with the CFGBuilder.
1985 for (const auto &D : fscope->PossiblyUnreachableDiags) {
1987 AC.registerForcedBlockExpression(D.stmt);
1992 for (const auto &D : fscope->PossiblyUnreachableDiags) {
1993 bool processed = false;
1995 const CFGBlock *block = AC.getBlockForRegisteredExpression(D.stmt);
1996 CFGReverseBlockReachabilityAnalysis *cra =
1997 AC.getCFGReachablityAnalysis();
1998 // FIXME: We should be able to assert that block is non-null, but
1999 // the CFG analysis can skip potentially-evaluated expressions in
2000 // edge cases; see test/Sema/vla-2.c.
2002 // Can this block be reached from the entrance?
2003 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
2004 S.Diag(D.Loc, D.PD);
2009 // Emit the warning anyway if we cannot map to a basic block.
2010 S.Diag(D.Loc, D.PD);
2016 flushDiagnostics(S, fscope);
2019 // Warning: check missing 'return'
2020 if (P.enableCheckFallThrough) {
2021 auto IsCoro = [&]() {
2022 if (auto *FD = dyn_cast<FunctionDecl>(D))
2023 if (FD->getBody() && isa<CoroutineBodyStmt>(FD->getBody()))
2027 const CheckFallThroughDiagnostics &CD =
2029 ? CheckFallThroughDiagnostics::MakeForBlock()
2030 : (isa<CXXMethodDecl>(D) &&
2031 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
2032 cast<CXXMethodDecl>(D)->getParent()->isLambda())
2033 ? CheckFallThroughDiagnostics::MakeForLambda()
2035 ? CheckFallThroughDiagnostics::MakeForCoroutine(D)
2036 : CheckFallThroughDiagnostics::MakeForFunction(D)));
2037 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
2040 // Warning: check for unreachable code
2041 if (P.enableCheckUnreachable) {
2042 // Only check for unreachable code on non-template instantiations.
2043 // Different template instantiations can effectively change the control-flow
2044 // and it is very difficult to prove that a snippet of code in a template
2045 // is unreachable for all instantiations.
2046 bool isTemplateInstantiation = false;
2047 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2048 isTemplateInstantiation = Function->isTemplateInstantiation();
2049 if (!isTemplateInstantiation)
2050 CheckUnreachable(S, AC);
2053 // Check for thread safety violations
2054 if (P.enableThreadSafetyAnalysis) {
2055 SourceLocation FL = AC.getDecl()->getLocation();
2056 SourceLocation FEL = AC.getDecl()->getLocEnd();
2057 threadSafety::ThreadSafetyReporter Reporter(S, FL, FEL);
2058 if (!Diags.isIgnored(diag::warn_thread_safety_beta, D->getLocStart()))
2059 Reporter.setIssueBetaWarnings(true);
2060 if (!Diags.isIgnored(diag::warn_thread_safety_verbose, D->getLocStart()))
2061 Reporter.setVerbose(true);
2063 threadSafety::runThreadSafetyAnalysis(AC, Reporter,
2064 &S.ThreadSafetyDeclCache);
2065 Reporter.emitDiagnostics();
2068 // Check for violations of consumed properties.
2069 if (P.enableConsumedAnalysis) {
2070 consumed::ConsumedWarningsHandler WarningHandler(S);
2071 consumed::ConsumedAnalyzer Analyzer(WarningHandler);
2075 if (!Diags.isIgnored(diag::warn_uninit_var, D->getLocStart()) ||
2076 !Diags.isIgnored(diag::warn_sometimes_uninit_var, D->getLocStart()) ||
2077 !Diags.isIgnored(diag::warn_maybe_uninit_var, D->getLocStart())) {
2078 if (CFG *cfg = AC.getCFG()) {
2079 UninitValsDiagReporter reporter(S);
2080 UninitVariablesAnalysisStats stats;
2081 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
2082 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
2085 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
2086 ++NumUninitAnalysisFunctions;
2087 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
2088 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
2089 MaxUninitAnalysisVariablesPerFunction =
2090 std::max(MaxUninitAnalysisVariablesPerFunction,
2091 stats.NumVariablesAnalyzed);
2092 MaxUninitAnalysisBlockVisitsPerFunction =
2093 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
2094 stats.NumBlockVisits);
2099 bool FallThroughDiagFull =
2100 !Diags.isIgnored(diag::warn_unannotated_fallthrough, D->getLocStart());
2101 bool FallThroughDiagPerFunction = !Diags.isIgnored(
2102 diag::warn_unannotated_fallthrough_per_function, D->getLocStart());
2103 if (FallThroughDiagFull || FallThroughDiagPerFunction ||
2104 fscope->HasFallthroughStmt) {
2105 DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
2108 if (S.getLangOpts().ObjCWeak &&
2109 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, D->getLocStart()))
2110 diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
2113 // Check for infinite self-recursion in functions
2114 if (!Diags.isIgnored(diag::warn_infinite_recursive_function,
2115 D->getLocStart())) {
2116 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2117 checkRecursiveFunction(S, FD, Body, AC);
2121 // If none of the previous checks caused a CFG build, trigger one here
2122 // for -Wtautological-overlap-compare
2123 if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
2124 D->getLocStart())) {
2128 // Collect statistics about the CFG if it was built.
2129 if (S.CollectStats && AC.isCFGBuilt()) {
2130 ++NumFunctionsAnalyzed;
2131 if (CFG *cfg = AC.getCFG()) {
2132 // If we successfully built a CFG for this context, record some more
2133 // detail information about it.
2134 NumCFGBlocks += cfg->getNumBlockIDs();
2135 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
2136 cfg->getNumBlockIDs());
2138 ++NumFunctionsWithBadCFGs;
2143 void clang::sema::AnalysisBasedWarnings::PrintStats() const {
2144 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
2146 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
2147 unsigned AvgCFGBlocksPerFunction =
2148 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
2149 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
2150 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
2151 << " " << NumCFGBlocks << " CFG blocks built.\n"
2152 << " " << AvgCFGBlocksPerFunction
2153 << " average CFG blocks per function.\n"
2154 << " " << MaxCFGBlocksPerFunction
2155 << " max CFG blocks per function.\n";
2157 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
2158 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
2159 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
2160 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
2161 llvm::errs() << NumUninitAnalysisFunctions
2162 << " functions analyzed for uninitialiazed variables\n"
2163 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
2164 << " " << AvgUninitVariablesPerFunction
2165 << " average variables per function.\n"
2166 << " " << MaxUninitAnalysisVariablesPerFunction
2167 << " max variables per function.\n"
2168 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
2169 << " " << AvgUninitBlockVisitsPerFunction
2170 << " average block visits per function.\n"
2171 << " " << MaxUninitAnalysisBlockVisitsPerFunction
2172 << " max block visits per function.\n";